hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
29596f1a1e3b253f18c8626c2854f30cc065f71f
9,810
cc
C++
device/bluetooth/device_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
device/bluetooth/device_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
device/bluetooth/device_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 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 "device/bluetooth/device.h" #include <memory> #include <string> #include <utility> #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" #include "device/bluetooth/test/mock_bluetooth_gatt_characteristic.h" #include "device/bluetooth/test/mock_bluetooth_gatt_connection.h" #include "device/bluetooth/test/mock_bluetooth_gatt_service.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::Return; namespace bluetooth { using NiceMockBluetoothAdapter = testing::NiceMock<device::MockBluetoothAdapter>; using NiceMockBluetoothDevice = testing::NiceMock<device::MockBluetoothDevice>; using NiceMockBluetoothGattService = testing::NiceMock<device::MockBluetoothGattService>; using NiceMockBluetoothGattCharacteristic = testing::NiceMock<device::MockBluetoothGattCharacteristic>; using NiceMockBluetoothGattConnection = testing::NiceMock<device::MockBluetoothGattConnection>; using Properties = device::BluetoothGattCharacteristic::Properties; using Property = device::BluetoothGattCharacteristic::Property; namespace { const char kTestLeDeviceAddress0[] = "11:22:33:44:55:66"; const char kTestLeDeviceName0[] = "Test LE Device 0"; const char kTestServiceId0[] = "service_id0"; const char kTestServiceUuid0[] = "1234"; const char kTestServiceId1[] = "service_id1"; const char kTestServiceUuid1[] = "5678"; const char kTestCharacteristicId0[] = "characteristic_id0"; const char kTestCharacteristicUuid0[] = "1234"; const char kTestCharacteristicId1[] = "characteristic_id1"; const char kTestCharacteristicUuid1[] = "5678"; const char kTestCharacteristicId2[] = "characteristic_id2"; const char kTestCharacteristicUuid2[] = "9012"; const Properties kReadWriteProperties = Property::PROPERTY_READ | Property::PROPERTY_WRITE; const Properties kAllProperties = Property::NUM_PROPERTY - 1; class BluetoothInterfaceDeviceTest : public testing::Test { public: enum class Call { EXPECTED, NOT_EXPECTED }; BluetoothInterfaceDeviceTest() : adapter_(new NiceMockBluetoothAdapter), device_(adapter_.get(), 0, kTestLeDeviceName0, kTestLeDeviceAddress0, false, true), weak_factory_(this) { ON_CALL(*adapter_, GetDevice(kTestLeDeviceAddress0)) .WillByDefault(Return(&device_)); auto service1 = std::make_unique<NiceMockBluetoothGattService>( &device_, kTestServiceId0, device::BluetoothUUID(kTestServiceUuid0), true /* is_primary */, false /* is_local */); auto characteristic1 = std::make_unique<NiceMockBluetoothGattCharacteristic>( service1.get(), kTestCharacteristicId0, device::BluetoothUUID(kTestCharacteristicUuid0), false /* is_local */, kReadWriteProperties, 0 /* permissions */); auto characteristic2 = std::make_unique<NiceMockBluetoothGattCharacteristic>( service1.get(), kTestCharacteristicId1, device::BluetoothUUID(kTestCharacteristicUuid1), false /* is_local */, kReadWriteProperties, 0 /* permissions */); service1->AddMockCharacteristic(std::move(characteristic1)); service1->AddMockCharacteristic(std::move(characteristic2)); auto service2 = std::make_unique<NiceMockBluetoothGattService>( &device_, kTestServiceId1, device::BluetoothUUID(kTestServiceUuid1), true /* is_primary */, false /* is_local */); auto characteristic3 = std::make_unique<NiceMockBluetoothGattCharacteristic>( service2.get(), kTestCharacteristicId2, device::BluetoothUUID(kTestCharacteristicUuid2), false /* is_local */, kAllProperties, 0 /* permissions */); service2->AddMockCharacteristic(std::move(characteristic3)); EXPECT_CALL(*service1, GetCharacteristics()) .WillRepeatedly( Invoke(service1.get(), &device::MockBluetoothGattService::GetMockCharacteristics)); EXPECT_CALL(*service2, GetCharacteristics()) .WillRepeatedly( Invoke(service2.get(), &device::MockBluetoothGattService::GetMockCharacteristics)); device_.AddMockService(std::move(service1)); device_.AddMockService(std::move(service2)); EXPECT_CALL(device_, GetGattServices()) .WillRepeatedly( Invoke(&device_, &device::MockBluetoothDevice::GetMockServices)); EXPECT_CALL(device_, GetGattService(testing::_)) .WillRepeatedly( Invoke(&device_, &device::MockBluetoothDevice::GetMockService)); auto connection = std::make_unique<NiceMockBluetoothGattConnection>( adapter_, device_.GetAddress()); Device::Create(adapter_, std::move(connection), mojo::MakeRequest(&proxy_)); proxy_.set_connection_error_handler( base::BindOnce(&BluetoothInterfaceDeviceTest::OnConnectionError, weak_factory_.GetWeakPtr())); } void TearDown() override { EXPECT_EQ(expected_success_callback_calls_, actual_success_callback_calls_); EXPECT_EQ(message_pipe_closed_, expect_device_service_deleted_); proxy_.reset(); base::RunLoop().RunUntilIdle(); } protected: void OnConnectionError() { message_pipe_closed_ = true; } void SimulateGattServicesDiscovered() { for (auto& observer : adapter_->GetObservers()) observer.GattServicesDiscovered(adapter_.get(), &device_); } void SimulateDeviceChanged() { for (auto& observer : adapter_->GetObservers()) observer.DeviceChanged(adapter_.get(), &device_); } void CheckGetServicesCountImpl(Call expected, size_t expected_service_count, int num_of_preceding_calls, std::vector<mojom::ServiceInfoPtr> services) { EXPECT_EQ(num_of_preceding_calls, actual_callback_count_); ++actual_callback_count_; if (expected == Call::EXPECTED) ++actual_success_callback_calls_; EXPECT_EQ(expected_service_count, services.size()); } Device::GetServicesCallback CheckGetServicesCount(Call expected) { if (expected == Call::EXPECTED) ++expected_success_callback_calls_; return base::BindOnce( &BluetoothInterfaceDeviceTest::CheckGetServicesCountImpl, weak_factory_.GetWeakPtr(), expected, 2 /* expected_service_count */, expected_callback_count_++); } scoped_refptr<NiceMockBluetoothAdapter> adapter_; NiceMockBluetoothDevice device_; base::test::ScopedTaskEnvironment scoped_task_environment_; mojom::DevicePtr proxy_; mojo::StrongBindingPtr<mojom::Device> binding_ptr_; bool message_pipe_closed_ = false; bool expect_device_service_deleted_ = false; int expected_success_callback_calls_ = 0; int actual_success_callback_calls_ = 0; int actual_callback_count_ = 0; int expected_callback_count_ = 0; base::WeakPtrFactory<BluetoothInterfaceDeviceTest> weak_factory_; }; } // namespace TEST_F(BluetoothInterfaceDeviceTest, GetServices) { EXPECT_CALL(device_, IsGattServicesDiscoveryComplete()) .WillRepeatedly(Return(true)); proxy_->GetServices(CheckGetServicesCount(Call::EXPECTED)); base::RunLoop().RunUntilIdle(); } TEST_F(BluetoothInterfaceDeviceTest, GetServicesNotDiscovered) { EXPECT_CALL(device_, IsGattServicesDiscoveryComplete()) .WillOnce(Return(false)) .WillOnce(Return(false)) .WillRepeatedly(Return(true)); // Client: Sends multiple requests for services. proxy_->GetServices(CheckGetServicesCount(Call::EXPECTED)); proxy_->GetServices(CheckGetServicesCount(Call::EXPECTED)); base::RunLoop().RunUntilIdle(); SimulateGattServicesDiscovered(); // No more GetServices calls will complete. SimulateGattServicesDiscovered(); base::RunLoop().RunUntilIdle(); // Client: Sends more requests which run immediately. proxy_->GetServices(CheckGetServicesCount(Call::EXPECTED)); proxy_->GetServices(CheckGetServicesCount(Call::EXPECTED)); base::RunLoop().RunUntilIdle(); // No more GetServices calls will complete. SimulateGattServicesDiscovered(); // Wait for message pipe to process error. base::RunLoop().RunUntilIdle(); } TEST_F(BluetoothInterfaceDeviceTest, GetServicesLostConnectionWithPendingRequests) { EXPECT_CALL(device_, IsGattServicesDiscoveryComplete()) .WillRepeatedly(Return(false)); // Client: Sends multiple requests for services. proxy_->GetServices(CheckGetServicesCount(Call::NOT_EXPECTED)); proxy_->GetServices(CheckGetServicesCount(Call::NOT_EXPECTED)); EXPECT_EQ(0, actual_callback_count_); // Simulate connection loss. device_.SetConnected(false); SimulateDeviceChanged(); expect_device_service_deleted_ = true; // Wait for message pipe to process error. base::RunLoop().RunUntilIdle(); } TEST_F(BluetoothInterfaceDeviceTest, GetServicesForcedDisconnectionWithPendingRequests) { EXPECT_CALL(device_, IsGattServicesDiscoveryComplete()) .WillRepeatedly(Return(false)); // Client: Sends multiple requests for services. proxy_->GetServices(CheckGetServicesCount(Call::NOT_EXPECTED)); proxy_->GetServices(CheckGetServicesCount(Call::NOT_EXPECTED)); EXPECT_EQ(0, actual_callback_count_); // Simulate connection loss. proxy_->Disconnect(); expect_device_service_deleted_ = true; // Wait for message pipe to process error. base::RunLoop().RunUntilIdle(); } } // namespace bluetooth
35.28777
80
0.734353
[ "vector" ]
2959d1c01458bc95f45df0b8709ea699bb53b3c7
10,028
cxx
C++
Code/IO/ctcRVFImageIO.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
1
2019-07-29T02:04:06.000Z
2019-07-29T02:04:06.000Z
Code/IO/ctcRVFImageIO.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
null
null
null
Code/IO/ctcRVFImageIO.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* Program: Wake Forest University - Virginia Tech CTC Software Id: $Id: ctcRVFImageIO.cxx 23 2006-06-29 14:45:24Z clwyatt $ Language: C++ *******************************************************************************/ #include <fstream> #include "ctcConfigure.h" #include "ctcByteSwap.h" #include "ctcRVFImageIO.h" #include "ctcRVFHeader.h" namespace ctc { bool RVFImageIO::CanReadFile(const char* file) { // First check the extension std::string filename = file; if( filename == "" ) { itkDebugMacro(<<"No filename specified."); return false; } bool extensionFound = false; std::string::size_type RVFPos = filename.rfind(".rvf"); if ((RVFPos != std::string::npos) && (RVFPos == filename.length() - 4)) { extensionFound = true; } RVFPos = filename.rfind(".RVF"); if ((RVFPos != std::string::npos) && (RVFPos == filename.length() - 4)) { extensionFound = true; } if( !extensionFound ) { itkDebugMacro(<<"The filename extension is not recognized"); return false; } // Now check the file header RVF_header header; std::ifstream infile(file); if(!infile){ itkExceptionMacro("Error RVFImageIO could not open file: " << file); return false; } infile.read((char *) &header, sizeof(header)); infile.close(); // determine endianness of the current machine // RVF files should always be big endian bool swabreq; if(!CTC_BIG_ENDIAN) //little endian swabreq = true; else // big endian swabreq = false; // swap if needed if(swabreq) { swab(header.magic); swab(header.version); swab(header.serial); swab(header.xDim); swab(header.yDim); swab(header.zDim); swab(header.bits); swab(header.x_flipX); swab(header.x_flipY); swab(header.y_flipX); swab(header.y_flipY); swab(header.z_flipX); swab(header.z_flipY); swab(header.xPat_org); swab(header.yPat_org); swab(header.zPat_org); swab(header.xPat_step); swab(header.yPat_step); swab(header.zPat_step); swab(header.dicomHeaderFollows); swab(header.dicomHeaderSize); } if(header.magic != RVF_MAGIC_NUMBER){ itkExceptionMacro("Error RVFImageIO could not open file: " << this->GetFileName()); return false; } // seems like we can read return true; } void RVFImageIO::Read(void* buffer) { itkDebugMacro("Read: file dimensions = " << this->GetNumberOfDimensions() ); RVF_header header; std::ifstream infile(m_FileName.c_str()); if(!infile){ itkExceptionMacro("Error RVFImageIO could not open file: " << this->GetFileName()); return; } infile.read((char *) &header, sizeof(header)); //swap if needed bool swabreq; if(!CTC_BIG_ENDIAN) swabreq = true; else swabreq = false; //swap if needed if(swabreq) { swab(header.magic); swab(header.version); swab(header.serial); swab(header.xDim); swab(header.yDim); swab(header.zDim); swab(header.bits); swab(header.x_flipX); swab(header.x_flipY); swab(header.y_flipX); swab(header.y_flipY); swab(header.z_flipX); swab(header.z_flipY); swab(header.xPat_org); swab(header.yPat_org); swab(header.zPat_org); swab(header.xPat_step); swab(header.yPat_step); swab(header.zPat_step); swab(header.dicomHeaderFollows); swab(header.dicomHeaderSize); } if(header.magic != RVF_MAGIC_NUMBER){ itkExceptionMacro("Error File not of type rvf: " << this->GetFileName()); return; } unsigned long size[3]; size[0] = header.xDim; size[1] = header.yDim; size[2] = header.zDim; // read voxels into buffer argument unsigned short * const p = static_cast<unsigned short *>(buffer); unsigned short temp; for(int k=0; k < size[2]*size[1]*size[0]; k++){ infile.read((char *)(&temp), sizeof(unsigned short)); if(swabreq) swab(temp); *(p + k) = temp; } // close the file infile.close(); } RVFImageIO::RVFImageIO() { this->SetNumberOfDimensions(3); m_PixelType = SCALAR; m_ComponentType = USHORT; m_Spacing[0] = 1.0; m_Spacing[1] = 1.0; m_Spacing[2] = 1.0; m_Origin[0] = 0.0; m_Origin[1] = 0.0; m_Origin[2] = 0.0; } RVFImageIO::~RVFImageIO() { } void RVFImageIO::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); //os << indent << "Compression Level : " << m_CompressionLevel << "\n"; } void RVFImageIO::ReadImageInformation() { RVF_header header; std::ifstream infile(m_FileName.c_str()); if(!infile){ itkExceptionMacro("Error RVFImageIO could not open file: " << this->GetFileName()); return; } infile.read((char *) &header, sizeof(header)); infile.close(); //swap if needed if(!CTC_BIG_ENDIAN) swab(header.magic); if(header.magic != RVF_MAGIC_NUMBER){ itkExceptionMacro("Error File not of type rvf: " << this->GetFileName()); return; } //swap if needed if(!CTC_BIG_ENDIAN) { swab(header.magic); swab(header.version); swab(header.serial); swab(header.xDim); swab(header.yDim); swab(header.zDim); swab(header.bits); swab(header.x_flipX); swab(header.x_flipY); swab(header.y_flipX); swab(header.y_flipY); swab(header.z_flipX); swab(header.z_flipY); swab(header.xPat_org); swab(header.yPat_org); swab(header.zPat_org); swab(header.xPat_step); swab(header.yPat_step); swab(header.zPat_step); swab(header.dicomHeaderFollows); swab(header.dicomHeaderSize); } this->SetNumberOfDimensions(3); m_Spacing[0] = header.xPat_step; m_Spacing[1] = header.yPat_step; m_Spacing[2] = header.zPat_step; m_Origin[0] = header.xPat_org; m_Origin[1] = header.yPat_org; m_Origin[2] = header.zPat_org; m_Dimensions[0] = header.xDim; m_Dimensions[1] = header.yDim; m_Dimensions[2] = header.zDim; m_PixelType = SCALAR; m_ComponentType = USHORT; return; } bool RVFImageIO::CanWriteFile( const char * name ) { std::string filename = name; if (filename == "") { return false; } std::string::size_type RVFPos = filename.rfind(".rvf"); if ( (RVFPos != std::string::npos) && (RVFPos == filename.length() - 4) ) { return true; } RVFPos = filename.rfind(".RVF"); if ( (RVFPos != std::string::npos) && (RVFPos == filename.length() - 4) ) { return true; } // make sure the output voxel type is ushort if ( (m_PixelType != SCALAR) || ( m_ComponentType != USHORT) ) { return false; } return false; } void RVFImageIO::WriteImageInformation(void) { } void RVFImageIO::Write(const void* buffer) { itk::ImageIORegion ioRegion = this->GetIORegion(); // make sure the region to be written is 3D const unsigned int ImageDimension = ioRegion.GetRegionDimension(); if ( ImageDimension != 3 ) { itkExceptionMacro(<<"RVF Writer can only write 3-dimensional sclar ushort images. You are requesting to write an image of dimension = " << ImageDimension << " with filename " << m_FileName); } // make sure the output voxel type is ushort if ( (m_PixelType != SCALAR) || ( m_ComponentType != USHORT) ) { itkExceptionMacro(<<"RVF Writer can only write 3-dimensional scalar ushort images."); } RVF_header header; header.magic = RVF_MAGIC_NUMBER; header.version = RVF_CURRENT_VERSION; header.serial = 1; // could use rand header.xDim = this->GetDimensions(0); header.yDim = this->GetDimensions(1); header.zDim = this->GetDimensions(2); header.bits = 16; header.x_flipX = 0; header.x_flipY = 0; header.y_flipX = 0; header.y_flipY = 0; header.z_flipX = 0; header.z_flipY = 0; header.xPat_org = this->GetOrigin(0); header.yPat_org = this->GetOrigin(1); header.zPat_org = this->GetOrigin(2); header.xPat_step = this->GetSpacing(0); header.yPat_step = this->GetSpacing(1); header.zPat_step = this->GetSpacing(2); header.dicomHeaderFollows = 0; header.dicomHeaderSize = 0; // determine endianness of the current machine // RVF files should always be written in big endian bool swabreq; if(!CTC_BIG_ENDIAN) //little endian swabreq = true; else // big endian swabreq = false; // swap if needed if(swabreq) { swab(header.magic); swab(header.version); swab(header.serial); swab(header.xDim); swab(header.yDim); swab(header.zDim); swab(header.bits); swab(header.x_flipX); swab(header.x_flipY); swab(header.y_flipX); swab(header.y_flipY); swab(header.z_flipX); swab(header.z_flipY); swab(header.xPat_org); swab(header.yPat_org); swab(header.zPat_org); swab(header.xPat_step); swab(header.yPat_step); swab(header.zPat_step); swab(header.dicomHeaderFollows); swab(header.dicomHeaderSize); } std::ofstream outfile; outfile.open(m_FileName.c_str()); if(!outfile){ // workaround for a bug in Visual Studio 7.1 in release mode // see ITK bug tracking for details ::itk::ExceptionObject excp(__FILE__, __LINE__, "Problem while opening the file.", "Write"); throw excp; } outfile.write((char *) (&header), sizeof(header)); // write voxels from buffer argument const unsigned short *p = ( (const unsigned short *) buffer); unsigned short temp; int size = (this->GetDimensions(2))*(this->GetDimensions(1))*(this->GetDimensions(0)); for(int k=0; k < size; k++){ temp = *(p + k); if(swabreq) swab(temp); outfile.write((char *)(&temp), sizeof(unsigned short)); } outfile.close(); } } // end namespace ctc
24.163855
196
0.618767
[ "3d" ]
295b458055389a931286496d803ce59ddbe2a5da
8,910
cc
C++
msr-poll-gaps.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
8
2019-01-17T12:48:34.000Z
2022-02-04T11:40:58.000Z
msr-poll-gaps.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
null
null
null
msr-poll-gaps.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
2
2019-12-01T02:23:07.000Z
2019-12-09T02:56:44.000Z
/* * msr-poll-gaps.cc * Find the average gap between RAPL updates by polling via MSR driver. * * Author: Mikael Hirki <mikael.hirki@aalto.fi> */ #include <vector> /* The number of gaps to be observed */ #define MAX_GAPS 1000 /* Read the RAPL registers on a sandybridge-ep machine */ /* Code based on Intel RAPL driver by Zhang Rui <rui.zhang@intel.com> */ /* */ /* The /dev/cpu/??/msr driver must be enabled and permissions set */ /* to allow read access for this to work. */ /* */ /* Code to properly get this info from Linux through a real device */ /* driver and the perf tool should be available as of Linux 3.14 */ /* Compile with: gcc -O2 -Wall -o rapl-read rapl-read.c -lm */ /* */ /* Vince Weaver -- vincent.weaver @ maine.edu -- 29 November 2013 */ /* */ /* Additional contributions by: */ /* Romain Dolbeau -- romain @ dolbeau.org */ /* */ /* Latency polling modification by: */ /* Mikael Hirki <mikael.hirki@aalto.fi> */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include <inttypes.h> #include <unistd.h> #include <math.h> #include <string.h> #include <sched.h> #define MSR_RAPL_POWER_UNIT 0x606 /* * Platform specific RAPL Domains. * Note that PP1 RAPL Domain is supported on 062A only * And DRAM RAPL Domain is supported on 062D only */ /* Package RAPL Domain */ #define MSR_PKG_RAPL_POWER_LIMIT 0x610 #define MSR_PKG_ENERGY_STATUS 0x611 #define MSR_PKG_PERF_STATUS 0x613 #define MSR_PKG_POWER_INFO 0x614 /* PP0 RAPL Domain */ #define MSR_PP0_POWER_LIMIT 0x638 #define MSR_PP0_ENERGY_STATUS 0x639 #define MSR_PP0_POLICY 0x63A #define MSR_PP0_PERF_STATUS 0x63B /* PP1 RAPL Domain, may reflect to uncore devices */ #define MSR_PP1_POWER_LIMIT 0x640 #define MSR_PP1_ENERGY_STATUS 0x641 #define MSR_PP1_POLICY 0x642 /* DRAM RAPL Domain */ #define MSR_DRAM_POWER_LIMIT 0x618 #define MSR_DRAM_ENERGY_STATUS 0x619 #define MSR_DRAM_PERF_STATUS 0x61B #define MSR_DRAM_POWER_INFO 0x61C /* RAPL UNIT BITMASK */ #define POWER_UNIT_OFFSET 0 #define POWER_UNIT_MASK 0x0F #define ENERGY_UNIT_OFFSET 0x08 #define ENERGY_UNIT_MASK 0x1F00 #define TIME_UNIT_OFFSET 0x10 #define TIME_UNIT_MASK 0xF000 static int open_msr(int core) { char msr_filename[BUFSIZ]; int fd; sprintf(msr_filename, "/dev/cpu/%d/msr", core); fd = open(msr_filename, O_RDONLY); if ( fd < 0 ) { if ( errno == ENXIO ) { fprintf(stderr, "rdmsr: No CPU %d\n", core); exit(2); } else if ( errno == EIO ) { fprintf(stderr, "rdmsr: CPU %d doesn't support MSRs\n", core); exit(3); } else { perror("rdmsr:open"); fprintf(stderr,"Trying to open %s\n",msr_filename); exit(127); } } return fd; } #if 1 static uint64_t read_msr(int fd, int which) { uint64_t data; if (pread(fd, &data, sizeof(data), which) != sizeof(data)) { perror("rdmsr:pread"); exit(127); } return data; } #else static uint64_t read_msr(int fd, int which) { uint64_t data; if (lseek(fd, which, SEEK_SET) == -1) { perror("lseek"); exit(127); } if (read(fd, &data, sizeof(data)) != sizeof(data)) { perror("read"); exit(127); } return data; } #endif #define CPU_SANDYBRIDGE 42 #define CPU_SANDYBRIDGE_EP 45 #define CPU_IVYBRIDGE 58 #define CPU_IVYBRIDGE_EP 62 #define CPU_HASWELL 60 static int detect_cpu(void) { FILE *fff; int family,model=-1; char buffer[BUFSIZ],*result; char vendor[BUFSIZ]; fff=fopen("/proc/cpuinfo","r"); if (fff==NULL) return -1; while(1) { result=fgets(buffer,BUFSIZ,fff); if (result==NULL) break; if (!strncmp(result,"vendor_id",8)) { sscanf(result,"%*s%*s%s",vendor); if (strncmp(vendor,"GenuineIntel",12)) { printf("%s not an Intel chip\n",vendor); return -1; } } if (!strncmp(result,"cpu family",10)) { sscanf(result,"%*s%*s%*s%d",&family); if (family!=6) { printf("Wrong CPU family %d\n",family); return -1; } } if (!strncmp(result,"model",5)) { sscanf(result,"%*s%*s%d",&model); } } fclose(fff); switch(model) { case CPU_SANDYBRIDGE: printf("Found Sandybridge CPU\n"); break; case CPU_SANDYBRIDGE_EP: printf("Found Sandybridge-EP CPU\n"); break; case CPU_IVYBRIDGE: printf("Found Ivybridge CPU\n"); break; case CPU_IVYBRIDGE_EP: printf("Found Ivybridge-EP CPU\n"); break; case CPU_HASWELL: printf("Found Haswell CPU\n"); break; default: printf("Unsupported model %d\n",model); model=-1; break; } return model; } #define RAPL_HAVE_PKG_ENERGY_STATUS 0x0001 #define RAPL_HAVE_PP0_ENERGY_STATUS 0x0002 #define RAPL_HAVE_PP1_ENERGY_STATUS 0x0004 #define RAPL_HAVE_DRAM_ENERGY_STATUS 0x0008 #define RAPL_HAVE_PKG_PERF_STATUS 0x0010 #define RAPL_HAVE_PP0_PERF_STATUS 0x0020 #define RAPL_HAVE_PP1_PERF_STATUS 0x0040 #define RAPL_HAVE_DRAM_PERF_STATUS 0x0080 static unsigned detect_rapl(int cpu_model) { unsigned capab = (RAPL_HAVE_PKG_ENERGY_STATUS | RAPL_HAVE_PP0_ENERGY_STATUS); /* only available on *Bridge-EP */ if ((cpu_model==CPU_SANDYBRIDGE_EP) || (cpu_model==CPU_IVYBRIDGE_EP)) { capab |= (RAPL_HAVE_PKG_PERF_STATUS | RAPL_HAVE_PP0_PERF_STATUS); } /* not available on *Bridge-EP */ if ((cpu_model==CPU_SANDYBRIDGE) || (cpu_model==CPU_IVYBRIDGE) || (cpu_model==CPU_HASWELL)) { capab |= RAPL_HAVE_PP1_ENERGY_STATUS; } /* Despite documentation saying otherwise, it looks like */ /* You can get DRAM readings on regular Haswell */ if ((cpu_model==CPU_SANDYBRIDGE_EP) || (cpu_model==CPU_IVYBRIDGE_EP) || (cpu_model==CPU_HASWELL)) { capab |= RAPL_HAVE_DRAM_ENERGY_STATUS; } return capab; } static int do_affinity(int core) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(core, &mask); int result = sched_setaffinity(0, sizeof(mask), &mask); return result >= 0; } static double gettimeofday_double() { struct timeval now; gettimeofday(&now, NULL); return now.tv_sec + now.tv_usec * 0.000001; } int main(int argc, char **argv) { int fd = -1; int core = 0; int c = 0; uint64_t result = 0; int cpu_model = -1; unsigned capab = 0; int i = 0, iteration = 0; opterr=0; while ((c = getopt (argc, argv, "c:")) != -1) { switch (c) { case 'c': core = atoi(optarg); break; default: exit(-1); } } do_affinity(core); cpu_model=detect_cpu(); if (cpu_model<0) { printf("Unsupported CPU type\n"); return -1; } capab = detect_rapl(cpu_model); fd=open_msr(core); // Benchmark MSR register reads uint64_t prev_energy = read_msr(fd, MSR_PKG_ENERGY_STATUS); double fstart = gettimeofday_double(); double fprev = fstart; double fnow = fstart; double gap = 0.0; std::vector<double> gaps; gaps.reserve(MAX_GAPS); double sum_gaps = 0.0; double biggest_gap = 0.0; int num_gaps = -1; for (iteration = 0; num_gaps < MAX_GAPS; iteration++) { result = read_msr(fd, MSR_PKG_ENERGY_STATUS); if (result != prev_energy) { prev_energy = result; fnow = gettimeofday_double(); gap = fnow - fprev; num_gaps++; // Ignore the first gap if (num_gaps > 0) { sum_gaps += gap; if (gap > biggest_gap) biggest_gap = gap; gaps.push_back(gap); } //printf("%lld at %f seconds, %f second gap since previous\n", prev_energy, fnow - fstart, gap); fprev = fnow; } } fnow = gettimeofday_double(); printf("%d iterations in %f seconds.\n", iteration, fnow - fstart); printf("Polling rate of %f hz.\n", iteration / (fnow - fstart)); printf("PAPI polling delay of %f microseconds.\n", (fnow - fstart) / iteration * 1000000.0); printf("Biggest gap was %f millisecond.\n", biggest_gap * 1000.0); double avg_gap = sum_gaps / num_gaps; printf("Average gap of %f milliseconds.\n", avg_gap * 1000.0); // Calculate standard deviation double sum_squares = 0.0; for (i = 0; i < num_gaps; i++) { double diff = gaps[i] - avg_gap; sum_squares += diff * diff; } printf("Standard deviation of the gaps is %f microseconds.\n", sqrt(sum_squares / num_gaps) * 1000000.0); // Dump the gaps to a file FILE *fp = fopen("gaps-msr.csv", "w"); if (!fp) { fprintf(stderr, "Failed to open gaps-msr.csv!\n"); } else { printf("Dumping data to gaps-msr.csv\n"); for (i = 0; i < num_gaps; i++) { fprintf(fp, "%f\n", gaps[i]); } fclose(fp); } // Kill compiler warnings (void)argc; (void)argv; (void)capab; (void)result; return 0; }
25.240793
106
0.637598
[ "vector", "model" ]
295b969b33e77078f0778655297475808fa92eaa
42,410
cpp
C++
Engine/source/gui/containers/guiScrollCtrl.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
10
2015-03-12T20:20:34.000Z
2021-02-03T08:07:31.000Z
Engine/source/gui/containers/guiScrollCtrl.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
3
2015-07-04T23:50:43.000Z
2016-08-01T09:19:52.000Z
Engine/source/gui/containers/guiScrollCtrl.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
6
2015-11-28T16:18:26.000Z
2020-03-29T17:14:56.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "platform/typetraits.h" #include "gui/containers/guiScrollCtrl.h" #include "console/engineAPI.h" #include "console/console.h" #include "gfx/bitmap/gBitmap.h" #include "gui/core/guiDefaultControlRender.h" #include "gfx/gfxDevice.h" #include "gfx/gfxDrawUtil.h" #include "gui/core/guiCanvas.h" IMPLEMENT_CONOBJECT( GuiScrollCtrl ); ConsoleDocClass( GuiScrollCtrl, "@brief A container that allows to view one or more possibly larger controls inside its area by " "providing horizontal and/or vertical scroll bars.\n\n" "@ingroup GuiContainers" ); ImplementEnumType( GuiScrollBarBehavior, "Display behavior of a scroll bar. Determines when a scrollbar will be visible.\n\n" "@ingroup GuiContainers" ) { GuiScrollCtrl::ScrollBarAlwaysOn, "alwaysOn", "Always visible." }, { GuiScrollCtrl::ScrollBarAlwaysOff, "alwaysOff", "Never visible." }, { GuiScrollCtrl::ScrollBarDynamic, "dynamic", "Only visible when actually needed, i.e. when the child control(s) exceed the visible space on the given axis." }, EndImplementEnumType; IMPLEMENT_CALLBACK( GuiScrollCtrl, onScroll, void, (), (), "Called each time the child controls are scrolled by some amount." ); //----------------------------------------------------------------------------- GuiScrollCtrl::GuiScrollCtrl() : mChildMargin( 0, 0 ), mBorderThickness( 1 ), mScrollBarThickness( 16 ), mScrollBarArrowBtnLength( 16 ), mScrollBarDragTolerance( 130 ), mStateDepressed( false ), mHitRegion( None ), mWillFirstRespond( true ), mUseConstantHeightThumb( false ), mForceVScrollBar( ScrollBarAlwaysOn ), mForceHScrollBar( ScrollBarAlwaysOn ), mLockHorizScroll( false ), mLockVertScroll( false ), mIgnoreChildResized( false ), mAnimating( false ), mScrollAnimSpeed( -1 ), mScrollTargetPos( -1, -1 ), mChildExt(0, 0), mChildPos(0, 0), mBaseThumbSize(0) { mIsContainer = true; setExtent(200,200); } //----------------------------------------------------------------------------- void GuiScrollCtrl::initPersistFields() { addGroup( "Scolling" ); addField( "willFirstRespond", TypeBool, Offset(mWillFirstRespond, GuiScrollCtrl)); addField( "hScrollBar", TYPEID< ScrollBarBehavior >(), Offset(mForceHScrollBar, GuiScrollCtrl), "When to display the horizontal scrollbar."); addField( "vScrollBar", TYPEID< ScrollBarBehavior >(), Offset(mForceVScrollBar, GuiScrollCtrl), "When to display the vertical scrollbar."); addField( "lockHorizScroll", TypeBool, Offset(mLockHorizScroll, GuiScrollCtrl), "Horizontal scrolling not allowed if set."); addField( "lockVertScroll", TypeBool, Offset(mLockVertScroll, GuiScrollCtrl), "Vertical scrolling not allowed if set."); addField( "constantThumbHeight", TypeBool, Offset(mUseConstantHeightThumb, GuiScrollCtrl)); addField( "childMargin", TypePoint2I, Offset(mChildMargin, GuiScrollCtrl), "Padding region to put around child contents." ); addField( "mouseWheelScrollSpeed", TypeS32, Offset(mScrollAnimSpeed, GuiScrollCtrl), "Pixels/Tick - if not positive then mousewheel scrolling occurs instantly (like other scrolling)."); endGroup( "Scrolling" ); Parent::initPersistFields(); } //----------------------------------------------------------------------------- bool GuiScrollCtrl::resize(const Point2I &newPos, const Point2I &newExt) { if( !Parent::resize(newPos, newExt) ) return false; computeSizes(); return true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::childResized(GuiControl *child) { if ( mIgnoreChildResized ) return; Parent::childResized(child); computeSizes(); } //----------------------------------------------------------------------------- bool GuiScrollCtrl::onWake() { if (! Parent::onWake()) return false; mTextureObject = mProfile->mTextureObject; if (mTextureObject && (mProfile->constructBitmapArray() >= BmpStates * BmpCount)) { mBitmapBounds = mProfile->mBitmapArrayRects.address(); //init mBaseThumbSize = mBitmapBounds[BmpStates * BmpVThumbTopCap].extent.y + mBitmapBounds[BmpStates * BmpVThumbBottomCap].extent.y; mScrollBarThickness = mBitmapBounds[BmpStates * BmpVPage].extent.x; mScrollBarArrowBtnLength = mBitmapBounds[BmpStates * BmpUp].extent.y; computeSizes(); } else { Con::warnf("No texture loaded for scroll control named %s with profile %s", getName(), mProfile->getName()); } return true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::onSleep() { // Reset the mouse tracking state of this control // when it is put to sleep mStateDepressed = false; mHitRegion = None; Parent::onSleep(); mTextureObject = NULL; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::calcChildExtents() { // scroll control should deal well with multiple gui controls if( !size() ) return false; // Find size and relative position of the client rectangle. Point2I maxPos( TypeTraits< S32 >::MIN, TypeTraits< S32 >::MIN ); Point2I minPos( TypeTraits< S32 >::MAX, TypeTraits< S32 >::MAX ); bool haveVisibleChild = false; for( U32 i = 0; i < size(); i++ ) { GuiControl *ctrl = (GuiControl*)at(i); if( ctrl->isVisible() ) { haveVisibleChild = true; minPos.x = getMin( ctrl->getPosition().x, minPos.x ); minPos.y = getMin( ctrl->getPosition().y, minPos.y ); // This is +1 but the remaining code here all works with extents +1. Point2I ctrlMax = ctrl->getPosition() + ctrl->getExtent(); maxPos.x = getMax( ctrlMax.x, maxPos.x ); maxPos.y = getMax( ctrlMax.y, maxPos.y ); } } if( !haveVisibleChild ) return false; mChildPos = minPos; mChildExt = maxPos - minPos; return true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollRectVisible(RectI rect) { // rect is passed in virtual client space if(rect.extent.x > mContentExt.x) rect.extent.x = mContentExt.x; if(rect.extent.y > mContentExt.y) rect.extent.y = mContentExt.y; // Determine the points bounding the requested rectangle Point2I rectUpperLeft = rect.point; Point2I rectLowerRight = rect.point + rect.extent; // Determine the points bounding the actual visible area... Point2I visUpperLeft = mChildRelPos; Point2I visLowerRight = mChildRelPos + mContentExt; Point2I delta(0,0); // We basically try to make sure that first the top left of the given // rect is visible, and if it is, then that the bottom right is visible. // Make sure the rectangle is visible along the X axis... if(rectUpperLeft.x < visUpperLeft.x) delta.x = rectUpperLeft.x - visUpperLeft.x; else if(rectLowerRight.x > visLowerRight.x) delta.x = rectLowerRight.x - visLowerRight.x; // Make sure the rectangle is visible along the Y axis... if(rectUpperLeft.y < visUpperLeft.y) delta.y = rectUpperLeft.y - visUpperLeft.y; else if(rectLowerRight.y > visLowerRight.y) delta.y = rectLowerRight.y - visLowerRight.y; // If we had any changes, scroll, otherwise don't. if(delta.x || delta.y) scrollDelta(delta.x, delta.y); } //----------------------------------------------------------------------------- bool GuiScrollCtrl::isPointVisible( const Point2I& point ) { return ( point.x >= mChildRelPos.x && point.x <= ( mChildRelPos.x + mContentExt.x ) ) && ( point.y >= mChildRelPos.y && point.y <= ( mChildRelPos.y + mContentExt.y ) ); } //----------------------------------------------------------------------------- bool GuiScrollCtrl::isRectCompletelyVisible(const RectI& rect) { // rect is passed in virtual client space // Determine the points bounding the requested rectangle Point2I rectUpperLeft = rect.point; Point2I rectLowerRight = rect.point + rect.extent; // Determine the points bounding the actual visible area... Point2I visUpperLeft = mChildRelPos; Point2I visLowerRight = mChildRelPos + mContentExt; // Make sure the rectangle is visible along the X axis... if(rectUpperLeft.x < visUpperLeft.x) return false; else if(rectLowerRight.x > visLowerRight.x) return false; // Make sure the rectangle is visible along the Y axis... if(rectUpperLeft.y < visUpperLeft.y) return false; else if(rectLowerRight.y > visLowerRight.y) return false; return true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::addObject(SimObject *object) { Parent::addObject(object); computeSizes(); } //----------------------------------------------------------------------------- GuiControl* GuiScrollCtrl::findHitControl(const Point2I &pt, S32 initialLayer) { if(pt.x < mProfile->mBorderThickness || pt.y < mProfile->mBorderThickness) return this; if(pt.x >= getWidth() - mProfile->mBorderThickness - (mHasVScrollBar ? mScrollBarThickness : 0) || pt.y >= getHeight() - mProfile->mBorderThickness - (mHasHScrollBar ? mScrollBarThickness : 0)) return this; return Parent::findHitControl(pt, initialLayer); } //----------------------------------------------------------------------------- void GuiScrollCtrl::computeSizes() { S32 thickness = (mProfile ? mProfile->mBorderThickness : 1); Point2I borderExtent(thickness, thickness); mContentPos = borderExtent + mChildMargin; mContentExt = getExtent() - (mChildMargin * 2) - (borderExtent * 2); Point2I childLowerRight; mHBarEnabled = false; mVBarEnabled = false; mHasVScrollBar = (mForceVScrollBar == ScrollBarAlwaysOn); mHasHScrollBar = (mForceHScrollBar == ScrollBarAlwaysOn); setUpdate(); if (calcChildExtents()) { childLowerRight = mChildPos + mChildExt; if (mHasVScrollBar) mContentExt.x -= mScrollBarThickness; if (mHasHScrollBar) mContentExt.y -= mScrollBarThickness; if (mChildExt.x > mContentExt.x && (mForceHScrollBar == ScrollBarDynamic)) { mHasHScrollBar = true; mContentExt.y -= mScrollBarThickness; } if (mChildExt.y > mContentExt.y && (mForceVScrollBar == ScrollBarDynamic)) { mHasVScrollBar = true; mContentExt.x -= mScrollBarThickness; // If Extent X Changed, check Horiz Scrollbar. if (mChildExt.x > mContentExt.x && !mHasHScrollBar && (mForceHScrollBar == ScrollBarDynamic)) { mHasHScrollBar = true; mContentExt.y -= mScrollBarThickness; } } Point2I contentLowerRight = mContentPos + mContentExt; // see if the child controls need to be repositioned (null space in control) Point2I delta(0,0); if (mChildPos.x > mContentPos.x) delta.x = mContentPos.x - mChildPos.x; else if (contentLowerRight.x > childLowerRight.x) { S32 diff = contentLowerRight.x - childLowerRight.x; delta.x = getMin(mContentPos.x - mChildPos.x, diff); } //reposition the children if the child extent > the scroll content extent if (mChildPos.y > mContentPos.y) delta.y = mContentPos.y - mChildPos.y; else if (contentLowerRight.y > childLowerRight.y) { S32 diff = contentLowerRight.y - childLowerRight.y; delta.y = getMin(mContentPos.y - mChildPos.y, diff); } // apply the deltas to the children... if (delta.x || delta.y) { SimGroup::iterator i; for(i = begin(); i != end();i++) { GuiControl *ctrl = (GuiControl *) (*i); ctrl->setPosition( ctrl->getPosition() + delta ); } mChildPos += delta; childLowerRight += delta; } // enable needed scroll bars if (mChildExt.x > mContentExt.x) mHBarEnabled = true; if (mChildExt.y > mContentExt.y) mVBarEnabled = true; mChildRelPos = mContentPos - mChildPos; } // Prevent resizing our children from recalling this function! mIgnoreChildResized = true; if ( mLockVertScroll ) { // If vertical scroll is locked we size our child's height to our own SimGroup::iterator i; for(i = begin(); i != end();i++) { GuiControl *ctrl = (GuiControl *) (*i); ctrl->setHeight( mContentExt.y ); } } if ( mLockHorizScroll ) { // If horizontal scroll is locked we size our child's width to our own SimGroup::iterator i; for(i = begin(); i != end();i++) { GuiControl *ctrl = (GuiControl *) (*i); ctrl->setWidth( mContentExt.x ); } } mIgnoreChildResized = false; // build all the rectangles and such... calcScrollRects(); calcThumbs(); } //----------------------------------------------------------------------------- void GuiScrollCtrl::calcScrollRects(void) { S32 thickness = ( mProfile ? mProfile->mBorderThickness : 1 ); if (mHasHScrollBar) { mLeftArrowRect.set(thickness, getHeight() - thickness - mScrollBarThickness, mScrollBarArrowBtnLength, mScrollBarThickness); mRightArrowRect.set(getWidth() - thickness - (mHasVScrollBar ? mScrollBarThickness - 1 : 0) - mScrollBarArrowBtnLength, getHeight() - thickness - mScrollBarThickness, mScrollBarArrowBtnLength, mScrollBarThickness); mHTrackRect.set(mLeftArrowRect.point.x + mLeftArrowRect.extent.x, mLeftArrowRect.point.y, mRightArrowRect.point.x - (mLeftArrowRect.point.x + mLeftArrowRect.extent.x), mScrollBarThickness); } if (mHasVScrollBar) { mUpArrowRect.set(getWidth() - thickness - mScrollBarThickness, thickness, mScrollBarThickness, mScrollBarArrowBtnLength); mDownArrowRect.set(getWidth() - thickness - mScrollBarThickness, getHeight() - thickness - (mHasHScrollBar ? mScrollBarThickness - 1 : 0) - mScrollBarArrowBtnLength, mScrollBarThickness, mScrollBarArrowBtnLength); mVTrackRect.set(mUpArrowRect.point.x, mUpArrowRect.point.y + mUpArrowRect.extent.y, mScrollBarThickness, mDownArrowRect.point.y - (mUpArrowRect.point.y + mUpArrowRect.extent.y) ); } } //----------------------------------------------------------------------------- void GuiScrollCtrl::calcThumbs() { if (mHBarEnabled && mChildExt.x > 0) { U32 trackSize = mHTrackRect.len_x(); if (mUseConstantHeightThumb) mHThumbSize = mBaseThumbSize; else mHThumbSize = getMax(mBaseThumbSize, ( S32 )mCeil( ( F32 )( mContentExt.x * trackSize) / ( F32 )mChildExt.x ) ); mHThumbPos = mHTrackRect.point.x + (mChildRelPos.x * (trackSize - mHThumbSize)) / (mChildExt.x - mContentExt.x); } if (mVBarEnabled && mChildExt.y > 0) { U32 trackSize = mVTrackRect.len_y(); if (mUseConstantHeightThumb) mVThumbSize = mBaseThumbSize; else mVThumbSize = getMax(mBaseThumbSize, ( S32 )mCeil( ( F32 )( mContentExt.y * trackSize ) / ( F32 )mChildExt.y ) ); mVThumbPos = mVTrackRect.point.y + (mChildRelPos.y * (trackSize - mVThumbSize)) / (mChildExt.y - mContentExt.y); } } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollDelta(S32 deltaX, S32 deltaY) { scrollTo(mChildRelPos.x + deltaX, mChildRelPos.y + deltaY); onScroll_callback(); } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollDeltaAnimate(S32 x, S32 y) { if ( !size() ) return; if ( mAnimating ) mScrollTargetPos += Point2I( x, y ); else mScrollTargetPos = mChildRelPos + Point2I( x, y ); setUpdate(); mScrollTargetPos.setMin( mChildExt - mContentExt ); mScrollTargetPos.setMax( Point2I::Zero ); mAnimating = true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollTo(S32 x, S32 y) { if( !size() ) return; if ( x == mChildRelPos.x && y == mChildRelPos.y ) return; setUpdate(); if (x > mChildExt.x - mContentExt.x) x = mChildExt.x - mContentExt.x; if (x < 0) x = 0; if (y > mChildExt.y - mContentExt.y) y = mChildExt.y - mContentExt.y; if (y < 0) y = 0; Point2I delta(x - mChildRelPos.x, y - mChildRelPos.y); mChildRelPos += delta; mChildPos -= delta; for(SimSet::iterator i = begin(); i != end();i++) { GuiControl *ctrl = (GuiControl *) (*i); ctrl->setPosition( ctrl->getPosition() - delta ); } calcThumbs(); onScroll_callback(); } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollToObject(GuiControl *targetControl) { bool isValidChild = false; Point2I relativePosition = targetControl->getPosition(); GuiControl* parentControl = targetControl->getParent(); while (parentControl) { GuiScrollCtrl* scrollControl = dynamic_cast<GuiScrollCtrl*>(parentControl); if (scrollControl == this) { relativePosition += scrollControl->getChildRelPos(); isValidChild = true; break; } relativePosition += parentControl->getPosition(); parentControl = parentControl->getParent(); } if (isValidChild) { scrollRectVisible(RectI(relativePosition, targetControl->getExtent())); } else { Con::errorf("GuiScrollCtrl::scrollToObject() - Specified object is not a child of this scroll control (%d)!", targetControl->getId()); } } //----------------------------------------------------------------------------- GuiScrollCtrl::Region GuiScrollCtrl::findHitRegion(const Point2I &pt) { if (mVBarEnabled && mHasVScrollBar) { if (mUpArrowRect.pointInRect(pt)) return UpArrow; else if (mDownArrowRect.pointInRect(pt)) return DownArrow; else if (mVTrackRect.pointInRect(pt)) { if (pt.y < mVThumbPos) return UpPage; else if (pt.y < mVThumbPos + mVThumbSize) return VertThumb; else return DownPage; } } if (mHBarEnabled && mHasHScrollBar) { if (mLeftArrowRect.pointInRect(pt)) return LeftArrow; else if (mRightArrowRect.pointInRect(pt)) return RightArrow; else if (mHTrackRect.pointInRect(pt)) { if (pt.x < mHThumbPos) return LeftPage; else if (pt.x < mHThumbPos + mHThumbSize) return HorizThumb; else return RightPage; } } return None; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::wantsTabListMembership() { return true; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::loseFirstResponder() { setUpdate(); return true; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::becomeFirstResponder() { setUpdate(); return mWillFirstRespond; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::onKeyDown(const GuiEvent &event) { if (mWillFirstRespond) { switch (event.keyCode) { case KEY_RIGHT: scrollByRegion(RightArrow); return true; case KEY_LEFT: scrollByRegion(LeftArrow); return true; case KEY_DOWN: scrollByRegion(DownArrow); return true; case KEY_UP: scrollByRegion(UpArrow); return true; case KEY_PAGE_UP: scrollByRegion(UpPage); return true; case KEY_PAGE_DOWN: scrollByRegion(DownPage); return true; default: break; } } return Parent::onKeyDown(event); } //----------------------------------------------------------------------------- void GuiScrollCtrl::_onMouseDown( const GuiEvent &event, bool lockMouse ) { if( lockMouse ) { mouseLock(); mStateDepressed = true; } setUpdate(); Point2I curMousePos = globalToLocalCoord(event.mousePoint); mHitRegion = findHitRegion(curMousePos); // Set a 0.5 second delay before we start scrolling mLastUpdated = Platform::getVirtualMilliseconds() + 500; scrollByRegion(mHitRegion); if (mHitRegion == VertThumb) { mChildRelPosAnchor = mChildRelPos; mThumbMouseDelta = curMousePos.y - mVThumbPos; } else if (mHitRegion == HorizThumb) { mChildRelPosAnchor = mChildRelPos; mThumbMouseDelta = curMousePos.x - mHThumbPos; } } //----------------------------------------------------------------------------- void GuiScrollCtrl::onMouseDown(const GuiEvent &event) { _onMouseDown( event, true ); } //----------------------------------------------------------------------------- bool GuiScrollCtrl::onMouseDownEditor( const GuiEvent& event, Point2I offset ) { // If ALT is pressed while clicking on a horizontal or vertical scrollbar, // do a scroll. if( event.modifier & SI_PRIMARY_ALT ) { Region hitRegion = findHitRegion( globalToLocalCoord( event.mousePoint ) ); if( hitRegion != None ) { _onMouseDown( event, false ); return true; } } return false; } //----------------------------------------------------------------------------- void GuiScrollCtrl::onMouseUp(const GuiEvent &) { mouseUnlock(); setUpdate(); mHitRegion = None; mStateDepressed = false; } //----------------------------------------------------------------------------- void GuiScrollCtrl::onMouseDragged(const GuiEvent &event) { Point2I curMousePos = globalToLocalCoord(event.mousePoint); setUpdate(); if ( (mHitRegion != VertThumb) && (mHitRegion != HorizThumb) ) { Region hit = findHitRegion(curMousePos); if (hit != mHitRegion) mStateDepressed = false; else mStateDepressed = true; return; } // ok... if the mouse is 'near' the scroll bar, scroll with it // otherwise, snap back to the previous position. if (mHitRegion == VertThumb) { if (curMousePos.x >= mVTrackRect.point.x - mScrollBarDragTolerance && curMousePos.x <= mVTrackRect.point.x + mVTrackRect.extent.x - 1 + mScrollBarDragTolerance && curMousePos.y >= mVTrackRect.point.y - mScrollBarDragTolerance && curMousePos.y <= mVTrackRect.point.y + mVTrackRect.extent.y - 1 + mScrollBarDragTolerance) { S32 newVThumbPos = curMousePos.y - mThumbMouseDelta; if(newVThumbPos != mVThumbPos) { S32 newVPos = (newVThumbPos - mVTrackRect.point.y) * (mChildExt.y - mContentExt.y) / (mVTrackRect.extent.y - mVThumbSize); scrollTo(mChildRelPosAnchor.x, newVPos); } } else scrollTo(mChildRelPosAnchor.x, mChildRelPosAnchor.y); } else if (mHitRegion == HorizThumb) { if (curMousePos.x >= mHTrackRect.point.x - mScrollBarDragTolerance && curMousePos.x <= mHTrackRect.point.x + mHTrackRect.extent.x - 1 + mScrollBarDragTolerance && curMousePos.y >= mHTrackRect.point.y - mScrollBarDragTolerance && curMousePos.y <= mHTrackRect.point.y + mHTrackRect.extent.y - 1 + mScrollBarDragTolerance) { S32 newHThumbPos = curMousePos.x - mThumbMouseDelta; if(newHThumbPos != mHThumbPos) { S32 newHPos = (newHThumbPos - mHTrackRect.point.x) * (mChildExt.x - mContentExt.x) / (mHTrackRect.extent.x - mHThumbSize); scrollTo(newHPos, mChildRelPosAnchor.y); } } else scrollTo(mChildRelPosAnchor.x, mChildRelPosAnchor.y); } } //----------------------------------------------------------------------------- bool GuiScrollCtrl::onMouseWheelUp(const GuiEvent &event) { if ( !mAwake || !mVisible ) return false; scrollByMouseWheel( event ); return true; } //----------------------------------------------------------------------------- bool GuiScrollCtrl::onMouseWheelDown(const GuiEvent &event) { if ( !mAwake || !mVisible ) return false; scrollByMouseWheel( event ); return true; } //----------------------------------------------------------------------------- void GuiScrollCtrl::updateChildMousePos() { // We pass a fake GuiEvent to child controls onMouseMove // since although the mouse has not moved 'they' have. // // Its possible this could cause problems if a GuiControl // responds to more than just the mouse position in the onMouseMove // event, like for example doing something different depending on // a modifier key, which we aren't filling in to the structure! GuiEvent event; event.mousePoint = getRoot()->getCursorPos(); iterator itr; for ( itr = begin(); itr != end(); itr++ ) { GuiControl *child = static_cast<GuiControl*>( *itr ); child->onMouseMove( event ); } } //----------------------------------------------------------------------------- void GuiScrollCtrl::onPreRender() { Parent::onPreRender(); S32 currentTime = Platform::getVirtualMilliseconds(); S32 deltaMs = currentTime - mLastPreRender; mLastPreRender = currentTime; // Update mouse-wheel scroll animation if we are currently doing one... if ( mAnimating ) { //U32 frames = Con::getIntVariable( "$frames", 0 ); //frames++; //Con::setIntVariable( "$frames", frames ); F32 deltaTicks = deltaMs / 32.0f; if ( mScrollAnimSpeed <= 0 ) { scrollTo( mScrollTargetPos.x, mScrollTargetPos.y ); } else { S32 maxPixels = deltaTicks * mScrollAnimSpeed; Point2I toTarget = mScrollTargetPos - mChildRelPos; S32 signx = toTarget.x > 0 ? 1 : -1; S32 signy = toTarget.y > 0 ? 1 : -1; S32 deltaX = getMin( mAbs(toTarget.x), maxPixels ) * signx; S32 deltaY = getMin( mAbs(toTarget.y), maxPixels ) * signy; scrollDelta( deltaX, deltaY ); } if ( mChildRelPos == mScrollTargetPos ) { //Con::printf( "Animated Frames : %d", frames ); //Con::setIntVariable( "$frames", 0 ); mAnimating = false; } updateChildMousePos(); } // Now scroll in response to a 'depressed state' if appropriate... // Short circuit if not depressed to save cycles if( mStateDepressed != true ) return; //default to one second, though it shouldn't be necessary U32 timeThreshold = 1000; // We don't want to scroll by pages at an interval the same as when we're scrolling // using the arrow buttons, so adjust accordingly. switch( mHitRegion ) { case UpPage: case DownPage: case LeftPage: case RightPage: timeThreshold = 200; break; case UpArrow: case DownArrow: case LeftArrow: case RightArrow: timeThreshold = 20; break; default: // Neither a button or a page, don't scroll (shouldn't get here) return; break; }; S32 timeElapsed = Platform::getVirtualMilliseconds() - mLastUpdated; if ( ( timeElapsed > 0 ) && ( timeElapsed > timeThreshold ) ) { mLastUpdated = Platform::getVirtualMilliseconds(); scrollByRegion(mHitRegion); } } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollByRegion(Region reg) { setUpdate(); if(!size()) return; GuiControl *content = (GuiControl *) front(); U32 rowHeight, columnWidth; U32 pageHeight, pageWidth; content->getScrollLineSizes(&rowHeight, &columnWidth); if(rowHeight >= mContentExt.y) pageHeight = 1; else pageHeight = mContentExt.y - rowHeight; if(columnWidth >= mContentExt.x) pageWidth = 1; else pageWidth = mContentExt.x - columnWidth; if (mVBarEnabled) { switch(reg) { case UpPage: scrollDelta(0, -(S32)pageHeight); break; case DownPage: scrollDelta(0, pageHeight); break; case UpArrow: scrollDelta(0, -(S32)rowHeight); break; case DownArrow: scrollDelta(0, rowHeight); break; default: break; } } if (mHBarEnabled) { switch(reg) { case LeftPage: scrollDelta(-(S32)pageWidth, 0); break; case RightPage: scrollDelta(pageWidth, 0); break; case LeftArrow: scrollDelta(-(S32)columnWidth, 0); break; case RightArrow: scrollDelta(columnWidth, 0); break; default: break; } } } //----------------------------------------------------------------------------- void GuiScrollCtrl::scrollByMouseWheel( const GuiEvent &event ) { setUpdate(); if ( !size() ) return; if( event.mouseAxis == 1 ) scrollDeltaAnimate( 0, -event.fval ); else scrollDeltaAnimate( -event.fval, 0 ); } //----------------------------------------------------------------------------- void GuiScrollCtrl::onRender(Point2I offset, const RectI &updateRect) { // draw content controls // create a rect to intersect with the updateRect RectI contentRect(mContentPos.x + offset.x, mContentPos.y + offset.y, mContentExt.x, mContentExt.y); contentRect.intersect(updateRect); // Always call parent Parent::onRender(offset, contentRect); if( mTextureObject ) { // Reset the ClipRect as the parent call can modify it when rendering // the child controls GFX->setClipRect( updateRect ); //draw the scroll corner if (mHasVScrollBar && mHasHScrollBar) drawScrollCorner(offset); // draw scroll bars if (mHasVScrollBar) drawVScrollBar(offset); if (mHasHScrollBar) drawHScrollBar(offset); } } //----------------------------------------------------------------------------- void GuiScrollCtrl::drawBorder( const Point2I &offset, bool /*isFirstResponder*/ ) { } //----------------------------------------------------------------------------- void GuiScrollCtrl::drawVScrollBar(const Point2I &offset) { if ( mTextureObject.isNull() ) { return; } // Start Point. Point2I pos = ( offset + mUpArrowRect.point ); // Up Arrow. S32 upArrowBitmap = ( BmpStates * BmpUp ); if ( !mVBarEnabled ) { upArrowBitmap += BmpDisabled; } else if ( mHitRegion == UpArrow && mStateDepressed ) { upArrowBitmap += BmpHilite; } // Render Up Arrow. GFXDrawUtil* drawUtil = GFX->getDrawUtil(); drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[upArrowBitmap]); // Update Pos. pos.y += mBitmapBounds[upArrowBitmap].extent.y; // Track. S32 trackBitmap = ( BmpStates * BmpVPage ); if ( !mVBarEnabled ) { trackBitmap += BmpDisabled; } else if ( mHitRegion == DownPage && mStateDepressed ) { trackBitmap += BmpHilite; } // Determine the Track Rect. RectI trackRect; trackRect.point = pos; trackRect.extent.x = mBitmapBounds[trackBitmap].extent.x; trackRect.extent.y = ( offset.y + mDownArrowRect.point.y ) - pos.y; // Render Track? if ( trackRect.extent.y > 0 ) { // Render Track. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapStretchSR(mTextureObject, trackRect, mBitmapBounds[trackBitmap]); } // Update Pos. pos.y += trackRect.extent.y; // Down Arrow. S32 downArrowBitmap = ( BmpStates * BmpDown ); if ( !mVBarEnabled ) { downArrowBitmap += BmpDisabled; } else if ( mHitRegion == DownArrow && mStateDepressed ) { downArrowBitmap += BmpHilite; } // Render Down Arrow. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[downArrowBitmap]); // Render the Thumb? if ( !mVBarEnabled ) { // Nope. return; } // Reset the Pos. pos.y = ( offset.y + mVThumbPos ); // Determine the Bitmaps. S32 thumbBitmapTop = ( BmpStates * BmpVThumbTopCap ); S32 thumbBitmapMiddle = ( BmpStates * BmpVThumb ); S32 thumbBitmapBottom = ( BmpStates * BmpVThumbBottomCap ); if ( mHitRegion == VertThumb && mStateDepressed ) { thumbBitmapTop += BmpHilite; thumbBitmapMiddle += BmpHilite; thumbBitmapBottom += BmpHilite; } // Render Thumb Top. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[thumbBitmapTop]); // Update Pos. pos.y += mBitmapBounds[thumbBitmapTop].extent.y; // Determine the Thumb Rect. RectI thumbRect; thumbRect.point = pos; thumbRect.extent.x = mBitmapBounds[thumbBitmapMiddle].extent.x; thumbRect.extent.y = mVThumbSize - ( mBitmapBounds[thumbBitmapTop].extent.y + mBitmapBounds[thumbBitmapBottom].extent.y ); // Render Thumb? if ( thumbRect.extent.y > 0 ) { // Render Track. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapStretchSR(mTextureObject, thumbRect, mBitmapBounds[thumbBitmapMiddle]); } // Update Pos. pos.y += thumbRect.extent.y; // Render the Thumb Bottom. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[thumbBitmapBottom]); } //----------------------------------------------------------------------------- void GuiScrollCtrl::drawHScrollBar(const Point2I &offset) { if ( mTextureObject.isNull() ) { return; } // Start Point. Point2I pos = ( offset + mLeftArrowRect.point ); // Left Arrow. S32 leftArrowBitmap = ( BmpStates * BmpLeft ); if ( !mHBarEnabled ) { leftArrowBitmap += BmpDisabled; } else if ( mHitRegion == LeftArrow && mStateDepressed ) { leftArrowBitmap += BmpHilite; } // Render Up Arrow. GFXDrawUtil* drawUtil = GFX->getDrawUtil(); drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[leftArrowBitmap]); // Update Pos. pos.x += mBitmapBounds[leftArrowBitmap].extent.x; // Track. S32 trackBitmap = ( BmpStates * BmpHPage ); if ( !mHBarEnabled ) { trackBitmap += BmpDisabled; } else if ( mHitRegion == LeftPage && mStateDepressed ) { trackBitmap += BmpHilite; } // Determine the Track Rect. RectI trackRect; trackRect.point = pos; trackRect.extent.x = ( offset.x + mRightArrowRect.point.x ) - pos.x; trackRect.extent.y = mBitmapBounds[trackBitmap].extent.y; // Render Track? if ( trackRect.extent.x > 0 ) { // Render Track. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapStretchSR(mTextureObject, trackRect, mBitmapBounds[trackBitmap]); } // Update Pos. pos.x += trackRect.extent.x; // Right Arrow. S32 rightArrowBitmap = ( BmpStates * BmpRight ); if ( !mHBarEnabled ) { rightArrowBitmap += BmpDisabled; } else if ( mHitRegion == RightArrow && mStateDepressed ) { rightArrowBitmap += BmpHilite; } // Render Right Arrow. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[rightArrowBitmap]); // Render the Thumb? if ( !mHBarEnabled ) { // Nope. return; } // Reset the Pos. pos.x = ( offset.x + mHThumbPos ); // Determine the Bitmaps. S32 thumbBitmapLeft = ( BmpStates * BmpHThumbLeftCap ); S32 thumbBitmapMiddle = ( BmpStates * BmpHThumb ); S32 thumbBitmapRight = ( BmpStates * BmpHThumbRightCap ); if ( mHitRegion == HorizThumb && mStateDepressed ) { thumbBitmapLeft += BmpHilite; thumbBitmapMiddle += BmpHilite; thumbBitmapRight += BmpHilite; } // Render Thumb Left. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[thumbBitmapLeft]); // Update Pos. pos.x += mBitmapBounds[thumbBitmapLeft].extent.x; // Determine the Thumb Rect. RectI thumbRect; thumbRect.point = pos; thumbRect.extent.x = mHThumbSize - ( mBitmapBounds[thumbBitmapLeft].extent.x + mBitmapBounds[thumbBitmapRight].extent.x ); thumbRect.extent.y = mBitmapBounds[thumbBitmapMiddle].extent.y; // Render Thumb? if ( thumbRect.extent.x > 0 ) { // Render Track. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapStretchSR(mTextureObject, thumbRect, mBitmapBounds[thumbBitmapMiddle]); } // Update Pos. pos.x += thumbRect.extent.x; // Render the Thumb Bottom. drawUtil->clearBitmapModulation(); drawUtil->drawBitmapSR(mTextureObject, pos, mBitmapBounds[thumbBitmapRight]); } //----------------------------------------------------------------------------- void GuiScrollCtrl::drawScrollCorner(const Point2I &offset) { Point2I pos = offset; pos.x += mRightArrowRect.point.x + mRightArrowRect.extent.x - 1; pos.y += mRightArrowRect.point.y; GFX->getDrawUtil()->clearBitmapModulation(); GFX->getDrawUtil()->drawBitmapSR(mTextureObject, pos, mBitmapBounds[BmpStates * BmpResize]); } //----------------------------------------------------------------------------- void GuiScrollCtrl::autoScroll(Region reg) { scrollByRegion(reg); } //============================================================================= // API. //============================================================================= // MARK: ---- API ---- //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, scrollToTop, void, (),, "Scroll all the way to the top of the vertical and left of the horizontal scrollbar." ) { object->scrollTo( 0, 0 ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, scrollToBottom, void, (),, "Scroll all the way to the bottom of the vertical scrollbar and the left of the horizontal bar." ) { object->scrollTo( 0, 0x7FFFFFFF ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, setScrollPosition, void, ( S32 x, S32 y ),, "Set the position of the scrolled content.\n\n" "@param x Position on X axis.\n" "@param y Position on y axis.\n" ) { object->scrollTo( x, y ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, scrollToObject, void, ( GuiControl* control ),, "Scroll the control so that the given child @a control is visible.\n\n" "@param control A child control." ) { if( control ) object->scrollToObject( control ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, getScrollPosition, Point2I, (),, "Get the current coordinates of the scrolled content.\n\n" "@return The current position of the scrolled content." ) { return object->getChildRelPos(); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, getScrollPositionX, S32, (),, "Get the current X coordinate of the scrolled content.\n\n" "@return The current X coordinate of the scrolled content." ) { return object->getChildRelPos().x; } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, getScrollPositionY, S32, (),, "Get the current Y coordinate of the scrolled content." "@return The current Y coordinate of the scrolled content." ) { return object->getChildRelPos().y; } //----------------------------------------------------------------------------- DefineEngineMethod( GuiScrollCtrl, computeSizes, void, (),, "Refresh sizing and positioning of child controls." ) { object->computeSizes(); }
29.971731
171
0.576774
[ "render", "object" ]
295c253bdd2c4c495fcd5f2a09c11a884cb5e015
4,313
cpp
C++
LucidGloves/src/ControllerPose.cpp
failsafe89/opengloves-driver
59c985326a17545ab36ea2f5f3a13ea9529e8ba1
[ "MIT" ]
1
2021-04-12T02:50:32.000Z
2021-04-12T02:50:32.000Z
LucidGloves/src/ControllerPose.cpp
failsafe89/opengloves-driver
59c985326a17545ab36ea2f5f3a13ea9529e8ba1
[ "MIT" ]
null
null
null
LucidGloves/src/ControllerPose.cpp
failsafe89/opengloves-driver
59c985326a17545ab36ea2f5f3a13ea9529e8ba1
[ "MIT" ]
null
null
null
#pragma once #include "ControllerPose.h" ControllerPose::ControllerPose(vr::ETrackedControllerRole shadowDeviceOfRole, std::string thisDeviceManufacturer, vr::HmdVector3_t offsetVector, vr::HmdVector3_t angleOffsetVector, uint32_t driverId) : m_shadowDeviceOfRole(shadowDeviceOfRole), m_driverId(driverId), m_thisDeviceManufacturer(thisDeviceManufacturer), m_offsetVector(offsetVector) { const vr::HmdVector3_t angleOffset = angleOffsetVector; m_offsetQuaternion = EulerToQuaternion(DegToRad(angleOffset.v[0]), DegToRad(angleOffset.v[1]), DegToRad(angleOffset.v[2])); DebugDriverLog("Offset calculated! {%.2f, %.2f, %.2f, %.2f}", m_offsetQuaternion.w, m_offsetQuaternion.x, m_offsetQuaternion.y, m_offsetQuaternion.z); } vr::DriverPose_t ControllerPose::UpdatePose() { vr::DriverPose_t newPose = { 0 }; newPose.qWorldFromDriverRotation.w = 1; newPose.qDriverFromHeadRotation.w = 1; if (m_shadowControllerId != -1) { vr::TrackedDevicePose_t trackedDevicePoses[vr::k_unMaxTrackedDeviceCount]; vr::VRServerDriverHost()->GetRawTrackedDevicePoses(0, trackedDevicePoses, vr::k_unMaxTrackedDeviceCount); if (trackedDevicePoses[m_shadowControllerId].bPoseIsValid) { //get the matrix that represents the position of the controller that we are shadowing vr::HmdMatrix34_t controllerMatrix = trackedDevicePoses[m_shadowControllerId].mDeviceToAbsoluteTracking; //get only the rotation (3x3 matrix), as the 3x4 matrix also includes position vr::HmdMatrix33_t controllerRotationMatrix = GetRotationMatrix(controllerMatrix); //multiply the rotation matrix by the offset vector set that is the offset of the controller relative to the hand vr::HmdVector3_t vectorOffset = MultiplyMatrix(controllerRotationMatrix, m_offsetVector); //combine these positions to get the resultant position vr::HmdVector3_t newControllerPosition = CombinePosition(controllerMatrix, vectorOffset); newPose.vecPosition[0] = newControllerPosition.v[0]; newPose.vecPosition[1] = newControllerPosition.v[1]; newPose.vecPosition[2] = newControllerPosition.v[2]; //Multiply rotation quaternions together, as the controller may be rotated relative to the hand newPose.qRotation = MultiplyQuaternion(GetRotation(controllerMatrix), m_offsetQuaternion); //Copy other values from the controller that we want for this device newPose.vecAngularVelocity[0] = trackedDevicePoses[m_shadowControllerId].vAngularVelocity.v[0]; newPose.vecAngularVelocity[1] = trackedDevicePoses[m_shadowControllerId].vAngularVelocity.v[1]; newPose.vecAngularVelocity[2] = trackedDevicePoses[m_shadowControllerId].vAngularVelocity.v[2]; newPose.vecVelocity[0] = trackedDevicePoses[m_shadowControllerId].vVelocity.v[0]; newPose.vecVelocity[1] = trackedDevicePoses[m_shadowControllerId].vVelocity.v[1]; newPose.vecVelocity[2] = trackedDevicePoses[m_shadowControllerId].vVelocity.v[2]; newPose.poseIsValid = true; newPose.deviceIsConnected = true; newPose.result = vr::TrackingResult_Running_OK; } else { newPose.poseIsValid = false; newPose.deviceIsConnected = true; newPose.result = vr::TrackingResult_Uninitialized; } } else { newPose.result = vr::TrackingResult_Uninitialized; newPose.deviceIsConnected = false; DiscoverController(); } return newPose; } void ControllerPose::DiscoverController() { //omit id 0, as this is always the headset pose for (int i = 1; i < vr::k_unMaxTrackedDeviceCount; i++) { vr::ETrackedPropertyError err; vr::PropertyContainerHandle_t container = vr::VRProperties()->TrackedDeviceToPropertyContainer(i); std::string foundDeviceManufacturer = vr::VRProperties()->GetStringProperty(container, vr::Prop_ManufacturerName_String, &err); int32_t deviceControllerRole = vr::VRProperties()->GetInt32Property(container, vr::ETrackedDeviceProperty::Prop_ControllerRoleHint_Int32, &err); //We have a device which identifies itself as a tracked device that we want to be searching for, and that device is not this one. if (deviceControllerRole == m_shadowDeviceOfRole && foundDeviceManufacturer != m_thisDeviceManufacturer) { DebugDriverLog("Discovered a controller! Id: %i, Manufacturer: %s", i, foundDeviceManufacturer.c_str()); m_shadowControllerId = i; break; } } }
44.463918
151
0.779968
[ "vector" ]
295cbf0782a268cda8b3473544c5621aeb7f35f8
8,358
cpp
C++
showKeypoints.cpp
cstahmer/archv
a28853a6d4cc0a96bef0053165f1f6fbb397c53d
[ "CC-BY-4.0" ]
15
2018-04-13T17:04:09.000Z
2019-05-24T11:56:12.000Z
showKeypoints.cpp
cstahmer/archv
a28853a6d4cc0a96bef0053165f1f6fbb397c53d
[ "CC-BY-4.0" ]
null
null
null
showKeypoints.cpp
cstahmer/archv
a28853a6d4cc0a96bef0053165f1f6fbb397c53d
[ "CC-BY-4.0" ]
null
null
null
/* ============================================================================================ showKeypoints.cpp Version 3 last update: 03/28/2019 this program: [1] reads in parameters for surf detection, input image and output image from command line if no options for surf specified will use those set in code in variable declaration [2] uses opencv's Feature Detection class to detect all the keypoints [3] filters the keypoints based on a sizemin and responsemin specified [4] uses opencv's Circle function to draw all the keypoints over the image [5] saves the image with drawn keypoints into file specified in step 1 mainly use this program to test parameters and to see the location and intensity of keypoints This file is part of the Arch-V Platform -- https://github.com/cstahmer/archv Copyright 2012 by Carl G. Stahmer -- http://www.carlstahmer.com Arch-V was originally created by Carl G. Stahmer through the generous support of the National Endowment for the Humanities. Subsequent development was performed by Carl G. Stahmer (http://www.carlstahmer.com) and Arthur Koehl (avkoehl@ucdavis.edu) at the Digital Scholars Lab at the the University of California Davis, Univeristy Library (http://ds.lib.ucdavis.edu/). Documentation authored by Henry Le (hutle@ucdavis.edu). Arch-V is licensed under a Creative Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0/legalcode). You are FREE to SHARE (copy and redistribute the material in any medium or format) and ADAPT (remix, transform, and build upon the material for any purpose, even commercially) WITH THE FOLLOWING RESTRICTIONS: 1. You must credit Carl G. Stahmer (http://www.carlstahmer.com) and Arthur Koehl (avkoehl@ucdavis.edu) as the original developers of this software. 2. You must credit the National Endowment for the Humanities and Univeristy of California, Davis Univeristy Library as having supported the original development of the software. 3. You must provide a copyright notice. 4. You must provide a link to the license (https://creativecommons.org/licenses/by/4.0/legalcode). 5. You must indicate if and what changes you made to the software. 6. You must provide a link to the original software at https://github.com/cstahmer/archv](https://github.com/cstahmer/archv ============================================================================================ */ #include <iostream> #include <fstream> #include <cstdlib> #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/nonfree/nonfree.hpp" using namespace std; using namespace cv; int usage (); void read_flags (int argc, char **argv, string *input, string *output, string *param, int *minh, int *octaves, int *layers, int *sizemin, double *responsemin); void read_surfparams (string param, int *min, int *octaves, int *layers, int *sizemin, double *responsemin); void filter_keypoints (vector <KeyPoint> &keypoints, int sizemin, double responsemin); int main(int argc, char **argv) { /* ===================================================================================== if program executed without commands or '-h' or '-help' flag then run usage ===================================================================================== */ if (argc < 2) return usage(); string checker = argv[1]; if (checker == "-h" || checker == "-help") return usage(); /* ===================================================================================== variables for surf parameters, file names, image, and vector of keypoints ===================================================================================== */ int minh = 2000; int octaves = 8; int layers = 8; int sizemin = 50; double responsemin = 100; string input, output; string param = ""; vector <KeyPoint> keypoints; Mat image; Mat outimage; /* ===================================================================================== parse command line into variables above and read in the image into Mat image ===================================================================================== */ read_flags(argc, argv, &input, &output, &param, &minh, &octaves, &layers, &sizemin, &responsemin); if (param != "") read_surfparams (param, &minh, &octaves, &layers, &sizemin, &responsemin); image = imread (input); /* ===================================================================================== create openCV's SurfFreatureDetector and then run detect() function ===================================================================================== */ SurfFeatureDetector detector (minh, octaves, layers); detector.detect (image, keypoints); int original = keypoints.size(); filter_keypoints (keypoints, sizemin, responsemin); /* ===================================================================================== call drawkeypoints from opencv and write to the output image ===================================================================================== */ drawKeypoints (image, keypoints, outimage, Scalar (155,0,0), 4); imwrite (output, outimage); return 0; } int usage () { cout << "./a.out -i input -o output -p paramfilepath " << endl; cout << "otherwise, without param file:" << endl; cout << "./a.out -i input -o output -h # -oct # -l # -s # -r #" << endl; return -1; } void read_flags (int argc, char **argv, string *input, string *output, string *param, int *minh, int *octaves, int *layers, int *sizemin, double *responsemin) { string parser; for (int i = 0; i < argc; i++) { parser = argv[i]; if (parser == "-i") *input = argv[i + 1]; if (parser == "-o") *output = argv[i+1]; if (parser == "-p") *param = argv[i+1]; if (parser == "-h") *minh = atoi(argv[i+1]); if (parser == "-oct") *octaves = atoi(argv[i+1]); if (parser == "-l") *layers = atoi(argv[i+1]); if (parser == "-s") *sizemin = atoi(argv[i+1]); if (parser == "-r") *responsemin = atoi(argv[i+1]); } } /* =============================================================================================== Procedure to read parameters for SURF from the parameter file =============================================================================================== */ void read_surfparams(string param, int *minHessian, int *octaves, int *octaveLayers, int *SizeMin, double *RespMin) { ifstream inFile; inFile.open(param.c_str()); string record; stringstream ss; while ( !inFile.eof () ) { getline(inFile,record); if (record.find("minHessian") != std::string::npos) { ss<<record.substr(record.find_last_of(":") + 1); ss>> *minHessian; ss.str(""); ss.clear(); } if (record.find("octaves") != std::string::npos) { ss<<record.substr(record.find_last_of(":") + 1); ss>> *octaves; ss.str(""); ss.clear(); } if (record.find("octaveLayers") != std::string::npos) { ss<<record.substr(record.find_last_of(":") + 1); ss>> *octaveLayers; ss.str(""); ss.clear(); } if (record.find("min Size") != std::string::npos) { ss<<record.substr(record.find_last_of(":") + 1); ss>> *SizeMin; ss.str(""); ss.clear(); } if (record.find("min Resp") != std::string::npos) { ss<<record.substr(record.find_last_of(":") + 1); ss>> *RespMin; ss.str(""); ss.clear(); } } } /* =============================================================================================== Procedure to filter the keypoints from the keypoint vector by minimum size and response =============================================================================================== */ void filter_keypoints (vector <KeyPoint> &keypoints, int sizemin, double responsemin) { vector <KeyPoint> temp; int npoints = keypoints.size(); int size; double response; //filter based on size and response size for (int i = 0; i < npoints; i++) { size = keypoints[i].size; response = keypoints[i].response; if (size > sizemin && response > responsemin) temp.push_back(keypoints[i]); } keypoints.clear(); keypoints = temp; return; }
36.657895
159
0.555037
[ "vector", "transform" ]
295db35db6a6ff9b3d37989be94c9d6ee8b43823
5,369
hpp
C++
include/internal/catch_generators.hpp
vadz/Catch
b18d719f9d8a6960379832b13c47baaeffe8183d
[ "BSL-1.0" ]
1
2020-05-24T17:33:37.000Z
2020-05-24T17:33:37.000Z
include/internal/catch_generators.hpp
vadz/Catch
b18d719f9d8a6960379832b13c47baaeffe8183d
[ "BSL-1.0" ]
null
null
null
include/internal/catch_generators.hpp
vadz/Catch
b18d719f9d8a6960379832b13c47baaeffe8183d
[ "BSL-1.0" ]
null
null
null
/* * Created by Phil on 27/01/2011. * Copyright 2011 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED #include "catch_context.h" #include <iterator> #include <vector> #include <string> #include <stdlib.h> namespace Catch { template<typename T> struct IGenerator { virtual ~IGenerator() {} virtual T getValue( std::size_t index ) const = 0; virtual std::size_t size () const = 0; }; template<typename T> class BetweenGenerator : public IGenerator<T> { public: BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} virtual T getValue( std::size_t index ) const { return m_from+static_cast<T>( index ); } virtual std::size_t size() const { return static_cast<std::size_t>( 1+m_to-m_from ); } private: T m_from; T m_to; }; template<typename T> class ValuesGenerator : public IGenerator<T> { public: ValuesGenerator(){} void add( T value ) { m_values.push_back( value ); } virtual T getValue( std::size_t index ) const { return m_values[index]; } virtual std::size_t size() const { return m_values.size(); } private: std::vector<T> m_values; }; template<typename T> class CompositeGenerator { public: CompositeGenerator() : m_totalSize( 0 ) {} // *** Move semantics, similar to auto_ptr *** CompositeGenerator( CompositeGenerator& other ) : m_fileInfo( other.m_fileInfo ), m_totalSize( 0 ) { move( other ); } CompositeGenerator& setFileInfo( const char* fileInfo ) { m_fileInfo = fileInfo; return *this; } ~CompositeGenerator() { deleteAll( m_composed ); } operator T () const { size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin(); typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end(); for( size_t index = 0; it != itEnd; ++it ) { const IGenerator<T>* generator = *it; if( overallIndex >= index && overallIndex < index + generator->size() ) { return generator->getValue( overallIndex-index ); } index += generator->size(); } CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so } void add( const IGenerator<T>* generator ) { m_totalSize += generator->size(); m_composed.push_back( generator ); } CompositeGenerator& then( CompositeGenerator& other ) { move( other ); return *this; } CompositeGenerator& then( T value ) { ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( value ); add( valuesGen ); return *this; } private: void move( CompositeGenerator& other ) { std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); m_totalSize += other.m_totalSize; other.m_composed.clear(); } std::vector<const IGenerator<T>*> m_composed; std::string m_fileInfo; size_t m_totalSize; }; namespace Generators { template<typename T> CompositeGenerator<T> between( T from, T to ) { CompositeGenerator<T> generators; generators.add( new BetweenGenerator<T>( from, to ) ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3 ){ CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); valuesGen->add( val4 ); generators.add( valuesGen ); return generators; } } // end namespace Generators using namespace Generators; } // end namespace Catch #define INTERNAL_CATCH_LINESTR2( line ) #line #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) #endif // TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
28.109948
141
0.628609
[ "vector" ]
295f7ce87d787e3d11e78572dd99c03b313a79f9
23,375
cpp
C++
lib/Onnxifi/Flags.cpp
mehrdad-shokri/glow-1
ef5fa727d388e0ab2d3739b96821744f9fae1308
[ "Apache-2.0" ]
null
null
null
lib/Onnxifi/Flags.cpp
mehrdad-shokri/glow-1
ef5fa727d388e0ab2d3739b96821744f9fae1308
[ "Apache-2.0" ]
null
null
null
lib/Onnxifi/Flags.cpp
mehrdad-shokri/glow-1
ef5fa727d388e0ab2d3739b96821744f9fae1308
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) Glow Contributors. See CONTRIBUTORS file. * * 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 <gflags/gflags.h> namespace glow { namespace onnxifi { extern int32_t GlowNumDevices; extern int32_t GlowSparseNNPartitioningSchemeNumCards; extern int64_t GlowSparseNNPartitioningSchemeSLSTableKBytesPerCard; extern int32_t GlowSparseNNPartitioningSchemeNumCoresSLS; extern int32_t GlowSparseNNPartitioningSchemeNumCoresOther; extern bool GlowDumpDebugTraces; extern int32_t GlowNumDebugTracesPerDump; extern std::string GlowOnnxifiBackend; extern bool GlowFP16; extern bool GlowFP16Placeholders; extern bool GlowFP16Constants; extern bool GlowFusedScaleOffsetFP16; extern bool GlowForceSLSAccumFP16; extern bool GlowClipFP16; extern bool GlowClipFP16SkipInputs; extern bool GlowEnableQuantParamChanges; extern bool GlowSaturateHost; extern bool GlowSaveOnnxifiModel; extern bool GlowSaveOnnxifiDAG; extern bool GlowSaveOnnxifiIO; extern bool GlowDelayAndRecordConstantModification; extern bool GlowEnablePartialTensors; extern bool GlowUseCustomOpsForExport; extern bool GlowUseSparseNNPartitioningScheme; extern bool GlowSparseNNPartitioningAddSLSConcats; extern bool GlowSparseNNPartitioningBalancePerfModel; extern bool GlowSparseNNPartitioningPairLNWithSLS; extern bool GlowDumpGraph; extern std::string GlowDumpGraphPath; extern bool GlowDumpInitialLoadedGraph; extern bool GlowUseDAGOptimizer; extern std::string GlowDAGOptimizerPlacementTaggingAlgorithm; extern std::string GlowDAGOptimizerParallelizationTaggingAlgorithm; extern int32_t GlowDAGOptimizerNumParallelChunks; extern size_t GlowMaxActiveRequests; extern size_t GlowMaxActiveRequestsPerInstance; extern size_t GlowMaxQueueSize; extern size_t GlowExecutorThreads; // Defined in glow/lib/Backends/NNPI/NNPI.cpp #ifdef GLOW_WITH_NNPI extern bool GlowDumpNNPICompilerData; extern bool GlowUsePerPartitionIcetConfig; extern bool GlowDisableNNPITransforms; extern bool GlowDisableNNPIPrivateTransforms; extern int32_t GlowNNPINumParallelChunks; extern int32_t GlowNNPIModelParallelSplitAlignment; #endif } // namespace onnxifi extern bool GlowEnableLoadBalancedPartitioning; extern bool GlowNNPILowerAllBatchMatMul; extern bool GlowNNPIAcceptUnarySLS; extern bool GlowNNPISpecializeAllOneSLS; namespace runtime { extern unsigned GlowInterpreterMemory; extern unsigned GlowCPUMemory; extern unsigned GlowHabanaMemory; #ifdef GLOW_WITH_NNPI extern unsigned GlowNNPIMemory; extern unsigned GlowNNPITimeout; #endif extern bool GlowEnableDRT; extern bool GlowEnableP2P; extern unsigned GlowDeviceInitTimeoutMs; extern std::string GlowAvailableDevices; } // namespace runtime extern bool GlowDumpCompilationLog; extern bool GlowLogPartition; extern bool GlowDumpPartition; } // namespace glow DEFINE_int32(glow_num_devices, 1, "Number of devices for Glow backend"); DEFINE_validator(glow_num_devices, [](const char *flagname, int32_t value) { glow::onnxifi::GlowNumDevices = value; return true; }); DEFINE_int32( glow_snn_partitioning_num_cards, 1, "Number of devices to distribute tables across in SparseNN partitioning"); DEFINE_validator(glow_snn_partitioning_num_cards, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowSparseNNPartitioningSchemeNumCards = value; return true; }); DEFINE_int32(glow_snn_partitioning_kbytes_per_card, 1, "Bytes per card used for SLS tables in SparseNN partitioning"); DEFINE_validator( glow_snn_partitioning_kbytes_per_card, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowSparseNNPartitioningSchemeSLSTableKBytesPerCard = value; return true; }); DEFINE_int32( glow_snn_partitioning_num_cores_sls, 1, "Number of cores to assign to SLS partition in SparseNN partitioning"); DEFINE_validator(glow_snn_partitioning_num_cores_sls, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowSparseNNPartitioningSchemeNumCoresSLS = value; return true; }); DEFINE_int32( glow_snn_partitioning_num_cores_other, 1, "Number of cores to assign to non-SLS partition in SparseNN partitioning"); DEFINE_validator(glow_snn_partitioning_num_cores_other, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowSparseNNPartitioningSchemeNumCoresOther = value; return true; }); DEFINE_bool(glow_dump_debug_traces, false, "Dump traces to /tmp"); DEFINE_validator(glow_dump_debug_traces, [](const char *flagname, bool value) { glow::onnxifi::GlowDumpDebugTraces = value; return true; }); DEFINE_int32(glow_num_debug_traces_per_dump, 100, "Maximum number of traces in each debug dump."); DEFINE_validator(glow_num_debug_traces_per_dump, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowNumDebugTracesPerDump = value; return true; }); DEFINE_string(glow_onnxifi_backend, "", "Glow backend used for ONNXIFI"); DEFINE_validator(glow_onnxifi_backend, [](const char *flagname, const std::string &value) { glow::onnxifi::GlowOnnxifiBackend = value; return true; }); DEFINE_string( glow_available_devices, "", "Comma separated list of devices which should be used, example 2,3,4"); DEFINE_validator(glow_available_devices, [](const char * /* unused */, const std::string &value) { glow::runtime::GlowAvailableDevices = value; return true; }); DEFINE_bool(glow_global_fp16, false, "Enable fp16 lowering for all ops on the net"); DEFINE_validator(glow_global_fp16, [](const char * /* unused */, bool value) { glow::onnxifi::GlowFP16 = value; return true; }); DEFINE_bool(glow_global_fp16_placeholders, true, "Enable fp16 conversion for Placeholders"); DEFINE_validator(glow_global_fp16_placeholders, [](const char * /* unused */, bool value) { glow::onnxifi::GlowFP16Placeholders = value; return true; }); DEFINE_bool(glow_global_fp16_constants, true, "Enable fp16 conversion for Constants"); DEFINE_validator(glow_global_fp16_constants, [](const char * /* unused */, bool value) { glow::onnxifi::GlowFP16Constants = value; return true; }); DEFINE_bool(glow_global_fused_scale_offset_fp16, false, "Enable fp16 lowering for all op inputs using fused scale/offset"); DEFINE_validator(glow_global_fused_scale_offset_fp16, [](const char * /* unused */, bool value) { glow::onnxifi::GlowFusedScaleOffsetFP16 = value; return true; }); DEFINE_bool( glow_global_force_sls_fp16_accum, true, "Force all SLS/SLWS ops to use FP16 accumulation. True by default."); DEFINE_validator(glow_global_force_sls_fp16_accum, [](const char * /* unused */, bool value) { glow::onnxifi::GlowForceSLSAccumFP16 = value; return true; }); DEFINE_bool(glow_enable_quant_param_changes, true, "Enable quantization param changes during optimizations"); DEFINE_validator(glow_enable_quant_param_changes, [](const char * /* unused */, bool value) { glow::onnxifi::GlowEnableQuantParamChanges = value; return true; }); DEFINE_bool(glow_use_sparsenn_partitioning_scheme, false, "Force glow to use SparseNN partitioning scheme"); DEFINE_validator(glow_use_sparsenn_partitioning_scheme, [](const char * /* flagname */, bool value) { glow::onnxifi::GlowUseSparseNNPartitioningScheme = value; return true; }); DEFINE_bool(glow_sparsenn_partitioning_add_sls_concats, false, "Add extra concats inside of SLS partitions for more efficient " "inter-partitition transfers"); DEFINE_validator(glow_sparsenn_partitioning_add_sls_concats, [](const char * /* flagname */, bool value) { glow::onnxifi::GlowSparseNNPartitioningAddSLSConcats = value; return true; }); DEFINE_bool(glow_sparsenn_partitioning_balance_perf_model, false, "Balance SLS tables across cards using a perf model"); DEFINE_validator(glow_sparsenn_partitioning_balance_perf_model, [](const char * /* flagname */, bool value) { glow::onnxifi::GlowSparseNNPartitioningBalancePerfModel = value; return true; }); DEFINE_bool(glow_sparsenn_partitioning_pair_ln_with_sls, false, "Put layer normalization nodes immediately following SLS into SLS " "Partitions"); DEFINE_validator(glow_sparsenn_partitioning_pair_ln_with_sls, [](const char * /* flagname */, bool value) { glow::onnxifi::GlowSparseNNPartitioningPairLNWithSLS = value; return true; }); DEFINE_bool(glow_clip_fp16, false, "Force glow to clip fp16 values to min/max"); DEFINE_validator(glow_clip_fp16, [](const char *flagname, bool value) { glow::onnxifi::GlowClipFP16 = value; return true; }); DEFINE_bool(glow_clip_fp16_skip_inputs, true, "Force glow to skip clipping fp16 Node inputs to min/max"); DEFINE_validator(glow_clip_fp16_skip_inputs, [](const char *flagname, bool value) { glow::onnxifi::GlowClipFP16SkipInputs = value; return true; }); DEFINE_bool(glow_saturate_host, false, "Try to use all available devices on the host"); DEFINE_validator(glow_saturate_host, [](const char *flagname, bool value) { glow::onnxifi::GlowSaturateHost = value; return true; }); DEFINE_bool( glow_save_onnxifi_dag, false, "Whether to serialize the DAG that has been optimized and partitioned."); DEFINE_validator(glow_save_onnxifi_dag, [](const char *flagname, bool value) { glow::onnxifi::GlowSaveOnnxifiDAG = value; return true; }); DEFINE_bool( glow_delay_and_record_constant_modification, false, "Whether to delay and record constant modification for serialization."); DEFINE_validator(glow_delay_and_record_constant_modification, [](const char *flagname, bool value) { glow::onnxifi::GlowDelayAndRecordConstantModification = value; return true; }); DEFINE_int32(glow_max_active_requests, 48, "Number of max active requests before host manager start queuing"); DEFINE_validator(glow_max_active_requests, [](const char *flagname, int32_t value) { glow::onnxifi::GlowMaxActiveRequests = value; return true; }); DEFINE_int32(glow_max_active_requests_per_instance, 48, "Number of max active requests per instance of a network."); DEFINE_validator(glow_max_active_requests_per_instance, [](const char * /* unused */, int32_t value) { glow::onnxifi::GlowMaxActiveRequestsPerInstance = value; return true; }); DEFINE_int32( glow_max_queue_size, 100, "Max number of pending requeusts in glow's host manager queue before " "rejecting new request"); DEFINE_validator(glow_max_queue_size, [](const char *flagname, int32_t value) { glow::onnxifi::GlowMaxQueueSize = value; return true; }); DEFINE_int32(glow_executor_threads, 10, "Number of executor threads for host manager"); DEFINE_validator(glow_executor_threads, [](const char *flagname, int32_t value) { glow::onnxifi::GlowExecutorThreads = value; return true; }); DEFINE_bool(glow_partitioner_enable_load_balance, false, "Enable a partitioner " "pass to optimize for load balance in addition to memory capacity " "constraints"); DEFINE_validator(glow_partitioner_enable_load_balance, [](const char *flagname, bool value) { glow::GlowEnableLoadBalancedPartitioning = value; return true; }); DEFINE_bool(glow_save_onnxifi_model, false, "Package the glow function and weights right before lowering"); DEFINE_validator(glow_save_onnxifi_model, [](const char * /* unused */, bool value) { glow::onnxifi::GlowSaveOnnxifiModel = value; return true; }); DEFINE_bool(glow_save_onnxifi_io, false, "Save the input and output result around ONNXIFI boundary"); DEFINE_validator(glow_save_onnxifi_io, [](const char * /* unused */, bool value) { glow::onnxifi::GlowSaveOnnxifiIO = value; return true; }); DEFINE_bool(glow_enable_partial_tensors, true, "Save the input and output result around ONNXIFI boundary"); DEFINE_validator(glow_enable_partial_tensors, [](const char * /* unused */, bool value) { glow::onnxifi::GlowEnablePartialTensors = value; return true; }); DEFINE_bool(glow_use_custom_ops_for_export, true, "Use custom ONNX ops when exporting Glow protos."); DEFINE_validator(glow_use_custom_ops_for_export, [](const char * /* unused */, bool value) { glow::onnxifi::GlowUseCustomOpsForExport = value; return true; }); DEFINE_bool(glow_dump_graph, false, "Dump the glow Graph into files before compilation"); DEFINE_validator(glow_dump_graph, [](const char * /* unused */, bool value) { glow::onnxifi::GlowDumpGraph = value; return true; }); DEFINE_string(glow_dump_graph_path, "./", "Directory path for the dumped graphs."); DEFINE_validator(glow_dump_graph_path, [](const char * /* unused */, const std::string &value) { glow::onnxifi::GlowDumpGraphPath = value; return true; }); DEFINE_bool(glow_dump_initial_loaded_graph, false, "Dump the glow Graph right after onnxification"); DEFINE_validator(glow_dump_initial_loaded_graph, [](const char * /* unused */, bool value) { glow::onnxifi::GlowDumpInitialLoadedGraph = value; return true; }); DEFINE_bool(glow_use_dag_optimizer, false, "Whether to call the DAG optimizer"); DEFINE_validator(glow_use_dag_optimizer, [](const char * /* unused */, bool value) { glow::onnxifi::GlowUseDAGOptimizer = value; return true; }); DEFINE_int32(glow_dag_optimizer_num_parallel_chunks, 1, "Number of parallel chunks for DAGOptimizer parallelization"); DEFINE_validator(glow_dag_optimizer_num_parallel_chunks, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowDAGOptimizerNumParallelChunks = value; return true; }); DEFINE_string(glow_dag_optimizer_placement_tagging_algorithm, "None", "Name of placement tagging algorithm to run in DAGOptimizer"); DEFINE_validator(glow_dag_optimizer_placement_tagging_algorithm, [](const char * /* flagname */, const std::string &value) { glow::onnxifi::GlowDAGOptimizerPlacementTaggingAlgorithm = value; return true; }); DEFINE_string( glow_dag_optimizer_parallelization_tagging_algorithm, "None", "Name of parallelization tagging algorithm to run in DAGOptimizer"); DEFINE_validator( glow_dag_optimizer_parallelization_tagging_algorithm, [](const char * /* flagname */, const std::string &value) { glow::onnxifi::GlowDAGOptimizerParallelizationTaggingAlgorithm = value; return true; }); #ifdef GLOW_WITH_NNPI // Defined in glow/lib/Backends/NNPI/NNPI.cpp DEFINE_bool(glow_use_per_partition_icet_config, false, "Read an icet_config.json file for each partition"); DEFINE_validator(glow_use_per_partition_icet_config, [](const char * /* unused */, bool value) { glow::onnxifi::GlowUsePerPartitionIcetConfig = value; return true; }); DEFINE_bool(glow_dump_nnpi_compiler_data, false, "Dump the NNPI compiler data into files before NNPI compilation"); DEFINE_validator(glow_dump_nnpi_compiler_data, [](const char * /* unused */, bool value) { glow::onnxifi::GlowDumpNNPICompilerData = value; return true; }); DEFINE_bool(glow_nnpi_specialize_all_one_sls, false, "Whether to import SLS ops with AllOne attribute to NNPI."); DEFINE_validator(glow_nnpi_specialize_all_one_sls, [](const char * /*unused*/, bool value) { glow::GlowNNPISpecializeAllOneSLS = value; return true; }); DEFINE_bool(glow_disable_nnpi_transforms, false, "Disable running NNPIBackend::transformPostLowering()."); DEFINE_validator(glow_disable_nnpi_transforms, [](const char * /* unused */, bool value) { glow::onnxifi::GlowDisableNNPITransforms = value; return true; }); DEFINE_bool(glow_disable_nnpi_private_transforms, false, "Disable running NNPIBackend::transformPrivate()."); DEFINE_validator(glow_disable_nnpi_private_transforms, [](const char * /* unused */, bool value) { glow::onnxifi::GlowDisableNNPIPrivateTransforms = value; return true; }); DEFINE_bool(glow_nnpi_lower_all_batch_matmul, false, "Whether to override default lowering for NNPI and always lower " "BatchMatMul to a series of MatMuls."); DEFINE_validator(glow_nnpi_lower_all_batch_matmul, [](const char * /* unused */, bool value) { glow::GlowNNPILowerAllBatchMatMul = value; return true; }); DEFINE_bool(glow_nnpi_accept_unary_sls, false, "Whether to accept unary SLS ops during ONNXIFI loading."); DEFINE_validator(glow_nnpi_accept_unary_sls, [](const char * /* unused */, bool value) { glow::GlowNNPIAcceptUnarySLS = value; return true; }); DEFINE_int32(glow_nnpi_num_parallel_chunks, 1, "Number of parallel chunks for NNPI"); DEFINE_validator(glow_nnpi_num_parallel_chunks, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowNNPINumParallelChunks = value; return true; }); DEFINE_int32(glow_nnpi_model_parallel_split_alignment, 1, "Alignment value for model parallel splits"); DEFINE_validator(glow_nnpi_model_parallel_split_alignment, [](const char * /* flagname */, int32_t value) { glow::onnxifi::GlowNNPIModelParallelSplitAlignment = value; return true; }); #endif /* GLOW_WITH_NNPI */ DEFINE_int32(glow_interpreter_memory, 0, "Amount of DRAM to allocate per Interpreter in KiB"); DEFINE_validator(glow_interpreter_memory, [](const char *, int32_t value) { glow::runtime::GlowInterpreterMemory = value; return true; }); #ifdef GLOW_WITH_CPU DEFINE_int32(glow_cpu_memory, 0, "Amount of DRAM to allocate per CPU in KiB"); DEFINE_validator(glow_cpu_memory, [](const char *, int32_t value) { glow::runtime::GlowCPUMemory = value; return true; }); #endif #ifdef GLOW_WITH_HABANA DEFINE_int32(glow_habana_memory, 7 << 20, "Amount of DRAM to allocate per Habana device in KiB"); DEFINE_validator(glow_habana_memory, [](const char *flagname, int32_t value) { glow::runtime::GlowHabanaMemory = value; return true; }); #endif #ifdef GLOW_WITH_NNPI DEFINE_int32(glow_nnpi_memory, 16 << 20, "Amount of DRAM to allocate per NNPI device in KiB"); DEFINE_validator(glow_nnpi_memory, [](const char *flagname, int32_t value) { glow::runtime::GlowNNPIMemory = value; return true; }); DEFINE_int32(glow_nnpi_timeout_ms, 0, "Timeout threshold for inferecnce in milliseconds. Default 0 " "means infinity"); DEFINE_validator(glow_nnpi_timeout_ms, [](const char * /*unused*/, int32_t value) { glow::runtime::GlowNNPITimeout = value * 1000; return true; }); #endif DEFINE_bool(glow_log_partition, true, "Enable logging partition info"); DEFINE_validator(glow_log_partition, [](const char * /*unused*/, bool value) { glow::GlowLogPartition = value; return true; }); DEFINE_bool(glow_enable_p2p, false, "Enable peer to peer support"); DEFINE_validator(glow_enable_p2p, [](const char * /*unused*/, bool value) { glow::runtime::GlowEnableP2P = value; return true; }); DEFINE_bool(glow_enable_drt, false, "Enable device resident tensor support"); DEFINE_validator(glow_enable_drt, [](const char * /*unused*/, bool value) { glow::runtime::GlowEnableDRT = value; return true; }); DEFINE_int32(glow_device_init_timeout_ms, 5000, "Timeout threshold for device initialization in milliseconds. " "Default 5000"); DEFINE_validator(glow_device_init_timeout_ms, [](const char * /*unused*/, int32_t value) { glow::runtime::GlowDeviceInitTimeoutMs = value; return true; }); DEFINE_bool(glow_dump_partition, false, "Enable dumping the graph of each partition"); DEFINE_validator(glow_dump_partition, [](const char * /*unused*/, bool value) { glow::GlowDumpPartition = value; return true; }); DEFINE_bool(glow_dump_compilation_log, false, "Dump the glow compilation log into /tmp during compilation"); DEFINE_validator(glow_dump_compilation_log, [](const char * /*unused*/, bool value) { glow::GlowDumpCompilationLog = value; return true; });
40.301724
80
0.661989
[ "model" ]
29616bad838409f287fb0bfd2d9ccc711c6235d0
95,541
cpp
C++
.pio/libdeps/heltec_wifi_kit_32/Adafruit GFX Library_ID13/Adafruit_SPITFT.cpp
Adam-Kareem/Vibration-Sensor
2157e51d9d488d5dff6997ab2cce809d016f89ed
[ "Apache-2.0" ]
118
2019-03-27T02:15:59.000Z
2022-03-18T16:42:42.000Z
.pio/libdeps/heltec_wifi_kit_32/Adafruit GFX Library_ID13/Adafruit_SPITFT.cpp
Adam-Kareem/Vibration-Sensor
2157e51d9d488d5dff6997ab2cce809d016f89ed
[ "Apache-2.0" ]
26
2019-04-17T16:39:30.000Z
2021-11-06T11:55:42.000Z
.pio/libdeps/heltec_wifi_kit_32/Adafruit GFX Library_ID13/Adafruit_SPITFT.cpp
Adam-Kareem/Vibration-Sensor
2157e51d9d488d5dff6997ab2cce809d016f89ed
[ "Apache-2.0" ]
58
2019-04-16T06:52:45.000Z
2022-03-08T01:57:08.000Z
/*! * @file Adafruit_SPITFT.cpp * * @mainpage Adafruit SPI TFT Displays (and some others) * * @section intro_sec Introduction * * Part of Adafruit's GFX graphics library. Originally this class was * written to handle a range of color TFT displays connected via SPI, * but over time this library and some display-specific subclasses have * mutated to include some color OLEDs as well as parallel-interfaced * displays. The name's been kept for the sake of older code. * * Adafruit invests time and resources providing this open source code, * please support Adafruit and open-source hardware by purchasing * products from Adafruit! * @section dependencies Dependencies * * This library depends on <a href="https://github.com/adafruit/Adafruit_GFX"> * Adafruit_GFX</a> being present on your system. Please make sure you have * installed the latest version before using this library. * * @section author Author * * Written by Limor "ladyada" Fried for Adafruit Industries, * with contributions from the open source community. * * @section license License * * BSD license, all text here must be included in any redistribution. */ #if !defined(__AVR_ATtiny85__) // Not for ATtiny, at all #include "Adafruit_SPITFT.h" #if defined(__AVR__) #if defined(__AVR_XMEGA__) // only tested with __AVR_ATmega4809__ #define AVR_WRITESPI(x) \ for (SPI0_DATA = (x); (!(SPI0_INTFLAGS & _BV(SPI_IF_bp)));) #else #define AVR_WRITESPI(x) for (SPDR = (x); (!(SPSR & _BV(SPIF)));) #endif #endif #if defined(PORT_IOBUS) // On SAMD21, redefine digitalPinToPort() to use the slightly-faster // PORT_IOBUS rather than PORT (not needed on SAMD51). #undef digitalPinToPort #define digitalPinToPort(P) (&(PORT_IOBUS->Group[g_APinDescription[P].ulPort])) #endif // end PORT_IOBUS #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)) // #pragma message ("GFX DMA IS ENABLED. HIGHLY EXPERIMENTAL.") #include "wiring_private.h" // pinPeripheral() function #include <Adafruit_ZeroDMA.h> #include <malloc.h> // memalign() function #define tcNum 2 // Timer/Counter for parallel write strobe PWM #define wrPeripheral PIO_CCL // Use CCL to invert write strobe // DMA transfer-in-progress indicator and callback static volatile bool dma_busy = false; static void dma_callback(Adafruit_ZeroDMA *dma) { dma_busy = false; } #if defined(__SAMD51__) // Timer/counter info by index # static const struct { Tc *tc; // -> Timer/Counter base address int gclk; // GCLK ID int evu; // EVSYS user ID } tcList[] = {{TC0, TC0_GCLK_ID, EVSYS_ID_USER_TC0_EVU}, {TC1, TC1_GCLK_ID, EVSYS_ID_USER_TC1_EVU}, {TC2, TC2_GCLK_ID, EVSYS_ID_USER_TC2_EVU}, {TC3, TC3_GCLK_ID, EVSYS_ID_USER_TC3_EVU}, #if defined(TC4) {TC4, TC4_GCLK_ID, EVSYS_ID_USER_TC4_EVU}, #endif #if defined(TC5) {TC5, TC5_GCLK_ID, EVSYS_ID_USER_TC5_EVU}, #endif #if defined(TC6) {TC6, TC6_GCLK_ID, EVSYS_ID_USER_TC6_EVU}, #endif #if defined(TC7) {TC7, TC7_GCLK_ID, EVSYS_ID_USER_TC7_EVU} #endif }; #define NUM_TIMERS (sizeof tcList / sizeof tcList[0]) ///< # timer/counters #endif // end __SAMD51__ #endif // end USE_SPI_DMA // Possible values for Adafruit_SPITFT.connection: #define TFT_HARD_SPI 0 ///< Display interface = hardware SPI #define TFT_SOFT_SPI 1 ///< Display interface = software SPI #define TFT_PARALLEL 2 ///< Display interface = 8- or 16-bit parallel // CONSTRUCTORS ------------------------------------------------------------ /*! @brief Adafruit_SPITFT constructor for software (bitbang) SPI. @param w Display width in pixels at default rotation setting (0). @param h Display height in pixels at default rotation setting (0). @param cs Arduino pin # for chip-select (-1 if unused, tie CS low). @param dc Arduino pin # for data/command select (required). @param mosi Arduino pin # for bitbang SPI MOSI signal (required). @param sck Arduino pin # for bitbang SPI SCK signal (required). @param rst Arduino pin # for display reset (optional, display reset can be tied to MCU reset, default of -1 means unused). @param miso Arduino pin # for bitbang SPI MISO signal (optional, -1 default, many displays don't support SPI read). @note Output pins are not initialized; application typically will need to call subclass' begin() function, which in turn calls this library's initSPI() function to initialize pins. */ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t mosi, int8_t sck, int8_t rst, int8_t miso) : Adafruit_GFX(w, h), connection(TFT_SOFT_SPI), _rst(rst), _cs(cs), _dc(dc) { swspi._sck = sck; swspi._mosi = mosi; swspi._miso = miso; #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(CORE_TEENSY) #if !defined(KINETISK) dcPinMask = digitalPinToBitMask(dc); swspi.sckPinMask = digitalPinToBitMask(sck); swspi.mosiPinMask = digitalPinToBitMask(mosi); #endif dcPortSet = portSetRegister(dc); dcPortClr = portClearRegister(dc); swspi.sckPortSet = portSetRegister(sck); swspi.sckPortClr = portClearRegister(sck); swspi.mosiPortSet = portSetRegister(mosi); swspi.mosiPortClr = portClearRegister(mosi); if (cs >= 0) { #if !defined(KINETISK) csPinMask = digitalPinToBitMask(cs); #endif csPortSet = portSetRegister(cs); csPortClr = portClearRegister(cs); } else { #if !defined(KINETISK) csPinMask = 0; #endif csPortSet = dcPortSet; csPortClr = dcPortClr; } if (miso >= 0) { swspi.misoPort = portInputRegister(miso); #if !defined(KINETISK) swspi.misoPinMask = digitalPinToBitMask(miso); #endif } else { swspi.misoPort = portInputRegister(dc); } #else // !CORE_TEENSY dcPinMask = digitalPinToBitMask(dc); swspi.sckPinMask = digitalPinToBitMask(sck); swspi.mosiPinMask = digitalPinToBitMask(mosi); dcPortSet = &(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg); dcPortClr = &(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg); swspi.sckPortSet = &(PORT->Group[g_APinDescription[sck].ulPort].OUTSET.reg); swspi.sckPortClr = &(PORT->Group[g_APinDescription[sck].ulPort].OUTCLR.reg); swspi.mosiPortSet = &(PORT->Group[g_APinDescription[mosi].ulPort].OUTSET.reg); swspi.mosiPortClr = &(PORT->Group[g_APinDescription[mosi].ulPort].OUTCLR.reg); if (cs >= 0) { csPinMask = digitalPinToBitMask(cs); csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg); csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPortSet = dcPortSet; csPortClr = dcPortClr; csPinMask = 0; } if (miso >= 0) { swspi.misoPinMask = digitalPinToBitMask(miso); swspi.misoPort = (PORTreg_t)portInputRegister(digitalPinToPort(miso)); } else { swspi.misoPinMask = 0; swspi.misoPort = (PORTreg_t)portInputRegister(digitalPinToPort(dc)); } #endif // end !CORE_TEENSY #else // !HAS_PORT_SET_CLR dcPort = (PORTreg_t)portOutputRegister(digitalPinToPort(dc)); dcPinMaskSet = digitalPinToBitMask(dc); swspi.sckPort = (PORTreg_t)portOutputRegister(digitalPinToPort(sck)); swspi.sckPinMaskSet = digitalPinToBitMask(sck); swspi.mosiPort = (PORTreg_t)portOutputRegister(digitalPinToPort(mosi)); swspi.mosiPinMaskSet = digitalPinToBitMask(mosi); if (cs >= 0) { csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs)); csPinMaskSet = digitalPinToBitMask(cs); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPort = dcPort; csPinMaskSet = 0; } if (miso >= 0) { swspi.misoPort = (PORTreg_t)portInputRegister(digitalPinToPort(miso)); swspi.misoPinMask = digitalPinToBitMask(miso); } else { swspi.misoPort = (PORTreg_t)portInputRegister(digitalPinToPort(dc)); swspi.misoPinMask = 0; } csPinMaskClr = ~csPinMaskSet; dcPinMaskClr = ~dcPinMaskSet; swspi.sckPinMaskClr = ~swspi.sckPinMaskSet; swspi.mosiPinMaskClr = ~swspi.mosiPinMaskSet; #endif // !end HAS_PORT_SET_CLR #endif // end USE_FAST_PINIO } /*! @brief Adafruit_SPITFT constructor for hardware SPI using the board's default SPI peripheral. @param w Display width in pixels at default rotation setting (0). @param h Display height in pixels at default rotation setting (0). @param cs Arduino pin # for chip-select (-1 if unused, tie CS low). @param dc Arduino pin # for data/command select (required). @param rst Arduino pin # for display reset (optional, display reset can be tied to MCU reset, default of -1 means unused). @note Output pins are not initialized; application typically will need to call subclass' begin() function, which in turn calls this library's initSPI() function to initialize pins. */ #if defined(ESP8266) // See notes below Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t rst) : Adafruit_GFX(w, h), connection(TFT_HARD_SPI), _rst(rst), _cs(cs), _dc(dc) { hwspi._spi = &SPI; } #else // !ESP8266 Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t rst) : Adafruit_SPITFT(w, h, &SPI, cs, dc, rst) { // This just invokes the hardware SPI constructor below, // passing the default SPI device (&SPI). } #endif // end !ESP8266 #if !defined(ESP8266) // ESP8266 compiler freaks out at this constructor -- it can't disambiguate // beteween the SPIClass pointer (argument #3) and a regular integer. // Solution here it to just not offer this variant on the ESP8266. You can // use the default hardware SPI peripheral, or you can use software SPI, // but if there's any library out there that creates a 'virtual' SPIClass // peripheral and drives it with software bitbanging, that's not supported. /*! @brief Adafruit_SPITFT constructor for hardware SPI using a specific SPI peripheral. @param w Display width in pixels at default rotation (0). @param h Display height in pixels at default rotation (0). @param spiClass Pointer to SPIClass type (e.g. &SPI or &SPI1). @param cs Arduino pin # for chip-select (-1 if unused, tie CS low). @param dc Arduino pin # for data/command select (required). @param rst Arduino pin # for display reset (optional, display reset can be tied to MCU reset, default of -1 means unused). @note Output pins are not initialized in constructor; application typically will need to call subclass' begin() function, which in turn calls this library's initSPI() function to initialize pins. EXCEPT...if you have built your own SERCOM SPI peripheral (calling the SPIClass constructor) rather than one of the built-in SPI devices (e.g. &SPI, &SPI1 and so forth), you will need to call the begin() function for your object as well as pinPeripheral() for the MOSI, MISO and SCK pins to configure GPIO manually. Do this BEFORE calling the display-specific begin or init function. Unfortunate but unavoidable. */ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, SPIClass *spiClass, int8_t cs, int8_t dc, int8_t rst) : Adafruit_GFX(w, h), connection(TFT_HARD_SPI), _rst(rst), _cs(cs), _dc(dc) { hwspi._spi = spiClass; #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(CORE_TEENSY) #if !defined(KINETISK) dcPinMask = digitalPinToBitMask(dc); #endif dcPortSet = portSetRegister(dc); dcPortClr = portClearRegister(dc); if (cs >= 0) { #if !defined(KINETISK) csPinMask = digitalPinToBitMask(cs); #endif csPortSet = portSetRegister(cs); csPortClr = portClearRegister(cs); } else { // see comments below #if !defined(KINETISK) csPinMask = 0; #endif csPortSet = dcPortSet; csPortClr = dcPortClr; } #else // !CORE_TEENSY dcPinMask = digitalPinToBitMask(dc); dcPortSet = &(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg); dcPortClr = &(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg); if (cs >= 0) { csPinMask = digitalPinToBitMask(cs); csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg); csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPortSet = dcPortSet; csPortClr = dcPortClr; csPinMask = 0; } #endif // end !CORE_TEENSY #else // !HAS_PORT_SET_CLR dcPort = (PORTreg_t)portOutputRegister(digitalPinToPort(dc)); dcPinMaskSet = digitalPinToBitMask(dc); if (cs >= 0) { csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs)); csPinMaskSet = digitalPinToBitMask(cs); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPort = dcPort; csPinMaskSet = 0; } csPinMaskClr = ~csPinMaskSet; dcPinMaskClr = ~dcPinMaskSet; #endif // end !HAS_PORT_SET_CLR #endif // end USE_FAST_PINIO } #endif // end !ESP8266 /*! @brief Adafruit_SPITFT constructor for parallel display connection. @param w Display width in pixels at default rotation (0). @param h Display height in pixels at default rotation (0). @param busWidth If tft16 (enumeration in header file), is a 16-bit parallel connection, else 8-bit. 16-bit isn't fully implemented or tested yet so applications should pass "tft8bitbus" for now...needed to stick a required enum argument in there to disambiguate this constructor from the soft-SPI case. Argument is ignored on 8-bit architectures (no 'wide' support there since PORTs are 8 bits anyway). @param d0 Arduino pin # for data bit 0 (1+ are extrapolated). The 8 (or 16) data bits MUST be contiguous and byte- aligned (or word-aligned for wide interface) within the same PORT register (might not correspond to Arduino pin sequence). @param wr Arduino pin # for write strobe (required). @param dc Arduino pin # for data/command select (required). @param cs Arduino pin # for chip-select (optional, -1 if unused, tie CS low). @param rst Arduino pin # for display reset (optional, display reset can be tied to MCU reset, default of -1 means unused). @param rd Arduino pin # for read strobe (optional, -1 if unused). @note Output pins are not initialized; application typically will need to call subclass' begin() function, which in turn calls this library's initSPI() function to initialize pins. Yes, the name is a misnomer...this library originally handled only SPI displays, parallel being a recent addition (but not wanting to break existing code). */ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, tftBusWidth busWidth, int8_t d0, int8_t wr, int8_t dc, int8_t cs, int8_t rst, int8_t rd) : Adafruit_GFX(w, h), connection(TFT_PARALLEL), _rst(rst), _cs(cs), _dc(dc) { tft8._d0 = d0; tft8._wr = wr; tft8._rd = rd; tft8.wide = (busWidth == tft16bitbus); #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(CORE_TEENSY) tft8.wrPortSet = portSetRegister(wr); tft8.wrPortClr = portClearRegister(wr); #if !defined(KINETISK) dcPinMask = digitalPinToBitMask(dc); #endif dcPortSet = portSetRegister(dc); dcPortClr = portClearRegister(dc); if (cs >= 0) { #if !defined(KINETISK) csPinMask = digitalPinToBitMask(cs); #endif csPortSet = portSetRegister(cs); csPortClr = portClearRegister(cs); } else { // see comments below #if !defined(KINETISK) csPinMask = 0; #endif csPortSet = dcPortSet; csPortClr = dcPortClr; } if (rd >= 0) { // if read-strobe pin specified... #if defined(KINETISK) tft8.rdPinMask = 1; #else // !KINETISK tft8.rdPinMask = digitalPinToBitMask(rd); #endif tft8.rdPortSet = portSetRegister(rd); tft8.rdPortClr = portClearRegister(rd); } else { tft8.rdPinMask = 0; tft8.rdPortSet = dcPortSet; tft8.rdPortClr = dcPortClr; } // These are all uint8_t* pointers -- elsewhere they're recast // as necessary if a 'wide' 16-bit interface is in use. tft8.writePort = portOutputRegister(d0); tft8.readPort = portInputRegister(d0); tft8.dirSet = portModeRegister(d0); tft8.dirClr = portModeRegister(d0); #else // !CORE_TEENSY tft8.wrPinMask = digitalPinToBitMask(wr); tft8.wrPortSet = &(PORT->Group[g_APinDescription[wr].ulPort].OUTSET.reg); tft8.wrPortClr = &(PORT->Group[g_APinDescription[wr].ulPort].OUTCLR.reg); dcPinMask = digitalPinToBitMask(dc); dcPortSet = &(PORT->Group[g_APinDescription[dc].ulPort].OUTSET.reg); dcPortClr = &(PORT->Group[g_APinDescription[dc].ulPort].OUTCLR.reg); if (cs >= 0) { csPinMask = digitalPinToBitMask(cs); csPortSet = &(PORT->Group[g_APinDescription[cs].ulPort].OUTSET.reg); csPortClr = &(PORT->Group[g_APinDescription[cs].ulPort].OUTCLR.reg); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPortSet = dcPortSet; csPortClr = dcPortClr; csPinMask = 0; } if (rd >= 0) { // if read-strobe pin specified... tft8.rdPinMask = digitalPinToBitMask(rd); tft8.rdPortSet = &(PORT->Group[g_APinDescription[rd].ulPort].OUTSET.reg); tft8.rdPortClr = &(PORT->Group[g_APinDescription[rd].ulPort].OUTCLR.reg); } else { tft8.rdPinMask = 0; tft8.rdPortSet = dcPortSet; tft8.rdPortClr = dcPortClr; } // Get pointers to PORT write/read/dir bytes within 32-bit PORT uint8_t dBit = g_APinDescription[d0].ulPin; // d0 bit # in PORT PortGroup *p = (&(PORT->Group[g_APinDescription[d0].ulPort])); uint8_t offset = dBit / 8; // d[7:0] byte # within PORT if (tft8.wide) offset &= ~1; // d[15:8] byte # within PORT // These are all uint8_t* pointers -- elsewhere they're recast // as necessary if a 'wide' 16-bit interface is in use. tft8.writePort = (volatile uint8_t *)&(p->OUT.reg) + offset; tft8.readPort = (volatile uint8_t *)&(p->IN.reg) + offset; tft8.dirSet = (volatile uint8_t *)&(p->DIRSET.reg) + offset; tft8.dirClr = (volatile uint8_t *)&(p->DIRCLR.reg) + offset; #endif // end !CORE_TEENSY #else // !HAS_PORT_SET_CLR tft8.wrPort = (PORTreg_t)portOutputRegister(digitalPinToPort(wr)); tft8.wrPinMaskSet = digitalPinToBitMask(wr); dcPort = (PORTreg_t)portOutputRegister(digitalPinToPort(dc)); dcPinMaskSet = digitalPinToBitMask(dc); if (cs >= 0) { csPort = (PORTreg_t)portOutputRegister(digitalPinToPort(cs)); csPinMaskSet = digitalPinToBitMask(cs); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csPort = dcPort; csPinMaskSet = 0; } if (rd >= 0) { // if read-strobe pin specified... tft8.rdPort = (PORTreg_t)portOutputRegister(digitalPinToPort(rd)); tft8.rdPinMaskSet = digitalPinToBitMask(rd); } else { tft8.rdPort = dcPort; tft8.rdPinMaskSet = 0; } csPinMaskClr = ~csPinMaskSet; dcPinMaskClr = ~dcPinMaskSet; tft8.wrPinMaskClr = ~tft8.wrPinMaskSet; tft8.rdPinMaskClr = ~tft8.rdPinMaskSet; tft8.writePort = (PORTreg_t)portOutputRegister(digitalPinToPort(d0)); tft8.readPort = (PORTreg_t)portInputRegister(digitalPinToPort(d0)); tft8.portDir = (PORTreg_t)portModeRegister(digitalPinToPort(d0)); #endif // end !HAS_PORT_SET_CLR #endif // end USE_FAST_PINIO } // end constructors ------- // CLASS MEMBER FUNCTIONS -------------------------------------------------- // begin() and setAddrWindow() MUST be declared by any subclass. /*! @brief Configure microcontroller pins for TFT interfacing. Typically called by a subclass' begin() function. @param freq SPI frequency when using hardware SPI. If default (0) is passed, will fall back on a device-specific value. Value is ignored when using software SPI or parallel connection. @param spiMode SPI mode when using hardware SPI. MUST be one of the values SPI_MODE0, SPI_MODE1, SPI_MODE2 or SPI_MODE3 defined in SPI.h. Do NOT attempt to pass '0' for SPI_MODE0 and so forth...the values are NOT the same! Use ONLY the defines! (Pity it's not an enum.) @note Another anachronistically-named function; this is called even when the display connection is parallel (not SPI). Also, this could probably be made private...quite a few class functions were generously put in the public section. */ void Adafruit_SPITFT::initSPI(uint32_t freq, uint8_t spiMode) { if (!freq) freq = DEFAULT_SPI_FREQ; // If no freq specified, use default // Init basic control pins common to all connection types if (_cs >= 0) { pinMode(_cs, OUTPUT); digitalWrite(_cs, HIGH); // Deselect } pinMode(_dc, OUTPUT); digitalWrite(_dc, HIGH); // Data mode if (connection == TFT_HARD_SPI) { #if defined(SPI_HAS_TRANSACTION) hwspi.settings = SPISettings(freq, MSBFIRST, spiMode); #else hwspi._freq = freq; // Save freq value for later #endif hwspi._mode = spiMode; // Save spiMode value for later // Call hwspi._spi->begin() ONLY if this is among the 'established' // SPI interfaces in variant.h. For DIY roll-your-own SERCOM SPIs, // begin() and pinPeripheral() calls MUST be made in one's calling // code, BEFORE the screen-specific begin/init function is called. // Reason for this is that SPI::begin() makes its own calls to // pinPeripheral() based on g_APinDescription[n].ulPinType, which // on non-established SPI interface pins will always be PIO_DIGITAL // or similar, while we need PIO_SERCOM or PIO_SERCOM_ALT...it's // highly unique between devices and variants for each pin or // SERCOM so we can't make those calls ourselves here. And the SPI // device needs to be set up before calling this because it's // immediately followed with initialization commands. Blargh. if ( #if !defined(SPI_INTERFACES_COUNT) 1 #endif #if SPI_INTERFACES_COUNT > 0 (hwspi._spi == &SPI) #endif #if SPI_INTERFACES_COUNT > 1 || (hwspi._spi == &SPI1) #endif #if SPI_INTERFACES_COUNT > 2 || (hwspi._spi == &SPI2) #endif #if SPI_INTERFACES_COUNT > 3 || (hwspi._spi == &SPI3) #endif #if SPI_INTERFACES_COUNT > 4 || (hwspi._spi == &SPI4) #endif #if SPI_INTERFACES_COUNT > 5 || (hwspi._spi == &SPI5) #endif ) { hwspi._spi->begin(); } } else if (connection == TFT_SOFT_SPI) { pinMode(swspi._mosi, OUTPUT); digitalWrite(swspi._mosi, LOW); pinMode(swspi._sck, OUTPUT); digitalWrite(swspi._sck, LOW); if (swspi._miso >= 0) { pinMode(swspi._miso, INPUT); } } else { // TFT_PARALLEL // Initialize data pins. We were only passed d0, so scan // the pin description list looking for the other pins. // They'll be on the same PORT, and within the next 7 (or 15) bits // (because we need to write to a contiguous PORT byte or word). #if defined(__AVR__) // PORT registers are 8 bits wide, so just need a register match... for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) { if ((PORTreg_t)portOutputRegister(digitalPinToPort(i)) == tft8.writePort) { pinMode(i, OUTPUT); digitalWrite(i, LOW); } } #elif defined(USE_FAST_PINIO) #if defined(CORE_TEENSY) if (!tft8.wide) { *tft8.dirSet = 0xFF; // Set port to output *tft8.writePort = 0x00; // Write all 0s } else { *(volatile uint16_t *)tft8.dirSet = 0xFFFF; *(volatile uint16_t *)tft8.writePort = 0x0000; } #else // !CORE_TEENSY uint8_t portNum = g_APinDescription[tft8._d0].ulPort, // d0 PORT # dBit = g_APinDescription[tft8._d0].ulPin, // d0 bit in PORT lastBit = dBit + (tft8.wide ? 15 : 7); for (uint8_t i = 0; i < PINS_COUNT; i++) { if ((g_APinDescription[i].ulPort == portNum) && (g_APinDescription[i].ulPin >= dBit) && (g_APinDescription[i].ulPin <= (uint32_t)lastBit)) { pinMode(i, OUTPUT); digitalWrite(i, LOW); } } #endif // end !CORE_TEENSY #endif pinMode(tft8._wr, OUTPUT); digitalWrite(tft8._wr, HIGH); if (tft8._rd >= 0) { pinMode(tft8._rd, OUTPUT); digitalWrite(tft8._rd, HIGH); } } if (_rst >= 0) { // Toggle _rst low to reset pinMode(_rst, OUTPUT); digitalWrite(_rst, HIGH); delay(100); digitalWrite(_rst, LOW); delay(100); digitalWrite(_rst, HIGH); delay(200); } #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)) if (((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) && (dma.allocate() == DMA_STATUS_OK)) { // Allocate channel // The DMA library needs to alloc at least one valid descriptor, // so we do that here. It's not used in the usual sense though, // just before a transfer we copy descriptor[0] to this address. if (dptr = dma.addDescriptor(NULL, NULL, 42, DMA_BEAT_SIZE_BYTE, false, false)) { // Alloc 2 scanlines worth of pixels on display's major axis, // whichever that is, rounding each up to 2-pixel boundary. int major = (WIDTH > HEIGHT) ? WIDTH : HEIGHT; major += (major & 1); // -> next 2-pixel bound, if needed. maxFillLen = major * 2; // 2 scanlines // Note to future self: if you decide to make the pixel buffer // much larger, remember that DMA transfer descriptors can't // exceed 65,535 bytes (not 65,536), meaning 32,767 pixels max. // Not that we have that kind of RAM to throw around right now. if ((pixelBuf[0] = (uint16_t *)malloc(maxFillLen * sizeof(uint16_t)))) { // Alloc OK. Get pointer to start of second scanline. pixelBuf[1] = &pixelBuf[0][major]; // Determine number of DMA descriptors needed to cover // entire screen when entire 2-line pixelBuf is used // (round up for fractional last descriptor). int numDescriptors = (WIDTH * HEIGHT + (maxFillLen - 1)) / maxFillLen; // DMA descriptors MUST be 128-bit (16 byte) aligned. // memalign() is considered obsolete but it's replacements // (aligned_alloc() or posix_memalign()) are not currently // available in the version of ARM GCC in use, but this // is, so here we are. if ((descriptor = (DmacDescriptor *)memalign( 16, numDescriptors * sizeof(DmacDescriptor)))) { int dmac_id; volatile uint32_t *data_reg; if (connection == TFT_HARD_SPI) { // THIS IS AN AFFRONT TO NATURE, but I don't know // any "clean" way to get the sercom number from the // the SPIClass pointer (e.g. &SPI or &SPI1), which // is all we have to work with. SPIClass does contain // a SERCOM pointer but it is a PRIVATE member! // Doing an UNSPEAKABLY HORRIBLE THING here, directly // accessing the first 32-bit value in the SPIClass // structure, knowing that's (currently) where the // SERCOM pointer lives, but this ENTIRELY DEPENDS on // that structure not changing nor the compiler // rearranging things. Oh the humanity! if (*(SERCOM **)hwspi._spi == &sercom0) { dmac_id = SERCOM0_DMAC_ID_TX; data_reg = &SERCOM0->SPI.DATA.reg; #if defined SERCOM1 } else if (*(SERCOM **)hwspi._spi == &sercom1) { dmac_id = SERCOM1_DMAC_ID_TX; data_reg = &SERCOM1->SPI.DATA.reg; #endif #if defined SERCOM2 } else if (*(SERCOM **)hwspi._spi == &sercom2) { dmac_id = SERCOM2_DMAC_ID_TX; data_reg = &SERCOM2->SPI.DATA.reg; #endif #if defined SERCOM3 } else if (*(SERCOM **)hwspi._spi == &sercom3) { dmac_id = SERCOM3_DMAC_ID_TX; data_reg = &SERCOM3->SPI.DATA.reg; #endif #if defined SERCOM4 } else if (*(SERCOM **)hwspi._spi == &sercom4) { dmac_id = SERCOM4_DMAC_ID_TX; data_reg = &SERCOM4->SPI.DATA.reg; #endif #if defined SERCOM5 } else if (*(SERCOM **)hwspi._spi == &sercom5) { dmac_id = SERCOM5_DMAC_ID_TX; data_reg = &SERCOM5->SPI.DATA.reg; #endif #if defined SERCOM6 } else if (*(SERCOM **)hwspi._spi == &sercom6) { dmac_id = SERCOM6_DMAC_ID_TX; data_reg = &SERCOM6->SPI.DATA.reg; #endif #if defined SERCOM7 } else if (*(SERCOM **)hwspi._spi == &sercom7) { dmac_id = SERCOM7_DMAC_ID_TX; data_reg = &SERCOM7->SPI.DATA.reg; #endif } dma.setPriority(DMA_PRIORITY_3); dma.setTrigger(dmac_id); dma.setAction(DMA_TRIGGER_ACTON_BEAT); // Initialize descriptor list. for (int d = 0; d < numDescriptors; d++) { // No need to set SRCADDR, DESCADDR or BTCNT -- // those are done in the pixel-writing functions. descriptor[d].BTCTRL.bit.VALID = true; descriptor[d].BTCTRL.bit.EVOSEL = DMA_EVENT_OUTPUT_DISABLE; descriptor[d].BTCTRL.bit.BLOCKACT = DMA_BLOCK_ACTION_NOACT; descriptor[d].BTCTRL.bit.BEATSIZE = DMA_BEAT_SIZE_BYTE; descriptor[d].BTCTRL.bit.DSTINC = 0; descriptor[d].BTCTRL.bit.STEPSEL = DMA_STEPSEL_SRC; descriptor[d].BTCTRL.bit.STEPSIZE = DMA_ADDRESS_INCREMENT_STEP_SIZE_1; descriptor[d].DSTADDR.reg = (uint32_t)data_reg; } } else { // Parallel connection #if defined(__SAMD51__) int dmaChannel = dma.getChannel(); // Enable event output, use EVOSEL output DMAC->Channel[dmaChannel].CHEVCTRL.bit.EVOE = 1; DMAC->Channel[dmaChannel].CHEVCTRL.bit.EVOMODE = 0; // CONFIGURE TIMER/COUNTER (for write strobe) Tc *timer = tcList[tcNum].tc; // -> Timer struct int id = tcList[tcNum].gclk; // Timer GCLK ID GCLK_PCHCTRL_Type pchctrl; // Set up timer clock source from GCLK GCLK->PCHCTRL[id].bit.CHEN = 0; // Stop timer while (GCLK->PCHCTRL[id].bit.CHEN) ; // Wait for it pchctrl.bit.GEN = GCLK_PCHCTRL_GEN_GCLK0_Val; pchctrl.bit.CHEN = 1; // Enable GCLK->PCHCTRL[id].reg = pchctrl.reg; while (!GCLK->PCHCTRL[id].bit.CHEN) ; // Wait for it // Disable timer/counter before configuring it timer->COUNT8.CTRLA.bit.ENABLE = 0; while (timer->COUNT8.SYNCBUSY.bit.STATUS) ; timer->COUNT8.WAVE.bit.WAVEGEN = 2; // NPWM timer->COUNT8.CTRLA.bit.MODE = 1; // 8-bit timer->COUNT8.CTRLA.bit.PRESCALER = 0; // 1:1 while (timer->COUNT8.SYNCBUSY.bit.STATUS) ; timer->COUNT8.CTRLBCLR.bit.DIR = 1; // Count UP while (timer->COUNT8.SYNCBUSY.bit.CTRLB) ; timer->COUNT8.CTRLBSET.bit.ONESHOT = 1; // One-shot while (timer->COUNT8.SYNCBUSY.bit.CTRLB) ; timer->COUNT8.PER.reg = 6; // PWM top while (timer->COUNT8.SYNCBUSY.bit.PER) ; timer->COUNT8.CC[0].reg = 2; // Compare while (timer->COUNT8.SYNCBUSY.bit.CC0) ; // Enable async input events, // event action = restart. timer->COUNT8.EVCTRL.bit.TCEI = 1; timer->COUNT8.EVCTRL.bit.EVACT = 1; // Enable timer timer->COUNT8.CTRLA.reg |= TC_CTRLA_ENABLE; while (timer->COUNT8.SYNCBUSY.bit.STATUS) ; #if (wrPeripheral == PIO_CCL) // CONFIGURE CCL (inverts timer/counter output) MCLK->APBCMASK.bit.CCL_ = 1; // Enable CCL clock CCL->CTRL.bit.ENABLE = 0; // Disable to config CCL->CTRL.bit.SWRST = 1; // Reset CCL registers CCL->LUTCTRL[tcNum].bit.ENABLE = 0; // Disable LUT CCL->LUTCTRL[tcNum].bit.FILTSEL = 0; // No filter CCL->LUTCTRL[tcNum].bit.INSEL0 = 6; // TC input CCL->LUTCTRL[tcNum].bit.INSEL1 = 0; // MASK CCL->LUTCTRL[tcNum].bit.INSEL2 = 0; // MASK CCL->LUTCTRL[tcNum].bit.TRUTH = 1; // Invert in 0 CCL->LUTCTRL[tcNum].bit.ENABLE = 1; // Enable LUT CCL->CTRL.bit.ENABLE = 1; // Enable CCL #endif // CONFIGURE EVENT SYSTEM // Set up event system clock source from GCLK... // Disable EVSYS, wait for disable GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN = 0; while (GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN) ; pchctrl.bit.GEN = GCLK_PCHCTRL_GEN_GCLK0_Val; pchctrl.bit.CHEN = 1; // Re-enable GCLK->PCHCTRL[EVSYS_GCLK_ID_0].reg = pchctrl.reg; // Wait for it, then enable EVSYS clock while (!GCLK->PCHCTRL[EVSYS_GCLK_ID_0].bit.CHEN) ; MCLK->APBBMASK.bit.EVSYS_ = 1; // Connect Timer EVU to ch 0 EVSYS->USER[tcList[tcNum].evu].reg = 1; // Datasheet recommends single write operation; // reg instead of bit. Also datasheet: PATH bits // must be zero when using async! EVSYS_CHANNEL_Type ev; ev.reg = 0; ev.bit.PATH = 2; // Asynchronous ev.bit.EVGEN = 0x22 + dmaChannel; // DMA channel 0+ EVSYS->Channel[0].CHANNEL.reg = ev.reg; // Initialize descriptor list. for (int d = 0; d < numDescriptors; d++) { // No need to set SRCADDR, DESCADDR or BTCNT -- // those are done in the pixel-writing functions. descriptor[d].BTCTRL.bit.VALID = true; // Event strobe on beat xfer: descriptor[d].BTCTRL.bit.EVOSEL = 0x3; descriptor[d].BTCTRL.bit.BLOCKACT = DMA_BLOCK_ACTION_NOACT; descriptor[d].BTCTRL.bit.BEATSIZE = tft8.wide ? DMA_BEAT_SIZE_HWORD : DMA_BEAT_SIZE_BYTE; descriptor[d].BTCTRL.bit.SRCINC = 1; descriptor[d].BTCTRL.bit.DSTINC = 0; descriptor[d].BTCTRL.bit.STEPSEL = DMA_STEPSEL_SRC; descriptor[d].BTCTRL.bit.STEPSIZE = DMA_ADDRESS_INCREMENT_STEP_SIZE_1; descriptor[d].DSTADDR.reg = (uint32_t)tft8.writePort; } #endif // __SAMD51 } // end parallel-specific DMA setup lastFillColor = 0x0000; lastFillLen = 0; dma.setCallback(dma_callback); return; // Success! // else clean up any partial allocation... } // end descriptor memalign() free(pixelBuf[0]); pixelBuf[0] = pixelBuf[1] = NULL; } // end pixelBuf malloc() // Don't currently have a descriptor delete function in // ZeroDMA lib, but if we did, it would be called here. } // end addDescriptor() dma.free(); // Deallocate DMA channel } #endif // end USE_SPI_DMA } /*! @brief Allow changing the SPI clock speed after initialization @param freq Desired frequency of SPI clock, may not be the end frequency you get based on what the chip can do! */ void Adafruit_SPITFT::setSPISpeed(uint32_t freq) { #if defined(SPI_HAS_TRANSACTION) hwspi.settings = SPISettings(freq, MSBFIRST, hwspi._mode); #else hwspi._freq = freq; // Save freq value for later #endif } /*! @brief Call before issuing command(s) or data to display. Performs chip-select (if required) and starts an SPI transaction (if using hardware SPI and transactions are supported). Required for all display types; not an SPI-specific function. */ void Adafruit_SPITFT::startWrite(void) { SPI_BEGIN_TRANSACTION(); if (_cs >= 0) SPI_CS_LOW(); } /*! @brief Call after issuing command(s) or data to display. Performs chip-deselect (if required) and ends an SPI transaction (if using hardware SPI and transactions are supported). Required for all display types; not an SPI-specific function. */ void Adafruit_SPITFT::endWrite(void) { if (_cs >= 0) SPI_CS_HIGH(); SPI_END_TRANSACTION(); } // ------------------------------------------------------------------------- // Lower-level graphics operations. These functions require a chip-select // and/or SPI transaction around them (via startWrite(), endWrite() above). // Higher-level graphics primitives might start a single transaction and // then make multiple calls to these functions (e.g. circle or text // rendering might make repeated lines or rects) before ending the // transaction. It's more efficient than starting a transaction every time. /*! @brief Draw a single pixel to the display at requested coordinates. Not self-contained; should follow a startWrite() call. @param x Horizontal position (0 = left). @param y Vertical position (0 = top). @param color 16-bit pixel color in '565' RGB format. */ void Adafruit_SPITFT::writePixel(int16_t x, int16_t y, uint16_t color) { if ((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) { setAddrWindow(x, y, 1, 1); SPI_WRITE16(color); } } /*! @brief Issue a series of pixels from memory to the display. Not self- contained; should follow startWrite() and setAddrWindow() calls. @param colors Pointer to array of 16-bit pixel values in '565' RGB format. @param len Number of elements in 'colors' array. @param block If true (default case if unspecified), function blocks until DMA transfer is complete. This is simply IGNORED if DMA is not enabled. If false, the function returns immediately after the last DMA transfer is started, and one should use the dmaWait() function before doing ANY other display-related activities (or even any SPI-related activities, if using an SPI display that shares the bus with other devices). @param bigEndian If using DMA, and if set true, bitmap in memory is in big-endian order (most significant byte first). By default this is false, as most microcontrollers seem to be little-endian and 16-bit pixel values must be byte-swapped before issuing to the display (which tend to be big-endian when using SPI or 8-bit parallel). If an application can optimize around this -- for example, a bitmap in a uint16_t array having the byte values already reordered big-endian, this can save some processing time here, ESPECIALLY if using this function's non-blocking DMA mode. Not all cases are covered...this is really here only for SAMD DMA and much forethought on the application side. */ void Adafruit_SPITFT::writePixels(uint16_t *colors, uint32_t len, bool block, bool bigEndian) { if (!len) return; // Avoid 0-byte transfers // avoid paramater-not-used complaints (void)block; (void)bigEndian; #if defined(ESP32) // ESP32 has a special SPI pixel-writing function... if (connection == TFT_HARD_SPI) { hwspi._spi->writePixels(colors, len * 2); return; } #elif defined(ARDUINO_NRF52_ADAFRUIT) && \ defined(NRF52840_XXAA) // Adafruit nRF52 use SPIM3 DMA at 32Mhz // TFT and SPI DMA endian is different we need to swap bytes if (!bigEndian) { for (uint32_t i = 0; i < len; i++) { colors[i] = __builtin_bswap16(colors[i]); } } // use the separate tx, rx buf variant to prevent overwrite the buffer hwspi._spi->transfer(colors, NULL, 2 * len); // swap back color buffer if (!bigEndian) { for (uint32_t i = 0; i < len; i++) { colors[i] = __builtin_bswap16(colors[i]); } } return; #elif defined(USE_SPI_DMA) && \ (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)) if ((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) { int maxSpan = maxFillLen / 2; // One scanline max uint8_t pixelBufIdx = 0; // Active pixel buffer number #if defined(__SAMD51__) if (connection == TFT_PARALLEL) { // Switch WR pin to PWM or CCL pinPeripheral(tft8._wr, wrPeripheral); } #endif // end __SAMD51__ if (!bigEndian) { // Normal little-endian situation... while (len) { int count = (len < maxSpan) ? len : maxSpan; // Because TFT and SAMD endianisms are different, must swap // bytes from the 'colors' array passed into a DMA working // buffer. This can take place while the prior DMA transfer // is in progress, hence the need for two pixelBufs. for (int i = 0; i < count; i++) { pixelBuf[pixelBufIdx][i] = __builtin_bswap16(*colors++); } // The transfers themselves are relatively small, so we don't // need a long descriptor list. We just alternate between the // first two, sharing pixelBufIdx for that purpose. descriptor[pixelBufIdx].SRCADDR.reg = (uint32_t)pixelBuf[pixelBufIdx] + count * 2; descriptor[pixelBufIdx].BTCTRL.bit.SRCINC = 1; descriptor[pixelBufIdx].BTCNT.reg = count * 2; descriptor[pixelBufIdx].DESCADDR.reg = 0; while (dma_busy) ; // Wait for prior line to finish // Move new descriptor into place... memcpy(dptr, &descriptor[pixelBufIdx], sizeof(DmacDescriptor)); dma_busy = true; dma.startJob(); // Trigger SPI DMA transfer if (connection == TFT_PARALLEL) dma.trigger(); pixelBufIdx = 1 - pixelBufIdx; // Swap DMA pixel buffers len -= count; } } else { // bigEndian == true // With big-endian pixel data, this can be handled as a single // DMA transfer using chained descriptors. Even full screen, this // needs only a relatively short descriptor list, each // transferring a max of 32,767 (not 32,768) pixels. The list // was allocated large enough to accommodate a full screen's // worth of data, so this won't run past the end of the list. int d, numDescriptors = (len + 32766) / 32767; for (d = 0; d < numDescriptors; d++) { int count = (len < 32767) ? len : 32767; descriptor[d].SRCADDR.reg = (uint32_t)colors + count * 2; descriptor[d].BTCTRL.bit.SRCINC = 1; descriptor[d].BTCNT.reg = count * 2; descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d + 1]; len -= count; colors += count; } descriptor[d - 1].DESCADDR.reg = 0; while (dma_busy) ; // Wait for prior transfer (if any) to finish // Move first descriptor into place and start transfer... memcpy(dptr, &descriptor[0], sizeof(DmacDescriptor)); dma_busy = true; dma.startJob(); // Trigger SPI DMA transfer if (connection == TFT_PARALLEL) dma.trigger(); } // end bigEndian lastFillColor = 0x0000; // pixelBuf has been sullied lastFillLen = 0; if (block) { while (dma_busy) ; // Wait for last line to complete #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO) if (connection == TFT_HARD_SPI) { // See SAMD51/21 note in writeColor() hwspi._spi->setDataMode(hwspi._mode); } else { pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO } #endif // end __SAMD51__ || ARDUINO_SAMD_ZERO } return; } #endif // end USE_SPI_DMA // All other cases (bitbang SPI or non-DMA hard SPI or parallel), // use a loop with the normal 16-bit data write function: while (len--) { SPI_WRITE16(*colors++); } } /*! @brief Wait for the last DMA transfer in a prior non-blocking writePixels() call to complete. This does nothing if DMA is not enabled, and is not needed if blocking writePixels() was used (as is the default case). */ void Adafruit_SPITFT::dmaWait(void) { #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)) while (dma_busy) ; #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO) if (connection == TFT_HARD_SPI) { // See SAMD51/21 note in writeColor() hwspi._spi->setDataMode(hwspi._mode); } else { pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO } #endif // end __SAMD51__ || ARDUINO_SAMD_ZERO #endif } /*! @brief Issue a series of pixels, all the same color. Not self- contained; should follow startWrite() and setAddrWindow() calls. @param color 16-bit pixel color in '565' RGB format. @param len Number of pixels to draw. */ void Adafruit_SPITFT::writeColor(uint16_t color, uint32_t len) { if (!len) return; // Avoid 0-byte transfers uint8_t hi = color >> 8, lo = color; #if defined(ESP32) // ESP32 has a special SPI pixel-writing function... if (connection == TFT_HARD_SPI) { #define SPI_MAX_PIXELS_AT_ONCE 32 #define TMPBUF_LONGWORDS (SPI_MAX_PIXELS_AT_ONCE + 1) / 2 #define TMPBUF_PIXELS (TMPBUF_LONGWORDS * 2) static uint32_t temp[TMPBUF_LONGWORDS]; uint32_t c32 = color * 0x00010001; uint16_t bufLen = (len < TMPBUF_PIXELS) ? len : TMPBUF_PIXELS, xferLen, fillLen; // Fill temp buffer 32 bits at a time fillLen = (bufLen + 1) / 2; // Round up to next 32-bit boundary for (uint32_t t = 0; t < fillLen; t++) { temp[t] = c32; } // Issue pixels in blocks from temp buffer while (len) { // While pixels remain xferLen = (bufLen < len) ? bufLen : len; // How many this pass? writePixels((uint16_t *)temp, xferLen); len -= xferLen; } return; } #elif defined(ARDUINO_NRF52_ADAFRUIT) && \ defined(NRF52840_XXAA) // Adafruit nRF52840 use SPIM3 DMA at 32Mhz // at most 2 scan lines uint32_t const pixbufcount = min(len, ((uint32_t)2 * width())); uint16_t *pixbuf = (uint16_t *)rtos_malloc(2 * pixbufcount); // use SPI3 DMA if we could allocate buffer, else fall back to writing each // pixel loop below if (pixbuf) { uint16_t const swap_color = __builtin_bswap16(color); // fill buffer with color for (uint32_t i = 0; i < pixbufcount; i++) { pixbuf[i] = swap_color; } while (len) { uint32_t const count = min(len, pixbufcount); writePixels(pixbuf, count, true, true); len -= count; } rtos_free(pixbuf); return; } #else // !ESP32 #if defined(USE_SPI_DMA) && (defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO)) if (((connection == TFT_HARD_SPI) || (connection == TFT_PARALLEL)) && (len >= 16)) { // Don't bother with DMA on short pixel runs int i, d, numDescriptors; if (hi == lo) { // If high & low bytes are same... onePixelBuf = color; // Can do this with a relatively short descriptor list, // each transferring a max of 32,767 (not 32,768) pixels. // This won't run off the end of the allocated descriptor list, // since we're using much larger chunks per descriptor here. numDescriptors = (len + 32766) / 32767; for (d = 0; d < numDescriptors; d++) { int count = (len < 32767) ? len : 32767; descriptor[d].SRCADDR.reg = (uint32_t)&onePixelBuf; descriptor[d].BTCTRL.bit.SRCINC = 0; descriptor[d].BTCNT.reg = count * 2; descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d + 1]; len -= count; } descriptor[d - 1].DESCADDR.reg = 0; } else { // If high and low bytes are distinct, it's necessary to fill // a buffer with pixel data (swapping high and low bytes because // TFT and SAMD are different endianisms) and create a longer // descriptor list pointing repeatedly to this data. We can do // this slightly faster working 2 pixels (32 bits) at a time. uint32_t *pixelPtr = (uint32_t *)pixelBuf[0], twoPixels = __builtin_bswap16(color) * 0x00010001; // We can avoid some or all of the buffer-filling if the color // is the same as last time... if (color == lastFillColor) { // If length is longer than prior instance, fill only the // additional pixels in the buffer and update lastFillLen. if (len > lastFillLen) { int fillStart = lastFillLen / 2, fillEnd = (((len < maxFillLen) ? len : maxFillLen) + 1) / 2; for (i = fillStart; i < fillEnd; i++) pixelPtr[i] = twoPixels; lastFillLen = fillEnd * 2; } // else do nothing, don't set pixels or change lastFillLen } else { int fillEnd = (((len < maxFillLen) ? len : maxFillLen) + 1) / 2; for (i = 0; i < fillEnd; i++) pixelPtr[i] = twoPixels; lastFillLen = fillEnd * 2; lastFillColor = color; } numDescriptors = (len + maxFillLen - 1) / maxFillLen; for (d = 0; d < numDescriptors; d++) { int pixels = (len < maxFillLen) ? len : maxFillLen, bytes = pixels * 2; descriptor[d].SRCADDR.reg = (uint32_t)pixelPtr + bytes; descriptor[d].BTCTRL.bit.SRCINC = 1; descriptor[d].BTCNT.reg = bytes; descriptor[d].DESCADDR.reg = (uint32_t)&descriptor[d + 1]; len -= pixels; } descriptor[d - 1].DESCADDR.reg = 0; } memcpy(dptr, &descriptor[0], sizeof(DmacDescriptor)); #if defined(__SAMD51__) if (connection == TFT_PARALLEL) { // Switch WR pin to PWM or CCL pinPeripheral(tft8._wr, wrPeripheral); } #endif // end __SAMD51__ dma_busy = true; dma.startJob(); if (connection == TFT_PARALLEL) dma.trigger(); while (dma_busy) ; // Wait for completion // Unfortunately blocking is necessary. An earlier version returned // immediately and checked dma_busy on startWrite() instead, but it // turns out to be MUCH slower on many graphics operations (as when // drawing lines, pixel-by-pixel), perhaps because it's a volatile // type and doesn't cache. Working on this. #if defined(__SAMD51__) || defined(ARDUINO_SAMD_ZERO) if (connection == TFT_HARD_SPI) { // SAMD51: SPI DMA seems to leave the SPI peripheral in a freaky // state on completion. Workaround is to explicitly set it back... // (5/17/2019: apparently SAMD21 too, in certain cases, observed // with ST7789 display.) hwspi._spi->setDataMode(hwspi._mode); } else { pinPeripheral(tft8._wr, PIO_OUTPUT); // Switch WR back to GPIO } #endif // end __SAMD51__ return; } #endif // end USE_SPI_DMA #endif // end !ESP32 // All other cases (non-DMA hard SPI, bitbang SPI, parallel)... if (connection == TFT_HARD_SPI) { #if defined(ESP8266) do { uint32_t pixelsThisPass = len; if (pixelsThisPass > 50000) pixelsThisPass = 50000; len -= pixelsThisPass; yield(); // Periodic yield() on long fills while (pixelsThisPass--) { hwspi._spi->write(hi); hwspi._spi->write(lo); } } while (len); #else // !ESP8266 while (len--) { #if defined(__AVR__) AVR_WRITESPI(hi); AVR_WRITESPI(lo); #elif defined(ESP32) hwspi._spi->write(hi); hwspi._spi->write(lo); #else hwspi._spi->transfer(hi); hwspi._spi->transfer(lo); #endif } #endif // end !ESP8266 } else if (connection == TFT_SOFT_SPI) { #if defined(ESP8266) do { uint32_t pixelsThisPass = len; if (pixelsThisPass > 20000) pixelsThisPass = 20000; len -= pixelsThisPass; yield(); // Periodic yield() on long fills while (pixelsThisPass--) { for (uint16_t bit = 0, x = color; bit < 16; bit++) { if (x & 0x8000) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); SPI_SCK_LOW(); x <<= 1; } } } while (len); #else // !ESP8266 while (len--) { #if defined(__AVR__) for (uint8_t bit = 0, x = hi; bit < 8; bit++) { if (x & 0x80) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); SPI_SCK_LOW(); x <<= 1; } for (uint8_t bit = 0, x = lo; bit < 8; bit++) { if (x & 0x80) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); SPI_SCK_LOW(); x <<= 1; } #else // !__AVR__ for (uint16_t bit = 0, x = color; bit < 16; bit++) { if (x & 0x8000) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); x <<= 1; SPI_SCK_LOW(); } #endif // end !__AVR__ } #endif // end !ESP8266 } else { // PARALLEL if (hi == lo) { #if defined(__AVR__) len *= 2; *tft8.writePort = hi; while (len--) { TFT_WR_STROBE(); } #elif defined(USE_FAST_PINIO) if (!tft8.wide) { len *= 2; *tft8.writePort = hi; } else { *(volatile uint16_t *)tft8.writePort = color; } while (len--) { TFT_WR_STROBE(); } #endif } else { while (len--) { #if defined(__AVR__) *tft8.writePort = hi; TFT_WR_STROBE(); *tft8.writePort = lo; #elif defined(USE_FAST_PINIO) if (!tft8.wide) { *tft8.writePort = hi; TFT_WR_STROBE(); *tft8.writePort = lo; } else { *(volatile uint16_t *)tft8.writePort = color; } #endif TFT_WR_STROBE(); } } } } /*! @brief Draw a filled rectangle to the display. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self-contained fillRect() instead. writeFillRect() performs its own edge clipping and rejection; see writeFillRectPreclipped() for a more 'raw' implementation. @param x Horizontal position of first corner. @param y Vertical position of first corner. @param w Rectangle width in pixels (positive = right of first corner, negative = left of first corner). @param h Rectangle height in pixels (positive = below first corner, negative = above first corner). @param color 16-bit fill color in '565' RGB format. @note Written in this deep-nested way because C by definition will optimize for the 'if' case, not the 'else' -- avoids branches and rejects clipped rectangles at the least-work possibility. */ void Adafruit_SPITFT::writeFillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if (w && h) { // Nonzero width and height? if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Rectangle partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (x2 >= _width) { w = _width - x; } // Clip right if (y2 >= _height) { h = _height - y; } // Clip bottom writeFillRectPreclipped(x, y, w, h, color); } } } } } } /*! @brief Draw a horizontal line on the display. Performs edge clipping and rejection. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self- contained drawFastHLine() instead. @param x Horizontal position of first point. @param y Vertical position of first point. @param w Line width in pixels (positive = right of first point, negative = point of first corner). @param color 16-bit line color in '565' RGB format. */ void inline Adafruit_SPITFT::writeFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { if ((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left // Line partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (x2 >= _width) { w = _width - x; } // Clip right writeFillRectPreclipped(x, y, w, 1, color); } } } } /*! @brief Draw a vertical line on the display. Performs edge clipping and rejection. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self- contained drawFastVLine() instead. @param x Horizontal position of first point. @param y Vertical position of first point. @param h Line height in pixels (positive = below first point, negative = above first point). @param color 16-bit line color in '565' RGB format. */ void inline Adafruit_SPITFT::writeFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if ((x >= 0) && (x < _width) && h) { // X on screen, nonzero height if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Line partly or fully overlaps screen if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (y2 >= _height) { h = _height - y; } // Clip bottom writeFillRectPreclipped(x, y, 1, h, color); } } } } /*! @brief A lower-level version of writeFillRect(). This version requires all inputs are in-bounds, that width and height are positive, and no part extends offscreen. NO EDGE CLIPPING OR REJECTION IS PERFORMED. If higher-level graphics primitives are written to handle their own clipping earlier in the drawing process, this can avoid unnecessary function calls and repeated clipping operations in the lower-level functions. @param x Horizontal position of first corner. MUST BE WITHIN SCREEN BOUNDS. @param y Vertical position of first corner. MUST BE WITHIN SCREEN BOUNDS. @param w Rectangle width in pixels. MUST BE POSITIVE AND NOT EXTEND OFF SCREEN. @param h Rectangle height in pixels. MUST BE POSITIVE AND NOT EXTEND OFF SCREEN. @param color 16-bit fill color in '565' RGB format. @note This is a new function, no graphics primitives besides rects and horizontal/vertical lines are written to best use this yet. */ inline void Adafruit_SPITFT::writeFillRectPreclipped(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { setAddrWindow(x, y, w, h); writeColor(color, (uint32_t)w * h); } // ------------------------------------------------------------------------- // Ever-so-slightly higher-level graphics operations. Similar to the 'write' // functions above, but these contain their own chip-select and SPI // transactions as needed (via startWrite(), endWrite()). They're typically // used solo -- as graphics primitives in themselves, not invoked by higher- // level primitives (which should use the functions above for better // performance). /*! @brief Draw a single pixel to the display at requested coordinates. Self-contained and provides its own transaction as needed (see writePixel(x,y,color) for a lower-level variant). Edge clipping is performed here. @param x Horizontal position (0 = left). @param y Vertical position (0 = top). @param color 16-bit pixel color in '565' RGB format. */ void Adafruit_SPITFT::drawPixel(int16_t x, int16_t y, uint16_t color) { // Clip first... if ((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) { // THEN set up transaction (if needed) and draw... startWrite(); setAddrWindow(x, y, 1, 1); SPI_WRITE16(color); endWrite(); } } /*! @brief Draw a filled rectangle to the display. Self-contained and provides its own transaction as needed (see writeFillRect() or writeFillRectPreclipped() for lower-level variants). Edge clipping and rejection is performed here. @param x Horizontal position of first corner. @param y Vertical position of first corner. @param w Rectangle width in pixels (positive = right of first corner, negative = left of first corner). @param h Rectangle height in pixels (positive = below first corner, negative = above first corner). @param color 16-bit fill color in '565' RGB format. @note This repeats the writeFillRect() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFillRect() to handle clipping and so forth) so that the transaction isn't performed at all if the rectangle is rejected. It's really not that much code. */ void Adafruit_SPITFT::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if (w && h) { // Nonzero width and height? if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Rectangle partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (x2 >= _width) { w = _width - x; } // Clip right if (y2 >= _height) { h = _height - y; } // Clip bottom startWrite(); writeFillRectPreclipped(x, y, w, h, color); endWrite(); } } } } } } /*! @brief Draw a horizontal line on the display. Self-contained and provides its own transaction as needed (see writeFastHLine() for a lower-level variant). Edge clipping and rejection is performed here. @param x Horizontal position of first point. @param y Vertical position of first point. @param w Line width in pixels (positive = right of first point, negative = point of first corner). @param color 16-bit line color in '565' RGB format. @note This repeats the writeFastHLine() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFastHLine() to handle clipping and so forth) so that the transaction isn't performed at all if the line is rejected. */ void Adafruit_SPITFT::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { if ((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left // Line partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (x2 >= _width) { w = _width - x; } // Clip right startWrite(); writeFillRectPreclipped(x, y, w, 1, color); endWrite(); } } } } /*! @brief Draw a vertical line on the display. Self-contained and provides its own transaction as needed (see writeFastHLine() for a lower- level variant). Edge clipping and rejection is performed here. @param x Horizontal position of first point. @param y Vertical position of first point. @param h Line height in pixels (positive = below first point, negative = above first point). @param color 16-bit line color in '565' RGB format. @note This repeats the writeFastVLine() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFastVLine() to handle clipping and so forth) so that the transaction isn't performed at all if the line is rejected. */ void Adafruit_SPITFT::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if ((x >= 0) && (x < _width) && h) { // X on screen, nonzero height if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Line partly or fully overlaps screen if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (y2 >= _height) { h = _height - y; } // Clip bottom startWrite(); writeFillRectPreclipped(x, y, 1, h, color); endWrite(); } } } } /*! @brief Essentially writePixel() with a transaction around it. I don't think this is in use by any of our code anymore (believe it was for some older BMP-reading examples), but is kept here in case any user code relies on it. Consider it DEPRECATED. @param color 16-bit pixel color in '565' RGB format. */ void Adafruit_SPITFT::pushColor(uint16_t color) { startWrite(); SPI_WRITE16(color); endWrite(); } /*! @brief Draw a 16-bit image (565 RGB) at the specified (x,y) position. For 16-bit display devices; no color reduction performed. Adapted from https://github.com/PaulStoffregen/ILI9341_t3 by Marc MERLIN. See examples/pictureEmbed to use this. 5/6/2017: function name and arguments have changed for compatibility with current GFX library and to avoid naming problems in prior implementation. Formerly drawBitmap() with arguments in different order. Handles its own transaction and edge clipping/rejection. @param x Top left corner horizontal coordinate. @param y Top left corner vertical coordinate. @param pcolors Pointer to 16-bit array of pixel values. @param w Width of bitmap in pixels. @param h Height of bitmap in pixels. */ void Adafruit_SPITFT::drawRGBBitmap(int16_t x, int16_t y, uint16_t *pcolors, int16_t w, int16_t h) { int16_t x2, y2; // Lower-right coord if ((x >= _width) || // Off-edge right (y >= _height) || // " top ((x2 = (x + w - 1)) < 0) || // " left ((y2 = (y + h - 1)) < 0)) return; // " bottom int16_t bx1 = 0, by1 = 0, // Clipped top-left within bitmap saveW = w; // Save original bitmap width value if (x < 0) { // Clip left w += x; bx1 = -x; x = 0; } if (y < 0) { // Clip top h += y; by1 = -y; y = 0; } if (x2 >= _width) w = _width - x; // Clip right if (y2 >= _height) h = _height - y; // Clip bottom pcolors += by1 * saveW + bx1; // Offset bitmap ptr to clipped top-left startWrite(); setAddrWindow(x, y, w, h); // Clipped area while (h--) { // For each (clipped) scanline... writePixels(pcolors, w); // Push one (clipped) row pcolors += saveW; // Advance pointer by one full (unclipped) line } endWrite(); } // ------------------------------------------------------------------------- // Miscellaneous class member functions that don't draw anything. /*! @brief Invert the colors of the display (if supported by hardware). Self-contained, no transaction setup required. @param i true = inverted display, false = normal display. */ void Adafruit_SPITFT::invertDisplay(bool i) { startWrite(); writeCommand(i ? invertOnCommand : invertOffCommand); endWrite(); } /*! @brief Given 8-bit red, green and blue values, return a 'packed' 16-bit color value in '565' RGB format (5 bits red, 6 bits green, 5 bits blue). This is just a mathematical operation, no hardware is touched. @param red 8-bit red brightnesss (0 = off, 255 = max). @param green 8-bit green brightnesss (0 = off, 255 = max). @param blue 8-bit blue brightnesss (0 = off, 255 = max). @return 'Packed' 16-bit color value (565 format). */ uint16_t Adafruit_SPITFT::color565(uint8_t red, uint8_t green, uint8_t blue) { return ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | (blue >> 3); } /*! @brief Adafruit_SPITFT Send Command handles complete sending of commands and data @param commandByte The Command Byte @param dataBytes A pointer to the Data bytes to send @param numDataBytes The number of bytes we should send */ void Adafruit_SPITFT::sendCommand(uint8_t commandByte, uint8_t *dataBytes, uint8_t numDataBytes) { SPI_BEGIN_TRANSACTION(); if (_cs >= 0) SPI_CS_LOW(); SPI_DC_LOW(); // Command mode spiWrite(commandByte); // Send the command byte SPI_DC_HIGH(); for (int i = 0; i < numDataBytes; i++) { if ((connection == TFT_PARALLEL) && tft8.wide) { SPI_WRITE16(*(uint16_t *)dataBytes); dataBytes += 2; } else { spiWrite(*dataBytes); // Send the data bytes dataBytes++; } } if (_cs >= 0) SPI_CS_HIGH(); SPI_END_TRANSACTION(); } /*! @brief Adafruit_SPITFT Send Command handles complete sending of commands and data @param commandByte The Command Byte @param dataBytes A pointer to the Data bytes to send @param numDataBytes The number of bytes we should send */ void Adafruit_SPITFT::sendCommand(uint8_t commandByte, const uint8_t *dataBytes, uint8_t numDataBytes) { SPI_BEGIN_TRANSACTION(); if (_cs >= 0) SPI_CS_LOW(); SPI_DC_LOW(); // Command mode spiWrite(commandByte); // Send the command byte SPI_DC_HIGH(); for (int i = 0; i < numDataBytes; i++) { if ((connection == TFT_PARALLEL) && tft8.wide) { SPI_WRITE16(*(uint16_t *)dataBytes); dataBytes += 2; } else { spiWrite(pgm_read_byte(dataBytes++)); } } if (_cs >= 0) SPI_CS_HIGH(); SPI_END_TRANSACTION(); } /*! @brief Adafruit_SPITFT sendCommand16 handles complete sending of commands and data for 16-bit parallel displays. Currently somewhat rigged for the NT35510, which has the odd behavior of wanting commands 16-bit, but subsequent data as 8-bit values, despite the 16-bit bus (high byte is always 0). Also seems to require issuing and incrementing address with each transfer. @param commandWord The command word (16 bits) @param dataBytes A pointer to the data bytes to send @param numDataBytes The number of bytes we should send */ void Adafruit_SPITFT::sendCommand16(uint16_t commandWord, const uint8_t *dataBytes, uint8_t numDataBytes) { SPI_BEGIN_TRANSACTION(); if (_cs >= 0) SPI_CS_LOW(); if (numDataBytes == 0) { SPI_DC_LOW(); // Command mode SPI_WRITE16(commandWord); // Send the command word SPI_DC_HIGH(); // Data mode } for (int i = 0; i < numDataBytes; i++) { SPI_DC_LOW(); // Command mode SPI_WRITE16(commandWord); // Send the command word SPI_DC_HIGH(); // Data mode commandWord++; SPI_WRITE16((uint16_t)pgm_read_byte(dataBytes++)); } if (_cs >= 0) SPI_CS_HIGH(); SPI_END_TRANSACTION(); } /*! @brief Read 8 bits of data from display configuration memory (not RAM). This is highly undocumented/supported and should be avoided, function is only included because some of the examples use it. @param commandByte The command register to read data from. @param index The byte index into the command to read from. @return Unsigned 8-bit data read from display register. */ /**************************************************************************/ uint8_t Adafruit_SPITFT::readcommand8(uint8_t commandByte, uint8_t index) { uint8_t result; startWrite(); SPI_DC_LOW(); // Command mode spiWrite(commandByte); SPI_DC_HIGH(); // Data mode do { result = spiRead(); } while (index--); // Discard bytes up to index'th endWrite(); return result; } /*! @brief Read 16 bits of data from display register. For 16-bit parallel displays only. @param addr Command/register to access. @return Unsigned 16-bit data. */ uint16_t Adafruit_SPITFT::readcommand16(uint16_t addr) { #if defined(USE_FAST_PINIO) // NOT SUPPORTED without USE_FAST_PINIO uint16_t result = 0; if ((connection == TFT_PARALLEL) && tft8.wide) { startWrite(); SPI_DC_LOW(); // Command mode SPI_WRITE16(addr); SPI_DC_HIGH(); // Data mode TFT_RD_LOW(); // Read line LOW #if defined(HAS_PORT_SET_CLR) *(volatile uint16_t *)tft8.dirClr = 0xFFFF; // Input state result = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.dirSet = 0xFFFF; // Output state #else // !HAS_PORT_SET_CLR *(volatile uint16_t *)tft8.portDir = 0x0000; // Input state result = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.portDir = 0xFFFF; // Output state #endif // end !HAS_PORT_SET_CLR TFT_RD_HIGH(); // Read line HIGH endWrite(); } return result; #else return 0; #endif // end !USE_FAST_PINIO } // ------------------------------------------------------------------------- // Lowest-level hardware-interfacing functions. Many of these are inline and // compile to different things based on #defines -- typically just a few // instructions. Others, not so much, those are not inlined. /*! @brief Start an SPI transaction if using the hardware SPI interface to the display. If using an earlier version of the Arduino platform (before the addition of SPI transactions), this instead attempts to set up the SPI clock and mode. No action is taken if the connection is not hardware SPI-based. This does NOT include a chip-select operation -- see startWrite() for a function that encapsulated both actions. */ inline void Adafruit_SPITFT::SPI_BEGIN_TRANSACTION(void) { if (connection == TFT_HARD_SPI) { #if defined(SPI_HAS_TRANSACTION) hwspi._spi->beginTransaction(hwspi.settings); #else // No transactions, configure SPI manually... #if defined(__AVR__) || defined(TEENSYDUINO) || defined(ARDUINO_ARCH_STM32F1) hwspi._spi->setClockDivider(SPI_CLOCK_DIV2); #elif defined(__arm__) hwspi._spi->setClockDivider(11); #elif defined(ESP8266) || defined(ESP32) hwspi._spi->setFrequency(hwspi._freq); #elif defined(RASPI) || defined(ARDUINO_ARCH_STM32F1) hwspi._spi->setClock(hwspi._freq); #endif hwspi._spi->setBitOrder(MSBFIRST); hwspi._spi->setDataMode(hwspi._mode); #endif // end !SPI_HAS_TRANSACTION } } /*! @brief End an SPI transaction if using the hardware SPI interface to the display. No action is taken if the connection is not hardware SPI-based or if using an earlier version of the Arduino platform (before the addition of SPI transactions). This does NOT include a chip-deselect operation -- see endWrite() for a function that encapsulated both actions. */ inline void Adafruit_SPITFT::SPI_END_TRANSACTION(void) { #if defined(SPI_HAS_TRANSACTION) if (connection == TFT_HARD_SPI) { hwspi._spi->endTransaction(); } #endif } /*! @brief Issue a single 8-bit value to the display. Chip-select, transaction and data/command selection must have been previously set -- this ONLY issues the byte. This is another of those functions in the library with a now-not-accurate name that's being maintained for compatibility with outside code. This function is used even if display connection is parallel. @param b 8-bit value to write. */ void Adafruit_SPITFT::spiWrite(uint8_t b) { if (connection == TFT_HARD_SPI) { #if defined(__AVR__) AVR_WRITESPI(b); #elif defined(ESP8266) || defined(ESP32) hwspi._spi->write(b); #else hwspi._spi->transfer(b); #endif } else if (connection == TFT_SOFT_SPI) { for (uint8_t bit = 0; bit < 8; bit++) { if (b & 0x80) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); b <<= 1; SPI_SCK_LOW(); } } else { // TFT_PARALLEL #if defined(__AVR__) *tft8.writePort = b; #elif defined(USE_FAST_PINIO) if (!tft8.wide) *tft8.writePort = b; else *(volatile uint16_t *)tft8.writePort = b; #endif TFT_WR_STROBE(); } } /*! @brief Write a single command byte to the display. Chip-select and transaction must have been previously set -- this ONLY sets the device to COMMAND mode, issues the byte and then restores DATA mode. There is no corresponding explicit writeData() function -- just use spiWrite(). @param cmd 8-bit command to write. */ void Adafruit_SPITFT::writeCommand(uint8_t cmd) { SPI_DC_LOW(); spiWrite(cmd); SPI_DC_HIGH(); } /*! @brief Read a single 8-bit value from the display. Chip-select and transaction must have been previously set -- this ONLY reads the byte. This is another of those functions in the library with a now-not-accurate name that's being maintained for compatibility with outside code. This function is used even if display connection is parallel. @return Unsigned 8-bit value read (always zero if USE_FAST_PINIO is not supported by the MCU architecture). */ uint8_t Adafruit_SPITFT::spiRead(void) { uint8_t b = 0; uint16_t w = 0; if (connection == TFT_HARD_SPI) { return hwspi._spi->transfer((uint8_t)0); } else if (connection == TFT_SOFT_SPI) { if (swspi._miso >= 0) { for (uint8_t i = 0; i < 8; i++) { SPI_SCK_HIGH(); b <<= 1; if (SPI_MISO_READ()) b++; SPI_SCK_LOW(); } } return b; } else { // TFT_PARALLEL if (tft8._rd >= 0) { #if defined(USE_FAST_PINIO) TFT_RD_LOW(); // Read line LOW #if defined(__AVR__) *tft8.portDir = 0x00; // Set port to input state w = *tft8.readPort; // Read value from port *tft8.portDir = 0xFF; // Restore port to output #else // !__AVR__ if (!tft8.wide) { // 8-bit TFT connection #if defined(HAS_PORT_SET_CLR) *tft8.dirClr = 0xFF; // Set port to input state w = *tft8.readPort; // Read value from port *tft8.dirSet = 0xFF; // Restore port to output #else // !HAS_PORT_SET_CLR *tft8.portDir = 0x00; // Set port to input state w = *tft8.readPort; // Read value from port *tft8.portDir = 0xFF; // Restore port to output #endif // end HAS_PORT_SET_CLR } else { // 16-bit TFT connection #if defined(HAS_PORT_SET_CLR) *(volatile uint16_t *)tft8.dirClr = 0xFFFF; // Input state w = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.dirSet = 0xFFFF; // Output state #else // !HAS_PORT_SET_CLR *(volatile uint16_t *)tft8.portDir = 0x0000; // Input state w = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.portDir = 0xFFFF; // Output state #endif // end !HAS_PORT_SET_CLR } TFT_RD_HIGH(); // Read line HIGH #endif // end !__AVR__ #else // !USE_FAST_PINIO w = 0; // Parallel TFT is NOT SUPPORTED without USE_FAST_PINIO #endif // end !USE_FAST_PINIO } return w; } } /*! @brief Issue a single 16-bit value to the display. Chip-select, transaction and data/command selection must have been previously set -- this ONLY issues the word. Thus operates ONLY on 'wide' (16-bit) parallel displays! @param w 16-bit value to write. */ void Adafruit_SPITFT::write16(uint16_t w) { if (connection == TFT_PARALLEL) { #if defined(USE_FAST_PINIO) if (tft8.wide) *(volatile uint16_t *)tft8.writePort = w; #endif TFT_WR_STROBE(); } } /*! @brief Write a single command word to the display. Chip-select and transaction must have been previously set -- this ONLY sets the device to COMMAND mode, issues the byte and then restores DATA mode. This operates ONLY on 'wide' (16-bit) parallel displays! @param cmd 16-bit command to write. */ void Adafruit_SPITFT::writeCommand16(uint16_t cmd) { SPI_DC_LOW(); write16(cmd); SPI_DC_HIGH(); } /*! @brief Read a single 16-bit value from the display. Chip-select and transaction must have been previously set -- this ONLY reads the byte. This operates ONLY on 'wide' (16-bit) parallel displays! @return Unsigned 16-bit value read (always zero if USE_FAST_PINIO is not supported by the MCU architecture). */ uint16_t Adafruit_SPITFT::read16(void) { uint16_t w = 0; if (connection == TFT_PARALLEL) { if (tft8._rd >= 0) { #if defined(USE_FAST_PINIO) TFT_RD_LOW(); // Read line LOW if (tft8.wide) { // 16-bit TFT connection #if defined(HAS_PORT_SET_CLR) *(volatile uint16_t *)tft8.dirClr = 0xFFFF; // Input state w = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.dirSet = 0xFFFF; // Output state #else // !HAS_PORT_SET_CLR *(volatile uint16_t *)tft8.portDir = 0x0000; // Input state w = *(volatile uint16_t *)tft8.readPort; // 16-bit read *(volatile uint16_t *)tft8.portDir = 0xFFFF; // Output state #endif // end !HAS_PORT_SET_CLR } TFT_RD_HIGH(); // Read line HIGH #else // !USE_FAST_PINIO w = 0; // Parallel TFT is NOT SUPPORTED without USE_FAST_PINIO #endif // end !USE_FAST_PINIO } } return w; } /*! @brief Set the software (bitbang) SPI MOSI line HIGH. */ inline void Adafruit_SPITFT::SPI_MOSI_HIGH(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(KINETISK) *swspi.mosiPortSet = 1; #else // !KINETISK *swspi.mosiPortSet = swspi.mosiPinMask; #endif #else // !HAS_PORT_SET_CLR *swspi.mosiPort |= swspi.mosiPinMaskSet; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(swspi._mosi, HIGH); #if defined(ESP32) for (volatile uint8_t i = 0; i < 1; i++) ; #endif // end ESP32 #endif // end !USE_FAST_PINIO } /*! @brief Set the software (bitbang) SPI MOSI line LOW. */ inline void Adafruit_SPITFT::SPI_MOSI_LOW(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(KINETISK) *swspi.mosiPortClr = 1; #else // !KINETISK *swspi.mosiPortClr = swspi.mosiPinMask; #endif #else // !HAS_PORT_SET_CLR *swspi.mosiPort &= swspi.mosiPinMaskClr; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(swspi._mosi, LOW); #if defined(ESP32) for (volatile uint8_t i = 0; i < 1; i++) ; #endif // end ESP32 #endif // end !USE_FAST_PINIO } /*! @brief Set the software (bitbang) SPI SCK line HIGH. */ inline void Adafruit_SPITFT::SPI_SCK_HIGH(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(KINETISK) *swspi.sckPortSet = 1; #else // !KINETISK *swspi.sckPortSet = swspi.sckPinMask; #if defined(__IMXRT1052__) || defined(__IMXRT1062__) // Teensy 4.x for (volatile uint8_t i = 0; i < 1; i++) ; #endif #endif #else // !HAS_PORT_SET_CLR *swspi.sckPort |= swspi.sckPinMaskSet; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(swspi._sck, HIGH); #if defined(ESP32) for (volatile uint8_t i = 0; i < 1; i++) ; #endif // end ESP32 #endif // end !USE_FAST_PINIO } /*! @brief Set the software (bitbang) SPI SCK line LOW. */ inline void Adafruit_SPITFT::SPI_SCK_LOW(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(KINETISK) *swspi.sckPortClr = 1; #else // !KINETISK *swspi.sckPortClr = swspi.sckPinMask; #if defined(__IMXRT1052__) || defined(__IMXRT1062__) // Teensy 4.x for (volatile uint8_t i = 0; i < 1; i++) ; #endif #endif #else // !HAS_PORT_SET_CLR *swspi.sckPort &= swspi.sckPinMaskClr; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(swspi._sck, LOW); #if defined(ESP32) for (volatile uint8_t i = 0; i < 1; i++) ; #endif // end ESP32 #endif // end !USE_FAST_PINIO } /*! @brief Read the state of the software (bitbang) SPI MISO line. @return true if HIGH, false if LOW. */ inline bool Adafruit_SPITFT::SPI_MISO_READ(void) { #if defined(USE_FAST_PINIO) #if defined(KINETISK) return *swspi.misoPort; #else // !KINETISK return *swspi.misoPort & swspi.misoPinMask; #endif // end !KINETISK #else // !USE_FAST_PINIO return digitalRead(swspi._miso); #endif // end !USE_FAST_PINIO } /*! @brief Issue a single 16-bit value to the display. Chip-select, transaction and data/command selection must have been previously set -- this ONLY issues the word. Despite the name, this function is used even if display connection is parallel; name was maintaned for backward compatibility. Naming is also not consistent with the 8-bit version, spiWrite(). Sorry about that. Again, staying compatible with outside code. @param w 16-bit value to write. */ void Adafruit_SPITFT::SPI_WRITE16(uint16_t w) { if (connection == TFT_HARD_SPI) { #if defined(__AVR__) AVR_WRITESPI(w >> 8); AVR_WRITESPI(w); #elif defined(ESP8266) || defined(ESP32) hwspi._spi->write16(w); #else hwspi._spi->transfer(w >> 8); hwspi._spi->transfer(w); #endif } else if (connection == TFT_SOFT_SPI) { for (uint8_t bit = 0; bit < 16; bit++) { if (w & 0x8000) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); SPI_SCK_LOW(); w <<= 1; } } else { // TFT_PARALLEL #if defined(__AVR__) *tft8.writePort = w >> 8; TFT_WR_STROBE(); *tft8.writePort = w; #elif defined(USE_FAST_PINIO) if (!tft8.wide) { *tft8.writePort = w >> 8; TFT_WR_STROBE(); *tft8.writePort = w; } else { *(volatile uint16_t *)tft8.writePort = w; } #endif TFT_WR_STROBE(); } } /*! @brief Issue a single 32-bit value to the display. Chip-select, transaction and data/command selection must have been previously set -- this ONLY issues the longword. Despite the name, this function is used even if display connection is parallel; name was maintaned for backward compatibility. Naming is also not consistent with the 8-bit version, spiWrite(). Sorry about that. Again, staying compatible with outside code. @param l 32-bit value to write. */ void Adafruit_SPITFT::SPI_WRITE32(uint32_t l) { if (connection == TFT_HARD_SPI) { #if defined(__AVR__) AVR_WRITESPI(l >> 24); AVR_WRITESPI(l >> 16); AVR_WRITESPI(l >> 8); AVR_WRITESPI(l); #elif defined(ESP8266) || defined(ESP32) hwspi._spi->write32(l); #else hwspi._spi->transfer(l >> 24); hwspi._spi->transfer(l >> 16); hwspi._spi->transfer(l >> 8); hwspi._spi->transfer(l); #endif } else if (connection == TFT_SOFT_SPI) { for (uint8_t bit = 0; bit < 32; bit++) { if (l & 0x80000000) SPI_MOSI_HIGH(); else SPI_MOSI_LOW(); SPI_SCK_HIGH(); SPI_SCK_LOW(); l <<= 1; } } else { // TFT_PARALLEL #if defined(__AVR__) *tft8.writePort = l >> 24; TFT_WR_STROBE(); *tft8.writePort = l >> 16; TFT_WR_STROBE(); *tft8.writePort = l >> 8; TFT_WR_STROBE(); *tft8.writePort = l; #elif defined(USE_FAST_PINIO) if (!tft8.wide) { *tft8.writePort = l >> 24; TFT_WR_STROBE(); *tft8.writePort = l >> 16; TFT_WR_STROBE(); *tft8.writePort = l >> 8; TFT_WR_STROBE(); *tft8.writePort = l; } else { *(volatile uint16_t *)tft8.writePort = l >> 16; TFT_WR_STROBE(); *(volatile uint16_t *)tft8.writePort = l; } #endif TFT_WR_STROBE(); } } /*! @brief Set the WR line LOW, then HIGH. Used for parallel-connected interfaces when writing data. */ inline void Adafruit_SPITFT::TFT_WR_STROBE(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) #if defined(KINETISK) *tft8.wrPortClr = 1; *tft8.wrPortSet = 1; #else // !KINETISK *tft8.wrPortClr = tft8.wrPinMask; *tft8.wrPortSet = tft8.wrPinMask; #endif // end !KINETISK #else // !HAS_PORT_SET_CLR *tft8.wrPort &= tft8.wrPinMaskClr; *tft8.wrPort |= tft8.wrPinMaskSet; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(tft8._wr, LOW); digitalWrite(tft8._wr, HIGH); #endif // end !USE_FAST_PINIO } /*! @brief Set the RD line HIGH. Used for parallel-connected interfaces when reading data. */ inline void Adafruit_SPITFT::TFT_RD_HIGH(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) *tft8.rdPortSet = tft8.rdPinMask; #else // !HAS_PORT_SET_CLR *tft8.rdPort |= tft8.rdPinMaskSet; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(tft8._rd, HIGH); #endif // end !USE_FAST_PINIO } /*! @brief Set the RD line LOW. Used for parallel-connected interfaces when reading data. */ inline void Adafruit_SPITFT::TFT_RD_LOW(void) { #if defined(USE_FAST_PINIO) #if defined(HAS_PORT_SET_CLR) *tft8.rdPortClr = tft8.rdPinMask; #else // !HAS_PORT_SET_CLR *tft8.rdPort &= tft8.rdPinMaskClr; #endif // end !HAS_PORT_SET_CLR #else // !USE_FAST_PINIO digitalWrite(tft8._rd, LOW); #endif // end !USE_FAST_PINIO } #endif // end __AVR_ATtiny85__
38.033838
80
0.611497
[ "object" ]
2961e419de1701b0ac246a3079e77da0f28e3e54
8,914
cpp
C++
src/preprocess/Preprocessor.cpp
shiruizhao/swift
2026acce35f0717c7a3e9dc522ff1c69f8dc3227
[ "BSD-4-Clause-UC", "BSD-4-Clause" ]
22
2016-07-11T15:34:14.000Z
2021-04-19T04:11:13.000Z
src/preprocess/Preprocessor.cpp
shiruizhao/swift
2026acce35f0717c7a3e9dc522ff1c69f8dc3227
[ "BSD-4-Clause-UC", "BSD-4-Clause" ]
14
2016-07-11T14:28:42.000Z
2017-01-27T02:59:24.000Z
src/preprocess/Preprocessor.cpp
shiruizhao/swift
2026acce35f0717c7a3e9dc522ff1c69f8dc3227
[ "BSD-4-Clause-UC", "BSD-4-Clause" ]
7
2016-10-03T10:05:06.000Z
2021-05-31T00:58:35.000Z
/* * Preprocessor.cpp * * Created on: Feb 18, 2014 * Author: yiwu */ #include "Preprocessor.h" #include "../absyn/ArrayExpr.h" #include <cassert> #include <memory> #include <utility> namespace swift { namespace preprocess { Preprocessor::Preprocessor() : errorMsg(stderr), blogProg(NULL) { } Preprocessor::~Preprocessor() { } void Preprocessor::process(absyn::BlogProgram* prog) { blogProg = prog; // Process Set Evidence processSetEvidence(blogProg); // Process Macros used in the expressions processMacro(blogProg); } void Preprocessor::processSetEvidence(absyn::BlogProgram*& prog) { // Note: It is reference here! We have to modify the BLOG program! std::vector<absyn::Stmt*>& all = prog->getAllRef(); for (size_t i = 0; i < all.size(); ++i) { absyn::Evidence* ev = dynamic_cast<absyn::Evidence*>(all[i]); if (ev == NULL) continue; absyn::SetExpr* lt = dynamic_cast<absyn::SetExpr*>(ev->getLeft()); absyn::ListSet* rt = dynamic_cast<absyn::ListSet*>(ev->getRight()); if (lt == NULL || rt == NULL) continue; if (dynamic_cast<absyn::ListSet*>(lt)!= NULL) continue; int line = rt->line, col = rt->col; absyn::CondSet* lcs = dynamic_cast<absyn::CondSet*>(lt); absyn::TupleSetExpr* lts = dynamic_cast<absyn::TupleSetExpr*>(lt); std::vector<absyn::Expr*> lfunc; if (lts != NULL) lfunc = lts->getExps(); absyn::Expr* lcond = (lts != NULL ? lts->getCond() : lcs->getCond()); if (lts != NULL && lts->getVarDecls().size() != 1) { //TODO: to support tupleset with multiple vars error(ev->line, ev->col, "For Set Evidence, we DO NOT support TupleSetExpr with Mutiple Variables!"); return ; } if (ev->getVarDecls().size() > 0) { //TODO: to support set evidence with for-loop error(ev->line, ev->col, "For Set Evidence, we DO NOT support for-loop now!"); return; } absyn::VarDecl lvar(lts != NULL ? lts->getVarDecl(0) : lcs->getVar()); // Set Evidence: obs {CondSet} = {ListSet} absyn::Expr* cd = lcond; if (cd != NULL) { // We DO support condition now, but a warning will be printer // TODO: use UniformChoiceK to better support condition warning(cd->line, cd->col, "For Evidence Set, condition on the set expression is not recommended!"); } // TODO: IMPORTANT!!! // due to lack of clone method, // we only support list set containing VarRef (FuncApp with no arguments) std::vector<absyn::Symbol> sym; for (size_t k = 0; k < rt->size(); ++k) { auto ref = dynamic_cast<absyn::FuncApp*>(rt->get(k)); if (ref == NULL || ref->size() > 0) { error(rt->line, rt->col, "For Evidence Set, We Only Support VarRef (FuncApp with no arguments) in the List Set (right hand side of the evidence)."); return; } sym.push_back(ref->getFuncName()); } // For the same reason, we do not support general expression in TupleSetExpr if (lfunc.size() != 1 || dynamic_cast<absyn::FuncApp*>(lfunc[0]) == NULL || (dynamic_cast<absyn::FuncApp*>(lfunc[0])->size() > 0) || (dynamic_cast<absyn::FuncApp*>(lfunc[0]))->getFuncName().getValue() != lvar.getVar().getValue()) { error(cd->line, cd->col, "For Evidence Set, We DO NOT general expression in TupleSetExpr (the left hand side of the evidence)."); return; } // Modify BLOG Program now! // :::=> obs {} = int literal absyn::VarDecl var = lvar; ev->setLeft(new absyn::CardinalityExpr(line, col, lt)); ev->setRight(new absyn::IntLiteral(line, col, rt->size())); // :::=> randon <element> ~ UniformChoice({T t: t != prev}) for (size_t k = 0; k < sym.size(); ++k) { auto dist = new absyn::FuncApp(line, col, absyn::Symbol("UniformChoice")); absyn::Expr* root = (lcond != NULL ? lcond->clone() : NULL); for (size_t p = 0; p < k; ++p) { absyn::Expr* cur = new absyn::OpExpr(line, col, absyn::AbsynConstant::NEQ, new absyn::FuncApp(line, col, var.getVar()), new absyn::FuncApp(line, col, sym[p])); if (root == NULL) root = cur; else root = new absyn::OpExpr(line, col, absyn::AbsynConstant::AND, root->clone(), cur); } auto arg = new absyn::CondSet(line, col, var, root); dist->add(arg); auto ucfunc = new absyn::FuncDecl(line, col, true, var.getTyp(), sym[k], dist); all.push_back(ucfunc); } // Do the Pointer Clearance delete rt; } } std::vector<absyn::Expr*> Preprocessor::parse_macro_EXPAND(absyn::FuncApp* fun) { assert(fun->getFuncName().getValue() == "EXPAND"); std::vector<absyn::Expr*> ret; if (fun->size() != 3) { error(fun->line, fun->col, "error usage for macro <EXPAND>! correct syntax: EXPAND(expr, a, b) where a and b must be non-negative FIXED integers and a <= b!"); return ret; } auto& args = fun->getAllExpr(); auto expr = args[0]; auto a = dynamic_cast<absyn::IntLiteral*>(args[1]); auto b = dynamic_cast<absyn::IntLiteral*>(args[2]); if (expr == NULL || a == NULL || b == NULL || a->getValue() > b->getValue() || a->getValue() < 0) { error(fun->line, fun->col, "error usage for macro <EXPAND>! correct syntax: EXPAND(expr, a, b) where a and b must be non-negative FIXED integers and a <= b!"); return ret; } int v_a = a->getValue(), v_b = b->getValue(); for (int i = v_a; i <= v_b; ++i) { ret.push_back(new absyn::OpExpr(fun->line,fun->col, absyn::AbsynConstant::SUB, expr->clone(), new absyn::IntLiteral(fun->line, fun->col, i))); } return ret; } absyn::Expr* Preprocessor::parse_expr(absyn::Expr* expr) { if (expr == NULL) return NULL; auto& args = expr->getAllExpr(); auto fun = dynamic_cast<absyn::FuncApp*>(expr); auto lstset = dynamic_cast<absyn::ListSet*>(expr); auto arr = dynamic_cast<absyn::ArrayExpr*>(expr); if (fun != NULL || lstset != NULL || arr != NULL) { // Check Macro: EXPAND, which locates in a restricted environment size_t ptr = 0; for (; ptr < args.size(); ++ ptr) { auto subfun = dynamic_cast<absyn::FuncApp*>(args[ptr]); if (subfun != NULL && subfun->getFuncName().getValue() == "EXPAND") { auto ret = parse_macro_EXPAND(subfun); if (ret.size() == 0) continue; // error delete args[ptr]; args.erase(args.begin() + ptr); args.insert(args.begin() + ptr, ret.begin(), ret.end()); -- ptr; // make sure that ptr keeps in the same position continue; } } } for (size_t i = 0; i < args.size(); ++i) { absyn::Expr* ret = NULL; ret = parse_expr(args[i]); if (ret != NULL) args[i] = ret; } if (arr != NULL) { // ensure <dim> field in ArrayExpr int base_dim = -1; absyn::ArrayExpr* sub; bool ok=true; for (size_t i = 0; i < arr->size(); i++) { sub = dynamic_cast<absyn::ArrayExpr*>(arr->get(i)); if (sub != NULL) { if (base_dim < 0) base_dim = sub->getDim(); else if (base_dim != sub->getDim()) { ok = false; if (sub->getDim() > base_dim) base_dim = sub->getDim(); } } else { if (base_dim < 0) base_dim = 0; else if (base_dim != 0) ok=false; } } if (!ok) { error(arr->line, arr->col, "Illegal <ArrayExpr>: Every element in the array should have the same dimension."); } if (base_dim < 0) base_dim = 0; if (arr->getDim() != base_dim + 1) { arr->setDim(base_dim + 1); } } return NULL; } void Preprocessor::processMacro(absyn::BlogProgram*& prog) { for (auto& st : prog->getAll()) { absyn::Expr* ret = NULL; auto fun = dynamic_cast<absyn::FuncDecl*>(st); if (fun != NULL) { ret = parse_expr(fun->getExpr()); if (ret != NULL) fun->getExpr() = ret; } auto num = dynamic_cast<absyn::NumStDecl*>(st); if (num != NULL) { ret = parse_expr(num->getExpr()); if (ret != NULL) num->getExpr() = ret; } auto query = dynamic_cast<absyn::Query*>(st); if (query != NULL) { ret = parse_expr(query->getExpr()); if (ret != NULL) query->getExpr() = ret; } auto evi = dynamic_cast<absyn::Evidence*>(st); if (evi != NULL) { ret = parse_expr(evi->getLeft()); if (ret != NULL) evi->setLeft(ret); ret = parse_expr(evi->getRight()); if (ret != NULL) evi->setRight(ret); if (evi->getCond() != NULL) { ret = parse_expr(evi->getCond()); if (ret != NULL) evi->setCond(ret); } } } } void Preprocessor::error(int line, int col, std::string info) { errorMsg.error(line, col, info); } void Preprocessor::warning(int line, int col, std::string info) { errorMsg.warning(line, col, info); } bool Preprocessor::Okay() { return errorMsg.Okay(); } absyn::BlogProgram* Preprocessor::getProg() { return blogProg; } } } /* namespace swift */
34.022901
163
0.593561
[ "vector" ]
2963902e55e01a257adae0366c3ea4c9f1209509
10,911
cc
C++
bench/Fused8BitRowwiseEmbeddingBenchmark.cc
wuhuikx/FBGEMM
672beabd4c315a020adf07a1b8bd2018a18e0dd1
[ "BSD-3-Clause" ]
null
null
null
bench/Fused8BitRowwiseEmbeddingBenchmark.cc
wuhuikx/FBGEMM
672beabd4c315a020adf07a1b8bd2018a18e0dd1
[ "BSD-3-Clause" ]
null
null
null
bench/Fused8BitRowwiseEmbeddingBenchmark.cc
wuhuikx/FBGEMM
672beabd4c315a020adf07a1b8bd2018a18e0dd1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <immintrin.h> #include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> #include <random> #include <set> #include <vector> #include "fbgemm/Fbgemm.h" #include "fbgemm/Utils.h" #include "src/RefImplementations.h" using namespace std; using namespace fbgemm; namespace { template <typename T> void llc_flush(std::vector<T>& v) { constexpr int CACHE_LINE_SIZE = 64; for (int i = 0; i < v.size(); i += CACHE_LINE_SIZE / sizeof(T)) { _mm_clflush(&v[i]); } } void llc_flush_fused_table(const uint8_t* table, int size) { constexpr int CACHE_LINE_SIZE = 64; for (int i = 0; i < size; i += CACHE_LINE_SIZE) { _mm_clflush(&table[i]); } } } // anonymous namespace void print_outupt(int rows, int embedding_dim, const float* output) { for (int i = 0; i < rows; i++) { std::cout << "output row: " << i << " : " << std::endl; for (int ii = 0; ii < embedding_dim; ii++) { std::cout << output[i * embedding_dim + ii] << ","; } std::cout << std::endl; } } void print_fused_table(int rows, int embedding_dim, const uint8_t* table) { for (int i = 0; i < rows; i++) { std::cout << "row: " << i << " : " << std::endl; for (int ii = 0; ii < embedding_dim; ii++) { std::cout << (int)table[i * (embedding_dim + 2 * sizeof(float)) + ii] << ","; } std::cout << std::endl; } } static vector<vector<int>> GetInputs_() { vector<vector<int>> input_dims = { // batch size, number of rows of table, emb dim , avg lengthl // TODO: Add more inputs // Use these -- but they are slow. //{100, 4000000, 32, 100}, // {10, 4000000, 64, 100}, // {10, 4000000, 128, 100}, // {10, 4000000, 256, 100}, // Use these for debugging {2, 16, 128, 10}, {10, 4000, 128, 100}, {10, 4000, 128, 100}, {10, 4000, 128, 100}, }; return input_dims; } int run_benchmark( int batch_size, int num_unique_ids, int embedding_dim, int average_len, bool normalize_by_lengths, bool use_32_bit_indices = false, bool prefetch = false) { // Create embedding table vector<uint8_t> embedding_table( num_unique_ids * (embedding_dim + 2 * sizeof(float))); default_random_engine generator; normal_distribution<float> embedding_distribution; uint8_t* fused_embedding_table = new uint8_t[num_unique_ids * (embedding_dim + 2 * sizeof(float))]; for (int i = 0; i < num_unique_ids; i++) { for (int ii = 0; ii < embedding_dim; ii++) { fused_embedding_table[i * (embedding_dim + 2 * sizeof(float)) + ii] = 2; } float* scale_bias = reinterpret_cast<float*>( fused_embedding_table + i * (embedding_dim + 2 * sizeof(float)) + embedding_dim); scale_bias[0] = 2.0; scale_bias[1] = 1.0; } // print_fused_table(num_unique_ids, embedding_dim, fused_embedding_table); // Generate lengths uniform_int_distribution<int> length_distribution(1, 2 * average_len + 1); vector<int> lengths(batch_size); for (int i = 0; i < batch_size; ++i) { lengths[i] = length_distribution(generator); } // Compute the number of indices int lengths_sum = accumulate(lengths.begin(), lengths.end(), 0); cout << "lengths_sum " << lengths_sum << endl; // Generate indices vector<int64_t> indices; vector<int32_t> indices_32; vector<int> container(num_unique_ids); map<int64_t, set<int>> dedup_map; // index -> set(output index) // please note we generate unique indices for (int i = 0; i < batch_size; ++i) { iota(container.begin(), container.end(), 0); random_shuffle(container.begin(), container.end()); copy( container.begin(), container.begin() + lengths[i], back_inserter(indices)); } copy(begin(indices), end(indices), back_inserter(indices_32)); // Generate weights vector<float> weights(lengths_sum); for (int i = 0; i < lengths_sum; ++i) { weights[i] = embedding_distribution(generator); } vector<float> output_sls_ref(batch_size * embedding_dim); vector<float> output_slws_ref(output_sls_ref.size()), output_sls(output_sls_ref.size()), output_slws(output_sls_ref.size()); chrono::time_point<chrono::system_clock> t_begin, t_end; double t; constexpr int NUM_WARMUP = 4; constexpr int NUM_ITER = 10; // Only counts the number of bytes for reading embedding table and ignore // others. Should be good enough as long as embdding_dim is big enough. double bytes = static_cast<double>(NUM_ITER) * lengths_sum * (embedding_dim * sizeof(uint8_t) + 2 * sizeof(float)); double bytes_padded = static_cast<double>(NUM_ITER) * lengths_sum * 64 * static_cast<int>( (embedding_dim * sizeof(uint8_t) + 2 * sizeof(float) + 63) / 64); for (bool has_weight : {false, true}) { vector<float>& output_ref = has_weight ? output_slws_ref : output_sls_ref; for (int i = 0; i < NUM_WARMUP + NUM_ITER; ++i) { if (use_32_bit_indices) { fbgemm:: Fused8BitRowwiseEmbeddingLookup_ref<int32_t, uint8_t, float, false>( embedding_dim, batch_size, lengths_sum, num_unique_ids, fused_embedding_table, indices_32.data(), lengths.data(), has_weight ? weights.data() : nullptr, normalize_by_lengths, output_ref.data()); } else { fbgemm:: Fused8BitRowwiseEmbeddingLookup_ref<int64_t, uint8_t, float, false>( embedding_dim, batch_size, lengths_sum, num_unique_ids, fused_embedding_table, indices.data(), lengths.data(), has_weight ? weights.data() : nullptr, normalize_by_lengths, output_ref.data()); } } vector<float>& output = has_weight ? output_slws : output_sls; for (bool flush_cache : {false, true}) { t = 0; for (int i = 0; i < NUM_WARMUP + NUM_ITER; ++i) { if (flush_cache) { llc_flush(embedding_table); llc_flush_fused_table( fused_embedding_table, num_unique_ids * (embedding_dim + 8)); llc_flush(indices); llc_flush(indices_32); llc_flush(lengths); llc_flush(weights); llc_flush(output); } if (use_32_bit_indices) { t_begin = chrono::system_clock::now(); fbgemm::Fused8BitRowwiseEmbeddingLookup<int32_t>( embedding_dim, batch_size, lengths_sum, num_unique_ids, fused_embedding_table, indices_32.data(), lengths.data(), has_weight ? weights.data() : nullptr, normalize_by_lengths, output.data(), prefetch ? 16 : 0); t_end = chrono::system_clock::now(); } else { t_begin = chrono::system_clock::now(); fbgemm::Fused8BitRowwiseEmbeddingLookup<int64_t>( embedding_dim, batch_size, lengths_sum, num_unique_ids, fused_embedding_table, indices.data(), lengths.data(), has_weight ? weights.data() : nullptr, normalize_by_lengths, output.data(), prefetch ? 16 : 0); t_end = chrono::system_clock::now(); } if (i >= NUM_WARMUP) { t += chrono::duration<double>(t_end - t_begin).count(); } } // print_outupt(batch_size, embedding_dim, output.data()); // print_outupt(batch_size, embedding_dim, output_ref.data()); // Check correctness if (!flush_cache) { // vector<float>& output_ref = // has_weight ? output_slws_ref : output_sls_ref; for (int i = 0; i < output.size(); ++i) { assert(fabs(output[i] - output_ref[i]) < 1e-3); if (fabs(output[i] - output_ref[i]) >= 1e-3) { cout << i << " " << output[i] << " " << output_ref[i] << endl; } } } if (has_weight) { cout << setw(16) << "SLW(WEIGHTED) "; } else { cout << setw(16) << "SLS "; } if (flush_cache) { cout << setw(20) << "cache flushed"; } else { cout << setw(20) << "cache not flushed"; } if (prefetch) { cout << setw(16) << "prefetch on"; } else { cout << setw(16) << "prefetch off"; } cout << setw(8) << "b/w" << setw(10) << bytes / 1e9 / t << " GB/s" << setw(20) << "effective b/w: " << setw(16) << bytes_padded / 1e9 / t << "GB/s" << setw(8) << " time " << setw(16) << t << endl; } // flush_cache } // has_weight return 0; } int main() { int batch_size; int num_unique_ids; int embedding_dim; int average_len; vector<vector<int>> inputs(GetInputs_()); for (auto& input : inputs) { assert(input.size() > 3); batch_size = input[0]; num_unique_ids = input[1]; embedding_dim = input[2]; average_len = input[3]; cout << "batch size" << setw(6) << batch_size << setw(10) << "num rows" << setw(16) << num_unique_ids << setw(10) << "emb dim" << setw(6) << embedding_dim << setw(16) << "avg length" << setw(6) << average_len << endl; // args: batch sz, num rows, emb dim, avg len, normalize, use 32b, prefetch cout << "64 bit indices, "; run_benchmark( batch_size, num_unique_ids, embedding_dim, average_len, false); cout << "64 bit indices with prefetching, "; run_benchmark( batch_size, num_unique_ids, embedding_dim, average_len, false, false, true); cout << "32 bit indices, "; run_benchmark( batch_size, num_unique_ids, embedding_dim, average_len, false, true); cout << "32 bit indices with prefetching, "; run_benchmark( batch_size, num_unique_ids, embedding_dim, average_len, false, true, true); // running with normalize by lengths // run_benchmark(batch_size, num_unique_ids, embedding_dim, average_len, // true); run_benchmark( // batch_size, num_unique_ids, embedding_dim, average_len, true, true); // run_benchmark( // batch_size, // num_unique_ids, // embedding_dim, // average_len, // false, // true, // true); } return 0; }
30.477654
80
0.578774
[ "vector" ]
296699b3c7c9bb238b9c279c14325097ceb6f23a
23,226
cpp
C++
src/test/rpc/ShardArchiveHandler_test.cpp
sneh19337/rippled
442205bdf270d26f0936f7ece5f03bcc952a6a8b
[ "BSL-1.0" ]
3,804
2015-01-02T01:50:44.000Z
2022-03-31T23:28:19.000Z
src/test/rpc/ShardArchiveHandler_test.cpp
sneh19337/rippled
442205bdf270d26f0936f7ece5f03bcc952a6a8b
[ "BSL-1.0" ]
3,131
2015-01-01T04:00:06.000Z
2022-03-31T19:41:33.000Z
src/test/rpc/ShardArchiveHandler_test.cpp
sneh19337/rippled
442205bdf270d26f0936f7ece5f03bcc952a6a8b
[ "BSL-1.0" ]
1,349
2015-01-04T04:36:22.000Z
2022-03-31T08:56:50.000Z
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2020 Ripple Labs Inc. 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. */ //============================================================================== #include <ripple/app/rdb/RelationalDBInterface_shards.h> #include <ripple/beast/utility/temp_dir.h> #include <ripple/core/ConfigSections.h> #include <ripple/nodestore/DummyScheduler.h> #include <ripple/nodestore/Manager.h> #include <ripple/nodestore/impl/DecodedBlob.h> #include <ripple/protocol/jss.h> #include <ripple/rpc/ShardArchiveHandler.h> #include <test/jtx/CaptureLogs.h> #include <test/jtx/Env.h> #include <test/jtx/TrustedPublisherServer.h> #include <test/jtx/envconfig.h> #include <test/nodestore/TestBase.h> namespace ripple { namespace test { class ShardArchiveHandler_test : public beast::unit_test::suite { using Downloads = std::vector<std::pair<std::uint32_t, std::string>>; std::shared_ptr<TrustedPublisherServer> createServer(jtx::Env& env, bool ssl = true) { std::vector<TrustedPublisherServer::Validator> list; list.push_back(TrustedPublisherServer::randomValidator()); return make_TrustedPublisherServer( env.app().getIOService(), list, env.timeKeeper().now() + std::chrono::seconds{3600}, // No future VLs {}, ssl); } public: // Test the shard downloading module by queueing // a download and verifying the contents of the // state database. void testSingleDownloadAndStateDB() { testcase("testSingleDownloadAndStateDB"); beast::temp_dir tempDir; auto c = jtx::envconfig(); auto& section = c->section(ConfigSection::shardDatabase()); section.set("path", tempDir.path()); section.set("max_historical_shards", "20"); c->setupControl(true, true, true); jtx::Env env(*this, std::move(c)); auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT(dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); std::string const rawUrl = "https://foo:443/1.tar.lz4"; parsedURL url; parseUrl(url, rawUrl); handler->add(1, {url, rawUrl}); { std::lock_guard<std::mutex> lock(handler->m_); std::uint64_t rowCount = 0; readArchiveDB( *handler->sqlDB_, [&](std::string const& url, int state) { BEAST_EXPECT(state == 1); BEAST_EXPECT(url == rawUrl); ++rowCount; }); BEAST_EXPECT(rowCount == 1); } handler->release(); } // Test the shard downloading module by queueing // three downloads and verifying the contents of // the state database. void testDownloadsAndStateDB() { testcase("testDownloadsAndStateDB"); beast::temp_dir tempDir; auto c = jtx::envconfig(); auto& section = c->section(ConfigSection::shardDatabase()); section.set("path", tempDir.path()); section.set("max_historical_shards", "20"); c->setupControl(true, true, true); jtx::Env env(*this, std::move(c)); auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT(dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); Downloads const dl = { {1, "https://foo:443/1.tar.lz4"}, {2, "https://foo:443/2.tar.lz4"}, {3, "https://foo:443/3.tar.lz4"}}; for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } { std::lock_guard<std::mutex> lock(handler->m_); std::uint64_t pos = 0; readArchiveDB( *handler->sqlDB_, [&](std::string const& url, int state) { BEAST_EXPECT(state == dl[pos].first); BEAST_EXPECT(url == dl[pos].second); ++pos; }); BEAST_EXPECT(pos == dl.size()); } handler->release(); } // Test the shard downloading module by initiating // and completing ten downloads and verifying the // contents of the filesystem and the handler's // archives. void testDownloadsAndFileSystem() { testcase("testDownloadsAndFileSystem"); beast::temp_dir tempDir; auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "20"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); jtx::Env env(*this, std::move(c)); std::uint8_t const numberOfDownloads = 10; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * (numberOfDownloads + 1); ++i) { env.close(); } auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT(dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); auto server = createServer(env); auto host = server->local_endpoint().address().to_string(); auto port = std::to_string(server->local_endpoint().port()); server->stop(); Downloads const dl = [count = numberOfDownloads, &host, &port] { Downloads ret; for (int i = 1; i <= count; ++i) { ret.push_back( {i, (boost::format("https://%s:%d/%d.tar.lz4") % host % port % i) .str()}); } return ret; }(); for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } BEAST_EXPECT(handler->start()); auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory(env.app().config()); std::unique_lock<std::mutex> lock(handler->m_); BEAST_EXPECT( boost::filesystem::exists(stateDir) || handler->archives_.empty()); using namespace std::chrono_literals; auto waitMax = 60s; while (!handler->archives_.empty()) { lock.unlock(); std::this_thread::sleep_for(1s); if (waitMax -= 1s; waitMax <= 0s) { BEAST_EXPECT(false); break; } lock.lock(); } BEAST_EXPECT(!boost::filesystem::exists(stateDir)); } // Test the shard downloading module by initiating // and completing ten downloads and verifying the // contents of the filesystem and the handler's // archives. Then restart the application and ensure // that the handler is created and started automatically. void testDownloadsAndRestart() { testcase("testDownloadsAndRestart"); beast::temp_dir tempDir; { auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "20"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); jtx::Env env(*this, std::move(c)); std::uint8_t const numberOfDownloads = 10; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * (numberOfDownloads + 1); ++i) { env.close(); } auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT( dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); auto server = createServer(env); auto host = server->local_endpoint().address().to_string(); auto port = std::to_string(server->local_endpoint().port()); server->stop(); Downloads const dl = [count = numberOfDownloads, &host, &port] { Downloads ret; for (int i = 1; i <= count; ++i) { ret.push_back( {i, (boost::format("https://%s:%d/%d.tar.lz4") % host % port % i) .str()}); } return ret; }(); for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory( env.app().config()); boost::filesystem::copy_file( stateDir / stateDBName, boost::filesystem::path(tempDir.path()) / stateDBName); BEAST_EXPECT(handler->start()); std::unique_lock<std::mutex> lock(handler->m_); BEAST_EXPECT( boost::filesystem::exists(stateDir) || handler->archives_.empty()); using namespace std::chrono_literals; auto waitMax = 60s; while (!handler->archives_.empty()) { lock.unlock(); std::this_thread::sleep_for(1s); if (waitMax -= 1s; waitMax <= 0s) { BEAST_EXPECT(false); break; } lock.lock(); } BEAST_EXPECT(!boost::filesystem::exists(stateDir)); boost::filesystem::create_directory(stateDir); boost::filesystem::copy_file( boost::filesystem::path(tempDir.path()) / stateDBName, stateDir / stateDBName); } auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "20"); section.set("shard_verification_retry_interval", "1"); section.set("shard_verification_max_attempts", "10000"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); jtx::Env env(*this, std::move(c)); std::uint8_t const numberOfDownloads = 10; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * (numberOfDownloads + 1); ++i) { env.close(); } auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(dynamic_cast<RPC::RecoveryHandler*>(handler) != nullptr); auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory(env.app().config()); std::unique_lock<std::mutex> lock(handler->m_); BEAST_EXPECT( boost::filesystem::exists(stateDir) || handler->archives_.empty()); using namespace std::chrono_literals; auto waitMax = 60s; while (!handler->archives_.empty()) { lock.unlock(); std::this_thread::sleep_for(1s); if (waitMax -= 1s; waitMax <= 0s) { BEAST_EXPECT(false); break; } lock.lock(); } BEAST_EXPECT(!boost::filesystem::exists(stateDir)); } // Ensure that downloads fail when the shard // database cannot store any more shards void testShardCountFailure() { testcase("testShardCountFailure"); std::string capturedLogs; { beast::temp_dir tempDir; auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "1"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); std::unique_ptr<Logs> logs(new CaptureLogs(&capturedLogs)); jtx::Env env(*this, std::move(c), std::move(logs)); std::uint8_t const numberOfDownloads = 10; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * (numberOfDownloads + 1); ++i) { env.close(); } auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT( dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); auto server = createServer(env); auto host = server->local_endpoint().address().to_string(); auto port = std::to_string(server->local_endpoint().port()); server->stop(); Downloads const dl = [count = numberOfDownloads, &host, &port] { Downloads ret; for (int i = 1; i <= count; ++i) { ret.push_back( {i, (boost::format("https://%s:%d/%d.tar.lz4") % host % port % i) .str()}); } return ret; }(); for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } BEAST_EXPECT(!handler->start()); auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory( env.app().config()); handler->release(); BEAST_EXPECT(!boost::filesystem::exists(stateDir)); } auto const expectedErrorMessage = "shards 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 maximum number of historical " "shards reached"; BEAST_EXPECT( capturedLogs.find(expectedErrorMessage) != std::string::npos); { beast::temp_dir tempDir; auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "0"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); std::unique_ptr<Logs> logs(new CaptureLogs(&capturedLogs)); jtx::Env env(*this, std::move(c), std::move(logs)); std::uint8_t const numberOfDownloads = 1; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * ((numberOfDownloads * 3) + 1); ++i) { env.close(); } auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT( dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); auto server = createServer(env); auto host = server->local_endpoint().address().to_string(); auto port = std::to_string(server->local_endpoint().port()); server->stop(); Downloads const dl = [count = numberOfDownloads, &host, &port] { Downloads ret; for (int i = 1; i <= count; ++i) { ret.push_back( {i, (boost::format("https://%s:%d/%d.tar.lz4") % host % port % i) .str()}); } return ret; }(); for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } BEAST_EXPECT(!handler->start()); auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory( env.app().config()); handler->release(); BEAST_EXPECT(!boost::filesystem::exists(stateDir)); } auto const expectedErrorMessage2 = "shard 1 maximum number of historical shards reached"; BEAST_EXPECT( capturedLogs.find(expectedErrorMessage2) != std::string::npos); } // Ensure that downloads fail when the shard // database has already stored one of the // queued shards void testRedundantShardFailure() { testcase("testRedundantShardFailure"); std::string capturedLogs; { beast::temp_dir tempDir; auto c = jtx::envconfig(); { auto& section{c->section(ConfigSection::shardDatabase())}; section.set("path", tempDir.path()); section.set("max_historical_shards", "1"); section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } { auto& section{c->section(ConfigSection::nodeDatabase())}; section.set("ledgers_per_shard", "256"); section.set("earliest_seq", "257"); } c->setupControl(true, true, true); std::unique_ptr<Logs> logs(new CaptureLogs(&capturedLogs)); jtx::Env env( *this, std::move(c), std::move(logs), beast::severities::kDebug); std::uint8_t const numberOfDownloads = 10; // Create some ledgers so that the ShardArchiveHandler // can verify the last ledger hash for the shard // downloads. for (int i = 0; i < env.app().getShardStore()->ledgersPerShard() * (numberOfDownloads + 1); ++i) { env.close(); } BEAST_EXPECT(env.app().getShardStore()->prepareShards({1})); auto handler = env.app().getShardArchiveHandler(); BEAST_EXPECT(handler); BEAST_EXPECT( dynamic_cast<RPC::RecoveryHandler*>(handler) == nullptr); auto server = createServer(env); auto host = server->local_endpoint().address().to_string(); auto port = std::to_string(server->local_endpoint().port()); server->stop(); Downloads const dl = [count = numberOfDownloads, &host, &port] { Downloads ret; for (int i = 1; i <= count; ++i) { ret.push_back( {i, (boost::format("https://%s:%d/%d.tar.lz4") % host % port % i) .str()}); } return ret; }(); for (auto const& entry : dl) { parsedURL url; parseUrl(url, entry.second); handler->add(entry.first, {url, entry.second}); } BEAST_EXPECT(!handler->start()); auto stateDir = RPC::ShardArchiveHandler::getDownloadDirectory( env.app().config()); handler->release(); BEAST_EXPECT(!boost::filesystem::exists(stateDir)); } auto const expectedErrorMessage = "shard 1 is already queued for import"; BEAST_EXPECT( capturedLogs.find(expectedErrorMessage) != std::string::npos); } void run() override { testSingleDownloadAndStateDB(); testDownloadsAndStateDB(); testDownloadsAndFileSystem(); testDownloadsAndRestart(); testShardCountFailure(); testRedundantShardFailure(); } }; BEAST_DEFINE_TESTSUITE_PRIO(ShardArchiveHandler, app, ripple, 3); } // namespace test } // namespace ripple
33.038407
80
0.519504
[ "vector" ]
2967c09b11e495c50a09593f14fcfa42f730e37b
12,644
cpp
C++
src/herder/test/QuorumTrackerTests.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
10
2017-09-23T08:25:40.000Z
2022-01-04T10:28:02.000Z
src/herder/test/QuorumTrackerTests.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2021-11-10T00:25:10.000Z
2021-11-10T02:50:40.000Z
src/herder/test/QuorumTrackerTests.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
2
2021-10-21T20:34:04.000Z
2021-11-21T14:13:54.000Z
// Copyright 2019 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "herder/HerderImpl.h" #include "herder/QuorumTracker.h" #include "lib/catch.hpp" #include "main/Application.h" #include "main/Config.h" #include "scp/SCP.h" #include "test/TestUtils.h" #include "test/test.h" #include "xdr/Stellar-ledger.h" using namespace stellar; void testQuorumTracker() { Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE)); cfg.MANUAL_CLOSE = false; std::vector<SecretKey> otherKeys; int const kKeysCount = 7; for (int i = 0; i < kKeysCount; i++) { otherKeys.emplace_back(SecretKey::pseudoRandomForTesting()); } auto buildQSet = [&](int i) { SCPQuorumSet q; q.threshold = 2; q.validators.emplace_back(otherKeys[i].getPublicKey()); q.validators.emplace_back(otherKeys[i + 1].getPublicKey()); return q; }; cfg.QUORUM_SET = buildQSet(0); auto qSet0 = buildQSet(2); auto qSet0b = buildQSet(4); auto qSet2 = buildQSet(5); qSet2.threshold++; qSet2.validators.emplace_back(cfg.NODE_SEED.getPublicKey()); auto clock = std::make_shared<VirtualClock>(); Application::pointer app = createTestApplication(*clock, cfg); auto* herder = static_cast<HerderImpl*>(&app->getHerder()); auto* penEnvs = &herder->getPendingEnvelopes(); // allow SCP messages from other slots to be processed herder->lostSync(); auto valSigner = SecretKey::pseudoRandomForTesting(); struct ValuesTxSet { Value mSignedV; TxSetFramePtr mTxSet; }; auto recvEnvelope = [&](SCPEnvelope envelope, uint64 slotID, SecretKey const& k, SCPQuorumSet const& qSet, std::vector<ValuesTxSet> const& pp) { // herder must want the TxSet before receiving it, so we are sending it // fake envelope envelope.statement.slotIndex = slotID; auto qSetH = sha256(xdr::xdr_to_opaque(qSet)); envelope.statement.nodeID = k.getPublicKey(); envelope.signature = k.sign(xdr::xdr_to_opaque( app->getNetworkID(), ENVELOPE_TYPE_SCP, envelope.statement)); herder->recvSCPEnvelope(envelope); herder->recvSCPQuorumSet(qSetH, qSet); for (auto& p : pp) { herder->recvTxSet(p.mTxSet->getContentsHash(), *p.mTxSet); } }; auto recvNom = [&](uint64 slotID, SecretKey const& k, SCPQuorumSet const& qSet, std::vector<ValuesTxSet> const& pp) { SCPEnvelope envelope; envelope.statement.pledges.type(SCP_ST_NOMINATE); auto& nom = envelope.statement.pledges.nominate(); std::set<Value> values; for (auto& p : pp) { values.insert(p.mSignedV); } nom.votes.insert(nom.votes.begin(), values.begin(), values.end()); auto qSetH = sha256(xdr::xdr_to_opaque(qSet)); nom.quorumSetHash = qSetH; recvEnvelope(envelope, slotID, k, qSet, pp); }; auto recvExternalize = [&](uint64 slotID, SecretKey const& k, SCPQuorumSet const& qSet, ValuesTxSet const& v) { SCPEnvelope envelope; envelope.statement.pledges.type(SCP_ST_EXTERNALIZE); auto& ext = envelope.statement.pledges.externalize(); ext.commit.counter = UINT32_MAX; ext.commit.value = v.mSignedV; ext.nH = UINT32_MAX; auto qSetH = sha256(xdr::xdr_to_opaque(qSet)); ext.commitQuorumSetHash = qSetH; std::vector<ValuesTxSet> pp = {v}; recvEnvelope(envelope, slotID, k, qSet, pp); }; auto makeValue = [&](int i) { auto const& lcl = app->getLedgerManager().getLastClosedLedgerHeader(); auto txSet = std::make_shared<TxSetFrame>(lcl.hash); StellarValue sv = herder->makeStellarValue( txSet->getContentsHash(), lcl.header.scpValue.closeTime + i, emptyUpgradeSteps, valSigner); auto v = xdr::xdr_to_opaque(sv); return ValuesTxSet{v, txSet}; }; auto vv = makeValue(1); auto checkInQuorum = [&](std::set<int> ids) { REQUIRE( penEnvs->isNodeDefinitelyInQuorum(cfg.NODE_SEED.getPublicKey())); for (int j = 0; j < kKeysCount; j++) { bool inQuorum = (ids.find(j) != ids.end()); REQUIRE(penEnvs->isNodeDefinitelyInQuorum( otherKeys[j].getPublicKey()) == inQuorum); } }; SECTION("Receive self") { checkInQuorum({0, 1}); recvNom(3, cfg.NODE_SEED, cfg.QUORUM_SET, {vv}); checkInQuorum({0, 1}); } SECTION("Expand 0") { checkInQuorum({0, 1}); recvNom(3, otherKeys[0], qSet0, {vv}); checkInQuorum({0, 1, 2, 3}); SECTION("Expand 2") { recvNom(3, otherKeys[2], qSet2, {vv}); checkInQuorum({0, 1, 2, 3, 5, 6}); SECTION("node restart") { // externalize -> we persist quorum information recvExternalize(3, otherKeys[0], qSet0, vv); // use qSet0 for node1 recvExternalize(3, otherKeys[1], qSet0, vv); checkInQuorum({0, 1, 2, 3, 5, 6}); app.reset(); clock.reset(); clock = std::make_shared<VirtualClock>(); app = Application::create(*clock, cfg, false); app->start(); herder = static_cast<HerderImpl*>(&app->getHerder()); penEnvs = &herder->getPendingEnvelopes(); checkInQuorum({0, 1, 2, 3, 5, 6}); } } SECTION("Update 0's qSet") { auto vv2 = makeValue(2); recvNom(3, otherKeys[0], qSet0b, {vv, vv2}); checkInQuorum({0, 1, 4, 5}); } SECTION("Update 0's qSet in an old slot") { auto vv2 = makeValue(2); recvNom(2, otherKeys[0], qSet0b, {vv, vv2}); // nothing changes (slot 3 has precedence) checkInQuorum({0, 1, 2, 3}); } } } TEST_CASE("quorum tracker", "[quorum][herder]") { testQuorumTracker(); } TEST_CASE("quorum tracker closest validators", "[quorum][herder]") { Config cfg(getTestConfig(0, Config::TESTDB_IN_MEMORY_SQLITE)); std::vector<PublicKey> otherKeys; int const kKeysCount = 7; otherKeys.push_back(cfg.NODE_SEED.getPublicKey()); int self = 0; for (int i = self + 1; i < kKeysCount; i++) { otherKeys.emplace_back( SecretKey::pseudoRandomForTesting().getPublicKey()); } auto makeQset = [&](std::vector<int> const& validatorIndexes, int selfIndex) { SCPQuorumSet q; q.threshold = static_cast<uint32>(validatorIndexes.size()) + 1; std::transform(validatorIndexes.begin(), validatorIndexes.end(), std::back_inserter(q.validators), [&](int i) { return otherKeys[i]; }); q.validators.push_back(otherKeys[self]); return std::make_shared<SCPQuorumSet>(q); }; auto selfQSet = makeQset({2, 1}, self); cfg.QUORUM_SET = *selfQSet; auto clock = std::make_shared<VirtualClock>(); Application::pointer app = createTestApplication(*clock, cfg); auto* herder = static_cast<HerderImpl*>(&app->getHerder()); auto const localNodeID = herder->getSCP().getLocalNodeID(); QuorumTracker qt(localNodeID); auto lookup = [&](NodeID const& node) -> SCPQuorumSetPtr { if (node == localNodeID) { return selfQSet; } auto it = std::find(otherKeys.begin(), otherKeys.end(), node); auto idx = std::distance(otherKeys.begin(), it); switch (idx) { case 0: return selfQSet; case 1: return makeQset({self, 2, 4, 5}, 1); case 2: return makeQset({self, 1, 5}, 2); case 5: return makeQset({1, 3, 4}, 5); case 4: return makeQset({2}, 4); case 3: case 6: return std::make_shared<SCPQuorumSet>(); default: abort(); } }; auto checkRes = [&](NodeID const& key, std::set<NodeID> const& otherKeys, bool notFound = false) { auto hasValidators = qt.isNodeDefinitelyInQuorum(key); if (notFound) { REQUIRE(!hasValidators); } else { REQUIRE(hasValidators); REQUIRE(otherKeys == qt.findClosestValidators(key)); } }; auto validateRebuildResult = [&]() { checkRes(otherKeys[1], std::set<NodeID>{otherKeys[1]}); checkRes(otherKeys[2], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[3], std::set<NodeID>{otherKeys[1], otherKeys[2]}); checkRes(otherKeys[4], std::set<NodeID>{otherKeys[1]}); checkRes(otherKeys[5], std::set<NodeID>{otherKeys[1], otherKeys[2]}); // No path for node 6 checkRes(otherKeys[6], {}, true); }; // Rebuilding quorum map from scratch yields optimal distances SECTION("rebuild") { qt.rebuild(lookup); validateRebuildResult(); } // Incrementally expand quorum map: depending on the order of expansion, // intermediate "closest validators" might be suboptimal. // If finished successfully, result must be identical to // rebuilding from scratch (thus yielding optimal distances) SECTION("expand") { // Rebuild only knowing about "self" qt.rebuild([&](NodeID const& node) -> SCPQuorumSetPtr { if (node == cfg.NODE_SEED.getPublicKey()) { return selfQSet; } else { return nullptr; } }); checkRes(otherKeys[1], std::set<NodeID>{otherKeys[1]}); checkRes(otherKeys[2], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[3], {}, true); checkRes(otherKeys[4], {}, true); checkRes(otherKeys[5], {}, true); checkRes(otherKeys[6], {}, true); SECTION("cannot expand some") { // Now expand qSets for 2 and 5 REQUIRE(qt.expand(otherKeys[2], lookup(otherKeys[2]))); REQUIRE(qt.expand(otherKeys[5], lookup(otherKeys[5]))); // Distances are not optimal yet because some parts of // the quorum are unknown checkRes(otherKeys[1], std::set<NodeID>{otherKeys[1]}); checkRes(otherKeys[2], std::set<NodeID>{otherKeys[2]}); // "2" is associated with "3" (shortest path not discovered yet) checkRes(otherKeys[3], std::set<NodeID>{otherKeys[2]}); // "2" is associated with "4" (shortest path not discovered yet) checkRes(otherKeys[4], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[5], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[6], {}, true); // Now learn about more qSets, but `expand` should return false // because closest validators for 3 could not be updated REQUIRE_FALSE(qt.expand(otherKeys[1], lookup(otherKeys[1]))); checkRes(otherKeys[1], std::set<NodeID>{otherKeys[1]}); checkRes(otherKeys[2], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[4], std::set<NodeID>{otherKeys[1]}); // 5, 3 failed to update checkRes(otherKeys[3], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[5], std::set<NodeID>{otherKeys[2]}); checkRes(otherKeys[6], {}, true); // Ensure rebuild runs correctly after `expand` attempts qt.rebuild(lookup); validateRebuildResult(); } SECTION("expand success") { // Even though distances are not expanded by shortest distance, // still arrive at the same result as rebuild // "0" and "4" are expanded first REQUIRE(qt.expand(otherKeys[1], lookup(otherKeys[1]))); REQUIRE(qt.expand(otherKeys[4], lookup(otherKeys[4]))); // "1" and "5" are expanded next, success REQUIRE(qt.expand(otherKeys[2], lookup(otherKeys[2]))); REQUIRE(qt.expand(otherKeys[5], lookup(otherKeys[5]))); validateRebuildResult(); } } }
35.616901
80
0.573711
[ "vector", "transform" ]
2969215598f7265409b2898631ff9852a41adef9
48,540
cpp
C++
src/renderer.cpp
carol-dcf/GTR_Framework
065b1060de3c0c48ebb23124ba3183cab5c8b6dc
[ "MIT" ]
null
null
null
src/renderer.cpp
carol-dcf/GTR_Framework
065b1060de3c0c48ebb23124ba3183cab5c8b6dc
[ "MIT" ]
null
null
null
src/renderer.cpp
carol-dcf/GTR_Framework
065b1060de3c0c48ebb23124ba3183cab5c8b6dc
[ "MIT" ]
null
null
null
#include "renderer.h" #include "camera.h" #include "shader.h" #include "mesh.h" #include "texture.h" #include "prefab.h" #include "material.h" #include "utils.h" #include "scene.h" #include "extra/hdre.h" #include <algorithm> // std::sort #include "application.h" using namespace GTR; Vector3 degamma(Vector3 color) { Vector3 g_color; g_color.x = pow(color.x, 2.2); g_color.y = pow(color.y, 2.2); g_color.z = pow(color.z, 2.2); return g_color; } GTR::RenderCall::RenderCall() {} GTR::Renderer::Renderer() { float w = Application::instance->window_width; float h = Application::instance->window_height; render_mode = GTR::eRenderMode::DEFAULT; pipeline_mode = GTR::ePipelineMode::FORWARD; gbuffers_fbo = FBO(); gbuffers_fbo.create(w, h, 3, GL_RGBA, GL_UNSIGNED_BYTE, true); dithering = true; ssao_fbo = FBO(); ssao_fbo.create(w, h, 1, GL_RGB); ssao_blur = FBO(); ssao_blur.create(w, h); blur_ssao = true; illumination_fbo = FBO(); illumination_fbo.create(w, h, 1, GL_RGB, GL_FLOAT, false); hdr = true; random_points = generateSpherePoints(64, 1.0, true); irr_fbo = FBO(); irr_fbo.create(64, 64, 1, GL_RGB, GL_FLOAT); show_probe = false; irr_normal_distance = 10.0; reflections_fbo = FBO(); reflections_fbo.create(64, 64, 1, GL_RGB, GL_FLOAT); show_ref_probes = false; show_volumetric = true; decals_fbo = FBO(); decals_fbo.create(w, h, 3, GL_RGBA, GL_UNSIGNED_BYTE, true); dof_fbo = FBO(); dof_fbo.create(w, h, 3, GL_RGBA, GL_UNSIGNED_BYTE, true); show_dof = true; focus_plane = 0.05; aperture = 4.0; downsample_fbo = FBO(); downsample_fbo.create(w, h, 3, GL_RGBA, GL_FLOAT, true); upsample_tex1 = new Texture(w, h, GL_RGBA, GL_FLOAT); upsample_tex2 = new Texture(w, h, GL_RGBA, GL_FLOAT); show_glow = false; glow_factor = 2.0; postpo_fbo = FBO(); postpo_fbo.create(w, h, 1, GL_RGBA, GL_FLOAT, true); show_chroma = false; chroma_amount = 0.002; show_lens = false; } void Renderer::initReflectionProbe(Scene* scene) { std::cout << " - Creating reflection grid" << std::endl; reflection_probes.clear(); //create the probe sReflectionProbe* probe = new sReflectionProbe; //set it up probe->pos = Vector3(0, 10, 20); probe->cubemap = new Texture(); probe->cubemap->createCubemap(512, 512, NULL, GL_RGB, GL_UNSIGNED_INT, false); //add it to the list reflection_probes.push_back(probe); captureCubemaps(scene); } void Renderer::captureCubemaps(Scene* scene) { //for every reflection probe... //define camera with fov 90 Camera cam; cam.setPerspective(90, 1, 0.1, 1000); int num = reflection_probes.size(); //now compute the coeffs for every probe for (int iP = 0; iP < num; ++iP) { int probe_index = iP; sReflectionProbe probe = *reflection_probes[iP]; //render the view from every side for (int i = 0; i < 6; ++i) { //assign cubemap face to FBO reflections_fbo.setTexture(probe.cubemap, i); //bind FBO reflections_fbo.bind(); //render view Vector3 eye = probe.pos; Vector3 center = probe.pos + cubemapFaceNormals[i][2]; Vector3 up = cubemapFaceNormals[i][1]; cam.lookAt(eye, center, up); cam.enable(); renderSceneForward(scene, &cam); reflections_fbo.unbind(); } //generate the mipmaps probe.cubemap->generateMipmaps(); } } void Renderer::renderSkyBox(Texture* environment, Camera* camera) { Mesh* sphere = Mesh::Get("data/meshes/sphere.obj", false); Shader* s = Shader::Get("skybox"); s->enable(); Matrix44 m; m.translate(camera->eye.x, camera->eye.y , camera->eye.z); m.scale(10.0, 10.0, 10.0); s->setUniform("u_model", m); s->setUniform("u_viewprojection", camera->viewprojection_matrix); s->setUniform("u_camera_eye", camera->eye); s->setTexture("u_texture", environment, 0); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); sphere->render(GL_TRIANGLES); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); s->disable(); } void Renderer::renderProbe(Vector3 pos, float size, float* coeffs) { Camera* camera = Camera::current; Shader* shader = Shader::Get("probe"); Mesh* mesh = Mesh::Get("data/meshes/sphere.obj", false); glEnable(GL_CULL_FACE); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); Matrix44 model; model.setTranslation(pos.x, pos.y, pos.z); model.scale(size, size, size); shader->enable(); shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_camera_position", camera->eye); shader->setUniform("u_model", model); shader->setUniform3Array("u_coeffs", coeffs, 9); mesh->render(GL_TRIANGLES); } void Renderer::renderReflectionProbe(Vector3 pos, Texture* cubemap, float size) { Camera* camera = Camera::current; Shader* shader = Shader::Get("ref_probe"); Mesh* mesh = Mesh::Get("data/meshes/sphere.obj", false); glEnable(GL_CULL_FACE); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); Matrix44 model; model.setTranslation(pos.x, pos.y, pos.z); model.scale(size, size, size); shader->enable(); shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_camera_position", camera->eye); shader->setUniform("u_model", model); shader->setUniform("u_reflection_texture", cubemap, 1); mesh->render(GL_TRIANGLES); } void Renderer::updateIrradianceCache(Scene* scene) { std::cout << " - Updating Irradiance Cache" << std::endl; computeProbeCoefficients(scene); uploadProbes(); } void Renderer::defineGrid(Scene* scene) { std::cout << " - Creating irradiance grid" << std::endl; //define the corners of the axis aligned grid //compute the vector from one corner to the other delta = (end_pos - start_pos); //and scale it down according to the subdivisions //we substract one to be sure the last probe is at end pos delta.x /= (dim.x - 1); delta.y /= (dim.y - 1); delta.z /= (dim.z - 1); probes.clear(); //lets compute the centers //pay attention at the order at which we add them for (int z = 0; z < dim.z; ++z) for (int y = 0; y < dim.y; ++y) for (int x = 0; x < dim.x; ++x) { sProbe p; p.local.set(x, y, z); //index in the linear array p.index = x + y * dim.x + z * dim.x * dim.y; //and its position p.pos = start_pos + delta * Vector3(x, y, z); probes.push_back(p); } probes_texture = new Texture(9, probes.size(), GL_RGB, GL_FLOAT); computeProbeCoefficients(scene); uploadProbes(); } void Renderer::computeProbeCoefficients(Scene* scene) { FloatImage images[6]; //here we will store the six views //set the fov to 90 and the aspect to 1 Camera cam; cam.setPerspective(90, 1, 0.1, 1000); int num = probes.size(); //now compute the coeffs for every probe for (int iP = 0; iP < num; ++iP) { int probe_index = iP; sProbe* p = &probes[iP]; for (int i = 0; i < 6; ++i) //for every cubemap face { //compute camera orientation using defined vectors Vector3 eye = p->pos; Vector3 front = cubemapFaceNormals[i][2]; Vector3 center = p->pos + front; Vector3 up = cubemapFaceNormals[i][1]; cam.lookAt(eye, center, up); cam.enable(); //render the scene from this point of view irr_fbo.bind(); GTR::eRenderMode aux_render_mode = render_mode; render_mode = GTR::eRenderMode::DEFAULT; renderSceneForward(scene, &cam); render_mode = aux_render_mode; irr_fbo.unbind(); //read the pixels back and store in a FloatImage images[i].fromTexture(irr_fbo.color_textures[0]); } //compute the coefficients given the six images p->sh = computeSH(images); } } void Renderer::uploadProbes() { SphericalHarmonics* sh_data = NULL; sh_data = new SphericalHarmonics[dim.x * dim.y * dim.z]; // fill data sProbe p; int index; for (int z = 0; z < dim.z; ++z) for (int y = 0; y < dim.y; ++y) for (int x = 0; x < dim.x; ++x) { index = x + y * dim.x + z * dim.x * dim.y; p = probes[index]; sh_data[index] = p.sh; } //now upload the data to the GPU probes_texture->upload(GL_RGB, GL_FLOAT, false, (uint8*)sh_data); //disable any texture filtering when reading probes_texture->bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //always free memory after allocating it!!! delete[] sh_data; } void GTR::Renderer::addRenderCall(RenderCall renderCall) { renderCalls.push_back(renderCall); } RenderCall GTR::Renderer::createRenderCall(Matrix44 model, Mesh* mesh, Material* material, float distance_to_camera) { RenderCall renderCall = GTR::RenderCall(); renderCall.material = material; renderCall.mesh = mesh; renderCall.model = model; renderCall.distance_to_camera = distance_to_camera; return renderCall; } void GTR::Renderer::collectRCsandLights(GTR::Scene* scene, Camera* camera) { renderCalls.clear(); scene->l_entities.clear(); //collect entities for (int i = 0; i < scene->entities.size(); ++i) { BaseEntity* ent = scene->entities[i]; if (!ent->visible) continue; //is a prefab! if (ent->entity_type == PREFAB) { PrefabEntity* pent = (GTR::PrefabEntity*)ent; if (pent->prefab) renderPrefab(ent->model, pent->prefab, camera); } //is a light if (ent->entity_type == LIGHT) { float aspect = Application::instance->window_width / (float)Application::instance->window_height; LightEntity* lent = (GTR::LightEntity*)ent; //BoundingBox light_bbox = BoundingBox(lent->model.getTranslation(), Vector3(lent->max_distance, lent->max_distance, lent->max_distance)); //BoundingBox world_bounding = transformBoundingBox(lent->model, light_bbox); //if bounding box is inside the camera frustum then the object is probably visible //if (camera->testBoxInFrustum(world_bounding.center, world_bounding.halfsize)) { scene->l_entities.push_back(lent); if (lent->light_type == SPOT) // SPOT LIGHT CAMERA { Vector3 eye = lent->model.getTranslation(); // camera position Vector3 center = lent->model.rotateVector(Vector3(0, 0, 1)); lent->light_camera->lookAt(eye, eye + center, Vector3(0, 1, 0)); lent->light_camera->setPerspective(lent->cone_angle, aspect, 1.0f, lent->max_distance); } else if (lent->light_type == DIRECTIONAL) // DIRECTIONAL LIGHT CAMERA { Camera* light_camera = lent->light_camera; Vector3 eye = lent->model.getTranslation(); // camera position Vector3 center = lent->model.rotateVector(Vector3(0, 0, 1)); light_camera->lookAt(eye, eye + center, Vector3(0, 1, 0)); float a_size = lent->area_size; light_camera->setOrthographic(-a_size, a_size, -a_size / aspect, a_size / aspect, 10, 10000); } } } //std::sort(std::begin(renderCalls), std::end(renderCalls), less_than_alpha()); //std::sort(std::begin(renderCalls), std::end(renderCalls), less_than_depth()); std::sort(std::begin(renderCalls), std::end(renderCalls), sort_alpha_depth()); } void Renderer::renderToFBOForward(GTR::Scene* scene, Camera* camera) { float w = Application::instance->window_width; float h = Application::instance->window_height; // create lights' FBO generateShadowmaps(scene); // show scene glEnable(GL_DEPTH_TEST); glViewport(0, 0, w, h); renderScene(scene, camera); } void Renderer::renderToFBODeferred(GTR::Scene* scene, Camera* camera) { generateShadowmaps(scene); gbuffers_fbo.bind(); gbuffers_fbo.enableSingleBuffer(0); //clear GB0 with the color (and depth) glClearColor(0.1, 0.1, 0.1, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //and now enable the second GB to clear it to black gbuffers_fbo.enableSingleBuffer(1); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); //enable all buffers back gbuffers_fbo.enableAllBuffers(); renderScene(scene, camera); gbuffers_fbo.unbind(); // PING PONG PARA DECALS gbuffers_fbo.color_textures[0]->copyTo(decals_fbo.color_textures[0]); gbuffers_fbo.color_textures[1]->copyTo(decals_fbo.color_textures[1]); gbuffers_fbo.color_textures[2]->copyTo(decals_fbo.color_textures[2]); decals_fbo.bind(); gbuffers_fbo.depth_texture->copyTo(NULL); renderDecals(scene, camera); decals_fbo.unbind(); decals_fbo.color_textures[0]->copyTo(gbuffers_fbo.color_textures[0]); decals_fbo.color_textures[1]->copyTo(gbuffers_fbo.color_textures[1]); decals_fbo.color_textures[2]->copyTo(gbuffers_fbo.color_textures[2]); Shader* shader = Shader::Get("depth"); shader->enable(); shader->setUniform("u_camera_nearfar", Vector2(camera->near_plane, camera->far_plane)); float w = Application::instance->window_width; float h = Application::instance->window_height; if (render_mode == SHOW_GBUFFERS) { glDisable(GL_BLEND); glViewport(0.0f, 0.0f, w / 2, h / 2); gbuffers_fbo.color_textures[0]->toViewport(); glViewport(w / 2, 0.0f, w / 2, h / 2); gbuffers_fbo.color_textures[1]->toViewport(); glViewport(0.0f, h / 2, w / 2, h / 2); gbuffers_fbo.color_textures[2]->toViewport(); glViewport(w / 2, h / 2, w / 2, h / 2); gbuffers_fbo.depth_texture->toViewport(shader); } else if (render_mode == SHOW_SSAO) { generateSSAO(scene, camera); glViewport(0.0f, 0.0f, w, h); ssao_blur.color_textures[0]->toViewport(); } else { // show deferred all together generateSSAO(scene, camera); //start rendering to the illumination fbo illumination_fbo.bind(); //create and FBO glClearColor(0, 0, 0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderSkyBox(scene->environment, camera); if (render_mode == SHOW_IRRADIANCE) showIrradiance(scene, camera); else { // RENDER LIGHTS illuminationDeferred(scene, camera); // REFLECTION showReflection(camera); // VOLUMETRIC if(show_volumetric) showVolumetric(scene, camera); } if (show_probe) { sProbe probe; for (int i = 0; i < probes.size(); i++) { probe = probes[i]; renderProbe(probe.pos, 5.0, probe.sh.coeffs[0].v); } } if (show_ref_probes) { sReflectionProbe* r_probe = reflection_probes[0]; renderReflectionProbe(r_probe->pos, r_probe->cubemap, 10.0); } illumination_fbo.unbind(); // RENDER POSTPROCESSING FX if (render_mode != SHOW_IRRADIANCE) { // DOF if (show_dof) showDoF(scene, camera); // GLOW if (show_glow) showGlow(); // CHROMATIC ABERRATION if (show_chroma) showChromaticAberration(); // LENS DISTORTION if (show_lens) showLensDistortion(); } //be sure blending is not active glDisable(GL_BLEND); Shader* s_final = NULL; if (hdr) s_final = Shader::Get("final"); glViewport(0.0f, 0.0f, w, h); if (render_mode == SHOW_DOWNSAMPLING) { show_glow = true; glDisable(GL_BLEND); glViewport(0.0f, h / 2, w / 2, h / 2); illumination_fbo.color_textures[0]->toViewport(s_final); glViewport(w / 2, h / 2, w / 2, h / 2); downsample_fbo.color_textures[0]->toViewport(s_final); glViewport(0.0f, 0.0f, w / 2, h / 2); downsample_fbo.color_textures[1]->toViewport(s_final); glViewport(w / 2, 0.0f, w / 2, h / 2); downsample_fbo.color_textures[2]->toViewport(s_final); } else illumination_fbo.color_textures[0]->toViewport(s_final); } shader->disable(); glDisable(GL_BLEND); } void Renderer::showLensDistortion() { postpo_fbo.bind(); float w = Application::instance->window_width; float h = Application::instance->window_height; Mesh* quad = Mesh::getQuad(); Shader* s = Shader::Get("lens_dist"); s->enable(); s->setUniform("u_texture", illumination_fbo.color_textures[0], 0); s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_power", lens_power); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); quad->render(GL_TRIANGLES); postpo_fbo.unbind(); postpo_fbo.color_textures[0]->copyTo(illumination_fbo.color_textures[0]); } void Renderer::showChromaticAberration() { postpo_fbo.bind(); float w = Application::instance->window_width; float h = Application::instance->window_height; Mesh* quad = Mesh::getQuad(); Shader* s = Shader::Get("chromatic"); s->enable(); s->setUniform("u_texture", illumination_fbo.color_textures[0], 0); s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_amount", (float)chroma_amount); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); quad->render(GL_TRIANGLES); postpo_fbo.unbind(); postpo_fbo.color_textures[0]->copyTo(illumination_fbo.color_textures[0]); } void Renderer::showGlow() { downsampleGlow(); upsampleGlow(); upsample_tex1->copyTo(illumination_fbo.color_textures[0]); } void Renderer::downsampleGlow() { float w = Application::instance->window_width; float h = Application::instance->window_height; Mesh* quad = Mesh::getQuad(); Shader* s = Shader::Get("blur_down"); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); s->enable(); s->setUniform("u_texture", illumination_fbo.color_textures[0], 0); s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_base", (float)glow_factor); downsample_fbo.bind(); quad->render(GL_TRIANGLES); downsample_fbo.unbind(); s->disable(); } void Renderer::upsampleGlow() { float w = Application::instance->window_width; float h = Application::instance->window_height; Shader* s = Shader::Get("blur_up"); Mesh* quad = Mesh::getQuad(); s->enable(); // first upsampling upsample_fbo = Texture::getGlobalFBO(upsample_tex1); upsample_fbo->bind(); s->setUniform("u_texture", downsample_fbo.color_textures[2], 0); s->setUniform("u_texture_toblend", downsample_fbo.color_textures[1], 1); quad->render(GL_TRIANGLES); upsample_fbo->unbind(); // second upsampling upsample_fbo = Texture::getGlobalFBO(upsample_tex2); upsample_fbo->bind(); s->setUniform("u_texture", upsample_tex1, 0); s->setUniform("u_texture_toblend", downsample_fbo.color_textures[0], 1); quad->render(GL_TRIANGLES); upsample_fbo->unbind(); // third upsampling upsample_fbo = Texture::getGlobalFBO(upsample_tex1); upsample_fbo->bind(); s->setUniform("u_texture", upsample_tex2, 0); s->setUniform("u_texture_toblend", illumination_fbo.color_textures[0], 1); quad->render(GL_TRIANGLES); upsample_fbo->unbind(); } void Renderer::showVolumetric(GTR::Scene* scene, Camera* camera) { Mesh* quad = Mesh::getQuad(); Shader* s = Shader::Get("volumetric"); float w = Application::instance->window_width; float h = Application::instance->window_height; Matrix44 inv_vp = camera->viewprojection_matrix; inv_vp.inverse(); s->enable(); s->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); s->setUniform("u_inverse_viewprojection", inv_vp); s->setUniform("u_near", camera->near_plane); LightEntity* light; for (int i = 0; i < scene->l_entities.size(); ++i) { if (scene->l_entities[i]->name == "moonlight") { light = scene->l_entities[i]; break; } } Matrix44 shadow_proj = light->light_camera->viewprojection_matrix; s->setUniform("u_viewprojection", shadow_proj); Texture* shadowmap = light->shadow_buffer; s->setTexture("shadowmap", shadowmap, 5); s->setUniform("u_bias", light->bias); s->setUniform("u_light_color", light->color); s->setUniform("u_camera_eye", camera->eye); s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); quad->render(GL_TRIANGLES); } void Renderer::showIrradiance(GTR::Scene* scene, Camera* camera) { float w = Application::instance->window_width; float h = Application::instance->window_height; Matrix44 inv_vp = camera->viewprojection_matrix; inv_vp.inverse(); //we need a fullscreen quad Mesh* quad = Mesh::getQuad(); // AMBIENT Shader* s = Shader::Get("show_irradiance"); s->enable(); s->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); s->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); s->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); s->setUniform("u_probes_texture", probes_texture, 6); //pass the inverse projection of the camera to reconstruct world pos. s->setUniform("u_inverse_viewprojection", inv_vp); //pass the inverse window resolution, this may be useful s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_irr_end", end_pos); s->setUniform("u_irr_start", start_pos); s->setUniform("u_irr_normal_distance", irr_normal_distance); s->setUniform("u_irr_delta", delta); s->setUniform("u_irr_dims", dim); s->setUniform("u_num_probes", (float)probes.size()); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); quad->render(GL_TRIANGLES); s->disable(); glEnable(GL_BLEND); } void GTR::Renderer::showDoF(GTR::Scene* scene, Camera* camera) { float w = Application::instance->window_width; float h = Application::instance->window_height; dof_fbo.bind(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); Mesh* quad = Mesh::getQuad(); Shader* shader = Shader::Get("dof"); shader->enable(); shader->setTexture("u_texture", illumination_fbo.color_textures[0], 0); shader->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); shader->setUniform("u_size", (float)20.0); shader->setUniform("u_aperture", (float)aperture); float f = 1.0f / tan(camera->fov * float(DEG2RAD) * 0.5f); shader->setUniform("u_focal_length", f); shader->setUniform("u_plane", (float)focus_plane); shader->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 1); shader->setUniform("u_camera_nearfar", Vector2(camera->near_plane, camera->far_plane)); quad->render(GL_TRIANGLES); shader->disable(); dof_fbo.unbind(); dof_fbo.color_textures[0]->copyTo(illumination_fbo.color_textures[0]); } void Renderer::illuminationDeferred(GTR::Scene* scene, Camera* camera) { float w = Application::instance->window_width; float h = Application::instance->window_height; Matrix44 inv_vp = camera->viewprojection_matrix; inv_vp.inverse(); //we need a fullscreen quad Mesh* quad = Mesh::getQuad(); // AMBIENT Shader* s = Shader::Get("deferred"); s->enable(); s->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); s->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); s->setUniform("u_extra_texture", gbuffers_fbo.color_textures[2], 2); s->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); s->setUniform("u_ao_texture", ssao_blur.color_textures[0], 4); s->setUniform("u_probes_texture", probes_texture, 6); //pass the inverse projection of the camera to reconstruct world pos. s->setUniform("u_inverse_viewprojection", inv_vp); //pass the inverse window resolution, this may be useful s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_irr_end", end_pos); s->setUniform("u_irr_start", start_pos); s->setUniform("u_irr_normal_distance", irr_normal_distance); s->setUniform("u_irr_delta", delta); s->setUniform("u_irr_dims", dim); s->setUniform("u_num_probes", (float)probes.size()); s->setUniform("u_first_pass", true); s->setUniform("u_ambient_light", scene->ambient_light); s->setUniform("u_viewprojection", camera->viewprojection_matrix); s->setUniform("u_hdr", hdr); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); quad->render(GL_TRIANGLES); s->disable(); Mesh* sphere = Mesh::Get("data/meshes/sphere.obj", false); Shader* sh = Shader::Get("deferred_ws"); sh->enable(); //pass the gbuffers to the shader sh->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); sh->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); sh->setUniform("u_extra_texture", gbuffers_fbo.color_textures[2], 2); sh->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); sh->setUniform("u_ao_texture", ssao_blur.color_textures[0], 4); sh->setUniform("u_probes_texture", probes_texture, 6); sh->setUniform("u_first_pass", false); //pass the inverse projection of the camera to reconstruct world pos. sh->setUniform("u_inverse_viewprojection", inv_vp); //pass the inverse window resolution, this may be useful sh->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); //scene->ambient_light sh->setUniform("u_ambient_light", Vector3(0, 0, 0)); sh->setUniform("u_viewprojection", camera->viewprojection_matrix); sh->setUniform("u_camera_eye", camera->eye); sh->setUniform("u_hdr", hdr); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glFrontFace(GL_CW); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); std::vector<LightEntity*> directionals; for (int i = 0; i < scene->l_entities.size(); ++i) { LightEntity* lent = scene->l_entities[i]; if (!lent->visible) continue; lent->setUniforms(sh); if (lent->light_type == POINT || lent->light_type == SPOT) { Matrix44 m; m.setTranslation(lent->model.getTranslation().x, lent->model.getTranslation().y, lent->model.getTranslation().z); m.scale(lent->max_distance, lent->max_distance, lent->max_distance); //and scale it according to the max_distance of the light sh->setUniform("u_model", m); //pass the model to the shader to render the sphere sphere->render(GL_TRIANGLES); } else if (lent->light_type == DIRECTIONAL) { directionals.push_back(lent); } } // DIRECTIONAL glDisable(GL_CULL_FACE); glFrontFace(GL_CCW); glDisable(GL_DEPTH_TEST); s->enable(); for (int i = 0; i < directionals.size(); ++i) { LightEntity* lent = directionals[i]; if (!lent->visible) continue; lent->setUniforms(s); s->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); s->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); s->setUniform("u_extra_texture", gbuffers_fbo.color_textures[2], 2); s->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); s->setUniform("u_ao_texture", ssao_blur.color_textures[0], 4); s->setUniform("u_probes_texture", probes_texture, 6); //pass the inverse projection of the camera to reconstruct world pos. s->setUniform("u_inverse_viewprojection", inv_vp); //pass the inverse window resolution, this may be useful s->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s->setUniform("u_first_pass", false); s->setUniform("u_ambient_light", Vector3(0, 0, 0)); s->setUniform("u_viewprojection", camera->viewprojection_matrix); s->setUniform("u_hdr", hdr); quad->render(GL_TRIANGLES); } s->disable(); directionals.clear(); glFrontFace(GL_CCW); } void Renderer::showReflection(Camera* camera) { float w = Application::instance->window_width; float h = Application::instance->window_height; Matrix44 inv_vp = camera->viewprojection_matrix; inv_vp.inverse(); Mesh* quad = Mesh::getQuad(); Shader* s_ref = Shader::Get("reflection_def"); s_ref->enable(); s_ref->setUniform("u_inverse_viewprojection", inv_vp); s_ref->setUniform("u_iRes", Vector2(1.0 / (float)w, 1.0 / (float)h)); s_ref->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); s_ref->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); s_ref->setUniform("u_extra_texture", gbuffers_fbo.color_textures[2], 2); s_ref->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); s_ref->setUniform("u_reflection_texture", reflection_probes[0]->cubemap, 7); s_ref->setUniform("u_camera_eye", camera->eye); s_ref->setUniform("u_hdr", hdr); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); quad->render(GL_TRIANGLES); s_ref->disable(); } void Renderer::generateSSAO(GTR::Scene* scene, Camera* camera) { gbuffers_fbo.depth_texture->bind(); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //start rendering inside the ssao texture ssao_fbo.bind(); Mesh* quad = Mesh::getQuad(); Matrix44 invvp = camera->viewprojection_matrix; invvp.inverse(); //get the shader for SSAO (remember to create it using the atlas) Shader* shader = Shader::Get("ssao"); shader->enable(); //send info to reconstruct the world position shader->setUniform("u_inverse_viewprojection", invvp); shader->setTexture("u_depth_texture", gbuffers_fbo.depth_texture, 0); shader->setTexture("u_normal_texture", gbuffers_fbo.color_textures[1], 1); //we need the pixel size so we can center the samples shader->setUniform("u_iRes", Vector2(1.0 / (float)gbuffers_fbo.depth_texture->width, 1.0 / (float)gbuffers_fbo.depth_texture->height)); //we will need the viewprojection to obtain the uv in the depthtexture of any random position of our world shader->setUniform("u_viewprojection", camera->viewprojection_matrix); //send random points so we can fetch around shader->setUniform3Array("u_points", (float*)&random_points[0], random_points.size()); glDisable(GL_DEPTH_TEST); //render fullscreen quad quad->render(GL_TRIANGLES); glEnable(GL_DEPTH_TEST); //stop rendering to the texture ssao_fbo.unbind(); ssao_fbo.color_textures[0]->copyTo(ssao_blur.color_textures[0]); // BLUR if (blur_ssao) { ssao_blur.bind(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); Mesh* quad = Mesh::getQuad(); shader = Shader::Get("blur"); shader->enable(); shader->setTexture("u_ssao_texture", ssao_blur.color_textures[0], 0); shader->setUniform("horizontal", true); quad->render(GL_TRIANGLES); shader->setUniform("horizontal", false); quad->render(GL_TRIANGLES); shader->disable(); ssao_blur.unbind(); } } std::vector<Vector3> Renderer::generateSpherePoints(int num, float radius, bool hemi) { std::vector<Vector3> points; points.resize(num); for (int i = 0; i < num; i += 3) { Vector3& p = points[i]; float u = random(); float v = random(); float theta = u * 2.0 * PI; float phi = acos(2.0 * v - 1.0); float r = cbrt(random() * 0.9 + 0.1) * radius; float sinTheta = sin(theta); float cosTheta = cos(theta); float sinPhi = sin(phi); float cosPhi = cos(phi); p.x = r * sinPhi * cosTheta; p.y = r * sinPhi * sinTheta; p.z = r * cosPhi; if (hemi && p.z < 0) p.z *= -1.0; } return points; } void Renderer::renderToFBO(GTR::Scene* scene, Camera* camera) { switch (pipeline_mode) { case FORWARD: renderToFBOForward(scene, camera); break; case DEFERRED: renderToFBODeferred(scene, camera); break; } } void Renderer::renderMeshDeferred(const Matrix44 model, Mesh* mesh, GTR::Material* material, Camera* camera) { Shader* shader = Shader::Get("multi"); Texture* texture = NULL; Texture* normal_texture = NULL; Texture* mat_properties_texture = NULL; texture = material->color_texture.texture; if (texture == NULL) texture = Texture::getWhiteTexture(); //a 1x1 white texture bool read_normal = true; normal_texture = material->normal_texture.texture; if (!normal_texture) read_normal = false; mat_properties_texture = material->metallic_roughness_texture.texture; if (mat_properties_texture == NULL) mat_properties_texture = Texture::getBlackTexture(); //a 1x1 white texture bool changed = false; if (!dithering && material->alpha_mode == GTR::eAlphaMode::BLEND) return; else if (dithering && material->alpha_mode != GTR::eAlphaMode::BLEND) { dithering = false; changed = true; } else glDisable(GL_BLEND); //select if render both sides of the triangles if (material->two_sided) glDisable(GL_CULL_FACE); else glEnable(GL_CULL_FACE); assert(glGetError() == GL_NO_ERROR); shader->enable(); shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_camera_position", camera->eye); shader->setUniform("u_model", model); float t = getTime(); shader->setUniform("u_time", t); shader->setUniform("u_color", material->color); shader->setUniform("u_emissive_factor", material->emissive_factor); if (texture) shader->setUniform("u_texture", texture, 0); if (normal_texture) shader->setUniform("u_normal_texture", normal_texture, 1); if (mat_properties_texture) shader->setUniform("u_mat_properties_texture", mat_properties_texture, 2); shader->setUniform("u_read_normal", read_normal); shader->setUniform("u_alpha_cutoff", material->alpha_mode == GTR::eAlphaMode::MASK ? material->alpha_cutoff : 0); shader->setUniform("u_dither", dithering); mesh->render(GL_TRIANGLES); shader->disable(); glDisable(GL_BLEND); if (changed) dithering = true; } void GTR::Renderer::renderDecals(GTR::Scene* scene, Camera* camera) { static Mesh* mesh = NULL; if (mesh == NULL) { mesh = new Mesh(); mesh->createCube(); } Shader* shader = Shader::Get("decals"); shader->enable(); Matrix44 inv_vp = camera->viewprojection_matrix; inv_vp.inverse(); shader->setUniform("u_inverse_viewprojection", inv_vp); shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_color_texture", gbuffers_fbo.color_textures[0], 0); shader->setUniform("u_normal_texture", gbuffers_fbo.color_textures[1], 1); shader->setUniform("u_extra_texture", gbuffers_fbo.color_textures[2], 1); shader->setUniform("u_depth_texture", gbuffers_fbo.depth_texture, 3); shader->setUniform("u_iRes", Vector2(1.0 / (float)gbuffers_fbo.color_textures[0]->width, 1.0 / (float)gbuffers_fbo.color_textures[0]->height)); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); for (int i = 0; i < scene->entities.size(); ++i) { BaseEntity* ent = scene->entities[i]; if (ent->entity_type != eEntityType::DECAL) continue; DecalEntity* decal = (DecalEntity*)ent; Matrix44 imodel = decal->model; imodel.inverse(); shader->setUniform("u_model", decal->model); shader->setUniform("u_iModel", imodel); shader->setTexture("u_decal_texture", decal->albedo, 8); mesh->render(GL_TRIANGLES); //mesh->renderBounding(decal->model); } } void Renderer::renderScene(GTR::Scene* scene, Camera* camera) { //set the clear color (the background color) glClearColor(scene->background_color.x, scene->background_color.y, scene->background_color.z, 1.0); // Clear the color and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); checkGLErrors(); if (pipeline_mode == FORWARD) renderSkyBox(scene->environment, camera); collectRCsandLights(scene, camera); for (int i = 0; i < renderCalls.size(); ++i) { RenderCall render_call = renderCalls[i]; if (pipeline_mode == FORWARD) renderMeshWithMaterial(render_call.model, render_call.mesh, render_call.material, camera); else { if (dithering) renderMeshDeferred(render_call.model, render_call.mesh, render_call.material, camera); else { if (render_call.material->alpha_mode == BLEND) renderMeshWithMaterial(render_call.model, render_call.mesh, render_call.material, camera); else renderMeshDeferred(render_call.model, render_call.mesh, render_call.material, camera); } } } } void GTR::Renderer::renderSceneForward(GTR::Scene* scene, Camera* camera) { //set the clear color (the background color) glClearColor(scene->background_color.x, scene->background_color.y, scene->background_color.z, 1.0); // Clear the color and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); checkGLErrors(); renderSkyBox(scene->environment, camera); collectRCsandLights(scene, camera); for (int i = 0; i < renderCalls.size(); ++i) { RenderCall render_call = renderCalls[i]; renderMeshWithMaterial(render_call.model, render_call.mesh, render_call.material, camera, scene); } } void GTR::Renderer::renderShadow(GTR::Scene* scene, Camera* camera) { //set the clear color (the background color) glClearColor(0, 0, 0, 0); // Clear the color and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); checkGLErrors(); collectRCsandLights(scene, camera); for (int i = 0; i < renderCalls.size(); ++i) { RenderCall render_call = renderCalls[i]; getShadows(render_call.model, render_call.mesh, render_call.material, camera); } } void GTR::Renderer::generateShadowmaps(GTR::Scene* scene) { for (int i = 0; i < scene->l_entities.size(); ++i) { LightEntity* light = scene->l_entities[i]; if (light->light_type != POINT) { if (light->fbo.fbo_id == 0) { light->fbo = FBO(); light->fbo.setDepthOnly(2048, 2048); light->shadow_buffer = new Texture(); } light->fbo.bind(); glColorMask(false, false, false, false); glClear(GL_DEPTH_BUFFER_BIT); renderShadow(scene, light->light_camera); light->fbo.unbind(); glColorMask(true, true, true, true); light->shadow_buffer = light->fbo.depth_texture; } } } //renders all the prefab void Renderer::renderPrefab(const Matrix44& model, GTR::Prefab* prefab, Camera* camera) { assert(prefab && "PREFAB IS NULL"); //assign the model to the root node renderNode(model, &prefab->root, camera); } //renders a node of the prefab and its children void Renderer::renderNode(const Matrix44& prefab_model, GTR::Node* node, Camera* camera) { GTR::Scene* scene = GTR::Scene::instance; if (!node->visible) return; //compute global matrix Matrix44 node_model = node->getGlobalMatrix(true) * prefab_model; //does this node have a mesh? then we must render it if (node->mesh && node->material) { //compute the bounding box of the object in world space (by using the mesh bounding box transformed to world space) BoundingBox world_bounding = transformBoundingBox(node_model, node->mesh->box); //if bounding box is inside the camera frustum then the object is probably visible if (camera->testBoxInFrustum(world_bounding.center, world_bounding.halfsize)) { //render node mesh //renderMeshWithMaterial( node_model, node->mesh, node->material, camera ); float distance_to_camera = world_bounding.center.distance(camera->eye); RenderCall render_Call = createRenderCall(node_model, node->mesh, node->material, distance_to_camera); addRenderCall(render_Call); //node->mesh->renderBounding(node_model, true); } } //iterate recursively with children for (int i = 0; i < node->children.size(); ++i) renderNode(prefab_model, node->children[i], camera); } //renders a mesh given its transform and material void Renderer::renderMeshWithMaterial(const Matrix44 model, Mesh* mesh, GTR::Material* material, Camera* camera, Scene* scene) { //in case there is nothing to do if (!mesh || !mesh->getNumVertices() || !material) return; assert(glGetError() == GL_NO_ERROR); //define locals to simplify coding Shader* shader = NULL; Texture* texture = NULL; Texture* mr_texture = NULL; Texture* emissive_texture = NULL; Texture* occ_texture = NULL; Texture* normal_texture = NULL; bool have_normalmap = true; if(scene == nullptr) scene = GTR::Scene::instance; //GTR::Scene* scene = GTR::Scene::instance; // textures texture = material->color_texture.texture; emissive_texture = material->emissive_texture.texture; mr_texture = material->metallic_roughness_texture.texture; normal_texture = material->normal_texture.texture; occ_texture = material->occlusion_texture.texture; if (texture == NULL) texture = Texture::getWhiteTexture(); //a 1x1 white texture if (mr_texture == NULL) mr_texture = Texture::getWhiteTexture(); //a 1x1 white texture if (emissive_texture == NULL) emissive_texture = Texture::getWhiteTexture(); //a 1x1 white texture if (occ_texture == NULL) occ_texture = Texture::getWhiteTexture(); //a 1x1 white texture //if (normal_texture == NULL) normal_texture = Texture::getWhiteTexture(); //a 1x1 white texture if (normal_texture == NULL) have_normalmap = false; //select the blending if (material->alpha_mode == GTR::eAlphaMode::BLEND) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else glDisable(GL_BLEND); //select if render both sides of the triangles if (material->two_sided) glDisable(GL_CULL_FACE); else glEnable(GL_CULL_FACE); assert(glGetError() == GL_NO_ERROR); //chose a shader switch (render_mode) { case SHOW_NORMAL: shader = Shader::Get("normal"); break; case SHOW_UVS: shader = Shader::Get("uvs"); break; case SHOW_TEXTURE: shader = Shader::Get("texture"); break; case SHOW_DEFERRED: shader = Shader::Get("texture"); break; case SHOW_AO: shader = Shader::Get("occlusion"); break; case DEFAULT: shader = Shader::Get("light_singlepass"); break; case SHOW_MULTI: shader = Shader::Get("light_multipass"); break; } assert(glGetError() == GL_NO_ERROR); //no shader? then nothing to render if (!shader) return; shader->enable(); //upload uniforms shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_camera_position", camera->eye); shader->setUniform("u_model", model); float t = getTime(); shader->setUniform("u_time", t); shader->setUniform("u_color", material->color); if (texture) shader->setUniform("u_texture", texture, 0); if (mr_texture) shader->setUniform("u_metallic_roughness_texture", mr_texture, 1); if (emissive_texture) shader->setUniform("u_emissive_texture", emissive_texture, 2); if (occ_texture) shader->setUniform("u_occ_texture", occ_texture, 3); if (normal_texture) shader->setUniform("u_normal_texture", normal_texture, 4); shader->setUniform("u_read_normal", have_normalmap); //this is used to say which is the alpha threshold to what we should not paint a pixel on the screen (to cut polygons according to texture alpha) shader->setUniform("u_alpha_cutoff", material->alpha_mode == GTR::eAlphaMode::MASK ? material->alpha_cutoff : 0); // light information shader->setUniform("u_ambient_light", scene->ambient_light); shader->setUniform("u_emissive_factor", material->emissive_factor); if (scene->environment) shader->setTexture("u_environment_texture", scene->environment, 7); // SINGLE PASS if (render_mode == DEFAULT) { // lights int num_lights = 5; Vector3 light_position[5]; Vector3 light_color[5]; Vector3 light_vector[5]; int light_type[5] = {}; float max_distances[5]; float light_intensities[5]; float light_cos_cutoff[5]; float light_exponents[5]; for (int j = 0; j < num_lights; ++j) { LightEntity* lent = scene->l_entities[j]; light_color[j] = lent->color; light_position[j] = lent->model.getTranslation(); //convert a position from local to world light_type[j] = static_cast<int>(lent->light_type); if (lent->light_type == SPOT) light_vector[j] = lent->model.frontVector(); else if (lent->light_type == DIRECTIONAL) light_vector[j] = lent->model.rotateVector(Vector3(0, 0, -1)); if (lent->light_type == SPOT) { light_cos_cutoff[j] = cos(lent->cone_angle * DEG2RAD); light_exponents[j] = lent->exponent; } max_distances[j] = lent->max_distance; light_intensities[j] = lent->intensity; } shader->setUniform3Array("u_light_pos", (float*)&light_position, 5); shader->setUniform3Array("u_light_color", (float*)&light_color, 5); shader->setUniform1Array("u_light_type", (int*)&light_type, 5); shader->setUniform3Array("u_direction", (float*)&light_vector, 5); shader->setUniform1("u_num_lights", num_lights); shader->setUniform1Array("u_maxdist", (float*)&max_distances, 5); shader->setUniform1Array("u_light_factor", (float*)&light_intensities, 5); shader->setUniform1Array("u_spotCosineCutoff", (float*)&light_cos_cutoff, 5); shader->setUniform1Array("u_spotExponent", (float*)&light_exponents, 5); //do the draw call that renders the mesh into the screen mesh->render(GL_TRIANGLES); } // MULTI PASS else if (render_mode == SHOW_MULTI) { //allow to render pixels that have the same depth as the one in the depth buffer glDepthFunc(GL_LEQUAL); //set blending mode to additive, this will collide with materials with blend... glBlendFunc(GL_SRC_ALPHA, GL_ONE); for (int i = 0; i < scene->l_entities.size(); ++i) { LightEntity* light = scene->l_entities[i]; //first pass doesn't use blending if (i == 0) { if (material->alpha_mode == GTR::eAlphaMode::BLEND) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDisable(GL_BLEND); } } else { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); shader->setUniform("u_ambient_light", Vector3(0, 0, 0)); shader->setUniform("u_emissive_factor", Vector3(0, 0, 0)); } light->setUniforms(shader); //render the mesh mesh->render(GL_TRIANGLES); } glDepthFunc(GL_LESS); //as default } else mesh->render(GL_TRIANGLES); //do the draw call that renders the mesh into the screen //disable shader shader->disable(); //set the render state as it was before to avoid problems with future renders glDisable(GL_BLEND); glDepthFunc(GL_LESS); } void GTR::Renderer::resize(int width, int height) { illumination_fbo.create(width, height, 3, GL_RGB, GL_FLOAT, false); dof_fbo.create(width, height, 3, GL_RGB, GL_FLOAT, false); } void GTR::Renderer::getShadows(const Matrix44 model, Mesh* mesh, GTR::Material* material, Camera* camera) { //in case there is nothing to do if (!mesh || !mesh->getNumVertices() || !material) return; assert(glGetError() == GL_NO_ERROR); //define locals to simplify coding Shader* shader = NULL; GTR::Scene* scene = GTR::Scene::instance; //select the blending if (material->alpha_mode == GTR::eAlphaMode::BLEND) return; else glDisable(GL_BLEND); if (material->two_sided) glDisable(GL_CULL_FACE); else glEnable(GL_CULL_FACE); assert(glGetError() == GL_NO_ERROR); shader = Shader::Get("shadow"); assert(glGetError() == GL_NO_ERROR); //no shader? then nothing to render if (!shader) return; shader->enable(); shader->setUniform("u_viewprojection", camera->viewprojection_matrix); shader->setUniform("u_camera_position", camera->eye); shader->setUniform("u_model", model); shader->setUniform("u_color", material->color); shader->setUniform("u_alpha_cutoff", material->alpha_mode == GTR::eAlphaMode::MASK ? material->alpha_cutoff : 0); Texture* texture = NULL; texture = material->color_texture.texture; if (texture == NULL) texture = Texture::getWhiteTexture(); //a 1x1 white texture if (texture) shader->setUniform("u_texture", texture, 0); glDepthFunc(GL_LESS); //as default //do the draw call that renders the mesh into the screen mesh->render(GL_TRIANGLES); //disable shader shader->disable(); //set the render state as it was before to avoid problems with future renders glDisable(GL_BLEND); } Texture* GTR::CubemapFromHDRE(const char* filename) { HDRE* hdre = HDRE::Get(filename); if (!hdre) return NULL; Texture* texture = new Texture(); if (hdre->getFacesf(0)) { texture->createCubemap(hdre->width, hdre->height, (Uint8**)hdre->getFacesf(0), hdre->header.numChannels == 3 ? GL_RGB : GL_RGBA, GL_FLOAT); for (int i = 1; i < hdre->levels; ++i) texture->uploadCubemap(texture->format, texture->type, false, (Uint8**)hdre->getFacesf(i), GL_RGBA32F, i); } else if (hdre->getFacesh(0)) { texture->createCubemap(hdre->width, hdre->height, (Uint8**)hdre->getFacesh(0), hdre->header.numChannels == 3 ? GL_RGB : GL_RGBA, GL_HALF_FLOAT); for (int i = 1; i < hdre->levels; ++i) texture->uploadCubemap(texture->format, texture->type, false, (Uint8**)hdre->getFacesh(i), GL_RGBA16F, i); } return texture; }
30.956633
147
0.690791
[ "mesh", "render", "object", "vector", "model", "transform" ]
296aec66805a444ffc1789e5881791ec2f398660
8,169
cpp
C++
llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
58
2016-08-27T03:19:14.000Z
2022-01-05T17:33:44.000Z
llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
14
2017-12-01T17:16:59.000Z
2020-12-21T12:16:35.000Z
llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
22
2016-11-27T09:53:31.000Z
2021-11-22T00:22:53.000Z
// MallocSizeofChecker.cpp - Check for dubious malloc arguments ---*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Reports inconsistencies between the casted type of the return value of a // malloc/calloc/realloc call and the operand of any sizeof expressions // contained within its argument(s). // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/TypeLoc.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace ento; namespace { typedef std::pair<const TypeSourceInfo *, const CallExpr *> TypeCallPair; typedef llvm::PointerUnion<const Stmt *, const VarDecl *> ExprParent; class CastedAllocFinder : public ConstStmtVisitor<CastedAllocFinder, TypeCallPair> { IdentifierInfo *II_malloc, *II_calloc, *II_realloc; public: struct CallRecord { ExprParent CastedExprParent; const Expr *CastedExpr; const TypeSourceInfo *ExplicitCastType; const CallExpr *AllocCall; CallRecord(ExprParent CastedExprParent, const Expr *CastedExpr, const TypeSourceInfo *ExplicitCastType, const CallExpr *AllocCall) : CastedExprParent(CastedExprParent), CastedExpr(CastedExpr), ExplicitCastType(ExplicitCastType), AllocCall(AllocCall) {} }; typedef std::vector<CallRecord> CallVec; CallVec Calls; CastedAllocFinder(ASTContext *Ctx) : II_malloc(&Ctx->Idents.get("malloc")), II_calloc(&Ctx->Idents.get("calloc")), II_realloc(&Ctx->Idents.get("realloc")) {} void VisitChild(ExprParent Parent, const Stmt *S) { TypeCallPair AllocCall = Visit(S); if (AllocCall.second && AllocCall.second != S) Calls.push_back(CallRecord(Parent, cast<Expr>(S), AllocCall.first, AllocCall.second)); } void VisitChildren(const Stmt *S) { for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) if (const Stmt *child = *I) VisitChild(S, child); } TypeCallPair VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); } TypeCallPair VisitExplicitCastExpr(const ExplicitCastExpr *E) { return TypeCallPair(E->getTypeInfoAsWritten(), Visit(E->getSubExpr()).second); } TypeCallPair VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } TypeCallPair VisitStmt(const Stmt *S) { VisitChildren(S); return TypeCallPair(); } TypeCallPair VisitCallExpr(const CallExpr *E) { VisitChildren(E); const FunctionDecl *FD = E->getDirectCallee(); if (FD) { IdentifierInfo *II = FD->getIdentifier(); if (II == II_malloc || II == II_calloc || II == II_realloc) return TypeCallPair((const TypeSourceInfo *)nullptr, E); } return TypeCallPair(); } TypeCallPair VisitDeclStmt(const DeclStmt *S) { for (const auto *I : S->decls()) if (const VarDecl *VD = dyn_cast<VarDecl>(I)) if (const Expr *Init = VD->getInit()) VisitChild(VD, Init); return TypeCallPair(); } }; class SizeofFinder : public ConstStmtVisitor<SizeofFinder> { public: std::vector<const UnaryExprOrTypeTraitExpr *> Sizeofs; void VisitBinMul(const BinaryOperator *E) { Visit(E->getLHS()); Visit(E->getRHS()); } void VisitImplicitCastExpr(const ImplicitCastExpr *E) { return Visit(E->getSubExpr()); } void VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) { if (E->getKind() != UETT_SizeOf) return; Sizeofs.push_back(E); } }; // Determine if the pointee and sizeof types are compatible. Here // we ignore constness of pointer types. static bool typesCompatible(ASTContext &C, QualType A, QualType B) { // sizeof(void*) is compatible with any other pointer. if (B->isVoidPointerType() && A->getAs<PointerType>()) return true; while (true) { A = A.getCanonicalType(); B = B.getCanonicalType(); if (A.getTypePtr() == B.getTypePtr()) return true; if (const PointerType *ptrA = A->getAs<PointerType>()) if (const PointerType *ptrB = B->getAs<PointerType>()) { A = ptrA->getPointeeType(); B = ptrB->getPointeeType(); continue; } break; } return false; } static bool compatibleWithArrayType(ASTContext &C, QualType PT, QualType T) { // Ex: 'int a[10][2]' is compatible with 'int', 'int[2]', 'int[10][2]'. while (const ArrayType *AT = T->getAsArrayTypeUnsafe()) { QualType ElemType = AT->getElementType(); if (typesCompatible(C, PT, AT->getElementType())) return true; T = ElemType; } return false; } class MallocSizeofChecker : public Checker<check::ASTCodeBody> { public: void checkASTCodeBody(const Decl *D, AnalysisManager& mgr, BugReporter &BR) const { AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D); CastedAllocFinder Finder(&BR.getContext()); Finder.Visit(D->getBody()); for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(), e = Finder.Calls.end(); i != e; ++i) { QualType CastedType = i->CastedExpr->getType(); if (!CastedType->isPointerType()) continue; QualType PointeeType = CastedType->getAs<PointerType>()->getPointeeType(); if (PointeeType->isVoidType()) continue; for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(), ae = i->AllocCall->arg_end(); ai != ae; ++ai) { if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType()) continue; SizeofFinder SFinder; SFinder.Visit(*ai); if (SFinder.Sizeofs.size() != 1) continue; QualType SizeofType = SFinder.Sizeofs[0]->getTypeOfArgument(); if (typesCompatible(BR.getContext(), PointeeType, SizeofType)) continue; // If the argument to sizeof is an array, the result could be a // pointer to any array element. if (compatibleWithArrayType(BR.getContext(), PointeeType, SizeofType)) continue; const TypeSourceInfo *TSI = nullptr; if (i->CastedExprParent.is<const VarDecl *>()) { TSI = i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo(); } else { TSI = i->ExplicitCastType; } SmallString<64> buf; llvm::raw_svector_ostream OS(buf); OS << "Result of "; const FunctionDecl *Callee = i->AllocCall->getDirectCallee(); if (Callee && Callee->getIdentifier()) OS << '\'' << Callee->getIdentifier()->getName() << '\''; else OS << "call"; OS << " is converted to a pointer of type '" << PointeeType.getAsString() << "', which is incompatible with " << "sizeof operand type '" << SizeofType.getAsString() << "'"; SmallVector<SourceRange, 4> Ranges; Ranges.push_back(i->AllocCall->getCallee()->getSourceRange()); Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange()); if (TSI) Ranges.push_back(TSI->getTypeLoc().getSourceRange()); PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(), BR.getSourceManager(), ADC); BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch", categories::UnixAPI, OS.str(), L, Ranges); } } } }; } void ento::registerMallocSizeofChecker(CheckerManager &mgr) { mgr.registerChecker<MallocSizeofChecker>(); }
32.161417
80
0.634717
[ "vector" ]
296c767b55cd6f7fab5be58328fa4b214a3a22a8
8,294
cpp
C++
src/showrepaint.cpp
soreau/wayfire-plugins-extra
9da2d1ba78d166d3397c43c032034036870b5ca0
[ "MIT" ]
1
2020-05-28T22:30:24.000Z
2020-05-28T22:30:24.000Z
src/showrepaint.cpp
damianatorrpm/wayfire-plugins-extra
6b8ca602ef2b23a44c7a1c20e86201eae13ce68e
[ "MIT" ]
null
null
null
src/showrepaint.cpp
damianatorrpm/wayfire-plugins-extra
6b8ca602ef2b23a44c7a1c20e86201eae13ce68e
[ "MIT" ]
1
2020-05-16T21:42:05.000Z
2020-05-16T21:42:05.000Z
/* * The MIT License (MIT) * * Copyright (c) 2020 Scott Moreau * * 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 <wayfire/plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/opengl.hpp> #include <wayfire/render-manager.hpp> #include <wayfire/util/log.hpp> extern "C" { #include <EGL/egl.h> } class wayfire_showrepaint : public wf::plugin_interface_t { wf::option_wrapper_t<wf::activatorbinding_t> toggle_binding{"showrepaint/toggle"}; wf::option_wrapper_t<bool> reduce_flicker{"showrepaint/reduce_flicker"}; bool active, egl_swap_buffers_with_damage; wf::framebuffer_base_t last_buffer; public: void init() override { active = false; egl_swap_buffers_with_damage = egl_extension_supported("EGL_KHR_swap_buffers_with_damage") || egl_extension_supported("EGL_EXT_swap_buffers_with_damage"); output->add_activator(toggle_binding, &toggle_cb); reduce_flicker.set_callback(option_changed); } wf::config::option_base_t::updated_callback_t option_changed = [=] () { output->render->damage_whole(); }; wf::activator_callback toggle_cb = [=] (wf::activator_source_t, uint32_t) { active = !active; if (active) { output->render->add_effect(&overlay_hook, wf::OUTPUT_EFFECT_OVERLAY); } else { output->render->rem_effect(&overlay_hook); } output->render->damage_whole(); return true; }; bool egl_extension_supported(std::string ext) { OpenGL::render_begin(); EGLDisplay egl_display = eglGetCurrentDisplay(); std::string extensions = std::string(eglQueryString(egl_display, EGL_EXTENSIONS)); OpenGL::render_end(); size_t pos = extensions.find(ext); if (pos == std::string::npos) { return false; } return true; } void get_random_color(wf::color_t& color) { color.r = 0.15 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 0.25)); color.g = 0.15 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 0.25)); color.b = 0.15 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 0.25)); color.a = 0.25; } wf::effect_hook_t overlay_hook = [=] () { wf::framebuffer_t target_fb = output->render->get_target_framebuffer(); wf::region_t swap_damage = output->render->get_swap_damage(); wf::region_t scheduled_damage = output->render->get_scheduled_damage(); auto fbg = target_fb.geometry; wf::region_t output_region{fbg}; wf::region_t inverted_damage; wf::region_t damage; /* Show scheduled client damage. Scheduled damage is the client damage * in union with last frame client damage. If this region is empty, we * use swap damage, which is the same as scheduled damage unless something * is rendering the entire frame buffer, in which case it is the whole * output region. The reason for this is because we want to display both * scheduled client damage region and the swap damage region, in contrast. */ wf::color_t color; get_random_color(color); damage = scheduled_damage.empty() ? swap_damage : scheduled_damage; OpenGL::render_begin(target_fb); for (const auto& b : damage) { wlr_box box{b.x1, b.y1, b.x2 - b.x1, b.y2 - b.y1}; OpenGL::render_rectangle(box, color, target_fb.get_orthographic_projection()); } if (reduce_flicker) { /* Show swap damage. It might be possible that we blit right over this * but in the case of cube and expo, it shows client and swap damage in * contrast. This makes sense since the idea is to show damage as colored * regions. We don't do this if the reduce_flicker option isn't set because * we don't repaint the inverted damage from the last buffer in this case, * so we would keep painting it with different colors until it is white. */ get_random_color(color); inverted_damage = output_region ^ damage; for (const auto& b : inverted_damage) { wlr_box box{b.x1, b.y1, b.x2 - b.x1, b.y2 - b.y1}; OpenGL::render_rectangle(box, color, target_fb.get_orthographic_projection()); } } OpenGL::render_end(); /* If swap_buffers_with_damage is supported, we do not need the * following to be executed. */ if (egl_swap_buffers_with_damage) { return; } /* User option. */ if (!reduce_flicker) { return; } fbg.width = target_fb.viewport_width; fbg.height = target_fb.viewport_height; OpenGL::render_begin(); last_buffer.allocate(fbg.width, fbg.height); OpenGL::render_end(); /* Repaint the inverted damage region with the last buffer contents. * We only want to see what actually changed on screen. If we don't * do this, things like mouse and keyboard input cause buffer swaps * which only make the screen flicker between buffers, without showing * any actual damage changes. If swap_buffers_with_damage is supported, * we do not need to do this since the damage region that is passed to * swap is only repainted. If it isn't supported, the entire buffer is * repainted. */ OpenGL::render_begin(target_fb); GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, last_buffer.fb)); damage = swap_damage.empty() ? scheduled_damage : swap_damage; output_region *= target_fb.scale; inverted_damage = output_region ^ damage; inverted_damage *= 1.0 / target_fb.scale; for (const auto& rect : inverted_damage) { pixman_box32_t b = pixman_box_from_wlr_box( target_fb.framebuffer_box_from_geometry_box( wlr_box_from_pixman_box(rect))); GL_CALL(glBlitFramebuffer( b.x1, fbg.height - b.y2, b.x2, fbg.height - b.y1, b.x1, fbg.height - b.y2, b.x2, fbg.height - b.y1, GL_COLOR_BUFFER_BIT, GL_LINEAR)); } OpenGL::render_end(); /* Save the current buffer to last buffer so we can render the * inverted damage from the last buffer to the current buffer * on next frame. We have to save the entire buffer because we * don't know what the next frame damage will be. */ OpenGL::render_begin(last_buffer); GL_CALL(glBindFramebuffer(GL_READ_FRAMEBUFFER, target_fb.fb)); GL_CALL(glBlitFramebuffer( 0, 0, fbg.width, fbg.height, 0, 0, fbg.width, fbg.height, GL_COLOR_BUFFER_BIT, GL_LINEAR)); OpenGL::render_end(); }; void fini() override { output->rem_binding(&toggle_cb); output->render->rem_effect(&overlay_hook); } }; DECLARE_WAYFIRE_PLUGIN(wayfire_showrepaint);
38.045872
96
0.637208
[ "geometry", "render" ]
296fe92910e0c859d941398563ad9aa65dc9f117
12,645
cpp
C++
wrappers/openvino/dnn/rs-dnn-vino.cpp
Moktarino/librealsense
fdd863f30b9e71d1c34f226aa0e62659ddb46dbb
[ "Apache-2.0" ]
6,457
2016-01-21T03:56:07.000Z
2022-03-31T11:57:15.000Z
wrappers/openvino/dnn/rs-dnn-vino.cpp
Moktarino/librealsense
fdd863f30b9e71d1c34f226aa0e62659ddb46dbb
[ "Apache-2.0" ]
8,393
2016-01-21T09:47:28.000Z
2022-03-31T22:21:42.000Z
wrappers/openvino/dnn/rs-dnn-vino.cpp
Moktarino/librealsense
fdd863f30b9e71d1c34f226aa0e62659ddb46dbb
[ "Apache-2.0" ]
4,874
2016-01-21T09:20:08.000Z
2022-03-31T15:18:00.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include <librealsense2/rs.hpp> // Include RealSense Cross Platform API #include "cv-helpers.hpp" // frame_to_mat #include <opencv2/core/utils/filesystem.hpp> // glob namespace fs = cv::utils::fs; #include <rs-vino/object-detection.h> #include <rs-vino/detected-object.h> #include <easylogging++.h> #ifdef BUILD_SHARED_LIBS // With static linkage, ELPP is initialized by librealsense, so doing it here will // create errors. When we're using the shared .so/.dll, the two are separate and we have // to initialize ours if we want to use the APIs! INITIALIZE_EASYLOGGINGPP #endif #include <rs-vino/openvino-helpers.h> namespace openvino = InferenceEngine; #include <chrono> using namespace std::chrono; /* Enable loading multiple detectors at once, so we can switch at runtime. Each detector has its associated labels. */ struct detector_and_labels { std::shared_ptr< openvino_helpers::object_detection > detector; std::vector< std::string > labels; detector_and_labels( std::string const & path_to_xml ) : detector( std::make_shared< openvino_helpers::object_detection >( path_to_xml, 0.5 ) ) { } openvino_helpers::object_detection * operator->() { return detector.get(); } void load_labels() { try { labels = openvino_helpers::read_labels( openvino_helpers::remove_ext( detector->pathToModel ) + ".labels" ); } catch( const std::exception & e ) { // If we have no labels, warn and continue... we can continue without them LOG(WARNING) << "Failed to load labels: " << e.what(); } } }; /* Populate a collection of detectors from those we find on disk (*.xml), load their labels, add them to the engine & device, etc. The detectors are loaded with all default values. */ void load_detectors_into( std::vector< detector_and_labels > & detectors, openvino::Core & engine, std::string const & device_name ) { std::vector< std::string > xmls; fs::glob_relative( ".", "*.xml", xmls ); for( auto path_to_xml : xmls ) { if (path_to_xml == "plugins.xml") continue; // plugin.xml is not model file, skip it in model search if exist detector_and_labels detector { path_to_xml }; try { detector->load_into( engine, device_name ); // May throw! detector.load_labels(); detectors.push_back( detector ); LOG(INFO) << " ... press '" << char( '0' + detectors.size() ) << "' to switch to it"; } catch( const std::exception & e ) { // The model files should have been downloaded automatically by CMake into build/wrappers/openvino/dnn, // which is also where Visual Studio runs the sample from. However, you may need to copy these files: // *.bin // *.xml // *.labels [optional] // Into the local directory where you run from (or change the path given in the ctor above) LOG(ERROR) << "Failed to load model: " << e.what(); } } } /* Main detection code: Detected objects are placed into 'objects'. Each new object is assigned 'next_id', which is then incremented. The 'labels' are optional, and used to give labels to each object. Some basic effort is made to keep the creation of new objects to a minimum: previous objects (passed in via 'objects') are compared with new detections to see if the new are simply new positions for the old. An "intersection over union" (IoU) quotient is calculated and, if over a threshold, an existing object is moved rather than a new one created. */ void detect_objects( cv::Mat const & image, std::vector< openvino_helpers::object_detection::Result > const & results, std::vector< std::string > & labels, size_t & next_id, openvino_helpers::detected_objects & objects ) { openvino_helpers::detected_objects prev_objects{ std::move( objects ) }; objects.clear(); for( auto const & result : results ) { if( result.label <= 0 ) continue; // ignore "background", though not clear why we'd get it cv::Rect rect = result.location; rect = rect & cv::Rect( 0, 0, image.cols, image.rows ); auto object_ptr = openvino_helpers::find_object( rect, prev_objects ); if( ! object_ptr ) { // New object std::string label; if( result.label < labels.size() ) label = labels[result.label]; object_ptr = std::make_shared< openvino_helpers::detected_object >( next_id++, label, rect ); } else { // Existing face; just update its parameters object_ptr->move( rect ); } objects.push_back( object_ptr ); } } /* Draws the detected objects with a distance calculated at the center pixel of each face */ void draw_objects( cv::Mat & image, rs2::depth_frame depth_frame, openvino_helpers::detected_objects const & objects ) { cv::Scalar const green( 0, 255, 0 ); // BGR cv::Scalar const white( 255, 255, 255 ); // BGR for( auto && object : objects ) { auto r = object->get_location(); cv::rectangle( image, r, green ); // Output the distance to the center auto center_x = r.x + r.width / 2; auto center_y = r.y + r.height / 2; auto d = depth_frame.get_distance( center_x, center_y ); if( d ) { std::ostringstream ss; ss << object->get_label() << " "; ss << std::setprecision( 2 ) << d; ss << " meters away"; cv::putText( image, ss.str(), cv::Point( r.x + 5, r.y + r.height - 5 ), cv::FONT_HERSHEY_SIMPLEX, 0.4, white ); } } } /* When the user switches betweem models we show the detector number for 1 second as an overlay over the image, centered. */ void draw_detector_overlay( cv::Mat & image, size_t current_detector, high_resolution_clock::time_point switch_time ) { auto ms_since_switch = duration_cast< milliseconds >( high_resolution_clock::now() - switch_time ).count(); if( ms_since_switch > 1000 ) ms_since_switch = 1000; double alpha = ( 1000 - ms_since_switch ) / 1000.; std::string str( 1, char( '1' + current_detector ) ); auto size = cv::getTextSize( str, cv::FONT_HERSHEY_SIMPLEX, 3, 1, nullptr ); cv::Point center{ image.cols / 2, image.rows / 2 }; cv::Rect r{ center.x - size.width, center.y - size.height, size.width * 2, size.height * 2 }; cv::Mat roi = image( r ); cv::Mat overlay( roi.size(), CV_8UC3, cv::Scalar( 32, 32, 32 ) ); cv::putText( overlay, str, cv::Point{ r.width / 2 - size.width / 2, r.height / 2 + size.height / 2 }, cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar{ 255, 255, 255 } ); cv::addWeighted( overlay, alpha, roi, 1 - alpha, 0, roi ); // roi = overlay * alpha + roi * (1-alpha) + 0 } int main(int argc, char * argv[]) try { el::Configurations conf; conf.set( el::Level::Global, el::ConfigurationType::Format, "[%level] %msg" ); //conf.set( el::Level::Debug, el::ConfigurationType::Enabled, "false" ); el::Loggers::reconfigureLogger( "default", conf ); rs2::log_to_console( RS2_LOG_SEVERITY_WARN ); // only warnings (and above) should come through // Declare RealSense pipeline, encapsulating the actual device and sensors rs2::pipeline pipe; pipe.start(); rs2::align align_to( RS2_STREAM_COLOR ); // Start the inference engine, needed to accomplish anything. We also add a CPU extension, allowing // us to run the inference on the CPU. A GPU solution may be possible but, at least without a GPU, // a CPU-bound process is faster. To change to GPU, use "GPU" instead (and remove AddExtension()): openvino::Core engine; #ifdef OPENVINO2019 openvino_helpers::error_listener error_listener; engine.SetLogCallback( error_listener ); #endif std::string const device_name { "CPU" }; // Cpu extensions library was removed in OpenVINO >= 2020.1, extensions were merged into the cpu plugin. #ifdef OPENVINO2019 engine.AddExtension(std::make_shared< openvino::Extensions::Cpu::CpuExtensions >(), device_name); #endif std::vector< detector_and_labels > detectors; load_detectors_into( detectors, engine, device_name ); if( detectors.empty() ) { LOG(ERROR) << "No detectors available in: " << fs::getcwd(); return EXIT_FAILURE; } // Look for the mobilenet-ssd so it always starts the same... otherwise default to the first detector we found size_t current_detector = 0; for( size_t i = 1; i < detectors.size(); ++i ) { if( detectors[i]->pathToModel == "mobilenet-ssd.xml" ) { current_detector = i; break; } } auto p_detector = detectors[current_detector].detector; LOG(INFO) << "Current detector set to (" << current_detector+1 << ") \"" << openvino_helpers::remove_ext( p_detector->pathToModel ) << "\""; auto p_labels = &detectors[current_detector].labels; const auto window_name = "OpenVINO DNN sample"; cv::namedWindow( window_name, cv::WINDOW_AUTOSIZE ); cv::Mat prev_image; openvino_helpers::detected_objects objects; size_t id = 0; uint64 last_frame_number = 0; high_resolution_clock::time_point switch_time = high_resolution_clock::now(); while( cv::getWindowProperty( window_name, cv::WND_PROP_AUTOSIZE ) >= 0 ) { // Wait for the next set of frames auto frames = pipe.wait_for_frames(); // Make sure the frames are spatially aligned frames = align_to.process( frames ); auto color_frame = frames.get_color_frame(); auto depth_frame = frames.get_depth_frame(); if( ! color_frame || ! depth_frame ) continue; // If we only received a new depth frame, but the color did not update, continue if( color_frame.get_frame_number() == last_frame_number ) continue; last_frame_number = color_frame.get_frame_number(); auto image = frame_to_mat( color_frame ); // We process the previous frame so if this is our first then queue it and continue if( ! p_detector->_request ) { p_detector->enqueue( image ); p_detector->submit_request(); prev_image = image; continue; } // Wait for the results of the previous frame we enqueued: we're going to process these p_detector->wait(); auto const results = p_detector->fetch_results(); // Enqueue the current frame so we'd get the results when the next frame comes along! p_detector->enqueue( image ); p_detector->submit_request(); // MAIN DETECTION detect_objects( image, results, *p_labels, id, objects ); // Keep it alive so we can actually process pieces of it once we have the results prev_image = image; // Display the results (from the last frame) as rectangles on top (of the current frame) draw_objects( image, depth_frame, objects ); draw_detector_overlay( image, current_detector, switch_time ); imshow( window_name, image ); // Handle the keyboard before moving to the next frame const int key = cv::waitKey( 1 ); if( key == 27 ) break; // escape if( key >= '1' && key < '1' + detectors.size() ) { size_t detector_index = key - '1'; if( detector_index != current_detector ) { current_detector = detector_index; p_detector = detectors[current_detector].detector; p_labels = &detectors[current_detector].labels; objects.clear(); LOG(INFO) << "Current detector set to (" << current_detector+1 << ") \"" << openvino_helpers::remove_ext( p_detector->pathToModel ) << "\""; } switch_time = high_resolution_clock::now(); } } return EXIT_SUCCESS; } catch (const rs2::error & e) { LOG(ERROR) << "Caught RealSense exception from " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what(); return EXIT_FAILURE; } catch (const std::exception& e) { LOG(ERROR) << "Unknown exception caught: " << e.what(); return EXIT_FAILURE; }
36.865889
165
0.627916
[ "object", "vector", "model" ]
2975945491253a0b901ac8973cfddac6a5f679bf
135,765
cpp
C++
llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp
cbjeukendrup/llvm-project
4c11c3e0f978a9ebdd05822e6e130630fa8680c2
[ "Apache-2.0" ]
null
null
null
llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp
cbjeukendrup/llvm-project
4c11c3e0f978a9ebdd05822e6e130630fa8680c2
[ "Apache-2.0" ]
null
null
null
llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp
cbjeukendrup/llvm-project
4c11c3e0f978a9ebdd05822e6e130630fa8680c2
[ "Apache-2.0" ]
null
null
null
//===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file InstrRefBasedImpl.cpp /// /// This is a separate implementation of LiveDebugValues, see /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. /// /// This pass propagates variable locations between basic blocks, resolving /// control flow conflicts between them. The problem is SSA construction, where /// each debug instruction assigns the *value* that a variable has, and every /// instruction where the variable is in scope uses that variable. The resulting /// map of instruction-to-value is then translated into a register (or spill) /// location for each variable over each instruction. /// /// The primary difference from normal SSA construction is that we cannot /// _create_ PHI values that contain variable values. CodeGen has already /// completed, and we can't alter it just to make debug-info complete. Thus: /// we can identify function positions where we would like a PHI value for a /// variable, but must search the MachineFunction to see whether such a PHI is /// available. If no such PHI exists, the variable location must be dropped. /// /// To achieve this, we perform two kinds of analysis. First, we identify /// every value defined by every instruction (ignoring those that only move /// another value), then re-compute an SSA-form representation of the /// MachineFunction, using value propagation to eliminate any un-necessary /// PHI values. This gives us a map of every value computed in the function, /// and its location within the register file / stack. /// /// Secondly, for each variable we perform the same analysis, where each debug /// instruction is considered a def, and every instruction where the variable /// is in lexical scope as a use. Value propagation is used again to eliminate /// any un-necessary PHIs. This gives us a map of each variable to the value /// it should have in a block. /// /// Once both are complete, we have two maps for each block: /// * Variables to the values they should have, /// * Values to the register / spill slot they are located in. /// After which we can marry-up variable values with a location, and emit /// DBG_VALUE instructions specifying those locations. Variable locations may /// be dropped in this process due to the desired variable value not being /// resident in any machine location, or because there is no PHI value in any /// location that accurately represents the desired value. The building of /// location lists for each block is left to DbgEntityHistoryCalculator. /// /// This pass is kept efficient because the size of the first SSA problem /// is proportional to the working-set size of the function, which the compiler /// tries to keep small. (It's also proportional to the number of blocks). /// Additionally, we repeatedly perform the second SSA problem analysis with /// only the variables and blocks in a single lexical scope, exploiting their /// locality. /// /// ### Terminology /// /// A machine location is a register or spill slot, a value is something that's /// defined by an instruction or PHI node, while a variable value is the value /// assigned to a variable. A variable location is a machine location, that must /// contain the appropriate variable value. A value that is a PHI node is /// occasionally called an mphi. /// /// The first SSA problem is the "machine value location" problem, /// because we're determining which machine locations contain which values. /// The "locations" are constant: what's unknown is what value they contain. /// /// The second SSA problem (the one for variables) is the "variable value /// problem", because it's determining what values a variable has, rather than /// what location those values are placed in. /// /// TODO: /// Overlapping fragments /// Entry values /// Add back DEBUG statements for debugging this /// Collect statistics /// //===----------------------------------------------------------------------===// #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/IteratedDominanceFrontier.h" #include "llvm/CodeGen/LexicalScopes.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineInstrBundle.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/PseudoSourceValue.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/InitializePasses.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TypeSize.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" #include <algorithm> #include <cassert> #include <cstdint> #include <functional> #include <limits.h> #include <limits> #include <queue> #include <tuple> #include <utility> #include <vector> #include "InstrRefBasedImpl.h" #include "LiveDebugValues.h" using namespace llvm; using namespace LiveDebugValues; // SSAUpdaterImple sets DEBUG_TYPE, change it. #undef DEBUG_TYPE #define DEBUG_TYPE "livedebugvalues" // Act more like the VarLoc implementation, by propagating some locations too // far and ignoring some transfers. static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, cl::desc("Act like old LiveDebugValues did"), cl::init(false)); static bool isSwiftAsyncContext(const MachineFunction &MF, Register Reg) { const llvm::Function &F = MF.getFunction(); if (!MF.getProperties().hasProperty( MachineFunctionProperties::Property::TracksLiveness)) return false; unsigned I = 0; for (auto R : MF.getRegInfo().liveins()) { if (R.first == (unsigned)Reg && F.hasParamAttribute(I, Attribute::SwiftAsync)) return true; ++I; } return false; } /// Tracker for converting machine value locations and variable values into /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs /// specifying block live-in locations and transfers within blocks. /// /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker /// and must be initialized with the set of variable values that are live-in to /// the block. The caller then repeatedly calls process(). TransferTracker picks /// out variable locations for the live-in variable values (if there _is_ a /// location) and creates the corresponding DBG_VALUEs. Then, as the block is /// stepped through, transfers of values between machine locations are /// identified and if profitable, a DBG_VALUE created. /// /// This is where debug use-before-defs would be resolved: a variable with an /// unavailable value could materialize in the middle of a block, when the /// value becomes available. Or, we could detect clobbers and re-specify the /// variable in a backup location. (XXX these are unimplemented). class TransferTracker { public: const TargetInstrInfo *TII; const TargetLowering *TLI; /// This machine location tracker is assumed to always contain the up-to-date /// value mapping for all machine locations. TransferTracker only reads /// information from it. (XXX make it const?) MLocTracker *MTracker; MachineFunction &MF; bool ShouldEmitDebugEntryValues; /// Record of all changes in variable locations at a block position. Awkwardly /// we allow inserting either before or after the point: MBB != nullptr /// indicates it's before, otherwise after. struct Transfer { MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes MachineBasicBlock *MBB; /// non-null if we should insert after. SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. }; struct LocAndProperties { LocIdx Loc; DbgValueProperties Properties; }; /// Collection of transfers (DBG_VALUEs) to be inserted. SmallVector<Transfer, 32> Transfers; /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences /// between TransferTrackers view of variable locations and MLocTrackers. For /// example, MLocTracker observes all clobbers, but TransferTracker lazily /// does not. SmallVector<ValueIDNum, 32> VarLocs; /// Map from LocIdxes to which DebugVariables are based that location. /// Mantained while stepping through the block. Not accurate if /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; /// Map from DebugVariable to it's current location and qualifying meta /// information. To be used in conjunction with ActiveMLocs to construct /// enough information for the DBG_VALUEs for a particular LocIdx. DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. SmallVector<MachineInstr *, 4> PendingDbgValues; /// Record of a use-before-def: created when a value that's live-in to the /// current block isn't available in any machine location, but it will be /// defined in this block. struct UseBeforeDef { /// Value of this variable, def'd in block. ValueIDNum ID; /// Identity of this variable. DebugVariable Var; /// Additional variable properties. DbgValueProperties Properties; }; /// Map from instruction index (within the block) to the set of UseBeforeDefs /// that become defined at that instruction. DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; /// The set of variables that are in UseBeforeDefs and can become a location /// once the relevant value is defined. An element being erased from this /// collection prevents the use-before-def materializing. DenseSet<DebugVariable> UseBeforeDefVariables; const TargetRegisterInfo &TRI; const BitVector &CalleeSavedRegs; TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, MachineFunction &MF, const TargetRegisterInfo &TRI, const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), CalleeSavedRegs(CalleeSavedRegs) { TLI = MF.getSubtarget().getTargetLowering(); auto &TM = TPC.getTM<TargetMachine>(); ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); } /// Load object with live-in variable values. \p mlocs contains the live-in /// values in each machine location, while \p vlocs the live-in variable /// values. This method picks variable locations for the live-in variables, /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other /// object fields to track variable locations as we step through the block. /// FIXME: could just examine mloctracker instead of passing in \p mlocs? void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs, SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, unsigned NumLocs) { ActiveMLocs.clear(); ActiveVLocs.clear(); VarLocs.clear(); VarLocs.reserve(NumLocs); UseBeforeDefs.clear(); UseBeforeDefVariables.clear(); auto isCalleeSaved = [&](LocIdx L) { unsigned Reg = MTracker->LocIdxToLocID[L]; if (Reg >= MTracker->NumRegs) return false; for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) if (CalleeSavedRegs.test(*RAI)) return true; return false; }; // Map of the preferred location for each value. std::map<ValueIDNum, LocIdx> ValueToLoc; ActiveMLocs.reserve(VLocs.size()); ActiveVLocs.reserve(VLocs.size()); // Produce a map of value numbers to the current machine locs they live // in. When emulating VarLocBasedImpl, there should only be one // location; when not, we get to pick. for (auto Location : MTracker->locations()) { LocIdx Idx = Location.Idx; ValueIDNum &VNum = MLocs[Idx.asU64()]; VarLocs.push_back(VNum); // Short-circuit unnecessary preferred location update. if (VLocs.empty()) continue; auto it = ValueToLoc.find(VNum); // In order of preference, pick: // * Callee saved registers, // * Other registers, // * Spill slots. if (it == ValueToLoc.end() || MTracker->isSpill(it->second) || (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) { // Insert, or overwrite if insertion failed. auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx)); if (!PrefLocRes.second) PrefLocRes.first->second = Idx; } } // Now map variables to their picked LocIdxes. for (auto Var : VLocs) { if (Var.second.Kind == DbgValue::Const) { PendingDbgValues.push_back( emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); continue; } // If the value has no location, we can't make a variable location. const ValueIDNum &Num = Var.second.ID; auto ValuesPreferredLoc = ValueToLoc.find(Num); if (ValuesPreferredLoc == ValueToLoc.end()) { // If it's a def that occurs in this block, register it as a // use-before-def to be resolved as we step through the block. if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) addUseBeforeDef(Var.first, Var.second.Properties, Num); else recoverAsEntryValue(Var.first, Var.second.Properties, Num); continue; } LocIdx M = ValuesPreferredLoc->second; auto NewValue = LocAndProperties{M, Var.second.Properties}; auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); if (!Result.second) Result.first->second = NewValue; ActiveMLocs[M].insert(Var.first); PendingDbgValues.push_back( MTracker->emitLoc(M, Var.first, Var.second.Properties)); } flushDbgValues(MBB.begin(), &MBB); } /// Record that \p Var has value \p ID, a value that becomes available /// later in the function. void addUseBeforeDef(const DebugVariable &Var, const DbgValueProperties &Properties, ValueIDNum ID) { UseBeforeDef UBD = {ID, Var, Properties}; UseBeforeDefs[ID.getInst()].push_back(UBD); UseBeforeDefVariables.insert(Var); } /// After the instruction at index \p Inst and position \p pos has been /// processed, check whether it defines a variable value in a use-before-def. /// If so, and the variable value hasn't changed since the start of the /// block, create a DBG_VALUE. void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { auto MIt = UseBeforeDefs.find(Inst); if (MIt == UseBeforeDefs.end()) return; for (auto &Use : MIt->second) { LocIdx L = Use.ID.getLoc(); // If something goes very wrong, we might end up labelling a COPY // instruction or similar with an instruction number, where it doesn't // actually define a new value, instead it moves a value. In case this // happens, discard. if (MTracker->readMLoc(L) != Use.ID) continue; // If a different debug instruction defined the variable value / location // since the start of the block, don't materialize this use-before-def. if (!UseBeforeDefVariables.count(Use.Var)) continue; PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); } flushDbgValues(pos, nullptr); } /// Helper to move created DBG_VALUEs into Transfers collection. void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { if (PendingDbgValues.size() == 0) return; // Pick out the instruction start position. MachineBasicBlock::instr_iterator BundleStart; if (MBB && Pos == MBB->begin()) BundleStart = MBB->instr_begin(); else BundleStart = getBundleStart(Pos->getIterator()); Transfers.push_back({BundleStart, MBB, PendingDbgValues}); PendingDbgValues.clear(); } bool isEntryValueVariable(const DebugVariable &Var, const DIExpression *Expr) const { if (!Var.getVariable()->isParameter()) return false; if (Var.getInlinedAt()) return false; if (Expr->getNumElements() > 0) return false; return true; } bool isEntryValueValue(const ValueIDNum &Val) const { // Must be in entry block (block number zero), and be a PHI / live-in value. if (Val.getBlock() || !Val.isPHI()) return false; // Entry values must enter in a register. if (MTracker->isSpill(Val.getLoc())) return false; Register SP = TLI->getStackPointerRegisterToSaveRestore(); Register FP = TRI.getFrameRegister(MF); Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; return Reg != SP && Reg != FP; } bool recoverAsEntryValue(const DebugVariable &Var, DbgValueProperties &Prop, const ValueIDNum &Num) { // Is this variable location a candidate to be an entry value. First, // should we be trying this at all? if (!ShouldEmitDebugEntryValues) return false; // Is the value assigned to this variable still the entry value? if (!isEntryValueValue(Num)) return false; Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; // Is the variable appropriate for entry values (i.e., is a parameter). if (!isEntryValueVariable(Var, Prop.DIExpr) && !isSwiftAsyncContext(MF, Reg)) return false; // Emit a variable location using an entry value expression. DIExpression *NewExpr = DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); MachineOperand MO = MachineOperand::CreateReg(Reg, false); PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); return true; } /// Change a variable value after encountering a DBG_VALUE inside a block. void redefVar(const MachineInstr &MI) { DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), MI.getDebugLoc()->getInlinedAt()); DbgValueProperties Properties(MI); const MachineOperand &MO = MI.getOperand(0); // Ignore non-register locations, we don't transfer those. if (!MO.isReg() || MO.getReg() == 0) { auto It = ActiveVLocs.find(Var); if (It != ActiveVLocs.end()) { ActiveMLocs[It->second.Loc].erase(Var); ActiveVLocs.erase(It); } // Any use-before-defs no longer apply. UseBeforeDefVariables.erase(Var); return; } Register Reg = MO.getReg(); LocIdx NewLoc = MTracker->getRegMLoc(Reg); redefVar(MI, Properties, NewLoc); } /// Handle a change in variable location within a block. Terminate the /// variables current location, and record the value it now refers to, so /// that we can detect location transfers later on. void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, Optional<LocIdx> OptNewLoc) { DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), MI.getDebugLoc()->getInlinedAt()); // Any use-before-defs no longer apply. UseBeforeDefVariables.erase(Var); // Erase any previous location, auto It = ActiveVLocs.find(Var); if (It != ActiveVLocs.end()) ActiveMLocs[It->second.Loc].erase(Var); // If there _is_ no new location, all we had to do was erase. if (!OptNewLoc) return; LocIdx NewLoc = *OptNewLoc; // Check whether our local copy of values-by-location in #VarLocs is out of // date. Wipe old tracking data for the location if it's been clobbered in // the meantime. if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { for (auto &P : ActiveMLocs[NewLoc]) { ActiveVLocs.erase(P); } ActiveMLocs[NewLoc.asU64()].clear(); VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); } ActiveMLocs[NewLoc].insert(Var); if (It == ActiveVLocs.end()) { ActiveVLocs.insert( std::make_pair(Var, LocAndProperties{NewLoc, Properties})); } else { It->second.Loc = NewLoc; It->second.Properties = Properties; } } /// Account for a location \p mloc being clobbered. Examine the variable /// locations that will be terminated: and try to recover them by using /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to /// explicitly terminate a location if it can't be recovered. void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, bool MakeUndef = true) { auto ActiveMLocIt = ActiveMLocs.find(MLoc); if (ActiveMLocIt == ActiveMLocs.end()) return; // What was the old variable value? ValueIDNum OldValue = VarLocs[MLoc.asU64()]; VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; // Examine the remaining variable locations: if we can find the same value // again, we can recover the location. Optional<LocIdx> NewLoc = None; for (auto Loc : MTracker->locations()) if (Loc.Value == OldValue) NewLoc = Loc.Idx; // If there is no location, and we weren't asked to make the variable // explicitly undef, then stop here. if (!NewLoc && !MakeUndef) { // Try and recover a few more locations with entry values. for (auto &Var : ActiveMLocIt->second) { auto &Prop = ActiveVLocs.find(Var)->second.Properties; recoverAsEntryValue(Var, Prop, OldValue); } flushDbgValues(Pos, nullptr); return; } // Examine all the variables based on this location. DenseSet<DebugVariable> NewMLocs; for (auto &Var : ActiveMLocIt->second) { auto ActiveVLocIt = ActiveVLocs.find(Var); // Re-state the variable location: if there's no replacement then NewLoc // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE // identifying the alternative location will be emitted. const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); // Update machine locations <=> variable locations maps. Defer updating // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. if (!NewLoc) { ActiveVLocs.erase(ActiveVLocIt); } else { ActiveVLocIt->second.Loc = *NewLoc; NewMLocs.insert(Var); } } // Commit any deferred ActiveMLoc changes. if (!NewMLocs.empty()) for (auto &Var : NewMLocs) ActiveMLocs[*NewLoc].insert(Var); // We lazily track what locations have which values; if we've found a new // location for the clobbered value, remember it. if (NewLoc) VarLocs[NewLoc->asU64()] = OldValue; flushDbgValues(Pos, nullptr); // Re-find ActiveMLocIt, iterator could have been invalidated. ActiveMLocIt = ActiveMLocs.find(MLoc); ActiveMLocIt->second.clear(); } /// Transfer variables based on \p Src to be based on \p Dst. This handles /// both register copies as well as spills and restores. Creates DBG_VALUEs /// describing the movement. void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { // Does Src still contain the value num we expect? If not, it's been // clobbered in the meantime, and our variable locations are stale. if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) return; // assert(ActiveMLocs[Dst].size() == 0); //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? // Move set of active variables from one location to another. auto MovingVars = ActiveMLocs[Src]; ActiveMLocs[Dst] = MovingVars; VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; // For each variable based on Src; create a location at Dst. for (auto &Var : MovingVars) { auto ActiveVLocIt = ActiveVLocs.find(Var); assert(ActiveVLocIt != ActiveVLocs.end()); ActiveVLocIt->second.Loc = Dst; MachineInstr *MI = MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); PendingDbgValues.push_back(MI); } ActiveMLocs[Src].clear(); flushDbgValues(Pos, nullptr); // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data // about the old location. if (EmulateOldLDV) VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; } MachineInstrBuilder emitMOLoc(const MachineOperand &MO, const DebugVariable &Var, const DbgValueProperties &Properties) { DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, Var.getVariable()->getScope(), const_cast<DILocation *>(Var.getInlinedAt())); auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); MIB.add(MO); if (Properties.Indirect) MIB.addImm(0); else MIB.addReg(0); MIB.addMetadata(Var.getVariable()); MIB.addMetadata(Properties.DIExpr); return MIB; } }; //===----------------------------------------------------------------------===// // Implementation //===----------------------------------------------------------------------===// ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; #ifndef NDEBUG void DbgValue::dump(const MLocTracker *MTrack) const { if (Kind == Const) { MO->dump(); } else if (Kind == NoVal) { dbgs() << "NoVal(" << BlockNo << ")"; } else if (Kind == VPHI) { dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; } else { assert(Kind == Def); dbgs() << MTrack->IDAsString(ID); } if (Properties.Indirect) dbgs() << " indir"; if (Properties.DIExpr) dbgs() << " " << *Properties.DIExpr; } #endif MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const TargetLowering &TLI) : MF(MF), TII(TII), TRI(TRI), TLI(TLI), LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { NumRegs = TRI.getNumRegs(); reset(); LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure // Always track SP. This avoids the implicit clobbering caused by regmasks // from affectings its values. (LiveDebugValues disbelieves calls and // regmasks that claim to clobber SP). Register SP = TLI.getStackPointerRegisterToSaveRestore(); if (SP) { unsigned ID = getLocID(SP); (void)lookupOrTrackRegister(ID); for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) SPAliases.insert(*RAI); } // Build some common stack positions -- full registers being spilt to the // stack. StackSlotIdxes.insert({{8, 0}, 0}); StackSlotIdxes.insert({{16, 0}, 1}); StackSlotIdxes.insert({{32, 0}, 2}); StackSlotIdxes.insert({{64, 0}, 3}); StackSlotIdxes.insert({{128, 0}, 4}); StackSlotIdxes.insert({{256, 0}, 5}); StackSlotIdxes.insert({{512, 0}, 6}); // Traverse all the subregister idxes, and ensure there's an index for them. // Duplicates are no problem: we're interested in their position in the // stack slot, we don't want to type the slot. for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { unsigned Size = TRI.getSubRegIdxSize(I); unsigned Offs = TRI.getSubRegIdxOffset(I); unsigned Idx = StackSlotIdxes.size(); // Some subregs have -1, -2 and so forth fed into their fields, to mean // special backend things. Ignore those. if (Size > 60000 || Offs > 60000) continue; StackSlotIdxes.insert({{Size, Offs}, Idx}); } for (auto &Idx : StackSlotIdxes) StackIdxesToPos[Idx.second] = Idx.first; NumSlotIdxes = StackSlotIdxes.size(); } LocIdx MLocTracker::trackRegister(unsigned ID) { assert(ID != 0); LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); LocIdxToIDNum.grow(NewIdx); LocIdxToLocID.grow(NewIdx); // Default: it's an mphi. ValueIDNum ValNum = {CurBB, 0, NewIdx}; // Was this reg ever touched by a regmask? for (const auto &MaskPair : reverse(Masks)) { if (MaskPair.first->clobbersPhysReg(ID)) { // There was an earlier def we skipped. ValNum = {CurBB, MaskPair.second, NewIdx}; break; } } LocIdxToIDNum[NewIdx] = ValNum; LocIdxToLocID[NewIdx] = ID; return NewIdx; } void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) { // Def any register we track have that isn't preserved. The regmask // terminates the liveness of a register, meaning its value can't be // relied upon -- we represent this by giving it a new value. for (auto Location : locations()) { unsigned ID = LocIdxToLocID[Location.Idx]; // Don't clobber SP, even if the mask says it's clobbered. if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) defReg(ID, CurBB, InstID); } Masks.push_back(std::make_pair(MO, InstID)); } SpillLocationNo MLocTracker::getOrTrackSpillLoc(SpillLoc L) { SpillLocationNo SpillID(SpillLocs.idFor(L)); if (SpillID.id() == 0) { // Spill location is untracked: create record for this one, and all // subregister slots too. SpillID = SpillLocationNo(SpillLocs.insert(L)); for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { unsigned L = getSpillIDWithIdx(SpillID, StackIdx); LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx LocIdxToIDNum.grow(Idx); LocIdxToLocID.grow(Idx); LocIDToLocIdx.push_back(Idx); LocIdxToLocID[Idx] = L; // Initialize to PHI value; corresponds to the location's live-in value // during transfer function construction. LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); } } return SpillID; } std::string MLocTracker::LocIdxToName(LocIdx Idx) const { unsigned ID = LocIdxToLocID[Idx]; if (ID >= NumRegs) { StackSlotPos Pos = locIDToSpillIdx(ID); ID -= NumRegs; unsigned Slot = ID / NumSlotIdxes; return Twine("slot ") .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) .concat(Twine(" offs ").concat(Twine(Pos.second)))))) .str(); } else { return TRI.getRegAsmName(ID).str(); } } std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { std::string DefName = LocIdxToName(Num.getLoc()); return Num.asString(DefName); } #ifndef NDEBUG LLVM_DUMP_METHOD void MLocTracker::dump() { for (auto Location : locations()) { std::string MLocName = LocIdxToName(Location.Value.getLoc()); std::string DefName = Location.Value.asString(MLocName); dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; } } LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { for (auto Location : locations()) { std::string foo = LocIdxToName(Location.Idx); dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; } } #endif MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, const DbgValueProperties &Properties) { DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, Var.getVariable()->getScope(), const_cast<DILocation *>(Var.getInlinedAt())); auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); const DIExpression *Expr = Properties.DIExpr; if (!MLoc) { // No location -> DBG_VALUE $noreg MIB.addReg(0); MIB.addReg(0); } else if (LocIdxToLocID[*MLoc] >= NumRegs) { unsigned LocID = LocIdxToLocID[*MLoc]; SpillLocationNo SpillID = locIDToSpill(LocID); StackSlotPos StackIdx = locIDToSpillIdx(LocID); unsigned short Offset = StackIdx.second; // TODO: support variables that are located in spill slots, with non-zero // offsets from the start of the spill slot. It would require some more // complex DIExpression calculations. This doesn't seem to be produced by // LLVM right now, so don't try and support it. // Accept no-subregister slots and subregisters where the offset is zero. // The consumer should already have type information to work out how large // the variable is. if (Offset == 0) { const SpillLoc &Spill = SpillLocs[SpillID.id()]; Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, Spill.SpillOffset); unsigned Base = Spill.SpillBase; MIB.addReg(Base); MIB.addImm(0); // Being on the stack makes this location indirect; if it was _already_ // indirect though, we need to add extra indirection. See this test for // a scenario where this happens: // llvm/test/DebugInfo/X86/spill-nontrivial-param.ll if (Properties.Indirect) { std::vector<uint64_t> Elts = {dwarf::DW_OP_deref}; Expr = DIExpression::append(Expr, Elts); } } else { // This is a stack location with a weird subregister offset: emit an undef // DBG_VALUE instead. MIB.addReg(0); MIB.addReg(0); } } else { // Non-empty, non-stack slot, must be a plain register. unsigned LocID = LocIdxToLocID[*MLoc]; MIB.addReg(LocID); if (Properties.Indirect) MIB.addImm(0); else MIB.addReg(0); } MIB.addMetadata(Var.getVariable()); MIB.addMetadata(Expr); return MIB; } /// Default construct and initialize the pass. InstrRefBasedLDV::InstrRefBasedLDV() {} bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { unsigned Reg = MTracker->LocIdxToLocID[L]; for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) if (CalleeSavedRegs.test(*RAI)) return true; return false; } //===----------------------------------------------------------------------===// // Debug Range Extension Implementation //===----------------------------------------------------------------------===// #ifndef NDEBUG // Something to restore in the future. // void InstrRefBasedLDV::printVarLocInMBB(..) #endif SpillLocationNo InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { assert(MI.hasOneMemOperand() && "Spill instruction does not have exactly one memory operand?"); auto MMOI = MI.memoperands_begin(); const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); assert(PVal->kind() == PseudoSourceValue::FixedStack && "Inconsistent memory operand in spill instruction"); int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); const MachineBasicBlock *MBB = MI.getParent(); Register Reg; StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); return MTracker->getOrTrackSpillLoc({Reg, Offset}); } Optional<LocIdx> InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { SpillLocationNo SpillLoc = extractSpillBaseRegAndOffset(MI); // Where in the stack slot is this value defined -- i.e., what size of value // is this? An important question, because it could be loaded into a register // from the stack at some point. Happily the memory operand will tell us // the size written to the stack. auto *MemOperand = *MI.memoperands_begin(); unsigned SizeInBits = MemOperand->getSizeInBits(); // Find that position in the stack indexes we're tracking. auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); if (IdxIt == MTracker->StackSlotIdxes.end()) // That index is not tracked. This is suprising, and unlikely to ever // occur, but the safe action is to indicate the variable is optimised out. return None; unsigned SpillID = MTracker->getSpillIDWithIdx(SpillLoc, IdxIt->second); return MTracker->getSpillMLoc(SpillID); } /// End all previous ranges related to @MI and start a new range from @MI /// if it is a DBG_VALUE instr. bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { if (!MI.isDebugValue()) return false; const DILocalVariable *Var = MI.getDebugVariable(); const DIExpression *Expr = MI.getDebugExpression(); const DILocation *DebugLoc = MI.getDebugLoc(); const DILocation *InlinedAt = DebugLoc->getInlinedAt(); assert(Var->isValidLocationForIntrinsic(DebugLoc) && "Expected inlined-at fields to agree"); DebugVariable V(Var, Expr, InlinedAt); DbgValueProperties Properties(MI); // If there are no instructions in this lexical scope, do no location tracking // at all, this variable shouldn't get a legitimate location range. auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); if (Scope == nullptr) return true; // handled it; by doing nothing // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to // contribute to locations in this block, but don't propagate further. // Interpret it like a DBG_VALUE $noreg. if (MI.isDebugValueList()) { if (VTracker) VTracker->defVar(MI, Properties, None); if (TTracker) TTracker->redefVar(MI, Properties, None); return true; } const MachineOperand &MO = MI.getOperand(0); // MLocTracker needs to know that this register is read, even if it's only // read by a debug inst. if (MO.isReg() && MO.getReg() != 0) { (void)MTracker->readReg(MO.getReg()); auto *Expr = MI.getDebugExpression(); const llvm::MachineFunction *MF = MI.getParent()->getParent(); if (!(Expr && Expr->isEntryValue()) && isSwiftAsyncContext(*MF, MO.getReg())) { // In Swift async functions entry values are preferred, since they // can be evaluated in both live frames and virtual backtraces. const_cast<MachineInstr *>(&MI)->getOperand(3).setMetadata( DIExpression::prepend(Expr, DIExpression::EntryValue)); } } // If we're preparing for the second analysis (variables), the machine value // locations are already solved, and we report this DBG_VALUE and the value // it refers to to VLocTracker. if (VTracker) { if (MO.isReg()) { // Feed defVar the new variable location, or if this is a // DBG_VALUE $noreg, feed defVar None. if (MO.getReg()) VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); else VTracker->defVar(MI, Properties, None); } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) { VTracker->defVar(MI, MI.getOperand(0)); } } // If performing final tracking of transfers, report this variable definition // to the TransferTracker too. if (TTracker) TTracker->redefVar(MI); return true; } bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, ValueIDNum **MLiveIns) { if (!MI.isDebugRef()) return false; // Only handle this instruction when we are building the variable value // transfer function. if (!VTracker) return false; unsigned InstNo = MI.getOperand(0).getImm(); unsigned OpNo = MI.getOperand(1).getImm(); const DILocalVariable *Var = MI.getDebugVariable(); const DIExpression *Expr = MI.getDebugExpression(); const DILocation *DebugLoc = MI.getDebugLoc(); const DILocation *InlinedAt = DebugLoc->getInlinedAt(); assert(Var->isValidLocationForIntrinsic(DebugLoc) && "Expected inlined-at fields to agree"); DebugVariable V(Var, Expr, InlinedAt); auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); if (Scope == nullptr) return true; // Handled by doing nothing. This variable is never in scope. const MachineFunction &MF = *MI.getParent()->getParent(); // Various optimizations may have happened to the value during codegen, // recorded in the value substitution table. Apply any substitutions to // the instruction / operand number in this DBG_INSTR_REF, and collect // any subregister extractions performed during optimization. // Create dummy substitution with Src set, for lookup. auto SoughtSub = MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); SmallVector<unsigned, 4> SeenSubregs; auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); while (LowerBoundIt != MF.DebugValueSubstitutions.end() && LowerBoundIt->Src == SoughtSub.Src) { std::tie(InstNo, OpNo) = LowerBoundIt->Dest; SoughtSub.Src = LowerBoundIt->Dest; if (unsigned Subreg = LowerBoundIt->Subreg) SeenSubregs.push_back(Subreg); LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); } // Default machine value number is <None> -- if no instruction defines // the corresponding value, it must have been optimized out. Optional<ValueIDNum> NewID = None; // Try to lookup the instruction number, and find the machine value number // that it defines. It could be an instruction, or a PHI. auto InstrIt = DebugInstrNumToInstr.find(InstNo); auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), DebugPHINumToValue.end(), InstNo); if (InstrIt != DebugInstrNumToInstr.end()) { const MachineInstr &TargetInstr = *InstrIt->second.first; uint64_t BlockNo = TargetInstr.getParent()->getNumber(); // Pick out the designated operand. It might be a memory reference, if // a register def was folded into a stack store. if (OpNo == MachineFunction::DebugOperandMemNumber && TargetInstr.hasOneMemOperand()) { Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); if (L) NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); } else if (OpNo != MachineFunction::DebugOperandMemNumber) { assert(OpNo < TargetInstr.getNumOperands()); const MachineOperand &MO = TargetInstr.getOperand(OpNo); // Today, this can only be a register. assert(MO.isReg() && MO.isDef()); unsigned LocID = MTracker->getLocID(MO.getReg()); LocIdx L = MTracker->LocIDToLocIdx[LocID]; NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); } // else: NewID is left as None. } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { // It's actually a PHI value. Which value it is might not be obvious, use // the resolver helper to find out. NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, MI, InstNo); } // Apply any subregister extractions, in reverse. We might have seen code // like this: // CALL64 @foo, implicit-def $rax // %0:gr64 = COPY $rax // %1:gr32 = COPY %0.sub_32bit // %2:gr16 = COPY %1.sub_16bit // %3:gr8 = COPY %2.sub_8bit // In which case each copy would have been recorded as a substitution with // a subregister qualifier. Apply those qualifiers now. if (NewID && !SeenSubregs.empty()) { unsigned Offset = 0; unsigned Size = 0; // Look at each subregister that we passed through, and progressively // narrow in, accumulating any offsets that occur. Substitutions should // only ever be the same or narrower width than what they read from; // iterate in reverse order so that we go from wide to small. for (unsigned Subreg : reverse(SeenSubregs)) { unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); Offset += ThisOffset; Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); } // If that worked, look for an appropriate subregister with the register // where the define happens. Don't look at values that were defined during // a stack write: we can't currently express register locations within // spills. LocIdx L = NewID->getLoc(); if (NewID && !MTracker->isSpill(L)) { // Find the register class for the register where this def happened. // FIXME: no index for this? Register Reg = MTracker->LocIdxToLocID[L]; const TargetRegisterClass *TRC = nullptr; for (auto *TRCI : TRI->regclasses()) if (TRCI->contains(Reg)) TRC = TRCI; assert(TRC && "Couldn't find target register class?"); // If the register we have isn't the right size or in the right place, // Try to find a subregister inside it. unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); if (Size != MainRegSize || Offset) { // Enumerate all subregisters, searching. Register NewReg = 0; for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); if (SubregSize == Size && SubregOffset == Offset) { NewReg = *SRI; break; } } // If we didn't find anything: there's no way to express our value. if (!NewReg) { NewID = None; } else { // Re-state the value as being defined within the subregister // that we found. LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); } } } else { // If we can't handle subregisters, unset the new value. NewID = None; } } // We, we have a value number or None. Tell the variable value tracker about // it. The rest of this LiveDebugValues implementation acts exactly the same // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that // aren't immediately available). DbgValueProperties Properties(Expr, false); VTracker->defVar(MI, Properties, NewID); // If we're on the final pass through the function, decompose this INSTR_REF // into a plain DBG_VALUE. if (!TTracker) return true; // Pick a location for the machine value number, if such a location exists. // (This information could be stored in TransferTracker to make it faster). Optional<LocIdx> FoundLoc = None; for (auto Location : MTracker->locations()) { LocIdx CurL = Location.Idx; ValueIDNum ID = MTracker->readMLoc(CurL); if (NewID && ID == NewID) { // If this is the first location with that value, pick it. Otherwise, // consider whether it's a "longer term" location. if (!FoundLoc) { FoundLoc = CurL; continue; } if (MTracker->isSpill(CurL)) FoundLoc = CurL; // Spills are a longer term location. else if (!MTracker->isSpill(*FoundLoc) && !MTracker->isSpill(CurL) && !isCalleeSaved(*FoundLoc) && isCalleeSaved(CurL)) FoundLoc = CurL; // Callee saved regs are longer term than normal. } } // Tell transfer tracker that the variable value has changed. TTracker->redefVar(MI, Properties, FoundLoc); // If there was a value with no location; but the value is defined in a // later instruction in this block, this is a block-local use-before-def. if (!FoundLoc && NewID && NewID->getBlock() == CurBB && NewID->getInst() > CurInst) TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. // This DBG_VALUE is potentially a $noreg / undefined location, if // FoundLoc is None. // (XXX -- could morph the DBG_INSTR_REF in the future). MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); TTracker->PendingDbgValues.push_back(DbgMI); TTracker->flushDbgValues(MI.getIterator(), nullptr); return true; } bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { if (!MI.isDebugPHI()) return false; // Analyse these only when solving the machine value location problem. if (VTracker || TTracker) return true; // First operand is the value location, either a stack slot or register. // Second is the debug instruction number of the original PHI. const MachineOperand &MO = MI.getOperand(0); unsigned InstrNum = MI.getOperand(1).getImm(); if (MO.isReg()) { // The value is whatever's currently in the register. Read and record it, // to be analysed later. Register Reg = MO.getReg(); ValueIDNum Num = MTracker->readReg(Reg); auto PHIRec = DebugPHIRecord( {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); DebugPHINumToValue.push_back(PHIRec); // Ensure this register is tracked. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) MTracker->lookupOrTrackRegister(*RAI); } else { // The value is whatever's in this stack slot. assert(MO.isFI()); unsigned FI = MO.getIndex(); // If the stack slot is dead, then this was optimized away. // FIXME: stack slot colouring should account for slots that get merged. if (MFI->isDeadObjectIndex(FI)) return true; // Identify this spill slot, ensure it's tracked. Register Base; StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); SpillLoc SL = {Base, Offs}; SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(SL); // Problem: what value should we extract from the stack? LLVM does not // record what size the last store to the slot was, and it would become // sketchy after stack slot colouring anyway. Take a look at what values // are stored on the stack, and pick the largest one that wasn't def'd // by a spill (i.e., the value most likely to have been def'd in a register // and then spilt. std::array<unsigned, 4> CandidateSizes = {64, 32, 16, 8}; Optional<ValueIDNum> Result = None; Optional<LocIdx> SpillLoc = None; for (unsigned CS : CandidateSizes) { unsigned SpillID = MTracker->getLocID(SpillNo, {CS, 0}); SpillLoc = MTracker->getSpillMLoc(SpillID); ValueIDNum Val = MTracker->readMLoc(*SpillLoc); // If this value was defined in it's own position, then it was probably // an aliasing index of a small value that was spilt. if (Val.getLoc() != SpillLoc->asU64()) { Result = Val; break; } } // If we didn't find anything, we're probably looking at a PHI, or a memory // store folded into an instruction. FIXME: Take a guess that's it's 64 // bits. This isn't ideal, but tracking the size that the spill is // "supposed" to be is more complex, and benefits a small number of // locations. if (!Result) { unsigned SpillID = MTracker->getLocID(SpillNo, {64, 0}); SpillLoc = MTracker->getSpillMLoc(SpillID); Result = MTracker->readMLoc(*SpillLoc); } // Record this DBG_PHI for later analysis. auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), *Result, *SpillLoc}); DebugPHINumToValue.push_back(DbgPHI); } return true; } void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { // Meta Instructions do not affect the debug liveness of any register they // define. if (MI.isImplicitDef()) { // Except when there's an implicit def, and the location it's defining has // no value number. The whole point of an implicit def is to announce that // the register is live, without be specific about it's value. So define // a value if there isn't one already. ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); // Has a legitimate value -> ignore the implicit def. if (Num.getLoc() != 0) return; // Otherwise, def it here. } else if (MI.isMetaInstruction()) return; // We always ignore SP defines on call instructions, they don't actually // change the value of the stack pointer... except for win32's _chkstk. This // is rare: filter quickly for the common case (no stack adjustments, not a // call, etc). If it is a call that modifies SP, recognise the SP register // defs. bool CallChangesSP = false; if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) CallChangesSP = true; // Test whether we should ignore a def of this register due to it being part // of the stack pointer. auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { if (CallChangesSP) return false; return MI.isCall() && MTracker->SPAliases.count(R); }; // Find the regs killed by MI, and find regmasks of preserved regs. // Max out the number of statically allocated elements in `DeadRegs`, as this // prevents fallback to std::set::count() operations. SmallSet<uint32_t, 32> DeadRegs; SmallVector<const uint32_t *, 4> RegMasks; SmallVector<const MachineOperand *, 4> RegMaskPtrs; for (const MachineOperand &MO : MI.operands()) { // Determine whether the operand is a register def. if (MO.isReg() && MO.isDef() && MO.getReg() && Register::isPhysicalRegister(MO.getReg()) && !IgnoreSPAlias(MO.getReg())) { // Remove ranges of all aliased registers. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) // FIXME: Can we break out of this loop early if no insertion occurs? DeadRegs.insert(*RAI); } else if (MO.isRegMask()) { RegMasks.push_back(MO.getRegMask()); RegMaskPtrs.push_back(&MO); } } // Tell MLocTracker about all definitions, of regmasks and otherwise. for (uint32_t DeadReg : DeadRegs) MTracker->defReg(DeadReg, CurBB, CurInst); for (auto *MO : RegMaskPtrs) MTracker->writeRegMask(MO, CurBB, CurInst); // If this instruction writes to a spill slot, def that slot. if (hasFoldedStackStore(MI)) { SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI); for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I); LocIdx L = MTracker->getSpillMLoc(SpillID); MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); } } if (!TTracker) return; // When committing variable values to locations: tell transfer tracker that // we've clobbered things. It may be able to recover the variable from a // different location. // Inform TTracker about any direct clobbers. for (uint32_t DeadReg : DeadRegs) { LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); TTracker->clobberMloc(Loc, MI.getIterator(), false); } // Look for any clobbers performed by a register mask. Only test locations // that are actually being tracked. for (auto L : MTracker->locations()) { // Stack locations can't be clobbered by regmasks. if (MTracker->isSpill(L.Idx)) continue; Register Reg = MTracker->LocIdxToLocID[L.Idx]; if (IgnoreSPAlias(Reg)) continue; for (auto *MO : RegMaskPtrs) if (MO->clobbersPhysReg(Reg)) TTracker->clobberMloc(L.Idx, MI.getIterator(), false); } // Tell TTracker about any folded stack store. if (hasFoldedStackStore(MI)) { SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI); for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I); LocIdx L = MTracker->getSpillMLoc(SpillID); TTracker->clobberMloc(L, MI.getIterator(), true); } } } void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { // In all circumstances, re-def all aliases. It's definitely a new value now. for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) MTracker->defReg(*RAI, CurBB, CurInst); ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); MTracker->setReg(DstRegNum, SrcValue); // Copy subregisters from one location to another. for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { unsigned SrcSubReg = SRI.getSubReg(); unsigned SubRegIdx = SRI.getSubRegIndex(); unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); if (!DstSubReg) continue; // Do copy. There are two matching subregisters, the source value should // have been def'd when the super-reg was, the latter might not be tracked // yet. // This will force SrcSubReg to be tracked, if it isn't yet. Will read // mphi values if it wasn't tracked. LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); (void)SrcL; (void)DstL; ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); MTracker->setReg(DstSubReg, CpyValue); } } bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, MachineFunction *MF) { // TODO: Handle multiple stores folded into one. if (!MI.hasOneMemOperand()) return false; // Reject any memory operand that's aliased -- we can't guarantee its value. auto MMOI = MI.memoperands_begin(); const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); if (PVal->isAliased(MFI)) return false; if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) return false; // This is not a spill instruction, since no valid size was // returned from either function. return true; } bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, MachineFunction *MF, unsigned &Reg) { if (!isSpillInstruction(MI, MF)) return false; int FI; Reg = TII->isStoreToStackSlotPostFE(MI, FI); return Reg != 0; } Optional<SpillLocationNo> InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, MachineFunction *MF, unsigned &Reg) { if (!MI.hasOneMemOperand()) return None; // FIXME: Handle folded restore instructions with more than one memory // operand. if (MI.getRestoreSize(TII)) { Reg = MI.getOperand(0).getReg(); return extractSpillBaseRegAndOffset(MI); } return None; } bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { // XXX -- it's too difficult to implement VarLocBasedImpl's stack location // limitations under the new model. Therefore, when comparing them, compare // versions that don't attempt spills or restores at all. if (EmulateOldLDV) return false; // Strictly limit ourselves to plain loads and stores, not all instructions // that can access the stack. int DummyFI = -1; if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) return false; MachineFunction *MF = MI.getMF(); unsigned Reg; LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); // Strictly limit ourselves to plain loads and stores, not all instructions // that can access the stack. int FIDummy; if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) return false; // First, if there are any DBG_VALUEs pointing at a spill slot that is // written to, terminate that variable location. The value in memory // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. if (isSpillInstruction(MI, MF)) { SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI); // Un-set this location and clobber, so that earlier locations don't // continue past this store. for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { unsigned SpillID = MTracker->getSpillIDWithIdx(Loc, SlotIdx); Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); if (!MLoc) continue; // We need to over-write the stack slot with something (here, a def at // this instruction) to ensure no values are preserved in this stack slot // after the spill. It also prevents TTracker from trying to recover the // location and re-installing it in the same place. ValueIDNum Def(CurBB, CurInst, *MLoc); MTracker->setMLoc(*MLoc, Def); if (TTracker) TTracker->clobberMloc(*MLoc, MI.getIterator()); } } // Try to recognise spill and restore instructions that may transfer a value. if (isLocationSpill(MI, MF, Reg)) { SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI); auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { auto ReadValue = MTracker->readReg(SrcReg); LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); MTracker->setMLoc(DstLoc, ReadValue); if (TTracker) { LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); } }; // Then, transfer subreg bits. for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { // Ensure this reg is tracked, (void)MTracker->lookupOrTrackRegister(*SRI); unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); DoTransfer(*SRI, SpillID); } // Directly lookup size of main source reg, and transfer. unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); DoTransfer(Reg, SpillID); } else { Optional<SpillLocationNo> OptLoc = isRestoreInstruction(MI, MF, Reg); if (!OptLoc) return false; SpillLocationNo Loc = *OptLoc; // Assumption: we're reading from the base of the stack slot, not some // offset into it. It seems very unlikely LLVM would ever generate // restores where this wasn't true. This then becomes a question of what // subregisters in the destination register line up with positions in the // stack slot. // Def all registers that alias the destination. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) MTracker->defReg(*RAI, CurBB, CurInst); // Now find subregisters within the destination register, and load values // from stack slot positions. auto DoTransfer = [&](Register DestReg, unsigned SpillID) { LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); auto ReadValue = MTracker->readMLoc(SrcIdx); MTracker->setReg(DestReg, ReadValue); if (TTracker) { LocIdx DstLoc = MTracker->getRegMLoc(DestReg); TTracker->transferMlocs(SrcIdx, DstLoc, MI.getIterator()); } }; for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); unsigned SpillID = MTracker->getLocID(Loc, Subreg); DoTransfer(*SRI, SpillID); } // Directly look up this registers slot idx by size, and transfer. unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); DoTransfer(Reg, SpillID); } return true; } bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { auto DestSrc = TII->isCopyInstr(MI); if (!DestSrc) return false; const MachineOperand *DestRegOp = DestSrc->Destination; const MachineOperand *SrcRegOp = DestSrc->Source; auto isCalleeSavedReg = [&](unsigned Reg) { for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) if (CalleeSavedRegs.test(*RAI)) return true; return false; }; Register SrcReg = SrcRegOp->getReg(); Register DestReg = DestRegOp->getReg(); // Ignore identity copies. Yep, these make it as far as LiveDebugValues. if (SrcReg == DestReg) return true; // For emulating VarLocBasedImpl: // We want to recognize instructions where destination register is callee // saved register. If register that could be clobbered by the call is // included, there would be a great chance that it is going to be clobbered // soon. It is more likely that previous register, which is callee saved, is // going to stay unclobbered longer, even if it is killed. // // For InstrRefBasedImpl, we can track multiple locations per value, so // ignore this condition. if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) return false; // InstrRefBasedImpl only followed killing copies. if (EmulateOldLDV && !SrcRegOp->isKill()) return false; // Copy MTracker info, including subregs if available. InstrRefBasedLDV::performCopy(SrcReg, DestReg); // Only produce a transfer of DBG_VALUE within a block where old LDV // would have. We might make use of the additional value tracking in some // other way, later. if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), MTracker->getRegMLoc(DestReg), MI.getIterator()); // VarLocBasedImpl would quit tracking the old location after copying. if (EmulateOldLDV && SrcReg != DestReg) MTracker->defReg(SrcReg, CurBB, CurInst); // Finally, the copy might have clobbered variables based on the destination // register. Tell TTracker about it, in case a backup location exists. if (TTracker) { for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); } } return true; } /// Accumulate a mapping between each DILocalVariable fragment and other /// fragments of that DILocalVariable which overlap. This reduces work during /// the data-flow stage from "Find any overlapping fragments" to "Check if the /// known-to-overlap fragments are present". /// \param MI A previously unprocessed debug instruction to analyze for /// fragment usage. void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { assert(MI.isDebugValue() || MI.isDebugRef()); DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), MI.getDebugLoc()->getInlinedAt()); FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); // If this is the first sighting of this variable, then we are guaranteed // there are currently no overlapping fragments either. Initialize the set // of seen fragments, record no overlaps for the current one, and return. auto SeenIt = SeenFragments.find(MIVar.getVariable()); if (SeenIt == SeenFragments.end()) { SmallSet<FragmentInfo, 4> OneFragment; OneFragment.insert(ThisFragment); SeenFragments.insert({MIVar.getVariable(), OneFragment}); OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); return; } // If this particular Variable/Fragment pair already exists in the overlap // map, it has already been accounted for. auto IsInOLapMap = OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); if (!IsInOLapMap.second) return; auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; auto &AllSeenFragments = SeenIt->second; // Otherwise, examine all other seen fragments for this variable, with "this" // fragment being a previously unseen fragment. Record any pair of // overlapping fragments. for (auto &ASeenFragment : AllSeenFragments) { // Does this previously seen fragment overlap? if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { // Yes: Mark the current fragment as being overlapped. ThisFragmentsOverlaps.push_back(ASeenFragment); // Mark the previously seen fragment as being overlapped by the current // one. auto ASeenFragmentsOverlaps = OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); assert(ASeenFragmentsOverlaps != OverlapFragments.end() && "Previously seen var fragment has no vector of overlaps"); ASeenFragmentsOverlaps->second.push_back(ThisFragment); } } AllSeenFragments.insert(ThisFragment); } void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts, ValueIDNum **MLiveIns) { // Try to interpret an MI as a debug or transfer instruction. Only if it's // none of these should we interpret it's register defs as new value // definitions. if (transferDebugValue(MI)) return; if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) return; if (transferDebugPHI(MI)) return; if (transferRegisterCopy(MI)) return; if (transferSpillOrRestoreInst(MI)) return; transferRegisterDef(MI); } void InstrRefBasedLDV::produceMLocTransferFunction( MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, unsigned MaxNumBlocks) { // Because we try to optimize around register mask operands by ignoring regs // that aren't currently tracked, we set up something ugly for later: RegMask // operands that are seen earlier than the first use of a register, still need // to clobber that register in the transfer function. But this information // isn't actively recorded. Instead, we track each RegMask used in each block, // and accumulated the clobbered but untracked registers in each block into // the following bitvector. Later, if new values are tracked, we can add // appropriate clobbers. SmallVector<BitVector, 32> BlockMasks; BlockMasks.resize(MaxNumBlocks); // Reserve one bit per register for the masks described above. unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); for (auto &BV : BlockMasks) BV.resize(TRI->getNumRegs(), true); // Step through all instructions and inhale the transfer function. for (auto &MBB : MF) { // Object fields that are read by trackers to know where we are in the // function. CurBB = MBB.getNumber(); CurInst = 1; // Set all machine locations to a PHI value. For transfer function // production only, this signifies the live-in value to the block. MTracker->reset(); MTracker->setMPhis(CurBB); // Step through each instruction in this block. for (auto &MI : MBB) { process(MI); // Also accumulate fragment map. if (MI.isDebugValue() || MI.isDebugRef()) accumulateFragmentMap(MI); // Create a map from the instruction number (if present) to the // MachineInstr and its position. if (uint64_t InstrNo = MI.peekDebugInstrNum()) { auto InstrAndPos = std::make_pair(&MI, CurInst); auto InsertResult = DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); // There should never be duplicate instruction numbers. assert(InsertResult.second); (void)InsertResult; } ++CurInst; } // Produce the transfer function, a map of machine location to new value. If // any machine location has the live-in phi value from the start of the // block, it's live-through and doesn't need recording in the transfer // function. for (auto Location : MTracker->locations()) { LocIdx Idx = Location.Idx; ValueIDNum &P = Location.Value; if (P.isPHI() && P.getLoc() == Idx.asU64()) continue; // Insert-or-update. auto &TransferMap = MLocTransfer[CurBB]; auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); if (!Result.second) Result.first->second = P; } // Accumulate any bitmask operands into the clobberred reg mask for this // block. for (auto &P : MTracker->Masks) { BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); } } // Compute a bitvector of all the registers that are tracked in this block. BitVector UsedRegs(TRI->getNumRegs()); for (auto Location : MTracker->locations()) { unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; // Ignore stack slots, and aliases of the stack pointer. if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) continue; UsedRegs.set(ID); } // Check that any regmask-clobber of a register that gets tracked, is not // live-through in the transfer function. It needs to be clobbered at the // very least. for (unsigned int I = 0; I < MaxNumBlocks; ++I) { BitVector &BV = BlockMasks[I]; BV.flip(); BV &= UsedRegs; // This produces all the bits that we clobber, but also use. Check that // they're all clobbered or at least set in the designated transfer // elem. for (unsigned Bit : BV.set_bits()) { unsigned ID = MTracker->getLocID(Bit); LocIdx Idx = MTracker->LocIDToLocIdx[ID]; auto &TransferMap = MLocTransfer[I]; // Install a value representing the fact that this location is effectively // written to in this block. As there's no reserved value, instead use // a value number that is never generated. Pick the value number for the // first instruction in the block, def'ing this location, which we know // this block never used anyway. ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); if (!Result.second) { ValueIDNum &ValueID = Result.first->second; if (ValueID.getBlock() == I && ValueID.isPHI()) // It was left as live-through. Set it to clobbered. ValueID = NotGeneratedNum; } } } } bool InstrRefBasedLDV::mlocJoin( MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, ValueIDNum **OutLocs, ValueIDNum *InLocs) { LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); bool Changed = false; // Handle value-propagation when control flow merges on entry to a block. For // any location without a PHI already placed, the location has the same value // as its predecessors. If a PHI is placed, test to see whether it's now a // redundant PHI that we can eliminate. SmallVector<const MachineBasicBlock *, 8> BlockOrders; for (auto Pred : MBB.predecessors()) BlockOrders.push_back(Pred); // Visit predecessors in RPOT order. auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { return BBToOrder.find(A)->second < BBToOrder.find(B)->second; }; llvm::sort(BlockOrders, Cmp); // Skip entry block. if (BlockOrders.size() == 0) return false; // Step through all machine locations, look at each predecessor and test // whether we can eliminate redundant PHIs. for (auto Location : MTracker->locations()) { LocIdx Idx = Location.Idx; // Pick out the first predecessors live-out value for this location. It's // guaranteed to not be a backedge, as we order by RPO. ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; // If we've already eliminated a PHI here, do no further checking, just // propagate the first live-in value into this block. if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { if (InLocs[Idx.asU64()] != FirstVal) { InLocs[Idx.asU64()] = FirstVal; Changed |= true; } continue; } // We're now examining a PHI to see whether it's un-necessary. Loop around // the other live-in values and test whether they're all the same. bool Disagree = false; for (unsigned int I = 1; I < BlockOrders.size(); ++I) { const MachineBasicBlock *PredMBB = BlockOrders[I]; const ValueIDNum &PredLiveOut = OutLocs[PredMBB->getNumber()][Idx.asU64()]; // Incoming values agree, continue trying to eliminate this PHI. if (FirstVal == PredLiveOut) continue; // We can also accept a PHI value that feeds back into itself. if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) continue; // Live-out of a predecessor disagrees with the first predecessor. Disagree = true; } // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. if (!Disagree) { InLocs[Idx.asU64()] = FirstVal; Changed |= true; } } // TODO: Reimplement NumInserted and NumRemoved. return Changed; } void InstrRefBasedLDV::findStackIndexInterference( SmallVectorImpl<unsigned> &Slots) { // We could spend a bit of time finding the exact, minimal, set of stack // indexes that interfere with each other, much like reg units. Or, we can // rely on the fact that: // * The smallest / lowest index will interfere with everything at zero // offset, which will be the largest set of registers, // * Most indexes with non-zero offset will end up being interference units // anyway. // So just pick those out and return them. // We can rely on a single-byte stack index existing already, because we // initialize them in MLocTracker. auto It = MTracker->StackSlotIdxes.find({8, 0}); assert(It != MTracker->StackSlotIdxes.end()); Slots.push_back(It->second); // Find anything that has a non-zero offset and add that too. for (auto &Pair : MTracker->StackSlotIdxes) { // Is offset zero? If so, ignore. if (!Pair.first.second) continue; Slots.push_back(Pair.second); } } void InstrRefBasedLDV::placeMLocPHIs( MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { SmallVector<unsigned, 4> StackUnits; findStackIndexInterference(StackUnits); // To avoid repeatedly running the PHI placement algorithm, leverage the // fact that a def of register MUST also def its register units. Find the // units for registers, place PHIs for them, and then replicate them for // aliasing registers. Some inputs that are never def'd (DBG_PHIs of // arguments) don't lead to register units being tracked, just place PHIs for // those registers directly. Stack slots have their own form of "unit", // store them to one side. SmallSet<Register, 32> RegUnitsToPHIUp; SmallSet<LocIdx, 32> NormalLocsToPHI; SmallSet<SpillLocationNo, 32> StackSlots; for (auto Location : MTracker->locations()) { LocIdx L = Location.Idx; if (MTracker->isSpill(L)) { StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); continue; } Register R = MTracker->LocIdxToLocID[L]; SmallSet<Register, 8> FoundRegUnits; bool AnyIllegal = false; for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ if (!MTracker->isRegisterTracked(*URoot)) { // Not all roots were loaded into the tracking map: this register // isn't actually def'd anywhere, we only read from it. Generate PHIs // for this reg, but don't iterate units. AnyIllegal = true; } else { FoundRegUnits.insert(*URoot); } } } if (AnyIllegal) { NormalLocsToPHI.insert(L); continue; } RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); } // Lambda to fetch PHIs for a given location, and write into the PHIBlocks // collection. SmallVector<MachineBasicBlock *, 32> PHIBlocks; auto CollectPHIsForLoc = [&](LocIdx L) { // Collect the set of defs. SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; for (unsigned int I = 0; I < OrderToBB.size(); ++I) { MachineBasicBlock *MBB = OrderToBB[I]; const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; if (TransferFunc.find(L) != TransferFunc.end()) DefBlocks.insert(MBB); } // The entry block defs the location too: it's the live-in / argument value. // Only insert if there are other defs though; everything is trivially live // through otherwise. if (!DefBlocks.empty()) DefBlocks.insert(&*MF.begin()); // Ask the SSA construction algorithm where we should put PHIs. Clear // anything that might have been hanging around from earlier. PHIBlocks.clear(); BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); }; auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { for (const MachineBasicBlock *MBB : PHIBlocks) MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); }; // For locations with no reg units, just place PHIs. for (LocIdx L : NormalLocsToPHI) { CollectPHIsForLoc(L); // Install those PHI values into the live-in value array. InstallPHIsAtLoc(L); } // For stack slots, calculate PHIs for the equivalent of the units, then // install for each index. for (SpillLocationNo Slot : StackSlots) { for (unsigned Idx : StackUnits) { unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); LocIdx L = MTracker->getSpillMLoc(SpillID); CollectPHIsForLoc(L); InstallPHIsAtLoc(L); // Find anything that aliases this stack index, install PHIs for it too. unsigned Size, Offset; std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; for (auto &Pair : MTracker->StackSlotIdxes) { unsigned ThisSize, ThisOffset; std::tie(ThisSize, ThisOffset) = Pair.first; if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) continue; unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); LocIdx ThisL = MTracker->getSpillMLoc(ThisID); InstallPHIsAtLoc(ThisL); } } } // For reg units, place PHIs, and then place them for any aliasing registers. for (Register R : RegUnitsToPHIUp) { LocIdx L = MTracker->lookupOrTrackRegister(R); CollectPHIsForLoc(L); // Install those PHI values into the live-in value array. InstallPHIsAtLoc(L); // Now find aliases and install PHIs for those. for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { // Super-registers that are "above" the largest register read/written by // the function will alias, but will not be tracked. if (!MTracker->isRegisterTracked(*RAI)) continue; LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); InstallPHIsAtLoc(AliasLoc); } } } void InstrRefBasedLDV::buildMLocValueMap( MachineFunction &MF, ValueIDNum **MInLocs, ValueIDNum **MOutLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { std::priority_queue<unsigned int, std::vector<unsigned int>, std::greater<unsigned int>> Worklist, Pending; // We track what is on the current and pending worklist to avoid inserting // the same thing twice. We could avoid this with a custom priority queue, // but this is probably not worth it. SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; // Initialize worklist with every block to be visited. Also produce list of // all blocks. SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; for (unsigned int I = 0; I < BBToOrder.size(); ++I) { Worklist.push(I); OnWorklist.insert(OrderToBB[I]); AllBlocks.insert(OrderToBB[I]); } // Initialize entry block to PHIs. These represent arguments. for (auto Location : MTracker->locations()) MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); MTracker->reset(); // Start by placing PHIs, using the usual SSA constructor algorithm. Consider // any machine-location that isn't live-through a block to be def'd in that // block. placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); // Propagate values to eliminate redundant PHIs. At the same time, this // produces the table of Block x Location => Value for the entry to each // block. // The kind of PHIs we can eliminate are, for example, where one path in a // conditional spills and restores a register, and the register still has // the same value once control flow joins, unbeknowns to the PHI placement // code. Propagating values allows us to identify such un-necessary PHIs and // remove them. SmallPtrSet<const MachineBasicBlock *, 16> Visited; while (!Worklist.empty() || !Pending.empty()) { // Vector for storing the evaluated block transfer function. SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; while (!Worklist.empty()) { MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; CurBB = MBB->getNumber(); Worklist.pop(); // Join the values in all predecessor blocks. bool InLocsChanged; InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); InLocsChanged |= Visited.insert(MBB).second; // Don't examine transfer function if we've visited this loc at least // once, and inlocs haven't changed. if (!InLocsChanged) continue; // Load the current set of live-ins into MLocTracker. MTracker->loadFromArray(MInLocs[CurBB], CurBB); // Each element of the transfer function can be a new def, or a read of // a live-in value. Evaluate each element, and store to "ToRemap". ToRemap.clear(); for (auto &P : MLocTransfer[CurBB]) { if (P.second.getBlock() == CurBB && P.second.isPHI()) { // This is a movement of whatever was live in. Read it. ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); ToRemap.push_back(std::make_pair(P.first, NewID)); } else { // It's a def. Just set it. assert(P.second.getBlock() == CurBB); ToRemap.push_back(std::make_pair(P.first, P.second)); } } // Commit the transfer function changes into mloc tracker, which // transforms the contents of the MLocTracker into the live-outs. for (auto &P : ToRemap) MTracker->setMLoc(P.first, P.second); // Now copy out-locs from mloc tracker into out-loc vector, checking // whether changes have occurred. These changes can have come from both // the transfer function, and mlocJoin. bool OLChanged = false; for (auto Location : MTracker->locations()) { OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; } MTracker->reset(); // No need to examine successors again if out-locs didn't change. if (!OLChanged) continue; // All successors should be visited: put any back-edges on the pending // list for the next pass-through, and any other successors to be // visited this pass, if they're not going to be already. for (auto s : MBB->successors()) { // Does branching to this successor represent a back-edge? if (BBToOrder[s] > BBToOrder[MBB]) { // No: visit it during this dataflow iteration. if (OnWorklist.insert(s).second) Worklist.push(BBToOrder[s]); } else { // Yes: visit it on the next iteration. if (OnPending.insert(s).second) Pending.push(BBToOrder[s]); } } } Worklist.swap(Pending); std::swap(OnPending, OnWorklist); OnPending.clear(); // At this point, pending must be empty, since it was just the empty // worklist assert(Pending.empty() && "Pending should be empty"); } // Once all the live-ins don't change on mlocJoin(), we've eliminated all // redundant PHIs. } // Boilerplate for feeding MachineBasicBlocks into IDF calculator. Provide // template specialisations for graph traits and a successor enumerator. namespace llvm { template <> struct GraphTraits<MachineBasicBlock> { using NodeRef = MachineBasicBlock *; using ChildIteratorType = MachineBasicBlock::succ_iterator; static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; } static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); } static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); } }; template <> struct GraphTraits<const MachineBasicBlock> { using NodeRef = const MachineBasicBlock *; using ChildIteratorType = MachineBasicBlock::const_succ_iterator; static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; } static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); } static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); } }; using MachineDomTreeBase = DomTreeBase<MachineBasicBlock>::NodeType; using MachineDomTreeChildGetter = typename IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false>; namespace IDFCalculatorDetail { template <> typename MachineDomTreeChildGetter::ChildrenTy MachineDomTreeChildGetter::get(const NodeRef &N) { return {N->succ_begin(), N->succ_end()}; } } // namespace IDFCalculatorDetail } // namespace llvm void InstrRefBasedLDV::BlockPHIPlacement( const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { // Apply IDF calculator to the designated set of location defs, storing // required PHIs into PHIBlocks. Uses the dominator tree stored in the // InstrRefBasedLDV object. IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false> foo; IDFCalculatorBase<MachineDomTreeBase, false> IDF(DomTree->getBase(), foo); IDF.setLiveInBlocks(AllBlocks); IDF.setDefiningBlocks(DefBlocks); IDF.calculate(PHIBlocks); } Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( const MachineBasicBlock &MBB, const DebugVariable &Var, const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { // Collect a set of locations from predecessor where its live-out value can // be found. SmallVector<SmallVector<LocIdx, 4>, 8> Locs; SmallVector<const DbgValueProperties *, 4> Properties; unsigned NumLocs = MTracker->getNumLocs(); // No predecessors means no PHIs. if (BlockOrders.empty()) return None; for (auto p : BlockOrders) { unsigned ThisBBNum = p->getNumber(); auto OutValIt = LiveOuts.find(p); if (OutValIt == LiveOuts.end()) // If we have a predecessor not in scope, we'll never find a PHI position. return None; const DbgValue &OutVal = *OutValIt->second; if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) // Consts and no-values cannot have locations we can join on. return None; Properties.push_back(&OutVal.Properties); // Create new empty vector of locations. Locs.resize(Locs.size() + 1); // If the live-in value is a def, find the locations where that value is // present. Do the same for VPHIs where we know the VPHI value. if (OutVal.Kind == DbgValue::Def || (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && OutVal.ID != ValueIDNum::EmptyValue)) { ValueIDNum ValToLookFor = OutVal.ID; // Search the live-outs of the predecessor for the specified value. for (unsigned int I = 0; I < NumLocs; ++I) { if (MOutLocs[ThisBBNum][I] == ValToLookFor) Locs.back().push_back(LocIdx(I)); } } else { assert(OutVal.Kind == DbgValue::VPHI); // For VPHIs where we don't know the location, we definitely can't find // a join loc. if (OutVal.BlockNo != MBB.getNumber()) return None; // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. // a value that's live-through the whole loop. (It has to be a backedge, // because a block can't dominate itself). We can accept as a PHI location // any location where the other predecessors agree, _and_ the machine // locations feed back into themselves. Therefore, add all self-looping // machine-value PHI locations. for (unsigned int I = 0; I < NumLocs; ++I) { ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); if (MOutLocs[ThisBBNum][I] == MPHI) Locs.back().push_back(LocIdx(I)); } } } // We should have found locations for all predecessors, or returned. assert(Locs.size() == BlockOrders.size()); // Check that all properties are the same. We can't pick a location if they're // not. const DbgValueProperties *Properties0 = Properties[0]; for (auto *Prop : Properties) if (*Prop != *Properties0) return None; // Starting with the first set of locations, take the intersection with // subsequent sets. SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; for (unsigned int I = 1; I < Locs.size(); ++I) { auto &LocVec = Locs[I]; SmallVector<LocIdx, 4> NewCandidates; std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); CandidateLocs = NewCandidates; } if (CandidateLocs.empty()) return None; // We now have a set of LocIdxes that contain the right output value in // each of the predecessors. Pick the lowest; if there's a register loc, // that'll be it. LocIdx L = *CandidateLocs.begin(); // Return a PHI-value-number for the found location. ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; return PHIVal; } bool InstrRefBasedLDV::vlocJoin( MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, DbgValue &LiveIn) { LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); bool Changed = false; // Order predecessors by RPOT order, for exploring them in that order. SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { return BBToOrder[A] < BBToOrder[B]; }; llvm::sort(BlockOrders, Cmp); unsigned CurBlockRPONum = BBToOrder[&MBB]; // Collect all the incoming DbgValues for this variable, from predecessor // live-out values. SmallVector<InValueT, 8> Values; bool Bail = false; int BackEdgesStart = 0; for (auto p : BlockOrders) { // If the predecessor isn't in scope / to be explored, we'll never be // able to join any locations. if (!BlocksToExplore.contains(p)) { Bail = true; break; } // All Live-outs will have been initialized. DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; // Keep track of where back-edges begin in the Values vector. Relies on // BlockOrders being sorted by RPO. unsigned ThisBBRPONum = BBToOrder[p]; if (ThisBBRPONum < CurBlockRPONum) ++BackEdgesStart; Values.push_back(std::make_pair(p, &OutLoc)); } // If there were no values, or one of the predecessors couldn't have a // value, then give up immediately. It's not safe to produce a live-in // value. Leave as whatever it was before. if (Bail || Values.size() == 0) return false; // All (non-entry) blocks have at least one non-backedge predecessor. // Pick the variable value from the first of these, to compare against // all others. const DbgValue &FirstVal = *Values[0].second; // If the old live-in value is not a PHI then either a) no PHI is needed // here, or b) we eliminated the PHI that was here. If so, we can just // propagate in the first parent's incoming value. if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { Changed = LiveIn != FirstVal; if (Changed) LiveIn = FirstVal; return Changed; } // Scan for variable values that can never be resolved: if they have // different DIExpressions, different indirectness, or are mixed constants / // non-constants. for (auto &V : Values) { if (V.second->Properties != FirstVal.Properties) return false; if (V.second->Kind == DbgValue::NoVal) return false; if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) return false; } // Try to eliminate this PHI. Do the incoming values all agree? bool Disagree = false; for (auto &V : Values) { if (*V.second == FirstVal) continue; // No disagreement. // Eliminate if a backedge feeds a VPHI back into itself. if (V.second->Kind == DbgValue::VPHI && V.second->BlockNo == MBB.getNumber() && // Is this a backedge? std::distance(Values.begin(), &V) >= BackEdgesStart) continue; Disagree = true; } // No disagreement -> live-through value. if (!Disagree) { Changed = LiveIn != FirstVal; if (Changed) LiveIn = FirstVal; return Changed; } else { // Otherwise use a VPHI. DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); Changed = LiveIn != VPHI; if (Changed) LiveIn = VPHI; return Changed; } } void InstrRefBasedLDV::buildVLocValueMap(const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, ValueIDNum **MOutLocs, ValueIDNum **MInLocs, SmallVectorImpl<VLocTracker> &AllTheVLocs) { // This method is much like buildMLocValueMap: but focuses on a single // LexicalScope at a time. Pick out a set of blocks and variables that are // to have their value assignments solved, then run our dataflow algorithm // until a fixedpoint is reached. std::priority_queue<unsigned int, std::vector<unsigned int>, std::greater<unsigned int>> Worklist, Pending; SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; // The set of blocks we'll be examining. SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; // The order in which to examine them (RPO). SmallVector<MachineBasicBlock *, 8> BlockOrders; // RPO ordering function. auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { return BBToOrder[A] < BBToOrder[B]; }; LS.getMachineBasicBlocks(DILoc, BlocksToExplore); // A separate container to distinguish "blocks we're exploring" versus // "blocks that are potentially in scope. See comment at start of vlocJoin. SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore; // VarLoc LiveDebugValues tracks variable locations that are defined in // blocks not in scope. This is something we could legitimately ignore, but // lets allow it for now for the sake of coverage. BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); // We also need to propagate variable values through any artificial blocks // that immediately follow blocks in scope. DenseSet<const MachineBasicBlock *> ToAdd; // Helper lambda: For a given block in scope, perform a depth first search // of all the artificial successors, adding them to the ToAdd collection. auto AccumulateArtificialBlocks = [this, &ToAdd, &BlocksToExplore, &InScopeBlocks](const MachineBasicBlock *MBB) { // Depth-first-search state: each node is a block and which successor // we're currently exploring. SmallVector<std::pair<const MachineBasicBlock *, MachineBasicBlock::const_succ_iterator>, 8> DFS; // Find any artificial successors not already tracked. for (auto *succ : MBB->successors()) { if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ)) continue; if (!ArtificialBlocks.count(succ)) continue; ToAdd.insert(succ); DFS.push_back(std::make_pair(succ, succ->succ_begin())); } // Search all those blocks, depth first. while (!DFS.empty()) { const MachineBasicBlock *CurBB = DFS.back().first; MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; // Walk back if we've explored this blocks successors to the end. if (CurSucc == CurBB->succ_end()) { DFS.pop_back(); continue; } // If the current successor is artificial and unexplored, descend into // it. if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { ToAdd.insert(*CurSucc); DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin())); continue; } ++CurSucc; } }; // Search in-scope blocks and those containing a DBG_VALUE from this scope // for artificial successors. for (auto *MBB : BlocksToExplore) AccumulateArtificialBlocks(MBB); for (auto *MBB : InScopeBlocks) AccumulateArtificialBlocks(MBB); BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); InScopeBlocks.insert(ToAdd.begin(), ToAdd.end()); // Single block scope: not interesting! No propagation at all. Note that // this could probably go above ArtificialBlocks without damage, but // that then produces output differences from original-live-debug-values, // which propagates from a single block into many artificial ones. if (BlocksToExplore.size() == 1) return; // Convert a const set to a non-const set. LexicalScopes // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. // (Neither of them mutate anything). SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; for (const auto *MBB : BlocksToExplore) MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); // Picks out relevants blocks RPO order and sort them. for (auto *MBB : BlocksToExplore) BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); llvm::sort(BlockOrders, Cmp); unsigned NumBlocks = BlockOrders.size(); // Allocate some vectors for storing the live ins and live outs. Large. SmallVector<DbgValue, 32> LiveIns, LiveOuts; LiveIns.reserve(NumBlocks); LiveOuts.reserve(NumBlocks); // Initialize all values to start as NoVals. This signifies "it's live // through, but we don't know what it is". DbgValueProperties EmptyProperties(EmptyExpr, false); for (unsigned int I = 0; I < NumBlocks; ++I) { DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); LiveIns.push_back(EmptyDbgValue); LiveOuts.push_back(EmptyDbgValue); } // Produce by-MBB indexes of live-in/live-outs, to ease lookup within // vlocJoin. LiveIdxT LiveOutIdx, LiveInIdx; LiveOutIdx.reserve(NumBlocks); LiveInIdx.reserve(NumBlocks); for (unsigned I = 0; I < NumBlocks; ++I) { LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; LiveInIdx[BlockOrders[I]] = &LiveIns[I]; } // Loop over each variable and place PHIs for it, then propagate values // between blocks. This keeps the locality of working on one lexical scope at // at time, but avoids re-processing variable values because some other // variable has been assigned. for (auto &Var : VarsWeCareAbout) { // Re-initialize live-ins and live-outs, to clear the remains of previous // variables live-ins / live-outs. for (unsigned int I = 0; I < NumBlocks; ++I) { DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); LiveIns[I] = EmptyDbgValue; LiveOuts[I] = EmptyDbgValue; } // Place PHIs for variable values, using the LLVM IDF calculator. // Collect the set of blocks where variables are def'd. SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; if (TransferFunc.find(Var) != TransferFunc.end()) DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); } SmallVector<MachineBasicBlock *, 32> PHIBlocks; // Request the set of PHIs we should insert for this variable. BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); // Insert PHIs into the per-block live-in tables for this variable. for (MachineBasicBlock *PHIMBB : PHIBlocks) { unsigned BlockNo = PHIMBB->getNumber(); DbgValue *LiveIn = LiveInIdx[PHIMBB]; *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); } for (auto *MBB : BlockOrders) { Worklist.push(BBToOrder[MBB]); OnWorklist.insert(MBB); } // Iterate over all the blocks we selected, propagating the variables value. // This loop does two things: // * Eliminates un-necessary VPHIs in vlocJoin, // * Evaluates the blocks transfer function (i.e. variable assignments) and // stores the result to the blocks live-outs. // Always evaluate the transfer function on the first iteration, and when // the live-ins change thereafter. bool FirstTrip = true; while (!Worklist.empty() || !Pending.empty()) { while (!Worklist.empty()) { auto *MBB = OrderToBB[Worklist.top()]; CurBB = MBB->getNumber(); Worklist.pop(); auto LiveInsIt = LiveInIdx.find(MBB); assert(LiveInsIt != LiveInIdx.end()); DbgValue *LiveIn = LiveInsIt->second; // Join values from predecessors. Updates LiveInIdx, and writes output // into JoinedInLocs. bool InLocsChanged = vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); SmallVector<const MachineBasicBlock *, 8> Preds; for (const auto *Pred : MBB->predecessors()) Preds.push_back(Pred); // If this block's live-in value is a VPHI, try to pick a machine-value // for it. This makes the machine-value available and propagated // through all blocks by the time value propagation finishes. We can't // do this any earlier as it needs to read the block live-outs. if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { // There's a small possibility that on a preceeding path, a VPHI is // eliminated and transitions from VPHI-with-location to // live-through-value. As a result, the selected location of any VPHI // might change, so we need to re-compute it on each iteration. Optional<ValueIDNum> ValueNum = pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); if (ValueNum) { InLocsChanged |= LiveIn->ID != *ValueNum; LiveIn->ID = *ValueNum; } } if (!InLocsChanged && !FirstTrip) continue; DbgValue *LiveOut = LiveOutIdx[MBB]; bool OLChanged = false; // Do transfer function. auto &VTracker = AllTheVLocs[MBB->getNumber()]; auto TransferIt = VTracker.Vars.find(Var); if (TransferIt != VTracker.Vars.end()) { // Erase on empty transfer (DBG_VALUE $noreg). if (TransferIt->second.Kind == DbgValue::Undef) { DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); if (*LiveOut != NewVal) { *LiveOut = NewVal; OLChanged = true; } } else { // Insert new variable value; or overwrite. if (*LiveOut != TransferIt->second) { *LiveOut = TransferIt->second; OLChanged = true; } } } else { // Just copy live-ins to live-outs, for anything not transferred. if (*LiveOut != *LiveIn) { *LiveOut = *LiveIn; OLChanged = true; } } // If no live-out value changed, there's no need to explore further. if (!OLChanged) continue; // We should visit all successors. Ensure we'll visit any non-backedge // successors during this dataflow iteration; book backedge successors // to be visited next time around. for (auto s : MBB->successors()) { // Ignore out of scope / not-to-be-explored successors. if (LiveInIdx.find(s) == LiveInIdx.end()) continue; if (BBToOrder[s] > BBToOrder[MBB]) { if (OnWorklist.insert(s).second) Worklist.push(BBToOrder[s]); } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { Pending.push(BBToOrder[s]); } } } Worklist.swap(Pending); std::swap(OnWorklist, OnPending); OnPending.clear(); assert(Pending.empty()); FirstTrip = false; } // Save live-ins to output vector. Ignore any that are still marked as being // VPHIs with no location -- those are variables that we know the value of, // but are not actually available in the register file. for (auto *MBB : BlockOrders) { DbgValue *BlockLiveIn = LiveInIdx[MBB]; if (BlockLiveIn->Kind == DbgValue::NoVal) continue; if (BlockLiveIn->Kind == DbgValue::VPHI && BlockLiveIn->ID == ValueIDNum::EmptyValue) continue; if (BlockLiveIn->Kind == DbgValue::VPHI) BlockLiveIn->Kind = DbgValue::Def; assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == Var.getFragment() && "Fragment info missing during value prop"); Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); } } // Per-variable loop. BlockOrders.clear(); BlocksToExplore.clear(); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void InstrRefBasedLDV::dump_mloc_transfer( const MLocTransferMap &mloc_transfer) const { for (auto &P : mloc_transfer) { std::string foo = MTracker->LocIdxToName(P.first); std::string bar = MTracker->IDAsString(P.second); dbgs() << "Loc " << foo << " --> " << bar << "\n"; } } #endif void InstrRefBasedLDV::emitLocations( MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs, ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering, const TargetPassConfig &TPC) { TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); unsigned NumLocs = MTracker->getNumLocs(); // For each block, load in the machine value locations and variable value // live-ins, then step through each instruction in the block. New DBG_VALUEs // to be inserted will be created along the way. for (MachineBasicBlock &MBB : MF) { unsigned bbnum = MBB.getNumber(); MTracker->reset(); MTracker->loadFromArray(MInLocs[bbnum], bbnum); TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()], NumLocs); CurBB = bbnum; CurInst = 1; for (auto &MI : MBB) { process(MI, MOutLocs, MInLocs); TTracker->checkInstForNewValues(CurInst, MI.getIterator()); ++CurInst; } } // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer // in DWARF in different orders. Use the order that they appear when walking // through each block / each instruction, stored in AllVarsNumbering. auto OrderDbgValues = [&](const MachineInstr *A, const MachineInstr *B) -> bool { DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(), A->getDebugLoc()->getInlinedAt()); DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(), B->getDebugLoc()->getInlinedAt()); return AllVarsNumbering.find(VarA)->second < AllVarsNumbering.find(VarB)->second; }; // Go through all the transfers recorded in the TransferTracker -- this is // both the live-ins to a block, and any movements of values that happen // in the middle. for (auto &P : TTracker->Transfers) { // Sort them according to appearance order. llvm::sort(P.Insts, OrderDbgValues); // Insert either before or after the designated point... if (P.MBB) { MachineBasicBlock &MBB = *P.MBB; for (auto *MI : P.Insts) { MBB.insert(P.Pos, MI); } } else { // Terminators, like tail calls, can clobber things. Don't try and place // transfers after them. if (P.Pos->isTerminator()) continue; MachineBasicBlock &MBB = *P.Pos->getParent(); for (auto *MI : P.Insts) { MBB.insertAfterBundle(P.Pos, MI); } } } } void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { // Build some useful data structures. LLVMContext &Context = MF.getFunction().getContext(); EmptyExpr = DIExpression::get(Context, {}); auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { if (const DebugLoc &DL = MI.getDebugLoc()) return DL.getLine() != 0; return false; }; // Collect a set of all the artificial blocks. for (auto &MBB : MF) if (none_of(MBB.instrs(), hasNonArtificialLocation)) ArtificialBlocks.insert(&MBB); // Compute mappings of block <=> RPO order. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); unsigned int RPONumber = 0; for (MachineBasicBlock *MBB : RPOT) { OrderToBB[RPONumber] = MBB; BBToOrder[MBB] = RPONumber; BBNumToRPO[MBB->getNumber()] = RPONumber; ++RPONumber; } // Order value substitutions by their "source" operand pair, for quick lookup. llvm::sort(MF.DebugValueSubstitutions); #ifdef EXPENSIVE_CHECKS // As an expensive check, test whether there are any duplicate substitution // sources in the collection. if (MF.DebugValueSubstitutions.size() > 2) { for (auto It = MF.DebugValueSubstitutions.begin(); It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { assert(It->Src != std::next(It)->Src && "Duplicate variable location " "substitution seen"); } } #endif } /// Calculate the liveness information for the given machine function and /// extend ranges across basic blocks. bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree, TargetPassConfig *TPC, unsigned InputBBLimit, unsigned InputDbgValLimit) { // No subprogram means this function contains no debuginfo. if (!MF.getFunction().getSubprogram()) return false; LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); this->TPC = TPC; this->DomTree = DomTree; TRI = MF.getSubtarget().getRegisterInfo(); MRI = &MF.getRegInfo(); TII = MF.getSubtarget().getInstrInfo(); TFI = MF.getSubtarget().getFrameLowering(); TFI->getCalleeSaves(MF, CalleeSavedRegs); MFI = &MF.getFrameInfo(); LS.initialize(MF); const auto &STI = MF.getSubtarget(); AdjustsStackInCalls = MFI->adjustsStack() && STI.getFrameLowering()->stackProbeFunctionModifiesSP(); if (AdjustsStackInCalls) StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); MTracker = new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); VTracker = nullptr; TTracker = nullptr; SmallVector<MLocTransferMap, 32> MLocTransfer; SmallVector<VLocTracker, 8> vlocs; LiveInsT SavedLiveIns; int MaxNumBlocks = -1; for (auto &MBB : MF) MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); assert(MaxNumBlocks >= 0); ++MaxNumBlocks; MLocTransfer.resize(MaxNumBlocks); vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); SavedLiveIns.resize(MaxNumBlocks); initialSetup(MF); produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); // Allocate and initialize two array-of-arrays for the live-in and live-out // machine values. The outer dimension is the block number; while the inner // dimension is a LocIdx from MLocTracker. ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks]; ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks]; unsigned NumLocs = MTracker->getNumLocs(); for (int i = 0; i < MaxNumBlocks; ++i) { // These all auto-initialize to ValueIDNum::EmptyValue MOutLocs[i] = new ValueIDNum[NumLocs]; MInLocs[i] = new ValueIDNum[NumLocs]; } // Solve the machine value dataflow problem using the MLocTransfer function, // storing the computed live-ins / live-outs into the array-of-arrays. We use // both live-ins and live-outs for decision making in the variable value // dataflow problem. buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); // Patch up debug phi numbers, turning unknown block-live-in values into // either live-through machine values, or PHIs. for (auto &DBG_PHI : DebugPHINumToValue) { // Identify unresolved block-live-ins. ValueIDNum &Num = DBG_PHI.ValueRead; if (!Num.isPHI()) continue; unsigned BlockNo = Num.getBlock(); LocIdx LocNo = Num.getLoc(); Num = MInLocs[BlockNo][LocNo.asU64()]; } // Later, we'll be looking up ranges of instruction numbers. llvm::sort(DebugPHINumToValue); // Walk back through each block / instruction, collecting DBG_VALUE // instructions and recording what machine value their operands refer to. for (auto &OrderPair : OrderToBB) { MachineBasicBlock &MBB = *OrderPair.second; CurBB = MBB.getNumber(); VTracker = &vlocs[CurBB]; VTracker->MBB = &MBB; MTracker->loadFromArray(MInLocs[CurBB], CurBB); CurInst = 1; for (auto &MI : MBB) { process(MI, MOutLocs, MInLocs); ++CurInst; } MTracker->reset(); } // Number all variables in the order that they appear, to be used as a stable // insertion order later. DenseMap<DebugVariable, unsigned> AllVarsNumbering; // Map from one LexicalScope to all the variables in that scope. DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars; // Map from One lexical scope to all blocks in that scope. DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>> ScopeToBlocks; // Store a DILocation that describes a scope. DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation; // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise // the order is unimportant, it just has to be stable. unsigned VarAssignCount = 0; for (unsigned int I = 0; I < OrderToBB.size(); ++I) { auto *MBB = OrderToBB[I]; auto *VTracker = &vlocs[MBB->getNumber()]; // Collect each variable with a DBG_VALUE in this block. for (auto &idx : VTracker->Vars) { const auto &Var = idx.first; const DILocation *ScopeLoc = VTracker->Scopes[Var]; assert(ScopeLoc != nullptr); auto *Scope = LS.findLexicalScope(ScopeLoc); // No insts in scope -> shouldn't have been recorded. assert(Scope != nullptr); AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); ScopeToVars[Scope].insert(Var); ScopeToBlocks[Scope].insert(VTracker->MBB); ScopeToDILocation[Scope] = ScopeLoc; ++VarAssignCount; } } bool Changed = false; // If we have an extremely large number of variable assignments and blocks, // bail out at this point. We've burnt some time doing analysis already, // however we should cut our losses. if ((unsigned)MaxNumBlocks > InputBBLimit && VarAssignCount > InputDbgValLimit) { LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() << " has " << MaxNumBlocks << " basic blocks and " << VarAssignCount << " variable assignments, exceeding limits.\n"); } else { // Compute the extended ranges, iterating over scopes. There might be // something to be said for ordering them by size/locality, but that's for // the future. For each scope, solve the variable value problem, producing // a map of variables to values in SavedLiveIns. for (auto &P : ScopeToVars) { buildVLocValueMap(ScopeToDILocation[P.first], P.second, ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs, vlocs); } // Using the computed value locations and variable values for each block, // create the DBG_VALUE instructions representing the extended variable // locations. emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC); // Did we actually make any changes? If we created any DBG_VALUEs, then yes. Changed = TTracker->Transfers.size() != 0; } // Common clean-up of memory. for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) { delete[] MOutLocs[Idx]; delete[] MInLocs[Idx]; } delete[] MOutLocs; delete[] MInLocs; delete MTracker; delete TTracker; MTracker = nullptr; VTracker = nullptr; TTracker = nullptr; ArtificialBlocks.clear(); OrderToBB.clear(); BBToOrder.clear(); BBNumToRPO.clear(); DebugInstrNumToInstr.clear(); DebugPHINumToValue.clear(); OverlapFragments.clear(); SeenFragments.clear(); return Changed; } LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { return new InstrRefBasedLDV(); } namespace { class LDVSSABlock; class LDVSSAUpdater; // Pick a type to identify incoming block values as we construct SSA. We // can't use anything more robust than an integer unfortunately, as SSAUpdater // expects to zero-initialize the type. typedef uint64_t BlockValueNum; /// Represents an SSA PHI node for the SSA updater class. Contains the block /// this PHI is in, the value number it would have, and the expected incoming /// values from parent blocks. class LDVSSAPhi { public: SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; LDVSSABlock *ParentBlock; BlockValueNum PHIValNum; LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} LDVSSABlock *getParent() { return ParentBlock; } }; /// Thin wrapper around a block predecessor iterator. Only difference from a /// normal block iterator is that it dereferences to an LDVSSABlock. class LDVSSABlockIterator { public: MachineBasicBlock::pred_iterator PredIt; LDVSSAUpdater &Updater; LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, LDVSSAUpdater &Updater) : PredIt(PredIt), Updater(Updater) {} bool operator!=(const LDVSSABlockIterator &OtherIt) const { return OtherIt.PredIt != PredIt; } LDVSSABlockIterator &operator++() { ++PredIt; return *this; } LDVSSABlock *operator*(); }; /// Thin wrapper around a block for SSA Updater interface. Necessary because /// we need to track the PHI value(s) that we may have observed as necessary /// in this block. class LDVSSABlock { public: MachineBasicBlock &BB; LDVSSAUpdater &Updater; using PHIListT = SmallVector<LDVSSAPhi, 1>; /// List of PHIs in this block. There should only ever be one. PHIListT PHIList; LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) : BB(BB), Updater(Updater) {} LDVSSABlockIterator succ_begin() { return LDVSSABlockIterator(BB.succ_begin(), Updater); } LDVSSABlockIterator succ_end() { return LDVSSABlockIterator(BB.succ_end(), Updater); } /// SSAUpdater has requested a PHI: create that within this block record. LDVSSAPhi *newPHI(BlockValueNum Value) { PHIList.emplace_back(Value, this); return &PHIList.back(); } /// SSAUpdater wishes to know what PHIs already exist in this block. PHIListT &phis() { return PHIList; } }; /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to // SSAUpdaterTraits<LDVSSAUpdater>. class LDVSSAUpdater { public: /// Map of value numbers to PHI records. DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; /// Map of which blocks generate Undef values -- blocks that are not /// dominated by any Def. DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; /// Map of machine blocks to our own records of them. DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; /// Machine location where any PHI must occur. LocIdx Loc; /// Table of live-in machine value numbers for blocks / locations. ValueIDNum **MLiveIns; LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {} void reset() { for (auto &Block : BlockMap) delete Block.second; PHIs.clear(); UndefMap.clear(); BlockMap.clear(); } ~LDVSSAUpdater() { reset(); } /// For a given MBB, create a wrapper block for it. Stores it in the /// LDVSSAUpdater block map. LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { auto it = BlockMap.find(BB); if (it == BlockMap.end()) { BlockMap[BB] = new LDVSSABlock(*BB, *this); it = BlockMap.find(BB); } return it->second; } /// Find the live-in value number for the given block. Looks up the value at /// the PHI location on entry. BlockValueNum getValue(LDVSSABlock *LDVBB) { return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); } }; LDVSSABlock *LDVSSABlockIterator::operator*() { return Updater.getSSALDVBlock(*PredIt); } #ifndef NDEBUG raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { out << "SSALDVPHI " << PHI.PHIValNum; return out; } #endif } // namespace namespace llvm { /// Template specialization to give SSAUpdater access to CFG and value /// information. SSAUpdater calls methods in these traits, passing in the /// LDVSSAUpdater object, to learn about blocks and the values they define. /// It also provides methods to create PHI nodes and track them. template <> class SSAUpdaterTraits<LDVSSAUpdater> { public: using BlkT = LDVSSABlock; using ValT = BlockValueNum; using PhiT = LDVSSAPhi; using BlkSucc_iterator = LDVSSABlockIterator; // Methods to access block successors -- dereferencing to our wrapper class. static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } /// Iterator for PHI operands. class PHI_iterator { private: LDVSSAPhi *PHI; unsigned Idx; public: explicit PHI_iterator(LDVSSAPhi *P) // begin iterator : PHI(P), Idx(0) {} PHI_iterator(LDVSSAPhi *P, bool) // end iterator : PHI(P), Idx(PHI->IncomingValues.size()) {} PHI_iterator &operator++() { Idx++; return *this; } bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } bool operator!=(const PHI_iterator &X) const { return !operator==(X); } BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } }; static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } static inline PHI_iterator PHI_end(PhiT *PHI) { return PHI_iterator(PHI, true); } /// FindPredecessorBlocks - Put the predecessors of BB into the Preds /// vector. static void FindPredecessorBlocks(LDVSSABlock *BB, SmallVectorImpl<LDVSSABlock *> *Preds) { for (MachineBasicBlock *Pred : BB->BB.predecessors()) Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); } /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new /// register. For LiveDebugValues, represents a block identified as not having /// any DBG_PHI predecessors. static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { // Create a value number for this block -- it needs to be unique and in the // "undef" collection, so that we know it's not real. Use a number // representing a PHI into this block. BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); Updater->UndefMap[&BB->BB] = Num; return Num; } /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. /// SSAUpdater will populate it with information about incoming values. The /// value number of this PHI is whatever the machine value number problem /// solution determined it to be. This includes non-phi values if SSAUpdater /// tries to create a PHI where the incoming values are identical. static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, LDVSSAUpdater *Updater) { BlockValueNum PHIValNum = Updater->getValue(BB); LDVSSAPhi *PHI = BB->newPHI(PHIValNum); Updater->PHIs[PHIValNum] = PHI; return PHIValNum; } /// AddPHIOperand - Add the specified value as an operand of the PHI for /// the specified predecessor block. static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); } /// ValueIsPHI - Check if the instruction that defines the specified value /// is a PHI instruction. static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { auto PHIIt = Updater->PHIs.find(Val); if (PHIIt == Updater->PHIs.end()) return nullptr; return PHIIt->second; } /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source /// operands, i.e., it was just added. static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); if (PHI && PHI->IncomingValues.size() == 0) return PHI; return nullptr; } /// GetPHIValue - For the specified PHI instruction, return the value /// that it defines. static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } }; } // end namespace llvm Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF, ValueIDNum **MLiveOuts, ValueIDNum **MLiveIns, MachineInstr &Here, uint64_t InstrNum) { // Pick out records of DBG_PHI instructions that have been observed. If there // are none, then we cannot compute a value number. auto RangePair = std::equal_range(DebugPHINumToValue.begin(), DebugPHINumToValue.end(), InstrNum); auto LowerIt = RangePair.first; auto UpperIt = RangePair.second; // No DBG_PHI means there can be no location. if (LowerIt == UpperIt) return None; // If there's only one DBG_PHI, then that is our value number. if (std::distance(LowerIt, UpperIt) == 1) return LowerIt->ValueRead; auto DBGPHIRange = make_range(LowerIt, UpperIt); // Pick out the location (physreg, slot) where any PHIs must occur. It's // technically possible for us to merge values in different registers in each // block, but highly unlikely that LLVM will generate such code after register // allocation. LocIdx Loc = LowerIt->ReadLoc; // We have several DBG_PHIs, and a use position (the Here inst). All each // DBG_PHI does is identify a value at a program position. We can treat each // DBG_PHI like it's a Def of a value, and the use position is a Use of a // value, just like SSA. We use the bulk-standard LLVM SSA updater class to // determine which Def is used at the Use, and any PHIs that happen along // the way. // Adapted LLVM SSA Updater: LDVSSAUpdater Updater(Loc, MLiveIns); // Map of which Def or PHI is the current value in each block. DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; // Set of PHIs that we have created along the way. SmallVector<LDVSSAPhi *, 8> CreatedPHIs; // Each existing DBG_PHI is a Def'd value under this model. Record these Defs // for the SSAUpdater. for (const auto &DBG_PHI : DBGPHIRange) { LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); const ValueIDNum &Num = DBG_PHI.ValueRead; AvailableValues.insert(std::make_pair(Block, Num.asU64())); } LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); const auto &AvailIt = AvailableValues.find(HereBlock); if (AvailIt != AvailableValues.end()) { // Actually, we already know what the value is -- the Use is in the same // block as the Def. return ValueIDNum::fromU64(AvailIt->second); } // Otherwise, we must use the SSA Updater. It will identify the value number // that we are to use, and the PHIs that must happen along the way. SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); ValueIDNum Result = ValueIDNum::fromU64(ResultInt); // We have the number for a PHI, or possibly live-through value, to be used // at this Use. There are a number of things we have to check about it though: // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this // Use was not completely dominated by DBG_PHIs and we should abort. // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that // we've left SSA form. Validate that the inputs to each PHI are the // expected values. // * Is a PHI we've created actually a merging of values, or are all the // predecessor values the same, leading to a non-PHI machine value number? // (SSAUpdater doesn't know that either). Remap validated PHIs into the // the ValidatedValues collection below to sort this out. DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; // Define all the input DBG_PHI values in ValidatedValues. for (const auto &DBG_PHI : DBGPHIRange) { LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); const ValueIDNum &Num = DBG_PHI.ValueRead; ValidatedValues.insert(std::make_pair(Block, Num)); } // Sort PHIs to validate into RPO-order. SmallVector<LDVSSAPhi *, 8> SortedPHIs; for (auto &PHI : CreatedPHIs) SortedPHIs.push_back(PHI); std::sort( SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; }); for (auto &PHI : SortedPHIs) { ValueIDNum ThisBlockValueNum = MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; // Are all these things actually defined? for (auto &PHIIt : PHI->IncomingValues) { // Any undef input means DBG_PHIs didn't dominate the use point. if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) return None; ValueIDNum ValueToCheck; ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; auto VVal = ValidatedValues.find(PHIIt.first); if (VVal == ValidatedValues.end()) { // We cross a loop, and this is a backedge. LLVMs tail duplication // happens so late that DBG_PHI instructions should not be able to // migrate into loops -- meaning we can only be live-through this // loop. ValueToCheck = ThisBlockValueNum; } else { // Does the block have as a live-out, in the location we're examining, // the value that we expect? If not, it's been moved or clobbered. ValueToCheck = VVal->second; } if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) return None; } // Record this value as validated. ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); } // All the PHIs are valid: we can return what the SSAUpdater said our value // number was. return Result; }
38.812178
109
0.675005
[ "object", "vector", "model" ]
2976c58000eb20427dd3017cf398af21587a9a19
813
cpp
C++
test/container/bitfield/empty.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/bitfield/empty.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/bitfield/empty.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/no_init.hpp> #include <fcppt/container/bitfield/object.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> TEST_CASE( "container::bitfield empty", "[container],[bitfield]" ) { typedef std::integral_constant< unsigned, 0 > static_size; typedef fcppt::container::bitfield::object< unsigned, static_size > empty_bitfield; CHECK( empty_bitfield{ fcppt::no_init() }.array().empty() ); static_assert( empty_bitfield::static_size::value == 0u, "" ); }
17.297872
61
0.694957
[ "object" ]
29773945c5927d834fbcced0a76aede69c386ba4
2,045
cpp
C++
Bearcity Renting.cpp
ducthienbui97/IEEExtreme13
7bf98d5b73528386db90e9b3d957eb4025076d9f
[ "MIT" ]
6
2019-10-21T06:28:09.000Z
2021-10-19T12:07:59.000Z
Bearcity Renting.cpp
ducthienbui97/IEEExtreme13
7bf98d5b73528386db90e9b3d957eb4025076d9f
[ "MIT" ]
null
null
null
Bearcity Renting.cpp
ducthienbui97/IEEExtreme13
7bf98d5b73528386db90e9b3d957eb4025076d9f
[ "MIT" ]
2
2019-10-21T05:56:29.000Z
2020-10-21T06:19:11.000Z
#include <bits/stdc++.h> using namespace std; int findRoot(int u, vector<int>& root) { if(u == root[u]) return u; return root[u] = findRoot(root[u], root); } int cnt = 0; int dfs(int u, int p, unordered_map<int, unordered_map<int, int>>& d, unordered_map<int, int>& low, unordered_map<int, int>& vs) { low[u] = vs[u] = ++cnt; int ans = 0; for(auto& pp: d[u]) if(pp.first != p) { int v = pp.first; if(vs[v]) low[u] = min(low[u], low[v]); else { ans += dfs(v, u, d, low, vs); low[u] = min(low[u], low[v]); if(pp.second == 1 && low[v] >= vs[v]) { ans++; } } } return ans; } int main() { int n,m; cin >> n >> m; vector<pair<int, pair<int,int>>> edges(m); vector<int> r(n + 1); for(int i = 1; i <= n; i++) r[i] = i; for(int i = 0 ; i < m; i++) { cin >> edges[i].second.first >> edges[i].second.second >> edges[i].first; } int ans = 0;; sort(edges.begin(), edges.end()); for(int i = 0; i < m;) { unordered_map<int, unordered_map<int, int>> d; unordered_map<int, int> low; unordered_set<int> nodes; unordered_map<int, int> vs; int j; for(j = i; j < m && edges[i].first == edges[j].first; j++) { int x = findRoot(edges[j].second.first, r); int y = findRoot(edges[j].second.second, r); if(x != y) { d[x][y] ++; d[y][x] ++; } nodes.insert(x); nodes.insert(y); } cnt = 0; for(auto& v: nodes) if(!vs[v]) ans += dfs(v, -1, d, low, vs); for(j = i; j < m && edges[i].first == edges[j].first; j++) { int x = findRoot(edges[j].second.first, r); int y = findRoot(edges[j].second.second, r); r[x] = y; } i = j; } cout << ans << endl; return 0; }
29.637681
81
0.433252
[ "vector" ]
2977561c16b5de1d3c6c8db5c73f59985938d7a9
3,820
cc
C++
src/nnet2bin/nnet2-shuffle-egs.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
2
2017-05-02T15:45:03.000Z
2017-07-06T06:34:51.000Z
src/nnet2bin/nnet2-shuffle-egs.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
null
null
null
src/nnet2bin/nnet2-shuffle-egs.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
null
null
null
// nnet2bin/nnet2-shuffle-egs.cc // Copyright 2012 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "hmm/transition-model.h" #include "nnet2/nnet-randomize.h" int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::nnet2; typedef kaldi::int32 int32; typedef kaldi::int64 int64; const char *usage = "Copy examples (typically single frames) for neural network training,\n" "from the input to output, but randomly shuffle the order. This program will keep\n" "all of the examples in memory at once, so don't give it too many.\n" "\n" "Usage: nnet2-shuffle-egs [options] <egs-rspecifier> <egs-wspecifier>\n" "\n" "nnet2-shuffle-egs --srand=1 ark:train.egs ark:shuffled.egs\n"; int32 srand_seed = 0; int32 buffer_size = 0; ParseOptions po(usage); po.Register("srand", &srand_seed, "Seed for random number generator "); po.Register("buffer-size", &buffer_size, "If >0, size of a buffer we use " "to do limited-memory partial randomization. Otherwise, do " "full randomization."); po.Read(argc, argv); srand(srand_seed); if (po.NumArgs() != 2) { po.PrintUsage(); exit(1); } std::string examples_rspecifier = po.GetArg(1), examples_wspecifier = po.GetArg(2); int64 num_done = 0; std::vector<NnetExample*> egs; SequentialNnetExampleReader example_reader(examples_rspecifier); NnetExampleWriter example_writer(examples_wspecifier); if (buffer_size == 0) { // Do full randomization // Putting in an extra level of indirection here to avoid excessive // computation and memory demands when we have to resize the vector. for (; !example_reader.Done(); example_reader.Next()) egs.push_back(new NnetExample(example_reader.Value())); std::random_shuffle(egs.begin(), egs.end()); } else { KALDI_ASSERT(buffer_size > 0); egs.resize(buffer_size, NULL); for (; !example_reader.Done(); example_reader.Next()) { int32 index = RandInt(0, buffer_size - 1); if (egs[index] == NULL) { egs[index] = new NnetExample(example_reader.Value()); } else { std::ostringstream ostr; ostr << num_done; example_writer.Write(ostr.str(), *(egs[index])); *(egs[index]) = example_reader.Value(); num_done++; } } } for (size_t i = 0; i < egs.size(); i++) { std::ostringstream ostr; ostr << num_done; if (egs[i] != NULL) { example_writer.Write(ostr.str(), *(egs[i])); delete egs[i]; } num_done++; } KALDI_LOG << "Shuffled order of " << num_done << " neural-network training examples " << (buffer_size ? "using a buffer (partial randomization)" : ""); return (num_done == 0 ? 1 : 0); } catch(const std::exception &e) { std::cerr << e.what() << '\n'; return -1; } }
34.107143
93
0.627487
[ "vector", "model" ]
2978f8344e9eaf9106da68ecb3c35b682f14bc7f
1,433
cpp
C++
test/stopwatch_test.cpp
timwillett4/FunctionalPlus
1c19cff615e9ccc56a6e3c56920a6ef6ef467079
[ "BSL-1.0" ]
1
2020-07-20T10:11:28.000Z
2020-07-20T10:11:28.000Z
test/stopwatch_test.cpp
timwillett4/FunctionalPlus
1c19cff615e9ccc56a6e3c56920a6ef6ef467079
[ "BSL-1.0" ]
null
null
null
test/stopwatch_test.cpp
timwillett4/FunctionalPlus
1c19cff615e9ccc56a6e3c56920a6ef6ef467079
[ "BSL-1.0" ]
null
null
null
// (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest/doctest.h" #include <fplus/fplus.hpp> #include <fplus/stopwatch.hpp> using namespace std::chrono_literals; template<typename Function> auto invoke_n_times(int n, Function f) { for (int i = 0; i < n; i++) { f(); } } TEST_CASE("Timer, test_accuracy") { #ifdef NDEBUG // only on release builds using namespace fplus; using namespace std::chrono_literals; auto measure_delta = []() { fplus::stopwatch t; std::this_thread::sleep_for(0.05s); auto duration = t.elapsed(); auto delta = duration - 0.05; return fabs(delta); }; // we ask for a sleep of 0.05s, but we will have a duration that can be higher // (up to 15 ms higher, since the cpu scheduler might switch to another process during this sleep) // to account for the cpu/task scheduler double max_acceptable_delta__task_scheduler = 0.02; // One run { auto delta = measure_delta(); REQUIRE_LT(delta, max_acceptable_delta__task_scheduler); } // 10 consecutive runs (total duration = 0.5 seconds) { std::vector<double> deltas; invoke_n_times(10, [&]() { deltas.push_back(measure_delta()); }); auto mean_dev = fplus::mean_stddev<double>(deltas); REQUIRE_LT(mean_dev.first, 0.03); REQUIRE_LT(mean_dev.second, 0.01); } #endif }
25.140351
100
0.688765
[ "vector" ]
297b6fab1d65b4ad4e81cbb1ecf51648326e33a5
24,460
cpp
C++
tests/test_flashfatfs/test_flashfatfs.cpp
DG12/ruuvi.gateway_esp.c
cf22748af0c0a37287f08b49477f06f56456f72f
[ "BSD-3-Clause" ]
18
2020-01-22T13:27:38.000Z
2022-01-30T20:18:41.000Z
tests/test_flashfatfs/test_flashfatfs.cpp
mangelino/ruuvi.gateway_esp.c
134edffff173930b3d2e71455945d36d96478280
[ "BSD-3-Clause" ]
289
2019-12-16T13:33:24.000Z
2022-03-30T06:11:10.000Z
tests/test_flashfatfs/test_flashfatfs.cpp
mangelino/ruuvi.gateway_esp.c
134edffff173930b3d2e71455945d36d96478280
[ "BSD-3-Clause" ]
15
2019-12-21T04:13:22.000Z
2021-11-30T08:21:27.000Z
/** * @file test_flashfatfs.cpp * @author TheSomeMan * @date 2020-10-19 * @copyright Ruuvi Innovations Ltd, license BSD-3-Clause. */ #include "flashfatfs.h" #include <string> #include <sys/stat.h> #include <ftw.h> #include "gtest/gtest.h" #include "esp_log_wrapper.hpp" #include "esp_err.h" #include "esp_vfs_fat.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" using namespace std; /*** Google-test class implementation * *********************************************************************************/ struct flash_fat_fs_t { char * mount_point; wl_handle_t wl_handle; }; class TestFlashFatFs; static TestFlashFatFs *g_pTestClass; class FlashFatFs_VFS_FAT_MountInfo { public: string base_path; string partition_label; esp_vfs_fat_mount_config_t mount_config = {}; bool flag_mounted = false; esp_err_t mount_err = ESP_OK; esp_err_t unmount_err = ESP_OK; wl_handle_t wl_handle = 0; }; class MemAllocTrace { vector<void *> allocated_mem; std::vector<void *>::iterator find(void *ptr) { for (auto iter = this->allocated_mem.begin(); iter != this->allocated_mem.end(); ++iter) { if (*iter == ptr) { return iter; } } return this->allocated_mem.end(); } public: void add(void *ptr) { auto iter = find(ptr); assert(iter == this->allocated_mem.end()); // ptr was found in the list of allocated memory blocks this->allocated_mem.push_back(ptr); } void remove(void *ptr) { auto iter = find(ptr); assert(iter != this->allocated_mem.end()); // ptr was not found in the list of allocated memory blocks this->allocated_mem.erase(iter); } bool is_empty() { return this->allocated_mem.empty(); } }; static int remove_file(const char *filename, const struct stat *status, int flag, struct FTW *p_info) { return remove(filename); } static void remove_dir_with_files(const char *path) { struct stat st = { 0 }; if (stat(path, &st) == 0) { if (S_ISDIR(st.st_mode)) { const int res = nftw(path, remove_file, 10, FTW_DEPTH | FTW_MOUNT | FTW_PHYS); assert(0 == res); } else { const int res = remove(path); assert(0 == res); } } } class TestFlashFatFs : public ::testing::Test { private: protected: FILE * m_fd; const flash_fat_fs_t *m_p_ffs; const char * m_mount_point_dir; const char * m_mount_point; void SetUp() override { #define FS_NRF52_MOUNT_POINT "fs_nrf52" this->m_mount_point_dir = FS_NRF52_MOUNT_POINT; this->m_mount_point = "/" FS_NRF52_MOUNT_POINT; { remove_dir_with_files(this->m_mount_point_dir); mkdir(this->m_mount_point_dir, 0700); } this->m_fd = nullptr; this->m_p_ffs = nullptr; esp_log_wrapper_init(); g_pTestClass = this; this->m_malloc_cnt = 0; this->m_malloc_fail_on_cnt = 0; this->m_mount_info.flag_mounted = false; this->m_mount_info.mount_err = ESP_OK; this->m_mount_info.unmount_err = ESP_OK; this->m_mount_info.wl_handle = 0; } void TearDown() override { if (nullptr != this->m_fd) { fclose(this->m_fd); this->m_fd = nullptr; } if (nullptr != this->m_p_ffs) { flashfatfs_unmount(&this->m_p_ffs); } { remove_dir_with_files(this->m_mount_point_dir); } esp_log_wrapper_deinit(); g_pTestClass = nullptr; } FILE * open_file(const char *file_name, const char *mode) { char full_path_info_txt[40]; snprintf(full_path_info_txt, sizeof(full_path_info_txt), "%s/%s", this->m_mount_point_dir, file_name); return fopen(full_path_info_txt, mode); } public: TestFlashFatFs(); ~TestFlashFatFs() override; uint32_t m_malloc_cnt; uint32_t m_malloc_fail_on_cnt; FlashFatFs_VFS_FAT_MountInfo m_mount_info; MemAllocTrace m_mem_alloc_trace; }; TestFlashFatFs::TestFlashFatFs() : Test() { } TestFlashFatFs::~TestFlashFatFs() = default; extern "C" { const char * os_task_get_name(void) { static const char g_task_name[] = "main"; return const_cast<char *>(g_task_name); } void * os_malloc(const size_t size) { if (++g_pTestClass->m_malloc_cnt == g_pTestClass->m_malloc_fail_on_cnt) { return nullptr; } void *ptr = malloc(size); assert(nullptr != ptr); g_pTestClass->m_mem_alloc_trace.add(ptr); return ptr; } void os_free_internal(void *ptr) { g_pTestClass->m_mem_alloc_trace.remove(ptr); free(ptr); } void * os_calloc(const size_t nmemb, const size_t size) { if (++g_pTestClass->m_malloc_cnt == g_pTestClass->m_malloc_fail_on_cnt) { return nullptr; } void *ptr = calloc(nmemb, size); assert(nullptr != ptr); g_pTestClass->m_mem_alloc_trace.add(ptr); return ptr; } esp_err_t esp_vfs_fat_spiflash_mount( const char * base_path, const char * partition_label, const esp_vfs_fat_mount_config_t *mount_config, wl_handle_t * wl_handle) { g_pTestClass->m_mount_info.base_path = string(base_path); g_pTestClass->m_mount_info.partition_label = string(partition_label); g_pTestClass->m_mount_info.mount_config = *mount_config; *wl_handle = g_pTestClass->m_mount_info.wl_handle; g_pTestClass->m_mount_info.flag_mounted = true; return g_pTestClass->m_mount_info.mount_err; } esp_err_t esp_vfs_fat_spiflash_unmount(const char *base_path, wl_handle_t wl_handle) { assert(nullptr != g_pTestClass); assert(g_pTestClass->m_mount_info.flag_mounted); assert(g_pTestClass->m_mount_info.wl_handle == wl_handle); g_pTestClass->m_mount_info.flag_mounted = false; return g_pTestClass->m_mount_info.unmount_err; } } // extern "C" #define TEST_CHECK_LOG_RECORD(level_, msg_) ESP_LOG_WRAPPER_TEST_CHECK_LOG_RECORD("FlashFatFS", level_, msg_); /*** Unit-Tests * *******************************************************************************************************/ TEST_F(TestFlashFatFs, flashfatfs_mount_ok_rel_path) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); ASSERT_EQ(string("fs_nrf52"), string(this->m_p_ffs->mount_point)); ASSERT_EQ(wl_handle, this->m_p_ffs->wl_handle); ASSERT_TRUE(this->m_mount_info.flag_mounted); ASSERT_EQ("fs_nrf52", this->m_mount_info.base_path); ASSERT_EQ(GW_NRF_PARTITION, this->m_mount_info.partition_label); ASSERT_FALSE(this->m_mount_info.mount_config.format_if_mount_failed); ASSERT_EQ(max_files, this->m_mount_info.mount_config.max_files); ASSERT_EQ(512U, this->m_mount_info.mount_config.allocation_unit_size); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_mount_ok_abs_path) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; this->m_p_ffs = flashfatfs_mount("/fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); ASSERT_EQ(string("./fs_nrf52"), string(this->m_p_ffs->mount_point)); ASSERT_EQ(wl_handle, this->m_p_ffs->wl_handle); ASSERT_TRUE(this->m_mount_info.flag_mounted); ASSERT_EQ("/fs_nrf52", this->m_mount_info.base_path); ASSERT_EQ(GW_NRF_PARTITION, this->m_mount_info.partition_label); ASSERT_FALSE(this->m_mount_info.mount_config.format_if_mount_failed); ASSERT_EQ(max_files, this->m_mount_info.mount_config.max_files); ASSERT_EQ(512U, this->m_mount_info.mount_config.allocation_unit_size); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point /fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to /fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount ./fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_mount_ok_unmount_failed) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); this->m_mount_info.unmount_err = ESP_ERR_NOT_SUPPORTED; ASSERT_FALSE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "esp_vfs_fat_spiflash_unmount failed, err=262 (UNKNOWN ERROR)"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_mount_failed_no_mem) // NOLINT { const int max_files = 1; this->m_malloc_fail_on_cnt = 1; this->m_p_ffs = flashfatfs_mount(this->m_mount_point, GW_NRF_PARTITION, max_files); ASSERT_EQ(nullptr, this->m_p_ffs); TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point /fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "Can't allocate memory"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_mount_failed_on_spiflash_mount) // NOLINT { const int max_files = 1; this->m_mount_info.mount_err = ESP_ERR_NOT_FOUND; this->m_p_ffs = flashfatfs_mount(this->m_mount_point, GW_NRF_PARTITION, max_files); ASSERT_EQ(nullptr, this->m_p_ffs); TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point /fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "esp_vfs_fat_spiflash_mount failed, err=261 (UNKNOWN ERROR)"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_get_full_path_no_mount_point) // NOLINT { { const char * file_name = "abc"; flashfatfs_path_t path = flashfatfs_get_full_path(nullptr, file_name); ASSERT_EQ(string(path.buf), "/abc"); } { const char * file_name = "123456789012345678901234567890123456789012345678901234567890123456789012345678"; flashfatfs_path_t path = flashfatfs_get_full_path(nullptr, file_name); ASSERT_EQ(string(path.buf), string("/") + string(file_name)); } { flashfatfs_path_t path = flashfatfs_get_full_path( nullptr, "123456789012345678901234567890123456789012345678901234567890123456789012345678A"); ASSERT_EQ(string(path.buf), "/123456789012345678901234567890123456789012345678901234567890123456789012345678"); } } TEST_F(TestFlashFatFs, flashfatfs_get_full_path_with_mount_point) // NOLINT { const char *mount_point = "/fs_nrf52"; this->m_p_ffs = flashfatfs_mount(mount_point, GW_NRF_PARTITION, 1); { const char * file_name = "abc"; flashfatfs_path_t path = flashfatfs_get_full_path(this->m_p_ffs, file_name); ASSERT_EQ(string(path.buf), string("./fs_nrf52/abc")); } { flashfatfs_path_t path = flashfatfs_get_full_path( this->m_p_ffs, "123456789012345678901234567890123456789012345678901234567890123456789012345678A"); ASSERT_EQ(string(path.buf), "./fs_nrf52/12345678901234567890123456789012345678901234567890123456789012345678"); } } TEST_F(TestFlashFatFs, flashfatfs_open_without_ffs) // NOLINT { const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } file_descriptor_t fd = flashfatfs_open(nullptr, test_file_name); ASSERT_EQ(fd, -1); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "p_ffs is NULL"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_open_ok) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); file_descriptor_t fd = flashfatfs_open(this->m_p_ffs, test_file_name); ASSERT_GE(fd, 0); { char buf[80]; const int len = read(fd, buf, sizeof(buf)); ASSERT_EQ(8, len); buf[len] = '\0'; ASSERT_EQ(string(test_text), string(buf)); } close(fd); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_open_failed) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); file_descriptor_t fd = flashfatfs_open(this->m_p_ffs, test_file_name); ASSERT_LT(fd, 0); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "Can't open: fs_nrf52/test1.txt"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_fopen_ascii_ok) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); const bool flag_use_binary_mode = false; FILE * p_fd = flashfatfs_fopen(this->m_p_ffs, test_file_name, flag_use_binary_mode); ASSERT_NE(nullptr, p_fd); { char buf[80]; const int len = fread(buf, 1, sizeof(buf), p_fd); ASSERT_EQ(8, len); buf[len] = '\0'; ASSERT_EQ(string(test_text), string(buf)); } fclose(p_fd); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_fopen_binary_ok) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); const bool flag_use_binary_mode = true; FILE * p_fd = flashfatfs_fopen(this->m_p_ffs, test_file_name, flag_use_binary_mode); ASSERT_NE(nullptr, p_fd); { char buf[80]; const int len = fread(buf, 1, sizeof(buf), p_fd); ASSERT_EQ(8, len); buf[len] = '\0'; ASSERT_EQ(string(test_text), string(buf)); } fclose(p_fd); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_fopen_failed) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); const bool flag_use_binary_mode = false; FILE * p_fd = flashfatfs_fopen(this->m_p_ffs, test_file_name, flag_use_binary_mode); ASSERT_EQ(nullptr, p_fd); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_ERROR, "Can't open: fs_nrf52/test1.txt"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_stat_ok) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); struct stat st = { 0 }; ASSERT_TRUE(flashfatfs_stat(this->m_p_ffs, test_file_name, &st)); ASSERT_EQ(st.st_size, strlen(test_text)); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_stat_failed) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); struct stat st = { 0 }; ASSERT_FALSE(flashfatfs_stat(this->m_p_ffs, test_file_name, &st)); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_get_file_size_ok) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; const char *test_text = "test123\n"; { char tmp_file_path[80]; snprintf(tmp_file_path, sizeof(tmp_file_path), "%s/%s", this->m_mount_point_dir, test_file_name); FILE *fd = fopen(tmp_file_path, "w"); ASSERT_NE(nullptr, fd); fprintf(fd, "%s", test_text); fclose(fd); } this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); size_t size = 0; ASSERT_TRUE(flashfatfs_get_file_size(this->m_p_ffs, test_file_name, &size)); ASSERT_EQ(size, strlen(test_text)); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); } TEST_F(TestFlashFatFs, flashfatfs_get_file_size_failed) // NOLINT { const wl_handle_t wl_handle = 25; const int max_files = 1; this->m_mount_info.wl_handle = wl_handle; const char *test_file_name = "test1.txt"; this->m_p_ffs = flashfatfs_mount("fs_nrf52", GW_NRF_PARTITION, max_files); ASSERT_NE(nullptr, this->m_p_ffs); size_t size = 0; ASSERT_FALSE(flashfatfs_get_file_size(this->m_p_ffs, test_file_name, &size)); ASSERT_TRUE(flashfatfs_unmount(&this->m_p_ffs)); this->m_p_ffs = nullptr; TEST_CHECK_LOG_RECORD(ESP_LOG_DEBUG, "Mount partition 'fatfs_nrf52' to the mount point fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Partition 'fatfs_nrf52' mounted successfully to fs_nrf52"); TEST_CHECK_LOG_RECORD(ESP_LOG_INFO, "Unmount fs_nrf52"); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_TRUE(this->m_mem_alloc_trace.is_empty()); }
34.019471
119
0.67776
[ "vector" ]
297d597620e5b981bf0cd3311ade505caac988be
567
cpp
C++
aws-cpp-sdk-auditmanager/source/model/DeleteAssessmentFrameworkRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-auditmanager/source/model/DeleteAssessmentFrameworkRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-auditmanager/source/model/DeleteAssessmentFrameworkRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/auditmanager/model/DeleteAssessmentFrameworkRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::AuditManager::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeleteAssessmentFrameworkRequest::DeleteAssessmentFrameworkRequest() : m_frameworkIdHasBeenSet(false) { } Aws::String DeleteAssessmentFrameworkRequest::SerializePayload() const { return {}; }
20.25
71
0.768959
[ "model" ]
2985f56649e2350786e9ef82e825e280ec33854f
75,673
cc
C++
gazebo/common/ColladaLoader.cc
michaelhuang14/gazebo
ca55c6e5c82c72e0987cb25c7e52a8acc0788aa7
[ "ECL-2.0", "Apache-2.0" ]
2
2021-09-04T07:42:58.000Z
2021-10-01T07:00:46.000Z
gazebo/common/ColladaLoader.cc
Pro/gazebo
063d7386ed5499c2883de48e19ff5fb9dec01dff
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/common/ColladaLoader.cc
Pro/gazebo
063d7386ed5499c2883de48e19ff5fb9dec01dff
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012 Open Source Robotics Foundation * * 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 <tinyxml.h> #include <math.h> #include <sstream> #include <set> #include <memory> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/unordered_map.hpp> #include <ignition/math/Color.hh> #include <ignition/math/Helpers.hh> #include <ignition/math/Matrix4.hh> #include <ignition/math/Vector2.hh> #include <ignition/math/Vector3.hh> #include "gazebo/common/Console.hh" #include "gazebo/common/Material.hh" #include "gazebo/common/Mesh.hh" #include "gazebo/common/Skeleton.hh" #include "gazebo/common/SkeletonAnimation.hh" #include "gazebo/common/SystemPaths.hh" #include "gazebo/common/Exception.hh" #include "gazebo/common/ColladaLoaderPrivate.hh" #include "gazebo/common/ColladaLoader.hh" using namespace gazebo; using namespace common; ///////////////////////////////////////////////// // std::unary_function was removed in c++17 but can be reproduced easily // copied from https://stackoverflow.com/a/56001387 template <typename ArgumentType, typename ResultType> struct unary_function { using argument_type = ArgumentType; using result_type = ResultType; }; ///////////////////////////////////////////////// struct Vector3Hash : unary_function<const ignition::math::Vector3d, std::size_t> { std::size_t operator()(const ignition::math::Vector3d &_v) const { std::size_t seed = 0; boost::hash_combine(seed, _v.X()); boost::hash_combine(seed, _v.Y()); boost::hash_combine(seed, _v.Z()); return seed; } }; ///////////////////////////////////////////////// struct Vector2dHash : unary_function<const ignition::math::Vector2d, std::size_t> { std::size_t operator()(const ignition::math::Vector2d &_v) const { std::size_t seed = 0; boost::hash_combine(seed, _v.X()); boost::hash_combine(seed, _v.Y()); return seed; } }; ////////////////////////////////////////////////// ColladaLoader::ColladaLoader() : MeshLoader(), dataPtr(new ColladaLoaderPrivate) { this->dataPtr->meter = 1.0; } ////////////////////////////////////////////////// ColladaLoader::~ColladaLoader() { delete this->dataPtr; this->dataPtr = 0; } ////////////////////////////////////////////////// Mesh *ColladaLoader::Load(const std::string &_filename) { this->dataPtr->positionIds.clear(); this->dataPtr->normalIds.clear(); this->dataPtr->texcoordIds.clear(); this->dataPtr->materialIds.clear(); this->dataPtr->positionDuplicateMap.clear(); this->dataPtr->normalDuplicateMap.clear(); this->dataPtr->texcoordDuplicateMap.clear(); // reset scale this->dataPtr->meter = 1.0; TiXmlDocument xmlDoc; boost::filesystem::path p(_filename); this->dataPtr->path = p.parent_path().generic_string(); this->dataPtr->filename = _filename; if (!xmlDoc.LoadFile(_filename)) gzerr << "Unable to load collada file[" << _filename << "]\n"; this->dataPtr->colladaXml = xmlDoc.FirstChildElement("COLLADA"); if (!this->dataPtr->colladaXml) gzerr << "Missing COLLADA tag\n"; if (std::string(this->dataPtr->colladaXml->Attribute("version")) != "1.4.0" && std::string(this->dataPtr->colladaXml->Attribute("version")) != "1.4.1") gzerr << "Invalid collada file. Must be version 1.4.0 or 1.4.1\n"; TiXmlElement *assetXml = this->dataPtr->colladaXml->FirstChildElement("asset"); if (assetXml) { TiXmlElement *unitXml = assetXml->FirstChildElement("unit"); if (unitXml && unitXml->Attribute("meter")) this->dataPtr->meter = ignition::math::parseFloat( unitXml->Attribute("meter")); } Mesh *mesh = new Mesh(); mesh->SetPath(this->dataPtr->path); this->LoadScene(mesh); if (mesh->HasSkeleton()) ApplyInvBindTransform(mesh->GetSkeleton()); // This will make the model the correct size. mesh->Scale(this->dataPtr->meter); if (mesh->HasSkeleton()) mesh->GetSkeleton()->Scale(this->dataPtr->meter); return mesh; } ///////////////////////////////////////////////// void ColladaLoader::LoadScene(Mesh *_mesh) { TiXmlElement *sceneXml = this->dataPtr->colladaXml->FirstChildElement("scene"); std::string sceneURL = sceneXml->FirstChildElement("instance_visual_scene")->Attribute("url"); TiXmlElement *visSceneXml = this->GetElementId("visual_scene", sceneURL); this->dataPtr->currentScene = visSceneXml; if (!visSceneXml) { gzerr << "Unable to find visual_scene id ='" << sceneURL << "'\n"; return; } TiXmlElement *nodeXml = visSceneXml->FirstChildElement("node"); while (nodeXml) { this->LoadNode(nodeXml, _mesh, ignition::math::Matrix4d::Identity); nodeXml = nodeXml->NextSiblingElement("node"); } } ///////////////////////////////////////////////// void ColladaLoader::LoadNode(TiXmlElement *_elem, Mesh *_mesh, const ignition::math::Matrix4d &_transform) { TiXmlElement *nodeXml; TiXmlElement *instGeomXml; ignition::math::Matrix4d transform = this->LoadNodeTransform(_elem); transform = _transform * transform; if (_elem->Attribute("name")) { this->dataPtr->currentNodeName = _elem->Attribute("name"); } nodeXml = _elem->FirstChildElement("node"); while (nodeXml) { this->LoadNode(nodeXml, _mesh, transform); nodeXml = nodeXml->NextSiblingElement("node"); } if (_elem->FirstChildElement("instance_node")) { std::string nodeURLStr = _elem->FirstChildElement("instance_node")->Attribute("url"); nodeXml = this->GetElementId("node", nodeURLStr); if (!nodeXml) { gzerr << "Unable to find node[" << nodeURLStr << "]\n"; return; } this->LoadNode(nodeXml, _mesh, transform); return; } else nodeXml = _elem; instGeomXml = nodeXml->FirstChildElement("instance_geometry"); while (instGeomXml) { std::string geomURL = instGeomXml->Attribute("url"); TiXmlElement *geomXml = this->GetElementId("geometry", geomURL); this->dataPtr->materialMap.clear(); TiXmlElement *bindMatXml, *techniqueXml, *matXml; bindMatXml = instGeomXml->FirstChildElement("bind_material"); while (bindMatXml) { if ((techniqueXml = bindMatXml->FirstChildElement("technique_common"))) { matXml = techniqueXml->FirstChildElement("instance_material"); while (matXml) { std::string symbol = matXml->Attribute("symbol"); std::string target = matXml->Attribute("target"); this->dataPtr->materialMap[symbol] = target; matXml = matXml->NextSiblingElement("instance_material"); } } bindMatXml = bindMatXml->NextSiblingElement("bind_material"); } if (_mesh->GetSkeleton()) _mesh->GetSkeleton()->SetNumVertAttached(0); this->LoadGeometry(geomXml, transform, _mesh); instGeomXml = instGeomXml->NextSiblingElement("instance_geometry"); } TiXmlElement *instContrXml = nodeXml->FirstChildElement("instance_controller"); while (instContrXml) { std::string contrURL = instContrXml->Attribute("url"); TiXmlElement *contrXml = this->GetElementId("controller", contrURL); this->dataPtr->materialMap.clear(); TiXmlElement *bindMatXml, *techniqueXml, *matXml; bindMatXml = instContrXml->FirstChildElement("bind_material"); while (bindMatXml) { if ((techniqueXml = bindMatXml->FirstChildElement("technique_common"))) { matXml = techniqueXml->FirstChildElement("instance_material"); while (matXml) { std::string symbol = matXml->Attribute("symbol"); std::string target = matXml->Attribute("target"); this->dataPtr->materialMap[symbol] = target; matXml = matXml->NextSiblingElement("instance_material"); } } bindMatXml = bindMatXml->NextSiblingElement("bind_material"); } std::vector<TiXmlElement*> rootNodeXmls; TiXmlNode *child = nullptr; while ((child = instContrXml->IterateChildren("skeleton", child))) { TiXmlElement *instSkelXml = child->ToElement(); std::string rootURL = instSkelXml->GetText(); rootNodeXmls.emplace_back(this->GetElementId("node", rootURL)); } // no skeleton tag present, assume whole scene is a skeleton if (rootNodeXmls.empty()) { TiXmlNode *childNode = nullptr; while ((childNode = this->dataPtr->currentScene->IterateChildren("node", childNode))) { rootNodeXmls.emplace_back(childNode->ToElement()); } } this->LoadController(contrXml, rootNodeXmls, transform, _mesh); instContrXml = instContrXml->NextSiblingElement("instance_controller"); } } ///////////////////////////////////////////////// ignition::math::Matrix4d ColladaLoader::LoadNodeTransform(TiXmlElement *_elem) { ignition::math::Matrix4d transform(ignition::math::Matrix4d::Identity); if (_elem->FirstChildElement("matrix")) { std::string matrixStr = _elem->FirstChildElement("matrix")->GetText(); std::istringstream iss(matrixStr); std::vector<double> values(16); for (unsigned int i = 0; i < 16; ++i) iss >> values[i]; transform.Set(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); } else { if (_elem->FirstChildElement("translate")) { std::string transStr = _elem->FirstChildElement("translate")->GetText(); ignition::math::Vector3d translate; translate = boost::lexical_cast<ignition::math::Vector3d>(transStr); // translate *= this->dataPtr->meter; transform.SetTranslation(translate); } TiXmlElement *rotateXml = _elem->FirstChildElement("rotate"); while (rotateXml) { ignition::math::Matrix3d mat; ignition::math::Vector3d axis; double angle; std::string rotateStr = rotateXml->GetText(); std::istringstream iss(rotateStr); iss >> axis.X() >> axis.Y() >> axis.Z(); iss >> angle; mat.Axis(axis, IGN_DTOR(angle)); ignition::math::Matrix4d mat4(ignition::math::Matrix4d::Identity); mat4 = mat; transform = transform * mat4; rotateXml = rotateXml->NextSiblingElement("rotate"); } if (_elem->FirstChildElement("scale")) { std::string scaleStr = _elem->FirstChildElement("scale")->GetText(); ignition::math::Vector3d scale; scale = boost::lexical_cast<ignition::math::Vector3d>(scaleStr); ignition::math::Matrix4d scaleMat; scaleMat.Scale(scale); transform = transform * scaleMat; } } return transform; } ///////////////////////////////////////////////// void ColladaLoader::LoadController(TiXmlElement *_contrXml, const std::vector<TiXmlElement*> &rootNodeXmls, const ignition::math::Matrix4d &_transform, Mesh *_mesh) { TiXmlElement *skinXml = _contrXml->FirstChildElement("skin"); std::string geomURL = skinXml->Attribute("source"); ignition::math::Matrix4d bindTrans; std::string matrixStr = skinXml->FirstChildElement("bind_shape_matrix")->GetText(); std::istringstream iss(matrixStr); std::vector<double> values(16); for (unsigned int i = 0; i < 16; ++i) iss >> values[i]; bindTrans.Set(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); TiXmlElement *jointsXml = skinXml->FirstChildElement("joints"); std::string jointsURL, invBindMatURL; TiXmlElement *inputXml = jointsXml->FirstChildElement("input"); while (inputXml) { std::string semantic = inputXml->Attribute("semantic"); std::string source = inputXml->Attribute("source"); if (semantic == "JOINT") jointsURL = source; else { if (semantic == "INV_BIND_MATRIX") invBindMatURL = source; } inputXml = inputXml->NextSiblingElement("input"); } jointsXml = this->GetElementId("source", jointsURL); if (!jointsXml) { gzerr << "Could not find node[" << jointsURL << "]\n"; gzthrow("Faild to parse skinning information in Collada file."); } std::string jointsStr = jointsXml->FirstChildElement("Name_array")->GetText(); std::vector<std::string> joints; boost::split(joints, jointsStr, boost::is_any_of(" \t")); // Load the skeleton Skeleton *skeleton = nullptr; if (_mesh->HasSkeleton()) skeleton = _mesh->GetSkeleton(); for (TiXmlElement *rootNodeXml : rootNodeXmls) { SkeletonNode *rootSkelNode = this->LoadSkeletonNodes(rootNodeXml, nullptr); if (skeleton) this->MergeSkeleton(skeleton, rootSkelNode); else { skeleton = new Skeleton(rootSkelNode); _mesh->SetSkeleton(skeleton); } } skeleton->SetBindShapeTransform(bindTrans); TiXmlElement *rootXml = _contrXml->GetDocument()->RootElement(); if (rootXml->FirstChildElement("library_animations")) { this->LoadAnimations(rootXml->FirstChildElement("library_animations"), skeleton); } TiXmlElement *invBMXml = this->GetElementId("source", invBindMatURL); if (!invBMXml) { gzerr << "Could not find node[" << invBindMatURL << "]\n"; gzthrow("Faild to parse skinning information in Collada file."); } std::string posesStr = invBMXml->FirstChildElement("float_array")->GetText(); std::vector<std::string> strs; boost::split(strs, posesStr, boost::is_any_of(" \t")); for (unsigned int i = 0; i < joints.size(); ++i) { unsigned int id = i * 16; ignition::math::Matrix4d mat; mat.Set(ignition::math::parseFloat(strs[id + 0]), ignition::math::parseFloat(strs[id + 1]), ignition::math::parseFloat(strs[id + 2]), ignition::math::parseFloat(strs[id + 3]), ignition::math::parseFloat(strs[id + 4]), ignition::math::parseFloat(strs[id + 5]), ignition::math::parseFloat(strs[id + 6]), ignition::math::parseFloat(strs[id + 7]), ignition::math::parseFloat(strs[id + 8]), ignition::math::parseFloat(strs[id + 9]), ignition::math::parseFloat(strs[id + 10]), ignition::math::parseFloat(strs[id + 11]), ignition::math::parseFloat(strs[id + 12]), ignition::math::parseFloat(strs[id + 13]), ignition::math::parseFloat(strs[id + 14]), ignition::math::parseFloat(strs[id + 15])); skeleton->GetNodeByName(joints[i])->SetInverseBindTransform(mat); } TiXmlElement *vertWeightsXml = skinXml->FirstChildElement("vertex_weights"); inputXml = vertWeightsXml->FirstChildElement("input"); unsigned int jOffset = 0; unsigned int wOffset = 0; std::string weightsURL; while (inputXml) { std::string semantic = inputXml->Attribute("semantic"); std::string source = inputXml->Attribute("source"); int offset; inputXml->Attribute("offset", &offset); if (semantic == "JOINT") jOffset = offset; else if (semantic == "WEIGHT") { weightsURL = source; wOffset = offset; } inputXml = inputXml->NextSiblingElement("input"); } TiXmlElement *weightsXml = this->GetElementId("source", weightsURL); std::string wString = weightsXml->FirstChildElement("float_array")->GetText(); std::vector<std::string> wStrs; boost::split(wStrs, wString, boost::is_any_of(" \t")); std::vector<float> weights; for (unsigned int i = 0; i < wStrs.size(); ++i) weights.push_back(ignition::math::parseFloat(wStrs[i])); std::string cString = vertWeightsXml->FirstChildElement("vcount")->GetText(); std::string vString = vertWeightsXml->FirstChildElement("v")->GetText(); std::vector<std::string> vCountStrs; std::vector<std::string> vStrs; boost::split(vCountStrs, cString, boost::is_any_of(" \t")); boost::split(vStrs, vString, boost::is_any_of(" \t")); std::vector<unsigned int> vCount; std::vector<unsigned int> v; for (unsigned int i = 0; i < vCountStrs.size(); ++i) vCount.push_back(ignition::math::parseInt(vCountStrs[i])); for (unsigned int i = 0; i < vStrs.size(); ++i) v.push_back(ignition::math::parseInt(vStrs[i])); skeleton->SetNumVertAttached(vCount.size()); unsigned int vIndex = 0; for (unsigned int i = 0; i < vCount.size(); ++i) { for (unsigned int j = 0; j < vCount[i]; ++j) { skeleton->AddVertNodeWeight(i, joints[v[vIndex + jOffset]], weights[v[vIndex + wOffset]]); vIndex += (jOffset + wOffset + 1); } } TiXmlElement *geomXml = this->GetElementId("geometry", geomURL); this->LoadGeometry(geomXml, _transform, _mesh); } ///////////////////////////////////////////////// void ColladaLoader::LoadAnimations(TiXmlElement *_xml, Skeleton *_skel) { TiXmlElement *childXml = _xml->FirstChildElement("animation"); if (childXml->FirstChildElement("animation")) { while (childXml) { this->LoadAnimationSet(childXml, _skel); childXml = childXml->NextSiblingElement("animation"); } } else this->LoadAnimationSet(_xml, _skel); } ///////////////////////////////////////////////// void ColladaLoader::LoadAnimationSet(TiXmlElement *_xml, Skeleton *_skel) { std::stringstream animName; if (_xml->Attribute("name")) animName << _xml->Attribute("name"); else if (_xml->Attribute("id")) animName << _xml->Attribute("id"); else animName << "animation" << (_skel->GetNumAnimations() + 1); RawSkeletonAnim animation; TiXmlElement *animXml = _xml->FirstChildElement("animation"); while (animXml) { TiXmlElement *chanXml = animXml->FirstChildElement("channel"); while (chanXml) { std::string sourceURL = chanXml->Attribute("source"); std::string targetStr = chanXml->Attribute("target"); std::string targetBone = targetStr.substr(0, targetStr.find('/')); char sep = '0'; if (targetStr.find('(') != std::string::npos) sep = '('; else if (targetStr.find('.') != std::string::npos) sep = '.'; std::string targetTrans; if (sep == '0') targetTrans = targetStr.substr(targetStr.find('/') + 1); else targetTrans = targetStr.substr(targetStr.find('/') + 1, targetStr.find(sep) - targetStr.find('/') - 1); std::string idxStr = targetStr.substr(targetStr.find(sep) + 1); int idx1 = -1; int idx2 = -1; if (sep == '.') idx1 = (idxStr == "X") ? 0 : ((idxStr == "Y") ? 1 : ((idxStr == "Z") ? 2 : ((idxStr == "ANGLE") ? 3 : -1))); else if (sep == '(') { std::string idx1Str = idxStr.substr(0, 1); idx1 = ignition::math::parseInt(idx1Str); if (idxStr.length() > 4) { std::string idx2Str = idxStr.substr(3, 1); idx2 = ignition::math::parseInt(idx2Str); } } TiXmlElement *frameTimesXml = nullptr; TiXmlElement *frameTransXml = nullptr; TiXmlElement *sampXml = this->GetElementId("sampler", sourceURL); TiXmlElement *inputXml = sampXml->FirstChildElement("input"); while (inputXml) { std::string semantic = inputXml->Attribute("semantic"); if (semantic == "INPUT") frameTimesXml = this->GetElementId("source", inputXml->Attribute("source")); else if (semantic == "OUTPUT") frameTransXml = this->GetElementId("source", inputXml->Attribute("source")); /// FIXME interpolation semantic? inputXml = inputXml->NextSiblingElement("input"); } TiXmlElement *timeArray = frameTimesXml->FirstChildElement("float_array"); std::string timeStr = timeArray->GetText(); std::vector<std::string> timeStrs; boost::split(timeStrs, timeStr, boost::is_any_of(" \t")); std::vector<double> times; for (unsigned int i = 0; i < timeStrs.size(); ++i) times.push_back(ignition::math::parseFloat(timeStrs[i])); TiXmlElement *output = frameTransXml->FirstChildElement("float_array"); std::string outputStr = output->GetText(); std::vector<std::string> outputStrs; boost::split(outputStrs, outputStr, boost::is_any_of(" \t")); std::vector<double> values; for (unsigned int i = 0; i < outputStrs.size(); ++i) values.push_back(ignition::math::parseFloat(outputStrs[i])); TiXmlElement *accessor = frameTransXml->FirstChildElement("technique_common"); accessor = accessor->FirstChildElement("accessor"); // stride is optional, default to 1 unsigned int stride = 1; auto *strideAttribute = accessor->Attribute("stride"); if (strideAttribute) { stride = static_cast<unsigned int>( ignition::math::parseInt(strideAttribute)); } SkeletonNode *targetNode = _skel->GetNodeById(targetBone); if (targetNode == nullptr) { TiXmlElement *targetNodeXml = this->GetElementId("node", targetBone); if (targetNodeXml == nullptr) { gzerr << "Failed to load animation, '" << targetBone << "' not found" << std::endl; gzthrow("Failed to load animation"); } targetNode = this->LoadSkeletonNodes(targetNodeXml, nullptr); this->MergeSkeleton(_skel, targetNode); } // In COLLOADA, `target` is specified to be the `id` of a node, however // the nodes are identified by `name` in this loader. Here, we resolve // `targetBone` to the node's `name` to prevent missing animations. std::string targetBoneName = targetNode->GetName(); for (unsigned int i = 0; i < times.size(); ++i) { if (animation[targetBoneName].find(times[i]) == animation[targetBoneName].end()) { animation[targetBoneName][times[i]] = _skel->GetNodeById(targetBone)->GetTransforms(); } std::vector<NodeTransform> *frame = &animation[targetBoneName][times[i]]; for (unsigned int j = 0; j < (*frame).size(); ++j) { NodeTransform *nt = &((*frame)[j]); if (nt->GetSID() == targetTrans) { if (idx1 != -1) { int index = (idx2 == -1) ? idx1 : (idx1 * 4) + idx2; nt->SetComponent(index, values[i]); } else for (unsigned int k = 0; k < stride; k++) nt->SetComponent(k, values[(i*stride) + k]); } } } chanXml = chanXml->NextSiblingElement("channel"); } animXml = animXml->NextSiblingElement("animation"); } SkeletonAnimation *anim = new SkeletonAnimation(animName.str()); for (RawSkeletonAnim::iterator iter = animation.begin(); iter != animation.end(); ++iter) for (RawNodeAnim::iterator niter = iter->second.begin(); niter != iter->second.end(); ++niter) { ignition::math::Matrix4d transform(ignition::math::Matrix4d::Identity); for (unsigned int i = 0; i < niter->second.size(); ++i) { niter->second[i].RecalculateMatrix(); transform = transform * niter->second[i](); } anim->AddKeyFrame(iter->first, niter->first, transform); } _skel->AddAnimation(anim); } ///////////////////////////////////////////////// SkeletonNode* ColladaLoader::LoadSingleSkeletonNode(TiXmlElement *_xml, SkeletonNode *_parent) { std::string name; if (_xml->Attribute("sid")) name = _xml->Attribute("sid"); else if (_xml->Attribute("name")) name = _xml->Attribute("name"); else name = _xml->Attribute("id"); SkeletonNode* node = new SkeletonNode(_parent, name, _xml->Attribute("id")); if (!_xml->Attribute("type") || std::string(_xml->Attribute("type")) == "NODE") { node->SetType(SkeletonNode::NODE); } return node; } ///////////////////////////////////////////////// SkeletonNode* ColladaLoader::LoadSkeletonNodes(TiXmlElement *_xml, SkeletonNode *_parent) { SkeletonNode *node = this->LoadSingleSkeletonNode(_xml, _parent); this->SetSkeletonNodeTransform(_xml, node); TiXmlElement *childXml = _xml->FirstChildElement("node"); while (childXml) { this->LoadSkeletonNodes(childXml, node); childXml = childXml->NextSiblingElement("node"); } return node; } ///////////////////////////////////////////////// void ColladaLoader::SetSkeletonNodeTransform(TiXmlElement *_elem, SkeletonNode *_node) { ignition::math::Matrix4d transform(ignition::math::Matrix4d::Identity); if (_elem->FirstChildElement("matrix")) { std::string matrixStr = _elem->FirstChildElement("matrix")->GetText(); std::istringstream iss(matrixStr); std::vector<double> values(16); for (unsigned int i = 0; i < 16; ++i) iss >> values[i]; transform.Set(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); NodeTransform nt(transform); nt.SetSourceValues(transform); if (_elem->FirstChildElement("matrix")->Attribute("sid")) nt.SetSID(_elem->FirstChildElement("matrix")->Attribute("sid")); _node->AddRawTransform(nt); } else { if (_elem->FirstChildElement("translate")) { std::string transStr = _elem->FirstChildElement("translate")->GetText(); ignition::math::Vector3d translate; translate = boost::lexical_cast<ignition::math::Vector3d>(transStr); // translate *= this->dataPtr->meter; transform.SetTranslation(translate); NodeTransform nt(transform); if (_elem->FirstChildElement("translate")->Attribute("sid")) nt.SetSID(_elem->FirstChildElement("translate")->Attribute("sid")); nt.SetType(NodeTransform::TRANSLATE); nt.SetSourceValues(translate); _node->AddRawTransform(nt); } TiXmlElement *rotateXml = _elem->FirstChildElement("rotate"); while (rotateXml) { ignition::math::Matrix3d mat; ignition::math::Vector3d axis; double angle; std::string rotateStr = rotateXml->GetText(); std::istringstream iss(rotateStr); iss >> axis.X() >> axis.Y() >> axis.Z(); iss >> angle; mat.Axis(axis, IGN_DTOR(angle)); ignition::math::Matrix4d mat4(ignition::math::Matrix4d::Identity); mat4 = mat; NodeTransform nt(mat4); if (rotateXml->Attribute("sid")) nt.SetSID(rotateXml->Attribute("sid")); nt.SetType(NodeTransform::ROTATE); nt.SetSourceValues(axis, angle); _node->AddRawTransform(nt); transform = transform * mat4; rotateXml = rotateXml->NextSiblingElement("rotate"); } if (_elem->FirstChildElement("scale")) { std::string scaleStr = _elem->FirstChildElement("scale")->GetText(); ignition::math::Vector3d scale; scale = boost::lexical_cast<ignition::math::Vector3d>(scaleStr); ignition::math::Matrix4d scaleMat; scaleMat.Scale(scale); NodeTransform nt(scaleMat); TiXmlElement *matrix = _elem->FirstChildElement("matrix"); if (matrix && matrix->Attribute("sid")) nt.SetSID(_elem->FirstChildElement("matrix")->Attribute("sid")); nt.SetType(NodeTransform::SCALE); nt.SetSourceValues(scale); _node->AddRawTransform(nt); transform = transform * scaleMat; } } _node->SetTransform(transform); } ///////////////////////////////////////////////// void ColladaLoader::LoadGeometry(TiXmlElement *_xml, const ignition::math::Matrix4d &_transform, Mesh *_mesh) { TiXmlElement *meshXml = _xml->FirstChildElement("mesh"); TiXmlElement *childXml; if (!meshXml) return; childXml = meshXml->FirstChildElement("triangles"); while (childXml) { this->LoadTriangles(childXml, _transform, _mesh); childXml = childXml->NextSiblingElement("triangles"); } childXml = meshXml->FirstChildElement("polylist"); while (childXml) { this->LoadPolylist(childXml, _transform, _mesh); childXml = childXml->NextSiblingElement("polylist"); } childXml = meshXml->FirstChildElement("lines"); while (childXml) { this->LoadLines(childXml, _transform, _mesh); childXml = childXml->NextSiblingElement("lines"); } } ///////////////////////////////////////////////// TiXmlElement *ColladaLoader::GetElementId(const std::string &_name, const std::string &_id) { return this->GetElementId(this->dataPtr->colladaXml, _name, _id); } ///////////////////////////////////////////////// TiXmlElement *ColladaLoader::GetElementId(TiXmlElement *_parent, const std::string &_name, const std::string &_id) { std::string id = _id; if (id.length() > 0 && id[0] == '#') id.erase(0, 1); if ((id.empty() && _parent->Value() == _name) || (_parent->Attribute("id") && _parent->Attribute("id") == id) || (_parent->Attribute("sid") && _parent->Attribute("sid") == id)) { return _parent; } TiXmlElement *elem = _parent->FirstChildElement(); while (elem) { TiXmlElement *result = this->GetElementId(elem, _name, _id); if (result) { return result; } elem = elem->NextSiblingElement(); } return nullptr; } ///////////////////////////////////////////////// void ColladaLoader::LoadVertices(const std::string &_id, const ignition::math::Matrix4d &_transform, std::vector<ignition::math::Vector3d> &_verts, std::vector<ignition::math::Vector3d> &_norms) { std::map<unsigned int, unsigned int> vertDup; std::map<unsigned int, unsigned int> normDup; this->LoadVertices(_id, _transform, _verts, _norms, vertDup, normDup); } ///////////////////////////////////////////////// void ColladaLoader::LoadVertices(const std::string &_id, const ignition::math::Matrix4d &_transform, std::vector<ignition::math::Vector3d> &_verts, std::vector<ignition::math::Vector3d> &_norms, std::map<unsigned int, unsigned int> &_vertDups, std::map<unsigned int, unsigned int> &_normDups) { TiXmlElement *verticesXml = this->GetElementId(this->dataPtr->colladaXml, "vertices", _id); if (!verticesXml) { gzerr << "Unable to find vertices[" << _id << "] in collada file\n"; return; } TiXmlElement *inputXml = verticesXml->FirstChildElement("input"); while (inputXml) { std::string semantic = inputXml->Attribute("semantic"); std::string sourceStr = inputXml->Attribute("source"); if (semantic == "NORMAL") { this->LoadNormals(sourceStr, _transform, _norms, _normDups); } else if (semantic == "POSITION") { this->LoadPositions(sourceStr, _transform, _verts, _vertDups); } inputXml = inputXml->NextSiblingElement("input"); } } ///////////////////////////////////////////////// void ColladaLoader::LoadPositions(const std::string &_id, const ignition::math::Matrix4d &_transform, std::vector<ignition::math::Vector3d> &_values, std::map<unsigned int, unsigned int> &_duplicates) { if (this->dataPtr->positionIds.find(_id) != this->dataPtr->positionIds.end()) { _values = this->dataPtr->positionIds[_id]; _duplicates = this->dataPtr->positionDuplicateMap[_id]; return; } TiXmlElement *sourceXml = this->GetElementId("source", _id); if (!sourceXml) { gzerr << "Unable to find source\n"; return; } TiXmlElement *floatArrayXml = sourceXml->FirstChildElement("float_array"); if (!floatArrayXml || !floatArrayXml->GetText()) { int count = 1; if (floatArrayXml && floatArrayXml->Attribute("count")) { try { count = boost::lexical_cast<int>(floatArrayXml->Attribute("count")); } catch(...) { // Do nothing. Messages are printed out below. } } if (count) { gzerr << "Vertex source missing float_array element, " << "or count is invalid.\n"; } else { gzlog << "Vertex source has a float_array with a count of zero. " << "This is likely not desired\n"; } return; } std::string valueStr = floatArrayXml->GetText(); boost::unordered_map<ignition::math::Vector3d, unsigned int, Vector3Hash> unique; std::vector<std::string> strs; std::vector<std::string>::iterator iter, end; boost::split(strs, valueStr, boost::is_any_of(" \t")); end = strs.end(); for (iter = strs.begin(); iter != end; iter += 3) { ignition::math::Vector3d vec(ignition::math::parseFloat(*iter), ignition::math::parseFloat(*(iter+1)), ignition::math::parseFloat(*(iter+2))); vec = _transform * vec; _values.push_back(vec); // create a map of duplicate indices if (unique.find(vec) != unique.end()) _duplicates[_values.size()-1] = unique[vec]; else unique[vec] = _values.size()-1; } this->dataPtr->positionDuplicateMap[_id] = _duplicates; this->dataPtr->positionIds[_id] = _values; } ///////////////////////////////////////////////// void ColladaLoader::LoadNormals(const std::string &_id, const ignition::math::Matrix4d &_transform, std::vector<ignition::math::Vector3d> &_values, std::map<unsigned int, unsigned int> &_duplicates) { if (this->dataPtr->normalIds.find(_id) != this->dataPtr->normalIds.end()) { _values = this->dataPtr->normalIds[_id]; _duplicates = this->dataPtr->normalDuplicateMap[_id]; return; } ignition::math::Matrix4d rotMat = _transform; rotMat.SetTranslation(ignition::math::Vector3d::Zero); TiXmlElement *normalsXml = this->GetElementId("source", _id); if (!normalsXml) { gzerr << "Unable to find normals[" << _id << "] in collada file\n"; return; } TiXmlElement *floatArrayXml = normalsXml->FirstChildElement("float_array"); if (!floatArrayXml || !floatArrayXml->GetText()) { int count = 1; if (floatArrayXml && floatArrayXml->Attribute("count")) { try { count = boost::lexical_cast<int>(floatArrayXml->Attribute("count")); } catch(...) { // Do nothing. Messages are printed out below. } } if (count) { gzwarn << "Normal source missing float_array element, or count is " << "invalid.\n"; } else { gzlog << "Normal source has a float_array with a count of zero. " << "This is likely not desired\n"; } return; } boost::unordered_map<ignition::math::Vector3d, unsigned int, Vector3Hash> unique; std::string valueStr = floatArrayXml->GetText(); std::istringstream iss(valueStr); do { ignition::math::Vector3d vec; iss >> vec.X() >> vec.Y() >> vec.Z(); if (iss) { vec = rotMat * vec; vec.Normalize(); _values.push_back(vec); // create a map of duplicate indices if (unique.find(vec) != unique.end()) _duplicates[_values.size()-1] = unique[vec]; else unique[vec] = _values.size()-1; } } while (iss); this->dataPtr->normalDuplicateMap[_id] = _duplicates; this->dataPtr->normalIds[_id] = _values; } ///////////////////////////////////////////////// void ColladaLoader::LoadTexCoords(const std::string &_id, std::vector<ignition::math::Vector2d> &_values, std::map<unsigned int, unsigned int> &_duplicates) { if (this->dataPtr->texcoordIds.find(_id) != this->dataPtr->texcoordIds.end()) { _values = this->dataPtr->texcoordIds[_id]; _duplicates = this->dataPtr->texcoordDuplicateMap[_id]; return; } int stride = 0; int texCount = 0; int totCount = 0; // Get the source element for the texture coordinates. TiXmlElement *xml = this->GetElementId("source", _id); if (!xml) { gzerr << "Unable to find tex coords[" << _id << "] in collada file\n"; return; } // Get the array of float values. These are the raw values for the texture // coordinates. TiXmlElement *floatArrayXml = xml->FirstChildElement("float_array"); if (!floatArrayXml || !floatArrayXml->GetText()) { int count = 1; if (floatArrayXml && floatArrayXml->Attribute("count")) { try { count = boost::lexical_cast<int>(floatArrayXml->Attribute("count")); } catch(...) { // Do nothing. Messages are printed out below. } } if (count) { gzerr << "Normal source missing float_array element, or count is " << "invalid.\n"; } else { gzlog << "Normal source has a float_array with a count of zero. " << "This is likely not desired\n"; } return; } // Read in the total number of texture coordinate values else if (floatArrayXml->Attribute("count")) totCount = boost::lexical_cast<int>(floatArrayXml->Attribute("count")); else { gzerr << "<float_array> has no count attribute in texture coordinate " << "element with id[" << _id << "]\n"; return; } // The technique_common holds an <accessor> element that indicates how to // parse the float array. xml = xml->FirstChildElement("technique_common"); if (!xml) { gzerr << "Unable to find technique_common element for texture " << "coordinates with id[" << _id << "]\n"; return; } // Get the accessor XML element. xml = xml->FirstChildElement("accessor"); if (!xml) { gzerr << "Unable to find <accessor> as a child of <technique_common> " << "for texture coordinates with id[" << _id << "]\n"; return; } // Read in the stride for the texture coordinate values. The stride // indicates the number of values in the float array the comprise // a complete texture coordinate. if (xml->Attribute("stride")) stride = boost::lexical_cast<int>(xml->Attribute("stride")); else { gzerr << "<accessor> has no stride attribute in texture coordinate element " << "with id[" << _id << "]\n"; return; } // Read in the count of texture coordinates. if (xml->Attribute("count")) texCount = boost::lexical_cast<int>(xml->Attribute("count")); else { gzerr << "<accessor> has no count attribute in texture coordinate element " << "with id[" << _id << "]\n"; return; } // \TODO This is a good a GZ_ASSERT // The total number of texture values should equal the stride multiplied // by the number of texture coordinates. if (texCount * stride != totCount) { gzerr << "Error reading texture coordinates. Coordinate counts in element " "with id[" << _id << "] do not add up correctly\n"; return; } // Nothing to read. Don't print a warning because the collada file is // correct. if (totCount == 0) return; boost::unordered_map<ignition::math::Vector2d, unsigned int, Vector2dHash> unique; // Read the raw texture values, and split them on spaces. std::string valueStr = floatArrayXml->GetText(); std::vector<std::string> values; boost::split(values, valueStr, boost::is_any_of(" ")); // Read in all the texture coordinates. for (int i = 0; i < totCount; i += stride) { // We only handle 2D texture coordinates right now. ignition::math::Vector2d vec(boost::lexical_cast<double>(values[i]), 1.0 - boost::lexical_cast<double>(values[i+1])); _values.push_back(vec); // create a map of duplicate indices if (unique.find(vec) != unique.end()) { _duplicates[_values.size()-1] = unique[vec]; } else unique[vec] = _values.size()-1; } this->dataPtr->texcoordDuplicateMap[_id] = _duplicates; this->dataPtr->texcoordIds[_id] = _values; } ///////////////////////////////////////////////// Material *ColladaLoader::LoadMaterial(const std::string &_name) { if (this->dataPtr->materialIds.find(_name) != this->dataPtr->materialIds.end()) { return this->dataPtr->materialIds[_name]; } TiXmlElement *matXml = this->GetElementId("material", _name); if (!matXml || !matXml->FirstChildElement("instance_effect")) return nullptr; Material *mat = new Material(); std::string effectName = matXml->FirstChildElement("instance_effect")->Attribute("url"); TiXmlElement *effectXml = this->GetElementId("effect", effectName); TiXmlElement *commonXml = effectXml->FirstChildElement("profile_COMMON"); if (commonXml) { TiXmlElement *techniqueXml = commonXml->FirstChildElement("technique"); TiXmlElement *lambertXml = techniqueXml->FirstChildElement("lambert"); TiXmlElement *phongXml = techniqueXml->FirstChildElement("phong"); TiXmlElement *blinnXml = techniqueXml->FirstChildElement("blinn"); if (lambertXml) { this->LoadColorOrTexture(lambertXml, "ambient", mat); this->LoadColorOrTexture(lambertXml, "emission", mat); this->LoadColorOrTexture(lambertXml, "diffuse", mat); // order matters: transparency needs to be loaded before transparent. if (lambertXml->FirstChildElement("transparency")) { mat->SetTransparency( this->LoadFloat(lambertXml->FirstChildElement("transparency"))); } if (lambertXml->FirstChildElement("transparent")) { TiXmlElement *transXml = lambertXml->FirstChildElement("transparent"); this->LoadTransparent(transXml, mat); } else { // no <transparent> tag, revert to zero transparency mat->SetTransparency(0.0); } } else if (phongXml) { this->LoadColorOrTexture(phongXml, "ambient", mat); this->LoadColorOrTexture(phongXml, "emission", mat); this->LoadColorOrTexture(phongXml, "specular", mat); this->LoadColorOrTexture(phongXml, "diffuse", mat); if (phongXml->FirstChildElement("shininess")) mat->SetShininess( this->LoadFloat(phongXml->FirstChildElement("shininess"))); // order matters: transparency needs to be loaded before transparent if (phongXml->FirstChildElement("transparency")) mat->SetTransparency( this->LoadFloat(phongXml->FirstChildElement("transparency"))); if (phongXml->FirstChildElement("transparent")) { TiXmlElement *transXml = phongXml->FirstChildElement("transparent"); this->LoadTransparent(transXml, mat); } else { // no <transparent> tag, revert to zero transparency mat->SetTransparency(0.0); } } else if (blinnXml) { this->LoadColorOrTexture(blinnXml, "ambient", mat); this->LoadColorOrTexture(blinnXml, "emission", mat); this->LoadColorOrTexture(blinnXml, "specular", mat); this->LoadColorOrTexture(blinnXml, "diffuse", mat); if (blinnXml->FirstChildElement("shininess")) mat->SetShininess( this->LoadFloat(blinnXml->FirstChildElement("shininess"))); // order matters: transparency needs to be loaded before transparent if (blinnXml->FirstChildElement("transparency")) mat->SetTransparency( this->LoadFloat(blinnXml->FirstChildElement("transparency"))); if (blinnXml->FirstChildElement("transparent")) { TiXmlElement *transXml = blinnXml->FirstChildElement("transparent"); this->LoadTransparent(transXml, mat); } else { // no <transparent> tag, revert to zero transparency mat->SetTransparency(0.0); } } } TiXmlElement *glslXml = effectXml->FirstChildElement("profile_GLSL"); if (glslXml) gzerr << "profile_GLSL unsupported\n"; TiXmlElement *cgXml = effectXml->FirstChildElement("profile_CG"); if (cgXml) gzerr << "profile_CG unsupported\n"; this->dataPtr->materialIds[_name] = mat; return mat; } ///////////////////////////////////////////////// void ColladaLoader::LoadColorOrTexture(TiXmlElement *_elem, const std::string &_type, Material *_mat) { if (!_elem || !_elem->FirstChildElement(_type)) return; TiXmlElement *typeElem = _elem->FirstChildElement(_type); if (typeElem->FirstChildElement("color")) { std::string colorStr = typeElem->FirstChildElement("color")->GetText(); auto color = boost::lexical_cast<ignition::math::Color>(colorStr); if (_type == "diffuse") _mat->SetDiffuse(color); else if (_type == "ambient") _mat->SetAmbient(color); else if (_type == "emission") _mat->SetEmissive(color); else if (_type == "specular") _mat->SetSpecular(color); } else if (typeElem->FirstChildElement("texture")) { if (_type == "ambient") { gzwarn << "ambient texture not supported" << std::endl; return; } if (_type == "emission") { gzwarn << "emission texture not supported" << std::endl; return; } if (_type == "specular") { gzwarn << "specular texture not supported" << std::endl; return; } // gazebo rendering pipeline doesn't respect the blend mode, here we set // the diffuse to full white as a workaround. if (_type == "diffuse" && _mat->GetBlendMode() == Material::BlendMode::REPLACE) { _mat->SetDiffuse(ignition::math::Color(1, 1, 1, 1)); } _mat->SetLighting(true); TiXmlElement *imageXml = nullptr; std::string textureName = typeElem->FirstChildElement("texture")->Attribute("texture"); TiXmlElement *textureXml = this->GetElementId("newparam", textureName); if (textureXml) { if (std::string(textureXml->Value()) == "image") { imageXml = textureXml; } else { TiXmlElement *sampler = textureXml->FirstChildElement("sampler2D"); if (sampler) { std::string sourceName = sampler->FirstChildElement("source")->GetText(); TiXmlElement *sourceXml = this->GetElementId("newparam", sourceName); if (sourceXml) { TiXmlElement *surfaceXml = sourceXml->FirstChildElement("surface"); if (surfaceXml && surfaceXml->FirstChildElement("init_from")) { imageXml = this->GetElementId("image", surfaceXml->FirstChildElement("init_from")->GetText()); } } } } } else { imageXml = this->GetElementId("image", textureName); } if (imageXml && imageXml->FirstChildElement("init_from")) { std::string imgFile = imageXml->FirstChildElement("init_from")->GetText(); _mat->SetTextureImage(imgFile, this->dataPtr->path); } } } ///////////////////////////////////////////////// void ColladaLoader::LoadPolylist(TiXmlElement *_polylistXml, const ignition::math::Matrix4d &_transform, Mesh *_mesh) { // This function parses polylist types in collada into // a set of triangle meshes. The assumption is that // each polylist polygon is convex, and we do decomposion // by anchoring each triangle about vertex 0 or each polygon SubMesh *subMesh = new SubMesh; subMesh->SetName(this->dataPtr->currentNodeName); bool combinedVertNorms = false; subMesh->SetPrimitiveType(SubMesh::TRIANGLES); if (_polylistXml->Attribute("material")) { std::map<std::string, std::string>::iterator iter; std::string matStr = _polylistXml->Attribute("material"); int matIndex = -1; iter = this->dataPtr->materialMap.find(matStr); if (iter != this->dataPtr->materialMap.end()) matStr = iter->second; common::Material *mat = this->LoadMaterial(matStr); matIndex = _mesh->GetMaterialIndex(mat); if (matIndex < 0) matIndex = _mesh->AddMaterial(mat); if (matIndex < 0) gzwarn << "Unable to add material[" << matStr << "]\n"; else subMesh->SetMaterialIndex(matIndex); } TiXmlElement *polylistInputXml = _polylistXml->FirstChildElement("input"); std::vector<ignition::math::Vector3d> verts; std::vector<ignition::math::Vector3d> norms; std::vector<ignition::math::Vector2d> texcoords; const unsigned int VERTEX = 0; const unsigned int NORMAL = 1; const unsigned int TEXCOORD = 2; unsigned int otherSemantics = TEXCOORD + 1; // look up table of position/normal/texcoord duplicate indices std::map<unsigned int, unsigned int> texDupMap; std::map<unsigned int, unsigned int> normalDupMap; std::map<unsigned int, unsigned int> positionDupMap; ignition::math::Matrix4d bindShapeMat(ignition::math::Matrix4d::Identity); if (_mesh->HasSkeleton()) bindShapeMat = _mesh->GetSkeleton()->BindShapeTransform(); // read input elements. A vector of int is used because there can be // multiple TEXCOORD inputs. std::map<const unsigned int, std::set<int>> inputs; unsigned int inputSize = 0; while (polylistInputXml) { std::string semantic = polylistInputXml->Attribute("semantic"); std::string source = polylistInputXml->Attribute("source"); std::string offset = polylistInputXml->Attribute("offset"); if (semantic == "VERTEX") { unsigned int count = norms.size(); this->LoadVertices(source, _transform, verts, norms, positionDupMap, normalDupMap); if (norms.size() > count) combinedVertNorms = true; inputs[VERTEX].insert(ignition::math::parseInt(offset)); } else if (semantic == "NORMAL") { this->LoadNormals(source, _transform, norms, normalDupMap); combinedVertNorms = false; inputs[NORMAL].insert(ignition::math::parseInt(offset)); } else if (semantic == "TEXCOORD") { this->LoadTexCoords(source, texcoords, texDupMap); inputs[TEXCOORD].insert(ignition::math::parseInt(offset)); } else { inputs[otherSemantics++].insert(ignition::math::parseInt(offset)); gzwarn << "Polylist input semantic: '" << semantic << "' is currently" << " not supported" << std::endl; } polylistInputXml = polylistInputXml->NextSiblingElement("input"); } std::set<int> totalInputs; for (const auto &input : inputs) { totalInputs.insert(input.second.begin(), input.second.end()); } inputSize += totalInputs.size(); // read vcount // break poly into triangles // if vcount >= 4, anchor around 0 (note this is bad for concave elements) // e.g. if vcount = 4, break into triangle 1: [0,1,2], triangle 2: [0,2,3] std::vector<std::string> vcountStrs; TiXmlElement *vcountXml = _polylistXml->FirstChildElement("vcount"); std::string vcountStr = vcountXml->GetText(); boost::split(vcountStrs, vcountStr, boost::is_any_of(" \t")); std::vector<int> vcounts; for (unsigned int j = 0; j < vcountStrs.size(); ++j) vcounts.push_back(ignition::math::parseInt(vcountStrs[j])); // read p TiXmlElement *pXml = _polylistXml->FirstChildElement("p"); std::string pStr = pXml->GetText(); // vertexIndexMap is a map of collada vertex index to Gazebo submesh vertex // indices, used for identifying vertices that can be shared. std::map<unsigned int, std::vector<GeometryIndices> > vertexIndexMap; unsigned int *values = new unsigned int[inputSize]; memset(values, 0, inputSize); std::vector<std::string> strs; boost::split(strs, pStr, boost::is_any_of(" \t")); std::vector<std::string>::iterator strsIter = strs.begin(); for (unsigned int l = 0; l < vcounts.size(); ++l) { // put us at the beginning of the polygon list if (l > 0) strsIter += inputSize*vcounts[l-1]; for (unsigned int k = 2; k < (unsigned int)vcounts[l]; ++k) { // if vcounts[l] = 5, then read 0,1,2, then 0,2,3, 0,3,4,... // here k = the last number in the series // j is the triangle loop for (unsigned int j = 0; j < 3; ++j) { // break polygon into triangles unsigned int triangle_index; if (j == 0) triangle_index = 0; if (j == 1) triangle_index = (k-1)*inputSize; if (j == 2) triangle_index = (k)*inputSize; for (unsigned int i = 0; i < inputSize; ++i) { values[i] = ignition::math::parseInt(strsIter[triangle_index+i]); /*gzerr << "debug parsing " << " poly-i[" << l << "] tri-end-index[" << k << "] tri-vertex-i[" << j << "] triangle[" << triangle_index << "] input[" << i << "] value[" << values[i] << "]\n"; */ } unsigned int daeVertIndex = 0; bool addIndex = inputs[VERTEX].empty(); // find a set of vertex/normal/texcoord that can be reused // only do this if the mesh has vertices if (!inputs[VERTEX].empty()) { // Get the vertex position index value. If it is a duplicate then use // the existing index instead daeVertIndex = values[*inputs[VERTEX].begin()]; if (positionDupMap.find(daeVertIndex) != positionDupMap.end()) daeVertIndex = positionDupMap[daeVertIndex]; // if the vertex index has not been previously added then just add it. if (vertexIndexMap.find(daeVertIndex) == vertexIndexMap.end()) { addIndex = true; } else { // if the vertex index was previously added, check to see if it has // the same normal and texcoord index values bool toDuplicate = true; unsigned int reuseIndex = 0; std::vector<GeometryIndices> inputValues = vertexIndexMap[daeVertIndex]; for (unsigned int i = 0; i < inputValues.size(); ++i) { GeometryIndices iv = inputValues[i]; bool normEqual = false; bool texEqual = false; if (!inputs[NORMAL].empty()) { // Get the vertex normal index value. If the normal is a // duplicate then reset the index to the first instance of the // duplicated position unsigned int remappedNormalIndex = values[*inputs[NORMAL].begin()]; if (normalDupMap.find(remappedNormalIndex) != normalDupMap.end()) { remappedNormalIndex = normalDupMap[remappedNormalIndex]; } if (iv.normalIndex == remappedNormalIndex) normEqual = true; } if (!inputs[TEXCOORD].empty()) { // \todo: Add support for multiple texture maps to SubMesh. // Here we are only using the first texture coordinates, when // multiple could have been specified. See Gazebo issue #532. // Get the vertex texcoord index value. If the texcoord is a // duplicate then reset the index to the first instance of the // duplicated texcoord unsigned int remappedTexcoordIndex = values[*inputs[TEXCOORD].begin()]; if (texDupMap.find(remappedTexcoordIndex) != texDupMap.end()) remappedTexcoordIndex = texDupMap[remappedTexcoordIndex]; texEqual = iv.texcoordIndex == remappedTexcoordIndex; } // if the vertex has matching normal and texcoord index values // then the vertex can be reused. if ((inputs[NORMAL].empty() || normEqual) && (inputs[TEXCOORD].empty() || texEqual)) { // found a vertex that can be shared. toDuplicate = false; reuseIndex = iv.mappedIndex; subMesh->AddIndex(reuseIndex); break; } } addIndex = toDuplicate; } } // if the vertex index is new or can not be shared then add it if (addIndex) { GeometryIndices input; if (!inputs[VERTEX].empty()) { subMesh->AddVertex(verts[daeVertIndex]); unsigned int newVertIndex = subMesh->GetVertexCount()-1; subMesh->AddIndex(newVertIndex); if (combinedVertNorms) subMesh->AddNormal(norms[daeVertIndex]); if (_mesh->HasSkeleton()) { subMesh->SetVertex(newVertIndex, bindShapeMat * subMesh->Vertex(newVertIndex)); Skeleton *skel = _mesh->GetSkeleton(); for (unsigned int i = 0; i < skel->GetNumVertNodeWeights(daeVertIndex); ++i) { std::pair<std::string, double> node_weight = skel->GetVertNodeWeight(daeVertIndex, i); SkeletonNode *node = _mesh->GetSkeleton()->GetNodeByName(node_weight.first); subMesh->AddNodeAssignment(subMesh->GetVertexCount()-1, node->GetHandle(), node_weight.second); } } input.vertexIndex = daeVertIndex; input.mappedIndex = newVertIndex; } if (!inputs[NORMAL].empty()) { unsigned int inputRemappedNormalIndex = values[*inputs[NORMAL].begin()]; if (normalDupMap.find(inputRemappedNormalIndex) != normalDupMap.end()) inputRemappedNormalIndex = normalDupMap[inputRemappedNormalIndex]; subMesh->AddNormal(norms[inputRemappedNormalIndex]); input.normalIndex = inputRemappedNormalIndex; } if (!inputs[TEXCOORD].empty()) { // \todo: Add support for multiple texture maps to SubMesh. // Here we are only using the first texture coordinates, when // multiple could have been specified. unsigned int inputRemappedTexcoordIndex = values[*inputs[TEXCOORD].begin()]; if (texDupMap.find(inputRemappedTexcoordIndex) != texDupMap.end()) { inputRemappedTexcoordIndex = texDupMap[inputRemappedTexcoordIndex]; } subMesh->AddTexCoord(texcoords[inputRemappedTexcoordIndex].X(), texcoords[inputRemappedTexcoordIndex].Y()); input.texcoordIndex = inputRemappedTexcoordIndex; } // add the new gazebo submesh vertex index to the map if (!inputs[VERTEX].empty()) { std::vector<GeometryIndices> inputValues; inputValues.push_back(input); vertexIndexMap[daeVertIndex] = inputValues; } } } } } delete [] values; _mesh->AddSubMesh(subMesh); } ///////////////////////////////////////////////// void ColladaLoader::LoadTriangles(TiXmlElement *_trianglesXml, const ignition::math::Matrix4d &_transform, Mesh *_mesh) { std::unique_ptr<SubMesh> subMesh(new SubMesh); subMesh->SetName(this->dataPtr->currentNodeName); bool combinedVertNorms = false; subMesh->SetPrimitiveType(SubMesh::TRIANGLES); if (_trianglesXml->Attribute("material")) { std::map<std::string, std::string>::iterator iter; std::string matStr = _trianglesXml->Attribute("material"); int matIndex = -1; iter = this->dataPtr->materialMap.find(matStr); if (iter != this->dataPtr->materialMap.end()) matStr = iter->second; common::Material *mat = this->LoadMaterial(matStr); matIndex = _mesh->GetMaterialIndex(mat); if (matIndex < 0) matIndex = _mesh->AddMaterial(mat); if (matIndex < 0) gzwarn << "Unable to add material[" << matStr << "]\n"; else subMesh->SetMaterialIndex(matIndex); } TiXmlElement *trianglesInputXml = _trianglesXml->FirstChildElement("input"); std::vector<ignition::math::Vector3d> verts; std::vector<ignition::math::Vector3d> norms; std::vector<ignition::math::Vector2d> texcoords; const unsigned int VERTEX = 0; const unsigned int NORMAL = 1; const unsigned int TEXCOORD = 2; unsigned int otherSemantics = TEXCOORD + 1; bool hasVertices = false; bool hasNormals = false; bool hasTexcoords = false; unsigned int offsetSize = 0; // read input elements. A vector of int is used because there can be // multiple TEXCOORD inputs. std::map<const unsigned int, std::set<int>> inputs; // look up table of position/normal/texcoord duplicate indices std::map<unsigned int, unsigned int> texDupMap; std::map<unsigned int, unsigned int> normalDupMap; std::map<unsigned int, unsigned int> positionDupMap; while (trianglesInputXml) { std::string semantic = trianglesInputXml->Attribute("semantic"); std::string source = trianglesInputXml->Attribute("source"); std::string offset = trianglesInputXml->Attribute("offset"); if (semantic == "VERTEX") { unsigned int count = norms.size(); this->LoadVertices(source, _transform, verts, norms, positionDupMap, normalDupMap); if (norms.size() > count) combinedVertNorms = true; inputs[VERTEX].insert(ignition::math::parseInt(offset)); hasVertices = true; } else if (semantic == "NORMAL") { this->LoadNormals(source, _transform, norms, normalDupMap); combinedVertNorms = false; inputs[NORMAL].insert(ignition::math::parseInt(offset)); hasNormals = true; } else if (semantic == "TEXCOORD") { // we currently only support one set of UVs this->LoadTexCoords(source, texcoords, texDupMap); inputs[TEXCOORD].insert(ignition::math::parseInt(offset)); hasTexcoords = true; } else { inputs[otherSemantics++].insert(ignition::math::parseInt(offset)); gzwarn << "Triangle input semantic: '" << semantic << "' is currently" << " not supported" << std::endl; } trianglesInputXml = trianglesInputXml->NextSiblingElement("input"); } for (const auto &input : inputs) offsetSize += input.second.size(); TiXmlElement *pXml = _trianglesXml->FirstChildElement("p"); if (!pXml || !pXml->GetText()) { int count = 1; if (_trianglesXml->Attribute("count")) { try { count = boost::lexical_cast<int>(_trianglesXml->Attribute("count")); } catch(...) { // Do nothing. Messages are printed out below. } } // It's possible that the triangle count is zero. In this case, we // should not output an error message if (count) { gzerr << "Collada file[" << this->dataPtr->filename << "] is invalid. Loading what we can...\n"; } else { gzlog << "Triangle input has a count of zero. " << "This is likely not desired\n"; } return; } std::string pStr = pXml->GetText(); // Collada format allows normals and texcoords to have their own set of // indices for more efficient storage of data but opengl only supports one // index buffer. So we need to reorder normals/texcoord to match the vertex // index and duplicate any vertices that have the same index but different // normal/texcoord. // vertexIndexMap is a map of collada vertex index to Gazebo submesh vertex // indices, used for identifying vertices that can be shared. std::map<unsigned int, std::vector<GeometryIndices> > vertexIndexMap; std::vector<unsigned int> values(offsetSize); std::vector<std::string> strs; boost::split(strs, pStr, boost::is_any_of(" \t")); for (unsigned int j = 0; j < strs.size(); j += offsetSize) { for (unsigned int i = 0; i < offsetSize; ++i) values.at(i) = ignition::math::parseInt(strs[j+i]); unsigned int daeVertIndex = 0; bool addIndex = !hasVertices; // find a set of vertex/normal/texcoord that can be reused // only do this if the mesh has vertices if (hasVertices) { // Get the vertex position index value. If the position is a duplicate // then reset the index to the first instance of the duplicated position daeVertIndex = values.at(*inputs[VERTEX].begin()); if (positionDupMap.find(daeVertIndex) != positionDupMap.end()) daeVertIndex = positionDupMap[daeVertIndex]; // if the vertex index has not been previously added then just add it. if (vertexIndexMap.find(daeVertIndex) == vertexIndexMap.end()) { addIndex = true; } else { // if the vertex index was previously added, check to see if it has the // same normal and texcoord index values bool toDuplicate = true; unsigned int reuseIndex = 0; std::vector<GeometryIndices> inputValues = vertexIndexMap[daeVertIndex]; for (unsigned int i = 0; i < inputValues.size(); ++i) { GeometryIndices iv = inputValues[i]; bool normEqual = false; bool texEqual = false; if (hasNormals) { // Get the vertex normal index value. If the normal is a duplicate // then reset the index to the first instance of the duplicated // position unsigned int remappedNormalIndex = values.at(*inputs[NORMAL].begin()); if (normalDupMap.find(remappedNormalIndex) != normalDupMap.end()) remappedNormalIndex = normalDupMap[remappedNormalIndex]; if (iv.normalIndex == remappedNormalIndex) normEqual = true; } if (hasTexcoords) { // Get the vertex texcoord index value. If the texcoord is a // duplicate then reset the index to the first instance of the // duplicated texcoord unsigned int remappedTexcoordIndex = values.at(*inputs[TEXCOORD].begin()); if (texDupMap.find(remappedTexcoordIndex) != texDupMap.end()) remappedTexcoordIndex = texDupMap[remappedTexcoordIndex]; if (iv.texcoordIndex == remappedTexcoordIndex) texEqual = true; } // if the vertex has matching normal and texcoord index values then // the vertex can be reused. if ((!hasNormals || normEqual) && (!hasTexcoords || texEqual)) { // found a vertex that can be shared. toDuplicate = false; reuseIndex = iv.mappedIndex; subMesh->AddIndex(reuseIndex); break; } } addIndex = toDuplicate; } } // if the vertex index is new or can not be shared then add it if (addIndex) { GeometryIndices input; if (hasVertices) { subMesh->AddVertex(verts[daeVertIndex]); unsigned int newVertIndex = subMesh->GetVertexCount()-1; subMesh->AddIndex(newVertIndex); if (combinedVertNorms) subMesh->AddNormal(norms[daeVertIndex]); if (_mesh->HasSkeleton()) { Skeleton *skel = _mesh->GetSkeleton(); for (unsigned int i = 0; i < skel->GetNumVertNodeWeights(daeVertIndex); ++i) { std::pair<std::string, double> node_weight = skel->GetVertNodeWeight(daeVertIndex, i); SkeletonNode *node = _mesh->GetSkeleton()->GetNodeByName(node_weight.first); subMesh->AddNodeAssignment(subMesh->GetVertexCount()-1, node->GetHandle(), node_weight.second); } } input.vertexIndex = daeVertIndex; input.mappedIndex = newVertIndex; } if (hasNormals) { unsigned int inputRemappedNormalIndex = values.at(*inputs[NORMAL].begin()); if (normalDupMap.find(inputRemappedNormalIndex) != normalDupMap.end()) inputRemappedNormalIndex = normalDupMap[inputRemappedNormalIndex]; subMesh->AddNormal(norms[inputRemappedNormalIndex]); input.normalIndex = inputRemappedNormalIndex; } if (hasTexcoords) { unsigned int inputRemappedTexcoordIndex = values.at(*inputs[TEXCOORD].begin()); if (texDupMap.find(inputRemappedTexcoordIndex) != texDupMap.end()) inputRemappedTexcoordIndex = texDupMap[inputRemappedTexcoordIndex]; subMesh->AddTexCoord(texcoords[inputRemappedTexcoordIndex].X(), texcoords[inputRemappedTexcoordIndex].Y()); input.texcoordIndex = inputRemappedTexcoordIndex; } // add the new gazebo submesh vertex index to the map if (hasVertices) { std::vector<GeometryIndices> inputValues; inputValues.push_back(input); vertexIndexMap[daeVertIndex] = inputValues; } } } _mesh->AddSubMesh(subMesh.release()); } ///////////////////////////////////////////////// void ColladaLoader::LoadLines(TiXmlElement *_xml, const ignition::math::Matrix4d &_transform, Mesh *_mesh) { SubMesh *subMesh = new SubMesh; subMesh->SetName(this->dataPtr->currentNodeName); subMesh->SetPrimitiveType(SubMesh::LINES); TiXmlElement *inputXml = _xml->FirstChildElement("input"); // std::string semantic = inputXml->Attribute("semantic"); std::string source = inputXml->Attribute("source"); std::vector<ignition::math::Vector3d> verts; std::vector<ignition::math::Vector3d> norms; this->LoadVertices(source, _transform, verts, norms); TiXmlElement *pXml = _xml->FirstChildElement("p"); std::string pStr = pXml->GetText(); std::istringstream iss(pStr); do { int a, b; iss >> a >> b; if (!iss) break; subMesh->AddVertex(verts[a]); subMesh->AddIndex(subMesh->GetVertexCount() - 1); subMesh->AddVertex(verts[b]); subMesh->AddIndex(subMesh->GetVertexCount() - 1); } while (iss); _mesh->AddSubMesh(subMesh); } ///////////////////////////////////////////////// float ColladaLoader::LoadFloat(TiXmlElement *_elem) { float value = 0; if (_elem->FirstChildElement("float")) { value = ignition::math::parseFloat(_elem->FirstChildElement("float")->GetText()); } return value; } ///////////////////////////////////////////////// void ColladaLoader::LoadTransparent(TiXmlElement *_elem, Material *_mat) { const char *opaqueCStr = _elem->Attribute("opaque"); if (!opaqueCStr) { // no opaque mode, revert transparency to 0.0 _mat->SetTransparency(0.0); return; } // TODO: Handle transparent textures if (_elem->FirstChildElement("texture")) { gzwarn << "texture based transparency not supported" << std::endl; _mat->SetTransparency(0.0); } else if (_elem->FirstChildElement("color")) { const char *colorCStr = _elem->FirstChildElement("color")->GetText(); if (!colorCStr) { gzerr << "No color string\n"; return; } std::string opaqueStr = opaqueCStr; std::string colorStr = colorCStr; auto color = boost::lexical_cast<ignition::math::Color>(colorStr); // src is the texel value and dst is the existing pixel value double srcFactor = 0; double dstFactor = 0; // Calculate alpha based on opaque mode. // Equations are extracted from collada spec // Make sure to update the final transparency value // final mat transparency = 1 - srcFactor = dstFactor if (opaqueStr == "RGB_ZERO") { // Lunimance based on ISO/CIE color standards ITU-R BT.709-4 float luminance = 0.212671 * color.R() + 0.715160 * color.G() + 0.072169 * color.B(); // result.a = fb.a * (lumiance(transparent.rgb) * transparency) + mat.a * // (1.0f - luminance(transparent.rgb) * transparency) // where fb corresponds to the framebuffer (existing pixel) and // mat corresponds to material before transparency (texel) dstFactor = luminance * _mat->GetTransparency(); srcFactor = 1.0 - luminance * _mat->GetTransparency(); _mat->SetTransparency(dstFactor); } else if (opaqueStr == "RGB_ONE") { // Lunimance based on ISO/CIE color standards ITU-R BT.709-4 float luminance = 0.212671 * color.R() + 0.715160 * color.G() + 0.072169 * color.B(); // result.a = fb.a * (1.0f - lumiance(transparent.rgb) * transparency) + // mat.a * (luminance(transparent.rgb) * transparency) // where fb corresponds to the framebuffer (existing pixel) and // mat corresponds to material before transparency (texel) dstFactor = 1.0 - luminance * _mat->GetTransparency(); srcFactor = luminance * _mat->GetTransparency(); _mat->SetTransparency(dstFactor); } else if (opaqueStr == "A_ONE") { // result.a = fb.a * (1.0f - transparent.a * transparency) + mat.a * // (transparent.a * transparency) // where fb corresponds to the framebuffer (existing pixel) and // mat corresponds to material before transparency (texel) dstFactor = 1.0 - color.A() * _mat->GetTransparency(); srcFactor = color.A() * _mat->GetTransparency(); _mat->SetTransparency(dstFactor); } else if (opaqueStr == "A_ZERO") { // result.a = fb.a * (transparent.a * transparency) + mat.a * // (1.0f - transparent.a * transparency) // where fb corresponds to the framebuffer (existing pixel) and // mat corresponds to material before transparency (texel) dstFactor = color.A() * _mat->GetTransparency(); srcFactor = 1.0 - color.A() * _mat->GetTransparency(); _mat->SetTransparency(dstFactor); } _mat->SetBlendFactors(srcFactor, dstFactor); } } ///////////////////////////////////////////////// void ColladaLoader::MergeSkeleton(Skeleton *_skeleton, SkeletonNode *_mergeNode) { if (_skeleton->GetNodeById(_mergeNode->GetId())) return; SkeletonNode *currentRoot = _skeleton->GetRootNode(); if (currentRoot->GetId() == _mergeNode->GetId()) return; if (_mergeNode->GetChildById(currentRoot->GetId())) { _skeleton->SetRootNode(_mergeNode); return; } SkeletonNode *dummyRoot = nullptr; if (currentRoot->GetId() == "gazebo-dummy-root") dummyRoot = currentRoot; else { dummyRoot = new SkeletonNode(nullptr, "gazebo-dummy-root", "gazebo-dummy-root"); } if (dummyRoot != currentRoot) { dummyRoot->AddChild(currentRoot); currentRoot->SetParent(dummyRoot); } dummyRoot->AddChild(_mergeNode); _mergeNode->SetParent(dummyRoot); dummyRoot->SetTransform(ignition::math::Matrix4d::Identity); _skeleton->SetRootNode(dummyRoot); } ///////////////////////////////////////////////// void ColladaLoader::ApplyInvBindTransform(Skeleton *_skeleton) { std::list<SkeletonNode*> queue; queue.push_back(_skeleton->GetRootNode()); while (!queue.empty()) { SkeletonNode *node = queue.front(); if (node->HasInvBindTransform()) node->SetModelTransform(node->InverseBindTransform().Inverse(), false); for (unsigned int i = 0; i < node->GetChildCount(); i++) queue.push_back(node->GetChild(i)); queue.pop_front(); } }
32.815698
80
0.616296
[ "mesh", "geometry", "vector", "model", "transform" ]
29887e2dcf15158a3848238e13fec76d4743d72b
868
cc
C++
cpp/Codeforces/601-650/621A_Wet_Shark.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/601-650/621A_Wet_Shark.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/601-650/621A_Wet_Shark.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <unordered_map> #include <stdint.h> #include <cmath> #include <algorithm> #include <map> using namespace std; typedef int64_t Int; typedef uint64_t UInt; int main(int argc, char **argv) { string line = ""; UInt n = 0; UInt sum = 0; Int minOdd = -1; if ( getline( cin, line ) ) { stringstream ss( line ); ss >> n; } if ( getline( cin, line ) ) { stringstream ss( line ); for ( int i = 0; i < n; ++i ) { UInt num = 0; ss >> num; sum += num; if ( ( num % 2 == 1 ) && ( ( minOdd == -1 ) || ( minOdd > num ) ) ) { minOdd = num; } } if ( sum % 2 == 1 ) { sum -= minOdd; } } cout << sum; return 0; }
18.869565
81
0.459677
[ "vector" ]
298948b069f8e2e3146fa67df9255220f7d7fc42
28,364
cc
C++
src/lib/fidl_codec/semantic_parser_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
4
2020-02-23T09:02:06.000Z
2022-01-08T17:06:28.000Z
src/lib/fidl_codec/semantic_parser_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/lib/fidl_codec/semantic_parser_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2020 The Fuchsia 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 "src/lib/fidl_codec/semantic_parser.h" #include <iostream> #include <sstream> #include <string> #include <vector> #include <gtest/gtest.h> #include "src/lib/fidl_codec/library_loader.h" #include "src/lib/fidl_codec/list_test_data.h" #include "src/lib/fidl_codec/semantic_parser_test.h" #include "src/lib/fidl_codec/wire_types.h" namespace fidl_codec { namespace semantic { // Checks the semantic parser. // Checks that we detects errors. // Checks that we do a good recovery on errors (only a few tests display more than one error). SemanticParserTest::SemanticParserTest() { fidl_codec_test::SdkExamples sdk_examples; // Loads all the files in sdk/core.fidl_json.txt. for (const auto& element : sdk_examples.map()) { library_loader_.AddContent(element.second, &err_); } } void SemanticParserTest::SetUp() {} TEST_F(SemanticParserTest, GlobalExample) { // Checks that Directory::Open exists in fuchsia.io. Library* library = library_loader_.GetLibraryFromName("fuchsia.io"); ASSERT_NE(library, nullptr); library->DecodeTypes(); Interface* interface = nullptr; library->GetInterfaceByName("fuchsia.io/Directory", &interface); ASSERT_NE(interface, nullptr); InterfaceMethod* method = interface->GetMethodByName("Open"); ASSERT_NE(method, nullptr); // Checks that we currently don't have any semantic for Open. ASSERT_EQ(method->semantic(), nullptr); std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n" "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescription('server-control', request.launch_info.url);\n" " }\n" "}\n"; ParserErrors parser_errors; SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); // Checks that we now have the right semantic. ASSERT_NE(method->semantic(), nullptr); std::stringstream ss; method->semantic()->Dump(ss); std::string result = ss.str(); ASSERT_EQ(result, "request.object = handle / request.path\n"); } TEST_F(SemanticParserTest, GlobalPrintExample) { // Checks that Directory::Open exists in fuchsia.io. Library* library = library_loader_.GetLibraryFromName("fuchsia.io"); ASSERT_NE(library, nullptr); library->DecodeTypes(); Interface* interface = nullptr; library->GetInterfaceByName("fuchsia.io/Directory", &interface); ASSERT_NE(interface, nullptr); InterfaceMethod* method = interface->GetMethodByName("Open"); ASSERT_NE(method, nullptr); std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags as directory_open_flags;\n" " print mode as directory_open_mode;\n" " }\n" "}\n"; ParserErrors parser_errors; SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); StructMember* flags = method->SearchMember("flags"); ASSERT_NE(flags, nullptr); Uint32Type* flags_type = flags->type()->AsUint32Type(); ASSERT_NE(flags_type, nullptr); ASSERT_EQ(flags_type->kind(), Uint32Type::Kind::kDirectoryOpenFlags); StructMember* mode = method->SearchMember("mode"); ASSERT_NE(mode, nullptr); Uint32Type* mode_type = mode->type()->AsUint32Type(); ASSERT_NE(mode_type, nullptr); ASSERT_EQ(mode_type->kind(), Uint32Type::Kind::kDirectoryOpenMode); // Checks that the fields are printed correctly. std::stringstream out; PrettyPrinter printer(out, WithoutColors, false, "", 100, false); IntegerValue flags_value(8912896, /*negative=*/false); flags->type()->PrettyPrint(&flags_value, printer); out << '\n'; IntegerValue mode_value(16384, /*negative=*/false); mode->type()->PrettyPrint(&mode_value, printer); out << '\n'; ASSERT_EQ(out.str(), "OPEN_FLAG_DIRECTORY | OPEN_FLAG_DESCRIBE\n" "MODE_TYPE_DIRECTORY\n"); } TEST_F(SemanticParserTest, CheckAssignments) { std::string text = "request.object = handle / request.path;\n" "request.foo = handle;\n" "request.bar = handle / request.other_path;\n" "request.bar2 = handle : 'cloned';\n"; ParserErrors parser_errors; SemanticParser parser(&library_loader_, text, &parser_errors); MethodSemantic semantic; while (!parser.IsEof()) { parser.ParseAssignment(&semantic); } std::stringstream ss; semantic.Dump(ss); std::string result = ss.str(); ASSERT_EQ(result, "request.object = handle / request.path\n" "request.foo = handle\n" "request.bar = handle / request.other_path\n" "request.bar2 = handle : 'cloned'\n"); } TEST_F(SemanticParserTest, CheckDisplay) { std::string text = " input_field: request.path;\n" " result: request.object;\n" " input_field: request.data.size ' bytes';\n" " input_field: 'buffer of ' request.data.size ' bytes';\n" " input_field: 'size = ' request.data.size;\n" "}\n"; InterfaceMethod method; ParserErrors parser_errors; SemanticParser parser(&library_loader_, text, &parser_errors); while (!parser.IsEof()) { parser.ParseMethod(&method); } ASSERT_NE(method.short_display(), nullptr); std::stringstream ss; method.short_display()->Dump(ss); std::string result = ss.str(); ASSERT_EQ(result, "input_field: request.path;\n" "input_field: request.data.size \" bytes\";\n" "input_field: \"buffer of \" request.data.size \" bytes\";\n" "input_field: \"size = \" request.data.size;\n" "result: request.object;\n"); } TEST_F(SemanticParserTest, EmptyText) { std::string text = ""; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); MethodSemantic semantic; parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, ""); } TEST_F(SemanticParserTest, LibraryExpected) { std::string text = "xxx fuchsia.io {\n" " Directory::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, "xxx fuchsia.io {\n" "^\n" "1:1: Keyword 'library' expected.\n"); } TEST_F(SemanticParserTest, LibraryNameExpected) { std::string text = "library {\n" " Directory::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, "library {\n" " ^\n" "1:9: Library name expected.\n"); } TEST_F(SemanticParserTest, LibraryNotFound) { std::string text = "library fuchsia.xxx {\n" " Directory::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, "library fuchsia.xxx {\n" " ^\n" "1:9: Library fuchsia.xxx not found.\n"); } TEST_F(SemanticParserTest, MissingLeftBrace1) { std::string text = "library fuchsia.io\n" " Directory::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " Directory::Open {\n" " ^\n" "2:3: Symbol '{' expected.\n"); } TEST_F(SemanticParserTest, ProtocolNameExpected) { std::string text = "library fuchsia.io {\n" " ::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " ::Open {\n" " ^\n" "2:3: Protocol name expected.\n"); } TEST_F(SemanticParserTest, ProtocolNotFound) { std::string text = "library fuchsia.io {\n" " Xxx::Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " Xxx::Open {\n" " ^\n" "2:3: Protocol Xxx not found in library fuchsia.io\n"); } TEST_F(SemanticParserTest, DoubleColonExpected) { std::string text = "library fuchsia.io {\n" " Directory Open {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " Directory Open {\n" " ^\n" "2:13: Symbol '::' expected.\n"); } TEST_F(SemanticParserTest, MethodNameExpected) { std::string text = "library fuchsia.io {\n" " Directory:: {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " Directory:: {\n" " ^\n" "2:15: Method name expected.\n"); } TEST_F(SemanticParserTest, MethodNotFound) { std::string text = "library fuchsia.io {\n" " Directory::Xxx {\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " Directory::Xxx {\n" " ^\n" "2:14: Method Xxx not found in protocol fuchsia.io/Directory\n"); } TEST_F(SemanticParserTest, MissingLeftBrace2) { std::string text = "library fuchsia.io {\n" " Directory::Open\n" " request.object = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.object = handle / request.path;\n" " ^\n" "3:5: Symbol '{' expected.\n" "}\n" "^\n" "5:1: Keyword 'library' expected.\n"); } TEST_F(SemanticParserTest, InputFieldColonExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " input_field request.path;\n" " result: request.object;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " input_field request.path;\n" " ^\n" "3:17: Symbol ':' expected.\n"); } TEST_F(SemanticParserTest, ResultColonExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " input_field: request.path;\n" " result request.object;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " result request.object;\n" " ^\n" "4:12: Symbol ':' expected.\n"); } TEST_F(SemanticParserTest, InputFieldSemiColonExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " input_field: request.path\n" " result: request.object;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " result: request.object;\n" " ^\n" "4:5: Symbol ';' expected.\n"); } TEST_F(SemanticParserTest, ResultSemiColonExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " input_field: request.path;\n" " result: request.object\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " }\n" " ^\n" "5:3: Symbol ';' expected.\n"); } TEST_F(SemanticParserTest, AssignmentExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " = handle / request.path;\n" " ^\n" "3:5: Assignment expected.\n"); } TEST_F(SemanticParserTest, FieldNameExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request. = handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request. = handle / request.path;\n" " ^\n" "3:14: Field name expected.\n"); } TEST_F(SemanticParserTest, EqualExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object handle / request.path;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.object handle / request.path;\n" " ^\n" "3:20: Symbol '=' expected.\n"); } TEST_F(SemanticParserTest, ExpressionExpected1) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object =;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.object =;\n" " ^\n" "3:21: Expression expected.\n"); } TEST_F(SemanticParserTest, ExpressionExpected2) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object = handle /;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.object = handle /;\n" " ^\n" "3:30: Expression expected.\n"); } TEST_F(SemanticParserTest, ExpressionExpected3) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object = xxx;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.object = xxx;\n" " ^\n" "3:22: Expression expected.\n"); } TEST_F(SemanticParserTest, SemicolonExpected) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " request.object = handle / request.path\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " }\n" " ^\n" "4:3: Symbol ';' expected.\n"); } TEST_F(SemanticParserTest, HandleDescriptionTypo) { std::string text = "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescriptions('server-control', request.launch_info.url);\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ( result, " request.controller = HandleDescriptions('server-control', request.launch_info.url);\n" " ^\n" "3:25: Expression expected.\n"); } TEST_F(SemanticParserTest, UnterminatedString) { std::string text = "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescription('server-control, request.launch_info.url);\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.controller = HandleDescription('server-control, request.launch_info.url);\n" " ^\n3:43: Unterminated string.\n" " request.controller = HandleDescription('server-control, request.launch_info.url);\n" " ^\n3:44: Symbol ',' expected.\n"); } TEST_F(SemanticParserTest, LeftParenthesisExpected) { std::string text = "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescription 'server-control', request.launch_info.url);\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ( result, " request.controller = HandleDescription 'server-control', request.launch_info.url);\n" " ^\n" "3:43: Symbol '(' expected.\n"); } TEST_F(SemanticParserTest, CommaExpected) { std::string text = "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescription('server-control' request.launch_info.url);\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.controller = HandleDescription('server-control' request.launch_info.url);\n" " ^\n" "3:60: Symbol ',' expected.\n"); } TEST_F(SemanticParserTest, RightParenthesisExpected) { std::string text = "library fuchsia.sys {\n" " Launcher::CreateComponent {\n" " request.controller = HandleDescription('server-control', request.launch_info.url;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " request.controller = HandleDescription('server-control', request.launch_info.url;\n" " ^\n" "3:84: Symbol ')' expected.\n"); } TEST_F(SemanticParserTest, MissingFieldName) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print;\n" " ^\n" "3:10: Field name expected.\n"); } TEST_F(SemanticParserTest, BadFieldName) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print xx as directory_open_flags;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print xx as directory_open_flags;\n" " ^\n" "3:11: Field <xx> not found.\n" " print xx as directory_open_flags;\n" " ^\n" "3:14: Symbol ';' expected.\n"); } TEST_F(SemanticParserTest, TypeNotDefined) { // Checks that Directory::Open exists in fuchsia.io. Library* library = library_loader_.GetLibraryFromName("fuchsia.io"); ASSERT_NE(library, nullptr); library->DecodeTypes(); Interface* interface = nullptr; library->GetInterfaceByName("fuchsia.io/Directory", &interface); ASSERT_NE(interface, nullptr); InterfaceMethod* method = interface->GetMethodByName("Open"); ASSERT_NE(method, nullptr); method->Decode(); StructMember* flags = method->SearchMember("flags"); ASSERT_NE(flags, nullptr); // Reset the type to trigger the error. flags->reset_type(); std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags as directory_open_flags;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print flags as directory_open_flags;\n" " ^\n" "3:11: Type not defined for field <flags>.\n" " print flags as directory_open_flags;\n" " ^\n" "3:17: Symbol ';' expected.\n"); } TEST_F(SemanticParserTest, MissingDecodeFunction) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags as;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print flags as;\n" " ^\n" "3:19: Decode function expected.\n"); } TEST_F(SemanticParserTest, BadFieldType1) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print path as directory_open_flags;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print path as directory_open_flags;\n" " ^\n" "3:19: <path> should be an Uint32.\n"); } TEST_F(SemanticParserTest, BadFieldType2) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print path as directory_open_mode;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print path as directory_open_mode;\n" " ^\n" "3:19: <path> should be an Uint32.\n"); } TEST_F(SemanticParserTest, MissingAs) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags directory_open_flags;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print flags directory_open_flags;\n" " ^\n" "3:17: Keyword 'as' expected.\n"); } TEST_F(SemanticParserTest, BadPrintType) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags as xxx;\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print flags as xxx;\n" " ^\n" "3:20: Print type <xxx> not found.\n"); } TEST_F(SemanticParserTest, SemicolonExpected2) { std::string text = "library fuchsia.io {\n" " Directory::Open {\n" " print flags as directory_open_flags\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " }\n" " ^\n" "4:3: Symbol ';' expected.\n"); } // Checks that we can access response fields. TEST_F(SemanticParserTest, ResponseField) { std::string text = "library fuchsia.io {\n" " Node::OnOpen {\n" " print info as directory_open_flags\n" " }\n" "}\n"; std::stringstream error_stream; ParserErrors parser_errors(error_stream); SemanticParser parser(&library_loader_, text, &parser_errors); parser.ParseSemantic(); std::string result = error_stream.str(); ASSERT_EQ(result, " print info as directory_open_flags\n" " ^\n" "3:19: <info> should be an Uint32.\n" " }\n" " ^\n" "4:3: Symbol ';' expected.\n"); } } // namespace semantic } // namespace fidl_codec
31.306843
100
0.619236
[ "object", "vector" ]
298deb48b2024525f1d150af2b0e43db2775e50c
18,526
cpp
C++
openstudiocore/src/model/CurveBiquadratic.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/CurveBiquadratic.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/CurveBiquadratic.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * 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 **********************************************************************/ #include <model/CurveBiquadratic.hpp> #include <model/CurveBiquadratic_Impl.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Curve_Biquadratic_FieldEnums.hxx> #include <utilities/core/Assert.hpp> #include <cmath> using namespace std; namespace openstudio { namespace model { namespace detail { CurveBiquadratic_Impl::CurveBiquadratic_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : Curve_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == CurveBiquadratic::iddObjectType()); } CurveBiquadratic_Impl::CurveBiquadratic_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : Curve_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == CurveBiquadratic::iddObjectType()); } CurveBiquadratic_Impl::CurveBiquadratic_Impl(const CurveBiquadratic_Impl& other, Model_Impl* model, bool keepHandle) : Curve_Impl(other,model,keepHandle) {} const std::vector<std::string>& CurveBiquadratic_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType CurveBiquadratic_Impl::iddObjectType() const { return CurveBiquadratic::iddObjectType(); } int CurveBiquadratic_Impl::numVariables() const { return 2u; } double CurveBiquadratic_Impl::evaluate(const std::vector<double>& x) const { OS_ASSERT(x.size() == 2u); double result = coefficient1Constant(); result += coefficient2x() * x[0]; result += coefficient3xPOW2() * pow(x[0],2); result += coefficient4y() * x[1]; result += coefficient5yPOW2() * pow(x[1],2); result += coefficient6xTIMESY() * x[0] * x[1]; return result; } double CurveBiquadratic_Impl::coefficient1Constant() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient1Constant,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::coefficient2x() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient2x,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::coefficient3xPOW2() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient3x_POW_2,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::coefficient4y() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient4y,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::coefficient5yPOW2() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient5y_POW_2,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::coefficient6xTIMESY() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::Coefficient6x_TIMES_y,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::minimumValueofx() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::MinimumValueofx,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::maximumValueofx() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::MaximumValueofx,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::minimumValueofy() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::MinimumValueofy,true); OS_ASSERT(value); return value.get(); } double CurveBiquadratic_Impl::maximumValueofy() const { boost::optional<double> value = getDouble(OS_Curve_BiquadraticFields::MaximumValueofy,true); OS_ASSERT(value); return value.get(); } boost::optional<double> CurveBiquadratic_Impl::minimumCurveOutput() const { return getDouble(OS_Curve_BiquadraticFields::MinimumCurveOutput,true); } boost::optional<double> CurveBiquadratic_Impl::maximumCurveOutput() const { return getDouble(OS_Curve_BiquadraticFields::MaximumCurveOutput,true); } std::string CurveBiquadratic_Impl::inputUnitTypeforX() const { boost::optional<std::string> value = getString(OS_Curve_BiquadraticFields::InputUnitTypeforX,true); OS_ASSERT(value); return value.get(); } bool CurveBiquadratic_Impl::isInputUnitTypeforXDefaulted() const { return isEmpty(OS_Curve_BiquadraticFields::InputUnitTypeforX); } std::string CurveBiquadratic_Impl::inputUnitTypeforY() const { boost::optional<std::string> value = getString(OS_Curve_BiquadraticFields::InputUnitTypeforY,true); OS_ASSERT(value); return value.get(); } bool CurveBiquadratic_Impl::isInputUnitTypeforYDefaulted() const { return isEmpty(OS_Curve_BiquadraticFields::InputUnitTypeforY); } std::string CurveBiquadratic_Impl::outputUnitType() const { boost::optional<std::string> value = getString(OS_Curve_BiquadraticFields::OutputUnitType,true); OS_ASSERT(value); return value.get(); } bool CurveBiquadratic_Impl::isOutputUnitTypeDefaulted() const { return isEmpty(OS_Curve_BiquadraticFields::OutputUnitType); } void CurveBiquadratic_Impl::setCoefficient1Constant(double coefficient1Constant) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient1Constant, coefficient1Constant); OS_ASSERT(result); } void CurveBiquadratic_Impl::setCoefficient2x(double coefficient2x) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient2x, coefficient2x); OS_ASSERT(result); } void CurveBiquadratic_Impl::setCoefficient3xPOW2(double coefficient3xPOW2) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient3x_POW_2, coefficient3xPOW2); OS_ASSERT(result); } void CurveBiquadratic_Impl::setCoefficient4y(double coefficient4y) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient4y, coefficient4y); OS_ASSERT(result); } void CurveBiquadratic_Impl::setCoefficient5yPOW2(double coefficient5yPOW2) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient5y_POW_2, coefficient5yPOW2); OS_ASSERT(result); } void CurveBiquadratic_Impl::setCoefficient6xTIMESY(double coefficient6xTIMESY) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::Coefficient6x_TIMES_y, coefficient6xTIMESY); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMinimumValueofx(double minimumValueofx) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::MinimumValueofx, minimumValueofx); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMaximumValueofx(double maximumValueofx) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::MaximumValueofx, maximumValueofx); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMinimumValueofy(double minimumValueofy) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::MinimumValueofy, minimumValueofy); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMaximumValueofy(double maximumValueofy) { bool result = false; result = setDouble(OS_Curve_BiquadraticFields::MaximumValueofy, maximumValueofy); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMinimumCurveOutput(boost::optional<double> minimumCurveOutput) { bool result = false; if (minimumCurveOutput) { result = setDouble(OS_Curve_BiquadraticFields::MinimumCurveOutput, minimumCurveOutput.get()); } else { result = setString(OS_Curve_BiquadraticFields::MinimumCurveOutput, ""); } OS_ASSERT(result); } void CurveBiquadratic_Impl::resetMinimumCurveOutput() { bool result = setString(OS_Curve_BiquadraticFields::MinimumCurveOutput, ""); OS_ASSERT(result); } void CurveBiquadratic_Impl::setMaximumCurveOutput(boost::optional<double> maximumCurveOutput) { bool result = false; if (maximumCurveOutput) { result = setDouble(OS_Curve_BiquadraticFields::MaximumCurveOutput, maximumCurveOutput.get()); } else { result = setString(OS_Curve_BiquadraticFields::MaximumCurveOutput, ""); } OS_ASSERT(result); } void CurveBiquadratic_Impl::resetMaximumCurveOutput() { bool result = setString(OS_Curve_BiquadraticFields::MaximumCurveOutput, ""); OS_ASSERT(result); } bool CurveBiquadratic_Impl::setInputUnitTypeforX(std::string inputUnitTypeforX) { bool result = false; result = setString(OS_Curve_BiquadraticFields::InputUnitTypeforX, inputUnitTypeforX); return result; } void CurveBiquadratic_Impl::resetInputUnitTypeforX() { bool result = setString(OS_Curve_BiquadraticFields::InputUnitTypeforX, ""); OS_ASSERT(result); } bool CurveBiquadratic_Impl::setInputUnitTypeforY(std::string inputUnitTypeforY) { bool result = false; result = setString(OS_Curve_BiquadraticFields::InputUnitTypeforY, inputUnitTypeforY); return result; } void CurveBiquadratic_Impl::resetInputUnitTypeforY() { bool result = setString(OS_Curve_BiquadraticFields::InputUnitTypeforY, ""); OS_ASSERT(result); } bool CurveBiquadratic_Impl::setOutputUnitType(std::string outputUnitType) { bool result = false; result = setString(OS_Curve_BiquadraticFields::OutputUnitType, outputUnitType); return result; } void CurveBiquadratic_Impl::resetOutputUnitType() { bool result = setString(OS_Curve_BiquadraticFields::OutputUnitType, ""); OS_ASSERT(result); } } // detail CurveBiquadratic::CurveBiquadratic(const Model& model) : Curve(CurveBiquadratic::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CurveBiquadratic_Impl>()); setDouble(OS_Curve_BiquadraticFields::Coefficient1Constant,0.0); setDouble(OS_Curve_BiquadraticFields::Coefficient2x,0.0); setDouble(OS_Curve_BiquadraticFields::Coefficient3x_POW_2,0.0); setDouble(OS_Curve_BiquadraticFields::Coefficient4y,0.0); setDouble(OS_Curve_BiquadraticFields::Coefficient5y_POW_2,0.0); setDouble(OS_Curve_BiquadraticFields::Coefficient6x_TIMES_y,0.0); setDouble(OS_Curve_BiquadraticFields::MinimumValueofx,0.0); setDouble(OS_Curve_BiquadraticFields::MaximumValueofx,1.0); setDouble(OS_Curve_BiquadraticFields::MinimumValueofy,0.0); setDouble(OS_Curve_BiquadraticFields::MaximumValueofy,1.0); } IddObjectType CurveBiquadratic::iddObjectType() { IddObjectType result(IddObjectType::OS_Curve_Biquadratic); return result; } std::vector<std::string> CurveBiquadratic::validInputUnitTypeforXValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Curve_BiquadraticFields::InputUnitTypeforX); } std::vector<std::string> CurveBiquadratic::validInputUnitTypeforYValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Curve_BiquadraticFields::InputUnitTypeforY); } std::vector<std::string> CurveBiquadratic::validOutputUnitTypeValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Curve_BiquadraticFields::OutputUnitType); } double CurveBiquadratic::coefficient1Constant() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient1Constant(); } double CurveBiquadratic::coefficient2x() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient2x(); } double CurveBiquadratic::coefficient3xPOW2() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient3xPOW2(); } double CurveBiquadratic::coefficient4y() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient4y(); } double CurveBiquadratic::coefficient5yPOW2() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient5yPOW2(); } double CurveBiquadratic::coefficient6xTIMESY() const { return getImpl<detail::CurveBiquadratic_Impl>()->coefficient6xTIMESY(); } double CurveBiquadratic::minimumValueofx() const { return getImpl<detail::CurveBiquadratic_Impl>()->minimumValueofx(); } double CurveBiquadratic::maximumValueofx() const { return getImpl<detail::CurveBiquadratic_Impl>()->maximumValueofx(); } double CurveBiquadratic::minimumValueofy() const { return getImpl<detail::CurveBiquadratic_Impl>()->minimumValueofy(); } double CurveBiquadratic::maximumValueofy() const { return getImpl<detail::CurveBiquadratic_Impl>()->maximumValueofy(); } boost::optional<double> CurveBiquadratic::minimumCurveOutput() const { return getImpl<detail::CurveBiquadratic_Impl>()->minimumCurveOutput(); } boost::optional<double> CurveBiquadratic::maximumCurveOutput() const { return getImpl<detail::CurveBiquadratic_Impl>()->maximumCurveOutput(); } std::string CurveBiquadratic::inputUnitTypeforX() const { return getImpl<detail::CurveBiquadratic_Impl>()->inputUnitTypeforX(); } bool CurveBiquadratic::isInputUnitTypeforXDefaulted() const { return getImpl<detail::CurveBiquadratic_Impl>()->isInputUnitTypeforXDefaulted(); } std::string CurveBiquadratic::inputUnitTypeforY() const { return getImpl<detail::CurveBiquadratic_Impl>()->inputUnitTypeforY(); } bool CurveBiquadratic::isInputUnitTypeforYDefaulted() const { return getImpl<detail::CurveBiquadratic_Impl>()->isInputUnitTypeforYDefaulted(); } std::string CurveBiquadratic::outputUnitType() const { return getImpl<detail::CurveBiquadratic_Impl>()->outputUnitType(); } bool CurveBiquadratic::isOutputUnitTypeDefaulted() const { return getImpl<detail::CurveBiquadratic_Impl>()->isOutputUnitTypeDefaulted(); } void CurveBiquadratic::setCoefficient1Constant(double coefficient1Constant) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient1Constant(coefficient1Constant); } void CurveBiquadratic::setCoefficient2x(double coefficient2x) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient2x(coefficient2x); } void CurveBiquadratic::setCoefficient3xPOW2(double coefficient3xPOW2) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient3xPOW2(coefficient3xPOW2); } void CurveBiquadratic::setCoefficient4y(double coefficient4y) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient4y(coefficient4y); } void CurveBiquadratic::setCoefficient5yPOW2(double coefficient5yPOW2) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient5yPOW2(coefficient5yPOW2); } void CurveBiquadratic::setCoefficient6xTIMESY(double coefficient6xTIMESY) { getImpl<detail::CurveBiquadratic_Impl>()->setCoefficient6xTIMESY(coefficient6xTIMESY); } void CurveBiquadratic::setMinimumValueofx(double minimumValueofx) { getImpl<detail::CurveBiquadratic_Impl>()->setMinimumValueofx(minimumValueofx); } void CurveBiquadratic::setMaximumValueofx(double maximumValueofx) { getImpl<detail::CurveBiquadratic_Impl>()->setMaximumValueofx(maximumValueofx); } void CurveBiquadratic::setMinimumValueofy(double minimumValueofy) { getImpl<detail::CurveBiquadratic_Impl>()->setMinimumValueofy(minimumValueofy); } void CurveBiquadratic::setMaximumValueofy(double maximumValueofy) { getImpl<detail::CurveBiquadratic_Impl>()->setMaximumValueofy(maximumValueofy); } void CurveBiquadratic::setMinimumCurveOutput(double minimumCurveOutput) { getImpl<detail::CurveBiquadratic_Impl>()->setMinimumCurveOutput(minimumCurveOutput); } void CurveBiquadratic::resetMinimumCurveOutput() { getImpl<detail::CurveBiquadratic_Impl>()->resetMinimumCurveOutput(); } void CurveBiquadratic::setMaximumCurveOutput(double maximumCurveOutput) { getImpl<detail::CurveBiquadratic_Impl>()->setMaximumCurveOutput(maximumCurveOutput); } void CurveBiquadratic::resetMaximumCurveOutput() { getImpl<detail::CurveBiquadratic_Impl>()->resetMaximumCurveOutput(); } bool CurveBiquadratic::setInputUnitTypeforX(std::string inputUnitTypeforX) { return getImpl<detail::CurveBiquadratic_Impl>()->setInputUnitTypeforX(inputUnitTypeforX); } void CurveBiquadratic::resetInputUnitTypeforX() { getImpl<detail::CurveBiquadratic_Impl>()->resetInputUnitTypeforX(); } bool CurveBiquadratic::setInputUnitTypeforY(std::string inputUnitTypeforY) { return getImpl<detail::CurveBiquadratic_Impl>()->setInputUnitTypeforY(inputUnitTypeforY); } void CurveBiquadratic::resetInputUnitTypeforY() { getImpl<detail::CurveBiquadratic_Impl>()->resetInputUnitTypeforY(); } bool CurveBiquadratic::setOutputUnitType(std::string outputUnitType) { return getImpl<detail::CurveBiquadratic_Impl>()->setOutputUnitType(outputUnitType); } void CurveBiquadratic::resetOutputUnitType() { getImpl<detail::CurveBiquadratic_Impl>()->resetOutputUnitType(); } /// @cond CurveBiquadratic::CurveBiquadratic(boost::shared_ptr<detail::CurveBiquadratic_Impl> impl) : Curve(impl) {} /// @endcond } // model } // openstudio
36.831014
111
0.737126
[ "vector", "model" ]
298e9ae5b05303d389b420d6661ebc1024dacb68
10,857
cc
C++
ppapi/proxy/ppb_file_chooser_proxy.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
ppapi/proxy/ppb_file_chooser_proxy.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
ppapi/proxy/ppb_file_chooser_proxy.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 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 "ppapi/proxy/ppb_file_chooser_proxy.h" #include <queue> #include "base/bind.h" #include "ppapi/c/dev/ppb_file_chooser_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/private/ppb_proxy_private.h" #include "ppapi/c/trusted/ppb_file_chooser_trusted.h" #include "ppapi/proxy/enter_proxy.h" #include "ppapi/proxy/host_dispatcher.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/ppb_file_ref_proxy.h" #include "ppapi/proxy/serialized_var.h" #include "ppapi/shared_impl/array_writer.h" #include "ppapi/shared_impl/ppapi_globals.h" #include "ppapi/shared_impl/resource_tracker.h" #include "ppapi/shared_impl/tracked_callback.h" #include "ppapi/shared_impl/var.h" #include "ppapi/thunk/resource_creation_api.h" #include "ppapi/thunk/thunk.h" using ppapi::thunk::PPB_FileChooser_API; namespace ppapi { namespace proxy { namespace { InterfaceProxy* CreateFileChooserProxy(Dispatcher* dispatcher) { return new PPB_FileChooser_Proxy(dispatcher); } class FileChooser : public Resource, public PPB_FileChooser_API { public: FileChooser(const HostResource& resource); virtual ~FileChooser(); // Resource overrides. virtual PPB_FileChooser_API* AsPPB_FileChooser_API() OVERRIDE; // PPB_FileChooser_API implementation. virtual int32_t Show(const PP_ArrayOutput& output, const PP_CompletionCallback& callback) OVERRIDE; virtual int32_t ShowWithoutUserGesture( PP_Bool save_as, PP_Var suggested_file_name, const PP_ArrayOutput& output, const PP_CompletionCallback& callback); virtual int32_t Show0_5(const PP_CompletionCallback& callback) OVERRIDE; virtual PP_Resource GetNextChosenFile() OVERRIDE; virtual int32_t ShowWithoutUserGesture0_5( PP_Bool save_as, PP_Var suggested_file_name, const PP_CompletionCallback& callback) OVERRIDE; // Handles the choose complete notification from the host. void ChooseComplete( int32_t result_code, const std::vector<PPB_FileRef_CreateInfo>& chosen_files); private: int32_t Show(bool require_user_gesture, PP_Bool save_as, PP_Var suggested_file_name, const PP_CompletionCallback& callback); // When using v0.6 of the API, contains the array output info. ArrayWriter output_; scoped_refptr<TrackedCallback> current_show_callback_; // When using v0.5 of the API, contains all files returned by the current // show callback that haven't yet been given to the plugin. The plugin will // repeatedly call us to get the next file, and we'll vend those out of this // queue, removing them when ownership has transferred to the plugin. std::queue<PP_Resource> file_queue_; DISALLOW_COPY_AND_ASSIGN(FileChooser); }; FileChooser::FileChooser(const HostResource& resource) : Resource(OBJECT_IS_PROXY, resource) { } FileChooser::~FileChooser() { // Any existing files we haven't transferred ownership to the plugin need // to be freed. ResourceTracker* tracker = PpapiGlobals::Get()->GetResourceTracker(); while (!file_queue_.empty()) { tracker->ReleaseResource(file_queue_.front()); file_queue_.pop(); } } PPB_FileChooser_API* FileChooser::AsPPB_FileChooser_API() { return this; } int32_t FileChooser::Show(const PP_ArrayOutput& output, const PP_CompletionCallback& callback) { int32_t result = Show(true, PP_FALSE, PP_MakeUndefined(), callback); if (result == PP_OK_COMPLETIONPENDING) output_.set_pp_array_output(output); return result; } int32_t FileChooser::ShowWithoutUserGesture( PP_Bool save_as, PP_Var suggested_file_name, const PP_ArrayOutput& output, const PP_CompletionCallback& callback) { int32_t result = Show(false, save_as, PP_MakeUndefined(), callback); if (result == PP_OK_COMPLETIONPENDING) output_.set_pp_array_output(output); return result; } int32_t FileChooser::Show0_5(const PP_CompletionCallback& callback) { return Show(true, PP_FALSE, PP_MakeUndefined(), callback); } int32_t FileChooser::ShowWithoutUserGesture0_5( PP_Bool save_as, PP_Var suggested_file_name, const PP_CompletionCallback& callback) { return Show(false, save_as, suggested_file_name, callback); } int32_t FileChooser::Show(bool require_user_gesture, PP_Bool save_as, PP_Var suggested_file_name, const PP_CompletionCallback& callback) { if (!callback.func) return PP_ERROR_BLOCKS_MAIN_THREAD; if (TrackedCallback::IsPending(current_show_callback_)) return PP_ERROR_INPROGRESS; // Can't show more than once. current_show_callback_ = new TrackedCallback(this, callback); PluginDispatcher* dispatcher = PluginDispatcher::GetForResource(this); dispatcher->Send( new PpapiHostMsg_PPBFileChooser_Show( API_ID_PPB_FILE_CHOOSER, host_resource(), save_as, SerializedVarSendInput(dispatcher, suggested_file_name), require_user_gesture)); return PP_OK_COMPLETIONPENDING; } PP_Resource FileChooser::GetNextChosenFile() { if (file_queue_.empty()) return 0; // Return the next resource in the queue. These resource have already been // addrefed (they're currently owned by the FileChooser) and returning them // transfers ownership of that reference to the plugin. PP_Resource next = file_queue_.front(); file_queue_.pop(); return next; } void FileChooser::ChooseComplete( int32_t result_code, const std::vector<PPB_FileRef_CreateInfo>& chosen_files) { if (output_.is_valid()) { // Using v0.6 of the API with the output array. std::vector<PP_Resource> files; for (size_t i = 0; i < chosen_files.size(); i++) files.push_back(PPB_FileRef_Proxy::DeserializeFileRef(chosen_files[i])); output_.StoreResourceVector(files); } else { // Convert each of the passed in file infos to resources. These will be // owned by the FileChooser object until they're passed to the plugin. DCHECK(file_queue_.empty()); for (size_t i = 0; i < chosen_files.size(); i++) { file_queue_.push(PPB_FileRef_Proxy::DeserializeFileRef( chosen_files[i])); } } // Notify the plugin of the new data. TrackedCallback::ClearAndRun(&current_show_callback_, result_code); // DANGER: May delete |this|! } } // namespace PPB_FileChooser_Proxy::PPB_FileChooser_Proxy(Dispatcher* dispatcher) : InterfaceProxy(dispatcher), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } PPB_FileChooser_Proxy::~PPB_FileChooser_Proxy() { } // static const InterfaceProxy::Info* PPB_FileChooser_Proxy::GetTrustedInfo() { static const Info info = { thunk::GetPPB_FileChooser_Trusted_0_5_Thunk(), PPB_FILECHOOSER_TRUSTED_INTERFACE_0_5, API_ID_NONE, // FILE_CHOOSER is the canonical one. false, &CreateFileChooserProxy }; return &info; } // static PP_Resource PPB_FileChooser_Proxy::CreateProxyResource( PP_Instance instance, PP_FileChooserMode_Dev mode, const char* accept_mime_types) { Dispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher) return 0; HostResource result; dispatcher->Send(new PpapiHostMsg_PPBFileChooser_Create( API_ID_PPB_FILE_CHOOSER, instance, mode, accept_mime_types ? accept_mime_types : "", &result)); if (result.is_null()) return 0; return (new FileChooser(result))->GetReference(); } bool PPB_FileChooser_Proxy::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_FileChooser_Proxy, msg) // Plugin -> host messages. IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFileChooser_Create, OnMsgCreate) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFileChooser_Show, OnMsgShow) // Host -> plugin messages. IPC_MESSAGE_HANDLER(PpapiMsg_PPBFileChooser_ChooseComplete, OnMsgChooseComplete) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PPB_FileChooser_Proxy::OnMsgCreate( PP_Instance instance, int mode, std::string accept_mime_types, HostResource* result) { thunk::EnterResourceCreation enter(instance); if (enter.succeeded()) { result->SetHostResource(instance, enter.functions()->CreateFileChooser( instance, static_cast<PP_FileChooserMode_Dev>(mode), accept_mime_types.c_str())); } } void PPB_FileChooser_Proxy::OnMsgShow( const HostResource& chooser, PP_Bool save_as, SerializedVarReceiveInput suggested_file_name, bool require_user_gesture) { scoped_refptr<RefCountedArrayOutputAdapter<PP_Resource> > output( new RefCountedArrayOutputAdapter<PP_Resource>); EnterHostFromHostResourceForceCallback<PPB_FileChooser_API> enter( chooser, callback_factory_.NewOptionalCallback( &PPB_FileChooser_Proxy::OnShowCallback, output, chooser)); if (enter.succeeded()) { if (require_user_gesture) { enter.SetResult(enter.object()->Show(output->pp_array_output(), enter.callback())); } else { enter.SetResult(enter.object()->ShowWithoutUserGesture( save_as, suggested_file_name.Get(dispatcher()), output->pp_array_output(), enter.callback())); } } } void PPB_FileChooser_Proxy::OnMsgChooseComplete( const HostResource& chooser, int32_t result_code, const std::vector<PPB_FileRef_CreateInfo>& chosen_files) { EnterPluginFromHostResource<PPB_FileChooser_API> enter(chooser); if (enter.succeeded()) { static_cast<FileChooser*>(enter.object())->ChooseComplete( result_code, chosen_files); } } void PPB_FileChooser_Proxy::OnShowCallback( int32_t result, scoped_refptr<RefCountedArrayOutputAdapter<PP_Resource> > output, HostResource chooser) { EnterHostFromHostResource<PPB_FileChooser_API> enter(chooser); std::vector<PPB_FileRef_CreateInfo> files; if (enter.succeeded() && result == PP_OK) { PPB_FileRef_Proxy* file_ref_proxy = static_cast<PPB_FileRef_Proxy*>( dispatcher()->GetInterfaceProxy(API_ID_PPB_FILE_REF)); // Convert the returned files to the serialized info. for (size_t i = 0; i < output->output().size(); i++) { PPB_FileRef_CreateInfo cur_create_info; file_ref_proxy->SerializeFileRef(output->output()[i], &cur_create_info); files.push_back(cur_create_info); } } dispatcher()->Send(new PpapiMsg_PPBFileChooser_ChooseComplete( API_ID_PPB_FILE_CHOOSER, chooser, result, files)); } } // namespace proxy } // namespace ppapi
33.201835
78
0.731694
[ "object", "vector" ]
298f2c18667432ac6c17325478d5980666d6f537
2,179
cpp
C++
Tree/Path_queries.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
2
2021-02-05T04:21:42.000Z
2021-02-10T14:24:38.000Z
Tree/Path_queries.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
Tree/Path_queries.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ll long long int #define fast ios_base::sync_with_stdio(false) #define fast_input cin.tie(NULL) #define fast_output cout.tie(NULL) #define vi vector<long long int> #define pb push_back #define pa pair<long long int ,long long int> #define f(a,x,b) for(int a=x;a<b;a++) #define sort(x) sort(x.begin(),x.end()); #define siz(a) (int)a.size() #define mod 1000000007 #define F first #define S second #define um unordered_map<ll,ll> #define ordered_set tree<pa, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> vi g[200001]; vi order; vi val(200001); void dfs(ll v,ll par=-1) { order.pb(v); for(ll d:g[v]) { if(d-par) { dfs(d,v); } } order.pb(v); } namespace fenwick { ll bit[500001],n; void upd(ll ind,ll val) { while(ind<=n) { bit[ind]+=val; ind+=(ind&-ind); } } ll get(ll ind) { ll res=0; while(ind>=1) { res+=bit[ind]; ind-=(ind&-ind); } return res; } } void solve() { ll n,q; cin>>n>>q; f(i,0,n) { cin>>val[i]; } f(i,1,n) { ll x,y; cin>>x>>y; x--,y--; g[x].pb(y); g[y].pb(x); } dfs(0); // f(i,0,order.size()) // { // cout<<order[i]<<" "; // } fenwick::n=order.size(); vector<pa>rng(n); f(i,0,order.size()) { if(rng[order[i]].F==0) { rng[order[i]].F=i+1; } else { rng[order[i]].S=i+1; } } f(i,0,n) { fenwick::upd(rng[i].F,val[i]); fenwick::upd(rng[i].S+1,-val[i]); } f(i,0,q) { ll t; cin>>t; if(t==1) { ll x,va; cin>>x>>va; x--; ll ge=va-val[x]; val[x]=va; fenwick::upd(rng[x].F,ge); fenwick::upd(rng[x].S+1,-ge); } else { ll x; cin>>x; x--; cout<<fenwick::get(rng[x].F)<<endl; } } } int main() { fast; fast_input; fast_output; // ll t; // cin>>t; // f(i,0,t) // { // cout<<"Case #"<<i+1<<":"<<" "; solve(); // } return 0; }
16.261194
97
0.518128
[ "vector" ]
29986c81dce74b99efe5f10fa2ce9c2b17131444
4,023
cpp
C++
NAS2D/StringUtils.cpp
cugone/nas2d-core
632983fa6e9d334d79fdf2dfc54719eee5b5d3ca
[ "Zlib" ]
13
2017-03-23T06:11:30.000Z
2021-09-15T16:22:56.000Z
NAS2D/StringUtils.cpp
cugone/nas2d-core
632983fa6e9d334d79fdf2dfc54719eee5b5d3ca
[ "Zlib" ]
467
2016-06-28T22:47:06.000Z
2022-02-08T18:08:12.000Z
NAS2D/StringUtils.cpp
cugone/nas2d-core
632983fa6e9d334d79fdf2dfc54719eee5b5d3ca
[ "Zlib" ]
8
2015-10-12T21:36:10.000Z
2021-06-24T07:46:31.000Z
// ================================================================================== // = NAS2D // = Copyright © 2008 - 2020 New Age Software // ================================================================================== // = NAS2D is distributed under the terms of the zlib license. You are free to copy, // = modify and distribute the software under the terms of the zlib license. // = // = Acknowledgment of your use of NAS2D is appreciated but is not required. // ================================================================================== #include "StringUtils.h" #include "ContainerUtils.h" #include <algorithm> #include <cctype> #include <numeric> #include <sstream> namespace NAS2D { /** * Converts a string to lowercase. * * \param str Source string. * * \return Returns the converted string. */ std::string toLowercase(std::string str) { std::transform(std::begin(str), std::end(str), std::begin(str), [](unsigned char c) noexcept->unsigned char { return static_cast<unsigned char>(::tolower(c)); }); return str; } /** * Converts a string to uppercase. * * \param str Source string. * * \return Returns the converted string. */ std::string toUppercase(std::string str) { std::transform(std::begin(str), std::end(str), std::begin(str), [](unsigned char c) noexcept->unsigned char { return static_cast<unsigned char>(::toupper(c)); }); return str; } std::vector<std::string> split(const std::string& str, char delim /*= ','*/) { const auto potentialCount = static_cast<std::size_t>(1 + std::count(std::begin(str), std::end(str), delim)); StringList result{}; result.reserve(potentialCount); std::istringstream ss(str); std::string curString{}; while (std::getline(ss, curString, delim)) { result.push_back(curString); } if (ss.eof() && !str.empty() && str.back() == delim) { result.push_back(std::string{}); } result.shrink_to_fit(); return result; } std::pair<std::string, std::string> splitOnFirst(const std::string& str, char delim) { const auto delim_loc = str.find_first_of(delim); if (delim_loc == std::string::npos) { return std::make_pair(str, std::string{}); } else { return std::make_pair(str.substr(0, delim_loc), str.substr(delim_loc + 1)); } } std::pair<std::string, std::string> splitOnLast(const std::string& str, char delim) { const auto delim_loc = str.find_last_of(delim); if (delim_loc == std::string::npos) { return std::make_pair(std::string{}, str); } else { return std::make_pair(str.substr(0, delim_loc), str.substr(delim_loc + 1)); } } std::string join(const std::vector<std::string>& strs, std::string_view delimiter) { std::string result; if (!strs.empty()) { const auto totalStringSize = flattenSize(strs); const auto delimiterSize = (strs.size() - 1) * delimiter.size(); result.reserve(totalStringSize + delimiterSize); result += strs.front(); for (auto iter = std::begin(strs) + 1; iter != std::end(strs); ++iter) { result += delimiter; result += (*iter); } } return result; } std::string trimWhitespace(std::string_view string) { const auto first_non_space = string.find_first_not_of(" \r\n\t\v\f"); if (first_non_space == std::string::npos) { return std::string{}; } const auto last_non_space = string.find_last_not_of(" \r\n\t\v\f"); return std::string{string.substr(first_non_space, last_non_space - first_non_space + 1)}; } bool startsWith(std::string_view string, std::string_view start) noexcept { return string.compare(0, start.size(), start) == 0; } bool endsWith(std::string_view string, std::string_view end) noexcept { return string.compare(string.size() - end.size(), end.size(), end) == 0; } bool startsWith(std::string_view string, char start) noexcept { return !string.empty() && string.front() == start; } bool endsWith(std::string_view string, char end) noexcept { return !string.empty() && string.back() == end; } } // namespace
27
164
0.62267
[ "vector", "transform" ]
2999c5753e1a8c618ff2fb91cc4c6b313774f9d3
1,131
hpp
C++
src/stateMachine.hpp
przemekBielak/HSM
df9397ab80d366a4524e3d708485d231741f62dc
[ "MIT" ]
null
null
null
src/stateMachine.hpp
przemekBielak/HSM
df9397ab80d366a4524e3d708485d231741f62dc
[ "MIT" ]
null
null
null
src/stateMachine.hpp
przemekBielak/HSM
df9397ab80d366a4524e3d708485d231741f62dc
[ "MIT" ]
null
null
null
/** * @file stateMachine.hpp * @author Przemyslaw Bielak (przemyslaw.bielak@protonmail.com) * @brief Describes a state machine logic. * @version 0.1 * @date 2019-02-01 * * @copyright Copyright (c) 2019 * */ #ifndef STATEMACHINE_H #define STATEMACHINE_H #include "state.hpp" /** * @brief Adds logic and data between State elements * */ class StateMachine { public: /** * @brief Construct a new State Machine object * * @param initState Pointer to initial state */ StateMachine(State * const initState); /** * @brief Get the current state object * * @return State* */ State *getCurrState(); /** * @brief Executes state machine transition (if possible) * * @param ev Requested event. * @return true event found * @return false event not found */ bool run(const event_t event) ; private: /** * @brief Current state * */ State *m_currState; }; #endif // #ifndef STATEMACHINE_H
20.944444
65
0.55084
[ "object" ]
299ec57a0fa6dbcf3602dc4d1681a8db564c1f9f
3,225
cpp
C++
ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp
WenjieXuZJU/ogs
cc464a7efb726ad1ab657d0b82fbdb1623303cca
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp
WenjieXuZJU/ogs
cc464a7efb726ad1ab657d0b82fbdb1623303cca
[ "BSD-4-Clause" ]
2
2019-06-05T12:06:11.000Z
2019-06-06T08:45:30.000Z
ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp
bilke/ogs
517d0eaac7b1710d77ec7ddfc2957d7c59fecade
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "CreatePythonSourceTerm.h" #include <pybind11/pybind11.h> #include "BaseLib/ConfigTree.h" #include "MeshLib/Mesh.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "ProcessLib/SourceTerms/SourceTerm.h" #include "PythonSourceTerm.h" namespace ProcessLib { std::unique_ptr<SourceTerm> createPythonSourceTerm( BaseLib::ConfigTree const& config, MeshLib::Mesh const& source_term_mesh, std::unique_ptr<NumLib::LocalToGlobalIndexMap> dof_table, std::size_t const bulk_mesh_id, int const variable_id, int const component_id, unsigned const integration_order, unsigned const shapefunction_order, unsigned const global_dim) { DBUG("Constructing PythonSourceTerm from config."); //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__type} config.checkConfigParameter("type", "Python"); auto const source_term_object = //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__Python__source_term_object} config.getConfigParameter<std::string>("source_term_object"); //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__Python__flush_stdout} auto const flush_stdout = config.getConfigParameter("flush_stdout", false); // Evaluate Python code in scope of main module pybind11::object scope = pybind11::module::import("__main__").attr("__dict__"); if (!scope.contains(source_term_object)) { OGS_FATAL( "Function `%s' is not defined in the python script file, or there " "was no python script file specified.", source_term_object.c_str()); } auto* source_term = scope[source_term_object.c_str()] .cast<ProcessLib::SourceTerms::Python:: PythonSourceTermPythonSideInterface*>(); // In case of partitioned mesh the source_term could be empty, i.e. there is // no source_term condition. #ifdef USE_PETSC // This can be extracted to createSourceTerm() but then the config // parameters are not read and will cause an error. // TODO (naumov): Add a function to ConfigTree for skipping the tags of the // subtree and move the code up in createSourceTerm(). if (source_term_mesh.getDimension() == 0 && source_term_mesh.getNumberOfNodes() == 0 && source_term_mesh.getNumberOfElements() == 0) { return nullptr; } #endif // USE_PETSC auto const global_component_id = dof_table->getGlobalComponent(variable_id, component_id); return std::make_unique<ProcessLib::SourceTerms::Python::PythonSourceTerm>( std::move(dof_table), ProcessLib::SourceTerms::Python::PythonSourceTermData{ source_term, bulk_mesh_id, global_component_id, source_term_mesh}, integration_order, shapefunction_order, global_dim, flush_stdout); } } // namespace ProcessLib
40.3125
120
0.714109
[ "mesh", "object" ]
29a090db50dc82b5179043c4ad0ae48f4b711ec8
10,534
cpp
C++
src/client/types.cpp
fada-catec/ouster_ros
231e6d1131a965a174b43124c383358c5c8b41b6
[ "BSD-3-Clause" ]
9
2020-11-24T15:56:28.000Z
2022-02-10T13:58:02.000Z
src/client/types.cpp
fada-catec/ouster_ros
231e6d1131a965a174b43124c383358c5c8b41b6
[ "BSD-3-Clause" ]
null
null
null
src/client/types.cpp
fada-catec/ouster_ros
231e6d1131a965a174b43124c383358c5c8b41b6
[ "BSD-3-Clause" ]
1
2020-11-25T07:30:54.000Z
2020-11-25T07:30:54.000Z
#include "ouster_ros/client/types.h" #include <json/json.h> #include <algorithm> #include <array> #include <cmath> #include <sstream> #include <string> #include <vector> #include "ouster_ros/client/packet.h" #include "ouster_ros/client/version.h" namespace ouster { namespace sensor { namespace { const std::array<std::pair<lidar_mode, std::string>, 5> lidar_mode_strings = {{{MODE_512x10, "512x10"}, {MODE_512x20, "512x20"}, {MODE_1024x10, "1024x10"}, {MODE_1024x20, "1024x20"}, {MODE_2048x10, "2048x10"}}}; const std::array<std::pair<timestamp_mode, std::string>, 3> timestamp_mode_strings = { {{TIME_FROM_INTERNAL_OSC, "TIME_FROM_INTERNAL_OSC"}, {TIME_FROM_SYNC_PULSE_IN, "TIME_FROM_SYNC_PULSE_IN"}, {TIME_FROM_PTP_1588, "TIME_FROM_PTP_1588"}}}; } // namespace data_format default_data_format(lidar_mode mode) { auto repeat = [](int n, const std::vector<int>& v) { std::vector<int> res{}; for (int i = 0; i < n; i++) res.insert(res.end(), v.begin(), v.end()); return res; }; uint32_t pixels_per_column = 64; uint32_t columns_per_packet = 16; uint32_t columns_per_frame = n_cols_of_lidar_mode(mode); std::vector<int> offset; switch (columns_per_frame) { case 512: offset = repeat(16, {9, 6, 3, 0}); break; case 1024: offset = repeat(16, {18, 12, 6, 0}); break; case 2048: offset = repeat(16, {36, 24, 12, 0}); break; default: offset = repeat(16, {18, 12, 6, 0}); break; } return {pixels_per_column, columns_per_packet, columns_per_frame, offset}; } static double default_lidar_origin_to_beam_origin(std::string prod_line) { double lidar_origin_to_beam_origin_mm = 12.163; // default for gen 1 if (prod_line.find("OS-0-") == 0) lidar_origin_to_beam_origin_mm = 27.67; else if (prod_line.find("OS-1-") == 0) lidar_origin_to_beam_origin_mm = 15.806; else if (prod_line.find("OS-2-") == 0) lidar_origin_to_beam_origin_mm = 13.762; return lidar_origin_to_beam_origin_mm; } sensor_info default_sensor_info() { return sensor::sensor_info{"UNKNOWN", "000000000000", "UNKNOWN", MODE_1024x10, "OS-1-64", default_data_format(MODE_1024x10), gen1_azimuth_angles, gen1_altitude_angles, imu_to_sensor_transform, lidar_to_sensor_transform, default_lidar_origin_to_beam_origin("OS-1-64")}; } const packet_format& get_format(const data_format& format) { switch (format.pixels_per_column) { case 16: return packet__1_14_0__16; case 32: return packet__1_14_0__32; case 64: return packet__1_14_0__64; case 128: return packet__1_14_0__128; default: return packet__1_13_0; } } std::string to_string(lidar_mode mode) { auto end = lidar_mode_strings.end(); auto res = std::find_if(lidar_mode_strings.begin(), end, [&](const std::pair<lidar_mode, std::string>& p) { return p.first == mode; }); return res == end ? "UNKNOWN" : res->second; } lidar_mode lidar_mode_of_string(const std::string& s) { auto end = lidar_mode_strings.end(); auto res = std::find_if(lidar_mode_strings.begin(), end, [&](const std::pair<lidar_mode, std::string>& p) { return p.second == s; }); return res == end ? lidar_mode(0) : res->first; } int n_cols_of_lidar_mode(lidar_mode mode) { switch (mode) { case MODE_512x10: case MODE_512x20: return 512; case MODE_1024x10: case MODE_1024x20: return 1024; case MODE_2048x10: return 2048; default: throw std::invalid_argument{"n_cols_of_lidar_mode"}; } } std::string to_string(timestamp_mode mode) { auto end = timestamp_mode_strings.end(); auto res = std::find_if(timestamp_mode_strings.begin(), end, [&](const std::pair<timestamp_mode, std::string>& p) { return p.first == mode; }); return res == end ? "UNKNOWN" : res->second; } timestamp_mode timestamp_mode_of_string(const std::string& s) { auto end = timestamp_mode_strings.end(); auto res = std::find_if(timestamp_mode_strings.begin(), end, [&](const std::pair<timestamp_mode, std::string>& p) { return p.second == s; }); return res == end ? timestamp_mode(0) : res->first; } sensor_info parse_metadata(const std::string& meta) { Json::Value root{}; Json::CharReaderBuilder builder{}; std::string errors{}; std::stringstream ss{meta}; if (meta.size()) { if (!Json::parseFromStream(builder, ss, &root, &errors)) throw std::runtime_error{errors.c_str()}; } sensor_info info{}; info.hostname = root["hostname"].asString(); info.sn = root["prod_sn"].asString(); info.fw_rev = root["build_rev"].asString(); info.mode = lidar_mode_of_string(root["lidar_mode"].asString()); info.prod_line = root["prod_line"].asString(); // "data_format" introduced in fw 1.14. Fall back to common 1.13 parameters // otherwise if (root.isMember("data_format")) { info.format.pixels_per_column = root["data_format"]["pixels_per_column"].asInt(); info.format.columns_per_packet = root["data_format"]["columns_per_packet"].asInt(); info.format.columns_per_frame = root["data_format"]["columns_per_frame"].asInt(); for (const auto& v : root["data_format"]["pixel_shift_by_row"]) info.format.pixel_shift_by_row.push_back(v.asInt()); } else { info.format = default_data_format(info.mode); } // "lidar_origin_to_beam_origin_mm" introduced in fw 1.14. Fall back to // common 1.13 parameters otherwise if (root.isMember("lidar_origin_to_beam_origin_mm")) { info.lidar_origin_to_beam_origin_mm = root["lidar_origin_to_beam_origin_mm"].asDouble(); } else { info.lidar_origin_to_beam_origin_mm = default_lidar_origin_to_beam_origin(info.prod_line); } for (const auto& v : root["beam_altitude_angles"]) info.beam_altitude_angles.push_back(v.asDouble()); for (const auto& v : root["beam_azimuth_angles"]) info.beam_azimuth_angles.push_back(v.asDouble()); for (const auto& v : root["imu_to_sensor_transform"]) info.imu_to_sensor_transform.push_back(v.asDouble()); for (const auto& v : root["lidar_to_sensor_transform"]) info.lidar_to_sensor_transform.push_back(v.asDouble()); return info; } std::string to_string(const sensor_info& info) { Json::Value root{}; root["hostname"] = info.hostname; root["prod_sn"] = info.sn; root["build_rev"] = info.fw_rev; root["lidar_mode"] = to_string(info.mode); root["prod_line"] = info.prod_line; root["data_format"]["pixels_per_column"] = info.format.pixels_per_column; root["data_format"]["columns_per_packet"] = info.format.columns_per_packet; root["data_format"]["columns_per_frame"] = info.format.columns_per_frame; root["lidar_origin_to_beam_origin_mm"] = info.lidar_origin_to_beam_origin_mm; for (auto i : info.format.pixel_shift_by_row) root["data_format"]["pixel_shift_by_row"].append(i); for (auto i : info.beam_azimuth_angles) root["beam_azimuth_angles"].append(i); for (auto i : info.beam_altitude_angles) root["beam_altitude_angles"].append(i); for (auto i : info.imu_to_sensor_transform) root["imu_to_sensor_transform"].append(i); for (auto i : info.imu_to_sensor_transform) root["lidar_to_sensor_transform"].append(i); Json::StreamWriterBuilder builder; builder["enableYAMLCompatibility"] = true; builder["precision"] = 6; builder["indentation"] = " "; return Json::writeString(builder, root); } extern const std::vector<double> gen1_altitude_angles = { 16.611, 16.084, 15.557, 15.029, 14.502, 13.975, 13.447, 12.920, 12.393, 11.865, 11.338, 10.811, 10.283, 9.756, 9.229, 8.701, 8.174, 7.646, 7.119, 6.592, 6.064, 5.537, 5.010, 4.482, 3.955, 3.428, 2.900, 2.373, 1.846, 1.318, 0.791, 0.264, -0.264, -0.791, -1.318, -1.846, -2.373, -2.900, -3.428, -3.955, -4.482, -5.010, -5.537, -6.064, -6.592, -7.119, -7.646, -8.174, -8.701, -9.229, -9.756, -10.283, -10.811, -11.338, -11.865, -12.393, -12.920, -13.447, -13.975, -14.502, -15.029, -15.557, -16.084, -16.611, }; extern const std::vector<double> gen1_azimuth_angles = { 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, }; extern const std::vector<double> imu_to_sensor_transform = {1, 0, 0, 6.253, 0, 1, 0, -11.775, 0, 0, 1, 7.645, 0, 0, 0, 1}; extern const std::vector<double> lidar_to_sensor_transform = {-1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1}; } // namespace sensor namespace util { std::string to_string(const version& v) { if (v == invalid_version) return "UNKNOWN"; std::stringstream ss{}; ss << "v" << v.major << "." << v.minor << "." << v.patch; return ss.str(); } version version_of_string(const std::string& s) { std::istringstream is{s}; char c1, c2, c3; version v; is >> c1 >> v.major >> c2 >> v.minor >> c3 >> v.patch; if (is && c1 == 'v' && c2 == '.' && c3 == '.') return v; else return invalid_version; }; } // namespace util } // namespace ouster
34.880795
120
0.593886
[ "vector" ]
29a0b3048e3d066ea54593019fea84d4d6520230
161,681
cpp
C++
HexEdit/HexEdit.cpp
the-nerbs/HexEdit
deefee7cf19c46bfb43674a892f51d885d0ba4ca
[ "MIT" ]
null
null
null
HexEdit/HexEdit.cpp
the-nerbs/HexEdit
deefee7cf19c46bfb43674a892f51d885d0ba4ca
[ "MIT" ]
null
null
null
HexEdit/HexEdit.cpp
the-nerbs/HexEdit
deefee7cf19c46bfb43674a892f51d885d0ba4ca
[ "MIT" ]
null
null
null
// HexEdit.cpp : Defines the class behaviors for the application. // // Copyright (c) 2015 by Andrew W. Phillips // // This file is distributed under the MIT license, which basically says // you can do what you want with it and I take no responsibility for bugs. // See http://www.opensource.org/licenses/mit-license.php for full details. // #include "stdafx.h" //#include <vld.h> // For visual leak detector #include "afxwinappex.h" #include <locale.h> #include <afxadv.h> // for CRecentFileList #include <io.h> // for _access() //#include <bcghelpids.h> // For help on customize dlg // #include <afxhtml.h> // for CHtmlView #include <MAPI.h> // for MAPI constants #include <shlwapi.h> // for SHDeleteKey #define COMPILE_MULTIMON_STUBS 1 // Had to remove this to link with BCG static lib #include <MultiMon.h> // for multiple monitor support #undef COMPILE_MULTIMON_STUBS #include "HexEdit.h" #include <HtmlHelp.h> #include <imagehlp.h> // For ::MakeSureDirectoryPathExists() #include "HexFileList.h" #include "RecentFileDlg.h" #include "BookmarkDlg.h" #include "Bookmark.h" #include "boyer.h" #include "SystemSound.h" #include "MainFrm.h" #include "ChildFrm.h" #include "HexEditDoc.h" #include "HexEditView.h" #include "DataFormatView.h" #include "AerialView.h" #include "CompareView.h" #include "PrevwView.h" #include "TabView.h" #include "UserTool.h" // For CHexEditUserTool #include "Dialog.h" #include "OpenSpecialDlg.h" #include "Register.h" // For About dialog #include "Algorithm.h" // For encruption algorithm selection #include "CompressDlg.h" // For compression settings dialog #include "Password.h" // For encryption password dialog #include "Splasher.h" // For splash window #include <FreeImage.h> // The following is not in a public header extern BOOL AFXAPI AfxFullPath(LPTSTR lpszPathOut, LPCTSTR lpszFileIn); #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern DWORD hid_last_file_dialog = HIDD_FILE_OPEN; const char *CHexEditApp::bin_format_name = "BinaryData"; // for copy2cb_binary const char *CHexEditApp::temp_format_name = "HexEditLargeDataTempFile"; // for copy2cb_file const char *CHexEditApp::flag_format_name = "HexEditFlagTextIsHex"; // for copy2cb_flag_text_is_hextext ///////////////////////////////////////////////////////////////////////////// // CHexEditDocManager class CHexEditDocManager : public CDocManager { public: // We have to do it this way as CWinAppEx::DoPromptFileName is not virtual for some reason virtual BOOL DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate); }; BOOL CHexEditDocManager::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate) { ASSERT(!bOpenFileDialog); // we should only be calling this for save if (bOpenFileDialog) return CDocManager::DoPromptFileName(fileName, nIDSTitle, lFlags, bOpenFileDialog, pTemplate); (void)pTemplate; // This is passed to get associated filters but in our case we don't have any (and they're set by the user via GetCurrentFilters()) //hid_last_file_dialog = HIDD_FILE_SAVE; CHexFileDialog dlgFile("FileSaveDlg", HIDD_FILE_SAVE, FALSE, NULL, fileName, lFlags | OFN_SHOWHELP | OFN_ENABLESIZING, theApp.GetCurrentFilters(), "Save", AfxGetMainWnd()); CString title; ENSURE(title.LoadString(nIDSTitle)); dlgFile.m_ofn.lpstrTitle = title; // Change the initial directory CHexEditView * pv, * pvfirst; CString strDir; // folder name passed to dialog [this must not be destroyed until after dlgFile.DoModal()] switch (theApp.save_locn_) { case FL_DOC: // Get path of most recently viewed window backed by a file (ie excluding new files not yet saved to disk) pvfirst = GetView(); for (pv = pvfirst ; pv != NULL; ) { if (pv->GetDocument() != NULL && pv->GetDocument()->pfile1_ != NULL) { // Get the path from the filename of the active file CString filename = pv->GetDocument()->pfile1_->GetFilePath(); int path_len; // Length of path (full name without filename) path_len = filename.ReverseFind('\\'); if (path_len == -1) path_len = filename.ReverseFind('/'); if (path_len == -1) path_len = filename.ReverseFind(':'); if (path_len == -1) path_len = 0; else ++path_len; strDir = filename.Left(path_len); break; } // Get next most recent view and check if we have wrapped around to start if ((pv = pv->PrevView()) == pvfirst) pv = NULL; } break; case FL_LAST: strDir = theApp.last_save_folder_; break; case FL_BOTH: strDir = theApp.last_both_folder_; break; default: ASSERT(0); // fall through case FL_SPECIFIED: strDir = theApp.save_folder_; break; } // If still empty default to the specified folder if (strDir.IsEmpty()) strDir = theApp.save_folder_; dlgFile.m_ofn.lpstrInitialDir = strDir; dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH + 1); dlgFile.m_ofn.nMaxFile = _MAX_PATH; INT_PTR nResult = dlgFile.DoModal(); fileName.ReleaseBuffer(); theApp.last_open_folder_ = theApp.last_both_folder_ = fileName.Left(dlgFile.m_ofn.nFileOffset); return nResult == IDOK; } ///////////////////////////////////////////////////////////////////////////// // CHexEditApp const char * CHexEditApp::HexEditClassName = "HexEditMDIFrame"; const char * CHexEditApp::RegHelper = "RegHelper.exe"; // helper for things that require admin privileges // The following are used to enable the "Open with HexEdit" shell shortcut menu option. const char *CHexEditApp::HexEditSubKey = "*\\shell\\HexEdit"; const char *CHexEditApp::HexEditSubSubKey = "*\\shell\\HexEdit\\command"; // The following is used to enable "Open With" file extension associations (so that files can be on Win7 task list). const char * CHexEditApp::ProgID = "HexEdit.file"; BEGIN_MESSAGE_MAP(CHexEditApp, CWinAppEx) ON_COMMAND(CG_IDS_TIPOFTHEDAY, ShowTipOfTheDay) //{{AFX_MSG_MAP(CHexEditApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) ON_COMMAND(ID_OPTIONS, OnOptions) ON_COMMAND(ID_OPTIONS2, OnOptions2) ON_COMMAND(ID_OPTIONS_CODEPAGE, OnOptionsCodePage) ON_COMMAND(ID_RECORD, OnMacroRecord) ON_COMMAND(ID_PLAY, OnMacroPlay) ON_UPDATE_COMMAND_UI(ID_PLAY, OnUpdateMacroPlay) ON_UPDATE_COMMAND_UI(ID_RECORD, OnUpdateMacroRecord) ON_COMMAND(ID_PROPERTIES, OnProperties) ON_COMMAND(ID_PROPERTIES_BMP, OnPropertiesBitmap) ON_COMMAND(ID_MULTI_PLAY, OnMultiPlay) ON_COMMAND(ID_HELP_REPORT_ISSUE, OnHelpReportIssue) ON_UPDATE_COMMAND_UI(ID_HELP_REPORT_ISSUE, OnUpdateHelpReportIssue) ON_COMMAND(ID_HELP_WEB, OnHelpWeb) ON_UPDATE_COMMAND_UI(ID_HELP_WEB, OnUpdateHelpWeb) ON_COMMAND(ID_WEB_PAGE, OnWebPage) ON_COMMAND(ID_ENCRYPT_ALG, OnEncryptAlg) ON_COMMAND(ID_ENCRYPT_CLEAR, OnEncryptClear) ON_UPDATE_COMMAND_UI(ID_ENCRYPT_CLEAR, OnUpdateEncryptClear) ON_COMMAND(ID_ENCRYPT_PASSWORD, OnEncryptPassword) ON_COMMAND(ID_MACRO_MESSAGE, OnMacroMessage) ON_UPDATE_COMMAND_UI(ID_MACRO_MESSAGE, OnUpdateMacroMessage) ON_UPDATE_COMMAND_UI(ID_MULTI_PLAY, OnUpdateMultiPlay) ON_COMMAND(ID_RECENT_FILES, OnRecentFiles) ON_COMMAND(ID_BOOKMARKS_EDIT, OnBookmarksEdit) ON_COMMAND(ID_TAB_ICONS, OnTabIcons) ON_COMMAND(ID_TABS_AT_BOTTOM, OnTabsAtBottom) ON_UPDATE_COMMAND_UI(ID_TAB_ICONS, OnUpdateTabIcons) ON_UPDATE_COMMAND_UI(ID_TABS_AT_BOTTOM, OnUpdateTabsAtBottom) ON_COMMAND(ID_FILE_OPEN_SPECIAL, OnFileOpenSpecial) ON_UPDATE_COMMAND_UI(ID_FILE_OPEN_SPECIAL, OnUpdateFileOpenSpecial) //}}AFX_MSG_MAP ON_COMMAND(ID_ZLIB_SETTINGS, OnCompressionSettings) ON_COMMAND(ID_HELP_FORUM, OnHelpWebForum) ON_COMMAND(ID_HELP_HOMEPAGE, OnHelpWebHome) ON_UPDATE_COMMAND_UI(ID_HELP_FORUM, OnUpdateHelpWeb) ON_UPDATE_COMMAND_UI(ID_HELP_HOMEPAGE, OnUpdateHelpWeb) // Repair commands ON_COMMAND(ID_REPAIR_COPYUSERFILES, OnRepairFiles) ON_COMMAND(ID_REPAIR_DIALOGBARS, OnRepairDialogbars) ON_COMMAND(ID_REPAIR_CUST, OnRepairCust) ON_COMMAND(ID_REPAIR_SETTINGS, OnRepairSettings) ON_COMMAND(ID_REPAIR_ALL, OnRepairAll) // ON_COMMAND(ID_REPAIR_CHECK, OnRepairCheck) ON_COMMAND(ID_FILE_SAVE_ALL, OnFileSaveAll) ON_COMMAND(ID_FILE_CLOSE_ALL, OnFileCloseAll) ON_COMMAND(ID_FILE_CLOSE_OTHERS, OnFileCloseOthers) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, OnFileNew) ON_COMMAND(ID_FILE_OPEN, OnFileOpen) ON_COMMAND_EX_RANGE(ID_FILE_MRU_FILE1, ID_FILE_MRU_FILE16, OnOpenRecentFile) ON_COMMAND(ID_APP_EXIT, OnAppExit) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, OnFilePrintSetup) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHexEditApp construction #ifdef _DEBUG // Memory allocation hook function used for debugging memory allocation exceptions #if _MSC_VER <= 1100 static int alloc_hook( int allocType, void *userData, size_t size, int blockType, long requestNumber, const char *filename, int lineNumber) #else // For some reason this declaration has changed slightly (filename is now uchar) static int alloc_hook( int allocType, void *userData, size_t size, int blockType, long requestNumber, const unsigned char *filename, int lineNumber) #endif { BOOL retval = TRUE; // TRUE = proceed normally, FALSE = alloc error // Change retval to 0 (in debugger) before returning to test error handling switch (allocType) { case _HOOK_ALLOC: // malloc/calloc <= C++ new return retval; case _HOOK_REALLOC: // realloc return retval; case _HOOK_FREE: // free <= C++ delete & delete[] return retval; } ASSERT(0); return TRUE; } #endif CHexEditApp::CHexEditApp() : default_scheme_(""), default_ascii_scheme_(ASCII_NAME), default_ansi_scheme_(ANSI_NAME), default_oem_scheme_(OEM_NAME), default_ebcdic_scheme_(EBCDIC_NAME), default_unicode_scheme_(UNICODE_NAME), default_codepage_scheme_(CODEPAGE_NAME), default_multi_scheme_(MULTI_NAME) { #ifdef FILE_PREVIEW cleanup_thread_ = NULL; #endif // Add a memory allocation hook for debugging purposes // (Does nothing in release version.) _CrtSetAllocHook(&alloc_hook); recording_ = FALSE; macro_version_ = INTERNAL_VERSION; set_options_timer.reset(); highlight_ = FALSE; playing_ = 0; pv_ = pview_ = NULL; refresh_off_ = false; open_plf_ = open_oem_plf_ = open_mb_plf_ = NULL; last_cb_size_ = last_cb_seq_ = 0; #ifndef NDEBUG // Make default capacity for mac_ vector small to force reallocation sooner. // This increases likelihood of catching bugs related to reallocation. mac_.reserve(2); #else // Pre-allocate room for 128 elts for initial speed mac_.reserve(128); #endif open_disp_state_ = -1; // Set up the default colour scheme default_scheme_.AddRange("Other", -1, "0:255"); default_scheme_.mark_col_ = -1; default_scheme_.hex_addr_col_ = -1; default_scheme_.dec_addr_col_ = -1; default_ascii_scheme_.AddRange("ASCII text", -1, "32:126"); default_ascii_scheme_.AddRange("Special (TAB,LF,CR)", RGB(0,128,0), "9,10,13"); default_ascii_scheme_.AddRange("Other", RGB(255,0,0), "0:255"); default_ascii_scheme_.bg_col_ = RGB(255, 253, 244); default_ascii_scheme_.addr_bg_col_ = RGB(224, 240, 224); default_ansi_scheme_.AddRange("ASCII text", -1, "32:126"); default_ansi_scheme_.AddRange("Special (TAB,LF,CR)", RGB(0,128,0), "9,10,13"); default_ansi_scheme_.AddRange("ANSI text", RGB(0,0,128), "130:140,145:156,159:255"); default_ansi_scheme_.AddRange("Other", RGB(255,0,0), "0:255"); default_oem_scheme_.AddRange("ASCII text", -1, "32:126"); default_oem_scheme_.AddRange("Other", RGB(255,0,0), "0:255"); default_oem_scheme_.bg_col_ = RGB(255, 248, 255); default_oem_scheme_.addr_bg_col_ = RGB(240, 224, 240); default_ebcdic_scheme_.AddRange("EBCDIC text", -1, "64,74:80,90:97,106:111,121:127," "129:137,145:153,161:169,192:201,208:217,224,226:233,240:249"); default_ebcdic_scheme_.AddRange("Control", RGB(0,0,128), "0:7,10:34" "36:39,42:43,45:47,50,52:55,59:61,63"); default_ebcdic_scheme_.AddRange("Unassigned", RGB(255,0,0), "0:255"); default_ebcdic_scheme_.bg_col_ = RGB(240, 248, 255); default_ebcdic_scheme_.addr_bg_col_ = RGB(192, 224, 240); default_unicode_scheme_.bg_col_ = RGB(255, 255, 240); default_unicode_scheme_.addr_bg_col_ = RGB(224, 255, 255); default_unicode_scheme_.AddRange("All", RGB(128,128,0), "0:255"); default_codepage_scheme_.bg_col_ = RGB(240, 255, 255); default_codepage_scheme_.addr_bg_col_ = RGB(255, 240, 216); default_codepage_scheme_.AddRange("All", RGB(0,96,96), "0:255"); CString strRange; for (int ii = 0; ii < 51; ++ii) // Split into 51 ranges of 5 -> 255 colours { // Make 5 shades all of this same colour (hue) // We generate 51 hues in the full range - ie 1 to 98 (skipping a few). // Note that the get_rgb() has a bug (hue 99 == hue 0 == red) so we stop at 98 int hue = (ii * 99) / 51 + 1; // Get byte number for this colour strRange.Format("%d", ii*5 + 1); default_multi_scheme_.AddRange("Byte"+strRange, get_rgb(hue, 50, 100), strRange); strRange.Format("%d", ii*5 + 2); default_multi_scheme_.AddRange("Byte"+strRange, get_rgb(hue, 55, 60), strRange); // less saturated strRange.Format("%d", ii*5 + 3); default_multi_scheme_.AddRange("Byte"+strRange, get_rgb(hue, 40, 100), strRange); // less bright strRange.Format("%d", ii*5 + 4); default_multi_scheme_.AddRange("Byte"+strRange, get_rgb(hue, 65, 100), strRange); // more bright strRange.Format("%d", ii*5 + 5); default_multi_scheme_.AddRange("Byte"+strRange, get_rgb(hue, 45, 60), strRange); // less bright and less saturated } default_multi_scheme_.AddRange("All", RGB(255, 255, 255), "0:255"); // 00 (and any of the above later deleted) are white pboyer_ = NULL; algorithm_ = 0; // Default to built-in encryption m_pbookmark_list = NULL; open_current_readonly_ = -1; open_current_shared_ = -1; delete_reg_settings_ = FALSE; delete_all_settings_ = FALSE; // MFC 7.1 has special HTML help mode (but this stuffed our use of HTML help) SetHelpMode(afxHTMLHelp); no_ask_insert_ = false; } CHexEditApp::~CHexEditApp() { if (open_plf_ != NULL) delete open_plf_; if (open_oem_plf_ != NULL) delete open_oem_plf_; if (open_mb_plf_ != NULL) delete open_mb_plf_; } ///////////////////////////////////////////////////////////////////////////// // The one and only CHexEditApp object CHexEditApp theApp; UINT CHexEditApp::wm_hexedit = ::RegisterWindowMessage("HexEditOpenMessage"); static void freeImageOutput(FREE_IMAGE_FORMAT fif, const char* msg) { TRACE("### [FreeImage] [Format=%d] %s\r\n", (int)fif, msg); } ///////////////////////////////////////////////////////////////////////////// // CHexEditApp initialization BOOL CHexEditApp::InitInstance() { FreeImage_SetOutputMessage(freeImageOutput); #if _MFC_VER >= 0x0A00 CString appid; appid.LoadStringA(AFX_IDS_APP_ID); SetAppID(appid); #endif // Note: if this is changed you also need to change the registry string // at the end of ExitInstance (see delete_reg_settings_). SetRegistryKey("ECSoftware"); // Required before registry use (and prevents use of .INI file) //Bring up the splash screen in a secondary UI thread CSplashThread * pSplashThread = NULL; // Check reg setting directly rather than use splash_ so we can display the splash screen quickly (before LoadOptions() is called) if (GetProfileInt("Options", "Splash", 1) == 1) { CString sFileName = ::GetExePath() + FILENAME_SPLASH; if (_access(sFileName, 0) != -1) pSplashThread = (CSplashThread*) AfxBeginThread(RUNTIME_CLASS(CSplashThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); if (pSplashThread != NULL) { ASSERT(pSplashThread->IsKindOf(RUNTIME_CLASS(CSplashThread))); pSplashThread->SetBitmapToUse(sFileName); pSplashThread->ResumeThread(); //Resume the thread now that we have set it up } } if (!AfxOleInit()) // For BCG and COM (calls CoInitialize()) { AfxMessageBox("OLE initialization failed. Make sure that the OLE libraries are the correct version."); return FALSE; } // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Check for /clean on command line Parse command line (before use of // CCommandLineParser - see later) before callling LoadOptions() so // that we can force a clean of registry settings before code is run // that may cause a crash if something is really wrong with reg settings. if (__argc > 1 && (__argv[1][0] == '/' || __argv[1][0] == '-') && _strnicmp(__argv[1]+1, "clean", 5) == 0) { // /cleanup found on cmd line so delete registry settings and exit theApp.delete_reg_settings_ = TRUE; // this forces ExitInstance to delete all reg. settings theApp.ExitInstance(); exit(0); } // Override the document manager so we can make save dialog resizeable if (m_pDocManager != NULL) delete m_pDocManager; m_pDocManager = new CHexEditDocManager; LoadOptions(); InitVersionInfo(); // CCommandLineParser replaces app's CommandLineInfo class. // This uses ParseParam() method (via app's ParseCommandLine() method) // to get all file names on the command line and open them (or tell // already running copt of HexEdit to open them if "one_only_" is true). CCommandLineParser cmdInfo; // Work out if there is a previous instance running hwnd_1st_ = ::FindWindow(HexEditClassName, NULL); if (hwnd_1st_ != (HWND)0 && one_only_) { #ifdef _DEBUG AfxMessageBox("HexEdit ALREADY RUNNING!"); #endif // Make sure it's on top and not minimised before opening files in it ::BringWindowToTop(hwnd_1st_); WINDOWPLACEMENT wp; wp.length = sizeof(wp); if (::GetWindowPlacement(hwnd_1st_, &wp) && (wp.showCmd == SW_MINIMIZE || wp.showCmd == SW_SHOWMINIMIZED)) { ::ShowWindow(hwnd_1st_, SW_RESTORE); } // Now use command line parser (CCommandLineParser::ParseParam) to open // any files specified on the command line in running instance CCommandLineParser cmdInfo; ParseCommandLine(cmdInfo); // Terminate this instance return FALSE; } InitWorkspace(); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. // CMultiDocTemplate* pDocTemplate; // Made pDocTemplate a member variable so I can use it to get all documents of the app. // A better way may have been to get the CDocTemplate from m_pDocManger->m_templateList? m_pDocTemplate = new CMultiDocTemplate( IDR_HEXEDTYPE, RUNTIME_CLASS(CHexEditDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CHexEditView)); AddDocTemplate(m_pDocTemplate); // We must do this before we create the mainframe so that we have bookmarks for the bookmarks dlg m_pbookmark_list = new CBookmarkList(FILENAME_BOOKMARKS); m_pbookmark_list->ReadList(); // create main MDI Frame window. // NOTE: This triggers a lot of other initialization (see CMainFrame::OnCreate) CMainFrame* pMainFrame = new CMainFrame; m_pMainWnd = pMainFrame; // Need this before LoadFrame as calc constructor get main window if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) { return FALSE; } EnableLoadWindowPlacement(FALSE); m_pMainWnd->DragAcceptFiles(); // CHexEditFontCombo::SaveCharSet(); // NOTE: the name "RecentFiles" is also used at end of ExitInstance m_pRecentFileList = new CHexFileList(0, FILENAME_RECENTFILES, recent_files_); m_pRecentFileList->ReadList(); // NOTE: Don't try to open files (eg command line) before this point GetFileList()->SetupJumpList(); // set up Win7 task bar // This used to be after the command line parsing but was moved here so that // when files are opened the size of the main window is known so that they // are opened in sensible sizes and positions. pMainFrame->ShowWindow(m_nCmdShow); m_pMainWnd->SetFocus(); // pMainFrame->ShowWindow(SW_SHOWMAXIMIZED); // Open any files on the command line ParseCommandLine(cmdInfo); // If ParseCommandLine found a shell operation to perform then do it. // If the command is FileOpen then the file has alreay been opened - so nothing needed. // If the command is FileNothing or FileNew then do nothing. if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileOpen && cmdInfo.m_nShellCommand != CCommandLineInfo::FileNothing && cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo)) { return FALSE; } //pMainFrame->FixPanes(); // workaround for BCG bug #ifdef _DEBUG // This avoids all sorts of confusion when testing/debugging // due to toolbars being restored to a previous state. // (Another way would be to just remove all registry settings.) CMFCToolBar::ResetAll(); #endif // It's about time to hide the splash window if (pSplashThread != NULL) pSplashThread->HideSplash(); pMainFrame->UpdateWindow(); // I moved this here (from LoadOptions) as the window sometimes comes up behind and there is // no way to tell that it is even there (since there was no main window-> nothing on task bar). if (cb_text_type_ >= 4 /*CB_TEXT_LAST*/) { const TASKDIALOG_BUTTON custom_buttons[] = { { IDYES, L"Use \"Hex Text\" format" }, { IDNO, L"Use \"traditional\" binary + text formats" }, }; cb_text_type_ = AvoidableTaskDialog ( IDS_CLIPBOARD_FORMAT, "HexEdit supports two main options for using the Windows " "Clipboard. Binary data can be cut, copied and pasted " "as hex digits or as binary data + text.\n\n" "Choose your preferred option for using binary data.", "\nOn user request the \"Hex Text\" clipboard format is now supported " "but this format does have disadvantages as explained below.\n\n" "Hex Text\n\n" "Each byte is placed on the clipboard as two hex digits (with " "appropriate spacing). This makes it easy to paste the hex data " "into a text editor or document. The disadvantage is that it " "uses more memory which may be a problem for large amounts of " "data. It also means you can't copy the actual text content (eg. " "if the binary data happens to be ASCII or other form of text).\n\n" "Binary Data + Text\n\n" "The data is stored in two different formats - as binary data and " "as text. The binary format is efficient and compatible with the " "Visual Studio hex editor. The text format depends on the current " "text format in use such as ASCII or Unicode and allows you to " "copy any text content (non-text byte are ignored).\n\n" "Note that both options preserve all binary values when copying " "and pasting, including NUL (zero) bytes.\n\n" "Also note that you can change this setting at any time " "or choose other options using the Workspace/Edit page " "of the Options dialog.", NULL, 0, MAKEINTRESOURCE(IDI_QUESTIONMARK), custom_buttons, 2 ) == IDYES; } // CG: This line inserted by 'Tip of the Day' component. ShowTipAtStartup(); if (run_autoexec_) RunAutoExec(); #ifdef FILE_PREVIEW // Start background task to clean up old thumbnails CleanupPreviewFiles(); #endif return TRUE; } void CHexEditApp::InitVersionInfo() { // Get HexEdit version info from version resource DWORD dummy; // Version functions take parameters that do nothing?! size_t vi_size; // Size of all version info void* buf = nullptr; // Buffer to hold all version info void *p_version; // Holds ptr to product version string in buffer UINT len; // Length of product version string if ((vi_size = ::GetFileVersionInfoSize(__argv[0], &dummy)) > 0 && (buf = malloc(vi_size+1)) != NULL && ::GetFileVersionInfo(__argv[0], dummy, vi_size, buf) && ::VerQueryValue(buf, "\\StringFileInfo\\040904B0\\ProductVersion", &p_version, &len) ) { CString strVer; if (*((char *)p_version + 1) == 0) strVer = CString((wchar_t *)p_version); else strVer = CString((char *)p_version); char *endptr = strVer.GetBuffer(); version_ = short(strtol(endptr, &endptr, 10) * 100); if (*endptr != '\0') { ++endptr; version_ += short(strtol(endptr, &endptr, 10)); // Check if a beta version if (*endptr != '\0') { ++endptr; beta_ = (short)strtol(endptr, &endptr, 10); if (*endptr != '\0') { ++endptr; revision_ = (short)strtol(endptr, &endptr, 10); } } } } free(buf); // Getting OS version info OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(osvi); GetVersionEx(&osvi); is_nt_ = osvi.dwPlatformId == VER_PLATFORM_WIN32_NT; is_xp_ = osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion >= 5 && osvi.dwMinorVersion >= 1; is_vista_ = osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion >= 6; is_win7_ = osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion >= 6 && osvi.dwMinorVersion >= 1; // Determine if multiple monitor supported (Win 98 or NT >= 5.0) // Note that Windows 95 is 4.00 and Windows 98 is 4.10 mult_monitor_ = (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && osvi.dwMajorVersion == 4 && osvi.dwMinorVersion >= 10 || osvi.dwMajorVersion >= 5) && ::GetSystemMetrics(SM_CMONITORS) > 1; // mult_monitor_ = osvi.dwMajorVersion >= 5; // Check for hexedit.chm file (USE_HTML_HELP) htmlhelp_file_ = m_pszHelpFilePath; htmlhelp_file_.MakeUpper(); if (htmlhelp_file_.Right(4) == ".HLP") { htmlhelp_file_ = htmlhelp_file_.Left(htmlhelp_file_.GetLength() - 4) + ".CHM"; if (_access(htmlhelp_file_, 0) == -1) htmlhelp_file_.Empty(); } // We must do this after getting version info as it relies on is_nt_ m_pspecial_list = special_list_scan_ ? new CSpecialList() : NULL; InitConversions(); // Read EBCDIC conversion table etc and validate conversions // Seed the random number generators unsigned int seed = ::GetTickCount(); srand(seed); // Seed compiler PRNG (simple one) ::rand_good_seed(seed); // Seed our own PRNG // Set the locale to the native environment -- hopefully the MSC run-time // code does something suitable. (This is currently just for thousands sep.) setlocale(LC_ALL, ""); // Set to native locale // Get decimal point characters, thousands separator and grouping struct lconv *plconv = localeconv(); // Set defaults dec_sep_char_ = ','; dec_group_ = 3; dec_point_ = '.'; // Work out thousands separator if (strlen(plconv->thousands_sep) == 1) dec_sep_char_ = *plconv->thousands_sep; // Work out thousands grouping if (strlen(plconv->grouping) != 1) { // Rarely used option of no grouping switch (GetProfileInt("Options", "AllowNoDigitGrouping", -1)) { case -1: if (TaskMessageBox("Number Display Problem", "You have digit grouping for large numbers turned " "off or are using an unsupported grouping/format. " "(See Regional Settings in the Control Panel.)\n\n" "Numbers will be displayed without grouping, eg:\n" "\n2489754937\n\n" "Do you want the default digit grouping instead? eg:\n" "\n2,489,754,937\n\n", MB_YESNO) == IDNO) { WriteProfileInt("Options", "AllowNoDigitGrouping", 1); dec_group_ = 9999; // a big number so that grouping is not done } else { // Remember for next time so we don't ask every time HexEdit is run WriteProfileInt("Options", "AllowNoDigitGrouping", 0); } break; case 1: dec_group_ = 9999; // a big number so that grouping is not done break; case 0: break; // Nothing required - just use default settings above default: ASSERT(0); } } else dec_group_ = *plconv->grouping; // Work out decimal point if (strlen(plconv->decimal_point) == 1) dec_point_ = *plconv->decimal_point; // Work out if we appear to be in US for spelling changes is_us_ = _strnicmp("English_United States", ::setlocale(LC_COLLATE, NULL), 20) == 0; } void CHexEditApp::InitWorkspace() { // The following are for MFC9 (BCG) init SetRegistryBase(_T("Settings")); CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // CMFCVisualManager::GetInstance()->SetFadeInactiveImage(FALSE); VERIFY(InitMouseManager()); VERIFY(InitContextMenuManager()); VERIFY(InitKeyboardManager()); VERIFY(InitShellManager()); //CMFCPopupMenu::EnableMenuSound(FALSE); // These are commands that are always shown in menus (not to be confused // with commands not on toolbars - see AddToolBarForImageCollection) static int dv_id[] = { ID_FILE_NEW, ID_FILE_OPEN, ID_FILE_CLOSE, ID_FILE_SAVE, ID_FILE_PRINT, ID_EXPORT_HEX_TEXT, ID_IMPORT_HEX_TEXT, ID_APP_EXIT, ID_EDIT_UNDO, ID_EDIT_CUT, ID_EDIT_COPY, ID_EDIT_PASTE, ID_COPY_HEX, ID_COPY_CCHAR, ID_PASTE_ASCII, ID_PASTE_UNICODE, ID_PASTE_EBCDIC, ID_MARK, ID_GOTO_MARK, ID_BOOKMARKS_EDIT, ID_EDIT_FIND, ID_EDIT_GOTO, ID_VIEW_VIEWBAR, ID_VIEW_EDITBAR, ID_VIEW_CALCULATOR, ID_VIEW_BOOKMARKS, ID_VIEW_FIND, ID_VIEW_PROPERTIES, ID_VIEW_EXPL, ID_VIEW_STATUS_BAR, ID_VIEW_RULER, ID_AUTOFIT, ID_ADDR_TOGGLE, ID_DISPLAY_HEX, ID_DISPLAY_BOTH, ID_CHARSET_ASCII, ID_CHARSET_ANSI, ID_CHARSET_OEM, ID_CHARSET_EBCDIC, ID_CONTROL_NONE, ID_CONTROL_ALPHA, ID_CONTROL_C, ID_PROPERTIES, ID_ASC2EBC, ID_EBC2ASC, ID_ANSI2IBM, ID_IBM2ANSI, ID_CRC32, ID_MD5, ID_SHA1, ID_SHA256, ID_ENCRYPT_ENCRYPT, ID_ENCRYPT_DECRYPT, ID_ZLIB_COMPRESS, ID_ZLIB_DECOMPRESS, ID_RAND_BYTE, ID_FLIP_16BIT, ID_REV_BYTE, ID_ASSIGN_BYTE, ID_NEG_BYTE, ID_INC_BYTE, ID_DEC_BYTE, ID_GTR_BYTE, ID_LESS_BYTE, ID_ADD_BYTE, ID_SUBTRACT_BYTE, ID_SUBTRACT_X_BYTE, ID_MUL_BYTE, ID_DIV_BYTE, ID_DIV_X_BYTE, ID_MOD_BYTE, ID_MOD_X_BYTE, ID_AND_BYTE, ID_OR_BYTE, ID_INVERT, ID_XOR_BYTE, ID_ROL_BYTE, ID_ROR_BYTE, ID_LSL_BYTE, ID_LSR_BYTE, ID_ASR_BYTE, ID_DFFD_NEW, ID_DFFD_OPEN_FIRST, ID_DFFD_HIDE, ID_DFFD_SPLIT, ID_DFFD_SYNC, ID_DFFD_REFRESH, ID_AERIAL_HIDE, ID_AERIAL_SPLIT, ID_COMP_NEW, ID_COMP_HIDE, ID_COMP_SPLIT, ID_PREVW_HIDE, ID_PREVW_SPLIT, ID_CALCULATOR, ID_CUSTOMIZE, ID_OPTIONS, ID_RECORD, ID_MACRO_LAST, ID_PLAY, ID_WINDOW_NEW, ID_WINDOW_NEXT, ID_HELP_FINDER, ID_CONTEXT_HELP, ID_HELP_TUTE4, ID_HELP_TUTE1, ID_HELP_TUTE2, ID_HELP_TUTE3, ID_HELP_FORUM, ID_HELP_HOMEPAGE, ID_REPAIR_DIALOGBARS, ID_REPAIR_CUST, ID_APP_ABOUT, ID_HIGHLIGHT, ID_DIALOGS_DOCKABLE, ID_IND_SEL, ID_ANT_SEL, ID_AERIAL_ZOOM1, ID_AERIAL_ZOOM2, ID_AERIAL_ZOOM4, ID_AERIAL_ZOOM8, }; CMFCMenuBar::SetRecentlyUsedMenus(FALSE); for (int ii = 0; ii < sizeof(dv_id)/sizeof(*dv_id); ++ii) CMFCToolBar::AddBasicCommand(dv_id[ii]); // Enable BCG tools menu handling // (see CMainFrame::LoadFrame for default tools setup) EnableUserTools(ID_TOOLS_ENTRY, ID_TOOL1, ID_TOOL9, RUNTIME_CLASS (CHexEditUserTool)); #ifdef SYS_SOUNDS // Make sure sound registry settings are present CSystemSound::Add(_T("Invalid Character"), CSystemSound::Get(_T(".Default"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Macro Finished"), CSystemSound::Get(_T("SystemAsterisk"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Macro Error"), CSystemSound::Get(_T(".Default"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Calculator Overflow"), CSystemSound::Get(_T(".Default"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Calculator Error"), CSystemSound::Get(_T(".Default"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Comparison Difference Found")); CSystemSound::Add(_T("Comparison Difference Not Found"), CSystemSound::Get(_T("SystemAsterisk"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Search Text Found")); CSystemSound::Add(_T("Search Text Not Found"), CSystemSound::Get(_T("SystemAsterisk"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Background Search Finished")); CSystemSound::Add(_T("Background Scan Finished")); CSystemSound::Add(_T("Background Compare Finished")); CSystemSound::Add(_T("Invalid Address"), CSystemSound::Get(_T("SystemAsterisk"), _T(".Default"), _T(".Default"))); CSystemSound::Add(_T("Read Only"), CSystemSound::Get(_T("SystemAsterisk"), _T(".Default"), _T(".Default"))); #endif LoadStdProfileSettings(0); // Load standard INI file options (including MRU) GetXMLFileList(); } void CHexEditApp::OnAppExit() { SaveToMacro(km_exit); CWinAppEx::OnAppExit(); } #if 0 // xxx do we need this? // Called on 1st run after upgrade to a new version void CHexEditApp::OnNewVersion(int old_ver, int new_ver) { if (old_ver == 200) { // Version 2.0 used BCG 5.3 which did not support resource smart update CMFCToolBar::ResetAll(); } else if (old_ver == 210) { // We need to reset the Edit Bar otherwise the edit controls (Find/Jump tools) don't work properly CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); mm->m_wndEditBar.RestoreOriginalstate(); } } #endif // Called when a user runs HexEdit who has never run it before void CHexEditApp::OnNewUser() { CString dstFolder; if (!::GetDataPath(dstFolder)) return; // no point in continuing (Win95?) CString dstFile = dstFolder + FILENAME_DTD; // If DTD file exists, probably just the registry settings were deleted so don't ask // if we want to copy (but copy over files if not already there if (::_access(dstFile, 0) == -1 && TaskMessageBox("New User", "This is the first time you have run this version of HexEdit.\n\n" "Do you want to set up you own personal copies of templates and macros?", MB_YESNO) == IDYES) { CopyUserFiles(); } } void CHexEditApp::CopyUserFiles() { CString srcFolder = ::GetExePath(); CString dstFolder; if (srcFolder.IsEmpty() || !::GetDataPath(dstFolder)) { ASSERT(0); return; // no point in continuing if we can't get paths (Win95?) } CString srcFile, dstFile; dstFile = dstFolder + FILENAME_DTD; // We need to copy the following files from the HexEdit binary directory // to the user's application data directory: // BinaryFileFormat.DTD - DTD for templates // *.XML - the templates including Default.XML, _standard_types.XML etc // _windows_constants.TXT - used by C/C++ parser // *.HEM - any provided keystroke macros srcFile = srcFolder + FILENAME_DTD; //dstFile = dstFolder + FILENAME_DTD; // already done above ::MakeSureDirectoryPathExists(dstFile); // this creates any folders if necessary ::CopyFile(srcFile, dstFile, FALSE); srcFile = srcFolder + "_windows_constants.txt"; dstFile = dstFolder + "_windows_constants.txt"; ::CopyFile(srcFile, dstFile, TRUE); CFileFind ff; BOOL bContinue = ff.FindFile(srcFolder + "*.XML"); while (bContinue) { bContinue = ff.FindNextFile(); ::CopyFile(ff.GetFilePath(), dstFolder + ff.GetFileName(), TRUE); } bContinue = ff.FindFile(srcFolder + "*.HEM"); while (bContinue) { bContinue = ff.FindNextFile(); ::CopyFile(ff.GetFilePath(), dstFolder + ff.GetFileName(), TRUE); } } void CHexEditApp::OnFileNew() { no_ask_insert_ = false; // make sure we show ask the user for insert options CWinAppEx::OnFileNew(); } void CHexEditApp::FileFromString(LPCTSTR str) { no_ask_insert_ = true; // turn off insert options as we are simply inserting a string CWinAppEx::OnFileNew(); no_ask_insert_ = false; CHexEditView * pview = GetView(); if (pview != NULL) pview->GetDocument()->Change(mod_insert, 0, strlen(str), (unsigned char *)str, 0, pview); } void CHexEditApp::OnFileOpen() { DWORD flags = OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_SHOWHELP; if (no_recent_add_) flags |= OFN_DONTADDTORECENT; CFileOpenDialog dlgFile(NULL, flags, GetCurrentFilters()); //CHexFileDialog dlgFile("FileOpenDlg", TRUE, NULL, NULL, // flags, GetCurrentFilters()); // Set up buffer where selected file names are stored & default to none char all_files[16384]; all_files[0] = all_files[1] = '\0'; dlgFile.m_ofn.lpstrFile = all_files; dlgFile.m_ofn.nMaxFile = sizeof(all_files)-1; // Set up the title of the dialog CString title; VERIFY(title.LoadString(AFX_IDS_OPENFILE)); dlgFile.m_ofn.lpstrTitle = title; // Change the initial directory CHexEditView * pv; CString strDir; // folder name passed to dialog [this must not be detroyed until after dlgFile.DoModal()] switch (open_locn_) { case FL_DOC: if ((pv = GetView()) != NULL && pv->GetDocument() != NULL && pv->GetDocument()->pfile1_ != NULL) { // Get the path from the filename of the active file CString filename = pv->GetDocument()->pfile1_->GetFilePath(); int path_len; // Length of path (full name without filename) path_len = filename.ReverseFind('\\'); if (path_len == -1) path_len = filename.ReverseFind('/'); if (path_len == -1) path_len = filename.ReverseFind(':'); if (path_len == -1) path_len = 0; else ++path_len; strDir = filename.Left(path_len); } break; case FL_LAST: strDir = last_open_folder_; break; case FL_BOTH: strDir = last_both_folder_; break; default: ASSERT(0); // fall through case FL_SPECIFIED: strDir = open_folder_; break; } // If still empty default to the specified folder if (strDir.IsEmpty()) strDir = open_folder_; dlgFile.m_ofn.lpstrInitialDir = strDir; if (dlgFile.DoModal() != IDOK) // ===== run dialog ======= { mac_error_ = 2; return; } //open_file_readonly_ = (dlgFile.m_ofn.Flags & OFN_READONLY) != 0; // For some absolutely ridiculous reason if the user only selects one file // the full filename is just returned rather than as specified for more than // one file with OFN_ALLOWMULTISELECT. So we need special code to handle this. if (dlgFile.m_ofn.nFileOffset < strlen(all_files)) { ASSERT(all_files[dlgFile.m_ofn.nFileOffset-1] == '\\'); all_files[strlen(all_files)+1] = '\0'; // Ensure double null ended all_files[dlgFile.m_ofn.nFileOffset-1] = '\0'; } // Get directory name as first part of files buffer CString dir_name(all_files); last_open_folder_ = last_both_folder_ = dir_name; // Get file names separated by nul char ('\0') stop on 2 nul chars for (const char *pp = all_files + strlen(all_files) + 1; *pp != '\0'; pp = pp + strlen(pp) + 1) { CString filename; if (dir_name[dir_name.GetLength()-1] == '\\') filename = dir_name + pp; else filename= dir_name + "\\" + pp; // Store this here so the document can find out if it has to open read-only // Note; this is done for each file as it is cleared after each use in file_open ASSERT(open_current_readonly_ == -1); ASSERT(open_current_shared_ == -1); open_current_readonly_ = (dlgFile.m_ofn.Flags & OFN_READONLY) != 0; open_current_shared_ = dlgFile.open_shareable_; CHexEditDoc *pdoc; if ((pdoc = (CHexEditDoc*)(OpenDocumentFile(filename))) != NULL) { // Completed OK so store in macro if recording if (recording_ && mac_.size() > 0 && (mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) mac_.pop_back(); } SaveToMacro(km_open, filename); } else mac_error_ = 20; } } CDocument* CHexEditApp::OpenDocumentFile(LPCTSTR lpszFileName) { CWaitCursor wc; CDocument *retval = CWinAppEx::OpenDocumentFile(lpszFileName); open_current_readonly_ = open_current_shared_ = -1; // just in case OnOpenDocument() not called because file is already open if (retval == NULL) return NULL; // File or device not found (error message has already been shown) // Get file extension and change "." to "_" and make macro filename ASSERT(mac_dir_.Right(1) == "\\"); CString mac_filename = lpszFileName; if (mac_filename.ReverseFind('.') == -1) mac_filename = mac_dir_ + "_.hem"; // Filename without extension else mac_filename = mac_dir_ + CString("_") + mac_filename.Mid(mac_filename.ReverseFind('.')+1) + ".hem"; std::vector<key_macro> mac; CString comment; int halt_lev; long plays; int version; // Version of HexEdit in which the macro was recorded if (::_access(mac_filename, 0) == 0 && macro_load(mac_filename, &mac, comment, halt_lev, plays, version)) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText(comment); macro_play(plays, &mac, halt_lev); } return retval; } void CHexEditApp::CloseByName(const char * fname) { // For each document, allow the user to save it if modified, then close it POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); if (pdoc->GetFilePath().CompareNoCase(fname) == 0) { pdoc->OnCloseDocument(); return; } } } BOOL CHexEditApp::OnOpenRecentFile(UINT nID) { // I had to completely override OnOpenRecentFile (copying most of the code from // CWinAppEx::OnOpenRecentFile) since it does not return FALSE if the file is not // found -- in fact it always returns TRUE. I'd say this is an MFC bug. ASSERT(m_pRecentFileList != NULL); ASSERT(nID >= ID_FILE_MRU_FILE1); ASSERT(nID < ID_FILE_MRU_FILE1 + (UINT)m_pRecentFileList->GetSize()); int nIndex = nID - ID_FILE_MRU_FILE1; ASSERT((*m_pRecentFileList)[nIndex].GetLength() != 0); TRACE2("MRU: open file (%d) '%s'.\n", (nIndex) + 1, (LPCTSTR)(*m_pRecentFileList)[nIndex]); // Save file name now since its index will be zero after it's opened CString file_name = (*m_pRecentFileList)[nIndex]; ASSERT(open_current_readonly_ == -1); ASSERT(open_current_shared_ == -1); if (OpenDocumentFile((*m_pRecentFileList)[nIndex]) == NULL) { if (AvoidableTaskDialog(IDS_RECENT_GONE, "The file or device could not be opened.\n\n" "Do you want to remove the entry from the recent file list?", NULL, NULL, TDCBF_YES_BUTTON | TDCBF_NO_BUTTON) == IDYES) { m_pRecentFileList->Remove(nIndex); } mac_error_ = 10; // User has been told that file could not be found return FALSE; } else { // Completed OK so store in macro if recording if (recording_ && mac_.size() > 0 && (mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) mac_.pop_back(); } SaveToMacro(km_open, file_name); return TRUE; } ASSERT(0); // We shouldn't get here } void CHexEditApp::OnFilePrintSetup() { CPrintDialog pd(TRUE); DoPrintDialog(&pd); SaveToMacro(km_print_setup); } void CHexEditApp::OnFileSaveAll() { // SaveAllModified will prompt to save - we want to simply always save //m_pDocManager->SaveAllModified(); // Get each open document and force save POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); // Note: We don't display a message if the file name is empty as this was a // file that was not yet written to disk and the user probably cancelled // out of the file save dialog (so they already know the file is not saved). if (pdoc->IsModified() && !pdoc->DoFileSave() && !pdoc->GetFileName().IsEmpty()) TaskMessageBox("File Not Saved", "During the \"Save All\" operation the following file could not be saved:\n\n" + pdoc->GetFileName()); } } void CHexEditApp::OnFileCloseAll() { // For each document, allow the user to save it if modified, then close it POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); if (!pdoc->SaveModified()) // save/no save return true, cancel/error returns false return; pdoc->OnCloseDocument(); } } void CHexEditApp::OnFileCloseOthers() { CHexEditDoc *pcurrent = NULL; // current doc (not to be closed) CHexEditView *pview = GetView(); // get current view if (pview != NULL) pcurrent = pview->GetDocument(); // For each document, allow the user to save it if modified, then close it POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); if (pdoc == pcurrent) continue; // bypass current document if (!pdoc->SaveModified()) // save/no save return true, cancel/error returns false return; pdoc->OnCloseDocument(); } } void CHexEditApp::OnFileOpenSpecial() { COpenSpecialDlg dlg; if (dlg.DoModal() == IDOK) { // Store this here so the document can find out if it has to open read-only ASSERT(open_current_readonly_ == -1); open_current_readonly_ = dlg.ReadOnly(); CHexEditDoc *pdoc; if ((pdoc = (CHexEditDoc*)(OpenDocumentFile(dlg.SelectedDevice()))) != NULL) { // Completed OK so store in macro if recording if (recording_ && mac_.size() > 0 && (mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) mac_.pop_back(); } SaveToMacro(km_open, dlg.SelectedDevice()); } else mac_error_ = 20; } else mac_error_ = 2; // User cancelled out of dialog is a minor error } void CHexEditApp::OnUpdateFileOpenSpecial(CCmdUI* pCmdUI) { pCmdUI->Enable(); } void CHexEditApp::OnRepairFiles() { if (TaskMessageBox("Set Up Personal Files?", "This copies factory default files to your personal data folders, " "including macros and templates.\n" "\nIf you already have these files and have made changes to any " "of them then your changes will be overwritten.\n" "\nDo you want to continue?", MB_YESNO) != IDYES) return; CopyUserFiles(); } void CHexEditApp::OnRepairDialogbars() { if (TaskMessageBox("Restore All Dialogs?", "This restores all modeless dialogs so they are " "visible, undocked and unrolled. They include:\n" "* Calculator\n" "* Properties dialog\n" "* Bookmarks dialog\n" "* Find dialog\n" "* Explorer Window\n" "\nYou may need to do this if you cannot restore any of the above dialogs.\n" "\nDo you want to continue?", MB_YESNO) != IDYES) return; CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); ASSERT(mm != NULL); mm->InitDockWindows(); //mm->m_paneExpl.ShowAndUnroll(); mm->m_paneExpl.ShowPane(TRUE, FALSE, TRUE); mm->m_paneFind.ShowPane(TRUE, FALSE, TRUE); mm->m_paneCompareList.ShowPane(TRUE, FALSE, TRUE); } void CHexEditApp::OnRepairCust() { if (TaskMessageBox("Reset Customizations?", "You may need to repair customizations if:\n" "* standard toolbars are missing\n" "* toolbar buttons or menu items are missing\n" "* toolbar or menu icons are incorrect\n" "* standard keystrokes do not work\n" "* you cannot assign custom keystrokes to a command\n\n" "You will lose all customizations including:\n" "* changes to standard toolbars\n" "* changes to all menus including context (popup) menus\n" "* keyboard customizations\n" "\nDo you want to continue?", MB_YESNO, MAKEINTRESOURCE(IDI_CROSS)) != IDYES) return; GetContextMenuManager()->ResetState(); GetKeyboardManager()->ResetAll(); CMFCToolBar::ResetAll(); } void CHexEditApp::OnRepairSettings() { if (TaskMessageBox("Reset Settings?", "All customizations and changes to " "settings will be removed. " "(All registry entries will be removed.)\n" "\nTo do this HexEdit must close.\n" "\nDo you want to continue?", MB_YESNO, MAKEINTRESOURCE(IDI_CROSS)) != IDYES) return; // Signal deletion of all registry settings delete_reg_settings_ = TRUE; CWinAppEx::OnAppExit(); } void CHexEditApp::OnRepairAll() { if (TaskMessageBox("Repair All", "All customizations, registry settings, " "file settings etc will be removed, including:\n" "* toolbar, menu and keyboard customizations\n" "* settings made in the Options dialog\n" "* previously opened files settings (columns etc)\n" "* recent file list, bookmarks, highlights etc\n\n" "When complete you will need to restart HexEdit.\n" "\nAre you absolutely sure you want to continue?", MB_YESNO, MAKEINTRESOURCE(IDI_CROSS)) != IDYES) return; // Signal deletion of all registry settings and settings files delete_all_settings_ = TRUE; CWinAppEx::OnAppExit(); } void CHexEditApp::OnMacroRecord() { // Allow calculator to tidy up any pending macro ops if (recording_) ((CMainFrame *)AfxGetMainWnd())->m_wndCalc.FinishMacro(); recording_ = !recording_; // Don't clear the last macro until we get the first key of the next if (recording_) no_keys_ = TRUE; // Flag to say new macro started else // Track that we are recording in the current version. Note that macro_version_ // may be different if we loaded a macro recorded in a diff version of HexEdt. macro_version_ = INTERNAL_VERSION; #ifdef _DEBUG // Some commands call other commands as part of there task. This can acc- // identally result in extra commands being unintentionally recorded. To // help detect this we display a trace message (in debug version) if there // is more than one entry in the macro vector - to detect problems we must // record a macro with just one command & check the debug window when run. if (!recording_ && mac_.size() > 1) TRACE1("Macro size is %ld\n", long(mac_.size())); #endif // If invoked from toolbar make sure focus returns to view CHexEditView *pview = GetView(); // The active view (or NULL if none) if (pview != NULL && pview != pview->GetFocus()) pview->SetFocus(); } void CHexEditApp::OnUpdateMacroRecord(CCmdUI* pCmdUI) { if (recording_) pCmdUI->SetText("Stop Recording"); else pCmdUI->SetText("Record Macro"); pCmdUI->SetCheck(recording_); } void CHexEditApp::OnMacroPlay() { ASSERT(!recording_); macro_play(); // Set focus to currently active view CHexEditView *pview = GetView(); // The active view (or NULL if none) if (pview != NULL && pview != pview->GetFocus()) pview->SetFocus(); } void CHexEditApp::OnUpdateMacroPlay(CCmdUI* pCmdUI) { // We can play the current macro if we're not recording it and it's not empty pCmdUI->Enable(!recording_ && mac_.size() > 0); } void CHexEditApp::OnMacroMessage() { ASSERT(recording_); if (recording_) { CMacroMessage dlg; if (dlg.DoModal() == IDOK) SaveToMacro(km_macro_message, dlg.message_); } } void CHexEditApp::OnUpdateMacroMessage(CCmdUI* pCmdUI) { pCmdUI->Enable(recording_); } void CHexEditApp::OnMultiPlay() { CMultiplay dlg; dlg.plays_ = plays_; if (dlg.DoModal() == IDOK) { if (dlg.macro_name_ == DEFAULT_MACRO_NAME) { ASSERT(!recording_); plays_ = dlg.plays_; macro_play(plays_); } else { play_macro_file(dlg.macro_name_, dlg.plays_); } } // Set focus to currently active view CHexEditView *pview = GetView(); // The active view (or NULL if none) if (pview != NULL && pview != pview->GetFocus()) pview->SetFocus(); } void CHexEditApp::OnUpdateMultiPlay(CCmdUI* pCmdUI) { if (!recording_ && mac_.size() > 0) { pCmdUI->Enable(TRUE); return; } else { CFileFind ff; ASSERT(mac_dir_.Right(1) == "\\"); BOOL bContinue = ff.FindFile(mac_dir_ + "*.hem"); while (bContinue) { // At least one match - check them all bContinue = ff.FindNextFile(); // Enable if there are macro file that do not start with an underscore OR // there are any macro file if we are recording. if (recording_ || ff.GetFileTitle().Left(1) != "_") { pCmdUI->Enable(TRUE); return; } } } pCmdUI->Enable(FALSE); } void CHexEditApp::play_macro_file(const CString &filename, int pp /*= -1*/) { std::vector<key_macro> tmp; CString comment; int halt_lev; long plays; int version; // Version of HexEdit in which the macro was recorded ASSERT(mac_dir_.Right(1) == "\\"); if (macro_load(mac_dir_ + filename + ".hem", &tmp, comment, halt_lev, plays, version)) { BOOL saved_recording = recording_; recording_ = FALSE; macro_play(pp == -1 ? plays : pp, &tmp, halt_lev); recording_ = saved_recording; SaveToMacro(km_macro_play, filename); } } void CHexEditApp::RunAutoExec() { ASSERT(mac_dir_.Right(1) == "\\"); CString filename = mac_dir_ + "autoexec.hem"; std::vector<key_macro> mac; CString comment; int halt_lev; long plays; int version; // Version of HexEdit in which the macro was recorded if (::_access(filename, 0) == 0 && macro_load(filename, &mac, comment, halt_lev, plays, version)) { ((CMainFrame *)AfxGetMainWnd())->StatusBarText(comment); macro_play(plays, &mac, halt_lev); // Set focus to currently active view CHexEditView *pview = GetView(); // The active view (or NULL if none) if (pview != NULL && pview != pview->GetFocus()) pview->SetFocus(); } } void CHexEditApp::OnRecentFiles() { CRecentFileDlg dlg; dlg.DoModal(); } void CHexEditApp::OnBookmarksEdit() { ASSERT(AfxGetMainWnd() != NULL); ((CMainFrame *)AfxGetMainWnd())->m_paneBookmarks.ShowAndUnroll(); } void CHexEditApp::OnTabIcons() { tabicons_ = !tabicons_; update_tabs(); } void CHexEditApp::OnUpdateTabIcons(CCmdUI* pCmdUI) { pCmdUI->SetCheck(tabicons_); } void CHexEditApp::OnTabsAtBottom() { tabsbottom_ = !tabsbottom_; update_tabs(); } void CHexEditApp::OnUpdateTabsAtBottom(CCmdUI* pCmdUI) { pCmdUI->SetCheck(tabsbottom_); } void CHexEditApp::update_tabs() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (mm != NULL) { ASSERT_KINDOF(CMainFrame, mm); CMDITabInfo mdiTabParams; mdiTabParams.m_bTabIcons = tabicons_; mdiTabParams.m_tabLocation = tabsbottom_ ? CMFCTabCtrl::LOCATION_BOTTOM : CMFCTabCtrl::LOCATION_TOP; mdiTabParams.m_bActiveTabCloseButton = tabclose_; mdiTabParams.m_bAutoColor = tabcolour_; mdiTabParams.m_style = tabcolour_ ? CMFCTabCtrl::STYLE_3D_ONENOTE : CMFCTabCtrl::STYLE_3D_SCROLLED; mdiTabParams.m_bTabCustomTooltips = TRUE; mm->EnableMDITabbedGroups(mditabs_, mdiTabParams); } } ///////////////////////////////////////////////////////////////////////////// // CHexEditApp commands int CHexEditApp::ExitInstance() { #ifdef FILE_PREVIEW // Tell cleanup thread to forget it appdata_.Lock(); if (cleanup_thread_ != NULL) thread_stop_ = true; appdata_.Unlock(); #endif // Save "save on exit" option if it has changed if (save_exit_ != orig_save_exit_) WriteProfileInt("Options", "SaveExit", save_exit_ ? 1 : 0); // Save other options if saving on exit if (save_exit_) SaveOptions(); // If we have a custom clipboard (large temp file) format // then we need to remove it and the temp file. if (!last_cb_temp_file_.IsEmpty()) { // First check if it is still on the clipboard if (last_cb_seq_ == ::GetClipboardSequenceNumber()) { #ifdef _DEBUG // Ensure that the format is still present (else something is very wrong) UINT fmt = ::RegisterClipboardFormat(temp_format_name); ASSERT(::IsClipboardFormatAvailable(fmt)); #endif if (::OpenClipboard(HWND(0))) ::EmptyClipboard(); ::CloseClipboard(); } ::remove(last_cb_temp_file_); last_cb_temp_file_.Empty(); } // If we wrote something big to the clipboard ask the user if they want to delete it else if (last_cb_size_ > 500000 && last_cb_seq_ == ::GetClipboardSequenceNumber() && ::OpenClipboard(HWND(0))) { CString mess; mess.Format("You currently have a large amount of data on the clipboard (%sbytes).\n\n" "Do you want to leave the data on the clipboard?", NumScale((double)last_cb_size_)); if (AvoidableTaskDialog(IDS_LEAVE_LARGE_CB, mess, NULL, NULL, TDCBF_YES_BUTTON | TDCBF_NO_BUTTON) != IDYES) ::EmptyClipboard(); ::CloseClipboard(); } if (pboyer_ != NULL) delete pboyer_; afxGlobalData.CleanUp(); if (m_pbookmark_list != NULL) { m_pbookmark_list->WriteList(); delete m_pbookmark_list; } if (m_pspecial_list != NULL) { delete m_pspecial_list; } int retval = CWinAppEx::ExitInstance(); if (delete_reg_settings_ || delete_all_settings_) { ::SHDeleteKey(HKEY_CURRENT_USER, "Software\\ECSoftware\\HexEdit"); // user settings ::SHDeleteKey(HKEY_LOCAL_MACHINE, "Software\\ECSoftware\\HexEdit"); // machine settings } if (delete_all_settings_) { CString data_path; ::GetDataPath(data_path); if (!data_path.IsEmpty()) { // NOTE: This needs to be updated when new data files added remove(data_path + FILENAME_RECENTFILES); remove(data_path + FILENAME_BOOKMARKS); remove(data_path + FILENAME_BACKGROUND); } } return retval; } BOOL CHexEditApp::PreTranslateMessage(MSG* pMsg) { // The following is necessary to allow controls in the calculator and bookmarks dialog to process // keystrokes normally (eg DEL and TAB keys). If this is not done CWnd::WalkPreTranslateTree // is called which allows the mainframe window to process accelerator keys. This problem was noticed // when DEL and TAB were turned into commands (with associated accelerators) but could have always // happened since 2.0 if the user assigned these keys, arrow keys etc to a command in Customize dialog. HWND hw = ::GetParent(pMsg->hwnd); if (m_pMainWnd != NULL && pMsg->message == WM_KEYDOWN && (hw == ((CMainFrame*)m_pMainWnd)->m_wndCalc || hw == ((CMainFrame*)m_pMainWnd)->m_wndExpl || hw == ((CMainFrame*)m_pMainWnd)->m_wndBookmarks) ) { // Return 0 to allow processing (WM_KEYDOWN) but because we don't call base class version // (CWinAppEx::PreTranslateMessage) we avoid the key being absorbed by a keyboard accelerator. return FALSE; } // This allows a tilde to be inserted in char area (rather than being used for NOT command) CWnd *pwnd = CWnd::FromHandlePermanent(pMsg->hwnd); CHexEditView *pv; if (pMsg->message == WM_CHAR && pwnd != NULL && pwnd->IsKindOf(RUNTIME_CLASS(CHexEditView)) && (pv = DYNAMIC_DOWNCAST(CHexEditView, pwnd)) != NULL && pv->CharMode()) { return FALSE; } #ifdef _DEBUG if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 65) pMsg->message = WM_KEYDOWN; // This is just so we can put a breakpoint here #endif return CWinAppEx::PreTranslateMessage(pMsg); } void CHexEditApp::WinHelp(DWORD dwData, UINT nCmd) { switch(nCmd) { case HELP_CONTEXT: if (::HtmlHelp(m_pMainWnd->GetSafeHwnd(), htmlhelp_file_, HH_HELP_CONTEXT, dwData)) return; break; case HELP_FINDER: if (::HtmlHelp(m_pMainWnd->GetSafeHwnd(), htmlhelp_file_, HH_DISPLAY_TOPIC, dwData)) return; break; } ASSERT(0); AfxMessageBox(AFX_IDP_FAILED_TO_LAUNCH_HELP); } void CHexEditApp::OnAppContextHelp (CWnd* pWndControl, const DWORD dwHelpIDArray []) { CWinAppEx::OnAppContextHelp(pWndControl, dwHelpIDArray); } BOOL CHexEditApp::OnIdle(LONG lCount) { ASSERT(AfxGetMainWnd() != NULL); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); mm->m_wndFind.SendMessage(WM_KICKIDLE); mm->m_wndBookmarks.SendMessage(WM_KICKIDLE); mm->m_wndProp.SendMessage(WM_KICKIDLE); mm->m_wndCalc.SendMessage(WM_KICKIDLE); mm->m_wndCalcHist.SendMessage(WM_KICKIDLE); mm->m_wndExpl.SendMessage(WM_KICKIDLE); mm->m_wndCompareList.SendMessage(WM_KICKIDLE); // Allow docs to check if their background processing has completed POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); if (pdoc != NULL) pdoc->CheckBGProcessing(); } CHexEditView *pview = GetView(); if (lCount == 1 && pview != NULL) { // Check things for the active view pview->check_error(); // check if read error } BOOL tmp1 = mm->UpdateBGSearchProgress(); BOOL tmp2 = mm->UpdateBGCompareProgress(); if (tmp1 || tmp2) { (void)CWinAppEx::OnIdle(lCount); return TRUE; // we want more processing } if (last_cb_seq_ != ::GetClipboardSequenceNumber()) { // clipboard has changed if (!last_cb_temp_file_.IsEmpty()) { ::remove(last_cb_temp_file_); last_cb_temp_file_.Empty(); } } return CWinAppEx::OnIdle(lCount); } void CHexEditApp::PreLoadState() { // Add double click handlers GetMouseManager()->AddView(IDR_CONTEXT_ADDRESS, "Address Area"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_ADDRESS, ID_SELECT_LINE); GetMouseManager()->AddView(IDR_CONTEXT_HEX, "Hex Area"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_HEX, ID_MARK); GetMouseManager()->AddView(IDR_CONTEXT_CHAR, "Character Area"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_CHAR, ID_MARK); GetMouseManager()->AddView(IDR_CONTEXT_HIGHLIGHT, "Highlight"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_HIGHLIGHT, ID_HIGHLIGHT_SELECT); GetMouseManager()->AddView(IDR_CONTEXT_BOOKMARKS, "Bookmark"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_BOOKMARKS, ID_BOOKMARKS_EDIT); GetMouseManager()->AddView(IDR_CONTEXT_OFFSET_HANDLE, "Ruler:Offset Handle"); GetMouseManager()->AddView(IDR_CONTEXT_GROUP_BY_HANDLE, "Ruler:Group Handle"); GetMouseManager()->AddView(IDR_CONTEXT_ROWSIZE_HANDLE, "Ruler:Cols Handle"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_ROWSIZE_HANDLE, ID_AUTOFIT); // default to turn on autofit GetMouseManager()->AddView(IDR_CONTEXT_RULER, "Ruler"); GetMouseManager()->SetCommandForDblClk(IDR_CONTEXT_RULER, ID_ADDR_TOGGLE); // default to toggle hex/dec addresses in adress area and ruler GetContextMenuManager()->AddMenu(_T("Address Area"), IDR_CONTEXT_ADDRESS); GetContextMenuManager()->AddMenu(_T("Hex Area"), IDR_CONTEXT_HEX); GetContextMenuManager()->AddMenu(_T("Character Area"), IDR_CONTEXT_CHAR); GetContextMenuManager()->AddMenu(_T("Aerial View"), IDR_CONTEXT_AERIAL); GetContextMenuManager()->AddMenu(_T("Preview View"), IDR_CONTEXT_PREVW); GetContextMenuManager()->AddMenu(_T("Compare View"), IDR_CONTEXT_COMPARE); GetContextMenuManager()->AddMenu(_T("Highlight"), IDR_CONTEXT_HIGHLIGHT); GetContextMenuManager()->AddMenu(_T("Bookmarks"), IDR_CONTEXT_BOOKMARKS); GetContextMenuManager()->AddMenu(_T("Selection"), IDR_CONTEXT_SELECTION); GetContextMenuManager()->AddMenu(_T("Status Bar"), IDR_CONTEXT_STATBAR); GetContextMenuManager()->AddMenu(_T("Window Tabs"), IDR_CONTEXT_TABS); } // Starts bg searches in all documents except the active doc (passed in pp) void CHexEditApp::StartSearches(CHexEditDoc *pp) { POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); if (pdoc != pp) { CHexEditView *pview = pdoc->GetBestView(); ASSERT(pview != NULL); pdoc->base_addr_ = theApp.align_rel_ ? pview->GetSearchBase() : 0; pdoc->StartSearch(); } } } // Starts bg searches in all documents except the active doc (passed in pp) void CHexEditApp::StopSearches() { POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->StopSearch(); } } void CHexEditApp::NewSearch(const unsigned char *pat, const unsigned char *mask, size_t len, BOOL icase, int tt, BOOL ww, int aa, int offset, bool align_rel) { CSingleLock s2(&appdata_, TRUE); // Save search params for bg search to use if (pboyer_ != NULL) delete pboyer_; pboyer_ = new boyer(pat, len, mask); text_type_ = tt; icase_ = icase; wholeword_ = ww; alignment_ = aa; offset_ = offset; align_rel_ = align_rel; } // Get new encryption algorithm void CHexEditApp::OnEncryptAlg() { CAlgorithm dlg; dlg.m_alg = algorithm_; if (dlg.DoModal() == IDOK) { // Clear password for old algorithm if (algorithm_ > 0) crypto_.SetPassword(algorithm_-1, NULL); // Get new algorithm and create key based on current password algorithm_ = dlg.m_alg; ASSERT(algorithm_ == 0 || algorithm_ - 1 < (int)crypto_.GetNum()); if (algorithm_ > 0 && !password_.IsEmpty()) { // Set key based on password crypto_.SetPassword(algorithm_-1, password_); } else if (algorithm_ > 0 && password_.IsEmpty()) { // Clear password crypto_.SetPassword(algorithm_-1, NULL); } SaveToMacro(km_encrypt_alg, algorithm_==0 ? INTERNAL_ALGORITHM : crypto_.GetName(algorithm_-1)); } } void CHexEditApp::set_alg(const char *pp) { algorithm_ = 0; // Default to internal in case it's not found if (strcmp(pp, INTERNAL_ALGORITHM) != 0) { int ii; for (ii = 0; ii < (int)crypto_.GetNum(); ++ii) { if (strcmp(crypto_.GetName(ii), pp) == 0) { algorithm_ = ii+1; break; } } if (ii == crypto_.GetNum()) { AfxMessageBox(CString("Encryption algorithm not found:\n") + pp); mac_error_ = 10; return; } // ASSERT(algorithm_ > 0); if (!password_.IsEmpty()) { // Set key based on password crypto_.SetPassword(algorithm_-1, password_); } else if (algorithm_ > 0 && password_.IsEmpty()) { // Clear password crypto_.SetPassword(algorithm_-1, NULL); } } } // Get new encryption password void CHexEditApp::OnEncryptPassword() { CPassword dlg; dlg.m_password = password_; if (dlg.DoModal() == IDOK) { password_ = dlg.m_password; // Create encryption key with new password if (algorithm_ > 0) { ASSERT(algorithm_ - 1 < (int)crypto_.GetNum()); crypto_.SetPassword(algorithm_-1, password_); } SaveToMacro(km_encrypt_password, (const char *)password_); } } void CHexEditApp::OnEncryptClear() { password_.Empty(); // Clear password if (algorithm_ > 0) { ASSERT(algorithm_ - 1 < (int)crypto_.GetNum()); crypto_.SetPassword(algorithm_-1, NULL); } SaveToMacro(km_encrypt_password, ""); } void CHexEditApp::set_password(const char *pp) { password_ = pp; if (algorithm_ > 0) { ASSERT(algorithm_ - 1 < (int)crypto_.GetNum()); if (password_.IsEmpty()) crypto_.SetPassword(algorithm_-1, NULL); else crypto_.SetPassword(algorithm_-1, password_); } } void CHexEditApp::OnUpdateEncryptClear(CCmdUI* pCmdUI) { pCmdUI->SetCheck(password_.IsEmpty()); // Set check if password is clear } void CHexEditApp::OnCompressionSettings() { CCompressDlg dlg; dlg.m_defaultLevel = GetProfileInt("Options", "ZlibCompressionDVLevel", 1) ? TRUE : FALSE; dlg.m_defaultWindow = GetProfileInt("Options", "ZlibCompressionDVWindow", 1) ? TRUE : FALSE; dlg.m_defaultMemory = GetProfileInt("Options", "ZlibCompressionDVMemory", 1) ? TRUE : FALSE; dlg.m_level = GetProfileInt("Options", "ZlibCompressionLevel", 7); dlg.m_window = GetProfileInt("Options", "ZlibCompressionWindow", 15); dlg.m_memory = GetProfileInt("Options", "ZlibCompressionMemory", 9); dlg.m_sync = GetProfileInt("Options", "ZlibCompressionSync", 0); dlg.m_headerType = GetProfileInt("Options", "ZlibCompressionHeaderType", 1); dlg.m_strategy = GetProfileInt("Options", "ZlibCompressionStrategy", 0); if (dlg.DoModal() == IDOK) { WriteProfileInt("Options", "ZlibCompressionDVLevel", dlg.m_defaultLevel); WriteProfileInt("Options", "ZlibCompressionDVWindow", dlg.m_defaultWindow); WriteProfileInt("Options", "ZlibCompressionDVMemory", dlg.m_defaultMemory); WriteProfileInt("Options", "ZlibCompressionLevel", dlg.m_level); WriteProfileInt("Options", "ZlibCompressionWindow", dlg.m_window); WriteProfileInt("Options", "ZlibCompressionMemory", dlg.m_memory); WriteProfileInt("Options", "ZlibCompressionSync", dlg.m_sync); WriteProfileInt("Options", "ZlibCompressionHeaderType", dlg.m_headerType); WriteProfileInt("Options", "ZlibCompressionStrategy", dlg.m_strategy); SaveToMacro(km_compress); } } // Retrieve options from .INI file/registry void CHexEditApp::LoadOptions() { switch(GetProfileInt("Options", "SaveExit", 99)) { case 0: orig_save_exit_ = save_exit_ = FALSE; break; case 99: // Option not found OnNewUser(); // Since save_exit_ is only saved when it changes this sets it to // the default (TRUE) and ensure the initial value is saved. orig_save_exit_ = !(save_exit_ = TRUE); break; default: orig_save_exit_ = save_exit_ = TRUE; } one_only_ = GetProfileInt("Options", "OneInstanceOnly", 1) ? TRUE : FALSE; open_restore_ = GetProfileInt("MainFrame", "Restore", 1) ? TRUE : FALSE; special_list_scan_ = GetProfileInt("Options", "DeviceScan", 0) ? TRUE : FALSE; splash_ = GetProfileInt("Options", "Splash", 1) ? TRUE : FALSE; tipofday_ = GetProfileInt("Tip", "StartUp", 0) ? FALSE : TRUE; // inverted run_autoexec_ = GetProfileInt("Options", "RunAutoExec", 1) ? TRUE : FALSE; open_locn_ = GetProfileInt("Options", "OpenLocn", 1); open_folder_ = GetProfileString("Options", "OpenFolder"); if (open_folder_.IsEmpty() && !::GetDataPath(open_folder_)) open_folder_ = ::GetExePath(); save_locn_ = GetProfileInt("Options", "SaveLocn", 0); save_folder_ = GetProfileString("Options", "SaveFolder"); if (save_folder_.IsEmpty() && !::GetDataPath(save_folder_)) save_folder_ = ::GetExePath(); #ifdef FILE_PREVIEW thumbnail_ = GetProfileInt("Options", "ThumbNail", 1) ? TRUE : FALSE; //thumb_8bit_ = GetProfileInt("Options", "ThumbNail8Bit", 0) ? TRUE : FALSE; thumb_frame_ = GetProfileInt("Options", "ThumbNailAllViews", 1) ? TRUE : FALSE; thumb_size_ = GetProfileInt("Options", "ThumbNailSize", 300); if (thumb_size_ < 100 || thumb_size_ > 2000) thumb_size_ = 300 ; thumb_zoom_ = strtod(GetProfileString("Options", "ThumbNailZoom", "1.5"), NULL); if (thumb_zoom_ < 0.5 || thumb_zoom_ > 10) thumb_zoom_ = 1.0; thumb_type_ = GetProfileInt("Options", "ThumbNailType", JPEG_AVERAGE); // default to ave. jpeg if (thumb_type_ <= THUMB_NONE || thumb_type_ >= THUMB_LAST) thumb_type_ = JPEG_AVERAGE; cleanup_days_ = GetProfileInt("Options", "ThumbCleanDays", 100); #endif wipe_type_ = (wipe_t)GetProfileInt("Options", "WipeStrategy", 1); if (wipe_type_ < 0 || wipe_type_ >= WIPE_LAST) wipe_type_ = WIPE_GOOD; show_not_indexed_ = (BOOL)GetProfileInt("Options", "ShowNotIndexedAttribute", 1); sync_tree_ = (BOOL)GetProfileInt("Options", "SyncTreeWithExplorerFolder", 1); custom_explorer_menu_ = (BOOL)GetProfileInt("Options", "CustomExplorerContextMenu", 1); backup_ = (BOOL)GetProfileInt("Options", "CreateBackup", 0); backup_space_ = (BOOL)GetProfileInt("Options", "BackupIfSpace", 1); backup_size_ = GetProfileInt("Options", "BackupIfLess", 0); // 1 = 1KByte, 0 = always backup_prompt_ = (BOOL)GetProfileInt("Options", "BackupPrompt", 1); bg_search_ = GetProfileInt("Options", "BackgroundSearch", 1) ? TRUE : FALSE; bg_stats_ = GetProfileInt("Options", "BackgroundStats", 0) ? TRUE : FALSE; bg_stats_crc32_ = GetProfileInt("Options", "BackgroundStatsCRC32", 1) ? TRUE : FALSE; bg_stats_md5_ = GetProfileInt("Options", "BackgroundStatsMD5", 1) ? TRUE : FALSE; bg_stats_sha1_ = GetProfileInt("Options", "BackgroundStatsSHA1", 1) ? TRUE : FALSE; bg_stats_sha256_ = GetProfileInt("Options", "BackgroundStatsSHA256", 0) ? TRUE : FALSE; bg_stats_sha512_ = GetProfileInt("Options", "BackgroundStatsSHA512", 0) ? TRUE : FALSE; bg_exclude_network_ = GetProfileInt("Options", "BackgroundExcludeNetwork", 1) ? TRUE : FALSE; bg_exclude_removeable_ = GetProfileInt("Options", "BackgroundExcludeRemoveable", 0) ? TRUE : FALSE; bg_exclude_optical_ = GetProfileInt("Options", "BackgroundExcludeOptical", 1) ? TRUE : FALSE; bg_exclude_device_ = GetProfileInt("Options", "BackgroundExcludeDevice", 1) ? TRUE : FALSE; large_cursor_ = GetProfileInt("Options", "LargeCursor", 0) ? TRUE : FALSE; show_other_ = GetProfileInt("Options", "OtherAreaCursor", 1) ? TRUE : FALSE; no_recent_add_ = GetProfileInt("Options", "DontAddToRecent", 1) ? TRUE : FALSE; bool clear = GetProfileInt("Options", "ClearHist", 0) ? TRUE : FALSE; // if old reg entry true then default new list sizes to zero max_search_hist_ = GetProfileInt("History", "MaxSearch", clear ? 0 : 48); max_replace_hist_ = GetProfileInt("History", "MaxReplace", clear ? 0 : 16); max_hex_jump_hist_ = GetProfileInt("History", "MaxHexJump", clear ? 0 : 16); max_dec_jump_hist_ = GetProfileInt("History", "MaxDecJump", clear ? 0 : 16); max_expl_dir_hist_ = GetProfileInt("History", "MaxExplorerFolders", clear ? 0 : 32); max_expl_filt_hist_ = GetProfileInt("History", "MaxExplorerFilters", clear ? 0 : 16); clear_recent_file_list_ = GetProfileInt("Options", "ClearRecentFileList", 0) ? TRUE : FALSE; clear_bookmarks_ = GetProfileInt("Options", "ClearBookmarks", 0) ? TRUE : FALSE; clear_on_exit_ = GetProfileInt("Options", "ClearOnExit", 1) ? TRUE : FALSE; hex_ucase_ = GetProfileInt("Options", "UpperCaseHex", 1) ? TRUE : FALSE; k_abbrev_ = GetProfileInt("Options", "KAbbrev", 1); if (k_abbrev_ < 0) k_abbrev_ = 1; dlg_dock_ = TRUE; //GetProfileInt("MainFrame", "DockableDialogs", 0) > 0 ? TRUE : FALSE; dlg_move_ = GetProfileInt("MainFrame", "FloatDialogsMove", 1) ? TRUE : FALSE; nice_addr_ = GetProfileInt("Options", "NiceAddresses", 1) ? TRUE : FALSE; sel_len_tip_ = GetProfileInt("Options", "SelLenTip", 1) ? TRUE : FALSE; sel_len_div2_ = GetProfileInt("Options", "SelLenDiv2", 1) ? TRUE : FALSE; scroll_past_ends_ = GetProfileInt("Options", "ScrollPastEnds", 1) ? TRUE : FALSE; autoscroll_accel_ = GetProfileInt("Options", "AutoscrollAcceleration", 10); if (autoscroll_accel_ < 0 || autoscroll_accel_ > 50) autoscroll_accel_ = 10; reverse_zoom_ = GetProfileInt("Options", "ReverseMouseWheelZoomDirn", 1) ? TRUE : FALSE; cont_char_ = GetProfileInt("Options", "ContinuationChar", UCODE_BLANK); invalid_char_ = GetProfileInt("Options", "InvalidChar", UCODE_FFFD); ruler_ = GetProfileInt("Options", "ShowRuler", 1) ? TRUE : FALSE; ruler_hex_ticks_ = GetProfileInt("Options", "RulerHexTicks", 4); ruler_dec_ticks_ = GetProfileInt("Options", "RulerDecTicks", 5); ruler_hex_nums_ = GetProfileInt("Options", "RulerHexNums", 1); ruler_dec_nums_ = GetProfileInt("Options", "RulerDecNums", 10); hl_caret_ = GetProfileInt("Options", "ShowCursorInRuler", 1) ? TRUE : FALSE; hl_mouse_ = GetProfileInt("Options", "ShowMouseInRuler", 1) ? TRUE : FALSE; intelligent_undo_ = GetProfileInt("Options", "UndoIntelligent", 0) ? TRUE : FALSE; undo_limit_ = GetProfileInt("Options", "UndoMerge", 5); cb_text_type_ = GetProfileInt("Options", "TextToClipboardAs", INT_MAX); char buf[2]; if (::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, buf, 2) > 0 && buf[0] == '0' && GetProfileString("Printer", "LeftMargin").IsEmpty() ) { print_units_ = prn_unit_t(GetProfileInt("Printer", "Units", 1)); } else { print_units_ = prn_unit_t(GetProfileInt("Printer", "Units", 0)); } left_margin_ = atof(GetProfileString("Printer", "LeftMargin", print_units_ ? "0.3" : "0.1")); right_margin_ = atof(GetProfileString("Printer", "RightMargin", print_units_ ? "0.3" : "0.1")); top_margin_ = atof(GetProfileString("Printer", "TopMargin", print_units_ ? "1.1" : "0.4")); bottom_margin_ = atof(GetProfileString("Printer", "BottomMargin", print_units_ ? "0.8" : "0.3")); print_watermark_ = GetProfileInt("Printer", "PrintWatermark", 0) != 0 ? true : false; watermark_ = GetProfileString("Printer", "Watermark", "CONFIDENTIAL"); header_ = GetProfileString("Printer", "Header", "&F | | &D"); // dv = filename + date diff_first_header_ = GetProfileInt("Printer", "DiffFirstHeader", 0) != 0 ? true : false; first_header_ = GetProfileString("Printer", "FirstHeader", "&A | &X | &N"); footer_ = GetProfileString("Printer", "Footer", " | = &P = | "); diff_first_footer_ = GetProfileInt("Printer", "DiffFirstFooter", 0) != 0 ? true : false; first_footer_ = GetProfileString("Printer", "FirstFooter", "Created: &C | Last modified: &M | Category: &G"); even_reverse_ = GetProfileInt("Printer", "ReverseHeaderFooterOnEvenPages", 0) != 0 ? true : false; header_edge_ = atof(GetProfileString("Printer", "HeaderEdge", print_units_ ? "0.5" : "0.2")); footer_edge_ = atof(GetProfileString("Printer", "FooterEdge", print_units_ ? "0.3" : "0.1")); print_box_ = GetProfileInt("Printer", "Border", 1) != 0 ? true : false; print_hdr_ = GetProfileInt("Printer", "Headings", 0) != 0 ? true : false; spacing_ = GetProfileInt("Printer", "LineSpacing", 0); print_mark_ = GetProfileInt("Printer", "PrintMark", 1) != 0 ? true : false; print_bookmarks_ = GetProfileInt("Printer", "PrintBookmarks", 1) != 0 ? true : false; print_highlights_ = GetProfileInt("Printer", "PrintHighlights", 1) != 0 ? true : false; print_search_ = GetProfileInt("Printer", "PrintSearchOccurrences", 1) != 0 ? true : false; print_change_ = GetProfileInt("Printer", "PrintChangeTracking", 1) != 0 ? true : false; print_compare_ = GetProfileInt("Printer", "PrintCompareTracking", 1) != 0 ? true : false; print_sectors_ = GetProfileInt("Printer", "PrintSectors", 0) != 0 ? true : false; int wt_flags = GetProfileInt("Options", "WindowTabs", 1); switch (wt_flags & 0x3) { case 1: mditabs_ = TRUE; tabsbottom_ = FALSE; break; case 2: mditabs_ = TRUE; tabsbottom_ = TRUE; break; default: mditabs_ = FALSE; tabsbottom_ = FALSE; break; } tabicons_ = (wt_flags & 0x4) == 0; tabclose_ = (wt_flags & 0x8) == 0; tabcolour_ = (wt_flags & 0x10) == 0; aerialview_ = GetProfileInt("Options", "AerialView", 0); aerial_disp_state_ = GetProfileInt("Options", "AerialDisplay", 0x000010B1F); auto_aerial_zoom_ = GetProfileInt("Options", "AerialAutoZoom", 1) != 0 ? true : false; // xxx check box in opt dlg aerial_max_ = GetProfileInt("Aerial", "MaxBitmapInMbytes", 256); if (aerial_max_ < 16) aerial_max_ = 16; else if (aerial_max_ > 999) aerial_max_ = 999; aerial_max_ *= 1024*1024; compview_ = GetProfileInt("Options", "CompareView", 0); prevwview_ = GetProfileInt("Options", "PrevwView", 0); dffdview_ = GetProfileInt("DataFormat", "TreeView", 0); max_fix_for_elts_ = GetProfileInt("DataFormat", "MaxFixForElts", 20); alt_data_bg_cols_ = GetProfileInt("DataFormat", "AltDataBgCols", 1) != 0 ? true : false; default_char_format_ = GetProfileString("DataFormat", "CharDefault", "'%c'"); default_string_format_ = GetProfileString("DataFormat", "StringDefault", "\"%s\""); default_int_format_ = GetProfileString("DataFormat", "IntDefault", "%d"); default_unsigned_format_ = GetProfileString("DataFormat", "UnsignedDefault", "%u"); default_real_format_ = GetProfileString("DataFormat", "RealDefault", "%g"); default_date_format_ = GetProfileString("DataFormat", "DateDefault", "%c"); xml_dir_ = GetProfileString("DataFormat", "Folder"); if (xml_dir_.IsEmpty()) { // If templates in data folder use it else use hexedit .exe directory CString ss; ::GetDataPath(ss); CFileFind ff; if (!ss.IsEmpty() && ff.FindFile(ss + "*.xml")) xml_dir_ = ss; else xml_dir_ = GetExePath(); } // if (xml_dir_.Right(1) != "\\") // xml_dir_ += "\\"; mac_dir_ = GetProfileString("MacroOptions", "Folder"); if (mac_dir_.IsEmpty()) { // If macros in data folder use it else use hexedit .exe directory CString ss; ::GetDataPath(ss); CFileFind ff; if (!ss.IsEmpty() && ff.FindFile(ss + "*.hem")) mac_dir_ = ss; else mac_dir_ = GetExePath(); } // if (mac_dir_.Right(1) != "\\") // mac_dir_ += "\\"; refresh_ = GetProfileInt("MacroOptions", "Refresh", 1); num_secs_ = GetProfileInt("MacroOptions", "Seconds", 5); num_keys_ = GetProfileInt("MacroOptions", "Keys", 1); num_plays_ = GetProfileInt("MacroOptions", "Plays", 1); refresh_bars_ = GetProfileInt("MacroOptions", "StatusBarUpdate", 1) ? TRUE : FALSE; refresh_props_ = GetProfileInt("MacroOptions", "PropertiesUpdate", 0) ? TRUE : FALSE; halt_level_ = GetProfileInt("MacroOptions", "ErrorHaltLevel", 1); plays_ = GetProfileInt("MacroOptions", "NumPlays", 1); open_max_ = GetProfileInt("Options", "OpenMax", 1) ? TRUE : FALSE; open_disp_state_ = GetProfileInt("Options", "OpenDisplayOptions", -1); if (open_disp_state_ == -1) { open_disp_state_ = 0; // all options off // The following block of code is usually redundant as we are saving all state info // in open_disp_state_ but this is here in case of old registry entries. { open_display_.hex_area = GetProfileInt("Options", "OpenDisplayHex", 1) ? TRUE : FALSE; open_display_.char_area = GetProfileInt("Options", "OpenDisplayChar", 1) ? TRUE : FALSE; if (GetProfileInt("Options", "OpenCodePage", 1) != 0) open_display_.char_set = CHARSET_CODEPAGE; else if (GetProfileInt("Options", "OpenEBCDIC", 0) != 0) open_display_.char_set = CHARSET_EBCDIC; else if (GetProfileInt("Options", "OpenGraphicChars", 0) == 0) // no graphics means ASCII open_display_.char_set = CHARSET_ASCII; else if (GetProfileInt("Options", "OpenOemChars", 0) != 0) open_display_.char_set = CHARSET_OEM; else open_display_.char_set = CHARSET_ANSI; open_display_.control = GetProfileInt("Options", "OpenControlChars", 0); open_display_.autofit = GetProfileInt("Options", "OpenAutoFit", 0) ? TRUE : FALSE; open_display_.dec_addr = GetProfileInt("Options", "OpenDecimalAddresses", 0) ? TRUE : FALSE; open_display_.hex_addr = !(open_display_.decimal_addr = open_display_.dec_addr); // don't change this - see above open_display_.hide_highlight = GetProfileInt("Options", "OpenHideHighlight", 0) ? TRUE : FALSE; open_display_.hide_bookmarks = GetProfileInt("Options", "OpenHideBookmarks", 0) ? TRUE : FALSE; open_display_.hide_replace = GetProfileInt("Options", "OpenHideReplace", 0) ? TRUE : FALSE; open_display_.hide_insert = GetProfileInt("Options", "OpenHideInsert", 0) ? TRUE : FALSE; open_display_.hide_delete = GetProfileInt("Options", "OpenHideDelete", 0) ? TRUE : FALSE; open_display_.delete_count = GetProfileInt("Options", "OpenDeleteCount", 1) ? TRUE : FALSE; open_display_.readonly = GetProfileInt("Options", "OpenAllowMods", 0) ? FALSE : TRUE; // reverse of reg value! open_display_.overtype = GetProfileInt("Options", "OpenInsert", 0) ? FALSE : TRUE; // reverse of reg value! open_display_.big_endian = GetProfileInt("Options", "OpenBigEndian", 0) ? TRUE : FALSE; // Don't add any more DISPLAY flags here } // Save back now in new entry in case we crash (and are left with no registry settings) WriteProfileInt("Options", "OpenDisplayOptions", open_disp_state_); // Clear out reg entries to save reg space and to avoid confusing user by leaving unused entries around WriteProfileString("Options", "OpenDisplayHex", NULL); WriteProfileString("Options", "OpenDisplayChar", NULL); WriteProfileString("Options", "OpenGraphicChars", NULL); WriteProfileString("Options", "OpenOemChars", NULL); WriteProfileString("Options", "OpenEBCDIC", NULL); WriteProfileString("Options", "OpenControlChars", NULL); WriteProfileString("Options", "OpenAutoFit", NULL); WriteProfileString("Options", "OpenDecimalAddresses", NULL); WriteProfileString("Options", "OpenHideHighlight", NULL); WriteProfileString("Options", "OpenHideBookmarks", NULL); WriteProfileString("Options", "OpenHideReplace", NULL); WriteProfileString("Options", "OpenHideInsert", NULL); WriteProfileString("Options", "OpenHideDelete", NULL); WriteProfileString("Options", "OpenDeleteCount", NULL); WriteProfileString("Options", "OpenAllowMods", NULL); WriteProfileString("Options", "OpenInsert", NULL); WriteProfileString("Options", "OpenBigEndian", NULL); } if (!open_display_.char_area) open_display_.hex_area = TRUE; // We need to display one or the other (or both) if (!open_display_.hex_area) open_display_.edit_char = open_display_.mark_char = TRUE; // Make sure char_set values are valid // Note: this will be removed later when we support more char sets (Unicode and code page char sets) if (open_display_.char_set == 2) open_display_.char_set = CHARSET_ASCII; // ASCII: 0/2 -> 0 //else if (open_display_.char_set > 4) // open_display_.char_set = CHARSET_EBCDIC; // EBCDIC: 4/5/6/7 -> 4 open_code_page_ = GetProfileInt("Options", "OpenCodePage", 1252); CString strFont = GetProfileString("Options", "OpenFont", "Courier,16"); // Font info string (fields are comma sep.) CString strFace; // Font FaceName from string CString strHeight; // Font height as string AfxExtractSubString(strFace, strFont, 0, ','); AfxExtractSubString(strHeight, strFont, 1, ','); if (!strFace.IsEmpty()) { open_plf_ = new LOGFONT; memset((void *)open_plf_, '\0', sizeof(*open_plf_)); strncpy(open_plf_->lfFaceName, strFace, LF_FACESIZE-1); open_plf_->lfFaceName[LF_FACESIZE-1] = '\0'; open_plf_->lfHeight = atol(strHeight); if (open_plf_->lfHeight < 2 || open_plf_->lfHeight > 100) open_plf_->lfHeight = 16; open_plf_->lfCharSet = ANSI_CHARSET; // Only allow ANSI character set fonts } else open_plf_ = NULL; strFont = GetProfileString("Options", "OpenOemFont", "Terminal,18"); // Font info for oem font AfxExtractSubString(strFace, strFont, 0, ','); AfxExtractSubString(strHeight, strFont, 1, ','); if (!strFace.IsEmpty()) { open_oem_plf_ = new LOGFONT; memset((void *)open_oem_plf_, '\0', sizeof(*open_oem_plf_)); strncpy(open_oem_plf_->lfFaceName, strFace, LF_FACESIZE-1); open_oem_plf_->lfFaceName[LF_FACESIZE-1] = '\0'; open_oem_plf_->lfHeight = atol(strHeight); if (open_oem_plf_->lfHeight < 2 || open_oem_plf_->lfHeight > 100) open_oem_plf_->lfHeight = 18; open_oem_plf_->lfCharSet = OEM_CHARSET; // Only allow OEM/IBM character set fonts } else open_oem_plf_ = NULL; strFont = GetProfileString("Options", "OpenMultibyteFont", "Lucida Sans Unicode,18"); // Font info for CodePage/Unicode font AfxExtractSubString(strFace, strFont, 0, ','); AfxExtractSubString(strHeight, strFont, 1, ','); if (!strFace.IsEmpty()) { open_mb_plf_ = new LOGFONT; memset((void *)open_mb_plf_, '\0', sizeof(*open_mb_plf_)); strncpy(open_mb_plf_->lfFaceName, strFace, LF_FACESIZE-1); open_mb_plf_->lfFaceName[LF_FACESIZE-1] = '\0'; open_mb_plf_->lfHeight = atol(strHeight); if (open_mb_plf_->lfHeight < 2 || open_mb_plf_->lfHeight > 100) open_mb_plf_->lfHeight = 18; } else open_mb_plf_ = NULL; open_rowsize_ = GetProfileInt("Options", "OpenColumns", 16); if (open_rowsize_ < 4 || open_rowsize_ > CHexEditView::max_buf) open_rowsize_ = 4; open_group_by_ = GetProfileInt("Options", "OpenGrouping", 4); if (open_group_by_ < 2) open_group_by_ = 2; open_offset_ = GetProfileInt("Options", "OpenOffset", 0); if (open_offset_ < 0 || open_offset_ >= open_rowsize_) open_offset_ = 0; open_vertbuffer_ = GetProfileInt("Options", "OpenScrollZone", 0); if (open_vertbuffer_ < 0) open_vertbuffer_ = 0; open_scheme_name_ = GetProfileString("Options", "OpenScheme"); open_keep_times_ = GetProfileInt("Options", "OpenKeepTimes", 0) ? TRUE : FALSE; LoadSchemes(); // Always default back to little-endian for decimal & fp pages prop_dec_endian_ = FALSE; prop_fp_endian_ = FALSE; //prop_ibmfp_endian_ = TRUE; prop_date_endian_ = FALSE; password_mask_ = GetProfileInt("Options", "PasswordMask", 1) ? TRUE : FALSE; password_min_ = GetProfileInt("Options", "PasswordMinLength", 8); // Last settings for property sheet prop_page_ = GetProfileInt("Property-Settings", "PropPage", 0); prop_dec_signed_ = GetProfileInt("Property-Settings", "DecFormat", 1); prop_fp_format_ = GetProfileInt("Property-Settings", "FPFormat", 1); //prop_ibmfp_format_ = GetProfileInt("Property-Settings", "IBMFPFormat", 1); prop_date_format_ = GetProfileInt("Property-Settings", "DateFormat", 0); // Restore default file dialog directories last_open_folder_ = GetProfileString("File-Settings", "DirOpen"); last_save_folder_ = GetProfileString("File-Settings", "DirSave"); last_both_folder_ = GetProfileString("File-Settings", "DirBoth"); //open_file_readonly_ = GetProfileInt("File-Settings", "OpenReadOnly", 0); //open_file_shared_ = GetProfileInt("File-Settings", "OpenShareable", 0); // current_save_ = GetProfileString("File-Settings", "Save"); current_write_ = GetProfileString("File-Settings", "Write"); current_read_ = GetProfileString("File-Settings", "Read"); // current_append_ = GetProfileString("File-Settings", "Append"); current_export_ = GetProfileString("File-Settings", "Export"); export_base_addr_ = GetProfileInt("File-Settings", "ExportBaseAddress", 0); export_line_len_ = GetProfileInt("File-Settings", "ExportLineLen", 32); current_import_ = GetProfileString("File-Settings", "Import"); import_discon_ = GetProfileInt("File-Settings", "ImportDiscontiguous", 0); import_highlight_ = GetProfileInt("File-Settings", "ImportHighlight", 0); recent_files_ = GetProfileInt("File-Settings", "RecentFileList", 8); current_filters_ = GetProfileString("File-Settings", "Filters", _T( "All Files (*.*)|*.*|" "Executable files (.exe;.dll;.ocx)|*.exe;*.dll;*.ocx|" "Text files (.txt;.asc;read*)|>*.txt;*.asc;read*|" "INI files (.ini)|>*.ini|" "Batch files (.bat;.cmd)|>*.bat;*.cmd|" "EBCDIC files (.cbl;.cob;.cpy;.ddl;.bms)|>*.cbl;*.cob;*.cpy;*.ddl;*.bms|" "Bitmap image files (.bmp;.dib)|>*.bmp;*.dib|" "Internet image files (.gif;.jpg;.jpeg;.png)|>*.gif;*.jpg;*.jpeg;*.png|" "Windows image files (.ico;.cur;.wmf)|>*.ico;*.cur;*.wmf|" "Other image files (.tif,.pcx)|>*.tif;*.pcx|" "All image file formats|*.bmp;*.dib;*.gif;*.jpg;*.jpeg;*.png;*.ico;*.cur;*.wmf;*.tif;*.pcx|" "Postscript files (.eps;.ps;.prn)|*.eps;*.ps;*.prn|" "MS Word files (.doc;.dot;.rtf)|*.doc;*.dot;*.rtf|" "Windows Write (.wri)|>*.wri|" "Rich Text Format (.rtf)|>*.rtf|" "MS Excel files (.xl*)|>*.xl*|" "MS Access databases (.mdb;.mda;.mdw;.mde)|*.mdb;*.mdw;*.mde;*.mda|" "Resource files (.rc;.rct;.res)|>*.rc;*.rct;*.res|" "HTML files (.htm;.html;.?html;.asp;.css;.php;.php?)|>*.htm;*.html;*.?html;*.asp;*.css;*.php;*.php?|" "XML files (.xml)|>*.xml|" "|")); // Get settings for info tip window tip_transparency_ = GetProfileInt("Options", "InfoTipTransparency", 200); tip_offset_.cx = GetProfileInt("Options", "InfoTipXOffset", 16); tip_offset_.cy = GetProfileInt("Options", "InfoTipYOffset", 16); // get flags which say which hard-coded info is enabled (currently only option is bookmarks) int hard = GetProfileInt("Options", "InfoTipFlags", 0); // if bit is zero option is in use tip_name_.push_back("Bookmarks"); tip_on_.push_back( (hard&0x1) == 0); tip_expr_.push_back(""); tip_format_.push_back(""); ASSERT(tip_name_.size() == FIRST_USER_TIP); // Next get user specified info lines. Each line has 4 fields: // 1. name - name shown to user - if preceded by '>' then this line is disabled (not shown) // 2. expression - evaluated expression involving special symbols such as "address", "byte", etc // 3. format - how the result of the expression is display // 4. unused - for future use (possibly colour and other options) // Symbols: address, sector, offset, byte, sbyte, word, uword, dword, udword, qword, uqword, // ieee32, ieee64, ibm32, ibm64, time_t, time_t_80, time_t_1899, time_t_mins, time64_t CString ss = GetProfileString("Options", "InfoTipUser", ">Address;address;;;" ">Hex Address;address;hex;;" ">Dec Address;address;dec;;" ">Offset Address;address - offset;;;" ">Offset Address;address - offset;hex;;" ">Offset Address;address - offset;dec;;" ">From Mark;address - mark;;;" ">From Mark;address - mark;hex;;" ">From Mark;address - mark;dec;;" ">Hex Sector;sector;hex;;" ">Sector;sector;dec;;" ">ASCII char;byte;%c;;" ">Bits ;byte;bin;;" ">High Bit ;(byte&0x80)!=0;OFF;;" ">Dec Byte;byte;dec;;" ">Sign Byte;sbyte;dec;;" ">Octal Byte;byte;oct;;" ">Word;word;dec;;" ">Word Bits;uword;bin;;" ">Unsigned Word;uword;dec;;" ">Double Word;dword;dec;;" ">Unsigned DWord;udword;dec;;" ">Quad Word;qword;dec;;" ">32 bit IEEE float;ieee32;%.7g;;" ">64 bit IEEE float;ieee64;%.15g;;" ">32 bit IBM float;ibm32;%.7g;;" ">64 bit IBM float;ibm64;%.16g;;" ">Date/time;time_t;%c;;" #ifdef TIME64_T ">64 bit date/time;time64_t;%c;;" #endif ">time_t MSC 5.1;time_t_80;%c;;" ">time_t MSC 7;time_t_1899;%c;;" ">time_t MINS;time_t_mins;%c;;" ">ANSI string;astring;%s;;" // TODO - also handle EBCDIC and Unicode strings ">To EOF;eof - address;dec;;" ";;"); for (int ii = 0; ; ii += 4) { CString name, expr, format; AfxExtractSubString(name, ss, ii, ';'); AfxExtractSubString(expr, ss, ii+1, ';'); if (name.IsEmpty() && expr.IsEmpty()) break; AfxExtractSubString(format, ss, ii+2, ';'); bool on = true; if (name[0] == '>') { on = false; name = name.Mid(1); } tip_name_.push_back(name); tip_on_.push_back(on); tip_expr_.push_back(expr); tip_format_.push_back(format); } } // Save global options to .INI file/registry void CHexEditApp::SaveOptions() { CString ss; // Save general options WriteProfileInt("Options", "SaveExit", save_exit_ ? 1 : 0); WriteProfileInt("Options", "OneInstanceOnly", one_only_ ? 1 : 0); WriteProfileInt("Options", "DeviceScan", special_list_scan_ ? 1 : 0); WriteProfileInt("Options", "Splash", splash_ ? 1 : 0); WriteProfileInt("Tip", "StartUp", tipofday_ ? 0 : 1); // inverted WriteProfileInt("Options", "RunAutoExec", run_autoexec_ ? 1 : 0); WriteProfileInt("Options", "OpenLocn", open_locn_); WriteProfileString("Options", "OpenFolder", open_folder_); WriteProfileInt("Options", "SaveLocn", save_locn_); WriteProfileString("Options", "SaveFolder", save_folder_); #ifdef FILE_PREVIEW WriteProfileInt("Options", "ThumbNail", thumbnail_ ? 1 : 0); //WriteProfileInt("Options", "ThumbNail8Bit", thumb_8bit_ ? 1 : 0); WriteProfileInt("Options", "ThumbNailAllViews", thumb_frame_ ? 1 : 0); WriteProfileInt("Options", "ThumbNailSize", thumb_size_); ss.Format("%g", thumb_zoom_); WriteProfileString("Options", "ThumbNailZoom", ss); WriteProfileInt("Options", "ThumbNailType", thumb_type_); WriteProfileInt("Options", "ThumbCleanDays", cleanup_days_); #endif WriteProfileInt("Options", "WipeStrategy", wipe_type_); WriteProfileInt("Options", "ShowNotIndexedAttribute", show_not_indexed_ ? 1 : 0); WriteProfileInt("Options", "SyncTreeWithExplorerFolder", sync_tree_ ? 1 : 0); WriteProfileInt("Options", "CustomExplorerContextMenu", custom_explorer_menu_ ? 1 : 0); //WriteProfileInt("MainFrame", "DockableDialogs", dlg_dock_ ? 1 : 0); WriteProfileInt("MainFrame", "FloatDialogsMove", dlg_move_ ? 1 : 0); WriteProfileInt("Options", "UpperCaseHex", hex_ucase_ ? 1 : 0); WriteProfileInt("Options", "KAbbrev", k_abbrev_); WriteProfileInt("Options", "NiceAddresses", nice_addr_ ? 1 : 0); WriteProfileInt("Options", "SelLenTip", sel_len_tip_ ? 1 : 0); WriteProfileInt("Options", "SelLenDiv2", sel_len_div2_ ? 1 : 0); WriteProfileInt("Options", "ScrollPastEnds", scroll_past_ends_ ? 1 : 0); WriteProfileInt("Options", "AutoscrollAcceleration", autoscroll_accel_); WriteProfileInt("Options", "ReverseMouseWheelZoomDirn", reverse_zoom_ ? 1 : 0); WriteProfileInt("Options", "ContinuationChar", cont_char_); WriteProfileInt("Options", "InvalidChar", invalid_char_); WriteProfileInt("Options", "ShowRuler", ruler_ ? 1 : 0); WriteProfileInt("Options", "RulerHexTicks", ruler_hex_ticks_); WriteProfileInt("Options", "RulerDecTicks", ruler_dec_ticks_); WriteProfileInt("Options", "RulerHexNums", ruler_hex_nums_); WriteProfileInt("Options", "RulerDecNums", ruler_dec_nums_); WriteProfileInt("Options", "ShowCursorInRuler", hl_caret_ ? 1 : 0); WriteProfileInt("Options", "ShowMouseInRuler", hl_mouse_ ? 1 : 0); WriteProfileInt("Options", "CreateBackup", backup_); WriteProfileInt("Options", "BackupIfSpace", int(backup_space_)); WriteProfileInt("Options", "BackupIfLess", backup_size_); WriteProfileInt("Options", "BackupPrompt", int(backup_prompt_)); WriteProfileInt("Options", "BackgroundSearch", bg_search_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStats", bg_stats_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStatsCRC32", bg_stats_crc32_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStatsMD5", bg_stats_md5_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStatsSHA1", bg_stats_sha1_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStatsSHA256", bg_stats_sha256_ ? 1 : 0); WriteProfileInt("Options", "BackgroundStatsSHA512", bg_stats_sha512_ ? 1 : 0); WriteProfileInt("Options", "BackgroundExcludeNetwork", bg_exclude_network_ ? 1 : 0); WriteProfileInt("Options", "BackgroundExcludeRemoveable", bg_exclude_removeable_ ? 1 : 0); WriteProfileInt("Options", "BackgroundExcludeOptical", bg_exclude_optical_ ? 1 : 0); WriteProfileInt("Options", "BackgroundExcludeDevice", bg_exclude_device_ ? 1 : 0); WriteProfileInt("Options", "LargeCursor", large_cursor_ ? 1 : 0); WriteProfileInt("Options", "OtherAreaCursor", show_other_ ? 1 : 0); WriteProfileInt("Options", "DontAddToRecent", no_recent_add_ ? 1 : 0); WriteProfileInt("History", "MaxSearch", max_search_hist_); WriteProfileInt("History", "MaxReplace", max_replace_hist_); WriteProfileInt("History", "MaxHexJump", max_hex_jump_hist_); WriteProfileInt("History", "MaxDecJump", max_dec_jump_hist_); WriteProfileInt("History", "MaxExplorerFolders", max_expl_dir_hist_); WriteProfileInt("History", "MaxExplorerFilters", max_expl_filt_hist_); WriteProfileInt("Options", "ClearRecentFileList", clear_recent_file_list_ ? 1 : 0); WriteProfileInt("Options", "ClearBookmarks", clear_bookmarks_ ? 1 : 0); // ClearHist has been replaced by MaxSearch etc being set to zero //WriteProfileInt("Options", "ClearHist", clear_hist_ ? 1 : 0); WriteProfileInt("Options", "ClearOnExit", clear_on_exit_ ? 1 : 0); WriteProfileInt("Options", "UndoIntelligent", intelligent_undo_ ? 1 : 0); WriteProfileInt("Options", "UndoMerge", undo_limit_); WriteProfileInt("Options", "TextToClipboardAs", cb_text_type_); WriteProfileInt("Printer", "Border", print_box_ ? 1 : 0); WriteProfileInt("Printer", "Headings", print_hdr_ ? 1 : 0); WriteProfileInt("Printer", "PrintMark", print_mark_ ? 1 : 0); WriteProfileInt("Printer", "PrintBookmarks", print_bookmarks_ ? 1 : 0); WriteProfileInt("Printer", "PrintHighlights", print_highlights_ ? 1 : 0); WriteProfileInt("Printer", "PrintSearchOccurrences", print_search_ ? 1 : 0); WriteProfileInt("Printer", "PrintChangeTracking", print_change_ ? 1 : 0); WriteProfileInt("Printer", "PrintCompareTracking", print_compare_ ? 1 : 0); WriteProfileInt("Printer", "PrintSectors", print_sectors_ ? 1 : 0); WriteProfileInt("Printer", "Units", int(print_units_)); ss.Format("%g", left_margin_); WriteProfileString("Printer", "LeftMargin", ss); ss.Format("%g", right_margin_); WriteProfileString("Printer", "RightMargin", ss); ss.Format("%g", top_margin_); WriteProfileString("Printer", "TopMargin", ss); ss.Format("%g", bottom_margin_); WriteProfileString("Printer", "BottomMargin", ss); WriteProfileInt("Printer", "LineSpacing", spacing_); WriteProfileInt("Printer", "PrintWatermark", print_watermark_ ? 1 : 0); WriteProfileString("Printer", "Watermark", watermark_); WriteProfileString("Printer", "Header", header_); WriteProfileInt("Printer", "DiffFirstHeader", diff_first_header_ ? 1 : 0); WriteProfileString("Printer", "FirstHeader", first_header_); WriteProfileString("Printer", "Footer", footer_); WriteProfileInt("Printer", "DiffFirstFooter", diff_first_footer_ ? 1 : 0); WriteProfileString("Printer", "FirstFooter", first_footer_); WriteProfileInt("Printer", "ReverseHeaderFooterOnEvenPages", even_reverse_ ? 1 : 0); ss.Format("%g", header_edge_); WriteProfileString("Printer", "HeaderEdge", ss); ss.Format("%g", footer_edge_); WriteProfileString("Printer", "FooterEdge", ss); WriteProfileInt("Options", "WindowTabs", !mditabs_ ? 0 : (tabsbottom_ ? 2 : 1) | (!tabicons_ ? 4 : 0) | (!tabclose_ ? 8 : 0) | (!tabcolour_ ? 0x10 : 0)); CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (mm != NULL) mm->SaveFrameOptions(); WriteProfileInt("Options", "AerialView", aerialview_); WriteProfileInt("Options", "AerialDisplay", aerial_disp_state_); WriteProfileInt("Options", "AerialAutoZoom", auto_aerial_zoom_); WriteProfileInt("Aerial", "MaxBitmapInMbytes", aerial_max_/(1024*1024)); WriteProfileInt("Options", "CompareView", compview_); WriteProfileInt("Options", "PrevwView", prevwview_); // Save data format view options WriteProfileInt("DataFormat", "TreeView", dffdview_); WriteProfileInt("DataFormat", "MaxFixForElts", max_fix_for_elts_); WriteProfileInt("DataFormat", "AltDataBgCols", alt_data_bg_cols_ ? 1 : 0); ASSERT(xml_dir_.Right(1) == "\\"); WriteProfileString("DataFormat", "CharDefault", default_char_format_); WriteProfileString("DataFormat", "StringDefault", default_string_format_); WriteProfileString("DataFormat", "IntDefault", default_int_format_); WriteProfileString("DataFormat", "UnsignedDefault", default_unsigned_format_); WriteProfileString("DataFormat", "RealDefault", default_real_format_); WriteProfileString("DataFormat", "DateDefault", default_date_format_); WriteProfileString("DataFormat", "Folder", xml_dir_); // Save macro options ASSERT(mac_dir_.Right(1) == "\\"); WriteProfileString("MacroOptions", "Folder", mac_dir_); WriteProfileInt("MacroOptions", "Refresh", refresh_); WriteProfileInt("MacroOptions", "Seconds", num_secs_); WriteProfileInt("MacroOptions", "Keys", num_keys_); WriteProfileInt("MacroOptions", "Plays", num_plays_); WriteProfileInt("MacroOptions", "StatusBarUpdate", refresh_bars_ ? 1 : 0); WriteProfileInt("MacroOptions", "PropertiesUpdate", refresh_props_ ? 1 : 0); WriteProfileInt("MacroOptions", "ErrorHaltLevel", halt_level_); WriteProfileInt("MacroOptions", "NumPlays", plays_); // Save default window options WriteProfileInt("Options", "OpenMax", open_max_ ? 1 : 0); WriteProfileInt("Options", "OpenDisplayOptions", open_disp_state_); //WriteProfileInt("Options", "OpenDisplayHex", open_display_.hex_area ? 1 : 0); //WriteProfileInt("Options", "OpenDisplayChar", open_display_.char_area ? 1 : 0); //WriteProfileInt("Options", "OpenGraphicChars", open_display_.graphic ? 1 : 0); //WriteProfileInt("Options", "OpenOemChars", open_display_.oem ? 1 : 0); //WriteProfileInt("Options", "OpenEBCDIC", open_display_.ebcdic ? 1 : 0); //WriteProfileInt("Options", "OpenControlChars", open_display_.control); //WriteProfileInt("Options", "OpenAutoFit", open_display_.autofit ? 1 : 0); //WriteProfileInt("Options", "OpenDecimalAddresses", open_display_.dec_addr ? 1 : 0); //WriteProfileInt("Options", "OpenHideHighlight", open_display_.hide_highlight ? 1 : 0); //WriteProfileInt("Options", "OpenHideBookmarks", open_display_.hide_bookmarks ? 1 : 0); //WriteProfileInt("Options", "OpenHideReplace", open_display_.hide_replace ? 1 : 0); //WriteProfileInt("Options", "OpenHideInsert", open_display_.hide_insert ? 1 : 0); //WriteProfileInt("Options", "OpenHideDelete", open_display_.hide_delete ? 1 : 0); //WriteProfileInt("Options", "OpenDeleteCount", open_display_.delete_count ? 1 : 0); //WriteProfileInt("Options", "OpenAllowMods", open_display_.readonly ? 0 : 1); // reverse of reg value! //WriteProfileInt("Options", "OpenInsert", open_display_.overtype ? 0 : 1); // reverse of reg value! //WriteProfileInt("Options", "OpenBigEndian", open_display_.big_endian ? 1 : 0); WriteProfileInt("Options", "OpenCodePage", open_code_page_); WriteProfileInt("Options", "OpenKeepTimes", open_keep_times_ ? 1 : 0); CString strFont; if (open_plf_ != NULL) { strFont.Format("%s,%ld", open_plf_->lfFaceName, open_plf_->lfHeight); WriteProfileString("Options", "OpenFont", strFont); } if (open_oem_plf_ != NULL) { strFont.Format("%s,%ld", open_oem_plf_->lfFaceName, open_oem_plf_->lfHeight); WriteProfileString("Options", "OpenOemFont", strFont); } if (open_mb_plf_ != NULL) { strFont.Format("%s,%ld", open_mb_plf_->lfFaceName, open_mb_plf_->lfHeight); WriteProfileString("Options", "OpenMultibyteFont", strFont); } WriteProfileInt("Options", "OpenColumns", open_rowsize_); WriteProfileInt("Options", "OpenGrouping", open_group_by_); WriteProfileInt("Options", "OpenOffset", open_offset_); WriteProfileInt("Options", "OpenScrollZone", open_vertbuffer_); WriteProfileString("Options", "OpenScheme", open_scheme_name_); // Encryption password options WriteProfileInt("Options", "PasswordMask", password_mask_ ? 1 : 0); if (password_min_ != 8) WriteProfileInt("Options", "PasswordMinLength", password_min_); SaveSchemes(); // Save info about modeless dialogs (find and properties) WriteProfileInt("Property-Settings", "PropPage", prop_page_); WriteProfileInt("Property-Settings", "DecFormat", prop_dec_signed_); WriteProfileInt("Property-Settings", "FPFormat", prop_fp_format_); //WriteProfileInt("Property-Settings", "IBMFPFormat", prop_ibmfp_format_); WriteProfileInt("Property-Settings", "DateFormat", prop_date_format_); // Save directories for file dialogs WriteProfileString("File-Settings", "DirOpen", last_open_folder_); WriteProfileString("File-Settings", "DirSave", last_save_folder_); WriteProfileString("File-Settings", "DirBoth", last_both_folder_); //WriteProfileInt("File-Settings", "OpenReadOnly", open_file_readonly_); //WriteProfileInt("File-Settings", "OpenShareable", open_file_shared_); // WriteProfileString("File-Settings", "Save", current_save_); WriteProfileString("File-Settings", "Write", current_write_); WriteProfileString("File-Settings", "Read", current_read_); WriteProfileInt("File-Settings", "RecentFileList", recent_files_); // WriteProfileString("File-Settings", "Append", current_append_); WriteProfileString("File-Settings", "Export", current_export_); WriteProfileInt("File-Settings", "ExportBaseAddress", export_base_addr_); WriteProfileInt("File-Settings", "ExportLineLen", export_line_len_); WriteProfileString("File-Settings", "Import", current_import_); WriteProfileInt("File-Settings", "ImportDiscontiguous", import_discon_); WriteProfileInt("File-Settings", "ImportHighlight", import_highlight_); WriteProfileString("File-Settings", "Filters", current_filters_); // Save tip (info) window options int hard = 0; CString soft; for (size_t ii = 0; ii < tip_name_.size(); ++ii) { if (ii < FIRST_USER_TIP) { if (!tip_on_[ii]) hard |= (1<<ii); // turn bit on to indicate this one is disabled } else { CString ss; ss.Format("%s%s;%s;%s;;", tip_on_[ii] ? "" : ">", tip_name_[ii], tip_expr_[ii], tip_format_[ii]); soft += ss; } } soft += ";;"; // mark end of list WriteProfileInt("Options", "InfoTipTransparency", tip_transparency_); WriteProfileInt("Options", "InfoTipXOffset", tip_offset_.cx); WriteProfileInt("Options", "InfoTipYOffset", tip_offset_.cy); WriteProfileInt("Options", "InfoTipFlags", hard); WriteProfileString("Options", "InfoTipUser", soft); } void CHexEditApp::LoadSchemes() { scheme_.clear(); // Get the number of schemes int num_schemes = GetProfileInt("Options", "NumberOfSchemes", 0); // For each scheme bool multi_found = false; for (int ii = 0; ii < num_schemes; ++ii) { CString strKey; strKey.Format("Scheme%d", ii+1); // get name, and normal colours (bg etc) CString scheme_name = GetProfileString(strKey, "Name", ""); if (scheme_name.IsEmpty()) break; ASSERT(ii != 0 || scheme_name == ASCII_NAME); ASSERT(ii != 1 || scheme_name == ANSI_NAME); ASSERT(ii != 2 || scheme_name == OEM_NAME); ASSERT(ii != 3 || scheme_name == EBCDIC_NAME); ASSERT(ii != 4 || scheme_name == UNICODE_NAME); ASSERT(ii != 5 || scheme_name == CODEPAGE_NAME); if (scheme_name == MULTI_NAME) multi_found = true; CScheme scheme(scheme_name); scheme.bg_col_ = GetProfileInt(strKey, "BackgroundColour", -2); // Use -2 here to detect new scheme bool is_new = (scheme.bg_col_ == -2); if (is_new) scheme.bg_col_ = -1; // use default background for new scheme scheme.dec_addr_col_ = GetProfileInt(strKey, "DecAddressColour", -1); scheme.hex_addr_col_ = GetProfileInt(strKey, "HexAddressColour", -1); scheme.hi_col_ = GetProfileInt(strKey, "HiColour", -1); scheme.bm_col_ = GetProfileInt(strKey, "BookmarkColour", -1); scheme.mark_col_ = GetProfileInt(strKey, "MarkColour", -2); // If this is an old scheme but no has mark colour (-2) make it the same as // bookmark colour unless bookmark colour is default (-1) thence make it cyan. // (This should make the mark the same colour as in previous version for upgraders.) if (scheme.mark_col_ == -2) scheme.mark_col_ = is_new ? -1 : (scheme.bm_col_ == -1 ? RGB(0, 224, 224) : scheme.bm_col_); scheme.search_col_ = GetProfileInt(strKey, "SearchColour", -1); scheme.trk_col_ = GetProfileInt(strKey, "ChangeTrackingColour", -1); scheme.comp_col_ = GetProfileInt(strKey, "CompareColour", -1); scheme.addr_bg_col_ = GetProfileInt(strKey, "AddressBackgroundColour", -2); // Make address background same as normal background for upgraders. if (scheme.addr_bg_col_ == -2) scheme.addr_bg_col_ = is_new ? -1 : scheme.bg_col_; scheme.sector_col_ = GetProfileInt(strKey, "SectorColour", -1); // For all ranges for (int jj = 0; ; ++jj) { // Get name, colour and range CString name, range, ss; COLORREF col; ss.Format("Name%d", jj+1); name = GetProfileString(strKey, ss); if (name.IsEmpty()) break; ss.Format("Colour%d", jj+1); col = (COLORREF)GetProfileInt(strKey, ss, 0); ss.Format("Range%d", jj+1); range = GetProfileString(strKey, ss, "0:255"); scheme.AddRange(name, col, range); } scheme_.push_back(scheme); } num_schemes = scheme_.size(); // Ensure the "standard" schemes are present if (num_schemes < 1 || scheme_[0].name_.Compare(ASCII_NAME) != 0) scheme_.insert(scheme_.begin() + 0, default_ascii_scheme_); if (num_schemes < 2 || scheme_[1].name_.Compare(ANSI_NAME) != 0) scheme_.insert(scheme_.begin() + 1, default_ansi_scheme_); if (num_schemes < 3 || scheme_[2].name_.Compare(OEM_NAME) != 0) scheme_.insert(scheme_.begin() + 2, default_oem_scheme_); if (num_schemes < 4 || scheme_[3].name_.Compare(EBCDIC_NAME) != 0) scheme_.insert(scheme_.begin() + 3, default_ebcdic_scheme_); if (num_schemes < 5 || scheme_[4].name_.Compare(UNICODE_NAME) != 0) scheme_.insert(scheme_.begin() + 4, default_unicode_scheme_); if (num_schemes < 6 || scheme_[5].name_.Compare(CODEPAGE_NAME) != 0) scheme_.insert(scheme_.begin() + 5, default_codepage_scheme_); // If we had to add schemes then also add our extra ones if (num_schemes < 4) { // At least one standard scheme was missing so it seems that this is // a new installation so should add the plain and multi schemes. CScheme new_scheme(PLAIN_NAME); new_scheme.AddRange("ALL", -1, "0:255"); // Restore these to "Automatic" values which are plain greys & pastels new_scheme.mark_col_ = new_scheme.hex_addr_col_ = new_scheme.dec_addr_col_ = -1; new_scheme.addr_bg_col_ = RGB(240, 240, 240); // Make sure this is always grey new_scheme.hi_col_ = RGB(255, 255, 192); new_scheme.sector_col_ = RGB(224, 192, 192); new_scheme.trk_col_ = RGB(255, 192, 96); new_scheme.comp_col_ = RGB(255, 128, 255); // new_scheme.can_delete_ = TRUE; scheme_.push_back(new_scheme); /* // Leave out rainbow scheme now that we have "Many" scheme CScheme new_scheme2(PRETTY_NAME); new_scheme2.AddRange("NullByte", RGB(254, 254, 254), "0"); // Give nul bytes their own colour (grey) new_scheme2.AddRange("range1", RGB(200, 0, 0), "1:21"); new_scheme2.AddRange("range2", RGB(200, 100, 0), "22:42"); new_scheme2.AddRange("range3", RGB(200, 200, 0), "43:63"); new_scheme2.AddRange("range4", RGB(100, 200, 0), "64:84"); new_scheme2.AddRange("range5", RGB(0, 200, 0), "85:105"); new_scheme2.AddRange("range6", RGB(0, 200, 100), "106:127"); new_scheme2.AddRange("range7", RGB(0, 200, 200), "128:148"); new_scheme2.AddRange("range8", RGB(0, 100, 200), "149:169"); new_scheme2.AddRange("range9", RGB(0, 0, 200), "170:191"); new_scheme2.AddRange("range10", RGB(100, 0, 200), "192:212"); new_scheme2.AddRange("range11", RGB(200, 0, 200), "213:233"); new_scheme2.AddRange("range12", RGB(200, 0, 100), "234:254"); new_scheme2.AddRange("CatchAll", -1, "0:255"); // This should only catch 0xFF scheme_.push_back(new_scheme2); */ } // Add multi scheme if not found if (!multi_found) scheme_.push_back(default_multi_scheme_); } void CHexEditApp::SaveSchemes() { std::vector<CScheme>::const_iterator ps; int ii, jj; // Loop counters CString ss; // Temp reg key name // Save the number of schemes WriteProfileInt("Options", "NumberOfSchemes", scheme_.size()); // Save each scheme for (ii = 0, ps = scheme_.begin(); ps != scheme_.end(); ++ii, ++ps) { CString strKey; strKey.Format("Scheme%d", ii+1); // Save name, and normal colours WriteProfileString(strKey, "Name", ps->name_); WriteProfileInt(strKey, "BackgroundColour", ps->bg_col_); WriteProfileInt(strKey, "DecAddressColour", ps->dec_addr_col_); WriteProfileInt(strKey, "HexAddressColour", ps->hex_addr_col_); WriteProfileInt(strKey, "HiColour", ps->hi_col_); WriteProfileInt(strKey, "BookmarkColour", ps->bm_col_); WriteProfileInt(strKey, "MarkColour", ps->mark_col_); WriteProfileInt(strKey, "SearchColour", ps->search_col_); WriteProfileInt(strKey, "ChangeTrackingColour", ps->trk_col_); WriteProfileInt(strKey, "CompareColour", ps->comp_col_); WriteProfileInt(strKey, "AddressBackgroundColour", ps->addr_bg_col_); WriteProfileInt(strKey, "SectorColour", ps->sector_col_); // Save each range for (jj = 0; jj < (int)ps->range_name_.size(); ++jj) { ss.Format("Name%d", jj+1); WriteProfileString(strKey, ss, ps->range_name_[jj]); ss.Format("Colour%d", jj+1); WriteProfileInt(strKey, ss, ps->range_col_[jj]); std::ostringstream strstr; strstr << ps->range_val_[jj]; ss.Format("Range%d", jj+1); WriteProfileString(strKey, ss, strstr.str().c_str()); } // Delete entry past last one so that any old values are not used ss.Format("Name%d", jj+1); WriteProfileString(strKey, ss, NULL); } } // Get name or description of all XML files for display in drop list void CHexEditApp::GetXMLFileList() { CFileFind ff; xml_file_name_.clear(); ASSERT(xml_dir_.Right(1) == "\\"); BOOL bContinue = ff.FindFile(xml_dir_ + _T("*.XML")); while (bContinue) { // At least one match - check them all bContinue = ff.FindNextFile(); xml_file_name_.push_back(ff.GetFileTitle()); } } #if 0 // replaced by schemes bool CHexEditApp::GetColours(const char *section, const char *key1, const char *key2, const char *key3, partn &retval) { CString name = GetProfileString(section, key1, ""); if (name.IsEmpty()) return false; COLORREF colour = (COLORREF)GetProfileInt(section, key2, 0); CString range = GetProfileString(section, key3, "0:255"); retval = partn(name, colour, range); return true; } void CHexEditApp::SetColours(const char *section, const char *key1, const char *key2, const char *key3, const partn &v) { // Write the range name and RGB value WriteProfileString(section, key1, v.name); WriteProfileInt(section, key2, v.col); // Convert the range itself to a string and write it std::ostringstream strstr; strstr << v.range; WriteProfileString(section, key3, strstr.str().c_str()); } #endif void CHexEditApp::OnProperties() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); // Save this so that we get it before the page activation "keystroke" // (km_prop_file, km_prop_char, etc) SaveToMacro(km_prop); mm->m_paneProp.ShowAndUnroll(); mm->m_wndProp.SetFocus(); mm->m_wndProp.UpdateWindow(); // Needed for when prop dlg opened in a macro } void CHexEditApp::OnPropertiesBitmap() { CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); SaveToMacro(km_prop_bitmap); mm->m_paneProp.ShowAndUnroll(); mm->m_wndProp.SetFocus(); if (mm->m_wndProp.SetActivePage(&mm->m_wndProp.prop_bitmap)) mm->m_wndProp.prop_bitmap.UpdateWindow(); } void CHexEditApp::OnOptions() { display_options(); } void CHexEditApp::OnOptions2() { display_options(WIN_OPTIONS_PAGE); } void CHexEditApp::OnOptionsCodePage() { CHexEditView *pview = GetView(); if (pview != NULL && !pview->CodePageMode()) pview->OnCharsetCodepage(); // switch to code page mode if not already in it display_options(WIN_OPTIONS_PAGE); } // Invoke the options dialog // Param "display_page" indicates which page we want to show // Param "must_show_page" means to force showing of the page void CHexEditApp::display_options(int display_page /* = -1 */, BOOL must_show_page /*=FALSE*/) { // Construct property sheet + its pages COptSheet optSheet(_T("HexEdit Options"), display_page, must_show_page); // Load current settings into the property sheet get_options(optSheet.val_); optSheet.m_psh.dwFlags &= ~(PSH_HASHELP); // Turn off help button optSheet.DoModal(); // Note: updating the options in response to DoModal returning IDOK is // not a good idea as then the Apply button does nothing. } // Get current options into member variables for most pages. // Note: Info tips, Colours and Filters pages are handled differently // They handle their own initialization (OnInitDialog) void CHexEditApp::get_options(struct OptValues &val) { char buf[_MAX_PATH + 3]; // Stores value of key (not used) long buf_size = sizeof(buf); // Size of buffer and returned key value // System val.save_exit_ = save_exit_; val.shell_open_ = RegQueryValue(HKEY_CLASSES_ROOT, HexEditSubSubKey, buf, &buf_size) == ERROR_SUCCESS; val.one_only_ = one_only_; val.special_list_scan_ = special_list_scan_; val.splash_ = splash_; val.tipofday_ = tipofday_; val.run_autoexec_ = run_autoexec_; // Folder options val.open_locn_ = open_locn_; val.open_folder_ = open_folder_; val.save_locn_ = save_locn_; val.save_folder_ = save_folder_; // Preview options val.thumbnail_ = thumbnail_; val.thumb_frame_ = thumb_frame_; val.thumb_size_ = thumb_size_; val.thumb_type_ = thumb_type_ - 1; // THUMB_TYPE to drop-list index val.thumb_zoom_ = thumb_zoom_; val.cleanup_days_ = cleanup_days_; // Explorer options val.wipe_type_ = wipe_type_; val.show_not_indexed_ = show_not_indexed_; val.sync_tree_ = sync_tree_; val.custom_explorer_menu_ = custom_explorer_menu_; // History val.recent_files_ = recent_files_; val.no_recent_add_ = no_recent_add_; val.max_search_hist_ = max_search_hist_; val.max_replace_hist_ = max_replace_hist_; val.max_hex_jump_hist_ = max_hex_jump_hist_; val.max_dec_jump_hist_ = max_dec_jump_hist_; val.max_expl_dir_hist_ = max_expl_dir_hist_; val.max_expl_filt_hist_ = max_expl_filt_hist_; val.clear_recent_file_list_ = clear_recent_file_list_; val.clear_bookmarks_ = clear_bookmarks_; val.clear_on_exit_ = clear_on_exit_; // Macros val.refresh_ = refresh_; val.num_secs_ = num_secs_; val.num_keys_ = num_keys_; val.num_plays_ = num_plays_; val.refresh_props_ = refresh_props_; val.refresh_bars_ = refresh_bars_; val.halt_level_ = halt_level_; // Printer pages val.border_ = print_box_; val.headings_ = print_hdr_; val.print_mark_ = print_mark_; val.print_bookmarks_ = print_bookmarks_; val.print_highlights_ = print_highlights_; val.print_search_ = print_search_; val.print_change_ = print_change_; val.print_compare_ = print_compare_; val.print_sectors_ = print_sectors_; val.units_ = int(print_units_); val.print_watermark_ = print_watermark_; val.watermark_ = watermark_; val.header_ = header_; val.diff_first_header_ = diff_first_header_; val.first_header_ = first_header_; val.footer_ = footer_; val.diff_first_footer_ = diff_first_footer_; val.first_footer_ = first_footer_; val.even_reverse_ = even_reverse_; val.left_ = left_margin_; val.right_ = right_margin_; val.top_ = top_margin_; val.bottom_ = bottom_margin_; val.header_edge_ = header_edge_; val.footer_edge_ = footer_edge_; val.spacing_ = spacing_; // Global display val.open_restore_ = open_restore_; val.mditabs_ = mditabs_; val.tabsbottom_ = tabsbottom_; val.tabicons_ = tabicons_; val.tabclose_ = tabclose_; val.tabcolour_ = tabcolour_; //val.dlg_dock_ = dlg_dock_; val.dlg_move_ = dlg_move_; val.hex_ucase_ = hex_ucase_; val.k_abbrev_ = std::min(k_abbrev_, 3); // may need to increase this if we add more options (eg Tera, etc) val.large_cursor_ = large_cursor_; val.show_other_ = show_other_; val.nice_addr_ = nice_addr_; val.sel_len_tip_ = sel_len_tip_; val.sel_len_div2_ = sel_len_div2_; val.ruler_ = ruler_; val.ruler_dec_ticks_ = ruler_dec_ticks_; val.ruler_dec_nums_ = ruler_dec_nums_; val.ruler_hex_ticks_ = ruler_hex_ticks_; val.ruler_hex_nums_ = ruler_hex_nums_; val.scroll_past_ends_ = scroll_past_ends_; val.autoscroll_accel_ = autoscroll_accel_; val.reverse_zoom_ = reverse_zoom_; val.hl_caret_ = hl_caret_; val.hl_mouse_ = hl_mouse_; val.cont_char_ = cont_char_; val.invalid_char_ = invalid_char_; // Workspace val.intelligent_undo_ = intelligent_undo_; val.undo_limit_ = undo_limit_ - 1; val.cb_text_type_ = cb_text_type_; val.bg_search_ = bg_search_; val.bg_stats_ = bg_stats_; val.bg_stats_crc32_ = bg_stats_crc32_; val.bg_stats_md5_ = bg_stats_md5_; val.bg_stats_sha1_ = bg_stats_sha1_; val.bg_stats_sha256_ = bg_stats_sha256_; val.bg_stats_sha512_ = bg_stats_sha512_; val.bg_exclude_network_ = bg_exclude_network_; val.bg_exclude_removeable_ = bg_exclude_removeable_; val.bg_exclude_optical_ = bg_exclude_optical_; val.bg_exclude_device_ = bg_exclude_device_; // Backup val.backup_ = backup_; val.backup_space_ = backup_space_; val.backup_if_size_ = backup_size_ > 0; val.backup_size_ = backup_size_; val.backup_prompt_ = backup_prompt_; // Export val.address_specified_ = export_base_addr_ != -1; val.base_address_ = export_base_addr_ != -1 ? export_base_addr_ : 0; val.export_line_len_ = export_line_len_; val.aerial_max_ = aerial_max_/(1024*1024); // Global template val.max_fix_for_elts_ = max_fix_for_elts_; val.default_char_format_ = default_char_format_; val.default_int_format_ = default_int_format_; val.default_unsigned_format_ = default_unsigned_format_; val.default_string_format_ = default_string_format_; val.default_real_format_ = default_real_format_; val.default_date_format_ = default_date_format_; // Window page(s) CHexEditView *pview = GetView(); if (pview != NULL) { // Get the name of the active view window and save in window_name_ ((CMDIChildWnd *)((CMainFrame *)AfxGetMainWnd())->MDIGetActive())-> GetWindowText(val.window_name_); val.display_template_ = pview->TemplateViewType(); val.display_aerial_ = pview->AerialViewType(); val.display_comp_ = pview->CompViewType(); val.display_prevw_ = pview->PrevwViewType(); val.disp_state_ = pview->disp_state_; val.code_page_ = pview->code_page_; val.lf_ = pview->lf_; val.oem_lf_ = pview->oem_lf_; val.mb_lf_ = pview->mb_lf_; val.cols_ = pview->rowsize_; val.offset_ = pview->real_offset_; val.grouping_ = pview->group_by_; val.vertbuffer_ = pview->GetVertBufferZone(); // Get whether or not the window is currently maximized WINDOWPLACEMENT wp; CWnd *cc = pview->GetParent(); // Get owner child frame (ancestor window) while (cc != NULL && !cc->IsKindOf(RUNTIME_CLASS(CChildFrame))) // view may be in splitter(s) cc = cc->GetParent(); ASSERT_KINDOF(CChildFrame, cc); cc->GetWindowPlacement(&wp); val.maximize_ = wp.showCmd == SW_SHOWMAXIMIZED; } } // Set options from the dialog after user clicks OK/APPLY void CHexEditApp::set_options(struct OptValues &val) { // This is a big kludge because of problems with property sheets. // First the problem: Each page of a property sheet is an autonomous // dialog with it's own OnOK() etc. The trouble is if the user never // uses a page it is not even created & nothing in that page is called // (ie OnInitDialog() etc) so you can't rely on anything particularly // being called when the user click the OK (or Apply) button in the // property sheet; you can't rely on any particular property page's // OnOK() being called and there is no (easy) way to intercept the // property sheet's button clicking. // We want this so we can update from all pages in this function. // This allows easier moving of controls between pages etc. // But we need to make sure that set_options() is called exactly once // when the user clicks OK or Apply. The solution is to use a timer. // If it has been less than half a second since the last call then // we can assume this is still for the same click of the OK button. if (set_options_timer.elapsed() < 0.3) { TRACE("----------- NOT setting options -------------\n"); set_options_timer.reset(); // ensure repeated calls don't eventually time out return; } TRACE("--------------- setting options -------------\n"); bool invalidate_views = false; // Has something changed that requires redrawing hex windows? CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); char buf[_MAX_PATH + 3]; // Stores value of key (not used) long buf_size = sizeof(buf); // Size of buffer and returned key value if (val.shell_open_ != (RegQueryValue(HKEY_CLASSES_ROOT, HexEditSubSubKey, buf, &buf_size) == ERROR_SUCCESS)) { // Option has been changed (turned on or off) if (AvoidableTaskDialog(IDS_REG_REQUIRED, "In order to change registry settings for all users " "you may be prompted for Administrator privileges.\n\n" "Do you wish to continue?\n\n", NULL, "Admin Privileges", TDCBF_YES_BUTTON | TDCBF_NO_BUTTON) == IDYES) { if (val.shell_open_) { // Create the registry entries that allow "Open with HexEdit" on shortcut menus RegisterOpenAll(); } else { UnregisterOpenAll(); } } } save_exit_ = val.save_exit_; one_only_ = val.one_only_; special_list_scan_ = val.special_list_scan_; splash_ = val.splash_; tipofday_ = val.tipofday_; run_autoexec_ = val.run_autoexec_; open_locn_ = val.open_locn_; open_folder_ = val.open_folder_; save_locn_ = val.save_locn_; save_folder_ = val.save_folder_; thumbnail_ = val.thumbnail_; thumb_frame_ = val.thumb_frame_; thumb_size_ = val.thumb_size_; thumb_type_ = val.thumb_type_ + 1; // drop-list index to enum THUMB_TYPE thumb_zoom_ = val.thumb_zoom_; cleanup_days_ = val.cleanup_days_; wipe_type_ = (wipe_t)val.wipe_type_; show_not_indexed_ = val.show_not_indexed_; if (sync_tree_ != val.sync_tree_) { sync_tree_ = val.sync_tree_; if (sync_tree_) ((CMainFrame*)m_pMainWnd)->m_wndExpl.LinkToTree(); else ((CMainFrame*)m_pMainWnd)->m_wndExpl.UnlinkToTree(); } custom_explorer_menu_ = val.custom_explorer_menu_; if (recent_files_ != val.recent_files_) { recent_files_ = val.recent_files_; GetFileList()->ChangeSize(recent_files_); } no_recent_add_ = val.no_recent_add_; max_search_hist_ = val.max_search_hist_; max_replace_hist_ = val.max_replace_hist_; max_hex_jump_hist_ = val.max_hex_jump_hist_; max_dec_jump_hist_ = val.max_dec_jump_hist_; max_expl_dir_hist_ = val.max_expl_dir_hist_; max_expl_filt_hist_ = val.max_expl_filt_hist_; clear_recent_file_list_ = val.clear_recent_file_list_; clear_bookmarks_ = val.clear_bookmarks_; clear_on_exit_ = val.clear_on_exit_; intelligent_undo_ = val.intelligent_undo_; undo_limit_ = val.undo_limit_ + 1; cb_text_type_ = val.cb_text_type_; // Remember what has changed before starting/stopping background processing bool search_changed = bg_search_ != val.bg_search_ || bg_exclude_device_ != val.bg_exclude_device_ || bg_exclude_network_ != val.bg_exclude_network_ || bg_exclude_removeable_ != val.bg_exclude_removeable_ || bg_exclude_optical_ != val.bg_exclude_optical_; bool stats_changed = bg_stats_ != val.bg_stats_ || bg_exclude_device_ != val.bg_exclude_device_ || bg_exclude_network_ != val.bg_exclude_network_ || bg_exclude_removeable_ != val.bg_exclude_removeable_ || bg_exclude_optical_ != val.bg_exclude_optical_; bool stats_restart = false; if (!stats_changed && val.bg_stats_) { // Stats was on and is still on - we need to check if it needs to restart stats_restart = !bg_stats_crc32_ && val.bg_stats_crc32_ || !bg_stats_md5_ && val.bg_stats_md5_ || !bg_stats_sha1_ && val.bg_stats_sha1_ || !bg_stats_sha256_ && val.bg_stats_sha256_ || !bg_stats_sha512_ && val.bg_stats_sha512_; } bg_search_ = val.bg_search_; bg_stats_ = val.bg_stats_; bg_stats_crc32_ = val.bg_stats_crc32_; bg_stats_md5_ = val.bg_stats_md5_; bg_stats_sha1_ = val.bg_stats_sha1_; bg_stats_sha256_ = val.bg_stats_sha256_; bg_stats_sha512_ = val.bg_stats_sha512_; bg_exclude_network_ = val.bg_exclude_network_; bg_exclude_removeable_ = val.bg_exclude_removeable_; bg_exclude_optical_ = val.bg_exclude_optical_; bg_exclude_device_ = val.bg_exclude_device_; if (search_changed) { POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->AlohaSearch(); // say hello or goodbye to the bg search thread } } if (stats_changed) { POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->AlohaStats(); // say hello or goodbye to the bg stats thread } } else if (stats_restart) { ASSERT(bg_stats_); // stats should be on before we restart them bg_stats_ = FALSE; POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->AlohaStats(); // stop } bg_stats_ = TRUE; posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->AlohaStats(); // restart } } backup_ = val.backup_; backup_space_ = val.backup_space_; backup_size_ = val.backup_if_size_ ? val.backup_size_ : 0; backup_prompt_ = val.backup_prompt_; export_base_addr_ = val.address_specified_ ? val.base_address_ : -1; export_line_len_ = val.export_line_len_; ///////////////////////////////////////////////////////// open_restore_ = val.open_restore_; if (mditabs_ != val.mditabs_ || (mditabs_ && tabsbottom_ != val.tabsbottom_) || (mditabs_ && tabicons_ != val.tabicons_) || (mditabs_ && tabclose_ != val.tabclose_) || (mditabs_ && tabcolour_ != val.tabcolour_) ) { mditabs_ = val.mditabs_; tabsbottom_ = val.tabsbottom_; tabicons_ = val.tabicons_; tabclose_ = val.tabclose_; tabcolour_ = val.tabcolour_; update_tabs(); } if (hex_ucase_ != val.hex_ucase_) { hex_ucase_ = val.hex_ucase_; invalidate_views = true; // redraw windows as they are probably showing hex digits // Fix up case of search strings (find tool, find dlg) CSearchEditControl::RedisplayAll(); mm->m_wndFind.Redisplay(); // Fix up case of hex addresses in hex jump tool(s) CHexEditControl::RedisplayAll(); } if (k_abbrev_ != val.k_abbrev_) { k_abbrev_ = val.k_abbrev_; mm->m_wndProp.Update(GetView()); // may need to update file sizes } //if (dlg_dock_ != val.dlg_dock_) // mm->OnDockableToggle(); dlg_move_ = val.dlg_move_; if (large_cursor_ != val.large_cursor_) { large_cursor_ = val.large_cursor_; // Change caret of all views CMDIChildWnd *nextc; // Loops through all MDI child frames // Find all view windows for (nextc = dynamic_cast<CMDIChildWnd *>(mm->MDIGetActive()); nextc != NULL; nextc = dynamic_cast<CMDIChildWnd *>(nextc->GetWindow(GW_HWNDNEXT)) ) { CHexEditView *pview = dynamic_cast<CHexEditView *>(nextc->GetActiveView()); // Note pview may be NULL if in print preview if (pview != NULL && pview->IsKindOf(RUNTIME_CLASS(CHexEditView))) { if (large_cursor_) pview->BlockCaret(); else pview->LineCaret(); } } } if (show_other_ != val.show_other_) { show_other_ = val.show_other_; invalidate_views = true; } if (nice_addr_ != val.nice_addr_) { nice_addr_ = val.nice_addr_; invalidate_views = true; } sel_len_tip_ = val.sel_len_tip_; sel_len_div2_ = val.sel_len_div2_; if (ruler_ != val.ruler_) { ruler_ = val.ruler_; invalidate_views = true; } if (ruler_dec_ticks_ != val.ruler_dec_ticks_) { ruler_dec_ticks_ = val.ruler_dec_ticks_; invalidate_views = true; } if (ruler_dec_nums_ != val.ruler_dec_nums_) { ruler_dec_nums_ = val.ruler_dec_nums_; invalidate_views = true; } if (ruler_hex_ticks_ != val.ruler_hex_ticks_) { ruler_hex_ticks_ = val.ruler_hex_ticks_; invalidate_views = true; } if (ruler_hex_nums_ != val.ruler_hex_nums_) { ruler_hex_nums_ = val.ruler_hex_nums_; invalidate_views = true; } if (hl_caret_ != val.hl_caret_) { hl_caret_ = val.hl_caret_; invalidate_views = true; } if (hl_mouse_ != val.hl_mouse_) { hl_mouse_ = val.hl_mouse_; invalidate_views = true; } if (scroll_past_ends_ != val.scroll_past_ends_) { scroll_past_ends_ = val.scroll_past_ends_; invalidate_views = true; } if (autoscroll_accel_ != val.autoscroll_accel_) { autoscroll_accel_ = val.autoscroll_accel_; invalidate_views = true; // causes recalc_display which sets accel } reverse_zoom_ = val.reverse_zoom_; if (cont_char_ != val.cont_char_) { cont_char_ = val.cont_char_; invalidate_views = true; } if (invalid_char_ != val.invalid_char_) { invalid_char_ = val.invalid_char_; invalidate_views = true; } aerial_max_ = val.aerial_max_ * 1024 * 1024; // global template options max_fix_for_elts_ = val.max_fix_for_elts_; default_char_format_ = val.default_char_format_; default_int_format_ = val.default_int_format_; default_unsigned_format_ = val.default_unsigned_format_; default_string_format_ = val.default_string_format_; default_real_format_ = val.default_real_format_; default_date_format_ = val.default_date_format_; ///////////////////////////////////////////////////////// refresh_ = val.refresh_; num_secs_ = val.num_secs_; num_keys_ = val.num_keys_; num_plays_ = val.num_plays_; refresh_props_ = val.refresh_props_; refresh_bars_ = val.refresh_bars_; halt_level_ = val.halt_level_; ///////////////////////////////////////////////////////// print_box_ = val.border_ ? true : false; print_hdr_ = val.headings_ ? true : false; print_mark_ = val.print_mark_ ? true : false; print_bookmarks_ = val.print_bookmarks_ ? true : false; print_highlights_ = val.print_highlights_ ? true : false; print_search_ = val.print_search_ ? true : false; print_change_ = val.print_change_ ? true : false; print_compare_ = val.print_compare_ ? true : false; print_sectors_ = val.print_sectors_ ? true : false; print_units_ = prn_unit_t(val.units_); print_watermark_ = val.print_watermark_ ? true : false; watermark_ = val.watermark_; header_ = val.header_; diff_first_header_ = val.diff_first_header_ ? true : false; first_header_ = val.first_header_; footer_ = val.footer_; diff_first_footer_ = val.diff_first_footer_ ? true : false; first_footer_ = val.first_footer_; even_reverse_ = val.even_reverse_ ? true : false; left_margin_ = val.left_; right_margin_ = val.right_; top_margin_ = val.top_; bottom_margin_ = val.bottom_; header_edge_ = val.header_edge_; footer_edge_ = val.footer_edge_; spacing_ = val.spacing_; ///////////////////////////////////////////////////////// // Window page(s) CHexEditView *pview = GetView(); if (pview != NULL) { bool one_done = false; // Have we already made a change (saving undo info) // one_done is used to keep track of the changes made to the view so that // "previous_too" flag is set for all changes made at once except for the // first. This allows all the changes made at the same time to be undone // with one undo operation, which will make more sense to the user. // Make the window maximized or not depending on setting chosen WINDOWPLACEMENT wp; // Get owner child frame (ancestor window) CWnd *cc = pview->GetParent(); while (cc != NULL && !cc->IsKindOf(RUNTIME_CLASS(CChildFrame))) // view may be in splitter(s) cc = cc->GetParent(); ASSERT_KINDOF(CChildFrame, cc); cc->GetWindowPlacement(&wp); if (val.maximize_ != (wp.showCmd == SW_SHOWMAXIMIZED)) { wp.showCmd = val.maximize_ ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL; cc->SetWindowPlacement(&wp); } if (val.display_template_ != pview->TemplateViewType()) { switch (val.display_template_) { case 0: pview->OnDffdHide(); break; case 1: pview->OnDffdSplit(); break; case 2: pview->OnDffdTab(); break; } } if (val.display_aerial_ != pview->AerialViewType()) { switch (val.display_aerial_) { case 0: pview->OnAerialHide(); break; case 1: pview->OnAerialSplit(); break; case 2: pview->OnAerialTab(); break; } } if (val.display_comp_ != pview->CompViewType()) { switch (val.display_comp_) { case 0: pview->OnCompHide(); break; case 1: pview->OnCompSplit(); break; case 2: pview->OnCompTab(); break; } } if (val.display_prevw_ != pview->PrevwViewType()) { switch (val.display_prevw_) { case 0: pview->OnPrevwHide(); break; case 1: pview->OnPrevwSplit(); break; case 2: pview->OnPrevwTab(); break; } } // Make other (undoable) changes if any of the options have changed bool change_required = (!val.autofit_ && pview->rowsize_ != val.cols_) || pview->group_by_ != val.grouping_ || pview->real_offset_ != val.offset_ || pview->disp_state_ != val.disp_state_ || pview->code_page_ != val.code_page_ || (val.display_.FontRequired() == FONT_ANSI && memcmp(&pview->lf_, &val.lf_, sizeof(LOGFONT)) != 0) || (val.display_.FontRequired() == FONT_OEM && memcmp(&pview->oem_lf_, &val.oem_lf_, sizeof(LOGFONT)) != 0) || (val.display_.FontRequired() == FONT_UCODE && memcmp(&pview->mb_lf_, &val.mb_lf_, sizeof(LOGFONT)) != 0); if (change_required) pview->begin_change(); // If current scheme is std scheme and it matches charset change scheme to match new charset if (val.display_.char_set != pview->display_.char_set) { if (pview->scheme_name_ == ANSI_NAME && pview->display_.char_set == CHARSET_ANSI || pview->scheme_name_ == ASCII_NAME && pview->display_.char_set == CHARSET_ASCII || pview->scheme_name_ == OEM_NAME && pview->display_.char_set == CHARSET_OEM || pview->scheme_name_ == EBCDIC_NAME && pview->display_.char_set == CHARSET_EBCDIC || pview->scheme_name_ == UNICODE_NAME && (pview->display_.char_set == CHARSET_UCODE_EVEN || pview->display_.char_set == CHARSET_UCODE_ODD) || pview->scheme_name_ == CODEPAGE_NAME && pview->display_.char_set == CHARSET_CODEPAGE ) { if (val.display_.char_set == CHARSET_ASCII) pview->SetScheme(ASCII_NAME); else if (val.display_.char_set == CHARSET_OEM) pview->SetScheme(OEM_NAME); else if (val.display_.char_set == CHARSET_EBCDIC) pview->SetScheme(EBCDIC_NAME); else if (pview->display_.char_set == CHARSET_UCODE_EVEN || pview->display_.char_set == CHARSET_UCODE_ODD) pview->SetScheme(UNICODE_NAME); else if (val.display_.char_set == CHARSET_CODEPAGE) pview->SetScheme(CODEPAGE_NAME); else pview->SetScheme(ANSI_NAME); if (one_done) pview->undo_.back().previous_too = true; one_done = true; } } if (val.display_.autofit != pview->display_.autofit) { pview->do_autofit(val.display_.autofit); if (one_done) pview->undo_.back().previous_too = true; one_done = true; } pview->disp_state_ = val.disp_state_; pview->SetCodePage(val.code_page_); // xxx also allow undo of code page if (change_required) { one_done = pview->make_change(one_done) != 0; // save disp_state_ in undo vector SaveToMacro(km_display_state, pview->disp_state_); } if (val.display_.vert_display && pview->GetVertBufferZone() < 2) pview->SetVertBufferZone(2); // Make sure we can always see the other 2 rows at the same address // Do this after autofit changed so that rowsize_ is not messed up by old autofit value if (!val.display_.autofit && pview->rowsize_ != val.cols_) { pview->change_rowsize(val.cols_); if (one_done) pview->undo_.back().previous_too = true; one_done = true; } if (pview->group_by_ != val.grouping_) { pview->change_group_by(val.grouping_); if (one_done) pview->undo_.back().previous_too = true; one_done = true; } if (pview->real_offset_ != val.offset_) { pview->change_offset(val.offset_); if (one_done) pview->undo_.back().previous_too = true; one_done = true; } // Do this after disp_state_ change as restoring the correct font // (ANSI or OEM) relies on the state being correct. if (val.display_.FontRequired() == FONT_ANSI && memcmp(&pview->lf_, &val.lf_, sizeof(LOGFONT)) != 0) { LOGFONT *prev_lf = new LOGFONT; *prev_lf = pview->lf_; pview->lf_ = val.lf_; pview->undo_.push_back(view_undo(undo_font)); // Allow undo of font change pview->undo_.back().plf = prev_lf; if (one_done) pview->undo_.back().previous_too = true; one_done = true; } if (val.display_.FontRequired() == FONT_OEM && memcmp(&pview->oem_lf_, &val.oem_lf_, sizeof(LOGFONT)) != 0) { LOGFONT *prev_lf = new LOGFONT; *prev_lf = pview->oem_lf_; pview->oem_lf_ = val.oem_lf_; pview->undo_.push_back(view_undo(undo_font)); // Allow undo of font change pview->undo_.back().plf = prev_lf; if (one_done) pview->undo_.back().previous_too = true; one_done = true; } // xxx TODO we should have 3 separate undo_font_xxx for the 3 fonts ??? xxx if (val.display_.FontRequired() == FONT_UCODE && memcmp(&pview->mb_lf_, &val.mb_lf_, sizeof(LOGFONT)) != 0) { LOGFONT *prev_lf = new LOGFONT; *prev_lf = pview->mb_lf_; pview->mb_lf_ = val.mb_lf_; pview->undo_.push_back(view_undo(undo_font)); // Allow undo of font change pview->undo_.back().plf = prev_lf; if (one_done) pview->undo_.back().previous_too = true; one_done = true; } // Vert buffer zone is not an undoable operation if (val.vertbuffer_ != pview->GetVertBufferZone()) pview->SetVertBufferZone(val.vertbuffer_); if (change_required) { pview->end_change(); // updates display AfxGetApp()->OnIdle(0); // This forces buttons & status bar pane update when Apply button used } } if (invalidate_views) { // Invalidate all views to change display of hex digits CMainFrame *mm = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); CMDIChildWnd *nextc; // Loops through all MDI child frames // Invalidate all view windows for (nextc = dynamic_cast<CMDIChildWnd *>(mm->MDIGetActive()); nextc != NULL; nextc = dynamic_cast<CMDIChildWnd *>(nextc->GetWindow(GW_HWNDNEXT)) ) { CChildFrame * pfrm = dynamic_cast<CChildFrame *>(nextc); CHexEditView * phev = pfrm->GetHexEditView(); if (phev != NULL) { phev->recalc_display(); // Address width, etc may have changed phev->DoInvalidate(); } } } set_options_timer.reset(); } CString CHexEditApp::GetCurrentFilters() { CString retval; // Set up the grid cells for (int ii = 0; ; ++ii) { CString s1, s2; AfxExtractSubString(s1, current_filters_, ii*2, '|'); AfxExtractSubString(s2, current_filters_, ii*2+1, '|'); if (s1.IsEmpty() && s2.IsEmpty()) break; if (s1.IsEmpty() || s2.IsEmpty() || s2[0] == '>') continue; retval += s1 + "|" + s2 + "|"; } if (retval.IsEmpty()) retval = "All Files (*.*)|*.*||"; else retval += "|"; return retval; } void CHexEditApp::ShowTipAtStartup(void) { // CG: This function added by 'Tip of the Day' component. CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); if (cmdInfo.m_bShowSplash /* && _access("HexEdit.tip", 0) == 0*/) { CTipDlg dlg; if (dlg.m_bStartup) dlg.DoModal(); } } void CHexEditApp::ShowTipOfTheDay(void) { // CG: This function added by 'Tip of the Day' component. CTipDlg dlg; dlg.DoModal(); // This bit not added by the automatic "Tip of the Day" component SaveToMacro(km_tips); } void CHexEditApp::OnHelpReportIssue() { ::BrowseWeb(IDS_WEB_REPORT_ISSUE); } void CHexEditApp::OnUpdateHelpReportIssue(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CHexEditApp::OnWebPage() { // Go to hexedit web site ::BrowseWeb(IDS_WEB_ADDRESS); } BOOL CHexEditApp::backup(LPCTSTR filename, FILE_ADDRESS file_len) const { BOOL retval = FALSE; if (backup_) { // Default to TRUE but if any test below fails set to FALSE retval = TRUE; if (retval && backup_space_ && file_len >= AvailableSpace(filename) - 65536) // allow 64K leeway { retval = FALSE; } // Make sure file length is less than max backup size (in Mbytes) if (retval && backup_size_ > 0 && file_len > FILE_ADDRESS(backup_size_)*1024) { retval = FALSE; } // If still backing up and prompt the user (if required) if (retval && backup_prompt_ && TaskMessageBox("Create Backup?", "Do you want to create a backup copy of this file?", MB_YESNO) != IDYES) { retval = FALSE; } } return retval; } #if 0 // This dummy doc no longer needed since we no lomger use CHtmlView // This is all needed I think just to get a dummy document class class CDummyDoc : public CDocument { protected: // create from serialization only CDummyDoc() {} DECLARE_DYNCREATE(CDummyDoc) public: virtual ~CDummyDoc() {} protected: DECLARE_MESSAGE_MAP() }; IMPLEMENT_DYNCREATE(CDummyDoc, CDocument) BEGIN_MESSAGE_MAP(CDummyDoc, CDocument) END_MESSAGE_MAP() #endif void CHexEditApp::OnHelpWeb() { #if 0 // Don't use HtmlView, just fire up browser instead static CMultiDocTemplate *pDocTemplate = NULL; if (pDocTemplate == NULL) { pDocTemplate = new CMultiDocTemplate( IDR_HEXEDTYPE, RUNTIME_CLASS(CDummyDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CHtmlView)); } CDocument *pDoc = pDocTemplate->OpenDocumentFile(NULL); ASSERT(pDoc != NULL); if (pDoc == NULL) return; POSITION pos = pDoc->GetFirstViewPosition(); if (pos != NULL) { CHtmlView *pView = (CHtmlView *)pDoc->GetNextView(pos); ASSERT_KINDOF(CHtmlView, pView); // Go to hexedit web site CString str; VERIFY(str.LoadString(IDS_WEB_HELP)); pView->Navigate2(str); } #elif 0 ::BrowseWeb(IDS_WEB_HELP); #else // TODO: online help. HWND hWindow = AfxGetMainWnd()->GetSafeHwnd(); MessageBox(hWindow, "Online help is not available just yet. Sorry for the inconvenience!", "HexEdit", MB_ICONINFORMATION | MB_OK); #endif } void CHexEditApp::OnHelpWebForum() { // note: links to github discussions (as of 9 August 2021) ::BrowseWeb(IDS_WEB_FORUMS); } void CHexEditApp::OnHelpWebHome() { // note: links to github repo home (as of 9 August 2021) ::BrowseWeb(IDS_WEB_ADDRESS); } void CHexEditApp::OnUpdateHelpWeb(CCmdUI* pCmdUI) { // TODO: online help. BOOL enabled = pCmdUI->m_nID != ID_HELP_WEB; pCmdUI->Enable(enabled); } // App command to run the dialog void CHexEditApp::OnAppAbout() { CAbout aboutDlg; aboutDlg.DoModal(); } void CHexEditApp::UpdateAllViews() { POSITION posn = m_pDocTemplate->GetFirstDocPosition(); while (posn != NULL) { CHexEditDoc *pdoc = dynamic_cast<CHexEditDoc *>(m_pDocTemplate->GetNextDoc(posn)); ASSERT(pdoc != NULL); pdoc->UpdateAllViews(NULL); } } #ifdef FILE_PREVIEW // Startup point of the background thread that cleans up preview thumbnail files static UINT cleanup_func(LPVOID pParam) { CHexEditApp *pApp = (CHexEditApp *)pParam; return pApp->RunCleanupThread(); } // Called to start thumbnail cleanup void CHexEditApp::CleanupPreviewFiles() { thread_stop_ = false; cleanup_thread_ = AfxBeginThread(&cleanup_func, this, THREAD_PRIORITY_LOWEST); } // Handles thumbnail cleanup UINT CHexEditApp::RunCleanupThread() { // Wait for a little while to avoid any chance of slowing things while starting up for (int ii = 0; ii < 100; ++ii) { appdata_.Lock(); if (thread_stop_) { cleanup_thread_ = NULL; appdata_.Unlock(); return 0; } appdata_.Unlock(); Sleep(1000); } CString preview_folder; if (::GetDataPath(preview_folder)) { // Get directory used for preview thumbnails preview_folder += DIRNAME_PREVIEW; // Work out the cut-off date for which files modified before that time are deleted SYSTEMTIME now; GetSystemTime(&now); COleDateTime dtCut(now); dtCut -= COleDateTimeSpan(cleanup_days_, 0, 0, 0); // Get all the names of all the files with modification times before the cut-off time std::vector<CString> fileNames; CFileFind ff; BOOL bContinue = ff.FindFile(preview_folder + "HE*.*"); while (bContinue) { bContinue = ff.FindNextFile(); // Work out the modification time of this file as a COleDateTime FILETIME ft; SYSTEMTIME st; VERIFY(ff.GetLastWriteTime(&ft)); FileTimeToSystemTime(&ft, &st); COleDateTime dtFile(st); // If the time is before the cut-off remember this file name for deletion if (dtFile < dtCut) fileNames.push_back(ff.GetFilePath()); // Check if we have been told to terminate appdata_.Lock(); if (thread_stop_) { cleanup_thread_ = NULL; appdata_.Unlock(); return 0; } appdata_.Unlock(); } // Now delete all the files for (std::vector<CString>::const_iterator pfn = fileNames.begin(); pfn != fileNames.end(); ++pfn) ::DeleteFile(*pfn); } appdata_.Lock(); cleanup_thread_ = NULL; appdata_.Unlock(); return 0; } #endif // FILE_PREVIEW #if _MFC_VER >= 0x0A00 // Only needed for Win7 jump lists which are only supported in MFC 10 // RegisterExtensions is used to register file extensions so that the type of files can be opened // in HexEdit (ie HexEdit appears on the "Open With" Explorer menu). // Since this requires admin privileges as separate program (RegHelper.exe) is fired up while // using the ShellExecute() verb "runas". The parameter takes one or more file extensions, // separated by vertical bars (|), for example ".jpg|.jpeg". bool CHexEditApp::RegisterExtensions(LPCTSTR extensions) { CString strCmdLine; CString strExeFullName; AfxGetModuleFileName(0, strExeFullName); strCmdLine.Format("EXT \"%s\" \"%s\" \"HexEdit file\" \"%s\" \"%s\"", strExeFullName, ProgID, m_pszAppID, extensions); return CallRegHelper(strCmdLine); } #endif //_MFC_VER >= 0x0A00 bool CHexEditApp::RegisterOpenAll() { CString strCmdLine; //CString FullName; //AfxGetModuleFileName(0, FullName); TCHAR FullName[MAX_PATH]; ::GetModuleFileName(0, FullName, sizeof(FullName)); strCmdLine.Format("REGALL \"%s\" \"%s\" \"%s\" \"Open with HexEdit\"", FullName, HexEditSubKey, HexEditSubSubKey); return CallRegHelper(strCmdLine); } bool CHexEditApp::UnregisterOpenAll() { CString strCmdLine; strCmdLine.Format("UNREGALL \"%s\" \"%s\"", HexEditSubKey, HexEditSubSubKey); return CallRegHelper(strCmdLine); } bool CHexEditApp::CallRegHelper(LPCTSTR cmdLine) { CString strRegHelperFullName = GetExePath() + RegHelper; SHELLEXECUTEINFO shex; memset( &shex, 0, sizeof( shex) ); shex.cbSize = sizeof( SHELLEXECUTEINFO ); shex.fMask = 0; shex.hwnd = AfxGetMainWnd()->GetSafeHwnd(); shex.lpVerb = _T("runas"); shex.lpFile = strRegHelperFullName; shex.lpParameters = cmdLine; shex.lpDirectory = _T("."); shex.nShow = SW_NORMAL; if (!::ShellExecuteEx( &shex )) { TaskMessageBox("Modifying Registry Settings (All Users)", "There was an error running:\n\n" + CString(RegHelper) + "\n\nfrom the folder:\n\n" + GetExePath()); return false; } return true; } ///////////////////////////////////////////////////////////////////////////// // CCommandLineParser member functions void CCommandLineParser::ParseParam(const TCHAR* pszParam, BOOL bFlag, BOOL bLast) { if (non_std) { if (bFlag) { // If there are any flags set then assume this is a standard command line non_std = FALSE; } else { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); ASSERT(aa->open_current_readonly_ == -1); ASSERT(aa->open_current_shared_ == -1); if (aa->hwnd_1st_ != (HWND)0 && aa->one_only_) { // Get full path name as other instance may have different current directory char fullname[_MAX_PATH]; AfxFullPath(fullname, pszParam); ATOM atom = ::GlobalAddAtom(fullname); ASSERT(atom != 0); if (atom == 0) return; DWORD dw = 0; ::SendMessageTimeout(aa->hwnd_1st_, aa->wm_hexedit, 0, (LPARAM)atom, SMTO_ABORTIFHUNG, 2000, &dw); ::GlobalDeleteAtom(atom); return; } else if (aa->OpenDocumentFile(pszParam)) { m_nShellCommand = FileNothing; // file already opened so no shell command required return; } } } // Do standard command line processing using base class CCommandLineInfo::ParseParam(pszParam, bFlag, bLast); } ///////////////////////////////////////////////////////////////////////////// // Global functions // Return a ptr to the active view or NULL if none // Ie, the current hex view if it is the active view OR // the hex view associated with the active view if it is an aerial/template/compare view. CHexEditView *GetView() { if (theApp.pv_ != NULL) { ASSERT(theApp.playing_ > 0); if (!IsWindow(theApp.pv_->m_hWnd) || !theApp.pv_->IsKindOf(RUNTIME_CLASS(CHexEditView))) return NULL; else return theApp.pv_; } CMainFrame *mm = (CMainFrame *)AfxGetMainWnd(); if (mm != NULL) { CMDIChildWnd *pwind = mm->MDIGetActive(); // Ignore if there are no views open if (pwind != NULL) { // CHexEditView *pv = dynamic_cast<CHexEditView *>(pwind->GetActiveView()); CView *pv = pwind->GetActiveView(); if (pv != NULL) // May be NULL if print preview { if (pv->IsKindOf(RUNTIME_CLASS(CHexEditView))) return (CHexEditView *)pv; else if (pv->IsKindOf(RUNTIME_CLASS(CDataFormatView))) return ((CDataFormatView *)pv)->phev_; else if (pv->IsKindOf(RUNTIME_CLASS(CAerialView))) return ((CAerialView *)pv)->phev_; else if (pv->IsKindOf(RUNTIME_CLASS(CCompareView))) return ((CCompareView *)pv)->phev_; else if (pv->IsKindOf(RUNTIME_CLASS(CPrevwView))) return ((CPrevwView *)pv)->phev_; else if (pv->IsKindOf(RUNTIME_CLASS(CHexTabView))) { // Find the hex view (left-most tab) CHexTabView *ptv = (CHexTabView *)pv; ptv->SetActiveView(0); // hex view is always left-most (index 0) ASSERT_KINDOF(CHexEditView, ptv->GetActiveView()); return (CHexEditView *)ptv->GetActiveView(); } } } } return NULL; } COLORREF BestDecAddrCol() { CHexEditView *pv = GetView(); if (pv == NULL) return theApp.scheme_[0].dec_addr_col_; else return pv->GetDecAddrCol(); } COLORREF BestHexAddrCol() { CHexEditView *pv = GetView(); if (pv == NULL) return theApp.scheme_[0].hex_addr_col_; else return pv->GetHexAddrCol(); } COLORREF BestSearchCol() { CHexEditView *pv = GetView(); if (pv == NULL) return theApp.scheme_[0].search_col_; else return pv->GetSearchCol(); }
35.809745
151
0.681898
[ "object", "vector" ]
29a114d6cc27b04367b1b388944fc17c666ac91a
49,095
cpp
C++
Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp
egecetin/PcapPlusPlus
5dd6cec932e5dee2d040206c4b17c63994940ed8
[ "Unlicense" ]
null
null
null
Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp
egecetin/PcapPlusPlus
5dd6cec932e5dee2d040206c4b17c63994940ed8
[ "Unlicense" ]
null
null
null
Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp
egecetin/PcapPlusPlus
5dd6cec932e5dee2d040206c4b17c63994940ed8
[ "Unlicense" ]
null
null
null
#include "../TestDefinition.h" #include "../Common/TestUtils.h" #include <sstream> #include <fstream> #include <algorithm> #include "EndianPortable.h" #include "SystemUtils.h" #include "TcpReassembly.h" #include "IPv4Layer.h" #include "TcpLayer.h" #include "PayloadLayer.h" #include "PcapFileDevice.h" // ~~~~~~~~~~~~~~~~~~ // TcpReassemblyStats // ~~~~~~~~~~~~~~~~~~ struct TcpReassemblyStats { std::string reassembledData; int numOfDataPackets; int8_t curSide; int numOfMessagesFromSide[2]; bool connectionsStarted; bool connectionsEnded; bool connectionsEndedManually; size_t totalMissingBytes; pcpp::ConnectionData connData; TcpReassemblyStats() { clear(); } void clear() { reassembledData = ""; numOfDataPackets = 0; curSide = -1; numOfMessagesFromSide[0] = 0; numOfMessagesFromSide[1] = 0; connectionsStarted = false; connectionsEnded = false; connectionsEndedManually = false; totalMissingBytes = 0;} }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // TcpReassemblyMultipleConnStats // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ struct TcpReassemblyMultipleConnStats { typedef std::vector<uint32_t> FlowKeysList; typedef std::map<uint32_t, TcpReassemblyStats> Stats; Stats stats; FlowKeysList flowKeysList; std::vector<timeval>timestamps; void clear() { stats.clear(); flowKeysList.clear(); } }; // ~~~~~~~~~~~~~~~~~~~~ // readFileIntoString() // ~~~~~~~~~~~~~~~~~~~~ static std::string readFileIntoString(std::string fileName) { std::ifstream infile(fileName.c_str(), std::ios::binary); std::ostringstream ostrm; ostrm << infile.rdbuf(); std::string res = ostrm.str(); return res; } // ~~~~~~~~~~~~~~~~~~~~ // getPayloadLen() // ~~~~~~~~~~~~~~~~~~~~ static size_t getPayloadLen(pcpp::RawPacket& rawPacket) { pcpp::Packet packet(&rawPacket); pcpp::TcpLayer* tcpLayer = packet.getLayerOfType<pcpp::TcpLayer>(); if (tcpLayer == NULL) throw; pcpp::IPv4Layer* ipLayer = packet.getLayerOfType<pcpp::IPv4Layer>(); if (ipLayer == NULL) throw; return be16toh(ipLayer->getIPv4Header()->totalLength)-ipLayer->getHeaderLen()-tcpLayer->getHeaderLen(); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyMsgReadyCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static void tcpReassemblyMsgReadyCallback(int8_t sideIndex, const pcpp::TcpStreamData& tcpData, void* userCookie) { TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(tcpData.getConnectionData().flowKey); if (iter == stats.end()) { stats.insert(std::make_pair(tcpData.getConnectionData().flowKey, TcpReassemblyStats())); iter = stats.find(tcpData.getConnectionData().flowKey); } iter->second.totalMissingBytes += tcpData.getMissingByteCount(); if (sideIndex != iter->second.curSide) { iter->second.numOfMessagesFromSide[sideIndex]++; iter->second.curSide = sideIndex; } ((TcpReassemblyMultipleConnStats *)userCookie)->timestamps.push_back(tcpData.getTimeStamp()); iter->second.numOfDataPackets++; iter->second.reassembledData += std::string((char*)tcpData.getData(), tcpData.getDataLength()); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyConnectionStartCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static void tcpReassemblyConnectionStartCallback(const pcpp::ConnectionData& connectionData, void* userCookie) { TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(connectionData.flowKey); if (iter == stats.end()) { stats.insert(std::make_pair(connectionData.flowKey, TcpReassemblyStats())); iter = stats.find(connectionData.flowKey); } TcpReassemblyMultipleConnStats::FlowKeysList &flowKeys = ((TcpReassemblyMultipleConnStats *)userCookie)->flowKeysList; if(std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) flowKeys.push_back(connectionData.flowKey); iter->second.connectionsStarted = true; iter->second.connData = connectionData; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyConnectionEndCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static void tcpReassemblyConnectionEndCallback(const pcpp::ConnectionData& connectionData, pcpp::TcpReassembly::ConnectionEndReason reason, void* userCookie) { TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(connectionData.flowKey); if (iter == stats.end()) { stats.insert(std::make_pair(connectionData.flowKey, TcpReassemblyStats())); iter = stats.find(connectionData.flowKey); } TcpReassemblyMultipleConnStats::FlowKeysList &flowKeys = ((TcpReassemblyMultipleConnStats *)userCookie)->flowKeysList; if(std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) flowKeys.push_back(connectionData.flowKey); if (reason == pcpp::TcpReassembly::TcpReassemblyConnectionClosedManually) iter->second.connectionsEndedManually = true; else iter->second.connectionsEnded = true; } // ~~~~~~~~~~~~~~~~~~~ // tcpReassemblyTest() // ~~~~~~~~~~~~~~~~~~~ static bool tcpReassemblyTest(std::vector<pcpp::RawPacket>& packetStream, TcpReassemblyMultipleConnStats& results, bool monitorOpenCloseConns, bool closeConnsManually) { pcpp::TcpReassembly* tcpReassembly = NULL; if (monitorOpenCloseConns) tcpReassembly = new pcpp::TcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback); else tcpReassembly = new pcpp::TcpReassembly(tcpReassemblyMsgReadyCallback, &results); for (std::vector<pcpp::RawPacket>::iterator iter = packetStream.begin(); iter != packetStream.end(); iter++) { pcpp::Packet packet(&(*iter)); tcpReassembly->reassemblePacket(packet); } //for(TcpReassemblyMultipleConnStats::Stats::iterator iter = results.stats.begin(); iter != results.stats.end(); iter++) //{ // // replace \r\n with \n // size_t index = 0; // while (true) // { // index = iter->second.reassembledData.find("\r\n", index); // if (index == string::npos) break; // iter->second.reassembledData.replace(index, 2, "\n"); // index += 1; // } //} if (closeConnsManually) tcpReassembly->closeAllConnections(); delete tcpReassembly; return true; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyAddRetransmissions() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static pcpp::RawPacket tcpReassemblyAddRetransmissions(pcpp::RawPacket rawPacket, int beginning, int numOfBytes) { pcpp::Packet packet(&rawPacket); pcpp::TcpLayer* tcpLayer = packet.getLayerOfType<pcpp::TcpLayer>(); if (tcpLayer == NULL) throw; pcpp::IPv4Layer* ipLayer = packet.getLayerOfType<pcpp::IPv4Layer>(); if (ipLayer == NULL) throw; int tcpPayloadSize = be16toh(ipLayer->getIPv4Header()->totalLength)-ipLayer->getHeaderLen()-tcpLayer->getHeaderLen(); if (numOfBytes <= 0) numOfBytes = tcpPayloadSize-beginning; uint8_t* newPayload = new uint8_t[numOfBytes]; if (beginning + numOfBytes <= tcpPayloadSize) { memcpy(newPayload, tcpLayer->getLayerPayload()+beginning, numOfBytes); } else { int bytesToCopy = tcpPayloadSize-beginning; memcpy(newPayload, tcpLayer->getLayerPayload()+beginning, bytesToCopy); for (int i = bytesToCopy; i < numOfBytes; i++) { newPayload[i] = '*'; } } pcpp::Layer* layerToRemove = tcpLayer->getNextLayer(); if (layerToRemove != NULL) packet.removeLayer(layerToRemove->getProtocol()); tcpLayer->getTcpHeader()->sequenceNumber = htobe32(be32toh(tcpLayer->getTcpHeader()->sequenceNumber) + beginning); pcpp::PayloadLayer newPayloadLayer(newPayload, numOfBytes, false); packet.addLayer(&newPayloadLayer); packet.computeCalculateFields(); delete [] newPayload; return *(packet.getRawPacket()); } // ~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~ // Test Cases start here // ~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~ PTF_TEST_CASE(TestTcpReassemblySanity) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); PTF_ASSERT_TRUE(stats.begin()->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(stats.begin()->second.connData.dstIP.isValid()); pcpp::IPv4Address expectedSrcIP(std::string("10.0.0.1")); pcpp::IPv4Address expectedDstIP(std::string("81.218.72.15")); PTF_ASSERT_EQUAL(stats.begin()->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.dstIP, expectedDstIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1491516383); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 915793); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblySanity PTF_TEST_CASE(TestTcpReassemblyRetran) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // retransmission includes exact same data pcpp::RawPacket retPacket1 = tcpReassemblyAddRetransmissions(packetStream.at(4), 0, 0); // retransmission includes 10 bytes less than original data (missing bytes are from the beginning) pcpp::RawPacket retPacket2 = tcpReassemblyAddRetransmissions(packetStream.at(10), 10, 0); // retransmission includes 20 bytes less than original data (missing bytes are from the end) pcpp::RawPacket retPacket3 = tcpReassemblyAddRetransmissions(packetStream.at(13), 0, 1340); // retransmission includes 10 bytes more than original data (original data + 10 bytes) pcpp::RawPacket retPacket4 = tcpReassemblyAddRetransmissions(packetStream.at(21), 0, 1430); // retransmission includes 10 bytes less in the beginning and 20 bytes more at the end pcpp::RawPacket retPacket5 = tcpReassemblyAddRetransmissions(packetStream.at(28), 10, 1370); // retransmission includes 10 bytes less in the beginning and 15 bytes less at the end pcpp::RawPacket retPacket6 = tcpReassemblyAddRetransmissions(packetStream.at(34), 10, 91); packetStream.insert(packetStream.begin() + 5, retPacket1); packetStream.insert(packetStream.begin() + 12, retPacket2); packetStream.insert(packetStream.begin() + 16, retPacket3); packetStream.insert(packetStream.begin() + 25, retPacket4); packetStream.insert(packetStream.begin() + 33, retPacket5); packetStream.insert(packetStream.begin() + 40, retPacket6); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, false, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 21); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_retransmission_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyRetran PTF_TEST_CASE(TestTcpReassemblyMissingData) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); size_t expectedLoss = 0; // remove 20 bytes from the beginning pcpp::RawPacket missPacket1 = tcpReassemblyAddRetransmissions(packetStream.at(3), 20, 0); packetStream.insert(packetStream.begin() + 4, missPacket1); packetStream.erase(packetStream.begin() + 3); expectedLoss += 20; // remove 30 bytes from the end pcpp::RawPacket missPacket2 = tcpReassemblyAddRetransmissions(packetStream.at(20), 0, 1390); packetStream.insert(packetStream.begin() + 21, missPacket2); packetStream.erase(packetStream.begin() + 20); expectedLoss += 30; // remove whole packets expectedLoss += getPayloadLen(*(packetStream.begin() + 28)); expectedLoss += getPayloadLen(*(packetStream.begin() + 30)); packetStream.erase(packetStream.begin() + 28); packetStream.erase(packetStream.begin() + 30); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, false, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.begin()->second.totalMissingBytes, expectedLoss); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 17); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_missing_data_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); // test flow without SYN packet PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // remove SYN and SYN/ACK packets packetStream.erase(packetStream.begin()); packetStream.erase(packetStream.begin()); tcpReassemblyTest(packetStream, tcpReassemblyResults, false, true); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyMissingData PTF_TEST_CASE(TestTcpReassemblyOutOfOrder) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // swap 2 consequent packets std::swap(packetStream[9], packetStream[10]); // swap 2 non-consequent packets pcpp::RawPacket oooPacket1 = packetStream[18]; packetStream.erase(packetStream.begin() + 18); packetStream.insert(packetStream.begin() + 23, oooPacket1); // reverse order of all packets in message for (int i = 0; i < 12; i++) { pcpp::RawPacket oooPacketTemp = packetStream[35]; packetStream.erase(packetStream.begin() + 35); packetStream.insert(packetStream.begin() + 24 + i, oooPacketTemp); } TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_out_of_order_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); // test out-of-order + missing data PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // reverse order of all packets in message for (int i = 0; i < 12; i++) { pcpp::RawPacket oooPacketTemp = packetStream[35]; packetStream.erase(packetStream.begin() + 35); packetStream.insert(packetStream.begin() + 24 + i, oooPacketTemp); } // remove one packet packetStream.erase(packetStream.begin() + 29); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 18); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_missing_data_output_ooo.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyOutOfOrder PTF_TEST_CASE(TestTcpReassemblyWithFIN_RST) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; TcpReassemblyMultipleConnStats tcpReassemblyResults; std::string expectedReassemblyData; // test fin packet in end of connection PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin.pcap", packetStream, errMsg)); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 5); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEnded); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); // test rst packet in end of connection PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_rst.pcap", packetStream, errMsg)); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEnded); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_rst_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); //test fin packet in end of connection that has also data PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin2.pcap", packetStream, errMsg)); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 6); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEnded); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin2_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); // test missing data before fin PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin2.pcap", packetStream, errMsg)); // move second packet of server->client message to the end of the message (after FIN) pcpp::RawPacket oooPacketTemp = packetStream[6]; packetStream.erase(packetStream.begin() + 6); packetStream.insert(packetStream.begin() + 12, oooPacketTemp); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 5); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEnded); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin2_output2.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyWithFIN_RST PTF_TEST_CASE(TestTcpReassemblyMalformedPkts) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; TcpReassemblyMultipleConnStats tcpReassemblyResults; std::string expectedReassemblyData; // test retransmission with new data but payload doesn't really contain all the new data PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin2.pcap", packetStream, errMsg)); // take one of the packets and increase the IPv4 total length field pcpp::Packet malPacket(&packetStream.at(8)); pcpp::IPv4Layer* ipLayer = malPacket.getLayerOfType<pcpp::IPv4Layer>(); PTF_ASSERT_NOT_NULL(ipLayer); ipLayer->getIPv4Header()->totalLength = be16toh(htobe16(ipLayer->getIPv4Header()->totalLength) + 40); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 6); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEnded); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin2_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyMalformedPkts PTF_TEST_CASE(TestTcpReassemblyMultipleConns) { TcpReassemblyMultipleConnStats results; std::string errMsg; std::string expectedReassemblyData; pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback); std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/three_http_streams.pcap", packetStream, errMsg)); pcpp::RawPacket finPacket1 = packetStream.at(13); pcpp::RawPacket finPacket2 = packetStream.at(15); packetStream.erase(packetStream.begin() + 13); packetStream.erase(packetStream.begin() + 14); pcpp::TcpReassembly::ReassemblyStatus expectedStatuses[26] = { pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::FIN_RSTWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::FIN_RSTWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::FIN_RSTWithNoData, pcpp::TcpReassembly::FIN_RSTWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, }; int statusIndex = 0; for (std::vector<pcpp::RawPacket>::iterator iter = packetStream.begin(); iter != packetStream.end(); iter++) { pcpp::Packet packet(&(*iter)); pcpp::TcpReassembly::ReassemblyStatus status = tcpReassembly.reassemblePacket(packet); PTF_ASSERT_EQUAL(status, expectedStatuses[statusIndex++], enum); } TcpReassemblyMultipleConnStats::Stats &stats = results.stats; PTF_ASSERT_EQUAL(stats.size(), 3); PTF_ASSERT_EQUAL(results.flowKeysList.size(), 3); TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.begin(); PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 2); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_TRUE(iter->second.connectionsEnded); PTF_ASSERT_FALSE(iter->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/three_http_streams_conn_1_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); iter++; PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 2); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_TRUE(iter->second.connectionsEnded); PTF_ASSERT_FALSE(iter->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/three_http_streams_conn_2_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); iter++; PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 2); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_FALSE(iter->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/three_http_streams_conn_3_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); // test getConnectionInformation and isConnectionOpen const pcpp::TcpReassembly::ConnectionInfoList &managedConnections = tcpReassembly.getConnectionInformation(); PTF_ASSERT_EQUAL(managedConnections.size(), 3); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections.find(results.flowKeysList[0]); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections.find(results.flowKeysList[1]); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = managedConnections.find(results.flowKeysList[2]); PTF_ASSERT_NOT_EQUAL(iterConn1, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn2, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn3, managedConnections.end(), object_no_str); PTF_ASSERT_GREATER_THAN(tcpReassembly.isConnectionOpen(iterConn1->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), 0); //test Connection Information data pcpp::IPv4Address expectedSrcIP("172.16.133.132"); pcpp::IPv4Address expectedDstIP("98.139.161.29"); PTF_ASSERT_EQUAL(iterConn1->second.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(iterConn1->second.dstIP, expectedDstIP); PTF_ASSERT_EQUAL(iterConn1->second.srcPort, 54615); PTF_ASSERT_EQUAL(iterConn1->second.dstPort, 80); PTF_ASSERT_EQUAL(iterConn1->second.flowKey, results.flowKeysList[0]); PTF_ASSERT_EQUAL(iterConn1->second.startTime.tv_sec, 1361916156); PTF_ASSERT_EQUAL(iterConn1->second.startTime.tv_usec, 677488); PTF_ASSERT_EQUAL(iterConn1->second.endTime.tv_sec, 1361916156); PTF_ASSERT_EQUAL(iterConn1->second.endTime.tv_usec, 766111); // test the return of invalid connection flowKey pcpp::ConnectionData dummyConn; dummyConn.flowKey = 0x12345678; PTF_ASSERT_LOWER_THAN(tcpReassembly.isConnectionOpen(dummyConn), 0); // close flow manually and verify it's closed tcpReassembly.closeConnection(iter->first); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); // now send FIN packets of conn 3 and verify they are ignored pcpp::TcpReassembly::ReassemblyStatus status = tcpReassembly.reassemblePacket(&finPacket1); PTF_ASSERT_EQUAL(status, pcpp::TcpReassembly::Ignore_PacketOfClosedFlow, enum); status = tcpReassembly.reassemblePacket(&finPacket2); PTF_ASSERT_EQUAL(status, pcpp::TcpReassembly::Ignore_PacketOfClosedFlow, enum); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); } // TestTcpReassemblyMultipleConns PTF_TEST_CASE(TestTcpReassemblyIPv6) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_ipv6_http_stream.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 10); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 3); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 3); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); PTF_ASSERT_TRUE(stats.begin()->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(stats.begin()->second.connData.dstIP.isValid()); pcpp::IPv6Address expectedSrcIP("2001:618:400::5199:cc70"); pcpp::IPv6Address expectedDstIP("2001:618:1:8000::5"); PTF_ASSERT_EQUAL(stats.begin()->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.dstIP, expectedDstIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551796); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 702602); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyIPv6 PTF_TEST_CASE(TestTcpReassemblyIPv6MultConns) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; std::string expectedReassemblyData; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/four_ipv6_http_streams.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 4); TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.begin(); pcpp::IPv6Address expectedSrcIP("2001:618:400::5199:cc70"); pcpp::IPv6Address expectedDstIP1("2001:618:1:8000::5"); pcpp::IPv6Address expectedDstIP2("2001:638:902:1:202:b3ff:feee:5dc2"); PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 14); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 3); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 3); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); PTF_ASSERT_TRUE(iter->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(iter->second.connData.dstIP.isValid()); PTF_ASSERT_EQUAL(iter->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(iter->second.connData.dstIP, expectedDstIP1); PTF_ASSERT_EQUAL(iter->second.connData.srcPort, 35995); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551795); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 526632); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream4.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); iter++; PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 10); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); PTF_ASSERT_TRUE(iter->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(iter->second.connData.dstIP.isValid()); PTF_ASSERT_EQUAL(iter->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(iter->second.connData.dstIP, expectedDstIP1); PTF_ASSERT_EQUAL(iter->second.connData.srcPort, 35999); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551795); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 526632); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); iter++; PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 2); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 1); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 1); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); PTF_ASSERT_TRUE(iter->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(iter->second.connData.dstIP.isValid()); PTF_ASSERT_EQUAL(iter->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(iter->second.connData.dstIP, expectedDstIP2); PTF_ASSERT_EQUAL(iter->second.connData.srcPort, 40426); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551795); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 526632); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream3.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); iter++; PTF_ASSERT_EQUAL(iter->second.numOfDataPackets, 13); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[0], 4); PTF_ASSERT_EQUAL(iter->second.numOfMessagesFromSide[1], 4); PTF_ASSERT_TRUE(iter->second.connectionsStarted); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); PTF_ASSERT_TRUE(iter->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(iter->second.connData.dstIP.isValid()); PTF_ASSERT_EQUAL(iter->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(iter->second.connData.dstIP, expectedDstIP1); PTF_ASSERT_EQUAL(iter->second.connData.srcPort, 35997); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551795); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 526632); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream2.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); } // TestTcpReassemblyIPv6MultConns PTF_TEST_CASE(TestTcpReassemblyIPv6_OOO) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_ipv6_http_stream.pcap", packetStream, errMsg)); // swap 2 non-consequent packets pcpp::RawPacket oooPacket1 = packetStream[10]; packetStream.erase(packetStream.begin() + 10); packetStream.insert(packetStream.begin() + 12, oooPacket1); // swap additional 2 non-consequent packets oooPacket1 = packetStream[15]; packetStream.erase(packetStream.begin() + 15); packetStream.insert(packetStream.begin() + 17, oooPacket1); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 10); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 3); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 3); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); PTF_ASSERT_TRUE(stats.begin()->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(stats.begin()->second.connData.dstIP.isValid()); pcpp::IPv6Address expectedSrcIP("2001:618:400::5199:cc70"); pcpp::IPv6Address expectedDstIP("2001:618:1:8000::5"); PTF_ASSERT_EQUAL(stats.begin()->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.dstIP, expectedDstIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1147551796); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 702602); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } // TestTcpReassemblyIPv6_OOO PTF_TEST_CASE(TestTcpReassemblyCleanup) { TcpReassemblyMultipleConnStats results; std::string errMsg; pcpp::TcpReassemblyConfiguration config(true, 2, 1); pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config); std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/three_http_streams.pcap", packetStream, errMsg)); pcpp::RawPacket lastPacket = packetStream.back(); packetStream.pop_back(); for(std::vector<pcpp::RawPacket>::iterator iter = packetStream.begin(); iter != packetStream.end(); iter++) { pcpp::Packet packet(&(*iter)); tcpReassembly.reassemblePacket(packet); } pcpp::TcpReassembly::ConnectionInfoList managedConnections = tcpReassembly.getConnectionInformation(); // make a copy of list PTF_ASSERT_EQUAL(managedConnections.size(), 3); PTF_ASSERT_EQUAL(results.flowKeysList.size(), 3); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections.find(results.flowKeysList[0]); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections.find(results.flowKeysList[1]); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = managedConnections.find(results.flowKeysList[2]); PTF_ASSERT_NOT_EQUAL(iterConn1, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn2, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn3, managedConnections.end(), object_no_str); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn1->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), 0); pcpp::multiPlatformSleep(3); tcpReassembly.reassemblePacket(&lastPacket); // automatic cleanup of 1 item PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 2); tcpReassembly.purgeClosedConnections(); // manually initiated cleanup of 1 item PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 1); tcpReassembly.purgeClosedConnections(0xFFFFFFFF); // manually initiated cleanup of all items PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 0); const TcpReassemblyMultipleConnStats::FlowKeysList& flowKeys = results.flowKeysList; iterConn1 = managedConnections.find(flowKeys[0]); iterConn2 = managedConnections.find(flowKeys[1]); iterConn3 = managedConnections.find(flowKeys[2]); PTF_ASSERT_NOT_EQUAL(iterConn1, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn2, managedConnections.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn3, managedConnections.end(), object_no_str); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn1->second), -1); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), -1); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), -1); } // TestTcpReassemblyCleanup PTF_TEST_CASE(TestTcpReassemblyMaxOOOFrags) { TcpReassemblyMultipleConnStats results1; TcpReassemblyMultipleConnStats results2; std::string errMsg; pcpp::TcpReassemblyConfiguration config1(true, 5, 30); pcpp::TcpReassemblyConfiguration config2(true, 5, 30, 5); // the fourth argument is the max allowed out-of-order fragments, so we only allow 5 pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config1); pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config2); std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); for(std::vector<pcpp::RawPacket>::iterator iter = packetStream.begin(); iter != packetStream.end(); iter++) { pcpp::Packet packet(&(*iter)); tcpReassembly1.reassemblePacket(packet); tcpReassembly2.reassemblePacket(packet); } pcpp::TcpReassembly::ConnectionInfoList managedConnections1 = tcpReassembly1.getConnectionInformation(); pcpp::TcpReassembly::ConnectionInfoList managedConnections2 = tcpReassembly2.getConnectionInformation(); // make a copy of list PTF_ASSERT_EQUAL(managedConnections1.size(), 1); PTF_ASSERT_EQUAL(managedConnections2.size(), 1); PTF_ASSERT_EQUAL(results1.flowKeysList.size(), 1); PTF_ASSERT_EQUAL(results2.flowKeysList.size(), 1); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections1.find(results1.flowKeysList[0]); pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections2.find(results2.flowKeysList[0]); PTF_ASSERT_NOT_EQUAL(iterConn1, managedConnections1.end(), object_no_str); PTF_ASSERT_NOT_EQUAL(iterConn2, managedConnections2.end(), object_no_str); PTF_ASSERT_EQUAL(tcpReassembly1.isConnectionOpen(iterConn1->second), 1); PTF_ASSERT_EQUAL(tcpReassembly2.isConnectionOpen(iterConn2->second), 1); PTF_ASSERT_EQUAL(results1.stats.begin()->second.numOfDataPackets, 1); // The second data packet is incomplete so we stopped at one PTF_ASSERT_EQUAL(results2.stats.begin()->second.numOfDataPackets, 7); // We hit the fragment limit so skipped the missing fragment and continued to the end // Close the connections, forcing cleanup tcpReassembly1.closeAllConnections(); tcpReassembly2.closeAllConnections(); // Everything should be processed now PTF_ASSERT_EQUAL(results1.stats.begin()->second.numOfDataPackets, 7); PTF_ASSERT_EQUAL(results2.stats.begin()->second.numOfDataPackets, 7); } // TestTcpReassemblyCleanup PTF_TEST_CASE(TestTcpReassemblyMaxSeq) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream_max_seq.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); PTF_ASSERT_TRUE(stats.begin()->second.connectionsStarted); PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); PTF_ASSERT_TRUE(stats.begin()->second.connData.srcIP.isValid()); PTF_ASSERT_TRUE(stats.begin()->second.connData.dstIP.isValid()); pcpp::IPv4Address expectedSrcIP(std::string("10.0.0.1")); pcpp::IPv4Address expectedDstIP(std::string("81.218.72.15")); PTF_ASSERT_EQUAL(stats.begin()->second.connData.srcIP, expectedSrcIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.dstIP, expectedDstIP); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_sec, 1491516383); PTF_ASSERT_EQUAL(stats.begin()->second.connData.startTime.tv_usec, 915793); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_sec, 0); PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); } //TestTcpReassemblyMaxSeq PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBaseOutOfOrderBufferCleanupCondition { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; TcpReassemblyMultipleConnStats results1; TcpReassemblyMultipleConnStats results2; pcpp::TcpReassemblyConfiguration config1(true, 5, 30, 20, true); pcpp::TcpReassemblyConfiguration config2(true, 5, 30, 20, false); pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config1); pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config2); PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // unserting a data packet from reverse direction b/w swap 2 consequent data packets std::swap(packetStream[12], packetStream[13]); std::swap(packetStream[13], packetStream[18]); TcpReassemblyMultipleConnStats tcpReassemblyResults; for (std::vector<pcpp::RawPacket>::iterator iter = packetStream.begin(); iter != packetStream.end(); iter++) { pcpp::Packet packet(&(*iter)); tcpReassembly1.reassemblePacket(packet); tcpReassembly2.reassemblePacket(packet); } tcpReassembly1.closeAllConnections(); tcpReassembly2.closeAllConnections(); TcpReassemblyMultipleConnStats::Stats &stats1 = results1.stats; TcpReassemblyMultipleConnStats::Stats &stats2 = results2.stats; PTF_ASSERT_EQUAL(stats1.size(), 1); PTF_ASSERT_EQUAL(stats2.size(), 1); PTF_ASSERT_EQUAL(stats1.begin()->second.numOfDataPackets, 18); PTF_ASSERT_EQUAL(stats2.begin()->second.numOfDataPackets, 19); packetStream.clear(); tcpReassemblyResults.clear(); } // TestTcpReassemblyDisableOOOCleanup PTF_TEST_CASE(TestTcpReassemblyTimeStamps) { std::string errMsg; std::vector<pcpp::RawPacket> packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets,7); std::ifstream expectedOutput("PcapExamples/timestamp_output.txt"); for(long unsigned int i = 0;i<tcpReassemblyResults.timestamps.size();i++){ timeval t = tcpReassemblyResults.timestamps[i]; std::string expected; expectedOutput>>expected; //TODO: Change to atoll to stoll after switching to C++11 int expUsec = atoll(expected.c_str())%1000000; int expSec = atoll(expected.c_str())/1000000; PTF_ASSERT_EQUAL(t.tv_usec,expUsec); PTF_ASSERT_EQUAL(t.tv_sec, expSec); } expectedOutput.close(); packetStream.clear(); tcpReassemblyResults.clear(); } // TestTcpReassemblyTimeStamps
43.1036
245
0.78894
[ "vector" ]
29a82d56a5f889a4892fb33dd75435de24827520
27,446
cc
C++
third_party/blink/renderer/modules/service_worker/service_worker_container.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
third_party/blink/renderer/modules/service_worker/service_worker_container.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
third_party/blink/renderer/modules/service_worker/service_worker_container.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/modules/service_worker/service_worker_container.h" #include <memory> #include <utility> #include "base/macros.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom-blink.h" #include "third_party/blink/public/platform/web_fetch_client_settings_object.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/events/native_event_listener.h" #include "third_party/blink/renderer/core/events/message_event.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" #include "third_party/blink/renderer/core/frame/deprecation.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/messaging/blink_transferable_message.h" #include "third_party/blink/renderer/core/messaging/message_port.h" #include "third_party/blink/renderer/core/script/script.h" #include "third_party/blink/renderer/modules/event_target_modules.h" #include "third_party/blink/renderer/modules/service_worker/service_worker.h" #include "third_party/blink/renderer/modules/service_worker/service_worker_error.h" #include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h" #include "third_party/blink/renderer/platform/weborigin/reporting_disposition.h" #include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { namespace { void MaybeRecordThirdPartyServiceWorkerUsage( ExecutionContext* execution_context) { DCHECK(execution_context); // ServiceWorkerContainer is only supported on windows. LocalDOMWindow* window = To<LocalDOMWindow>(execution_context); DCHECK(window); if (window->IsCrossSiteSubframe()) UseCounter::Count(window, WebFeature::kThirdPartyServiceWorker); } bool HasFiredDomContentLoaded(const Document& document) { return !document.GetTiming().DomContentLoadedEventStart().is_null(); } mojom::ServiceWorkerUpdateViaCache ParseUpdateViaCache(const String& value) { if (value == "imports") return mojom::ServiceWorkerUpdateViaCache::kImports; if (value == "all") return mojom::ServiceWorkerUpdateViaCache::kAll; if (value == "none") return mojom::ServiceWorkerUpdateViaCache::kNone; // Default value. return mojom::ServiceWorkerUpdateViaCache::kImports; } class GetRegistrationCallback : public WebServiceWorkerProvider:: WebServiceWorkerGetRegistrationCallbacks { public: explicit GetRegistrationCallback(ScriptPromiseResolver* resolver) : resolver_(resolver) {} ~GetRegistrationCallback() override = default; void OnSuccess(WebServiceWorkerRegistrationObjectInfo info) override { if (!resolver_->GetExecutionContext() || resolver_->GetExecutionContext()->IsContextDestroyed()) return; if (info.registration_id == mojom::blink::kInvalidServiceWorkerRegistrationId) { // Resolve the promise with undefined. resolver_->Resolve(); return; } resolver_->Resolve( ServiceWorkerRegistration::Take(resolver_, std::move(info))); } void OnError(const WebServiceWorkerError& error) override { if (!resolver_->GetExecutionContext() || resolver_->GetExecutionContext()->IsContextDestroyed()) return; resolver_->Reject(ServiceWorkerError::Take(resolver_.Get(), error)); } private: Persistent<ScriptPromiseResolver> resolver_; DISALLOW_COPY_AND_ASSIGN(GetRegistrationCallback); }; } // namespace class ServiceWorkerContainer::DomContentLoadedListener final : public NativeEventListener { public: void Invoke(ExecutionContext* execution_context, Event* event) override { DCHECK_EQ(event->type(), "DOMContentLoaded"); LocalDOMWindow& window = *To<LocalDOMWindow>(execution_context); DCHECK(HasFiredDomContentLoaded(*window.document())); auto* container = Supplement<LocalDOMWindow>::From<ServiceWorkerContainer>(window); if (!container) { // There is no container for some reason, which means there's no message // queue to start. Just abort. return; } container->EnableClientMessageQueue(); } }; const char ServiceWorkerContainer::kSupplementName[] = "ServiceWorkerContainer"; ServiceWorkerContainer* ServiceWorkerContainer::From(LocalDOMWindow& window) { ServiceWorkerContainer* container = Supplement<LocalDOMWindow>::From<ServiceWorkerContainer>(window); if (!container) { // TODO(leonhsl): Figure out whether it's really necessary to create an // instance when there's no frame or frame client for |window|. container = MakeGarbageCollected<ServiceWorkerContainer>(window); Supplement<LocalDOMWindow>::ProvideTo(window, container); if (window.GetFrame() && window.GetFrame()->Client()) { std::unique_ptr<WebServiceWorkerProvider> provider = window.GetFrame()->Client()->CreateServiceWorkerProvider(); if (provider) { provider->SetClient(container); container->provider_ = std::move(provider); } } } return container; } ServiceWorkerContainer* ServiceWorkerContainer::CreateForTesting( LocalDOMWindow& window, std::unique_ptr<WebServiceWorkerProvider> provider) { ServiceWorkerContainer* container = MakeGarbageCollected<ServiceWorkerContainer>(window); container->provider_ = std::move(provider); return container; } ServiceWorkerContainer::~ServiceWorkerContainer() { DCHECK(!provider_); } void ServiceWorkerContainer::ContextDestroyed() { if (provider_) { provider_->SetClient(nullptr); provider_ = nullptr; } controller_ = nullptr; } void ServiceWorkerContainer::Trace(Visitor* visitor) const { visitor->Trace(controller_); visitor->Trace(ready_); visitor->Trace(dom_content_loaded_observer_); visitor->Trace(service_worker_registration_objects_); visitor->Trace(service_worker_objects_); EventTargetWithInlineData::Trace(visitor); Supplement<LocalDOMWindow>::Trace(visitor); ExecutionContextLifecycleObserver::Trace(visitor); } ScriptPromise ServiceWorkerContainer::registerServiceWorker( ScriptState* script_state, const String& url, const RegistrationOptions* options) { auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); // TODO(crbug.com/824647): Remove this check after module loading for // ServiceWorker is enabled by default. if (options->type() == "module" && !RuntimeEnabledFeatures::ModuleServiceWorkerEnabled()) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kNotSupportedError, "type 'module' in RegistrationOptions is not implemented yet." "See https://crbug.com/824647 for details.")); return promise; } auto callbacks = std::make_unique<CallbackPromiseAdapter< ServiceWorkerRegistration, ServiceWorkerErrorForUpdate>>(resolver); ExecutionContext* execution_context = ExecutionContext::From(script_state); MaybeRecordThirdPartyServiceWorkerUsage(execution_context); // The IDL definition is expected to restrict service worker to secure // contexts. CHECK(execution_context->IsSecureContext()); scoped_refptr<const SecurityOrigin> document_origin = execution_context->GetSecurityOrigin(); KURL page_url = KURL(NullURL(), document_origin->ToString()); if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( page_url.Protocol())) { callbacks->OnError(WebServiceWorkerError( mojom::blink::ServiceWorkerErrorType::kType, String("Failed to register a ServiceWorker: The URL protocol of the " "current origin ('" + document_origin->ToString() + "') is not supported."))); return promise; } KURL script_url = execution_context->CompleteURL(url); script_url.RemoveFragmentIdentifier(); if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( script_url.Protocol())) { callbacks->OnError(WebServiceWorkerError( mojom::blink::ServiceWorkerErrorType::kType, String("Failed to register a ServiceWorker: The URL protocol of the " "script ('" + script_url.GetString() + "') is not supported."))); return promise; } if (!document_origin->CanRequest(script_url)) { scoped_refptr<const SecurityOrigin> script_origin = SecurityOrigin::Create(script_url); callbacks->OnError( WebServiceWorkerError(mojom::blink::ServiceWorkerErrorType::kSecurity, String("Failed to register a ServiceWorker: The " "origin of the provided scriptURL ('" + script_origin->ToString() + "') does not match the current origin ('" + document_origin->ToString() + "')."))); return promise; } KURL scope_url; if (options->hasScope()) scope_url = execution_context->CompleteURL(options->scope()); else scope_url = KURL(script_url, "./"); scope_url.RemoveFragmentIdentifier(); if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( scope_url.Protocol())) { callbacks->OnError(WebServiceWorkerError( mojom::blink::ServiceWorkerErrorType::kType, String("Failed to register a ServiceWorker: The URL protocol of the " "scope ('" + scope_url.GetString() + "') is not supported."))); return promise; } if (!document_origin->CanRequest(scope_url)) { scoped_refptr<const SecurityOrigin> scope_origin = SecurityOrigin::Create(scope_url); callbacks->OnError( WebServiceWorkerError(mojom::blink::ServiceWorkerErrorType::kSecurity, String("Failed to register a ServiceWorker: The " "origin of the provided scope ('" + scope_origin->ToString() + "') does not match the current origin ('" + document_origin->ToString() + "')."))); return promise; } if (!provider_) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError, "Failed to register a ServiceWorker: " "The document is in an invalid " "state.")); return promise; } WebString web_error_message; if (!provider_->ValidateScopeAndScriptURL(scope_url, script_url, &web_error_message)) { callbacks->OnError(WebServiceWorkerError( mojom::blink::ServiceWorkerErrorType::kType, WebString::FromUTF8("Failed to register a ServiceWorker: " + web_error_message.Utf8()))); return promise; } ContentSecurityPolicy* csp = execution_context->GetContentSecurityPolicy(); if (csp) { if (!csp->AllowWorkerContextFromSource(script_url)) { callbacks->OnError(WebServiceWorkerError( mojom::blink::ServiceWorkerErrorType::kSecurity, String( "Failed to register a ServiceWorker: The provided scriptURL ('" + script_url.GetString() + "') violates the Content Security Policy."))); return promise; } } mojom::ServiceWorkerUpdateViaCache update_via_cache = ParseUpdateViaCache(options->updateViaCache()); absl::optional<mojom::blink::ScriptType> script_type = Script::ParseScriptType(options->type()); DCHECK(script_type); WebFetchClientSettingsObject fetch_client_settings_object( execution_context->Fetcher() ->GetProperties() .GetFetchClientSettingsObject()); provider_->RegisterServiceWorker( scope_url, script_url, *script_type, update_via_cache, std::move(fetch_client_settings_object), std::move(callbacks)); return promise; } ScriptPromise ServiceWorkerContainer::getRegistration( ScriptState* script_state, const String& document_url) { auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); ExecutionContext* execution_context = ExecutionContext::From(script_state); // The IDL definition is expected to restrict service worker to secure // contexts. CHECK(execution_context->IsSecureContext()); scoped_refptr<const SecurityOrigin> document_origin = execution_context->GetSecurityOrigin(); KURL page_url = KURL(NullURL(), document_origin->ToString()); if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( page_url.Protocol())) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Failed to get a ServiceWorkerRegistration: The URL protocol of the " "current origin ('" + document_origin->ToString() + "') is not supported.")); return promise; } KURL completed_url = execution_context->CompleteURL(document_url); completed_url.RemoveFragmentIdentifier(); if (!document_origin->CanRequest(completed_url)) { scoped_refptr<const SecurityOrigin> document_url_origin = SecurityOrigin::Create(completed_url); resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Failed to get a ServiceWorkerRegistration: The " "origin of the provided documentURL ('" + document_url_origin->ToString() + "') does not match the current origin ('" + document_origin->ToString() + "').")); return promise; } if (!provider_) { resolver->Reject( MakeGarbageCollected<DOMException>(DOMExceptionCode::kInvalidStateError, "Failed to get a " "ServiceWorkerRegistration: The " "document is in an invalid state.")); return promise; } provider_->GetRegistration( completed_url, std::make_unique<GetRegistrationCallback>(resolver)); return promise; } ScriptPromise ServiceWorkerContainer::getRegistrations( ScriptState* script_state) { auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); if (!provider_) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kInvalidStateError, "Failed to get ServiceWorkerRegistration objects: " "The document is in an invalid state.")); return promise; } ExecutionContext* execution_context = ExecutionContext::From(script_state); // The IDL definition is expected to restrict service worker to secure // contexts. CHECK(execution_context->IsSecureContext()); scoped_refptr<const SecurityOrigin> document_origin = execution_context->GetSecurityOrigin(); KURL page_url = KURL(NullURL(), document_origin->ToString()); if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( page_url.Protocol())) { resolver->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Failed to get ServiceWorkerRegistration objects: The URL protocol of " "the current origin ('" + document_origin->ToString() + "') is not supported.")); return promise; } provider_->GetRegistrations( std::make_unique<CallbackPromiseAdapter<ServiceWorkerRegistrationArray, ServiceWorkerError>>(resolver)); return promise; } // https://w3c.github.io/ServiceWorker/#dom-serviceworkercontainer-startmessages void ServiceWorkerContainer::startMessages() { // "startMessages() method must enable the context object’s client message // queue if it is not enabled." EnableClientMessageQueue(); } ScriptPromise ServiceWorkerContainer::ready(ScriptState* caller_state, ExceptionState& exception_state) { if (!GetExecutionContext()) return ScriptPromise(); if (!caller_state->World().IsMainWorld()) { // FIXME: Support .ready from isolated worlds when // ScriptPromiseProperty can vend Promises in isolated worlds. exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError, "'ready' is only supported in pages."); return ScriptPromise(); } if (!ready_) { ready_ = CreateReadyProperty(); if (provider_) { provider_->GetRegistrationForReady( WTF::Bind(&ServiceWorkerContainer::OnGetRegistrationForReady, WrapPersistent(this))); } } return ready_->Promise(caller_state->World()); } void ServiceWorkerContainer::SetController( WebServiceWorkerObjectInfo info, bool should_notify_controller_change) { if (!GetExecutionContext()) return; controller_ = ServiceWorker::From(GetExecutionContext(), std::move(info)); if (controller_) { MaybeRecordThirdPartyServiceWorkerUsage(GetExecutionContext()); UseCounter::Count(GetExecutionContext(), WebFeature::kServiceWorkerControlledPage); } if (should_notify_controller_change) DispatchEvent(*Event::Create(event_type_names::kControllerchange)); } void ServiceWorkerContainer::ReceiveMessage(WebServiceWorkerObjectInfo source, TransferableMessage message) { auto* window = DynamicTo<LocalDOMWindow>(GetExecutionContext()); if (!window) return; // ServiceWorkerContainer is only supported on documents. auto* document = window->document(); DCHECK(document); if (!is_client_message_queue_enabled_) { if (!HasFiredDomContentLoaded(*document)) { // Wait for DOMContentLoaded. This corresponds to the specification steps // for "Parsing HTML documents": "The end" at // https://html.spec.whatwg.org/C/#the-end: // // 1. Fire an event named DOMContentLoaded at the Document object, with // its bubbles attribute initialized to true. // 2. Enable the client message queue of the ServiceWorkerContainer object // whose associated service worker client is the Document object's // relevant settings object. if (!dom_content_loaded_observer_) { dom_content_loaded_observer_ = MakeGarbageCollected<DomContentLoadedListener>(); document->addEventListener(event_type_names::kDOMContentLoaded, dom_content_loaded_observer_.Get(), false); } queued_messages_.emplace_back(std::make_unique<MessageFromServiceWorker>( std::move(source), std::move(message))); // The messages will be dispatched once EnableClientMessageQueue() is // called. return; } // DOMContentLoaded was fired already, so enable the queue. EnableClientMessageQueue(); } DispatchMessageEvent(std::move(source), std::move(message)); } void ServiceWorkerContainer::CountFeature(mojom::WebFeature feature) { if (!GetExecutionContext()) return; if (Deprecation::DeprecationMessage(feature).IsEmpty()) UseCounter::Count(GetExecutionContext(), feature); else Deprecation::CountDeprecation(GetExecutionContext(), feature); } ExecutionContext* ServiceWorkerContainer::GetExecutionContext() const { return GetSupplementable()->GetExecutionContext(); } const AtomicString& ServiceWorkerContainer::InterfaceName() const { return event_target_names::kServiceWorkerContainer; } void ServiceWorkerContainer::setOnmessage(EventListener* listener) { SetAttributeEventListener(event_type_names::kMessage, listener); // https://w3c.github.io/ServiceWorker/#dom-serviceworkercontainer-onmessage: // "The first time the context object’s onmessage IDL attribute is set, its // client message queue must be enabled." EnableClientMessageQueue(); } EventListener* ServiceWorkerContainer::onmessage() { return GetAttributeEventListener(event_type_names::kMessage); } ServiceWorkerRegistration* ServiceWorkerContainer::GetOrCreateServiceWorkerRegistration( WebServiceWorkerRegistrationObjectInfo info) { if (info.registration_id == mojom::blink::kInvalidServiceWorkerRegistrationId) return nullptr; ServiceWorkerRegistration* registration = service_worker_registration_objects_.at(info.registration_id); if (registration) { registration->Attach(std::move(info)); return registration; } const int64_t registration_id = info.registration_id; registration = MakeGarbageCollected<ServiceWorkerRegistration>( GetSupplementable()->GetExecutionContext(), std::move(info)); service_worker_registration_objects_.Set(registration_id, registration); return registration; } ServiceWorker* ServiceWorkerContainer::GetOrCreateServiceWorker( WebServiceWorkerObjectInfo info) { if (info.version_id == mojom::blink::kInvalidServiceWorkerVersionId) return nullptr; ServiceWorker* worker = service_worker_objects_.at(info.version_id); if (!worker) { const int64_t version_id = info.version_id; worker = ServiceWorker::Create(GetSupplementable()->GetExecutionContext(), std::move(info)); service_worker_objects_.Set(version_id, worker); } return worker; } ServiceWorkerContainer::ServiceWorkerContainer(LocalDOMWindow& window) : Supplement<LocalDOMWindow>(window), ExecutionContextLifecycleObserver(&window) {} ServiceWorkerContainer::ReadyProperty* ServiceWorkerContainer::CreateReadyProperty() { return MakeGarbageCollected<ReadyProperty>(GetExecutionContext()); } void ServiceWorkerContainer::EnableClientMessageQueue() { dom_content_loaded_observer_ = nullptr; if (is_client_message_queue_enabled_) { DCHECK(queued_messages_.IsEmpty()); return; } is_client_message_queue_enabled_ = true; Vector<std::unique_ptr<MessageFromServiceWorker>> messages; messages.swap(queued_messages_); for (auto& message : messages) { DispatchMessageEvent(std::move(message->source), std::move(message->message)); } } void ServiceWorkerContainer::DispatchMessageEvent( WebServiceWorkerObjectInfo source, TransferableMessage message) { DCHECK(is_client_message_queue_enabled_); auto msg = BlinkTransferableMessage::FromTransferableMessage(std::move(message)); MessagePortArray* ports = MessagePort::EntanglePorts(*GetExecutionContext(), std::move(msg.ports)); ServiceWorker* service_worker = ServiceWorker::From(GetExecutionContext(), std::move(source)); Event* event = nullptr; // TODO(crbug.com/1018092): Factor out these security checks so they aren't // duplicated in so many places. if (msg.message->IsOriginCheckRequired()) { const SecurityOrigin* target_origin = GetExecutionContext()->GetSecurityOrigin(); if (!msg.sender_origin || !msg.sender_origin->IsSameOriginWith(target_origin)) { event = MessageEvent::CreateError( GetExecutionContext()->GetSecurityOrigin()->ToString(), service_worker); } } if (!event) { if (!msg.locked_agent_cluster_id || GetExecutionContext()->IsSameAgentCluster( *msg.locked_agent_cluster_id)) { event = MessageEvent::Create( ports, std::move(msg.message), GetExecutionContext()->GetSecurityOrigin()->ToString(), String() /* lastEventId */, service_worker); } else { event = MessageEvent::CreateError( GetExecutionContext()->GetSecurityOrigin()->ToString(), service_worker); } } // Schedule the event to be dispatched on the correct task source: // https://w3c.github.io/ServiceWorker/#dfn-client-message-queue EnqueueEvent(*event, TaskType::kServiceWorkerClientMessage); } void ServiceWorkerContainer::OnGetRegistrationForReady( WebServiceWorkerRegistrationObjectInfo info) { DCHECK_EQ(ready_->GetState(), ReadyProperty::kPending); if (ready_->GetExecutionContext() && !ready_->GetExecutionContext()->IsContextDestroyed()) { ready_->Resolve( ServiceWorkerContainer::From( *To<LocalDOMWindow>(ready_->GetExecutionContext())) ->GetOrCreateServiceWorkerRegistration(std::move(info))); } } } // namespace blink
40.125731
102
0.721526
[ "object", "vector" ]
29a95dd8da0e5f827338db9b0fbe9cf215e57045
20,526
cc
C++
tensorflow/core/kernels/mkl_maxpooling_op.cc
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
3
2018-06-24T01:57:02.000Z
2022-03-13T11:19:33.000Z
tensorflow/core/kernels/mkl_maxpooling_op.cc
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/mkl_maxpooling_op.cc
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
2
2017-11-05T02:57:04.000Z
2018-01-29T01:37:42.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #define EIGEN_USE_THREADS #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/kernels/mkl_pooling_ops_common.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/mkl_util.h" #include "tensorflow/core/util/padding.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; // An implementation of MaxPooling (forward). template <typename Device, typename T> class MklMaxPoolingOp : public OpKernel { public: explicit MklMaxPoolingOp(OpKernelConstruction* context) : OpKernel(context) { string data_format; OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format)); OP_REQUIRES(context, FormatFromString(data_format, &data_format_), errors::InvalidArgument("Invalid data format")); OP_REQUIRES_OK(context, context->GetAttr("ksize", &ksize_)); OP_REQUIRES(context, ksize_.size() == 4, errors::InvalidArgument("Sliding window ksize field must " "specify 4 dimensions")); OP_REQUIRES_OK(context, context->GetAttr("strides", &stride_)); OP_REQUIRES(context, stride_.size() == 4, errors::InvalidArgument("Sliding window stride field must " "specify 4 dimensions")); OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_)); OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1, errors::Unimplemented("Pooling is not yet supported on the " "batch dimension.")); workspace_enabled_ = false; // We may not get this attribute for this node if it does not go through // graph rewrite pass. So we do not check for error while retrieving this // attribute value. context->GetAttr("workspace_enabled", &workspace_enabled_); } void Compute(OpKernelContext* context) override { MklMaxPoolingOpContext mkl_context; // Get the input tensor const Tensor& tensor_in = MklGetInput(context, 0); GetMklShape(context, 0, &mkl_context.input_shape); bool input_in_mkl_format = mkl_context.input_shape.IsMklTensor(); mkl_context.params.in_dim = 4; MklPoolParameters pool_params; if (input_in_mkl_format == false) { pool_params.Init(context, ksize_, stride_, padding_, data_format_, tensor_in.shape()); OP_REQUIRES( context, (pool_params.depth_window == 1), errors::Unimplemented("Depthwise max pooling not supported by MKL")); } else { pool_params.Init(context, ksize_, stride_, padding_, data_format_, &mkl_context.input_shape); } // Extract the parameters for the op from the pooling specs ExtractMklOpParams(context, data_format_, pool_params, &mkl_context.params); mkl_context.MklCreateLayoutsAndPrimitives(context); // Declare output tensor TensorShape tensor_out_shape; MklShape mkl_out_shape; mkl_out_shape.SetMklTensor(true); mkl_out_shape.SetMklLayout(mkl_context.prim_pooling_fwd, dnnResourceDst); mkl_out_shape.SetTfLayout(mkl_context.params.in_dim, mkl_context.params.out_sizes, mkl_context.params.out_strides); mkl_out_shape.SetTfDimOrder(mkl_context.params.in_dim, data_format_); Tensor* output_tensor = nullptr; tensor_out_shape.AddDim(dnnLayoutGetMemorySize_F32(static_cast<dnnLayout_t>( mkl_out_shape.GetMklLayout())) / sizeof(T)); AllocateOutputSetMklShape(context, 0, &output_tensor, tensor_out_shape, mkl_out_shape); if (!workspace_enabled_) { mkl_out_shape.SetMklTensor(false); } Tensor* workspace_tensor; void* workspace_buf = nullptr; if (workspace_enabled_) { TensorShape workspace_shape; workspace_shape.AddDim( dnnLayoutGetMemorySize_F32( static_cast<dnnLayout_t>(mkl_context.lt_workspace)) / sizeof(T)); AllocateOutputSetMklShape(context, 1, &workspace_tensor, workspace_shape, mkl_out_shape); mkl_context.pooling_res[dnnResourceWorkspace] = const_cast<void*>( static_cast<const void*>(workspace_tensor->flat<T>().data())); } else { AllocTmpBuffer(context, workspace_tensor, mkl_context.lt_workspace, &workspace_buf); mkl_context.pooling_res[dnnResourceWorkspace] = workspace_buf; } mkl_context.pooling_res[dnnResourceSrc] = const_cast<void*>(static_cast<const void*>(tensor_in.flat<T>().data())); mkl_context.pooling_res[dnnResourceDst] = const_cast<void*>( static_cast<const void*>(output_tensor->flat<T>().data())); CHECK_EQ( dnnExecute_F32(mkl_context.prim_pooling_fwd, mkl_context.pooling_res), E_SUCCESS); mkl_context.MklCleanup(); } private: typedef struct { MklPoolingOpParams params; MklShape input_shape; void* pooling_res[dnnResourceNumber]; dnnPrimitive_t prim_pooling_fwd; dnnLayout_t lt_user_input, lt_workspace; void MklCreateLayoutsAndPrimitives(OpKernelContext* context) { bool input_in_mkl_format = input_shape.IsMklTensor(); // Create or use existing DNN user layout if (input_in_mkl_format == false) { CHECK_EQ(dnnLayoutCreate_F32(&lt_user_input, params.in_dim, params.in_sizes, params.in_strides), E_SUCCESS); } else { lt_user_input = (dnnLayout_t)input_shape.GetCurLayout(); } dnnAlgorithm_t algorithm = dnnAlgorithmPoolingMax; dnnPrimitiveAttributes_t primAttr = nullptr; // Create DNN primitives CHECK_EQ(dnnPoolingCreateForward_F32( &prim_pooling_fwd, primAttr, algorithm, lt_user_input, params.kernel_size, params.kernel_stride, params.in_offset, dnnBorderZerosAsymm), E_SUCCESS); // Creates layout for the workspace CHECK_EQ(dnnLayoutCreateFromPrimitive_F32(&lt_workspace, prim_pooling_fwd, dnnResourceWorkspace), E_SUCCESS); } void MklCleanup() { bool input_in_mkl_format = input_shape.IsMklTensor(); CHECK_EQ(dnnDelete_F32(prim_pooling_fwd), E_SUCCESS); if (!input_in_mkl_format) { CHECK_EQ(dnnLayoutDelete_F32(lt_user_input), E_SUCCESS); } CHECK_EQ(dnnLayoutDelete_F32(lt_workspace), E_SUCCESS); } } MklMaxPoolingOpContext; std::vector<int32> ksize_; std::vector<int32> stride_; Padding padding_; TensorFormat data_format_; bool workspace_enabled_; }; // The operation to compute MaxPool gradients. // It takes three inputs: // - The original input tensor // - The original output tensor // - Backprop tensor for output // It produces one output: backprop tensor for input. template <class Device, class T> class MklMaxPoolingGradOp : public OpKernel { public: explicit MklMaxPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) { string data_format; OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format)); OP_REQUIRES(context, FormatFromString(data_format, &data_format_), errors::InvalidArgument("Invalid data format")); OP_REQUIRES_OK(context, context->GetAttr("ksize", &ksize_)); OP_REQUIRES(context, ksize_.size() == 4, errors::InvalidArgument("Sliding window ksize field must " "specify 4 dimensions")); OP_REQUIRES_OK(context, context->GetAttr("strides", &stride_)); OP_REQUIRES(context, stride_.size() == 4, errors::InvalidArgument("Sliding window strides field must " "specify 4 dimensions")); OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_)); OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1, errors::Unimplemented( "Pooling is not yet supported on the batch dimension.")); workspace_enabled_ = false; // We may not get this attribute for this node if it does not go through // graph rewrite pass. So we do not check for error while retrieving this // attribute value. context->GetAttr("workspace_enabled", &workspace_enabled_); } void Compute(OpKernelContext* context) override { MklMaxPoolingGradOpContext mkl_context; // Input - The original input tensor const Tensor& tensor_in = MklGetInput(context, 0); // Output - Backprop tensor for input. Tensor* output_tensor = nullptr; GetMklShape(context, 0, &mkl_context.input_shape); GetMklShape(context, 2, &mkl_context.output_backprop_shape); bool input_in_mkl_format = mkl_context.input_shape.IsMklTensor(); if (input_in_mkl_format == false) mkl_context.params.in_dim = tensor_in.dims(); else mkl_context.params.in_dim = mkl_context.input_shape.GetDimension(); MklPoolParameters pool_params; if (input_in_mkl_format == false) { pool_params.Init(context, ksize_, stride_, padding_, data_format_, tensor_in.shape()); OP_REQUIRES( context, (pool_params.depth_window == 1), errors::Unimplemented("Depthwise max pooling not supported by MKL")); } else { pool_params.Init(context, ksize_, stride_, padding_, data_format_, &mkl_context.input_shape); } // Extract the parameters for the op from the pooling specs ExtractMklOpParams(context, data_format_, pool_params, &mkl_context.params); mkl_context.MklCreateLayouts(context); mkl_context.MklCreatePrimitives(context, workspace_enabled_); mkl_context.MklPrepareInputs(context, workspace_enabled_); // Create shape for the input back prop output TensorShape mkl_input_backprop; MklShape mkl_output_shape; mkl_output_shape.SetMklTensor(true); mkl_output_shape.SetMklLayout(mkl_context.prim_pooling_bwd, dnnResourceDiffSrc); mkl_output_shape.SetTfLayout(mkl_context.params.in_dim, mkl_context.params.in_sizes, mkl_context.params.in_strides); mkl_output_shape.SetTfDimOrder(mkl_context.params.in_dim, data_format_); mkl_input_backprop.AddDim( dnnLayoutGetMemorySize_F32( static_cast<dnnLayout_t>(mkl_output_shape.GetMklLayout())) / sizeof(T)); AllocateOutputSetMklShape(context, 0, &output_tensor, mkl_input_backprop, mkl_output_shape); mkl_context.pooling_res[dnnResourceDiffSrc] = const_cast<void*>( static_cast<const void*>(output_tensor->flat<T>().data())); int64 output_size = output_tensor->NumElements(); for (int64 i = 0; i < output_size; ++i) { (static_cast<float*>(mkl_context.pooling_res[dnnResourceDiffSrc]))[i] = 0; } CHECK_EQ( dnnExecute_F32(mkl_context.prim_pooling_bwd, mkl_context.pooling_res), E_SUCCESS); mkl_context.MklCleanup(workspace_enabled_); } private: typedef struct { MklPoolingOpParams params; MklShape input_shape, output_backprop_shape; void* pooling_resfwd[dnnResourceNumber]; void* pooling_res[dnnResourceNumber]; dnnPrimitive_t prim_pooling_fwd, prim_pooling_bwd, convert_input, convert_outbackprop; dnnLayout_t lt_outbackprop_user, lt_outbackprop_prim, lt_input_user, lt_input_prim; void* input_buf; void* outbackprop_buf; void MklCreateLayouts(OpKernelContext* context) { bool input_in_mkl_format = input_shape.IsMklTensor(); bool outbackprop_in_mkl_format = output_backprop_shape.IsMklTensor(); // Create DNN user layout for input and outbackprop or get existing layout if (input_in_mkl_format == false) { CHECK_EQ(dnnLayoutCreate_F32(&lt_input_user, params.in_dim, params.in_sizes, params.in_strides), E_SUCCESS); } else { lt_input_user = (dnnLayout_t)input_shape.GetCurLayout(); } // We dont care about the output layout for now as we can create it from // primitives for the max pooling fwd prop if (outbackprop_in_mkl_format == false) { CHECK_EQ(dnnLayoutCreate_F32(&lt_outbackprop_user, params.in_dim, params.out_sizes, params.out_strides), E_SUCCESS); } else { lt_outbackprop_user = (dnnLayout_t)output_backprop_shape.GetCurLayout(); } } // Create DNN primitives void MklCreatePrimitives(OpKernelContext* context, bool workspace_enabled) { dnnAlgorithm_t algorithm = dnnAlgorithmPoolingMax; dnnPrimitiveAttributes_t primAttr = nullptr; if (workspace_enabled == false) { CHECK_EQ(dnnPoolingCreateForward_F32( &prim_pooling_fwd, primAttr, algorithm, lt_input_user, params.kernel_size, params.kernel_stride, params.in_offset, dnnBorderZerosAsymm), E_SUCCESS); } CHECK_EQ(dnnPoolingCreateBackward_F32( &prim_pooling_bwd, primAttr, algorithm, lt_input_user, params.kernel_size, params.kernel_stride, params.in_offset, dnnBorderZerosAsymm), E_SUCCESS); // Creates conversions CHECK_EQ(dnnLayoutCreateFromPrimitive_F32( &lt_outbackprop_prim, prim_pooling_bwd, dnnResourceDiffDst), E_SUCCESS); // Tensors needed to create temporary buffers Tensor input_buf_tensor, outbackprop_buf_tensor; if (workspace_enabled == false) { CHECK_EQ(dnnLayoutCreateFromPrimitive_F32( &lt_input_prim, prim_pooling_fwd, dnnResourceSrc), E_SUCCESS); if (!dnnLayoutCompare_F32(lt_input_user, lt_input_prim)) { CHECK_EQ(dnnConversionCreate_F32(&convert_input, lt_input_user, lt_input_prim), E_SUCCESS); AllocTmpBuffer(context, &input_buf_tensor, lt_input_prim, &input_buf); } } if (!dnnLayoutCompare_F32(lt_outbackprop_user, lt_outbackprop_prim)) { CHECK_EQ( dnnConversionCreate_F32(&convert_outbackprop, lt_outbackprop_user, lt_outbackprop_prim), E_SUCCESS); AllocTmpBuffer(context, &outbackprop_buf_tensor, lt_outbackprop_prim, &outbackprop_buf); } } // Compare incoming tensor layouts with MKL preferred layouts and convert // data to the preferred layout if necessary void MklPrepareInputs(OpKernelContext* context, bool workspace_enabled) { const Tensor& tensor_in = MklGetInput(context, 0); const Tensor& out_backprop = MklGetInput(context, 2); bool input_in_mkl_format = input_shape.IsMklTensor(); bool outbackprop_in_mkl_format = output_backprop_shape.IsMklTensor(); void* tmp_output_buf; Tensor tmp_output_buf_tensor; void* workspace_buf; Tensor workspace_buf_tensor; if (workspace_enabled == false) { if (convert_input != nullptr) { if (input_in_mkl_format == false) { CHECK_EQ(dnnConversionExecute_F32( convert_input, const_cast<void*>(static_cast<const void*>( tensor_in.flat<T>().data())), input_buf), E_SUCCESS); CHECK_EQ(dnnDelete_F32(convert_input), E_SUCCESS); convert_input = nullptr; } else { input_shape.GetConvertedFlatData( lt_input_prim, const_cast<void*>( static_cast<const void*>(tensor_in.flat<T>().data())), input_buf); } pooling_resfwd[dnnResourceSrc] = input_buf; } else { pooling_resfwd[dnnResourceSrc] = const_cast<void*>( static_cast<const void*>(tensor_in.flat<T>().data())); } dnnLayout_t lt_workspace; CHECK_EQ(dnnLayoutCreateFromPrimitive_F32( &lt_workspace, prim_pooling_fwd, dnnResourceWorkspace), E_SUCCESS); AllocTmpBuffer(context, &workspace_buf_tensor, lt_workspace, &workspace_buf); pooling_resfwd[dnnResourceWorkspace] = workspace_buf; dnnLayoutDelete_F32(lt_workspace); // We create the layout for max pooling fwd prop tmp output here AllocTmpBuffer(context, &tmp_output_buf_tensor, lt_outbackprop_prim, &tmp_output_buf); pooling_resfwd[dnnResourceDst] = tmp_output_buf; CHECK_EQ(dnnExecute_F32(prim_pooling_fwd, pooling_resfwd), E_SUCCESS); pooling_res[dnnResourceWorkspace] = pooling_resfwd[dnnResourceWorkspace]; } else { const Tensor& workspace = MklGetInput(context, 3); pooling_res[dnnResourceWorkspace] = const_cast<void*>( static_cast<const void*>(workspace.flat<T>().data())); } // Out backprop conversions if needed if (convert_outbackprop != nullptr) { if (outbackprop_in_mkl_format == false) { CHECK_EQ(dnnConversionExecute_F32( convert_outbackprop, const_cast<void*>(static_cast<const void*>( out_backprop.flat<T>().data())), outbackprop_buf), E_SUCCESS); CHECK_EQ(dnnDelete_F32(convert_outbackprop), E_SUCCESS); } else { output_backprop_shape.GetConvertedFlatData( lt_outbackprop_prim, const_cast<void*>( static_cast<const void*>(out_backprop.flat<T>().data())), outbackprop_buf); } pooling_res[dnnResourceDiffDst] = outbackprop_buf; } else { pooling_res[dnnResourceDiffDst] = const_cast<void*>( static_cast<const void*>(out_backprop.flat<T>().data())); } } void MklCleanup(bool workspace_enabled) { bool input_in_mkl_format = input_shape.IsMklTensor(); bool outbackprop_in_mkl_format = output_backprop_shape.IsMklTensor(); if (workspace_enabled == false) { CHECK_EQ(dnnDelete_F32(prim_pooling_fwd), E_SUCCESS); } CHECK_EQ(dnnDelete_F32(prim_pooling_bwd), E_SUCCESS); if (outbackprop_in_mkl_format == false) { CHECK_EQ(dnnLayoutDelete_F32(lt_outbackprop_user), E_SUCCESS); } CHECK_EQ(dnnLayoutDelete_F32(lt_outbackprop_prim), E_SUCCESS); if (input_in_mkl_format == false) { CHECK_EQ(dnnLayoutDelete_F32(lt_input_user), E_SUCCESS); } if (workspace_enabled == false) { CHECK_EQ(dnnLayoutDelete_F32(lt_input_prim), E_SUCCESS); } } } MklMaxPoolingGradOpContext; std::vector<int32> ksize_; std::vector<int32> stride_; Padding padding_; TensorFormat data_format_; bool workspace_enabled_; }; REGISTER_KERNEL_BUILDER(Name("MklMaxPool") .Device(DEVICE_CPU) .TypeConstraint<float>("T") .Label(mkl_op_registry::kMklOpLabel), MklMaxPoolingOp<CPUDevice, float>); REGISTER_KERNEL_BUILDER(Name("MklMaxPoolGrad") .Device(DEVICE_CPU) .TypeConstraint<float>("T") .Label(mkl_op_registry::kMklOpLabel), MklMaxPoolingGradOp<CPUDevice, float>); } // namespace tensorflow #endif // INTEL_MKL
40.485207
80
0.652002
[ "shape", "vector" ]
29aaa064562a156fe2a1595caf098319d849e304
22,175
cpp
C++
samples/gpu/opticalflow_nvidia_api.cpp
sagarjoglekar/opencv
de4ee084b1958e859e5a2c74b6867310bb2e4940
[ "BSD-3-Clause" ]
3
2018-10-15T07:31:30.000Z
2020-10-16T08:59:46.000Z
samples/gpu/opticalflow_nvidia_api.cpp
cangunel/opencv
42f9ee3f3e580a2c8495b4b56669f06708de53b1
[ "BSD-3-Clause" ]
null
null
null
samples/gpu/opticalflow_nvidia_api.cpp
cangunel/opencv
42f9ee3f3e580a2c8495b4b56669f06708de53b1
[ "BSD-3-Clause" ]
2
2016-12-02T02:57:34.000Z
2020-01-09T11:03:24.000Z
#if defined _MSC_VER && _MSC_VER >= 1400 #pragma warning( disable : 4201 4408 4127 4100) #endif #include <iostream> #include <iomanip> #include <memory> #include <exception> #include <ctime> #include "cvconfig.h" #include <iostream> #include <iomanip> #include "opencv2/core/cuda.hpp" #include "opencv2/cudalegacy.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/highgui/highgui_c.h" #if !defined(HAVE_CUDA) int main( int, const char** ) { std::cout << "Please compile the library with CUDA support" << std::endl; return -1; } #else //using std::tr1::shared_ptr; using cv::Ptr; #define PARAM_LEFT "--left" #define PARAM_RIGHT "--right" #define PARAM_SCALE "--scale" #define PARAM_ALPHA "--alpha" #define PARAM_GAMMA "--gamma" #define PARAM_INNER "--inner" #define PARAM_OUTER "--outer" #define PARAM_SOLVER "--solver" #define PARAM_TIME_STEP "--time-step" #define PARAM_HELP "--help" Ptr<INCVMemAllocator> g_pGPUMemAllocator; Ptr<INCVMemAllocator> g_pHostMemAllocator; class RgbToMonochrome { public: float operator ()(unsigned char b, unsigned char g, unsigned char r) { float _r = static_cast<float>(r)/255.0f; float _g = static_cast<float>(g)/255.0f; float _b = static_cast<float>(b)/255.0f; return (_r + _g + _b)/3.0f; } }; class RgbToR { public: float operator ()(unsigned char /*b*/, unsigned char /*g*/, unsigned char r) { return static_cast<float>(r)/255.0f; } }; class RgbToG { public: float operator ()(unsigned char /*b*/, unsigned char g, unsigned char /*r*/) { return static_cast<float>(g)/255.0f; } }; class RgbToB { public: float operator ()(unsigned char b, unsigned char /*g*/, unsigned char /*r*/) { return static_cast<float>(b)/255.0f; } }; template<class T> NCVStatus CopyData(IplImage *image, Ptr<NCVMatrixAlloc<Ncv32f> >& dst) { dst = Ptr<NCVMatrixAlloc<Ncv32f> > (new NCVMatrixAlloc<Ncv32f> (*g_pHostMemAllocator, image->width, image->height)); ncvAssertReturn (dst->isMemAllocated (), NCV_ALLOCATOR_BAD_ALLOC); unsigned char *row = reinterpret_cast<unsigned char*> (image->imageData); T convert; for (int i = 0; i < image->height; ++i) { for (int j = 0; j < image->width; ++j) { if (image->nChannels < 3) { dst->ptr ()[j + i*dst->stride ()] = static_cast<float> (*(row + j*image->nChannels))/255.0f; } else { unsigned char *color = row + j * image->nChannels; dst->ptr ()[j +i*dst->stride ()] = convert (color[0], color[1], color[2]); } } row += image->widthStep; } return NCV_SUCCESS; } template<class T> NCVStatus CopyData(const IplImage *image, const NCVMatrixAlloc<Ncv32f> &dst) { unsigned char *row = reinterpret_cast<unsigned char*> (image->imageData); T convert; for (int i = 0; i < image->height; ++i) { for (int j = 0; j < image->width; ++j) { if (image->nChannels < 3) { dst.ptr ()[j + i*dst.stride ()] = static_cast<float>(*(row + j*image->nChannels))/255.0f; } else { unsigned char *color = row + j * image->nChannels; dst.ptr ()[j +i*dst.stride()] = convert (color[0], color[1], color[2]); } } row += image->widthStep; } return NCV_SUCCESS; } static NCVStatus LoadImages (const char *frame0Name, const char *frame1Name, int &width, int &height, Ptr<NCVMatrixAlloc<Ncv32f> > &src, Ptr<NCVMatrixAlloc<Ncv32f> > &dst, IplImage *&firstFrame, IplImage *&lastFrame) { IplImage *image; image = cvLoadImage (frame0Name); if (image == 0) { std::cout << "Could not open '" << frame0Name << "'\n"; return NCV_FILE_ERROR; } firstFrame = image; // copy data to src ncvAssertReturnNcvStat (CopyData<RgbToMonochrome> (image, src)); IplImage *image2; image2 = cvLoadImage (frame1Name); if (image2 == 0) { std::cout << "Could not open '" << frame1Name << "'\n"; return NCV_FILE_ERROR; } lastFrame = image2; ncvAssertReturnNcvStat (CopyData<RgbToMonochrome> (image2, dst)); width = image->width; height = image->height; return NCV_SUCCESS; } template<typename T> inline T Clamp (T x, T a, T b) { return ((x) > (a) ? ((x) < (b) ? (x) : (b)) : (a)); } template<typename T> inline T MapValue (T x, T a, T b, T c, T d) { x = Clamp (x, a, b); return c + (d - c) * (x - a) / (b - a); } static NCVStatus ShowFlow (NCVMatrixAlloc<Ncv32f> &u, NCVMatrixAlloc<Ncv32f> &v, const char *name) { IplImage *flowField; NCVMatrixAlloc<Ncv32f> host_u(*g_pHostMemAllocator, u.width(), u.height()); ncvAssertReturn(host_u.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32f> host_v (*g_pHostMemAllocator, u.width (), u.height ()); ncvAssertReturn (host_v.isMemAllocated (), NCV_ALLOCATOR_BAD_ALLOC); ncvAssertReturnNcvStat (u.copySolid (host_u, 0)); ncvAssertReturnNcvStat (v.copySolid (host_v, 0)); float *ptr_u = host_u.ptr (); float *ptr_v = host_v.ptr (); float maxDisplacement = 1.0f; for (Ncv32u i = 0; i < u.height (); ++i) { for (Ncv32u j = 0; j < u.width (); ++j) { float d = std::max ( fabsf(*ptr_u), fabsf(*ptr_v) ); if (d > maxDisplacement) maxDisplacement = d; ++ptr_u; ++ptr_v; } ptr_u += u.stride () - u.width (); ptr_v += v.stride () - v.width (); } CvSize image_size = cvSize (u.width (), u.height ()); flowField = cvCreateImage (image_size, IPL_DEPTH_8U, 4); if (flowField == 0) return NCV_NULL_PTR; unsigned char *row = reinterpret_cast<unsigned char *> (flowField->imageData); ptr_u = host_u.ptr(); ptr_v = host_v.ptr(); for (int i = 0; i < flowField->height; ++i) { for (int j = 0; j < flowField->width; ++j) { (row + j * flowField->nChannels)[0] = 0; (row + j * flowField->nChannels)[1] = static_cast<unsigned char> (MapValue (-(*ptr_v), -maxDisplacement, maxDisplacement, 0.0f, 255.0f)); (row + j * flowField->nChannels)[2] = static_cast<unsigned char> (MapValue (*ptr_u , -maxDisplacement, maxDisplacement, 0.0f, 255.0f)); (row + j * flowField->nChannels)[3] = 255; ++ptr_u; ++ptr_v; } row += flowField->widthStep; ptr_u += u.stride () - u.width (); ptr_v += v.stride () - v.width (); } cvShowImage (name, flowField); return NCV_SUCCESS; } static IplImage *CreateImage (NCVMatrixAlloc<Ncv32f> &h_r, NCVMatrixAlloc<Ncv32f> &h_g, NCVMatrixAlloc<Ncv32f> &h_b) { CvSize imageSize = cvSize (h_r.width (), h_r.height ()); IplImage *image = cvCreateImage (imageSize, IPL_DEPTH_8U, 4); if (image == 0) return 0; unsigned char *row = reinterpret_cast<unsigned char*> (image->imageData); for (int i = 0; i < image->height; ++i) { for (int j = 0; j < image->width; ++j) { int offset = j * image->nChannels; int pos = i * h_r.stride () + j; row[offset + 0] = static_cast<unsigned char> (h_b.ptr ()[pos] * 255.0f); row[offset + 1] = static_cast<unsigned char> (h_g.ptr ()[pos] * 255.0f); row[offset + 2] = static_cast<unsigned char> (h_r.ptr ()[pos] * 255.0f); row[offset + 3] = 255; } row += image->widthStep; } return image; } static void PrintHelp () { std::cout << "Usage help:\n"; std::cout << std::setiosflags(std::ios::left); std::cout << "\t" << std::setw(15) << PARAM_ALPHA << " - set alpha\n"; std::cout << "\t" << std::setw(15) << PARAM_GAMMA << " - set gamma\n"; std::cout << "\t" << std::setw(15) << PARAM_INNER << " - set number of inner iterations\n"; std::cout << "\t" << std::setw(15) << PARAM_LEFT << " - specify left image\n"; std::cout << "\t" << std::setw(15) << PARAM_RIGHT << " - specify right image\n"; std::cout << "\t" << std::setw(15) << PARAM_OUTER << " - set number of outer iterations\n"; std::cout << "\t" << std::setw(15) << PARAM_SCALE << " - set pyramid scale factor\n"; std::cout << "\t" << std::setw(15) << PARAM_SOLVER << " - set number of basic solver iterations\n"; std::cout << "\t" << std::setw(15) << PARAM_TIME_STEP << " - set frame interpolation time step\n"; std::cout << "\t" << std::setw(15) << PARAM_HELP << " - display this help message\n"; } static int ProcessCommandLine(int argc, char **argv, Ncv32f &timeStep, char *&frame0Name, char *&frame1Name, NCVBroxOpticalFlowDescriptor &desc) { timeStep = 0.25f; for (int iarg = 1; iarg < argc; ++iarg) { if (strcmp(argv[iarg], PARAM_LEFT) == 0) { if (iarg + 1 < argc) { frame0Name = argv[++iarg]; } else return -1; } if (strcmp(argv[iarg], PARAM_RIGHT) == 0) { if (iarg + 1 < argc) { frame1Name = argv[++iarg]; } else return -1; } else if(strcmp(argv[iarg], PARAM_SCALE) == 0) { if (iarg + 1 < argc) desc.scale_factor = static_cast<Ncv32f>(atof(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_ALPHA) == 0) { if (iarg + 1 < argc) desc.alpha = static_cast<Ncv32f>(atof(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_GAMMA) == 0) { if (iarg + 1 < argc) desc.gamma = static_cast<Ncv32f>(atof(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_INNER) == 0) { if (iarg + 1 < argc) desc.number_of_inner_iterations = static_cast<Ncv32u>(atoi(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_OUTER) == 0) { if (iarg + 1 < argc) desc.number_of_outer_iterations = static_cast<Ncv32u>(atoi(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_SOLVER) == 0) { if (iarg + 1 < argc) desc.number_of_solver_iterations = static_cast<Ncv32u>(atoi(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_TIME_STEP) == 0) { if (iarg + 1 < argc) timeStep = static_cast<Ncv32f>(atof(argv[++iarg])); else return -1; } else if(strcmp(argv[iarg], PARAM_HELP) == 0) { PrintHelp (); return 0; } } return 0; } int main(int argc, char **argv) { char *frame0Name = 0, *frame1Name = 0; Ncv32f timeStep = 0.01f; NCVBroxOpticalFlowDescriptor desc; desc.alpha = 0.197f; desc.gamma = 50.0f; desc.number_of_inner_iterations = 10; desc.number_of_outer_iterations = 77; desc.number_of_solver_iterations = 10; desc.scale_factor = 0.8f; int result = ProcessCommandLine (argc, argv, timeStep, frame0Name, frame1Name, desc); if (argc == 1 || result) { PrintHelp(); return result; } cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice()); std::cout << "OpenCV / NVIDIA Computer Vision\n"; std::cout << "Optical Flow Demo: Frame Interpolation\n"; std::cout << "=========================================\n"; std::cout << "Press:\n ESC to quit\n 'a' to move to the previous frame\n 's' to move to the next frame\n"; int devId; ncvAssertCUDAReturn(cudaGetDevice(&devId), -1); cudaDeviceProp devProp; ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), -1); std::cout << "Using GPU: " << devId << "(" << devProp.name << "), arch=" << devProp.major << "." << devProp.minor << std::endl; g_pGPUMemAllocator = Ptr<INCVMemAllocator> (new NCVMemNativeAllocator (NCVMemoryTypeDevice, static_cast<Ncv32u>(devProp.textureAlignment))); ncvAssertPrintReturn (g_pGPUMemAllocator->isInitialized (), "Device memory allocator isn't initialized", -1); g_pHostMemAllocator = Ptr<INCVMemAllocator> (new NCVMemNativeAllocator (NCVMemoryTypeHostPageable, static_cast<Ncv32u>(devProp.textureAlignment))); ncvAssertPrintReturn (g_pHostMemAllocator->isInitialized (), "Host memory allocator isn't initialized", -1); int width, height; Ptr<NCVMatrixAlloc<Ncv32f> > src_host; Ptr<NCVMatrixAlloc<Ncv32f> > dst_host; IplImage *firstFrame, *lastFrame; if (frame0Name != 0 && frame1Name != 0) { ncvAssertReturnNcvStat (LoadImages (frame0Name, frame1Name, width, height, src_host, dst_host, firstFrame, lastFrame)); } else { ncvAssertReturnNcvStat (LoadImages ("frame10.bmp", "frame11.bmp", width, height, src_host, dst_host, firstFrame, lastFrame)); } Ptr<NCVMatrixAlloc<Ncv32f> > src (new NCVMatrixAlloc<Ncv32f> (*g_pGPUMemAllocator, src_host->width (), src_host->height ())); ncvAssertReturn(src->isMemAllocated(), -1); Ptr<NCVMatrixAlloc<Ncv32f> > dst (new NCVMatrixAlloc<Ncv32f> (*g_pGPUMemAllocator, src_host->width (), src_host->height ())); ncvAssertReturn (dst->isMemAllocated (), -1); ncvAssertReturnNcvStat (src_host->copySolid ( *src, 0 )); ncvAssertReturnNcvStat (dst_host->copySolid ( *dst, 0 )); #if defined SAFE_MAT_DECL #undef SAFE_MAT_DECL #endif #define SAFE_MAT_DECL(name, allocator, sx, sy) \ NCVMatrixAlloc<Ncv32f> name(*allocator, sx, sy);\ ncvAssertReturn(name.isMemAllocated(), -1); SAFE_MAT_DECL (u, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (v, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (uBck, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (vBck, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (h_r, g_pHostMemAllocator, width, height); SAFE_MAT_DECL (h_g, g_pHostMemAllocator, width, height); SAFE_MAT_DECL (h_b, g_pHostMemAllocator, width, height); std::cout << "Estimating optical flow\nForward...\n"; if (NCV_SUCCESS != NCVBroxOpticalFlow (desc, *g_pGPUMemAllocator, *src, *dst, u, v, 0)) { std::cout << "Failed\n"; return -1; } std::cout << "Backward...\n"; if (NCV_SUCCESS != NCVBroxOpticalFlow (desc, *g_pGPUMemAllocator, *dst, *src, uBck, vBck, 0)) { std::cout << "Failed\n"; return -1; } // matrix for temporary data SAFE_MAT_DECL (d_temp, g_pGPUMemAllocator, width, height); // first frame color components (GPU memory) SAFE_MAT_DECL (d_r, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_g, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_b, g_pGPUMemAllocator, width, height); // second frame color components (GPU memory) SAFE_MAT_DECL (d_rt, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_gt, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_bt, g_pGPUMemAllocator, width, height); // intermediate frame color components (GPU memory) SAFE_MAT_DECL (d_rNew, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_gNew, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (d_bNew, g_pGPUMemAllocator, width, height); // interpolated forward flow SAFE_MAT_DECL (ui, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (vi, g_pGPUMemAllocator, width, height); // interpolated backward flow SAFE_MAT_DECL (ubi, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (vbi, g_pGPUMemAllocator, width, height); // occlusion masks SAFE_MAT_DECL (occ0, g_pGPUMemAllocator, width, height); SAFE_MAT_DECL (occ1, g_pGPUMemAllocator, width, height); // prepare color components on host and copy them to device memory ncvAssertReturnNcvStat (CopyData<RgbToR> (firstFrame, h_r)); ncvAssertReturnNcvStat (CopyData<RgbToG> (firstFrame, h_g)); ncvAssertReturnNcvStat (CopyData<RgbToB> (firstFrame, h_b)); ncvAssertReturnNcvStat (h_r.copySolid ( d_r, 0 )); ncvAssertReturnNcvStat (h_g.copySolid ( d_g, 0 )); ncvAssertReturnNcvStat (h_b.copySolid ( d_b, 0 )); ncvAssertReturnNcvStat (CopyData<RgbToR> (lastFrame, h_r)); ncvAssertReturnNcvStat (CopyData<RgbToG> (lastFrame, h_g)); ncvAssertReturnNcvStat (CopyData<RgbToB> (lastFrame, h_b)); ncvAssertReturnNcvStat (h_r.copySolid ( d_rt, 0 )); ncvAssertReturnNcvStat (h_g.copySolid ( d_gt, 0 )); ncvAssertReturnNcvStat (h_b.copySolid ( d_bt, 0 )); std::cout << "Interpolating...\n"; std::cout.precision (4); std::vector<IplImage*> frames; frames.push_back (firstFrame); // compute interpolated frames for (Ncv32f timePos = timeStep; timePos < 1.0f; timePos += timeStep) { ncvAssertCUDAReturn (cudaMemset (ui.ptr (), 0, ui.pitch () * ui.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vi.ptr (), 0, vi.pitch () * vi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (ubi.ptr (), 0, ubi.pitch () * ubi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vbi.ptr (), 0, vbi.pitch () * vbi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ0.ptr (), 0, occ0.pitch () * occ0.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ1.ptr (), 0, occ1.pitch () * occ1.height ()), NCV_CUDA_ERROR); NppStInterpolationState state; // interpolation state should be filled once except pSrcFrame0, pSrcFrame1, and pNewFrame // we will only need to reset buffers content to 0 since interpolator doesn't do this itself state.size = NcvSize32u (width, height); state.nStep = d_r.pitch (); state.pSrcFrame0 = d_r.ptr (); state.pSrcFrame1 = d_rt.ptr (); state.pFU = u.ptr (); state.pFV = v.ptr (); state.pBU = uBck.ptr (); state.pBV = vBck.ptr (); state.pos = timePos; state.pNewFrame = d_rNew.ptr (); state.ppBuffers[0] = occ0.ptr (); state.ppBuffers[1] = occ1.ptr (); state.ppBuffers[2] = ui.ptr (); state.ppBuffers[3] = vi.ptr (); state.ppBuffers[4] = ubi.ptr (); state.ppBuffers[5] = vbi.ptr (); // interpolate red channel nppiStInterpolateFrames (&state); // reset buffers ncvAssertCUDAReturn (cudaMemset (ui.ptr (), 0, ui.pitch () * ui.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vi.ptr (), 0, vi.pitch () * vi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (ubi.ptr (), 0, ubi.pitch () * ubi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vbi.ptr (), 0, vbi.pitch () * vbi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ0.ptr (), 0, occ0.pitch () * occ0.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ1.ptr (), 0, occ1.pitch () * occ1.height ()), NCV_CUDA_ERROR); // interpolate green channel state.pSrcFrame0 = d_g.ptr (); state.pSrcFrame1 = d_gt.ptr (); state.pNewFrame = d_gNew.ptr (); nppiStInterpolateFrames (&state); // reset buffers ncvAssertCUDAReturn (cudaMemset (ui.ptr (), 0, ui.pitch () * ui.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vi.ptr (), 0, vi.pitch () * vi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (ubi.ptr (), 0, ubi.pitch () * ubi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (vbi.ptr (), 0, vbi.pitch () * vbi.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ0.ptr (), 0, occ0.pitch () * occ0.height ()), NCV_CUDA_ERROR); ncvAssertCUDAReturn (cudaMemset (occ1.ptr (), 0, occ1.pitch () * occ1.height ()), NCV_CUDA_ERROR); // interpolate blue channel state.pSrcFrame0 = d_b.ptr (); state.pSrcFrame1 = d_bt.ptr (); state.pNewFrame = d_bNew.ptr (); nppiStInterpolateFrames (&state); // copy to host memory ncvAssertReturnNcvStat (d_rNew.copySolid (h_r, 0)); ncvAssertReturnNcvStat (d_gNew.copySolid (h_g, 0)); ncvAssertReturnNcvStat (d_bNew.copySolid (h_b, 0)); // convert to IplImage IplImage *newFrame = CreateImage (h_r, h_g, h_b); if (newFrame == 0) { std::cout << "Could not create new frame in host memory\n"; break; } frames.push_back (newFrame); std::cout << timePos * 100.0f << "%\r"; } std::cout << std::setw (5) << "100%\n"; frames.push_back (lastFrame); Ncv32u currentFrame; currentFrame = 0; ShowFlow (u, v, "Forward flow"); ShowFlow (uBck, vBck, "Backward flow"); cvShowImage ("Interpolated frame", frames[currentFrame]); bool qPressed = false; while ( !qPressed ) { int key = toupper (cvWaitKey (10)); switch (key) { case 27: qPressed = true; break; case 'A': if (currentFrame > 0) --currentFrame; cvShowImage ("Interpolated frame", frames[currentFrame]); break; case 'S': if (currentFrame < frames.size()-1) ++currentFrame; cvShowImage ("Interpolated frame", frames[currentFrame]); break; } } cvDestroyAllWindows (); std::vector<IplImage*>::iterator iter; for (iter = frames.begin (); iter != frames.end (); ++iter) { cvReleaseImage (&(*iter)); } return 0; } #endif
34.115385
151
0.591612
[ "vector" ]
29ad734a0abdfff477a2f18d0feaaa9f20e5db8a
4,701
cpp
C++
tc 160+/SolvePolynomial.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/SolvePolynomial.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/SolvePolynomial.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <set> using namespace std; void gen(vector<int> &X, vector<int> &Y, vector<int> &A) { int lX = X.size(); int lY = Y.size(); for (int i=0; i<(int)A.size(); ++i) { int p = i%lX; int q = (i + Y[i%lY])%lX; A[i] = X[p]; X[p] = X[q]; X[q] = A[i]; } } vector<long long> F; bool test(long long r, const vector<int> &A, long long target) { assert(target/r * r == target); for (int i=(int)A.size()-1; i>=0; --i) { target -= A[i]; if (target/r * r != target) { return false; } target = target/r; } return (target==0); } class SolvePolynomial { public: vector <int> integerRoots(vector <int> X, vector <int> Y, int n) { vector<int> A(n+1, 0); gen(X, Y, A); while (A.size()>0 && A.back()==0) { A.pop_back(); } if (A.size() == 0) { return vector<int> (1, 0); } reverse(A.begin(), A.end()); vector<int> sol; if (A.back() == 0) { sol.push_back(0); } while (A.size()>0 && A.back()==0) { A.pop_back(); } if (A.size() > 0) { F.assign(n, 0); int last = abs(A.back()); for (int d=1; d<=last/d; ++d) { if (last%d == 0) { if (test(-d, A, 0)) { sol.push_back(-d); } if (test(d, A, 0)) { sol.push_back(d); } if (d*d < last) { if (test(-last/d, A, 0)) { sol.push_back(-last/d); } if (test(last/d, A, 0)) { sol.push_back(last/d); } } } } } sort(sol.begin(), sol.end()); return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arr0[] = {-4, 2, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; int Arr3[] = {-2, 1 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(0, Arg3, integerRoots(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {1, 2, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2, 0, 0, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; int Arr3[] = {-1 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(1, Arg3, integerRoots(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {1, 4, 4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; int Arr3[] = { }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(2, Arg3, integerRoots(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {-15, -10, 2, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; int Arr3[] = {3 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(3, Arg3, integerRoots(Arg0, Arg1, Arg2)); } void test_case_4() { int Arr0[] = {735134400, 1383, 4121, 18875, 10463, 13512, 19603, 28679, 13483, 9509, 1701, 13383, 24425, 7923, 7978, 21702, 30989, 20676, 18547, 28130, 10944}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {34,23,6,5,3,5,4,34,37,5,6,21,17,9}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 10000; int Arr3[] = { }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(4, Arg3, integerRoots(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { SolvePolynomial ___test; ___test.run_test(-1); } // END CUT HERE
38.85124
370
0.552223
[ "vector" ]
29b026e2416758095f0a310e962683b7bb5dafdc
14,532
cpp
C++
cpp/open3d/pipelines/color_map/ColorMapUtils.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
3,673
2019-04-06T05:35:43.000Z
2021-07-27T14:53:14.000Z
cpp/open3d/pipelines/color_map/ColorMapUtils.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
2,904
2019-04-06T06:51:22.000Z
2021-07-27T13:49:54.000Z
cpp/open3d/pipelines/color_map/ColorMapUtils.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
1,127
2019-04-06T09:39:17.000Z
2021-07-27T03:06:49.000Z
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/pipelines/color_map/ColorMapUtils.h" #include "open3d/camera/PinholeCameraTrajectory.h" #include "open3d/geometry/Image.h" #include "open3d/geometry/KDTreeFlann.h" #include "open3d/geometry/RGBDImage.h" #include "open3d/geometry/TriangleMesh.h" #include "open3d/pipelines/color_map/ImageWarpingField.h" #include "open3d/utility/Parallel.h" namespace open3d { namespace pipelines { namespace color_map { static std::tuple<float, float, float> Project3DPointAndGetUVDepth( const Eigen::Vector3d X, const camera::PinholeCameraParameters& camera_parameter) { std::pair<double, double> f = camera_parameter.intrinsic_.GetFocalLength(); std::pair<double, double> p = camera_parameter.intrinsic_.GetPrincipalPoint(); Eigen::Vector4d Vt = camera_parameter.extrinsic_ * Eigen::Vector4d(X(0), X(1), X(2), 1); float u = float((Vt(0) * f.first) / Vt(2) + p.first); float v = float((Vt(1) * f.second) / Vt(2) + p.second); float z = float(Vt(2)); return std::make_tuple(u, v, z); } template <typename T> static std::tuple<bool, T> QueryImageIntensity( const geometry::Image& img, const utility::optional<ImageWarpingField>& optional_warping_field, const Eigen::Vector3d& V, const camera::PinholeCameraParameters& camera_parameter, utility::optional<int> channel, int image_boundary_margin) { float u, v, depth; std::tie(u, v, depth) = Project3DPointAndGetUVDepth(V, camera_parameter); // TODO: check why we use the u, ve before warpping for TestImageBoundary. if (img.TestImageBoundary(u, v, image_boundary_margin)) { if (optional_warping_field.has_value()) { Eigen::Vector2d uv_shift = optional_warping_field.value().GetImageWarpingField(u, v); u = static_cast<float>(uv_shift(0)); v = static_cast<float>(uv_shift(1)); } if (img.TestImageBoundary(u, v, image_boundary_margin)) { int u_round = int(u); int v_round = int(v); if (channel.has_value()) { return std::make_tuple( true, *img.PointerAt<T>(u_round, v_round, channel.value())); } else { return std::make_tuple(true, *img.PointerAt<T>(u_round, v_round)); } } } return std::make_tuple(false, 0); } std::tuple<std::vector<geometry::Image>, std::vector<geometry::Image>, std::vector<geometry::Image>, std::vector<geometry::Image>, std::vector<geometry::Image>> CreateUtilImagesFromRGBD(const std::vector<geometry::RGBDImage>& images_rgbd) { std::vector<geometry::Image> images_gray; std::vector<geometry::Image> images_dx; std::vector<geometry::Image> images_dy; std::vector<geometry::Image> images_color; std::vector<geometry::Image> images_depth; for (size_t i = 0; i < images_rgbd.size(); i++) { auto gray_image = images_rgbd[i].color_.CreateFloatImage(); auto gray_image_filtered = gray_image->Filter(geometry::Image::FilterType::Gaussian3); images_gray.push_back(*gray_image_filtered); images_dx.push_back(*gray_image_filtered->Filter( geometry::Image::FilterType::Sobel3Dx)); images_dy.push_back(*gray_image_filtered->Filter( geometry::Image::FilterType::Sobel3Dy)); auto color = std::make_shared<geometry::Image>(images_rgbd[i].color_); auto depth = std::make_shared<geometry::Image>(images_rgbd[i].depth_); images_color.push_back(*color); images_depth.push_back(*depth); } return std::make_tuple(images_gray, images_dx, images_dy, images_color, images_depth); } std::vector<geometry::Image> CreateDepthBoundaryMasks( const std::vector<geometry::Image>& images_depth, double depth_threshold_for_discontinuity_check, int half_dilation_kernel_size_for_discontinuity_map) { auto n_images = images_depth.size(); std::vector<geometry::Image> masks; for (size_t i = 0; i < n_images; i++) { utility::LogDebug("[MakeDepthMasks] geometry::Image {:d}/{:d}", i, n_images); masks.push_back(*images_depth[i].CreateDepthBoundaryMask( depth_threshold_for_discontinuity_check, half_dilation_kernel_size_for_discontinuity_map)); } return masks; } std::tuple<std::vector<std::vector<int>>, std::vector<std::vector<int>>> CreateVertexAndImageVisibility( const geometry::TriangleMesh& mesh, const std::vector<geometry::Image>& images_depth, const std::vector<geometry::Image>& images_mask, const camera::PinholeCameraTrajectory& camera_trajectory, double maximum_allowable_depth, double depth_threshold_for_visibility_check) { size_t n_camera = camera_trajectory.parameters_.size(); size_t n_vertex = mesh.vertices_.size(); // visibility_image_to_vertex[c]: vertices visible by camera c. std::vector<std::vector<int>> visibility_image_to_vertex; visibility_image_to_vertex.resize(n_camera); // visibility_vertex_to_image[v]: cameras that can see vertex v. std::vector<std::vector<int>> visibility_vertex_to_image; visibility_vertex_to_image.resize(n_vertex); #pragma omp parallel for schedule(static) \ num_threads(utility::EstimateMaxThreads()) for (int camera_id = 0; camera_id < int(n_camera); camera_id++) { for (int vertex_id = 0; vertex_id < int(n_vertex); vertex_id++) { Eigen::Vector3d X = mesh.vertices_[vertex_id]; float u, v, d; std::tie(u, v, d) = Project3DPointAndGetUVDepth( X, camera_trajectory.parameters_[camera_id]); int u_d = int(round(u)), v_d = int(round(v)); // Skip if vertex in image boundary. if (d < 0.0 || !images_depth[camera_id].TestImageBoundary(u_d, v_d)) { continue; } // Skip if vertex's depth is too large (e.g. background). float d_sensor = *images_depth[camera_id].PointerAt<float>(u_d, v_d); if (d_sensor > maximum_allowable_depth) { continue; } // Check depth boundary mask. If a vertex is located at the boundary // of an object, its color will be highly diverse from different // viewing angles. if (*images_mask[camera_id].PointerAt<uint8_t>(u_d, v_d) == 255) { continue; } // Check depth errors. if (std::fabs(d - d_sensor) >= depth_threshold_for_visibility_check) { continue; } visibility_image_to_vertex[camera_id].push_back(vertex_id); #pragma omp critical(CreateVertexAndImageVisibility) { visibility_vertex_to_image[vertex_id].push_back(camera_id); } } } for (int camera_id = 0; camera_id < int(n_camera); camera_id++) { size_t n_visible_vertex = visibility_image_to_vertex[camera_id].size(); utility::LogDebug( "[cam {:d}]: {:d}/{:d} ({:.5f}%) vertices are visible", camera_id, n_visible_vertex, n_vertex, double(n_visible_vertex) / n_vertex * 100); } return std::make_tuple(visibility_vertex_to_image, visibility_image_to_vertex); } void SetProxyIntensityForVertex( const geometry::TriangleMesh& mesh, const std::vector<geometry::Image>& images_gray, const utility::optional<std::vector<ImageWarpingField>>& warping_fields, const camera::PinholeCameraTrajectory& camera_trajectory, const std::vector<std::vector<int>>& visibility_vertex_to_image, std::vector<double>& proxy_intensity, int image_boundary_margin) { auto n_vertex = mesh.vertices_.size(); proxy_intensity.resize(n_vertex); #pragma omp parallel for schedule(static) \ num_threads(utility::EstimateMaxThreads()) for (int i = 0; i < int(n_vertex); i++) { proxy_intensity[i] = 0.0; float sum = 0.0; for (size_t iter = 0; iter < visibility_vertex_to_image[i].size(); iter++) { int j = visibility_vertex_to_image[i][iter]; float gray; bool valid = false; if (warping_fields.has_value()) { std::tie(valid, gray) = QueryImageIntensity<float>( images_gray[j], warping_fields.value()[j], mesh.vertices_[i], camera_trajectory.parameters_[j], utility::nullopt, image_boundary_margin); } else { std::tie(valid, gray) = QueryImageIntensity<float>( images_gray[j], utility::nullopt, mesh.vertices_[i], camera_trajectory.parameters_[j], utility::nullopt, image_boundary_margin); } if (valid) { sum += 1.0; proxy_intensity[i] += gray; } } if (sum > 0) { proxy_intensity[i] /= sum; } } } void SetGeometryColorAverage( geometry::TriangleMesh& mesh, const std::vector<geometry::Image>& images_color, const utility::optional<std::vector<ImageWarpingField>>& warping_fields, const camera::PinholeCameraTrajectory& camera_trajectory, const std::vector<std::vector<int>>& visibility_vertex_to_image, int image_boundary_margin, int invisible_vertex_color_knn) { size_t n_vertex = mesh.vertices_.size(); mesh.vertex_colors_.clear(); mesh.vertex_colors_.resize(n_vertex); std::vector<size_t> valid_vertices; std::vector<size_t> invalid_vertices; #pragma omp parallel for schedule(static) \ num_threads(utility::EstimateMaxThreads()) for (int i = 0; i < (int)n_vertex; i++) { mesh.vertex_colors_[i] = Eigen::Vector3d::Zero(); double sum = 0.0; for (size_t iter = 0; iter < visibility_vertex_to_image[i].size(); iter++) { int j = visibility_vertex_to_image[i][iter]; uint8_t r_temp, g_temp, b_temp; bool valid = false; utility::optional<ImageWarpingField> optional_warping_field; if (warping_fields.has_value()) { optional_warping_field = warping_fields.value()[j]; } else { optional_warping_field = utility::nullopt; } std::tie(valid, r_temp) = QueryImageIntensity<uint8_t>( images_color[j], optional_warping_field, mesh.vertices_[i], camera_trajectory.parameters_[j], 0, image_boundary_margin); std::tie(valid, g_temp) = QueryImageIntensity<uint8_t>( images_color[j], optional_warping_field, mesh.vertices_[i], camera_trajectory.parameters_[j], 1, image_boundary_margin); std::tie(valid, b_temp) = QueryImageIntensity<uint8_t>( images_color[j], optional_warping_field, mesh.vertices_[i], camera_trajectory.parameters_[j], 2, image_boundary_margin); float r = (float)r_temp / 255.0f; float g = (float)g_temp / 255.0f; float b = (float)b_temp / 255.0f; if (valid) { mesh.vertex_colors_[i] += Eigen::Vector3d(r, g, b); sum += 1.0; } } #pragma omp critical(SetGeometryColorAverage) { if (sum > 0.0) { mesh.vertex_colors_[i] /= sum; valid_vertices.push_back(i); } else { invalid_vertices.push_back(i); } } } if (invisible_vertex_color_knn > 0) { std::shared_ptr<geometry::TriangleMesh> valid_mesh = mesh.SelectByIndex(valid_vertices); geometry::KDTreeFlann kd_tree(*valid_mesh); #pragma omp parallel for schedule(static) \ num_threads(utility::EstimateMaxThreads()) for (int i = 0; i < (int)invalid_vertices.size(); ++i) { size_t invalid_vertex = invalid_vertices[i]; std::vector<int> indices; // indices to valid_mesh std::vector<double> dists; kd_tree.SearchKNN(mesh.vertices_[invalid_vertex], invisible_vertex_color_knn, indices, dists); Eigen::Vector3d new_color(0, 0, 0); for (const int& index : indices) { new_color += valid_mesh->vertex_colors_[index]; } if (indices.size() > 0) { new_color /= static_cast<double>(indices.size()); } mesh.vertex_colors_[invalid_vertex] = new_color; } } } } // namespace color_map } // namespace pipelines } // namespace open3d
44.440367
80
0.609551
[ "mesh", "geometry", "object", "vector" ]
29b14231d0552581b3fa7902980b2ff2d514a9ab
28,259
cpp
C++
lib/Bitcode/Writer/ValueEnumerator.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
lib/Bitcode/Writer/ValueEnumerator.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
lib/Bitcode/Writer/ValueEnumerator.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
//===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===// // // The LLVM37 Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ValueEnumerator class. // //===----------------------------------------------------------------------===// #include "ValueEnumerator.h" #include "llvm37/ADT/STLExtras.h" #include "llvm37/ADT/SmallPtrSet.h" #include "llvm37/IR/Constants.h" #include "llvm37/IR/DebugInfoMetadata.h" #include "llvm37/IR/DerivedTypes.h" #include "llvm37/IR/Instructions.h" #include "llvm37/IR/Module.h" #include "llvm37/IR/UseListOrder.h" #include "llvm37/IR/ValueSymbolTable.h" #include "llvm37/Support/Debug.h" #include "llvm37/Support/raw_ostream.h" #include <algorithm> using namespace llvm37; namespace { struct OrderMap { DenseMap<const Value *, std::pair<unsigned, bool>> IDs; unsigned LastGlobalConstantID; unsigned LastGlobalValueID; OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {} bool isGlobalConstant(unsigned ID) const { return ID <= LastGlobalConstantID; } bool isGlobalValue(unsigned ID) const { return ID <= LastGlobalValueID && !isGlobalConstant(ID); } unsigned size() const { return IDs.size(); } std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; } std::pair<unsigned, bool> lookup(const Value *V) const { return IDs.lookup(V); } void index(const Value *V) { // Explicitly sequence get-size and insert-value operations to avoid UB. unsigned ID = IDs.size() + 1; IDs[V].first = ID; } }; } static void orderValue(const Value *V, OrderMap &OM) { if (OM.lookup(V).first) return; if (const Constant *C = dyn_cast<Constant>(V)) if (C->getNumOperands() && !isa<GlobalValue>(C)) for (const Value *Op : C->operands()) if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) orderValue(Op, OM); // Note: we cannot cache this lookup above, since inserting into the map // changes the map's size, and thus affects the other IDs. OM.index(V); } static OrderMap orderModule(const Module &M) { // This needs to match the order used by ValueEnumerator::ValueEnumerator() // and ValueEnumerator::incorporateFunction(). OrderMap OM; // In the reader, initializers of GlobalValues are set *after* all the // globals have been read. Rather than awkwardly modeling this behaviour // directly in predictValueUseListOrderImpl(), just assign IDs to // initializers of GlobalValues before GlobalValues themselves to model this // implicitly. for (const GlobalVariable &G : M.globals()) if (G.hasInitializer()) if (!isa<GlobalValue>(G.getInitializer())) orderValue(G.getInitializer(), OM); for (const GlobalAlias &A : M.aliases()) if (!isa<GlobalValue>(A.getAliasee())) orderValue(A.getAliasee(), OM); for (const Function &F : M) { if (F.hasPrefixData()) if (!isa<GlobalValue>(F.getPrefixData())) orderValue(F.getPrefixData(), OM); if (F.hasPrologueData()) if (!isa<GlobalValue>(F.getPrologueData())) orderValue(F.getPrologueData(), OM); if (F.hasPersonalityFn()) if (!isa<GlobalValue>(F.getPersonalityFn())) orderValue(F.getPersonalityFn(), OM); } OM.LastGlobalConstantID = OM.size(); // Initializers of GlobalValues are processed in // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather // than ValueEnumerator, and match the code in predictValueUseListOrderImpl() // by giving IDs in reverse order. // // Since GlobalValues never reference each other directly (just through // initializers), their relative IDs only matter for determining order of // uses in their initializers. for (const Function &F : M) orderValue(&F, OM); for (const GlobalAlias &A : M.aliases()) orderValue(&A, OM); for (const GlobalVariable &G : M.globals()) orderValue(&G, OM); OM.LastGlobalValueID = OM.size(); for (const Function &F : M) { if (F.isDeclaration()) continue; // Here we need to match the union of ValueEnumerator::incorporateFunction() // and WriteFunction(). Basic blocks are implicitly declared before // anything else (by declaring their size). for (const BasicBlock &BB : F) orderValue(&BB, OM); for (const Argument &A : F.args()) orderValue(&A, OM); for (const BasicBlock &BB : F) for (const Instruction &I : BB) for (const Value *Op : I.operands()) if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || isa<InlineAsm>(*Op)) orderValue(Op, OM); for (const BasicBlock &BB : F) for (const Instruction &I : BB) orderValue(&I, OM); } return OM; } static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack) { // Predict use-list order for this one. typedef std::pair<const Use *, unsigned> Entry; SmallVector<Entry, 64> List; for (const Use &U : V->uses()) // Check if this user will be serialized. if (OM.lookup(U.getUser()).first) List.push_back(std::make_pair(&U, List.size())); if (List.size() < 2) // We may have lost some users. return; bool IsGlobalValue = OM.isGlobalValue(ID); std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) { const Use *LU = L.first; const Use *RU = R.first; if (LU == RU) return false; auto LID = OM.lookup(LU->getUser()).first; auto RID = OM.lookup(RU->getUser()).first; // Global values are processed in reverse order. // // Moreover, initializers of GlobalValues are set *after* all the globals // have been read (despite having earlier IDs). Rather than awkwardly // modeling this behaviour here, orderModule() has assigned IDs to // initializers of GlobalValues before GlobalValues themselves. if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID)) return LID < RID; // If ID is 4, then expect: 7 6 5 1 2 3. if (LID < RID) { if (RID <= ID) if (!IsGlobalValue) // GlobalValue uses don't get reversed. return true; return false; } if (RID < LID) { if (LID <= ID) if (!IsGlobalValue) // GlobalValue uses don't get reversed. return false; return true; } // LID and RID are equal, so we have different operands of the same user. // Assume operands are added in order for all instructions. if (LID <= ID) if (!IsGlobalValue) // GlobalValue uses don't get reversed. return LU->getOperandNo() < RU->getOperandNo(); return LU->getOperandNo() > RU->getOperandNo(); }); if (std::is_sorted( List.begin(), List.end(), [](const Entry &L, const Entry &R) { return L.second < R.second; })) // Order is already correct. return; // Store the shuffle. Stack.emplace_back(V, F, List.size()); assert(List.size() == Stack.back().Shuffle.size() && "Wrong size"); for (size_t I = 0, E = List.size(); I != E; ++I) Stack.back().Shuffle[I] = List[I].second; } static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack) { auto &IDPair = OM[V]; assert(IDPair.first && "Unmapped value"); if (IDPair.second) // Already predicted. return; // Do the actual prediction. IDPair.second = true; if (!V->use_empty() && std::next(V->use_begin()) != V->use_end()) predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack); // Recursive descent into constants. if (const Constant *C = dyn_cast<Constant>(V)) if (C->getNumOperands()) // Visit GlobalValues. for (const Value *Op : C->operands()) if (isa<Constant>(Op)) // Visit GlobalValues. predictValueUseListOrder(Op, F, OM, Stack); } static UseListOrderStack predictUseListOrder(const Module &M) { OrderMap OM = orderModule(M); // Use-list orders need to be serialized after all the users have been added // to a value, or else the shuffles will be incomplete. Store them per // function in a stack. // // Aside from function order, the order of values doesn't matter much here. UseListOrderStack Stack; // We want to visit the functions backward now so we can list function-local // constants in the last Function they're used in. Module-level constants // have already been visited above. for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) { const Function &F = *I; if (F.isDeclaration()) continue; for (const BasicBlock &BB : F) predictValueUseListOrder(&BB, &F, OM, Stack); for (const Argument &A : F.args()) predictValueUseListOrder(&A, &F, OM, Stack); for (const BasicBlock &BB : F) for (const Instruction &I : BB) for (const Value *Op : I.operands()) if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues. predictValueUseListOrder(Op, &F, OM, Stack); for (const BasicBlock &BB : F) for (const Instruction &I : BB) predictValueUseListOrder(&I, &F, OM, Stack); } // Visit globals last, since the module-level use-list block will be seen // before the function bodies are processed. for (const GlobalVariable &G : M.globals()) predictValueUseListOrder(&G, nullptr, OM, Stack); for (const Function &F : M) predictValueUseListOrder(&F, nullptr, OM, Stack); for (const GlobalAlias &A : M.aliases()) predictValueUseListOrder(&A, nullptr, OM, Stack); for (const GlobalVariable &G : M.globals()) if (G.hasInitializer()) predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack); for (const GlobalAlias &A : M.aliases()) predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack); for (const Function &F : M) { if (F.hasPrefixData()) predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack); if (F.hasPrologueData()) predictValueUseListOrder(F.getPrologueData(), nullptr, OM, Stack); if (F.hasPersonalityFn()) predictValueUseListOrder(F.getPersonalityFn(), nullptr, OM, Stack); } return Stack; } static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) { return V.first->getType()->isIntOrIntVectorTy(); } ValueEnumerator::ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder) : HasMDString(false), HasDILocation(false), HasGenericDINode(false), ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { if (ShouldPreserveUseListOrder) UseListOrders = predictUseListOrder(M); // Enumerate the global variables. for (const GlobalVariable &GV : M.globals()) EnumerateValue(&GV); // Enumerate the functions. for (const Function & F : M) { EnumerateValue(&F); EnumerateAttributes(F.getAttributes()); } // Enumerate the aliases. for (const GlobalAlias &GA : M.aliases()) EnumerateValue(&GA); // Remember what is the cutoff between globalvalue's and other constants. unsigned FirstConstant = Values.size(); // Enumerate the global variable initializers. for (const GlobalVariable &GV : M.globals()) if (GV.hasInitializer()) EnumerateValue(GV.getInitializer()); // Enumerate the aliasees. for (const GlobalAlias &GA : M.aliases()) EnumerateValue(GA.getAliasee()); // Enumerate the prefix data constants. for (const Function &F : M) if (F.hasPrefixData()) EnumerateValue(F.getPrefixData()); // Enumerate the prologue data constants. for (const Function &F : M) if (F.hasPrologueData()) EnumerateValue(F.getPrologueData()); // Enumerate the personality functions. for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) if (I->hasPersonalityFn()) EnumerateValue(I->getPersonalityFn()); // Enumerate the metadata type. // // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode // only encodes the metadata type when it's used as a value. EnumerateType(Type::getMetadataTy(M.getContext())); // Insert constants and metadata that are named at module level into the slot // pool so that the module symbol table can refer to them... EnumerateValueSymbolTable(M.getValueSymbolTable()); EnumerateNamedMetadata(M); SmallVector<std::pair<unsigned, MDNode *>, 8> MDs; // Enumerate types used by function bodies and argument lists. for (const Function &F : M) { for (const Argument &A : F.args()) EnumerateType(A.getType()); // Enumerate metadata attached to this function. F.getAllMetadata(MDs); for (const auto &I : MDs) EnumerateMetadata(I.second); for (const BasicBlock &BB : F) for (const Instruction &I : BB) { for (const Use &Op : I.operands()) { auto *MD = dyn_cast<MetadataAsValue>(&Op); if (!MD) { EnumerateOperandType(Op); continue; } // Local metadata is enumerated during function-incorporation. if (isa<LocalAsMetadata>(MD->getMetadata())) continue; EnumerateMetadata(MD->getMetadata()); } EnumerateType(I.getType()); if (const CallInst *CI = dyn_cast<CallInst>(&I)) EnumerateAttributes(CI->getAttributes()); else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) EnumerateAttributes(II->getAttributes()); // Enumerate metadata attached with this instruction. MDs.clear(); I.getAllMetadataOtherThanDebugLoc(MDs); for (unsigned i = 0, e = MDs.size(); i != e; ++i) EnumerateMetadata(MDs[i].second); // Don't enumerate the location directly -- it has a special record // type -- but enumerate its operands. if (DILocation *L = I.getDebugLoc()) EnumerateMDNodeOperands(L); } } // Optimize constant ordering. OptimizeConstants(FirstConstant, Values.size()); } unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const { InstructionMapType::const_iterator I = InstructionMap.find(Inst); assert(I != InstructionMap.end() && "Instruction is not mapped!"); return I->second; } unsigned ValueEnumerator::getComdatID(const Comdat *C) const { unsigned ComdatID = Comdats.idFor(C); assert(ComdatID && "Comdat not found!"); return ComdatID; } void ValueEnumerator::setInstructionID(const Instruction *I) { InstructionMap[I] = InstructionCount++; } unsigned ValueEnumerator::getValueID(const Value *V) const { if (auto *MD = dyn_cast<MetadataAsValue>(V)) return getMetadataID(MD->getMetadata()); ValueMapType::const_iterator I = ValueMap.find(V); assert(I != ValueMap.end() && "Value not in slotcalculator!"); return I->second-1; } void ValueEnumerator::dump() const { print(dbgs(), ValueMap, "Default"); dbgs() << '\n'; print(dbgs(), MDValueMap, "MetaData"); dbgs() << '\n'; } void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const { OS << "Map Name: " << Name << "\n"; OS << "Size: " << Map.size() << "\n"; for (ValueMapType::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I) { const Value *V = I->first; if (V->hasName()) OS << "Value: " << V->getName(); else OS << "Value: [null]\n"; V->dump(); OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):"; for (const Use &U : V->uses()) { if (&U != &*V->use_begin()) OS << ","; if(U->hasName()) OS << " " << U->getName(); else OS << " [null]"; } OS << "\n\n"; } } void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map, const char *Name) const { OS << "Map Name: " << Name << "\n"; OS << "Size: " << Map.size() << "\n"; for (auto I = Map.begin(), E = Map.end(); I != E; ++I) { const Metadata *MD = I->first; OS << "Metadata: slot = " << I->second << "\n"; MD->print(OS); } } /// OptimizeConstants - Reorder constant pool for denser encoding. void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) { if (CstStart == CstEnd || CstStart+1 == CstEnd) return; if (ShouldPreserveUseListOrder) // Optimizing constants makes the use-list order difficult to predict. // Disable it for now when trying to preserve the order. return; std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd, [this](const std::pair<const Value *, unsigned> &LHS, const std::pair<const Value *, unsigned> &RHS) { // Sort by plane. if (LHS.first->getType() != RHS.first->getType()) return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType()); // Then by frequency. return LHS.second > RHS.second; }); // Ensure that integer and vector of integer constants are at the start of the // constant pool. This is important so that GEP structure indices come before // gep constant exprs. std::partition(Values.begin()+CstStart, Values.begin()+CstEnd, isIntOrIntVectorValue); // Rebuild the modified portion of ValueMap. for (; CstStart != CstEnd; ++CstStart) ValueMap[Values[CstStart].first] = CstStart+1; } /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol /// table into the values table. void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) { for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); VI != VE; ++VI) EnumerateValue(VI->getValue()); } /// Insert all of the values referenced by named metadata in the specified /// module. void ValueEnumerator::EnumerateNamedMetadata(const Module &M) { for (Module::const_named_metadata_iterator I = M.named_metadata_begin(), E = M.named_metadata_end(); I != E; ++I) EnumerateNamedMDNode(I); } void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) { for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i) EnumerateMetadata(MD->getOperand(i)); } /// EnumerateMDNodeOperands - Enumerate all non-function-local values /// and types referenced by the given MDNode. void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) { for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { Metadata *MD = N->getOperand(i); if (!MD) continue; assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local"); EnumerateMetadata(MD); } } void ValueEnumerator::EnumerateMetadata(const Metadata *MD) { assert( (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) && "Invalid metadata kind"); // Insert a dummy ID to block the co-recursive call to // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph. // // Return early if there's already an ID. if (!MDValueMap.insert(std::make_pair(MD, 0)).second) return; // Visit operands first to minimize RAUW. if (auto *N = dyn_cast<MDNode>(MD)) EnumerateMDNodeOperands(N); else if (auto *C = dyn_cast<ConstantAsMetadata>(MD)) EnumerateValue(C->getValue()); HasMDString |= isa<MDString>(MD); HasDILocation |= isa<DILocation>(MD); HasGenericDINode |= isa<GenericDINode>(MD); // Replace the dummy ID inserted above with the correct one. MDValueMap may // have changed by inserting operands, so we need a fresh lookup here. MDs.push_back(MD); MDValueMap[MD] = MDs.size(); } /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata /// information reachable from the metadata. void ValueEnumerator::EnumerateFunctionLocalMetadata( const LocalAsMetadata *Local) { // Check to see if it's already in! unsigned &MDValueID = MDValueMap[Local]; if (MDValueID) return; MDs.push_back(Local); MDValueID = MDs.size(); EnumerateValue(Local->getValue()); // Also, collect all function-local metadata for easy access. FunctionLocalMDs.push_back(Local); } void ValueEnumerator::EnumerateValue(const Value *V) { assert(!V->getType()->isVoidTy() && "Can't insert void values!"); assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!"); // Check to see if it's already in! unsigned &ValueID = ValueMap[V]; if (ValueID) { // Increment use count. Values[ValueID-1].second++; return; } if (auto *GO = dyn_cast<GlobalObject>(V)) if (const Comdat *C = GO->getComdat()) Comdats.insert(C); // Enumerate the type of this value. EnumerateType(V->getType()); if (const Constant *C = dyn_cast<Constant>(V)) { if (isa<GlobalValue>(C)) { // Initializers for globals are handled explicitly elsewhere. } else if (C->getNumOperands()) { // If a constant has operands, enumerate them. This makes sure that if a // constant has uses (for example an array of const ints), that they are // inserted also. // We prefer to enumerate them with values before we enumerate the user // itself. This makes it more likely that we can avoid forward references // in the reader. We know that there can be no cycles in the constants // graph that don't go through a global variable. for (User::const_op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress. EnumerateValue(*I); // Finally, add the value. Doing this could make the ValueID reference be // dangling, don't reuse it. Values.push_back(std::make_pair(V, 1U)); ValueMap[V] = Values.size(); return; } } // Add the value. Values.push_back(std::make_pair(V, 1U)); ValueID = Values.size(); } void ValueEnumerator::EnumerateType(Type *Ty) { unsigned *TypeID = &TypeMap[Ty]; // We've already seen this type. if (*TypeID) return; // If it is a non-anonymous struct, mark the type as being visited so that we // don't recursively visit it. This is safe because we allow forward // references of these in the bitcode reader. if (StructType *STy = dyn_cast<StructType>(Ty)) if (!STy->isLiteral()) *TypeID = ~0U; // Enumerate all of the subtypes before we enumerate this type. This ensures // that the type will be enumerated in an order that can be directly built. for (Type *SubTy : Ty->subtypes()) EnumerateType(SubTy); // Refresh the TypeID pointer in case the table rehashed. TypeID = &TypeMap[Ty]; // Check to see if we got the pointer another way. This can happen when // enumerating recursive types that hit the base case deeper than they start. // // If this is actually a struct that we are treating as forward ref'able, // then emit the definition now that all of its contents are available. if (*TypeID && *TypeID != ~0U) return; // Add this type now that its contents are all happily enumerated. Types.push_back(Ty); *TypeID = Types.size(); } // Enumerate the types for the specified value. If the value is a constant, // walk through it, enumerating the types of the constant. void ValueEnumerator::EnumerateOperandType(const Value *V) { EnumerateType(V->getType()); if (auto *MD = dyn_cast<MetadataAsValue>(V)) { assert(!isa<LocalAsMetadata>(MD->getMetadata()) && "Function-local metadata should be left for later"); EnumerateMetadata(MD->getMetadata()); return; } const Constant *C = dyn_cast<Constant>(V); if (!C) return; // If this constant is already enumerated, ignore it, we know its type must // be enumerated. if (ValueMap.count(C)) return; // This constant may have operands, make sure to enumerate the types in // them. for (const Value *Op : C->operands()) { // Don't enumerate basic blocks here, this happens as operands to // blockaddress. if (isa<BasicBlock>(Op)) continue; EnumerateOperandType(Op); } } void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) { if (PAL.isEmpty()) return; // null is always 0. // Do a lookup. unsigned &Entry = AttributeMap[PAL]; if (Entry == 0) { // Never saw this before, add it. Attribute.push_back(PAL); Entry = Attribute.size(); } // Do lookups for all attribute groups. for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) { AttributeSet AS = PAL.getSlotAttributes(i); unsigned &Entry = AttributeGroupMap[AS]; if (Entry == 0) { AttributeGroups.push_back(AS); Entry = AttributeGroups.size(); } } } void ValueEnumerator::incorporateFunction(const Function &F) { InstructionCount = 0; NumModuleValues = Values.size(); NumModuleMDs = MDs.size(); // Adding function arguments to the value table. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) EnumerateValue(I); FirstFuncConstantID = Values.size(); // Add all function-level constants to the value table. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) { if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) || isa<InlineAsm>(*OI)) EnumerateValue(*OI); } BasicBlocks.push_back(BB); ValueMap[BB] = BasicBlocks.size(); } // Optimize the constant layout. OptimizeConstants(FirstFuncConstantID, Values.size()); // Add the function's parameter attributes so they are available for use in // the function's instruction. EnumerateAttributes(F.getAttributes()); FirstInstID = Values.size(); SmallVector<LocalAsMetadata *, 8> FnLocalMDVector; // Add all of the instructions. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) { for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) { if (auto *MD = dyn_cast<MetadataAsValue>(&*OI)) if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata())) // Enumerate metadata after the instructions they might refer to. FnLocalMDVector.push_back(Local); } if (!I->getType()->isVoidTy()) EnumerateValue(I); } } // Add all of the function-local metadata. for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) EnumerateFunctionLocalMetadata(FnLocalMDVector[i]); } void ValueEnumerator::purgeFunction() { /// Remove purged values from the ValueMap. for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i) ValueMap.erase(Values[i].first); for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i) MDValueMap.erase(MDs[i]); for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i) ValueMap.erase(BasicBlocks[i]); Values.resize(NumModuleValues); MDs.resize(NumModuleMDs); BasicBlocks.clear(); FunctionLocalMDs.clear(); } static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, DenseMap<const BasicBlock*, unsigned> &IDMap) { unsigned Counter = 0; for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) IDMap[BB] = ++Counter; } /// getGlobalBasicBlockID - This returns the function-specific ID for the /// specified basic block. This is relatively expensive information, so it /// should only be used by rare constructs such as address-of-label. unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const { unsigned &Idx = GlobalBasicBlockIDs[BB]; if (Idx != 0) return Idx-1; IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs); return getGlobalBasicBlockID(BB); } uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const { return Log2_32_Ceil(getTypes().size() + 1); }
34.504274
80
0.648395
[ "vector", "model" ]
29b3d7ea1398d55d66a1be8355b9e0295033382a
10,406
cc
C++
phrasinator/gibbs_train_plm.cc
agesmundo/FasterCubePruning
f80150140b5273fd1eb0dfb34bdd789c4cbd35e6
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2019-06-03T00:44:01.000Z
2019-06-03T00:44:01.000Z
phrasinator/gibbs_train_plm.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
null
null
null
phrasinator/gibbs_train_plm.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2021-02-19T12:44:54.000Z
2021-02-19T12:44:54.000Z
#include <iostream> #include <tr1/memory> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "filelib.h" #include "dict.h" #include "sampler.h" #include "ccrp.h" using namespace std; using namespace std::tr1; namespace po = boost::program_options; Dict d; // global dictionary string Join(char joiner, const vector<int>& phrase) { ostringstream os; for (int i = 0; i < phrase.size(); ++i) { if (i > 0) os << joiner; os << d.Convert(phrase[i]); } return os.str(); } ostream& operator<<(ostream& os, const vector<int>& phrase) { for (int i = 0; i < phrase.size(); ++i) os << (i == 0 ? "" : " ") << d.Convert(phrase[i]); return os; } struct UnigramLM { explicit UnigramLM(const string& fname) { ifstream in(fname.c_str()); assert(in); } double logprob(int word) const { assert(word < freqs_.size()); return freqs_[word]; } vector<double> freqs_; }; void InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples") ("input,i",po::value<string>(),"Read file from") ("random_seed,S",po::value<uint32_t>(), "Random seed") ("write_cdec_grammar,g", po::value<string>(), "Write cdec grammar to this file") ("write_cdec_weights,w", po::value<string>(), "Write cdec weights to this file") ("poisson_length,p", "Use a Poisson distribution as the length of a phrase in the base distribuion") ("no_hyperparameter_inference,N", "Disable hyperparameter inference"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help") || (conf->count("input") == 0)) { cerr << dcmdline_options << endl; exit(1); } } void ReadCorpus(const string& filename, vector<vector<int> >* c, set<int>* vocab) { c->clear(); istream* in; if (filename == "-") in = &cin; else in = new ifstream(filename.c_str()); assert(*in); string line; while(*in) { getline(*in, line); if (line.empty() && !*in) break; c->push_back(vector<int>()); vector<int>& v = c->back(); d.ConvertWhitespaceDelimitedLine(line, &v); for (int i = 0; i < v.size(); ++i) vocab->insert(v[i]); } if (in != &cin) delete in; } double log_poisson(unsigned x, const double& lambda) { assert(lambda > 0.0); return log(lambda) * x - lgamma(x + 1) - lambda; } struct UniphraseLM { UniphraseLM(const vector<vector<int> >& corpus, const set<int>& vocab, const po::variables_map& conf) : phrases_(1,1,1,1), gen_(1,1,1,1), corpus_(corpus), uniform_word_(1.0 / vocab.size()), gen_p0_(0.5), p_end_(0.5), use_poisson_(conf.count("poisson_length") > 0) {} double p0(const vector<int>& phrase) const { static vector<double> p0s(10000, 0.0); assert(phrase.size() < 10000); double& p = p0s[phrase.size()]; if (p) return p; p = exp(log_p0(phrase)); if (!p) { cerr << "0 prob phrase: " << phrase << "\nAssigning std::numeric_limits<double>::min()\n"; p = std::numeric_limits<double>::min(); } return p; } double log_p0(const vector<int>& phrase) const { double len_logprob; if (use_poisson_) len_logprob = log_poisson(phrase.size(), 1.0); else len_logprob = log(1 - p_end_) * (phrase.size() -1) + log(p_end_); return log(uniform_word_) * phrase.size() + len_logprob; } double llh() const { double llh = gen_.log_crp_prob(); llh += gen_.num_tables(false) * log(gen_p0_) + gen_.num_tables(true) * log(1 - gen_p0_); double llhr = phrases_.log_crp_prob(); for (CCRP<vector<int> >::const_iterator it = phrases_.begin(); it != phrases_.end(); ++it) { llhr += phrases_.num_tables(it->first) * log_p0(it->first); //llhr += log_p0(it->first); if (!isfinite(llh)) { cerr << it->first << endl; cerr << log_p0(it->first) << endl; abort(); } } return llh + llhr; } void Sample(unsigned int samples, bool hyp_inf, MT19937* rng) { cerr << "Initializing...\n"; z_.resize(corpus_.size()); int tc = 0; for (int i = 0; i < corpus_.size(); ++i) { const vector<int>& line = corpus_[i]; const int ls = line.size(); const int last_pos = ls - 1; vector<bool>& z = z_[i]; z.resize(ls); int prev = 0; for (int j = 0; j < ls; ++j) { z[j] = rng->next() < 0.5; if (j == last_pos) z[j] = true; // break phrase at the end of the sentence if (z[j]) { const vector<int> p(line.begin() + prev, line.begin() + j + 1); phrases_.increment(p, p0(p), rng); //cerr << p << ": " << p0(p) << endl; prev = j + 1; gen_.increment(false, gen_p0_, rng); ++tc; // remove } } ++tc; gen_.increment(true, 1.0 - gen_p0_, rng); // end of utterance } cerr << "TC: " << tc << endl; cerr << "Initial LLH: " << llh() << endl; cerr << "Sampling...\n"; cerr << gen_ << endl; for (int s = 1; s < samples; ++s) { cerr << '.'; if (s % 10 == 0) { cerr << " [" << s; if (hyp_inf) ResampleHyperparameters(rng); cerr << " LLH=" << llh() << "]\n"; vector<int> z(z_[0].size(), 0); //for (int j = 0; j < z.size(); ++j) z[j] = z_[0][j]; //SegCorpus::Write(corpus_[0], z, d); } for (int i = 0; i < corpus_.size(); ++i) { const vector<int>& line = corpus_[i]; const int ls = line.size(); const int last_pos = ls - 1; vector<bool>& z = z_[i]; int prev = 0; for (int j = 0; j < last_pos; ++j) { // don't resample last position int next = j+1; while(!z[next]) { ++next; } const vector<int> p1p2(line.begin() + prev, line.begin() + next + 1); const vector<int> p1(line.begin() + prev, line.begin() + j + 1); const vector<int> p2(line.begin() + j + 1, line.begin() + next + 1); if (z[j]) { phrases_.decrement(p1, rng); phrases_.decrement(p2, rng); gen_.decrement(false, rng); gen_.decrement(false, rng); } else { phrases_.decrement(p1p2, rng); gen_.decrement(false, rng); } const double d1 = phrases_.prob(p1p2, p0(p1p2)) * gen_.prob(false, gen_p0_); double d2 = phrases_.prob(p1, p0(p1)) * gen_.prob(false, gen_p0_); phrases_.increment(p1, p0(p1), rng); gen_.increment(false, gen_p0_, rng); d2 *= phrases_.prob(p2, p0(p2)) * gen_.prob(false, gen_p0_); phrases_.decrement(p1, rng); gen_.decrement(false, rng); z[j] = rng->SelectSample(d1, d2); if (z[j]) { phrases_.increment(p1, p0(p1), rng); phrases_.increment(p2, p0(p2), rng); gen_.increment(false, gen_p0_, rng); gen_.increment(false, gen_p0_, rng); prev = j + 1; } else { phrases_.increment(p1p2, p0(p1p2), rng); gen_.increment(false, gen_p0_, rng); } } } } // cerr << endl << endl << gen_ << endl << phrases_ << endl; cerr << gen_.prob(false, gen_p0_) << " " << gen_.prob(true, 1 - gen_p0_) << endl; } void WriteCdecGrammarForCurrentSample(ostream* os) const { CCRP<vector<int> >::const_iterator it = phrases_.begin(); for (; it != phrases_.end(); ++it) { (*os) << "[X] ||| " << Join(' ', it->first) << " ||| " << Join('_', it->first) << " ||| C=1 P=" << log(phrases_.prob(it->first, p0(it->first))) << endl; } } double OOVUnigramLogProb() const { vector<int> x(1,99999999); return log(phrases_.prob(x, p0(x))); } void ResampleHyperparameters(MT19937* rng) { phrases_.resample_hyperparameters(rng); gen_.resample_hyperparameters(rng); cerr << " d=" << phrases_.discount() << ",c=" << phrases_.concentration(); } CCRP<vector<int> > phrases_; CCRP<bool> gen_; vector<vector<bool> > z_; // z_[i] is there a phrase boundary after the ith word const vector<vector<int> >& corpus_; const double uniform_word_; const double gen_p0_; const double p_end_; // in base length distribution, p of the end of a phrase const bool use_poisson_; }; int main(int argc, char** argv) { po::variables_map conf; InitCommandLine(argc, argv, &conf); shared_ptr<MT19937> prng; if (conf.count("random_seed")) prng.reset(new MT19937(conf["random_seed"].as<uint32_t>())); else prng.reset(new MT19937); MT19937& rng = *prng; vector<vector<int> > corpus; set<int> vocab; ReadCorpus(conf["input"].as<string>(), &corpus, &vocab); cerr << "Corpus size: " << corpus.size() << " sentences\n"; cerr << "Vocabulary size: " << vocab.size() << " types\n"; UniphraseLM ulm(corpus, vocab, conf); ulm.Sample(conf["samples"].as<unsigned>(), conf.count("no_hyperparameter_inference") == 0, &rng); cerr << "OOV unigram prob: " << ulm.OOVUnigramLogProb() << endl; for (int i = 0; i < corpus.size(); ++i) // SegCorpus::Write(corpus[i], shmmlm.z_[i], d); ; if (conf.count("write_cdec_grammar")) { string fname = conf["write_cdec_grammar"].as<string>(); cerr << "Writing model to " << fname << " ...\n"; WriteFile wf(fname); ulm.WriteCdecGrammarForCurrentSample(wf.stream()); } if (conf.count("write_cdec_weights")) { string fname = conf["write_cdec_weights"].as<string>(); cerr << "Writing weights to " << fname << " .\n"; WriteFile wf(fname); ostream& os = *wf.stream(); os << "# make C smaller to use more phrases\nP 1\nPassThrough " << ulm.OOVUnigramLogProb() << "\nC -3\n"; } return 0; }
32.93038
109
0.573707
[ "vector", "model" ]
29bd10d55115b18b71fdcc5be270b98e5bb2808e
13,080
cc
C++
encoder/optimize_rlefont.cc
aliansari91/mcufont
538d17aa6fa889128282028b33633ecf93a5867b
[ "MIT" ]
null
null
null
encoder/optimize_rlefont.cc
aliansari91/mcufont
538d17aa6fa889128282028b33633ecf93a5867b
[ "MIT" ]
null
null
null
encoder/optimize_rlefont.cc
aliansari91/mcufont
538d17aa6fa889128282028b33633ecf93a5867b
[ "MIT" ]
null
null
null
#include "optimize_rlefont.hh" #include "encode_rlefont.hh" #include <random> #include <iostream> #include <set> #include <thread> #include <algorithm> namespace mcufont { namespace rlefont { typedef std::mt19937 rnd_t; // Select a random substring among all the glyphs in the datafile. std::unique_ptr<DataFile::pixels_t> random_substring(const DataFile &datafile, rnd_t &rnd) { std::uniform_int_distribution<size_t> dist1(0, datafile.GetGlyphCount() - 1); size_t index = dist1(rnd); const DataFile::pixels_t &pixels = datafile.GetGlyphEntry(index).data; std::uniform_int_distribution<size_t> dist2(2, pixels.size()); size_t length = dist2(rnd); std::uniform_int_distribution<size_t> dist3(0, pixels.size() - length); size_t start = dist3(rnd); std::unique_ptr<DataFile::pixels_t> result; result.reset(new DataFile::pixels_t(pixels.begin() + start, pixels.begin() + start + length)); return result; } // Try to replace the worst dictionary entry with a better one. void optimize_worst(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { std::uniform_int_distribution<size_t> dist(0, 1); DataFile trial = datafile; size_t worst = trial.GetLowScoreIndex(); DataFile::dictentry_t d = trial.GetDictionaryEntry(worst); d.replacement = *random_substring(datafile, rnd); d.ref_encode = dist(rnd); trial.SetDictionaryEntry(worst, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(worst, d); size = newsize; if (verbose) std::cout << "optimize_worst: replaced " << worst << " score " << d.score << std::endl; } } // Try to replace random dictionary entry with another one. void optimize_any(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { DataFile trial = datafile; std::uniform_int_distribution<size_t> dist(0, DataFile::dictionarysize - 1); size_t index = dist(rnd); DataFile::dictentry_t d = trial.GetDictionaryEntry(index); d.replacement = *random_substring(datafile, rnd); trial.SetDictionaryEntry(index, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(index, d); size = newsize; if (verbose) std::cout << "optimize_any: replaced " << index << " score " << d.score << std::endl; } } // Try to append or prepend random dictionary entry. void optimize_expand(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose, bool binary_only) { DataFile trial = datafile; std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1); size_t index = dist1(rnd); DataFile::dictentry_t d = trial.GetDictionaryEntry(index); std::uniform_int_distribution<size_t> dist3(1, 3); size_t count = dist3(rnd); for (size_t i = 0; i < count; i++) { std::uniform_int_distribution<size_t> booldist(0, 1); std::uniform_int_distribution<size_t> pixeldist(0, 15); uint8_t pixel; if (binary_only) { pixel = booldist(rnd) ? 15 : 0; } else { pixel = pixeldist(rnd); } bool prepend = booldist(rnd); if (prepend) { d.replacement.insert(d.replacement.begin(), pixel); } else { d.replacement.push_back(pixel); } } trial.SetDictionaryEntry(index, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(index, d); size = newsize; if (verbose) std::cout << "optimize_expand: expanded " << index << " by " << count << " pixels, score " << d.score << std::endl; } } // Try to trim random dictionary entry. void optimize_trim(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { DataFile trial = datafile; std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1); size_t index = dist1(rnd); DataFile::dictentry_t d = trial.GetDictionaryEntry(index); if (d.replacement.size() <= 2) return; std::uniform_int_distribution<size_t> dist2(0, std::min((int)d.replacement.size() / 2, 5)); size_t start = dist2(rnd); size_t end = dist2(rnd); if (start) { d.replacement.erase(d.replacement.begin(), d.replacement.begin() + start); } if (end) { d.replacement.erase(d.replacement.end() - end, d.replacement.end() - 1); } trial.SetDictionaryEntry(index, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(index, d); size = newsize; if (verbose) std::cout << "optimize_trim: trimmed " << index << " by " << start << " pixels from start and " << end << " pixels from end, score " << d.score << std::endl; } } // Switch random dictionary entry to use ref encoding or back to rle. void optimize_refdict(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { DataFile trial = datafile; std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1); size_t index = dist1(rnd); DataFile::dictentry_t d = trial.GetDictionaryEntry(index); d.ref_encode = !d.ref_encode; trial.SetDictionaryEntry(index, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(index, d); size = newsize; if (verbose) std::cout << "optimize_refdict: switched " << index << " to " << (d.ref_encode ? "ref" : "RLE") << ", score " << d.score << std::endl; } } // Combine two random dictionary entries. void optimize_combine(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { DataFile trial = datafile; std::uniform_int_distribution<size_t> dist1(0, DataFile::dictionarysize - 1); size_t worst = datafile.GetLowScoreIndex(); size_t index1 = dist1(rnd); size_t index2 = dist1(rnd); const DataFile::pixels_t &part1 = datafile.GetDictionaryEntry(index1).replacement; const DataFile::pixels_t &part2 = datafile.GetDictionaryEntry(index2).replacement; DataFile::dictentry_t d; d.replacement = part1; d.replacement.insert(d.replacement.end(), part2.begin(), part2.end()); d.ref_encode = true; trial.SetDictionaryEntry(worst, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(worst, d); size = newsize; if (verbose) std::cout << "optimize_combine: combined " << index1 << " and " << index2 << " to replace " << worst << ", score " << d.score << std::endl; } } // Pick a random part of an encoded glyph and encode it as a ref dict. void optimize_encpart(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { std::unique_ptr<encoded_font_t> e = encode_font(datafile); // Pick a random encoded glyph std::uniform_int_distribution<size_t> dist1(0, datafile.GetGlyphCount() - 1); size_t index = dist1(rnd); const encoded_font_t::refstring_t &refstr = e->glyphs.at(index); if (refstr.size() < 2) return; // Pick a random part of it std::uniform_int_distribution<size_t> dist2(2, refstr.size()); size_t length = dist2(rnd); std::uniform_int_distribution<size_t> dist3(0, refstr.size() - length); size_t start = dist3(rnd); // Decode that part encoded_font_t::refstring_t substr(refstr.begin() + start, refstr.begin() + start + length); std::unique_ptr<DataFile::pixels_t> decoded = decode_glyph(*e, substr, datafile.GetFontInfo()); // Add that as a new dictionary entry DataFile trial = datafile; size_t worst = trial.GetLowScoreIndex(); DataFile::dictentry_t d = trial.GetDictionaryEntry(worst); d.replacement = *decoded; d.ref_encode = true; trial.SetDictionaryEntry(worst, d); size_t newsize = get_encoded_size(trial); if (newsize < size) { d.score = size - newsize; datafile.SetDictionaryEntry(worst, d); size = newsize; if (verbose) std::cout << "optimize_encpart: replaced " << worst << " score " << d.score << std::endl; } } // Execute all the optimization algorithms once. void optimize_pass(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose) { optimize_worst(datafile, size, rnd, verbose); optimize_any(datafile, size, rnd, verbose); optimize_expand(datafile, size, rnd, verbose, false); optimize_expand(datafile, size, rnd, verbose, true); optimize_trim(datafile, size, rnd, verbose); optimize_refdict(datafile, size, rnd, verbose); optimize_combine(datafile, size, rnd, verbose); optimize_encpart(datafile, size, rnd, verbose); } // Execute multiple passes in parallel and take the one with the best result. // The amount of parallelism is hardcoded in order to retain deterministic // behaviour. void optimize_parallel(DataFile &datafile, size_t &size, rnd_t &rnd, bool verbose, int num_threads = 4) { std::vector<DataFile> datafiles; std::vector<size_t> sizes; std::vector<rnd_t> rnds; std::vector<std::unique_ptr<std::thread> > threads; for (int i = 0; i < num_threads; i++) { datafiles.emplace_back(datafile); sizes.emplace_back(size); rnds.emplace_back(rnd()); } for (int i = 0; i < num_threads; i++) { threads.emplace_back(new std::thread(optimize_pass, std::ref(datafiles.at(i)), std::ref(sizes.at(i)), std::ref(rnds.at(i)), verbose)); } for (int i = 0; i < num_threads; i++) { threads.at(i)->join(); } int best = std::min_element(sizes.begin(), sizes.end()) - sizes.begin(); size = sizes.at(best); datafile = datafiles.at(best); } // Go through all the dictionary entries and check what it costs to remove // them. Removes any entries with negative or zero score. void update_scores(DataFile &datafile, bool verbose) { size_t oldsize = get_encoded_size(datafile); for (size_t i = 0; i < DataFile::dictionarysize; i++) { DataFile trial = datafile; DataFile::dictentry_t dummy = {}; trial.SetDictionaryEntry(i, dummy); size_t newsize = get_encoded_size(trial); DataFile::dictentry_t d = datafile.GetDictionaryEntry(i); d.score = newsize - oldsize; if (d.score > 0) { datafile.SetDictionaryEntry(i, d); } else { datafile.SetDictionaryEntry(i, dummy); if (verbose && d.replacement.size() != 0) std::cout << "update_scores: dropped " << i << " score " << -d.score << std::endl; } } } void init_dictionary(DataFile &datafile) { rnd_t rnd(datafile.GetSeed()); if (datafile.GetGlyphCount() == 0) return; std::set<DataFile::pixels_t> seen_substrings; std::set<DataFile::pixels_t> added_substrings; size_t i = 0; while (i < DataFile::dictionarysize) { DataFile::pixels_t substring = *random_substring(datafile, rnd); if (!seen_substrings.count(substring)) { seen_substrings.insert(substring); } else if (!added_substrings.count(substring)) { // When we see a substring second time, add it. DataFile::dictentry_t d; d.score = 0; d.replacement = substring; datafile.SetDictionaryEntry(i, d); i++; added_substrings.insert(substring); } } } void optimize(DataFile &datafile, size_t iterations) { bool verbose = false; rnd_t rnd(datafile.GetSeed()); update_scores(datafile, verbose); size_t size = get_encoded_size(datafile); for (size_t i = 0; i < iterations; i++) { optimize_parallel(datafile, size, rnd, verbose); } std::uniform_int_distribution<size_t> dist(0, std::numeric_limits<uint32_t>::max()); datafile.SetSeed(dist(rnd)); } }}
31.366906
103
0.599235
[ "vector" ]
29c06c7493409f930dce0666881e105279365bc9
1,265
cc
C++
src/p566.reshapeTheMatrix.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
src/p566.reshapeTheMatrix.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
src/p566.reshapeTheMatrix.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=566 lang=cpp * * [566] Reshape the Matrix */ #include <vector> using namespace std; // @lc code=start class Solution { public: auto matrixReshape(vector<vector<int>> const& nums, int r, int c) -> vector<vector<int>> { auto const row = nums.size(); auto const column = nums[0].size(); if (r * c != row * column) { return nums; } if (r == row && c == column) { return nums; } vector<vector<int>> result(r, vector<int>(c, 0)); for (size_t i = 0; i < r; ++i) { for (size_t j = 0; j < c; ++j) { auto const index = i * c + j; auto const o_r = index / column; auto const o_c = index % column; result[i][j] = nums[o_r][o_c]; } } return result; } }; // @lc code=end #include <iostream> #include "vectorfmt.hh" auto main(int argc, char const* argv[]) -> int { Solution s; cout << s.matrixReshape({{1, 2, 3, 4}}, 2, 2) << endl; cout << s.matrixReshape({{1, 2, 3, 4}}, 5, 5) << endl; cout << s.matrixReshape({{1, 2}, {3, 4}}, 1, 4) << endl; cout << s.matrixReshape({{1, 2}, {3, 4}}, 4, 1) << endl; return 0; }
23.425926
94
0.484585
[ "vector" ]
29cccad5afc8e3c20d2fb3363617c19e6eeb9ad2
1,006
hpp
C++
vm/gpu/gpu.hpp
lukka/yagbe
8f66d55f455e8a13db84cd521eabb498a1165f44
[ "MIT" ]
1
2018-06-10T14:45:53.000Z
2018-06-10T14:45:53.000Z
vm/gpu/gpu.hpp
Kaosumaru/yagbe
13a2dea9dd50ae4b548bec3704fdc88c2a48d956
[ "MIT" ]
1
2020-02-16T02:50:36.000Z
2020-02-24T20:50:38.000Z
vm/gpu/gpu.hpp
lukka/yagbe
8f66d55f455e8a13db84cd521eabb498a1165f44
[ "MIT" ]
1
2020-02-16T00:36:38.000Z
2020-02-16T00:36:38.000Z
#pragma once #include <cstdint> #include <array> #include <vector> #include <functional> #include "gpu_base.hpp" #include "tilemap.hpp" #include "spritemap.hpp" #include "vm/utils.hpp" namespace yagbe { class gpu : public gpu_base { public: gpu(memory &m, interrupts &i) : gpu_base(m, i) {} std::function<void(const std::vector<color>&)> onFrameReady; protected: void push_screen() override { //push buffer to a renderer if (onFrameReady) onFrameReady(_buffer); } void render_scanline() override { auto y = line(); auto line_address = _buffer.data() + y * screen_size().x; _tilemap.render_scanline(line_address, y, screen_size().x); _spritemap.render_scanline(line_address, y, screen_size().x); } tilemap _tilemap { _m }; //handles BG & WINDOW spritemap _spritemap { _m, _tilemap }; //handles OBJ std::vector<color> _buffer { (std::size_t) screen_size().x * screen_size().y }; //output buffer with frame data, provided in onFrameReady }; };
20.958333
139
0.683897
[ "vector" ]
29cde124642b0546d8fb0710131cfd365f88113b
5,557
cc
C++
source/extensions/upstreams/http/config.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
3
2021-08-19T18:42:11.000Z
2022-02-20T10:31:30.000Z
source/extensions/upstreams/http/config.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
312
2021-04-19T01:53:05.000Z
2022-03-28T08:28:56.000Z
source/extensions/upstreams/http/config.cc
guillaumerosinosky/envoy
2cc9b69f28caa34bd0bc0d4371b669f027807ccd
[ "Apache-2.0" ]
2
2019-10-17T01:25:13.000Z
2021-09-13T16:25:11.000Z
#include "source/extensions/upstreams/http/config.h" #include <chrono> #include <memory> #include <string> #include <vector> #include "envoy/config/cluster/v3/cluster.pb.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/upstream/upstream.h" #include "source/common/config/utility.h" #include "source/common/http/http1/settings.h" #include "source/common/http/utility.h" #include "source/common/protobuf/utility.h" namespace Envoy { namespace Extensions { namespace Upstreams { namespace Http { namespace { const envoy::config::core::v3::Http1ProtocolOptions& getHttpOptions(const envoy::extensions::upstreams::http::v3::HttpProtocolOptions& options) { if (options.has_use_downstream_protocol_config()) { return options.use_downstream_protocol_config().http_protocol_options(); } if (options.has_auto_config()) { return options.auto_config().http_protocol_options(); } return options.explicit_http_config().http_protocol_options(); } const envoy::config::core::v3::Http2ProtocolOptions& getHttp2Options(const envoy::extensions::upstreams::http::v3::HttpProtocolOptions& options) { if (options.has_use_downstream_protocol_config()) { return options.use_downstream_protocol_config().http2_protocol_options(); } if (options.has_auto_config()) { return options.auto_config().http2_protocol_options(); } return options.explicit_http_config().http2_protocol_options(); } const envoy::config::core::v3::Http3ProtocolOptions& getHttp3Options(const envoy::extensions::upstreams::http::v3::HttpProtocolOptions& options) { if (options.has_use_downstream_protocol_config() && options.use_downstream_protocol_config().has_http3_protocol_options()) { return options.use_downstream_protocol_config().http3_protocol_options(); } if (options.has_auto_config()) { return options.auto_config().http3_protocol_options(); } return options.explicit_http_config().http3_protocol_options(); } } // namespace uint64_t ProtocolOptionsConfigImpl::parseFeatures(const envoy::config::cluster::v3::Cluster& config, const ProtocolOptionsConfigImpl& options) { uint64_t features = 0; if (options.use_http2_) { features |= Upstream::ClusterInfo::Features::HTTP2; } if (options.use_http3_) { features |= Upstream::ClusterInfo::Features::HTTP3; } if (options.use_downstream_protocol_) { features |= Upstream::ClusterInfo::Features::USE_DOWNSTREAM_PROTOCOL; } if (options.use_alpn_) { features |= Upstream::ClusterInfo::Features::USE_ALPN; } if (config.close_connections_on_host_health_failure()) { features |= Upstream::ClusterInfo::Features::CLOSE_CONNECTIONS_ON_HOST_HEALTH_FAILURE; } return features; } ProtocolOptionsConfigImpl::ProtocolOptionsConfigImpl( const envoy::extensions::upstreams::http::v3::HttpProtocolOptions& options, ProtobufMessage::ValidationVisitor& validation_visitor) : http1_settings_( Envoy::Http::Http1::parseHttp1Settings(getHttpOptions(options), validation_visitor)), http2_options_(Http2::Utility::initializeAndValidateOptions(getHttp2Options(options))), http3_options_(getHttp3Options(options)), common_http_protocol_options_(options.common_http_protocol_options()), upstream_http_protocol_options_( options.has_upstream_http_protocol_options() ? absl::make_optional<envoy::config::core::v3::UpstreamHttpProtocolOptions>( options.upstream_http_protocol_options()) : absl::nullopt) { if (options.has_explicit_http_config()) { if (options.explicit_http_config().has_http3_protocol_options()) { use_http3_ = true; } else if (options.explicit_http_config().has_http2_protocol_options()) { use_http2_ = true; } } if (options.has_use_downstream_protocol_config()) { if (options.use_downstream_protocol_config().has_http3_protocol_options()) { use_http3_ = true; } if (options.use_downstream_protocol_config().has_http2_protocol_options()) { use_http2_ = true; } use_downstream_protocol_ = true; } if (options.has_auto_config()) { use_http2_ = true; use_alpn_ = true; use_http3_ = options.auto_config().has_http3_protocol_options(); if (options.auto_config().has_alternate_protocols_cache_options()) { alternate_protocol_cache_options_ = options.auto_config().alternate_protocols_cache_options(); } } } ProtocolOptionsConfigImpl::ProtocolOptionsConfigImpl( const envoy::config::core::v3::Http1ProtocolOptions& http1_settings, const envoy::config::core::v3::Http2ProtocolOptions& http2_options, const envoy::config::core::v3::HttpProtocolOptions& common_options, const absl::optional<envoy::config::core::v3::UpstreamHttpProtocolOptions> upstream_options, bool use_downstream_protocol, bool use_http2, ProtobufMessage::ValidationVisitor& validation_visitor) : http1_settings_(Envoy::Http::Http1::parseHttp1Settings(http1_settings, validation_visitor)), http2_options_(Http2::Utility::initializeAndValidateOptions(http2_options)), common_http_protocol_options_(common_options), upstream_http_protocol_options_(upstream_options), use_downstream_protocol_(use_downstream_protocol), use_http2_(use_http2) {} REGISTER_FACTORY(ProtocolOptionsConfigFactory, Server::Configuration::ProtocolOptionsFactory){ "envoy.upstreams.http.http_protocol_options"}; } // namespace Http } // namespace Upstreams } // namespace Extensions } // namespace Envoy
39.978417
100
0.754724
[ "vector" ]
29cef288b976ca53d8dfc99fb669a1cc2210d2e8
15,211
hpp
C++
src/frovedis/ml/glm/ridge_regression_with_lbfgs.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
src/frovedis/ml/glm/ridge_regression_with_lbfgs.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
src/frovedis/ml/glm/ridge_regression_with_lbfgs.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#ifndef _RIDGE_LBFGS_HPP_ #define _RIDGE_LBFGS_HPP_ #include "lbfgs_parallelizer.hpp" namespace frovedis { class ridge_regression_with_lbfgs { public: template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>& data, dvector<T>& label, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>&& data, dvector<T>& label, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>&& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>&& data, dvector<T>& label, linear_regression_model<T>& lrm, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T, class I, class O> static linear_regression_model<T> train ( crs_matrix<T,I,O>& data, dvector<T>& label, linear_regression_model<T>& lrm, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID, #else MatType mType = CRS, #endif bool inputMovable=false ); // --- dense support --- template <class T> static linear_regression_model<T> train ( rowmajor_matrix<T>& data, dvector<T>& label, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T> static linear_regression_model<T> train ( rowmajor_matrix<T>& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T> static linear_regression_model<T> train ( const colmajor_matrix<T>& data, dvector<T>& label, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T> static linear_regression_model<T> train ( const colmajor_matrix<T>& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID #else MatType mType = CRS #endif ); template <class T> static linear_regression_model<T> train ( const colmajor_matrix<T>& data, dvector<T>& label, linear_regression_model<T>& lrm, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration=1000, double alpha=0.01, size_t hist_size=10, double regParam=0.01, bool isIntercept=false, double convergenceTol=0.001, #if defined(_SX) || defined(__ve__) MatType mType = HYBRID, #else MatType mType = CRS, #endif bool inputMovable = false ); }; template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>& data, dvector<T>& label, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); size_t n_iter = 0; std::vector<T> sample_weight; return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType,false); } template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType,false); } template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>&& data, dvector<T>& label, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); size_t n_iter = 0; std::vector<T> sample_weight; return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType,true); } template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>&& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType,true); } template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>&& data, dvector<T>& label, linear_regression_model<T>& initModel, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType,true); } // --- main api with sparse data support --- template <class T, class I, class O> linear_regression_model<T> ridge_regression_with_lbfgs::train (crs_matrix<T,I,O>& data, dvector<T>& label, linear_regression_model<T>& initModel, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType, bool inputMovable) { #ifdef _DEBUG_ std::cout << "Initial model: \n"; initModel.debug_print(); std::cout << "\n"; #endif if(sample_weight.empty()) sample_weight = vector_full<T>(data.num_row, 1); lbfgs_parallelizer par(hist_size); return par.template parallelize<T,I,O,linear_regression_model<T>, linear_gradient<T>, l2_regularizer<T>> (data,label,initModel,sample_weight,n_iter,numIteration,alpha,regParam, isIntercept,convergenceTol,mType,inputMovable); } template <class T> linear_regression_model<T> ridge_regression_with_lbfgs::train (rowmajor_matrix<T>& data, dvector<T>& label, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { return train<T>(colmajor_matrix<T>(data),label, numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType); } template <class T> linear_regression_model<T> ridge_regression_with_lbfgs::train (const colmajor_matrix<T>& data, dvector<T>& label, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); size_t n_iter = 0; std::vector<T> sample_weight; return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType); } template <class T> linear_regression_model<T> ridge_regression_with_lbfgs::train (const colmajor_matrix<T>& data, dvector<T>& label, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType) { size_t numFeatures = data.num_col; T intercept = isIntercept ? 1.0 : 0.0; linear_regression_model<T> initModel(numFeatures,intercept); return train<T>(data,label,initModel,sample_weight,n_iter,numIteration,alpha,hist_size, regParam,isIntercept,convergenceTol,mType); } // --- main api with dense data support --- template <class T> linear_regression_model<T> ridge_regression_with_lbfgs::train (const colmajor_matrix<T>& data, dvector<T>& label, linear_regression_model<T>& initModel, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, size_t hist_size, double regParam, bool isIntercept, double convergenceTol, MatType mType, bool inputMovable) { #ifdef _DEBUG_ std::cout << "Initial model: \n"; initModel.debug_print(); std::cout << "\n"; #endif if(sample_weight.empty()) sample_weight = vector_full<T>(data.num_row, 1); auto& dmat = const_cast<colmajor_matrix<T>&> (data); lbfgs_parallelizer par(hist_size); return par.template parallelize<T,linear_regression_model<T>, linear_gradient<T>, l2_regularizer<T>> (dmat,label,initModel,sample_weight,n_iter,numIteration,alpha,regParam, isIntercept,convergenceTol); } } #endif
35.12933
89
0.551049
[ "vector", "model" ]
29d18b6e4d7b3c32eb37c46bffb765d17353085d
11,795
cpp
C++
llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
34
2020-01-31T17:50:00.000Z
2022-02-16T20:19:29.000Z
llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
14
2020-02-03T23:39:51.000Z
2021-07-20T16:24:25.000Z
llvm/lib/ExecutionEngine/Orc/CompileOnDemandLayer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
5
2020-07-22T16:56:37.000Z
2022-01-08T02:50:20.000Z
//===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h" #include "llvm/IR/Mangler.h" #include "llvm/IR/Module.h" using namespace llvm; using namespace llvm::orc; static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM, StringRef Suffix, GVPredicate ShouldExtract) { auto DeleteExtractedDefs = [](GlobalValue &GV) { // Bump the linkage: this global will be provided by the external module. GV.setLinkage(GlobalValue::ExternalLinkage); // Delete the definition in the source module. if (isa<Function>(GV)) { auto &F = cast<Function>(GV); F.deleteBody(); F.setPersonalityFn(nullptr); } else if (isa<GlobalVariable>(GV)) { cast<GlobalVariable>(GV).setInitializer(nullptr); } else if (isa<GlobalAlias>(GV)) { // We need to turn deleted aliases into function or variable decls based // on the type of their aliasee. auto &A = cast<GlobalAlias>(GV); Constant *Aliasee = A.getAliasee(); assert(A.hasName() && "Anonymous alias?"); assert(Aliasee->hasName() && "Anonymous aliasee"); std::string AliasName = std::string(A.getName()); if (isa<Function>(Aliasee)) { auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee)); A.replaceAllUsesWith(F); A.eraseFromParent(); F->setName(AliasName); } else if (isa<GlobalVariable>(Aliasee)) { auto *G = cloneGlobalVariableDecl(*A.getParent(), *cast<GlobalVariable>(Aliasee)); A.replaceAllUsesWith(G); A.eraseFromParent(); G->setName(AliasName); } else llvm_unreachable("Alias to unsupported type"); } else llvm_unreachable("Unsupported global type"); }; auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs); NewTSM.withModuleDo([&](Module &M) { M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str()); }); return NewTSM; } namespace llvm { namespace orc { class PartitioningIRMaterializationUnit : public IRMaterializationUnit { public: PartitioningIRMaterializationUnit(ExecutionSession &ES, const ManglingOptions &MO, ThreadSafeModule TSM, VModuleKey K, CompileOnDemandLayer &Parent) : IRMaterializationUnit(ES, MO, std::move(TSM), std::move(K)), Parent(Parent) {} PartitioningIRMaterializationUnit( ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags, SymbolNameToDefinitionMap SymbolToDefinition, CompileOnDemandLayer &Parent) : IRMaterializationUnit(std::move(TSM), std::move(K), std::move(SymbolFlags), std::move(SymbolToDefinition)), Parent(Parent) {} private: void materialize(MaterializationResponsibility R) override { Parent.emitPartition(std::move(R), std::move(TSM), std::move(SymbolToDefinition)); } void discard(const JITDylib &V, const SymbolStringPtr &Name) override { // All original symbols were materialized by the CODLayer and should be // final. The function bodies provided by M should never be overridden. llvm_unreachable("Discard should never be called on an " "ExtractingIRMaterializationUnit"); } mutable std::mutex SourceModuleMutex; CompileOnDemandLayer &Parent; }; Optional<CompileOnDemandLayer::GlobalValueSet> CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) { return std::move(Requested); } Optional<CompileOnDemandLayer::GlobalValueSet> CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) { return None; } CompileOnDemandLayer::CompileOnDemandLayer( ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr, IndirectStubsManagerBuilder BuildIndirectStubsManager) : IRLayer(ES, BaseLayer.getManglingOptions()), BaseLayer(BaseLayer), LCTMgr(LCTMgr), BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {} void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) { this->Partition = std::move(Partition); } void CompileOnDemandLayer::setImplMap(ImplSymbolMap *Imp) { this->AliaseeImpls = Imp; } void CompileOnDemandLayer::emit(MaterializationResponsibility R, ThreadSafeModule TSM) { assert(TSM && "Null module"); auto &ES = getExecutionSession(); // Sort the callables and non-callables, build re-exports and lodge the // actual module with the implementation dylib. auto &PDR = getPerDylibResources(R.getTargetJITDylib()); SymbolAliasMap NonCallables; SymbolAliasMap Callables; TSM.withModuleDo([&](Module &M) { // First, do some cleanup on the module: cleanUpModule(M); }); for (auto &KV : R.getSymbols()) { auto &Name = KV.first; auto &Flags = KV.second; if (Flags.isCallable()) Callables[Name] = SymbolAliasMapEntry(Name, Flags); else NonCallables[Name] = SymbolAliasMapEntry(Name, Flags); } // Create a partitioning materialization unit and lodge it with the // implementation dylib. if (auto Err = PDR.getImplDylib().define( std::make_unique<PartitioningIRMaterializationUnit>( ES, *getManglingOptions(), std::move(TSM), R.getVModuleKey(), *this))) { ES.reportError(std::move(Err)); R.failMaterialization(); return; } R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables), JITDylibLookupFlags::MatchAllSymbols)); R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(), std::move(Callables), AliaseeImpls)); } CompileOnDemandLayer::PerDylibResources & CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) { auto I = DylibResources.find(&TargetD); if (I == DylibResources.end()) { auto &ImplD = getExecutionSession().createJITDylib(TargetD.getName() + ".impl"); TargetD.withSearchOrderDo( [&](const JITDylibSearchOrder &TargetSearchOrder) { auto NewSearchOrder = TargetSearchOrder; assert( !NewSearchOrder.empty() && NewSearchOrder.front().first == &TargetD && NewSearchOrder.front().second == JITDylibLookupFlags::MatchAllSymbols && "TargetD must be at the front of its own search order and match " "non-exported symbol"); NewSearchOrder.insert(std::next(NewSearchOrder.begin()), {&ImplD, JITDylibLookupFlags::MatchAllSymbols}); ImplD.setSearchOrder(std::move(NewSearchOrder), false); }); PerDylibResources PDR(ImplD, BuildIndirectStubsManager()); I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first; } return I->second; } void CompileOnDemandLayer::cleanUpModule(Module &M) { for (auto &F : M.functions()) { if (F.isDeclaration()) continue; if (F.hasAvailableExternallyLinkage()) { F.deleteBody(); F.setPersonalityFn(nullptr); continue; } } } void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) { // Expands the partition to ensure the following rules hold: // (1) If any alias is in the partition, its aliasee is also in the partition. // (2) If any aliasee is in the partition, its aliases are also in the // partiton. // (3) If any global variable is in the partition then all global variables // are in the partition. assert(!Partition.empty() && "Unexpected empty partition"); const Module &M = *(*Partition.begin())->getParent(); bool ContainsGlobalVariables = false; std::vector<const GlobalValue *> GVsToAdd; for (auto *GV : Partition) if (isa<GlobalAlias>(GV)) GVsToAdd.push_back( cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee())); else if (isa<GlobalVariable>(GV)) ContainsGlobalVariables = true; for (auto &A : M.aliases()) if (Partition.count(cast<GlobalValue>(A.getAliasee()))) GVsToAdd.push_back(&A); if (ContainsGlobalVariables) for (auto &G : M.globals()) GVsToAdd.push_back(&G); for (auto *GV : GVsToAdd) Partition.insert(GV); } void CompileOnDemandLayer::emitPartition( MaterializationResponsibility R, ThreadSafeModule TSM, IRMaterializationUnit::SymbolNameToDefinitionMap Defs) { // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the // extracted module key, extracted module, and source module key // together. This could be used, for example, to provide a specific // memory manager instance to the linking layer. auto &ES = getExecutionSession(); GlobalValueSet RequestedGVs; for (auto &Name : R.getRequestedSymbols()) { assert(Defs.count(Name) && "No definition for symbol"); RequestedGVs.insert(Defs[Name]); } /// Perform partitioning with the context lock held, since the partition /// function is allowed to access the globals to compute the partition. auto GVsToExtract = TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); }); // Take a 'None' partition to mean the whole module (as opposed to an empty // partition, which means "materialize nothing"). Emit the whole module // unmodified to the base layer. if (GVsToExtract == None) { Defs.clear(); BaseLayer.emit(std::move(R), std::move(TSM)); return; } // If the partition is empty, return the whole module to the symbol table. if (GVsToExtract->empty()) { R.replace(std::make_unique<PartitioningIRMaterializationUnit>( std::move(TSM), R.getSymbols(), std::move(Defs), *this)); return; } // Ok -- we actually need to partition the symbols. Promote the symbol // linkages/names, expand the partition to include any required symbols // (i.e. symbols that can't be separated from our partition), and // then extract the partition. // // FIXME: We apply this promotion once per partitioning. It's safe, but // overkill. auto ExtractedTSM = TSM.withModuleDo([&](Module &M) -> Expected<ThreadSafeModule> { auto PromotedGlobals = PromoteSymbols(M); if (!PromotedGlobals.empty()) { MangleAndInterner Mangle(ES, M.getDataLayout()); SymbolFlagsMap SymbolFlags; for (auto &GV : PromotedGlobals) SymbolFlags[Mangle(GV->getName())] = JITSymbolFlags::fromGlobalValue(*GV); if (auto Err = R.defineMaterializing(SymbolFlags)) return std::move(Err); } expandPartition(*GVsToExtract); // Extract the requested partiton (plus any necessary aliases) and // put the rest back into the impl dylib. auto ShouldExtract = [&](const GlobalValue &GV) -> bool { return GVsToExtract->count(&GV); }; return extractSubModule(TSM, ".submodule", ShouldExtract); }); if (!ExtractedTSM) { ES.reportError(ExtractedTSM.takeError()); R.failMaterialization(); return; } R.replace(std::make_unique<PartitioningIRMaterializationUnit>( ES, *getManglingOptions(), std::move(TSM), R.getVModuleKey(), *this)); BaseLayer.emit(std::move(R), std::move(*ExtractedTSM)); } } // end namespace orc } // end namespace llvm
36.404321
80
0.658923
[ "vector" ]
29d2375b9053d068bf0e2f743febd0e007ca28a4
133,790
cpp
C++
ODIN_II/SRC/simulate_blif.cpp
seongsikpark/vtr-verilog-to-routing
15313b6d26e0e7df9236232321bc1b0e3d78e69e
[ "MIT" ]
null
null
null
ODIN_II/SRC/simulate_blif.cpp
seongsikpark/vtr-verilog-to-routing
15313b6d26e0e7df9236232321bc1b0e3d78e69e
[ "MIT" ]
null
null
null
ODIN_II/SRC/simulate_blif.cpp
seongsikpark/vtr-verilog-to-routing
15313b6d26e0e7df9236232321bc1b0e3d78e69e
[ "MIT" ]
null
null
null
/* number_of_workers = std::max(1, global_args.parralelized_simulation.value()); 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 "simulate_blif.h" #include <algorithm> #include <unordered_map> #include <unordered_set> #include <cmath> #include "vtr_util.h" #include "vtr_memory.h" #include "odin_util.h" #include <string> #include <sstream> #include <chrono> #include <dlfcn.h> #include <mutex> #include <unistd.h> #include <thread> //#include <cthreads.h> //maria #include <sys/sysinfo.h> #define CLOCK_INITIAL_VALUE 1 #define MAX_REPEAT_SIM 128 static inline signed char init_value(nnode_t *node) { return (node && node->has_initial_value)? node->initial_value: global_args.sim_initial_value; } typedef enum { FALLING, RISING, HIGH, LOW, UNK }edge_eval_e; inline static edge_eval_e get_edge_type(npin_t *clk, int cycle) { if(!clk) return UNK; signed char prev = !CLOCK_INITIAL_VALUE; signed char cur = CLOCK_INITIAL_VALUE; if(cycle > 0) { prev = get_pin_value(clk, cycle-1); cur = get_pin_value(clk, cycle); } return ((prev != cur) && (prev == 0 || cur == 1))? RISING: ((prev != cur) && (prev == 1 || cur == 0))? FALLING: (cur == 1)? HIGH: (cur == 0)? LOW: UNK; } inline static bool ff_trigger(edge_type_e type, npin_t* clk, int cycle) { edge_eval_e clk_e = get_edge_type(clk, cycle); // update the flip-flop from the input value of the previous cycle. return ( (type == FALLING_EDGE_SENSITIVITY && clk_e == FALLING) || (type == RISING_EDGE_SENSITIVITY && clk_e == RISING) || (type == ACTIVE_HIGH_SENSITIVITY && clk_e == HIGH) || (type == ACTIVE_LOW_SENSITIVITY && clk_e == LOW) || (type == ASYNCHRONOUS_SENSITIVITY && (clk_e == RISING || clk_e == FALLING)) ); } inline static signed char get_D(npin_t* D, int cycle) { return get_pin_value(D,cycle-1); } inline static signed char get_Q(npin_t* Q, int cycle) { return get_pin_value(Q,cycle-1); } inline static signed char compute_ff(bool trigger, signed char D_val, signed char Q_val, int /*cycle*/) { return (trigger) ? D_val: Q_val; } inline static signed char compute_ff(bool trigger, npin_t* D, signed char Q_val, int cycle) { return compute_ff(trigger, get_D(D, cycle), Q_val, cycle); } inline static signed char compute_ff(bool trigger, signed char D_val, npin_t* Q, int cycle) { return compute_ff(trigger, D_val, get_Q(Q,cycle), cycle); } inline static signed char compute_ff(bool trigger, npin_t* D, npin_t* Q, int cycle) { return compute_ff(trigger, get_D(D,cycle), get_Q(Q,cycle), cycle); } static inline bool is_clock_node(nnode_t *node) { return node && ( (node->type == CLOCK_NODE) || (std::string(node->name) == "top^clk") // Strictly for memories. || (std::string(node->name) == DEFAULT_CLOCK_NAME) ); } //maria static thread_node_distribution *calculate_thread_distribution(stages_t *s); static void compute_and_store_part_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int cycle); //to remove static void compute_and_store_part_wave_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int from_wave,int to_wave); static void compute_and_store_part_in_waves_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int from_wave, int to_wave,int offset,bool /*notify_back*/); static void simulate_cycle_multithreaded(int cycle, thread_node_distribution *thread_distribution); static void simulate_cycle(int cycle, stages_t *s); static stages_t *simulate_first_cycle(netlist_t *netlist, int cycle, lines_t *output_lines); static stages_t *stage_ordered_nodes(nnode_t **ordered_nodes, int num_ordered_nodes); static void free_stages(stages_t *s); //maria static void free_thread_distribution(thread_node_distribution *thread_distribution); static int get_num_covered_nodes(stages_t *s); static int *get_children_pinnumber_of(nnode_t *node, int *num_children); //maria static nnode_t **get_parents_of(nnode_t *node, int *num_parents); static int is_node_ready(nnode_t* node, int cycle); static int is_node_complete(nnode_t* node, int cycle); static void write_back_memory_nodes(nnode_t **nodes, int num_nodes); static bool compute_and_store_value(nnode_t *node, int cycle); static void compute_memory_node(nnode_t *node, int cycle); static void compute_hard_ip_node(nnode_t *node, int cycle); static void compute_multiply_node(nnode_t *node, int cycle); static void compute_generic_node(nnode_t *node, int cycle); static void compute_add_node(nnode_t *node, int cycle, int type); static void compute_unary_sub_node(nnode_t *node, int cycle); static void update_pin_value(npin_t *pin, signed char value, int cycle); static int get_pin_cycle(npin_t *pin); signed char get_line_pin_value(line_t *line, int pin_num, int cycle); static int line_has_unknown_pin(line_t *line, int cycle); static void compute_flipflop_node(nnode_t *node, int cycle); static void compute_mux_2_node(nnode_t *node, int cycle); static int *multiply_arrays(int *a, int a_length, int *b, int b_length); static int *add_arrays(int *a, int a_length, int *b, int b_length, int *c, int c_length, int flag); static int *unary_sub_arrays(int *a, int a_length, int *c, int c_length); static void compute_single_port_memory(nnode_t *node, int cycle); static void compute_dual_port_memory(nnode_t *node, int cycle); static long compute_memory_address(signal_list_t *addr, int cycle); static void instantiate_memory(nnode_t *node, long data_width, long addr_width); static char *get_mif_filename(nnode_t *node); static FILE *preprocess_mif_file(FILE *source); static void assign_memory_from_mif_file(nnode_t *node, FILE *mif, char *filename, int width, long address_width); static int parse_mif_radix(char *radix); static int count_test_vectors(FILE *in); static int count_empty_test_vectors(FILE *in); static int is_vector(char *buffer); static int get_next_vector(FILE *file, char *buffer); static test_vector *parse_test_vector(char *buffer); static test_vector *generate_random_test_vector(int cycle, sim_data_t *sim_data); static int compare_test_vectors(test_vector *v1, test_vector *v2); static int verify_test_vector_headers(FILE *in, lines_t *l); static void free_test_vector(test_vector* v); static line_t *create_line(char *name); static int verify_lines(lines_t *l); static void free_lines(lines_t *l); static int find_portname_in_lines(char* port_name, lines_t *l); static lines_t *create_lines(netlist_t *netlist, int type); static void add_test_vector_to_lines(test_vector *v, lines_t *l, int cycle); static void assign_node_to_line(nnode_t *node, lines_t *l, int type, int single_pin); static void insert_pin_into_line(npin_t *pin, int pin_number, line_t *line, int type); static char *generate_vector_header(lines_t *l); static void write_vector_headers(FILE *file, lines_t *l); static void write_vector_to_file(lines_t *l, FILE *file, int cycle); static void write_cycle_to_file(lines_t *l, FILE* file, int cycle); static void write_vector_to_modelsim_file(lines_t *l, FILE *modelsim_out, int cycle); static void write_cycle_to_modelsim_file(netlist_t *netlist, lines_t *l, FILE* modelsim_out, int cycle); static int verify_output_vectors(char* output_vector_file, int num_test_vectors); static void add_additional_items_to_lines(nnode_t *node, lines_t *l); static char *vector_value_to_hex(signed char *value, int length); static void print_netlist_stats(stages_t *stages, int num_vectors); static void print_simulation_stats(stages_t *stages, int num_vectors, double total_time, double simulation_time); static void flag_undriven_input_pins(nnode_t *node); static void print_ancestry(nnode_t *node, int generations); static nnode_t *print_update_trace(nnode_t *bottom_node, int cycle); double used_time; int number_of_workers; bool batch_mode; bool found_best_time; int num_of_clock; //maria TODO maybe not the best place? pthread_cond_t start_threads,start_output; pthread_mutex_t threads_mp,output_mp,main_mp; int threads_done_wave = 0; int threads_created = 0; int threads_waves = 0; int threads_start = 0; int threads_end = 0; /* * Performs simulation. */ void simulate_netlist(netlist_t *netlist) { printf("Simulation starts \n"); sim_data_t *sim_data = init_simulation(netlist); printf("\n"); //int progress_bar_position = -1; //const int progress_bar_length = 50; double min_coverage =0.0; if(global_args.sim_min_coverage) { min_coverage = global_args.sim_min_coverage/100; } else if(global_args.sim_achieve_best) { min_coverage = 0.0001; } if (number_of_workers>1 && global_args.parralelized_simulation_in_batch) { int start_cycle = 0; int end_cycle = sim_data->num_vectors; simulate_steps_in_parallel(sim_data,start_cycle,end_cycle,min_coverage); } else { simulate_steps_sequential(sim_data,min_coverage); } fflush(sim_data->out); fprintf(sim_data->modelsim_out, "run %ld\n", sim_data->num_vectors*100); printf("\n"); // If a second output vector file was given via the -T option, verify that it matches. char *output_vector_file = global_args.sim_vector_output_file; if (output_vector_file) { if (verify_output_vectors(output_vector_file, sim_data->num_vectors)) printf("Vector file \"%s\" matches output\n", output_vector_file); else error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Vector files differ."); printf("\n"); } // Print statistics. print_simulation_stats(sim_data->stages, sim_data->num_vectors, sim_data->total_time, sim_data->simulation_time); // Perform ACE activity calculations calculate_activity ( netlist, sim_data->num_vectors, sim_data->act_out ); } /* * Performs simulation batches of cycles pass through the threads. */ // before /* void simulate_netlist(netlist_t *netlist) { sim_data_t *sim_data = init_simulation(netlist); printf("\n"); int progress_bar_position = -1; const int progress_bar_length = 50; int increment_vector_by = global_args.sim_num_test_vectors;; double min_coverage =0.0; if(global_args.sim_min_coverage) { min_coverage = global_args.sim_min_coverage/100; } else if(global_args.sim_achieve_best) { min_coverage = 0.0001; } double current_coverage =0.0; int cycle =0; while(cycle < sim_data->num_vectors) { double wave_start_time = wall_time(); // if we target a minimum coverage keep generating if(min_coverage > 0.0) { if(cycle+1 == sim_data->num_vectors) { current_coverage = (((double) get_num_covered_nodes(sim_data->stages) / (double) sim_data->stages->num_nodes)); if(global_args.sim_achieve_best) { if(current_coverage > min_coverage) { increment_vector_by = global_args.sim_num_test_vectors; min_coverage = current_coverage; sim_data->num_vectors += increment_vector_by; } else if(increment_vector_by) { //slowly reduce the search until there is no more possible increment, this prevent building too large of a comparative vector pair sim_data->num_vectors += increment_vector_by; increment_vector_by /= 2; } } else { if(current_coverage < min_coverage) sim_data->num_vectors += increment_vector_by; } } } else { current_coverage = cycle/(double)sim_data->num_vectors; } single_step(sim_data, cycle); // Print netlist-specific statistics. if (!cycle) print_netlist_stats(sim_data->stages, sim_data->num_vectors); sim_data->total_time += wall_time() - wave_start_time; // Delay drawing of the progress bar until the second wave to improve the accuracy of the ETA. if ((sim_data->num_vectors == 1) || cycle) progress_bar_position = print_progress_bar( cycle/(double)(sim_data->num_vectors), progress_bar_position, progress_bar_length, sim_data->total_time); cycle++; } fflush(sim_data->out); fprintf(sim_data->modelsim_out, "run %ld\n", sim_data->num_vectors*100); printf("\n"); // If a second output vector file was given via the -T option, verify that it matches. char *output_vector_file = global_args.sim_vector_output_file; if (output_vector_file) { if (verify_output_vectors(output_vector_file, sim_data->num_vectors)) printf("Vector file \"%s\" matches output\n", output_vector_file); else error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Vector files differ."); printf("\n"); } // Print statistics. print_simulation_stats(sim_data->stages, sim_data->num_vectors, sim_data->total_time, sim_data->simulation_time); // Perform ACE activity calculations calculate_activity ( netlist, sim_data->num_vectors, sim_data->act_out ); } */ /** * Initialize simulation */ sim_data_t *init_simulation(netlist_t *netlist) { //for multithreading used_time = std::numeric_limits<double>::max(); number_of_workers = global_args.parralelized_simulation.value(); if(number_of_workers >1 ) warning_message(SIMULATION_ERROR,-1,-1,"Executing simulation with maximum of %ld threads", number_of_workers); found_best_time = false; num_of_clock = 0; sim_data_t *sim_data = (sim_data_t *)vtr::malloc(sizeof(sim_data_t)); sim_data->netlist = netlist; printf("Beginning simulation. Output_files located @: %s\n", ((char *)global_args.sim_directory)); fflush(stdout); // Open the output vector file. char out_vec_file[BUFFER_MAX_SIZE] = { 0 }; odin_sprintf(out_vec_file,"%s/%s",((char *)global_args.sim_directory),OUTPUT_VECTOR_FILE_NAME); sim_data->out = fopen(out_vec_file, "w"); if (!sim_data->out) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not create output vector file."); // Open the input vector file. char in_vec_file[BUFFER_MAX_SIZE] = { 0 }; odin_sprintf(in_vec_file,"%s/%s",((char *)global_args.sim_directory),INPUT_VECTOR_FILE_NAME); sim_data->in_out = fopen(in_vec_file, "w+"); if (!sim_data->in_out) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not create input vector file."); // Open the activity output file. char act_file[BUFFER_MAX_SIZE] = { 0 }; odin_sprintf(act_file,"%s/%s",((char *)global_args.sim_directory),OUTPUT_ACTIVITY_FILE_NAME); sim_data->act_out = fopen(act_file, "w"); if (!sim_data->act_out) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not create activity output file."); // Open the modelsim vector file. char test_file[BUFFER_MAX_SIZE] = { 0 }; odin_sprintf(test_file,"%s/%s",((char *)global_args.sim_directory),MODEL_SIM_FILE_NAME); sim_data->modelsim_out = fopen(test_file, "w"); if (!sim_data->modelsim_out) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not create modelsim output file."); // Create and verify the lines. sim_data->input_lines = create_lines(netlist, INPUT); if (!verify_lines(sim_data->input_lines)) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Input lines could not be assigned."); sim_data->output_lines = create_lines(netlist, OUTPUT); if (!verify_lines(sim_data->output_lines)) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Output lines could not be assigned."); sim_data->in = NULL; sim_data->input_vector_file = NULL; // Passed via the -t option. Input vectors can either come from a file // if we expect no lines on input, then don't read the input file and generate as many input test vector as there are output // vectors so that simulation can run char *input_vector_file = global_args.sim_vector_input_file; if (input_vector_file && sim_data->input_lines->count != 0) { sim_data->input_vector_file = input_vector_file; sim_data->in = fopen(sim_data->input_vector_file, "r"); if (!sim_data->in) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector input file: %s", sim_data->input_vector_file); sim_data->num_vectors = count_test_vectors(sim_data->in); // Read the vector headers and check to make sure they match the lines. if (!verify_test_vector_headers(sim_data->in, sim_data->input_lines)) error_message(SIMULATION_ERROR, 0, -1, "Invalid vector header format in %s.", sim_data->input_vector_file); printf("Simulating %ld existing vectors from \"%s\".\n", sim_data->num_vectors, sim_data->input_vector_file); fflush(stdout); } // or be randomly generated. Passed via the -g option. it also serve as a fallback when we have an empty input else { if(input_vector_file) { sim_data->in = fopen(input_vector_file, "r"); if (!sim_data->in) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector input file: %s", input_vector_file); sim_data->num_vectors = count_empty_test_vectors(sim_data->in); } else { sim_data->num_vectors = global_args.sim_num_test_vectors; } printf("Simulating %ld new vectors.\n", sim_data->num_vectors); fflush(stdout); srand(global_args.sim_random_seed); } // Setup data structures for activity estimation alloc_and_init_ace_structs(netlist); // Determine which edge(s) we are outputting. sim_data->total_time = 0; // Includes I/O sim_data->simulation_time = 0; // Does not include I/O sim_data->stages = 0; //maria sim_data->thread_distribution = 0; if (!sim_data->num_vectors) { terminate_simulation(sim_data); error_message(SIMULATION_ERROR, 0, -1, "%s", "No vectors to simulate."); } return sim_data; } sim_data_t *terminate_simulation(sim_data_t *sim_data) { free_stages(sim_data->stages); //maria free_thread_distribution(sim_data->thread_distribution); fclose(sim_data->act_out); free_lines(sim_data->output_lines); free_lines(sim_data->input_lines); fclose(sim_data->modelsim_out); fclose(sim_data->in_out); if (sim_data->input_vector_file) fclose(sim_data->in); fclose(sim_data->out); vtr::free(sim_data); sim_data = NULL; return sim_data; } void simulate_steps_sequential(sim_data_t *sim_data,double min_coverage) { printf("\n"); int progress_bar_position = -1; const int progress_bar_length = 50; int increment_vector_by = global_args.sim_num_test_vectors;; double current_coverage =0.0; int cycle=0; while(cycle < sim_data->num_vectors) { double wave_start_time = wall_time(); // if we target a minimum coverage keep generating if(min_coverage > 0.0) { if(cycle+1 == sim_data->num_vectors) { current_coverage = (((double) get_num_covered_nodes(sim_data->stages) / (double) sim_data->stages->num_nodes)); if(global_args.sim_achieve_best) { if(current_coverage > min_coverage) { increment_vector_by = global_args.sim_num_test_vectors; min_coverage = current_coverage; sim_data->num_vectors += increment_vector_by; } else if(increment_vector_by) { //slowly reduce the search until there is no more possible increment, this prevent building too large of a comparative vector pair sim_data->num_vectors += increment_vector_by; increment_vector_by /= 2; } } else { if(current_coverage < min_coverage) sim_data->num_vectors += increment_vector_by; } } } else { current_coverage = cycle/(double)sim_data->num_vectors; } single_step(sim_data, cycle); // Print netlist-specific statistics. if (!cycle) print_netlist_stats(sim_data->stages, sim_data->num_vectors); sim_data->total_time += wall_time() - wave_start_time; // Delay drawing of the progress bar until the second wave to improve the accuracy of the ETA. if ((sim_data->num_vectors == 1) || cycle) progress_bar_position = print_progress_bar( (cycle+1)/(double)(sim_data->num_vectors), progress_bar_position, progress_bar_length, sim_data->total_time); cycle++; } } void simulate_steps_in_parallel(sim_data_t *sim_data,int from_wave,int to_wave,double min_coverage) { // produce a wave of values at each iteration double start_time = wall_time(); int progress_bar_position = -1; const int progress_bar_length = 50; int increment_vector_by = global_args.sim_num_test_vectors; double current_coverage =0.0; int offset = BUFFER_SIZE-1; // BUFFER_SIZE- simulation threads_waves = (to_wave-from_wave)/offset; threads_start = from_wave; threads_end = to_wave; pthread_cond_init(&start_threads, NULL); pthread_cond_init(&start_output, NULL); std::vector<std::thread> worker_threads; bool done = FALSE,restart = FALSE; while (!done) { for (int wave = 0; wave<=threads_waves; wave++) { double simulation_start_time = wall_time(); int from_cycle = from_wave + wave*offset; int to_cycle = from_cycle+offset; if (to_cycle > to_wave) to_cycle = to_wave; test_vector *v=NULL; // Assign vectors to lines, either by reading or generating them. // Every second cycle gets a new vector. char buffer[BUFFER_MAX_SIZE]; for (int i=from_cycle;i<to_cycle;i++) { v = NULL; if (sim_data->in) { //buffer = NULL; if (!get_next_vector(sim_data->in, buffer)) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not read next vector."); v = parse_test_vector(buffer); //printf("Here\n"); } else { v = generate_random_test_vector(i, sim_data); } //printf("v=%ld \n",v->values[0][0]); add_test_vector_to_lines(v, sim_data->input_lines, i); write_cycle_to_file(sim_data->input_lines, sim_data->in_out, i); write_cycle_to_modelsim_file(sim_data->netlist, sim_data->input_lines, sim_data->modelsim_out, i); } if (v) free_test_vector(v); if (wave == 0) { // lines as specified by the -p option. sim_data->stages = simulate_first_cycle(sim_data->netlist, from_cycle, sim_data->output_lines); // Make sure the output lines are still OK after adding custom lines. if (!verify_lines(sim_data->output_lines)) error_message(SIMULATION_ERROR, 0, -1,"%s\n", "Problem detected with the output lines after the first cycle."); //maria sim_data->thread_distribution = calculate_thread_distribution(sim_data->stages); //create_threads_and_let them wait for the signal for (int t=0; t<sim_data->thread_distribution->number_of_threads; t++) { worker_threads.push_back(std::thread(compute_and_store_part_in_waves_multithreaded,t,sim_data->thread_distribution->thread_nodes[t],from_wave,to_wave,offset,TRUE)); } } if (wave !=0 || restart) { pthread_mutex_lock(&output_mp); threads_done_wave =0; pthread_mutex_unlock(&output_mp); if( (errno =pthread_cond_broadcast(&start_threads)) !=0) printf("Broadcast Error!"); } pthread_mutex_lock(&threads_mp); while (threads_done_wave != sim_data->thread_distribution->number_of_threads) { pthread_cond_wait(&start_output,&threads_mp); } pthread_mutex_unlock(&threads_mp); for (int i=from_cycle;i<to_cycle;i++) { //if (i!=0) write_cycle_to_file(sim_data->output_lines, sim_data->out, i); } //update memory directories of all memory nodes write_back_memory_nodes(sim_data->thread_distribution->memory_nodes->nodes,sim_data->thread_distribution->memory_nodes->number_of_nodes); sim_data->simulation_time += wall_time() - simulation_start_time; if (wave==threads_waves) //check for coverage in the last cycle { if(min_coverage > 0.0) { current_coverage = (((double) get_num_covered_nodes(sim_data->stages) / (double) sim_data->stages->num_nodes)); if(global_args.sim_achieve_best) { if(current_coverage > min_coverage) { increment_vector_by = global_args.sim_num_test_vectors; min_coverage = current_coverage; sim_data->num_vectors += increment_vector_by; } else if(increment_vector_by) { //slowly reduce the search until there is no more possible increment, this prevent building too large of a comparative vector pair sim_data->num_vectors += increment_vector_by; increment_vector_by /= 2; } } else { if(current_coverage < min_coverage) sim_data->num_vectors += increment_vector_by; } //update the cycle boundaries to continue calculations if (sim_data->num_vectors != to_cycle) { from_wave = to_cycle+1; to_wave = sim_data->num_vectors; threads_waves = (to_wave-from_wave)/offset; pthread_mutex_lock(&output_mp); threads_start = from_cycle; threads_end = to_cycle; pthread_mutex_unlock(&output_mp); restart = TRUE; //printf("threads start %ld threads end %ld",threads_start,threads_end); } else done= TRUE; } else { current_coverage = to_cycle/(double)sim_data->num_vectors; done = TRUE; } } // Print netlist-specific statistics. if (wave == 0) print_netlist_stats(sim_data->stages, sim_data->num_vectors); sim_data->total_time = wall_time() - start_time; progress_bar_position = print_progress_bar( to_cycle/(double)(sim_data->num_vectors), progress_bar_position, progress_bar_length, sim_data->total_time); } if (done) { //signal to unblock threads and let them finish if( (errno =pthread_cond_broadcast(&start_threads)) !=0) printf("Broadcast Error!"); } } int threadnum = 0; for (auto &worker: worker_threads) { worker.join(); threadnum++; } //wait for them to be done pthread_cond_destroy(&start_output); pthread_cond_destroy(&start_threads); sim_data->total_time = wall_time() - start_time; progress_bar_position = print_progress_bar( (double)sim_data->num_vectors/(double)(sim_data->num_vectors), progress_bar_position, progress_bar_length, sim_data->total_time); } /** * single step sim */ int single_step(sim_data_t *sim_data, int cycle) { test_vector *v = NULL; // Assign vectors to lines, either by reading or generating them. // Every second cycle gets a new vector. double simulation_start_time = wall_time(); // Perform simulation if (sim_data->in) { char buffer[BUFFER_MAX_SIZE]; if (!get_next_vector(sim_data->in, buffer)) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Could not read next vector."); v = parse_test_vector(buffer); } else { v = generate_random_test_vector(cycle, sim_data); } add_test_vector_to_lines(v, sim_data->input_lines, cycle); write_cycle_to_file(sim_data->input_lines, sim_data->in_out, cycle); write_cycle_to_modelsim_file(sim_data->netlist, sim_data->input_lines, sim_data->modelsim_out, cycle); free_test_vector(v); if(!cycle) { // The first cycle produces the stages, and adds additional // lines as specified by the -p option. sim_data->stages = simulate_first_cycle(sim_data->netlist, cycle, sim_data->output_lines); //split the nodes into threads using the stages agbove for parallel calculations //maria //sim_data->thread_distribution = calculate_thread_distribution(sim_data->stages); // Make sure the output lines are still OK after adding custom lines. if (!verify_lines(sim_data->output_lines)) error_message(SIMULATION_ERROR, 0, -1,"%s\n", "Problem detected with the output lines after the first cycle."); } else { simulate_cycle(cycle, sim_data->stages); //maria //simulate_cycle_multithreaded(cycle, sim_data->thread_distribution); } write_cycle_to_file(sim_data->output_lines, sim_data->out, cycle); sim_data->simulation_time += wall_time() - simulation_start_time; return cycle +1; } /* * This simulates a single cycle using the stages generated * during the first cycle. * * simulation computes a small number of cycles sequentially and * a small number in parallel. The minimum parallel and sequential time is * taken for each stage, and that stage is computed in parallel for all subsequent * cycles if speedup is observed. */ static void compute_and_store_part(int start, int end, int current_stage, stages_t *s, int cycle) { for (int j = start;j >= 0 && j <= end && j < s->counts[current_stage]; j++) if(s->stages[current_stage][j]) compute_and_store_value(s->stages[current_stage][j], cycle); } static void simulate_cycle(int cycle, stages_t *s) { double total_run_time = 0; for(int i = 0; i < s->count; i++) { double time = wall_time(); std::vector<std::thread> workers; int previous_end = 0; int nodes_per_thread = s->counts[i]/number_of_workers; int remainder_nodes_per_thread = s->counts[i]%number_of_workers; for (int id =0; id < number_of_workers; id++) { int start = previous_end; int end = start + nodes_per_thread + ((remainder_nodes_per_thread > 0)? 1: 0); remainder_nodes_per_thread -= 1; previous_end = end + 1; if( (end-start) > 0 ) { if(id < number_of_workers-1) // if child threads workers.push_back(std::thread(compute_and_store_part,start,end,i,s,cycle)); else compute_and_store_part(start,end,i,s,cycle); } } for (auto &worker: workers) worker.join(); total_run_time += wall_time()-time; } } //maria static void compute_and_store_part_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int cycle) { int *nodes_done = (int*)vtr::calloc(thread_nodes->number_of_nodes,sizeof(int)); int nodes_counter = thread_nodes->number_of_nodes; nnode_t **nodes_in_progress = (nnode_t **)vtr::malloc(sizeof(nnode_t*) *thread_nodes->number_of_nodes ); for (int i=0;i<nodes_counter;i++) nodes_in_progress[i] = thread_nodes->nodes[i]; while (nodes_counter!=0 ) { for (int j = 0;j < nodes_counter; j++) { nnode_t *node = nodes_in_progress[j]; if(node && is_node_ready(node,cycle) && !is_node_complete(node,cycle) ) { compute_and_store_value(node, cycle); nodes_done[j]=1; } else if(!node || is_node_complete(node,cycle) ) nodes_done[j]=1; } nnode_t **temp = &(*nodes_in_progress); int not_done = 0; //number of nodes for (int i=0;i<nodes_counter;i++) { if (!nodes_done[i]) { nodes_in_progress[not_done] = temp[i]; not_done++; } nodes_done[i] = 0; } nodes_counter = not_done; } vtr::free(nodes_done); vtr::free(nodes_in_progress); } //maria static void compute_and_store_part_in_waves_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int from_wave, int to_wave,int offset,bool /*notify_back*/) { int *nodes_done = (int*)vtr::calloc(thread_nodes->number_of_nodes,sizeof(int)); int nodes_counter = thread_nodes->number_of_nodes; int waves = (to_wave-from_wave)/offset; //do while for (int wave = 0;wave<=waves; wave++) { int from_cycle = from_wave + wave*offset; int to_cycle = from_cycle+offset; if (to_cycle > to_wave) to_cycle = to_wave; for (int cycle = from_cycle; cycle<to_cycle; cycle++) { nodes_counter = thread_nodes->number_of_nodes; for (int i=0;i<nodes_counter;i++) nodes_done[i] = 0; int done = 0; while (nodes_counter!=done ) { for (int j = 0;j < nodes_counter; j++) { if (!nodes_done[j]) { nnode_t *node = thread_nodes->nodes[j]; if(node && is_node_ready(node,cycle) && !is_node_complete(node,cycle) ) { compute_and_store_value(node, cycle); nodes_done[j]=1; } else if(!node || is_node_complete(node,cycle) ) { nodes_done[j]=1; } } } done = 0; //number of nodes for (int i=0;i<nodes_counter;i++) { if (nodes_done[i]) { done++; } } } } //signal the current wave is done pthread_mutex_lock(&threads_mp); threads_done_wave++; pthread_cond_broadcast(&start_output); pthread_cond_wait(&start_threads,&threads_mp); pthread_mutex_unlock(&threads_mp); if (wave == waves) //check if we need to start again for coverage { int shared_from_wave,shared_to_wave; pthread_mutex_lock(&threads_mp); shared_from_wave = threads_start; shared_to_wave = threads_end; pthread_mutex_unlock(&threads_mp); //if the shared variable is changed then copy the other values and restart the loop if (shared_from_wave != from_wave) { from_wave = shared_from_wave; to_wave = shared_to_wave; waves = (to_wave-from_wave)/offset; } } } vtr::free(nodes_done); } //maria static void compute_and_store_part_wave_multithreaded(int /*t_id*/,netlist_subset *thread_nodes,int from_wave, int to_wave) { int *nodes_done = (int*)vtr::calloc(thread_nodes->number_of_nodes,sizeof(int)); int nodes_counter = thread_nodes->number_of_nodes; for (int cycle = from_wave; cycle<to_wave; cycle++) { nodes_counter = thread_nodes->number_of_nodes; for (int i=0;i<nodes_counter;i++) nodes_done[i] = 0; int done = 0; while (nodes_counter!=done ) { for (int j = 0;j < nodes_counter; j++) { if (!nodes_done[j]) { nnode_t *node = thread_nodes->nodes[j]; if(node && is_node_ready(node,cycle) && !is_node_complete(node,cycle) ) { compute_and_store_value(node, cycle); nodes_done[j]=1; } else if(!node || is_node_complete(node,cycle) ) nodes_done[j]=1; } } done = 0; //number of nodes for (int i=0;i<nodes_counter;i++) { if (nodes_done[i]) { done++; } } } } vtr::free(nodes_done); } //maria static void simulate_cycle_multithreaded(int cycle, thread_node_distribution *thread_distribution) { std::vector<std::thread> workers; for (int t=0; t<thread_distribution->number_of_threads; t++) { workers.push_back(std::thread(compute_and_store_part_wave_multithreaded,t,thread_distribution->thread_nodes[t],cycle,cycle+1)); } int threadnum = 0; for (auto &worker: workers) { worker.join(); threadnum++; } } /* * Updates all pins which have been flagged as undriven * to -1 for the given cycle. * * Also checks that other pins have been updated * by cycle 3 and throws an error if they haven't been. * * This function is called when each node is updated as a * safeguard. */ static void update_undriven_input_pins(nnode_t *node, int cycle) { int i; for (i = 0; i < node->num_undriven_pins; i++) update_pin_value(node->undriven_pins[i], init_value(node), cycle); // By the third cycle everything in the netlist should have been updated. if (cycle == 3) { for (i = 0; i < node->num_input_pins; i++) { if (get_pin_cycle( node->input_pins[i]) < cycle-1) { // Print the trace. nnode_t *root = print_update_trace(node, cycle); // Throw an error. error_message(SIMULATION_ERROR,0,-1,"Odin has detected that an input pin attached to %s isn't being updated.\n" "\tPin name: %s\n" "\tRoot node: %s\n" "\tSee the trace immediately above this message for details.\n", node->name, node->input_pins[i]->name, root?root->name:"N/A" ); } } } } /* * Checks to see if the node is ready to be simulated for the given cycle. */ static int is_node_ready(nnode_t* node, int cycle) { if (!cycle) { /* * Flags any inputs pins which are undriven and have * not already been flagged. */ int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; if (!pin->net || !pin->net->driver_pin || !pin->net->driver_pin->node) { int already_flagged = FALSE; int j; for (j = 0; j < node->num_undriven_pins; j++) { if (node->undriven_pins[j] == pin) already_flagged = TRUE; } if (!already_flagged) { node->undriven_pins = (npin_t **)vtr::realloc(node->undriven_pins, sizeof(npin_t *) * (node->num_undriven_pins + 1)); node->undriven_pins[node->num_undriven_pins++] = pin; warning_message(SIMULATION_ERROR,0,-1,"A node (%s) has an undriven input pin.", node->name); } } } update_undriven_input_pins(node, cycle); } if (node->type == FF_NODE) { npin_t *D_pin = node->input_pins[0]; npin_t *clock_pin = node->input_pins[1]; // Flip-flops depend on the D input from the previous cycle and the clock from this cycle. if (get_pin_cycle(D_pin) < cycle-1) return FALSE; if (get_pin_cycle(clock_pin) < cycle ) return FALSE; } else if (node->type == MEMORY) { int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; // The data and write enable inputs rely on the values from the previous cycle. if (!strcmp(pin->mapping, "data") || !strcmp(pin->mapping, "data1") || !strcmp(pin->mapping, "data2")) { if (get_pin_cycle(pin) < cycle-1) return FALSE; } else { if (get_pin_cycle(pin) < cycle) return FALSE; } } } else { int i; for (i = 0; i < node->num_input_pins; i++) if (get_pin_cycle(node->input_pins[i]) < cycle) return FALSE; } return TRUE; } /* * Simulates the first cycle by traversing the netlist and returns * the nodes organised into parallelizable stages. Also adds lines to * custom pins and nodes as requested via the -p option. */ static stages_t *simulate_first_cycle(netlist_t *netlist, int cycle, lines_t *l) { std::queue<nnode_t *> queue = std::queue<nnode_t *>(); // Enqueue top input nodes int i; for (i = 0; i < netlist->num_top_input_nodes; i++) { if(is_node_ready(netlist->top_input_nodes[i], cycle)) { netlist->top_input_nodes[i]->in_queue = TRUE; queue.push(netlist->top_input_nodes[i]); } } // Enqueue constant nodes. nnode_t *constant_nodes[] = {netlist->gnd_node, netlist->vcc_node, netlist->pad_node}; int num_constant_nodes = 3; for (i = 0; i < num_constant_nodes; i++) { if(is_node_ready(constant_nodes[i], cycle)) { constant_nodes[i]->in_queue = TRUE; queue.push(constant_nodes[i]); } } nnode_t **ordered_nodes = 0; int num_ordered_nodes = 0; while (! queue.empty()) { nnode_t *node = queue.front(); queue.pop(); compute_and_store_value(node, cycle); // Match node for items passed via -p and add to lines if there's a match. add_additional_items_to_lines(node, l); // Enqueue child nodes which are ready, not already queued, and not already complete. int num_children = 0; nnode_t **children = get_children_of(node, &num_children); for (i = 0; i < num_children; i++) { nnode_t* node2 = children[i]; if (!node2->in_queue && is_node_ready(node2, cycle) && !is_node_complete(node2, cycle)) { node2->in_queue = TRUE; queue.push(node2); } } vtr::free(children); node->in_queue = FALSE; // Add the node to the ordered nodes array. ordered_nodes = (nnode_t **)vtr::realloc(ordered_nodes, sizeof(nnode_t *) * (num_ordered_nodes + 1)); ordered_nodes[num_ordered_nodes++] = node; } // Reorganise the ordered nodes into stages for parallel computation. stages_t *s = stage_ordered_nodes(ordered_nodes, num_ordered_nodes); vtr::free(ordered_nodes); return s; } /* * Puts the ordered nodes in stages, each of which can be computed in parallel. */ static stages_t *stage_ordered_nodes(nnode_t **ordered_nodes, int num_ordered_nodes) { stages_t *s = (stages_t *)vtr::malloc(sizeof(stages_t)); s->stages = (nnode_t ***)vtr::calloc(1,sizeof(nnode_t**)); s->counts = (int *)vtr::calloc(1,sizeof(int)); s->num_children = (int *)vtr::calloc(1,sizeof(int)); s->count = 1; s->num_connections = 0; s->num_nodes = num_ordered_nodes; s->avg_worker_count = 0; s->worker_const = 1; s->worker_temp = 0; s->times =__DBL_MAX__; // Hash tables index the nodes in the current stage, as well as their children. std::unordered_set<nnode_t *> stage_children = std::unordered_set<nnode_t *>(); std::unordered_set<nnode_t *> stage_nodes = std::unordered_set<nnode_t *>(); int i; for (i = 0; i < num_ordered_nodes; i++) { nnode_t* node = ordered_nodes[i]; int stage = s->count-1; // Get the node's children for dependency checks. int num_children; nnode_t **children = get_children_of(node, &num_children); // Determine if the node is a child of any node in the current stage. bool is_child_of_stage = (stage_children.find(node) != stage_children.end()); // Determine if any node in the current stage is a child of this node. bool is_stage_child_of = false; if (!is_child_of_stage) for (int j = 0; j < num_children; j++) if ((is_stage_child_of = (stage_nodes.find(node) != stage_nodes.end()))) break; // Start a new stage if this node is related to any node in the current stage. if (is_child_of_stage || is_stage_child_of) { s->stages = (nnode_t ***)vtr::realloc(s->stages, sizeof(nnode_t**) * (s->count+1)); s->counts = (int *)vtr::realloc(s->counts, sizeof(int) * (s->count+1)); s->num_children = (int *)vtr::realloc(s->num_children, sizeof(int) * (s->count+1)); stage = s->count++; s->stages[stage] = 0; s->counts[stage] = 0; s->num_children[stage] = 0; stage_children.clear(); stage_nodes.clear(); } // Add the node to the current stage. s->stages[stage] = (nnode_t **)vtr::realloc(s->stages[stage],sizeof(nnode_t*) * (s->counts[stage]+1)); s->stages[stage][s->counts[stage]++] = node; // Index the node. stage_nodes.insert(node); //printf("NodeID %ld %s typeof %ld at stage %ld\n",node->unique_id,node->name,node->type,stage); // Index its children. for (int j = 0; j < num_children; j++) { //printf(" ChildID %ld %s typeof %ld \n ",children[j]->unique_id,children[j]->name,children[j]->type); stage_children.insert(children[j]); } // Record the number of children for computing the degree. s->num_connections += num_children; s->num_children[stage] += num_children; vtr::free(children); } stage_children.clear(); stage_nodes.clear(); return s; } //maria //simulate one cycle to determine the parallelization degree of the circuit //returns the number of threads static thread_node_distribution *calculate_thread_distribution(stages_t *s) { //double nodecost = 1; //double extranodeoverhead = 1.0*nodecost; //double lessnodeoverhead = -0.5*nodecost; double nodeoverhead_100 = 100; double nodeoverhead_200 = 200; double nodeoverhead_300 = 300; double nodeoverhead_400 = 400; double stagecost = nodeoverhead_300; //double threadoverheadcost = 5*nodecost; /** not portable * int max_available_threads = get_nprocs(); */ int max_available_threads = number_of_workers; //store nodes for each thread thread_node_distribution* thread_distribution= (thread_node_distribution *)vtr::malloc(sizeof(thread_node_distribution)); //for each stage double *stagescost = (double *)vtr::malloc(sizeof(double)* s->count); double graphcost = 0.0; int all_nodes = get_num_covered_nodes(s); std::map<int, int> nodes_inserted; //nodeId,flag thread_distribution->memory_nodes = (netlist_subset *)vtr::malloc(sizeof(netlist_subset)); int number_of_mem_nodes = 0; nnode_t** nodes_mem_sub = 0; //traverse and calculate the graph cost for(int i = 0; i < s->count; i++) { stagescost[i] = 0.0; nnode_t** nodes = s->stages[i]; //for each node for (int j =0; j < s->counts[i]; j++) { //stagescost[i]+=nodecost; if (nodes[j]->type == GND_NODE || nodes[j]->type == VCC_NODE || nodes[j]->type == OUTPUT_NODE || nodes[j]->type == CLOCK_NODE || nodes[j]->type == PAD_NODE || nodes[j]->type == MUX_2 || nodes[j]->type == LOGICAL_AND) stagescost[i]+=nodeoverhead_100; else if (nodes[j]->type == HARD_IP || nodes[j]->type == GENERIC || nodes[j]->type == MEMORY) stagescost[i]+=nodeoverhead_300; else if (nodes[j]->type == MULTIPLY) stagescost[i]+=nodeoverhead_400; else if (nodes[j]->type == INPUT_NODE) stagescost[i]+=1; else stagescost[i]+=nodeoverhead_200; nodes_inserted[nodes[j]->unique_id] = 0; } graphcost += stagecost+stagescost[i]; } thread_distribution->memory_nodes->number_of_nodes = number_of_mem_nodes; thread_distribution->memory_nodes->nodes = nodes_mem_sub; //printf("graphcost: %lf .\n",graphcost); double threadworkcost = ceil(graphcost/max_available_threads); int num_threads = 0; int current_stage = 0; int node_in_stage = 0; int nodes_assigned = 0; //printf("threadworkcost: %lf .\n",threadworkcost); //for each stage netlist_subset **circuit_borders = (netlist_subset **)vtr::malloc(sizeof(netlist_subset*) * max_available_threads); int threads = ceil(graphcost/threadworkcost); for(int i = 0; i < threads; i++) { circuit_borders[i] = (netlist_subset *)vtr::malloc(sizeof(netlist_subset)); circuit_borders[i]->nodes = 0; } for (int t =0;t<threads && nodes_assigned!=all_nodes;t++) { double threadcost = 0.0; //nodes per thread int number_of_nodes = 0; nnode_t** nodes_sub = 0; //(nnode_t **)vtr::calloc(1,sizeof(nnode_t*)); while (threadcost< threadworkcost) { nnode_t* node = s->stages[current_stage][node_in_stage]; //printf("NodeID %ld assigned to Thread %ld\n",node->unique_id,t); if (nodes_inserted[node->unique_id]==0) { nodes_sub = (nnode_t **)vtr::realloc(nodes_sub,sizeof(nnode_t*) * (number_of_nodes+1) ); nodes_sub[number_of_nodes++] = node; nodes_assigned++; nodes_inserted[node->unique_id] = 1; if (node->type == GND_NODE || node->type == VCC_NODE || node->type == OUTPUT_NODE || node->type == CLOCK_NODE || node->type == PAD_NODE || node->type == MUX_2 || node->type == LOGICAL_AND) threadcost+=nodeoverhead_100; else if (node->type == HARD_IP || node->type == GENERIC || node->type == MEMORY) threadcost+=nodeoverhead_300; else if (node->type == MULTIPLY) threadcost+=nodeoverhead_400; else if (node->type == INPUT_NODE) threadcost+=1; else threadcost+=nodeoverhead_200; //memory family put together if uncomment. not necessary /* int num_children; nnode_t **children = get_children_of(node, &num_children); nnode_t**memory_nodes = 0; int num_memory_nodes = 0; //find all decendeces and ancestors of evey memory node related nnode_t**memory_family = 0; int num_memory_family = 0; for(int child=0;child<num_children;child++) { if (children[child]->type == MEMORY || children[child]->type == HARD_IP) { memory_nodes = (nnode_t **)vtr::realloc(memory_nodes,sizeof(nnode_t*) * (num_memory_nodes+1) ); memory_nodes[num_memory_nodes++] = children[child]; nodes_inserted[children[child]->unique_id] = -1; //to be processed memory_family = (nnode_t **)vtr::realloc(memory_family,sizeof(nnode_t*) * (num_memory_family+1) ); memory_family[num_memory_family++] = children[child]; } } if (num_memory_nodes !=0 ) { int mem_index = 0; while(mem_index !=num_memory_nodes) { nnode_t* memnode = memory_nodes[mem_index]; nodes_inserted[memnode->unique_id] = -1; //printf("memnode tyope of %s\n ",memnode->name); int num_parents; nnode_t **parents = get_parents_of(memnode, &num_parents); for(int parent=0;parent<num_parents;parent++) { if ( nodes_inserted[parents[parent]->unique_id] != -1 ) //if it is not processed here { memory_family = (nnode_t **)vtr::realloc(memory_family,sizeof(nnode_t*) * (num_memory_family+1) ); memory_family[num_memory_family++] = parents[parent]; //printf("NodeP %ld -1\n",parents[parent]->unique_id); if (parents[parent]->type == HARD_IP || parents[parent]->type == MEMORY) //its a memory node add it to the queue { memory_nodes = (nnode_t **)vtr::realloc(memory_nodes,sizeof(nnode_t*) * (num_memory_nodes+1) ); memory_nodes[num_memory_nodes++] = parents[parent]; } else { nodes_inserted[parents[parent]->unique_id] = -1; } } } int num_children; nnode_t **children = get_children_of(memnode, &num_children); for(int child=0;child<num_children;child++) { if ( nodes_inserted[children[child]->unique_id] != -1 ) //if it is not processed here { memory_family = (nnode_t **)vtr::realloc(memory_family,sizeof(nnode_t*) * (num_memory_family+1) ); memory_family[num_memory_family++] = children[child]; if (children[child]->type == HARD_IP || children[child]->type == MEMORY) //its a memory node add it to the queue { memory_nodes = (nnode_t **)vtr::realloc(memory_nodes,sizeof(nnode_t*) * (num_memory_nodes+1) ); memory_nodes[num_memory_nodes++] = children[child]; //nodes_inserted[children[child]->unique_id] = -1; } else { nodes_inserted[children[child]->unique_id] = -1; } } } mem_index++; //printf("mem_index %ld num_memory_family %ld num_memory_nodes%ld \n",mem_index,num_memory_family,num_memory_nodes); } printf("Memory node found \n"); mem_index = 0; for (mem_index=0;mem_index<num_memory_family;mem_index++) { nnode_t* memnode = memory_family[mem_index]; //if (!nodes_inserted[memnode->unique_id]) //{ nodes_sub = (nnode_t **)vtr::realloc(nodes_sub,sizeof(nnode_t*) * (number_of_nodes+1) ); nodes_sub[number_of_nodes++] = memnode; nodes_assigned++; nodes_inserted[memnode->unique_id] = 1; threadcost+=nodecost; if (memnode->type == HARD_IP || memnode->type == GENERIC || memnode->type == MEMORY ) threadcost+=extranodeoverhead; if (memnode->type == GND_NODE || memnode->type == VCC_NODE || memnode->type == INPUT_NODE ) threadcost+=lessnodeoverhead; //} //printf("NodeP %ld 1\n",memnode->unique_id); //printf("Asgnd %ld out of %ld \n",nodes_assigned,all_nodes); } //vtr::free(memory_nodes); //printf(" Node added \n"); } */ } //printf("Next node %ld %ld/%ld \n",node->unique_id,nodes_assigned,all_nodes); if (node_in_stage == s->counts[current_stage]-1) //change stage { node_in_stage = 0; if (current_stage == s->count-1) //last stage { break; } else current_stage++; //next stage } else //same stage next node node_in_stage++; } // add them to the structure circuit_borders[num_threads]->nodes = nodes_sub; circuit_borders[num_threads]->number_of_nodes = number_of_nodes; ++num_threads; } // Create a map iterator and point to beginning of map std::map<int, int>::iterator it = nodes_inserted.begin(); // Iterate over the map using Iterator till end. while (it != nodes_inserted.end()) { // Accessing KEY from element pointed by it. int node_id = it->first; // Accessing VALUE from element pointed by it. int inserted = it->second; if (inserted !=1) { error_message(SIMULATION_ERROR,1475,-1,"Node %ld is not assigned for simulation!",node_id); } // Increment the Iterator to point to next entry it++; } //if (nodes_assigned == FALSE) //{ // error_message(SIMULATION_ERROR,1475,-1, "%s", "Some nodes are not assigned for simulation!"); //} thread_distribution->thread_nodes = circuit_borders; thread_distribution->number_of_threads = num_threads; number_of_workers = num_threads; vtr::free(stagescost); return thread_distribution; } /* * Given a node, this function will simulate that node's new outputs, * and updates those pins. */ static bool compute_and_store_value(nnode_t *node, int cycle) { //double computation_time = wall_time(); is_node_ready(node,cycle); operation_list type = is_clock_node(node)?CLOCK_NODE:node->type; switch(type) { case MUX_2: compute_mux_2_node(node, cycle); break; case FF_NODE: compute_flipflop_node(node, cycle); break; case MEMORY: compute_memory_node(node, cycle); break; case MULTIPLY: compute_multiply_node(node, cycle); break; case LOGICAL_AND: // && { verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; char zero = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 0) { zero = TRUE; break; } } if (zero) update_pin_value(node->output_pins[0], 0, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case LOGICAL_OR: { // || verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; char one = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 1) { one = TRUE; break; } } if (one) update_pin_value(node->output_pins[0], 1, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_NAND: { // !&& verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; char one = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 0) { one = TRUE; break; } } if (one) update_pin_value(node->output_pins[0], 1, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_NOT: // ! case LOGICAL_NOR: // !| { verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; char zero = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 1) { zero = TRUE; break; } } if (zero) update_pin_value(node->output_pins[0], 0, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case LT: // < 010 1 { verify_i_o_availabilty(node, 3, 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin0 == 0 && pin1 == 1 && pin2 == 0) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case GT: // > 100 1 { verify_i_o_availabilty(node, 3, 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin0 == 1 && pin1 == 0 && pin2 == 0) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case ADDER_FUNC: // 001 1\n010 1\n100 1\n111 1 { verify_i_o_availabilty(node, 3, 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if ( (pin0 == 0 && pin1 == 0 && pin2 == 1) || (pin0 == 0 && pin1 == 1 && pin2 == 0) || (pin0 == 1 && pin1 == 0 && pin2 == 0) || (pin0 == 1 && pin1 == 1 && pin2 == 1) ) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case CARRY_FUNC: // 011 1\n100 1\n110 1\n111 1 { verify_i_o_availabilty(node, 3, 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if ( (pin0 == 1 && (pin1 == 1 || pin2 == 1)) || (pin1 == 1 && pin2 == 1) ) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case NOT_EQUAL: // != case LOGICAL_XOR: // ^ { verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; int ones = 0; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; break; } else if (pin == 1) { ones++; } } if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_EQUAL: // == case LOGICAL_XNOR: // !^ { verify_i_o_availabilty(node, -1, 1); char unknown = FALSE; int ones = 0; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; break; } if (pin == 1) { ones++; } } if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 0, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case BITWISE_NOT: { verify_i_o_availabilty(node, 1, 1); signed char pin = get_pin_value(node->input_pins[0], cycle); if (pin < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin == 1) update_pin_value(node->output_pins[0], 0, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case CLOCK_NODE: { if(node->num_input_pins == 0) // driven by file or internally { verify_i_o_availabilty(node, -1, 1); /* if the pin is not an input.. find a clock to drive it.*/ int pin_cycle = get_pin_cycle(node->output_pins[0]); if(pin_cycle != cycle) { if(!node->internal_clk_warn) { node->internal_clk_warn = true; warning_message(SIMULATION_ERROR,-1,-1,"clock(%s) is internally driven, verify your circuit", node->name); } //toggle according to ratio signed char prev_value = !CLOCK_INITIAL_VALUE; if(cycle) prev_value = get_pin_value(node->output_pins[0], cycle-1); if(prev_value < 0) prev_value = !CLOCK_INITIAL_VALUE; signed char cur_value = (cycle % get_clock_ratio(node)) ? prev_value : !prev_value; update_pin_value(node->output_pins[0], cur_value, cycle); } } else // driven by another node { verify_i_o_availabilty(node, 1, 1); int pin_cycle = get_pin_cycle(node->input_pins[0]); if(pin_cycle == cycle) { update_pin_value(node->output_pins[0], get_pin_value(node->input_pins[0],cycle), cycle); } else { if(!node->internal_clk_warn) { node->internal_clk_warn = true; warning_message(SIMULATION_ERROR,-1,-1,"node used as clock (%s) is itself driven by a clock, verify your circuit", node->name); } update_pin_value(node->output_pins[0], get_pin_value(node->input_pins[0],cycle-1), cycle); } } break; } case GND_NODE: verify_i_o_availabilty(node, -1, 1); update_pin_value(node->output_pins[0], 0, cycle); break; case VCC_NODE: verify_i_o_availabilty(node, -1, 1); update_pin_value(node->output_pins[0], 1, cycle); break; case PAD_NODE: verify_i_o_availabilty(node, -1, 1); update_pin_value(node->output_pins[0], 0, cycle); break; case INPUT_NODE: break; case OUTPUT_NODE: verify_i_o_availabilty(node, 1, 1); update_pin_value(node->output_pins[0], get_pin_value(node->input_pins[0],cycle), cycle); break; case HARD_IP: compute_hard_ip_node(node,cycle); break; case GENERIC : compute_generic_node(node,cycle); break; //case FULLADDER: case ADD: compute_add_node(node, cycle, 0); break; case MINUS: if(node->num_input_port_sizes == 3) compute_add_node(node, cycle, 1); else compute_unary_sub_node(node, cycle); break; /* These should have already been converted to softer versions. */ case BITWISE_AND: case BITWISE_NAND: case BITWISE_NOR: case BITWISE_XNOR: case BITWISE_XOR: case BITWISE_OR: case BUF_NODE: case MULTI_PORT_MUX: case SL: case SR: case ASR: case CASE_EQUAL: case CASE_NOT_EQUAL: case DIVIDE: case MODULO: case GTE: case LTE: //case ADD: //case MINUS: default: error_message(SIMULATION_ERROR, 0, -1, "Node should have been converted to softer version: %s", node->name); break; } // Count number of ones and toggles for activity estimation bool covered = true; bool skip_node_from_coverage = ( type == INPUT_NODE || type == CLOCK_NODE || type == GND_NODE || type == VCC_NODE || type == PAD_NODE ); if(!skip_node_from_coverage) { for (int i = 0; i < node->num_output_pins; i++) { if ( node->output_pins[i]->ace_info != NULL ) { signed char pin_value = get_pin_value(node->output_pins[i],cycle); // last_pin_value = get_pin_value(node->output_pins[i],cycle-1); // Pin values for cycle-1 were not correct on Wave boundaries. Needed to store it in ace object. signed char last_pin_value = node->output_pins[i]->ace_info->value; // # of ones if ( pin_value == 1 ) { node->output_pins[i]->ace_info->num_ones += pin_value; } // # of toggles if ( ( pin_value != last_pin_value ) && (last_pin_value != -1 ) ) { node->output_pins[i]->ace_info->num_toggles++; node->output_pins[i]->coverage++; if(node->output_pins[i]->coverage < 2) covered = false; } node->output_pins[i]->ace_info->value = pin_value; } } } if(covered || skip_node_from_coverage) node->covered = true; //computation_time = wall_time() - computation_time; //printf("Node %s typeof %ld spent %lf\n",node->name,type,computation_time); return true; } /* * Gets the number of nodes whose output pins have been sufficiently covered. */ static int get_num_covered_nodes(stages_t *s) { int covered_nodes = 0; for(int i = 0; i < s->count; i++) for (int j = 0; j < s->counts[i]; j++) covered_nodes += (s->stages[i][j]->covered)? 1: 0; return covered_nodes; } /* * Determines if the given node has been simulated for the given cycle. */ static int is_node_complete(nnode_t* node, int cycle) { int i; for (i = 0; i < node->num_output_pins; i++) if (node->output_pins[i] && (get_pin_cycle(node->output_pins[i]) < cycle)) return FALSE; return TRUE; } /* * Changes the ratio of a clock node */ void set_clock_ratio(int rat, nnode_t *node) { //change the value only for clocks if(!is_clock_node(node)) return; node->ratio = rat; } /* * get the ratio of a clock node */ int get_clock_ratio(nnode_t *node) { //change the value only for clocks if(!is_clock_node(node)) return 0; return node->ratio; } /*Gets the parents of the given node. Return the number of * parents via the num_parents parameter.*/ //maria nnode_t **get_parents_of(nnode_t *node, int *num_parents) { nnode_t **parents = 0; int count = 0; int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; nnet_t *net = pin->net; if (pin && net && net->driver_pin->node) { nnode_t *parent_node = net->driver_pin->node; //char *parent_node_name = get_pin_name(parent_node->name); parents = (nnode_t **)vtr::realloc(parents, sizeof(nnode_t*) * (count + 1)); parents[count++] = parent_node; } } *num_parents = count; return parents; } /* * Gets the children of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ nnode_t **get_children_of(nnode_t *node, int *num_children) { nnode_t **children = 0; int count = 0; int i; for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); vtr::free(net_name); vtr::free(pin_name); vtr::free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. children = (nnode_t **)vtr::realloc(children, sizeof(nnode_t*) * (count + 1)); children[count++] = child_node; } } } } } *num_children = count; return children; } /* * Gets the children of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ static int *get_children_pinnumber_of(nnode_t *node, int *num_children) { int *pin_numbers = 0; int count = 0; int i; for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); vtr::free(net_name); vtr::free(pin_name); vtr::free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. pin_numbers = (int *)vtr::realloc(pin_numbers, sizeof(int) * (count + 1)); pin_numbers[count++] = i; } } } } } *num_children = count; return pin_numbers; } /* * Gets the children of a specific output pin of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ nnode_t **get_children_of_nodepin(nnode_t *node, int *num_children, int output_pin) { nnode_t **children = 0; int count = 0; int output_pin_number = node->num_output_pins; if(output_pin < 0 || output_pin > output_pin_number) { error_message(SIMULATION_ERROR, -1, -1, "%s", "Requested pin not available"); return children; } npin_t *pin = node->output_pins[output_pin]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); vtr::free(net_name); vtr::free(pin_name); vtr::free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. children = (nnode_t **)vtr::realloc(children, sizeof(nnode_t*) * (count + 1)); children[count++] = child_node; } } } } *num_children = count; return children; } /* * Allocates memory for the pin's value and cycle. * * Checks to see if this pin's net has a different driver, and * initialises that pin too. * * Fanout pins will share the same memory locations for cycle * and values so that the values don't have to be propagated * through the net. */ static void initialize_pin(npin_t *pin) { // Initialise the driver pin if this pin is not the driver. if (pin->net && pin->net->driver_pin && pin->net->driver_pin != pin) initialize_pin(pin->net->driver_pin); // If initialising the driver initialised this pin, we're OK to return. if (pin->values) return; if (pin->net) { if(!pin->net->values) { pin->net->values = std::make_shared<AtomicBuffer>(init_value(pin->node)); } pin->values = pin->net->values; for (int i = 0; i < pin->net->num_fanout_pins; i++) if (pin->net->fanout_pins[i]) pin->net->fanout_pins[i]->values = pin->net->values; } else { pin->values = std::make_shared<AtomicBuffer>(init_value(pin->node)); } } /* * Updates the value of a pin and its cycle. Pins should be updated using * only this function. * * Initializes the pin if need be. */ static void update_pin_value(npin_t *pin, signed char value, int cycle) { if (pin->values == NULL) initialize_pin(pin); pin->values->update_value(value, cycle); } /* * Gets the value of a pin. Pins should be checked using this function only. */ signed char get_pin_value(npin_t *pin, int cycle) { if (pin->values == NULL) { initialize_pin(pin); } return pin->values->get_value(cycle); } /* * Gets the cycle of the given pin */ static int get_pin_cycle(npin_t *pin) { if (pin->values == NULL) initialize_pin(pin); return pin->values->get_cycle(); } /* * Computes a node of type FF_NODE for the given cycle. */ static void compute_flipflop_node(nnode_t *node, int cycle) { verify_i_o_availabilty(node, 2, 1); npin_t *D = node->input_pins[0]; npin_t *Q = node->output_pins[0]; npin_t *clock_pin = node->input_pins[1]; npin_t *output_pin = node->output_pins[0]; bool trigger = ff_trigger(node->edge_type, clock_pin, cycle); signed char new_value = compute_ff(trigger, D, Q, cycle); update_pin_value(output_pin, new_value, cycle); } /* * Computes a node of type MUX_2 for the given cycle. */ static void compute_mux_2_node(nnode_t *node, int cycle) { verify_i_o_availabilty(node, -1, 1); oassert(node->num_input_port_sizes >= 2); oassert(node->input_port_sizes[0] == node->input_port_sizes[1]); ast_node_t *ast_node = node->related_ast_node; // Figure out which pin is being selected. char unknown = FALSE; int select = -1; int default_select = -1; int i; for (i = 0; i < node->input_port_sizes[0]; i++) { npin_t *pin = node->input_pins[i]; signed char value = get_pin_value(pin, cycle); if (value < 0) unknown = TRUE; else if (value == 1 && select == -1) // Take the first selection only. select = i; /* * If the pin comes from an "else" condition or a case "default" condition, * we favour it in the case where there are unknowns. */ if (ast_node && pin->is_default && (ast_node->type == IF || ast_node->type == CASE)) default_select = i; } // If there are unknowns and there is a default clause, select it. if (unknown && default_select >= 0) { unknown = FALSE; select = default_select; } npin_t *output_pin = node->output_pins[0]; // If any select pin is unknown (and we don't have a default), we take the value from the previous cycle. if (unknown) { /* * Conform to ModelSim's behaviour where in-line ifs are concerned. If the * condition is unknown, the inline if's output is unknown. */ if (ast_node && ast_node->type == IF_Q) update_pin_value(output_pin, -1, cycle); else update_pin_value(output_pin, get_pin_value(output_pin, cycle-1), cycle); } // If no selection is made (all 0) we output x. else if (select < 0) { update_pin_value(output_pin, -1, cycle); } else { npin_t *pin = node->input_pins[select + node->input_port_sizes[0]]; signed char value = get_pin_value(pin,cycle); // Drive implied drivers to unknown value. /*if (pin->is_implied && ast_node && (ast_node->type == CASE)) update_pin_value(output_pin, -1, cycle); else*/ update_pin_value(output_pin, value, cycle); } } // TODO: Needs to be verified. static void compute_hard_ip_node(nnode_t *node, int cycle) { oassert(node->input_port_sizes[0] > 0); oassert(node->output_port_sizes[0] > 0); #ifndef _WIN32 int *input_pins = (int *)vtr::malloc(sizeof(int)*node->num_input_pins); int *output_pins = (int *)vtr::malloc(sizeof(int)*node->num_output_pins); if (!node->simulate_block_cycle) { char *filename = (char *)vtr::malloc(sizeof(char)*strlen(node->name)); if (!strchr(node->name, '.')) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Couldn't extract the name of a shared library for hard-block simulation"); snprintf(filename, sizeof(char)*strlen(node->name), "%s.so", strchr(node->name, '.')+1); void *handle = dlopen(filename, RTLD_LAZY); if (!handle) error_message(SIMULATION_ERROR, 0, -1, "Couldn't open a shared library for hard-block simulation: %s", dlerror()); dlerror(); void (*func_pointer)(int, int, int*, int, int*) = (void(*)(int, int, int*, int, int*))dlsym(handle, "simulate_block_cycle"); char *error = dlerror(); if (error) error_message(SIMULATION_ERROR, 0, -1, "Couldn't load a shared library method for hard-block simulation: %s", error); node->simulate_block_cycle = func_pointer; vtr::free(filename); } int i; for (i = 0; i < node->num_input_pins; i++) input_pins[i] = get_pin_value(node->input_pins[i],cycle); (node->simulate_block_cycle) (cycle, node->num_input_pins, input_pins, node->num_output_pins, output_pins); for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], output_pins[i], cycle); vtr::free(input_pins); vtr::free(output_pins); #else //Not supported oassert(false); #endif } /* * Computes the given multiply node for the given cycle. */ static void compute_multiply_node(nnode_t *node, int cycle) { oassert(node->num_input_port_sizes == 2); oassert(node->num_output_port_sizes == 1); int i; char unknown = FALSE; for (i = 0; i < node->input_port_sizes[0] + node->input_port_sizes[1]; i++) { signed char pin = get_pin_value(node->input_pins[i],cycle); if (pin < 0) { unknown = TRUE; break; } } if (unknown) { for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], -1, cycle); } else { int *a = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[0]); int *b = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[1]); for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); int *result = multiply_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1]); for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[i], cycle); vtr::free(result); vtr::free(a); vtr::free(b); } } // TODO: Needs to be verified. static void compute_generic_node(nnode_t *node, int cycle) { int line_count_bitmap = node->bit_map_line_count; char **bit_map = node->bit_map; int lut_size = 0; while (bit_map[0][lut_size] != 0) lut_size++; int found = 0; int i; for (i = 0; i < line_count_bitmap && (!found); i++) { int j; for (j = 0; j < lut_size; j++) { if (get_pin_value(node->input_pins[j],cycle) < 0) { update_pin_value(node->output_pins[0], -1, cycle); return; } if ((bit_map[i][j] != '-') && (bit_map[i][j]-'0' != get_pin_value(node->input_pins[j],cycle))) break; } if (j == lut_size) found = TRUE; } if (node->generic_output == 1){ if (found) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); } else { if (found) update_pin_value(node->output_pins[0], 0, cycle); else update_pin_value(node->output_pins[0], 1, cycle); } } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their product. The * length of the returned array is twice that of the two parameters. * * This array will need to be freed later! */ static int *multiply_arrays(int *a, int a_length, int *b, int b_length) { int result_size = a_length + b_length; int *result = (int *)vtr::calloc(sizeof(int), result_size); int i; for (i = 0; i < a_length; i++) { if (a[i] == 1) { int j; for (j = 0; j < b_length; j++) result[i+j] += b[j]; } } for (i = 0; i < result_size; i++) { while (result[i] > 1) { result[i] -= 2; result[i+1]++; } } return result; } /* * Computes the given add node for the given cycle. * add by Sen */ static void compute_add_node(nnode_t *node, int cycle, int type) { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 2); int i, num; int flag = 0; int *a = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[0]); int *b = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[1]); int *c = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[2]); num = node->input_port_sizes[0]+ node->input_port_sizes[1]; //if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to ground, flag = 0 the initial adder for addition //if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to vcc, flag = 1 the initial adder for subtraction if(node->input_pins[num]->net->driver_pin->node->type == PAD_NODE) { if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == GND_NODE) flag = 0; else if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == VCC_NODE) flag = 1; } else flag = 2; for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); for (i = 0; i < node->input_port_sizes[2]; i++) //the initial cin of carry chain subtractor should be 1 if(flag == 1) c[i] = 1; //the initial cin of carry chain adder should be 0 else if(flag == 0) c[i] = 0; else c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i],cycle); int *result = add_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1], c, node->input_port_sizes[2],type); //update the pin value of output for (i = 1; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[(i - 1)], cycle); update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle); vtr::free(result); vtr::free(a); vtr::free(b); vtr::free(c); } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their sum. The * length of the returned array is the maximum of the two parameters plus one. * add by Sen * This array will need to be freed later! */ static int *add_arrays(int *a, int a_length, int *b, int b_length, int *c, int /*c_length*/, int /*flag*/) { int result_size = std::max(a_length , b_length) + 1; int *result = (int *)vtr::calloc(sizeof(int), result_size); //least significant bit would use the input carryIn, the other bits would use the compute value //if one of the number is unknown, then the answer should be unknown(same as ModelSim) if(a[0] == -1 || b[0] == -1 || c[0] == -1) { result[0] = -1; result[1] = -1; } else { result[0] = a[0] ^ b[0] ^ c[0]; result[1] = (a[0] & b[0]) | (c[0] & b[0]) | (a[0] & c[0]); } int temp_carry_in = result[1]; if(result_size > 2){ for(int i = 1; i < std::min(a_length,b_length); i++) { if(a[i] == -1 || b[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; } else { result[i] = a[i] ^ b[i] ^ temp_carry_in; result[i+1] = (a[i] & b[i]) | (a[i] & temp_carry_in) | (temp_carry_in & b[i]); } temp_carry_in = result[i+1]; } if(a_length >= b_length) { for(int i = b_length; i < a_length; i++) { if(a[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; } else { result[i] = a[i] ^ temp_carry_in; result[i+1] = a[i] & temp_carry_in; } temp_carry_in = result[i+1]; } } else { for(int i = a_length; i < b_length; i++) { if(b[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; }else { result[i] = b[i] ^ temp_carry_in; result[i+1] = b[i] & temp_carry_in; } temp_carry_in = result[i+1]; } } } return result; } /* * Computes the given add node for the given cycle. * add by Sen */ static void compute_unary_sub_node(nnode_t *node, int cycle) { oassert(node->num_input_port_sizes == 2); oassert(node->num_output_port_sizes == 2); int i; char unknown = FALSE; for (i = 0; i < (node->input_port_sizes[0] + node->input_port_sizes[1]); i++) { signed char pin = get_pin_value(node->input_pins[i],cycle); if (pin < 0) { unknown = TRUE; break; } } if (unknown) { for (i = 0; i < (node->output_port_sizes[0] + node->output_port_sizes[1]); i++) update_pin_value(node->output_pins[i], -1, cycle); } else { int *a = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[0]); int *c = (int *)vtr::malloc(sizeof(int)*node->input_port_sizes[1]); for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) if(node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i]->net->driver_pin->node->type == PAD_NODE) c[i] = 1; else c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); int *result = unary_sub_arrays(a, node->input_port_sizes[0], c, node->input_port_sizes[1]); for (i = 1; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[(i - 1)], cycle); update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle); vtr::free(result); vtr::free(a); vtr::free(c); } } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their sum. The * length of the returned array is the maximum of the two parameters plus one. * add by Sen * This array will need to be freed later! */ static int *unary_sub_arrays(int *a, int a_length, int *c, int /*c_length*/) { int result_size = a_length + 1; int *result = (int *)vtr::calloc(sizeof(int), result_size); int i; int temp_carry_in; c[0] = 1; result[0] = (!a[0]) ^ c[0] ^ 0; result[1] = ((!a[0]) & 0) | (c[0] & 0) | ((!a[0]) & c[0]); temp_carry_in = result[1]; if(result_size > 2){ for(i = 1; i < a_length; i++) { result[i] = (!a[i]) ^ 0 ^ temp_carry_in; result[i+1] = ((!a[i]) & 0) | ((!a[i]) & temp_carry_in) | (temp_carry_in & 0); temp_carry_in = result[i+1]; } } return result; } /* * Computes the given memory node. */ static void compute_memory_node(nnode_t *node, int cycle) { if (is_sp_ram(node)) compute_single_port_memory(node, cycle); else if (is_dp_ram(node)) compute_dual_port_memory(node, cycle); else error_message(SIMULATION_ERROR, 0, -1, "Could not resolve memory hard block %s to a valid type.", node->name); } /** * compute the address */ static long compute_address(signal_list_t *input_address, int cycle) { long address = 0; for (long i = 0; i < input_address->count && address >= 0; i++) { // If any address pins are x's, write x's we return -1. signed char value = get_pin_value(input_address->pins[i],cycle); if (value != 1 && value != 0) address = -1; else address += shift_left_value_with_overflow_check(value, i); } return address; } static void read_write_to_memory(nnode_t *node , signal_list_t *input_address, signal_list_t *data_out, signal_list_t *data_in, bool trigger, npin_t *write_enabled, int cycle) { long address = compute_address(input_address, cycle); //make a single trigger out of write_enable pin and if it was a positive edge bool write = (trigger && 1 == get_pin_value(write_enabled, cycle)); bool address_is_valid = (address >= 0 && address < node->memory_data.size()); /* init the vector with all -1 */ std::vector<signed char> new_values(data_out->count, -1); if(address_is_valid) { // init from memory pins first from previous value new_values = node->memory_data[address]; // if it is a valid write, grap the input pin and store those in a vector if (write) { for (long i = 0; i < data_out->count; i++) { new_values[i]= get_pin_value(data_in->pins[i],cycle-1); } } if (false == global_args.parralelized_simulation_in_batch) { node->memory_data[address] = new_values; } /** * use dictionnary when there are multiple workers */ else { /********* Critical section */ /* LOCK */node->memory_mtx.lock(); if(write) { if ( node->memory_directory.find(cycle) == node->memory_directory.end() ) { node->memory_directory[cycle] = {}; } node->memory_directory[cycle][address]= new_values; } /** * read from the dictionary if exist otherwise use current mem_data value */ else /* READ */ { for ( auto it = node->memory_directory.begin(); it != node->memory_directory.end(); it++ ) { int recorded_cycle = it->first; if (recorded_cycle <= cycle && ( node->memory_directory[recorded_cycle].find(address) != node->memory_directory[recorded_cycle].end() )) { new_values = node->memory_directory[recorded_cycle][address]; } } } /* UNLOCK */node->memory_mtx.unlock(); } } /** * now we update the output pins */ for (long i = 0; i < data_out->count; i++) { update_pin_value(data_out->pins[i], new_values[i], cycle); } } static void write_back_memory_nodes(nnode_t **nodes, int num_nodes) { int num; //printf("here\n"); for(num=0;num<num_nodes;num++) { nnode_t* node = nodes[num]; if (!node->memory_directory.empty()) { std::map<int,std::map<long,std::vector<signed char>>>::iterator it; for ( it = node->memory_directory.begin(); it != node->memory_directory.end(); it++ ) { int recorded_cycle = it->first; std::map<long,std::vector<signed char>>::iterator cit; for ( cit = node->memory_directory[recorded_cycle].begin(); cit != node->memory_directory[recorded_cycle].end(); cit++ ) { long address = cit->first; std::vector<signed char> new_values = cit->second; node->memory_data[address] = new_values; } node->memory_directory[recorded_cycle] = {}; } node->memory_directory={}; } } } /* * Computes single port memory. */ static void compute_single_port_memory(nnode_t *node, int cycle) { sp_ram_signals *signals = get_sp_ram_signals(node); bool trigger = ff_trigger(RISING_EDGE_SENSITIVITY, signals->clk, cycle); if (node->memory_data.empty()) instantiate_memory(node, signals->data->count, signals->addr->count); read_write_to_memory(node, signals->addr, signals->out, signals->data, trigger, signals->we, cycle); free_sp_ram_signals(signals); } /* * Computes dual port memory. */ static void compute_dual_port_memory(nnode_t *node, int cycle) { dp_ram_signals *signals = get_dp_ram_signals(node); bool trigger = ff_trigger(RISING_EDGE_SENSITIVITY, signals->clk, cycle); if (node->memory_data.empty()) instantiate_memory(node, std::max(signals->data1->count, signals->data2->count), std::max(signals->addr1->count,signals->addr2->count) ); read_write_to_memory(node, signals->addr1, signals->out1, signals->data1, trigger, signals->we1, cycle); read_write_to_memory(node, signals->addr2, signals->out2, signals->data2, trigger, signals->we2, cycle); free_dp_ram_signals(signals); } /* * Initialises memory using a memory information file (mif). If not * file is found, it is initialised to x's. */ static void instantiate_memory(nnode_t *node, long data_width, long addr_width) { long max_address = shift_left_value_with_overflow_check(0x1, addr_width); node->memory_data = std::vector<std::vector<signed char>>(max_address, std::vector<signed char>(data_width, init_value(node))); if(global_args.read_mif_input) { char *filename = get_mif_filename(node); FILE *mif = fopen(filename, "r"); if (!mif) { printf("MIF %s (%ldx%ld) not found. \n", filename, data_width, addr_width); } else { assign_memory_from_mif_file(node, mif, filename, data_width, addr_width); fclose(mif); } vtr::free(filename); } } /* * Removes white space (except new lines) and comments from * the given mif file and returns the resulting temporary file. */ static FILE *preprocess_mif_file(FILE *source) { FILE *destination = tmpfile(); destination = freopen(NULL, "r+", destination); rewind(source); char line[BUFFER_MAX_SIZE]; int in_multiline_comment = FALSE; while (fgets(line, BUFFER_MAX_SIZE, source)) { unsigned int i; for (i = 0; i < strlen(line); i++) { if (!in_multiline_comment) { // For a single line comment, skip the rest of the line. if (line[i] == '-' && line[i+1] == '-') break; // Start of a multiline comment else if (line[i] == '%') in_multiline_comment = TRUE; // Don't copy any white space over. else if (line[i] != '\n' && line[i] != ' ' && line[i] != '\r' && line[i] != '\t' ) fputc(line[i], destination); } else { // If we're in a multi-line comment, search for the % if (line[i] == '%') in_multiline_comment = FALSE; } } fputc('\n', destination); } rewind(destination); return destination; } static int parse_mif_radix(std::string radix) { return (radix == "HEX") ? 16: (radix == "DEC") ? 10: (radix == "OCT") ? 8: (radix == "BIN") ? 2: 0; } static void assign_memory_from_mif_file(nnode_t *node, FILE *mif, char *filename, int width, long address_width) { FILE *file = preprocess_mif_file(mif); rewind(file); std::unordered_map<std::string, std::string> symbols = std::unordered_map<std::string, std::string>(); char buffer_in[BUFFER_MAX_SIZE]; bool in_content = false; std::string last_line; int line_number = 0; int addr_radix = 0; int data_radix = 0; while (fgets(buffer_in, BUFFER_MAX_SIZE, file)) { line_number++; // Remove the newline. trim_string(buffer_in, "\n"); std::string buffer = buffer_in; // Only process lines which are not empty. if (buffer.size()) { // MIF files are case insensitive string_to_upper(buffer_in); // The content section of the file contains address:value; assignments. if (in_content) { // Parse at the : char *token = strtok(buffer_in, ":"); if (strlen(token)) { // END; signifies the end of the file. if(buffer == "END;") break; // The part before the : is the address. char *address_string = token; token = strtok(NULL, ";"); // The reset (before the ;) is the data_value. char *data_string = token; if (token) { // Make sure the address and value are valid strings of the specified radix. if (!is_string_of_radix(address_string, addr_radix)) error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is not a base %ld string.", filename, address_string, addr_radix); if (!is_string_of_radix(data_string, data_radix)) error_message(SIMULATION_ERROR, line_number, -1, "%s: data string %s is not a base %ld string.", filename, data_string, data_radix); char *binary_data = convert_string_of_radix_to_bit_string(data_string, data_radix, width); long address = convert_string_of_radix_to_long(address_string, addr_radix); if (address > address_width) error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is out of range.", filename, address_string); // Write the parsed value string to the memory location. for(int i=0; i<width; i++) node->memory_data[address][i] = binary_data[i] - '0'; } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error.", filename); } } } // The header section of the file contains parameters given as PARAMETER=value; else { // Grab the bit before the = sign. char *token = strtok(buffer_in, "="); if (strlen(token)) { char *symbol = token; token = strtok(NULL, ";"); // If is something after the equals sign and before the semicolon, add the symbol=value association to the symbol table. if (token) symbols.insert({symbol, token}); else if(buffer == "CONTENT") {} // We found "CONTENT" followed on the next line by "BEGIN". That means we're at the end of the parameters. else if(buffer == "BEGIN" && last_line == "CONTENT") { // Sanity check parameters to make sure we have what we need. std::unordered_map<std::string,std::string>::const_iterator item_in; // Verify the width parameter. item_in = symbols.find("WIDTH"); if ( item_in == symbols.end() ) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF WIDTH parameter unspecified.", filename); long mif_width = std::strtol(item_in->second.c_str(),NULL,10); if (mif_width != width) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF width mismatch: must be %ld but %ld was given", filename, width, mif_width); // Verify the depth parameter. item_in = symbols.find("DEPTH"); if ( item_in == symbols.end() ) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF DEPTH parameter unspecified.", filename); long mif_depth = std::strtol(item_in->second.c_str(),NULL,10); long expected_depth = shift_left_value_with_overflow_check(0x1, address_width); if (mif_depth != expected_depth) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF depth mismatch: must be %ld but %ld was given", filename, expected_depth, mif_depth); // Parse the radix specifications and make sure they're OK. item_in = symbols.find("ADDRESS_RADIX"); if ( item_in == symbols.end() ) error_message(SIMULATION_ERROR, -1, -1, "%s: ADDRESS_RADIX parameter unspecified.", filename); addr_radix = parse_mif_radix(item_in->second); if (!addr_radix) error_message(SIMULATION_ERROR, -1, -1, "%s: invalid or missing ADDRESS_RADIX: must specify DEC, HEX, OCT, or BIN", filename); item_in = symbols.find("DATA_RADIX"); if ( item_in == symbols.end() ) error_message(SIMULATION_ERROR, -1, -1, "%s: DATA_RADIX parameter unspecified.", filename); data_radix = parse_mif_radix(item_in->second); if (!data_radix) error_message(SIMULATION_ERROR, -1, -1, "%s: invalid or missing DATA_RADIX: must specify DEC, HEX, OCT, or BIN", filename); // If everything checks out, start reading the values. in_content = true; } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, buffer_in); } } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, buffer_in); } } last_line = buffer; } } fclose(file); } /* * Assigns the given node to its corresponding line in the given array of line. * Assumes the line has already been created. */ static void assign_node_to_line(nnode_t *node, lines_t *l, int type, int single_pin) { // Make sure the node has an output pin. if (!node->num_output_pins) { npin_t *pin = allocate_npin(); allocate_more_output_pins(node, 1); add_output_pin_to_node(node, pin, 0); } // Parse the node name into a pin number and a port name. int pin_number = get_pin_number(node->name); char *port_name; if (pin_number != -1 && !single_pin) { port_name = get_port_name(node->name); } else { port_name = get_pin_name(node->name); single_pin = TRUE; } // Search the lines for the port name. int j = find_portname_in_lines(port_name, l); vtr::free(port_name); if (single_pin) { if (j == -1) { warning_message(SIMULATION_ERROR, 0, -1, "Could not map single-bit node '%s' line", node->name); } else { pin_number = (pin_number == -1)?0:pin_number; int already_added = l->lines[j]->number_of_pins >= 1; if (!already_added) insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type); } } else { if (j == -1) warning_message(SIMULATION_ERROR, 0, -1, "Could not map multi-bit node '%s' to line", node->name); else insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type); } } /* * Inserts the given pin according to its pin number into the given line. */ static void insert_pin_into_line(npin_t *pin, int pin_number, line_t *line, int type) { // Allocate memory for the new pin. line->pins = (npin_t **)vtr::realloc(line->pins, sizeof(npin_t*) * (line->number_of_pins + 1)); line->pin_numbers = (int *)vtr::realloc(line->pin_numbers, sizeof(npin_t*) * (line->number_of_pins + 1)); // Find the proper place to insert this pin, and make room for it. int i; for (i = 0; i < line->number_of_pins; i++) { if (line->pin_numbers[i] > pin_number) { // Move other pins to the right to make room. int j; for (j = line->number_of_pins; j > i; j--) { line->pins[j] = line->pins[j-1]; line->pin_numbers[j] = line->pin_numbers[j-1]; } break; } } // Add the new pin. line->pins[i] = pin; line->pin_numbers[i] = pin_number; line->type = type; line->number_of_pins++; } /* * Given a netlist, this function maps the top_input_nodes * or top_output_nodes depending on the value of type * (INPUT or OUTPUT) to a line_t each. It stores them in a * lines_t struct and returns a pointer to it. */ static lines_t *create_lines(netlist_t *netlist, int type) { lines_t *l = (lines_t *)vtr::malloc(sizeof(lines_t)); l->lines = 0; l->count = 0; int num_nodes = (type == INPUT)?netlist->num_top_input_nodes:netlist->num_top_output_nodes; nnode_t **nodes = (type == INPUT)?netlist->top_input_nodes :netlist->top_output_nodes; int i; for (i = 0; i < num_nodes; i++) { nnode_t *node = nodes[i]; char *port_name = get_port_name(node->name); if (find_portname_in_lines(port_name, l) == -1) { line_t *line = create_line(port_name); l->lines = (line_t **)vtr::realloc(l->lines, sizeof(line_t *)*(l->count + 1)); l->lines[l->count++] = line; } assign_node_to_line(node, l, type, 0); /** * TODO: implicit memories with multiclock input (one for read and one for write) * is broken, need fixing */ if(is_clock_node(node)) set_clock_ratio(++num_of_clock,node); vtr::free(port_name); } return l; } /* * Creates a vector file header from the given lines, * and writes it to the given file. */ static void write_vector_headers(FILE *file, lines_t *l) { char* headers = generate_vector_header(l); fprintf(file, "%s", headers); vtr::free(headers); fflush(file); } /* * Parses the first line of the given file and compares it to the * given lines for identity. If there is any difference, a warning is printed, * and FALSE is returned. If there are no differences, the file pointer is left * at the start of the second line, and TRUE is returned. */ static int verify_test_vector_headers(FILE *in, lines_t *l) { int current_line = 0; int buffer_length = 0; // Read the header from the vector file. char read_buffer [BUFFER_MAX_SIZE]; rewind(in); if (!get_next_vector(in, read_buffer)) error_message(SIMULATION_ERROR, 0, -1, "%s\n", "Failed to read vector headers."); // Parse the header, checking each entity against the corresponding line. char buffer [BUFFER_MAX_SIZE]; buffer[0] = '\0'; unsigned int i; for (i = 0; i < strlen(read_buffer) && i < BUFFER_MAX_SIZE; i++) { char next = read_buffer[i]; if (next == EOF) { warning_message(SIMULATION_ERROR, 0, -1, "%s", "Hit end of file."); return FALSE; } else if (next == ' ' || next == '\t' || next == '\n') { if (buffer_length) { if(strcmp(l->lines[current_line]->name,buffer)) { char *expected_header = generate_vector_header(l); warning_message(SIMULATION_ERROR, 0, -1, "Vector header mismatch: \n " " Found: %s " " Expected: %s", read_buffer, expected_header); vtr::free(expected_header); return FALSE; } else { buffer_length = 0; current_line++; } } if (next == '\n') break; } else { buffer[buffer_length++] = next; buffer[buffer_length] = '\0'; } } return TRUE; } /* * Verifies that no lines have null pins. */ static int verify_lines (lines_t *l) { int i; for (i = 0; i < l->count; i++) { int j; for (j = 0; j < l->lines[i]->number_of_pins; j++) { if (!l->lines[i]->pins[j]) { warning_message(SIMULATION_ERROR, 0, -1, "A line %ld:(%s) has a NULL pin. ", j, l->lines[i]->name); return FALSE; } } } return TRUE; } /* * Searches for a line with the given name in the lines. Returns the index * or -1 if no such line was found. */ static int find_portname_in_lines(char* port_name, lines_t *l) { int j; for (j = 0; j < l->count; j++) if (!strcmp(l->lines[j]->name, port_name)) return j; return -1; } /* * allocates memory for and initialises a line_t struct */ static line_t *create_line(char *name) { line_t *line = (line_t *)vtr::malloc(sizeof(line_t)); line->number_of_pins = 0; line->pins = 0; line->pin_numbers = 0; line->type = -1; line->name = (char *)vtr::malloc(sizeof(char)*(strlen(name)+1)); strcpy(line->name, name); return line; } /* * Generates the appropriate vector headers based on the given lines. */ static char *generate_vector_header(lines_t *l) { char *header = (char *)vtr::calloc(BUFFER_MAX_SIZE, sizeof(char)); if (l->count) { int j; for (j = 0; j < l->count; j++) { // "+ 2" for null and newline/space. if ((strlen(header) + strlen(l->lines[j]->name) + 2) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "%s", "Buffer overflow anticipated while generating vector header."); strcat(header,l->lines[j]->name); strcat(header," "); } header[strlen(header)-1] = '\n'; } else { header[0] = '\n'; } header = (char *)vtr::realloc(header, sizeof(char)*(strlen(header)+1)); return header; } /* * Stores the given test vector in the given lines, with some sanity checking to ensure that it * has a compatible geometry. */ static void add_test_vector_to_lines(test_vector *v, lines_t *l, int cycle) { if (l->count < v->count) error_message(SIMULATION_ERROR, 0, -1, "Fewer lines (%ld) than values (%ld).", l->count, v->count); if (l->count > v->count) error_message(SIMULATION_ERROR, 0, -1, "More lines (%ld) than values (%ld).", l->count, v->count); int i; for (i = 0; i < v->count; i++) { line_t *line = l->lines[i]; if (line->number_of_pins < 1) error_message(SIMULATION_ERROR, 0, -1, "Found a line '%s' with no pins.", line->name); int j; for (j = 0; j < line->number_of_pins; j++) { if (j < v->counts[i]) update_pin_value(line->pins[j], v->values[i][j], cycle); else update_pin_value(line->pins[j], 0, cycle); } } } /* * Compares two test vectors for numerical and geometric identity. Returns FALSE if * they are found to be different, and TRUE otherwise. */ static int compare_test_vectors(test_vector *v1, test_vector *v2) { int equivalent = TRUE; if (v1->count != v2->count) { warning_message(SIMULATION_ERROR, 0, -1, "%s", "Vector lengths differ."); return FALSE; } int l; for (l = 0; l < v1->count; l++) { // Compare bit by bit. int i; for (i = 0; i < v1->counts[l] && i < v2->counts[l]; i++) { if (v1->values[l][i] != v2->values[l][i]) { if (v1->values[l][i] == -1) equivalent = -1; else return FALSE; } } /* * If one value has more bits than the other, they are still * equivalent as long as the higher order bits of the longer * one are zero. */ if (v1->counts[l] != v2->counts[l]) { test_vector *v = v1->counts[l] < v2->counts[l] ? v2 : v1; int j; for (j = i; j < v->counts[l]; j++) if (v->values[l][j] != 0) return FALSE; } } return equivalent; } /* * Parses the given line from a test vector file into a * test_vector data structure. */ static test_vector *parse_test_vector(char *buffer) { buffer = vtr::strdup(buffer); test_vector *v = (test_vector *)vtr::malloc(sizeof(test_vector)); v->values = 0; v->counts = 0; v->count = 0; trim_string(buffer,"\r\n"); const char *delim = " \t"; char *token = strtok(buffer, delim); while (token) { v->values = (signed char **)vtr::realloc(v->values, sizeof(signed char *) * (v->count + 1)); v->counts = (int *)vtr::realloc(v->counts, sizeof(int) * (v->count + 1)); v->values[v->count] = 0; v->counts[v->count] = 0; if (token[0] == '0' && (token[1] == 'x' || token[1] == 'X')) { // Value is hex. token += 2; int token_length = strlen(token); reverse_string(token, token_length); int i; for (i = 0; i < token_length; i++) { char temp[] = {token[i],'\0'}; int value = strtol(temp, NULL, 16); int k; for (k = 0; k < 4; k++) { signed char bit = 0; if (value > 0) { bit = value % 2; value /= 2; } v->values[v->count] = (signed char *)vtr::realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = bit; } } } else { // Value is binary. int i; for (i = strlen(token) - 1; i >= 0; i--) { signed char value = -1; if (token[i] == '0') value = 0; else if (token[i] == '1') value = 1; v->values[v->count] = (signed char *)vtr::realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = value; } } v->count++; token = strtok(NULL, delim); } vtr::free(buffer); return v; } /* * Generates a "random" test_vector structure based on the geometry of the given lines. * * If you want better randomness, call srand at some point. */ static bool contains_a_substr_of_name(std::vector<std::string> held, const char *name_in) { if(!name_in) return false; if(held.empty()) return false; std::string name = name_in; std::transform(name.begin(), name.end(), name.begin(), ::tolower); for(std::string sub_str: held) { std::transform(sub_str.begin(), sub_str.end(), sub_str.begin(), ::tolower); if(name.find(sub_str) != std::string::npos) return true; } return false; } static test_vector *generate_random_test_vector(int cycle, sim_data_t *sim_data) { /** * generate test vectors */ test_vector *v = (test_vector *)vtr::malloc(sizeof(test_vector)); v->values = 0; v->counts = 0; v->count = 0; for (int i = 0; i < sim_data->input_lines->count; i++) { v->values = (signed char **)vtr::realloc(v->values, sizeof(signed char *) * (v->count + 1)); v->counts = (int *)vtr::realloc(v->counts, sizeof(int) * (v->count + 1)); v->values[v->count] = 0; v->counts[v->count] = 0; line_t *line = sim_data->input_lines->lines[i]; for (int j = 0; j < line->number_of_pins; j++) { //default signed char value = (rand() % 2); npin_t *pin = line->pins[j]; signed char clock_ratio = get_clock_ratio(pin->node); /******************************************************** * if it is a clock node, use it's ratio to generate a cycle */ if(clock_ratio > 0) { if(!cycle) value = CLOCK_INITIAL_VALUE; else { signed char previous_cycle_clock_value = get_pin_value(pin, cycle-1); if((cycle%(clock_ratio)) == 0) { if(previous_cycle_clock_value == 0) value = 1; else value = 0; } else value = previous_cycle_clock_value; } } /******************************************************** * use input override to set the pin value to hold high if requested */ else if(contains_a_substr_of_name(global_args.sim_hold_high.value(),line->name)) { if (cycle < (num_of_clock*3)) value = 0; // start with reverse value else value = 1; // then hold to requested value } /******************************************************** * use input override to set the pin value to hold low if requested */ else if(contains_a_substr_of_name(global_args.sim_hold_low.value(),line->name)) { if (cycle < (num_of_clock*3)) value = 1; // start with reverse value else value = 0; // then hold to requested value } /******************************************************** * set the value via the -3 option */ else if( global_args.sim_generate_three_valued_logic) { value = (rand() % 3) - 1; } v->values[v->count] = (signed char *)vtr::realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = value; } v->count++; } return v; } /* * Writes a wave of vectors to the given file. Writes the headers * prior to cycle 0. * * When edge is -1, both edges of the clock are written. When edge is 0, * the falling edge is written. When edge is 1, the rising edge is written. */ static void write_cycle_to_file(lines_t *l, FILE* file, int cycle) { if (!cycle) write_vector_headers(file, l); write_vector_to_file(l, file, cycle); } /* * Writes all values in the given lines to a line in the given file * for the given cycle. */ static void write_vector_to_file(lines_t *l, FILE *file, int cycle) { std::stringstream buffer; int i; for (i = 0; i < l->count; i++) { buffer.str(std::string()); line_t *line = l->lines[i]; int num_pins = line->number_of_pins; if (line_has_unknown_pin(line, cycle) || num_pins == 1) { if ((num_pins + 1) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name); int j; for (j = num_pins - 1; j >= 0 ; j--) { signed char value = get_line_pin_value(line, j, cycle); if (value > 1){ error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %ld read from line %s.", value, line->name); }else if(value < 0){ buffer << "x"; }else{ buffer << std::dec <<(int)value; } } // If there are no known values, print a single capital X. // (Only for testing. Breaks machine readability.) //if (!known_values && num_pins > 1) // odin_sprintf(buffer, "X"); } else { // +1 for ceiling, +1 for null, +2 for "OX" if ((num_pins/4 + 1 + 1 + 2) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name); buffer << "0X"; int hex_digit = 0; int j; for (j = num_pins - 1; j >= 0; j--) { signed char value = get_line_pin_value(line,j,cycle); if (value > 1) error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %ld read from line %s.", value, line->name); hex_digit += value << j % 4; if (!(j % 4)) { buffer << std::hex << hex_digit; hex_digit = 0; } } } buffer << " "; // Expand the value to fill to space under the header. (Gets ugly sometimes.) //while (strlen(buffer) < strlen(l->lines[i]->name)) // strcat(buffer," "); fprintf(file,"%s",buffer.str().c_str()); } fprintf(file, "\n"); } /* * Writes a wave of vectors to the given modelsim out file. */ static void write_cycle_to_modelsim_file(netlist_t *netlist, lines_t *l, FILE* modelsim_out, int cycle) { if (!cycle) { fprintf(modelsim_out, "add wave *\n"); // Add clocks to the output file. int i; for (i = 0; i < netlist->num_top_input_nodes; i++) { nnode_t *node = netlist->top_input_nodes[i]; if (is_clock_node(node)) { char *port_name = get_port_name(node->name); fprintf(modelsim_out, "force %s 0 0, 1 50 -repeat 100\n", port_name); vtr::free(port_name); } } } write_vector_to_modelsim_file(l, modelsim_out, cycle); } /* * Writes a vector to the given modelsim out file. */ static void write_vector_to_modelsim_file(lines_t *l, FILE *modelsim_out, int cycle) { int i; for (i = 0; i < l->count; i++) { if (line_has_unknown_pin(l->lines[i], cycle) || l->lines[i]->number_of_pins == 1) { fprintf(modelsim_out, "force %s ",l->lines[i]->name); int j; for (j = l->lines[i]->number_of_pins - 1; j >= 0 ; j--) { int value = get_line_pin_value(l->lines[i],j,cycle); if (value < 0) fprintf(modelsim_out, "%s", "x"); else fprintf(modelsim_out, "%d", value); } fprintf(modelsim_out, " %d\n", cycle/2 * 100); } else { int value = 0; fprintf(modelsim_out, "force %s 16#", l->lines[i]->name); int j; for (j = l->lines[i]->number_of_pins - 1; j >= 0; j--) { if (get_line_pin_value(l->lines[i],j,cycle) > 0) value += my_power(2, j % 4); if (j % 4 == 0) { fprintf(modelsim_out, "%X", value); value = 0; } } fprintf(modelsim_out, " %d\n", cycle/2 * 100); } } } /* * Verify that the given output vector file is identical (numerically) * to the one written by the current simulation. This is done by parsing each * file vector by vector and comparing them. Also verifies that the headers are identical. * * Prints appropriate warning messages when differences are found. * * Returns false if the files differ and true if they are identical, with the exception of * number format. */ static int verify_output_vectors(char* output_vector_file, int num_vectors) { int error = FALSE; // The filename cannot be the same as our default output file. if (!strcmp(output_vector_file,OUTPUT_VECTOR_FILE_NAME)) { error = TRUE; warning_message(SIMULATION_ERROR,0,-1, "Vector file \"%s\" given for verification " "is the same as the default output file \"%s\". " "Ignoring.", output_vector_file, OUTPUT_VECTOR_FILE_NAME); } else { // The file being verified against. FILE *existing_out = fopen(output_vector_file, "r"); if (!existing_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector output file: %s", output_vector_file); // Our current output vectors. (Just produced.) char out_vec_file[BUFFER_MAX_SIZE] = { 0 }; odin_sprintf(out_vec_file,"%s/%s",((char *)global_args.sim_directory),OUTPUT_VECTOR_FILE_NAME); FILE *current_out = fopen(out_vec_file, "r"); if (!current_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open output vector file: %s", out_vec_file); int cycle; char buffer1[BUFFER_MAX_SIZE]; char buffer2[BUFFER_MAX_SIZE]; // Start at cycle -1 to check the headers. for (cycle = -1; cycle < num_vectors; cycle++) { if (!get_next_vector(existing_out, buffer1)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"Too few vectors in %s \n", output_vector_file); break; } else if (!get_next_vector(current_out, buffer2)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"Simulation produced fewer than %ld vectors. \n", num_vectors); break; } // The headers differ. else if ((cycle == -1) && strcmp(buffer1,buffer2)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1, "Vector headers do not match: \n" "\t%s" "in %s does not match\n" "\t%s" "in %s.\n\n", buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file ); break; } else { // Parse both vectors. test_vector *v1 = parse_test_vector(buffer1); test_vector *v2 = parse_test_vector(buffer2); int equivalent = compare_test_vectors(v1,v2); // Compare them and print an appropriate message if they differ. if (!equivalent) { trim_string(buffer1, "\n\t"); trim_string(buffer2, "\n\t"); error = TRUE; warning_message(SIMULATION_ERROR, 0, -1, "Vector %ld mismatch:\n" "\t%s in %s\n" "\t%s in %s\n", cycle, buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file ); } else if (equivalent == -1) { trim_string(buffer1, "\n\t"); trim_string(buffer2, "\n\t"); warning_message(SIMULATION_ERROR, 0, -1, "Vector %ld equivalent but output vector has bits set when expecting don't care :\n" "\t%s in %s\n" "\t%s in %s\n", cycle, buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file ); } free_test_vector(v1); free_test_vector(v2); } } // If the file we're checking against is longer than the current output, print an appropriate warning. if (!error && get_next_vector(existing_out, buffer1)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"%s contains more than %ld vectors.\n", output_vector_file, num_vectors); } fclose(existing_out); fclose(current_out); } return !error; } /* * If the given node matches one of the additional names (passed via -p), * it's added to the lines. (Matches on output pin names, net names, and node names). */ static void add_additional_items_to_lines(nnode_t *node, lines_t *l) { std::vector<std::string> p = global_args.sim_additional_pins.value(); if (!p.empty()) { int add = FALSE; int j, k = 0; // Search the output pin names for each user-defined item. for (j = 0; j < node->num_output_pins; j++) { npin_t *pin = node->output_pins[j]; if (pin->name) { for (k = 0; k < p.size(); k++) { if (strstr(pin->name, p[k].c_str())) { add = TRUE; break; } } if (add) break; } if (pin->net && pin->net->name) { for (k = 0; k < p.size(); k++) { if (strstr(pin->net->name, p[k].c_str())) { add = TRUE; break; } } if (add) break; } } // Search the node name for each user defined item. if (!add && node->name && strlen(node->name) && strchr(node->name, '^')) { for (k = 0; k < p.size(); k++) { if (strstr(node->name, p[k].c_str())) { add = TRUE; break; } } } if (add) { int single_pin = strchr(p[k].c_str(), '~')?1:0; if (strchr(node->name, '^')) { char *port_name; if (single_pin) port_name = get_pin_name(node->name); else port_name = get_port_name(node->name); if (find_portname_in_lines(port_name, l) == -1) { line_t *line = create_line(port_name); l->lines = (line_t **)vtr::realloc(l->lines, sizeof(line_t *)*((l->count)+1)); l->lines[l->count++] = line; } assign_node_to_line(node, l, OUTPUT, single_pin); vtr::free(port_name); } } } } /* * Parses the given (memory) node name into a corresponding * mif file name. */ static char *get_mif_filename(nnode_t *node) { char buffer[BUFFER_MAX_SIZE]; buffer[0] = 0; strcat(buffer, node->name); char *filename = strrchr(buffer, '+'); if (filename) filename += 1; else filename = buffer; strcat(filename, ".mif"); filename = vtr::strdup(filename); return filename; } /* * Returns TRUE if the given line has a pin for * the given cycle whose value is -1. */ static int line_has_unknown_pin(line_t *line, int cycle) { int unknown = FALSE; int j; for (j = line->number_of_pins - 1; j >= 0; j--) { if (get_line_pin_value(line, j, cycle) < 0) { unknown = TRUE; break; } } return unknown; } /* * Gets the value of the pin given pin within the given line * for the given cycle. */ signed char get_line_pin_value(line_t *line, int pin_num, int cycle) { return get_pin_value(line->pins[pin_num],cycle); } /* * Returns a value from a test_vectors struct in hex. Works * for the values arrays in pins as well. */ static char *vector_value_to_hex(signed char *value, int length) { char *tmp; char *string = (char *)vtr::calloc((length + 1),sizeof(char)); int j; for (j = 0; j < length; j++) string[j] = value[j] + '0'; reverse_string(string,strlen(string)); char *hex_string = (char *)vtr::malloc(sizeof(char) * ((length/4 + 1) + 1)); odin_sprintf(hex_string, "%X ", (unsigned int)strtol(string, &tmp, 2)); vtr::free(string); return hex_string; } /* * Counts the number of vectors in the given file. */ static int count_test_vectors(FILE *in) { rewind(in); int count = 0; char buffer[BUFFER_MAX_SIZE]; while (get_next_vector(in, buffer)) count++; if (count) // Don't count the headers. count--; rewind(in); return count; } /* * Counts the number of vectors in the given file. */ static int count_empty_test_vectors(FILE *in) { rewind(in); int count = 0; int buffer; while ( (buffer = getc(in)) != EOF ) if(((char)buffer) == '\n') count++; if (count) // Don't count the headers. count--; rewind(in); return count; } /* * A given line is a vector if it contains one or more * non-whitespace characters and does not being with a #. */ static int is_vector(char *buffer) { char *line = vtr::strdup(buffer); trim_string(line," \t\r\n"); if (line[0] != '#' && strlen(line)) { vtr::free(line); return TRUE; } else { vtr::free(line); return FALSE; } } /* * Gets the next line from the given file that * passes the is_vector() test and places it in * the buffer. Returns TRUE if a vector was found, * and FALSE if no vector was found. */ static int get_next_vector(FILE *file, char *buffer) { oassert(file != NULL && "unable to retrieve file for next test vector"); oassert(buffer != NULL && "unable to use buffer for next test vector as it is not initialized"); while (fgets(buffer, BUFFER_MAX_SIZE, file)) if (is_vector(buffer)) return TRUE; return FALSE; } /* * Free each element in lines[] and the array itself */ static void free_lines(lines_t *l) { if(l) { if(l->lines) { while (l->count--) { if(l->lines[l->count]) { if(l->lines[l->count]->name) vtr::free(l->lines[l->count]->name); if(l->lines[l->count]->pins) vtr::free(l->lines[l->count]->pins); vtr::free(l->lines[l->count]); } } vtr::free(l->lines); } vtr::free(l); } } /* * Free stages. */ static void free_stages(stages_t *s) { if(s) { if(s->stages) { while (s->count--) { if(s->stages[s->count]) vtr::free(s->stages[s->count]); } vtr::free(s->stages); } if(s->counts) { vtr::free(s->counts); } vtr::free(s); } } //maria //Free thread distribution static void free_thread_distribution(thread_node_distribution *thread_distribution) { if(thread_distribution) { if(thread_distribution->thread_nodes) { for(int i = 0; i < thread_distribution->number_of_threads; i++) { if(thread_distribution->thread_nodes[i]) { for (int j=0;j<thread_distribution->thread_nodes[i]->number_of_nodes;j++) { if(thread_distribution->thread_nodes[i]->nodes[j]) vtr::free(thread_distribution->thread_nodes[i]->nodes[j]); } if(thread_distribution->thread_nodes[i]->nodes) vtr::free(thread_distribution->thread_nodes[i]->nodes); vtr::free(thread_distribution->thread_nodes[i]); } } vtr::free(thread_distribution->thread_nodes); } vtr::free(thread_distribution); } } /* * Free the given test_vector. */ static void free_test_vector(test_vector* v) { if(v) { if(v->values) { while (v->count--) { if(v->values[v->count]) vtr::free(v->values[v->count]); } vtr::free(v->values); } if(v->counts) vtr::free(v->counts); vtr::free(v); } } /* * Prints information about the netlist we are simulating. */ static void print_netlist_stats(stages_t *stages, int /*num_vectors*/) { if(configuration.list_of_file_names.size() == 0) printf("%s:\n", (char*)global_args.blif_file); else for(long i=0; i < configuration.list_of_file_names.size(); i++) printf("%s:\n", configuration.list_of_file_names[i].c_str()); printf(" Nodes: %d\n", stages->num_nodes); printf(" Connections: %d\n", stages->num_connections); printf(" Threads: %d\n", number_of_workers); printf(" Degree: %3.2f\n", stages->num_connections/(float)stages->num_nodes); printf(" Stages: %d\n", stages->count); printf(" Nodes/thread: %d(%4.2f%%)\n", (stages->num_nodes/number_of_workers), 100.0/(double)number_of_workers); printf("\n"); } /* * Prints statistics. (Coverage and times.) */ static void print_simulation_stats(stages_t *stages, int /*num_vectors*/, double total_time, double simulation_time) { int covered_nodes = get_num_covered_nodes(stages); printf("Simulation time: "); print_time(simulation_time); printf("\n"); printf("Elapsed time: "); print_time(total_time); printf("\n"); printf("Coverage: " "%d (%4.1f%%)\n", covered_nodes, (covered_nodes/(double)stages->num_nodes) * 100); } /* * Prints n ancestors of the given node, complete * with their parents, ids, etc. */ static void print_ancestry(nnode_t *bottom_node, int n) { if (!n) n = 10; std::queue<nnode_t *> queue = std::queue<nnode_t *>(); queue.push(bottom_node); printf( " ------------\n"); printf( " BACKTRACE\n"); printf( " ------------\n"); while (n-- && !queue.empty()) { nnode_t *node = queue.front(); queue.pop(); char *name = get_pin_name(node->name); printf(" %s (%ld):\n", name, node->unique_id); vtr::free(name); int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; nnet_t *net = pin->net; nnode_t *node2 = net->driver_pin->node; queue.push(node2); char *name2 = get_pin_name(node2->name); printf("\t%s %s (%ld)\n", pin->mapping, name2, node2->unique_id);fflush(stdout); vtr::free(name2); } /*int count = 0; { printf( " ------------\n"); printf( " CHILDREN \n"); printf( " ------------\n"); printf( " O: %ld\n", node->num_output_pins);fflush(stdout); for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; if (pin) { nnet_t *net = pin->net; if (net) { int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *pin = net->fanout_pins[j]; if (pin) { nnode_t *node = pin->node; if (node) { char *name = get_pin_name(node->name); printf("\t%s %s (%ld)\n", pin->mapping, name, node->unique_id);fflush(stdout); vtr::free(name); } else { printf(" Null node %ld\n", ++count);fflush(stdout); } } else { printf(" Null fanout pin\n");fflush(stdout); } } } else { printf(" Null net\n");fflush(stdout); } } } }*/ printf( " ------------\n"); } printf( " END OF TRACE\n"); printf( " ------------\n"); } /* * Traces an node which is failing to update back to parent of * the earliest node in the net list with an unupdated pin. * (Pin whose cycle is less than cycle-1). Prints all nodes * traversed during the trace with the original node printed * first, and the root of the issue printed last. * * Returns the root node for inspection. */ static nnode_t *print_update_trace(nnode_t *bottom_node, int cycle) { // Limit the length of the trace. 0 for unlimited. const int max_depth = 0; printf( " --------------------------------------------------------------------------\n" " --------------------------------------------------------------------------\n" " BACKTRACE:\n" "\tFormat: Each node is listed followed by its parents. The parent \n" "\twhich is not updating is indicated with an astrisk. (*)\n" "\tEach node is listed in the form:\n" "\t\t(<mapping>) <Name> (<Unique ID>) <# of Parents> <# of Children> \n" " --------------------------------------------------------------------------\n" ); nnode_t *root_node = NULL; // Used to detect cycles. Based table size of max depth. If unlimited, set to something big. std::unordered_set<long> index; std::queue<nnode_t *> queue = std::queue<nnode_t *>(); queue.push(bottom_node); int depth = 0; // Traverse the netlist in reverse, starting with our current location. while (!queue.empty()) { nnode_t *node = queue.front(); queue.pop(); int found_undriven_pin = FALSE; if (index.find(node->unique_id) == index.end()) { depth++; index.insert(node->unique_id); char *name = get_pin_name(node->name); printf(" %s (%ld) %ld %ld\n", name, node->unique_id, node->num_input_pins, node->num_output_pins); vtr::free(name); int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; nnet_t *net = pin->net; nnode_t *node2 = net->driver_pin->node; // If an input is found which hasn't been updated since before cycle-1, traverse it. int is_undriven = FALSE; if (get_pin_cycle(pin) < cycle-1) { // Only add each node for traversal once. if (!found_undriven_pin) { found_undriven_pin = TRUE; queue.push(node2); } is_undriven = TRUE; } char *name2 = get_pin_name(node2->name); printf("\t(%s) %s (%ld) %ld %ld %s \n", pin->mapping, name2, node2->unique_id, node2->num_input_pins, node2->num_output_pins, is_undriven?"*":""); vtr::free(name2); } printf(" ------------\n"); } else { printf(" CYCLE DETECTED AFTER %d NODES.\n", depth); printf(" ------------\n"); break; } if (!found_undriven_pin) { printf(" TOP OF TRACE\n"); printf(" ------------\n"); root_node = node; break; } else if (max_depth && depth >=max_depth) { printf(" TRACE TRUNCATED AT %d NODES.\n", max_depth); printf(" ------------\n"); break; } } return root_node; }
28.142617
219
0.655139
[ "geometry", "object", "vector", "transform" ]
29d29385b2f30938d8b56d1f5cdb665de705700b
5,018
hpp
C++
krest/gui/Player.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
null
null
null
krest/gui/Player.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
null
null
null
krest/gui/Player.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
null
null
null
/* This file is part of Krest, and is distributed under the OSI-approved BSD * 3-Clause License. See top-level LICENSE file or * https://github.com/Kitware/krest/blob/master/LICENSE for details. */ #ifndef krest_gui_Player_hpp #define krest_gui_Player_hpp #include <krest/gui/Export.h> #include <krest/core/VideoDistributor.hpp> #include <vital/types/detected_object_set.h> #include <vital/types/image_container.h> #include <vital/types/transform_2d.h> #include <qtGlobal.h> #include <QMatrix4x4> #include <QOpenGLWidget> #include <QPointF> #include <QRectF> class QAbstractItemModel; class QImage; namespace krest { namespace gui { QTE_BEGIN_META_NAMESPACE(KREST_GUI_EXPORT, player_enums) enum class ContrastMode { Manual, Percentile, }; enum ExtentsType { ImageExtents = 1<<0, EntityExtents = 1<<1, }; QTE_ENUM_NS(ContrastMode) QTE_ENUM_NS(ExtentsType) Q_DECLARE_FLAGS(ExtentsTypes, ExtentsType) QTE_FLAG_NS(ExtentsTypes) QTE_END_META_NAMESPACE() #if defined(_MSC_VER) && _MSC_VER < 1920 // Work around name lookup bug in MSVC < 19.20 using player_enums::ContrastMode; #endif class PlayerTool; class PlayerPrivate; class KREST_GUI_EXPORT Player : public QOpenGLWidget { Q_OBJECT Q_PROPERTY(float zoom READ zoom WRITE setZoom NOTIFY zoomChanged) Q_PROPERTY(QPointF center READ center WRITE setCenter NOTIFY centerChanged) Q_PROPERTY(QSize homographyImageSize READ homographyImageSize WRITE setHomographyImageSize) Q_PROPERTY(ContrastMode contrastMode READ contrastMode WRITE setContrastMode NOTIFY contrastModeChanged) Q_PROPERTY(QMatrix4x4 homography READ homography WRITE setHomography) Q_PROPERTY(QMatrix4x4 viewHomography READ viewHomography) Q_PROPERTY(QColor defaultColor READ defaultColor WRITE setDefaultColor NOTIFY defaultColorChanged) Q_PROPERTY(QColor selectionColor READ selectionColor WRITE setSelectionColor NOTIFY defaultColorChanged) Q_PROPERTY(QColor pendingColor READ pendingColor WRITE setPendingColor NOTIFY pendingColorChanged) public: explicit Player(QWidget* parent = nullptr); ~Player() override; float zoom() const; QPointF center() const; bool hasImage() const; QSize effectiveImageSize() const; ContrastMode contrastMode() const; core::VideoDistributor* videoSource() const; virtual bool hasTransform() const; QSize homographyImageSize() const; QMatrix4x4 homography() const; QMatrix4x4 viewHomography() const; PlayerTool* activeTool() const; QPointF viewToImage(QPointF const& viewCoord) const; virtual QRectF extents(ExtentsTypes) const; QColor defaultColor() const; QColor selectionColor() const; QColor pendingColor() const; signals: void zoomChanged(float zoom) const; void centerChanged(QPointF center) const; void imageSizeChanged(QSize imageSize) const; void imageNameChanged(QString const& imageName) const; void activeToolChanged(PlayerTool* tool) const; void contrastModeChanged(ContrastMode mode) const; void defaultColorChanged(QColor const& color) const; void selectionColorChanged(QColor const& color) const; void pendingColorChanged(QColor const& color) const; void trackPicked(qint64 id) const; public slots: virtual void setImage(kwiver::vital::image_container_sptr const& image, krest::core::VideoMetaData const& metaData); virtual void setTrackModel(QAbstractItemModel* model); virtual void setSelectedTrackIds(QSet<qint64> const& selectedIds); void setHomography(QMatrix4x4 const& homography); void setHomographyImageSize(QSize size); void setZoom(float zoom); void setCenter(QPointF center); void setVideoSource(core::VideoDistributor* videoSource); void setContrastMode(ContrastMode mode); void setManualLevels(float low, float high); void setPercentiles(double deviance, double tolerance); void setActiveTool(PlayerTool* tool); void setTrackFilter(int role, QVariant const& low, QVariant const& high); void setDefaultColor(QColor const& color); void setSelectionColor(QColor const& color); void setPendingColor(QColor const& color); void setCenterToTrack(qint64 id, kwiver::vital::timestamp::time_t time); void setShadowTrackModel(QObject* source, QAbstractItemModel* model); void setShadowTransform( QObject* source, kwiver::vital::transform_2d_sptr const& transform); protected: QTE_DECLARE_PRIVATE(Player) void setNoVideoText(QString const& text); void initializeGL() override; void paintGL() override; void resizeGL(int w, int h) override; void paintEvent(QPaintEvent* event) override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; void wheelEvent(QWheelEvent* event) override; private: QTE_DECLARE_PRIVATE_RPTR(Player) }; } // namespace gui } // namespace krest Q_DECLARE_OPERATORS_FOR_FLAGS(krest::gui::ExtentsTypes) #endif
27.420765
77
0.770825
[ "model", "transform" ]
29d3f183a1977fb04dac4d0887e6d92117ededaa
9,814
cpp
C++
HoloIntervention/Source/Rendering/Mesh/MeshRenderer.cpp
adamrankin/HoloIntervention
0f2a4dc702729a0a04af5c210884ef4e08e49267
[ "Apache-2.0" ]
2
2020-06-17T09:55:59.000Z
2021-04-03T16:18:29.000Z
HoloIntervention/Source/Rendering/Mesh/MeshRenderer.cpp
adamrankin/HoloIntervention
0f2a4dc702729a0a04af5c210884ef4e08e49267
[ "Apache-2.0" ]
1
2018-09-02T02:39:21.000Z
2018-09-02T02:39:21.000Z
HoloIntervention/Source/Rendering/Mesh/MeshRenderer.cpp
adamrankin/HoloIntervention
0f2a4dc702729a0a04af5c210884ef4e08e49267
[ "Apache-2.0" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // Local includes #include "pch.h" #include "AppView.h" #include "MeshRenderer.h" // Common includes #include "DeviceResources.h" #include "DirectXHelper.h" #include "StepTimer.h" // System includes #include "NotificationSystem.h" #include "PhysicsAPI.h" using namespace Concurrency; using namespace DX; using namespace Platform; using namespace Windows::Foundation::Collections; using namespace Windows::Foundation::Numerics; using namespace Windows::Foundation; using namespace Windows::Graphics::DirectX; using namespace Windows::Media::SpeechRecognition; using namespace Windows::Perception::Spatial::Surfaces; using namespace Windows::Perception::Spatial; namespace { static const float LOOP_DURATION_MSEC = 2000.0f; } namespace HoloIntervention { namespace Rendering { //---------------------------------------------------------------------------- void MeshRenderer::RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap) { callbackMap[L"mesh on"] = [this](SpeechRecognitionResult ^ result) { this->SetEnabled(true); }; callbackMap[L"mesh off"] = [this](SpeechRecognitionResult ^ result) { this->SetEnabled(false); }; callbackMap[L"mesh solid"] = [this](SpeechRecognitionResult ^ result) { this->SetWireFrame(false); this->SetEnabled(true); }; callbackMap[L"mesh wireframe"] = [this](SpeechRecognitionResult ^ result) { this->SetWireFrame(true); this->SetEnabled(true); }; } //---------------------------------------------------------------------------- MeshRenderer::MeshRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources, Physics::PhysicsAPI& physics) : m_deviceResources(deviceResources) , m_physicsAPI(physics) { CreateDeviceDependentResources(); }; //---------------------------------------------------------------------------- // Renders one frame using the vertex, geometry, and pixel shaders. void MeshRenderer::Render() { // Loading is asynchronous. Only draw geometry after it's loaded. if (!m_componentReady || !m_renderEnabled) { return; } auto context = m_deviceResources->GetD3DDeviceContext(); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(m_inputLayout.Get()); // Attach our vertex shader. context->VSSetShader(m_vertexShader.Get(), nullptr, 0); if (!m_usingVprtShaders) { context->GSSetShader(m_geometryShader.Get(), nullptr, 0); } if (m_drawWireframe) { // Use a wireframe rasterizer state. context->RSSetState(m_wireframeRasterizerState.Get()); // Attach a pixel shader to render a solid color wireframe. context->PSSetShader(m_colorPixelShader.Get(), nullptr, 0); } else { // Use the default rasterizer state. context->RSSetState(m_defaultRasterizerState.Get()); // Attach a pixel shader that can do lighting. context->PSSetShader(m_lightingPixelShader.Get(), nullptr, 0); } auto meshes = m_physicsAPI.GetMeshes(); for (auto& pair : meshes) { pair.second->Render(m_usingVprtShaders); } context->RSSetState(nullptr); } //---------------------------------------------------------------------------- void MeshRenderer::SetEnabled(bool arg) { m_renderEnabled = arg; } //---------------------------------------------------------------------------- bool MeshRenderer::GetEnabled() const { return m_renderEnabled; } //---------------------------------------------------------------------------- void MeshRenderer::SetWireFrame(bool arg) { m_drawWireframe = arg; } //---------------------------------------------------------------------------- bool MeshRenderer::GetWireFrame() const { return m_drawWireframe; } //---------------------------------------------------------------------------- void MeshRenderer::CreateDeviceDependentResources() { m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt(); std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///SMRSurfaceVprtVertexShader.cso" : L"ms-appx:///SMRSurfaceVertexShader.cso"; // Load shaders asynchronously. task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName); task<std::vector<byte>> loadLightingPSTask = DX::ReadDataAsync(L"ms-appx:///SMRLightingPixelShader.cso"); task<std::vector<byte>> loadWireframePSTask = DX::ReadDataAsync(L"ms-appx:///SMRSolidColorPixelShader.cso"); task<std::vector<byte>> loadGSTask; if (!m_usingVprtShaders) { // Load the pass-through geometry shader. loadGSTask = DX::ReadDataAsync(L"ms-appx:///PPNCIGeometryShader.cso"); } // After the vertex shader file is loaded, create the shader and input layout. auto createVSTask = loadVSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateVertexShader(&fileData[0], fileData.size(), nullptr, &m_vertexShader) ); bool result = wait_until_condition([this]() {return m_physicsAPI.GetMeshOptions() != nullptr; }, 5000, 100); DXGI_FORMAT positionFormat; if (result) { positionFormat = (m_physicsAPI.GetMeshOptions()->VertexPositionFormat == DirectXPixelFormat::R32G32B32A32Float) ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32_FLOAT; } else { positionFormat = DXGI_FORMAT_R32G32B32A32_FLOAT; } static const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = { { "POSITION", 0, positionFormat, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R8G8B8A8_SNORM, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateInputLayout(vertexDesc, ARRAYSIZE(vertexDesc), &fileData[0], fileData.size(), &m_inputLayout) ); }); // After the pixel shader file is loaded, create the shader and constant buffer. auto createLightingPSTask = loadLightingPSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreatePixelShader(&fileData[0], fileData.size(), nullptr, &m_lightingPixelShader) ); }); // After the pixel shader file is loaded, create the shader and constant buffer. auto createWireframePSTask = loadWireframePSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreatePixelShader(&fileData[0], fileData.size(), nullptr, &m_colorPixelShader) ); }); task<void> createGSTask; if (!m_usingVprtShaders) { // After the pass-through geometry shader file is loaded, create the shader. createGSTask = loadGSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateGeometryShader(&fileData[0], fileData.size(), nullptr, &m_geometryShader) ); }); } // Once all shaders are loaded, create the mesh. task<void> shaderTaskGroup = m_usingVprtShaders ? (createLightingPSTask && createWireframePSTask && createVSTask) : (createLightingPSTask && createWireframePSTask && createVSTask && createGSTask); // Once the cube is loaded, the object is ready to be rendered. auto finishLoadingTask = shaderTaskGroup.then([this]() { // Create a default rasterizer state descriptor. D3D11_RASTERIZER_DESC rasterizerDesc = CD3D11_RASTERIZER_DESC(D3D11_DEFAULT); // Create the default rasterizer state. m_deviceResources->GetD3DDevice()->CreateRasterizerState(&rasterizerDesc, m_defaultRasterizerState.GetAddressOf()); // Change settings for wireframe rasterization. rasterizerDesc.AntialiasedLineEnable = true; rasterizerDesc.CullMode = D3D11_CULL_NONE; rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME; // Create a wireframe rasterizer state. m_deviceResources->GetD3DDevice()->CreateRasterizerState(&rasterizerDesc, m_wireframeRasterizerState.GetAddressOf()); m_componentReady = true; }); } //---------------------------------------------------------------------------- void MeshRenderer::ReleaseDeviceDependentResources() { m_componentReady = false; m_vertexShader.Reset(); m_inputLayout.Reset(); m_geometryShader.Reset(); m_lightingPixelShader.Reset(); m_colorPixelShader.Reset(); m_defaultRasterizerState.Reset(); m_wireframeRasterizerState.Reset(); } //---------------------------------------------------------------------------- void MeshRenderer::Reset() { ReleaseDeviceDependentResources(); m_drawWireframe = true; } } }
35.175627
185
0.604239
[ "mesh", "geometry", "render", "object", "vector", "solid" ]
29d406ab4dae43750054c8afaea2f78a209c5412
10,351
hpp
C++
src/AssemblyGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/AssemblyGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/AssemblyGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
#ifndef SHASTA_ASSEMBLY_GRAPH_HPP #define SHASTA_ASSEMBLY_GRAPH_HPP /*************************************************************************** The assembly graph is a "compressed" version of the marker graph, in which each linear chain of edges is replaced by a single edge. Each assembly graph vertex corresponds to a marker graph vertex, but the reverse is not true, because marker graph vertices that are internal to a linear chain of edges don't have a corresponding vertex in the assembly graph. ***************************************************************************/ // Shasta. #include "LongBaseSequence.hpp" #include "MarkerGraph.hpp" #include "MemoryMappedVectorOfVectors.hpp" // Standard library. #include <limits> namespace shasta { class AssemblyGraph; } class shasta::AssemblyGraph { public: // Use the same vertex and edge ids of the marker graph. // We could probably get away with 32 bits. using VertexId = MarkerGraph::VertexId; using EdgeId = MarkerGraph::EdgeId; static const VertexId invalidVertexId = std::numeric_limits<VertexId>::max(); static const VertexId invalidEdgeId = std::numeric_limits<EdgeId>::max(); // The vertices of the assembly graph. // Each assembly graph vertex corresponds to a marker graph vertex. // Indexed by vertex id in the assembly graph. // Contains the corresponding vertex id in the marker graph. MemoryMapped::Vector<VertexId> vertices; // The reverse complement of each vertex. // Indexed by VertexId. MemoryMapped::Vector<VertexId> reverseComplementVertex; // The edges of the assembly graph. // Indexed by edge id in the assembly graph. class Edge { public: VertexId source; VertexId target; // Minimum, average, and maximum coverage of marker graph vertices and edges // corresponding to this assembly graph edge. // Only internal vertices contribute to this - // the first and last vertex don't contribute. // If there is only one marker graph edge, there are // no internal vertices, and in that case vertex coverage // metrics are set to zero. uint32_t minVertexCoverage; uint32_t averageVertexCoverage; uint32_t maxVertexCoverage; uint32_t minEdgeCoverage; uint32_t averageEdgeCoverage; uint32_t maxEdgeCoverage; // Reason for removal. enum class RemovalReason : uint8_t { NotRemoved = 0, LowCoverageCrossEdge = 1, Pruned }; RemovalReason removalReason; bool wasRemoved() const { return removalReason != RemovalReason::NotRemoved; } Edge() : removalReason(RemovalReason::NotRemoved) {} }; MemoryMapped::Vector<Edge> edges; // Return the number of edges that were not removed. EdgeId edgeCount() const; // The reverse complement of each edge. // Indexed by EdgeId. MemoryMapped::Vector<EdgeId> reverseComplementEdge; // Return true if this edge is an assembled edge. // To avoid assembling both strands, we only assemble // one edge in each reverse complemented pair. bool isAssembledEdge(EdgeId edgeId) const { return edgeId <= reverseComplementEdge[edgeId]; } // The edges that each vertex is the source of. // Indexed by vertex id in the assembly graph. // Contains edge ids that can be used as indexes into edges and edgeLists. MemoryMapped::VectorOfVectors<EdgeId, EdgeId> edgesBySource; // The edges that each vertex is the target of. // Indexed by vertex id in the assembly graph. // Contains edge ids that can be used as indexes into edges and edgeLists. MemoryMapped::VectorOfVectors<EdgeId, EdgeId> edgesByTarget; // Fill in edgesBySource and edgesByTarget. void computeConnectivity(); // The edge ids of global marker graph edges corresponding // to each edge of the assembly graph. // Indexed by the edge id of the assembly graph edge. MemoryMapped::VectorOfVectors<EdgeId, EdgeId> edgeLists; // Find the out-degree or in-degree of a vertex. // This is not simply the same as counting edgesBySource // and edgesByTarget, because we have to skip edges // that were removed. VertexId inDegree(VertexId) const; VertexId outDegree(VertexId) const; // Find in-edges/out-edges of a vertex // that were not removed. // They are returned sorted by edge id. void findInEdges(VertexId, vector<EdgeId>&) const; void findOutEdges(VertexId, vector<EdgeId>&) const; // Bubbles in the assembly graph. // A bubble is a set of two vertices v0, v1 // such that the outgoing edges of v0 are the same // as the outgoing edges of v1, and // out-degree(v0) = in-degree(v1) > 1. // v0 is called the bubble source. // v1 is called the bubble target. // In defining and detecting bubbles, edges // that were removed are considered to not exist. class Bubble { public: VertexId v0; VertexId v1; Bubble() {} Bubble(VertexId v0, VertexId v1) : v0(v0), v1(v1) {} }; MemoryMapped::Vector<Bubble> bubbles; void findBubbles(); // Assumes bubble was already initialized. // Bubble chains. A bubble chain is a linear sequence of bubbles. // Each pair of consecutive bubbles in the sequence may be separated by // a homozygous segment, but the bubble can also be // immediately adjacent (v1 of thr first bubble is the same // as v0 of the second bubble). // For each bubble chain, we store the bubble ids (indexes in // the bubbles vector above). MemoryMapped::VectorOfVectors<uint64_t, uint64_t> bubbleChains; void findBubbleChains(); // Assumes bubbleChains was already initialized. // A table that can be used to find the locations of a marker graph // edge in the assembly graph, if any. // Note that, before detangling,or if detangling is not used, // each marker graph edge corresponds to at most one location // in the assembly graph. However, after detangling a marker // graph edge can correspond to multiple locations in the // assembly graph. // Indexed by the edge id in the marker graph, gives for each marker graph // edge a vector of pair(EdgeId, position), where: // - EdgeId is the id of the assembly graph edge containing the // given marker graph edge. // - Position is the index of this marker graph edge in that // assembly graph edge. MemoryMapped::VectorOfVectors< pair<EdgeId, uint32_t> , uint64_t> markerToAssemblyTable; void createMarkerToAssemblyTable(uint64_t markerGrapEdgeCount); // The assembled sequenced and repeat counts for each edge of the // assembly graph. // Indexed edge id in the assembly graph. LongBaseSequences sequences; MemoryMapped::VectorOfVectors<uint8_t, uint64_t> repeatCounts; // The oriented reads internal to each assembly graph edge. // Indexed by EdgeId. class OrientedReadInfo { public: OrientedReadId orientedReadId; // Number of marker graph vertices internal to the // assembly graph edge and containing this oriented read. uint64_t vertexCount; // Number of marker graph edges internal to the // assembly graph edge and containing this oriented read. uint64_t edgeCount; OrientedReadInfo() {} OrientedReadInfo( OrientedReadId orientedReadId, uint64_t vertexCount, uint64_t edgeCount) : orientedReadId(orientedReadId), vertexCount(vertexCount), edgeCount(edgeCount) {} }; MemoryMapped::VectorOfVectors<OrientedReadInfo, uint64_t> orientedReadsByEdge; // Compute the number of oriented reads in common between two segments. uint64_t commonOrientedReadCount( EdgeId, EdgeId, uint64_t minVertexCount, uint64_t minEdgeCount) const; // Close all open data. void close(); // Close and remove all open data. void remove(); // Basic Graphviz output of the global assembly graph. void writeGraphviz(const string& fileName) const; // Create a csv file that can be loaded in Bandage to color assembled segments // by similarity (number of common oriented reads) with a given assembled segment. void colorGfaBySimilarityToSegment( EdgeId, uint64_t minVertexCount, uint64_t minEdgeCount); // Write the AssemblyGraph to GFA without including sequence. // The sequence length of each edge is written as the number of // marker graph edges. // Equivalent functionbs including output of assembled sequence // are in class Assembler and should be moved here. void writeGfa1BothStrandsNoSequence(const string& fileName) const; void writeGfa1BothStrandsNoSequence(ostream&) const; // Assembly graph forks. // A fork is the set of outgoing edges of a vertex with out-degree>1, // or the set of incoming edges of a vertex with in-degree>1. // The edges of the set are called the fork branches. // A fork can have any number of branches>1. // A bubble generates only one fork (the set of outgoing edges // of the bubble source vertex which is also the set of // incoming edges of the bubble target vertex). class Fork { public: // The source or target vertex of the fork. VertexId vertexId; // Flag which is true if the fork consists of the vertex's // outgoing edges, false if the fork consists of // thevertex's incoming edges. // The fork corresponding to a bubble is stored only once. bool isForward; }; MemoryMapped::Vector<Fork> forks; void createForks(); span<EdgeId> getForkEdges(uint64_t forkId); private: // Class used by createForks. class ForkInfo : public Fork { public: vector<EdgeId> edgeIds; // Compare using only the edgeIds. bool operator==(const ForkInfo& that) const { return edgeIds == that.edgeIds; } bool operator<(const ForkInfo& that) const { return edgeIds < that.edgeIds; } }; }; #endif
33.826797
92
0.671143
[ "vector" ]
29d51fa1aca76765f8f8997720d68eb07dc92cff
3,800
cpp
C++
Source/Client.cpp
justus-zorn/Hazard
d24b708c5fa7000d965215d2de6d9943f3fc8d66
[ "MIT" ]
1
2022-02-06T17:24:09.000Z
2022-02-06T17:24:09.000Z
Source/Client.cpp
justus-zorn/Hazard
d24b708c5fa7000d965215d2de6d9943f3fc8d66
[ "MIT" ]
null
null
null
Source/Client.cpp
justus-zorn/Hazard
d24b708c5fa7000d965215d2de6d9943f3fc8d66
[ "MIT" ]
null
null
null
// Copyright 2022 Justus Zorn #include <iostream> #include "Client.h" #include "Net.h" using namespace Hazard; Client::Client(const std::string& playerName, const std::string& address, std::uint16_t defaultPort) { std::string hostname; std::uint16_t port; if (address.find(':') < address.size()) { hostname = address.substr(0, address.find(':')); port = std::stoi(address.substr(address.find(':') + 1)); } else { hostname = address; port = defaultPort; } host = enet_host_create(nullptr, 1, 4, 0, 0); if (!host) { std::cerr << "ERROR: Could not create ENet host\n"; return; } ENetAddress serverAddress = { 0 }; serverAddress.port = port; if (enet_address_set_host(&serverAddress, hostname.c_str()) < 0) { std::cerr << "ERROR: Could not resolve " << hostname << '\n'; return; } server = enet_host_connect(host, &serverAddress, 4, 0); if (!server) { std::cerr << "ERROR: Could not connect to " << address << '\n'; return; } ENetEvent event; if (enet_host_service(host, &event, 3000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT) { WritePacket packet; packet.WriteString(playerName); enet_peer_send(server, 0, packet.GetPacket(true)); } else { std::cerr << "ERROR: Could not connect to " << address << '\n'; } } Client::~Client() { enet_peer_disconnect_now(server, 0); enet_host_destroy(host); } bool Client::Update(const Input& input) { ENetEvent event; audioCommands.clear(); while (enet_host_service(host, &event, 0) > 0) { switch (event.type) { case ENET_EVENT_TYPE_DISCONNECT: case ENET_EVENT_TYPE_DISCONNECT_TIMEOUT: return false; case ENET_EVENT_TYPE_RECEIVE: if (event.channelID == 1) { ReadPacket packet(event.packet); std::uint32_t spriteCount = packet.Read32(); sprites.resize(spriteCount); for (std::uint32_t i = 0; i < spriteCount; ++i) { Sprite& sprite = sprites[i]; sprite.x = packet.Read32(); sprite.y = packet.Read32(); sprite.scale = packet.Read32(); if (packet.Read8()) { // Text sprite.isText = true; sprite.r = packet.Read8(); sprite.g = packet.Read8(); sprite.b = packet.Read8(); sprite.text = packet.ReadString(); } else { // Sprite sprite.isText = false; sprite.texture = packet.Read32(); sprite.animation = packet.Read32(); } } } else if (event.channelID == 3) { ReadPacket packet(event.packet); std::uint32_t audioCommandCount = packet.Read32(); audioCommands.resize(audioCommandCount); for (std::uint32_t i = 0; i < audioCommandCount; ++i) { AudioCommand& audioCommand = audioCommands[i]; audioCommand.type = static_cast<AudioCommand::Type>(packet.Read8()); audioCommand.volume = packet.Read8(); audioCommand.channel = packet.Read16(); audioCommand.sound = packet.Read32(); } } enet_packet_destroy(event.packet); break; } } WritePacket inputPacket; inputPacket.Write32(static_cast<std::uint32_t>(input.keyboardInputs.size())); for (KeyboardInput keyboardInput : input.keyboardInputs) { inputPacket.Write32(keyboardInput.key); inputPacket.Write8(keyboardInput.pressed); } inputPacket.Write32(static_cast<std::uint32_t>(input.buttonInputs.size())); for (ButtonInput buttonInput : input.buttonInputs) { inputPacket.Write8(buttonInput.button); inputPacket.Write8(buttonInput.pressed); } inputPacket.Write32(input.mouseMotionX); inputPacket.Write32(input.mouseMotionY); inputPacket.Write8(input.mouseMotion); inputPacket.WriteString(input.textInput); enet_peer_send(server, 2, inputPacket.GetPacket(true)); return true; } const std::vector<Sprite>& Client::GetSprites() const { return sprites; } const std::vector<AudioCommand>& Client::GetAudioCommands() const { return audioCommands; }
27.142857
102
0.681579
[ "vector" ]
29d8034d2a14b6fa2c49b5fa65cb409209b29944
26,301
cc
C++
tensorflow/core/graph/graph_partition_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
36
2016-12-17T15:25:25.000Z
2022-01-29T21:50:53.000Z
tensorflow/core/graph/graph_partition_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
59
2019-06-17T09:37:49.000Z
2022-01-19T01:21:34.000Z
tensorflow/core/graph/graph_partition_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
36
2017-07-27T21:12:40.000Z
2022-02-03T16:45:56.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/graph/graph_partition.h" #include <unordered_map> #include <utility> #include "tensorflow/cc/ops/array_ops.h" #include "tensorflow/cc/ops/const_op.h" #include "tensorflow/cc/ops/control_flow_ops.h" #include "tensorflow/cc/ops/control_flow_ops_internal.h" #include "tensorflow/cc/ops/math_ops.h" #include "tensorflow/cc/ops/random_ops.h" #include "tensorflow/cc/ops/sendrecv_ops.h" #include "tensorflow/cc/ops/while_loop.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/function_testlib.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/versions.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/graph/graph_def_builder.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/version.h" #include "tensorflow/core/util/equal_graph_def.h" namespace tensorflow { // from graph_partition.cc extern Status TopologicalSortNodesWithTimePriority( const GraphDef* gdef, std::vector<std::pair<const NodeDef*, int64>>* nodes, std::unordered_map<const NodeDef*, int64>* node_to_start_time_out); namespace { using ops::_Recv; using ops::_Send; using ops::Const; using ops::Identity; using ops::LoopCond; using ops::NextIteration; const char gpu_device[] = "/job:a/replica:0/task:0/device:GPU:0"; string SplitByDevice(const Node* node) { return node->assigned_device_name(); } string DeviceName(const Node* node) { char first = node->name()[0]; if (first == 'G') { return gpu_device; } else { const string cpu_prefix = "/job:a/replica:0/task:0/cpu:"; int index = first - 'A'; return strings::StrCat(cpu_prefix, index); } } void Partition(const GraphDef& graph_def, std::unordered_map<string, GraphDef>* partitions) { Graph g(OpRegistry::Global()); GraphConstructorOptions opts; TF_CHECK_OK(ConvertGraphDefToGraph(opts, graph_def, &g)); // Assigns devices to each node. Uses 1st letter of the node name as the // device index if no device is specified. for (Node* node : g.nodes()) { string device_name = !node->requested_device().empty() ? node->requested_device() : DeviceName(node); node->set_assigned_device_name(device_name); } PartitionOptions popts; popts.node_to_loc = SplitByDevice; popts.new_name = [&g](const string& prefix) { return g.NewName(prefix); }; popts.get_incarnation = [](const string& name) { return (name[0] - 'A') + 100; }; Status s = Partition(popts, &g, partitions); CHECK(s.ok()) << s; // Check versions. EXPECT_EQ(graph_def.versions().producer(), TF_GRAPH_DEF_VERSION); // Partitions must inherit the versions of the original graph. for (auto& it : *partitions) { EXPECT_EQ(graph_def.versions().producer(), it.second.versions().producer()); EXPECT_EQ(graph_def.versions().min_consumer(), it.second.versions().min_consumer()); } } void CheckLoopConstruction(const GraphDef& graph_def) { std::unordered_map<string, GraphDef> partitions; Partition(graph_def, &partitions); for (const auto& kv : partitions) { const GraphDef& gdef = kv.second; bool has_control_enter = false; bool has_control_merge = false; bool has_control_switch = false; bool has_control_next = false; for (const NodeDef& ndef : gdef.node()) { // _recvs must have a control input if (ndef.op() == "_Recv") { bool has_control = false; for (const string& input_name : ndef.input()) { if (str_util::StartsWith(input_name, "^")) { has_control = true; break; } } EXPECT_TRUE(has_control); } // Must have a control loop if (str_util::StartsWith(ndef.name(), "_cloop")) { if (ndef.op() == "Enter") { has_control_enter = true; } if (ndef.op() == "Merge") { has_control_merge = true; } if (ndef.op() == "Switch") { has_control_switch = true; } if (ndef.op() == "NextIteration") { has_control_next = true; } } } EXPECT_TRUE(has_control_enter); EXPECT_TRUE(has_control_merge); EXPECT_TRUE(has_control_switch); EXPECT_TRUE(has_control_next); } } REGISTER_OP("FloatInput") .Output("o: float") .SetShapeFn(shape_inference::UnknownShape); REGISTER_OP("BoolInput") .Output("o: bool") .SetShapeFn(shape_inference::UnknownShape); REGISTER_OP("Combine") .Input("a: float") .Input("b: float") .Output("o: float") .SetShapeFn(shape_inference::UnknownShape); Output ConstructOp(const Scope& scope, const string& op_type, const gtl::ArraySlice<Input>& inputs) { if (!scope.ok()) return Output(); const string unique_name = scope.GetUniqueNameForOp(op_type); auto builder = NodeBuilder(unique_name, op_type, scope.graph()->op_registry()); for (auto const& input : inputs) { builder.Input(ops::NodeOut(input.node(), input.index())); } scope.UpdateBuilder(&builder); Node* ret; scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return Output(); scope.UpdateStatus(scope.DoShapeInference(ret)); if (!scope.ok()) return Output(); return Output(ret); } Output FloatInput(const Scope& scope) { return ConstructOp(scope, "FloatInput", {}); } Output BoolInput(const Scope& scope) { return ConstructOp(scope, "BoolInput", {}); } Output Combine(const Scope& scope, Input a, Input b) { return ConstructOp(scope, "Combine", {std::move(a), std::move(b)}); } class GraphPartitionTest : public ::testing::Test { protected: GraphPartitionTest() : in_(Scope::NewRootScope().ExitOnError()), scope_a_(Scope::NewRootScope().ExitOnError().WithDevice( "/job:a/replica:0/task:0/cpu:0")), scope_b_(Scope::NewRootScope().ExitOnError().WithDevice( "/job:a/replica:0/task:0/cpu:1")) {} const GraphDef& ToGraphDef() { TF_EXPECT_OK(in_.ToGraphDef(&in_graph_def_)); return in_graph_def_; } void ExpectMatchA() { GraphDef graph_def; TF_EXPECT_OK(scope_a_.ToGraphDef(&graph_def)); string a = "/job:a/replica:0/task:0/cpu:0"; TF_EXPECT_GRAPH_EQ(graph_def, partitions_[a]); } void ExpectMatchB() { GraphDef graph_def; TF_EXPECT_OK(scope_b_.ToGraphDef(&graph_def)); string b = "/job:a/replica:0/task:0/cpu:1"; TF_EXPECT_GRAPH_EQ(graph_def, partitions_[b]); } void ExpectFunctions(const FunctionDefLibrary& library, const std::set<string>& expected_names) { std::set<string> actual_names; for (const FunctionDef& fdef : library.function()) { actual_names.insert(fdef.signature().name()); } EXPECT_EQ(actual_names, expected_names); } Scope in_; GraphDef in_graph_def_; Scope scope_a_; Scope scope_b_; std::unordered_map<string, GraphDef> partitions_; }; TEST_F(GraphPartitionTest, SingleDevice) { auto a1 = FloatInput(in_.WithOpName("A1")); Combine(in_.WithOpName("A2"), a1, a1); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(1, partitions_.size()); a1 = FloatInput(scope_a_.WithOpName("A1")); Combine(scope_a_.WithOpName("A2"), a1, a1); ExpectMatchA(); } TEST_F(GraphPartitionTest, CrossDeviceData) { auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); Combine(in_.WithOpName("B2"), a1, b1); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; a1 = FloatInput(scope_a_.WithOpName("A1")); _Send(scope_a_.WithOpName("A1/_0"), a1, "edge_1_A1", a, 82, b); ExpectMatchA(); b1 = FloatInput(scope_b_.WithOpName("B1")); auto recv = _Recv(scope_b_.WithOpName("A1/_1"), DT_FLOAT, "edge_1_A1", a, 82, b); Combine(scope_b_.WithOpName("B2"), recv, b1); ExpectMatchB(); } TEST_F(GraphPartitionTest, CrossDeviceControl) { auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); Combine(in_.WithOpName("B2").WithControlDependencies(a1), b1, b1); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; a1 = FloatInput(scope_a_.WithOpName("A1")); auto c = Const(scope_a_.WithOpName("A1/_0").WithControlDependencies(a1), {}); _Send(scope_a_.WithOpName("A1/_1"), c, "edge_3_A1", a, 82, b); ExpectMatchA(); auto recv = _Recv(scope_b_.WithOpName("A1/_2"), DT_FLOAT, "edge_3_A1", a, 82, b); auto id = Identity(scope_b_.WithOpName("A1/_3"), recv); b1 = FloatInput(scope_b_.WithOpName("B1")); Combine(scope_b_.WithOpName("B2").WithControlDependencies(id), b1, b1); ExpectMatchB(); } TEST_F(GraphPartitionTest, CrossDeviceData_MultiUse) { auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); Combine(in_.WithOpName("B2"), a1, b1); Combine(in_.WithOpName("B3"), a1, a1); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; a1 = FloatInput(scope_a_.WithOpName("A1")); _Send(scope_a_.WithOpName("A1/_0"), a1, "edge_1_A1", a, 82, b); ExpectMatchA(); auto recv = _Recv(scope_b_.WithOpName("A1/_1"), DT_FLOAT, "edge_1_A1", a, 82, b); b1 = FloatInput(scope_b_.WithOpName("B1")); Combine(scope_b_.WithOpName("B2"), recv, b1); Combine(scope_b_.WithOpName("B3"), recv, recv); ExpectMatchB(); } TEST_F(GraphPartitionTest, CrossDeviceControl_MultiUse) { auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); Combine(in_.WithOpName("B2").WithControlDependencies(a1), b1, b1); FloatInput(in_.WithOpName("B3").WithControlDependencies(a1)); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; a1 = FloatInput(scope_a_.WithOpName("A1")); auto c = Const(scope_a_.WithOpName("A1/_0").WithControlDependencies(a1), {}); _Send(scope_a_.WithOpName("A1/_1"), c, "edge_3_A1", a, 82, b); ExpectMatchA(); auto recv = _Recv(scope_b_.WithOpName("A1/_2"), DT_FLOAT, "edge_3_A1", a, 82, b); auto id = Identity(scope_b_.WithOpName("A1/_3"), recv); b1 = FloatInput(scope_b_.WithOpName("B1")); Combine(scope_b_.WithOpName("B2").WithControlDependencies(id), b1, b1); FloatInput(scope_b_.WithOpName("B3").WithControlDependencies(id)); ExpectMatchB(); } TEST_F(GraphPartitionTest, CrossDevice_DataControl) { auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); Combine(in_.WithOpName("B2"), a1, b1); FloatInput(in_.WithOpName("B3").WithControlDependencies(a1)); Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; a1 = FloatInput(scope_a_.WithOpName("A1")); _Send(scope_a_.WithOpName("A1/_0"), a1, "edge_1_A1", a, 82, b); auto c = Const(scope_a_.WithOpName("A1/_2").WithControlDependencies(a1), {}); // NOTE: Send 0 A1/_1 -> A1/_2 is not necessarily needed. We could // use A1/_0 -> A1/_4 as the control as a minor optimization. _Send(scope_a_.WithOpName("A1/_3"), c, "edge_3_A1", a, 82, b); ExpectMatchA(); auto recv1 = _Recv(scope_b_.WithOpName("A1/_4"), DT_FLOAT, "edge_3_A1", a, 82, b); auto id1 = Identity(scope_b_.WithOpName("A1/_5"), recv1); auto recv2 = _Recv(scope_b_.WithOpName("A1/_1"), DT_FLOAT, "edge_1_A1", a, 82, b); b1 = FloatInput(scope_b_.WithOpName("B1")); Combine(scope_b_.WithOpName("B2"), recv2, b1); FloatInput(scope_b_.WithOpName("B3").WithControlDependencies(id1)); ExpectMatchB(); } TEST_F(GraphPartitionTest, CrossDeviceLoopSimple) { auto a1 = BoolInput(in_.WithOpName("A1")); auto a2 = ::tensorflow::ops::internal::Enter(in_.WithOpName("A2"), a1, "foo"); auto a3 = ::tensorflow::ops::Merge(in_.WithOpName("A3"), {a2, Input("A5", 0, DT_BOOL)}) .output; LoopCond(in_.WithOpName("A4"), a3); auto b1 = Identity(in_.WithOpName("B1"), a3); NextIteration(in_.WithOpName("A5"), b1); CheckLoopConstruction(ToGraphDef()); } TEST_F(GraphPartitionTest, CrossDeviceLoopSimple1) { auto a1 = BoolInput(in_.WithOpName("A1")); auto a2 = ::tensorflow::ops::internal::Enter(in_.WithOpName("B2"), a1, "foo"); auto a3 = ::tensorflow::ops::Merge(in_.WithOpName("A3"), {a2, Input("B5", 0, DT_BOOL)}) .output; LoopCond(in_.WithOpName("A4"), a3); auto b1 = Identity(in_.WithOpName("B1"), a3); NextIteration(in_.WithOpName("B5"), b1); std::unordered_map<string, GraphDef> partitions; Partition(ToGraphDef(), &partitions); for (const auto& kv : partitions) { const GraphDef& gdef = kv.second; for (const NodeDef& ndef : gdef.node()) { if (ndef.name() == "A3") { // A3, B2, and B5 are on the same device. EXPECT_EQ(ndef.input(0), "B2"); EXPECT_EQ(ndef.input(1), "B5"); } } } } TEST_F(GraphPartitionTest, CrossDeviceLoopFull) { Scope cpu0 = in_.WithDevice("/job:a/replica:0/task:0/cpu:0"); auto p1 = ops::Placeholder(cpu0, DT_INT32); auto p2 = ops::Placeholder(cpu0, DT_INT32); OutputList outputs; // while i1 < 10: i1 += i2 TF_ASSERT_OK(ops::BuildWhileLoop( cpu0, {p1, p2}, [](const Scope& s, const std::vector<Output>& inputs, Output* output) { *output = ops::Less(s, inputs[0], 10); return s.status(); }, [](const Scope& s, const std::vector<Output>& inputs, std::vector<Output>* outputs) { Scope cpu1 = s.WithDevice("/job:a/replica:0/task:0/cpu:1"); outputs->push_back(ops::AddN(cpu1, {inputs[0], inputs[1]})); outputs->push_back(inputs[1]); return s.status(); }, "test_loop", &outputs)); CheckLoopConstruction(ToGraphDef()); } TEST_F(GraphPartitionTest, PartitionIncompleteGraph) { NodeDef ndef; Graph g(OpRegistry::Global()); // Invalid graph since the Combine node requires an input. bool parsed = protobuf::TextFormat::ParseFromString( R"EOF( name: "N" op: "Combine" )EOF", &ndef); ASSERT_TRUE(parsed); Status status; g.AddNode(ndef, &status); TF_ASSERT_OK(status); PartitionOptions popts; popts.node_to_loc = SplitByDevice; popts.new_name = [&g](const string& prefix) { return g.NewName(prefix); }; popts.get_incarnation = [](const string&) { return 1; }; std::unordered_map<string, GraphDef> partitions; status = Partition(popts, &g, &partitions); // Partitioning should fail, but not crash like it did before the // changes that accompanied the addition of this test. EXPECT_EQ(error::INVALID_ARGUMENT, status.code()) << status; } TEST_F(GraphPartitionTest, Functions) { FunctionDefLibrary fdef_lib; *fdef_lib.add_function() = test::function::XTimesTwo(); *fdef_lib.add_function() = test::function::XTimesFour(); TF_ASSERT_OK(in_.graph()->AddFunctionLibrary(fdef_lib)); using namespace ::tensorflow::ops; // NOLINT(build/namespaces) auto a1 = FloatInput(in_.WithOpName("A1")); auto b1 = FloatInput(in_.WithOpName("B1")); ConstructOp(in_.WithOpName("A2"), "XTimesTwo", {a1}); ConstructOp(in_.WithOpName("B2"), "XTimesFour", {b1}); // The `Partition()` helper function uses the first letter of the op name ('A' // or 'B') to choose a device for each node. Partition(ToGraphDef(), &partitions_); EXPECT_EQ(2, partitions_.size()); // Test that partition graphs inherit function library from original graph. string a = "/job:a/replica:0/task:0/cpu:0"; string b = "/job:a/replica:0/task:0/cpu:1"; // Node "A2" is placed in part `a`, and uses only "XTimesTwo". ExpectFunctions(partitions_[a].library(), {"XTimesTwo"}); // Node "B2" is placed in part `b`, and uses both "XTimesFour" directly, // and "XTimesTwo" in the body of "XTimesFour". ExpectFunctions(partitions_[b].library(), {"XTimesTwo", "XTimesFour"}); } TEST_F(GraphPartitionTest, SetIncarnation) { GraphDef gdef; const char* const kSendRecvAttrs = R"proto( attr { key: 'T' value { type: DT_FLOAT } } attr { key: 'client_terminated' value { b: false } } attr { key: 'recv_device' value { s: 'B' } } attr { key: 'send_device' value { s: 'A' } } attr { key: 'send_device_incarnation' value { i: 0 } } attr { key: 'tensor_name' value { s: 'test' } } )proto"; CHECK(protobuf::TextFormat::ParseFromString( strings::StrCat( "node { name: 'A/Pi' op: 'Const' ", " attr { key: 'dtype' value { type: DT_FLOAT } } ", " attr { key: 'value' value { tensor { ", " dtype: DT_FLOAT tensor_shape {} float_val: 3.14 } } } }", "node { name: 'A' op: '_Send' input: 'A/Pi' ", kSendRecvAttrs, "}", "node { name: 'B' op: '_Recv' ", kSendRecvAttrs, " attr { key: 'tensor_type' value { type:DT_FLOAT}}}"), &gdef)); gdef.mutable_versions()->set_producer(TF_GRAPH_DEF_VERSION); Partition(gdef, &partitions_); EXPECT_EQ(2, partitions_.size()); for (const auto& kv : partitions_) { const GraphDef& gdef = kv.second; for (const NodeDef& ndef : gdef.node()) { if (ndef.name() == "A" || ndef.name() == "B") { int64 val; TF_CHECK_OK(GetNodeAttr(ndef, "send_device_incarnation", &val)); EXPECT_EQ(val, 100); // Send device is "A". } } } } TEST(TopologicalSortNodesWithTimePriorityTest, NoDependencies) { // Create placeholders, shuffle them so the order in the graph is not strictly // increasing. Scope root = Scope::NewRootScope().ExitOnError(); std::vector<int> indexes; for (int i = 0; i < 20; ++i) { indexes.push_back((i + 2001) % 20); } std::vector<ops::Placeholder> placeholders; for (int i : indexes) { placeholders.emplace_back(root.WithOpName(strings::StrCat("p", i)), DT_FLOAT); placeholders.back().node()->AddAttr("_start_time", i + 1); } GraphDef gdef; TF_EXPECT_OK(root.ToGraphDef(&gdef)); std::vector<std::pair<const NodeDef*, int64>> nodes; std::unordered_map<const NodeDef*, int64> node_to_start_time; TF_CHECK_OK( TopologicalSortNodesWithTimePriority(&gdef, &nodes, &node_to_start_time)); ASSERT_EQ(nodes.size(), 20); for (int i = 0; i < nodes.size(); ++i) { EXPECT_EQ(strings::StrCat("p", i), nodes[i].first->name()); EXPECT_EQ(i + 1, nodes[i].second); } } TEST(TopologicalSortNodesWithTimePriority, Dependencies) { // Create placeholders, shuffle them so the order in the graph is not strictly // increasing. Scope root = Scope::NewRootScope().ExitOnError(); std::vector<int> indexes; std::vector<ops::Placeholder> placeholders_in_order; const int num_leaves = 20; for (int i = 0; i < num_leaves; ++i) { indexes.push_back((i + 2001) % num_leaves); placeholders_in_order.emplace_back(root.WithOpName(strings::StrCat("p", i)), DT_FLOAT); placeholders_in_order.back().node()->AddAttr("_start_time", i + 1); } std::vector<ops::Placeholder> placeholders; for (int i : indexes) { placeholders.push_back(placeholders_in_order[i]); } // Create ops that depend on the placeholders. We give start times to these // that are in descending order (e.g., the op that depends on the first // placeholder runs last). std::vector<ops::Square> squares; for (int i : indexes) { squares.emplace_back(root.WithOpName(strings::StrCat("s", i)), placeholders[i]); squares.back().node()->AddAttr("_start_time", 50 - (i + 1)); } // Create addn to sum all squares. std::vector<Input> inputs; for (const auto& s : squares) inputs.push_back(s); ops::AddN addn = ops::AddN(root.WithOpName("addn"), tensorflow::gtl::ArraySlice<Input>(inputs)); // Start times is actually listed earlier than the nodes it depends on. // But because of dependency ordering, it is last in the list. addn.node()->AddAttr("_start_time", 1); GraphDef gdef; TF_EXPECT_OK(root.ToGraphDef(&gdef)); std::vector<std::pair<const NodeDef*, int64>> nodes; std::unordered_map<const NodeDef*, int64> node_to_start_time; TF_CHECK_OK( TopologicalSortNodesWithTimePriority(&gdef, &nodes, &node_to_start_time)); ASSERT_EQ(1 + squares.size() + placeholders.size(), nodes.size()); for (int i = 0; i < placeholders.size(); ++i) { const NodeDef* node = nodes[i].first; EXPECT_EQ(strings::StrCat("p", i), node->name()); EXPECT_EQ(i + 1, nodes[i].second); EXPECT_EQ(i + 1, node_to_start_time[node]); } for (int i = 0; i < squares.size(); ++i) { int node_index = placeholders.size() + i; int square_index = num_leaves - 1 - i; const NodeDef* node = nodes[node_index].first; EXPECT_EQ(strings::StrCat("s", square_index), node->name()); EXPECT_EQ(50 - (square_index + 1), nodes[node_index].second); EXPECT_EQ(50 - (square_index + 1), node_to_start_time[node]); } EXPECT_EQ("addn", nodes.back().first->name()); EXPECT_EQ(50, nodes.back().second); EXPECT_EQ(50, node_to_start_time[nodes.back().first]); } TEST(TopologicalSortNodesWithTimePriority, WhileLoop) { using namespace ::tensorflow::ops; // NOLINT(build/namespaces) using namespace ::tensorflow::ops::internal; // NOLINT(build/namespaces) // Create placeholders. Scope root = Scope::NewRootScope().ExitOnError(); std::vector<int> indexes; std::vector<Placeholder> placeholders_in_order; const int num_leaves = 20; for (int i = 0; i < num_leaves; ++i) { indexes.push_back((i + 2001) % num_leaves); placeholders_in_order.emplace_back(root.WithOpName(strings::StrCat("p", i)), DT_FLOAT); placeholders_in_order.back().node()->AddAttr("_start_time", i + 1); } std::vector<Placeholder> placeholders; placeholders.reserve(indexes.size()); for (int i : indexes) { placeholders.push_back(placeholders_in_order[i]); } // Add a while loop above each placeholder. std::vector<Exit> while_exits; const int nodes_per_loop = 8; for (int i : indexes) { Scope scope = root.NewSubScope(strings::StrCat("while", i)); auto dummy = Placeholder(scope, DT_FLOAT); Enter enter(scope, placeholders[i], strings::StrCat("frame", i)); Merge merge(scope, std::initializer_list<Input>{enter, dummy}); auto cv = Const(scope.WithControlDependencies({merge.output}), false); LoopCond loop_cond(scope, cv); Switch switch_node(scope, merge.output, loop_cond); Identity identity(scope, switch_node.output_true); NextIteration next_iteration(scope, identity); while_exits.emplace_back(scope.WithOpName("exit"), switch_node.output_false); // Complete loop by removing dummy node and attaching NextIteration to // that input of the merge node. scope.graph()->RemoveNode(dummy.node()); scope.graph()->AddEdge(next_iteration.node(), 0, merge.output.node(), 1); int base_start_time = i * 10 + 100; for (const auto& op : std::initializer_list<Output>{ enter, merge.output, cv, loop_cond, switch_node.output_false, identity, next_iteration, while_exits.back()}) { op.node()->AddAttr("_start_time", base_start_time++); } } // Create ops that depend on the loop exits. std::vector<Square> squares; squares.reserve(indexes.size()); for (int i : indexes) { squares.emplace_back(root.WithOpName(strings::StrCat("s", i)), while_exits[i]); squares.back().node()->AddAttr("_start_time", 500 - (i + 1)); } GraphDef gdef; TF_EXPECT_OK(root.ToGraphDef(&gdef)); // Run the sort. The while loop nodes do not appear in the output <nodes>. std::vector<std::pair<const NodeDef*, int64>> nodes; std::unordered_map<const NodeDef*, int64> node_to_start_time; TF_CHECK_OK( TopologicalSortNodesWithTimePriority(&gdef, &nodes, &node_to_start_time)); ASSERT_LT(while_exits.size() + squares.size() + placeholders.size(), nodes.size()); int node_index = 0; for (int i = 0; i < placeholders.size(); ++i, ++node_index) { const NodeDef* node = nodes[i].first; EXPECT_EQ(strings::StrCat("p", i), node->name()); EXPECT_EQ(i + 1, nodes[i].second); EXPECT_EQ(i + 1, node_to_start_time[node]); } for (int i = 0; i < while_exits.size(); ++i, node_index += nodes_per_loop) { const NodeDef* node = nodes[node_index].first; EXPECT_EQ(strings::StrCat("while", i, "/Enter"), node->name()); EXPECT_EQ(100 + i * 10, nodes[node_index].second); EXPECT_EQ(100 + i * 10, node_to_start_time[node]); } for (int i = 0; i < squares.size(); ++i, ++node_index) { int square_index = num_leaves - 1 - i; const NodeDef* node = nodes[node_index].first; EXPECT_EQ(strings::StrCat("s", square_index), node->name()); EXPECT_EQ(500 - (square_index + 1), nodes[node_index].second); EXPECT_EQ(500 - (square_index + 1), node_to_start_time[node]); } } } // namespace } // namespace tensorflow
36.939607
80
0.663663
[ "vector" ]
29d961605afd19ca6549578dd1d4965495391e71
12,920
cc
C++
test/extensions/transport_sockets/tls/cert_validator/default_validator_test.cc
fishy/envoy
2757eb9eb0faece7b2779f7c1e21953b31b836f4
[ "Apache-2.0" ]
null
null
null
test/extensions/transport_sockets/tls/cert_validator/default_validator_test.cc
fishy/envoy
2757eb9eb0faece7b2779f7c1e21953b31b836f4
[ "Apache-2.0" ]
2
2022-03-25T09:42:17.000Z
2022-03-31T10:31:34.000Z
test/extensions/transport_sockets/tls/cert_validator/default_validator_test.cc
fishy/envoy
2757eb9eb0faece7b2779f7c1e21953b31b836f4
[ "Apache-2.0" ]
null
null
null
#include <string> #include <vector> #include "source/extensions/transport_sockets/tls/cert_validator/default_validator.h" #include "source/extensions/transport_sockets/tls/cert_validator/san_matcher.h" #include "test/extensions/transport_sockets/tls/ssl_test_utility.h" #include "test/test_common/environment.h" #include "test/test_common/test_runtime.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" #include "openssl/x509v3.h" namespace Envoy { namespace Extensions { namespace TransportSockets { namespace Tls { TEST(DefaultCertValidatorTest, TestVerifySubjectAltNameDNSMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); std::vector<std::string> verify_subject_alt_name_list = {"server1.example.com", "server2.example.com"}; EXPECT_TRUE(DefaultCertValidator::verifySubjectAltName(cert.get(), verify_subject_alt_name_list)); } TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameDNSMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw([^.]*\.example.com)raw")); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameIncorrectTypeMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw([^.]*\.example.com)raw")); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_URI, matcher)}); EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameWildcardDNSMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir " "}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.set_exact("api.example.com"); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestMultiLevelMatch) { // san_multiple_dns_cert matches *.example.com bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir " "}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.set_exact("foo.api.example.com"); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestVerifySubjectAltNameURIMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem")); std::vector<std::string> verify_subject_alt_name_list = {"spiffe://lyft.com/fake-team", "spiffe://lyft.com/test-team"}; EXPECT_TRUE(DefaultCertValidator::verifySubjectAltName(cert.get(), verify_subject_alt_name_list)); } TEST(DefaultCertValidatorTest, TestVerifySubjectAltMultiDomain) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir " "}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem")); std::vector<std::string> verify_subject_alt_name_list = {"https://a.www.example.com"}; EXPECT_FALSE( DefaultCertValidator::verifySubjectAltName(cert.get(), verify_subject_alt_name_list)); } TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameURIMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw(spiffe://lyft.com/[^/]*-team)raw")); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_URI, matcher)}); EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestVerifySubjectAltNameNotMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); std::vector<std::string> verify_subject_alt_name_list = {"foo", "bar"}; EXPECT_FALSE( DefaultCertValidator::verifySubjectAltName(cert.get(), verify_subject_alt_name_list)); } TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameNotMatched) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw([^.]*\.example\.net)raw")); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_IPADD, matcher)}); subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_URI, matcher)}); subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_EMAIL, matcher)}); EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } TEST(DefaultCertValidatorTest, TestCertificateVerificationWithSANMatcher) { Stats::TestUtil::TestStore test_store; SslStats stats = generateSslStats(test_store); // Create the default validator object. auto default_validator = std::make_unique<Extensions::TransportSockets::Tls::DefaultCertValidator>( /*CertificateValidationContextConfig=*/nullptr, stats, Event::GlobalTimeSystem().timeSystem()); bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw([^.]*\.example.com)raw")); std::vector<SanMatcherPtr> san_matchers; san_matchers.push_back(SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); // Verify the certificate with correct SAN regex matcher. EXPECT_EQ(default_validator->verifyCertificate(cert.get(), /*verify_san_list=*/{}, san_matchers), Envoy::Ssl::ClientValidationStatus::Validated); EXPECT_EQ(stats.fail_verify_san_.value(), 0); matcher.MergeFrom(TestUtility::createExactMatcher("hello.example.com")); std::vector<SanMatcherPtr> invalid_san_matchers; invalid_san_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); // Verify the certificate with incorrect SAN exact matcher. EXPECT_EQ(default_validator->verifyCertificate(cert.get(), /*verify_san_list=*/{}, invalid_san_matchers), Envoy::Ssl::ClientValidationStatus::Failed); EXPECT_EQ(stats.fail_verify_san_.value(), 1); } TEST(DefaultCertValidatorTest, TestCertificateVerificationWithNoValidationContext) { Stats::TestUtil::TestStore test_store; SslStats stats = generateSslStats(test_store); // Create the default validator object. auto default_validator = std::make_unique<Extensions::TransportSockets::Tls::DefaultCertValidator>( /*CertificateValidationContextConfig=*/nullptr, stats, Event::GlobalTimeSystem().timeSystem()); EXPECT_EQ(default_validator->verifyCertificate(/*cert=*/nullptr, /*verify_san_list=*/{}, /*subject_alt_name_matchers=*/{}), Envoy::Ssl::ClientValidationStatus::NotValidated); bssl::UniquePtr<X509> cert(X509_new()); EXPECT_EQ(default_validator->doVerifyCertChain(/*store_ctx=*/nullptr, /*ssl_extended_info=*/nullptr, /*leaf_cert=*/*cert, /*transport_socket_options=*/nullptr), 0); } TEST(DefaultCertValidatorTest, NoSanInCert) { bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/fake_ca_cert.pem")); envoy::type::matcher::v3::StringMatcher matcher; matcher.MergeFrom(TestUtility::createRegexMatcher(R"raw([^.]*\.example\.net)raw")); std::vector<SanMatcherPtr> subject_alt_name_matchers; subject_alt_name_matchers.push_back( SanMatcherPtr{std::make_unique<StringSanMatcher>(GEN_DNS, matcher)}); EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers)); } class MockCertificateValidationContextConfig : public Ssl::CertificateValidationContextConfig { public: MockCertificateValidationContextConfig() { auto matcher = envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher(); matcher.set_san_type( static_cast<envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher_SanType>( 123)); matchers_.emplace_back(matcher); }; const std::string& caCert() const override { return s_; } const std::string& caCertPath() const override { return s_; } const std::string& certificateRevocationList() const override { return s_; } const std::string& certificateRevocationListPath() const override { return s_; } const std::vector<envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher>& subjectAltNameMatchers() const override { return matchers_; } const std::vector<std::string>& verifyCertificateHashList() const override { return strs_; } const std::vector<std::string>& verifyCertificateSpkiList() const override { return strs_; } bool allowExpiredCertificate() const override { return false; } MOCK_METHOD(envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext:: TrustChainVerification, trustChainVerification, (), (const override)); MOCK_METHOD(const absl::optional<envoy::config::core::v3::TypedExtensionConfig>&, customValidatorConfig, (), (const override)); MOCK_METHOD(Api::Api&, api, (), (const override)); bool onlyVerifyLeafCertificateCrl() const override { return false; } private: std::string s_; std::vector<std::string> strs_; std::vector<envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher> matchers_; }; TEST(DefaultCertValidatorTest, TestUnexpectedSanMatcherType) { auto mock_context_config = std::make_unique<MockCertificateValidationContextConfig>(); EXPECT_CALL(*mock_context_config.get(), trustChainVerification()) .WillRepeatedly(testing::Return(envoy::extensions::transport_sockets::tls::v3:: CertificateValidationContext::ACCEPT_UNTRUSTED)); auto matchers = std::vector<envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher>(); Stats::TestUtil::TestStore store; auto ssl_stats = generateSslStats(store); auto validator = std::make_unique<DefaultCertValidator>(mock_context_config.get(), ssl_stats, Event::GlobalTimeSystem().timeSystem()); auto ctx = std::vector<SSL_CTX*>(); EXPECT_THROW_WITH_REGEX(validator->initializeSslContexts(ctx, false), EnvoyException, "Failed to create string SAN matcher of type.*"); } } // namespace Tls } // namespace TransportSockets } // namespace Extensions } // namespace Envoy
52.95082
100
0.745356
[ "object", "vector" ]
29dd86b7b6e58837e752eb114d249f4afe0eead2
5,884
cpp
C++
src/openpose/pose/poseParametersRender.cpp
jimfcarroll/openpose
fa8d6ff8f616f90c22eaae9d6926fef84db73ea6
[ "DOC", "MIT-CMU" ]
1
2019-01-01T08:55:18.000Z
2019-01-01T08:55:18.000Z
src/openpose/pose/poseParametersRender.cpp
jimfcarroll/openpose
fa8d6ff8f616f90c22eaae9d6926fef84db73ea6
[ "DOC", "MIT-CMU" ]
null
null
null
src/openpose/pose/poseParametersRender.cpp
jimfcarroll/openpose
fa8d6ff8f616f90c22eaae9d6926fef84db73ea6
[ "DOC", "MIT-CMU" ]
1
2019-03-14T02:59:01.000Z
2019-03-14T02:59:01.000Z
#include <openpose/pose/poseParameters.hpp> #include <openpose/pose/poseParametersRender.hpp> namespace op { const std::array<std::vector<float>, (int)PoseModel::Size> POSE_SCALES{ std::vector<float>{POSE_BODY_25_SCALES_RENDER_GPU}, // BODY_25 std::vector<float>{POSE_COCO_SCALES_RENDER_GPU}, // COCO std::vector<float>{POSE_MPI_SCALES_RENDER_GPU}, // MPI_15 std::vector<float>{POSE_MPI_SCALES_RENDER_GPU}, // MPI_15_4 std::vector<float>{POSE_BODY_19_SCALES_RENDER_GPU}, // BODY_19 std::vector<float>{POSE_BODY_19_SCALES_RENDER_GPU}, // BODY_19_X2 std::vector<float>{POSE_BODY_19_SCALES_RENDER_GPU}, // BODY_19N std::vector<float>{POSE_BODY_25_SCALES_RENDER_GPU}, // BODY_25E std::vector<float>{POSE_BODY_65_SCALES_RENDER_GPU}, // BODY_65 std::vector<float>{POSE_CAR_12_SCALES_RENDER_GPU}, // CAR_12 std::vector<float>{POSE_BODY_25_SCALES_RENDER_GPU}, // BODY_25D std::vector<float>{POSE_BODY_23_SCALES_RENDER_GPU}, // BODY_23 std::vector<float>{POSE_CAR_22_SCALES_RENDER_GPU}, // CAR_22 std::vector<float>{POSE_BODY_19_SCALES_RENDER_GPU}, // BODY_19E std::vector<float>{POSE_BODY_25B_SCALES_RENDER_GPU}, // BODY_25B std::vector<float>{POSE_BODY_95_SCALES_RENDER_GPU}, // BODY_95 }; const std::array<std::vector<float>, (int)PoseModel::Size> POSE_COLORS{ std::vector<float>{POSE_BODY_25_COLORS_RENDER_GPU}, // BODY_25 std::vector<float>{POSE_COCO_COLORS_RENDER_GPU}, // COCO std::vector<float>{POSE_MPI_COLORS_RENDER_GPU}, // MPI_15 std::vector<float>{POSE_MPI_COLORS_RENDER_GPU}, // MPI_15_4 std::vector<float>{POSE_BODY_19_COLORS_RENDER_GPU}, // BODY_19 std::vector<float>{POSE_BODY_19_COLORS_RENDER_GPU}, // BODY_19_X2 std::vector<float>{POSE_BODY_19_COLORS_RENDER_GPU}, // BODY_19N std::vector<float>{POSE_BODY_25_COLORS_RENDER_GPU}, // BODY_25E std::vector<float>{POSE_BODY_65_COLORS_RENDER_GPU}, // BODY_65 std::vector<float>{POSE_CAR_12_COLORS_RENDER_GPU}, // CAR_12 std::vector<float>{POSE_BODY_25_COLORS_RENDER_GPU}, // BODY_25D std::vector<float>{POSE_BODY_23_COLORS_RENDER_GPU}, // BODY_23 std::vector<float>{POSE_CAR_22_COLORS_RENDER_GPU}, // CAR_22 std::vector<float>{POSE_BODY_19_COLORS_RENDER_GPU}, // BODY_19E std::vector<float>{POSE_BODY_25B_COLORS_RENDER_GPU}, // BODY_25B std::vector<float>{POSE_BODY_95_COLORS_RENDER_GPU}, // BODY_95 }; const std::array<std::vector<unsigned int>, (int)PoseModel::Size> POSE_BODY_PART_PAIRS_RENDER{ std::vector<unsigned int>{POSE_BODY_25_PAIRS_RENDER_GPU}, // BODY_25 std::vector<unsigned int>{POSE_COCO_PAIRS_RENDER_GPU}, // COCO std::vector<unsigned int>{POSE_MPI_PAIRS_RENDER_GPU}, // MPI_15 std::vector<unsigned int>{POSE_MPI_PAIRS_RENDER_GPU}, // MPI_15_4 std::vector<unsigned int>{POSE_BODY_19_PAIRS_RENDER_GPU}, // BODY_19 std::vector<unsigned int>{POSE_BODY_19_PAIRS_RENDER_GPU}, // BODY_19_X2 std::vector<unsigned int>{POSE_BODY_19_PAIRS_RENDER_GPU}, // BODY_19N std::vector<unsigned int>{POSE_BODY_25_PAIRS_RENDER_GPU}, // BODY_25E std::vector<unsigned int>{POSE_BODY_65_PAIRS_RENDER_GPU}, // BODY_65 std::vector<unsigned int>{POSE_CAR_12_PAIRS_RENDER_GPU}, // CAR_12 std::vector<unsigned int>{POSE_BODY_25_PAIRS_RENDER_GPU}, // BODY_25D std::vector<unsigned int>{POSE_BODY_23_PAIRS_RENDER_GPU}, // BODY_23 std::vector<unsigned int>{POSE_CAR_22_PAIRS_RENDER_GPU}, // CAR_22 std::vector<unsigned int>{POSE_BODY_19_PAIRS_RENDER_GPU}, // BODY_19E std::vector<unsigned int>{POSE_BODY_25B_PAIRS_RENDER_GPU}, // BODY_25B std::vector<unsigned int>{POSE_BODY_95_PAIRS_RENDER_GPU}, // BODY_95 }; // Rendering functions const std::vector<float>& getPoseScales(const PoseModel poseModel) { try { return POSE_SCALES.at((int)poseModel); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return POSE_SCALES[(int)poseModel]; } } const std::vector<float>& getPoseColors(const PoseModel poseModel) { try { return POSE_COLORS.at((int)poseModel); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return POSE_COLORS[(int)poseModel]; } } const std::vector<unsigned int>& getPoseBodyPartPairsRender(const PoseModel poseModel) { try { return POSE_BODY_PART_PAIRS_RENDER.at((int)poseModel); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return POSE_BODY_PART_PAIRS_RENDER[(int)poseModel]; } } unsigned int getNumberElementsToRender(const PoseModel poseModel) { try { return (unsigned int)(getPoseBodyPartMapping(poseModel).size() + getPosePartPairs(poseModel).size()/2 + 3 + (poseModel == PoseModel::BODY_25D ? 2*(getPoseNumberBodyParts(poseModel) - 1) : 0) ); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return 0u; } } }
49.864407
98
0.621006
[ "vector" ]
29e02bb6a24eb5c00294c810e60f5c3c1c443945
7,830
cpp
C++
src/file/FileManager.cpp
heaven-chp/common-library-cpp
386d7abf9218ecba41ea10447e70b914faa40a4d
[ "Apache-2.0" ]
null
null
null
src/file/FileManager.cpp
heaven-chp/common-library-cpp
386d7abf9218ecba41ea10447e70b914faa40a4d
[ "Apache-2.0" ]
10
2021-12-19T07:47:50.000Z
2021-12-19T13:34:50.000Z
src/file/FileManager.cpp
heaven-chp/common-library-cpp
386d7abf9218ecba41ea10447e70b914faa40a4d
[ "Apache-2.0" ]
null
null
null
#include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <cstring> #include <fstream> #include <functional> using namespace std; #include "FileManager.h" template <class T> static T Run(const function<T(error_code &)> &func); template <class T> static T Run(const function<T(const string &, error_code &)> &func, const string &strPath); template <class T> static T Run(const function<T(const string &, const string &, error_code &)> &func, const string &strFromPath, const string &strToPath); template <class T> static T Run(const function<T(error_code &)> &func) { error_code errorCode; errorCode.clear(); const T result = func(errorCode); errno = errorCode.value(); return result; } template <class T> static T Run(const function<T(const string &, error_code &)> &func, const string &strPath) { error_code errorCode; errorCode.clear(); const T result = func(strPath, errorCode); errno = errorCode.value(); return result; } template <class T> static T Run(const function<T(const string &, const string &, error_code &)> &func, const string &strFromPath, const string &strToPath) { error_code errorCode; errorCode.clear(); const T result = func(strFromPath, strToPath, errorCode); errno = errorCode.value(); return result; } bool FileManager::IsExist(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::exists(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } bool FileManager::IsRegularFile(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::is_regular_file(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } bool FileManager::IsDirectory(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::is_directory(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } int FileManager::LockBetweenProcess(const string &strPath) { const mode_t mode = 0775; const int iFD = open(strPath.c_str(), O_CREAT | O_RDWR, mode); if(iFD < 0) { return -1; } flock sFlock; sFlock.l_type = F_RDLCK | F_WRLCK; sFlock.l_start = 0; sFlock.l_whence = SEEK_SET; sFlock.l_len = 0; if(fcntl(iFD, F_SETLK, &sFlock) == -1) { close(iFD); return -1; } return iFD; } bool FileManager::LockBetweenProcess(const int &iFD) { flock sFlock; sFlock.l_type = F_RDLCK | F_WRLCK; sFlock.l_start = 0; sFlock.l_whence = SEEK_SET; sFlock.l_len = 0; if(fcntl(iFD, F_SETLK, &sFlock) == -1) { return false; } return true; } bool FileManager::UnLockBetweenProcess(const int &iFD) { flock sFlock; sFlock.l_type = F_UNLCK; sFlock.l_start = 0; sFlock.l_whence = SEEK_SET; sFlock.l_len = 0; if(fcntl(iFD, F_SETLK, &sFlock) == -1) { return false; } return true; } bool FileManager::Read(const string &strPath, string &strResult) { strResult.clear(); ifstream ifs; ifs.open(strPath); if(ifs.is_open() == false) { return false; } ifs.seekg(0, ios::end); const int iSize = ifs.tellg(); strResult.resize(iSize); ifs.seekg(0, ios::beg); ifs.read(&strResult[0], iSize); return true; } bool FileManager::Write(const string &strPath, const string &strData, const ios_base::openmode &openMode) { ofstream ofs; ofs.open(strPath, openMode); if(ofs.is_open() == false) { return false; } ofs << strData; ofs.close(); return true; } bool FileManager::MakeDir(const string &strPath) { if(this->IsExist(strPath) && this->IsDirectory(strPath)) { return true; } auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::create_directory(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } bool FileManager::MakeDirs(const string &strPath) { if(this->IsExist(strPath) && this->IsDirectory(strPath)) { return true; } auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::create_directories(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } bool FileManager::Copy(const string &strFromPath, const string &strToPath) { auto job = [&](const string &strFromPath, const string &strToPath, error_code &errorCode) -> auto { filesystem::copy(filesystem::path(strFromPath), filesystem::path(strToPath), errorCode); return !errorCode; }; return Run<bool>(job, strFromPath, strToPath); } bool FileManager::Copy(const string &strFromPath, const string &strToPath, filesystem::copy_options options) { error_code errorCode; errorCode.clear(); filesystem::copy(filesystem::path(strFromPath), filesystem::path(strToPath), options, errorCode); errno = errorCode.value(); return !errorCode; } bool FileManager::CopyAll(const string &strFromPath, const string &strToPath) { auto job = [&](const string &strFromPath, const string &strToPath, error_code &errorCode) -> auto { filesystem::copy(filesystem::path(strFromPath), filesystem::path(strToPath), filesystem::copy_options::recursive, errorCode); return !errorCode; }; return Run<bool>(job, strFromPath, strToPath); } bool FileManager::Remove(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::remove(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } bool FileManager::RemoveAll(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::remove_all(filesystem::path(strPath), errorCode); }; return Run<bool>(job, strPath); } string FileManager::ToAbsolutePath(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::absolute(filesystem::path(strPath), errorCode); }; return Run<string>(job, strPath); } string FileManager::ToCanonicalPath(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::canonical(filesystem::path(strPath), errorCode); }; return Run<string>(job, strPath); } string FileManager::ToRelativePathToRootPath(const string &strPath) { return filesystem::path(strPath).relative_path(); } string FileManager::GetTempPath() { auto job = [&](error_code &errorCode) -> auto { return filesystem::temp_directory_path(errorCode); }; return Run<string>(job); } string FileManager::GetRootPath(const string &strPath) { return filesystem::path(strPath).root_directory(); } string FileManager::GetRelativePath(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { return filesystem::relative(filesystem::path(strPath), errorCode); }; return Run<string>(job, strPath); } vector<string> FileManager::GetPathList(const string &strPath) { vector<string> vecPath; vecPath.clear(); for(const filesystem::directory_entry &iter : filesystem::directory_iterator(strPath)) { vecPath.push_back(iter.path()); } return vecPath; } vector<string> FileManager::GetRecursivePathList(const string &strPath) { vector<string> vecPath; vecPath.clear(); for(const filesystem::directory_entry &iter : filesystem::recursive_directory_iterator(strPath)) { vecPath.push_back(iter.path()); } return vecPath; } string FileManager::GetCurrentPath() { auto job = [&](error_code &errorCode) -> auto { return filesystem::current_path(errorCode); }; return Run<string>(job); } bool FileManager::SetCurrentPath(const string &strPath) { auto job = [&](const string &strPath, error_code &errorCode) -> auto { filesystem::current_path(filesystem::path(strPath), errorCode); return !errorCode; }; return Run<bool>(job, strPath); }
22.5
136
0.706386
[ "vector" ]
29e328323acc5866f7f761a22d2749641a0b870f
2,699
cpp
C++
tools/bpp-phyl/src/Bpp/Phyl/Mapping/NaiveSubstitutionCount.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
2
2021-08-24T16:03:30.000Z
2022-03-18T14:52:43.000Z
tools/bpp-phyl/src/Bpp/Phyl/Mapping/NaiveSubstitutionCount.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
null
null
null
tools/bpp-phyl/src/Bpp/Phyl/Mapping/NaiveSubstitutionCount.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
null
null
null
// // File: NaiveSubstitutionCount.h // Created by: Julien Dutheil // Created on: Wed Apr 5 11:08 2006 // /* Copyright or © or Copr. Bio++ Development Team, (November 16, 2004, 2005, 2006) This software is a computer program whose purpose is to provide classes for phylogenetic data analysis. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #include "NaiveSubstitutionCount.h" using namespace bpp; Matrix<double>* NaiveSubstitutionCount::getAllNumbersOfSubstitutions(double length, size_t type) const { size_t n = supportedChars_.size(); RowMatrix<double>* mat = new RowMatrix<double>(n, n); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { (*mat)(i, j) = (register_->getType(i, j) == type ? (weights_ ? weights_->getIndex(supportedChars_[i], supportedChars_[j]) : 1.) : 0.); } } return mat; } LabelSubstitutionCount::LabelSubstitutionCount(const SubstitutionModel* model) : AbstractSubstitutionCount( new TotalSubstitutionRegister(model)), label_(model->getNumberOfStates(), model->getNumberOfStates()), supportedChars_(model->getAlphabetStates()) { size_t n = supportedChars_.size(); double count = 0; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { if (i == j) label_(i, j) = 0; else label_(i, j) = ++count; } } }
36.472973
140
0.732123
[ "model" ]
29e39bf296b4090b625f6b90f96b265cecfc0c32
3,227
cpp
C++
lib/AST/TypeJoinMeet.cpp
EBGToo/swift
8b917e1a87d7208b32542eec0eaf7186ccd97b57
[ "Apache-2.0" ]
null
null
null
lib/AST/TypeJoinMeet.cpp
EBGToo/swift
8b917e1a87d7208b32542eec0eaf7186ccd97b57
[ "Apache-2.0" ]
null
null
null
lib/AST/TypeJoinMeet.cpp
EBGToo/swift
8b917e1a87d7208b32542eec0eaf7186ccd97b57
[ "Apache-2.0" ]
null
null
null
//===--- TypeJoinMeet.cpp - Swift Type "join" and "meet" -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the "join" operation for types (and, eventually, // "meet"). // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Type.h" #include "swift/AST/Types.h" #include "llvm/ADT/SmallPtrSet.h" using namespace swift; Type Type::join(Type type1, Type type2) { assert(!type1->hasTypeVariable() && !type2->hasTypeVariable() && "Cannot compute join of types involving type variables"); // FIXME: This algorithm is woefully incomplete, and is only currently used // for optimizing away extra exploratory work in the constraint solver. It // should eventually encompass all of the subtyping rules of the language. // If the types are equivalent, the join is obvious. if (type1->isEqual(type2)) return type1; // If both are class types or opaque types that potentially have superclasses, // find the common superclass. if (type1->mayHaveSuperclass() && type2->mayHaveSuperclass()) { ASTContext &ctx = type1->getASTContext(); LazyResolver *resolver = ctx.getLazyResolver(); /// Walk the superclasses of type1 looking for type2. Record them for our /// second step. llvm::SmallPtrSet<CanType, 8> superclassesOfType1; CanType canType2 = type2->getCanonicalType(); for (Type super1 = type1; super1; super1 = super1->getSuperclass(resolver)){ CanType canSuper1 = super1->getCanonicalType(); // If we have found the second type, we're done. if (canSuper1 == canType2) return super1; superclassesOfType1.insert(canSuper1); } // Look through the superclasses of type2 to determine if any were also // superclasses of type1. for (Type super2 = type2; super2; super2 = super2->getSuperclass(resolver)){ CanType canSuper2 = super2->getCanonicalType(); // If we found the first type, we're done. if (superclassesOfType1.count(canSuper2)) return super2; } // There is no common superclass; we're done. return nullptr; } // If one or both of the types are optional types, look at the underlying // object type. OptionalTypeKind otk1, otk2; Type objectType1 = type1->getAnyOptionalObjectType(otk1); Type objectType2 = type2->getAnyOptionalObjectType(otk2); if (otk1 == OTK_Optional || otk2 == OTK_Optional) { // Compute the join of the unwrapped type. If there is none, we're done. Type unwrappedJoin = join(objectType1 ? objectType1 : type1, objectType2 ? objectType2 : type2); if (!unwrappedJoin) return nullptr; return OptionalType::get(unwrappedJoin); } // The join can only be an existential. return nullptr; }
37.964706
80
0.659436
[ "object" ]
29e78a3b5d4305b9a5587706fa7d87af43dcbd06
22,523
cpp
C++
applications/qTox/src/persistence/profile.cpp
gaohangaohan/qkd-net
90f52104412b5c5c82668362dbd3e4791261f332
[ "MIT" ]
17
2019-04-21T14:10:57.000Z
2022-03-26T09:32:53.000Z
applications/qTox/src/persistence/profile.cpp
gaohangaohan/qkd-net
90f52104412b5c5c82668362dbd3e4791261f332
[ "MIT" ]
22
2019-01-11T19:13:44.000Z
2022-02-26T17:58:32.000Z
applications/qTox/src/persistence/profile.cpp
gaohangaohan/qkd-net
90f52104412b5c5c82668362dbd3e4791261f332
[ "MIT" ]
17
2019-03-06T17:29:29.000Z
2021-08-10T10:17:09.000Z
/* Copyright © 2015-2017 by The qTox Project Contributors This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre 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. qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>. */ #include <QBuffer> #include <QDebug> #include <QDir> #include <QFileInfo> #include <QObject> #include <QSaveFile> #include <QThread> #include <cassert> #include <sodium.h> #include "profile.h" #include "profilelocker.h" #include "settings.h" #include "src/core/core.h" #include "src/net/avatarbroadcaster.h" #include "src/nexus.h" #include "src/widget/gui.h" #include "src/widget/tool/identicon.h" #include "src/widget/widget.h" /** * @class Profile * @brief Manages user profiles. * * @var bool Profile::newProfile * @brief True if this is a newly created profile, with no .tox save file yet. * * @var bool Profile::isRemoved * @brief True if the profile has been removed by remove(). */ QVector<QString> Profile::profiles; Profile::Profile(QString name, const QString& password, bool isNewProfile, const QByteArray& toxsave) : name{name} , newProfile{isNewProfile} , isRemoved{false} { Settings& s = Settings::getInstance(); s.setCurrentProfile(name); s.saveGlobal(); coreThread = new QThread(); coreThread->setObjectName("qTox Core"); core = new Core(coreThread, *this, &Settings::getInstance()); QObject::connect(core, &Core::idSet, this, [this, password](const ToxId& id) { loadDatabase(id, password); }, Qt::QueuedConnection); core->moveToThread(coreThread); QObject::connect(coreThread, &QThread::started, core, [=]() { core->start(toxsave); const ToxPk selfPk = core->getSelfPublicKey(); QByteArray data = loadAvatarData(selfPk); if (data.isEmpty()) { qDebug() << "Self avatar not found, will broadcast empty avatar to friends"; } setAvatar(data, selfPk); }); } /** * @brief Locks and loads an existing profile and creates the associate Core* instance. * @param name Profile name. * @param password Profile password. * @return Returns a nullptr on error. Profile pointer otherwise. * * @example If the profile is already in use return nullptr. */ Profile* Profile::loadProfile(QString name, const QString& password) { if (ProfileLocker::hasLock()) { qCritical() << "Tried to load profile " << name << ", but another profile is already locked!"; return nullptr; } if (!ProfileLocker::lock(name)) { qWarning() << "Failed to lock profile " << name; return nullptr; } std::unique_ptr<ToxEncrypt> tmpKey = nullptr; QByteArray data = QByteArray(); Profile* p = nullptr; qint64 fileSize = 0; QString path = Settings::getInstance().getSettingsDirPath() + name + ".tox"; QFile saveFile(path); qDebug() << "Loading tox save " << path; if (!saveFile.exists()) { qWarning() << "The tox save file " << path << " was not found"; goto fail; } if (!saveFile.open(QIODevice::ReadOnly)) { qCritical() << "The tox save file " << path << " couldn't' be opened"; goto fail; } fileSize = saveFile.size(); if (fileSize <= 0) { qWarning() << "The tox save file" << path << " is empty!"; goto fail; } data = saveFile.readAll(); if (ToxEncrypt::isEncrypted(data)) { if (password.isEmpty()) { qCritical() << "The tox save file is encrypted, but we don't have a password!"; goto fail; } tmpKey = ToxEncrypt::makeToxEncrypt(password, data); if (!tmpKey) { qCritical() << "Failed to derive key of the tox save file"; goto fail; } data = tmpKey->decrypt(data); if (data.isEmpty()) { qCritical() << "Failed to decrypt the tox save file"; goto fail; } } else { if (!password.isEmpty()) { qWarning() << "We have a password, but the tox save file is not encrypted"; } } saveFile.close(); p = new Profile(name, password, false, data); p->passkey = std::move(tmpKey); if (p->passkey) { p->encrypted = true; } return p; // cleanup in case of error fail: saveFile.close(); ProfileLocker::unlock(); return nullptr; } /** * @brief Creates a new profile and the associated Core* instance. * @param name Username. * @param password If password is not empty, the profile will be encrypted. * @return Returns a nullptr on error. Profile pointer otherwise. * * @note If the profile is already in use return nullptr. */ Profile* Profile::createProfile(QString name, QString password) { std::unique_ptr<ToxEncrypt> tmpKey; if (!password.isEmpty()) { tmpKey = ToxEncrypt::makeToxEncrypt(password); if (!tmpKey) { qCritical() << "Failed to derive key for the tox save"; return nullptr; } } if (ProfileLocker::hasLock()) { qCritical() << "Tried to create profile " << name << ", but another profile is already locked!"; return nullptr; } if (exists(name)) { qCritical() << "Tried to create profile " << name << ", but it already exists!"; return nullptr; } if (!ProfileLocker::lock(name)) { qWarning() << "Failed to lock profile " << name; return nullptr; } Settings::getInstance().createPersonal(name); Profile* p = new Profile(name, password, true, QByteArray()); p->passkey = std::move(tmpKey); if (p->passkey) { p->encrypted = true; } return p; } Profile::~Profile() { if (!isRemoved && core->isReady()) { saveToxSave(); } core->deleteLater(); while (coreThread->isRunning()) qApp->processEvents(); delete coreThread; if (!isRemoved) { Settings::getInstance().savePersonal(this); Settings::getInstance().sync(); ProfileLocker::assertLock(); assert(ProfileLocker::getCurLockName() == name); ProfileLocker::unlock(); } } /** * @brief Lists all the files in the config dir with a given extension * @param extension Raw extension, e.g. "jpeg" not ".jpeg". * @return Vector of filenames. */ QVector<QString> Profile::getFilesByExt(QString extension) { QDir dir(Settings::getInstance().getSettingsDirPath()); QVector<QString> out; dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); dir.setNameFilters(QStringList("*." + extension)); QFileInfoList list = dir.entryInfoList(); out.reserve(list.size()); for (QFileInfo file : list) { out += file.completeBaseName(); } return out; } /** * @brief Scan for profile, automatically importing them if needed. * @warning NOT thread-safe. */ void Profile::scanProfiles() { profiles.clear(); QVector<QString> toxfiles = getFilesByExt("tox"), inifiles = getFilesByExt("ini"); for (QString toxfile : toxfiles) { if (!inifiles.contains(toxfile)) { Settings::getInstance().createPersonal(toxfile); } profiles.append(toxfile); } } QVector<QString> Profile::getProfiles() { return profiles; } Core* Profile::getCore() { return core; } QString Profile::getName() const { return name; } /** * @brief Starts the Core thread */ void Profile::startCore() { coreThread->start(); } bool Profile::isNewProfile() { return newProfile; } /** * @brief Saves the profile's .tox save, encrypted if needed. * @warning Invalid on deleted profiles. */ void Profile::saveToxSave() { assert(core->isReady()); QByteArray data = core->getToxSaveData(); assert(data.size()); saveToxSave(data); } /** * @brief Write the .tox save, encrypted if needed. * @param data Byte array of profile save. * @warning Invalid on deleted profiles. */ void Profile::saveToxSave(QByteArray data) { assert(!isRemoved); ProfileLocker::assertLock(); assert(ProfileLocker::getCurLockName() == name); QString path = Settings::getInstance().getSettingsDirPath() + name + ".tox"; qDebug() << "Saving tox save to " << path; QSaveFile saveFile(path); if (!saveFile.open(QIODevice::WriteOnly)) { qCritical() << "Tox save file " << path << " couldn't be opened"; return; } if (encrypted) { data = passkey->encrypt(data); if (data.isEmpty()) { qCritical() << "Failed to encrypt, can't save!"; saveFile.cancelWriting(); return; } } saveFile.write(data); // check if everything got written if (saveFile.flush()) { saveFile.commit(); newProfile = false; } else { saveFile.cancelWriting(); qCritical() << "Failed to write, can't save!"; } } /** * @brief Gets the path of the avatar file cached by this profile and corresponding to this owner * ID. * @param owner Path to avatar of friend with this PK will returned. * @param forceUnencrypted If true, return the path to the plaintext file even if this is an * encrypted profile. * @return Path to the avatar. */ QString Profile::avatarPath(const ToxPk& owner, bool forceUnencrypted) { const QString ownerStr = owner.toString(); if (!encrypted || forceUnencrypted) { return Settings::getInstance().getSettingsDirPath() + "avatars/" + ownerStr + ".png"; } QByteArray idData = ownerStr.toUtf8(); QByteArray pubkeyData = core->getSelfId().getPublicKey().getKey(); constexpr int hashSize = TOX_PUBLIC_KEY_SIZE; static_assert(hashSize >= crypto_generichash_BYTES_MIN && hashSize <= crypto_generichash_BYTES_MAX, "Hash size not supported by libsodium"); static_assert(hashSize >= crypto_generichash_KEYBYTES_MIN && hashSize <= crypto_generichash_KEYBYTES_MAX, "Key size not supported by libsodium"); QByteArray hash(hashSize, 0); crypto_generichash((uint8_t*)hash.data(), hashSize, (uint8_t*)idData.data(), idData.size(), (uint8_t*)pubkeyData.data(), pubkeyData.size()); return Settings::getInstance().getSettingsDirPath() + "avatars/" + hash.toHex().toUpper() + ".png"; } /** * @brief Get our avatar from cache. * @return Avatar as QPixmap. */ QPixmap Profile::loadAvatar() { return loadAvatar(core->getSelfId().getPublicKey()); } /** * @brief Get a contact's avatar from cache. * @param owner Friend PK to load avatar. * @return Avatar as QPixmap. */ QPixmap Profile::loadAvatar(const ToxPk& owner) { QPixmap pic; if (Settings::getInstance().getShowIdenticons()) { const QByteArray avataData = loadAvatarData(owner); if (avataData.isEmpty()) { pic = QPixmap::fromImage(Identicon(owner.getKey()).toImage(16)); } else { pic.loadFromData(avataData); } } else { pic.loadFromData(loadAvatarData(owner)); } return pic; } /** * @brief Get a contact's avatar from cache. * @param owner Friend PK to load avatar. * @return Avatar as QByteArray. */ QByteArray Profile::loadAvatarData(const ToxPk& owner) { QString path = avatarPath(owner); bool avatarEncrypted = encrypted; // If the encrypted avatar isn't found, try loading the unencrypted one for the same ID if (avatarEncrypted && !QFile::exists(path)) { avatarEncrypted = false; path = avatarPath(owner, true); } QFile file(path); if (!file.open(QIODevice::ReadOnly)) { return {}; } QByteArray pic = file.readAll(); if (avatarEncrypted && !pic.isEmpty()) { pic = passkey->decrypt(pic); } return pic; } void Profile::loadDatabase(const ToxId& id, QString password) { if (isRemoved) { qDebug() << "Can't load database of removed profile"; return; } QByteArray salt = id.getPublicKey().getKey(); if (salt.size() != TOX_PASS_SALT_LENGTH) { qWarning() << "Couldn't compute salt from public key" << name; GUI::showError(QObject::tr("Error"), QObject::tr("qTox couldn't open your chat logs, they will be disabled.")); } // At this point it's too early to load the personal settings (Nexus will do it), so we always // load // the history, and if it fails we can't change the setting now, but we keep a nullptr database = std::make_shared<RawDatabase>(getDbPath(name), password, salt); if (database && database->isOpen()) { history.reset(new History(database)); } else { qWarning() << "Failed to open database for profile" << name; GUI::showError(QObject::tr("Error"), QObject::tr("qTox couldn't open your chat logs, they will be disabled.")); } } void Profile::setAvatar(QByteArray pic, const ToxPk& owner) { QPixmap pixmap; QByteArray avatarData; if (!pic.isEmpty()) { pixmap.loadFromData(pic); avatarData = pic; } else { if (Settings::getInstance().getShowIdenticons()) { // with IDENTICON_ROWS=5 this gives a 160x160 image file const QImage identicon = Identicon(owner.getKey()).toImage(32); pixmap = QPixmap::fromImage(identicon); } else { pixmap.load(":/img/contact_dark.svg"); } } saveAvatar(avatarData, owner); emit selfAvatarChanged(pixmap); AvatarBroadcaster::setAvatar(avatarData); AvatarBroadcaster::enableAutoBroadcast(); } /** * @brief Adds history message about friendship request attempt if history is enabled * @param friendPk Pk of a friend which request is destined to * @param message Friendship request message */ void Profile::onRequestSent(const ToxPk& friendPk, const QString& message) { if (!isHistoryEnabled()) { return; } QString pkStr = friendPk.toString(); QString inviteStr = Core::tr("/me offers friendship, \"%1\"").arg(message); QString selfStr = core->getSelfPublicKey().toString(); QDateTime datetime = QDateTime::currentDateTime(); history->addNewMessage(pkStr, inviteStr, selfStr, datetime, true, QString()); } /** * @brief Save an avatar to cache. * @param pic Picture to save. * @param owner PK of avatar owner. */ void Profile::saveAvatar(QByteArray pic, const ToxPk& owner) { if (encrypted && !pic.isEmpty()) { pic = passkey->encrypt(pic); } QString path = avatarPath(owner); QDir(Settings::getInstance().getSettingsDirPath()).mkdir("avatars"); if (pic.isEmpty()) { QFile::remove(path); } else { QSaveFile file(path); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "Tox avatar " << path << " couldn't be saved"; return; } file.write(pic); file.commit(); } } /** * @brief Get the tox hash of a cached avatar. * @param owner Friend PK to get hash. * @return Avatar tox hash. */ QByteArray Profile::getAvatarHash(const ToxPk& owner) { QByteArray pic = loadAvatarData(owner); QByteArray avatarHash(TOX_HASH_LENGTH, 0); tox_hash((uint8_t*)avatarHash.data(), (uint8_t*)pic.data(), pic.size()); return avatarHash; } /** * @brief Removes our own avatar. */ void Profile::removeAvatar() { removeAvatar(core->getSelfId().getPublicKey()); } /** * @brief Checks that the history is enabled in the settings, and loaded successfully for this * profile. * @return True if enabled, false otherwise. */ bool Profile::isHistoryEnabled() { return Settings::getInstance().getEnableLogging() && history; } /** * @brief Get chat history. * @return May return a nullptr if the history failed to load. */ History* Profile::getHistory() { return history.get(); } /** * @brief Removes a cached avatar. * @param owner Friend PK whose avater to delete. */ void Profile::removeAvatar(const ToxPk& owner) { QFile::remove(avatarPath(owner)); if (owner == core->getSelfId().getPublicKey()) { setAvatar({}, core->getSelfPublicKey()); } } bool Profile::exists(QString name) { QString path = Settings::getInstance().getSettingsDirPath() + name; return QFile::exists(path + ".tox"); } /** * @brief Checks, if profile has a password. * @return True if we have a password set (doesn't check the actual file on disk). */ bool Profile::isEncrypted() const { return encrypted; } /** * @brief Checks if profile is encrypted. * @note Checks the actual file on disk. * @param name Profile name. * @return True if profile is encrypted, false otherwise. */ bool Profile::isEncrypted(QString name) { uint8_t data[TOX_PASS_ENCRYPTION_EXTRA_LENGTH] = {0}; QString path = Settings::getInstance().getSettingsDirPath() + name + ".tox"; QFile saveFile(path); if (!saveFile.open(QIODevice::ReadOnly)) { qWarning() << "Couldn't open tox save " << path; return false; } saveFile.read((char*)data, TOX_PASS_ENCRYPTION_EXTRA_LENGTH); saveFile.close(); return tox_is_data_encrypted(data); } /** * @brief Removes the profile permanently. * Updates the profiles vector. * @return Vector of filenames that could not be removed. * @warning It is invalid to call loadToxSave or saveToxSave on a deleted profile. */ QVector<QString> Profile::remove() { if (isRemoved) { qWarning() << "Profile " << name << " is already removed!"; return {}; } isRemoved = true; qDebug() << "Removing profile" << name; for (int i = 0; i < profiles.size(); ++i) { if (profiles[i] == name) { profiles.removeAt(i); i--; } } QString path = Settings::getInstance().getSettingsDirPath() + name; ProfileLocker::unlock(); QFile profileMain{path + ".tox"}; QFile profileConfig{path + ".ini"}; QVector<QString> ret; if (!profileMain.remove() && profileMain.exists()) { ret.push_back(profileMain.fileName()); qWarning() << "Could not remove file " << profileMain.fileName(); } if (!profileConfig.remove() && profileConfig.exists()) { ret.push_back(profileConfig.fileName()); qWarning() << "Could not remove file " << profileConfig.fileName(); } QString dbPath = getDbPath(name); if (database && database->isOpen() && !database->remove() && QFile::exists(dbPath)) { ret.push_back(dbPath); qWarning() << "Could not remove file " << dbPath; } history.release(); database.reset(); return ret; } /** * @brief Tries to rename the profile. * @param newName New name for the profile. * @return False on error, true otherwise. */ bool Profile::rename(QString newName) { QString path = Settings::getInstance().getSettingsDirPath() + name, newPath = Settings::getInstance().getSettingsDirPath() + newName; if (!ProfileLocker::lock(newName)) { return false; } QFile::rename(path + ".tox", newPath + ".tox"); QFile::rename(path + ".ini", newPath + ".ini"); if (database) { database->rename(newName); } bool resetAutorun = Settings::getInstance().getAutorun(); Settings::getInstance().setAutorun(false); Settings::getInstance().setCurrentProfile(newName); if (resetAutorun) { Settings::getInstance().setAutorun(true); // fixes -p flag in autostart command line } name = newName; return true; } const ToxEncrypt* Profile::getPasskey() const { return passkey.get(); } /** * @brief Delete core and restart a new one */ void Profile::restartCore() { GUI::setEnabled(false); // Core::reset re-enables it if (!isRemoved && core->isReady()) { saveToxSave(); } QMetaObject::invokeMethod(core, "reset"); } /** * @brief Changes the encryption password and re-saves everything with it * @param newPassword Password for encryption, if empty profile will be decrypted. * @param oldPassword Supply previous password if already encrypted or empty QString if not yet * encrypted. * @return Empty QString on success or error message on failure. */ QString Profile::setPassword(const QString& newPassword) { if (newPassword.isEmpty()) { // remove password encrypted = false; } else { std::unique_ptr<ToxEncrypt> newpasskey = ToxEncrypt::makeToxEncrypt(newPassword); if (!newpasskey) { qCritical() << "Failed to derive key from password, the profile won't use the new password"; return tr( "Failed to derive key from password, the profile won't use the new password."); } // apply change passkey = std::move(newpasskey); encrypted = true; } // apply new encryption saveToxSave(); bool dbSuccess = false; // TODO: ensure the database and the tox save file use the same password if (database) { dbSuccess = database->setPassword(newPassword); } QString error{}; if (!dbSuccess) { error = tr("Couldn't change password on the database, it might be corrupted or use the old " "password."); } Nexus::getDesktopGUI()->reloadHistory(); QByteArray avatar = loadAvatarData(core->getSelfId().getPublicKey()); saveAvatar(avatar, core->getSelfId().getPublicKey()); QVector<uint32_t> friendList = core->getFriendList(); QVectorIterator<uint32_t> i(friendList); while (i.hasNext()) { const ToxPk friendPublicKey = core->getFriendPublicKey(i.next()); saveAvatar(loadAvatarData(friendPublicKey), friendPublicKey); } return error; } /** * @brief Retrieves the path to the database file for a given profile. * @param profileName Profile name. * @return Path to database. */ QString Profile::getDbPath(const QString& profileName) { return Settings::getInstance().getSettingsDirPath() + profileName + ".db"; }
28.510127
103
0.634374
[ "vector" ]
29eb19ab581642bb54fbe5a5dc6f50dc551975da
3,277
cc
C++
Codeforces/343 Division 2/Problem E/E.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/343 Division 2/Problem E/E.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/343 Division 2/Problem E/E.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <bits/stdc++.h> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb push_back #define mp make_pair #define foreach(it, v) for(__typeof((v).begin()) it=(v).begin(); it != (v).end(); ++it) #define meta __FUNCTION__,__LINE__ #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); using namespace std; template<typename S, typename T> ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;} template<typename T> ostream& operator<<(ostream& out,vector<T> const& v){ int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;} void tr(){cout << endl;} template<typename S, typename ... Strings> void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);} typedef long long ll; typedef pair<int,int> pii; const int LOGN = 17; const int N = 1 << LOGN; int n, m; vector<int> g[N]; int p[LOGN][N], l[N]; int sz[N]; ll allPaths[N]; ll allPathsR[N]; int LCA(int x, int y){ if(l[x] < l[y]) swap(x,y); int tmp = 1; while((1<<tmp) <= l[x]) tmp++; tmp--; for(int i = tmp; i >= 0; i--) if(l[x] - (1<<i) >= l[y]) x = p[i][x]; if(x == y) return y; for(int i = tmp; i >= 0; i--) if(p[i][x] > 0 and p[i][x] != p[i][y]) x = p[i][x], y = p[i][y]; return p[0][x]; } void dfs(int cur, int prev){ sz[cur] = 1; foreach(it, g[cur]){ int v = *it; if(v == prev) continue; p[0][v] = cur; l[v] = l[cur] + 1; dfs(v, cur); sz[cur] += sz[v]; allPaths[cur] += allPaths[v] + sz[v]; } } void dfs2(int cur, int prev){ foreach(it, g[cur]){ int v = *it; if(v == prev) continue; allPathsR[v] = allPathsR[cur] + allPaths[cur] - allPaths[v] - sz[v] + (n - sz[v]); dfs2(v, cur); } } int getAncestor(int x, int h){ if(l[x] == h) return x; int del = l[x] - h, tmp = 0; while((1 << tmp) <= del) tmp++; tmp--; while(true){ if(l[x] == h) return x; if(l[p[tmp][x]] >= h) x = p[tmp][x]; tmp--; } } int main(){ sd2(n,m); for(int i = 1; i < n; i++){ int a, b; sd2(a,b); g[a].pb(b); g[b].pb(a); } for(int i = 1; i <= n; i++){ if(g[i].size() == 1){ dfs(i,-1); dfs2(i,-1); break; } } for(int i = 1; i < LOGN; i++){ for(int j = 1; j <= n; j++){ p[i][j] = p[i-1][p[i-1][j]]; } } int u, v, lca; for(int i = 1; i <= m; i++){ u, v; sd2(u,v); lca = LCA(u,v); if(lca != u and lca != v){ int len = (l[u] + l[v] - 2*l[lca]) + 1; double ans = 0, factor = 1; factor /= sz[u]; factor /= sz[v]; ans += factor * allPaths[u] * sz[v]; ans += factor * allPaths[v] * sz[u]; printf("%.9lf\n", ans + len); } else{ if(lca == v) swap(u,v); int len = (l[v] - l[u]) + 1; int specialChild = getAncestor(v, l[u]+1); ll m_allPathsR = allPaths[u] + allPathsR[u] - allPaths[specialChild] - sz[specialChild]; long double ans = 0, factor = 1; factor /= sz[v]; factor /= (n - sz[specialChild]); ans += factor * m_allPathsR * sz[v]; ans += factor * allPaths[v] * (n - sz[specialChild]); printf("%.9lf\n", (double) ans + len); } } return 0; }
19.981707
97
0.521819
[ "vector" ]
29eb5ba9271adcbec52b919b06c84ff54c7c6ace
6,720
cpp
C++
Engine/Engine/JobManager.cpp
evil84/RenderLab
0fcf91465b2e6f31305a2257b3e2ad3b92cf6e93
[ "MIT" ]
3
2021-03-01T02:22:47.000Z
2021-04-22T02:55:50.000Z
Engine/Engine/JobManager.cpp
evil84/RenderLab
0fcf91465b2e6f31305a2257b3e2ad3b92cf6e93
[ "MIT" ]
null
null
null
Engine/Engine/JobManager.cpp
evil84/RenderLab
0fcf91465b2e6f31305a2257b3e2ad3b92cf6e93
[ "MIT" ]
null
null
null
#include "PCH.h" #include "JobManager.h" #include "Common/Assert.h" template <size_t COUNT> class LockFreeJobStealingQueue { public: static_assert(std::_Is_pow_2(COUNT)); static constexpr size_t MASK = COUNT - 1; LockFreeJobStealingQueue(const LockFreeJobStealingQueue&) = delete; LockFreeJobStealingQueue(const LockFreeJobStealingQueue&&) = delete; LockFreeJobStealingQueue& operator=(const LockFreeJobStealingQueue&) = delete; LockFreeJobStealingQueue& operator=(LockFreeJobStealingQueue&&) = delete; LockFreeJobStealingQueue() { } ~LockFreeJobStealingQueue() { } void Reset() noexcept { jobAllocated_ = 0; } Job* NewJob() noexcept { const uint32 index = jobAllocated_++; return &jobAllocator_[index & MASK]; } void Push(Job* job) noexcept { const int64 bottom = bottom_.load(std::memory_order_relaxed); JobList_[bottom & MASK] = job; bottom_.store(bottom + 1, std::memory_order_release); } Job* Pop() noexcept { int64 bottom = bottom_.fetch_sub(1, std::memory_order_seq_cst) - 1; Assert(bottom >= -1); int64 top = top_.load(std::memory_order_seq_cst); if (top < bottom) { return JobList_[bottom & MASK]; } Job* job = nullptr; if (top == bottom) { job = JobList_[bottom & MASK]; if (top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed)) { ++top; } else { job = nullptr; } } else { Assert(top - bottom == 1); } bottom_.store(top, std::memory_order_relaxed); return job; } Job* Steal() noexcept { while (true) { int64 top = top_.load(std::memory_order_seq_cst); int64 bottom = bottom_.load(std::memory_order_seq_cst); if (top >= bottom) { return nullptr; } Job* job = JobList_[top & MASK]; if (top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed)) { return job; } } } private: std::atomic<int64> top_ = 0; std::atomic<int64> bottom_ = 0; uint32 jobAllocated_ = 0; Job jobAllocator_[COUNT]; Job* JobList_[COUNT]; }; thread_local uint32 currentThreadId; thread_local Job* currentThreadJob; thread_local JobWorkThread* currentWorkThread; class JobWorkThread { static constexpr size_t JOB_QUEUE_SIZE = 4096; using JobQueue = LockFreeJobStealingQueue<JOB_QUEUE_SIZE>; public: JobWorkThread(JobManager* jobManager, uint32 threadId, bool mainThread) { jobManager_ = jobManager; threadId_ = threadId; if (mainThread) { currentThreadId = threadId; currentWorkThread = this; } else { workThread_ = new std::thread(&JobWorkThread::ThreadFunction, this); } } ~JobWorkThread() { } Job* NewJob() noexcept { return jobQueue_.NewJob(); } JobQueue& GetJobQueue() noexcept { return jobQueue_; } Job* GetJob() noexcept { Job* job = jobQueue_.Pop(); if (job) { return job; } JobQueue* stolenQueue = nullptr; do { uint32 randomThreadIndex = FastRandomNumber() % jobManager_->GetNumWorkerThreads(); JobWorkThread* workerThread = jobManager_->GetWorkerThreads()[randomThreadIndex]; stolenQueue = &workerThread->GetJobQueue(); } while (&jobQueue_ == stolenQueue); do { job = stolenQueue->Steal(); } while (!job && jobManager_->HasActiveJobs()); return job; } void ExecuteJob(Job* job) noexcept { jobManager_->numActiveJobs_.fetch_sub(1, std::memory_order_relaxed); job->func_(job, &job->padding); } void FinishJob(Job* job) noexcept { job->numUnfinishedJobs_.fetch_sub(1, std::memory_order_relaxed); const uint32 numUnfinishedJobs = job->numUnfinishedJobs_.load(std::memory_order_relaxed); if (numUnfinishedJobs == 0) { if (job->parent_) { FinishJob(job->parent_); } } } private: void ThreadFunction() { currentThreadId = threadId_; currentWorkThread = this; while (true) { if (requestExit_.load(std::memory_order_relaxed)) { break; } if (jobManager_->threadStartExecute_.load(std::memory_order_relaxed) == false) { std::this_thread::yield(); continue; } Job* job = GetJob(); if (job) { ExecuteJob(job); FinishJob(job); } else { jobManager_->Wait(); } } } uint32 FastRandomNumber() noexcept { seed_ = (214013 * seed_ + 2531011); return (seed_ >> 16) & 0x7FFF; } public: static uint32 GetCurrentThreadId() noexcept { return currentThreadId; } private: JobManager* jobManager_ = nullptr; uint32 threadId_ = 0; std::thread* workThread_ = nullptr; std::atomic<bool> requestExit_ = false; uint32 seed_ = 0; JobQueue jobQueue_; }; JobManager::JobManager(uint32 numWorkerThreads) : numWorkerThreads_(numWorkerThreads) { workerThreads_.reserve(numWorkerThreads); for (uint32 index = 0; index < numWorkerThreads; ++index) { workerThreads_.push_back(new JobWorkThread(this, index, index == 0)); } threadStartExecute_.store(true, std::memory_order_relaxed); } JobManager::~JobManager() { } const uint32 JobManager::GetNumWorkerThreads() const noexcept { return numWorkerThreads_; } Job* JobManager::CreateJob(JobFunction jobFunc, Job* parentJob) noexcept { if (parentJob) { parentJob->numUnfinishedJobs_.fetch_add(1, std::memory_order_relaxed); } JobWorkThread* workThread = GetCurrentWorkThread(); Job* newJob = workThread->NewJob(); newJob->func_ = jobFunc; newJob->parent_ = parentJob; newJob->numUnfinishedJobs_.store(1, std::memory_order_relaxed); return newJob; } void JobManager::Run(Job* job) { numActiveJobs_.fetch_add(1, std::memory_order_relaxed); JobWorkThread* currentWorkThread = GetCurrentWorkThread(); currentWorkThread->GetJobQueue().Push(job); Wake(); } void JobManager::Wait(Job* job) { JobWorkThread* currentWorkThread = GetCurrentWorkThread(); while (!HasJobCompleted(job)) { Job* nextJob = currentWorkThread->GetJob(); if (nextJob) { currentWorkThread->ExecuteJob(nextJob); currentWorkThread->FinishJob(nextJob); } } } std::vector<JobWorkThread*>& JobManager::GetWorkerThreads() noexcept { return workerThreads_; } bool JobManager::HasJobCompleted(Job* job) const noexcept { return job->numUnfinishedJobs_.load(std::memory_order_relaxed) <= 0; } JobWorkThread* JobManager::GetCurrentWorkThread() noexcept { uint32 currentWorkThreadId = JobWorkThread::GetCurrentThreadId(); return workerThreads_[currentWorkThreadId]; } void JobManager::Wait() noexcept { std::unique_lock<std::mutex> lock(waitMutex_); ++waitCount_; waitCv_.wait(lock); --waitCount_; } void JobManager::Wake() noexcept { waitMutex_.lock(); const uint32 waitNum = waitCount_; waitMutex_.unlock(); if (waitNum == 1) { waitCv_.notify_one(); } else { waitCv_.notify_all(); } } bool JobManager::HasActiveJobs() const noexcept { return numActiveJobs_.load(std::memory_order_relaxed) > 0; }
25.358491
106
0.715179
[ "vector" ]
29ee24d9eaec0b107b7adf443c6cf9a253c1e080
2,527
cpp
C++
FWCore/Utilities/test/callxnowait_t.cppunit.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
FWCore/Utilities/test/callxnowait_t.cppunit.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
FWCore/Utilities/test/callxnowait_t.cppunit.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/*---------------------------------------------------------------------- Test program for edm::TypeID class. Changed by Viji on 29-06-2005 ----------------------------------------------------------------------*/ #include <cassert> #include <cppunit/extensions/HelperMacros.h> #include "FWCore/Utilities/interface/CallOnceNoWait.h" #include "FWCore/Utilities/interface/CallNTimesNoWait.h" #include <thread> #include <atomic> class testCallXNoWait : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(testCallXNoWait); CPPUNIT_TEST(onceTest); CPPUNIT_TEST(nTimesTest); CPPUNIT_TEST(onceThreadedTest); CPPUNIT_TEST(nTimesThreadedTest); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void onceTest(); void nTimesTest(); void onceThreadedTest(); void nTimesThreadedTest(); }; ///registration of the test so that the runner can find it CPPUNIT_TEST_SUITE_REGISTRATION(testCallXNoWait); void testCallXNoWait::onceTest() { edm::CallOnceNoWait guard; unsigned int iCount = 0; guard([&iCount]() { ++iCount; }); CPPUNIT_ASSERT(iCount == 1); guard([&iCount]() { ++iCount; }); CPPUNIT_ASSERT(iCount == 1); } void testCallXNoWait::nTimesTest() { edm::CallNTimesNoWait guard{3}; unsigned int iCount = 0; for (unsigned int i = 0; i < 6; ++i) { guard([&iCount]() { ++iCount; }); if (i < 3) { CPPUNIT_ASSERT(iCount == i + 1); } else { CPPUNIT_ASSERT(iCount == 3); } } } void testCallXNoWait::onceThreadedTest() { edm::CallOnceNoWait guard; std::atomic<unsigned int> iCount{0}; std::vector<std::thread> threads; std::atomic<bool> start{false}; for (unsigned int i = 0; i < 4; ++i) { threads.emplace_back([&guard, &iCount, &start]() { while (not start) { } guard([&iCount]() { ++iCount; }); }); } CPPUNIT_ASSERT(iCount == 0); start = true; for (auto& t : threads) { t.join(); } CPPUNIT_ASSERT(iCount == 1); } void testCallXNoWait::nTimesThreadedTest() { const unsigned short kMaxTimes = 3; edm::CallNTimesNoWait guard(kMaxTimes); std::atomic<unsigned int> iCount{0}; std::vector<std::thread> threads; std::atomic<bool> start{false}; for (unsigned int i = 0; i < 2 * kMaxTimes; ++i) { threads.emplace_back([&guard, &iCount, &start]() { while (not start) { } guard([&iCount]() { ++iCount; }); }); } CPPUNIT_ASSERT(iCount == 0); start = true; for (auto& t : threads) { t.join(); } CPPUNIT_ASSERT(iCount == kMaxTimes); }
21.415254
73
0.609814
[ "vector" ]
29f243a7b60a495c9a0ae15c0126ac39c8ae839a
3,181
hpp
C++
include/sdsl/k2_treap_helper.hpp
qPCR4vir/sdsl-lite
3ae7ac30c3837553cf20243cc3df8ee658b9f00f
[ "BSD-3-Clause" ]
1
2021-02-10T11:26:38.000Z
2021-02-10T11:26:38.000Z
include/sdsl/k2_treap_helper.hpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
1
2019-03-10T23:59:27.000Z
2019-03-10T23:59:27.000Z
include/sdsl/k2_treap_helper.hpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016, the SDSL Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. /*! \file k2_treap_helper.hpp \brief k2_treap_helper.hpp contains helper functions and definitions for a k^2-treap implementation. \author Simon Gog */ #ifndef INCLUDED_SDSL_K2_TREAP_HELPER #define INCLUDED_SDSL_K2_TREAP_HELPER #include "sdsl/vectors.hpp" #include "sdsl/bits.hpp" #include <tuple> #include <algorithm> #include <iterator> #include <vector> #include <complex> #include <queue> #include <array> //! Namespace for the succinct data structure library. namespace sdsl { namespace k2_treap_ns { // Precomputed value for fast k^2 treap operations template <uint8_t t_k> struct precomp { static struct impl { uint64_t exp[65]; impl() { exp[0] = 1; for (uint8_t i = 1; i < 65; ++i) { exp[i] = t_k * exp[i - 1]; } } } data; static uint64_t exp(uint8_t l) { return data.exp[l]; } static uint64_t divexp(uint64_t x, uint8_t l) { return x / data.exp[l]; } static uint64_t modexp(uint64_t x, uint8_t l) { return x % data.exp[l]; } }; template <> struct precomp<2> { static uint64_t exp(uint8_t l) { return 1ULL << l; } static uint64_t divexp(uint64_t x, uint8_t l) { return x >> l; } static uint64_t modexp(uint64_t x, uint8_t l) { return x & bits::lo_set[l]; } }; template <> struct precomp<4> { static uint64_t exp(uint8_t l) { return 1ULL << (2 * l); } static uint64_t divexp(uint64_t x, uint8_t l) { return x >> (2 * l); } static uint64_t modexp(uint64_t x, uint8_t l) { return x & bits::lo_set[2 * l]; } }; template <> struct precomp<8> { static uint64_t exp(uint8_t l) { return 1ULL << (3 * l); } static uint64_t divexp(uint64_t x, uint8_t l) { return x >> (3 * l); } static uint64_t modexp(uint64_t x, uint8_t l) { return x & bits::lo_set[3 * l]; } }; template <> struct precomp<16> { static uint64_t exp(uint8_t l) { return 1ULL << (4 * l); } static uint64_t divexp(uint64_t x, uint8_t l) { return x >> (4 * l); } static uint64_t modexp(uint64_t x, uint8_t l) { return x & bits::lo_set[4 * l]; } }; template <uint8_t t_k> typename precomp<t_k>::impl precomp<t_k>::data; typedef std::complex<uint64_t> t_p; typedef t_p point_type; typedef t_p range_type; struct node_type { uint8_t t; // level; size of node 1<<t t_p p; // lower left corner uint64_t idx; // index in bp uint64_t max_v; // maximal value t_p max_p; // maximal point node_type() = default; node_type(uint8_t _t, t_p _p, uint64_t _idx, uint64_t _max_v, t_p _max_p) : t(_t), p(_p), idx(_idx), max_v(_max_v), max_p(_max_p) { } node_type(node_type&&) = default; node_type(const node_type&) = default; node_type& operator=(node_type&&) = default; node_type& operator=(const node_type&) = default; bool operator<(const node_type& v) const { if (max_v != v.max_v) { return max_v < v.max_v; } if (real(max_p) != real(v.max_p)) { return real(max_p) > real(v.max_p); } return imag(max_p) > imag(v.max_p); } }; } // end namepsace k2_treap_ns } // end nomespace sdsl #endif
25.448
104
0.673059
[ "vector" ]
29f829ddade1a1e2f1449209ed477cf229482bfe
13,392
cc
C++
src/estimators/generalized_absolute_pose.cc
Graffity-Technologies/colmap
316bff479e94dc919ee4a7ab19485af0c3ac235b
[ "BSD-3-Clause" ]
24
2021-05-28T07:43:27.000Z
2022-03-22T14:37:28.000Z
src/estimators/generalized_absolute_pose.cc
Skydes/colmap
4032790844ef2733cb3945938b63ebaa4bbbc0ea
[ "BSD-3-Clause" ]
null
null
null
src/estimators/generalized_absolute_pose.cc
Skydes/colmap
4032790844ef2733cb3945938b63ebaa4bbbc0ea
[ "BSD-3-Clause" ]
4
2021-09-14T04:47:35.000Z
2022-03-25T04:38:27.000Z
// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill. // 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 ETH Zurich and UNC Chapel Hill 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 HOLDERS 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: Johannes L. Schoenberger (jsch-at-demuc-dot-de) #include "estimators/generalized_absolute_pose.h" #include <array> #include "base/polynomial.h" #include "base/projection.h" #include "estimators/generalized_absolute_pose_coeffs.h" #include "util/logging.h" namespace colmap { namespace { // Check whether the rays are close to parallel. bool CheckParallelRays(const Eigen::Vector3d& ray1, const Eigen::Vector3d& ray2, const Eigen::Vector3d& ray3) { const double kParallelThreshold = 1e-5; return ray1.cross(ray2).isApproxToConstant(0, kParallelThreshold) && ray1.cross(ray3).isApproxToConstant(0, kParallelThreshold); } // Check whether the points are close to collinear. bool CheckCollinearPoints(const Eigen::Vector3d& X1, const Eigen::Vector3d& X2, const Eigen::Vector3d& X3) { const double kMinNonCollinearity = 1e-5; const Eigen::Vector3d X12 = X2 - X1; const double non_collinearity_measure = X12.cross(X1 - X3).squaredNorm() / X12.squaredNorm(); return non_collinearity_measure < kMinNonCollinearity; } Eigen::Vector6d ComposePlueckerLine(const Eigen::Matrix3x4d& rel_tform, const Eigen::Vector2d& point2D) { const Eigen::Matrix3x4d inv_proj_matrix = InvertProjectionMatrix(rel_tform); const Eigen::Vector3d bearing = inv_proj_matrix.leftCols<3>() * point2D.homogeneous(); const Eigen::Vector3d proj_center = inv_proj_matrix.rightCols<1>(); const Eigen::Vector3d bearing_normalized = bearing.normalized(); Eigen::Vector6d pluecker; pluecker << bearing_normalized, proj_center.cross(bearing_normalized); return pluecker; } Eigen::Vector3d PointFromPlueckerLineAndDepth(const Eigen::Vector6d& pluecker, const double depth) { return pluecker.head<3>().cross(pluecker.tail<3>()) + depth * pluecker.head<3>(); } // Compute the coefficients from the system of 3 equations, nonlinear in the // depth of the points. Inputs are three Pluecker lines and the locations of // their corresponding points in 3D. The system of equations comes from the // distance constraints between 3D points: // // || f_i - f_j ||^2 = || (q_i x q_i' + lambda_i * q_i) - // (q_j x q_j' + lambda_j * q_j) ||^2 // // where [q_i; q_i'] is the Pluecker coordinate of bearing i and f_i is the // coordinate of the corresponding 3D point in the global coordinate system. A // 3D point in the local camera coordinate system along this line is // parameterized through the depth scalar lambda_i as: // // B_fi = q_i x q_i' + lambda_i * q_i. // Eigen::Matrix<double, 3, 6> ComputePolynomialCoefficients( const std::vector<Eigen::Vector6d>& plueckers, const std::vector<Eigen::Vector3d>& points3D) { CHECK_EQ(plueckers.size(), 3); CHECK_EQ(points3D.size(), 3); Eigen::Matrix<double, 3, 6> K; const std::array<int, 3> is = {{0, 0, 1}}; const std::array<int, 3> js = {{1, 2, 2}}; for (int k = 0; k < 3; ++k) { const int i = is[k]; const int j = js[k]; const Eigen::Vector3d moment_difference = plueckers[i].head<3>().cross(plueckers[i].tail<3>()) - plueckers[j].head<3>().cross(plueckers[j].tail<3>()); K(k, 0) = 1; K(k, 1) = -2 * plueckers[i].head<3>().dot(plueckers[j].head<3>()); K(k, 2) = 2 * moment_difference.dot(plueckers[i].head<3>()); K(k, 3) = 1; K(k, 4) = -2 * moment_difference.dot(plueckers[j].head<3>()); K(k, 5) = moment_difference.squaredNorm() - (points3D[i] - points3D[j]).squaredNorm(); } return K; } // Solve quadratics of the form: x^2 + bx + c = 0. int SolveQuadratic(const double b, const double c, double* roots) { const double delta = b * b - 4 * c; // Do not allow complex solutions. if (delta >= 0) { const double sqrt_delta = std::sqrt(delta); roots[0] = -0.5 * (b + sqrt_delta); roots[1] = -0.5 * (b - sqrt_delta); return 2; } else { return 0; } } // Given lambda_j, return the values for lambda_i, where: // k1 lambda_i^2 + (k2 lambda_j + k3) lambda_i // + k4 lambda_j^2 + k5 lambda_j + k6 = 0. void ComputeLambdaValues(const Eigen::Matrix<double, 3, 6>::ConstRowXpr& k, const double lambda_j, std::vector<double>* lambdas_i) { // Note that we solve x^2 + bx + c = 0, since k(0) is one. double roots[2]; const int num_solutions = SolveQuadratic(k(1) * lambda_j + k(2), lambda_j * (k(3) * lambda_j + k(4)) + k(5), roots); for (int i = 0; i < num_solutions; ++i) { if (roots[i] > 0) { lambdas_i->push_back(roots[i]); } } } // Given the coefficients of the polynomial system return the depths of the // points along the Pluecker lines. Use Sylvester resultant to get and 8th // degree polynomial for lambda_3 and back-substite in the original equations. std::vector<Eigen::Vector3d> ComputeDepthsSylvester( const Eigen::Matrix<double, 3, 6>& K) { const Eigen::Matrix<double, 9, 1> coeffs = ComputeDepthsSylvesterCoeffs(K); Eigen::VectorXd roots_real; Eigen::VectorXd roots_imag; if (!FindPolynomialRootsCompanionMatrix(coeffs, &roots_real, &roots_imag)) { return std::vector<Eigen::Vector3d>(); } // Back-substitute every lambda_3 to the system of equations. std::vector<Eigen::Vector3d> depths; depths.reserve(roots_real.size()); for (Eigen::VectorXd::Index i = 0; i < roots_real.size(); ++i) { const double kMaxRootImagRatio = 1e-3; if (std::abs(roots_imag(i)) > kMaxRootImagRatio * std::abs(roots_real(i))) { continue; } const double lambda_3 = roots_real(i); if (lambda_3 <= 0) { continue; } std::vector<double> lambdas_2; ComputeLambdaValues(K.row(2), lambda_3, &lambdas_2); // Now we have two depths, lambda_2 and lambda_3. From the two remaining // equations, we must get the same lambda_1, otherwise the solution is // invalid. for (const double lambda_2 : lambdas_2) { std::vector<double> lambdas_1_1; ComputeLambdaValues(K.row(0), lambda_2, &lambdas_1_1); std::vector<double> lambdas_1_2; ComputeLambdaValues(K.row(1), lambda_3, &lambdas_1_2); for (const double lambda_1_1 : lambdas_1_1) { for (const double lambda_1_2 : lambdas_1_2) { const double kMaxLambdaRatio = 1e-2; if (std::abs(lambda_1_1 - lambda_1_2) < kMaxLambdaRatio * std::max(lambda_1_1, lambda_1_2)) { const double lambda_1 = (lambda_1_1 + lambda_1_2) / 2; depths.emplace_back(lambda_1, lambda_2, lambda_3); } } } } } return depths; } } // namespace std::vector<GP3PEstimator::M_t> GP3PEstimator::Estimate( const std::vector<X_t>& points2D, const std::vector<Y_t>& points3D) { CHECK_EQ(points2D.size(), 3); CHECK_EQ(points3D.size(), 3); if (CheckCollinearPoints(points3D[0], points3D[1], points3D[2])) { return std::vector<GP3PEstimator::M_t>({}); } // Transform 2D points into compact Pluecker line representation. std::vector<Eigen::Vector6d> plueckers(3); for (size_t i = 0; i < 3; ++i) { plueckers[i] = ComposePlueckerLine(points2D[i].rel_tform, points2D[i].xy); } if (CheckParallelRays(plueckers[0].head<3>(), plueckers[1].head<3>(), plueckers[2].head<3>())) { return std::vector<GP3PEstimator::M_t>({}); } // Compute the coefficients k1, k2, k3 using Eq. 4. const Eigen::Matrix<double, 3, 6> K = ComputePolynomialCoefficients(plueckers, points3D); // Compute the depths along the Pluecker lines of the observations. const std::vector<Eigen::Vector3d> depths = ComputeDepthsSylvester(K); if (depths.empty()) { return std::vector<GP3PEstimator::M_t>({}); } // For all valid depth values, compute the transformation between points in // the camera and the world frame. This uses Umeyama's method rather than the // algorithm proposed in the paper, since Umeyama's method is numerically more // stable and this part is not a bottleneck. Eigen::Matrix3d points3D_world; for (size_t i = 0; i < 3; ++i) { points3D_world.col(i) = points3D[i]; } std::vector<M_t> models(depths.size()); for (size_t i = 0; i < depths.size(); ++i) { Eigen::Matrix3d points3D_camera; for (size_t j = 0; j < 3; ++j) { points3D_camera.col(j) = PointFromPlueckerLineAndDepth(plueckers[j], depths[i][j]); } const Eigen::Matrix4d transform = Eigen::umeyama(points3D_world, points3D_camera, false); models[i] = transform.topLeftCorner<3, 4>(); } return models; } void GP3PEstimator::Residuals(const std::vector<X_t>& points2D, const std::vector<Y_t>& points3D, const M_t& proj_matrix, std::vector<double>* residuals) { CHECK_EQ(points2D.size(), points3D.size()); residuals->resize(points2D.size(), 0); // Note that this code might not be as nice as Eigen expressions, // but it is significantly faster in various tests. const double P_00 = proj_matrix(0, 0); const double P_01 = proj_matrix(0, 1); const double P_02 = proj_matrix(0, 2); const double P_03 = proj_matrix(0, 3); const double P_10 = proj_matrix(1, 0); const double P_11 = proj_matrix(1, 1); const double P_12 = proj_matrix(1, 2); const double P_13 = proj_matrix(1, 3); const double P_20 = proj_matrix(2, 0); const double P_21 = proj_matrix(2, 1); const double P_22 = proj_matrix(2, 2); const double P_23 = proj_matrix(2, 3); for (size_t i = 0; i < points2D.size(); ++i) { const Eigen::Matrix3x4d& rel_tform = points2D[i].rel_tform; const double X_0 = points3D[i](0); const double X_1 = points3D[i](1); const double X_2 = points3D[i](2); // Project 3D point from world to generalized camera. const double pgx_0 = P_00 * X_0 + P_01 * X_1 + P_02 * X_2 + P_03; const double pgx_1 = P_10 * X_0 + P_11 * X_1 + P_12 * X_2 + P_13; const double pgx_2 = P_20 * X_0 + P_21 * X_1 + P_22 * X_2 + P_23; // Projection 3D point from generalized camera to camera of the observation. const double pcx_2 = rel_tform(2, 0) * pgx_0 + rel_tform(2, 1) * pgx_1 + rel_tform(2, 2) * pgx_2 + rel_tform(2, 3); // Check if 3D point is in front of camera. if (pcx_2 > std::numeric_limits<double>::epsilon()) { const double pcx_0 = rel_tform(0, 0) * pgx_0 + rel_tform(0, 1) * pgx_1 + rel_tform(0, 2) * pgx_2 + rel_tform(0, 3); const double pcx_1 = rel_tform(1, 0) * pgx_0 + rel_tform(1, 1) * pgx_1 + rel_tform(1, 2) * pgx_2 + rel_tform(1, 3); const double inv_pcx_norm = 1 / std::sqrt(pcx_0 * pcx_0 + pcx_1 * pcx_1 + pcx_2 * pcx_2); const double x_0 = points2D[i].xy(0); const double x_1 = points2D[i].xy(1); if (residual_type == ResidualType::CosineDistance) { const double inv_x_norm = 1 / std::sqrt(x_0 * x_0 + x_1 * x_1 + 1); const double cosine_dist = 1 - inv_pcx_norm * inv_x_norm * (pcx_0 * x_0 + pcx_1 * x_1 + pcx_2); (*residuals)[i] = cosine_dist * cosine_dist; } else if (residual_type == ResidualType::ReprojectionError) { const double inv_pcx_2 = 1.0 / pcx_2; const double dx_0 = x_0 - pcx_0 * inv_pcx_2; const double dx_1 = x_1 - pcx_1 * inv_pcx_2; const double reproj_error = dx_0 * dx_0 + dx_1 * dx_1; (*residuals)[i] = reproj_error; } else { LOG(FATAL) << "Invalid residual type"; } } else { (*residuals)[i] = std::numeric_limits<double>::max(); } } } } // namespace colmap
39.504425
80
0.652703
[ "vector", "transform", "3d" ]
29f849d3c44be9ff2f9306e46b10c4d4c639709f
1,204
cpp
C++
aws-cpp-sdk-snowball/source/model/OnDeviceServiceConfiguration.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-snowball/source/model/OnDeviceServiceConfiguration.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-snowball/source/model/OnDeviceServiceConfiguration.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/snowball/model/OnDeviceServiceConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Snowball { namespace Model { OnDeviceServiceConfiguration::OnDeviceServiceConfiguration() : m_nFSOnDeviceServiceHasBeenSet(false) { } OnDeviceServiceConfiguration::OnDeviceServiceConfiguration(JsonView jsonValue) : m_nFSOnDeviceServiceHasBeenSet(false) { *this = jsonValue; } OnDeviceServiceConfiguration& OnDeviceServiceConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("NFSOnDeviceService")) { m_nFSOnDeviceService = jsonValue.GetObject("NFSOnDeviceService"); m_nFSOnDeviceServiceHasBeenSet = true; } return *this; } JsonValue OnDeviceServiceConfiguration::Jsonize() const { JsonValue payload; if(m_nFSOnDeviceServiceHasBeenSet) { payload.WithObject("NFSOnDeviceService", m_nFSOnDeviceService.Jsonize()); } return payload; } } // namespace Model } // namespace Snowball } // namespace Aws
20.066667
90
0.768272
[ "model" ]
29f94118515f3259caa02cf27129345673844de4
2,696
cxx
C++
Plugins/Debug/vtkOutputDisplayerFilter.cxx
cmpute/AnCloud
4e675b9fa126ce6546fab09b329460a685815b05
[ "Unlicense" ]
null
null
null
Plugins/Debug/vtkOutputDisplayerFilter.cxx
cmpute/AnCloud
4e675b9fa126ce6546fab09b329460a685815b05
[ "Unlicense" ]
null
null
null
Plugins/Debug/vtkOutputDisplayerFilter.cxx
cmpute/AnCloud
4e675b9fa126ce6546fab09b329460a685815b05
[ "Unlicense" ]
null
null
null
#include "vtkOutputDisplayerFilter.h" #include <vtkObjectFactory.h> #include <vtkInformationVector.h> #include <vtkInformation.h> #include <sstream> #include <QDebug> vtkStandardNewMacro(vtkOutputDisplayerFilter); vtkOutputDisplayerFilter::vtkOutputDisplayerFilter() { } int vtkOutputDisplayerFilter::RequestInformation( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { qDebug() << "===========[RequestInformation]==============\n"; DisplayInformation(request, inputVector, outputVector); return 1; } int vtkOutputDisplayerFilter::RequestUpdateExtent( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { qDebug() << "===========[RequestInformation]==============\n"; DisplayInformation(request, inputVector, outputVector); return 1; } int vtkOutputDisplayerFilter::RequestData( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { qDebug() << "===========[RequestData]==============\n"; DisplayInformation(request, inputVector, outputVector); vtkDataObject* input = vtkDataObject::GetData(inputVector[0], 0); vtkDataObject* output = vtkDataObject::GetData(outputVector,0); if(!output) output = input->NewInstance(); output->ShallowCopy(input); return 1; } void vtkOutputDisplayerFilter::DisplayInformation( vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { std::stringstream ss; qDebug() << "---------- Request information object ------------\n"; request->Print(ss); int numPorts = this->GetNumberOfInputPorts(); for (int p = 0; p < numPorts; p++) { qDebug() << "---------- Output port " << p << " ------------\n"; int numInputs = inputVector[p]->GetNumberOfInformationObjects(); for (int i = 0; i < numInputs; i++) { qDebug() << "---------- Output information object " << i << " ------------\n"; vtkInformation* inInfo = inputVector[p]->GetInformationObject(i); ss.str(""); inInfo->Print(ss); inInfo->Get(vtkDataObject::DATA_OBJECT())->Print(ss); qDebug() << std::string(ss.str()).c_str(); } } } int vtkOutputDisplayerFilter::FillInputPortInformation( int, vtkInformation *info) { //info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject"); info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1); info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); qDebug() << "===========[FillInputPortInformation]==============\n"; return 1; } void vtkOutputDisplayerFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
29.304348
81
0.678783
[ "object" ]
29fa37c7e0c8c7bd300321d0a8c01d8d3bac57df
18,646
cpp
C++
3RVX/Settings.cpp
grtamm/3RVX
7607cf95e132c07aa31982b2f0901dea31e86a99
[ "BSD-2-Clause" ]
320
2015-02-04T21:48:29.000Z
2022-03-18T03:57:54.000Z
3RVX/Settings.cpp
grtamm/3RVX
7607cf95e132c07aa31982b2f0901dea31e86a99
[ "BSD-2-Clause" ]
100
2015-01-31T17:31:16.000Z
2022-03-05T23:22:20.000Z
3RVX/Settings.cpp
grtamm/3RVX
7607cf95e132c07aa31982b2f0901dea31e86a99
[ "BSD-2-Clause" ]
93
2015-02-26T15:04:54.000Z
2022-03-05T16:00:10.000Z
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "Settings.h" #pragma comment(lib, "Shlwapi.lib") #include <algorithm> #include <ctime> #include <ShlObj.h> #include <Shlwapi.h> #include "DefaultSettings.h" #include "Error.h" #include "HotkeyInfo.h" #include "LanguageTranslator.h" #include "Logger.h" #include "Monitor.h" #include "Skin/Skin.h" #include "StringUtils.h" std::wstring Settings::_appDir(L""); Settings *Settings::instance; std::vector<std::wstring> Settings::OSDPosNames = { L"Top", L"Left", L"Right", L"Bottom", L"Center", L"Top-left", L"Top-right", L"Bottom-left", L"Bottom-right", L"Custom" }; Settings *Settings::Instance() { if (instance == NULL) { instance = new Settings(); } return instance; } void Settings::Load() { /* First, clean up (if needed) */ delete _translator; _translator = NULL; _file = SettingsFile(); CLOG(L"Loading settings: %s", _file.c_str()); FILE *fp; _wfopen_s(&fp, _file.c_str(), L"rb"); if (fp == NULL) { QCLOG(L"Failed to open file!"); LoadEmptySettings(); return; } tinyxml2::XMLError result = _xml.LoadFile(fp); fclose(fp); if (result != tinyxml2::XMLError::XML_SUCCESS) { LoadEmptySettings(); return; } _root = _xml.GetDocument()->FirstChildElement("settings"); if (_root == NULL) { Error::ErrorMessage(Error::GENERR_MISSING_XML, L"<settings>"); LoadEmptySettings(); return; } } void Settings::LoadEmptySettings() { _xml.Clear(); _xml.InsertFirstChild(_xml.NewDeclaration()); _root = _xml.NewElement("settings"); _xml.GetDocument()->InsertEndChild(_root); } int Settings::Save() { CreateSettingsDir(); FILE *stream; errno_t err = _wfopen_s(&stream, _file.c_str(), L"w"); if (err != 0 || stream == NULL) { CLOG(L"Could not open settings file for writing!"); return 100 + err; } tinyxml2::XMLError result = _xml.SaveFile(stream); fclose(stream); return result; } bool Settings::Portable() { std::wstring portableSettings = AppDir() + L"\\" + DefaultSettings::SettingsFileName; if (PathFileExists(portableSettings.c_str()) == TRUE) { return true; } return false; } std::wstring Settings::SettingsDir() { /* First, is this a portable installation? */ if (Portable()) { return AppDir(); } /* If the install isn't portable, use the roaming appdata directory. */ wchar_t appData[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, NULL, appData); if (FAILED(hr)) { HRESULT hr = SHGetFolderPath( NULL, CSIDL_LOCAL_APPDATA, NULL, NULL, appData); if (FAILED(hr)) { // TODO: This probably warrants an error message! return AppDir(); } } return std::wstring(appData) + L"\\3RVX"; } void Settings::CreateSettingsDir() { std::wstring settingsDir = SettingsDir(); CLOG(L"Creating settings directory: %s", settingsDir.c_str()); settingsDir = L"\\\\?\\" + settingsDir; /* Use long file path (\\?\) */ BOOL result = CreateDirectory(settingsDir.c_str(), NULL); if (result == FALSE) { if (GetLastError() == ERROR_ALREADY_EXISTS) { QCLOG(L"Directory already exists."); return; } if (GetLastError() == ERROR_PATH_NOT_FOUND) { QCLOG(L"Path not found!"); // TODO: error message? } } } std::wstring Settings::SettingsFile() { return SettingsDir() + std::wstring(L"\\") + DefaultSettings::SettingsFileName; } std::wstring Settings::AppDir() { if (_appDir.empty()) { wchar_t path[MAX_PATH] = { 0 }; if (GetModuleFileName(NULL, path, MAX_PATH)) { PathRemoveFileSpec(path); } _appDir = std::wstring(path); } return _appDir; } std::wstring Settings::SkinDir() { return AppDir() + L"\\" + DefaultSettings::SkinDirName; } std::wstring Settings::MainApp() { return Settings::AppDir() + L"\\" + DefaultSettings::MainAppName; } std::wstring Settings::SettingsApp() { return Settings::AppDir() + L"\\" + DefaultSettings::SettingsAppName; } std::wstring Settings::LanguagesDir() { return AppDir() + L"\\" + DefaultSettings::LanguageDirName; } void Settings::LaunchSettingsApp() { std::wstring app = SettingsApp(); CLOG(L"Opening Settings App: %s", app.c_str()); int exec = (int) ShellExecute( NULL, L"open", app.c_str(), NULL, NULL, SW_SHOWNORMAL); if (exec <= 32) { Error::ErrorMessage(Error::GENERR_NOTFOUND, app); } } void Settings::AudioDeviceID(std::wstring id) { std::string idStr = StringUtils::Narrow(id); return SetText(XML_AUDIODEV, idStr); } std::wstring Settings::AudioDeviceID() { return GetText(XML_AUDIODEV); } int Settings::VolumeCurveAdjustment() { return GetInt(XML_CURVE_ADJUST, 0); } void Settings::VolumeCurveAdjustment(int value) { if (value < 0) { value = 0; } SetElementValue(XML_CURVE_ADJUST, value); } float Settings::VolumeLimiter() { return GetFloat(XML_VOLUME_LIMITER, DefaultSettings::VolumeLimit); } void Settings::VolumeLimiter(float limit) { SetElementValue(XML_VOLUME_LIMITER, limit); } bool Settings::MuteOnLock() { return GetEnabled(XML_MUTELOCK, DefaultSettings::MuteLock); } void Settings::MuteOnLock(bool enable) { SetEnabled(XML_MUTELOCK, enable); } bool Settings::SubscribeVolumeEvents() { return GetEnabled( XML_SUBSCRIBE_VOL, DefaultSettings::SubscribeVolumeEvents); } void Settings::SubscribeVolumeEvents(bool enable) { SetEnabled(XML_SUBSCRIBE_VOL, enable); } std::wstring Settings::LanguageName() { std::wstring lang = GetText(XML_LANGUAGE); if (lang == L"") { return DefaultSettings::Language; } else { return lang; } } void Settings::LanguageName(std::wstring name) { std::string nName = StringUtils::Narrow(name); SetText(XML_LANGUAGE, nName); } bool Settings::AlwaysOnTop() { return GetEnabled(XML_ONTOP, DefaultSettings::OnTop); } void Settings::AlwaysOnTop(bool enable) { SetEnabled(XML_ONTOP, enable); } bool Settings::HideFullscreen() { return GetEnabled(XML_HIDE_WHENFULL, DefaultSettings::HideFullscreen); } void Settings::HideFullscreen(bool enable) { SetEnabled(XML_HIDE_WHENFULL, enable); } bool Settings::HideDirectX() { return GetEnabled(XML_HIDE_DIRECTX, DefaultSettings::HideDirectX); } void Settings::HideDirectX(bool enable) { SetEnabled(XML_HIDE_DIRECTX, enable); } std::wstring Settings::Monitor() { return GetText(XML_MONITOR); } void Settings::Monitor(std::wstring monitorName) { SetText(XML_MONITOR, StringUtils::Narrow(monitorName)); } int Settings::OSDEdgeOffset() { if (HasSetting(XML_OSD_OFFSET)) { return GetInt(XML_OSD_OFFSET); } else { return DefaultSettings::OSDOffset; } } void Settings::OSDEdgeOffset(int offset) { SetElementValue(XML_OSD_OFFSET, offset); } Settings::OSDPos Settings::OSDPosition() { std::wstring pos = GetText(XML_OSD_POS); const wchar_t *posStr = pos.c_str(); for (unsigned int i = 0; i < OSDPosNames.size(); ++i) { if (_wcsicmp(posStr, OSDPosNames[i].c_str()) == 0) { return (Settings::OSDPos) i; } } return DefaultSettings::OSDPosition; } void Settings::OSDPosition(OSDPos pos) { std::wstring posStr = OSDPosNames[(int) pos]; SetText(XML_OSD_POS, StringUtils::Narrow(posStr)); } int Settings::OSDX() { return GetInt(XML_OSD_X); } void Settings::OSDX(int x) { SetElementValue(XML_OSD_X, x); } int Settings::OSDY() { return GetInt(XML_OSD_Y); } void Settings::OSDY(int y) { SetElementValue(XML_OSD_Y, y); } bool Settings::BrightnessOSDEnabled() { return GetEnabled(XML_ENABLE_BOSD, DefaultSettings::BrightnessOSDEnabled); } void Settings::BrightnessOSDEnabled(bool enable) { SetEnabled(XML_ENABLE_BOSD, enable); } bool Settings::EjectOSDEnabled() { return GetEnabled(XML_ENABLE_EOSD, DefaultSettings::EjectOSDEnabled); } void Settings::EjectOSDEnabled(bool enable) { SetEnabled(XML_ENABLE_EOSD, enable); } bool Settings::KeyboardOSDEnabled() { return GetEnabled(XML_ENABLE_KOSD, DefaultSettings::KeyboardOSDEnabled); } void Settings::KeyboardOSDEnabled(bool enable) { SetEnabled(XML_ENABLE_KOSD, enable); } bool Settings::VolumeOSDEnabled() { return GetEnabled(XML_ENABLE_VOSD, DefaultSettings::VolumeOSDEnabled); } void Settings::VolumeOSDEnabled(bool enable) { SetEnabled(XML_ENABLE_VOSD, enable); } AnimationTypes::HideAnimation Settings::HideAnim() { std::wstring anim = GetText(XML_HIDEANIM); const wchar_t *animStr = anim.c_str(); std::vector<std::wstring> *names = &AnimationTypes::HideAnimationNames; for (unsigned int i = 0; i < names->size(); ++i) { if (_wcsicmp(animStr, (*names)[i].c_str()) == 0) { return (AnimationTypes::HideAnimation) i; } } return DefaultSettings::DefaultHideAnim; } void Settings::HideAnim(AnimationTypes::HideAnimation anim) { std::wstring hideStr = AnimationTypes::HideAnimationNames[(int) anim]; SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr)); } int Settings::HideDelay() { return GetInt(XML_HIDETIME, DefaultSettings::HideTime); } void Settings::HideDelay(int delay) { SetElementValue(XML_HIDETIME, delay); } int Settings::HideSpeed() { return GetInt(XML_HIDESPEED, DefaultSettings::HideSpeed); } void Settings::HideSpeed(int speed) { SetElementValue(XML_HIDESPEED, speed); } bool Settings::CurrentSkin(std::wstring skinName) { std::string name = StringUtils::Narrow(skinName); std::wstring xml = SkinXML(skinName); if (PathFileExists(xml.c_str()) == FALSE) { return false; } SetText(XML_SKIN, name); return true; } std::wstring Settings::CurrentSkin() { std::wstring name = GetText("skin"); if (name == L"") { return DefaultSettings::Skin; } else { return name; } } std::wstring Settings::SkinXML() { return SkinXML(CurrentSkin()); } std::wstring Settings::SkinXML(std::wstring skinName) { std::wstring skinXML = Settings::AppDir() + L"\\" + DefaultSettings::SkinDirName + L"\\" + skinName + L"\\" + DefaultSettings::SkinFileName; return skinXML; } std::unordered_map<int, HotkeyInfo> Settings::Hotkeys() { std::unordered_map<int, HotkeyInfo> keyMappings; tinyxml2::XMLElement *hotkeys = _root->FirstChildElement("hotkeys"); if (hotkeys == NULL) { return keyMappings; } tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement("hotkey"); for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) { const char *actionStr = hotkey->Attribute("action"); if (actionStr == NULL) { CLOG(L"No action provided for hotkey; skipping"); continue; } int action = -1; std::wstring wActionStr = StringUtils::Widen(actionStr); for (unsigned int i = 0; i < HotkeyInfo::ActionNames.size(); ++i) { const wchar_t *currentAction = HotkeyInfo::ActionNames[i].c_str(); if (_wcsicmp(wActionStr.c_str(), currentAction) == 0) { action = i; break; } } if (action == -1) { CLOG(L"Hotkey action '%s' not recognized; skipping", wActionStr.c_str()); continue; } int combination = -1; hotkey->QueryIntAttribute("combination", &combination); if (combination == -1) { CLOG(L"No key combination provided for hotkey; skipping"); continue; } HotkeyInfo hki; hki.action = action; hki.keyCombination = combination; /* Does this hotkey action have any arguments? */ tinyxml2::XMLElement *arg = hotkey->FirstChildElement("arg"); for (; arg != NULL; arg = arg->NextSiblingElement()) { const char *argStr = arg->GetText(); hki.args.push_back(StringUtils::Widen(argStr)); } /* Do a validity check on the finished HKI object */ if (hki.Valid() == false) { continue; } /* Whew, we made it! */ CLOG(L"%s", hki.ToString().c_str()); keyMappings[combination] = hki; } return keyMappings; } void Settings::Hotkeys(std::vector<HotkeyInfo> hotkeys) { tinyxml2::XMLElement *hkElem = GetOrCreateElement("hotkeys"); hkElem->DeleteChildren(); for (HotkeyInfo hotkey : hotkeys) { if (hotkey.Valid() == false) { continue; } tinyxml2::XMLElement *hk = _xml.NewElement("hotkey"); hk->SetAttribute("combination", hotkey.keyCombination); std::string actionStr = StringUtils::Narrow( HotkeyInfo::ActionNames[hotkey.action]); hk->SetAttribute("action", actionStr.c_str()); if (hotkey.args.size() > 0) { for (std::wstring arg : hotkey.args) { tinyxml2::XMLElement *argElem = _xml.NewElement("arg"); argElem->SetText(StringUtils::Narrow(arg).c_str()); hk->InsertEndChild(argElem); } } hkElem->InsertEndChild(hk); } } LanguageTranslator *Settings::Translator() { if (_translator == NULL) { std::wstring langDir = Settings::LanguagesDir(); std::wstring lang = Settings::LanguageName(); std::wstring langFile = langDir + L"\\" + lang + L".xml"; if (PathFileExists(langFile.c_str()) == FALSE) { _translator = new LanguageTranslator(); } else { _translator = new LanguageTranslator(langFile); _translator->LoadTranslations(); } } return _translator; } bool Settings::VolumeIconEnabled() { return GetEnabled(XML_VOLUMEICON, DefaultSettings::VolumeIcon); } void Settings::VolumeIconEnabled(bool enable) { SetEnabled(XML_VOLUMEICON, enable); } bool Settings::SoundEffectsEnabled() { return GetEnabled(XML_SOUNDS, DefaultSettings::SoundsEnabled); } void Settings::SoundEffectsEnabled(bool enable) { SetEnabled(XML_SOUNDS, enable); } bool Settings::EjectIconEnabled() { return GetEnabled(XML_EJECTICON, DefaultSettings::EjectIcon); } void Settings::EjectIconEnabled(bool enable) { SetEnabled(XML_EJECTICON, enable); } bool Settings::SubscribeEjectEvents() { return GetEnabled( XML_SUBSCRIBE_EJECT, DefaultSettings::SubscribeEjectEvents); } void Settings::SubscribeEjectEvents(bool enable) { SetEnabled(XML_SUBSCRIBE_EJECT, enable); } bool Settings::HasSetting(std::string elementName) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); return (el != NULL); } bool Settings::GetEnabled(std::string elementName, const bool defaultSetting) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); if (el == NULL) { if (ENABLE_3RVX_LOG) { std::wstring elStr = StringUtils::Widen(elementName); CLOG(L"Warning: XML element '%s' not found", elStr.c_str()); } return defaultSetting; } else { bool val = false; el->QueryBoolText(&val); return val; } } void Settings::SetEnabled(std::string elementName, bool enabled) { tinyxml2::XMLElement *el = GetOrCreateElement(elementName); el->SetText(enabled ? "true" : "false"); } std::wstring Settings::GetText(std::string elementName) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); if (el == NULL) { if (ENABLE_3RVX_LOG) { CLOG(L"Warning: XML element %s not found", StringUtils::Widen(elementName).c_str()); } return L""; } const char* str = el->GetText(); if (str == NULL) { return L""; } else { return StringUtils::Widen(str); } } void Settings::SetText(std::string elementName, std::string text) { tinyxml2::XMLElement *el = GetOrCreateElement(elementName); el->SetText(text.c_str()); } int Settings::GetInt(std::string elementName, const int defaultValue) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); if (el == NULL) { if (ENABLE_3RVX_LOG) { std::wstring elStr = StringUtils::Widen(elementName); CLOG(L"Warning: XML element '%s' not found", elStr.c_str()); } return defaultValue; } int val = defaultValue; el->QueryIntText(&val); return val; } float Settings::GetFloat(std::string elementName, const float defaultValue) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); if (el == NULL) { if (ENABLE_3RVX_LOG) { std::wstring elStr = StringUtils::Widen(elementName); CLOG(L"Warning: XML element '%s' not found", elStr.c_str()); } return defaultValue; } float val = defaultValue; el->QueryFloatText(&val); return val; } tinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) { tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str()); if (el == NULL) { el = _xml.NewElement(elementName.c_str()); _root->InsertEndChild(el); } return el; } bool Settings::AutomaticUpdates() { return GetEnabled(XML_UPDATEAUTO, DefaultSettings::AutoUpdate); } void Settings::AutomaticUpdates(bool enabled) { SetEnabled(XML_UPDATEAUTO, enabled); } void Settings::LastUpdateCheckNow() { LastUpdateCheck(std::time(nullptr)); } void Settings::LastUpdateCheck(long long time) { SetText(XML_UPDATECHECKTIME, std::to_string((long long) time)); } long long Settings::LastUpdateCheck() { tinyxml2::XMLElement *el = _root->FirstChildElement(XML_UPDATECHECKTIME); if (el == NULL) { return 0; } const char *timeStr; timeStr = el->GetText(); if (timeStr == NULL) { return 0; } return std::stoll(timeStr); } std::wstring Settings::IgnoreUpdate() { return GetText(XML_IGNOREUPDATE); } void Settings::IgnoreUpdate(std::wstring versionString) { SetText(XML_IGNOREUPDATE, StringUtils::Narrow(versionString)); } bool Settings::ShowOnStartup() { return GetEnabled(XML_SHOWONSTART, DefaultSettings::ShowOnStartup); } void Settings::ShowOnStartup(bool show) { SetEnabled(XML_SHOWONSTART, show); }
26.637143
79
0.645071
[ "object", "vector" ]
29fb370dbd27fd59595276bd6dcd84f5f43179a5
1,272
hpp
C++
Fizzy/Code/Game/GameStateMachine.hpp
cugone/Fizzy
6311533642d6feec2488011371027b13a8dfd96a
[ "MIT" ]
null
null
null
Fizzy/Code/Game/GameStateMachine.hpp
cugone/Fizzy
6311533642d6feec2488011371027b13a8dfd96a
[ "MIT" ]
null
null
null
Fizzy/Code/Game/GameStateMachine.hpp
cugone/Fizzy
6311533642d6feec2488011371027b13a8dfd96a
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Core/TimeUtils.hpp" #include "Game/IState.hpp" #include "Game/GameStateGravityDrag.hpp" #include "Game/GameStateConstraints.hpp" #include "Game/GameStateSleepManagement.hpp" #include <cstdint> #include <memory> #include <guiddef.h> class GameStateMachine { public: GameStateMachine() = default; GameStateMachine(const GUID& initialState); GameStateMachine(const GameStateMachine& other) = default; GameStateMachine(GameStateMachine&& other) = default; GameStateMachine& operator=(const GameStateMachine& other) = default; GameStateMachine& operator=(GameStateMachine&& other) = default; ~GameStateMachine() = default; void ChangeState(const GUID& newStateId) noexcept; void RestartState() noexcept; void BeginFrame() noexcept; void Update([[maybe_unused]] TimeUtils::FPSeconds deltaSeconds) noexcept; void Render() const noexcept; void EndFrame() noexcept; protected: private: bool HasStateChanged() const noexcept; void OnExitState() noexcept; void OnEnterState(const GUID& enteringStateId) noexcept; std::unique_ptr<IState> CreateStateFromId(const GUID& id) noexcept; GUID _currentStateId{}; GUID _nextStateId{}; std::unique_ptr<IState> _state{}; };
28.266667
77
0.742138
[ "render" ]
29fb3a7b12b08aed34e2a0a69a077d16fd87f820
6,198
hpp
C++
include/engine/guidance/route_step.hpp
jhermsmeier/osrm-backend
7b11cd3a11c939c957eeff71af7feddaa86e7f82
[ "BSD-2-Clause" ]
null
null
null
include/engine/guidance/route_step.hpp
jhermsmeier/osrm-backend
7b11cd3a11c939c957eeff71af7feddaa86e7f82
[ "BSD-2-Clause" ]
null
null
null
include/engine/guidance/route_step.hpp
jhermsmeier/osrm-backend
7b11cd3a11c939c957eeff71af7feddaa86e7f82
[ "BSD-2-Clause" ]
null
null
null
#ifndef ROUTE_STEP_HPP #define ROUTE_STEP_HPP #include "extractor/travel_mode.hpp" #include "engine/guidance/step_maneuver.hpp" #include "util/coordinate.hpp" #include "util/guidance/bearing_class.hpp" #include "util/guidance/entry_class.hpp" #include "extractor/guidance/turn_lane_types.hpp" #include "util/guidance/turn_lanes.hpp" #include <cstddef> #include <string> #include <vector> #include <boost/range/iterator_range.hpp> namespace osrm { namespace engine { namespace guidance { // Given the following turn from a,b to b,c over b: // a --> b --> c // this struct saves the information of the segment b,c. // Notable exceptions are Departure and Arrival steps. // Departure: s --> a --> b. Represents the segment s,a with location being s. // Arrive: a --> b --> t. The segment (b,t) is already covered by the previous segment. // A representation of intermediate intersections struct IntermediateIntersection { static const constexpr std::size_t NO_INDEX = std::numeric_limits<std::size_t>::max(); util::Coordinate location; std::vector<short> bearings; std::vector<bool> entry; std::size_t in; std::size_t out; // turn lane information util::guidance::LaneTuple lanes; extractor::guidance::TurnLaneDescription lane_description; }; inline IntermediateIntersection getInvalidIntersection() { return {util::Coordinate{util::FloatLongitude{0.0}, util::FloatLatitude{0.0}}, {}, {}, IntermediateIntersection::NO_INDEX, IntermediateIntersection::NO_INDEX, util::guidance::LaneTuple(), {}}; } struct RouteStep { unsigned name_id; std::string name; std::string ref; std::string pronunciation; std::string destinations; std::string rotary_name; std::string rotary_pronunciation; double duration; double distance; extractor::TravelMode mode; StepManeuver maneuver; // indices into the locations array stored the LegGeometry std::size_t geometry_begin; std::size_t geometry_end; std::vector<IntermediateIntersection> intersections; // remove all information from the route step, marking it as invalid (used to indicate empty // steps to be removed). void Invalidate(); // Elongate by another step in front RouteStep &AddInFront(const RouteStep &preceeding_step); // Elongate by another step in back RouteStep &ElongateBy(const RouteStep &following_step); /* Elongate without prior knowledge of in front, or in back, convenience function if you * don't know if step is augmented in front or at the back */ RouteStep &MergeWith(const RouteStep &by_step); // copy all strings from origin into the step, apart from rotary names RouteStep &AdaptStepSignage(const RouteStep &origin); LaneID NumLanesToTheRight() const; LaneID NumLanesToTheLeft() const; auto LanesToTheLeft() const; auto LanesToTheRight() const; }; inline void RouteStep::Invalidate() { name_id = EMPTY_NAMEID; name.clear(); ref.clear(); pronunciation.clear(); destinations.clear(); rotary_name.clear(); rotary_pronunciation.clear(); duration = 0; distance = 0; mode = TRAVEL_MODE_INACCESSIBLE; maneuver = getInvalidStepManeuver(); geometry_begin = 0; geometry_end = 0; intersections.clear(); intersections.push_back(getInvalidIntersection()); } // Elongate by another step in front inline RouteStep &RouteStep::AddInFront(const RouteStep &preceeding_step) { BOOST_ASSERT(preceeding_step.geometry_end == geometry_begin + 1); BOOST_ASSERT(mode == preceeding_step.mode); duration += preceeding_step.duration; distance += preceeding_step.distance; geometry_begin = preceeding_step.geometry_begin; intersections.insert(intersections.begin(), preceeding_step.intersections.begin(), preceeding_step.intersections.end()); return *this; } // Elongate by another step in back inline RouteStep &RouteStep::ElongateBy(const RouteStep &following_step) { BOOST_ASSERT(geometry_end == following_step.geometry_begin + 1); BOOST_ASSERT(mode == following_step.mode); duration += following_step.duration; distance += following_step.distance; geometry_end = following_step.geometry_end; intersections.insert(intersections.end(), following_step.intersections.begin(), following_step.intersections.end()); return *this; } // Elongate without prior knowledge of in front, or in back. inline RouteStep &RouteStep::MergeWith(const RouteStep &by_step) { // if our own geometry ends, where the next begins, we elongate by if (geometry_end == by_step.geometry_begin + 1) return AddInFront(by_step); else return ElongateBy(by_step); } // copy all strings from origin into the step, apart from rotary names inline RouteStep &RouteStep::AdaptStepSignage(const RouteStep &origin) { name_id = origin.name_id; name = origin.name; pronunciation = origin.pronunciation; destinations = origin.destinations; ref = origin.ref; return *this; } inline LaneID RouteStep::NumLanesToTheRight() const { return intersections.front().lanes.first_lane_from_the_right; } inline LaneID RouteStep::NumLanesToTheLeft() const { LaneID const total = intersections.front().lane_description.size(); return total - (intersections.front().lanes.lanes_in_turn + intersections.front().lanes.first_lane_from_the_right); } inline auto RouteStep::LanesToTheLeft() const { const auto &description = intersections.front().lane_description; LaneID num_lanes_left = NumLanesToTheLeft(); return boost::make_iterator_range(description.begin(), description.begin() + num_lanes_left); } inline auto RouteStep::LanesToTheRight() const { const auto &description = intersections.front().lane_description; LaneID num_lanes_right = NumLanesToTheRight(); return boost::make_iterator_range(description.end() - num_lanes_right, description.end()); } } // namespace guidance } // namespace engine } // namespace osrm #endif
30.087379
97
0.711681
[ "geometry", "vector" ]
29fe7e52e2b1b7df9016e1c07c2deb95e78b4d30
6,046
cpp
C++
src/MeanscriptCmd/MeanscriptCmd.cpp
Meanwhale/MeanscriptCLI
aa1adf2925170fa467e4fd7c2d79b7cf1b0934b2
[ "MIT" ]
2
2020-10-10T22:13:42.000Z
2021-08-04T07:27:29.000Z
src/MeanscriptCmd/MeanscriptCmd.cpp
Meanwhale/MeanscriptCLI
aa1adf2925170fa467e4fd7c2d79b7cf1b0934b2
[ "MIT" ]
null
null
null
src/MeanscriptCmd/MeanscriptCmd.cpp
Meanwhale/MeanscriptCLI
aa1adf2925170fa467e4fd7c2d79b7cf1b0934b2
[ "MIT" ]
1
2020-10-11T19:21:43.000Z
2020-10-11T19:21:43.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> //#include "MeanscriptCmd.h" #include "MS.h" #include "NativeTest.h" // memory debug #include <stdlib.h> #ifdef MS_VS_MEM_DEBUG #include <crtdbg.h> #endif using namespace std; using namespace meanscript; void printVersion() { MSPRINT("Meanscript CLI, ").print(MS_BUILD_INFO).endLine(); } void printCommandHelp(const char * cmd, const char * args, const char * description) { MSPRINT(" ").print(cmd).print(" ").print(args).print("\n ").print(description).endLine(); } void printHelp() { printVersion(); MSPRINT("Command line interface\n"); MSPRINT("USAGE:\n mean [command] [options] <file(s)>\n"); MSPRINT("OPTIONS:\n"); MSPRINT(" -v, --verbose Print command details.\n"); MSPRINT("COMMANDS:\n"); MSPRINT(" compile <script> <output> Compile a script and write bytecode to a file.\n"); MSPRINT(" cr <script> <output> Same as 'compile' but also run they bytecode.\n"); MSPRINT(" run <bytecode> Read and run a bytecode.\n"); MSPRINT(" decode <bytecode> Read bytecode and print its content.\n"); MSPRINT(" view <bytecode> Run code and view values.\n"); MSPRINT(" makejava <script> <module> <package> Generate Java classes.\n"); MSPRINT(" test Run unit tests.\n"); MSPRINT(" help Print help.\n"); MSPRINT(" version Print version.\n"); MSPRINT("\nEXAMPLES:\n"); MSPRINT("Print version: mean version\n"); MSPRINT("View contents of foo.mb: mean view foo.mb\n"); MSPRINT("Compile a file with verbose on: mean --verbose compile bar.ms foo.mb\n"); } enum CommandType { CMD_UNKNOWN, CMD_COMPILE_AND_RUN, CMD_COMPILE, CMD_RUN, CMD_DECODE, CMD_VIEW, CMD_MAKE_JAVA, CMD_TEST, CMD_HELP, CMD_VERSION }; int execute(int argc, char* argv[]) { //int32_t ints[3]; //ints[0] = 0x00000005; //ints[1] = 0x64636261; //ints[2] = 0x00000065; //std::cout << ((const char*)(ints+1)) << std::endl; if (argc == 1) { printHelp(); return 1; } string source; string destination; CommandType commandType = CMD_UNKNOWN; int i = 1; string arg(argv[i++]); // read subcommand if (arg == "cr") commandType = CMD_COMPILE_AND_RUN; else if (arg == "compile") commandType = CMD_COMPILE; else if (arg == "run") commandType = CMD_RUN; else if (arg == "decode") commandType = CMD_DECODE; else if (arg == "view") commandType = CMD_VIEW; else if (arg == "makejava") commandType = CMD_MAKE_JAVA; else if (arg == "test") commandType = CMD_TEST; else if (arg == "help") commandType = CMD_HELP; else if (arg == "version") commandType = CMD_VERSION; else { MSPRINT("invalid subcommand: ").print(arg).endLine(); printHelp(); return -1; } // read options for (; i < argc; ++i) { string arg(argv[i]); // check if arg starts with -- or - if (arg.rfind("--", 0) == 0) { if (arg == "--verbose") { MSPRINT("Set verbose on.").endLine(); setVerbose(true); } else { MSPRINT("Unknown argument: ").print(arg); return -1; } } else if (arg.rfind("-", 0) == 0) { if (arg.size() == 1) ERROR("flag arguments expected after a '-'"); for(size_t n=1; n<arg.size(); n++) { if (arg[n] == 'v') { setVerbose(true); } else { MSPRINT("Unknown flag: ").print((arg[n])); return -1; } } } else break; } switch (commandType) { case CMD_COMPILE_AND_RUN: case CMD_COMPILE: { if (argc != i + 2) { MSPRINT("compile: input and output files expected"); return -1; } MSFileInStream fis = getInput(argv[i]); MSCode m(fis, globalConfig.STREAM_SCRIPT); fis.close(); MSFileOutStream fos = getOutput(argv[i+1]); m.writeCode(fos); fos.close(); if (commandType == CMD_COMPILE_AND_RUN) { MSPRINT("run bytecode...\n\n"); m.run(); } } break; case CMD_RUN: { if (argc != i + 1) ERROR("bytecode file for input expected"); MSFileInStream fis = getInput(argv[i]); MSCode m(fis, globalConfig.STREAM_BYTECODE); m.run(); } break; case CMD_DECODE: { if (argc != i + 1) ERROR("bytecode file for input expected"); MSFileInStream fis = getInput(argv[i]); MSCode m(fis, globalConfig.STREAM_BYTECODE); m.printCode(); } break; case CMD_VIEW: { if (argc != i + 1) ERROR("bytecode file for input expected"); MSFileInStream fis = getInput(argv[i]); MSCode m(fis, globalConfig.STREAM_BYTECODE); m.run(); m.printData(); } break; case CMD_MAKE_JAVA: { // makejava <script> <module> <package> <target folder> Generate Java classes. if (argc != i + 3) { MSPRINT("makejava: wrong number of arguments\n"); return -1; } string script = argv[i]; string module = argv[i + 1]; string package = argv[i + 2]; MSPRINT("make Java classes!") .print("\nscript: ").print(script) .print("\nmodule: ").print(module) .print("\npackage: ").print(package).endLine(); MSFileInStream fis = getInput(script.c_str(), true); MSCode m(fis, globalConfig.STREAM_SCRIPT); fis.close(); m.run(); string outputDir = std::getenv("MS_OUTPUT"); outputDir += meanscript::filePathSeparator(); meanscriptcore::ClassMaker cm; cm.makeJava(m.getMM()->byteCode->code, package, module, outputDir); } break; case CMD_TEST: printVersion(); MSPRINT("Run unit tests...\n"); meanscriptcore::MeanscriptUnitTest::runAll(); MSPRINT("\nTESTS DONE!\n"); return 1; break; case CMD_HELP: printHelp(); return 1; break; case CMD_VERSION: printVersion(); return 1; default: MSPRINT("unknown command type: ").print(commandType).endLine(); return -1; } return 1; } int main(int argc, char* argv[]) { #ifdef MS_VS_MEM_DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif setVerbose(false); int a = execute(argc, argv); return a; }
21.748201
96
0.615117
[ "vector" ]
4b000ab83802a77eb55b7f038b9305d6f0af3e15
6,751
cpp
C++
src/ngraph/runtime/gpu/gpu_compiled_function.cpp
gf712/ngraph
3d9004c0ec4b4813f4c22859bb6fe859f426fc85
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/gpu/gpu_compiled_function.cpp
gf712/ngraph
3d9004c0ec4b4813f4c22859bb6fe859f426fc85
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/gpu/gpu_compiled_function.cpp
gf712/ngraph
3d9004c0ec4b4813f4c22859bb6fe859f426fc85
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2020 Intel 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 <algorithm> #include <cstdlib> #include <cublas_v2.h> #include <cuda.h> #include <cuda_runtime.h> #include <cudnn.h> #include <fstream> #include <locale> #include <mutex> #include <string> #include <tuple> #include "ngraph/descriptor/input.hpp" #include "ngraph/descriptor/layout/dense_tensor_layout.hpp" #include "ngraph/descriptor/output.hpp" #include "ngraph/file_util.hpp" #include "ngraph/function.hpp" #include "ngraph/node.hpp" #include "ngraph/pass/algebraic_simplification.hpp" #include "ngraph/pass/fused_op_decomposition.hpp" #include "ngraph/pass/get_output_element_elimination.hpp" #include "ngraph/pass/implicit_broadcast_elimination.hpp" #include "ngraph/pass/like_replacement.hpp" #include "ngraph/runtime/gpu/gpu_backend.hpp" #include "ngraph/runtime/gpu/gpu_compiled_function.hpp" #include "ngraph/runtime/gpu/gpu_external_function.hpp" #include "ngraph/runtime/gpu/gpu_internal_function.hpp" #include "ngraph/runtime/gpu/op/batch_norm.hpp" #include "ngraph/runtime/gpu/op/rnn.hpp" #include "ngraph/runtime/gpu/pass/gpu_batch_norm_cache.hpp" #include "ngraph/runtime/gpu/pass/gpu_layout.hpp" #include "ngraph/runtime/gpu/pass/gpu_rnn_fusion.hpp" #include "ngraph/runtime/gpu/pass/tensor_memory_reservation.hpp" using namespace std; using namespace ngraph; std::string runtime::gpu::GPUCompiledFunction::get_output_dir() { static std::string output_dir = "gpu_codegen"; return output_dir; } size_t runtime::gpu::GPUCompiledFunction::get_memory_alignment() { static size_t memory_pool_alignment = 64; return memory_pool_alignment; } static std::mutex s_compilation; class GPUStaticInitializers { public: GPUStaticInitializers() { file_util::remove_directory(runtime::gpu::GPUCompiledFunction::get_output_dir()); file_util::make_directory(runtime::gpu::GPUCompiledFunction::get_output_dir()); } }; static GPUStaticInitializers s_static_initializers; runtime::gpu::GPUCompiledFunction::GPUCompiledFunction( const shared_ptr<ngraph::Function>& function, const std::shared_ptr<GPU_Backend::BackendContext>& shared_context) : m_runtime(nullptr) , m_function(function) , m_emit_timing(false) , m_is_compiled(false) , m_shared_context(shared_context) { } runtime::gpu::GPUCompiledFunction::~GPUCompiledFunction() { } std::vector<std::string> get_case_variants(std::vector<std::string> cases) { std::vector<std::string> results; for (auto& c : cases) { results.push_back(c); if (std::all_of(c.begin(), c.end(), ::isdigit)) { continue; } for (auto i = 0u; i < c.size(); i++) { c[i] = std::toupper(c[i], std::locale()); if (i == 0) { results.emplace_back(c); } } results.emplace_back(c); } return results; } std::shared_ptr<runtime::gpu::GPUCompiledFunction> runtime::gpu::GPUCompiledFunction::make( const std::shared_ptr<ngraph::Function>& function, const std::shared_ptr<GPU_Backend::BackendContext>& shared_context) { #if defined(NGRAPH_DEX_ONLY) return std::make_shared<runtime::gpu::GPUInternalFunction>(function, shared_context); #else // For now codegen is default unless explicitly disabled bool use_codegen = true; if (auto env = std::getenv("NGRAPH_CODEGEN")) { std::string env_codegen(env); for (auto& opt : get_case_variants({"0", "false"})) { if (env_codegen == opt) { use_codegen = false; } } } if (use_codegen) { return std::make_shared<runtime::gpu::GPUExternalFunction>(function, shared_context); } else { return std::make_shared<runtime::gpu::GPUInternalFunction>(function, shared_context); } #endif } void runtime::gpu::GPUCompiledFunction::compile() { if (m_is_compiled) { return; } std::unique_lock<std::mutex> lock(s_compilation); m_function_name = m_function->get_name(); auto allocator = std::make_shared<runtime::gpu::GPUAllocator>( m_shared_context->m_primitive_emitter->get_memory_allocator()); ngraph::pass::Manager pass_manager; #if CUDNN_VERSION >= 7200 // recurrent network fusion pass_manager.register_pass<runtime::gpu::pass::LSTMFusion>(); pass_manager.register_pass<runtime::gpu::pass::RNNFusion>(); pass_manager.register_pass<ngraph::pass::AlgebraicSimplification>(); pass_manager.register_pass<runtime::gpu::pass::MultiLayerRNNFusion>(); #else pass_manager.register_pass<ngraph::pass::AlgebraicSimplification>(); #endif pass_manager.register_pass<runtime::gpu::pass::BatchNormCache>(); pass_manager.register_pass<ngraph::pass::LikeReplacement>(); pass_manager.register_pass<ngraph::pass::FusedOpDecomposition>(); pass_manager.register_pass<ngraph::pass::ImplicitBroadcastElimination>(); pass_manager.register_pass<runtime::gpu::pass::GPULayout>(this); pass_manager.register_pass<ngraph::pass::AssignLayout<descriptor::layout::DenseTensorLayout>>(); pass_manager.register_pass<ngraph::pass::GetOutputElementElimination>(); pass_manager.register_pass<ngraph::pass::Liveness>(); pass_manager.register_pass<ngraph::pass::MemoryLayout>(get_memory_alignment()); pass_manager.register_pass<runtime::gpu::pass::TensorMemoryReservation>( *allocator, m_tensor_memory_buffers); string dump_filename = file_util::path_join(get_output_dir(), m_function_name + "_ops.txt"); pass_manager.register_pass<ngraph::pass::DumpSorted>(dump_filename); pass_manager.run_passes(m_function); m_function_ordered_ops.emplace(m_function, m_function->get_ordered_ops()); add_passes(pass_manager); emit(); // allocate device buffers for primitive arguments and workspace allocator->close(); m_shared_context->m_primitive_emitter->allocate_primitive_memory(); compile_function(); m_is_compiled = true; }
33.924623
100
0.702414
[ "vector" ]
4b05f87d4c7788afd8e8367860e956d58529c6b6
1,734
cpp
C++
CppComponentSystem/Core/Mesh.cpp
chunkyguy/CppComponentSystem
d3d8c15ab917b97171c4209f97475799eed8336a
[ "MIT" ]
null
null
null
CppComponentSystem/Core/Mesh.cpp
chunkyguy/CppComponentSystem
d3d8c15ab917b97171c4209f97475799eed8336a
[ "MIT" ]
null
null
null
CppComponentSystem/Core/Mesh.cpp
chunkyguy/CppComponentSystem
d3d8c15ab917b97171c4209f97475799eed8336a
[ "MIT" ]
1
2020-04-14T02:31:11.000Z
2020-04-14T02:31:11.000Z
// // HS_Mesh.cpp // HitSoccer // // Created by Sid on 16/07/14. // Copyright (c) 2014 whackylabs. All rights reserved. // #include "Mesh.h" #include <OpenGLES/ES2/glext.h> #pragma mark - MeshMemory - MeshMemory::MeshMemory() : vao_(0), vbo_(0) { } bool MeshMemory::Load() { glGenVertexArraysOES(1, &vao_); glGenBuffers(1, &vbo_); return true; } MeshMemory::~MeshMemory() { if (vbo_) { glDeleteBuffers(1, &vbo_); vbo_ = 0; } if (vao_) { glDeleteVertexArraysOES(1, &vao_); vao_ = 0; } } void MeshMemory::Allocate(const GLsizeiptr size, const GLfloat *data, std::function<void()> format) { glBindVertexArrayOES(vao_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); format(); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArrayOES(0); } void MeshMemory::Enable() const { glBindVertexArrayOES(vao_); } #pragma mark - Mesh - Mesh::Mesh( const GLint drawIndex, const GLsizei vertexCount, const GLKVector4 &color ) : drawIndex_(drawIndex), vertexCount_(vertexCount), color_(color) {} void Mesh::Draw() const { glDrawArrays(GL_TRIANGLE_STRIP, drawIndex_, vertexCount_); } #pragma mark - MeshData - MeshData MeshDataWithSize(const GLKVector2 &size) { MeshData meshData; meshData.vertex[0].position = GLKVector2Make(-size.x/2.0, size.y/2.0); meshData.vertex[1].position = GLKVector2Make(-size.x/2.0, -size.y/2.0); meshData.vertex[2].position = GLKVector2Make(size.x/2.0, size.y/2.0); meshData.vertex[3].position = GLKVector2Make(size.x/2.0, -size.y/2.0); return meshData; }
21.407407
75
0.641292
[ "mesh" ]
4b063dbdc3440b58c9928e6a8f43035e27d0e57c
1,967
cc
C++
src/STL.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
src/STL.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
src/STL.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
#include "STL.hpp" STLWriter::STLWriter() : name("Default") {} void STLWriter::setName(const string& name) { this->name = name; } void STLWriter::pushTriangle(Vec3 v0, Vec3 v1, Vec3 v2, Vec3 normal) { struct STLTriangle triangle; triangle.normal[0] = normal.x; triangle.normal[1] = normal.y; triangle.normal[2] = normal.z; triangle.v0[0] = v0.x; triangle.v0[1] = v0.y; triangle.v0[2] = v0.z; triangle.v1[0] = v1.x; triangle.v1[1] = v1.y; triangle.v1[2] = v1.z; triangle.v2[0] = v2.x; triangle.v2[1] = v2.y; triangle.v2[2] = v2.z; triangle.attrib = 0; triangles.push_back(triangle); } unsigned STLWriter::getTriangleCount() { return triangles.size(); } void STLWriter::write(const string& filename, bool ascii) { FILE* fp = fopen(filename.c_str(), "wb"); if(!fp) return; if(ascii) { fprintf(fp, "solid %s\n", name.c_str()); for(auto &tri : triangles) { fprintf(fp, "facet normal %f %f %f\n", tri.normal[0], tri.normal[1], tri.normal[2]); fprintf(fp, "outer loop\n"); fprintf(fp, "vertex %f %f %f\n", tri.v0[0], tri.v0[1], tri.v0[2]); fprintf(fp, "vertex %f %f %f\n", tri.v1[0], tri.v1[1], tri.v1[2]); fprintf(fp, "vertex %f %f %f\n", tri.v2[0], tri.v2[1], tri.v2[2]); fprintf(fp, "endloop\n"); fprintf(fp, "endfacet\n"); } fprintf(fp, "endsolid %s\n", name.c_str()); } else { // Write header const char* data = name.c_str(); size_t sz = sizeof(data); struct BinarySTL info; std::memset(info.header, 0, sizeof(char) * 80); std::memcpy(info.header, data, sz); info.triangle_count = triangles.size(); fwrite(&info, sizeof(BinarySTL), 1, fp); // Write triangles for(auto &tri : triangles) { fwrite(&tri, sizeof(STLTriangle), 1, fp); } } fclose(fp); }
28.1
96
0.55516
[ "solid" ]
4b070683279258e0ceb4143e0df8f04a9c259d52
49,903
cpp
C++
Providers/PythonProvider.cpp
chsamala2/PowerShell-DSC-for-Linux
5cac971f1877dd545c71be50b0ffd29199ac1acc
[ "MIT" ]
110
2019-05-06T21:17:02.000Z
2022-03-27T12:57:57.000Z
Providers/PythonProvider.cpp
chsamala2/PowerShell-DSC-for-Linux
5cac971f1877dd545c71be50b0ffd29199ac1acc
[ "MIT" ]
82
2019-05-09T00:41:23.000Z
2022-03-22T07:35:26.000Z
Providers/PythonProvider.cpp
chsamala2/PowerShell-DSC-for-Linux
5cac971f1877dd545c71be50b0ffd29199ac1acc
[ "MIT" ]
65
2019-05-21T21:37:26.000Z
2022-03-19T01:25:38.000Z
/* PowerShell Desired State Configuration for Linux Copyright (c) Microsoft Corporation All rights reserved. MIT License 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 "PythonProvider.hpp" #include "debug_tags.hpp" #include <algorithm> #include <cstdlib> #include <cstring> #include <vector> #include <errno.h> #include <fcntl.h> #include <functional> #include <iomanip> #include <iostream> #include <sstream> #include <sys/socket.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <string.h> //#include <array> #include <cstring> namespace { typedef util::unique_ptr<char[]> char_array; char const OMI_PYTHON_VERSION_STR[] = "OMI_PYTHON_VERSION"; char const DEFAULT_PYTHON_VERSION[] = "python"; char const DEFAULT_OMI_PATH[] = "/opt/omi/"; char const SCRIPT_PATH_EXTENSION[] = "/lib/Scripts/"; char const DEFAULT_DSC_SCRIPT[] = "client"; char const PY_EXTENSION[] = ".py"; char const PYTHON3_COMMAND[] = "python3"; std::string determinePythonVersion(){ int buffer_length = 128; char buffer[buffer_length]; char* result = (char*)malloc(1); *result = 0; // Check for python2 FILE* pipe = popen("python2 --version 2>&1", "r"); if(!pipe) { std::cout << "Couldn't start command." << std::endl; } while(fgets(buffer, 128, pipe) != NULL) { result = (char*)realloc(result, (result ? strlen(result) : 0) + buffer_length ); strcat(result,buffer); } // If python2 --version does not contain 'not found' return python2 if(strstr(result, "not found") == NULL) { std::cout << "Found python2." << std::endl; return "python2"; } // Look for python3 result = (char*)malloc(1); *result = 0; pipe = popen("python3 --version 2>&1", "r"); if(!pipe) { std::cout << "Couldn't start command." << std::endl; } while(fgets(buffer, 128, pipe) != NULL) { result = (char*)realloc(result, (result ? strlen(result) : 0) + buffer_length ); strcat(result,buffer); } // If python3 --version does not contain 'not found' return python3 if(strstr(result, "not found") == NULL) { std::cout << "Found python3." << std::endl; return "python3"; } return "python"; } char_array::move_type get_python_version () { char_array pyV; std::cout << "In PythonProvider." << std::endl; std::string version = determinePythonVersion(); pyV.reset (strcpy (new char[1 + version.length()], version.c_str())); return pyV.move(); } char_array::move_type get_script_path () { size_t len = strlen(DSC_SCRIPT_PATH) + 1; char_array fullPath (strcpy (new char[len], DSC_SCRIPT_PATH)); char const* fileName = DEFAULT_DSC_SCRIPT; len += strlen ("/"); len += strlen (fileName); len += strlen (PY_EXTENSION); fullPath.reset (strcpy (new char[len], fullPath.get ())); strcat (fullPath.get (), "/"); if(strcmp( determinePythonVersion().c_str(), PYTHON3_COMMAND) == 0) { len += strlen (PYTHON3_COMMAND) + strlen ("/"); fullPath.reset (strcpy (new char[len], fullPath.get ())); strcat(fullPath.get (), PYTHON3_COMMAND); strcat(fullPath.get (), "/"); } strcat (fullPath.get (), fileName); strcat (fullPath.get (), PY_EXTENSION); std::cout << "Script path: "<< std::endl; std::cout << fullPath.get() << std::endl; return fullPath.move (); } class PropertyFinder { public: /*ctor*/ PropertyFinder (std::string const& name) : m_Name (name) { // empty } bool operator () (MI_PropertyDecl const* const pProperty) const { return pProperty->name ? m_Name == pProperty->name : false; } private: std::string const m_Name; }; struct MI_Deleter { void operator () ( MI_Instance*& pInstance) { if (0 != pInstance) { MI_Instance_Delete (pInstance); pInstance = 0; } } }; typedef util::unique_ptr<MI_Instance, MI_Deleter> MI_InstancePtr; int allocate_MI_Instance ( MI_Context* pContext, MI_Instance* const pInstance, std::string const name, MI_InstancePtr* ppInstanceOut) { //SCX_BOOKEND ("allocate_MI_Instance"); int rval = EXIT_FAILURE; // find the property by name MI_PropertyDecl const* const* const ppBegin = pInstance->classDecl->properties; MI_PropertyDecl const* const* const ppEnd = ppBegin + pInstance->classDecl->numProperties; MI_PropertyDecl const* const* const ppProperty = std::find_if (ppBegin, ppEnd, PropertyFinder (name)); if (name.compare("__Inventory") == 0) { MI_Instance* pNewInstance = 0; if (MI_RESULT_OK == MI_NewDynamicInstance ( pContext, pInstance->classDecl->name, NULL, &pNewInstance)) { ppInstanceOut->reset (pNewInstance); rval = EXIT_SUCCESS; } else { std::ostringstream strm; strm << __FILE__ << '[' << __LINE__ << ']' << "MI_NewDynamicInstance failed"; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; } return rval; } if (ppEnd != ppProperty) { MI_Instance* pNewInstance = 0; if (MI_RESULT_OK == MI_NewDynamicInstance ( pContext, (*ppProperty)->className, (*ppProperty)->flags, &pNewInstance)) { ppInstanceOut->reset (pNewInstance); rval = EXIT_SUCCESS; } else { std::ostringstream strm; strm << __FILE__ << '[' << __LINE__ << ']' << "MI_NewDynamicInstance failed"; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; } } else { std::ostringstream strm; strm << __FILE__ << '[' << __LINE__ << ']' << "encountered a member: " << name << " that is not in the ClassDecl."; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; } return rval; } } namespace scx { /*static*/ unsigned char const PythonProvider::MI_NULL_FLAG = 64; /*static*/ MI_Boolean PythonProvider::CHILD_SIGNAL_REGISTERED = MI_FALSE; template<typename T> /*static*/ int PythonProvider::TypeHelper<T>::recv ( PythonProvider* const pProvider, T* const pValueOut) { //SCX_BOOKEND ("TypeHelper::recv"); T temp; int rval = pProvider->recv (&temp); if (EXIT_SUCCESS == rval) { *pValueOut = temp; } return rval; } template<typename T> template<typename Array_t> /*static*/ int PythonProvider::TypeHelper<T>::recv_array ( PythonProvider* const pProvider, Array_t* const pValueOut, util::unique_ptr<char[]>* const pStorage) { //SCX_BOOKEND ("TypeHelper::recv_array"); int length; int rval = pProvider->recv (&length); if (EXIT_SUCCESS == rval) { pStorage->reset (new char[length * sizeof (T)]); T* const pArray = reinterpret_cast<T* const> (pStorage->get ()); for (int i = 0; EXIT_SUCCESS == rval && length > i; ++i) { rval = pProvider->recv (pArray + i); } if (EXIT_SUCCESS == rval) { pValueOut->data = pArray; pValueOut->size = static_cast<MI_Uint32> (length); } } return rval; } /*dtor*/ PythonProvider::~PythonProvider () { #if (PRINT_BOOKENDS) std::ostringstream strm; strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::dtor", strm.str ()); #endif if (INVALID_SOCKET != m_FD) { close (m_FD); } if( m_pid > 0 ) { waitpid(m_pid, NULL, 0); } for(size_t xCount = 0 ; xCount < m_PreviousPid.size(); xCount++) { waitpid(m_PreviousPid[xCount] , NULL, WNOHANG); } m_PreviousPid.clear(); } int PythonProvider::init () { int rval = EXIT_SUCCESS; #if (PRINT_BOOKENDS) std::ostringstream strm; strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::init", strm.str ()); #endif if (INVALID_SOCKET == m_FD) { rval = forkExec (); } return rval; } MI_Result PythonProvider::test ( MI_Instance const& instance, MI_Boolean* const pTestResultOut) { #if PRINT_BOOKENDS std::ostringstream strm; strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::test", strm.str ()); #endif MI_Result rval = MI_RESULT_FAILED; int result = sendRequest (TEST, instance); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("send succeeded"); result = recvResult (pTestResultOut); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("recv succeeded"); rval = MI_RESULT_OK; } else { SCX_BOOKEND_PRINT ("recv failed"); } } else { SCX_BOOKEND_PRINT ("send failed"); } return rval; } MI_Result PythonProvider::set ( MI_Instance const& instance, MI_Result* const pSetResultOut) { #if PRINT_BOOKENDS std::ostringstream strm; strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::set", strm.str ()); #endif MI_Result rval = MI_RESULT_FAILED; int result = sendRequest (SET, instance); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("send succeeded"); MI_Boolean boolResult = MI_FALSE; result = recvResult (&boolResult); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("recv succeeded"); rval = MI_RESULT_OK; *pSetResultOut = boolResult ? MI_RESULT_OK : MI_RESULT_FAILED; } else { SCX_BOOKEND_PRINT ("recv failed"); } } else { SCX_BOOKEND_PRINT ("send failed"); } return rval; } MI_Result PythonProvider::get ( MI_Instance const& instance, MI_Context* const pContext, MI_Instance* const pInstanceOut) { std::ostringstream strm; #if PRINT_BOOKENDS strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::get", strm.str ()); strm.str (""); strm.clear (); #endif // 1: send the request // 2: read (int) RESULT // A: RESULT is affirmative (0) // i: read (int) ARG_COUNT // ii: read ARG // iii: read ARG_TYPE // iv: read ARG_VALUE // v: add ARG to new instance // iv: goto ii // B: RESULT is negative (non-0) // i: read (string) error msg // ii: output error msg MI_Result rval = MI_RESULT_FAILED; int getResult = -1; int result = sendRequest (GET, instance); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("send succeeded"); result = recv (&getResult); if (EXIT_SUCCESS == result) { if (0 == getResult) { SCX_BOOKEND_PRINT ("recv'd POSITIVE"); result = recv (pContext, pInstanceOut); rval = EXIT_SUCCESS == result ? MI_RESULT_OK : MI_RESULT_FAILED; } else { SCX_BOOKEND_PRINT ("recv'd NEGATIVE"); std::string errorMsg; result = recv (&errorMsg); if (EXIT_SUCCESS == result) { if (0 != errorMsg.length ()) { strm << ": error msg: \"" << errorMsg << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); } else { SCX_BOOKEND_PRINT ("no error msg"); } } else { SCX_BOOKEND_PRINT ("failed to receive error msg"); } } } } else { SCX_BOOKEND_PRINT ("send failed"); } return rval; } MI_Result PythonProvider::inventory ( MI_Instance const& instance, MI_Context* const pContext, MI_Instance* const pInstanceOut) { std::ostringstream strm; #if PRINT_BOOKENDS strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::inventory", strm.str ()); strm.str (""); strm.clear (); #endif // 1: send the request // 2: read (int) RESULT // A: RESULT is affirmative (0) // i: read (int) ARG_COUNT // ii: read ARG // iii: read ARG_TYPE // iv: read ARG_VALUE // v: add ARG to new instance // iv: goto ii // B: RESULT is negative (non-0) // i: read (string) error msg // ii: output error msg MI_Result rval = MI_RESULT_FAILED; int inventoryResult = -1; int result = sendRequest (INVENTORY, instance); if (EXIT_SUCCESS == result) { SCX_BOOKEND_PRINT ("send succeeded"); result = recv (&inventoryResult); if (EXIT_SUCCESS == result) { if (0 == inventoryResult) { SCX_BOOKEND_PRINT ("recv'd POSITIVE"); result = recv (pContext, pInstanceOut); rval = EXIT_SUCCESS == result ? MI_RESULT_OK : MI_RESULT_FAILED; } else { SCX_BOOKEND_PRINT ("recv'd NEGATIVE"); std::string errorMsg; result = recv (&errorMsg); if (EXIT_SUCCESS == result) { if (0 != errorMsg.length ()) { strm << ": error msg: \"" << errorMsg << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); } else { SCX_BOOKEND_PRINT ("no error msg"); } } else { SCX_BOOKEND_PRINT ("failed to receive error msg"); } } } } else { SCX_BOOKEND_PRINT ("send failed"); } return rval; } int PythonProvider::forkExec () { int rval = EXIT_SUCCESS; std::ostringstream strm; #if (PRINT_BOOKENDS) strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::forkExec", strm.str ()); strm.str (""); strm.clear (); #endif if (INVALID_SOCKET == m_FD) { int sockets[2]; int pid; int result = socketpair (AF_UNIX, SOCK_STREAM, 0, sockets); if (-1 != result) { // socketpair succeeded SCX_BOOKEND_PRINT ("socketpair - succeeded"); pid = fork (); if (0 == pid) { // fork succeded, this is the child process SCX_BOOKEND_PRINT ("fork - succeeded: this is the child"); // close the parent socket close (sockets[1]); // create the argument list including the child socket name as a // command line arg size_t const SOCK_ID_BUF_LEN = 32; char socketID[SOCK_ID_BUF_LEN]; snprintf (socketID, SOCK_ID_BUF_LEN, "%d", sockets[0]); char_array pyV (get_python_version ()); char_array fullName (get_script_path ()); SCX_BOOKEND_PRINT (fullName); char* args[] = { pyV.get (), fullName.get (), socketID, 0 }; SCX_BOOKEND_PRINT ("In PythonProvider, using:"); SCX_BOOKEND_PRINT (args[0]); // exec execvp (args[0], args); SCX_BOOKEND_PRINT ("execvp - failed"); // if we got here, exec failed! // check errno { EACCES, ENOEXEC } strm << "PythonProvider::forkExec - exec failed: " << errno << ": \"" << errnoText << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); rval = EXIT_FAILURE; } else if (-1 != pid) { m_pid=pid; // fork succeeded, this is the parent process SCX_BOOKEND_PRINT ("fork - succeeded: this is the parent"); close (sockets[0]); m_FD = sockets[1]; rval = EXIT_SUCCESS; } else { // fork failed // error (check errno { EAGAIN, ENOMEM }) strm << "PythonProvider::forkExec - fork failed: " << errno << ": \"" << errnoText << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); rval = EXIT_FAILURE; } } else { // socketpair failed // error (check errno { EAFNOSUPPORT, EMFILE, EOPNOTSUPP, // EPROTONOSUPPORT, EPROTOTYPE, EACCES, ENOBUFS, ENOMEM }) strm << "PythonProvider::forkExec - socketpair_failed: " << errno << ": \"" << errnoText << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); rval = EXIT_FAILURE; } } else { SCX_BOOKEND_PRINT ("already initialized"); } return rval; } int PythonProvider::verifySocketState () { //SCX_BOOKEND ("PythonProvider::verifySocketState"); int result = EXIT_SUCCESS; // test for socket // if there is a socket... // test that the socket has no readable data // if there is data... // close the socket // if there is no socket.. // attempt to open a socket if (INVALID_SOCKET != m_FD) { // there should be no data on the socket // set the file to non-blocking and attempt to read // if there is data to read, the socket stream is in a bad state int flags = fcntl (m_FD, F_GETFL, 0); char buf[4]; if (-1 == flags || -1 == fcntl (m_FD, F_SETFL, flags | O_NONBLOCK) || -1 != read (m_FD, buf, 1) || EAGAIN != errno || -1 == fcntl (m_FD, F_SETFL, flags)) { // reset the socket handleSocketClosed (); } } if (INVALID_SOCKET == m_FD) { //Release previous disconnected child process if any if( m_pid > 0 ) { // It is possible that disconnected process is still running, in that case // try to do cleanup when the provider is unloaded. if( waitpid(m_pid , NULL, WNOHANG) == 0 ) { //If process isn't done, cleanup will be done when the provider is unloaded m_PreviousPid.push_back(m_pid); } m_pid = -2; } result = init (); } return result; } void PythonProvider::handleSocketClosed () { close (m_FD); m_FD = INVALID_SOCKET; } int PythonProvider::send ( char const* const str) { //SCX_BOOKEND ("PythonProvider::send (str)"); ssize_t const nStrLen = (0 == str) ? 0 : strlen (str); int rval = send (static_cast<int>(nStrLen)); ssize_t nCharsSent = 0; while (EXIT_SUCCESS == rval && nStrLen > nCharsSent) { ssize_t nSent = write (m_FD, str + nCharsSent, nStrLen - nCharsSent); if (-1 != nSent) { nCharsSent += nSent; } else if (EINTR != errno) { // error (check errno { EACCESS, EAGAIN, EWOULDBLOCK, EBADF, // ECONNRESET, EDESTADDRREQ, EFAULT, EINVAL, // EISCONN, EMSGSIZE, ENOBUFS, ENOMEM, // ENOTCONN, ENOTSOCK, EOPNOTSUPP, EPIPE }) handleSocketClosed (); rval = EXIT_FAILURE; std::ostringstream strm; strm << "error on socket: (" << errno << ") \"" << errnoText << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; } } return rval; } int PythonProvider::send ( MI_Datetime const& datetime) { //SCX_BOOKEND ("PythonProvider::send (MI_Datetime)"); int rval = send (static_cast<unsigned char>(datetime.isTimestamp)); if (EXIT_SUCCESS == rval) { if (datetime.isTimestamp) { if (EXIT_SUCCESS != send (datetime.u.timestamp.year) || EXIT_SUCCESS != send (datetime.u.timestamp.month) || EXIT_SUCCESS != send (datetime.u.timestamp.day) || EXIT_SUCCESS != send (datetime.u.timestamp.hour) || EXIT_SUCCESS != send (datetime.u.timestamp.minute) || EXIT_SUCCESS != send (datetime.u.timestamp.second) || EXIT_SUCCESS != send (datetime.u.timestamp.microseconds) || EXIT_SUCCESS != send (datetime.u.timestamp.utc)) { rval = EXIT_FAILURE; } } else { if (EXIT_SUCCESS != send (datetime.u.interval.days) || EXIT_SUCCESS != send (datetime.u.interval.hours) || EXIT_SUCCESS != send (datetime.u.interval.minutes) || EXIT_SUCCESS != send (datetime.u.interval.seconds) || EXIT_SUCCESS != send (datetime.u.interval.microseconds)) { rval = EXIT_FAILURE; } } } return rval; } int PythonProvider::send ( MI_Value const& value, MI_Type const type) { //SCX_BOOKEND ("PythonProvider::send (value, type)"); std::ostringstream strm; int rval = EXIT_SUCCESS; switch (type) { case MI_BOOLEAN: rval = send<unsigned char> (value.boolean); break; case MI_UINT8: rval = send (value.uint8); break; case MI_SINT8: rval = send (value.sint8); break; case MI_UINT16: rval = send (value.uint16); break; case MI_SINT16: rval = send (value.sint16); break; case MI_UINT32: rval = send (value.uint32); break; case MI_SINT32: rval = send (value.sint32); break; case MI_UINT64: rval = send (value.uint64); break; case MI_SINT64: rval = send (value.sint64); break; case MI_REAL32: rval = send (value.real32); break; case MI_REAL64: rval = send (value.real64); break; case MI_CHAR16: rval = send (value.char16); break; case MI_DATETIME: rval = send (value.datetime); break; case MI_STRING: rval = send (static_cast<char const* const> (value.string)); break; case MI_INSTANCE: rval = send (*(value.instance)); break; case MI_BOOLEANA: { //SCX_BOOKEND ("PythonProvider::send_array (bool)"); rval = send<int> (value.booleana.size); for (MI_Uint32 n = 0; EXIT_SUCCESS == rval && n < value.booleana.size; ++n) { rval = send<unsigned char> (value.booleana.data[n]); } } break; case MI_UINT8A: rval = send_array (value.uint8a); break; case MI_SINT8A: rval = send_array (value.sint8a); break; case MI_UINT16A: rval = send_array (value.uint16a); break; case MI_SINT16A: rval = send_array (value.sint16a); break; case MI_UINT32A: rval = send_array (value.uint32a); break; case MI_SINT32A: rval = send_array (value.sint32a); break; case MI_UINT64A: rval = send_array (value.uint64a); break; case MI_SINT64A: rval = send_array (value.sint64a); break; case MI_REAL32A: rval = send_array (value.real32a); break; case MI_REAL64A: rval = send_array (value.real64a); break; case MI_CHAR16A: rval = send_array (value.char16a); break; case MI_DATETIMEA: rval = send_array (value.datetimea); break; case MI_STRINGA: rval = send_str_array (value.stringa); break; case MI_INSTANCEA: rval = send_array (value.instancea); break; default: strm << __FILE__ << '[' << __LINE__ << ']' << "encountered an unhandled param type: " << type; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; rval = EXIT_FAILURE; break; } return rval; } int PythonProvider::send_str_array ( MI_StringA const& strArray) { //SCX_BOOKEND ("PythonProvider::send_str_array"); int rval = send<int> (strArray.size); for (MI_Uint32 n = 0; EXIT_SUCCESS == rval && n < strArray.size; ++n) { rval = send (static_cast<char const* const> (strArray.data[n])); } return rval; } int PythonProvider::send ( MI_Value const& value, MI_Type const type, MI_Uint32 const flags) { //SCX_BOOKEND ("PythonProvider::send (value, type, flags)"); int rval = EXIT_SUCCESS; std::ostringstream strm; if (MI_REFERENCE != type && MI_REFERENCEA != type) { if (0 == (MI_FLAG_NULL & flags)) { rval = send<unsigned char> (type); if (EXIT_SUCCESS == rval) { rval = send (value, type); } } else { rval = send<unsigned char> (type | MI_NULL_FLAG); } } else { strm << __FILE__ << '[' << __LINE__ << ']' << "encountered an unhandled param type: " << type; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; rval = EXIT_FAILURE; } return rval; } int PythonProvider::send ( MI_Instance const& instance) { //SCX_BOOKEND ("PythonProvider::send (MI_Instance)"); std::ostringstream strm; int rval = EXIT_SUCCESS; MI_Uint32 elementCount; if (EXIT_SUCCESS == rval && MI_RESULT_OK != MI_Instance_GetElementCount (&instance, &elementCount)) { SCX_BOOKEND_PRINT ("GetElementCount failed"); rval = EXIT_FAILURE; } int nArgs = 0; for (MI_Uint32 n = 0; EXIT_SUCCESS == rval && n < elementCount; ++n) { MI_Char const* elementName; MI_Value value; MI_Type type; MI_Uint32 flags; if (MI_RESULT_OK == MI_Instance_GetElementAt ( &instance, n, &elementName, &value, &type, &flags)) { if (!(MI_FLAG_READONLY == (MI_FLAG_READONLY & flags) && MI_FLAG_KEY != (MI_FLAG_KEY & flags))) { ++nArgs; } } else { SCX_BOOKEND_PRINT ("GetElementAt - failed"); rval = EXIT_FAILURE; } } if (EXIT_SUCCESS == rval) { rval = send (nArgs); } for (MI_Uint32 n = 0; EXIT_SUCCESS == rval && n < elementCount; ++n) { MI_Char const* elementName; MI_Value value; MI_Type type; MI_Uint32 flags; if (MI_RESULT_OK == MI_Instance_GetElementAt ( &instance, n, &elementName, &value, &type, &flags)) { if (!(MI_FLAG_READONLY == (MI_FLAG_READONLY & flags) && MI_FLAG_KEY != (MI_FLAG_KEY & flags))) { send (elementName); send (value, type, flags); } } else { SCX_BOOKEND_PRINT ("GetElementAt - failed"); rval = EXIT_FAILURE; } } return rval; } int PythonProvider::send ( MI_Instance* const pInstance) { return send (*pInstance); } int PythonProvider::sendRequest ( unsigned char const opType, MI_Instance const& instance) { std::ostringstream strm; #if PRINT_BOOKENDS strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::sendRequest", strm.str ()); #endif int rval = verifySocketState (); // 1: write the header // a: (unsigned char) OP_TYPE // b: (string) OP_NAME // c: (int) ARG_COUNT // 2: write each ARG if (EXIT_SUCCESS == rval) { rval = send (opType); } if (EXIT_SUCCESS == rval) { rval = send (m_Name); } if (EXIT_SUCCESS == rval) { rval = send (instance); } return rval; } int PythonProvider::recv ( std::string* const pStrOut) { //SCX_BOOKEND ("PythonProvider::recv (string)"); int nStrLen = 0; int rval = recv (&nStrLen); if (EXIT_SUCCESS == rval) { if (0 != nStrLen) { ssize_t nCharsRead = 0; char_array pBuffer (new char[nStrLen]); while (EXIT_SUCCESS == rval && nStrLen > nCharsRead) { ssize_t nRead = read (m_FD, pBuffer.get () + nCharsRead, nStrLen - nCharsRead); if (0 < nRead) { nCharsRead += nRead; } else if (0 == nRead) { // socket closed handleSocketClosed (); rval = EXIT_FAILURE; SCX_BOOKEND_PRINT ("socket closed unexpectedly"); std::cerr << "socket closed unexpectedly" << std::endl; } else if (EINTR != errno) { // Error - check errno { EAGAIN, EBADF, EFAULT, EINVAL, EIO, // EISDIR } handleSocketClosed (); rval = EXIT_FAILURE; std::ostringstream strm; strm << "error on socket: (" << errno << ") \"" << errnoText << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; } } if (EXIT_SUCCESS == rval) { pStrOut->assign (pBuffer.get (), nStrLen); } else { SCX_BOOKEND_PRINT ("unable to read string text"); std::cerr << "unable to read string text" << std::endl; } } else { pStrOut->erase (); } } else { SCX_BOOKEND_PRINT ("unable to read string size"); std::cerr << "unable to read string size" << std::endl; } return rval; } int PythonProvider::recv ( MI_Datetime* const pDatetimeOut) { //SCX_BOOKEND ("PythonProvider::recv (MI_Datetime)"); MI_Datetime tempVal; unsigned char isTimestamp; int rval = recv (&isTimestamp); if (EXIT_SUCCESS == rval) { if (isTimestamp) { tempVal.isTimestamp = MI_TRUE; if (EXIT_SUCCESS != recv (&(tempVal.u.timestamp.year)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.month)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.day)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.hour)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.minute)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.second)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.microseconds)) || EXIT_SUCCESS != recv (&(tempVal.u.timestamp.utc))) { rval = EXIT_FAILURE; } } else { tempVal.isTimestamp = MI_FALSE; if (EXIT_SUCCESS != recv (&(tempVal.u.interval.days)) || EXIT_SUCCESS != recv (&(tempVal.u.interval.hours)) || EXIT_SUCCESS != recv (&(tempVal.u.interval.minutes)) || EXIT_SUCCESS != recv (&(tempVal.u.interval.seconds)) || EXIT_SUCCESS != recv (&(tempVal.u.interval.microseconds))) { rval = EXIT_FAILURE; } } } if (EXIT_SUCCESS == rval) { *pDatetimeOut = tempVal; } return rval; } int PythonProvider::recvResult ( MI_Boolean* const pResultOut) { std::ostringstream strm; *pResultOut = MI_FALSE; #if (PRINT_BOOKENDS) strm << "name: \"" << m_Name << '\"'; SCX_BOOKEND_EX ("PythonProvider::recvResult", strm.str ()); strm.str (""); strm.clear (); #endif int result = -1; int rval = recv (&result); if (EXIT_SUCCESS == rval) { if (0 == result) { SCX_BOOKEND_PRINT ("recv'd POSITIVE"); *pResultOut = MI_TRUE; } else { SCX_BOOKEND_PRINT ("recv'd NEGATIVE"); std::string errorMsg; rval = recv (&errorMsg); if (EXIT_SUCCESS == rval) { if (0 != errorMsg.length ()) { strm << ": error msg: \"" << errorMsg << '\"'; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); } else { SCX_BOOKEND_PRINT ("no error msg"); } } else { SCX_BOOKEND_PRINT ("failed to receive error msg"); } } } else { SCX_BOOKEND_PRINT ("failed to receive result"); } return rval; } int PythonProvider::recv_MI_Value ( MI_Context* const pContext, MI_Instance* const pInstanceOut) { SCX_BOOKEND ("PythonProvider::recv_MI_Value"); std::string name; int rval = recv (&name); if (EXIT_SUCCESS == rval) { std::ostringstream strm; unsigned char type; rval = recv (&type); if (EXIT_SUCCESS == rval) { if (0 == (MI_NULL_FLAG & type)) { std::string tempStr; char_array pArray; util::unique_ptr<std::string[]> pStrArray; util::unique_ptr<MI_InstancePtr[]> ppInstanceArray; MI_Value val; switch (type) { case MI_BOOLEAN: { //SCX_BOOKEND ("recv_MI_Value (BOOLEAN)"); unsigned char temp; rval = recv (&temp); if (EXIT_SUCCESS == rval) { val.boolean = temp ? MI_TRUE : MI_FALSE; } } break; case MI_UINT8: rval = TypeHelper<MI_Uint8>::recv (this, &(val.uint8)); break; case MI_SINT8: rval = TypeHelper<MI_Sint8>::recv (this, &(val.sint8)); break; case MI_UINT16: rval = TypeHelper<MI_Uint16>::recv (this, &(val.uint16)); break; case MI_SINT16: rval = TypeHelper<MI_Sint16>::recv (this, &(val.sint16)); break; case MI_UINT32: rval = TypeHelper<MI_Uint32>::recv (this, &(val.uint32)); break; case MI_SINT32: rval = TypeHelper<MI_Sint32>::recv (this, &(val.sint32)); break; case MI_UINT64: rval = TypeHelper<MI_Uint64>::recv (this, &(val.uint64)); break; case MI_SINT64: rval = TypeHelper<MI_Sint64>::recv (this, &(val.sint64)); break; case MI_REAL32: rval = TypeHelper<MI_Real32>::recv (this, &(val.real32)); break; case MI_REAL64: rval = TypeHelper<MI_Real64>::recv (this, &(val.real64)); break; case MI_CHAR16: rval = TypeHelper<MI_Char16>::recv (this, &(val.char16)); break; case MI_DATETIME: rval = TypeHelper<MI_Datetime>::recv (this, &(val.datetime)); break; case MI_STRING: rval = recv (&tempStr); val.string = const_cast<MI_Char*>(tempStr.c_str ()); break; case MI_INSTANCE: { SCX_BOOKEND ("recv_MI_Value (MI_INSTANCE)"); ppInstanceArray.reset (new MI_InstancePtr[1]); if (EXIT_SUCCESS == (rval = allocate_MI_Instance ( pContext, pInstanceOut, name, &ppInstanceArray[0])) && EXIT_SUCCESS == (rval = recv ( ppInstanceArray[0].get ()))) { val.instance = ppInstanceArray[0].get (); } } break; case MI_BOOLEANA: { //SCX_BOOKEND ("recv_MI_Value (BOOLEANA)"); int length; rval = recv (&length); if (EXIT_SUCCESS == rval) { pArray.reset ( new char[length * sizeof (MI_Boolean)]); MI_Boolean* const pTemp = reinterpret_cast<MI_Boolean* const> ( pArray.get ()); for (int i = 0; EXIT_SUCCESS == rval && length > i; ++i) { unsigned char temp; rval = recv (&temp); if (EXIT_SUCCESS == rval) { pTemp[i] = temp ? MI_TRUE : MI_FALSE; } } if (EXIT_SUCCESS == rval) { val.booleana.data = pTemp; val.booleana.size = static_cast<MI_Uint32> (length); } } } break; case MI_UINT8A: rval = TypeHelper<MI_Uint8>::recv_array ( this, &(val.uint8a), &pArray); break; case MI_SINT8A: rval = TypeHelper<MI_Sint8>::recv_array ( this, &(val.sint8a), &pArray); break; case MI_UINT16A: rval = TypeHelper<MI_Uint16>::recv_array ( this, &(val.uint16a), &pArray); break; case MI_SINT16A: rval = TypeHelper<MI_Sint16>::recv_array ( this, &(val.sint16a), &pArray); break; case MI_UINT32A: rval = TypeHelper<MI_Uint32>::recv_array ( this, &(val.uint32a), &pArray); break; case MI_SINT32A: rval = TypeHelper<MI_Sint32>::recv_array ( this, &(val.sint32a), &pArray); break; case MI_UINT64A: rval = TypeHelper<MI_Uint64>::recv_array ( this, &(val.uint64a), &pArray); break; case MI_SINT64A: rval = TypeHelper<MI_Sint64>::recv_array ( this, &(val.sint64a), &pArray); break; case MI_REAL32A: rval = TypeHelper<MI_Real32>::recv_array ( this, &(val.real32a), &pArray); break; case MI_REAL64A: rval = TypeHelper<MI_Real64>::recv_array ( this, &(val.real64a), &pArray); break; case MI_CHAR16A: rval = TypeHelper<MI_Char16>::recv_array ( this, &(val.char16a), &pArray); break; case MI_DATETIMEA: rval = TypeHelper<MI_Datetime>::recv_array ( this, &(val.datetimea), &pArray); break; case MI_STRINGA: { //SCX_BOOKEND ("recv_MI_Value (STRINGA)"); int length; int rval = recv (&length); if (EXIT_SUCCESS == rval) { MI_Char** pTemp = 0; if (0 < length) { pArray.reset ( new char[length * sizeof (MI_Char*)]); pTemp = reinterpret_cast<MI_Char** const> ( pArray.get ()); pStrArray.reset (new std::string[length]); for (int i = 0; EXIT_SUCCESS == rval && length > i; ++i) { rval = recv (pStrArray.get () + i); if (EXIT_SUCCESS == rval) { pTemp[i] = const_cast<MI_Char*>( pStrArray[i].c_str ()); } } } if (EXIT_SUCCESS == rval) { val.stringa.data = pTemp; val.stringa.size = static_cast<MI_Uint32> (length); } } } break; case MI_INSTANCEA: // read the size // allocate the pointer array // for each instance // allocate an instance // read the instance // set the array // cleanup the memory { SCX_BOOKEND ("recv_MI_Value (INSTANCEA)"); int length; int rval = recv (&length); if (EXIT_SUCCESS == rval) { MI_Instance** pTemp = 0; if (0 < length) { pArray.reset ( new char[length * sizeof (MI_Instance*)]); pTemp = reinterpret_cast<MI_Instance** const> ( pArray.get ()); ppInstanceArray.reset ( new MI_InstancePtr[length]); for (int i = 0; EXIT_SUCCESS == rval && i < length; ++i) { rval = allocate_MI_Instance ( pContext, pInstanceOut, name, &ppInstanceArray[i]); if (EXIT_SUCCESS == rval) { rval = recv (pContext, ppInstanceArray[i].get ()); } if (EXIT_SUCCESS == rval) { pTemp[i] = ppInstanceArray[i].get (); } } } if (EXIT_SUCCESS == rval) { val.instancea.data = pTemp; val.instancea.size = static_cast<MI_Uint32> (length); } } } break; case MI_REFERENCE: case MI_REFERENCEA: strm << __FILE__ << '[' << __LINE__ << ']' << "encountered a non-standard param type: " << type; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); rval = EXIT_FAILURE; break; default: strm << __FILE__ << '[' << __LINE__ << ']' << "encountered an unknown param type: " << type; SCX_BOOKEND_PRINT (strm.str ()); std::cerr << strm.str () << std::endl; strm.str (""); strm.clear (); rval = EXIT_FAILURE; break; } if (EXIT_SUCCESS == rval) { MI_Value tmpVal; MI_Type tmpType; MI_Result result = MI_Instance_GetElement ( pInstanceOut, name.c_str (), &tmpVal, &tmpType, NULL, NULL); if (MI_RESULT_NO_SUCH_PROPERTY == result) { result = MI_Instance_AddElement ( pInstanceOut, name.c_str (), &val, static_cast<MI_Type>(type), 0); } else { result = MI_Instance_SetElement ( pInstanceOut, name.c_str (), &val, static_cast<MI_Type>(type), 0); } if (MI_RESULT_OK == result) { strm << "value added - name: \"" << name << "\" - type: " << static_cast<int>(type); } else { strm << "Failed to add value: \"" << name << "\" type: " << static_cast<int>(type) << " to instance"; rval = EXIT_FAILURE; } SCX_BOOKEND_PRINT (strm.str ()); strm.str (""); strm.clear (); } else { SCX_BOOKEND_PRINT ("Failed to read value"); } } } else { SCX_BOOKEND_PRINT ("Failed to read type"); } } else { SCX_BOOKEND_PRINT ("Failed to read name"); } return rval; } int PythonProvider::recv ( MI_Context* const pContext, MI_Instance* const pInstanceOut) { SCX_BOOKEND ("PythonProvider::recv (MI_Instance)"); int nItems; int rval = recv (&nItems); for (int i = 0; EXIT_SUCCESS == rval && i < nItems; ++i) { rval = recv_MI_Value (pContext, pInstanceOut); } return rval; } } // namespace scx
31.464691
463
0.470413
[ "vector" ]
4b08af8da1f7cd50c588519433acbe3a3412438e
1,567
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/tti/test/test_has_fun_compile.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/libs/tti/test/test_has_fun_compile.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/tti/test/test_has_fun_compile.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
// (C) Copyright Edward Diener 2012 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #include "test_has_fun.hpp" #include <boost/mpl/assert.hpp> int main() { // You can always instantiate without compiler errors TheTIntFunction<AType,void,boost::mpl::vector<long,double> > aVar; BOOST_TTI_HAS_FUNCTION_GEN(someFunctionMember)<AnotherType,double,boost::mpl::vector<short,short,long,int> > aVar2; Pickedname<AnotherType,AType,boost::mpl::vector<long,long> > aVar3; // Compile time asserts BOOST_MPL_ASSERT((TheTIntFunction<AnotherType,AType,boost::mpl::vector<long,double> >)); BOOST_MPL_ASSERT((BOOST_TTI_HAS_FUNCTION_GEN(VoidFunction)<AType,void>)); BOOST_MPL_ASSERT((FunctionReturningInt<AType,int>)); BOOST_MPL_ASSERT((FunctionReturningInt<AnotherType,double,boost::mpl::vector<int> >)); BOOST_MPL_ASSERT((BOOST_TTI_HAS_FUNCTION_GEN(TSFunction)<AnotherType,AType::AStructType,boost::mpl::vector<AType::AnIntType,double> >)); BOOST_MPL_ASSERT((BOOST_TTI_HAS_FUNCTION_GEN(aFunction)<AnotherType,AType,boost::mpl::vector<int> >)); BOOST_MPL_ASSERT((AnotherIntFunction<AnotherType,int,boost::mpl::vector<AType> >)); BOOST_MPL_ASSERT((HaveTheSIntFunction<AType,int,boost::mpl::vector<long,double> >)); BOOST_MPL_ASSERT((BOOST_TTI_HAS_FUNCTION_GEN(sFunction)<AnotherType,AType::AnIntType,boost::mpl::vector<int,long,double> >)); return 0; }
46.088235
139
0.750479
[ "vector" ]
4b092e2890c4ea2da54ea8d127d57914482d4905
1,569
hpp
C++
plugin/serializer/lib/msgpack-c/include/msgpack/adaptor/nil.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
478
2015-01-04T16:59:53.000Z
2022-03-07T20:28:07.000Z
include/msgpack/adaptor/nil.hpp
kangliqiang/msgpack-c
96c688708c13ec6f719f41c446183556d9d41c2b
[ "ECL-2.0", "Apache-2.0" ]
83
2015-01-15T21:45:06.000Z
2021-11-08T11:01:48.000Z
include/msgpack/adaptor/nil.hpp
kangliqiang/msgpack-c
96c688708c13ec6f719f41c446183556d9d41c2b
[ "ECL-2.0", "Apache-2.0" ]
175
2015-01-04T03:30:39.000Z
2020-01-27T17:08:14.000Z
// // MessagePack for C++ static resolution routine // // Copyright (C) 2008-2009 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MSGPACK_TYPE_NIL_HPP #define MSGPACK_TYPE_NIL_HPP #include "msgpack/versioning.hpp" #include "msgpack/object_fwd.hpp" namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(v1) { namespace type { struct nil { }; } // namespace type inline object const& operator>> (object const& o, type::nil&) { if(o.type != type::NIL) { throw type_error(); } return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, const type::nil&) { o.pack_nil(); return o; } inline void operator<< (object& o, type::nil) { o.type = type::NIL; } inline void operator<< (object::with_zone& o, type::nil v) { static_cast<object&>(o) << v; } template <> inline void object::as<void>() const { msgpack::type::nil v; convert(v); } } // MSGPACK_API_VERSION_NAMESPACE(v1) } // namespace msgpack #endif // MSGPACK_TYPE_NIL_HPP
22.73913
78
0.688974
[ "object" ]
4b0945aa8f564da8e0aadf1d324f6036bd594c60
26,624
cpp
C++
groups/bsl/bsls/bsls_performancehint.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
1
2019-06-27T11:32:37.000Z
2019-06-27T11:32:37.000Z
groups/bsl/bsls/bsls_performancehint.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
null
null
null
groups/bsl/bsls/bsls_performancehint.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
null
null
null
// bsls_performancehint.t.cpp -*-C++-*- #include <bsls_performancehint.h> #include <bsls_bsltestutil.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #if defined(BSLS_PLATFORM_OS_WINDOWS) #include <windows.h> // GetSystemTimeAsFileTime, Sleep #else #include <unistd.h> // sleep #include <sys/time.h> // gettimeofday #include <stdint.h> // uint64_t #endif #if defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VERSION < 1600 // stdint.h is only available starting is VS2010. typedef unsigned long long uint64_t; #else #include <stdint.h> #endif using namespace BloombergLP; using namespace bsls; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // This component provides MACROs to facilitate more intelligent code // generation by the compiler with regards to branch prediction and // prefetching. It is difficult to ensure the compiler behaves exactly as // *hinted*. This is because the hint is only taken under optimized build and // various other optimizations are performed simultaneously by the compiler. // Therefore, only the small usage example will be verified. // // In addition, macro safety is tested in all test cases. The common // 'using namespace BloombergLP' statement is intentionally commented out to // test that these macros function outside namespace 'BloombergLP'. // ---------------------------------------------------------------------------- // [ 1] Usage Example: Using 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' and // 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY' // [ 2] Usage Example: Using 'BSLS_PERFORMANCEHINT_PREDICT_EXPECT' // [ 3] Usage Example: Using 'prefetchForReading' and 'prefetchForWriting' //----------------------------------------------------------------------------- // [-1] Performance Test: Verifies the performance of test 1, 2, 3 //----------------------------------------------------------------------------- //============================================================================= // STANDARD BDE ASSERT TEST MACRO //----------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACROS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- namespace TestCase1 { const int TESTSIZE = 10000000; // test size used for timing int global; // uninitialized on purpose to prevent compiler // optimization } // close namespace TestCase1 namespace TestCase3 { const int SIZE = 10 * 1024 * 1024; // big enough so not all data sits in cache #if defined(BSLS_PLATFORM_CMP_SUN) // For some reason the sun machine is A LOT slower than the other // platforms, even in optimized mode. const int TESTSIZE = 10; #else const int TESTSIZE = 100; #endif #if defined(BSLS_PLATFORM_CMP_GNU) && !defined(BSLS_PLATFORM_CMP_CLANG) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wlarger-than=" #endif volatile int array1[SIZE]; // for 'addWithPrefetch' volatile int array2[SIZE]; // for 'addWithPrefetch' volatile int array3[SIZE]; // for 'addWithoutPrefetch volatile int array4[SIZE]; // for 'addWithoutPrefetch #if defined(BSLS_PLATFORM_CMP_GNU) && !defined(BSLS_PLATFORM_CMP_CLANG) #pragma GCC diagnostic pop #endif } // close namespace TestCase3 //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- #if defined(BSLS_PLATFORM_OS_WINDOWS) void sleep(unsigned int seconds) { Sleep(seconds * 1000); } #endif int64_t getTimer() // Return a 64-bit signed integer values indicating current time as an // offset in nanoseconds from some fixed (but unspecified) point in time. // Note that this value can be used to determine the number of nanoseconds // between two calls to 'getTimer'. Note also that this deliberately // simple implementation is provided to avoid a dependency on // 'bsls_timeutil'. { int64_t result; #if defined(BSLS_PLATFORM_OS_WINDOWS) const unsigned int k_NANOSECONDS_PER_TICK = 100; ULARGE_INTEGER fileTime; GetSystemTimeAsFileTime(reinterpret_cast<FILETIME *>(&fileTime)); result = static_cast<int64_t>(fileTime.QuadPart * k_NANOSECONDS_PER_TICK); #else timeval rawTime; gettimeofday(&rawTime, 0); const int64_t K = 1000; const int64_t M = 1000000; result = (static_cast<int64_t>(rawTime.tv_sec) * M + rawTime.tv_usec) * K; #endif return result; } class Stopwatch { // The 'class' provides an accumulator for the system time of the current // process. A stopwatch can be in either the STOPPED (initial) state or // the RUNNING state. The accumulated times can be accessed at any time // and in either state (RUNNING or STOPPED). // DATA int64_t d_startTime; int64_t d_accumulatedTime; bool d_isRunning; public: Stopwatch() : d_startTime(0), d_accumulatedTime(0), d_isRunning(false) {} // Create a stopwatch in the STOPPED state having total accumulated // system, user, and wall times all equal to 0.0. //! ~Stopwatch(); // Destroy this stopwatch. Note that this method's definition is // compiler generated. // MANIPULATORS void reset() // Place this stopwatch in the STOPPED state, unconditionally stopping // the accumulation of elapsed times, and set the quiescent elapsed // times to 0.0. { d_isRunning = false; d_accumulatedTime = 0; d_startTime = 0; } void start() // Place this stopwatch in the RUNNING state and begin accumulating // elapsed times if this object was in the STOPPED state. { d_isRunning = true; d_startTime = getTimer(); } void stop() // Place this stopwatch in the STOPPED state, unconditionally stopping // the accumulation of elapsed times. Note that the quiescent // accumulated elapsed times are available while in the STOPPED state. { d_isRunning = false; d_accumulatedTime = getTimer() - d_startTime; } // ACCESSORS double elapsedTime() const // Return the total (instantaneous and quiescent) elapsed wall time (in // seconds) accumulated by this stopwatch. Note that this method is // equivalent to 'accumulatedWallTime'. { const double k_NanosecondsPerSecond = 1.0E9; int64_t elapsedTime = (d_isRunning) ? getTimer() - d_startTime : d_accumulatedTime; return (double)elapsedTime / k_NanosecondsPerSecond; } bool isRunning() const { return d_isRunning; } // Return 'true' if this stopwatch is accumulating time, and 'false' // otherwise. }; //============================================================================= // GLOBAL TEST CASES //----------------------------------------------------------------------------- namespace TestCase1 { volatile int count1 = 0; volatile int count2 = 0; void foo() // Dummy function that sets the global variable. Used to prevent the // compiler from optimizing the code too much. { global = 1; count1++; count1++; count1++; count1++; count1++; count1++; count1++; count1++; } void bar() // Dummy function that sets the global variable. Used to prevent the // compiler from optimizing the code too much. { global = 2; count2++; count2++; count2++; count2++; count2++; count2++; count2++; count2++; } void testUsageExample1(int argc, bool assert) { int verbose = argc > 2; int veryVerbose = argc > 3; int veryVeryVerbose = argc > 4; (void) assert; (void) verbose; (void) veryVerbose; (void) veryVeryVerbose; Stopwatch timer; timer.reset(); if (veryVerbose) { printf("BSLS_PERFORMANCEHINT_PREDICT_LIKELY\n"); } timer.start(); for (int x = 0; x < TESTSIZE; ++x) { int y = rand() % 10; // Incorrect usage of 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' since there // is only a one in ten chance that this branch is taken. if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(y == 8)) { foo(); } else { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; bar(); } } timer.stop(); double likelyTime = timer.elapsedTime(); if (veryVerbose) { P(likelyTime); } if (veryVerbose) { printf("BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY\n"); } timer.reset(); timer.start(); for (int x = 0; x < TESTSIZE; ++x) { int y = rand() % 10; // Correct usage of 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY' since there // is only a one in ten chance that this branch is taken. if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(y == 8)) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; foo(); } else { bar(); } } timer.stop(); double unlikelyTime = timer.elapsedTime(); if (veryVerbose) { P(unlikelyTime); } #if defined(BDE_BUILD_TARGET_OPT) // Only check under optimized build. #if defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_SUN) || \ (defined(BSLS_PLATFORM_CMP_IBM) && BSLS_PLATFORM_CMP_VER_MAJOR >= 0x0900)\ // Only check when 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' and // 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY' expands into something // meaningful. double tolerance = 0.02; if (assert) { LOOP2_ASSERT(likelyTime, unlikelyTime, likelyTime + tolerance > unlikelyTime); } #endif #endif } } // close namespace TestCase1 namespace TestCase3 { void init(volatile int *arrayA, volatile int *arrayB) { #if defined(BSLS_PLATFORM_CMP_IBM) && BSLS_PLATFORM_CMP_VER_MAJOR >= 0x0900 // Only available under xlc 10. for (int i = 0; i < SIZE; ++i){ __dcbf((const void *)(arrayA++)); __dcbf((const void *)(arrayB++)); } #else // suppress 'unused parameter' compiler warnings: (void) arrayA; (void) arrayB; #endif } void addWithoutPrefetch(volatile int *arrayA, volatile int *arrayB) // Performs some form of addition on the specified 'arrayA' and 'arrayB' // without using prefetch. { for (int i = 0; i < SIZE/8; ++i){ *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; } } void addWithPrefetch(volatile int *arrayA, volatile int *arrayB) // Performs some form of addition on the specified 'arrayA' and 'arrayB' // using prefetch. { for (int i = 0; i < SIZE/8; ++i){ // cast away the volatile qualifiers when calling 'prefetch*': BloombergLP::bsls::PerformanceHint::prefetchForWriting( const_cast<int *>(arrayA + 16)); BloombergLP::bsls::PerformanceHint::prefetchForReading( const_cast<int *>(arrayB + 16)); *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; *arrayA += *(arrayB++); ++arrayA; } } void testUsageExample3(int argc, bool assert) { int verbose = argc > 2; int veryVerbose = argc > 3; int veryVeryVerbose = argc > 4; // suppress 'unused parameter' compiler warnings: (void) assert; (void) verbose; (void) veryVeryVerbose; if (veryVerbose) { printf("Adding without prefetch\n"); } TestCase3::init(TestCase3::array1, TestCase3::array2); Stopwatch timer; timer.start(); for(int i = 0; i < TESTSIZE; ++i) { TestCase3::addWithoutPrefetch(TestCase3::array1, TestCase3::array2); } timer.stop(); double withoutPrefetch = timer.elapsedTime(); if (veryVerbose) { P(withoutPrefetch); } if (veryVerbose) { printf("Adding with prefetch\n"); } TestCase3::init(TestCase3::array3, TestCase3::array4); timer.reset(); timer.start(); for(int i = 0; i < TestCase3::TESTSIZE; ++i) { addWithPrefetch(array3, array4); } timer.stop(); double withPrefetch = timer.elapsedTime(); if (veryVerbose) { P(withPrefetch); } #if defined(BDE_BUILD_TARGET_OPT) // Only check under optimized build. #if defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_IBM) || \ defined(BSLS_PLATFORM_CMP_SUN) || defined(BSLS_PLATFORM_OS_WINDOWS) // Only check when 'prefetchForReading' or 'prefetchForWriting' expands // expands into something meaningful. double tolerance = 0.02; // Note that when compiling using 'bde_build.pl -t opt_exc_mt', the // optimization flag is set to '-O'. Whereas, the optimization flag used // by 'IS_OPTIMIZED=1 pcomp' is set to '-xO2'. Therefore, the improvement // in efficiency is much less than what's described in the usage example // when compiled using bde_build. if (assert) { // Only assert in performance test case. LOOP2_ASSERT(withoutPrefetch, withPrefetch, withoutPrefetch + tolerance > withPrefetch); } #endif #endif } } // close namespace TestCase3 //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; int verbose = argc > 2; int veryVerbose = argc > 3; int veryVeryVerbose = argc > 4; (void) veryVeryVerbose; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: // Zero is always the leading case. case 4: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE 3 // This will test the usage example 3 provided in the component // header file for 'prefetchForReading' and 'prefetchForWriting'. // // Concerns: // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Run the usage example using 'prefetchForReading' and // 'prefetchForWriting'. // // Testing: // prefetchForReading // prefetchForWriting // -------------------------------------------------------------------- if (verbose) printf("\nTESTING USAGE EXAMPLE 3" "\n=======================\n"); TestCase3::testUsageExample3(argc, false); } break; case 3: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE 2 // This will test the usage example 2 provided in the component // header file for 'BSLS_PERFORMANCEHINT_PREDICT_EXPECT'. // // Concerns: // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Ensure the usage example compiles. // // Testing: // BSLS_PERFORMANCEHINT_PREDICT_EXPECT // -------------------------------------------------------------------- if (verbose) printf("\nTESTING USAGE EXAMPLE 2" "\n=======================\n"); int x = rand() % 4; // Incorrect usage of 'BSLS_PERFORMANCEHINT_PREDICT_EXPECT', since the // probability of getting a 3 is equivalent to other numbers (0, 1, 2). // However, this is sufficient to illustrate the intent of this macro. switch(BSLS_PERFORMANCEHINT_PREDICT_EXPECT(x, 3)) { case 1: //.. break; case 2: //.. break; case 3: //.. break; default: break; } } break; case 2: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE 1 // This will test the usage example 1 provided in the component // header file for 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' and // 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY'. // // Concerns: // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Run the usage example using 'BSLS_PERFORMANCEHINT_PREDICT_LIKELY' // and 'BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY'. // // Testing: // BSLS_PERFORMANCEHINT_PREDICT_LIKELY, // BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY // -------------------------------------------------------------------- if (verbose) printf("\nTESTING USAGE EXAMPLE 1" "\n=======================\n"); ASSERT(true); TestCase1::testUsageExample1(argc, false); } break; case 1: { // -------------------------------------------------------------------- // TESTING TEST-MACHINERY: 'Stopwatch' // // Concerns: //: 1 That 'Stopwatch' is created in a STOPPED state with an elapsed //: time of 0. //: //: 2 That 'start' puts the stopwatch in a RUNNING state //: //: 3 That 'stop' puts the soptwatch in a STOPPED state and recurds //: the accumuted time. //: //: 4 That 'elaspsedTime' returns the correct elapsed time in //: nanoseconds. //: //: 5 That 'reset' resets the 'Stopwatch' to its defualt constructed //: state. // // Plan: //: 1 Construct a 'Stopwatch' and verify 'isRunning' is 'false' and //: 'elapsedTime' is 0. (C-1) //: //: 2 Construct a 'Stopwatch', call 'start', sleep for ~1 second and //: verify 'isRunning' it 'true' and 'elapsedTime' is ~1 second. //: //: 2 Construct a 'Stopwatch', call 'start', sleep for ~1 second and //: then stop the 'Stopwatch'. Sleep another second. Verify //: 'isRunning' it 'false', 'elapsedTime' is ~1, and that the elapsed //: time has not changed since the stopwatch was stopped. // // Testing: // TESTING TEST-MACHINERY: 'Stopwatch' // -------------------------------------------------------------------- if (verbose) printf("\nTESTING TEST-MACHINERY: 'Stopwatch'" "\n===================================\n"); const double TOLERANCE = .5; if (veryVerbose) printf("\tCompare constructed 'Stopwatch'\n"); { Stopwatch mX; const Stopwatch& X = mX; ASSERT(false == X.isRunning()); ASSERT(0 == X.elapsedTime()); } if (veryVerbose) printf("Test starting a stopwatch\n"); { Stopwatch mX; const Stopwatch& X = mX; ASSERT(false == X.isRunning()); ASSERT(0 == X.elapsedTime()); mX.start(); sleep(1); ASSERT(true == X.isRunning()); ASSERT(1 - TOLERANCE < X.elapsedTime()); ASSERT(1 + TOLERANCE > X.elapsedTime()); } if (veryVerbose) printf("Test stop and elapsedTime\n"); { Stopwatch mX; const Stopwatch& X = mX; ASSERT(false == X.isRunning()); ASSERT(0 == X.elapsedTime()); mX.start(); sleep(1); ASSERT(true == X.isRunning()); ASSERT(0 < X.elapsedTime()); mX.stop(); double EXPECTED = X.elapsedTime(); sleep(1); double ACTUAL = X.elapsedTime(); ASSERTV(EXPECTED, ACTUAL, EXPECTED - EXPECTED * .00001 < ACTUAL && EXPECTED + EXPECTED * .00001 > ACTUAL); ASSERTV(X.elapsedTime(), 1 - TOLERANCE < X.elapsedTime()); ASSERTV(X.elapsedTime(), 1 + TOLERANCE > X.elapsedTime()); mX.reset(); ASSERT(false == X.isRunning()); ASSERT(0 == X.elapsedTime()); } } break; case -1: { // -------------------------------------------------------------------- // PERFORMANCE TEST // Test the improvement of performance in using various performance // hints. // // Concerns: // The performance of using the performance hints in the various // usage examples must be faster than not using them. // // Plan: // Using 'Stopwatch', compare the time it takes to run the test // using the performance hints and not using the hints. Then compare // and assert the time difference. The test driver must observe an // improvement in performance. To minimize the effect of caching // biasing the result, run the version that uses the proper hint // first. // // Testing: // PERFORMANCE TEST // -------------------------------------------------------------------- if (verbose) printf("\nPERFORMANCE TEST" "\n================\n"); if (veryVerbose) { printf("Usage Example 1:\n"); } TestCase1::testUsageExample1(argc, true); if (veryVerbose) { printf("Usage Example 3:\n"); } TestCase3::testUsageExample3(argc, true); } break; case -2: { // -------------------------------------------------------------------- // CONCERN: STOPWATCH ACCURACY // This test is concerned with the accuracy of 'Stopwatch'. It is a // negative test case because it takes ~1 minute to run. // Concerns: //: 1 That the 'elapsedTime' reported by 'Stopwatch' is accurate. // // Plan: //: 1 Perform a loop-based tested, sleeping over a series of different //: delay periods and comparing the results of //: 'Stopwatch::elapsedTime' to 'time' // // Testing: // CONCERN: STOPWATCH ACCURACY // -------------------------------------------------------------------- if (verbose) printf("\nCONCERN: STOPWATCH ACCURACY" "\n===========================\n"); if (veryVerbose) printf("\tCompare results w/ 'time'\n"); for (int i = 1; i < 7; ++i){ const int DELAY = i; time_t startTime = time(0); Stopwatch mX; mX.start(); sleep(DELAY); mX.stop(); time_t expectedElaspedTime = time(0) - startTime; if (veryVerbose) { P_(DELAY); P_(mX.elapsedTime()); P(expectedElaspedTime); } ASSERT(mX.elapsedTime() < expectedElaspedTime + 1 && mX.elapsedTime() > expectedElaspedTime - 1); } } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
31.545024
79
0.537898
[ "object" ]
4b0955f9c8f1d63c5ac306600fe65982bcd93bbc
21,641
cpp
C++
c_glib/arrow-flight-glib/server.cpp
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2021-11-24T04:43:52.000Z
2021-11-24T04:43:52.000Z
c_glib/arrow-flight-glib/server.cpp
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2
2021-11-17T14:36:51.000Z
2022-01-23T16:49:53.000Z
c_glib/arrow-flight-glib/server.cpp
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <arrow/util/make_unique.h> #include <arrow-glib/arrow-glib.hpp> #include <arrow-flight-glib/common.hpp> #include <arrow-flight-glib/server.hpp> G_BEGIN_DECLS /** * SECTION: server * @section_id: server * @title: Server related classes * @include: arrow-flight-glib/arrow-flight-glib.h * * #GAFlightDataStream is a class for producing a sequence of IPC * payloads to be sent in `FlightData` protobuf messages. Generally, * this is not used directly. Generally, #GAFlightRecordBatchStream is * used instead. * * #GAFlightRecordBatchStream is a class for producing a sequence of * IPC payloads to be sent in `FlightData` protobuf messages by * #GArrowRecordBatchReader`. * * #GAFlightServerOptions is a class for options of each server. * * #GAFlightServerCallContext is a class for context of each server call. * * #GAFlightServer is a class to develop an Apache Arrow Flight server. * * Since: 5.0.0 */ typedef struct GAFlightDataStreamPrivate_ { arrow::flight::FlightDataStream *stream; } GAFlightDataStreamPrivate; enum { PROP_STREAM = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GAFlightDataStream, gaflight_data_stream, G_TYPE_OBJECT) #define GAFLIGHT_DATA_STREAM_GET_PRIVATE(obj) \ static_cast<GAFlightDataStreamPrivate *>( \ gaflight_data_stream_get_instance_private( \ GAFLIGHT_DATA_STREAM(obj))) static void gaflight_data_stream_finalize(GObject *object) { auto priv = GAFLIGHT_DATA_STREAM_GET_PRIVATE(object); delete priv->stream; G_OBJECT_CLASS(gaflight_data_stream_parent_class)->finalize(object); } static void gaflight_data_stream_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_DATA_STREAM_GET_PRIVATE(object); switch (prop_id) { case PROP_STREAM: priv->stream = static_cast<arrow::flight::FlightDataStream *>( g_value_get_pointer(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_data_stream_init(GAFlightDataStream *object) { } static void gaflight_data_stream_class_init(GAFlightDataStreamClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->finalize = gaflight_data_stream_finalize; gobject_class->set_property = gaflight_data_stream_set_property; GParamSpec *spec; spec = g_param_spec_pointer("stream", "Stream", "The raw arrow::flight::FlightDataStream *", static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_STREAM, spec); } typedef struct GAFlightRecordBatchStreamPrivate_ { GArrowRecordBatchReader *reader; } GAFlightRecordBatchStreamPrivate; enum { PROP_READER = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GAFlightRecordBatchStream, gaflight_record_batch_stream, GAFLIGHT_TYPE_DATA_STREAM) #define GAFLIGHT_RECORD_BATCH_STREAM_GET_PRIVATE(obj) \ static_cast<GAFlightRecordBatchStreamPrivate *>( \ gaflight_record_batch_stream_get_instance_private( \ GAFLIGHT_RECORD_BATCH_STREAM(obj))) static void gaflight_record_batch_stream_dispose(GObject *object) { auto priv = GAFLIGHT_RECORD_BATCH_STREAM_GET_PRIVATE(object); if (priv->reader) { g_object_unref(priv->reader); priv->reader = NULL; } G_OBJECT_CLASS(gaflight_record_batch_stream_parent_class)->dispose(object); } static void gaflight_record_batch_stream_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_RECORD_BATCH_STREAM_GET_PRIVATE(object); switch (prop_id) { case PROP_READER: priv->reader = GARROW_RECORD_BATCH_READER(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_record_batch_stream_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_RECORD_BATCH_STREAM_GET_PRIVATE(object); switch (prop_id) { case PROP_READER: g_value_set_object(value, priv->reader); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_record_batch_stream_init(GAFlightRecordBatchStream *object) { } static void gaflight_record_batch_stream_class_init(GAFlightRecordBatchStreamClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = gaflight_record_batch_stream_dispose; gobject_class->set_property = gaflight_record_batch_stream_set_property; gobject_class->get_property = gaflight_record_batch_stream_get_property; GParamSpec *spec; /** * GAFlightRecordBatchStream:reader: * * The reader that produces record batches. * * Since: 6.0.0 */ spec = g_param_spec_object("reader", "Reader", "The reader that produces record batches", GARROW_TYPE_RECORD_BATCH_READER, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_READER, spec); } /** * gaflight_record_batch_stream_new: * @reader: A #GArrowRecordBatchReader to be read. * @options: (nullable): A #GArrowWriteOptions for writing record batches to * a client. * * Returns: The newly created #GAFlightRecordBatchStream. * * Since: 6.0.0 */ GAFlightRecordBatchStream * gaflight_record_batch_stream_new(GArrowRecordBatchReader *reader, GArrowWriteOptions *options) { auto arrow_reader = garrow_record_batch_reader_get_raw(reader); auto arrow_options_default = arrow::ipc::IpcWriteOptions::Defaults(); arrow::ipc::IpcWriteOptions *arrow_options = NULL; if (options) { arrow_options = garrow_write_options_get_raw(options); } else { arrow_options = &arrow_options_default; } auto stream = arrow::internal::make_unique< arrow::flight::RecordBatchStream>(arrow_reader, *arrow_options); return static_cast<GAFlightRecordBatchStream *>( g_object_new(GAFLIGHT_TYPE_RECORD_BATCH_STREAM, "stream", stream.release(), "reader", reader, NULL)); } typedef struct GAFlightServerOptionsPrivate_ { arrow::flight::FlightServerOptions options; GAFlightLocation *location; } GAFlightServerOptionsPrivate; enum { PROP_LOCATION = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GAFlightServerOptions, gaflight_server_options, G_TYPE_OBJECT) #define GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(obj) \ static_cast<GAFlightServerOptionsPrivate *>( \ gaflight_server_options_get_instance_private( \ GAFLIGHT_SERVER_OPTIONS(obj))) static void gaflight_server_options_dispose(GObject *object) { auto priv = GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(object); if (priv->location) { g_object_unref(priv->location); priv->location = NULL; } G_OBJECT_CLASS(gaflight_server_options_parent_class)->dispose(object); } static void gaflight_server_options_finalize(GObject *object) { auto priv = GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(object); priv->options.~FlightServerOptions(); G_OBJECT_CLASS(gaflight_server_options_parent_class)->finalize(object); } static void gaflight_server_options_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(object); switch (prop_id) { case PROP_LOCATION: { priv->location = GAFLIGHT_LOCATION(g_value_dup_object(value)); auto flight_location = gaflight_location_get_raw(priv->location); new(&(priv->options)) arrow::flight::FlightServerOptions(*flight_location); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_server_options_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(object); switch (prop_id) { case PROP_LOCATION: g_value_set_object(value, priv->location); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_server_options_init(GAFlightServerOptions *object) { } static void gaflight_server_options_class_init(GAFlightServerOptionsClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = gaflight_server_options_dispose; gobject_class->finalize = gaflight_server_options_finalize; gobject_class->set_property = gaflight_server_options_set_property; gobject_class->get_property = gaflight_server_options_get_property; GParamSpec *spec; spec = g_param_spec_object("location", "Location", "The location to be listened", GAFLIGHT_TYPE_LOCATION, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_LOCATION, spec); } /** * gaflight_server_options_new: * @location: A #GAFlightLocation to be listened. * * Returns: The newly created options for a server. * * Since: 5.0.0 */ GAFlightServerOptions * gaflight_server_options_new(GAFlightLocation *location) { return static_cast<GAFlightServerOptions *>( g_object_new(GAFLIGHT_TYPE_SERVER_OPTIONS, "location", location, NULL)); } typedef struct GAFlightServerCallContextPrivate_ { arrow::flight::ServerCallContext *call_context; } GAFlightServerCallContextPrivate; enum { PROP_CALL_CONTEXT = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GAFlightServerCallContext, gaflight_server_call_context, G_TYPE_OBJECT) #define GAFLIGHT_SERVER_CALL_CONTEXT_GET_PRIVATE(obj) \ static_cast<GAFlightServerCallContextPrivate *>( \ gaflight_server_call_context_get_instance_private( \ GAFLIGHT_SERVER_CALL_CONTEXT(obj))) static void gaflight_server_call_context_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GAFLIGHT_SERVER_CALL_CONTEXT_GET_PRIVATE(object); switch (prop_id) { case PROP_CALL_CONTEXT: priv->call_context = static_cast<arrow::flight::ServerCallContext *>( g_value_get_pointer(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void gaflight_server_call_context_init(GAFlightServerCallContext *object) { } static void gaflight_server_call_context_class_init(GAFlightServerCallContextClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->set_property = gaflight_server_call_context_set_property; GParamSpec *spec; spec = g_param_spec_pointer("call-context", "Call context", "The raw arrow::flight::ServerCallContext", static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_CALL_CONTEXT, spec); } G_END_DECLS namespace gaflight { class DataStream : public arrow::flight::FlightDataStream { public: DataStream(GAFlightDataStream *gastream) : arrow::flight::FlightDataStream(), gastream_(gastream) { } ~DataStream() override { g_object_unref(gastream_); } std::shared_ptr<arrow::Schema> schema() override { auto stream = gaflight_data_stream_get_raw(gastream_); return stream->schema(); } arrow::Result<arrow::flight::FlightPayload> GetSchemaPayload() override { auto stream = gaflight_data_stream_get_raw(gastream_); return stream->GetSchemaPayload(); } arrow::Result<arrow::flight::FlightPayload> Next() override { auto stream = gaflight_data_stream_get_raw(gastream_); return stream->Next(); } private: GAFlightDataStream *gastream_; }; class Server : public arrow::flight::FlightServerBase { public: Server(GAFlightServer *gaserver) : gaserver_(gaserver) { } arrow::Status ListFlights( const arrow::flight::ServerCallContext &context, const arrow::flight::Criteria *criteria, std::unique_ptr<arrow::flight::FlightListing> *listing) override { auto gacontext = gaflight_server_call_context_new_raw(&context); GAFlightCriteria *gacriteria = NULL; if (criteria) { gacriteria = gaflight_criteria_new_raw(criteria); } GError *gerror = NULL; auto gaflights = gaflight_server_list_flights(gaserver_, gacontext, gacriteria, &gerror); if (gacriteria) { g_object_unref(gacriteria); } g_object_unref(gacontext); if (gerror) { return garrow_error_to_status(gerror, arrow::StatusCode::UnknownError, "[flight-server][list-flights]"); } std::vector<arrow::flight::FlightInfo> flights; for (auto node = gaflights; node; node = node->next) { auto gaflight = GAFLIGHT_INFO(node->data); flights.push_back(*gaflight_info_get_raw(gaflight)); g_object_unref(gaflight); } g_list_free(gaflights); *listing = arrow::internal::make_unique< arrow::flight::SimpleFlightListing>(flights); return arrow::Status::OK(); } arrow::Status DoGet( const arrow::flight::ServerCallContext &context, const arrow::flight::Ticket &ticket, std::unique_ptr<arrow::flight::FlightDataStream> *stream) override { auto gacontext = gaflight_server_call_context_new_raw(&context); auto gaticket = gaflight_ticket_new_raw(&ticket); GError *gerror = NULL; auto gastream = gaflight_server_do_get(gaserver_, gacontext, gaticket, &gerror); g_object_unref(gaticket); g_object_unref(gacontext); if (gerror) { return garrow_error_to_status(gerror, arrow::StatusCode::UnknownError, "[flight-server][do-get]"); } *stream = arrow::internal::make_unique<DataStream>(gastream); return arrow::Status::OK(); } private: GAFlightServer *gaserver_; }; }; G_BEGIN_DECLS typedef struct GAFlightServerPrivate_ { gaflight::Server server; } GAFlightServerPrivate; G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE(GAFlightServer, gaflight_server, G_TYPE_OBJECT) #define GAFLIGHT_SERVER_GET_PRIVATE(obj) \ static_cast<GAFlightServerPrivate *>( \ gaflight_server_get_instance_private( \ GAFLIGHT_SERVER(obj))) static void gaflight_server_finalize(GObject *object) { auto priv = GAFLIGHT_SERVER_GET_PRIVATE(object); priv->server.~Server(); G_OBJECT_CLASS(gaflight_server_parent_class)->finalize(object); } static void gaflight_server_init(GAFlightServer *object) { auto priv = GAFLIGHT_SERVER_GET_PRIVATE(object); new(&(priv->server)) gaflight::Server(object); } static void gaflight_server_class_init(GAFlightServerClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->finalize = gaflight_server_finalize; } /** * gaflight_server_listen: * @server: A #GAFlightServer. * @options: A #GAFlightServerOptions. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: %TRUE on success, %FALSE on error. * * Since: 5.0.0 */ gboolean gaflight_server_listen(GAFlightServer *server, GAFlightServerOptions *options, GError **error) { auto flight_server = gaflight_server_get_raw(server); const auto flight_options = gaflight_server_options_get_raw(options); return garrow::check(error, flight_server->Init(*flight_options), "[flight-server][listen]"); } /** * gaflight_server_new: * @server: A #GAFlightServer. * * Returns: The port number listening. * * Since: 5.0.0 */ gint gaflight_server_get_port(GAFlightServer *server) { const auto flight_server = gaflight_server_get_raw(server); return flight_server->port(); } /** * gaflight_server_shutdown: * @server: A #GAFlightServer. * @error: (nullable): Return location for a #GError or %NULL. * * Shuts down the serve. This function can be called from signal * handler or another thread. * * Returns: %TRUE on success, %FALSE on error. * * Since: 5.0.0 */ gboolean gaflight_server_shutdown(GAFlightServer *server, GError **error) { auto flight_server = gaflight_server_get_raw(server); return garrow::check(error, flight_server->Shutdown(), "[flight-server][shutdown]"); } /** * gaflight_server_list_flights: * @server: A #GAFlightServer. * @context: A #GAFlightServerCallContext. * @criteria: (nullable): A #GAFlightCriteria. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (element-type GAFlightInfo) (transfer full): * #GList of #GAFlightInfo on success, %NULL on error. * * Since: 5.0.0 */ GList * gaflight_server_list_flights(GAFlightServer *server, GAFlightServerCallContext *context, GAFlightCriteria *criteria, GError **error) { auto klass = GAFLIGHT_SERVER_GET_CLASS(server); if (!(klass && klass->list_flights)) { g_set_error(error, GARROW_ERROR, GARROW_ERROR_NOT_IMPLEMENTED, "not implemented"); return NULL; } return (*(klass->list_flights))(server, context, criteria, error); } /** * gaflight_server_do_get: * @server: A #GAFlightServer. * @context: A #GAFlightServerCallContext. * @ticket: A #GAFlightTicket. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (transfer full): #GAFlightDataStream on success, %NULL on error. * * Since: 6.0.0 */ GAFlightDataStream * gaflight_server_do_get(GAFlightServer *server, GAFlightServerCallContext *context, GAFlightTicket *ticket, GError **error) { auto klass = GAFLIGHT_SERVER_GET_CLASS(server); if (!(klass && klass->do_get)) { g_set_error(error, GARROW_ERROR, GARROW_ERROR_NOT_IMPLEMENTED, "not implemented"); return NULL; } return (*(klass->do_get))(server, context, ticket, error); } G_END_DECLS arrow::flight::FlightDataStream * gaflight_data_stream_get_raw(GAFlightDataStream *stream) { auto priv = GAFLIGHT_DATA_STREAM_GET_PRIVATE(stream); return priv->stream; } arrow::flight::FlightServerOptions * gaflight_server_options_get_raw(GAFlightServerOptions *options) { auto priv = GAFLIGHT_SERVER_OPTIONS_GET_PRIVATE(options); return &(priv->options); } GAFlightServerCallContext * gaflight_server_call_context_new_raw( const arrow::flight::ServerCallContext *call_context) { return GAFLIGHT_SERVER_CALL_CONTEXT( g_object_new(GAFLIGHT_TYPE_SERVER_CALL_CONTEXT, "call-context", call_context, NULL)); } arrow::flight::FlightServerBase * gaflight_server_get_raw(GAFlightServer *server) { auto priv = GAFLIGHT_SERVER_GET_PRIVATE(server); return &(priv->server); }
29.890884
81
0.663324
[ "object", "vector" ]
4b0967ee60e2c0d60e370f73630f93306fba2ca5
4,142
cc
C++
src/ui/lib/escher/test/gtest_escher.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/ui/lib/escher/test/gtest_escher.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/ui/lib/escher/test/gtest_escher.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "src/ui/lib/escher/test/gtest_escher.h" #include <vulkan/vulkan.h> #include "src/ui/lib/escher/escher_process_init.h" #include <vulkan/vulkan.hpp> namespace escher { namespace test { namespace { #if !ESCHER_USE_RUNTIME_GLSL static void LoadShadersFromDisk(HackFilesystemPtr fs) { // NOTE: this and ../shaders/shaders.gni must be kept in sync. const std::vector<HackFilePath> paths = { // Flatland renderer. "shaders/shaders_flatland_flat_main_frag14695981039346656037.spirv", "shaders/shaders_flatland_flat_main_vert14695981039346656037.spirv", // Paper renderer. "shaders/shaders_model_renderer_main_frag17553292397499926694.spirv", "shaders/shaders_model_renderer_main_frag8280587512758179706.spirv", "shaders/shaders_model_renderer_main_vert11112688489391456647.spirv", "shaders/shaders_model_renderer_main_vert17553292397499926694.spirv", "shaders/shaders_model_renderer_main_vert4295183060635058569.spirv", "shaders/shaders_model_renderer_main_vert8280587512758179706.spirv", "shaders/shaders_paper_frag_main_ambient_light_frag17553292397499926694.spirv", "shaders/shaders_paper_frag_main_point_light_frag11112688489391456647.spirv", "shaders/shaders_paper_frag_main_point_light_frag4295183060635058569.spirv", // Pose buffer latching compute shader, from pose_buffer_latching_shader.cc. "shaders/shaders_compute_pose_buffer_latching_comp14695981039346656037.spirv", }; FXL_CHECK(fs->InitializeWithRealFiles(paths)); } #endif } // namespace Escher* GetEscher() { EXPECT_FALSE(VK_TESTS_SUPPRESSED()); return EscherEnvironment::GetGlobalTestEnvironment()->GetEscher(); } void EscherEnvironment::RegisterGlobalTestEnvironment() { FXL_CHECK(global_escher_environment_ == nullptr); global_escher_environment_ = static_cast<escher::test::EscherEnvironment*>( testing::AddGlobalTestEnvironment(new escher::test::EscherEnvironment)); } EscherEnvironment* EscherEnvironment::GetGlobalTestEnvironment() { FXL_CHECK(global_escher_environment_ != nullptr); return global_escher_environment_; } void EscherEnvironment::SetUp() { if (!VK_TESTS_SUPPRESSED()) { VulkanInstance::Params instance_params( {{}, {VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME}, false}); auto validation_layer_name = VulkanInstance::GetValidationLayerName(); if (validation_layer_name) { instance_params.layer_names.insert(*validation_layer_name); } VulkanDeviceQueues::Params device_params( {{VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME, VK_KHR_MAINTENANCE1_EXTENSION_NAME, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME}, {}, vk::SurfaceKHR()}); #ifdef VK_USE_PLATFORM_FUCHSIA device_params.required_extension_names.insert(VK_FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME); device_params.required_extension_names.insert(VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME); device_params.required_extension_names.insert(VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME); #endif vulkan_instance_ = VulkanInstance::New(instance_params); vulkan_device_ = VulkanDeviceQueues::New(vulkan_instance_, device_params); hack_filesystem_ = HackFilesystem::New(); #if !ESCHER_USE_RUNTIME_GLSL LoadShadersFromDisk(hack_filesystem_); #endif escher_ = std::make_unique<Escher>(vulkan_device_, hack_filesystem_); FXL_CHECK(escher_); #if ESCHER_USE_RUNTIME_GLSL escher::GlslangInitializeProcess(); #endif } } void EscherEnvironment::TearDown() { if (!VK_TESTS_SUPPRESSED()) { #if ESCHER_USE_RUNTIME_GLSL escher::GlslangFinalizeProcess(); #endif escher_.reset(); vulkan_device_.reset(); vulkan_instance_.reset(); } } } // namespace test } // namespace escher
36.333333
100
0.783921
[ "vector" ]
4b0b65cfe74c7fbbf071340206bda9ef0d0f247b
2,766
cpp
C++
numerics/root_finders_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
null
null
null
numerics/root_finders_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
null
null
null
numerics/root_finders_test.cpp
tinygrox/Principia
49a25646c673dcd84cefbc6295df410fc6d927d5
[ "MIT" ]
null
null
null
 #include "numerics/root_finders.hpp" #include <vector> #include "geometry/named_quantities.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" namespace principia { using geometry::Instant; using quantities::Acceleration; using quantities::Length; using quantities::Pow; using quantities::Sqrt; using quantities::Time; using quantities::si::Metre; using quantities::si::Second; using testing_utilities::AlmostEquals; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Ge; using ::testing::IsEmpty; using ::testing::Le; namespace si = quantities::si; namespace numerics { class RootFindersTest : public ::testing::Test {}; // Solving Δt * Δt == n. TEST_F(RootFindersTest, SquareRoots) { Instant const t_0; Instant const t_max = t_0 + 10 * Second; Length const n_max = Pow<2>(t_max - t_0) * si::Unit<Acceleration>; for (Length n = 1 * Metre; n < n_max; n += 1 * Metre) { int evaluations = 0; auto const equation = [t_0, n, &evaluations](Instant const& t) { ++evaluations; return Pow<2>(t - t_0) * si::Unit<Acceleration> - n; }; EXPECT_THAT(Bisect(equation, t_0, t_max) - t_0, AlmostEquals(Sqrt(n / si::Unit<Acceleration>), 0, 1)); if (n == 25 * Metre) { EXPECT_EQ(3, evaluations); } else { EXPECT_THAT(evaluations, AllOf(Ge(49), Le(58))); } } } TEST_F(RootFindersTest, QuadraticEquations) { // Golden ratio. auto const s1 = SolveQuadraticEquation(0.0, -1.0, -1.0, 1.0); EXPECT_THAT(s1, ElementsAre(AlmostEquals((1 - sqrt(5)) / 2, 1), AlmostEquals((1 + sqrt(5)) / 2, 0))); // No solutions. auto const s2 = SolveQuadraticEquation(0.0, 1.0, 0.0, 1.0); EXPECT_THAT(s2, IsEmpty()); // One solution. auto const s3 = SolveQuadraticEquation(0.0, 1.0, 2.0, 1.0); EXPECT_THAT(s3, ElementsAre(-1.0)); // An ill-conditioned system. I fart in its general direction. If done // naively, this yields {-100032., -99968.4} according to Mathematica. auto const s4 = SolveQuadraticEquation(0.0, 1.0000001e25, 2.0000003e20, 1.0000001e15); EXPECT_THAT(s4, ElementsAre(AlmostEquals(-100031.62777541532972762902, 66), AlmostEquals(-99968.38222458367027247098, 65))); // A typed system. Instant const t0; auto const s5 = SolveQuadraticEquation( t0, 1.0 * Metre, 2.0 * Metre / Second, 1.0 * Metre / Second / Second); EXPECT_THAT(s5, ElementsAre(t0 - 1.0 * Second)); } } // namespace numerics } // namespace principia
30.733333
76
0.632321
[ "geometry", "vector" ]
4b150839e9be21c265c589eda1848a3f33b3af8a
3,763
cc
C++
ChiTech/ChiPhysics/FieldFunction/lua/physics_exportfieldfunc.cc
zachhardy/chi-tech
18fb6cb691962a90820e2ef4fcb05473f4a6bdd6
[ "MIT" ]
7
2019-09-10T12:16:08.000Z
2021-05-06T16:01:59.000Z
ChiTech/ChiPhysics/FieldFunction/lua/physics_exportfieldfunc.cc
zachhardy/chi-tech
18fb6cb691962a90820e2ef4fcb05473f4a6bdd6
[ "MIT" ]
72
2019-09-04T15:00:25.000Z
2021-12-02T20:47:29.000Z
ChiTech/ChiPhysics/FieldFunction/lua/physics_exportfieldfunc.cc
Naktakala/chi-tech
df5f517d5aff1d167db50ccbcf4229ac0cb668c4
[ "MIT" ]
41
2019-09-02T15:33:31.000Z
2022-02-10T13:26:49.000Z
#include "ChiLua/chi_lua.h" #include "ChiPhysics/chi_physics.h" #include "ChiPhysics/FieldFunction/fieldfunction.h" #include <chi_log.h> extern ChiPhysics& chi_physics_handler; extern ChiLog& chi_log; //############################################################################# /** Exports a field function to VTK format. * \param FFHandle int Global handle to the field function. \param BaseName char Base name for the exported file. \ingroup LuaFieldFunc \author Jan*/ int chiExportFieldFunctionToVTK(lua_State *L) { int num_args = lua_gettop(L); if ((num_args < 2) or (num_args>3)) LuaPostArgAmountError("chiExportFieldFunctionToVTK", 2, num_args); int ff_handle = lua_tonumber(L,1); const char* base_name = lua_tostring(L,2); const char* field_name = base_name; if (num_args == 3) field_name = lua_tostring(L,3); //======================================================= Getting solver std::shared_ptr<chi_physics::FieldFunction> ff; try{ ff = chi_physics_handler.fieldfunc_stack.at(ff_handle); } catch(const std::out_of_range& o) { chi_log.Log(LOG_ALLERROR) << "Invalid field function handle in chiPhysicsExportFieldFunctionToVTK"; exit(EXIT_FAILURE); } ff->ExportToVTKComponentOnly(base_name, field_name); return 0; } //############################################################################# /** Exports all the groups in a field function to VTK format. * \param FFHandle int Global handle to the field function. \param BaseName char Base name for the exported file. \ingroup LuaFieldFunc \author Jan*/ int chiExportFieldFunctionToVTKG(lua_State *L) { int num_args = lua_gettop(L); if ((num_args < 2) or (num_args>3)) LuaPostArgAmountError("chiExportFieldFunctionToVTK", 2, num_args); int ff_handle = lua_tonumber(L,1); const char* base_name = lua_tostring(L,2); const char* field_name = base_name; if (num_args == 3) field_name = lua_tostring(L,3); //======================================================= Getting solver std::shared_ptr<chi_physics::FieldFunction> ff; try{ ff = chi_physics_handler.fieldfunc_stack.at(ff_handle); } catch(const std::out_of_range& o) { chi_log.Log(LOG_ALLERROR) << "Invalid field function handle in chiPhysicsExportFieldFunctionToVTK"; exit(EXIT_FAILURE); } ff->ExportToVTK(base_name, field_name); return 0; } //############################################################################# /** Exports all the field functions in a list to VTK format. * * \param listFFHandles table Global handles to the field functions \param BaseName char Base name for the exported file. \ingroup LuaFieldFunc \author Jan*/ int chiExportMultiFieldFunctionToVTK(lua_State *L) { int num_args = lua_gettop(L); if (num_args != 2) LuaPostArgAmountError(__FUNCTION__, 2, num_args); int list = lua_tonumber(L,1); const char* base_name = lua_tostring(L,2); LuaCheckTableValue(__FUNCTION__,L,1); int table_size = lua_rawlen(L,1); std::vector<std::shared_ptr<chi_physics::FieldFunction>> ffs; ffs.reserve(table_size); for (int i=0; i<table_size; ++i) { lua_pushnumber(L,i+1); lua_gettable(L,1); int ff_handle = lua_tonumber(L,-1); lua_pop(L,1); //======================================================= Getting solver std::shared_ptr<chi_physics::FieldFunction> ff; try{ ff = chi_physics_handler.fieldfunc_stack.at(ff_handle); ffs.push_back(ff); } catch(const std::out_of_range& o) { chi_log.Log(LOG_ALLERROR) << "Invalid field function handle in chiPhysicsExportFieldFunctionToVTK"; exit(EXIT_FAILURE); } } chi_physics::FieldFunction::ExportMultipleFFToVTK(base_name,ffs); return 0; }
28.08209
81
0.640181
[ "vector" ]
4b156a4457b56e3e22ee7feb6a6f78f4253d29a1
84,476
cpp
C++
test/test.cpp
bang-olufsen/uriparser
e938f3468dd9cd151b9c8a9d49f27efcdc4322b9
[ "BSD-3-Clause" ]
20
2021-11-01T10:22:12.000Z
2022-03-23T13:57:36.000Z
test/test.cpp
bang-olufsen/uriparser
e938f3468dd9cd151b9c8a9d49f27efcdc4322b9
[ "BSD-3-Clause" ]
30
2022-01-28T06:03:31.000Z
2022-03-26T04:33:44.000Z
test/test.cpp
nextgis-borsch/lib_uriparser
3a63b7ba2f25aef78dd334e5807d419a9dabd95c
[ "BSD-3-Clause" ]
4
2021-11-01T10:22:16.000Z
2022-03-31T15:50:53.000Z
/* * uriparser - RFC 3986 URI parsing library * * Copyright (C) 2007, Weijia Song <songweijia@gmail.com> * Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org> * * 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 */ #include <uriparser/Uri.h> #include <uriparser/UriIp4.h> #include <gtest/gtest.h> #include <memory> #include <cstdio> #include <cstdlib> #include <cwchar> using namespace std; extern "C" { UriBool uri_TESTING_ONLY_ParseIpSixA(const char * text); UriBool uri_TESTING_ONLY_ParseIpFourA(const char * text); int uriCompareRangeA(const UriTextRangeA * a, const UriTextRangeA * b); } #define URI_TEST_IP_FOUR_FAIL(x) ASSERT_TRUE(URI_FALSE == uri_TESTING_ONLY_ParseIpFourA(x)) #define URI_TEST_IP_FOUR_PASS(x) ASSERT_TRUE(URI_TRUE == uri_TESTING_ONLY_ParseIpFourA(x)) // Note the closing brackets! TODO #define URI_TEST_IP_SIX_FAIL(x) ASSERT_TRUE(URI_FALSE == uri_TESTING_ONLY_ParseIpSixA(x "]")) #define URI_TEST_IP_SIX_PASS(x) ASSERT_TRUE(URI_TRUE == uri_TESTING_ONLY_ParseIpSixA(x "]")) #define URI_EXPECT_BETWEEN(candidate, first, afterLast) \ EXPECT_TRUE((candidate >= first) && (candidate <= afterLast)) #define URI_EXPECT_OUTSIDE(candidate, first, afterLast) \ EXPECT_TRUE((candidate < first) || (candidate > afterLast)) #define URI_EXPECT_RANGE_BETWEEN(range, uriFirst, uriAfterLast) \ URI_EXPECT_BETWEEN(range.first, uriFirst, uriAfterLast); \ URI_EXPECT_BETWEEN(range.afterLast, uriFirst, uriAfterLast) #define URI_EXPECT_RANGE_OUTSIDE(range, uriFirst, uriAfterLast) \ URI_EXPECT_OUTSIDE(range.first, uriFirst, uriAfterLast); \ URI_EXPECT_OUTSIDE(range.afterLast, uriFirst, uriAfterLast) #define URI_EXPECT_RANGE_EMPTY(range) \ EXPECT_TRUE((range.first != NULL) \ && (range.afterLast != NULL) \ && (range.first == range.afterLast)) namespace { bool testDistinctionHelper(const char * uriText, bool expectedHostSet, bool expectedAbsPath, bool expectedEmptyTailSegment) { UriParserStateA state; UriUriA uri; state.uri = &uri; int res = uriParseUriA(&state, uriText); if (res != URI_SUCCESS) { uriFreeUriMembersA(&uri); return false; } if (expectedHostSet != (uri.hostText.first != NULL)) { uriFreeUriMembersA(&uri); return false; } if (expectedAbsPath != (uri.absolutePath == URI_TRUE)) { uriFreeUriMembersA(&uri); return false; } if (expectedEmptyTailSegment != ((uri.pathTail != NULL) && (uri.pathTail->text.first == uri.pathTail->text.afterLast))) { uriFreeUriMembersA(&uri); return false; } uriFreeUriMembersA(&uri); return true; } } // namespace TEST(UriSuite, TestDistinction) { /* ============================================================================ Rule | Example | hostSet | absPath | emptySeg ------------------------------------|---------|---------|---------|--------- 1) URI = scheme ":" hier-part ... | | | | 1) "//" authority path-abempty | "s://" | true | false | false | "s:///" | true | false | true | "s://a" | true | false | false | "s://a/"| true | false | true 2) path-absolute | "s:/" | false | true | false 3) path-rootless | "s:a" | false | false | false | "s:a/" | false | false | true 4) path-empty | "s:" | false | false | false ------------------------------------|---------|---------|---------|--------- 2) relative-ref = relative-part ... | | | | 1) "//" authority path-abempty | "//" | true | false | false | "///" | true | false | true 2) path-absolute | "/" | false | true | false 3) path-noscheme | "a" | false | false | false | "a/" | false | false | true 4) path-empty | "" | false | false | false ============================================================================ */ ASSERT_TRUE(testDistinctionHelper("s://", true, false, false)); ASSERT_TRUE(testDistinctionHelper("s:///", true, false, true)); ASSERT_TRUE(testDistinctionHelper("s://a", true, false, false)); ASSERT_TRUE(testDistinctionHelper("s://a/", true, false, true)); ASSERT_TRUE(testDistinctionHelper("s:/", false, true, false)); ASSERT_TRUE(testDistinctionHelper("s:a", false, false, false)); ASSERT_TRUE(testDistinctionHelper("s:a/", false, false, true)); ASSERT_TRUE(testDistinctionHelper("s:", false, false, false)); ASSERT_TRUE(testDistinctionHelper("//", true, false, false)); ASSERT_TRUE(testDistinctionHelper("///", true, false, true)); ASSERT_TRUE(testDistinctionHelper("/", false, true, false)); ASSERT_TRUE(testDistinctionHelper("a", false, false, false)); ASSERT_TRUE(testDistinctionHelper("a/", false, false, true)); ASSERT_TRUE(testDistinctionHelper("", false, false, false)); } TEST(UriSuite, TestIpFour) { URI_TEST_IP_FOUR_FAIL("01.0.0.0"); URI_TEST_IP_FOUR_FAIL("001.0.0.0"); URI_TEST_IP_FOUR_FAIL("00.0.0.0"); URI_TEST_IP_FOUR_FAIL("000.0.0.0"); URI_TEST_IP_FOUR_FAIL("256.0.0.0"); URI_TEST_IP_FOUR_FAIL("300.0.0.0"); URI_TEST_IP_FOUR_FAIL("1111.0.0.0"); URI_TEST_IP_FOUR_FAIL("-1.0.0.0"); URI_TEST_IP_FOUR_FAIL("0.0.0"); URI_TEST_IP_FOUR_FAIL("0.0.0."); URI_TEST_IP_FOUR_FAIL("0.0.0.0."); URI_TEST_IP_FOUR_FAIL("0.0.0.0.0"); URI_TEST_IP_FOUR_FAIL("0.0..0"); URI_TEST_IP_FOUR_FAIL(".0.0.0"); URI_TEST_IP_FOUR_PASS("255.0.0.0"); URI_TEST_IP_FOUR_PASS("0.0.0.0"); URI_TEST_IP_FOUR_PASS("1.0.0.0"); URI_TEST_IP_FOUR_PASS("2.0.0.0"); URI_TEST_IP_FOUR_PASS("3.0.0.0"); URI_TEST_IP_FOUR_PASS("30.0.0.0"); } TEST(UriSuite, TestIpSixPass) { // Quad length URI_TEST_IP_SIX_PASS("abcd::"); URI_TEST_IP_SIX_PASS("abcd::1"); URI_TEST_IP_SIX_PASS("abcd::12"); URI_TEST_IP_SIX_PASS("abcd::123"); URI_TEST_IP_SIX_PASS("abcd::1234"); // Full length URI_TEST_IP_SIX_PASS("2001:0db8:0100:f101:0210:a4ff:fee3:9566"); // lower hex URI_TEST_IP_SIX_PASS("2001:0DB8:0100:F101:0210:A4FF:FEE3:9566"); // Upper hex URI_TEST_IP_SIX_PASS("2001:db8:100:f101:210:a4ff:fee3:9566"); URI_TEST_IP_SIX_PASS("2001:0db8:100:f101:0:0:0:1"); URI_TEST_IP_SIX_PASS("1:2:3:4:5:6:255.255.255.255"); // Legal IPv4 URI_TEST_IP_SIX_PASS("::1.2.3.4"); URI_TEST_IP_SIX_PASS("3:4::5:1.2.3.4"); URI_TEST_IP_SIX_PASS("::ffff:1.2.3.4"); URI_TEST_IP_SIX_PASS("::0.0.0.0"); // Min IPv4 URI_TEST_IP_SIX_PASS("::255.255.255.255"); // Max IPv4 // Zipper position URI_TEST_IP_SIX_PASS("::1:2:3:4:5:6:7"); URI_TEST_IP_SIX_PASS("1::1:2:3:4:5:6"); URI_TEST_IP_SIX_PASS("1:2::1:2:3:4:5"); URI_TEST_IP_SIX_PASS("1:2:3::1:2:3:4"); URI_TEST_IP_SIX_PASS("1:2:3:4::1:2:3"); URI_TEST_IP_SIX_PASS("1:2:3:4:5::1:2"); URI_TEST_IP_SIX_PASS("1:2:3:4:5:6::1"); URI_TEST_IP_SIX_PASS("1:2:3:4:5:6:7::"); // Zipper length URI_TEST_IP_SIX_PASS("1:1:1::1:1:1:1"); URI_TEST_IP_SIX_PASS("1:1:1::1:1:1"); URI_TEST_IP_SIX_PASS("1:1:1::1:1"); URI_TEST_IP_SIX_PASS("1:1::1:1"); URI_TEST_IP_SIX_PASS("1:1::1"); URI_TEST_IP_SIX_PASS("1::1"); URI_TEST_IP_SIX_PASS("::1"); // == localhost URI_TEST_IP_SIX_PASS("::"); // == all addresses // A few more variations URI_TEST_IP_SIX_PASS("21ff:abcd::1"); URI_TEST_IP_SIX_PASS("2001:db8:100:f101::1"); URI_TEST_IP_SIX_PASS("a:b:c::12:1"); URI_TEST_IP_SIX_PASS("a:b::0:1:2:3"); } TEST(UriSuite, TestIpSixFail) { // 5 char quad URI_TEST_IP_SIX_FAIL("::12345"); // Two zippers URI_TEST_IP_SIX_FAIL("abcd::abcd::abcd"); // Triple-colon zipper URI_TEST_IP_SIX_FAIL(":::1234"); URI_TEST_IP_SIX_FAIL("1234:::1234:1234"); URI_TEST_IP_SIX_FAIL("1234:1234:::1234"); URI_TEST_IP_SIX_FAIL("1234:::"); // No quads, just IPv4 URI_TEST_IP_SIX_FAIL("1.2.3.4"); URI_TEST_IP_SIX_FAIL("0001.0002.0003.0004"); // Five quads URI_TEST_IP_SIX_FAIL("0000:0000:0000:0000:0000:1.2.3.4"); // Seven quads URI_TEST_IP_SIX_FAIL("0:0:0:0:0:0:0"); URI_TEST_IP_SIX_FAIL("0:0:0:0:0:0:0:"); URI_TEST_IP_SIX_FAIL("0:0:0:0:0:0:0:1.2.3.4"); // Nine quads (or more) URI_TEST_IP_SIX_FAIL("1:2:3:4:5:6:7:8:9"); URI_TEST_IP_SIX_FAIL("::2:3:4:5:6:7:8:9"); URI_TEST_IP_SIX_FAIL("1:2:3:4::6:7:8:9"); URI_TEST_IP_SIX_FAIL("1:2:3:4:5:6:7:8::"); // Invalid IPv4 part URI_TEST_IP_SIX_FAIL("::ffff:001.02.03.004"); // Leading zeros URI_TEST_IP_SIX_FAIL("::ffff:1.2.3.1111"); // Four char octet URI_TEST_IP_SIX_FAIL("::ffff:1.2.3.256"); // > 255 URI_TEST_IP_SIX_FAIL("::ffff:311.2.3.4"); // > 155 URI_TEST_IP_SIX_FAIL("::ffff:1.2.3:4"); // Not a dot URI_TEST_IP_SIX_FAIL("::ffff:1.2.3"); // Missing octet URI_TEST_IP_SIX_FAIL("::ffff:1.2.3."); // Missing octet URI_TEST_IP_SIX_FAIL("::ffff:1.2.3a.4"); // Hex in octet URI_TEST_IP_SIX_FAIL("::ffff:1.2.3.4:123"); // Crap input // Nonhex URI_TEST_IP_SIX_FAIL("g:0:0:0:0:0:0"); } TEST(UriSuite, TestIpSixOverread) { UriUriA uri; const char * errorPos; // NOTE: This string is designed to not have a terminator char uriText[2 + 3 + 2 + 1 + 1]; strncpy(uriText, "//[::44.1", sizeof(uriText)); EXPECT_EQ(uriParseSingleUriExA(&uri, uriText, uriText + sizeof(uriText), &errorPos), URI_ERROR_SYNTAX); EXPECT_EQ(errorPos, uriText + sizeof(uriText)); } TEST(UriSuite, TestUri) { UriParserStateA stateA; UriParserStateW stateW; UriUriA uriA; UriUriW uriW; stateA.uri = &uriA; stateW.uri = &uriW; // On/off for each ASSERT_TRUE(0 == uriParseUriA(&stateA, "//user:pass@[::1]:80/segment/index.html?query#frag")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://[::1]:80/segment/index.html?query#frag")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://user:pass@[::1]/segment/index.html?query#frag")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://user:pass@[::1]:80?query#frag")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://user:pass@[::1]:80/segment/index.html#frag")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://user:pass@[::1]:80/segment/index.html?query")); uriFreeUriMembersA(&uriA); // Schema, port, one segment ASSERT_TRUE(0 == uriParseUriA(&stateA, "ftp://host:21/gnu/")); uriFreeUriMembersA(&uriA); // Relative ASSERT_TRUE(0 == uriParseUriA(&stateA, "one/two/three")); ASSERT_TRUE(!uriA.absolutePath); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "/one/two/three")); ASSERT_TRUE(uriA.absolutePath); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "//user:pass@localhost/one/two/three")); uriFreeUriMembersA(&uriA); // Both narrow and wide string version ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://www.example.com/")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriW(&stateW, L"http://www.example.com/")); uriFreeUriMembersW(&uriW); // Real life examples ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://sourceforge.net/projects/uriparser/")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://sourceforge.net/project/platformdownload.php?group_id=182840")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "mailto:test@example.com")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "../../")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "/")); ASSERT_TRUE(uriA.absolutePath); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "")); ASSERT_TRUE(!uriA.absolutePath); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 == uriParseUriA(&stateA, "file:///bin/bash")); uriFreeUriMembersA(&uriA); // Percent encoding ASSERT_TRUE(0 == uriParseUriA(&stateA, "http://www.example.com/name%20with%20spaces/")); uriFreeUriMembersA(&uriA); ASSERT_TRUE(0 != uriParseUriA(&stateA, "http://www.example.com/name with spaces/")); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriComponents) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 15 01 0 7 01 const char * const input = "http" "://" "sourceforge.net" "/" "project" "/" // 0 20 01 0 15 "platformdownload.php" "?" "group_id=182840"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.scheme.first == input); ASSERT_TRUE(uriA.scheme.afterLast == input + 4); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 15); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); ASSERT_TRUE(uriA.pathHead->text.first == input + 4 + 3 + 15 + 1); ASSERT_TRUE(uriA.pathHead->text.afterLast == input + 4 + 3 + 15 + 1 + 7); ASSERT_TRUE(uriA.pathHead->next->text.first == input + 4 + 3 + 15 + 1 + 7 + 1); ASSERT_TRUE(uriA.pathHead->next->text.afterLast == input + 4 + 3 + 15 + 1 + 7 + 1 + 20); ASSERT_TRUE(uriA.pathHead->next->next == NULL); ASSERT_TRUE(uriA.pathTail == uriA.pathHead->next); ASSERT_TRUE(uriA.query.first == input + 4 + 3 + 15 + 1 + 7 + 1 + 20 + 1); ASSERT_TRUE(uriA.query.afterLast == input + 4 + 3 + 15 + 1 + 7 + 1 + 20 + 1 + 15); ASSERT_TRUE(uriA.fragment.first == NULL); ASSERT_TRUE(uriA.fragment.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriComponentsBug20070701) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 01 01 01 const char * const input = "a" ":" "b"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.scheme.first == input); ASSERT_TRUE(uriA.scheme.afterLast == input + 1); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.hostText.first == NULL); ASSERT_TRUE(uriA.hostText.afterLast == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); ASSERT_TRUE(uriA.pathHead->text.first == input + 1 + 1); ASSERT_TRUE(uriA.pathHead->text.afterLast == input + 1 + 1 + 1); ASSERT_TRUE(uriA.pathHead->next == NULL); ASSERT_TRUE(uriA.pathTail == uriA.pathHead); ASSERT_TRUE(uriA.query.first == NULL); ASSERT_TRUE(uriA.query.afterLast == NULL); ASSERT_TRUE(uriA.fragment.first == NULL); ASSERT_TRUE(uriA.fragment.afterLast == NULL); ASSERT_TRUE(!uriA.absolutePath); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort1) { // User info with ":", no port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 01 0 9 const char * const input = "http" "://" "abc:def" "@" "localhost"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == input + 4 + 3); ASSERT_TRUE(uriA.userInfo.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 7 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort2) { // User info with ":", with port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 01 0 9 const char * const input = "http" "://" "abc:def" "@" "localhost" // 01 0 3 ":" "123"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == input + 4 + 3); ASSERT_TRUE(uriA.userInfo.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 7 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9); ASSERT_TRUE(uriA.portText.first == input + 4 + 3 + 7 + 1 + 9 + 1); ASSERT_TRUE(uriA.portText.afterLast == input + 4 + 3 + 7 + 1 + 9 + 1 + 3); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort22Bug1948038) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; res = uriParseUriA(&stateA, "http://user:21@host/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "user:21", 7 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 7); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); res = uriParseUriA(&stateA, "http://user:1234@192.168.0.1:1234/foo.com"); ASSERT_TRUE(URI_SUCCESS == res); uriFreeUriMembersA(&uriA); res = uriParseUriA(&stateA, "http://moo:21@moo:21@moo/"); ASSERT_TRUE(URI_ERROR_SYNTAX == res); uriFreeUriMembersA(&uriA); res = uriParseUriA(&stateA, "http://moo:21@moo:21@moo:21/"); ASSERT_TRUE(URI_ERROR_SYNTAX == res); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198One) { // User info with ":", with port, with escaped chars in password UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 10 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "user:%2F21" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "user:%2F21", 10 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 10); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198Two) { // User info with ":", with port, with escaped chars in user name and password UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 13 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "%2Fuser:%2F21" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "%2Fuser:%2F21", 13 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 13); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198Three) { // User info with ":", with port, with escaped chars in password UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 16 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "user:!$&'()*+,;=" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "user:!$&'()*+,;=", 16 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 16); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198Four) { // User info with ":", with port, with escaped chars in user name and password UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 20 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "!$&'()*+,;=:password" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "!$&'()*+,;=:password", 20 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 20); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198RelatedOne) { // Empty user info UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(uriA.userInfo.afterLast != NULL); ASSERT_TRUE(uriA.userInfo.first != NULL); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 0); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198RelatedOneTwo) { // Empty user info UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 7 01 res = uriParseUriA(&stateA, "http" "://" "%2Fhost" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(!memcmp(uriA.hostText.first, "%2Fhost", 7 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 7); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort23Bug3510198RelatedTwo) { // Several colons in userinfo UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; int res; // 0 4 0 3 0 2 01 0 4 01 res = uriParseUriA(&stateA, "http" "://" "::" "@" "host" "/"); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(!memcmp(uriA.userInfo.first, "::", 2 * sizeof(char))); ASSERT_TRUE(uriA.userInfo.afterLast - uriA.userInfo.first == 2); ASSERT_TRUE(!memcmp(uriA.hostText.first, "host", 4 * sizeof(char))); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 4); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort3) { // User info without ":", no port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 01 0 9 const char * const input = "http" "://" "abcdefg" "@" "localhost"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == input + 4 + 3); ASSERT_TRUE(uriA.userInfo.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 7 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort4) { // User info without ":", with port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 01 0 9 const char * const input = "http" "://" "abcdefg" "@" "localhost" // 01 0 3 ":" "123"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == input + 4 + 3); ASSERT_TRUE(uriA.userInfo.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 7 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7 + 1 + 9); ASSERT_TRUE(uriA.portText.first == input + 4 + 3 + 7 + 1 + 9 + 1); ASSERT_TRUE(uriA.portText.afterLast == input + 4 + 3 + 7 + 1 + 9 + 1 + 3); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort5) { // No user info, no port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 9 const char * const input = "http" "://" "localhost"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 9); ASSERT_TRUE(uriA.portText.first == NULL); ASSERT_TRUE(uriA.portText.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriUserInfoHostPort6) { // No user info, with port UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 9 01 0 3 const char * const input = "http" "://" "localhost" ":" "123"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 9); ASSERT_TRUE(uriA.portText.first == input + 4 + 3 + 9 + 1); ASSERT_TRUE(uriA.portText.afterLast == input + 4 + 3 + 9 + 1 + 3); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostRegname) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 11 const char * const input = "http" "://" "example.com"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 11); ASSERT_TRUE(uriA.hostData.ip4 == NULL); ASSERT_TRUE(uriA.hostData.ip6 == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostIpFour1) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 01 0 2 const char * const input = "http" "://" "1.2.3.4" ":" "80"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostData.ip4 != NULL); ASSERT_TRUE(uriA.hostData.ip6 == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostIpFour2) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 0 7 const char * const input = "http" "://" "1.2.3.4"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 7); ASSERT_TRUE(uriA.hostData.ip4 != NULL); ASSERT_TRUE(uriA.hostData.ip6 == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostIpSix1) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 01 45 01 0 2 const char * const input = "http" "://" "[::1]" ":" "80"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 4); ASSERT_TRUE(uriA.hostData.ip4 == NULL); ASSERT_TRUE(uriA.hostData.ip6 != NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostIpSix2) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 01 45 const char * const input = "http" "://" "[::1]"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.hostText.first == input + 4 + 3 + 1); ASSERT_TRUE(uriA.hostText.afterLast == input + 4 + 3 + 4); ASSERT_TRUE(uriA.hostData.ip4 == NULL); ASSERT_TRUE(uriA.hostData.ip6 != NULL); ASSERT_TRUE(uriA.hostData.ipFuture.first == NULL); ASSERT_TRUE(uriA.hostData.ipFuture.afterLast == NULL); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostEmpty) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 4 0 3 01 0 3 const char * const input = "http" "://" ":" "123"; const int res = uriParseUriA(&stateA, input); ASSERT_TRUE(URI_SUCCESS == res); ASSERT_TRUE(uriA.userInfo.first == NULL); ASSERT_TRUE(uriA.userInfo.afterLast == NULL); ASSERT_TRUE(uriA.hostText.first != NULL); ASSERT_TRUE(uriA.hostText.afterLast != NULL); ASSERT_TRUE(uriA.hostText.afterLast - uriA.hostText.first == 0); ASSERT_TRUE(uriA.portText.first == input + 4 + 3 + 1); ASSERT_TRUE(uriA.portText.afterLast == input + 4 + 3 + 1 + 3); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestUriHostIpFuture) { // TODO } namespace { bool testEscapingHelper(const wchar_t * in, const wchar_t * expectedOut, bool spaceToPlus = false, bool normalizeBreaks = false) { wchar_t * const buffer = new wchar_t[(normalizeBreaks ? 6 : 3) * wcslen(in) + 1]; if (uriEscapeW(in, buffer, spaceToPlus, normalizeBreaks) != buffer + wcslen(expectedOut)) { delete [] buffer; return false; } const bool equal = !wcscmp(buffer, expectedOut); delete [] buffer; return equal; } } // namespace TEST(UriSuite, TestEscaping) { const bool SPACE_TO_PLUS = true; const bool SPACE_TO_PERCENT = false; const bool KEEP_UNMODIFIED = false; const bool NORMALIZE = true; // '+' to ' ' ASSERT_TRUE(testEscapingHelper(L"abc def", L"abc+def", SPACE_TO_PLUS)); ASSERT_TRUE(testEscapingHelper(L"abc def", L"abc%20def", SPACE_TO_PERCENT)); // Percent encoding ASSERT_TRUE(testEscapingHelper(L"\x00", L"\0")); ASSERT_TRUE(testEscapingHelper(L"\x01", L"%01")); ASSERT_TRUE(testEscapingHelper(L"\xff", L"%FF")); // Linebreak normalization ASSERT_TRUE(testEscapingHelper(L"\x0d", L"%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"g\x0d", L"g%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0dg", L"%0D%0Ag", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0d", L"%0D", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"g\x0d", L"g%0D", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0dg", L"%0Dg", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0a", L"%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"g\x0a", L"g%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0ag", L"%0D%0Ag", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0a", L"%0A", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"g\x0a", L"g%0A", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0ag", L"%0Ag", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0d\x0a", L"%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"g\x0d\x0a", L"g%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0d\x0ag", L"%0D%0Ag", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0d\x0a", L"%0D%0A", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"g\x0d\x0a", L"g%0D%0A", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0d\x0ag", L"%0D%0Ag", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0a\x0d", L"%0D%0A%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"g\x0a\x0d", L"g%0D%0A%0D%0A", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0a\x0dg", L"%0D%0A%0D%0Ag", SPACE_TO_PLUS, NORMALIZE)); ASSERT_TRUE(testEscapingHelper(L"\x0a\x0d", L"%0A%0D", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"g\x0a\x0d", L"g%0A%0D", SPACE_TO_PLUS, KEEP_UNMODIFIED)); ASSERT_TRUE(testEscapingHelper(L"\x0a\x0dg", L"%0A%0Dg", SPACE_TO_PLUS, KEEP_UNMODIFIED)); } namespace { bool testUnescapingHelper(const wchar_t * input, const wchar_t * output, bool plusToSpace = false, UriBreakConversion breakConversion = URI_BR_DONT_TOUCH) { wchar_t * working = new wchar_t[URI_STRLEN(input) + 1]; wcscpy(working, input); const wchar_t * newTermZero = uriUnescapeInPlaceExW(working, plusToSpace ? URI_TRUE : URI_FALSE, breakConversion); const bool success = ((newTermZero == working + wcslen(output)) && !wcscmp(working, output)); delete[] working; return success; } } // namespace TEST(UriSuite, TestUnescaping) { const bool PLUS_TO_SPACE = true; const bool PLUS_DONT_TOUCH = false; // Proper ASSERT_TRUE(testUnescapingHelper(L"abc%20%41BC", L"abc ABC")); ASSERT_TRUE(testUnescapingHelper(L"%20", L" ")); // Incomplete ASSERT_TRUE(testUnescapingHelper(L"%0", L"%0")); // Nonhex ASSERT_TRUE(testUnescapingHelper(L"%0g", L"%0g")); ASSERT_TRUE(testUnescapingHelper(L"%G0", L"%G0")); // No double decoding ASSERT_TRUE(testUnescapingHelper(L"%2520", L"%20")); // Decoding of '+' ASSERT_TRUE(testUnescapingHelper(L"abc+def", L"abc+def", PLUS_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"abc+def", L"abc def", PLUS_TO_SPACE)); // Line break conversion ASSERT_TRUE(testUnescapingHelper(L"%0d", L"\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d", L"\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d", L"\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d", L"\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0d", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0d", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0d", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0d", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a", L"\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a", L"\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a", L"\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a", L"\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0a", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0a", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0a", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0a", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a", L"\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a", L"\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a", L"\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a", L"\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0a", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0a", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0a", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0a", L"\x0d\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d", L"\x0d\x0a\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d%0a", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d%0a", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d%0a", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0d%0a%0d%0a", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d", L"\x0a\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a", L"\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a", L"\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a", L"\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a", L"\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0d", L"\x0a\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0d", L"\x0d\x0a\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0d", L"\x0d\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0d", L"\x0a\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a%0d", L"\x0a\x0a\x0a", PLUS_DONT_TOUCH, URI_BR_TO_UNIX)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a%0d", L"\x0d\x0a\x0d\x0a\x0d\x0a", PLUS_DONT_TOUCH, URI_BR_TO_WINDOWS)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a%0d", L"\x0d\x0d\x0d", PLUS_DONT_TOUCH, URI_BR_TO_MAC)); ASSERT_TRUE(testUnescapingHelper(L"%0a%0d%0a%0d", L"\x0a\x0d\x0a\x0d", PLUS_DONT_TOUCH, URI_BR_DONT_TOUCH)); } namespace { bool testAddBaseHelper(const wchar_t * base, const wchar_t * rel, const wchar_t * expectedResult, bool backward_compatibility = false) { UriParserStateW stateW; // Base UriUriW baseUri; stateW.uri = &baseUri; int res = uriParseUriW(&stateW, base); if (res != 0) { uriFreeUriMembersW(&baseUri); return false; } // Rel UriUriW relUri; stateW.uri = &relUri; res = uriParseUriW(&stateW, rel); if (res != 0) { uriFreeUriMembersW(&baseUri); uriFreeUriMembersW(&relUri); return false; } // Expected result UriUriW expectedUri; stateW.uri = &expectedUri; res = uriParseUriW(&stateW, expectedResult); if (res != 0) { uriFreeUriMembersW(&baseUri); uriFreeUriMembersW(&relUri); uriFreeUriMembersW(&expectedUri); return false; } // Transform UriUriW transformedUri; if (backward_compatibility) { res = uriAddBaseUriExW(&transformedUri, &relUri, &baseUri, URI_RESOLVE_IDENTICAL_SCHEME_COMPAT); } else { res = uriAddBaseUriW(&transformedUri, &relUri, &baseUri); } if (res != 0) { uriFreeUriMembersW(&baseUri); uriFreeUriMembersW(&relUri); uriFreeUriMembersW(&expectedUri); uriFreeUriMembersW(&transformedUri); return false; } const bool equal = (URI_TRUE == uriEqualsUriW(&transformedUri, &expectedUri)); if (!equal) { wchar_t transformedUriText[1024 * 8]; wchar_t expectedUriText[1024 * 8]; uriToStringW(transformedUriText, &transformedUri, 1024 * 8, NULL); uriToStringW(expectedUriText, &expectedUri, 1024 * 8, NULL); #ifdef HAVE_WPRINTF wprintf(L"\n\n\nExpected: \"%s\"\nReceived: \"%s\"\n\n\n", expectedUriText, transformedUriText); #endif } uriFreeUriMembersW(&baseUri); uriFreeUriMembersW(&relUri); uriFreeUriMembersW(&expectedUri); uriFreeUriMembersW(&transformedUri); return equal; } } // namespace TEST(UriSuite, TestTrailingSlash) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; // 0 3 01 const char * const input = "abc" "/"; ASSERT_TRUE(0 == uriParseUriA(&stateA, input)); ASSERT_TRUE(uriA.pathHead->text.first == input); ASSERT_TRUE(uriA.pathHead->text.afterLast == input + 3); ASSERT_TRUE(uriA.pathHead->next->text.first == uriA.pathHead->next->text.afterLast); ASSERT_TRUE(uriA.pathHead->next->next == NULL); ASSERT_TRUE(uriA.pathTail == uriA.pathHead->next); uriFreeUriMembersA(&uriA); } TEST(UriSuite, TestAddBase) { // 5.4.1. Normal Examples ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g:h", L"g:h")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g", L"http://a/b/c/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"./g", L"http://a/b/c/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g/", L"http://a/b/c/g/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"/g", L"http://a/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"//g", L"http://g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"?y", L"http://a/b/c/d;p?y")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g?y", L"http://a/b/c/g?y")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"#s", L"http://a/b/c/d;p?q#s")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g#s", L"http://a/b/c/g#s")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g?y#s", L"http://a/b/c/g?y#s")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L";x", L"http://a/b/c/;x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g;x", L"http://a/b/c/g;x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g;x?y#s", L"http://a/b/c/g;x?y#s")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"", L"http://a/b/c/d;p?q")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L".", L"http://a/b/c/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"./", L"http://a/b/c/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"..", L"http://a/b/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../", L"http://a/b/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../g", L"http://a/b/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../..", L"http://a/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../", L"http://a/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../g", L"http://a/g")); // 5.4.2. Abnormal Examples ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../../g", L"http://a/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../../../g", L"http://a/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"/./g", L"http://a/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"/../g", L"http://a/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g.", L"http://a/b/c/g.")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L".g", L"http://a/b/c/.g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g..", L"http://a/b/c/g..")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"..g", L"http://a/b/c/..g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"./../g", L"http://a/b/g")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"./g/.", L"http://a/b/c/g/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g/./h", L"http://a/b/c/g/h")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g/../h", L"http://a/b/c/h")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g;x=1/./y", L"http://a/b/c/g;x=1/y")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g;x=1/../y", L"http://a/b/c/y")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g?y/./x", L"http://a/b/c/g?y/./x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g?y/../x", L"http://a/b/c/g?y/../x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g#s/./x", L"http://a/b/c/g#s/./x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"g#s/../x", L"http://a/b/c/g#s/../x")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"http:g", L"http:g")); // Backward compatibility (feature request #4, RFC3986 5.4.2) ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"http:g", L"http:g", false)); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"http:g", L"http://a/b/c/g", true)); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"http:g?q#f", L"http://a/b/c/g?q#f", true)); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"other:g?q#f", L"other:g?q#f", true)); // Bug related to absolutePath flag set despite presence of host ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"/", L"http://a/")); ASSERT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"/g/", L"http://a/g/")); // GitHub issue #92 EXPECT_TRUE(testAddBaseHelper(L"http://a/b/c/../d;p?q", L"../..", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/b/c/../d;p?q", L"../../", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/b/../c/d;p?q", L"../..", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/b/../c/d;p?q", L"../../", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/../b/c/d;p?q", L"../..", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/../b/c/d;p?q", L"../../", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../..", L"http://a/")); EXPECT_TRUE(testAddBaseHelper(L"http://a/b/c/d;p?q", L"../../../", L"http://a/")); } namespace { bool testToStringHelper(const wchar_t * text) { // Parse UriParserStateW state; UriUriW uri; state.uri = &uri; int res = uriParseUriW(&state, text); if (res != 0) { uriFreeUriMembersW(&uri); return false; } // Back to string, _huge_ limit wchar_t shouldbeTheSame[1024 * 8]; res = uriToStringW(shouldbeTheSame, &uri, 1024 * 8, NULL); if (res != 0) { uriFreeUriMembersW(&uri); return false; } // Compare bool equals = (0 == wcscmp(shouldbeTheSame, text)); if (!equals) { #ifdef HAVE_WPRINTF wprintf(L"\n\n\nExpected: \"%s\"\nReceived: \"%s\"\n\n\n", text, shouldbeTheSame); #endif } // Back to string, _exact_ limit const int len = static_cast<int>(wcslen(text)); int charsWritten; res = uriToStringW(shouldbeTheSame, &uri, len + 1, &charsWritten); if ((res != 0) || (charsWritten != len + 1)) { uriFreeUriMembersW(&uri); return false; } // Back to string, _too small_ limit res = uriToStringW(shouldbeTheSame, &uri, len, &charsWritten); if ((res == 0) || (charsWritten >= len + 1)) { uriFreeUriMembersW(&uri); return false; } uriFreeUriMembersW(&uri); return equals; } } // namespace TEST(UriSuite, TestToString) { // Scheme ASSERT_TRUE(testToStringHelper(L"ftp://localhost/")); // UserInfo ASSERT_TRUE(testToStringHelper(L"http://user:pass@localhost/")); // IPv4 ASSERT_TRUE(testToStringHelper(L"http://123.0.1.255/")); // IPv6 ASSERT_TRUE(testToStringHelper(L"http://[abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd]/")); // IPvFuture ASSERT_TRUE(testToStringHelper(L"http://[vA.123456]/")); // Port ASSERT_TRUE(testToStringHelper(L"http://example.com:123/")); // Path ASSERT_TRUE(testToStringHelper(L"http://example.com")); ASSERT_TRUE(testToStringHelper(L"http://example.com/")); ASSERT_TRUE(testToStringHelper(L"http://example.com/abc/")); ASSERT_TRUE(testToStringHelper(L"http://example.com/abc/def")); ASSERT_TRUE(testToStringHelper(L"http://example.com/abc/def/")); ASSERT_TRUE(testToStringHelper(L"http://example.com//")); ASSERT_TRUE(testToStringHelper(L"http://example.com/./..")); // Query ASSERT_TRUE(testToStringHelper(L"http://example.com/?abc")); // Fragment ASSERT_TRUE(testToStringHelper(L"http://example.com/#abc")); ASSERT_TRUE(testToStringHelper(L"http://example.com/?def#abc")); // Relative ASSERT_TRUE(testToStringHelper(L"a")); ASSERT_TRUE(testToStringHelper(L"a/")); ASSERT_TRUE(testToStringHelper(L"/a")); ASSERT_TRUE(testToStringHelper(L"/a/")); ASSERT_TRUE(testToStringHelper(L"abc")); ASSERT_TRUE(testToStringHelper(L"abc/")); ASSERT_TRUE(testToStringHelper(L"/abc")); ASSERT_TRUE(testToStringHelper(L"/abc/")); ASSERT_TRUE(testToStringHelper(L"a/def")); ASSERT_TRUE(testToStringHelper(L"a/def/")); ASSERT_TRUE(testToStringHelper(L"/a/def")); ASSERT_TRUE(testToStringHelper(L"/a/def/")); ASSERT_TRUE(testToStringHelper(L"abc/def")); ASSERT_TRUE(testToStringHelper(L"abc/def/")); ASSERT_TRUE(testToStringHelper(L"/abc/def")); ASSERT_TRUE(testToStringHelper(L"/abc/def/")); ASSERT_TRUE(testToStringHelper(L"/")); ASSERT_TRUE(testToStringHelper(L"//a/")); ASSERT_TRUE(testToStringHelper(L".")); ASSERT_TRUE(testToStringHelper(L"./")); ASSERT_TRUE(testToStringHelper(L"/.")); ASSERT_TRUE(testToStringHelper(L"/./")); ASSERT_TRUE(testToStringHelper(L"")); ASSERT_TRUE(testToStringHelper(L"./abc/def")); ASSERT_TRUE(testToStringHelper(L"?query")); ASSERT_TRUE(testToStringHelper(L"#fragment")); ASSERT_TRUE(testToStringHelper(L"?query#fragment")); // Tests for bugs from the past ASSERT_TRUE(testToStringHelper(L"f:/.//g")); } TEST(UriSuite, TestToStringBug1950126) { UriParserStateW state; UriUriW uriOne; UriUriW uriTwo; const wchar_t * const uriOneString = L"http://e.com/"; const wchar_t * const uriTwoString = L"http://e.com"; state.uri = &uriOne; ASSERT_TRUE(URI_SUCCESS == uriParseUriW(&state, uriOneString)); state.uri = &uriTwo; ASSERT_TRUE(URI_SUCCESS == uriParseUriW(&state, uriTwoString)); ASSERT_TRUE(URI_FALSE == uriEqualsUriW(&uriOne, &uriTwo)); uriFreeUriMembersW(&uriOne); uriFreeUriMembersW(&uriTwo); ASSERT_TRUE(testToStringHelper(uriOneString)); ASSERT_TRUE(testToStringHelper(uriTwoString)); } namespace { bool testToStringCharsRequiredHelper(const wchar_t * text) { // Parse UriParserStateW state; UriUriW uri; state.uri = &uri; int res = uriParseUriW(&state, text); if (res != 0) { uriFreeUriMembersW(&uri); return false; } // Required space? int charsRequired; if (uriToStringCharsRequiredW(&uri, &charsRequired) != 0) { uriFreeUriMembersW(&uri); return false; } EXPECT_EQ(charsRequired, wcslen(text)); // Minimum wchar_t * buffer = new wchar_t[charsRequired + 1]; if (uriToStringW(buffer, &uri, charsRequired + 1, NULL) != 0) { uriFreeUriMembersW(&uri); delete [] buffer; return false; } // One less than minimum if (uriToStringW(buffer, &uri, charsRequired, NULL) == 0) { uriFreeUriMembersW(&uri); delete [] buffer; return false; } uriFreeUriMembersW(&uri); delete [] buffer; return true; } } // namespace TEST(UriSuite, TestToStringCharsRequired) { EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.1.1.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://12.1.1.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://123.1.1.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.12.1.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.123.1.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.1.12.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.1.123.1/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.1.1.12/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://1.1.1.123/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com:80/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://user:pass@www.example.com/")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com/index.html")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com/?abc")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com/#def")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"http://www.example.com/?abc#def")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"/test")); EXPECT_TRUE(testToStringCharsRequiredHelper(L"test")); } namespace { bool testNormalizeMaskHelper(const wchar_t * uriText, unsigned int expectedMask) { UriParserStateW state; UriUriW uri; state.uri = &uri; int res = uriParseUriW(&state, uriText); if (res != 0) { uriFreeUriMembersW(&uri); return false; } const unsigned int maskBefore = uriNormalizeSyntaxMaskRequiredW(&uri); if (maskBefore != expectedMask) { uriFreeUriMembersW(&uri); return false; } res = uriNormalizeSyntaxW(&uri); if (res != 0) { uriFreeUriMembersW(&uri); return false; } const unsigned int maskAfter = uriNormalizeSyntaxMaskRequiredW(&uri); uriFreeUriMembersW(&uri); // Second call should be no problem uriFreeUriMembersW(&uri); return (maskAfter == URI_NORMALIZED); } } // namespace TEST(UriSuite, TestNormalizeSyntaxMaskRequired) { ASSERT_TRUE(testNormalizeMaskHelper(L"http://localhost/", URI_NORMALIZED)); ASSERT_TRUE(testNormalizeMaskHelper(L"httP://localhost/", URI_NORMALIZE_SCHEME)); ASSERT_TRUE(testNormalizeMaskHelper(L"http://%0d@localhost/", URI_NORMALIZE_USER_INFO)); ASSERT_TRUE(testNormalizeMaskHelper(L"http://localhosT/", URI_NORMALIZE_HOST)); ASSERT_TRUE(testNormalizeMaskHelper(L"http://localhost/./abc", URI_NORMALIZE_PATH)); ASSERT_TRUE(testNormalizeMaskHelper(L"http://localhost/?AB%43", URI_NORMALIZE_QUERY)); ASSERT_TRUE(testNormalizeMaskHelper(L"http://localhost/#AB%43", URI_NORMALIZE_FRAGMENT)); } namespace { bool testNormalizeSyntaxHelper(const wchar_t * uriText, const wchar_t * expectedNormalized, unsigned int mask = static_cast<unsigned int>(-1)) { UriParserStateW stateW; int res; UriUriW testUri; stateW.uri = &testUri; res = uriParseUriW(&stateW, uriText); if (res != 0) { uriFreeUriMembersW(&testUri); return false; } // Expected result UriUriW expectedUri; stateW.uri = &expectedUri; res = uriParseUriW(&stateW, expectedNormalized); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } // First run res = uriNormalizeSyntaxExW(&testUri, mask); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } bool equalAfter = (URI_TRUE == uriEqualsUriW(&testUri, &expectedUri)); // Second run res = uriNormalizeSyntaxExW(&testUri, mask); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } equalAfter = equalAfter && (URI_TRUE == uriEqualsUriW(&testUri, &expectedUri)); uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return equalAfter; } } // namespace TEST(UriSuite, TestNormalizeSyntax) { ASSERT_TRUE(testNormalizeSyntaxHelper( L"eXAMPLE://a/./b/../b/%63/%7bfoo%7d", L"example://a/b/c/%7Bfoo%7D")); // Testcase by Adrian Manrique ASSERT_TRUE(testNormalizeSyntaxHelper( L"http://examp%4Ce.com/", L"http://example.com/")); // Testcase by Adrian Manrique ASSERT_TRUE(testNormalizeSyntaxHelper( L"http://example.com/a/b/%2E%2E/", L"http://example.com/a/")); // Reported by Adrian Manrique ASSERT_TRUE(testNormalizeSyntaxHelper( L"http://user:pass@SOMEHOST.COM:123", L"http://user:pass@somehost.com:123")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://a:b@HOST:123/./1/2/../%41?abc#def", L"http://a:b@host:123/1/A?abc#def")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"../../abc", L"../../abc")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"../../abc/..", L"../../")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"../../abc/../def", L"../../def")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"abc/..", L"")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"abc/../", L"")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"../../abc/./def", L"../../abc/def")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"./def", L"def")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"def/.", L"def/")); ASSERT_TRUE(testNormalizeSyntaxHelper( L"./abc:def", L"./abc:def")); } TEST(UriSuite, TestNormalizeSyntaxComponents) { ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"http://%41@EXAMPLE.ORG/../a?%41#%41", URI_NORMALIZE_SCHEME)); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"HTTP://A@EXAMPLE.ORG/../a?%41#%41", URI_NORMALIZE_USER_INFO)); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"HTTP://%41@example.org/../a?%41#%41", URI_NORMALIZE_HOST)); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"HTTP://%41@EXAMPLE.ORG/a?%41#%41", URI_NORMALIZE_PATH)); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"HTTP://%41@EXAMPLE.ORG/../a?A#%41", URI_NORMALIZE_QUERY)); ASSERT_TRUE(testNormalizeSyntaxHelper( L"HTTP://%41@EXAMPLE.ORG/../a?%41#%41", L"HTTP://%41@EXAMPLE.ORG/../a?%41#A", URI_NORMALIZE_FRAGMENT)); } TEST(UriSuite, TestNormalizeSyntaxPath) { // These are from GitHub issue #92 EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/b/c/../../..", L"http://a/", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/b/../c/../..", L"http://a/", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/b/c/../../..", L"http://a/", URI_NORMALIZE_PATH)); // .. and these are related EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/..", L"http://a/", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"/..", L"/", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/..///", L"http://a///", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"http://a/..///..", L"http://a//", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"a/b/c/../../..", L"", URI_NORMALIZE_PATH)); EXPECT_TRUE(testNormalizeSyntaxHelper( L"a/b/../../c/..", L"", URI_NORMALIZE_PATH)); } TEST(UriSuite, TestNormalizeCrashBug20080224) { UriParserStateW stateW; int res; UriUriW testUri; stateW.uri = &testUri; res = uriParseUriW(&stateW, L"http://example.org/abc//../def"); ASSERT_TRUE(res == 0); // First call will make us owner of copied memory res = uriNormalizeSyntaxExW(&testUri, URI_NORMALIZE_SCHEME); ASSERT_TRUE(res == 0); res = uriNormalizeSyntaxExW(&testUri, URI_NORMALIZE_HOST); ASSERT_TRUE(res == 0); // Frees empty path segment -> crash res = uriNormalizeSyntaxW(&testUri); ASSERT_TRUE(res == 0); uriFreeUriMembersW(&testUri); } namespace { void testFilenameUriConversionHelper(const wchar_t * filename, const wchar_t * uriString, bool forUnix, const wchar_t * expectedUriString = NULL) { const int prefixLen = forUnix ? 7 : 8; if (! expectedUriString) { expectedUriString = uriString; } // Filename to URI string const size_t uriBufferLen = prefixLen + 3 * wcslen(filename) + 1; wchar_t * uriBuffer = new wchar_t[uriBufferLen]; if (forUnix) { uriUnixFilenameToUriStringW(filename, uriBuffer); } else { uriWindowsFilenameToUriStringW(filename, uriBuffer); } #ifdef HAVE_WPRINTF // wprintf(L"1 [%s][%s]\n", uriBuffer, expectedUriString); #endif ASSERT_TRUE(!wcscmp(uriBuffer, expectedUriString)); delete [] uriBuffer; // URI string to filename const size_t filenameBufferLen = wcslen(uriString) + 1; wchar_t * filenameBuffer = new wchar_t[filenameBufferLen]; if (forUnix) { uriUriStringToUnixFilenameW(uriString, filenameBuffer); } else { uriUriStringToWindowsFilenameW(uriString, filenameBuffer); } #ifdef HAVE_WPRINTF // wprintf(L"2 [%s][%s]\n", filenameBuffer, filename); #endif ASSERT_TRUE(!wcscmp(filenameBuffer, filename)); delete [] filenameBuffer; } } // namespace TEST(UriSuite, TestFilenameUriConversion) { const bool FOR_UNIX = true; const bool FOR_WINDOWS = false; testFilenameUriConversionHelper(L"/bin/bash", L"file:///bin/bash", FOR_UNIX); testFilenameUriConversionHelper(L"/bin/bash", L"file:/bin/bash", FOR_UNIX, L"file:///bin/bash"); testFilenameUriConversionHelper(L"./configure", L"./configure", FOR_UNIX); testFilenameUriConversionHelper(L"E:\\Documents and Settings", L"file:///E:/Documents%20and%20Settings", FOR_WINDOWS); testFilenameUriConversionHelper(L"c:\\path\\to\\file.txt", L"file:c:/path/to/file.txt", FOR_WINDOWS, L"file:///c:/path/to/file.txt"); testFilenameUriConversionHelper(L".\\Readme.txt", L"./Readme.txt", FOR_WINDOWS); testFilenameUriConversionHelper(L"index.htm", L"index.htm", FOR_WINDOWS); testFilenameUriConversionHelper(L"index.htm", L"index.htm", FOR_UNIX); testFilenameUriConversionHelper(L"abc def", L"abc%20def", FOR_WINDOWS); testFilenameUriConversionHelper(L"abc def", L"abc%20def", FOR_UNIX); testFilenameUriConversionHelper(L"\\\\Server01\\user\\docs\\Letter.txt", L"file://Server01/user/docs/Letter.txt", FOR_WINDOWS); } TEST(UriSuite, TestCrashFreeUriMembersBug20080116) { // Testcase by Adrian Manrique UriParserStateA state; UriUriA uri; state.uri = &uri; uriParseUriA(&state, "http://test/?"); uriNormalizeSyntaxA(&uri); uriFreeUriMembersA(&uri); ASSERT_TRUE(true); } namespace { void helperTestQueryString(char const * uriString, int pairsExpected); } TEST(UriSuite, TestCrashReport2418192) { // Testcase by Harvey Vrsalovic helperTestQueryString("http://svcs.cnn.com/weather/wrapper.jsp?&csiID=csi1", 1); } TEST(UriSuite, TestPervertedQueryString) { helperTestQueryString("http://example.org/?&&=&&&=&&&&==&===&====", 5); } TEST(UriSuite, TestQueryStringEndingInEqualSignNonBug32) { const char * queryString = "firstname=sdsd&lastname="; UriQueryListA * queryList = NULL; int itemCount = 0; const int res = uriDissectQueryMallocA(&queryList, &itemCount, queryString, queryString + strlen(queryString)); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(itemCount == 2); ASSERT_TRUE(queryList != NULL); ASSERT_TRUE(strcmp(queryList->key, "firstname") == 0); ASSERT_TRUE(strcmp(queryList->value, "sdsd") == 0); ASSERT_TRUE(strcmp(queryList->next->key, "lastname") == 0); ASSERT_TRUE(strcmp(queryList->next->value, "") == 0); ASSERT_TRUE(queryList->next->next == NULL); uriFreeQueryListA(queryList); } namespace { void helperTestQueryString(char const * uriString, int pairsExpected) { UriParserStateA state; UriUriA uri; state.uri = &uri; int res = uriParseUriA(&state, uriString); ASSERT_TRUE(res == URI_SUCCESS); UriQueryListA * queryList = NULL; int itemCount = 0; res = uriDissectQueryMallocA(&queryList, &itemCount, uri.query.first, uri.query.afterLast); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(queryList != NULL); ASSERT_TRUE(itemCount == pairsExpected); uriFreeQueryListA(queryList); uriFreeUriMembersA(&uri); } } // namespace TEST(UriSuite, TestCrashMakeOwnerBug20080207) { // Testcase by Adrian Manrique UriParserStateA state; UriUriA sourceUri; state.uri = &sourceUri; const char * const sourceUriString = "http://user:pass@somehost.com:80/"; if (uriParseUriA(&state, sourceUriString) != 0) { ASSERT_TRUE(false); } if (uriNormalizeSyntaxA(&sourceUri) != 0) { ASSERT_TRUE(false); } uriFreeUriMembersA(&sourceUri); ASSERT_TRUE(true); } namespace { void testQueryListHelper(const wchar_t * input, int expectedItemCount) { int res; UriBool spacePlusConversion = URI_TRUE; UriBool normalizeBreaks = URI_FALSE; UriBreakConversion breakConversion = URI_BR_DONT_TOUCH; int itemCount; UriQueryListW * queryList; res = uriDissectQueryMallocExW(&queryList, &itemCount, input, input + wcslen(input), spacePlusConversion, breakConversion); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(itemCount == expectedItemCount); ASSERT_TRUE((queryList == NULL) == (expectedItemCount == 0)); if (expectedItemCount != 0) { // First int charsRequired; res = uriComposeQueryCharsRequiredExW(queryList, &charsRequired, spacePlusConversion, normalizeBreaks); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(charsRequired >= (int)wcslen(input)); wchar_t * recomposed = new wchar_t[charsRequired + 1]; int charsWritten; res = uriComposeQueryExW(recomposed, queryList, charsRequired + 1, &charsWritten, spacePlusConversion, normalizeBreaks); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(charsWritten <= charsRequired); ASSERT_TRUE(charsWritten == (int)wcslen(input) + 1); ASSERT_TRUE(!wcscmp(input, recomposed)); delete [] recomposed; recomposed = NULL; res = uriComposeQueryMallocW(&recomposed, queryList); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(recomposed != NULL); ASSERT_TRUE(charsWritten == (int)wcslen(input) + 1); ASSERT_TRUE(!wcscmp(input, recomposed)); free(recomposed); } uriFreeQueryListW(queryList); } } // namespace TEST(UriSuite, QueryList) { testQueryListHelper(L"one=ONE&two=TWO", 2); testQueryListHelper(L"one=ONE&two=&three=THREE", 3); testQueryListHelper(L"one=ONE&two&three=THREE", 3); testQueryListHelper(L"one=ONE", 1); testQueryListHelper(L"one", 1); testQueryListHelper(L"", 0); } namespace { void testQueryListPairHelper(const char * pair, const char * unescapedKey, const char * unescapedValue, const char * fixed = NULL) { int res; UriQueryListA * queryList; int itemCount; res = uriDissectQueryMallocA(&queryList, &itemCount, pair, pair + strlen(pair)); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(queryList != NULL); ASSERT_TRUE(itemCount == 1); ASSERT_TRUE(!strcmp(queryList->key, unescapedKey)); ASSERT_TRUE(!strcmp(queryList->value, unescapedValue)); char * recomposed; res = uriComposeQueryMallocA(&recomposed, queryList); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(recomposed != NULL); ASSERT_TRUE(!strcmp(recomposed, (fixed != NULL) ? fixed : pair)); free(recomposed); uriFreeQueryListA(queryList); } } // namespace TEST(UriSuite, TestQueryListPair) { testQueryListPairHelper("one+two+%26+three=%2B", "one two & three", "+"); testQueryListPairHelper("one=two=three", "one", "two=three", "one=two%3Dthree"); testQueryListPairHelper("one=two=three=four", "one", "two=three=four", "one=two%3Dthree%3Dfour"); } TEST(UriSuite, TestQueryDissectionBug3590761) { int res; UriQueryListA * queryList; int itemCount; const char * const pair = "q=hello&x=&y="; res = uriDissectQueryMallocA(&queryList, &itemCount, pair, pair + strlen(pair)); ASSERT_TRUE(res == URI_SUCCESS); ASSERT_TRUE(queryList != NULL); ASSERT_TRUE(itemCount == 3); ASSERT_TRUE(!strcmp(queryList->key, "q")); ASSERT_TRUE(!strcmp(queryList->value, "hello")); ASSERT_TRUE(!strcmp(queryList->next->key, "x")); ASSERT_TRUE(!strcmp(queryList->next->value, "")); ASSERT_TRUE(!strcmp(queryList->next->next->key, "y")); ASSERT_TRUE(!strcmp(queryList->next->next->value, "")); ASSERT_TRUE(! queryList->next->next->next); uriFreeQueryListA(queryList); } TEST(UriSuite, TestQueryCompositionMathCalc) { UriQueryListA second = { /*.key =*/ "k2", /*.value =*/ "v2", /*.next =*/ NULL }; UriQueryListA first = { /*.key =*/ "k1", /*.value =*/ "v1", /*.next =*/ &second }; int charsRequired; ASSERT_TRUE(uriComposeQueryCharsRequiredA(&first, &charsRequired) == URI_SUCCESS); const int FACTOR = 6; /* due to escaping with normalizeBreaks */ ASSERT_TRUE((unsigned)charsRequired == FACTOR * strlen(first.key) + 1 + FACTOR * strlen(first.value) + 1 + FACTOR * strlen(second.key) + 1 + FACTOR * strlen(second.value) ); } TEST(UriSuite, TestQueryCompositionMathWriteGoogleAutofuzz113244572) { UriQueryListA second = { /*.key =*/ "\x11", /*.value =*/ NULL, /*.next =*/ NULL }; UriQueryListA first = { /*.key =*/ "\x01", /*.value =*/ "\x02", /*.next =*/ &second }; const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_FALSE; /* for factor 3 but 6 */ const int charsRequired = (3 + 1 + 3) + 1 + (3); { // Minimum space to hold everything fine const char * const expected = "%01=%02" "&" "%11"; char dest[charsRequired + 1]; int charsWritten; ASSERT_TRUE(uriComposeQueryExA(dest, &first, sizeof(dest), &charsWritten, spaceToPlus, normalizeBreaks) == URI_SUCCESS); ASSERT_TRUE(! strcmp(dest, expected)); ASSERT_TRUE(charsWritten == strlen(expected) + 1); } { // Previous math failed to take ampersand into account char dest[charsRequired + 1 - 1]; int charsWritten; ASSERT_TRUE(uriComposeQueryExA(dest, &first, sizeof(dest), &charsWritten, spaceToPlus, normalizeBreaks) == URI_ERROR_OUTPUT_TOO_LARGE); } } TEST(UriSuite, TestFreeCrashBug20080827) { char const * const sourceUri = "abc"; char const * const baseUri = "http://www.example.org/"; int res; UriParserStateA state; UriUriA absoluteDest; UriUriA relativeSource; UriUriA absoluteBase; state.uri = &relativeSource; res = uriParseUriA(&state, sourceUri); ASSERT_TRUE(res == URI_SUCCESS); state.uri = &absoluteBase; res = uriParseUriA(&state, baseUri); ASSERT_TRUE(res == URI_SUCCESS); res = uriRemoveBaseUriA(&absoluteDest, &relativeSource, &absoluteBase, URI_FALSE); ASSERT_TRUE(res == URI_ERROR_REMOVEBASE_REL_SOURCE); uriFreeUriMembersA(&relativeSource); uriFreeUriMembersA(&absoluteBase); uriFreeUriMembersA(&absoluteDest); // Crashed here } TEST(UriSuite, TestInvalidInputBug16) { UriParserStateA stateA; UriUriA uriA; stateA.uri = &uriA; const char * const input = "A>B"; const int res = uriParseUriA(&stateA, input); ASSERT_TRUE(res == URI_ERROR_SYNTAX); ASSERT_TRUE(stateA.errorPos == input + 1); ASSERT_TRUE(stateA.errorCode == URI_ERROR_SYNTAX); /* failed previously */ uriFreeUriMembersA(&uriA); } namespace { void testEqualsHelper(const char * uri_to_test) { UriParserStateA state; UriUriA uriOne; UriUriA uriTwo; state.uri = &uriOne; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, uri_to_test)); state.uri = &uriTwo; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, uri_to_test)); ASSERT_TRUE(URI_TRUE == uriEqualsUriA(&uriOne, &uriTwo)); uriFreeUriMembersA(&uriOne); uriFreeUriMembersA(&uriTwo); } } // namespace TEST(UriSuite, TestEquals) { testEqualsHelper("http://host"); testEqualsHelper("http://host:123"); testEqualsHelper("http://foo:bar@host:123"); testEqualsHelper("http://foo:bar@host:123/"); testEqualsHelper("http://foo:bar@host:123/path"); testEqualsHelper("http://foo:bar@host:123/path?query"); testEqualsHelper("http://foo:bar@host:123/path?query#fragment"); testEqualsHelper("path"); testEqualsHelper("/path"); testEqualsHelper("/path/"); testEqualsHelper("//path/"); testEqualsHelper("//host"); testEqualsHelper("//host:123"); } TEST(UriSuite, TestHostTextTerminationIssue15) { UriParserStateA state; UriUriA uri; state.uri = &uri; // Empty host and port const char * const emptyHostWithPortUri = "//:123"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, emptyHostWithPortUri)); ASSERT_TRUE(uri.hostText.first == emptyHostWithPortUri + strlen("//")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + 0); ASSERT_TRUE(uri.portText.first == emptyHostWithPortUri + strlen("//:")); ASSERT_TRUE(uri.portText.afterLast == uri.portText.first + strlen("123")); uriFreeUriMembersA(&uri); // Non-empty host and port const char * const hostWithPortUri = "//h:123"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, hostWithPortUri)); ASSERT_TRUE(uri.hostText.first == hostWithPortUri + strlen("//")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + strlen("h")); ASSERT_TRUE(uri.portText.first == hostWithPortUri + strlen("//h:")); ASSERT_TRUE(uri.portText.afterLast == uri.portText.first + strlen("123")); uriFreeUriMembersA(&uri); // Empty host, empty user info const char * const emptyHostEmptyUserInfoUri = "//@"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, emptyHostEmptyUserInfoUri)); ASSERT_TRUE(uri.userInfo.first == emptyHostEmptyUserInfoUri + strlen("//")); ASSERT_TRUE(uri.userInfo.afterLast == uri.userInfo.first + 0); ASSERT_TRUE(uri.hostText.first == emptyHostEmptyUserInfoUri + strlen("//@")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + 0); uriFreeUriMembersA(&uri); // Non-empty host, empty user info const char * const hostEmptyUserInfoUri = "//@h"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, hostEmptyUserInfoUri)); ASSERT_TRUE(uri.userInfo.first == hostEmptyUserInfoUri + strlen("//")); ASSERT_TRUE(uri.userInfo.afterLast == uri.userInfo.first + 0); ASSERT_TRUE(uri.hostText.first == hostEmptyUserInfoUri + strlen("//@")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + strlen("h")); uriFreeUriMembersA(&uri); // Empty host, non-empty user info const char * const emptyHostWithUserInfoUri = "//:@"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, emptyHostWithUserInfoUri)); ASSERT_TRUE(uri.userInfo.first == emptyHostWithUserInfoUri + strlen("//")); ASSERT_TRUE(uri.userInfo.afterLast == uri.userInfo.first + 1); ASSERT_TRUE(uri.hostText.first == emptyHostWithUserInfoUri + strlen("//:@")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + 0); uriFreeUriMembersA(&uri); // Exact case from issue #15 const char * const issue15Uri = "//:%aa@"; ASSERT_TRUE(URI_SUCCESS == uriParseUriA(&state, issue15Uri)); ASSERT_TRUE(uri.userInfo.first == issue15Uri + strlen("//")); ASSERT_TRUE(uri.userInfo.afterLast == uri.userInfo.first + strlen(":%aa")); ASSERT_TRUE(uri.hostText.first == issue15Uri + strlen("//:%aa@")); ASSERT_TRUE(uri.hostText.afterLast == uri.hostText.first + 0); uriFreeUriMembersA(&uri); } namespace { void testCompareRangeHelper(const char * a, const char * b, int expected, bool avoidNullRange = true) { UriTextRangeA ra; UriTextRangeA rb; if (a) { ra.first = a; ra.afterLast = a + strlen(a); } else { ra.first = NULL; ra.afterLast = NULL; } if (b) { rb.first = b; rb.afterLast = b + strlen(b); } else { rb.first = NULL; rb.afterLast = NULL; } const int received = uriCompareRangeA( ((a == NULL) && avoidNullRange) ? NULL : &ra, ((b == NULL) && avoidNullRange) ? NULL : &rb); if (received != expected) { printf("Comparing <%s> to <%s> yields %d, expected %d.\n", a, b, received, expected); } ASSERT_TRUE(received == expected); } } // namespace TEST(UriSuite, TestRangeComparison) { testCompareRangeHelper("", "", 0); testCompareRangeHelper("a", "", 1); testCompareRangeHelper("", "a", -1); testCompareRangeHelper("a", "a", 0); testCompareRangeHelper("a", "b", -1); testCompareRangeHelper("b", "a", 1); testCompareRangeHelper("a", "aa", -1); testCompareRangeHelper("aa", "a", 1); // Fixed with 0.8.1: testCompareRangeHelper(NULL, "a", -1); testCompareRangeHelper("a", NULL, 1); testCompareRangeHelper(NULL, NULL, 0); // Fixed with 0.8.3 const bool KEEP_NULL_RANGE = false; const bool AVOID_NULL_RANGE = true; testCompareRangeHelper(NULL, "", -1, AVOID_NULL_RANGE); testCompareRangeHelper(NULL, "", -1, KEEP_NULL_RANGE); testCompareRangeHelper("", NULL, 1, AVOID_NULL_RANGE); testCompareRangeHelper("", NULL, 1, KEEP_NULL_RANGE); } namespace { void testRemoveBaseUriHelper(const char * expected, const char * absSourceStr, const char * absBaseStr) { UriParserStateA state; UriUriA absSource; UriUriA absBase; UriUriA dest; state.uri = &absSource; ASSERT_TRUE(uriParseUriA(&state, absSourceStr) == URI_SUCCESS); state.uri = &absBase; ASSERT_TRUE(uriParseUriA(&state, absBaseStr) == URI_SUCCESS); ASSERT_TRUE(uriRemoveBaseUriA(&dest, &absSource, &absBase, URI_FALSE) == URI_SUCCESS); int size = 0; ASSERT_TRUE(uriToStringCharsRequiredA(&dest, &size) == URI_SUCCESS); char * const buffer = (char *)malloc(size + 1); ASSERT_TRUE(buffer); ASSERT_TRUE(uriToStringA(buffer, &dest, size + 1, &size) == URI_SUCCESS); if (strcmp(buffer, expected)) { printf("Expected \"%s\" but got \"%s\"\n", expected, buffer); ASSERT_TRUE(0); } free(buffer); uriFreeUriMembersA(&absSource); uriFreeUriMembersA(&absBase); uriFreeUriMembersA(&dest); } } // namespace TEST(UriSuite, TestRangeComparisonRemoveBaseUriIssue19) { // scheme testRemoveBaseUriHelper("scheme://host/source", "scheme://host/source", "schemelonger://host/base"); testRemoveBaseUriHelper("schemelonger://host/source", "schemelonger://host/source", "scheme://host/base"); // hostText testRemoveBaseUriHelper("//host/source", "http://host/source", "http://hostlonger/base"); testRemoveBaseUriHelper("//hostlonger/source", "http://hostlonger/source", "http://host/base"); // hostData.ipFuture testRemoveBaseUriHelper("//[v7.host]/source", "http://[v7.host]/source", "http://[v7.hostlonger]/base"); testRemoveBaseUriHelper("//[v7.hostlonger]/source", "http://[v7.hostlonger]/source", "http://host/base"); // path testRemoveBaseUriHelper("path1", "http://host/path1", "http://host/path111"); testRemoveBaseUriHelper("../path1/path2", "http://host/path1/path2", "http://host/path111/path222"); testRemoveBaseUriHelper("path111", "http://host/path111", "http://host/path1"); testRemoveBaseUriHelper("../path111/path222", "http://host/path111/path222", "http://host/path1/path2"); // Exact issue #19 testRemoveBaseUriHelper("//example/x/abc", "http://example/x/abc", "http://example2/x/y/z"); } TEST(ErrorPosSuite, TestErrorPosIPvFuture) { UriUriA uri; const char * errorPos; const char * const uriText = "http://[vA.123456"; // missing "]" EXPECT_EQ(uriParseSingleUriA(&uri, uriText, &errorPos), URI_ERROR_SYNTAX); EXPECT_EQ(errorPos, uriText + strlen(uriText)); } TEST(UriParseSingleSuite, Success) { UriUriA uri; EXPECT_EQ(uriParseSingleUriA(&uri, "file:///home/user/song.mp3", NULL), URI_SUCCESS); uriFreeUriMembersA(&uri); } TEST(UriParseSingleSuite, ErrorSyntaxParseErrorSetsErrorPos) { UriUriA uri; const char * errorPos; const char * const uriString = "abc{}def"; EXPECT_EQ(uriParseSingleUriA(&uri, uriString, &errorPos), URI_ERROR_SYNTAX); EXPECT_EQ(errorPos, uriString + strlen("abc")); uriFreeUriMembersA(&uri); } TEST(UriParseSingleSuite, ErrorNullFirstDetected) { UriUriA uri; const char * errorPos; EXPECT_EQ(uriParseSingleUriExA(&uri, NULL, "notnull", &errorPos), URI_ERROR_NULL); } TEST(UriParseSingleSuite, ErrorNullAfterLastDetected) { UriUriA uri; EXPECT_EQ(uriParseSingleUriExA(&uri, "foo", NULL, NULL), URI_SUCCESS); uriFreeUriMembersA(&uri); } TEST(UriParseSingleSuite, ErrorNullMemoryManagerDetected) { UriUriA uri; const char * errorPos; const char * const uriString = "somethingwellformed"; EXPECT_EQ(uriParseSingleUriExMmA(&uri, uriString, uriString + strlen(uriString), &errorPos, NULL), URI_SUCCESS); EXPECT_EQ(uriFreeUriMembersMmA(&uri, NULL), URI_SUCCESS); } TEST(FreeUriMembersSuite, MultiFreeWorksFine) { UriUriA uri; EXPECT_EQ(uriParseSingleUriA(&uri, "file:///home/user/song.mp3", NULL), URI_SUCCESS); UriUriA uriBackup = uri; EXPECT_EQ(memcmp(&uriBackup, &uri, sizeof(UriUriA)), 0); uriFreeUriMembersA(&uri); // Did some pointers change (to NULL)? EXPECT_NE(memcmp(&uriBackup, &uri, sizeof(UriUriA)), 0); uriFreeUriMembersA(&uri); // second time } TEST(MakeOwnerSuite, MakeOwner) { const char * const uriString = "scheme://user:pass@[v7.X]:55555/path/../path/?query#fragment"; UriUriA uri; char * uriFirst = strdup(uriString); const size_t uriLen = strlen(uriFirst); char * uriAfterLast = uriFirst + uriLen; EXPECT_EQ(uriParseSingleUriExA(&uri, uriFirst, uriAfterLast, NULL), URI_SUCCESS); // After plain parse, all strings should point inside the original URI string EXPECT_EQ(uri.owner, URI_FALSE); URI_EXPECT_RANGE_BETWEEN(uri.scheme, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.userInfo, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.hostText, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.hostData.ipFuture, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.portText, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.pathHead->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.pathHead->next->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.pathHead->next->next->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_EMPTY(uri.pathHead->next->next->next->text); EXPECT_TRUE(uri.pathHead->next->next->next->next == NULL); URI_EXPECT_RANGE_BETWEEN(uri.query, uriFirst, uriAfterLast); URI_EXPECT_RANGE_BETWEEN(uri.fragment, uriFirst, uriAfterLast); EXPECT_EQ(uriMakeOwnerA(&uri), URI_SUCCESS); // After making owner, *none* of the strings should point inside the original URI string EXPECT_EQ(uri.owner, URI_TRUE); URI_EXPECT_RANGE_OUTSIDE(uri.scheme, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.userInfo, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.hostText, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.hostData.ipFuture, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.portText, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.pathHead->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.pathHead->next->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.pathHead->next->next->text, uriFirst, uriAfterLast); URI_EXPECT_RANGE_EMPTY(uri.pathHead->next->next->next->text); EXPECT_TRUE(uri.pathHead->next->next->next->next == NULL); URI_EXPECT_RANGE_OUTSIDE(uri.query, uriFirst, uriAfterLast); URI_EXPECT_RANGE_OUTSIDE(uri.fragment, uriFirst, uriAfterLast); // Free originally used memory so we'd get violations on access with ASan uriAfterLast = NULL; free(uriFirst); uriFirst = NULL; // Can we recompose the URI without accessing any old freed memory? int charsRequired; EXPECT_EQ(uriToStringCharsRequiredA(&uri, &charsRequired), URI_SUCCESS); EXPECT_TRUE((charsRequired >= 0) && (charsRequired >= static_cast<int>(uriLen))); char * const uriRemake = new char[charsRequired + 1]; EXPECT_TRUE(uriRemake != NULL); EXPECT_EQ(uriToStringA(uriRemake, &uri, charsRequired + 1, NULL), URI_SUCCESS); EXPECT_TRUE(! strcmp(uriString, uriRemake)); delete [] uriRemake; uriFreeUriMembersA(&uri); } TEST(ParseIpFourAddressSuite, FourSaneOctets) { unsigned char octetOutput[4]; const char * const ipAddressText = "111.22.3.40"; const int res = uriParseIpFourAddressA(octetOutput, ipAddressText, ipAddressText + strlen(ipAddressText)); EXPECT_EQ(res, URI_SUCCESS); EXPECT_EQ(octetOutput[0], 111); EXPECT_EQ(octetOutput[1], 22); EXPECT_EQ(octetOutput[2], 3); EXPECT_EQ(octetOutput[3], 40); } int main(int argc, char ** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
36.808715
137
0.680454
[ "transform" ]
4b1df16a12f8d32241b966283c975cb0c46600dd
9,679
hpp
C++
src/a2d/input/input.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
17
2018-11-12T11:13:23.000Z
2021-11-13T12:38:21.000Z
src/a2d/input/input.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
1
2018-11-12T11:16:01.000Z
2018-11-12T11:17:50.000Z
src/a2d/input/input.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
3
2019-05-28T12:44:09.000Z
2021-11-13T12:38:23.000Z
// // Created by selya on 19.11.2018. // #ifndef A2D_INPUT_HPP #define A2D_INPUT_HPP #include <a2d/renderer/gl.hpp> #include <a2d/math/vector.hpp> #include <queue> namespace a2d { class Input { friend class PlatformToNative; public: enum KeyCode { KEY_UNKNOWN = -1, KEY_SPACE = 32, KEY_APOSTROPHE = 39, /* ' */ KEY_COMMA = 44, /* , */ KEY_MINUS = 45, /* - */ KEY_PERIOD = 46, /* . */ KEY_SLASH = 47, /* / */ KEY_0 = 48, KEY_1 = 49, KEY_2 = 50, KEY_3 = 51, KEY_4 = 52, KEY_5 = 53, KEY_6 = 54, KEY_7 = 55, KEY_8 = 56, KEY_9 = 57, KEY_SEMICOLON = 59, /* ; */ KEY_EQUAL = 61, /* = */ KEY_A = 65, KEY_B = 66, KEY_C = 67, KEY_D = 68, KEY_E = 69, KEY_F = 70, KEY_G = 71, KEY_H = 72, KEY_I = 73, KEY_J = 74, KEY_K = 75, KEY_L = 76, KEY_M = 77, KEY_N = 78, KEY_O = 79, KEY_P = 80, KEY_Q = 81, KEY_R = 82, KEY_S = 83, KEY_T = 84, KEY_U = 85, KEY_V = 86, KEY_W = 87, KEY_X = 88, KEY_Y = 89, KEY_Z = 90, KEY_LEFT_BRACKET = 91, /* [ */ KEY_BACKSLASH = 92, /* \ */ KEY_RIGHT_BRACKET = 93, /* ] */ KEY_GRAVE_ACCENT = 96, /* ` */ KEY_WORLD_1 = 161, /* non-US #1 */ KEY_WORLD_2 = 162, /* non-US #2 */ KEY_ESCAPE = 256, KEY_ENTER = 257, KEY_TAB = 258, KEY_BACKSPACE = 259, KEY_INSERT = 260, KEY_DELETE = 261, KEY_RIGHT = 262, KEY_LEFT = 263, KEY_DOWN = 264, KEY_UP = 265, KEY_PAGE_UP = 266, KEY_PAGE_DOWN = 267, KEY_HOME = 268, KEY_END = 269, KEY_CAPS_LOCK = 280, KEY_SCROLL_LOCK = 281, KEY_NUM_LOCK = 282, KEY_PRINT_SCREEN = 283, KEY_PAUSE = 284, KEY_F1 = 290, KEY_F2 = 291, KEY_F3 = 292, KEY_F4 = 293, KEY_F5 = 294, KEY_F6 = 295, KEY_F7 = 296, KEY_F8 = 297, KEY_F9 = 298, KEY_F10 = 299, KEY_F11 = 300, KEY_F12 = 301, KEY_F13 = 302, KEY_F14 = 303, KEY_F15 = 304, KEY_F16 = 305, KEY_F17 = 306, KEY_F18 = 307, KEY_F19 = 308, KEY_F20 = 309, KEY_F21 = 310, KEY_F22 = 311, KEY_F23 = 312, KEY_F24 = 313, KEY_F25 = 314, KEY_KP_0 = 320, KEY_KP_1 = 321, KEY_KP_2 = 322, KEY_KP_3 = 323, KEY_KP_4 = 324, KEY_KP_5 = 325, KEY_KP_6 = 326, KEY_KP_7 = 327, KEY_KP_8 = 328, KEY_KP_9 = 329, KEY_KP_DECIMAL = 330, KEY_KP_DIVIDE = 331, KEY_KP_MULTIPLY = 332, KEY_KP_SUBTRACT = 333, KEY_KP_ADD = 334, KEY_KP_ENTER = 335, KEY_KP_EQUAL = 336, KEY_LEFT_SHIFT = 340, KEY_LEFT_CONTROL = 341, KEY_LEFT_ALT = 342, KEY_LEFT_SUPER = 343, KEY_RIGHT_SHIFT = 344, KEY_RIGHT_CONTROL = 345, KEY_RIGHT_ALT = 346, KEY_RIGHT_SUPER = 347, KEY_MENU = 348, }; enum MouseButtonCode { MOUSE_BUTTON_1 = 0, MOUSE_BUTTON_2 = 1, MOUSE_BUTTON_3 = 2, MOUSE_BUTTON_4 = 3, MOUSE_BUTTON_5 = 4, MOUSE_BUTTON_6 = 5, MOUSE_BUTTON_7 = 6, MOUSE_BUTTON_8 = 7, MOUSE_BUTTON_LAST = MOUSE_BUTTON_8, MOUSE_BUTTON_LEFT = MOUSE_BUTTON_1, MOUSE_BUTTON_RIGHT = MOUSE_BUTTON_2, MOUSE_BUTTON_MIDDLE = MOUSE_BUTTON_3 }; enum KeyState { KEY_STATE_RELEASED = 0, KEY_STATE_PRESSED = 1 }; enum TouchEvent { TOUCH_BEGAN, TOUCH_MOVED, TOUCH_ENDED }; struct Touch { enum TouchState { TOUCH_STATE_RELEASED = 0, TOUCH_STATE_PRESSED = 1, TOUCH_STATE_JUST_RELEASED = 2, TOUCH_STATE_JUST_PRESSED = 3 }; int index; Vector2f position; TouchState state; Touch(); Touch(int index, Vector2f position, TouchState state); }; /** * Returns key current state either PRESSED or RELEASED. * * @param key_code key code * @return key state */ static KeyState GetKeyState(KeyCode key_code); /** * Shows whether key was pressed in the current frame. * * @param key_code key code * @return true if key was pressed during current frame, false otherwise */ static bool IsKeyJustPressed(KeyCode key_code); /** * Shows whether key was released in the current frame. * * @param key_code key code * @return true if key was released during current frame, false otherwise */ static bool IsKeyJustReleased(KeyCode key_code); /** * Returns scroll delta during this frame. * * Simple mouse wheel provides only y-delta (vertical). * * @return scroll delta */ static Vector2f GetScrollDelta(); /** * Returns mouse position relative to bottom-left screen corner. * * On mobile platforms it is just touch 0 position. * * @return mouse position */ static Vector2f GetMousePosition(); /** * Returns mouse button current state either PRESSED or RELEASED. * * On mobile platforms it is same as touch 0 state. * * @param button_code mouse button code * @return mouse button state */ static KeyState GetMouseButtonState(MouseButtonCode button_code); /** * Shows whether mouse button was pressed in the current frame. * * On mobile platforms it is same as touch 0 state. * * @param button_code mouse button code * @return true if button was pressed during current frame, false otherwise */ static bool IsMouseButtonJustPressed(MouseButtonCode button_code); /** * Shows whether mouse button was released in the current frame. * * On mobile platforms it is same as touch 0 state. * * @param button_code mouse button code * @return true if button was released during current frame, false otherwise */ static bool IsMouseButtonJustReleased(MouseButtonCode button_code); /** * Returns number of currently active touches. * * @return number of currently active touches */ static int GetTouchesCount(); /** * Returns touch by its index. * * @param touch_index touch index * @return touch */ static Touch GetTouch(int touch_index); private: static bool Initialize(); static bool Step(); static void Uninitialize(); #if TARGET_DESKTOP static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); static void MousePositionCallback(GLFWwindow *window, double x_position, double y_position); static void MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); static void ScrollCallback(GLFWwindow *window, double x_offset, double y_offset); #elif TARGET_MOBILE static void TouchCallback(int touches_count, int touch_index, TouchEvent touch_event, float touch_x, float touch_y); #endif struct KeyInternalState { unsigned long long last_pressed = 0; unsigned long long last_released = 0; KeyState state = KeyState::KEY_STATE_RELEASED; }; struct TouchInternalState { unsigned long long last_pressed = 0; unsigned long long last_released = 0; Touch::TouchState state = Touch::TouchState::TOUCH_STATE_RELEASED; Vector2f position = Vector2f(); }; static int &GetInternalTouchesCount(); static KeyInternalState &GetKeyInternalState(KeyCode key_code); static KeyInternalState &GetMouseButtonInternalState(MouseButtonCode button_code); static TouchInternalState &GetTouchInternalState(int touch_index); static Vector2f &GetInternalMousePosition(); static Vector2f &GetInternalScrollDelta(); static std::queue<std::pair<int, TouchInternalState>> &GetInternalDelayedTouchesPool(); static int &GetInternalDelayedTouchesCount(); }; } //namespace a2d #endif //A2D_INPUT_HPP
30.629747
120
0.503048
[ "vector" ]
4b20373921f16d4b12678da90d85394d16eacedf
1,771
hh
C++
src/include/FissionWindow.hh
gobar07/Fission
f1e1cfb1eaf17894e60a5ec292419f725d620784
[ "BSD-3-Clause" ]
3
2019-10-07T13:41:45.000Z
2020-10-01T04:47:44.000Z
src/include/FissionWindow.hh
gobar07/Fission
f1e1cfb1eaf17894e60a5ec292419f725d620784
[ "BSD-3-Clause" ]
2
2020-10-15T17:02:45.000Z
2020-10-15T17:02:48.000Z
src/include/FissionWindow.hh
gobar07/Fission
f1e1cfb1eaf17894e60a5ec292419f725d620784
[ "BSD-3-Clause" ]
2
2020-10-01T04:47:50.000Z
2020-10-15T10:38:24.000Z
/*! \file FissionWindow.hh \brief Native system window wrapper This class provides a wrapper for the native operating system window. It is dependent on the rendering backend. Note that this is different from the Fission::Widgets::Window class, as that describes a child window of a parent Fission::FissionWindow. */ #pragma once #if !defined(__FISSION_WINDOW_HH__) #define __FISSION_WINDOW_HH__ #include <string> #include <mutex> #include <thread> #include <memory> #include <nuklear.h> #include <Backend/GenericBackend.hh> #include <Utility/BasicTypes.hh> #include <Utility/Event.hh> using Fission::Utility::WindowPos; using Fission::Utility::WindowSize; using Fission::Backends::WindowContext_t; namespace Fission { /*! \class FissionWindow \brief This class Represents a OS Window, not to be confused with a WindowWidget 1 Each Fission window has it's own render thread to keep your application logic and render events separate. */ class FissionWindow { private: std::string _WindowName; WindowSize _Size; WindowPos _Position; public: /*! \brief Construct a new FissionWindow \param WindowTitle [IN] The title for the window \param Size [IN] (Optional) The size of the window (defaults to 800x600) \param Position [IN] (Optional) The position of the window (defaults to 0,0) */ FissionWindow(std::string WindowTitle, WindowSize Size = {600, 800}, WindowPos Position = {0, 0}); ~FissionWindow(void); void ShowWindow(void); /* == Events == */ /*! \struct WindowResize \brief Triggers when any FissionWindow is resized */ struct WindowResize : Fission::Utility::BaseEvent { WindowSize NewSize; WindowResize(WindowSize Size) : NewSize(Size) {} }; }; } #endif /* __FISSION_WINDOW_HH__ */
24.260274
84
0.733484
[ "render" ]
4b254b25f7845d32dd14644697a42792106f0c1c
18,225
cpp
C++
src/hp.cpp
xwu64/libcds
7aeb69fa15913c6405ce514d0d970469f0cbef93
[ "BSL-1.0" ]
2,118
2015-01-01T00:30:42.000Z
2022-03-30T12:47:38.000Z
src/hp.cpp
liangwens/libcds
b4d11539824bb91ae4604f47aa1416fdd7cc1ff1
[ "BSL-1.0" ]
113
2015-01-03T15:29:40.000Z
2022-03-05T21:30:11.000Z
src/hp.cpp
liangwens/libcds
b4d11539824bb91ae4604f47aa1416fdd7cc1ff1
[ "BSL-1.0" ]
385
2015-01-01T21:51:48.000Z
2022-03-25T12:51:30.000Z
// Copyright (c) 2006-2018 Maxim Khizhinsky // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include <vector> #include <cds/gc/hp.h> #include <cds/os/thread.h> #include <cds/gc/hp_membar.h> #if CDS_OS_TYPE == CDS_OS_LINUX # include <unistd.h> # include <sys/syscall.h> // membarrier() was added in Linux 4.3 # if !defined( __NR_membarrier ) # define __NR_membarrier 324 # endif # ifdef CDS_HAVE_LINUX_MEMBARRIER_H # include <linux/membarrier.h> # else # define MEMBARRIER_CMD_QUERY 0 # define MEMBARRIER_CMD_SHARED (1<<0) # endif // linux 4.14+ # define CDS_MEMBARRIER_CMD_PRIVATE_EXPEDITED (1<<3) # define CDS_MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED (1<<4) #endif namespace cds { namespace gc { namespace hp { namespace details { std::atomic<unsigned> shared_var_membar::shared_var_{ 0 }; #if CDS_OS_TYPE == CDS_OS_LINUX bool asymmetric_membar::membarrier_available_ = false; void asymmetric_membar::check_membarrier_available() { int res = syscall( __NR_membarrier, MEMBARRIER_CMD_QUERY, 0 ); membarrier_available_ = !( res == -1 || ( res & CDS_MEMBARRIER_CMD_PRIVATE_EXPEDITED ) == 0 ) && syscall( __NR_membarrier, CDS_MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, 0 ) == 0; } void asymmetric_membar::call_membarrier() { assert( membarrier_available_ ); syscall( __NR_membarrier, CDS_MEMBARRIER_CMD_PRIVATE_EXPEDITED, 0 ); } bool asymmetric_global_membar::membarrier_available_ = false; void asymmetric_global_membar::check_membarrier_available() { int res = syscall( __NR_membarrier, MEMBARRIER_CMD_QUERY, 0 ); membarrier_available_ = !( res == -1 || ( res & MEMBARRIER_CMD_SHARED ) == 0 ); } void asymmetric_global_membar::call_membarrier() { assert( membarrier_available_ ); syscall( __NR_membarrier, MEMBARRIER_CMD_SHARED, 0 ); } #endif namespace { void * default_alloc_memory( size_t size ) { return new uintptr_t[( size + sizeof( uintptr_t ) - 1 ) / sizeof( uintptr_t) ]; } void default_free_memory( void* p ) { delete[] reinterpret_cast<uintptr_t*>( p ); } void* ( *s_alloc_memory )( size_t size ) = default_alloc_memory; void ( *s_free_memory )( void* p ) = default_free_memory; template <typename T> class allocator { public: typedef T value_type; allocator() {} allocator( allocator const& ) {} template <class U> explicit allocator( allocator<U> const& ) {} static T* allocate( size_t nCount ) { return reinterpret_cast<T*>( s_alloc_memory( sizeof( value_type ) * nCount )); } static void deallocate( T* p, size_t /*nCount*/ ) { s_free_memory( reinterpret_cast<void*>( p )); } }; struct defaults { static const size_t c_nHazardPointerPerThread = 8; static const size_t c_nMaxThreadCount = 100; }; size_t calc_retired_size( size_t nSize, size_t nHPCount, size_t nThreadCount ) { size_t const min_size = nHPCount * nThreadCount; return nSize < min_size ? min_size * 2 : nSize; } stat s_postmortem_stat; } // namespace /*static*/ CDS_EXPORT_API basic_smr* basic_smr::instance_ = nullptr; /*static*/ CDS_EXPORT_API void basic_smr::set_memory_allocator( void* ( *alloc_func )( size_t size ), void( *free_func )( void * p ) ) { // The memory allocation functions may be set BEFORE initializing HP SMR!!! assert( instance_ == nullptr ); s_alloc_memory = alloc_func; s_free_memory = free_func; } /*static*/ CDS_EXPORT_API void basic_smr::construct(size_t nHazardPtrCount, size_t nMaxThreadCount, size_t nMaxRetiredPtrCount, scan_type nScanType ) { if ( !instance_ ) { instance_ = new( s_alloc_memory(sizeof(basic_smr))) basic_smr(nHazardPtrCount, nMaxThreadCount, nMaxRetiredPtrCount, nScanType ); } } /*static*/ CDS_EXPORT_API void basic_smr::destruct(bool bDetachAll ) { if ( instance_ ) { if ( bDetachAll ) instance_->detach_all_thread(); instance_->~basic_smr(); s_free_memory( instance_ ); instance_ = nullptr; } } CDS_EXPORT_API basic_smr::basic_smr(size_t nHazardPtrCount, size_t nMaxThreadCount, size_t nMaxRetiredPtrCount, scan_type nScanType ) : hazard_ptr_count_( nHazardPtrCount == 0 ? defaults::c_nHazardPointerPerThread : nHazardPtrCount ) , max_thread_count_( nMaxThreadCount == 0 ? defaults::c_nMaxThreadCount : nMaxThreadCount ) , max_retired_ptr_count_( calc_retired_size( nMaxRetiredPtrCount, hazard_ptr_count_, max_thread_count_ )) , scan_type_( nScanType ) , scan_func_( nScanType == classic ? &basic_smr::classic_scan : &basic_smr::inplace_scan ) { thread_list_.store( nullptr, atomics::memory_order_release ); } CDS_EXPORT_API basic_smr::~basic_smr() { CDS_HPSTAT( statistics( s_postmortem_stat )); thread_record* pHead = thread_list_.load( atomics::memory_order_relaxed ); thread_list_.store( nullptr, atomics::memory_order_release ); thread_record* pNext = nullptr; for ( thread_record* hprec = pHead; hprec; hprec = pNext ) { assert( hprec->owner_rec_.load( atomics::memory_order_relaxed ) == nullptr || hprec->owner_rec_.load( atomics::memory_order_relaxed ) == hprec ); retired_array& arr = hprec->retired_; for ( retired_ptr* cur{ arr.first() }, *last{ arr.last() }; cur != last; ++cur ) { cur->free(); CDS_HPSTAT( ++s_postmortem_stat.free_count ); } arr.reset( 0 ); pNext = hprec->next_; hprec->free_.store( true, atomics::memory_order_relaxed ); destroy_thread_data( hprec ); } } CDS_EXPORT_API basic_smr::thread_record* basic_smr::create_thread_data() { size_t const guard_array_size = thread_hp_storage::calc_array_size( get_hazard_ptr_count()); size_t const retired_array_size = retired_array::calc_array_size( get_max_retired_ptr_count()); size_t const nSize = sizeof( thread_record ) + guard_array_size + retired_array_size; /* The memory is allocated by contnuous block Memory layout: +--------------------------+ | | | thread_record | | hazards_ +---+ +---| retired_ | | | | | | | |--------------------------| | | | hazard_ptr[] |<--+ | | | | | | | |--------------------------| +-->| retired_ptr[] | | | | | +--------------------------+ */ uint8_t* mem = reinterpret_cast<uint8_t*>( s_alloc_memory( nSize )); return new( mem ) thread_record( reinterpret_cast<guard*>( mem + sizeof( thread_record )), get_hazard_ptr_count(), reinterpret_cast<retired_ptr*>( mem + sizeof( thread_record ) + guard_array_size ), get_max_retired_ptr_count() ); } /*static*/ CDS_EXPORT_API void basic_smr::destroy_thread_data(thread_record* pRec ) { // all retired pointers must be freed assert( pRec->retired_.size() == 0 ); pRec->~thread_record(); s_free_memory( pRec ); } CDS_EXPORT_API basic_smr::thread_record* basic_smr::alloc_thread_data() { thread_record * hprec; // First try to reuse a free (non-active) HP record for ( hprec = thread_list_.load( atomics::memory_order_acquire ); hprec; hprec = hprec->next_ ) { thread_record* null_rec = nullptr; if ( !hprec->owner_rec_.compare_exchange_strong( null_rec, hprec, atomics::memory_order_relaxed, atomics::memory_order_relaxed )) continue; hprec->free_.store( false, atomics::memory_order_release ); return hprec; } // No HP records available for reuse // Allocate and push a new HP record hprec = create_thread_data(); hprec->owner_rec_.store( hprec, atomics::memory_order_relaxed ); thread_record* pOldHead = thread_list_.load( atomics::memory_order_relaxed ); do { hprec->next_ = pOldHead; } while ( !thread_list_.compare_exchange_weak( pOldHead, hprec, atomics::memory_order_release, atomics::memory_order_acquire )); return hprec; } CDS_EXPORT_API void basic_smr::free_thread_data(basic_smr::thread_record* pRec, bool callHelpScan ) { assert( pRec != nullptr ); pRec->hazards_.clear(); scan( pRec ); if ( callHelpScan ) help_scan( pRec ); pRec->owner_rec_.store( nullptr, atomics::memory_order_release ); } CDS_EXPORT_API void basic_smr::detach_all_thread() { thread_record * pNext = nullptr; for ( thread_record * hprec = thread_list_.load( atomics::memory_order_relaxed ); hprec; hprec = pNext ) { pNext = hprec->next_; if ( hprec->owner_rec_.load( atomics::memory_order_relaxed ) != nullptr ) { free_thread_data( hprec, false ); } } } CDS_EXPORT_API void basic_smr::inplace_scan(thread_data* pThreadRec ) { thread_record* pRec = static_cast<thread_record*>( pThreadRec ); //CDS_HAZARDPTR_STATISTIC( ++m_Stat.m_ScanCallCount ) // In-place scan algo uses LSB of retired ptr as a mark for internal purposes. // It is correct if all retired pointers are ar least 2-byte aligned (LSB is zero). // If it is wrong, we use classic scan algorithm // Check if all retired pointers has zero LSB // LSB is used for marking pointers that cannot be deleted yet retired_ptr* first_retired = pRec->retired_.first(); retired_ptr* last_retired = pRec->retired_.last(); if ( first_retired == last_retired ) return; for ( auto it = first_retired; it != last_retired; ++it ) { if ( it->m_n & 1 ) { // found a pointer with LSB bit set - use classic_scan classic_scan( pRec ); return; } } CDS_HPSTAT( ++pThreadRec->scan_count_ ); // Sort retired pointer array std::sort( first_retired, last_retired, retired_ptr::less ); // Check double free # ifdef _DEBUG { auto it = first_retired; auto itPrev = it; while ( ++it != last_retired ) { assert( itPrev->m_p < it->m_p ); itPrev = it; } } # endif // Search guarded pointers in retired array thread_record* pNode = thread_list_.load( atomics::memory_order_acquire ); { retired_ptr dummy_retired; while ( pNode ) { if ( pNode->owner_rec_.load( atomics::memory_order_relaxed ) != nullptr ) { thread_hp_storage& hpstg = pNode->hazards_; for ( auto hp = hpstg.begin(), end = hpstg.end(); hp != end; ++hp ) { void * hptr = hp->get( atomics::memory_order_relaxed ); if ( hptr ) { dummy_retired.m_p = hptr; retired_ptr* it = std::lower_bound(first_retired, last_retired, dummy_retired, retired_ptr::less); if ( it != last_retired && it->m_p == hptr ) { // Mark retired pointer as guarded it->m_n |= 1; } } } } pNode = pNode->next_; } } // Move all marked pointers to head of array { retired_ptr* insert_pos = first_retired; for ( retired_ptr* it = first_retired; it != last_retired; ++it ) { if ( it->m_n & 1 ) { it->m_n &= ~uintptr_t(1); if ( insert_pos != it ) *insert_pos = *it; ++insert_pos; } else { // Retired pointer may be freed it->free(); CDS_HPSTAT( ++pRec->free_count_ ); } } const size_t nDeferred = insert_pos - first_retired; pRec->retired_.reset( nDeferred ); } } // cppcheck-suppress functionConst CDS_EXPORT_API void basic_smr::classic_scan(thread_data* pThreadRec ) { thread_record* pRec = static_cast<thread_record*>( pThreadRec ); CDS_HPSTAT( ++pThreadRec->scan_count_ ); std::vector< void*, allocator<void*>> plist; plist.reserve( get_max_thread_count() * get_hazard_ptr_count()); assert( plist.size() == 0 ); // Stage 1: Scan HP list and insert non-null values in plist thread_record* pNode = thread_list_.load( atomics::memory_order_acquire ); while ( pNode ) { if ( pNode->owner_rec_.load( std::memory_order_relaxed ) != nullptr ) { for ( size_t i = 0; i < get_hazard_ptr_count(); ++i ) { void * hptr = pNode->hazards_[i].get(); if ( hptr ) plist.push_back( hptr ); } } pNode = pNode->next_; } // Sort plist to simplify search in std::sort( plist.begin(), plist.end()); // Stage 2: Search plist retired_array& retired = pRec->retired_; retired_ptr* first_retired = retired.first(); retired_ptr* last_retired = retired.last(); { auto itBegin = plist.begin(); auto itEnd = plist.end(); retired_ptr* insert_pos = first_retired; for ( retired_ptr* it = first_retired; it != last_retired; ++it ) { if ( std::binary_search( itBegin, itEnd, first_retired->m_p )) { if ( insert_pos != it ) *insert_pos = *it; ++insert_pos; } else { it->free(); CDS_HPSTAT( ++pRec->free_count_ ); } } retired.reset( insert_pos - first_retired ); } } CDS_EXPORT_API void basic_smr::help_scan(thread_data* pThis ) { assert( static_cast<thread_record*>( pThis )->owner_rec_.load( atomics::memory_order_relaxed ) == static_cast<thread_record*>( pThis )); CDS_HPSTAT( ++pThis->help_scan_count_ ); for ( thread_record* hprec = thread_list_.load( atomics::memory_order_acquire ); hprec; hprec = hprec->next_ ) { if ( hprec == static_cast<thread_record*>( pThis )) continue; // If free_ == true then hprec->retired_ is empty - we don't need to see it if ( hprec->free_.load( atomics::memory_order_acquire )) continue; // Owns hprec if it is empty. // Several threads may work concurrently so we use atomic technique only. { thread_record* curOwner = hprec->owner_rec_.load( atomics::memory_order_relaxed ); if ( curOwner == nullptr ) { if ( !hprec->owner_rec_.compare_exchange_strong( curOwner, hprec, atomics::memory_order_acquire, atomics::memory_order_relaxed )) continue; } else continue; } // We own the thread record successfully. Now, we can see whether it has retired pointers. // If it has ones then we move them to pThis that is private for current thread. retired_array& src = hprec->retired_; retired_array& dest = pThis->retired_; assert( !dest.full()); retired_ptr* src_first = src.first(); retired_ptr* src_last = src.last(); for ( ; src_first != src_last; ++src_first ) { if ( !dest.push( std::move( *src_first ))) scan( pThis ); } src.interthread_clear(); hprec->free_.store( true, atomics::memory_order_release ); hprec->owner_rec_.store( nullptr, atomics::memory_order_release ); scan( pThis ); } } CDS_EXPORT_API void basic_smr::statistics(stat& st ) { st.clear(); # ifdef CDS_ENABLE_HPSTAT for ( thread_record* hprec = thread_list_.load( atomics::memory_order_acquire ); hprec; hprec = hprec->next_ ) { CDS_TSAN_ANNOTATE_IGNORE_READS_BEGIN; ++st.thread_rec_count; st.guard_allocated += hprec->hazards_.alloc_guard_count_; st.guard_freed += hprec->hazards_.free_guard_count_; st.retired_count += hprec->retired_.retire_call_count_; st.free_count += hprec->free_count_; st.scan_count += hprec->scan_count_; st.help_scan_count += hprec->help_scan_count_; CDS_TSAN_ANNOTATE_IGNORE_READS_END; } # endif } cds::gc::hp::details::stat const& postmortem_statistics() { return s_postmortem_stat; } }}}} // namespace cds::gc::hp::details
36.232604
153
0.562085
[ "vector" ]
4b289eb3fb233b1793e80900fa51af17ad47c072
1,788
cpp
C++
src/nexus/backend/slice.cpp
dengwxn/nexus
c353fa7954e042cabf9e2e92f584aa0681a1bfc4
[ "BSD-3-Clause" ]
6
2021-07-01T23:03:28.000Z
2022-02-07T03:24:42.000Z
src/nexus/backend/slice.cpp
dengwxn/nexus
c353fa7954e042cabf9e2e92f584aa0681a1bfc4
[ "BSD-3-Clause" ]
null
null
null
src/nexus/backend/slice.cpp
dengwxn/nexus
c353fa7954e042cabf9e2e92f584aa0681a1bfc4
[ "BSD-3-Clause" ]
2
2021-04-06T11:09:35.000Z
2021-04-13T06:59:34.000Z
#include "nexus/backend/slice.h" #include <glog/logging.h> namespace nexus { namespace backend { Slice::Slice(size_t nsplits, size_t nfloats) : equal_split_(true) { size_t offset = 0; for (size_t i = 0; i < nsplits; ++i) { offsets_.push_back(offset); offset += nfloats; } total_elements_ = offset; equal_slice_size_ = nfloats; } Slice::Slice(std::vector<size_t> nfloats, size_t multiplier) : equal_split_(false) { size_t offset = 0; for (auto size : nfloats) { offsets_.push_back(offset); size_t slice_size = size * multiplier; slice_sizes_.push_back(slice_size); offset += slice_size; } total_elements_ = offset; } Slice::Slice(std::vector<float> nfloats, size_t multiplier) : equal_split_(false) { size_t offset = 0; for (auto size : nfloats) { offsets_.push_back(offset); size_t slice_size = size_t(size) * multiplier; slice_sizes_.push_back(slice_size); offset += slice_size; } total_elements_ = offset; } Slice::Slice(size_t nsplits, float* nfloats, size_t multiplier) : equal_split_(false) { size_t offset = 0; for (size_t i = 0; i < nsplits; ++i) { offsets_.push_back(offset); size_t slice_size = size_t(nfloats[i]) * multiplier; slice_sizes_.push_back(slice_size); offset += slice_size; } total_elements_ = offset; } size_t Slice::offset(int idx) const { CHECK_LT(idx, offsets_.size()) << "Index " << idx << " exceeds the boundary " << offsets_.size(); return offsets_[idx]; } size_t Slice::num_elements(int idx) const { CHECK_LT(idx, offsets_.size()) << "Index " << idx << " exceeds the boundary " << offsets_.size(); if (equal_split_) { return equal_slice_size_; } return slice_sizes_[idx]; } } // namespace backend } // namespace nexus
25.183099
72
0.671141
[ "vector" ]
4b28d9fc13a4638186a44d2e960d4fa641e39686
1,643
hpp
C++
inference-engine/tests_deprecated/functional/vpu/common/layers/myriad_layers_clamp_test.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
1
2020-06-21T09:51:42.000Z
2020-06-21T09:51:42.000Z
inference-engine/tests_deprecated/functional/vpu/common/layers/myriad_layers_clamp_test.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
inference-engine/tests_deprecated/functional/vpu/common/layers/myriad_layers_clamp_test.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "myriad_layers_tests.hpp" #define ERROR_BOUND (.1f) using namespace InferenceEngine; struct clamp_test_params { float min; float max; friend std::ostream& operator<<(std::ostream& os, clamp_test_params const& tst) { return os << " min=" << tst.min << ", max=" << tst.max; }; }; typedef myriadLayerTestBaseWithParam<std::tuple<SizeVector, clamp_test_params>> myriadLayersTestsClampParams_smoke; TEST_P(myriadLayersTestsClampParams_smoke, TestsClamp) { _config[VPU_CONFIG_KEY(DETECT_NETWORK_BATCH)] = CONFIG_VALUE(NO); auto param = GetParam(); SizeVector tensor = std::get<0>(param); clamp_test_params p = std::get<1>(param); std::map<std::string, std::string> params; params["min"] = std::to_string(p.min); params["max"] = std::to_string(p.max); SetInputTensors({tensor}); SetOutputTensors({tensor}); ASSERT_NO_FATAL_FAILURE(makeSingleLayerNetwork(LayerInitParams("Clamp").params(params))); /* input data preparation */ SetFirstInputToRange(-100.f, 100.f); ASSERT_TRUE(Infer()); /* output check */ auto outputBlob =_outputMap[_outputsInfo.begin()->first]; auto inputBlob = _inputMap[_inputsInfo.begin()->first]; ref_Clamp(inputBlob, _refBlob, p.min, p.max); CompareCommonAbsolute(outputBlob, _refBlob, ERROR_BOUND); } static std::vector<SizeVector> s_clampTensors = { {{1, 3, 10, 15}}, {{5, 6, 2, 3, 10, 15}}, }; static std::vector<clamp_test_params> s_clampParams = { {0.f, 6.0f}, {-10.f, 17.0f} };
28.327586
115
0.674376
[ "vector" ]
4b2f5d992ce16e5ad093c0152012be5cae14f3ca
2,433
hpp
C++
include/eve/detail/function/simd/x86/movemask.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
include/eve/detail/function/simd/x86/movemask.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
include/eve/detail/function/simd/x86/movemask.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/arch/logical.hpp> #include <utility> namespace eve::detail { template<real_scalar_value T, typename N> EVE_FORCEINLINE auto movemask( eve::logical<eve::wide<T, N>> const &v ) noexcept requires ( !abi_t<T, N>::is_wide_logical ) && x86_abi<abi_t<T, N>> { return std::pair{v.storage(), eve::lane<1>}; } template<typename T, typename N> EVE_FORCEINLINE auto movemask( eve::logical<eve::wide<T, N>> const &v ) noexcept requires ( abi_t<T, N>::is_wide_logical ) && x86_abi<abi_t<T, N>> { auto raw = [&] { if constexpr( std::same_as<abi_t<T, N>, x86_128_> ) { if constexpr( std::is_same_v<T, float > ) return (std::uint16_t)_mm_movemask_ps(v); else if constexpr( std::is_same_v<T, double> ) return (std::uint16_t)_mm_movemask_pd(v); else if constexpr( sizeof(T) == 8 ) return (std::uint16_t)_mm_movemask_pd((__m128d)v.storage()); else if constexpr( sizeof(T) == 4 ) return (std::uint16_t)_mm_movemask_ps((__m128)v.storage()); else return (std::uint16_t)_mm_movemask_epi8(v); } else { if constexpr( std::is_same_v<T, float > ) return (std::uint32_t)_mm256_movemask_ps(v); else if constexpr( std::is_same_v<T, double> ) return (std::uint32_t)_mm256_movemask_pd(v); else if constexpr( sizeof(T) == 8 ) return (std::uint32_t)_mm256_movemask_pd((__m256d)v.storage()); else if constexpr( sizeof(T) == 4 ) return (std::uint32_t)_mm256_movemask_ps((__m256)v.storage()); else if constexpr( current_api == avx2 ) return (std::uint32_t)_mm256_movemask_epi8(v); else if constexpr( current_api == avx ) { auto [l, h] = v.slice(); auto s = h.size(); if constexpr(sizeof(T) == 2) s *= 2; auto top = (std::uint32_t)movemask(h).first; auto bottom = movemask(l).first; return (top << s) | bottom; } } }(); return std::pair{raw, eve::lane<sizeof(T) == 2 ? 2: 1>}; } }
39.885246
118
0.545417
[ "vector" ]
4b3050cf1fd72549942572f108a976a1667aab36
65,675
cpp
C++
src/test_parser.cpp
rodrigue10/ciyam
80fa33c3e58eb17f508100e2d1d04081f6a00418
[ "MIT" ]
null
null
null
src/test_parser.cpp
rodrigue10/ciyam
80fa33c3e58eb17f508100e2d1d04081f6a00418
[ "MIT" ]
null
null
null
src/test_parser.cpp
rodrigue10/ciyam
80fa33c3e58eb17f508100e2d1d04081f6a00418
[ "MIT" ]
null
null
null
// Copyright (c) 2003-2012 CIYAM Pty. Ltd. ACN 093 704 539 // Copyright (c) 2012-2022 CIYAM Developers // // Distributed under the MIT/X11 software license, please refer to the file license.txt // in the root project directory or http://www.opensource.org/licenses/mit-license.php. #ifdef PRECOMPILE_H # include "precompile.h" #endif #pragma hdrstop #ifndef HAS_PRECOMPILED_STD_HEADERS # include <iostream> # ifdef __GNUG__ # include <unistd.h> # endif #endif #include "command_parser.h" #include "config.h" #include "macros.h" #include "console.h" #include "utilities.h" #ifdef __GNUG__ # ifdef RDLINE_SUPPORT extern "C" { # include <readline/history.h> } # endif #endif //#define DEBUG using namespace std; /* Format for node expressions: "type/prefix[=[default]][/parameter[#value][/description[/separator[/terminator]]]]" Allowed values for type are: opt pat (a regular expression pattern) val oval (same as val but will permit a blank value) list olist (same as list but will pemit blank values) By default a list will use a comma as the list separator unless a specific separator character has been provided. A terminator is only permitted for a list type and a separator provided for either an option or value will be stripped of the end of the value (if was found at the end so in that case can act as a terminator). A parameter with an empty prefix must have a name - if no name is provided then the parameter name is considered to be the same as its prefix. For "pat" type expressions the prefix is a regular expression pattern. If a parameter has no prefix then it cannot have an empty value unless provided via "", or through the use of leading/trailing/consecutive list separators, or by the use of a list terminator on its own. An unprefixed parameter cannot have any other unprefixed alternative parameter nor can it be the first parameter in an optional branch. The "default" value for a prefix is only applicable to val or oval nodes within an optional branch where there is at least one following matching node. Syntax and argument examples: ----------------------------- syntax <opt/cvs>{<opt/add>[<opt/-kb/binary>]<list//files/new files/ >}|{<opt/remove><list//files/existing files/ >} command cvs add -kb one two three command cvs remove one two three syntax <opt/filter>[<opt/-nodups/nodups>][<val/-a/after>][<val/-b/before>]<val/@/listfile>|<list//strings// > command filter -afirst -bsecond -nodups @test.lst command filter -afirst -bsecond -nodups s1 s2 s3 s4 syntax <opt/bcc32>[<list/-D/defs//;>][<opt/-v/debug#on>]<list//objs// /,><val//exe>[<oval//map//,>][<list//libs// >] command bcc32 -DONE -v -DTWO a.obj b.obj, x.exe command bcc32 -DONE -v -DTWO a.obj b.obj, x.exe a.lib b.lib command bcc32 -DONE -v -DTWO a.obj b.obj, x.exe , a.lib b.lib command bcc32 -v -DONE;TWO a.obj b.obj, x.exe x.map, a.lib b.lib syntax <opt/cvscheck>[<opt/-q/quiet>][<opt/-r/return>][<val/-p/path>][<list/-i/masks>][<val/-m/marker>]<list//files// > command cvscheck -pC:\\Work -i*.h,*.cpp -mTEST -q file1.h file1.cpp file2.h file2.cpp command cvscheck -r -i*.cpp file1.cpp file2.cpp */ struct syntax_text { const char* p_syntax; bool test_should_succeed; } syntax_texts[ ] = { { "<", false }, { ">", false }, { "|", false }, { "[", false }, { "]", false }, { "||", false }, { "[]", false }, { "][", false }, { "<<", false }, { ">>", false }, { "<>", false }, { "{}", false }, { "[{}]", false }, { "[{<>}]", false }, { "<opt/a>", true }, { "[<opt/a>]", true }, { "{<opt/a>}", true }, { "|<opt/a>", false }, { "<opt/a>|", false }, { "[<opt/a>", false }, { "<pat/[0-", false }, { "<opt/a>]", false }, { "|<opt/a>|", false }, { "<pat/[0-9", false }, { "<opt/abcd>", true }, { "<<opt/abcd>", false }, { "<opt/abcd>>", false }, { "[[<opt/a>]]", false }, { "<opt/a><opt/b>", true }, { "<pat/[0-*abc/>", false }, { "<opt/a>|<opt/b>", true }, { "[<opt/a>]<opt/b>", true }, { "<opt/a>{<opt/b>}", true }, { "<opt/a>[<opt/b>]", true }, { "[<opt/a><opt/b>]", true }, { "{<opt/a><opt/b>}", true }, { "|<opt/a>|<opt/b>", false }, { "<opt/a>|<opt/b>|", false }, { "<pat/[0-9]*abc/>", true }, { "[<opt/a>|<opt/b>]", true }, { "{<opt/a>}|<opt/b>", true }, { "[<opt/a>]|<opt/b>", false }, { "<opt/a>|[<opt/b>]", false }, { "[<opt/a>][<opt/b>]", true }, { "[<opt/a>{<opt/b>}]", true }, { "{[<opt/a>]<opt/b>}", true }, { "[<opt/a>]{<opt/b>}", true }, { "[<opt/a>]|[<opt/b>]", false }, { "[[<opt/a>][<opt/b>]]", false }, { "<opt/a><opt/b><opt/c>", true }, { "<opt/a>|<opt/b><opt/c>", true }, { "<opt/a><opt/b>|<opt/c>", true }, { "<opt/a>|<opt/b>|<opt/c>", true }, { "[<opt/a>]<opt/b>|<opt/c>", true }, { "<opt/a>|[<opt/b>]<opt/c>", true }, { "<opt/a>[<opt/b>|<opt/c>]", true }, { "<opt/a>|<opt/b>[<opt/c>]", true }, { "[<opt/a>]<opt/b>|<opt/c>", true }, { "<opt/a>[<opt/b>]|<opt/c>", true }, { "<opt/a>[<opt/b>[<opt/c>]]", true }, { "[<opt/a>]<opt/b>[<opt/c>]", true }, { "<opt/a>|<opt/b>|[<opt/c>]", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", true }, { "[<opt/a>]<opt/b>|[<opt/c>]", false }, { "<opt/a>[<opt/b>[<opt/c>]]]", false }, { "[[<opt/a>]<opt/b>[<opt/c>]", false }, { "[<opt/a>]<opt/b>[<opt/c>]]", false }, { "<opt/a>[[<opt/b>[<opt/c>]]]", false }, { "<pat/^[0-9]*abc.*[a-z0-9]$/>", true }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", true }, { "<opt/a>|<opt/b>|<opt/c>{<opt/d>", false }, { "<opt/a>|<opt/b>|<opt/c>{<opt/d>}", true }, { "<opt/a>|<opt/b>|<opt/c>{<opt/d>}}", false }, { "<opt/a>|[<opt/b>]<opt/c>|<opt/d>", true }, { "<opt/a>[<opt/b>]|<opt/c>|<opt/d>", true }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", true }, { "<opt/a>|[<opt/b>]|<opt/c>|<opt/d>", false }, { "{<opt/a>|<opt/b>[<opt/c>]}<opt/d>", true }, { "<opt/a>{<opt/b>{[<opt/c>]}|<opt/d>", false }, { "{<opt/a>|<opt/b>[<opt/c>]}|<opt/d>", true }, { "<pat/\\<[A-Za-z][A-Za-z0-9]*[^\\>]*\\>", false }, { "<pat/\\<[A-Za-z][A-Za-z0-9]*[^\\>]*\\>/>", true }, { "<opt/a>{<opt/b>{[<opt/c>]}}|<opt/d>", true }, { "<opt/a>{<opt/b>{[<opt/c>]}}|<opt/d>}", false }, { "<opt/a>{<opt/b>{[<opt/c>]}}|<opt/d>}", false }, { "<opt/a>{<opt/b>{[<opt/c>]}}|<opt/d>}}", false }, { "[<opt/a>{[<opt/b>]}|<opt/c>{[<opt/d>]}]", true }, { "{<opt/a>|<opt/b>[<opt/c>]}<opt/d>|<opt/e>", true }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", true }, { "{<opt/a>|<opt/b>[<opt/c>]}<opt/d>[<opt/e>]", true }, { "{<opt/a>|<opt/b>[<opt/c>]}[<opt/d>]|<opt/e>", true }, { "<pat/\\<([A-Za-z][A-Za-z0-9]*)[^\\>]*\\>.*\\<\\\\/\\\\\\\\1\\>/>", true }, { "[<opt/a>{[<opt/b>]}|<opt/c>{[<opt/d>]}]<opt/e>", true }, { "[<opt/a>{[<opt/b>]}|<opt/c>{[<opt/d>]}]<opt/e>]", false }, { "[<opt/a>{[<opt/b>]}|<opt/c>{[<opt/d>]}]<opt/e>}", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]}|<opt/f>]", false }, { "[<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]}|<opt/f>", false }, { "[<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]}|<opt/f>]", true } }; struct command_test { const char* p_syntax; const char* p_command; bool test_should_succeed; } command_tests[ ] = { { "<opt/a>", "", false }, { "<opt/a>", "a", true }, { "<opt/a>", "b", false }, { "<opt/a>", "a a", false }, { "[<opt/a>]", "", true }, { "[<opt/a>]", "a", true }, { "[<opt/a>]", "b", false }, { "[<opt/a>]", "a a", false }, { "{<opt/a>}", "", false }, { "{<opt/a>}", "a", true }, { "<pat/[0-9]>", "", false }, { "<pat/[0-9]>", " ", false }, { "<pat/[0-9]>", "a", false }, { "<pat/[0-9]>", "0", true }, { "<pat/[0-9]>", "9", true }, { "<pat/[0-9]>", " 8 ", true }, { "<pat/[0-9]>", "a1b", true }, { "<pat/[0-9]>", "a b", false }, { "<opt/a><opt/b>", "", false }, { "<opt/a><opt/b>", "a", false }, { "<opt/a><opt/b>", "b", false }, { "<opt/a><opt/b>", "a b", true }, { "<opt/a>|<opt/b>", "", false }, { "<opt/a>|<opt/b>", "a", true }, { "<opt/a>|<opt/b>", "b", true }, { "<opt/a>|<opt/b>", "a b", false }, { "<opt/a>|<opt/b>", "a a b", false }, { "<opt/a>[<opt/b>]", "", false }, { "<opt/a>[<opt/b>]", "a", true }, { "<opt/a>[<opt/b>]", "b", false }, { "<opt/a>[<opt/b>]", "a b", true }, { "{<opt/a>}|<opt/b>", "", false }, { "{<opt/a>}|<opt/b>", "a", true }, { "{<opt/a>}|<opt/b>", "b", true }, { "{<opt/a>}|<opt/b>", "a b", false }, { "[<opt/a>|<opt/b>]", "", true }, { "[<opt/a>|<opt/b>]", "a", true }, { "[<opt/a>|<opt/b>]", "b", true }, { "[<opt/a>|<opt/b>]", "a a", false }, { "[<opt/a>|<opt/b>]", "a b", false }, { "[<opt/a>|<opt/b>]", "b b", false }, { "[<opt/a>][<opt/b>]", "", true }, { "[<opt/a>][<opt/b>]", "a", true }, { "[<opt/a>][<opt/b>]", "b", true }, { "[<opt/a>][<opt/b>]", "c", false }, { "[<opt/a>][<opt/b>]", "a b", true }, { "[<opt/a>][<opt/b>]", "b a", true }, { "[<opt/a>][<opt/b>]", "a b a", false }, { "{<opt/a>}|{<opt/b>}", "", false }, { "{<opt/a>}|{<opt/b>}", "a", true }, { "{<opt/a>}|{<opt/b>}", "b", true }, { "{<opt/a>}|{<opt/b>}", "c", false }, { "{<opt/a>}|{<opt/b>}", "a a", false }, { "{<opt/a>}|{<opt/b>}", "a b", false }, { "{<opt/a>}|{<opt/b>}", "b b", false }, { "<pat/[0-9]*abc/test>", "abc", true }, { "<pat/[0-9]*abc/test>", "1abc", true }, { "<pat/[0-9]*abc/test>", "xabc", true }, { "<pat/[0-9]*abc/test>", "123abc", true }, { "<pat/[0-9]*abc/test>", "x123abc", true }, { "<pat/[0-9]*abc/test>", "x123ab", false }, { "<pat/[0-9].abc/test>", "abc", false }, { "<pat/[0-9].abc/test>", "0abc", false }, { "<pat/[0-9].abc/test>", "0xabc", true }, { "<pat/[0-9].abc/test>", "x9xabc", true }, { "<pat/[0-9]+abc/test>", "abc", false }, { "<pat/[0-9]+abc/test>", "0abc", true }, { "<pat/[0-9]+abc/test>", "01abc", true }, { "<pat/[0-9]+abc/test>", "0xabc", false }, { "<pat/[0-9]+abc/test>", "x012abcd", true }, { "<opt/a><opt/b><opt/c>", "", false }, { "<opt/a><opt/b><opt/c>", "a", false }, { "<opt/a><opt/b><opt/c>", "b", false }, { "<opt/a><opt/b><opt/c>", "c", false }, { "<opt/a><opt/b><opt/c>", "a b", false }, { "<opt/a><opt/b><opt/c>", "a c", false }, { "<opt/a><opt/b><opt/c>", "b c", false }, { "<opt/a><opt/b><opt/c>", "b a", false }, { "<opt/a><opt/b><opt/c>", "c a", false }, { "<opt/a><opt/b><opt/c>", "a b c", true }, { "<opt/a>|<opt/b><opt/c>", "", false }, { "<opt/a>|<opt/b><opt/c>", "a", false }, { "<opt/a>|<opt/b><opt/c>", "b", false }, { "<opt/a>|<opt/b><opt/c>", "c", false }, { "<opt/a>|<opt/b><opt/c>", "a a", false }, { "<opt/a>|<opt/b><opt/c>", "a b", false }, { "<opt/a>|<opt/b><opt/c>", "a c", true }, { "<opt/a>|<opt/b><opt/c>", "b c", true }, { "<opt/a>|<opt/b><opt/c>", "a b c", false }, { "<opt/a>|<opt/b><opt/c>", "a c a", false }, { "<opt/a>|<opt/b><opt/c>", "b c a", false }, { "<opt/a>|<opt/b><opt/c>", "c b a", false }, { "<opt/a>[<opt/b><opt/c>]", "", false }, { "<opt/a>[<opt/b><opt/c>]", "a", true }, { "<opt/a>[<opt/b><opt/c>]", "a b", false }, { "<opt/a>[<opt/b><opt/c>]", "b c", false }, { "<opt/a>[<opt/b><opt/c>]", "a b c", true }, { "<opt/a>[<opt/b><opt/c>]", "a a b c", false }, { "<opt/a>[<opt/b><opt/c>]", "a b b c", false }, { "<opt/a>[<opt/b><opt/c>]", "a b c c", false }, { "<opt/a>|<opt/b>|<opt/c>", "", false }, { "<opt/a>|<opt/b>|<opt/c>", "a", true }, { "<opt/a>|<opt/b>|<opt/c>", "b", true }, { "<opt/a>|<opt/b>|<opt/c>", "c", true }, { "<opt/a>|<opt/b>|<opt/c>", "a b", false }, { "<opt/a>|<opt/b>|<opt/c>", "a c", false }, { "<opt/a>|<opt/b>|<opt/c>", "b c", false }, { "<opt/a>|<opt/b>|<opt/c>", "a b c", false }, { "<opt/a>[<opt/b>]<opt/c>", "a", false }, { "<opt/a>[<opt/b>]<opt/c>", "a b", false }, { "<opt/a>[<opt/b>]<opt/c>", "a c", true }, { "<opt/a>[<opt/b>]<opt/c>", "b c", false }, { "<opt/a>[<opt/b>]<opt/c>", "a b c", true }, { "<opt/a>[<opt/b>]<opt/c>", "a b c b", false }, { "<opt/a>[<opt/b>]<opt/c>", "a a b c", false }, { "<opt/a>[<opt/b>]<opt/c>", "a b b c", false }, { "<pat/[0-9]{2,4}/test>", "abc", false }, { "<pat/[0-9]{2,4}/test>", "1abc", false }, { "<pat/[0-9]{2,4}/test>", "1abc1", false }, { "<pat/[0-9]{2,4}/test>", "abc11", true }, { "<pat/[0-9]{2,4}/test>", "00abc", true }, { "<pat/[0-9]{2,4}/test>", "11abc", true }, { "<pat/[0-9]{2,4}/test>", "01abc", true }, { "<pat/[0-9]{2,4}/test>", "10abc", true }, { "<pat/[0-9]{2,4}/test>", "1abc11", true }, { "<pat/[0-9]{2,4}/test>", "01abc01", true }, { "<pat/[0-9]{2,4}/test>", "abc101", true }, { "<pat/[0-9]{2,4}/test>", "0abc101", true }, { "<pat/abc(def)?ghi/test>", "defghi", false }, { "<pat/abc(def)?ghi/test>", "abcdef", false }, { "<pat/abc(def)?ghi/test>", "bcdefghi", false }, { "<pat/abc(def)?ghi/test>", "abcdefgh", false }, { "<pat/abc(def)?ghi/test>", "abcdefghi", true }, { "<opt/a>|[<opt/b>]<opt/c>", "", false }, { "<opt/a>|[<opt/b>]<opt/c>", "a", true }, { "<opt/a>|[<opt/b>]<opt/c>", "b", false }, { "<opt/a>|[<opt/b>]<opt/c>", "c", true }, { "<opt/a>|[<opt/b>]<opt/c>", "a b", false }, { "<opt/a>|[<opt/b>]<opt/c>", "a c", false }, { "<opt/a>|[<opt/b>]<opt/c>", "b c", true }, { "<opt/a>|[<opt/b>]<opt/c>", "a b c", false }, { "<opt/a>[<opt/b>]|<opt/c>", "a", true }, { "<opt/a>[<opt/b>]|<opt/c>", "b", false }, { "<opt/a>[<opt/b>]|<opt/c>", "c", true }, { "<opt/a>[<opt/b>]|<opt/c>", "a b", true }, { "<opt/a>[<opt/b>]|<opt/c>", "a c", false }, { "<opt/a>[<opt/b>]|<opt/c>", "b c", false }, { "<opt/a>[<opt/b>]|<opt/c>", "a b c", false }, { "<opt/a>[<opt/b>|<opt/c>]", "", false }, { "<opt/a>[<opt/b>|<opt/c>]", "a", true }, { "<opt/a>[<opt/b>|<opt/c>]", "b", false }, { "<opt/a>[<opt/b>|<opt/c>]", "c", false }, { "<opt/a>[<opt/b>|<opt/c>]", "a b", true }, { "<opt/a>[<opt/b>|<opt/c>]", "a c", true }, { "<opt/a>[<opt/b>|<opt/c>]", "b c", false }, { "<opt/a>[<opt/b>|<opt/c>]", "a b c", false }, { "[<opt/a>]<opt/b>|<opt/c>", "", false }, { "[<opt/a>]<opt/b>|<opt/c>", "a", false }, { "[<opt/a>]<opt/b>|<opt/c>", "b", true }, { "[<opt/a>]<opt/b>|<opt/c>", "c", true }, { "[<opt/a>]<opt/b>|<opt/c>", "a b", true }, { "[<opt/a>]<opt/b>|<opt/c>", "a c", true }, { "[<opt/a>]<opt/b>|<opt/c>", "b c", false }, { "[<opt/a>]<opt/b>|<opt/c>", "a b c", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "a", true }, { "<opt/a>[<opt/b>[<opt/c>]]", "b", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "c", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "a b", true }, { "<opt/a>[<opt/b>[<opt/c>]]", "a c", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "b c", false }, { "<opt/a>[<opt/b>[<opt/c>]]", "a b c", true }, { "<opt/a>[<opt/b>{<opt/c>}]", "", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "a", true }, { "<opt/a>[<opt/b>{<opt/c>}]", "b", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "c", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "a b", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "a c", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "b c", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "a b c", true }, { "<opt/a>[<opt/b>{<opt/c>}]", "b c a", false }, { "<opt/a>[<opt/b>{<opt/c>}]", "c b a", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "b", true }, { "[<opt/a>]<opt/b>[<opt/c>]", "a", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "c", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "a b", true }, { "[<opt/a>]<opt/b>[<opt/c>]", "a c", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "b c", true }, { "[<opt/a>]<opt/b>[<opt/c>]", "a b c", true }, { "[<opt/a>]<opt/b>[<opt/c>]", "a a c c", false }, { "[<opt/a>]<opt/b>[<opt/c>]", "a a b b c c", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", "", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", "a", true }, { "{<opt/a>|<opt/b>}[<opt/c>]", "b", true }, { "{<opt/a>|<opt/b>}[<opt/c>]", "c", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", "a b", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", "a c", true }, { "{<opt/a>|<opt/b>}[<opt/c>]", "b c", true }, { "{<opt/a>|<opt/b>}[<opt/c>]", "a c b", false }, { "{<opt/a>|<opt/b>}[<opt/c>]", "a b c", false }, { "{[<opt/a>]<opt/b>}|<opt/c>", "", false }, { "{[<opt/a>]<opt/b>}|<opt/c>", "a", false }, { "{[<opt/a>]<opt/b>}|<opt/c>", "b", true }, { "{[<opt/a>]<opt/b>}|<opt/c>", "c", true }, { "{[<opt/a>]<opt/b>}|<opt/c>", "a b", true }, { "{[<opt/a>]<opt/b>}|<opt/c>", "a c", false }, { "{[<opt/a>]<opt/b>}|<opt/c>", "b c", false }, { "{[<opt/a>]<opt/b>}|<opt/c>", "a b c", false }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "abc", true }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "abd", false }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "1abc", true }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "xabc", false }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "12abc34", true }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "12abc34x", true }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "12abc34X", false }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "x12abc34x", false }, { "<pat/^[0-9]*abc.*[a-z0-9]*$/>", "12abc34x56", true }, { "<pat/^.[0-9]*abc.*[a-z0-9]*$/>", "x12abc34x56", true }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "c", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a b", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a c", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a d", true }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b a", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b b", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b c", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "c d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a b c", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a b d", true }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a c d", true }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "b c d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a a b d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a a c d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a b c d", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a c d e", false }, { "<opt/a>[<opt/b>|<opt/c>]<opt/d>", "a b d e", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a", true }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "b", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "c", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "d", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a d", true }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a b", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a c", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "b c", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "c d", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "b d", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a b d", true }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a c d", true }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a b c", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "b c d", false }, { "<opt/a>[[<opt/b>|<opt/c>]<opt/d>]", "a b c d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a b", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a c", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a d", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "d a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a b c", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a c b", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b a c", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c a b", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c b a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a b d", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a d b", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a c d", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a d c", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b a d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b d a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b c a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b a c", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a b c d", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a c d b", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a d b c", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "a d c b", true }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b a c d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b c a d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "b d c a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c a b d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c b a d", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "c b d a", false }, { "<opt/a>[<opt/b>][<opt/c>][<opt/d>]", "d a b c", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "b", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "c", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "d", true }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a b", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a c", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a d", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "b c", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "b d", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a b c", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a b d", true }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "b a d", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "b c d", false }, { "[<opt/a>{<opt/b>[<opt/c>]}]<opt/d>", "a b c d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a a", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b b", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c c", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d d", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a b c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b a c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b d c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c a b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c b a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a b a", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b a b", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c b c", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b d b", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a d d", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a b c d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b a c d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b c a d", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b c d a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "c d a b", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d a b c", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d c b a", true }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d b c a d", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d b c a a", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "d b c a b", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "a b c d a", false }, { "[<opt/a>][<opt/b>][<opt/c>][<opt/d>]", "b c d a b", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "b", true }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "c", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "d", true }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a b", true }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a c", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a d", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "b c", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "b d", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "c d", true }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a b c", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a b d", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a c d", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "b c d", false }, { "{[<opt/a>]<opt/b>}|[<opt/c>]<opt/d>", "a b c d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "c", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a b", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a c", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b c", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "c d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "c e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a b c", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a c d", true }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a c e", true }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b c d", true }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b c e", true }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "c d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a b c d", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a b d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a c d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "b c d e", false }, { "<opt/a>|<opt/b><opt/c><opt/d>|<opt/e>", "a b c d e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a", true }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c", true }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e", true }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a c", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b a", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b c", true }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c a", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c c", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d a", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d c", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "d e", true }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e a", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e b", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e c", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "e e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a b c", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b c d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "c d e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a b c d", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "b c d e", false }, { "<opt/a>|[<opt/b>]<opt/c>|[<opt/d>]<opt/e>", "a b c d e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "c", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "d", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "e", true }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a b", true }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a c", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a d", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b c", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b d", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "c d", true }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "c e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a b c", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b c d", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "c d e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a b c d", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b c d e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "a b c d e", false }, { "<opt/a>{<opt/b>}|<opt/c>{<opt/d>}|<opt/e>", "b e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a", true }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "b", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "c", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "d", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a b", true }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a c", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a d", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a b c", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a c d", true }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a c e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a d e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a b d", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a b e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "b c d", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "b c e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "c d e", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a b c d", false }, { "<opt/a>[<opt/b>|{<opt/c><opt/d>[<opt/e>]}]", "a c d e", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "c", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a a", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a b", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a c", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b c", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "c c", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "c e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "d e", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "d d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "e e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a b c", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a b c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "b c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{<opt/e>}", "a b c d e", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-a", true }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-b", true }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-c", true }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-d", true }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-a -b", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-b -c", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-c -d", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-a -a", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-b -b", false }, { "{<opt/-a/a>}|{<opt/-b/b>}|{<opt/-c/c>}|<val//d>", "-c -c", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@b", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@b.", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@b.c", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@b.cd", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.d", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.de", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.def", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.de.fg", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defgh", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.def.g", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg.h", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg.hi", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg.hij", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg.hijk", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.defg.hijkl", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,4}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,5}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,6}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,7}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{2,8}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{3,8}$/>", "a@bc.de.fg.hi.jkl", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{4,8}$/>", "a@bc.de.fg.hi.jkl", false }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{4,8}$/>", "a@bc.de.fg.hi.jklm", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{4,8}$/>", "a@bc.de.fg.hi.jklmn", true }, { "<pat/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\\\\\.[A-Za-z]{4,8}$/>", "a@bc.de.fg.hi.jklmno", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<y></y>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<y></ye>", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<ye></y>", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<y>x</y>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<y>xx</y>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "x<y>y</y>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "x<y>y</y>z", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<yes></yes>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<yes>def</no>", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<yes>def</yes>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<!no><yes>def</no>", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<!no><yes>def</yes>", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<!no><yes>def</no>ghi", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "<!no><yes>def</yes>ghi", true }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "abc<!no><yes>def</no>ghi", false }, { "<pat/\\<([a-zA-Z][a-zA-Z0-9]*)[^\\>]*\\>(.*)\\<\\\\/\\\\\\\\1\\>/>", "abc<!no><yes>def</yes>ghi", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "d f", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a d f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b d f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c d f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "d e f", true }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c d", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c d f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "c d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c d e", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c d f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a c d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "b c d e f", false }, { "<opt/a>{[<opt/b>]<opt/c>}|<opt/d>{[<opt/e>]<opt/f>}", "a b c d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "g", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a b", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a c", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a d", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b c", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b d", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c d", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "e g", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a b c", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a c d", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b c d", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "e f g", true }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a b c d", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a c d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a e f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b c d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b e f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c e f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "d e f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "a b c d e", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b c d e f", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "b d e f g", false }, { "<opt/a>|[<opt/b>[<opt/c>]]<opt/d>|[<opt/e>[<opt/f>]]<opt/g>", "c d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "g", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a c", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b c", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d e", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d f", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "e g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b c", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a c d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b c d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d e f", true }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b c d", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a c d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b c d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b c d e", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a c d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b c d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "c d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b c d e f", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a c d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "b c d e f g", false }, { "<opt/a>[<opt/b>][<opt/c>]|<opt/d>[<opt/e>][<opt/f>]|<opt/g>", "a b c d e f g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "g", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a b", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a c", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a d", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b c", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b d", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c d", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d a", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d b", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d c", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "e f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "e g", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "f g", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "g e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "g f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a b c", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b c d", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c b d", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c d e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d e f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "e f g", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "f e g", true }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a b c d", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a c d e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a d e f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "a e f g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b c d e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b d e f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b e f g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "b g f e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c d e f", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c d f e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c f d e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "c e f g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d e f g", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d f g e", false }, { "[<opt/a>|[<opt/b>][<opt/c>]<opt/d>|[<opt/e>][<opt/f>]<opt/g>]", "d g f e", false } }; int main( int argc, char* argv[ ] ) { bool is_quiet = false; try { if( argc > 1 && string( argv[ 1 ] ) == "-quiet" ) { --argc; is_quiet = true; } if( argc > 1 && string( argv[ 1 ] ) == "-test" ) { cout << "performing tests...\n\n"; command_parser p; int num_tests = 0; int num_errors = 0; for( size_t i = 0; i < ARRAY_SIZE( syntax_texts ); i++ ) { #ifdef DEBUG cout << "syntax test #" << i << ": " << syntax_texts[ i ].p_syntax << endl; #endif p.parse_syntax( syntax_texts[ i ].p_syntax ); if( p.okay( ) != syntax_texts[ i ].test_should_succeed ) { ++num_errors; cout << "error: syntax test #" << ( i + 1 ) << ": " << syntax_texts[ i ].p_syntax << ( p.okay( ) ? " succeeded" : " failed" ) << " rather than" << ( syntax_texts[ i ].test_should_succeed ? " succeeded" : " failed" ) << '\n'; } if( p.okay( ) ) { p.output_syntax( cout ); cout << '\n'; } ++num_tests; } for( size_t i = 0; i < ARRAY_SIZE( command_tests ); i++ ) { p.parse_syntax( command_tests[ i ].p_syntax ); if( !p.okay( ) ) { ++num_errors; cout << "error: command test #" << ( i + 1 ) << ": " << command_tests[ i ].p_syntax << " syntax is not valid\n"; } else { vector< string > arguments; map< string, string > parameters; setup_arguments( command_tests[ i ].p_command, arguments ); if( p.parse_command( arguments, parameters ) != command_tests[ i ].test_should_succeed ) { ++num_errors; cout << "error: command test #" << ( i + 1 ) << " command '" << command_tests[ i ].p_command << "' for syntax '" << command_tests[ i ].p_syntax << "'" << ( command_tests[ i ].test_should_succeed ? " failed" : " succeeded" ) << " rather than" << ( command_tests[ i ].test_should_succeed ? " succeeded" : " failed" ) << '\n'; } } ++num_tests; } p.clear( ); if( p.get_num_nodes( ) != 0 ) { ++num_errors; cout << "error: p.get_num_nodes( ) is " << p.get_num_nodes( ) << " when it should be 0\n"; } cout << "\nperformed " << num_tests << " test(s) and found " << num_errors << " error(s)\n"; } else if( argc == 1 ) { #ifdef __GNUG__ # ifdef RDLINE_SUPPORT if( isatty( STDIN_FILENO ) ) using_history( ); # endif #endif command_parser p; string cmd, next; while( cin ) { next = get_line( "\n> " ); if( next.empty( ) ) continue; #ifdef __GNUG__ # ifdef RDLINE_SUPPORT if( isatty( STDIN_FILENO ) ) add_history( next.c_str( ) ); # endif #endif string::size_type pos = next.find( ' ' ); cmd = next.substr( 0, pos ); if( pos == string::npos ) next.erase( ); else next.erase( 0, pos + 1 ); if( cmd == "?" ) { cout << "commands:\n"; cout << "=========\n"; cout << "usage\n"; cout << "dump\n"; cout << "test [<value>]\n"; cout << "syntax [<expr>]\n"; cout << "command [<expr>]\n"; cout << "exit\n"; } else if( cmd == "usage" ) { p.output_usage( cout ); cout << endl; } else if( cmd == "dump" ) { p.dump_nodes( cout ); cout << endl; } else if( cmd == "test" ) { // NOTE: Dummy command for testing or prototyping. cout << next << endl; } else if( cmd == "syntax" ) { if( next.empty( ) ) { p.output_syntax( cout ); cout << endl; continue; } if( next.size( ) > 2 && next[ 0 ] == '"' && next[ next.size( ) - 1 ] == '"' ) { next.erase( 0, 1 ); next.erase( next.length( ) - 1 ); } p.parse_syntax( next.c_str( ) ); if( p.okay( ) ) cout << "okay" << endl; else cout << "error: invalid format '" << next << "'" << endl; } else if( cmd == "command" ) { vector< string > arguments; map< string, string > parameters; setup_arguments( next.c_str( ), arguments ); if( p.parse_command( arguments, parameters ) ) { cout << "okay" << endl; if( !is_quiet ) { map< string, string >::iterator i; if( !parameters.empty( ) ) cout << "\n[parameters]\n"; for( i = parameters.begin( ); i != parameters.end( ); ++i ) cout << "parameter: " << i->first << ", value = '" << i->second << "'\n"; } } else cout << "error: invalid command '" << next << "'" << endl; } else if( cmd == "exit" ) break; else cout << "unknown command '" << cmd << "' (type ? for list of commands)" << endl; } } else cout << "usage: test_parser [-test|-quiet]" << endl; } catch( exception& x ) { cerr << "error: " << x.what( ) << endl; } catch( ... ) { cerr << "error: unexpected exception caught" << endl; } }
55.050293
119
0.409928
[ "vector" ]
4b314b987734a3fd5236ce13216dba8e7ed33f34
2,057
cpp
C++
libs/math/src/TPoint2D.cpp
DavidLee999/mrpt
9f7bcad718906245a7efa4c9760d4d35c43ceb61
[ "BSD-3-Clause" ]
1
2020-02-01T15:43:00.000Z
2020-02-01T15:43:00.000Z
libs/math/src/TPoint2D.cpp
jolting/mrpt
2cfcd3a97aebd49290df5405976b15f8923c35cb
[ "BSD-3-Clause" ]
1
2017-11-30T19:51:29.000Z
2018-02-01T08:15:36.000Z
libs/math/src/TPoint2D.cpp
DavidLee999/mrpt
9f7bcad718906245a7efa4c9760d4d35c43ceb61
[ "BSD-3-Clause" ]
2
2017-01-12T02:08:10.000Z
2018-02-14T23:05:10.000Z
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "math-precomp.h" // Precompiled headers // #include <mrpt/math/TPoint2D.h> #include <mrpt/math/TPoint3D.h> #include <mrpt/math/TPose2D.h> #include <mrpt/math/TPose3D.h> namespace mrpt::math { static_assert(std::is_trivial_v<TPoint2D_data<float>>); static_assert(std::is_trivial_v<TPoint2D_data<double>>); static_assert(std::is_trivially_copyable_v<TPoint2D>); static_assert(std::is_trivially_copyable_v<TPoint2Df>); template <typename T> TPoint2D_<T>::TPoint2D_(const TPose2D& p) : TPoint2D_data<T>{static_cast<T>(p.x), static_cast<T>(p.y)} { } template <typename T> TPoint2D_<T>::TPoint2D_(const TPoint3D_<T>& p) : TPoint2D_data<T>{p.x, p.y} { } template <typename T> TPoint2D_<T>::TPoint2D_(const TPose3D& p) : TPoint2D_data<T>{static_cast<T>(p.x), static_cast<T>(p.y)} { } template <typename T> bool TPoint2D_<T>::operator<(const TPoint2D_<T>& p) const { if (this->x < p.x) return true; else if (this->x > p.x) return false; else return this->y < p.y; } template <typename T> void TPoint2D_<T>::fromString(const std::string& s) { CMatrixDynamic<T> m; if (!m.fromMatlabStringFormat(s)) THROW_EXCEPTION("Malformed expression in ::fromString"); ASSERTMSG_( m.rows() == 1 && m.cols() == 2, "Wrong size of vector in ::fromString"); this->x = m(0, 0); this->y = m(0, 1); } // Explicit instantiations: template struct TPoint2D_<float>; template struct TPoint2D_<double>; } // namespace mrpt::math
30.701493
80
0.586777
[ "vector" ]
4b34490774e0da346f3701c39f6b94111f871139
8,154
cpp
C++
examples/mobilenet_ssd/mssd.cpp
pheng12/Tengine
e1a52d49ae81225fdcde46dd4293bc7778977704
[ "Apache-2.0" ]
1
2019-02-12T08:19:15.000Z
2019-02-12T08:19:15.000Z
examples/mobilenet_ssd/mssd.cpp
xiaoyaozhuzi/Tengine
f377e20b011d48cd37940e04a98f07f06868e4b0
[ "Apache-2.0" ]
null
null
null
examples/mobilenet_ssd/mssd.cpp
xiaoyaozhuzi/Tengine
f377e20b011d48cd37940e04a98f07f06868e4b0
[ "Apache-2.0" ]
3
2019-04-19T01:00:42.000Z
2019-09-17T05:51:07.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2018, Open AI Lab * Author: chunyinglv@openailab.com */ #include <unistd.h> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "tengine_c_api.h" #include <sys/time.h> #include "common.hpp" #define DEF_PROTO "models/MobileNetSSD_deploy.prototxt" #define DEF_MODEL "models/MobileNetSSD_deploy.caffemodel" #define DEF_IMAGE "tests/images/ssd_dog.jpg" struct Box { float x0; float y0; float x1; float y1; int class_idx; float score; }; void get_input_data_ssd(std::string& image_file, float* input_data, int img_h, int img_w) { cv::Mat img = cv::imread(image_file); if (img.empty()) { std::cerr << "Failed to read image file " << image_file << ".\n"; return; } cv::resize(img, img, cv::Size(img_h, img_w)); img.convertTo(img, CV_32FC3); float *img_data = (float *)img.data; int hw = img_h * img_w; float mean[3]={127.5,127.5,127.5}; for (int h = 0; h < img_h; h++) { for (int w = 0; w < img_w; w++) { for (int c = 0; c < 3; c++) { input_data[c * hw + h * img_w + w] = 0.007843* (*img_data - mean[c]); img_data++; } } } } void post_process_ssd(std::string& image_file,float threshold,float* outdata,int num,std::string& save_name) { const char* class_names[] = {"background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"}; cv::Mat img = cv::imread(image_file); int raw_h = img.size().height; int raw_w = img.size().width; std::vector<Box> boxes; int line_width=raw_w*0.005; printf("detect ruesult num: %d \n",num); for (int i=0;i<num;i++) { if(outdata[1]>=threshold) { Box box; box.class_idx=outdata[0]; box.score=outdata[1]; box.x0=outdata[2]*raw_w; box.y0=outdata[3]*raw_h; box.x1=outdata[4]*raw_w; box.y1=outdata[5]*raw_h; boxes.push_back(box); printf("%s\t:%.0f%%\n", class_names[box.class_idx], box.score * 100); printf("BOX:( %g , %g ),( %g , %g )\n",box.x0,box.y0,box.x1,box.y1); } outdata+=6; } for(int i=0;i<(int)boxes.size();i++) { Box box=boxes[i]; cv::rectangle(img, cv::Rect(box.x0, box.y0,(box.x1-box.x0),(box.y1-box.y0)),cv::Scalar(255, 255, 0),line_width); std::ostringstream score_str; score_str<<box.score; std::string label = std::string(class_names[box.class_idx]) + ": " + score_str.str(); int baseLine = 0; cv::Size label_size = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); cv::rectangle(img, cv::Rect(cv::Point(box.x0,box.y0- label_size.height), cv::Size(label_size.width, label_size.height + baseLine)), cv::Scalar(255, 255, 0), CV_FILLED); cv::putText(img, label, cv::Point(box.x0, box.y0), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); } cv::imwrite(save_name,img); std::cout<<"======================================\n"; std::cout<<"[DETECTED IMAGE SAVED]:\t"<< save_name<<"\n"; std::cout<<"======================================\n"; } int main(int argc, char *argv[]) { const std::string root_path = get_root_path(); std::string proto_file; std::string model_file; std::string image_file; std::string save_name="save.jpg"; int res; while( ( res=getopt(argc,argv,"p:m:i:h"))!= -1) { switch(res) { case 'p': proto_file=optarg; break; case 'm': model_file=optarg; break; case 'i': image_file=optarg; break; case 'h': std::cout << "[Usage]: " << argv[0] << " [-h]\n" << " [-p proto_file] [-m model_file] [-i image_file]\n"; return 0; default: break; } } const char *model_name = "mssd_300"; if(proto_file.empty()) { proto_file = root_path + DEF_PROTO; std::cout<< "proto file not specified,using "<<proto_file<< " by default\n"; } if(model_file.empty()) { model_file = root_path + DEF_MODEL; std::cout<< "model file not specified,using "<<model_file<< " by default\n"; } if(image_file.empty()) { image_file = root_path + DEF_IMAGE; std::cout<< "image file not specified,using "<<image_file<< " by default\n"; } // init tengine init_tengine_library(); if (request_tengine_version("0.1") < 0) return 1; if (load_model(model_name, "caffe", proto_file.c_str(), model_file.c_str()) < 0) return 1; std::cout << "load model done!\n"; // create graph graph_t graph = create_runtime_graph("graph", model_name, NULL); if (!check_graph_valid(graph)) { std::cout << "create graph0 failed\n"; return 1; } // input int img_h = 300; int img_w = 300; int img_size = img_h * img_w * 3; float *input_data = (float *)malloc(sizeof(float) * img_size); int node_idx=0; int tensor_idx=0; tensor_t input_tensor = get_graph_input_tensor(graph, node_idx, tensor_idx); if(!check_tensor_valid(input_tensor)) { std::printf("Get input node failed : node_idx: %d, tensor_idx: %d\n",node_idx,tensor_idx); return 1; } int dims[] = {1, 3, img_h, img_w}; set_tensor_shape(input_tensor, dims, 4); prerun_graph(graph); int repeat_count = 1; const char *repeat = std::getenv("REPEAT_COUNT"); if (repeat) repeat_count = std::strtoul(repeat, NULL, 10); struct timeval t0, t1; float total_time = 0.f; for (int i = 0; i < repeat_count; i++) { get_input_data_ssd(image_file, input_data, img_h, img_w); gettimeofday(&t0, NULL); set_tensor_buffer(input_tensor, input_data, img_size * 4); run_graph(graph, 1); gettimeofday(&t1, NULL); float mytime = (float)((t1.tv_sec * 1000000 + t1.tv_usec) - (t0.tv_sec * 1000000 + t0.tv_usec)) / 1000; total_time += mytime; } std::cout << "--------------------------------------\n"; std::cout << "repeat " << repeat_count << " times, avg time per run is " << total_time / repeat_count << " ms\n"; tensor_t out_tensor = get_graph_output_tensor(graph, 0,0);//"detection_out"); int out_dim[4]; get_tensor_shape( out_tensor, out_dim, 4); float *outdata = (float *)get_tensor_buffer(out_tensor); int num=out_dim[1]; float show_threshold=0.5; post_process_ssd(image_file,show_threshold, outdata, num,save_name); postrun_graph(graph); free(input_data); destroy_runtime_graph(graph); remove_model(model_name); return 0; }
31.604651
120
0.568801
[ "vector", "model" ]
4b358218da57b45b17b1703af0cd1df7089ca7b3
3,451
cpp
C++
extern/tbb-2019-u4/examples/parallel_do/parallel_preorder/main.cpp
robgrzel/OpenCV_Examples
f504483325ad9a307690a95d3cf5e9f5e7dbd99c
[ "BSD-2-Clause" ]
13
2021-08-23T03:37:46.000Z
2022-02-16T03:00:09.000Z
examples/parallel_do/parallel_preorder/main.cpp
chissg/tbb
2ace525889b0c3de9c90da943fac9259220ef35f
[ "Apache-2.0" ]
2
2021-11-12T10:19:47.000Z
2021-12-21T14:26:36.000Z
examples/parallel_do/parallel_preorder/main.cpp
chissg/tbb
2ace525889b0c3de9c90da943fac9259220ef35f
[ "Apache-2.0" ]
4
2021-09-03T13:55:05.000Z
2021-11-09T10:59:33.000Z
/* Copyright (c) 2005-2019 Intel 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. */ /* Example program that shows how to use parallel_do to do parallel preorder traversal of a directed acyclic graph. */ #include <cstdlib> #include "tbb/task_scheduler_init.h" #include "tbb/tick_count.h" #include "../../common/utility/utility.h" #include <iostream> #include <vector> #include "Graph.h" // some forward declarations class Cell; void ParallelPreorderTraversal( const std::vector<Cell*>& root_set ); //------------------------------------------------------------------------ // Test driver //------------------------------------------------------------------------ utility::thread_number_range threads(tbb::task_scheduler_init::default_num_threads); static unsigned nodes = 1000; static unsigned traversals = 500; static bool SilentFlag = false; //! Parse the command line. static void ParseCommandLine( int argc, const char* argv[] ) { utility::parse_cli_arguments( argc,argv, utility::cli_argument_pack() //"-h" option for displaying help is present implicitly .positional_arg(threads,"n-of-threads",utility::thread_number_range_desc) .positional_arg(nodes,"n-of-nodes","number of nodes in the graph.") .positional_arg(traversals,"n-of-traversals","number of times to evaluate the graph. Reduce it (e.g. to 100) to shorten example run time\n") .arg(SilentFlag,"silent","no output except elapsed time ") ); } int main( int argc, const char* argv[] ) { try { tbb::tick_count main_start = tbb::tick_count::now(); ParseCommandLine(argc,argv); // Start scheduler with given number of threads. for( int p=threads.first; p<=threads.last; p = threads.step(p) ) { tbb::tick_count t0 = tbb::tick_count::now(); tbb::task_scheduler_init init(p); srand(2); size_t root_set_size = 0; { Graph g; g.create_random_dag(nodes); std::vector<Cell*> root_set; g.get_root_set(root_set); root_set_size = root_set.size(); for( unsigned int trial=0; trial<traversals; ++trial ) { ParallelPreorderTraversal(root_set); } } tbb::tick_count::interval_t interval = tbb::tick_count::now()-t0; if (!SilentFlag){ std::cout <<interval.seconds()<<" seconds using "<<p<<" threads ("<<root_set_size<<" nodes in root_set)\n"; } } utility::report_elapsed_time((tbb::tick_count::now()-main_start).seconds()); return 0; }catch(std::exception& e){ std::cerr << "unexpected error occurred. \n" << "error description: "<<e.what()<<std::endl; return -1; } }
36.712766
156
0.597798
[ "vector" ]
4b38f3e5731f31b14df0ab2f569d9a223f299f24
2,432
cpp
C++
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/3rdparty/HalideIR/src/base/Util.cpp
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
193
2017-08-18T03:17:02.000Z
2022-02-09T07:00:45.000Z
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/3rdparty/HalideIR/src/base/Util.cpp
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
23
2019-07-29T05:21:52.000Z
2020-08-31T18:51:42.000Z
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/3rdparty/HalideIR/src/base/Util.cpp
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
58
2017-10-09T20:18:58.000Z
2022-02-23T05:40:47.000Z
#include "./Util.h" #include "./Debug.h" #include "./Error.h" #include <string> #include <vector> namespace HalideIR { namespace Internal { std::vector<std::string> split_string(const std::string &source, const std::string &delim) { std::vector<std::string> elements; size_t start = 0; size_t found = 0; while ((found = source.find(delim, start)) != std::string::npos) { elements.push_back(source.substr(start, found - start)); start = found + delim.size(); } // If start is exactly source.size(), the last thing in source is a // delimiter, in which case we want to add an empty string to elements. if (start <= source.size()) { elements.push_back(source.substr(start, std::string::npos)); } return elements; } std::string extract_namespaces(const std::string &name, std::vector<std::string> &namespaces) { namespaces = split_string(name, "::"); std::string result = namespaces.back(); namespaces.pop_back(); return result; } bool add_would_overflow(int bits, int64_t a, int64_t b) { int64_t max_val = 0x7fffffffffffffffLL >> (64 - bits); int64_t min_val = -max_val - 1; return ((b > 0 && a > max_val - b) || // (a + b) > max_val, rewritten to avoid overflow (b < 0 && a < min_val - b)); // (a + b) < min_val, rewritten to avoid overflow } bool sub_would_overflow(int bits, int64_t a, int64_t b) { int64_t max_val = 0x7fffffffffffffffLL >> (64 - bits); int64_t min_val = -max_val - 1; return ((b < 0 && a > max_val + b) || // (a - b) > max_val, rewritten to avoid overflow (b > 0 && a < min_val + b)); // (a - b) < min_val, rewritten to avoid overflow } bool mul_would_overflow(int bits, int64_t a, int64_t b) { int64_t max_val = 0x7fffffffffffffffLL >> (64 - bits); int64_t min_val = -max_val - 1; if (a == 0) { return false; } else if (a == -1) { return b == min_val; } else { // Do the multiplication as a uint64, for which overflow is // well defined, then cast the bits back to int64 to get // multiplication modulo 2^64. int64_t ab = (int64_t)((uint64_t)a)*((uint64_t)b); // The first two clauses catch overflow mod 2^bits, assuming // no 64-bit overflow occurs, and the third clause catches // 64-bit overflow. return ab < min_val || ab > max_val || (ab / a != b); } } } }
34.742857
95
0.612664
[ "vector" ]
4b3f33adf2dabc909d6758ff681b0a38d3c1d061
2,027
cpp
C++
BAC_2nd/ch6/UVa122b.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch6/UVa122b.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch6/UVa122b.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa122 Trees on the level // Rujia Liu #include<cstdio> #include<cstdlib> #include<cstring> #include<vector> #include<queue> using namespace std; const int maxn = 256 + 10; struct Node{ bool have_value; int v; Node* left, *right; Node():have_value(false),left(NULL),right(NULL){} }; Node* root; queue<Node*> freenodes; // 空闲列表 Node node[maxn]; // 内存池 void init() { for(int i = 0; i < maxn; i++) freenodes.push(&node[i]); } Node* newnode() { Node* u = freenodes.front(); u->left = u->right = NULL; u->have_value = false; // 重新初始化该结点 freenodes.pop(); return u; } void deletenode(Node* u) { freenodes.push(u); } bool failed; void addnode(int v, char* s) { int n = strlen(s); Node* u = root; for(int i = 0; i < n; i++) if(s[i] == 'L') { if(u->left == NULL) u->left = newnode(); u = u->left; } else if(s[i] == 'R') { if(u->right == NULL) u->right = newnode(); u = u->right; } if(u->have_value) failed = true; u->v = v; u->have_value = true; } void remove_tree(Node* u) { if(u == NULL) return; remove_tree(u->left); remove_tree(u->right); deletenode(u); } char s[maxn]; bool read_input() { failed = false; remove_tree(root); root = newnode(); for(;;) { if(scanf("%s", s) != 1) return false; if(!strcmp(s, "()")) break; int v; sscanf(&s[1], "%d", &v); addnode(v, strchr(s, ',')+1); } return true; } bool bfs(vector<int>& ans) { queue<Node*> q; ans.clear(); q.push(root); while(!q.empty()) { Node* u = q.front(); q.pop(); if(!u->have_value) return false; ans.push_back(u->v); if(u->left != NULL) q.push(u->left); if(u->right != NULL) q.push(u->right); } return true; } int main() { vector<int> ans; init(); while(read_input()) { if(!bfs(ans)) failed = 1; if(failed) printf("not complete\n"); else { for(int i = 0; i < ans.size(); i++) { if(i != 0) printf(" "); printf("%d", ans[i]); } printf("\n"); } } return 0; }
18.59633
63
0.544154
[ "vector" ]
4b47ac23573bda73b6ae3a34a1113aa79f1dabb6
4,260
cpp
C++
GenTest/src/modules/TranslationEngine/CrudeListener.cpp
ZwFink/deepstate
fbbecae988fec0519cf56e4f1b341dc6dcac587e
[ "Apache-2.0" ]
null
null
null
GenTest/src/modules/TranslationEngine/CrudeListener.cpp
ZwFink/deepstate
fbbecae988fec0519cf56e4f1b341dc6dcac587e
[ "Apache-2.0" ]
null
null
null
GenTest/src/modules/TranslationEngine/CrudeListener.cpp
ZwFink/deepstate
fbbecae988fec0519cf56e4f1b341dc6dcac587e
[ "Apache-2.0" ]
1
2020-03-09T22:15:33.000Z
2020-03-09T22:15:33.000Z
// Program Header Information /////////////////////////// /** * @file CrudeListener.cpp * * @team GenTest ( Team 22 ) * * @brief Main file for the Crude Listener class. * * @details Contains the implementation of the Crude Listener Interface. * * @version 0.15 * Joshua Johnson ( 31 January 2020 ) * Initial incorporation of ANTLR library into GenTest codebase. */ //#include "CrudeListener.h" //void CrudeListener::enterDeepstate_noinline( GenTestParser::Deepstate_noinlineContext * ctx ) //{ // // Initialize new node. // node newNode; // // Configure newNode. // newNode.type = DEEPSTATE_NOINLINE; // newNode.lineNum = ctx->getStart()->getLine(); // newNode.colNum = ctx->getStop()->getStopIndex(); // // // Push to back of vector. // CrudeListener::transList.push_back( newNode ); //} //void CrudeListener::enterDs_assert( GenTestParser::Ds_assertContext * ctx ) //{ // // Initialize new node. // node newNode; // // Configure newNode. // newNode.type = DEEPSTATE_ASSERT; // newNode.lineNum = ctx->getStart()->getLine(); // newNode.colNum = ctx->getStop()->getStopIndex(); // // // Push to back of vector. // CrudeListener::transList.push_back( newNode ); //} //void CrudeListener::enterDs_assume( GenTestParser::Ds_assumeContext * ctx ) //{ // // Initialize new node. // node newNode; // // Configure newNode. // newNode.type = DEEPSTATE_ASSUME; // newNode.lineNum = ctx->getStart()->getLine(); // newNode.colNum = ctx->getStop()->getStopIndex(); // // // Push to back of vector. // CrudeListener::transList.push_back( newNode ); //} //void CrudeListener::enterDs_check( GenTestParser::Ds_checkContext * ctx ) //{ // // Initialize new node. // node newNode; // // Configure newNode. // newNode.type = DEEPSTATE_CHECK; // newNode.lineNum = ctx->getStart()->getLine(); // newNode.colNum = ctx->getStop()->getStopIndex(); // // // Push to back of vector. // CrudeListener::transList.push_back( newNode ); //} //void CrudeListener::enterSymbolic( GenTestParser::SymbolicContext * ctx ) //{ // // Initialize new node. // node newNode; // // Configure newNode. // newNode.lineNum = ctx->getStart()->getLine(); // newNode.colNum = ctx->getStop()->getStopIndex(); // // // Push to back of vector. // CrudeListener::transList.push_back( newNode ); // // Set flag. // CrudeListener::typeFlag = true; //} //void CrudeListener::enterType( GenTestParser::TypeContext * ctx ) //{ // if( CrudeListener::typeFlag ) // { // // Initialize pointer. // node * endPtr = &( CrudeListener::transList.at( CrudeListener::transList.size() - 1 ) ); // std::string type = ctx->getStart()->getText(); // // Initialize node to symbolic. // if( type.compare( "int" ) == 0 ) // { // endPtr->type = X_INT; // } // else if( type.compare( "double" ) == 0 ) // { // endPtr->type = X_DOUBLE; // } // else if( type.compare( "short" ) == 0 ) // { // endPtr->type = X_SHORT; // } // else if( type.compare( "long" ) == 0 ) // { // endPtr->type = X_LONG; // } // else if( type.compare( "uint8_t" ) == 0 ) // { // endPtr->type = X_UINT8; // } // else if( type.compare( "uint16_t" ) == 0 ) // { // endPtr->type = X_UINT16; // } // else if( type.compare( "uint32_t" ) == 0 ) // { // endPtr->type = X_UINT32; // } // else if( type.compare( "uint64_t" ) == 0 ) // { // endPtr->type = X_UINT64; // } // else if( type.compare( "char" ) == 0 ) // { // endPtr->type = X_CHAR; // } // else if( type.compare( "float" ) == 0 ) // { // endPtr->type = X_FLOAT; // } // else if( type.compare( "unsigned" ) == 0 ) // { // endPtr->type = X_UNSIGNED; // } // // Reset flag. // CrudeListener::typeFlag = false; // } //} //std::vector<node> CrudeListener::getList() //{ // return CrudeListener::transList; //}
27.483871
98
0.546244
[ "vector" ]
4b4c2a374987db9630fe97c5237df3df084b078b
1,931
cpp
C++
aws-cpp-sdk-glue/source/model/RemoveSchemaVersionMetadataResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-glue/source/model/RemoveSchemaVersionMetadataResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-glue/source/model/RemoveSchemaVersionMetadataResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/glue/model/RemoveSchemaVersionMetadataResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Glue::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; RemoveSchemaVersionMetadataResult::RemoveSchemaVersionMetadataResult() : m_latestVersion(false), m_versionNumber(0) { } RemoveSchemaVersionMetadataResult::RemoveSchemaVersionMetadataResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_latestVersion(false), m_versionNumber(0) { *this = result; } RemoveSchemaVersionMetadataResult& RemoveSchemaVersionMetadataResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("SchemaArn")) { m_schemaArn = jsonValue.GetString("SchemaArn"); } if(jsonValue.ValueExists("SchemaName")) { m_schemaName = jsonValue.GetString("SchemaName"); } if(jsonValue.ValueExists("RegistryName")) { m_registryName = jsonValue.GetString("RegistryName"); } if(jsonValue.ValueExists("LatestVersion")) { m_latestVersion = jsonValue.GetBool("LatestVersion"); } if(jsonValue.ValueExists("VersionNumber")) { m_versionNumber = jsonValue.GetInt64("VersionNumber"); } if(jsonValue.ValueExists("SchemaVersionId")) { m_schemaVersionId = jsonValue.GetString("SchemaVersionId"); } if(jsonValue.ValueExists("MetadataKey")) { m_metadataKey = jsonValue.GetString("MetadataKey"); } if(jsonValue.ValueExists("MetadataValue")) { m_metadataValue = jsonValue.GetString("MetadataValue"); } return *this; }
22.195402
134
0.740031
[ "model" ]
4b4e7285791518e4313fd43da35f3abd2608277f
10,160
cpp
C++
native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/renderer/pipeline/custom/LayoutGraphTypes.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. 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. ****************************************************************************/ /** * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= * The following section is auto-generated. * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ // clang-format off #include "LayoutGraphTypes.h" namespace cc { namespace render { UniformBlockDB::UniformBlockDB(const allocator_type& alloc) noexcept : values(alloc) {} UniformBlockDB::UniformBlockDB(UniformBlockDB&& rhs, const allocator_type& alloc) : values(std::move(rhs.values), alloc) {} UniformBlockDB::UniformBlockDB(UniformBlockDB const& rhs, const allocator_type& alloc) : values(rhs.values, alloc) {} DescriptorBlock::DescriptorBlock(const allocator_type& alloc) noexcept : descriptors(alloc), uniformBlocks(alloc), merged(alloc) {} DescriptorBlock::DescriptorBlock(DescriptorBlock&& rhs, const allocator_type& alloc) : descriptors(std::move(rhs.descriptors), alloc), uniformBlocks(std::move(rhs.uniformBlocks), alloc), merged(std::move(rhs.merged), alloc), capacity(rhs.capacity), start(rhs.start), count(rhs.count) {} DescriptorBlock::DescriptorBlock(DescriptorBlock const& rhs, const allocator_type& alloc) : descriptors(rhs.descriptors, alloc), uniformBlocks(rhs.uniformBlocks, alloc), merged(rhs.merged, alloc), capacity(rhs.capacity), start(rhs.start), count(rhs.count) {} DescriptorDB::DescriptorDB(const allocator_type& alloc) noexcept : blocks(alloc) {} DescriptorDB::DescriptorDB(DescriptorDB&& rhs, const allocator_type& alloc) : blocks(std::move(rhs.blocks), alloc) {} DescriptorDB::DescriptorDB(DescriptorDB const& rhs, const allocator_type& alloc) : blocks(rhs.blocks, alloc) {} RenderPhase::RenderPhase(const allocator_type& alloc) noexcept : shaders(alloc) {} RenderPhase::RenderPhase(RenderPhase&& rhs, const allocator_type& alloc) : shaders(std::move(rhs.shaders), alloc) {} RenderPhase::RenderPhase(RenderPhase const& rhs, const allocator_type& alloc) : shaders(rhs.shaders, alloc) {} LayoutGraph::LayoutGraph(const allocator_type& alloc) noexcept : vertices(alloc), names(alloc), descriptors(alloc), stages(alloc), phases(alloc), pathIndex(alloc) {} LayoutGraph::LayoutGraph(LayoutGraph&& rhs, const allocator_type& alloc) : vertices(std::move(rhs.vertices), alloc), names(std::move(rhs.names), alloc), descriptors(std::move(rhs.descriptors), alloc), stages(std::move(rhs.stages), alloc), phases(std::move(rhs.phases), alloc), pathIndex(std::move(rhs.pathIndex), alloc) {} LayoutGraph::LayoutGraph(LayoutGraph const& rhs, const allocator_type& alloc) : vertices(rhs.vertices, alloc), names(rhs.names, alloc), descriptors(rhs.descriptors, alloc), stages(rhs.stages, alloc), phases(rhs.phases, alloc), pathIndex(rhs.pathIndex, alloc) {} // ContinuousContainer void LayoutGraph::reserve(vertices_size_type sz) { vertices.reserve(sz); names.reserve(sz); descriptors.reserve(sz); } LayoutGraph::Vertex::Vertex(const allocator_type& alloc) noexcept : outEdges(alloc), inEdges(alloc) {} LayoutGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) : outEdges(std::move(rhs.outEdges), alloc), inEdges(std::move(rhs.inEdges), alloc), handle(std::move(rhs.handle)) {} LayoutGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc), handle(rhs.handle) {} UniformBlockData::UniformBlockData(const allocator_type& alloc) noexcept : uniforms(alloc) {} UniformBlockData::UniformBlockData(UniformBlockData&& rhs, const allocator_type& alloc) : bufferSize(rhs.bufferSize), uniforms(std::move(rhs.uniforms), alloc) {} UniformBlockData::UniformBlockData(UniformBlockData const& rhs, const allocator_type& alloc) : bufferSize(rhs.bufferSize), uniforms(rhs.uniforms, alloc) {} DescriptorBlockData::DescriptorBlockData(const allocator_type& alloc) noexcept : descriptors(alloc), uniformBlocks(alloc) {} DescriptorBlockData::DescriptorBlockData(DescriptorIndex typeIn, uint32_t capacityIn, const allocator_type& alloc) noexcept : type(typeIn), capacity(capacityIn), descriptors(alloc), uniformBlocks(alloc) {} DescriptorBlockData::DescriptorBlockData(DescriptorBlockData&& rhs, const allocator_type& alloc) : type(rhs.type), capacity(rhs.capacity), descriptors(std::move(rhs.descriptors), alloc), uniformBlocks(std::move(rhs.uniformBlocks), alloc) {} DescriptorBlockData::DescriptorBlockData(DescriptorBlockData const& rhs, const allocator_type& alloc) : type(rhs.type), capacity(rhs.capacity), descriptors(rhs.descriptors, alloc), uniformBlocks(rhs.uniformBlocks, alloc) {} DescriptorTableData::DescriptorTableData(const allocator_type& alloc) noexcept : descriptorBlocks(alloc) {} DescriptorTableData::DescriptorTableData(uint32_t tableIDIn, uint32_t capacityIn, const allocator_type& alloc) noexcept // NOLINT : tableID(tableIDIn), capacity(capacityIn), descriptorBlocks(alloc) {} DescriptorTableData::DescriptorTableData(DescriptorTableData&& rhs, const allocator_type& alloc) : tableID(rhs.tableID), capacity(rhs.capacity), descriptorBlocks(std::move(rhs.descriptorBlocks), alloc) {} DescriptorTableData::DescriptorTableData(DescriptorTableData const& rhs, const allocator_type& alloc) : tableID(rhs.tableID), capacity(rhs.capacity), descriptorBlocks(rhs.descriptorBlocks, alloc) {} DescriptorSetData::DescriptorSetData(const allocator_type& alloc) noexcept : tables(alloc) {} DescriptorSetData::DescriptorSetData(DescriptorSetData&& rhs, const allocator_type& alloc) : tables(std::move(rhs.tables), alloc) {} DescriptorSetData::DescriptorSetData(DescriptorSetData const& rhs, const allocator_type& alloc) : tables(rhs.tables, alloc) {} PipelineLayoutData::PipelineLayoutData(const allocator_type& alloc) noexcept : descriptorSets(alloc) {} PipelineLayoutData::PipelineLayoutData(PipelineLayoutData&& rhs, const allocator_type& alloc) : descriptorSets(std::move(rhs.descriptorSets), alloc) {} PipelineLayoutData::PipelineLayoutData(PipelineLayoutData const& rhs, const allocator_type& alloc) : descriptorSets(rhs.descriptorSets, alloc) {} ShaderProgramData::ShaderProgramData(const allocator_type& alloc) noexcept : layout(alloc) {} ShaderProgramData::ShaderProgramData(ShaderProgramData&& rhs, const allocator_type& alloc) : layout(std::move(rhs.layout), alloc) {} ShaderProgramData::ShaderProgramData(ShaderProgramData const& rhs, const allocator_type& alloc) : layout(rhs.layout, alloc) {} RenderPhaseData::RenderPhaseData(const allocator_type& alloc) noexcept : rootSignature(alloc), shaderPrograms(alloc), shaderIndex(alloc) {} RenderPhaseData::RenderPhaseData(RenderPhaseData&& rhs, const allocator_type& alloc) : rootSignature(std::move(rhs.rootSignature), alloc), shaderPrograms(std::move(rhs.shaderPrograms), alloc), shaderIndex(std::move(rhs.shaderIndex), alloc) {} RenderPhaseData::RenderPhaseData(RenderPhaseData const& rhs, const allocator_type& alloc) : rootSignature(rhs.rootSignature, alloc), shaderPrograms(rhs.shaderPrograms, alloc), shaderIndex(rhs.shaderIndex, alloc) {} LayoutGraphData::LayoutGraphData(const allocator_type& alloc) noexcept : vertices(alloc), names(alloc), updateFrequencies(alloc), layouts(alloc), stages(alloc), phases(alloc), pathIndex(alloc) {} LayoutGraphData::LayoutGraphData(LayoutGraphData&& rhs, const allocator_type& alloc) : vertices(std::move(rhs.vertices), alloc), names(std::move(rhs.names), alloc), updateFrequencies(std::move(rhs.updateFrequencies), alloc), layouts(std::move(rhs.layouts), alloc), stages(std::move(rhs.stages), alloc), phases(std::move(rhs.phases), alloc), pathIndex(std::move(rhs.pathIndex), alloc) {} LayoutGraphData::LayoutGraphData(LayoutGraphData const& rhs, const allocator_type& alloc) : vertices(rhs.vertices, alloc), names(rhs.names, alloc), updateFrequencies(rhs.updateFrequencies, alloc), layouts(rhs.layouts, alloc), stages(rhs.stages, alloc), phases(rhs.phases, alloc), pathIndex(rhs.pathIndex, alloc) {} // ContinuousContainer void LayoutGraphData::reserve(vertices_size_type sz) { vertices.reserve(sz); names.reserve(sz); updateFrequencies.reserve(sz); layouts.reserve(sz); } LayoutGraphData::Vertex::Vertex(const allocator_type& alloc) noexcept : outEdges(alloc), inEdges(alloc) {} LayoutGraphData::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) : outEdges(std::move(rhs.outEdges), alloc), inEdges(std::move(rhs.inEdges), alloc), handle(std::move(rhs.handle)) {} LayoutGraphData::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc), handle(rhs.handle) {} } // namespace render } // namespace cc // clang-format on
36.546763
129
0.751083
[ "render" ]
4b4f0b93df412e96fbe7bcdfef0e187db33413e5
10,570
hpp
C++
include/GlobalNamespace/MockPause.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MockPause.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MockPause.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: IGamePause #include "GlobalNamespace/IGamePause.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Action class Action; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: MockPause class MockPause; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::MockPause); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::MockPause*, "", "MockPause"); // Type namespace: namespace GlobalNamespace { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: MockPause // [TokenAttribute] Offset: FFFFFFFF class MockPause : public ::Il2CppObject/*, public ::GlobalNamespace::IGamePause*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Action didPauseEvent // Size: 0x8 // Offset: 0x10 ::System::Action* didPauseEvent; // Field size check static_assert(sizeof(::System::Action*) == 0x8); // private System.Action willResumeEvent // Size: 0x8 // Offset: 0x18 ::System::Action* willResumeEvent; // Field size check static_assert(sizeof(::System::Action*) == 0x8); // private System.Action didResumeEvent // Size: 0x8 // Offset: 0x20 ::System::Action* didResumeEvent; // Field size check static_assert(sizeof(::System::Action*) == 0x8); public: // Creating interface conversion operator: operator ::GlobalNamespace::IGamePause operator ::GlobalNamespace::IGamePause() noexcept { return *reinterpret_cast<::GlobalNamespace::IGamePause*>(this); } // Get instance field reference: private System.Action didPauseEvent ::System::Action*& dyn_didPauseEvent(); // Get instance field reference: private System.Action willResumeEvent ::System::Action*& dyn_willResumeEvent(); // Get instance field reference: private System.Action didResumeEvent ::System::Action*& dyn_didResumeEvent(); // public System.Boolean get_isPaused() // Offset: 0x13C5C6C bool get_isPaused(); // public System.Void add_didPauseEvent(System.Action value) // Offset: 0x13C5C74 void add_didPauseEvent(::System::Action* value); // public System.Void remove_didPauseEvent(System.Action value) // Offset: 0x13C5D18 void remove_didPauseEvent(::System::Action* value); // public System.Void add_willResumeEvent(System.Action value) // Offset: 0x13C5DBC void add_willResumeEvent(::System::Action* value); // public System.Void remove_willResumeEvent(System.Action value) // Offset: 0x13C5E60 void remove_willResumeEvent(::System::Action* value); // public System.Void add_didResumeEvent(System.Action value) // Offset: 0x13C5F04 void add_didResumeEvent(::System::Action* value); // public System.Void remove_didResumeEvent(System.Action value) // Offset: 0x13C5FA8 void remove_didResumeEvent(::System::Action* value); // public System.Void Pause() // Offset: 0x13C604C void Pause(); // public System.Void WillResume() // Offset: 0x13C60AC void WillResume(); // public System.Void Resume() // Offset: 0x13C610C void Resume(); // public System.Void .ctor() // Offset: 0x13C616C // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MockPause* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::MockPause::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MockPause*, creationType>())); } }; // MockPause #pragma pack(pop) static check_size<sizeof(MockPause), 32 + sizeof(::System::Action*)> __GlobalNamespace_MockPauseSizeCheck; static_assert(sizeof(MockPause) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::MockPause::get_isPaused // Il2CppName: get_isPaused template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MockPause::*)()>(&GlobalNamespace::MockPause::get_isPaused)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "get_isPaused", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::add_didPauseEvent // Il2CppName: add_didPauseEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::add_didPauseEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "add_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::remove_didPauseEvent // Il2CppName: remove_didPauseEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::remove_didPauseEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "remove_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::add_willResumeEvent // Il2CppName: add_willResumeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::add_willResumeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "add_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::remove_willResumeEvent // Il2CppName: remove_willResumeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::remove_willResumeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "remove_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::add_didResumeEvent // Il2CppName: add_didResumeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::add_didResumeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "add_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::remove_didResumeEvent // Il2CppName: remove_didResumeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)(::System::Action*)>(&GlobalNamespace::MockPause::remove_didResumeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "remove_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::Pause // Il2CppName: Pause template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)()>(&GlobalNamespace::MockPause::Pause)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "Pause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::WillResume // Il2CppName: WillResume template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)()>(&GlobalNamespace::MockPause::WillResume)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "WillResume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::Resume // Il2CppName: Resume template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MockPause::*)()>(&GlobalNamespace::MockPause::Resume)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MockPause*), "Resume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MockPause::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
50.094787
182
0.719868
[ "object", "vector" ]