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
9cae76998620ee738818d0bf761d50b1ffa06290
30,890
cpp
C++
aws-cpp-sdk-license-manager/source/LicenseManagerClient.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-license-manager/source/LicenseManagerClient.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-license-manager/source/LicenseManagerClient.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/license-manager/LicenseManagerClient.h> #include <aws/license-manager/LicenseManagerEndpoint.h> #include <aws/license-manager/LicenseManagerErrorMarshaller.h> #include <aws/license-manager/model/CreateLicenseConfigurationRequest.h> #include <aws/license-manager/model/DeleteLicenseConfigurationRequest.h> #include <aws/license-manager/model/GetLicenseConfigurationRequest.h> #include <aws/license-manager/model/GetServiceSettingsRequest.h> #include <aws/license-manager/model/ListAssociationsForLicenseConfigurationRequest.h> #include <aws/license-manager/model/ListLicenseConfigurationsRequest.h> #include <aws/license-manager/model/ListLicenseSpecificationsForResourceRequest.h> #include <aws/license-manager/model/ListResourceInventoryRequest.h> #include <aws/license-manager/model/ListTagsForResourceRequest.h> #include <aws/license-manager/model/ListUsageForLicenseConfigurationRequest.h> #include <aws/license-manager/model/TagResourceRequest.h> #include <aws/license-manager/model/UntagResourceRequest.h> #include <aws/license-manager/model/UpdateLicenseConfigurationRequest.h> #include <aws/license-manager/model/UpdateLicenseSpecificationsForResourceRequest.h> #include <aws/license-manager/model/UpdateServiceSettingsRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::LicenseManager; using namespace Aws::LicenseManager::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "license-manager"; static const char* ALLOCATION_TAG = "LicenseManagerClient"; LicenseManagerClient::LicenseManagerClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<LicenseManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LicenseManagerClient::LicenseManagerClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<LicenseManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LicenseManagerClient::LicenseManagerClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<LicenseManagerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LicenseManagerClient::~LicenseManagerClient() { } void LicenseManagerClient::init(const ClientConfiguration& config) { m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + LicenseManagerEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void LicenseManagerClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } CreateLicenseConfigurationOutcome LicenseManagerClient::CreateLicenseConfiguration(const CreateLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return CreateLicenseConfigurationOutcome(CreateLicenseConfigurationResult(outcome.GetResult())); } else { return CreateLicenseConfigurationOutcome(outcome.GetError()); } } CreateLicenseConfigurationOutcomeCallable LicenseManagerClient::CreateLicenseConfigurationCallable(const CreateLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::CreateLicenseConfigurationAsync(const CreateLicenseConfigurationRequest& request, const CreateLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::CreateLicenseConfigurationAsyncHelper(const CreateLicenseConfigurationRequest& request, const CreateLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateLicenseConfiguration(request), context); } DeleteLicenseConfigurationOutcome LicenseManagerClient::DeleteLicenseConfiguration(const DeleteLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteLicenseConfigurationOutcome(DeleteLicenseConfigurationResult(outcome.GetResult())); } else { return DeleteLicenseConfigurationOutcome(outcome.GetError()); } } DeleteLicenseConfigurationOutcomeCallable LicenseManagerClient::DeleteLicenseConfigurationCallable(const DeleteLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::DeleteLicenseConfigurationAsync(const DeleteLicenseConfigurationRequest& request, const DeleteLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::DeleteLicenseConfigurationAsyncHelper(const DeleteLicenseConfigurationRequest& request, const DeleteLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteLicenseConfiguration(request), context); } GetLicenseConfigurationOutcome LicenseManagerClient::GetLicenseConfiguration(const GetLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetLicenseConfigurationOutcome(GetLicenseConfigurationResult(outcome.GetResult())); } else { return GetLicenseConfigurationOutcome(outcome.GetError()); } } GetLicenseConfigurationOutcomeCallable LicenseManagerClient::GetLicenseConfigurationCallable(const GetLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::GetLicenseConfigurationAsync(const GetLicenseConfigurationRequest& request, const GetLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::GetLicenseConfigurationAsyncHelper(const GetLicenseConfigurationRequest& request, const GetLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetLicenseConfiguration(request), context); } GetServiceSettingsOutcome LicenseManagerClient::GetServiceSettings(const GetServiceSettingsRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetServiceSettingsOutcome(GetServiceSettingsResult(outcome.GetResult())); } else { return GetServiceSettingsOutcome(outcome.GetError()); } } GetServiceSettingsOutcomeCallable LicenseManagerClient::GetServiceSettingsCallable(const GetServiceSettingsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetServiceSettingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetServiceSettings(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::GetServiceSettingsAsync(const GetServiceSettingsRequest& request, const GetServiceSettingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetServiceSettingsAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::GetServiceSettingsAsyncHelper(const GetServiceSettingsRequest& request, const GetServiceSettingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetServiceSettings(request), context); } ListAssociationsForLicenseConfigurationOutcome LicenseManagerClient::ListAssociationsForLicenseConfiguration(const ListAssociationsForLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListAssociationsForLicenseConfigurationOutcome(ListAssociationsForLicenseConfigurationResult(outcome.GetResult())); } else { return ListAssociationsForLicenseConfigurationOutcome(outcome.GetError()); } } ListAssociationsForLicenseConfigurationOutcomeCallable LicenseManagerClient::ListAssociationsForLicenseConfigurationCallable(const ListAssociationsForLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAssociationsForLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAssociationsForLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListAssociationsForLicenseConfigurationAsync(const ListAssociationsForLicenseConfigurationRequest& request, const ListAssociationsForLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAssociationsForLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListAssociationsForLicenseConfigurationAsyncHelper(const ListAssociationsForLicenseConfigurationRequest& request, const ListAssociationsForLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAssociationsForLicenseConfiguration(request), context); } ListLicenseConfigurationsOutcome LicenseManagerClient::ListLicenseConfigurations(const ListLicenseConfigurationsRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListLicenseConfigurationsOutcome(ListLicenseConfigurationsResult(outcome.GetResult())); } else { return ListLicenseConfigurationsOutcome(outcome.GetError()); } } ListLicenseConfigurationsOutcomeCallable LicenseManagerClient::ListLicenseConfigurationsCallable(const ListLicenseConfigurationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListLicenseConfigurationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListLicenseConfigurations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListLicenseConfigurationsAsync(const ListLicenseConfigurationsRequest& request, const ListLicenseConfigurationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListLicenseConfigurationsAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListLicenseConfigurationsAsyncHelper(const ListLicenseConfigurationsRequest& request, const ListLicenseConfigurationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListLicenseConfigurations(request), context); } ListLicenseSpecificationsForResourceOutcome LicenseManagerClient::ListLicenseSpecificationsForResource(const ListLicenseSpecificationsForResourceRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListLicenseSpecificationsForResourceOutcome(ListLicenseSpecificationsForResourceResult(outcome.GetResult())); } else { return ListLicenseSpecificationsForResourceOutcome(outcome.GetError()); } } ListLicenseSpecificationsForResourceOutcomeCallable LicenseManagerClient::ListLicenseSpecificationsForResourceCallable(const ListLicenseSpecificationsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListLicenseSpecificationsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListLicenseSpecificationsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListLicenseSpecificationsForResourceAsync(const ListLicenseSpecificationsForResourceRequest& request, const ListLicenseSpecificationsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListLicenseSpecificationsForResourceAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListLicenseSpecificationsForResourceAsyncHelper(const ListLicenseSpecificationsForResourceRequest& request, const ListLicenseSpecificationsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListLicenseSpecificationsForResource(request), context); } ListResourceInventoryOutcome LicenseManagerClient::ListResourceInventory(const ListResourceInventoryRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListResourceInventoryOutcome(ListResourceInventoryResult(outcome.GetResult())); } else { return ListResourceInventoryOutcome(outcome.GetError()); } } ListResourceInventoryOutcomeCallable LicenseManagerClient::ListResourceInventoryCallable(const ListResourceInventoryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListResourceInventoryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListResourceInventory(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListResourceInventoryAsync(const ListResourceInventoryRequest& request, const ListResourceInventoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListResourceInventoryAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListResourceInventoryAsyncHelper(const ListResourceInventoryRequest& request, const ListResourceInventoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListResourceInventory(request), context); } ListTagsForResourceOutcome LicenseManagerClient::ListTagsForResource(const ListTagsForResourceRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListTagsForResourceOutcome(ListTagsForResourceResult(outcome.GetResult())); } else { return ListTagsForResourceOutcome(outcome.GetError()); } } ListTagsForResourceOutcomeCallable LicenseManagerClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTagsForResource(request), context); } ListUsageForLicenseConfigurationOutcome LicenseManagerClient::ListUsageForLicenseConfiguration(const ListUsageForLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return ListUsageForLicenseConfigurationOutcome(ListUsageForLicenseConfigurationResult(outcome.GetResult())); } else { return ListUsageForLicenseConfigurationOutcome(outcome.GetError()); } } ListUsageForLicenseConfigurationOutcomeCallable LicenseManagerClient::ListUsageForLicenseConfigurationCallable(const ListUsageForLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListUsageForLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListUsageForLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::ListUsageForLicenseConfigurationAsync(const ListUsageForLicenseConfigurationRequest& request, const ListUsageForLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListUsageForLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::ListUsageForLicenseConfigurationAsyncHelper(const ListUsageForLicenseConfigurationRequest& request, const ListUsageForLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListUsageForLicenseConfiguration(request), context); } TagResourceOutcome LicenseManagerClient::TagResource(const TagResourceRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return TagResourceOutcome(TagResourceResult(outcome.GetResult())); } else { return TagResourceOutcome(outcome.GetError()); } } TagResourceOutcomeCallable LicenseManagerClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome LicenseManagerClient::UntagResource(const UntagResourceRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UntagResourceOutcome(UntagResourceResult(outcome.GetResult())); } else { return UntagResourceOutcome(outcome.GetError()); } } UntagResourceOutcomeCallable LicenseManagerClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); } UpdateLicenseConfigurationOutcome LicenseManagerClient::UpdateLicenseConfiguration(const UpdateLicenseConfigurationRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateLicenseConfigurationOutcome(UpdateLicenseConfigurationResult(outcome.GetResult())); } else { return UpdateLicenseConfigurationOutcome(outcome.GetError()); } } UpdateLicenseConfigurationOutcomeCallable LicenseManagerClient::UpdateLicenseConfigurationCallable(const UpdateLicenseConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateLicenseConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateLicenseConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::UpdateLicenseConfigurationAsync(const UpdateLicenseConfigurationRequest& request, const UpdateLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateLicenseConfigurationAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::UpdateLicenseConfigurationAsyncHelper(const UpdateLicenseConfigurationRequest& request, const UpdateLicenseConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateLicenseConfiguration(request), context); } UpdateLicenseSpecificationsForResourceOutcome LicenseManagerClient::UpdateLicenseSpecificationsForResource(const UpdateLicenseSpecificationsForResourceRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateLicenseSpecificationsForResourceOutcome(UpdateLicenseSpecificationsForResourceResult(outcome.GetResult())); } else { return UpdateLicenseSpecificationsForResourceOutcome(outcome.GetError()); } } UpdateLicenseSpecificationsForResourceOutcomeCallable LicenseManagerClient::UpdateLicenseSpecificationsForResourceCallable(const UpdateLicenseSpecificationsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateLicenseSpecificationsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateLicenseSpecificationsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::UpdateLicenseSpecificationsForResourceAsync(const UpdateLicenseSpecificationsForResourceRequest& request, const UpdateLicenseSpecificationsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateLicenseSpecificationsForResourceAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::UpdateLicenseSpecificationsForResourceAsyncHelper(const UpdateLicenseSpecificationsForResourceRequest& request, const UpdateLicenseSpecificationsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateLicenseSpecificationsForResource(request), context); } UpdateServiceSettingsOutcome LicenseManagerClient::UpdateServiceSettings(const UpdateServiceSettingsRequest& request) const { Aws::StringStream ss; Aws::Http::URI uri = m_uri; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return UpdateServiceSettingsOutcome(UpdateServiceSettingsResult(outcome.GetResult())); } else { return UpdateServiceSettingsOutcome(outcome.GetError()); } } UpdateServiceSettingsOutcomeCallable LicenseManagerClient::UpdateServiceSettingsCallable(const UpdateServiceSettingsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateServiceSettingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateServiceSettings(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LicenseManagerClient::UpdateServiceSettingsAsync(const UpdateServiceSettingsRequest& request, const UpdateServiceSettingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateServiceSettingsAsyncHelper( request, handler, context ); } ); } void LicenseManagerClient::UpdateServiceSettingsAsyncHelper(const UpdateServiceSettingsRequest& request, const UpdateServiceSettingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateServiceSettings(request), context); }
47.891473
296
0.797443
[ "model" ]
9cb066b5082ef93acf60712f4fdfc82b32277632
8,153
cpp
C++
externals/IFCConvert/src/IFCC_Surface.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
externals/IFCConvert/src/IFCC_Surface.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
externals/IFCConvert/src/IFCC_Surface.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
#include "IFCC_Surface.h" #include <limits> #include <fstream> #include <sstream> #include <IBK_math.h> #include <IBK_assert.h> #include "IFCC_Clippertools.h" #include "IFCC_Helper.h" //#define SURFACE_DUMP namespace IFCC { Surface::Surface() : m_id(-1), m_elementEntityId(-1), m_positionType(PT_Unknown), m_virtualSurface(false) { } Surface::Surface(carve::mesh::Face<3>* face) : m_id(-1), m_elementEntityId(-1), m_positionType(PT_Unknown), m_virtualSurface(false) { IBK_ASSERT(face != nullptr); std::vector<carve::mesh::Vertex<3>* > vertices; face->getVertices(vertices); for(size_t vi=0; vi<vertices.size(); ++vi) { double x = vertices[vi]->v.x; double y = vertices[vi]->v.y; double z = vertices[vi]->v.z; m_polyVect.emplace_back(IBKMK::Vector3D(x,y,z)); } m_planeCarve = face->plane; PlaneHesseNormal hesse(face->plane); m_planeNormal = PlaneNormal(hesse, m_polyVect); } Surface::Surface(const polygon3D_t& polygon) : m_id(-1), m_elementEntityId(-1), m_positionType(PT_Unknown), m_virtualSurface(false), m_polyVect(polygon) { if(m_polyVect.size() > 2) { m_planeNormal = PlaneNormal(polygon); PlaneHesseNormal planeHesseNormal(polygon); m_planeCarve.N = carve::geom::VECTOR(planeHesseNormal.m_n0.m_x,planeHesseNormal.m_n0.m_x,planeHesseNormal.m_n0.m_x); m_planeCarve.d = planeHesseNormal.m_d; } } void Surface::set(int id, int elementId, const std::string& name, bool isVirtual) { m_id = id; m_elementEntityId = elementId; m_name = name; m_virtualSurface = isVirtual; } double Surface::distanceToParallelPlane(const Surface& other) const { double negFact = 1.0; if(!nearEqual(m_planeNormal.m_lz, other.m_planeNormal.m_lz)) { if(!nearEqual(m_planeNormal.m_lz*-1,other.m_planeNormal.m_lz)) return std::numeric_limits<double>::max(); else negFact = -1.0; } double dist = std::fabs(other.m_planeNormal.m_distance - (m_planeNormal.m_distance * negFact)); IBKMK::Vector3D t = m_polyVect[0] - other.m_polyVect[0]; // double dist2 = t.scalarProduct(PlaneHesseNormal(m_polyVect).m_n0); return dist; } bool Surface::isParallelTo(const Surface& other) const { double a; double b; double c; carve::geom::vector<3> v1 = m_planeCarve.N; carve::geom::vector<3> v2 = other.m_planeCarve.N; if(IBK::near_zero(v2.x)) { if(!IBK::near_zero(v1.x)) return false; a = 1; } else { a = v1.x / v2.x; } if(IBK::near_zero(v2.y)) { if(!IBK::near_zero(v1.y)) return false; b = 1; } else { b = v1.y / v2.y; } if(IBK::near_zero(v2.z)) { if(!IBK::near_zero(v1.z)) return false; c = 1; } else { c = v1.z / v2.z; } if(IBK::near_equal(a,b) && IBK::near_equal(a,c)) { return true; } carve::geom::vector<3> negV1 = v1.negated(); if(IBK::near_zero(v2.x)) { if(!IBK::near_zero(negV1.x)) return false; a = 1; } else { a = negV1.x / v2.x; } if(IBK::near_zero(v2.y)) { if(!IBK::near_zero(negV1.y)) return false; b = 1; } else { b = negV1.y / v2.y; } if(IBK::near_zero(v2.z)) { if(!IBK::near_zero(negV1.z)) return false; c = 1; } else { c = negV1.z / v2.z; } if(IBK::near_equal(a,b) && IBK::near_equal(a,c)) { return true; } return false; } std::vector<std::pair<size_t,size_t>> Surface::samePoints(const Surface& other) const { std::vector<std::pair<size_t,size_t>> equalPoints; const std::vector<IBKMK::Vector3D>& otherPoly = other.polygon(); for(size_t i=0; i<m_polyVect.size(); ++i) { for(size_t j=0; j<otherPoly.size(); ++j) { if(nearEqual(m_polyVect[i], otherPoly[j])) equalPoints.push_back(std::make_pair(i,j)); } } return equalPoints; } bool Surface::isIntersected(const Surface& other) const { polygon3D_t result = intersectPolygons(m_polyVect, other.polygon(), m_planeNormal); if(result.empty() || areaPolygon(result) < 1e-4) return false; return true; // return intersects(m_polyVectOrg, other.polygon()); } Surface Surface::intersect(const Surface& other) const { polygon3D_t result = intersectPolygons(m_polyVect, other.polygon(), m_planeNormal); if(result.empty() || areaPolygon(result) < 1e-4) return Surface(); return Surface(result); } Surface::IntersectionResult Surface::intersect2(const Surface& other) const { IFCC::IntersectionResult tmp = intersectPolygons2(m_polyVect, other.polygon(), m_planeNormal); Surface::IntersectionResult result; for(const polygon3D_t& poly : tmp.m_intersections) { if(poly.size() > 3 && areaPolygon(poly) > 1e-4) result.m_intersections.push_back(Surface(poly)); } for(size_t i=0; i<tmp.m_diffBaseMinusClip.size(); ++i) { const polygon3D_t& poly = tmp.m_diffBaseMinusClip[i]; if(poly.size() > 3 && areaPolygon(poly) > 1e-4) { result.m_diffBaseMinusClip.push_back(Surface(poly)); result.m_holesBaseMinusClip.push_back(std::vector<Surface>()); for(const polygon3D_t& hole : tmp.m_holesBaseMinusClip[i]) { if(hole.size() > 3 && areaPolygon(hole) > 1e-4) result.m_holesBaseMinusClip.back().push_back(hole); } } } for(size_t i=0; i<tmp.m_diffClipMinusBase.size(); ++i) { const polygon3D_t& poly = tmp.m_diffClipMinusBase[i]; if(poly.size() > 3 && areaPolygon(poly) > 1e-4) { result.m_diffClipMinusBase.push_back(Surface(poly)); result.m_holesClipMinusBase.push_back(std::vector<Surface>()); for(const polygon3D_t& hole : tmp.m_holesClipMinusBase[i]) { if(hole.size() > 3 && areaPolygon(hole) > 1e-4) result.m_holesClipMinusBase.back().push_back(hole); } } } return result; } bool Surface::merge(const Surface& subsurface) { polygon3D_t result = mergePolygons(m_polyVect, subsurface.polygon(), m_planeNormal); if(result.empty()) return false; m_polyVect = result; return true; } bool Surface::addSubSurface(const Surface& subsurface) { SubSurface sub(subsurface.polygon(), *this); if(!sub.isValid()) return false; sub.set(GUID_maker::instance().guid(), subsurface.m_name, subsurface.m_elementEntityId); m_subSurfaces.push_back(sub); return true; } double Surface::area() const { return areaPolygon(m_polyVect); } TiXmlElement * Surface::writeXML(TiXmlElement * parent) const { if (m_id == -1) return nullptr; TiXmlElement * e = new TiXmlElement("Surface"); parent->LinkEndChild(e); e->SetAttribute("id", IBK::val2string<unsigned int>(m_id)); if (!m_name.empty()) e->SetAttribute("displayName", m_name); // e->SetAttribute("visible", IBK::val2string<bool>(true)); if(!m_polyVect.empty()) { TiXmlElement * child = new TiXmlElement("Polygon3D"); e->LinkEndChild(child); std::stringstream vals; for (unsigned int i=0; i<m_polyVect.size(); ++i) { vals << m_polyVect[i].m_x << " " << m_polyVect[i].m_y << " " << m_polyVect[i].m_z; if (i<m_polyVect.size()-1) vals << ", "; } TiXmlText * text = new TiXmlText( vals.str() ); child->LinkEndChild( text ); } if(!m_subSurfaces.empty()) { TiXmlElement * child = new TiXmlElement("SubSurfaces"); e->LinkEndChild(child); for( const SubSurface& subsurface : m_subSurfaces) { subsurface.writeXML(child); } } return e; } void Surface::setSurfaceType(IfcInternalOrExternalEnum::IfcInternalOrExternalEnumEnum type) { switch(type) { case IfcInternalOrExternalEnum::ENUM_INTERNAL: m_positionType = Surface::PT_Internal; break; case IfcInternalOrExternalEnum::ENUM_EXTERNAL: m_positionType = Surface::PT_External; break; case IfcInternalOrExternalEnum::ENUM_EXTERNAL_EARTH: m_positionType = Surface::PT_External_Ground; break; case IfcInternalOrExternalEnum::ENUM_EXTERNAL_WATER: case IfcInternalOrExternalEnum::ENUM_EXTERNAL_FIRE: case IfcInternalOrExternalEnum::ENUM_NOTDEFINED: m_positionType = Surface::PT_Unknown; break; } } bool Surface::isValid() const { return m_polyVect.size() > 2; } VICUS::Surface Surface::getVicusObject() const { VICUS::Surface res; res.m_displayName = QString::fromUtf8(m_name.c_str()); res.setPolygon3D(m_polyVect); std::vector<VICUS::SubSurface> vicusSubs; for(const auto& subsurf : m_subSurfaces) { VICUS::SubSurface vs; vs.m_displayName = QString::fromUtf8(subsurf.name().c_str()); vs.m_polygon2D = subsurf.polygon(); vicusSubs.push_back(vs); } res.setSubSurfaces(vicusSubs); return res; } } // namespace IFCC
26.643791
118
0.703054
[ "mesh", "vector" ]
9cb527946a74efbb10166b70c99720c3feadeee0
6,741
hpp
C++
ext/restbed/source/corvusoft/restbed/request.hpp
SCP-1310-JP/openscp1310jp1
79465672a0e8c7867ac063f86bdc75e9e932b20b
[ "BSD-3-Clause" ]
1
2021-05-21T13:46:23.000Z
2021-05-21T13:46:23.000Z
ext/restbed/source/corvusoft/restbed/request.hpp
SCP-1310-JP/openscp1310jp1
79465672a0e8c7867ac063f86bdc75e9e932b20b
[ "BSD-3-Clause" ]
7
2018-04-06T07:30:18.000Z
2018-05-06T14:29:03.000Z
ext/restbed/source/corvusoft/restbed/request.hpp
SCP-1310-JP/openscp1310jp1
79465672a0e8c7867ac063f86bdc75e9e932b20b
[ "BSD-3-Clause" ]
6
2018-02-14T00:29:47.000Z
2018-11-10T12:32:58.000Z
/* * Copyright 2013-2016, Corvusoft Ltd, All Rights Reserved. */ #ifndef _RESTBED_REQUEST_H #define _RESTBED_REQUEST_H 1 //System Includes #include <map> #include <limits> #include <string> #include <memory> #include <cstdint> #include <stdexcept> #include <functional> //Project Includes #include <corvusoft/restbed/byte.hpp> #include <corvusoft/restbed/common.hpp> //External Includes //System Namespaces //Project Namespaces //External Namespaces namespace restbed { //Forward Declarations class Uri; class Http; class Session; class Response; namespace detail { class HttpImpl; class SessionImpl; class ServiceImpl; struct RequestImpl; class WebSocketManagerImpl; } class Request { public: //Friends //Definitions //Constructors Request( void ); Request( const Uri& value ); virtual ~Request( void ); //Functionality bool has_header( const std::string& name ) const; bool has_path_parameter( const std::string& name ) const; bool has_query_parameter( const std::string& name ) const; //Getters uint16_t get_port( void ) const; double get_version( void ) const; const Bytes& get_body( void ) const; const std::shared_ptr< const Response > get_response( void ) const; std::string get_host( const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::string get_path( const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::string get_method( const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::string get_protocol( const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; void get_body( std::string& body, const std::function< std::string ( const Bytes& ) >& transform = nullptr ) const; template< typename Type, typename std::enable_if< std::is_arithmetic< Type >::value, Type >::type = 0 > Type get_header( const std::string& name, const Type default_value ) const { return Common::parse_parameter( get_header( name ), default_value ); } std::string get_header( const std::string& name, const std::string& default_value ) const; std::string get_header( const std::string& name, const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::multimap< std::string, std::string > get_headers( const std::string& name = "" ) const; template< typename Type, typename std::enable_if< std::is_arithmetic< Type >::value, Type >::type = 0 > Type get_query_parameter( const std::string& name, const Type default_value ) const { return Common::parse_parameter( get_query_parameter( name ), default_value ); } std::string get_query_parameter( const std::string& name, const std::string& default_value ) const; std::string get_query_parameter( const std::string& name, const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::multimap< std::string, std::string > get_query_parameters( const std::string& name = "" ) const; template< typename Type, typename std::enable_if< std::is_arithmetic< Type >::value, Type >::type = 0 > Type get_path_parameter( const std::string& name, const Type default_value ) const { return Common::parse_parameter( get_path_parameter( name ), default_value ); } std::string get_path_parameter( const std::string& name, const std::string& default_value ) const; std::string get_path_parameter( const std::string& name, const std::function< std::string ( const std::string& ) >& transform = nullptr ) const; std::map< std::string, std::string > get_path_parameters( const std::string& name = "" ) const; //Setters void set_body( const Bytes& value ); void set_body( const std::string& value ); void set_port( const uint16_t value ); void set_version( const double value ); void set_path( const std::string& value ); void set_host( const std::string& value ); void set_method( const std::string& value ); void set_protocol( const std::string& value ); void add_header( const std::string& name, const std::string& value ); void set_header( const std::string& name, const std::string& value ); void set_headers( const std::multimap< std::string, std::string >& values ); void set_query_parameter( const std::string& name, const std::string& value ); void set_query_parameters( const std::multimap< std::string, std::string >& values ); //Operators //Properties protected: //Friends //Definitions //Constructors //Functionality //Getters //Setters //Operators //Properties private: //Friends friend Http; friend Session; friend detail::HttpImpl; friend detail::SessionImpl; friend detail::ServiceImpl; friend detail::WebSocketManagerImpl; //Definitions //Constructors Request( const Request& original ) = delete; //Functionality //Getters //Setters //Operators Request& operator =( const Request& value ) = delete; //Properties std::unique_ptr< detail::RequestImpl > m_pimpl; }; } #endif /* _RESTBED_REQUEST_H */
33.874372
157
0.534342
[ "transform" ]
9cb721cc2d7e3669c864cd174dcc9e158310169f
5,492
cxx
C++
src/Cxx/Interaction/MoveAVertexUnstructuredGrid.cxx
cvandijck/VTKExamples
b6bb89414522afc1467be8a1f0089a37d0c16883
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/Interaction/MoveAVertexUnstructuredGrid.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/Interaction/MoveAVertexUnstructuredGrid.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkSmartPointer.h> #include <vtkPointPicker.h> #include <vtkSphereSource.h> #include <vtkGlyph3D.h> #include <vtkPointData.h> #include <vtkIdTypeArray.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkRendererCollection.h> #include <vtkProperty.h> #include <vtkPlanes.h> #include <vtkObjectFactory.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkPolyData.h> #include <vtkPointSource.h> #include <vtkInteractorStyleTrackballActor.h> #include <vtkAreaPicker.h> #include <vtkExtractGeometry.h> #include <vtkDataSetMapper.h> #include <vtkUnstructuredGrid.h> #include <vtkVertexGlyphFilter.h> #include <vtkIdFilter.h> // Define interaction style class InteractorStyleMoveVertex : public vtkInteractorStyleTrackballActor { public: static InteractorStyleMoveVertex* New(); vtkTypeMacro(InteractorStyleMoveVertex,vtkInteractorStyleTrackballActor); InteractorStyleMoveVertex() { this->Move = false; this->PointPicker = vtkSmartPointer<vtkPointPicker>::New(); // Setup ghost glyph vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0,0,0); this->MovePolyData = vtkSmartPointer<vtkPolyData>::New(); this->MovePolyData->SetPoints(points); this->MoveGlyphFilter = vtkSmartPointer<vtkVertexGlyphFilter>::New(); this->MoveGlyphFilter->SetInputData(this->MovePolyData); this->MoveGlyphFilter->Update(); this->MoveMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); this->MoveMapper->SetInputConnection(this->MoveGlyphFilter->GetOutputPort()); this->MoveActor = vtkSmartPointer<vtkActor>::New(); this->MoveActor->SetMapper(this->MoveMapper); this->MoveActor->VisibilityOff(); this->MoveActor->GetProperty()->SetPointSize(10); this->MoveActor->GetProperty()->SetColor(1,0,0); } void OnMouseMove() override { if(!this->Move) { return; } vtkInteractorStyleTrackballActor::OnMouseMove(); } void OnMiddleButtonUp() override { this->EndPan(); this->Move = false; this->MoveActor->VisibilityOff(); this->Data->GetPoints()->SetPoint(this->SelectedPoint, this->MoveActor->GetPosition()); this->Data->Modified(); this->GetCurrentRenderer()->Render(); this->GetCurrentRenderer()->GetRenderWindow()->Render(); } void OnMiddleButtonDown() override { // Get the selected point int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; this->FindPokedRenderer(x, y); this->PointPicker->Pick(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1], 0, // always zero. this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()); if(this->PointPicker->GetPointId() >= 0) { this->StartPan(); this->MoveActor->VisibilityOn(); this->Move = true; this->SelectedPoint = this->PointPicker->GetPointId(); std::cout << "Dragging point " << this->SelectedPoint << std::endl; double p[3]; this->Data->GetPoint(this->SelectedPoint, p); std::cout << "p: " << p[0] << " " << p[1] << " " << p[2] << std::endl; this->MoveActor->SetPosition(p); this->GetCurrentRenderer()->AddActor(this->MoveActor); this->InteractionProp = this->MoveActor; } } vtkUnstructuredGrid* Data; vtkPolyData* GlyphData; vtkSmartPointer<vtkPolyDataMapper> MoveMapper; vtkSmartPointer<vtkActor> MoveActor; vtkSmartPointer<vtkPolyData> MovePolyData; vtkSmartPointer<vtkVertexGlyphFilter> MoveGlyphFilter; vtkSmartPointer<vtkPointPicker> PointPicker; bool Move; vtkIdType SelectedPoint; }; vtkStandardNewMacro(InteractorStyleMoveVertex); int main (int, char *[]) { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0,0,0); points->InsertNextPoint(1,0,0); points->InsertNextPoint(2,0,0); vtkSmartPointer<vtkUnstructuredGrid> input = vtkSmartPointer<vtkUnstructuredGrid>::New(); input->SetPoints(points); vtkSmartPointer<vtkVertexGlyphFilter> glyphFilter = vtkSmartPointer<vtkVertexGlyphFilter>::New(); glyphFilter->SetInputData(input); glyphFilter->Update(); // Create a mapper and actor vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(glyphFilter->GetOutputPort()); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); actor->GetProperty()->SetPointSize(10); // Visualize vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); //renderer->SetBackground(1,1,1); // Background color white renderWindow->Render(); vtkSmartPointer<InteractorStyleMoveVertex> style = vtkSmartPointer<InteractorStyleMoveVertex>::New(); renderWindowInteractor->SetInteractorStyle( style ); style->Data = input; renderWindowInteractor->Start(); return EXIT_SUCCESS; }
30.853933
101
0.715768
[ "render" ]
9cb783fb0d45ac3c4032763f875ac24c9ad58cfd
8,939
hxx
C++
Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkMeanSquaresImageToImageMetric_hxx #define itkMeanSquaresImageToImageMetric_hxx #include "itkCovariantVector.h" #include "itkImageRegionIterator.h" #include "itkImageIterator.h" #include "itkMath.h" namespace itk { /** * Constructor */ template <typename TFixedImage, typename TMovingImage> MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::MeanSquaresImageToImageMetric() { this->SetComputeGradient(true); m_PerThread = nullptr; this->m_WithinThreadPreProcess = false; this->m_WithinThreadPostProcess = false; // For backward compatibility, the default behavior is to use all the pixels // in the fixed image. // This should be fixed in ITKv4 so that this metric behaves as the others. this->SetUseAllPixels(true); } template <typename TFixedImage, typename TMovingImage> MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::~MeanSquaresImageToImageMetric() { delete[] m_PerThread; m_PerThread = nullptr; } /** * Print out internal information about this class */ template <typename TFixedImage, typename TMovingImage> void MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /** * Initialize */ template <typename TFixedImage, typename TMovingImage> void MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::Initialize() { this->Superclass::Initialize(); this->Superclass::MultiThreadingInitialize(); delete[] m_PerThread; m_PerThread = new AlignedPerThreadType[this->m_NumberOfWorkUnits]; for (ThreadIdType workUnitID = 0; workUnitID < this->m_NumberOfWorkUnits; ++workUnitID) { m_PerThread[workUnitID].m_MSEDerivative.SetSize(this->m_NumberOfParameters); } } template <typename TFixedImage, typename TMovingImage> inline bool MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::GetValueThreadProcessSample( ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue) const { double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; m_PerThread[threadId].m_MSE += diff * diff; return true; } template <typename TFixedImage, typename TMovingImage> auto MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::GetValue(const ParametersType & parameters) const -> MeasureType { itkDebugMacro("GetValue( " << parameters << " ) "); if (!this->m_FixedImage) { itkExceptionMacro(<< "Fixed image has not been assigned"); } for (unsigned int i = 0; i < this->m_NumberOfWorkUnits; ++i) { m_PerThread[i].m_MSE = NumericTraits<MeasureType>::ZeroValue(); } // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedInitiate(); itkDebugMacro("Ratio of voxels mapping into moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); if (this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 4) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } double mse = m_PerThread[0].m_MSE; for (unsigned int t = 1; t < this->m_NumberOfWorkUnits; ++t) { mse += m_PerThread[t].m_MSE; } mse /= this->m_NumberOfPixelsCounted; return mse; } template <typename TFixedImage, typename TMovingImage> inline bool MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::GetValueAndDerivativeThreadProcessSample( ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue, const ImageDerivativesType & movingImageGradientValue) const { double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; AlignedPerThreadType & threadS = m_PerThread[threadId]; threadS.m_MSE += diff * diff; FixedImagePointType fixedImagePoint = this->m_FixedImageSamples[fixedImageSample].point; // Need to use one of the threader transforms if we're // not in thread 0. // // Use a raw pointer here to avoid the overhead of smart pointers. // For instance, Register and UnRegister have mutex locks around // the reference counts. TransformType * transform; if (threadId > 0) { transform = this->m_ThreaderTransform[threadId - 1]; } else { transform = this->m_Transform; } // Jacobian should be evaluated at the unmapped (fixed image) point. transform->ComputeJacobianWithRespectToParameters(fixedImagePoint, threadS.m_Jacobian); for (unsigned int par = 0; par < this->m_NumberOfParameters; ++par) { double sum = 0.0; for (unsigned int dim = 0; dim < MovingImageDimension; ++dim) { sum += 2.0 * diff * threadS.m_Jacobian(dim, par) * movingImageGradientValue[dim]; } threadS.m_MSEDerivative[par] += sum; } return true; } /** * Get the both Value and Derivative Measure */ template <typename TFixedImage, typename TMovingImage> void MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::GetValueAndDerivative(const ParametersType & parameters, MeasureType & value, DerivativeType & derivative) const { if (!this->m_FixedImage) { itkExceptionMacro(<< "Fixed image has not been assigned"); } // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); // Reset the joint pdfs to zero for (unsigned int i = 0; i < this->m_NumberOfWorkUnits; ++i) { m_PerThread[i].m_MSE = NumericTraits<MeasureType>::ZeroValue(); } // Set output values to zero if (derivative.GetSize() != this->m_NumberOfParameters) { derivative = DerivativeType(this->m_NumberOfParameters); } memset(derivative.data_block(), 0, this->m_NumberOfParameters * sizeof(double)); for (ThreadIdType workUnitID = 0; workUnitID < this->m_NumberOfWorkUnits; ++workUnitID) { memset(m_PerThread[workUnitID].m_MSEDerivative.data_block(), 0, this->m_NumberOfParameters * sizeof(double)); } // MUST BE CALLED TO INITIATE PROCESSING this->GetValueAndDerivativeMultiThreadedInitiate(); itkDebugMacro("Ratio of voxels mapping into moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); if (this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 4) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } value = 0; for (unsigned int t = 0; t < this->m_NumberOfWorkUnits; ++t) { value += m_PerThread[t].m_MSE; for (unsigned int parameter = 0; parameter < this->m_NumberOfParameters; ++parameter) { derivative[parameter] += m_PerThread[t].m_MSEDerivative[parameter]; } } value /= this->m_NumberOfPixelsCounted; for (unsigned int parameter = 0; parameter < this->m_NumberOfParameters; ++parameter) { derivative[parameter] /= this->m_NumberOfPixelsCounted; } } /** * Get the match measure derivative */ template <typename TFixedImage, typename TMovingImage> void MeanSquaresImageToImageMetric<TFixedImage, TMovingImage>::GetDerivative(const ParametersType & parameters, DerivativeType & derivative) const { if (!this->m_FixedImage) { itkExceptionMacro(<< "Fixed image has not been assigned"); } MeasureType value; // call the combined version this->GetValueAndDerivative(parameters, value, derivative); } } // end namespace itk #endif
32.624088
120
0.68464
[ "transform" ]
9cbdc798b341ec82d060ea52f67453a0766febfe
5,254
cpp
C++
libnd4j/include/ops/declarable/impl/LegacyStatsOp.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
2,206
2019-06-12T18:57:14.000Z
2022-03-29T08:14:27.000Z
libnd4j/include/ops/declarable/impl/LegacyStatsOp.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
1,685
2019-06-12T17:41:33.000Z
2022-03-29T21:45:15.000Z
libnd4j/include/ops/declarable/impl/LegacyStatsOp.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
572
2019-06-12T22:13:57.000Z
2022-03-31T16:46:46.000Z
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by raver119 on 17.10.2017. // #include <array/DataTypeUtils.h> #include <helpers/ConstantTadHelper.h> #include <helpers/ShapeUtils.h> #include <helpers/TAD.h> #include <ops/declarable/LegacyStatsOp.h> namespace sd { namespace ops { sd::Status LegacyStatsOp::validateAndExecute(Context &block) { auto x = INPUT_VARIABLE(0); auto z = OUTPUT_VARIABLE(0); NDArray::prepareSpecialUse({z}, {x}); // we assume that opNuk is either stored in block, or was provided via op constructor int opNum = block.opNum() < 0 ? this->_opNum : block.opNum(); // bias goes as first argument, unlike all other reductions bool biasCorrected = false; if (block.getIArguments()->size() > 0) biasCorrected = INT_ARG(0) > 0; ExtraArguments extras(*block.getTArguments()); PointersManager manager(block.launchContext(), "LegacyStatsOp"); if (block.getIArguments()->size() == 1 || (block.getIArguments()->size() == 2 && INT_ARG(1) == sd::DataTypeUtils::max<int>())) { // scalar NativeOpExecutioner::execSummaryStatsScalar(block.launchContext(), opNum, x->buffer(), x->shapeInfo(), x->specialBuffer(), x->specialShapeInfo(), extras.argumentsAsT(z->dataType()), z->buffer(), z->shapeInfo(), z->specialBuffer(), z->specialShapeInfo(), biasCorrected); } else { // dimensions for TAD // we should skip first argument here, because it's addressing bias correction std::vector<int> dims(*block.getIArguments()); for (int e = 0; e < dims.size(); e++) if (dims[e] < 0) dims[e] += x->rankOf(); REQUIRE_TRUE(dims.size() > 0, 0, "Some dimensions requuired for reduction!"); auto packX = sd::ConstantTadHelper::getInstance().tadForDimensions(x->shapeInfo(), dims); auto pTadShape = Environment::getInstance().isCPU() ? packX.primaryShapeInfo() : packX.specialShapeInfo(); //(sd::LongType *) manager.replicatePointer(tad.tadOnlyShapeInfo, //shape::shapeInfoByteLength(tad.tadOnlyShapeInfo)); auto pTadOffsets = Environment::getInstance().isCPU() ? packX.primaryOffsets() : packX.specialOffsets(); //(sd::LongType *) manager.replicatePointer(tad.tadOffsets, //tad.numTads * sizeof(sd::LongType)); NativeOpExecutioner::execSummaryStats(block.launchContext(), opNum, x->buffer(), x->shapeInfo(), x->specialBuffer(), x->specialShapeInfo(), extras.argumentsAsT(z->dataType()), z->buffer(), z->shapeInfo(), z->specialBuffer(), z->specialShapeInfo(), dims.data(), (int)dims.size(), pTadShape, pTadOffsets, biasCorrected); } manager.synchronize(); STORE_RESULT(*z); return sd::Status::OK; } LegacyStatsOp::LegacyStatsOp() : LegacyOp::LegacyOp(1) { // } LegacyStatsOp::LegacyStatsOp(int opNum) : LegacyOp::LegacyOp(1, opNum) { // } LegacyOp *LegacyStatsOp::clone() { return new LegacyStatsOp(this->_opNum); } /** * For all reductions rules are simple: either you return scalar, or you return reduced NDArray. * It solely depends on input shape, and requested dimensions */ ShapeList *LegacyStatsOp::calculateOutputShape(ShapeList *inputShape, sd::graph::Context &block) { auto inShape = inputShape->at(0); sd::LongType *newShape; if (block.getIArguments()->size() == 0 || (block.getIArguments()->size() == 1 && INT_ARG(0) == sd::DataTypeUtils::max<int>())) { // in this case we just return scalar ALLOCATE(newShape, block.getWorkspace(), shape::shapeInfoLength(2), sd::LongType); newShape[0] = 2; newShape[1] = 1; newShape[2] = 1; newShape[3] = 1; newShape[4] = 1; newShape[5] = 0; newShape[6] = 1; newShape[7] = 99; } else { // in this case we're building proper shape for reduction auto array = new NDArray(nullptr, inShape, block.launchContext()); auto newShape = ShapeUtils::evalReduceShapeInfo('c', *block.getIArguments(), *array, false, true); delete array; return SHAPELIST(newShape); } return SHAPELIST(CONSTANT(newShape)); } } // namespace ops } // namespace sd
40.728682
120
0.613247
[ "shape", "vector" ]
9cbf5edc3a693fd7db18adac6c79fa2147a5b6d5
16,400
cpp
C++
tools/rpkg/src/statement.cpp
Mu-L/duckdb
9a1c3f674b9ecec4aee52c599dbeb30fa79fc751
[ "MIT" ]
null
null
null
tools/rpkg/src/statement.cpp
Mu-L/duckdb
9a1c3f674b9ecec4aee52c599dbeb30fa79fc751
[ "MIT" ]
null
null
null
tools/rpkg/src/statement.cpp
Mu-L/duckdb
9a1c3f674b9ecec4aee52c599dbeb30fa79fc751
[ "MIT" ]
null
null
null
#include "rapi.hpp" #include "typesr.hpp" #include "altrepstring.hpp" #include "duckdb/common/types/timestamp.hpp" using namespace duckdb; // converter for primitive types template <class SRC, class DEST> static void VectorToR(Vector &src_vec, size_t count, void *dest, uint64_t dest_offset, DEST na_val) { auto src_ptr = FlatVector::GetData<SRC>(src_vec); auto &mask = FlatVector::Validity(src_vec); auto dest_ptr = ((DEST *)dest) + dest_offset; for (size_t row_idx = 0; row_idx < count; row_idx++) { dest_ptr[row_idx] = !mask.RowIsValid(row_idx) ? na_val : src_ptr[row_idx]; } } struct RStatement { unique_ptr<PreparedStatement> stmt; vector<Value> parameters; }; SEXP RApi::Release(SEXP stmtsexp) { if (TYPEOF(stmtsexp) != EXTPTRSXP) { Rf_error("duckdb_release_R: Need external pointer parameter"); } RStatement *stmtholder = (RStatement *)R_ExternalPtrAddr(stmtsexp); if (stmtsexp) { R_ClearExternalPtr(stmtsexp); delete stmtholder; } return R_NilValue; } static SEXP duckdb_finalize_statement_R(SEXP stmtsexp) { return RApi::Release(stmtsexp); } SEXP RApi::Prepare(SEXP connsexp, SEXP querysexp) { RProtector r; if (TYPEOF(querysexp) != STRSXP || Rf_length(querysexp) != 1) { Rf_error("duckdb_prepare_R: Need single string parameter for query"); } if (TYPEOF(connsexp) != EXTPTRSXP) { Rf_error("duckdb_prepare_R: Need external pointer parameter for connections"); } char *query = (char *)CHAR(STRING_ELT(querysexp, 0)); if (!query) { Rf_error("duckdb_prepare_R: No query"); } Connection *conn = (Connection *)R_ExternalPtrAddr(connsexp); if (!conn) { Rf_error("duckdb_prepare_R: Invalid connection"); } auto stmt = conn->Prepare(query); if (!stmt->success) { Rf_error("duckdb_prepare_R: Failed to prepare query %s\nError: %s", query, stmt->error.c_str()); } auto stmtholder = new RStatement(); stmtholder->stmt = move(stmt); SEXP retlist = r.Protect(NEW_LIST(6)); SEXP stmtsexp = r.Protect(R_MakeExternalPtr(stmtholder, R_NilValue, R_NilValue)); R_RegisterCFinalizer(stmtsexp, (void (*)(SEXP))duckdb_finalize_statement_R); SEXP ret_names = RApi::StringsToSexp({"str", "ref", "type", "names", "rtypes", "n_param"}); SET_NAMES(retlist, ret_names); SET_VECTOR_ELT(retlist, 0, querysexp); SET_VECTOR_ELT(retlist, 1, stmtsexp); SEXP stmt_type = RApi::StringsToSexp({StatementTypeToString(stmtholder->stmt->GetStatementType())}); SET_VECTOR_ELT(retlist, 2, stmt_type); SEXP col_names = RApi::StringsToSexp(stmtholder->stmt->GetNames()); SET_VECTOR_ELT(retlist, 3, col_names); vector<string> rtypes; for (auto &stype : stmtholder->stmt->GetTypes()) { string rtype = ""; switch (stype.id()) { case LogicalTypeId::BOOLEAN: rtype = "logical"; break; case LogicalTypeId::TINYINT: case LogicalTypeId::SMALLINT: case LogicalTypeId::INTEGER: rtype = "integer"; break; case LogicalTypeId::TIMESTAMP: rtype = "POSIXct"; break; case LogicalTypeId::DATE: rtype = "Date"; break; case LogicalTypeId::TIME: rtype = "difftime"; break; case LogicalTypeId::BIGINT: case LogicalTypeId::HUGEINT: case LogicalTypeId::FLOAT: case LogicalTypeId::DOUBLE: case LogicalTypeId::DECIMAL: rtype = "numeric"; break; case LogicalTypeId::VARCHAR: rtype = "character"; break; case LogicalTypeId::BLOB: rtype = "raw"; break; default: Rf_error("duckdb_prepare_R: Unknown column type for prepare: %s", stype.ToString().c_str()); break; } rtypes.push_back(rtype); } SEXP rtypessexp = StringsToSexp(rtypes); SET_VECTOR_ELT(retlist, 4, rtypessexp); SET_VECTOR_ELT(retlist, 5, Rf_ScalarInteger(stmtholder->stmt->n_param)); return retlist; } SEXP RApi::Bind(SEXP stmtsexp, SEXP paramsexp) { if (TYPEOF(stmtsexp) != EXTPTRSXP) { Rf_error("duckdb_bind_R: Need external pointer parameter"); } RStatement *stmtholder = (RStatement *)R_ExternalPtrAddr(stmtsexp); if (!stmtholder || !stmtholder->stmt) { Rf_error("duckdb_bind_R: Invalid statement"); } stmtholder->parameters.clear(); stmtholder->parameters.resize(stmtholder->stmt->n_param); if (stmtholder->stmt->n_param == 0) { Rf_error("duckdb_bind_R: dbBind called but query takes no parameters"); return R_NilValue; } if (TYPEOF(paramsexp) != VECSXP || (idx_t)Rf_length(paramsexp) != stmtholder->stmt->n_param) { Rf_error("duckdb_bind_R: bind parameters need to be a list of length %i", stmtholder->stmt->n_param); } for (idx_t param_idx = 0; param_idx < (idx_t)Rf_length(paramsexp); param_idx++) { Value val; SEXP valsexp = VECTOR_ELT(paramsexp, param_idx); if (Rf_length(valsexp) != 1) { Rf_error("duckdb_bind_R: bind parameter values need to have length 1"); } auto rtype = RApiTypes::DetectRType(valsexp); switch (rtype) { case RType::LOGICAL: { auto lgl_val = INTEGER_POINTER(valsexp)[0]; val = Value::BOOLEAN(lgl_val); val.is_null = RBooleanType::IsNull(lgl_val); break; } case RType::INTEGER: { auto int_val = INTEGER_POINTER(valsexp)[0]; val = Value::INTEGER(int_val); val.is_null = RIntegerType::IsNull(int_val); break; } case RType::NUMERIC: { auto dbl_val = NUMERIC_POINTER(valsexp)[0]; val = Value::DOUBLE(dbl_val); val.is_null = RDoubleType::IsNull(dbl_val); break; } case RType::STRING: { auto str_val = STRING_ELT(valsexp, 0); val = Value(CHAR(str_val)); val.is_null = str_val == NA_STRING; break; } case RType::FACTOR: { auto int_val = INTEGER_POINTER(valsexp)[0]; auto levels = GET_LEVELS(valsexp); bool is_null = RIntegerType::IsNull(int_val); if (!is_null) { auto str_val = STRING_ELT(levels, int_val - 1); val = Value(CHAR(str_val)); } else { val = Value(LogicalType::VARCHAR); } break; } case RType::TIMESTAMP: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIMESTAMP(RTimestampType::Convert(ts_val)); val.is_null = RTimestampType::IsNull(ts_val); break; } case RType::DATE: { auto d_val = NUMERIC_POINTER(valsexp)[0]; val = Value::DATE(RDateType::Convert(d_val)); val.is_null = RDateType::IsNull(d_val); break; } case RType::TIME_SECONDS: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIME(RTimeSecondsType::Convert(ts_val)); val.is_null = RTimeSecondsType::IsNull(ts_val); break; } case RType::TIME_MINUTES: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIME(RTimeMinutesType::Convert(ts_val)); val.is_null = RTimeMinutesType::IsNull(ts_val); break; } case RType::TIME_HOURS: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIME(RTimeHoursType::Convert(ts_val)); val.is_null = RTimeHoursType::IsNull(ts_val); break; } case RType::TIME_DAYS: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIME(RTimeDaysType::Convert(ts_val)); val.is_null = RTimeDaysType::IsNull(ts_val); break; } case RType::TIME_WEEKS: { auto ts_val = NUMERIC_POINTER(valsexp)[0]; val = Value::TIME(RTimeWeeksType::Convert(ts_val)); val.is_null = RTimeWeeksType::IsNull(ts_val); break; } default: Rf_error("duckdb_bind_R: Unsupported parameter type"); } stmtholder->parameters[param_idx] = val; } return R_NilValue; } static SEXP duckdb_execute_R_impl(MaterializedQueryResult *result) { RProtector r; // step 2: create result data frame and allocate columns uint32_t ncols = result->types.size(); if (ncols == 0) { return Rf_ScalarReal(0); // no need for protection because no allocation can happen afterwards } uint64_t nrows = result->collection.Count(); SEXP retlist = r.Protect(NEW_LIST(ncols)); SET_NAMES(retlist, RApi::StringsToSexp(result->names)); for (size_t col_idx = 0; col_idx < ncols; col_idx++) { RProtector r_varvalue; SEXP varvalue = NULL; switch (result->types[col_idx].id()) { case LogicalTypeId::BOOLEAN: varvalue = r_varvalue.Protect(NEW_LOGICAL(nrows)); break; case LogicalTypeId::TINYINT: case LogicalTypeId::SMALLINT: case LogicalTypeId::INTEGER: varvalue = r_varvalue.Protect(NEW_INTEGER(nrows)); break; case LogicalTypeId::BIGINT: case LogicalTypeId::HUGEINT: case LogicalTypeId::FLOAT: case LogicalTypeId::DOUBLE: case LogicalTypeId::DECIMAL: case LogicalTypeId::TIMESTAMP: case LogicalTypeId::DATE: case LogicalTypeId::TIME: varvalue = r_varvalue.Protect(NEW_NUMERIC(nrows)); break; case LogicalTypeId::VARCHAR: { auto wrapper = new DuckDBAltrepStringWrapper(); wrapper->length = nrows; wrapper->vectors.resize(result->collection.Chunks().size()); auto ptr = PROTECT(R_MakeExternalPtr((void *)wrapper, R_NilValue, R_NilValue)); R_RegisterCFinalizer(ptr, AltrepString::Finalize); varvalue = r_varvalue.Protect(R_new_altrep(AltrepString::rclass, ptr, R_NilValue)); UNPROTECT(1); break; } case LogicalTypeId::BLOB: varvalue = r_varvalue.Protect(NEW_LIST(nrows)); break; default: Rf_error("duckdb_execute_R: Unknown column type for execute: %s", result->types[col_idx].ToString().c_str()); } if (!varvalue) { throw std::bad_alloc(); } SET_VECTOR_ELT(retlist, col_idx, varvalue); } // at this point retlist is fully allocated and the only protected SEXP // step 3: set values from chunks uint64_t dest_offset = 0; idx_t chunk_idx = 0; while (true) { auto chunk = result->Fetch(); if (!chunk || chunk->size() == 0) { break; } D_ASSERT(chunk->ColumnCount() == ncols); D_ASSERT(chunk->ColumnCount() == (idx_t)Rf_length(retlist)); for (size_t col_idx = 0; col_idx < chunk->ColumnCount(); col_idx++) { SEXP dest = VECTOR_ELT(retlist, col_idx); switch (result->types[col_idx].id()) { case LogicalTypeId::BOOLEAN: VectorToR<int8_t, uint32_t>(chunk->data[col_idx], chunk->size(), LOGICAL_POINTER(dest), dest_offset, NA_LOGICAL); break; case LogicalTypeId::TINYINT: VectorToR<int8_t, uint32_t>(chunk->data[col_idx], chunk->size(), INTEGER_POINTER(dest), dest_offset, NA_INTEGER); break; case LogicalTypeId::SMALLINT: VectorToR<int16_t, uint32_t>(chunk->data[col_idx], chunk->size(), INTEGER_POINTER(dest), dest_offset, NA_INTEGER); break; case LogicalTypeId::INTEGER: VectorToR<int32_t, uint32_t>(chunk->data[col_idx], chunk->size(), INTEGER_POINTER(dest), dest_offset, NA_INTEGER); break; case LogicalTypeId::TIMESTAMP: { auto &src_vec = chunk->data[col_idx]; auto src_data = FlatVector::GetData<timestamp_t>(src_vec); auto &mask = FlatVector::Validity(src_vec); double *dest_ptr = ((double *)NUMERIC_POINTER(dest)) + dest_offset; for (size_t row_idx = 0; row_idx < chunk->size(); row_idx++) { dest_ptr[row_idx] = !mask.RowIsValid(row_idx) ? NA_REAL : (double)Timestamp::GetEpochSeconds(src_data[row_idx]); } // some dresssup for R RProtector r_ts; SEXP cl = r_ts.Protect(NEW_STRING(2)); SET_STRING_ELT(cl, 0, r_ts.Protect(Rf_mkChar("POSIXct"))); SET_STRING_ELT(cl, 1, r_ts.Protect(Rf_mkChar("POSIXt"))); SET_CLASS(dest, cl); Rf_setAttrib(dest, Rf_install("tzone"), r_ts.Protect(Rf_mkString("UTC"))); break; } case LogicalTypeId::DATE: { auto &src_vec = chunk->data[col_idx]; auto src_data = FlatVector::GetData<date_t>(src_vec); auto &mask = FlatVector::Validity(src_vec); double *dest_ptr = ((double *)NUMERIC_POINTER(dest)) + dest_offset; for (size_t row_idx = 0; row_idx < chunk->size(); row_idx++) { dest_ptr[row_idx] = !mask.RowIsValid(row_idx) ? NA_REAL : (double)int32_t(src_data[row_idx]); } // some dresssup for R RProtector r_date; SET_CLASS(dest, r_date.Protect(Rf_mkString("Date"))); break; } case LogicalTypeId::TIME: { auto &src_vec = chunk->data[col_idx]; auto src_data = FlatVector::GetData<dtime_t>(src_vec); auto &mask = FlatVector::Validity(src_vec); double *dest_ptr = ((double *)NUMERIC_POINTER(dest)) + dest_offset; for (size_t row_idx = 0; row_idx < chunk->size(); row_idx++) { if (!mask.RowIsValid(row_idx)) { dest_ptr[row_idx] = NA_REAL; } else { dtime_t n = src_data[row_idx]; dest_ptr[row_idx] = n.micros / 1000000.0; } } // some dresssup for R RProtector r_time; SET_CLASS(dest, r_time.Protect(Rf_mkString("difftime"))); Rf_setAttrib(dest, Rf_install("units"), r_time.Protect(Rf_mkString("secs"))); break; } case LogicalTypeId::BIGINT: VectorToR<int64_t, double>(chunk->data[col_idx], chunk->size(), NUMERIC_POINTER(dest), dest_offset, NA_REAL); break; case LogicalTypeId::HUGEINT: { auto &src_vec = chunk->data[col_idx]; auto src_data = FlatVector::GetData<hugeint_t>(src_vec); auto &mask = FlatVector::Validity(src_vec); double *dest_ptr = ((double *)NUMERIC_POINTER(dest)) + dest_offset; for (size_t row_idx = 0; row_idx < chunk->size(); row_idx++) { if (!mask.RowIsValid(row_idx)) { dest_ptr[row_idx] = NA_REAL; } else { Hugeint::TryCast(src_data[row_idx], dest_ptr[row_idx]); } } break; } case LogicalTypeId::DECIMAL: { auto &src_vec = chunk->data[col_idx]; auto &decimal_type = result->types[col_idx]; double *dest_ptr = ((double *)NUMERIC_POINTER(dest)) + dest_offset; auto dec_scale = decimal_type.scale(); switch (decimal_type.InternalType()) { case PhysicalType::INT16: RDecimalCastLoop<int16_t>(src_vec, chunk->size(), dest_ptr, dec_scale); break; case PhysicalType::INT32: RDecimalCastLoop<int32_t>(src_vec, chunk->size(), dest_ptr, dec_scale); break; case PhysicalType::INT64: RDecimalCastLoop<int64_t>(src_vec, chunk->size(), dest_ptr, dec_scale); break; case PhysicalType::INT128: RDecimalCastLoop<hugeint_t>(src_vec, chunk->size(), dest_ptr, dec_scale); break; default: throw NotImplementedException("Unimplemented internal type for DECIMAL"); } break; } case LogicalTypeId::FLOAT: VectorToR<float, double>(chunk->data[col_idx], chunk->size(), NUMERIC_POINTER(dest), dest_offset, NA_REAL); break; case LogicalTypeId::DOUBLE: VectorToR<double, double>(chunk->data[col_idx], chunk->size(), NUMERIC_POINTER(dest), dest_offset, NA_REAL); break; case LogicalTypeId::VARCHAR: { auto wrapper = (DuckDBAltrepStringWrapper *)R_ExternalPtrAddr(R_altrep_data1(dest)); wrapper->vectors[chunk_idx].Reference(chunk->data[col_idx]); break; } case LogicalTypeId::BLOB: { auto src_ptr = FlatVector::GetData<string_t>(chunk->data[col_idx]); auto &mask = FlatVector::Validity(chunk->data[col_idx]); for (size_t row_idx = 0; row_idx < chunk->size(); row_idx++) { if (!mask.RowIsValid(row_idx)) { SET_VECTOR_ELT(dest, dest_offset + row_idx, Rf_ScalarLogical(NA_LOGICAL)); } else { SEXP rawval = NEW_RAW(src_ptr[row_idx].GetSize()); if (!rawval) { throw std::bad_alloc(); } memcpy(RAW_POINTER(rawval), src_ptr[row_idx].GetDataUnsafe(), src_ptr[row_idx].GetSize()); SET_VECTOR_ELT(dest, dest_offset + row_idx, rawval); } } break; } default: Rf_error("duckdb_execute_R: Unknown column type for convert: %s", chunk->GetTypes()[col_idx].ToString().c_str()); break; } } dest_offset += chunk->size(); chunk_idx++; } D_ASSERT(dest_offset == nrows); return retlist; } SEXP RApi::Execute(SEXP stmtsexp) { if (TYPEOF(stmtsexp) != EXTPTRSXP) { Rf_error("duckdb_execute_R: Need external pointer parameter"); } RStatement *stmtholder = (RStatement *)R_ExternalPtrAddr(stmtsexp); if (!stmtholder || !stmtholder->stmt) { Rf_error("duckdb_execute_R: Invalid statement"); } RProtector r; SEXP out; { auto generic_result = stmtholder->stmt->Execute(stmtholder->parameters, false); if (!generic_result->success) { Rf_error("duckdb_execute_R: Failed to run query\nError: %s", generic_result->error.c_str()); } D_ASSERT(generic_result->type == QueryResultType::MATERIALIZED_RESULT); MaterializedQueryResult *result = (MaterializedQueryResult *)generic_result.get(); // Protect during destruction of generic_result out = r.Protect(duckdb_execute_R_impl(result)); } return out; }
32.283465
105
0.684634
[ "vector" ]
9cc0974f8fcb456adab17d5bafc135f5c1548408
9,732
cpp
C++
service/method-dedup/ConstantValue.cpp
srivastavaayu/redex
0440e2badcc6c503b14ca734f1c09b7f41cb97ec
[ "MIT" ]
null
null
null
service/method-dedup/ConstantValue.cpp
srivastavaayu/redex
0440e2badcc6c503b14ca734f1c09b7f41cb97ec
[ "MIT" ]
null
null
null
service/method-dedup/ConstantValue.cpp
srivastavaayu/redex
0440e2badcc6c503b14ca734f1c09b7f41cb97ec
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ConstantValue.h" #include <boost/algorithm/string.hpp> #include "Creators.h" #include "TypeReference.h" namespace { constexpr uint64_t MAX_NUM_CONST_VALUE = 10; std::vector<IRInstruction*> make_string_const(reg_t dest, const std::string& val) { std::vector<IRInstruction*> res; IRInstruction* load = new IRInstruction(OPCODE_CONST_STRING); load->set_string(DexString::make_string(val)); IRInstruction* move_result_pseudo = new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT); move_result_pseudo->set_dest(dest); res.push_back(load); res.push_back(move_result_pseudo); return res; } } // namespace ConstantValue::ConstantValue(const TypeTags* type_tags, const std::string& kind_str, const std::string& val_str, reg_t param_reg) : m_param_reg(param_reg) { if (kind_str == "I") { m_kind = ConstantKind::INT; m_int_val = std::stoll(val_str); } else if (kind_str == "T") { auto type_val = DexType::get_type(val_str.c_str()); if (type_val != nullptr && type_tags->has_type_tag(type_val)) { m_kind = ConstantKind::TYPE; m_int_val = type_tags->get_type_tag(type_val); if (m_int_val == 0) { TRACE(METH_DEDUP, 9, "const value: skipping type tag value of 0"); m_kind = ConstantKind::INVALID; } return; } else if (type_val == nullptr) { TRACE(METH_DEDUP, 9, "const value: unable to find type %s", val_str.c_str()); } else { TRACE( METH_DEDUP, 9, "const value: no type tag found %s", val_str.c_str()); } // Cannot find type or not type tag. m_kind = ConstantKind::INVALID; } else if (kind_str == "S") { m_kind = ConstantKind::STRING; m_str_val = val_str; } else { always_assert_log( kind_str.size() > 1, "Unexpected kind str %s\n", kind_str.c_str()); TRACE(METH_DEDUP, 9, "const lift: trying to decode more than one kind %s", kind_str.c_str()); m_kind = ConstantKind::INVALID; } } std::vector<ConstantValue::ConstantLoad> ConstantValue::collect_constant_loads_in(const IRCode* code) { std::vector<ConstantValue::ConstantLoad> res; always_assert(is_valid()); auto ii = InstructionIterable(code); for (auto it = ii.begin(); it != ii.end(); ++it) { auto insn = it->insn; if (is_int_value() && is_literal_const(insn->opcode())) { int64_t literal = insn->get_literal(); // Special handling for type tags to avoid sign extensionon on int64_t. if (m_kind == ConstantKind::TYPE) { literal = static_cast<uint32_t>(literal); } if (is_int_value() && literal == m_int_val) { res.emplace_back(insn, insn->dest()); } } else if (is_str_value() && insn->opcode() == OPCODE_CONST_STRING) { if (strcmp(insn->get_string()->c_str(), m_str_val.c_str()) == 0) { auto pseudo_move = std::next(it)->insn; always_assert(pseudo_move->opcode() == IOPCODE_MOVE_RESULT_PSEUDO_OBJECT); res.emplace_back(insn, pseudo_move->dest()); } } } return res; } std::vector<IRInstruction*> ConstantValue::make_load_const(reg_t const_reg) { always_assert(is_valid()); if (is_int_value()) { std::vector<IRInstruction*> res; auto load = method_reference::make_load_const(const_reg, m_int_val); res.push_back(load); return res; } else { return make_string_const(const_reg, m_str_val); } } ConstantValues::ConstantValues(const TypeTags* type_tags, const std::string& kinds_str, const std::string& vals_str, const size_t stud_method_threshold, IRCode* code) : m_stub_method_threshold(stud_method_threshold) { // Split vals_str. std::vector<std::string> vals_vec; boost::split(vals_vec, vals_str, [](char c) { return c == ':'; }); always_assert(vals_vec.size() == kinds_str.length()); if (kinds_str.size() > MAX_NUM_CONST_VALUE) { TRACE(METH_DEDUP, 8, "const value: skip large number of const values %ld", kinds_str.size()); return; } // Build kind_to_val pairs. std::vector<std::pair<std::string, std::string>> kind_to_val; auto vals_it = vals_vec.begin(); for (std::string::const_iterator it = kinds_str.begin(); it != kinds_str.end(); ++it) { std::string kind_str = std::string(1, *it); kind_to_val.emplace_back(kind_str, *vals_it); ++vals_it; } // Populate the const_vals set. for (auto& pair : kind_to_val) { auto param_reg = code->allocate_temp(); ConstantValue cval(type_tags, pair.first, pair.second, param_reg); m_const_vals.emplace_back(cval); if (cval.is_invalid()) { m_skip_multiple_const_0 = true; TRACE(METH_DEDUP, 9, "const value: skip multiple const 0"); } } } std::vector<ConstantValues::ConstantValueLoad> ConstantValues::collect_constant_loads(const IRCode* code) { std::vector<ConstantValueLoad> const_val_loads; std::unordered_set<IRInstruction*> matched_loads; for (auto& const_val : m_const_vals) { if (const_val.is_invalid()) { continue; } auto const_loads = const_val.collect_constant_loads_in(code); if (m_skip_multiple_const_0 && const_val.is_int_kind() && const_val.get_int_value() == 0 && !const_loads.empty()) { const_val_loads.emplace_back(const_val, const_loads.front()); TRACE(METH_DEDUP, 9, "const value: skip const 0 loads"); continue; } for (auto& load : const_loads) { if (matched_loads.count(load.first) > 0) { // If the same const load insn has been matched for multiple const // values in the @MethodMeta annotation, we skip it. // Trying to lift the same const load insn later will lead to a crash. continue; } const_val_loads.emplace_back(const_val, load); TRACE(METH_DEDUP, 9, "const value: %s matched with const-load %s", const_val.to_str().c_str(), SHOW(load.first)); matched_loads.insert(load.first); } } return const_val_loads; } std::vector<IRInstruction*> ConstantValues::make_const_loads( std::vector<reg_t>& const_regs) { always_assert(const_regs.size() == size()); std::vector<IRInstruction*> res; size_t reg_idx = 0; for (auto& cval : m_const_vals) { if (cval.is_valid()) { auto loads = cval.make_load_const(const_regs.at(reg_idx++)); res.insert(res.end(), loads.begin(), loads.end()); } } return res; } /** * Will return a newly created method that loads the argument values and * passes them to the `callee` method. * * <ret_type> <method_name>$redex(<method_args>...) { * const-* <local_reg_0> field_1_data * const-* <local_reg_1> field_2_data * ... * invoke-static <callee> <method_args ...> <local_regs ...> * } */ DexMethod* ConstantValues::create_stub_method(DexMethod* callee) { DexType* type = callee->get_class(); // Assuming that callee's proto is already modified by appending the lifted // params. auto appended_proto = callee->get_proto(); auto stub_arg_list = type_reference::drop_and_make(appended_proto->get_args(), size()); auto stub_proto = DexProto::make_proto(appended_proto->get_rtype(), stub_arg_list); auto name = DexString::make_string(callee->get_name()->str() + "$stub"); name = DexMethod::get_unique_name(type, name, stub_proto); TRACE(METH_DEDUP, 9, "const value: stub name %s", name->c_str()); auto mc = new MethodCreator(type, name, stub_proto, callee->get_access(), nullptr, // anno false // with_debug_item ); auto mb = mc->get_main_block(); // Setup args for calling the callee. size_t arg_loc = 0; std::vector<Location> args; if (!is_static(callee)) { args.push_back(mc->get_local(arg_loc++)); } for (size_t i = 0; i < stub_arg_list->size(); ++i) { args.push_back(mc->get_local(arg_loc++)); } for (auto& cval : m_const_vals) { if (cval.is_invalid()) { continue; } auto loc = mc->make_local(cval.get_constant_type()); if (cval.is_int_value()) { mb->load_const(loc, static_cast<int32_t>(cval.get_int_value())); } else { mb->load_const(loc, DexString::make_string(cval.get_str_value())); } args.push_back(loc); } mb->invoke(callee, args); DexType* ret_type = callee->get_proto()->get_rtype(); if (ret_type == type::_void()) { mb->ret_void(); } else { auto ret_loc = mc->make_local(ret_type); mb->move_result(ret_loc, ret_type); mb->ret(ret_type, ret_loc); } auto stub = mc->create(); // Propogate deobfuscated name auto orig_name = callee->get_deobfuscated_name(); auto pos = orig_name.find(':'); always_assert(pos != std::string::npos); auto new_name = orig_name.substr(0, pos) + "$stub" + ":" + show_deobfuscated(stub_proto); stub->set_deobfuscated_name(new_name); TRACE(METH_DEDUP, 9, "stub's new deobfuscated name %s", new_name.c_str()); // Add stub to class type_class(type)->add_method(stub); TRACE(METH_DEDUP, 9, "const value: created stub %s\n%s", SHOW(stub), SHOW(stub->get_code())); return stub; }
33.558621
79
0.628339
[ "vector" ]
9cc31218dbd6992c6066914d8c453c609a8ec9df
15,893
cxx
C++
src-plugins/libs/vtkInria/vtkVisuManagement/vtkLookupTableManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/vtkVisuManagement/vtkLookupTableManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/vtkVisuManagement/vtkLookupTableManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "vtkLookupTableManager.h" #include <vtkObjectFactory.h> vtkCxxRevisionMacro(vtkLookupTableManager, "$Revision: 1378 $"); vtkStandardNewMacro(vtkLookupTableManager); #include "lut/Spectrum.h" #include "lut/HotMetal.h" #include "lut/GEColor.h" #include "lut/Flow.h" #include "lut/LONI.h" #include "lut/LONI2.h" #include "lut/Asymmetry.h" #include "lut/VRMusclesBones.h" #include "lut/Cardiac.h" #include "lut/GrayRainbow.h" #include "lut/HotGreen.h" #include "lut/HotIron.h" #include "lut/Stern.h" #include "lut/VRBones.h" #include "lut/VRRedVessels.h" #include "lut/BlackBody.h" #include "lut/jet.h" #include <time.h> vtkLookupTableManager::vtkLookupTableManager() {} vtkLookupTableManager::~vtkLookupTableManager() {} std::vector<std::string> vtkLookupTableManager::GetAvailableLookupTables() { std::string lutNames[]={"Default", "Black & White", "Black & White Inversed", "Spectrum", "Hot Metal", "Hot Green", "Hot Iron", "GE", "Flow", "Loni", "Loni 2", "Asymmetry", "P-Value", "Red Black Alpha", "Green Black Alpha", "Blue Black Alpha", "Muscles & Bones", "Bones", "Red Vessels", "Cardiac", "Gray Rainbow", "Stern", "Black Body", "Jet"}; std::vector<std::string> v_lutNames; for( int i=0; i<24; i++) { v_lutNames.push_back(lutNames[i]); } return v_lutNames; } vtkLookupTable* vtkLookupTableManager::GetLookupTable(const int& n) { std::vector< std::string > luts = GetAvailableLookupTables(); if (n<0 || n>= (int)luts.size()) return vtkLookupTableManager::GetBWLookupTable(); return GetLookupTable ( luts[n] ); } vtkLookupTable* vtkLookupTableManager::GetLookupTable(const std::string & name) { if (name=="Default") return vtkLookupTableManager::GetBWLookupTable(); else if ( name == "Black & White" ) return vtkLookupTableManager::GetBWLookupTable(); else if ( name == "Black & White Inversed" ) return vtkLookupTableManager::GetBWInverseLookupTable(); else if ( name == "Spectrum" ) return vtkLookupTableManager::GetSpectrumLookupTable(); else if ( name == "Hot Metal" ) return vtkLookupTableManager::GetHotMetalLookupTable(); else if ( name == "Hot Green" ) return vtkLookupTableManager::GetHotGreenLookupTable(); else if ( name == "Hot Iron" ) return vtkLookupTableManager::GetHotIronLookupTable(); else if ( name == "GE" ) return vtkLookupTableManager::GetGEColorLookupTable(); else if ( name == "Flow" ) return vtkLookupTableManager::GetFlowLookupTable(); else if ( name == "Loni" ) return vtkLookupTableManager::GetLONILookupTable(); else if ( name == "Loni 2" ) return vtkLookupTableManager::GetLONI2LookupTable(); else if ( name == "Asymmetry" ) return vtkLookupTableManager::GetAsymmetryLookupTable(); else if ( name == "P-Value" ) return vtkLookupTableManager::GetPValueLookupTable(); else if ( name == "Red Black Alpha" ) return vtkLookupTableManager::GetRedBlackAlphaLookupTable(); else if ( name == "Green Black Alpha" ) return vtkLookupTableManager::GetGreenBlackAlphaLookupTable(); else if ( name == "Blue Black Alpha" ) return vtkLookupTableManager::GetBlueBlackAlphaLookupTable(); else if ( name == "Muscles & Bones" ) return vtkLookupTableManager::GetVRMusclesBonesLookupTable(); else if ( name == "Bones" ) return vtkLookupTableManager::GetVRBonesLookupTable(); else if ( name == "Red Vessels" ) return vtkLookupTableManager::GetVRRedVesselsLookupTable(); else if ( name == "Cardiac" ) return vtkLookupTableManager::GetCardiacLookupTable(); else if ( name == "Gray Rainbow" ) return vtkLookupTableManager::GetGrayRainbowLookupTable(); else if ( name == "Stern" ) return vtkLookupTableManager::GetSternLookupTable(); else if ( name == "Black Body" ) return vtkLookupTableManager::GetBlackBodyLookupTable(); else if ( name == "Jet" ) return vtkLookupTableManager::GetJetLookupTable(); else return vtkLookupTableManager::GetBWLookupTable(); } vtkLookupTable* vtkLookupTableManager::GetBWLookupTable() { vtkLookupTable* bwLut = vtkLookupTable::New(); bwLut->SetTableRange (0, 1); bwLut->SetSaturationRange (0, 0); bwLut->SetHueRange (0, 0); bwLut->SetValueRange (0, 1); bwLut->SetAlphaRange (0, 1); bwLut->Build(); return bwLut; } vtkLookupTable* vtkLookupTableManager::GetBWInverseLookupTable() { vtkLookupTable* bwLut = vtkLookupTable::New(); bwLut->SetTableRange (0, 1); bwLut->SetSaturationRange (0, 0); bwLut->SetHueRange (0, 0); bwLut->SetValueRange (1, 0); bwLut->SetAlphaRange (1, 0); bwLut->Build(); return bwLut; } vtkLookupTable* vtkLookupTableManager::GetSpectrumLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)Spectrum[i]/255.0, (double)Spectrum[256+i]/255.0, (double)Spectrum[256*2+i]/255.0, (double)(i)/255.0 ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetHotMetalLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)HotMetal[i]/255.0, (double)HotMetal[256+i]/255.0, (double)HotMetal[256*2+i]/255.0, (double)i/255.0 ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetGEColorLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)GEColor[i]/255.0, (double)GEColor[256+i]/255.0, (double)GEColor[256*2+i]/255.0, (double)i/255.0 ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetFlowLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)Flow[i]/255.0, (double)Flow[256+i]/255.0, (double)Flow[256*2+i]/255.0, (double)i/255.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetLONILookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(203); lut->Build(); for( int i=0; i<203; i++) { lut->SetTableValue(i, (double)LONI[i][0], (double)LONI[i][1], (double)LONI[i][2], (double)i/202.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetLONI2LookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(120); lut->Build(); for( int i=0; i<120; i++) { lut->SetTableValue(i, (double)LONI2[i][0], (double)LONI2[i][1], (double)LONI2[i][2], (double)i/119.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetAsymmetryLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)AsymmetryLUT[i][0], (double)AsymmetryLUT[i][1], (double)AsymmetryLUT[i][2], (double)i/255.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetPValueLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetTableRange (0, 1); lut->SetSaturationRange (1.0, 1.5); lut->SetHueRange (0.666, 0.8333); //lut->SetHueRange (0.666, 0.0); lut->SetValueRange (0.5, 1.0); lut->SetAlphaRange (0, 1); lut->Build(); return lut; } vtkLookupTable* vtkLookupTableManager::GetRedBlackAlphaLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); lut->SetTableValue(0,0,0,0,0); for( int i=1; i<256; i++) { lut->SetTableValue(i, i/255.0, 0.0, 0.0, (i/255.0*68.0 + 187)/255.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetGreenBlackAlphaLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); lut->SetTableValue(0,0,0,0,0); for( int i=1; i<256; i++) { lut->SetTableValue(i, 0.0, i/255.0, 0.0, (i/255.0*68.0 + 187)/255.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetBlueBlackAlphaLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); lut->SetTableValue(0,0,0,0,0); for( int i=1; i<256; i++) { lut->SetTableValue(i, 0.0, 0.0, i/255.0, (i/255.0*68.0 + 187)/255.0); } return lut; } vtkLookupTable* vtkLookupTableManager::GetVRMusclesBonesLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)VRMusclesBones[i]/255.0, (double)VRMusclesBones[256+i]/255.0, (double)VRMusclesBones[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetROILookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues (256); lut->SetTableValue (0, 0.0, 0.0, 0.0, 0.0); // erase color lut->SetTableValue (1, 1.0, 0.0, 0.0, 0.5); lut->SetTableValue (2, 0.0, 1.0, 0.0, 0.5); lut->SetTableValue (3, 0.0, 0.0, 1.0, 0.5); lut->SetTableValue (4, 1.0, 1.0, 0.0, 0.5); lut->SetTableValue (5, 0.0, 1.0, 1.0, 0.5); lut->SetTableValue (6, 1.0, 0.0, 1.0, 0.5); lut->SetTableValue (7, 1.0, 0.5, 0.0, 0.5); lut->SetTableValue (8, 0.0, 1.0, 0.5, 0.5); lut->SetTableValue (9, 0.5, 0.0, 1.0, 0.5); lut->SetTableValue (10, 1.0, 1.0, 0.5, 0.5); lut->SetTableValue (11, 0.5, 1.0, 1.0, 0.5); lut->SetTableValue (12, 1.0, 0.5, 1.0, 0.5); // Fill the rest of the labels with color ramps, code taken from SNAP // for (int i = 13; i < 256; i++) // { // if (i < 85) // { // lut->SetTableValue (i, ((84.0-i)/85.0 * 200.0 + 50.0)/255.0, (i/85.0 * 200.0 + 50.0)/255.0, 0, 0.5); // } // else if (i < 170) // { // lut->SetTableValue (i, 0, ((169.0-i)/85.0 * 200.0 + 50)/255.0, ((i-85)/85.0 * 200.0 + 50)/255.0, 0.5); // } // else // { // lut->SetTableValue (i, ((i-170)/85.0 * 200.0 + 50)/255.0, 0.0, ((255.0-i)/85.0 * 200.0 + 50)/255.0, 0.5); // } // } // Fill the rest with random colors // for (int i = 13; i < 256; i++) // { // srand (clock()); // // put a random color // int i1 = 1 + (int) (100.0 * ((double)rand() / (RAND_MAX + 1.0))); // int i2 = 1 + (int) (100.0 * ((double)rand() / (RAND_MAX + 1.0))); // int i3 = 1 + (int) (100.0 * ((double)rand() / (RAND_MAX + 1.0))); // double rand_1 = (double)(i1)/(100.0); // double rand_2 = (double)(i2)/(100.0); // double rand_3 = (double)(i3)/(100.0); // double r = rand_1, g = rand_2, b = rand_3; // if (i1 < 33) // r = 1; // else if (i1 < 66) // g = 1; // else if (i1 < 100) // b = 1; // lut->SetTableValue (i, r, g, b, 0.5); // } for (int i = 12; i < 256; i++) { if (i%12 == 0) lut->SetTableValue (i, 1.0, 0.0, 0.0, 0.5); else if (i%12 == 1) lut->SetTableValue (i, 0.0, 1.0, 0.0, 0.5); else if (i%12 == 2) lut->SetTableValue (i, 0.0, 0.0, 1.0, 0.5); else if (i%12 == 3) lut->SetTableValue (i, 1.0, 1.0, 0.0, 0.5); else if (i%12 == 4) lut->SetTableValue (i, 0.0, 1.0, 1.0, 0.5); else if (i%12 == 5) lut->SetTableValue (i, 1.0, 0.0, 1.0, 0.5); else if (i%12 == 6) lut->SetTableValue (i, 1.0, 0.5, 0.0, 0.5); else if (i%12 == 7) lut->SetTableValue (i, 0.0, 1.0, 0.5, 0.5); else if (i%12 == 8) lut->SetTableValue (i, 0.5, 0.0, 1.0, 0.5); else if (i%12 == 9) lut->SetTableValue (i, 1.0, 1.0, 0.5, 0.5); else if (i%12 == 10) lut->SetTableValue (i, 0.5, 1.0, 1.0, 0.5); else if (i%12 == 11) lut->SetTableValue (i, 1.0, 0.5, 1.0, 0.5); } return lut; } vtkLookupTable* vtkLookupTableManager::GetCardiacLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)Cardiac[i]/255.0, (double)Cardiac[256+i]/255.0, (double)Cardiac[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetGrayRainbowLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)GrayRainbow[i]/255.0, (double)GrayRainbow[256+i]/255.0, (double)GrayRainbow[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetHotGreenLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)HotGreen[i]/255.0, (double)HotGreen[256+i]/255.0, (double)HotGreen[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetHotIronLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)HotIron[i]/255.0, (double)HotIron[256+i]/255.0, (double)HotIron[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetSternLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)Stern[i]/255.0, (double)Stern[256+i]/255.0, (double)Stern[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetVRBonesLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)VRBones[i]/255.0, (double)VRBones[256+i]/255.0, (double)VRBones[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetVRRedVesselsLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)VRRedVessels[i]/255.0, (double)VRRedVessels[256+i]/255.0, (double)VRRedVessels[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetBlackBodyLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(256); lut->Build(); for( int i=0; i<256; i++) { lut->SetTableValue(i, (double)BlackBody[i]/255.0, (double)BlackBody[256+i]/255.0, (double)BlackBody[256*2+i]/255.0, /*(double)(i)/255.0*/ log (1.0+(double)(i)/255.0*9.0)/log (10.0) ); } return lut; } vtkLookupTable* vtkLookupTableManager::GetJetLookupTable() { vtkLookupTable* lut = vtkLookupTable::New(); lut->SetNumberOfTableValues(64); lut->Build(); for( int i=0; i<64; i++) { lut->SetTableValue(i, (double)jet[i][0], (double)jet[i][1], (double)jet[i][2], (double)1.0); } return lut; }
26.269421
202
0.629774
[ "vector" ]
9cc3d29eaaca27c1c6ed5dbfcf68096fb7db3ded
444
cpp
C++
137. Single Number II.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
137. Single Number II.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
137. Single Number II.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
class Solution { public: int singleNumber(vector<int>& nums) { map<int,int> mp; int res; for(auto i:nums){ mp[i]++; } for(auto i:mp){ if(i.second==1){ res = i.first; break; } } return res; } };
15.857143
41
0.274775
[ "vector" ]
9cc8fd09f60858c5fba1553bd8b789ea6c52604d
3,634
cpp
C++
src/io/pedigree/pedigree_reader.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
src/io/pedigree/pedigree_reader.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
src/io/pedigree/pedigree_reader.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2019 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include "pedigree_reader.hpp" #include <deque> #include <string> #include <sstream> #include <iterator> #include <algorithm> #include <fstream> #include <stdexcept> #include <boost/optional.hpp> #include <boost/filesystem/operations.hpp> #include "exceptions/missing_file_error.hpp" #include "exceptions/malformed_file_error.hpp" #include "utils/string_utils.hpp" namespace octopus { namespace io { class MissingPedigreeFile : public MissingFileError { std::string do_where() const override { return "read_pedigree"; } public: MissingPedigreeFile(boost::filesystem::path p) : MissingFileError {std::move(p), "pedigree"} {}; }; class MalformedPED : public MalformedFileError { std::string do_where() const override { return "read_pedigree"; } std::string do_help() const override { return "refer to the latest PED specification"; } public: MalformedPED(boost::filesystem::path file) : MalformedFileError {std::move(file), "ped"} {} }; namespace { auto open_ped(const boost::filesystem::path& ped_file) { return std::ifstream {ped_file.string()}; } struct Line { std::string line_data; operator std::string() const { return line_data; } }; std::istream& operator>>(std::istream& is, Line& data) { std::getline(is, data.line_data); if (!data.line_data.empty() && data.line_data.back() == '\r') { data.line_data.pop_back(); } return is; } struct PedRecord { std::string ped_id, sample, sex, mother, father; }; bool is_valid_ped_record(const std::vector<std::string>& fields) { return fields.size() >= 5 && (fields[4] == "1" || fields[4] == "2"); } PedRecord parse_ped_line(const std::string& line) { static const std::string delims {' ', '\t'}; auto fields = utils::split(line, delims); if (!is_valid_ped_record(fields)) { throw std::runtime_error {"Malformed PED record"}; } return {fields[0], fields[1], fields[4], fields[2], fields[3]}; } bool is_founder(const PedRecord& record) { return record.mother == "0" || record.father == "0"; } Pedigree::Member::Sex to_pedigree_sex(const std::string& ped_sex) { using Sex = Pedigree::Member::Sex; if (ped_sex == "1") { return Sex::male; } else { return Sex::female; } } } // namespace Pedigree read_pedigree(const boost::filesystem::path& ped_file) { if (!boost::filesystem::exists(ped_file)) { throw MissingPedigreeFile {ped_file}; } auto ped_stream = open_ped(ped_file); std::deque<PedRecord> records {}; try { std::transform(std::istream_iterator<Line> {ped_stream}, std::istream_iterator<Line> {}, std::back_inserter(records), [] (const auto& line) { return parse_ped_line(line); }); } catch (const std::runtime_error& e) { throw MalformedPED {ped_file}; } const auto first_descendant = std::partition(std::begin(records), std::end(records), is_founder); Pedigree result {records.size()}; std::for_each(std::begin(records), first_descendant, [&result] (PedRecord& record) { result.add_founder({record.sample, to_pedigree_sex(record.sex)}); }); std::for_each(first_descendant, std::end(records), [&result] (PedRecord& record) { result.add_descendant({record.sample, to_pedigree_sex(record.sex)}, record.mother, record.father); }); return result; } } // namespace io } // namespace octopus
29.072
120
0.656026
[ "vector", "transform" ]
9ccd1cb39952507e164de5ab9c4b030b442d0491
208,036
cpp
C++
dynadjust/dynadjust/dnaimport/dnainterop.cpp
ccrook/DynAdjust
d8e5c3c441c3a7065807915d83fe623af0add2b8
[ "Apache-2.0" ]
null
null
null
dynadjust/dynadjust/dnaimport/dnainterop.cpp
ccrook/DynAdjust
d8e5c3c441c3a7065807915d83fe623af0add2b8
[ "Apache-2.0" ]
null
null
null
dynadjust/dynadjust/dnaimport/dnainterop.cpp
ccrook/DynAdjust
d8e5c3c441c3a7065807915d83fe623af0add2b8
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Name : dnainterop.cpp // Author : Roger Fraser // Contributors : // Version : 1.00 // Copyright : Copyright 2017 Geoscience Australia // // 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. // // Description : DynAdjust Interoperability library //============================================================================ //#include <include/functions/dnaparallelfuncs.hpp> #include <dynadjust/dnaimport/dnainterop.hpp> #include <include/parameters/dnaepsg.hpp> #include <include/functions/dnafilepathfuncs.hpp> #include <include/io/DynaML-schema.hxx> using namespace dynadjust::epsg; using namespace boost::gregorian; using namespace boost::posix_time; MsrTally g_map_tally; MsrTally g_parsemsr_tally; StnTally g_parsestn_tally; UINT32 g_fileOrder; int compare_chararray(const void *a, const void *b) { const char* a1 = *(const char**)a; const char* b1 = *(const char**)b; return strcmp(a1,b1); } namespace dynadjust { namespace dynamlinterop { boost::mutex import_file_mutex; dna_import::dna_import() : percentComplete_(-99.) , isProcessing_(false) { ifsInputFILE_ = 0; g_fileOrder = 0; p_parsemsr_tally = &g_parsemsr_tally; p_parsestn_tally = &g_parsestn_tally; #ifdef _MSC_VER #if (_MSC_VER < 1900) { // this function is obsolete in MS VC++ 14.0, VS2015 // Set scientific format to print two places for the exponent _set_output_format(_TWO_DIGIT_EXPONENT); } #endif #endif m_strProjectDefaultEpsg = DEFAULT_EPSG_S; m_strProjectDefaultEpoch = DEFAULT_EPOCH; stn_discontinuities_.clear(); } dna_import::dna_import(const dna_import& newdynamlparser) { ifsInputFILE_ = newdynamlparser.ifsInputFILE_; percentComplete_ = newdynamlparser.percentComplete_; sifsFileSize_ = newdynamlparser.sifsFileSize_; isProcessing_ = newdynamlparser.isProcessing_; p_parsemsr_tally = newdynamlparser.p_parsemsr_tally; p_parsestn_tally = newdynamlparser.p_parsestn_tally; stn_discontinuities_.clear(); m_strProjectDefaultEpoch = DEFAULT_EPOCH; } dna_import::~dna_import() { } void dna_import::coutVersion() { string msg; fileproc_help_header(&msg); cout << msg << endl; } double dna_import::GetProgress() { // calculate on the fly if (!isProcessing_) return -1; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); try { if (ifsInputFILE_) percentComplete_ = fabs(ifsInputFILE_->tellg() * 100. / sifsFileSize_); } // Catch any type of error; do nothing. catch (...) { //if (ifsInputFILE_->eof()) // return percentComplete_; //if (ifsInputFILE_->rdstate() & std::ifstream::eofbit) // return percentComplete_; } import_file_mutex.unlock(); return percentComplete_; } void dna_import::DetermineBoundingBox() { if (projectSettings_.i.bounding_box.empty()) return; if (GetFields(const_cast<char*>(projectSettings_.i.bounding_box.c_str()), ',', false, "ffff", &bbox_upperLat_, &bbox_lowerLon_, &bbox_lowerLat_, &bbox_upperLon_) < 4) return; bbox_upperLat_ = DmstoRad(bbox_upperLat_); bbox_upperLon_ = DmstoRad(bbox_upperLon_); bbox_lowerLat_ = DmstoRad(bbox_lowerLat_); bbox_lowerLon_ = DmstoRad(bbox_lowerLon_); } void dna_import::BuildExtractStationsList(const string& stnList, pvstring vstnList) { // Extract stations from comma delimited string try { SplitDelimitedString<string>(stnList, string(","), vstnList); } catch (...) { stringstream ss; ss << "BuildExtractStationsList(): An error was encountered when parsing " << stnList << "." << endl; SignalExceptionParse(ss.str(), 0); } } void dna_import::UpdateEpoch(const vifm_t* vinput_file_meta) { // Inspect the first file that was loaded. // Assume that the epoch in that file is the desired epoch. string epoch(""); if (vinput_file_meta->empty()) // Do nothing return; epoch = vinput_file_meta->at(0).epoch; if (epoch.empty()) // Do nothing return; m_strProjectDefaultEpoch = epoch; // Set default epoch datum_.SetEpoch(epoch); // Update bst and bms files accordingly sprintf(bst_meta_.epoch, "%s", epoch.substr(0, STN_EPOCH_WIDTH).c_str()); sprintf(bms_meta_.epoch, "%s", epoch.substr(0, STN_EPOCH_WIDTH).c_str()); } void dna_import::InitialiseDatum(const string& reference_frame) { try { // Take the default reference frame, set either by the user or // the datum_ constructor (GDA94). Epoch is that of the default // reference frame (indicated by "") datum_.SetDatumFromName(reference_frame, ""); } catch (const runtime_error& e) { stringstream ss; ss << "InitialiseDatum(): An error occurred while initialising " << endl << " the default reference frame. Details:" << endl << " " << e.what() << endl; SignalExceptionParse(ss.str(), 0); } // Get epsg code and epoch from the 'parsed' datum and epoch m_strProjectDefaultEpsg = datum_.GetEpsgCode_s(); m_strProjectDefaultEpoch = datum_.GetEpoch_s(); // Update binary file meta // Note: the following rule applies each time a new file is loaded: // * This method (InitialiseDatum) is called (from dnaimportwrapper) before any files are loaded // * By default, the bst & bms meta is initialised with the reference frame and reference epoch. // * As each file is loaded, the frame and epoch from the files are captured from the header // * Once all files have been loaded, UpdateEpoch() is called to update the default epoch, with the // assumption that the first file contains the epoch that is to be used for the default, e.g. SINEX file. // * DynAdjust will not attempt to reconcile multiple default epochs found across the input files sprintf(bst_meta_.epsgCode, "%s", m_strProjectDefaultEpsg.substr(0, STN_EPSG_WIDTH).c_str()); sprintf(bms_meta_.epsgCode, "%s", m_strProjectDefaultEpsg.substr(0, STN_EPSG_WIDTH).c_str()); sprintf(bst_meta_.epoch, "%s", m_strProjectDefaultEpoch.substr(0, STN_EPOCH_WIDTH).c_str()); sprintf(bms_meta_.epoch, "%s", m_strProjectDefaultEpoch.substr(0, STN_EPOCH_WIDTH).c_str()); } // DynaXML, dna v.1-2 and sinex file formats do not contain reference frame information, so // by default the reference frame for all stations is set to GDA. // This function is called to modify the default frame to a user-specified frame void dna_import::SetDefaultReferenceFrame(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements) { // Default is GDA94. switch (m_ift) { case sinex: // SNX // For sinex files, the default (or user input) reference frame is set in // parse_sinex_msr and parse_sinex_stn. The epoch of the sinex file is // also set in these functions. Hence, there is no need to override here. return; case dynaml: // DynaML - *stn.xml and *msr.xml // Reference frame is properly handled in and dnaparser_pskel.cxx dnaparser_pimpl.cxx case dna: // DNA - .stn and .msr // Reference frame is properly handled in and ParseDNAMSR... return; case geodesyml: // GeodesyML - GML application schema case csv: // CSV // Does the user want to override what is contained in the input files? if (projectSettings_.i.override_input_rfame == 0) // No, so don't override the reference frame found in the input files return; break; } // Yes, override what is contained in the input files. // Get defaults string strEpsg(datum_.GetEpsgCode_s()); string strEpoch(datum_.GetEpoch_s()); for_each(vStations->begin(), vStations->end(), [this, &strEpsg, &strEpoch] (dnaStnPtr& s) { s->SetReferenceFrame(projectSettings_.i.reference_frame); s->SetEpoch(strEpoch); }); // If only some dna records have frame and epoch, the default reference frame and epoch will be used. CDnaGpsBaselineCluster* bslCluster; CDnaGpsPointCluster* pntCluster; for_each(vMeasurements->begin(), vMeasurements->end(), [this, &bslCluster, &pntCluster, &strEpsg, &strEpoch](dnaMsrPtr& m){ // Set reference frame (and reference epoch) in the CDnaMeasurement (parent class) m->SetReferenceFrame(projectSettings_.i.reference_frame); m->SetEpoch(strEpoch); switch (m->GetTypeC()) { case 'G': // Single Baseline (treat as a single-baseline cluster) bslCluster = (CDnaGpsBaselineCluster*) (m.get()); bslCluster->SetReferenceFrame(projectSettings_.i.reference_frame); bslCluster->SetEpoch(strEpoch); break; case 'X': // GPS Baseline cluster bslCluster = (CDnaGpsBaselineCluster*) (m.get()); bslCluster->SetReferenceFrame(projectSettings_.i.reference_frame); bslCluster->SetEpoch(strEpoch); break; case 'Y': // GPS point cluster pntCluster = (CDnaGpsPointCluster*) (m.get()); pntCluster->SetReferenceFrame(projectSettings_.i.reference_frame); pntCluster->SetEpoch(strEpoch); break; default: break; } }); } _PARSE_STATUS_ dna_import::ParseInputFile(const string& fileName, vdnaStnPtr* vStations, PUINT32 stnCount, vdnaMsrPtr* vMeasurements, PUINT32 msrCount, PUINT32 clusterID, input_file_meta_t* input_file_meta, string* success_msg, project_settings* p) { projectSettings_ = *p; *success_msg = ""; DetermineBoundingBox(); percentComplete_ = -99.0; isProcessing_ = true; stringstream ss; try { // Reset default datum for the input file // Note, the following call assumes InitialiseDatum(...) // has already been called, and set m_strEpsg and m_strEpoch. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionParse(e.what(), 0); } try { // Obtain exclusive use of the input file pointer import_file_mutex.lock(); if (ifsInputFILE_) { ifsInputFILE_->close(); delete ifsInputFILE_; } ifsInputFILE_ = new std::ifstream; // Open and seek to end immediately after opening. file_opener(ifsInputFILE_, fileName, ios::in | ios::ate, ascii, true); // get file size and return to start sifsFileSize_ = (size_t)ifsInputFILE_->tellg(); ifsInputFILE_->seekg(0, ios::beg); // release file pointer mutex import_file_mutex.unlock(); } catch (const ios_base::failure f) { ss.str(""); ss << "ParseInputFile(): An error was encountered when opening " << fileName << "." << endl << " " << f.what() << endl << " Check that the file exists and that the file is not already opened."; SignalExceptionParse(ss.str(), 0); } catch (...) { ss.str(""); ss << "ParseInputFile(): An error was encountered when opening " << fileName << "." << endl << " Check that the file exists and that the file is not already opened."; SignalExceptionParse(ss.str(), 0); } // Firstly, see what type of file this is, then decide what to do with it char first_chars[PRINT_LINE_LENGTH+1]; string fileEpsg, fileEpoch; try { // Obtain exclusive use of the input file pointer import_file_mutex.lock(); ifsInputFILE_->get(first_chars, PRINT_LINE_LENGTH, '\n'); ifsInputFILE_->seekg(0, ios::beg); // put back to beginning // release file pointer mutex import_file_mutex.unlock(); } catch (const ios_base::failure f) { ss.str(""); ss << "ParseInputFile(): An error was encountered when reading " << fileName << "." << endl << " " << f.what() << endl; SignalExceptionParse(ss.str(), 0); } ///////////////////////////////////////// // Test file type and handle accordingly // // XML file if (strncmp(first_chars, "<?xml", 5) == 0) { // Set the file type input_file_meta->filetype = dynaml; m_ift = dynaml; // Parse the DynaML file ParseXML(fileName, vStations, stnCount, vMeasurements, msrCount, clusterID, fileEpsg, fileEpoch, success_msg); if (fileEpsg.empty()) fileEpsg = m_strProjectDefaultEpsg; // record the file's default reference frame sprintf(input_file_meta->epsgCode, "%s", fileEpsg.substr(0, STN_EPSG_WIDTH).c_str()); sprintf(input_file_meta->epoch, "%s", fileEpoch.substr(0, STN_EPOCH_WIDTH).c_str()); } // SNX else if (strncmp(first_chars, "%=SNX", 5) == 0) { // Set the file type input_file_meta->filetype = sinex; m_ift = sinex; m_idt = stn_msr_data; // Parse the SINEX file and capture the epoch ParseSNX(fileName, vStations, stnCount, vMeasurements, msrCount, clusterID, success_msg); // Since SINEX files do not permit recording of reference frame within the file, set // the frame to the default reference frame sprintf(input_file_meta->epsgCode, "%s", m_strProjectDefaultEpsg.substr(0, STN_EPSG_WIDTH).c_str()); sprintf(input_file_meta->epoch, "%s", datum_.GetEpoch_s().substr(0, STN_EPOCH_WIDTH).c_str()); SignalComplete(); } // STN or MSR else if ( // use boost::algorithm::ifind_first, which is a case insensitive implementation of the find first algorithm. strncmp(first_chars, "!#=DNA", 6) == 0 || // dna file? ifind_first(fileName, ".stn") || // dna station file ifind_first(fileName, ".msr")) // dna measurement file { // Set the file type input_file_meta->filetype = dna; m_ift = dna; // Parse the DNA file ParseDNA(fileName, vStations, stnCount, vMeasurements, msrCount, clusterID, fileEpsg, fileEpoch, success_msg); if (fileEpsg.empty()) fileEpsg = m_strProjectDefaultEpsg; // record the file's default reference frame sprintf(input_file_meta->epsgCode, "%s", fileEpsg.substr(0, STN_EPSG_WIDTH).c_str()); sprintf(input_file_meta->epoch, "%s", fileEpoch.substr(0, STN_EPOCH_WIDTH).c_str()); SignalComplete(); } else { //throw XMLInteropException("ParseInputFile(): Could not deduce file type from extension or contents.", 0); ss.str(""); ss << "ParseInputFile(): " << leafStr<string>(fileName) << " is not a recognised station or" << endl << " measurement input file."; (*success_msg) = ss.str(); //SignalExceptionParse(ss.str(), 0); parseStatus_ = PARSE_UNRECOGNISED_FILE; throw XMLInteropException(ss.str(), 0); } /////////////////////////////////// // Apply discontinuities (if they exist) to each file except SINEX // SINEX files are automatically handled if (m_ift != sinex) { if (p->i.apply_discontinuities) ApplyDiscontinuities(vStations, vMeasurements, p); } // Set default reference frame (if the file type does not specify it). SetDefaultReferenceFrame(vStations, vMeasurements); // Populate metadata sprintf(input_file_meta->filename, "%s", fileName.c_str()); if (*stnCount > 0 && *msrCount > 0) input_file_meta->datatype = stn_msr_data; else if (*stnCount > 0) input_file_meta->datatype = stn_data; else if (*msrCount > 0) input_file_meta->datatype = msr_data; return parseStatus_; } void dna_import::ParseXML(const string& fileName, vdnaStnPtr* vStations, PUINT32 stnCount, vdnaMsrPtr* vMeasurements, PUINT32 msrCount, PUINT32 clusterID, string& fileEpsg, string& fileEpoch, string* success_msg) { parseStatus_ = PARSE_SUCCESS; try { // Change current directory to the import folder // A hack to circumvent the problem caused by importing DynaML files in // different directories to where import is run from, causing errors // because DynaML.xsd cannot be found. path currentPath(current_path()); current_path(path(projectSettings_.g.input_folder)); // Instantiate individual parsers. DnaXmlFormat_pimpl DnaXmlFormat_p(ifsInputFILE_, // pass file stream to enable progress to be calculated clusterID, // pass cluster ID so that a unique number can be retained across multiple files datum_.GetName(), // pass the default reference frame datum_.GetEpoch_s(), // pass the default epoch projectSettings_.i.user_supplied_frame==1, // Has a reference frame been supplied? projectSettings_.i.override_input_rfame==1); // Should this reference frame override all others? ::DnaStation_pimpl DnaStation_p; ::xml_schema::string_pimpl string_p; ::StationCoord_pimpl StationCoord_p; ::Height_pimpl Height_p; ::DnaMeasurement_pimpl DnaMeasurement_p; ::Directions_pimpl Directions_p; ::GeoidModel_pimpl GeoidModel_p; ::GPSBaseline_pimpl GPSBaseline_p; ::GPSCovariance_pimpl GPSCovariance_p; ::Clusterpoint_pimpl Clusterpoint_p; ::PointCovariance_pimpl PointCovariance_p; ::type_pimpl type_p; ::referenceframe_pimpl referenceframe_p; ::epoch_pimpl epoch_p; // Connect the parsers together. // DnaXmlFormat_p.parsers (DnaStation_p, DnaMeasurement_p, // attributes type_p, referenceframe_p, epoch_p); DnaStation_p.parsers (string_p, string_p, string_p, StationCoord_p, string_p); StationCoord_p.parsers (string_p, string_p, string_p, Height_p, string_p, GeoidModel_p); DnaMeasurement_p.parsers (string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, Directions_p, string_p, string_p, string_p, GPSBaseline_p, string_p, string_p, string_p, Clusterpoint_p, string_p, string_p, string_p, string_p, (projectSettings_.i.prefer_single_x_as_g == TRUE ? true : false)); Directions_p.parsers (string_p, string_p, string_p, string_p, string_p); GPSBaseline_p.parsers (string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, GPSCovariance_p); GPSCovariance_p.parsers (string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p); Clusterpoint_p.parsers (string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, PointCovariance_p); PointCovariance_p.parsers (string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p, string_p); // Parse the XML document. // ::xml_schema::document doc_p (DnaXmlFormat_p, "DnaXmlFormat"); DnaXmlFormat_p.pre(); doc_p.parse (*ifsInputFILE_); DnaXmlFormat_p.post_DnaXmlFormat (vStations, vMeasurements); SignalComplete(); *clusterID = DnaXmlFormat_p.CurrentClusterID(); *stnCount = DnaXmlFormat_p.NumStationsRead(); *msrCount = DnaXmlFormat_p.NumMeasurementsRead(); *success_msg = DnaXmlFormat_p.DnaXmlParseMessage() + "\n"; try { // Get the reference frame from the XML file (i.e. referenceframe attribute in DnaXmlFormat element) string xml_referenceframe = referenceframe_p.str(); string xml_epoch = epoch_p.str(); // Is this attribute value an empty string? As long as a default value // is specified in DynaML.xsd, this value will never be empty, unless the user // has inadvertently set in the xml file, e.g.: // <DnaXmlFormat referenceframe="" ... > if (xml_referenceframe.empty()) // No, so get the epsg code from the default datum fileEpsg = datum_.GetEpsgCode_s(); else fileEpsg = epsgStringFromName<string>(xml_referenceframe); if (xml_epoch.empty()) // No, so get the epoch from the default datum fileEpoch = datum_.GetEpoch_s(); else fileEpoch = xml_epoch; } catch (...) { stringstream ss; ss << "The default input file reference frame \"" << referenceframe_p.str() << "\" is not recognised."; SignalExceptionParse(static_cast<string>(ss.str()), 0); } if (!vStations->empty() && !vMeasurements->empty()) m_idt = stn_msr_data; else if (!vStations->empty()) m_idt = stn_data; else if (!vMeasurements->empty()) m_idt = msr_data; current_path(currentPath); } catch (const ios_base::failure& f) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } if (ifsInputFILE_->rdstate() & std::ifstream::eofbit) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseInputFile(): An ios_base failure was encountered while parsing " << fileName << "." << endl << " " << f.what(); SignalExceptionParse(static_cast<string>(ss.str()), 0); } catch (const std::system_error& e) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } if (ifsInputFILE_->rdstate() & std::ifstream::eofbit) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseInputFile(): An ios_base failure was encountered while parsing " << fileName << "." << endl << " " << e.what(); SignalExceptionParse(static_cast<string>(ss.str()), 0); } catch (const XMLInteropException& e) { stringstream ss; ss << "ParseInputFile(): An exception was encountered while parsing " << fileName << "." << endl << " " << e.what(); SignalExceptionParse(static_cast<string>(ss.str()), 0); } catch (const ::xml_schema::parsing& e) { stringstream ss(""); ss << e.what(); ::xsd::cxx::parser::diagnostics<char>::const_iterator _it; for (_it=e.diagnostics().begin(); _it!=e.diagnostics().end(); _it++) { ss << endl; ss << " - line " << _it->line(); ss << ", column " << _it->column(); ss << ", severity " << _it->severity() << endl; ss << " - " << _it->message(); } SignalExceptionParse(ss.str(), 0); } catch (const ::xml_schema::exception& e) { stringstream ss; ss << "ParseInputFile(): An xml_schema exception was encountered while parsing " << fileName << "." << endl << " " << e.what(); SignalExceptionParse(static_cast<string>(ss.str()), 0); } catch (...) { stringstream ss; ss << "ParseInputFile(): An unknown error was encountered while parsing " << fileName << "." << endl; SignalExceptionParse(ss.str(), 0); } if (parseStatus_ != PARSE_SUCCESS) { stringstream ss(""); ss.str(""); ss << "- Warning: Parse success code = " << PARSE_SUCCESS << "." << endl; (*success_msg) += ss.str(); } } void dna_import::ParseSNX(const string& fileName, vdnaStnPtr* vStations, PUINT32 stnCount, vdnaMsrPtr* vMeasurements, PUINT32 msrCount, PUINT32 clusterID, string* success_msg) { try { // Load sinex file and capture epoch. Throws runtime_error on failure. dna_io_snx snx; snx.parse_sinex(&ifsInputFILE_, fileName, vStations, stnCount, vMeasurements, msrCount, clusterID, success_msg, g_parsestn_tally, g_parsemsr_tally, g_fileOrder, datum_, projectSettings_.i.apply_discontinuities==1, &stn_discontinuities_, m_discontsSortedbyName, m_lineNo, m_columnNo, parseStatus_); } catch (const runtime_error& e) { SignalExceptionParse(e.what(), 0); } } // Parse discontinuities and create discontinuity tuple void dna_import::ParseDiscontinuities(const string& fileName) { std::ifstream discont_file; try { // Open discontinuity file. Throws runtime_error on failure. file_opener(discont_file, fileName, ios::in, ascii, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { // Load discontinuity file. Throws runtime_error on failure. dna_io_snx snx; projectSettings_.i.apply_discontinuities = true; snx.parse_discontinuity_file(&discont_file, fileName, &stn_discontinuities_, m_discontsSortedbyName, m_lineNo, m_columnNo, parseStatus_); } catch (const runtime_error& e) { SignalExceptionParse(e.what(), 0); } discont_file.close(); } void dna_import::AddDiscontinuityStations(vdnaStnPtr* vStations) { _it_vdnastnptr _it_stn(vStations->begin()); it_string_pair stn_renames_it; dnaStnPtr stn_ptr; string stationName; UINT32 i, station_count(static_cast<UINT32>(vStations->size())); UINT32 station_index(station_count); for (i=0; i<station_count; ++i) { stationName = vStations->at(i)->GetName(); // For each occurrence of stationName in stn_renamed_, create a clone and add it to // vStations so that the measurement stations renamed by ApplyDiscontinuitiesMeasurements // are supported by corresponding stations while ((stn_renames_it = binary_search_index_pair(stn_renamed_.begin(), stn_renamed_.end(), stationName)) != stn_renamed_.end()) { // If a sinex file has been loaded and stationName exists in the sinex file, stn_renames_it->second may // already exist in vStations. In this case, the following code will add a duplicate station. // For this reason, duplicates will be removed at the end of this function. // Whilst this might seem inefficient, the alternative (i.e. search for stn_renames_it->second // in vStations before push_back) is far less efficient. Also, if the first occurrence of this station // is the correct station loaded from a sinex file, the (cloned) duplicate will be removed on account of // the duplicate having a larger file order, via SetfileOrder(++station_index) below. stn_ptr.reset(vStations->at(i)->clone()); stn_ptr->SetName(stn_renames_it->second); stn_ptr->SetfileOrder(++station_index); vStations->push_back(stn_ptr); if (!stn_renamed_.empty()) stn_renamed_.erase(stn_renames_it); } if (stn_renamed_.empty()) break; } // Removde duplicates which may have been added through the above process sort(vStations->begin(), vStations->end(), CompareStationName<dnaStnPtr>()); _it_vdnastnptr _it_stn_newend = unique(vStations->begin(), vStations->end(), EqualStationName<dnaStnPtr>()); if (_it_stn_newend != vStations->end()) vStations->resize(_it_stn_newend - vStations->begin()); } void dna_import::ApplyDiscontinuities(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, project_settings* p) { #ifndef _MSDEBUG // return on release return; #endif if (stn_discontinuities_.empty()) return; if (!m_discontsSortedbyName) { sort(stn_discontinuities_.begin(), stn_discontinuities_.end(), CompareSiteTuplesByName<discontinuity_tuple>()); m_discontsSortedbyName = true; } // There isn't any need to apply discontinuities to a station file, since those // stations will be introduced via the process of handling a discontinuity file. // DynAdjust should load the stations as normal. If a station becomes renamed // through the process of applying discontinuities to measurements, then it will // be flagged as unused (since it won't be found in the measurements). if (!vMeasurements->empty()) ApplyDiscontinuitiesMeasurements(vMeasurements, p); } void dna_import::TrackDiscontinuitySite(const string& site, const string& site_renamed) { if (!binary_search(stn_renamed_.begin(), stn_renamed_.end(), site_renamed, ComparePairSecond<string>())) { stn_renamed_.push_back(string_string_pair(site, site_renamed)); sort(stn_renamed_.begin(), stn_renamed_.end(), ComparePairFirst<string>()); } } // This function renames stations in each measurement based on a discontinuity file // NOTE: A fundamental prerequisite for the proper renaming of discontinuity sites // in this function is a valid epoch for each measurement!s void dna_import::ApplyDiscontinuitiesMeasurements(vdnaMsrPtr* vMeasurements, project_settings* p) { _it_vdiscontinuity_tuple _it_discont(stn_discontinuities_.begin()); string site_renamed, stn1, stn2, stn3; date site_date; vector<CDnaDirection>* vdirns; vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsPoint>* vgpsPnts; _it_vdnamsrptr _it_msr(vMeasurements->begin()); // Update station names for (_it_msr = vMeasurements->begin(); _it_msr != vMeasurements->end(); _it_msr++) { // 1. Handle nested type measurements (D, G, X, Y) separately switch (_it_msr->get()->GetTypeC()) { case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vgpsBsls = _it_msr->get()->GetBaselines_ptr(); ApplyDiscontinuitiesMeasurements_GX(vgpsBsls); continue; case 'Y': // GPS point cluster vgpsPnts = _it_msr->get()->GetPoints_ptr(); ApplyDiscontinuitiesMeasurements_Y(vgpsPnts); continue; } // Capture the epoch of the measurement site_date = dateFromString<date>(_it_msr->get()->GetEpoch()); // 2. Handle 'first' station for every measurement type stn1 = _it_msr->get()->GetFirst(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn1)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn1, site_date, site_renamed)) { _it_msr->get()->SetFirst(site_renamed); TrackDiscontinuitySite(stn1, site_renamed); } } // Finished with single station measurements switch (_it_msr->get()->GetTypeC()) { case 'H': // Orthometric height case 'R': // Ellipsoidal height case 'I': // Astronomic latitude case 'J': // Astronomic longitude case 'P': // Geodetic latitude case 'Q': // Geodetic longitude continue; } // 3. Handle 'second' station for every measurement type stn2 = _it_msr->get()->GetTarget(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn2)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn2, site_date, site_renamed)) { _it_msr->get()->SetTarget(site_renamed); TrackDiscontinuitySite(stn2, site_renamed); } } // 3. Handle D measurement directions switch (_it_msr->get()->GetTypeC()) { case 'D': // Direction set // handle the directions in the set vdirns = _it_msr->get()->GetDirections_ptr(); ApplyDiscontinuitiesMeasurements_D(vdirns); continue; // Finished with single station measurements case 'B': // Geodetic azimuth case 'C': // Chord dist case 'E': // Ellipsoid arc case 'K': // Astronomic azimuth case 'L': // Level difference case 'M': // MSL arc case 'S': // Slope distance case 'V': // Zenith angle case 'Z': // Vertical angle continue; } // 4. multiple station measurements stn3 = _it_msr->get()->GetTarget2(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn3)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (_it_discont->discontinuity_exists) { // Rename station name according to date if it is a discontinuity site if (rename_discont_station(_it_discont, stn3, site_date, site_renamed)) { _it_msr->get()->SetTarget2(site_renamed); TrackDiscontinuitySite(stn3, site_renamed); } } } } } void dna_import::ApplyDiscontinuitiesMeasurements_GX(vector<CDnaGpsBaseline>* vGpsBaselines) { vector< CDnaGpsBaseline >::iterator _it_msr(vGpsBaselines->begin()); _it_vdiscontinuity_tuple _it_discont(stn_discontinuities_.begin()); string site_renamed, stn1, stn2, stn3; date site_date; for (_it_msr = vGpsBaselines->begin(); _it_msr != vGpsBaselines->end(); _it_msr++) { // Capture the start date of the site site_date = dateFromString<date>(_it_msr->GetEpoch()); // Station 1 stn1 = _it_msr->GetFirst(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn1)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn1, site_date, site_renamed)) { _it_msr->SetFirst(site_renamed); TrackDiscontinuitySite(stn1, site_renamed); } } // Station 2 stn2 = _it_msr->GetTarget(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn2)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn2, site_date, site_renamed)) { _it_msr->SetTarget(site_renamed); TrackDiscontinuitySite(stn2, site_renamed); } } } } void dna_import::ApplyDiscontinuitiesMeasurements_Y(vector<CDnaGpsPoint>* vGpsPoints) { vector< CDnaGpsPoint >::iterator _it_msr(vGpsPoints->begin()); _it_vdiscontinuity_tuple _it_discont(stn_discontinuities_.begin()); string site_renamed, stn1, stn2, stn3; date site_date; for (_it_msr = vGpsPoints->begin(); _it_msr != vGpsPoints->end(); _it_msr++) { // Capture the start date of the site site_date = dateFromString<date>(_it_msr->GetEpoch()); // Station 1 stn1 = _it_msr->GetFirst(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn1)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn1, site_date, site_renamed)) { _it_msr->SetFirst(site_renamed); TrackDiscontinuitySite(stn1, site_renamed); } } } } void dna_import::ApplyDiscontinuitiesMeasurements_D(vector<CDnaDirection>* vDirections) { vector< CDnaDirection >::iterator _it_msr(vDirections->begin()); _it_vdiscontinuity_tuple _it_discont(stn_discontinuities_.begin()); string site_renamed, stn1, stn2, stn3; date site_date; for (_it_msr = vDirections->begin(); _it_msr != vDirections->end(); _it_msr++) { // Capture the epoch of the measurement site_date = dateFromString<date>(_it_msr->GetEpoch()); // Station 1 stn1 = _it_msr->GetFirst(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn1)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn1, site_date, site_renamed)) { _it_msr->SetFirst(site_renamed); TrackDiscontinuitySite(stn1, site_renamed); } } // Station 2 stn2 = _it_msr->GetTarget(); _it_discont = stn_discontinuities_.begin(); if ((_it_discont = binary_search_discontinuity_site( _it_discont, stn_discontinuities_.end(), stn2)) != stn_discontinuities_.end()) { // Site found in discontinuity file! // Handle renaming, and add this to the list of 'renamed stations' if (rename_discont_station(_it_discont, stn2, site_date, site_renamed)) { _it_msr->SetTarget(site_renamed); TrackDiscontinuitySite(stn2, site_renamed); } } } } // Get version number and assign field widths/locations void dna_import::ParseDNAVersion(const INPUT_DATA_TYPE& idt) { string sBuf; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Set the default version string version("1.00"); // Attempt to get this file's version try { if (iequals("!#=DNA", sBuf.substr(0, 6))) version = trimstr(sBuf.substr(6, 6)); } catch (...) { SignalExceptionParseDNA("ParseDNAVersion(): Could not extract file version from the record: ", sBuf, 6); } stringstream ss; switch (idt) { case stn_data: determineDNASTNFieldParameters<UINT16>(version, dsl_, dsw_); break; case msr_data: determineDNAMSRFieldParameters<UINT16>(version, dml_, dmw_); break; default: ss << " Unknown file type." << endl; m_columnNo = 0; throw XMLInteropException(ss.str(), m_lineNo); } } void dna_import::ParseDNA(const string& fileName, vdnaStnPtr* vStations, PUINT32 stnCount, vdnaMsrPtr* vMeasurements, PUINT32 msrCount, PUINT32 clusterID, string& fileEpsg, string& fileEpoch, string* success_msg) { parseStatus_ = PARSE_SUCCESS; (*stnCount) = 0; (*msrCount) = 0; g_parsestn_tally.initialise(); g_parsemsr_tally.initialise(); string stn_file_type(".stn"), msr_file_type(".msr"); string version, geoversion; INPUT_DATA_TYPE idt; UINT32 count; size_t pos = 0; m_lineNo = 1; m_columnNo = 0; dna_io_dna dnaFile; // Get header information try { // Read DNA header // Obtain exclusive use of the input file pointer import_file_mutex.lock(); // Read the dna file header, and set the // reference frame based on the header and user preferences dnaFile.read_dna_header(ifsInputFILE_, version, idt, datum_, // default datum projectSettings_.i.user_supplied_frame==1, // Has a reference frame been supplied? projectSettings_.i.override_input_rfame==1, // does the user want to override the datum in the input files? fileEpsg, fileEpoch, geoversion, count); // release file pointer mutex import_file_mutex.unlock(); } catch (const runtime_error& e) { SignalExceptionParse(static_cast<string>(e.what()), 0); } // Station file if (idt == stn_data || (pos = fileName.find(stn_file_type, 0)) != string::npos) { // Determine the file format version //ParseDNAVersion(stn_data); dsl_ = dnaFile.dna_stn_positions(); dsw_ = dnaFile.dna_stn_widths(); try { ParseDNASTN(vStations, stnCount, success_msg); m_idt = stn_data; } catch (const ios_base::failure& f) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNA(): An ios_base failure was encountered when attempting to read stations file " << fileName << "." << endl << " " << f.what(); SignalExceptionParse(ss.str(), 0); } catch (const XMLInteropException& f) { stringstream ss; ss << " - line " << m_lineNo; ss << ", column " << m_columnNo << endl; ss << " - " << f.what(); SignalExceptionParse(ss.str(), 0); } catch (...) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNA(): An error was encountered when attempting to read stations file " << fileName << "."; SignalExceptionParse(ss.str(), 0); } } else if (idt == msr_data || (pos = fileName.find(msr_file_type, 0)) != string::npos) { // Determine the file format version //ParseDNAVersion(msr_data); dml_ = dnaFile.dna_msr_positions(); dmw_ = dnaFile.dna_msr_widths(); try { ParseDNAMSR(vStations, vMeasurements, msrCount, clusterID, success_msg); m_idt = msr_data; } catch (const ios_base::failure& f) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNA(): An ios_base failure was encountered when attempting to read measurements file " << fileName << "." << endl << " " << f.what(); SignalExceptionParse(ss.str(), 0); } catch (const XMLInteropException& f) { stringstream ss; ss << endl << " - line " << m_lineNo; ss << ", column " << m_columnNo << endl; ss << " - " << f.what(); SignalExceptionParse(ss.str(), 0); } catch (...) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNA(): An error was encountered when attempting to read measurements file " << fileName << "." << endl; ss << " - line " << m_lineNo; ss << ", column " << m_columnNo << endl; SignalExceptionParse(ss.str(), 0); } } } void dna_import::ParseDNASTN(vdnaStnPtr* vStations, PUINT32 stnCount, string* success_msg) { string sBuf, tmp; dnaStnPtr stn_ptr; vStations->clear(); //while (!ifsInputFILE_->eof()) // while EOF not found while (ifsInputFILE_) { // Obtain exclusive use of the input file pointer import_file_mutex.lock(); if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); break; } m_lineNo++; try { getline((*ifsInputFILE_), sBuf); stn_ptr.reset(new CDnaStation(datum_.GetName(), datum_.GetEpoch_s())); } catch (...) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNASTN(): Could not read from the station file." << endl; m_columnNo = 0; throw XMLInteropException(ss.str(), m_lineNo); } // release file pointer mutex import_file_mutex.unlock(); // blank or whitespace? if (trimstr(sBuf).empty()) continue; // Ignore lines with blank station name if (trimstr(sBuf.substr(dsl_.stn_name, dsw_.stn_name)).empty()) continue; // Ignore lines with comments if (sBuf.compare(0, 1, "*") == 0) continue; stn_ptr->SetfileOrder(g_fileOrder++); // name try { tmp = trimstr(sBuf.substr(dsl_.stn_name, dsw_.stn_name)); stn_ptr->SetName(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract station name from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_name+1; throw XMLInteropException(ss.str(), m_lineNo); } // constraints try { tmp = trimstr(sBuf.substr(dsl_.stn_const, dsw_.stn_const)); stn_ptr->SetConstraints(tmp); g_parsestn_tally.addstation(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract station constraints from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_const+1; throw XMLInteropException(ss.str(), m_lineNo); } // coordinate type try { tmp = trimstr(sBuf.substr(dsl_.stn_type, dsw_.stn_type)); stn_ptr->SetCoordType(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract coordinate type from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_type+1; throw XMLInteropException(ss.str(), m_lineNo); } // coordinates try { tmp = trimstr(sBuf.substr(dsl_.stn_e_phi_x, dsw_.stn_e_phi_x)); // easting, latitude, X stn_ptr->SetXAxis(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract station "; switch (stn_ptr.get()->GetMyCoordTypeC()) { case XYZ_type_i: ss << "X"; break; case UTM_type_i: ss << "easting"; break; case LLH_type_i: case LLh_type_i: ss << "latitude"; break; } ss << " value from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_e_phi_x+1; throw XMLInteropException(ss.str(), m_lineNo); } try { tmp = trimstr(sBuf.substr(dsl_.stn_n_lam_y, dsw_.stn_n_lam_y)); // northing, longitude, Y stn_ptr->SetYAxis(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract station "; switch (stn_ptr->GetMyCoordTypeC()) { case XYZ_type_i: ss << "Y"; break; case UTM_type_i: ss << "northing"; break; case LLH_type_i: case LLh_type_i: ss << "longitude"; break; } ss << " value from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_n_lam_y+1; throw XMLInteropException(ss.str(), m_lineNo); } try { tmp = trimstr(sBuf.substr(dsl_.stn_ht_z, dsw_.stn_ht_z)); // orthometric height, Z if (stn_ptr->GetMyCoordTypeC() == XYZ_type_i) stn_ptr->SetZAxis(tmp); else stn_ptr->SetHeight(tmp); } catch (...) { stringstream ss; ss << "ParseDNASTN(): Could not extract station "; switch (stn_ptr->GetMyCoordTypeC()) { case XYZ_type_i: ss << "Z"; break; case LLH_type_i: case LLh_type_i: case UTM_type_i: ss << "height"; break; } ss << " value from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_ht_z+1; throw XMLInteropException(ss.str(), m_lineNo); } if (sBuf.length() > dsl_.stn_hemi_zo) { try { tmp = trimstr(sBuf.substr(dsl_.stn_hemi_zo, dsw_.stn_hemi_zo)); // hemisphere-zone stn_ptr->SetHemisphereZone(tmp); } catch (...) { switch (stn_ptr->GetMyCoordTypeC()) { case UTM_type_i: // Hemisphere and zone is only essential for UTM types stringstream ss; ss << "ParseDNASTN(): Could not extract station hemisphere and zone from the record: " << endl << " " << sBuf << endl; m_columnNo = dsl_.stn_hemi_zo+1; throw XMLInteropException(ss.str(), m_lineNo); } } } if (sBuf.length() > dsl_.stn_desc) { try { tmp = trimstr(sBuf.substr(dsl_.stn_desc)); // description stn_ptr->SetDescription(tmp); } catch (...) { // do nothing (description is not compulsory) } } (*stnCount)++; vStations->push_back(stn_ptr); } } void dna_import::ParseDNAMSR(vdnaStnPtr* vStations, pvdnaMsrPtr vMeasurements, PUINT32 msrCount, PUINT32 clusterID, string* success_msg) { string sBuf, tmp; dnaMsrPtr msr_ptr; vMeasurements->clear(); char cType; bool ignoreMsr; bool measurementRead(false); m_msrComments.clear(); //while (!ifsInputFILE_->eof()) // while EOF not found while (ifsInputFILE_) { // Obtain exclusive use of the input file pointer import_file_mutex.lock(); if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); break; } m_lineNo++; try { getline((*ifsInputFILE_), sBuf); } catch (...) { if (ifsInputFILE_->eof()) { // release file pointer mutex import_file_mutex.unlock(); return; } stringstream ss; ss << "ParseDNAMSR(): Could not read from the measurement file." << endl; m_columnNo = 0; throw XMLInteropException(ss.str(), m_lineNo); } // release file pointer mutex import_file_mutex.unlock(); // blank or whitespace? if (trimstr(sBuf).empty()) continue; // no station value? if (trimstr(sBuf.substr(dml_.msr_inst, dmw_.msr_inst)).empty()) continue; // Capture comment (which may apply to several measurements) if (sBuf.compare(0, 1, "*") == 0) { // Is this a new comment? if (measurementRead) // The last record was a measurement, so this is a new comment m_msrComments.clear(); measurementRead = false; if (!m_msrComments.empty()) m_msrComments += "\n"; m_msrComments += sBuf.substr(1); continue; } // no station value? if (trimstr(sBuf.substr(dml_.msr_inst, dmw_.msr_inst)).empty()) continue; try { tmp = trimstr(sBuf.substr(dml_.msr_type, 1)); cType = (tmp.c_str())[0]; cType = static_cast<char>(toupper(cType)); } catch (...) { stringstream ss; ss << "ParseDNAMSR(): Could not extract measurement type from the record: " << endl << " " << sBuf << endl; m_columnNo = dml_.msr_type+1; throw XMLInteropException(ss.str(), m_lineNo); } ignoreMsr = iequals("*", sBuf.substr(dml_.msr_ignore, dmw_.msr_ignore)); switch (cType) { case 'A': // Horizontal angle g_parsemsr_tally.A++; msr_ptr.reset(new CDnaAngle); ParseDNAMSRAngular(sBuf, msr_ptr); (*msrCount) += 1; break; case 'B': // Geodetic azimuth g_parsemsr_tally.B++; msr_ptr.reset(new CDnaAzimuth); ParseDNAMSRAngular(sBuf, msr_ptr); (*msrCount) += 1; break; case 'C': // Chord dist g_parsemsr_tally.C++; msr_ptr.reset(new CDnaDistance); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'D': // Direction set msr_ptr.reset(new CDnaDirectionSet(++(*clusterID))); ParseDNAMSRDirections(sBuf, msr_ptr, ignoreMsr); (*msrCount) += static_cast<UINT32>(msr_ptr->GetDirections_ptr()->size()); break; case 'E': // Ellipsoid arc g_parsemsr_tally.E++; msr_ptr.reset(new CDnaDistance); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster msr_ptr.reset(new CDnaGpsBaselineCluster(++(*clusterID), datum_.GetName(), datum_.GetEpoch_s())); ParseDNAMSRGPSBaselines(sBuf, msr_ptr, ignoreMsr); (*msrCount) += static_cast<UINT32>(msr_ptr->GetBaselines_ptr()->size() * 3); break; case 'H': // Orthometric height g_parsemsr_tally.H++; msr_ptr.reset(new CDnaHeight); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'I': // Astronomic latitude g_parsemsr_tally.I++; msr_ptr.reset(new CDnaCoordinate); ParseDNAMSRCoordinate(sBuf, msr_ptr); (*msrCount) += 1; break; case 'J': // Astronomic longitude g_parsemsr_tally.J++; msr_ptr.reset(new CDnaCoordinate); ParseDNAMSRCoordinate(sBuf, msr_ptr); (*msrCount) += 1; break; case 'K': // Astronomic azimuth g_parsemsr_tally.K++; msr_ptr.reset(new CDnaAzimuth); ParseDNAMSRAngular(sBuf, msr_ptr); (*msrCount) += 1; break; case 'L': // Level difference g_parsemsr_tally.L++; msr_ptr.reset(new CDnaHeightDifference); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'M': // MSL arc g_parsemsr_tally.M++; msr_ptr.reset(new CDnaDistance); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'P': // Geodetic latitude g_parsemsr_tally.P++; msr_ptr.reset(new CDnaCoordinate); ParseDNAMSRCoordinate(sBuf, msr_ptr); (*msrCount) += 1; break; case 'Q': // Geodetic longitude g_parsemsr_tally.Q++; msr_ptr.reset(new CDnaCoordinate); ParseDNAMSRCoordinate(sBuf, msr_ptr); (*msrCount) += 1; break; case 'R': // Ellipsoidal height g_parsemsr_tally.R++; msr_ptr.reset(new CDnaHeight); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'S': // Slope distance g_parsemsr_tally.S++; msr_ptr.reset(new CDnaDistance); ParseDNAMSRLinear(sBuf, msr_ptr); (*msrCount) += 1; break; case 'V': // Zenith angle g_parsemsr_tally.V++; msr_ptr.reset(new CDnaDirection); ParseDNAMSRAngular(sBuf, msr_ptr); (*msrCount) += 1; break; case 'Y': // GPS point cluster msr_ptr.reset(new CDnaGpsPointCluster(++(*clusterID), datum_.GetName(), datum_.GetEpoch_s())); ParseDNAMSRGPSPoints(sBuf, msr_ptr, ignoreMsr); (*msrCount) += static_cast<UINT32>(msr_ptr->GetPoints_ptr()->size() * 3); break; case 'Z': // Vertical angle g_parsemsr_tally.Z++; msr_ptr.reset(new CDnaDirection); ParseDNAMSRAngular(sBuf, msr_ptr); (*msrCount) += 1; break; default: stringstream ss; ss << "ParseDNAMSR(): Unknown measurement type: " << cType << endl; throw XMLInteropException(ss.str(), m_lineNo); } measurementRead = true; // set ignore flag msr_ptr->SetIgnore(ignoreMsr); // add the measurement to the list vMeasurements->push_back(msr_ptr); } } void dna_import::ParseDNAMSRLinear(const string& sBuf, dnaMsrPtr& msr_ptr) { // Measurement type try { msr_ptr->SetType(trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type))); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRLinear(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseLinear")); // Target station if (msr_ptr->GetMsrStnCount() >= TWO_STATION) msr_ptr->SetTarget(ParseTargetValue(sBuf, "ParseLinear")); // If import is being used to simulate measurements, return as the // expected input is: // Measurement // From station // To station // So no need to read any further if (projectSettings_.i.simulate_measurements) return; // Value msr_ptr->SetValue(ParseLinearValue(sBuf, measurement_name<char, string>(msr_ptr->GetTypeC()), "ParseLinear")); // Standard deviation msr_ptr->SetStdDev(ParseStdDevValue(sBuf, "ParseLinear")); // Capture msr_id and cluster_id (for database referencing) m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseLinear", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); // instrument and target heights only make sense for // slope distances, vertical angles and zenith distances switch (msr_ptr->GetTypeC()) { case 'S': break; default: // don't need instrument height for all other measurement types return; } // Instrument and target heights if (sBuf.length() <= dml_.msr_inst_ht) { msr_ptr->SetInstrumentHeight("0.0"); msr_ptr->SetTargetHeight("0.0"); return; } msr_ptr->SetInstrumentHeight(ParseInstHeightValue(sBuf, "ParseLinear")); // Target height if (sBuf.length() <= dml_.msr_targ_ht) { msr_ptr->SetTargetHeight("0.0"); return; } msr_ptr->SetTargetHeight(ParseTargHeightValue(sBuf, "ParseLinear")); } void dna_import::ParseDNAMSRCoordinate(const string& sBuf, dnaMsrPtr& msr_ptr) { // Measurement type try { msr_ptr->SetType(trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type))); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRCoordinate(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRCoordinate")); // If import is being used to simulate measurements, return as the // expected input is: // Measurement // From station // To station // So no need to read any further if (projectSettings_.i.simulate_measurements) return; // Value msr_ptr->SetValue(ParseLinearValue(sBuf, measurement_name<char, string>(msr_ptr->GetTypeC()), "ParseDNAMSRCoordinate")); // Standard deviation msr_ptr->SetStdDev(ParseStdDevValue(sBuf, "ParseDNAMSRCoordinate")); // Capture msr_id and cluster_id (for database referencing), then set // database id info m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseDNAMSRCoordinate", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); } void dna_import::ParseDNAMSRGPSBaselines(string& sBuf, dnaMsrPtr& msr_ptr, bool ignoreMsr) { CDnaGpsBaseline bslTmp; CDnaCovariance covTmp; bslTmp.SetReferenceFrame(msr_ptr->GetReferenceFrame()); bslTmp.SetEpoch(msr_ptr->GetEpoch()); // Measurement type string tmp; try { tmp = trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type)); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRGPSBaselines(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } msr_ptr->SetType(tmp); bslTmp.SetType(tmp); bslTmp.SetIgnore(ignoreMsr); covTmp.SetType(tmp); covTmp.SetIgnore(ignoreMsr); // So no need to read database ID if (!projectSettings_.i.simulate_measurements) { // Capture msr_id and cluster_id (for database referencing) m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseDNAMSRGPSBaselines", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); bslTmp.SetClusterID(msr_ptr->GetClusterID()); covTmp.SetClusterID(msr_ptr->GetClusterID()); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetFirst(msr_ptr->GetFirst()); // Target station bslTmp.SetTarget(ParseTargetValue(sBuf, "ParseDNAMSRGPSBaselines")); // Number of baselines UINT32 bslCount(1); if (iequals(msr_ptr->GetType(), "X")) msr_ptr->SetTotal(ParseMsrCountValue(sBuf, bslCount, "ParseDNAMSRGPSBaselines")); msr_ptr->SetRecordedTotal(bslCount); bslTmp.SetRecordedTotal(bslCount); msr_ptr->GetBaselines_ptr()->reserve(bslCount); if (iequals(msr_ptr->GetType(), "X")) g_parsemsr_tally.X += bslCount * 3; else g_parsemsr_tally.G += bslCount * 3; // V-scale msr_ptr->SetVscale(ParseScaleVValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetVscale(msr_ptr->GetVscale()); // P-scale msr_ptr->SetPscale(ParseScalePValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetPscale(msr_ptr->GetPscale()); // L-scale supplied? msr_ptr->SetLscale(ParseScaleLValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetLscale(msr_ptr->GetLscale()); // H-scale supplied? msr_ptr->SetHscale(ParseScaleHValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetHscale(msr_ptr->GetHscale()); // Process for setting reference frame is: // 1. Set the default reference frame in ParseDNAMSR when msr_ptr is initialised // 2. Initialise bslTmp using msr_ptr // 3. When a reference frame element is found here, change the reference frame // using checks on override // same as: // - DnaXmlFormat_pskel::_start_element_impl when DnaMeasurement is reached // - DnaMeasurement_pimpl::ReferenceFrame when ReferenceFrame tag is found // - GPSBaseline_pimpl::pre() if (projectSettings_.i.override_input_rfame) { // Set the cluster frame msr_ptr->SetReferenceFrame(projectSettings_.i.reference_frame); // Set the baseline frame bslTmp.SetReferenceFrame(projectSettings_.i.reference_frame); } else //if (!projectSettings_.i.override_input_rfame) { try { // Get the reference frame from the file tmp = ParseRefFrameValue(sBuf, "ParseDNAMSRGPSBaselines"); if (!tmp.empty()) { // Set the cluster frame msr_ptr->SetReferenceFrame(tmp); // Set the baseline frame bslTmp.SetReferenceFrame(tmp); } } catch (runtime_error& e) { stringstream ss; ss << "ParseDNAMSRGPSBaselines(): Error parsing reference frame: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), "", dml_.msr_gps_reframe); } try { // Get the epoch from the file tmp = ParseEpochValue(sBuf, "ParseDNAMSRGPSBaselines"); if (!tmp.empty()) { // Set the cluster epoch msr_ptr->SetEpoch(tmp); // Set the baseline epoch bslTmp.SetEpoch(tmp); } } catch (runtime_error& e) { stringstream ss; ss << "ParseDNAMSRGPSBaselines(): Error parsing epoch: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), "", dml_.msr_gps_epoch); } } bool first_run(true); UINT32 cov, covCount(bslCount - 1); for (UINT32 b(0); b<bslCount; ++b, --covCount) { if (!first_run) { m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRGPSBaselines")); bslTmp.SetFirst(msr_ptr->GetFirst()); // Target station bslTmp.SetTarget(ParseTargetValue(sBuf, "ParseDNAMSRGPSBaselines")); } first_run = false; if (!projectSettings_.i.simulate_measurements) { m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Capture msr_id and cluster_id (for database referencing), then set // database id info ParseDatabaseIds(sBuf, "ParseDNAMSRGPSBaselines", msr_ptr->GetTypeC()); bslTmp.SetDatabaseMap(m_msr_db_map, m_databaseIdSet); bslTmp.SetX(ParseGPSMsrValue(sBuf, "X", "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaXX(ParseGPSVarValue(sBuf, "X", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSBaselines")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); bslTmp.SetY(ParseGPSMsrValue(sBuf, "Y", "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaXY(ParseGPSVarValue(sBuf, "Y", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaYY(ParseGPSVarValue(sBuf, "Y", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRGPSBaselines")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); bslTmp.SetZ(ParseGPSMsrValue(sBuf, "Z", "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaXZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaYZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRGPSBaselines")); bslTmp.SetSigmaZZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_3, dmw_.msr_gps_vcv_3, "ParseDNAMSRGPSBaselines")); } bslTmp.ResizeGpsCovariancesCount(); bslTmp.ReserveGpsCovariancesCount(covCount); for (cov=0; cov<covCount; ++cov) { if (!projectSettings_.i.simulate_measurements) ParseDNAMSRCovariance(covTmp); bslTmp.AddGpsCovariance(&covTmp); } msr_ptr->AddGpsBaseline(((CDnaGpsBaseline*)&bslTmp)); } } void dna_import::ParseDNAMSRGPSPoints(string& sBuf, dnaMsrPtr& msr_ptr, bool ignoreMsr) { CDnaGpsPoint pntTmp; CDnaCovariance covTmp; pntTmp.SetReferenceFrame(msr_ptr->GetReferenceFrame()); pntTmp.SetEpoch(msr_ptr->GetEpoch()); // Measurement type string tmp; try { tmp = trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type)); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRGPSPoints(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } msr_ptr->SetType(tmp); pntTmp.SetType(tmp); pntTmp.SetIgnore(ignoreMsr); covTmp.SetType(tmp); covTmp.SetIgnore(ignoreMsr); // So no need to read database ID if (!projectSettings_.i.simulate_measurements) { // Capture msr_id and cluster_id (for database referencing) m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseDNAMSRGPSPoints", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); pntTmp.SetClusterID(msr_ptr->GetClusterID()); covTmp.SetClusterID(msr_ptr->GetClusterID()); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetFirst(msr_ptr->GetFirst()); try { // Measurement type (i.e. LLH or XYZ) tmp = trimstr(sBuf.substr(dml_.msr_targ1, dmw_.msr_targ1)); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRGPSPoints(): Could not extract Y cluster coordinate type from the record: ", sBuf, dml_.msr_targ1); } try { if (tmp.empty()) msr_ptr->SetCoordType(XYZ_type); else msr_ptr->SetCoordType(tmp); pntTmp.SetCoordType(msr_ptr->GetCoordType()); } catch (runtime_error& e) { SignalExceptionParseDNA("ParseDNAMSRGPSPoints(): " + string(e.what()), "", dml_.msr_targ1); } // Number of points UINT32 pntCount(1); msr_ptr->SetTotal(ParseMsrCountValue(sBuf, pntCount, "ParseDNAMSRGPSPoints")); msr_ptr->SetRecordedTotal(pntCount); pntTmp.SetRecordedTotal(pntCount); msr_ptr->GetPoints_ptr()->reserve(pntCount); g_parsemsr_tally.Y += pntCount * 3; // V-scale msr_ptr->SetVscale(ParseScaleVValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetVscale(msr_ptr->GetVscale()); // P-scale msr_ptr->SetPscale(ParseScalePValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetPscale(msr_ptr->GetPscale()); // L-scale supplied? msr_ptr->SetLscale(ParseScaleLValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetLscale(msr_ptr->GetLscale()); // H-scale supplied? msr_ptr->SetHscale(ParseScaleHValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetHscale(msr_ptr->GetHscale()); // Process for setting reference frame is: // 1. Set the default reference frame in ParseDNAMSR when msr_ptr is initialised // 2. Initialise bslTmp using msr_ptr // 3. When a reference frame element is found here, change the reference frame // using checks on override // same as: // - DnaXmlFormat_pskel::_start_element_impl when DnaMeasurement is reached // - DnaMeasurement_pimpl::ReferenceFrame when ReferenceFrame tag is found // - Clusterpoint_pimpl::pre() if (projectSettings_.i.override_input_rfame) { // Set the cluster frame msr_ptr->SetReferenceFrame(projectSettings_.i.reference_frame); // Set the point frame pntTmp.SetReferenceFrame(projectSettings_.i.reference_frame); pntTmp.SetEpoch(msr_ptr->GetEpoch()); } else //if (!projectSettings_.i.override_input_rfame) { try { // Get the reference frame from the file tmp = ParseRefFrameValue(sBuf, "ParseDNAMSRGPSPoints"); if (!tmp.empty()) { // Set the cluster frame msr_ptr->SetReferenceFrame(tmp); // Set the point frame pntTmp.SetReferenceFrame(tmp); } } catch (runtime_error& e) { stringstream ss; ss << "ParseDNAMSRGPSPoints(): Error parsing reference frame: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), "", dml_.msr_gps_reframe); } try { // Get the epoch from the file tmp = ParseEpochValue(sBuf, "ParseDNAMSRGPSPoints"); if (!tmp.empty()) { // Set the cluster epoch msr_ptr->SetEpoch(tmp); // Set the point epoch pntTmp.SetEpoch(tmp); } } catch (runtime_error& e) { stringstream ss; ss << "ParseDNAMSRGPSPoints(): Error parsing epoch: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), "", dml_.msr_gps_epoch); } } bool first_run(true); UINT32 cov, covCount(pntCount - 1); for (UINT32 b(0); b<pntCount; ++b, --covCount) { if (!first_run) { m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRGPSPoints")); pntTmp.SetFirst(msr_ptr->GetFirst()); } first_run = false; if (!projectSettings_.i.simulate_measurements) { m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Capture msr_id and cluster_id (for database referencing), then set // database id info ParseDatabaseIds(sBuf, "ParseDNAMSRGPSPoints", msr_ptr->GetTypeC()); pntTmp.SetDatabaseMap(m_msr_db_map, m_databaseIdSet); pntTmp.SetX(ParseGPSMsrValue(sBuf, "X", "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaXX(ParseGPSVarValue(sBuf, "X", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSPoints")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); pntTmp.SetY(ParseGPSMsrValue(sBuf, "Y", "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaXY(ParseGPSVarValue(sBuf, "Y", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaYY(ParseGPSVarValue(sBuf, "Y", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRGPSPoints")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); pntTmp.SetZ(ParseGPSMsrValue(sBuf, "Z", "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaXZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaYZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRGPSPoints")); pntTmp.SetSigmaZZ(ParseGPSVarValue(sBuf, "Z", dml_.msr_gps_vcv_3, dmw_.msr_gps_vcv_3, "ParseDNAMSRGPSPoints")); } pntTmp.ResizeGpsCovariancesCount(); pntTmp.ReserveGpsCovariancesCount(covCount); for (cov=0; cov<covCount; ++cov) { if (!projectSettings_.i.simulate_measurements) ParseDNAMSRCovariance(covTmp); pntTmp.AddPointCovariance(&covTmp); } msr_ptr->AddGpsPoint(((CDnaGpsPoint*)&pntTmp)); } } void dna_import::ParseDNAMSRCovariance(CDnaCovariance& cov) { string sBuf; m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // m11, m12, m13 cov.SetM11(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRCovariance")); cov.SetM12(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRCovariance")); cov.SetM13(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_3, dmw_.msr_gps_vcv_3, "ParseDNAMSRCovariance")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // m21, m22, m23 cov.SetM21(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRCovariance")); cov.SetM22(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRCovariance")); cov.SetM23(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_3, dmw_.msr_gps_vcv_3, "ParseDNAMSRCovariance")); m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // m31, m32, m33 cov.SetM31(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_1, dmw_.msr_gps_vcv_1, "ParseDNAMSRCovariance")); cov.SetM32(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_2, dmw_.msr_gps_vcv_2, "ParseDNAMSRCovariance")); cov.SetM33(ParseGPSVarValue(sBuf, "co", dml_.msr_gps_vcv_3, dmw_.msr_gps_vcv_3, "ParseDNAMSRCovariance")); } void dna_import::ParseDatabaseIds(const string& sBuf, const string& calling_function, const char msrType) { m_databaseIdSet = false; // No msr id? if (sBuf.length() <= dml_.msr_id_msr) return; // all measurement types: capture msr id if (ParseDatabaseMsrId(sBuf, calling_function).empty()) return; m_databaseIdSet = true; // Initialise bms index. This member will be set // in SerialiseBms() //m_msr_db_map.bms_index = 0; // Initialise cluster id. ParseDatabaseClusterId will // update this member if a value is found m_msr_db_map.cluster_id = 0; switch (msrType) { // Cluster types: capture cluster ID case 'D': case 'G': case 'X': case 'Y': if (sBuf.length() > dml_.msr_id_cluster) if (ParseDatabaseClusterId(sBuf, calling_function).empty()) return; } } string dna_import::ParseDatabaseClusterId(const string& sBuf, const string& calling_function) { string parsed_value; // Cluster ID try { parsed_value = trimstr(sBuf.substr(dml_.msr_id_cluster)); if (!parsed_value.empty()) m_msr_db_map.cluster_id = LongFromString<UINT32>(parsed_value); } catch (runtime_error& e) { stringstream ss; ss << calling_function << "(): Could not extract database cluster id from the record: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), sBuf, dml_.msr_id_msr); } return parsed_value; } string dna_import::ParseDatabaseMsrId(const string& sBuf, const string& calling_function) { string parsed_value; // Measurement ID try { parsed_value = trimstr(sBuf.substr(dml_.msr_id_msr, dmw_.msr_id_msr)); if (!parsed_value.empty()) m_msr_db_map.msr_id = LongFromString<UINT32>(parsed_value); } catch (runtime_error& e) { stringstream ss; ss << calling_function << "(): Could not extract database msr id from the record: " << endl << " " << e.what(); SignalExceptionParseDNA(ss.str(), sBuf, dml_.msr_id_msr); } return parsed_value; } string dna_import::ParseAngularValue(const string& sBuf, const string& calling_function) { string parsed_value, tmp; double d; // degrees value try { parsed_value = trimstr(sBuf.substr(dml_.msr_ang_d, dmw_.msr_ang_d)) + "."; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract degrees value from the record: ", sBuf, dml_.msr_ang_d); } // minutes value try { tmp = trimstr(sBuf.substr(dml_.msr_ang_m, dmw_.msr_ang_m)); d = DoubleFromString<double>(tmp); if (d < 10 && tmp.at(0) != '0') parsed_value.append("0"); parsed_value.append(tmp); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract minutes value from the record: ", sBuf, dml_.msr_ang_m); } // seconds value size_t pos = 0; try { tmp = trimstr(sBuf.substr(dml_.msr_ang_s, dmw_.msr_ang_s)); d = DoubleFromString<double>(tmp); if (d < 10 && tmp.at(0) != '0') parsed_value.append("0"); if ((pos = tmp.find(".", pos)) != string::npos) parsed_value.append(tmp.substr(0, pos) + tmp.substr(pos+1)); else parsed_value.append(tmp); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract seconds value from the record: ", sBuf, dml_.msr_ang_s); } return parsed_value; } string dna_import::ParseLinearValue(const string& sBuf, const string& msrName, const string& calling_function) { try { return trimstr(sBuf.substr(dml_.msr_linear, dmw_.msr_linear)); // coordinate value } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract the " + msrName + " value from the record: ", sBuf, dml_.msr_linear); } return ""; } string dna_import::ParseInstrumentValue(const string& sBuf, const string& calling_function) { try { // Capture string from the designated columns; throws on failure string stn = trimstr(sBuf.substr(dml_.msr_inst, dmw_.msr_inst)); // instrument station // No value supplied? if (stn.empty()) SignalExceptionParseDNA(calling_function + "(): The following record doesn't contain an instrument station name: ", sBuf, dml_.msr_inst); return stn; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract first station name from the record: ", sBuf, dml_.msr_inst); } return ""; } string dna_import::ParseTargetValue(const string& sBuf, const string& calling_function) { try { // Capture string from the designated columns; throws on failure string stn = trimstr(sBuf.substr(dml_.msr_targ1, dmw_.msr_targ1)); // first target station // No value supplied? if (stn.empty()) SignalExceptionParseDNA(calling_function + "(): The following record doesn't contain a target station name: ", sBuf, dml_.msr_targ1); return stn; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract second station name from the record: ", sBuf, dml_.msr_targ1); } return ""; } string dna_import::ParseTarget2Value(const string& sBuf, const string& calling_function) { try { // Capture string from the designated columns; throws on failure string stn = trimstr(sBuf.substr(dml_.msr_targ2, dmw_.msr_targ2)); // second target station // No value supplied? if (stn.empty()) SignalExceptionParseDNA(calling_function + "(): The following record doesn't contain a second target station name: ", sBuf, dml_.msr_targ2); return stn; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract third station name from the record: ", sBuf, dml_.msr_targ2); } return ""; } string dna_import::ParseStdDevValue(const string& sBuf, const string& calling_function) { string tmp; try { tmp = trimstr(sBuf.substr(dml_.msr_stddev, dmw_.msr_stddev)); // standard deviation } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract standard deviation from the record: ", sBuf, dml_.msr_stddev); } if (DoubleFromString<double>(tmp) < PRECISION_1E25) SignalExceptionParseDNA(calling_function + "(): Invalid standard deviation (" + tmp + "). Values cannot be zero or negative: ", sBuf, dml_.msr_stddev); return tmp; } string dna_import::ParseInstHeightValue(const string& sBuf, const string& calling_function) { try { if (sBuf.length() > dml_.msr_targ_ht) return trimstr(sBuf.substr(dml_.msr_inst_ht, dmw_.msr_inst_ht)); // instrument height else return trimstr(sBuf.substr(dml_.msr_inst_ht)); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract instrument height from the record: ", sBuf, dml_.msr_inst_ht); } return ""; } string dna_import::ParseTargHeightValue(const string& sBuf, const string& calling_function) { try { if (sBuf.length() > static_cast<string::size_type>(dml_.msr_targ_ht + 1 + dmw_.msr_targ_ht)) return trimstr(sBuf.substr(dml_.msr_targ_ht, dmw_.msr_targ_ht)); // target height else return trimstr(sBuf.substr(dml_.msr_targ_ht)); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract target height from the record: ", sBuf, dml_.msr_targ_ht); } return ""; } string dna_import::ParseMsrCountValue(const string& sBuf, UINT32& msrCount, const string& calling_function) { try { string count(trimstr(sBuf.substr(dml_.msr_targ2, dmw_.msr_targ2))); // number of measurements if (count.empty()) SignalExceptionParseDNA(calling_function + "(): Could not extract number of measurements from the record: ", sBuf, dml_.msr_targ2); msrCount = LongFromString<UINT32>(count); return count; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract number of measurements from the record: ", sBuf, dml_.msr_targ2); } return ""; } string dna_import::ParseScaleVValue(const string& sBuf, const string& calling_function) { if (sBuf.length() <= dml_.msr_gps_vscale) return "1"; string scalar; try { if (sBuf.length() > dml_.msr_gps_pscale) scalar = trimstr(sBuf.substr(dml_.msr_gps_vscale, dmw_.msr_gps_vscale)); // v-scale else scalar = trimstr(sBuf.substr(dml_.msr_gps_vscale)); if (scalar.empty()) return "1"; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract v-scale from the record: ", sBuf, dml_.msr_gps_vscale); } return scalar; } string dna_import::ParseScalePValue(const string& sBuf, const string& calling_function) { if (sBuf.length() <= dml_.msr_gps_pscale) return "1"; string scalar; try { if (sBuf.length() > dml_.msr_gps_lscale) scalar = trimstr(sBuf.substr(dml_.msr_gps_pscale, dmw_.msr_gps_pscale)); // p-scale else scalar = trimstr(sBuf.substr(dml_.msr_gps_pscale)); if (scalar.empty()) return "1"; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract p-scale from the record: ", sBuf, dml_.msr_gps_pscale); } return scalar; } string dna_import::ParseScaleLValue(const string& sBuf, const string& calling_function) { if (sBuf.length() <= dml_.msr_gps_lscale) return "1"; string scalar; try { if (sBuf.length() > dml_.msr_gps_hscale) scalar = trimstr(sBuf.substr(dml_.msr_gps_lscale, dmw_.msr_gps_lscale)); // l-scale else scalar = trimstr(sBuf.substr(dml_.msr_gps_lscale)); if (scalar.empty()) return "1"; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract l-scale from the record: ", sBuf, dml_.msr_gps_lscale); } return scalar; } string dna_import::ParseScaleHValue(const string& sBuf, const string& calling_function) { if (sBuf.length() <= dml_.msr_gps_hscale) return "1"; string scalar; try { if (sBuf.length() > (dml_.msr_gps_reframe)) scalar = trimstr(sBuf.substr(dml_.msr_gps_hscale, dmw_.msr_gps_hscale)); // h-scale else scalar = trimstr(sBuf.substr(dml_.msr_gps_hscale)); if (scalar.empty()) return "1"; } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract h-scale from the record: ", sBuf, dml_.msr_gps_hscale); } return scalar; } string dna_import::ParseRefFrameValue(const string& sBuf, const string& calling_function) { // Override the reference frame with the user specified frame? if (projectSettings_.i.override_input_rfame) return projectSettings_.i.reference_frame; if (sBuf.length() <= dml_.msr_gps_reframe) return ""; string frame; try { if (sBuf.length() > (dml_.msr_gps_epoch)) frame = trimstr(sBuf.substr(dml_.msr_gps_reframe, dmw_.msr_gps_reframe)); // reference frame else frame = trimstr(sBuf.substr(dml_.msr_gps_reframe)); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract reference frame from the record: ", sBuf, dml_.msr_gps_reframe); } return frame; } string dna_import::ParseEpochValue(const string& sBuf, const string& calling_function) { if (sBuf.length() <= dml_.msr_gps_epoch) return ""; string epoch; try { if (sBuf.length() > static_cast<string::size_type>(dml_.msr_gps_epoch + dmw_.msr_gps_epoch)) epoch = trimstr(sBuf.substr(dml_.msr_gps_epoch, dmw_.msr_gps_epoch)); // epoch else epoch = trimstr(sBuf.substr(dml_.msr_gps_epoch)); } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract epoch from the record: ", sBuf, dml_.msr_gps_epoch); } return epoch; } string dna_import::ParseGPSMsrValue(const string& sBuf, const string& element, const string& calling_function) { try { return trimstr(sBuf.substr(dml_.msr_gps, dmw_.msr_gps)); // value } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract GNSS " + element + " measurement from the record: ", sBuf, dml_.msr_gps); } return ""; } string dna_import::ParseGPSVarValue(const string& sBuf, const string& element, const UINT32 location, const UINT32 width, const string& calling_function) { try { return trimstr(sBuf.substr(location, width)); // variance } catch (...) { SignalExceptionParseDNA(calling_function + "(): Could not extract GNSS " + element + " variance from the record: ", sBuf, location); } return ""; } void dna_import::ParseDNAMSRAngular(const string& sBuf, dnaMsrPtr& msr_ptr) { // Measurement type try { msr_ptr->SetType(trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type))); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRAngular(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRAngular")); // Target station if (msr_ptr->GetMsrStnCount() >= TWO_STATION) msr_ptr->SetTarget(ParseTargetValue(sBuf, "ParseDNAMSRAngular")); // Second target station if (msr_ptr->GetMsrStnCount() == THREE_STATION) msr_ptr->SetTarget2(ParseTarget2Value(sBuf, "ParseDNAMSRAngular")); // If import is being used to simulate measurements, return as the // expected input is: // Measurement // From station // To station // So no need to read any further if (projectSettings_.i.simulate_measurements) return; // Value msr_ptr->SetValue(ParseAngularValue(sBuf, "ParseDNAMSRAngular")); // Standard deviation msr_ptr->SetStdDev(ParseStdDevValue(sBuf, "ParseDNAMSRAngular")); // Capture msr_id and cluster_id (for database referencing), then set // database id info m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseDNAMSRAngular", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); // instrument and target heights only make sense for // slope distances, vertical angles and zenith distances switch (msr_ptr->GetTypeC()) { case 'V': case 'Z': break; default: // don't need instrument height for all other measurement types return; } // Instrument and target heights if (sBuf.length() <= dml_.msr_inst_ht) { msr_ptr->SetInstrumentHeight("0.0"); msr_ptr->SetTargetHeight("0.0"); return; } msr_ptr->SetInstrumentHeight(ParseInstHeightValue(sBuf, "ParseDNAMSRAngular")); // Target height if (sBuf.length() <= dml_.msr_targ_ht) { msr_ptr->SetTargetHeight("0.0"); return; } msr_ptr->SetTargetHeight(ParseTargHeightValue(sBuf, "ParseDNAMSRAngular")); } void dna_import::ParseDNAMSRDirections(string& sBuf, dnaMsrPtr& msr_ptr, bool ignoreMsr) { // Measurement type try { msr_ptr->SetType(trimstr(sBuf.substr(dml_.msr_type, dmw_.msr_type))); } catch (...) { SignalExceptionParseDNA("ParseDNAMSRDirections(): Could not extract measurement type from the record: ", sBuf, dml_.msr_type); } // Instrument station msr_ptr->SetFirst(ParseInstrumentValue(sBuf, "ParseDNAMSRDirections")); // Target station if (msr_ptr->GetMsrStnCount() >= TWO_STATION) msr_ptr->SetTarget(ParseTargetValue(sBuf, "ParseDNAMSRDirections")); // Number of directions UINT32 dirnCount; msr_ptr->SetTotal(ParseMsrCountValue(sBuf, dirnCount, "ParseDNAMSRDirections")); msr_ptr->GetDirections_ptr()->reserve(dirnCount); CDnaDirection dirnTmp; dirnTmp.SetRecordedTotal(0); // If import is being used to simulate measurements, return as the // expected input is: // Measurement // From station // To station // So no need to read direction values or database ID if (!projectSettings_.i.simulate_measurements) { // Value msr_ptr->SetValue(ParseAngularValue(sBuf, "ParseDNAMSRDirections")); // Standard deviation msr_ptr->SetStdDev(ParseStdDevValue(sBuf, "ParseDNAMSRDirections")); // Capture msr_id and cluster_id (for database referencing) m_databaseIdSet = false; ParseDatabaseIds(sBuf, "ParseDNAMSRDirections", msr_ptr->GetTypeC()); msr_ptr->SetDatabaseMap(m_msr_db_map, m_databaseIdSet); dirnTmp.SetClusterID(msr_ptr->GetClusterID()); } for (UINT32 dirn=0; dirn<dirnCount; ++dirn) { dirnTmp.SetFirst(msr_ptr->GetFirst()); dirnTmp.SetIgnore(ignoreMsr); g_parsemsr_tally.D++; m_lineNo++; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); getline((*ifsInputFILE_), sBuf); // release file pointer mutex import_file_mutex.unlock(); // Second target station dirnTmp.SetTarget(ParseTarget2Value(sBuf, "ParseDNAMSRDirections")); // Again, no need to read direction values if (!projectSettings_.i.simulate_measurements) { // Value dirnTmp.SetValue(ParseAngularValue(sBuf, "ParseDNAMSRDirections")); // Standard deviation dirnTmp.SetStdDev(ParseStdDevValue(sBuf, "ParseDNAMSRDirections")); // Capture msr_id and cluster_id (for database referencing) ParseDatabaseIds(sBuf, "ParseDNAMSRDirections", msr_ptr->GetTypeC()); dirnTmp.SetDatabaseMap(m_msr_db_map, m_databaseIdSet); } // add the direction msr_ptr->AddDirection(((CDnaMeasurement*)&dirnTmp)); } } void dna_import::RemoveIgnoredMeasurements(vdnaMsrPtr* vMeasurements, MsrTally* parsemsrTally) { // Remove ignored measurements erase_if(vMeasurements, CompareIgnoredMsr<CDnaMeasurement>()); // Rebuild measurement tally parsemsrTally->CreateTally(*vMeasurements); } void dna_import::IncludeMeasurementTypes(const string& includeMsrs, vdnaMsrPtr* vMeasurements, MsrTally* parsemsrTally) { _it_vdnamsrptr _it_msr; string msrTypes = includeMsrs; // convert to upper case str_toupper<int>(msrTypes); CompareNonMeasType<CDnaMeasurement> meastypeCompareFunc(msrTypes); erase_if(vMeasurements, meastypeCompareFunc); MsrTally msrtallyTmp; for (UINT16 i=0; i<msrTypes.length(); ++i) { switch ((msrTypes.c_str())[i]) { case 'A': // Horizontal angle msrtallyTmp.A = parsemsrTally->A; break; case 'B': // Geodetic azimuth msrtallyTmp.B = parsemsrTally->B; break; case 'C': // Chord dist msrtallyTmp.C = parsemsrTally->C; break; case 'D': // Direction set msrtallyTmp.D = parsemsrTally->D; break; case 'E': // Ellipsoid arc msrtallyTmp.E = parsemsrTally->E; break; case 'G': // GPS Baseline msrtallyTmp.G = parsemsrTally->G; break; case 'H': // Orthometric height msrtallyTmp.H = parsemsrTally->H; break; case 'I': // Astronomic latitude msrtallyTmp.I = parsemsrTally->I; break; case 'J': // Astronomic longitude msrtallyTmp.J = parsemsrTally->J; break; case 'K': // Astronomic azimuth msrtallyTmp.K = parsemsrTally->K; break; case 'L': // Level difference msrtallyTmp.L = parsemsrTally->L; break; case 'M': // MSL arc msrtallyTmp.M = parsemsrTally->M; break; case 'P': // Geodetic latitude msrtallyTmp.P = parsemsrTally->P; break; case 'Q': // Geodetic longitude msrtallyTmp.Q = parsemsrTally->Q; break; case 'R': // Ellipsoidal height msrtallyTmp.R = parsemsrTally->R; break; case 'S': // Slope distance msrtallyTmp.S = parsemsrTally->S; break; case 'V': // Zenith angle msrtallyTmp.V = parsemsrTally->V; break; case 'X': // GPS Baseline cluster msrtallyTmp.X = parsemsrTally->X; break; case 'Y': // GPS point cluster msrtallyTmp.Y = parsemsrTally->Y; break; case 'Z': // Vertical angle msrtallyTmp.Z = parsemsrTally->Z; break; } } *parsemsrTally = msrtallyTmp; } void dna_import::ExcludeMeasurementTypes(const string& excludeMsrs, vdnaMsrPtr* vMeasurements, MsrTally* parsemsrTally) { _it_vdnamsrptr _it_msr; string msrTypes = excludeMsrs; // convert to upper case str_toupper<int>(msrTypes); CompareMeasType<CDnaMeasurement> meastypeCompareFunc(msrTypes); erase_if(vMeasurements, meastypeCompareFunc); for (UINT16 i=0; i<msrTypes.length(); ++i) { switch ((msrTypes.c_str())[i]) { case 'A': // Horizontal angle parsemsrTally->A = 0; break; case 'B': // Geodetic azimuth parsemsrTally->B = 0; break; case 'C': // Chord dist parsemsrTally->C = 0; break; case 'D': // Direction set parsemsrTally->D = 0; break; case 'E': // Ellipsoid arc parsemsrTally->E = 0; break; case 'G': // GPS Baseline parsemsrTally->G = 0; break; case 'H': // Orthometric height parsemsrTally->H = 0; break; case 'I': // Astronomic latitude parsemsrTally->I = 0; break; case 'J': // Astronomic longitude parsemsrTally->J = 0; break; case 'K': // Astronomic azimuth parsemsrTally->K = 0; break; case 'L': // Level difference parsemsrTally->L = 0; break; case 'M': // MSL arc parsemsrTally->M = 0; break; case 'P': // Geodetic latitude parsemsrTally->P = 0; break; case 'Q': // Geodetic longitude parsemsrTally->Q = 0; break; case 'R': // Ellipsoidal height parsemsrTally->R = 0; break; case 'S': // Slope distance parsemsrTally->S = 0; break; case 'V': // Zenith angle parsemsrTally->V = 0; break; case 'X': // GPS Baseline cluster parsemsrTally->X = 0; break; case 'Y': // GPS point cluster parsemsrTally->Y = 0; break; case 'Z': // Vertical angle parsemsrTally->Z = 0; break; } } } void dna_import::ExcludeAllOutsideBoundingBox(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, StnTally* parsestnTally, MsrTally* parsemsrTally, pvstring vExcludedStns, const project_settings& p, bool& splitXmsrs, bool& splitYmsrs) { splitXmsrs = splitYmsrs = false; // backup station vector vdnaStnPtr bvStation = *vStations; // TestNotEqualStationName requires vStations to be sorted (for binary_search) sort(vStations->begin(), vStations->end()); // Remove all stations outside the bounding box // vExcludedStns will contain the names of all the stations (if any) that were outside the bounding box. // This list will be used to strip the corresponding measurements. vExcludedStns->clear(); FindStnsWithinBoundingBox<double> boundingBoxFunc(bbox_upperLat_, bbox_upperLon_, bbox_lowerLat_, bbox_lowerLon_, vExcludedStns); erase_if(vStations, boundingBoxFunc); // create vstring of used stations vstring vIncludedStns; vIncludedStns.reserve(vStations->size()); _it_vdnastnptr _it_stn(vStations->begin()); for_each(vStations->begin(), vStations->end(), [&vIncludedStns] (dnaStnPtr& s) { vIncludedStns.push_back(s.get()->GetName()); }); // FindMsrsConnectedToStns requires vExcludedStns to be sorted (for binary_search) sort(vExcludedStns->begin(), vExcludedStns->end()); // OK, now measurements... if (p.i.include_transcending_msrs == 1) ExtractAssociatedMsrsConnectedToStns(vMeasurements, parsemsrTally, &vIncludedStns, vExcludedStns, p, splitXmsrs, splitYmsrs); else ExtractAssociatedMsrsBoundingBox(vMeasurements, parsemsrTally, &vIncludedStns, vExcludedStns, p, splitXmsrs, splitYmsrs); strip_duplicates(vIncludedStns); // restore station vector, and erase stations not in vIncludedStns *vStations = bvStation; vExcludedStns->clear(); TestNotEqualStationName<dnaStnPtr, string> selectStnFunc(&vIncludedStns, vExcludedStns); erase_if(vStations, selectStnFunc); // Rebuild station tally parsestnTally->CreateTally(*vStations); } void dna_import::ExtractStnsAndAssociatedMsrs(const string& stnListInclude, const string& stnListExclude, vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, StnTally* parsestnTally, MsrTally* parsemsrTally, pvstring vExcludedStns, const project_settings& p, bool& splitXmsrs, bool& splitYmsrs) { splitXmsrs = splitYmsrs = false; // backup station vector vdnaStnPtr bvStations = *vStations; const string *stnListIn, *stnListEx; vstring vIncludedStns; pvstring pvStnsIn, pvStnsEx; // Has the user provided a list of stations to include? if (!stnListInclude.empty()) { pvStnsIn = &vIncludedStns; pvStnsEx = vExcludedStns; stnListIn = &stnListInclude; stnListEx = &stnListExclude; } // Has the user provided a list of stations to exclude? else if (!stnListExclude.empty()) { pvStnsIn = vExcludedStns; pvStnsEx = &vIncludedStns; stnListIn = &stnListExclude; stnListEx = &stnListInclude; } else { // nothing to do return; } // Form vector of included stations from user-input string BuildExtractStationsList(*stnListIn, pvStnsIn); // TestNotEqualStationName requires stations to be sorted (for binary_search) strip_duplicates(pvStnsIn); // Strip duplicates and sort sort(pvStnsIn->begin(), pvStnsIn->end()); pvStnsEx->clear(); // Remove all stations not in vIncludedStns // vExcludedStns will contain the names of all the stations (if any) that were outside the bounding box. // This list will be used to strip the corresponding measurements. if (!stnListInclude.empty()) { TestNotEqualStationName<dnaStnPtr, string> selectStnFunc(pvStnsIn, pvStnsEx); erase_if(vStations, selectStnFunc); } else { TestEqualStationName<dnaStnPtr, string> selectStnFunc(pvStnsIn, pvStnsEx); erase_if(vStations, selectStnFunc); pvStnsIn = &vIncludedStns; pvStnsEx = vExcludedStns; sort(pvStnsIn->begin(), pvStnsIn->end()); } // FindMsrsConnectedToStns requires vExcludedStns to be sorted (for binary_search) sort(pvStnsEx->begin(), pvStnsEx->end()); // OK, get all measurements connected associated with vIncludedStns, splitting clusters as necessary if (!stnListInclude.empty()) ExtractAssociatedMsrsConnectedToStns(vMeasurements, parsemsrTally, pvStnsIn, pvStnsEx, p, splitXmsrs, splitYmsrs); else ExtractAssociatedMsrsBoundingBox(vMeasurements, parsemsrTally, pvStnsIn, pvStnsEx, p, splitXmsrs, splitYmsrs); strip_duplicates(pvStnsIn); // restore station vector, and erase stations not in pvStnsIn // This repeat step is required since pvStnsIn may contain more // or less depending on how many stations the function // ExtractAssociatedMsrsConnectedToStns retrieves *vStations = bvStations; pvStnsEx->clear(); TestNotEqualStationName<dnaStnPtr, string> selectStnFunc(pvStnsIn, pvStnsEx); erase_if(vStations, selectStnFunc); // Rebuild station tally parsestnTally->CreateTally(*vStations); } void dna_import::SplitClusterMsrs(vdnaMsrPtr& msrsConnectedToStns, pvstring pvIncludedStns, pvstring pvExcludedStns, vdnaMsrPtr* vMeasurements, bool& splitXmsrs, bool& splitYmsrs) { // Backup (all) measurements straddling selection vdnaMsrPtr XYmsrsConnectedToStns(msrsConnectedToStns); // Get non-XY measurements CompareMeasType<CDnaMeasurement> meastypeCompareFunc_XY("XY"); erase_if(msrsConnectedToStns, meastypeCompareFunc_XY); // Get XY measurements CompareNonMeasType<CDnaMeasurement> meastypeCompareFunc_nonXY("XY"); erase_if(XYmsrsConnectedToStns, meastypeCompareFunc_nonXY); // Split the XY measurements, keeping only those measurements directly // connected to pvIncludedStns SplitClusterMsrsConnectedToStns(&XYmsrsConnectedToStns, pvIncludedStns, pvExcludedStns, splitXmsrs, splitYmsrs); // Add the split XY measurements vMeasurements->insert(vMeasurements->end(), XYmsrsConnectedToStns.begin(), XYmsrsConnectedToStns.end()); // Add the non-XY measurements vMeasurements->insert(vMeasurements->end(), msrsConnectedToStns.begin(), msrsConnectedToStns.end()); } void dna_import::SplitClusterMsrsConnectedToStns(vdnaMsrPtr* vClusterMsrs, pvstring pvIncludedStns, pvstring pvExcludedStns, bool& splitXmsrs, bool& splitYmsrs) { _it_vdnamsrptr _it_msr; vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsPoint>* vgpsPnts; vector<CDnaCovariance>* vgpsCovs; vector<CDnaGpsBaseline>::iterator _it_gps_bsl; vector<CDnaGpsPoint>::iterator _it_gps_pnt; vector<CDnaCovariance>::iterator _it_gps_cov; UINT32 msr(0), index(0), subindex(0), keepCount; vUINT32 vIndices; for (_it_msr=vClusterMsrs->begin(); _it_msr!=vClusterMsrs->end(); ++_it_msr, ++msr) { switch (_it_msr->get()->GetTypeC()) { case 'X': vgpsBsls = _it_msr->get()->GetBaselines_ptr(); vIndices.clear(); index = 0; // Step 1. Set ignore flag for all baselines to true for_each(vgpsBsls->begin(), vgpsBsls->end(), [this](CDnaGpsBaseline& bsl) { bsl.SetIgnore(true); }); // Step 2. Set the baselines connected to the included stations to false for_each(vgpsBsls->begin(), vgpsBsls->end(), [pvIncludedStns](CDnaGpsBaseline& bsl) { if (binary_search(pvIncludedStns->begin(), pvIncludedStns->end(), bsl.GetFirst())) bsl.SetIgnore(false); else if (binary_search(pvIncludedStns->begin(), pvIncludedStns->end(), bsl.GetTarget())) bsl.SetIgnore(false); }); // Step 3. Create a vector of measurement indices which are to be removed for_each(vgpsBsls->begin(), vgpsBsls->end(), [&vIndices, &index](CDnaGpsBaseline& bsl) { if (bsl.GetIgnore()) vIndices.push_back(index); index++; }); // Any baselines to remove? if (vIndices.empty()) continue; splitXmsrs = true; // Step 4. Set the ignore flag for the unwanted covariances using the vector of // indices created above index = 0; for (_it_gps_bsl=vgpsBsls->begin(); _it_gps_bsl!=vgpsBsls->end(); ++_it_gps_bsl, ++index) { // is this cluster measurement ignored? If so, continue as the entire record will be // removed later if (binary_search(vIndices.begin(), vIndices.end(), index)) continue; subindex = index+1; vgpsCovs = _it_gps_bsl->GetCovariances_ptr(); for (_it_gps_cov=vgpsCovs->begin(); _it_gps_cov!=vgpsCovs->end(); ++_it_gps_cov, ++subindex) if (binary_search(vIndices.begin(), vIndices.end(), subindex)) _it_gps_cov->SetIgnore(true); } // Step 5. Remove the 'ignored' cluster measurements, and reset the measurement count erase_if(vgpsBsls, CompareIgnoreedClusterMeas<CDnaGpsBaseline>()); // Step 6. Set the total count for the cluster and for each clustered measurement keepCount = static_cast<UINT32>(vgpsBsls->size()); _it_msr->get()->SetTotal(keepCount); if (vgpsBsls->empty()) continue; for_each(vgpsBsls->begin(), vgpsBsls->end(), [&keepCount](CDnaGpsBaseline& bsl){ bsl.SetTotal(keepCount); }); // Step 7. Remove the 'ignored' cluster covariances, and reset the measurement count for (_it_gps_bsl=vgpsBsls->begin(); _it_gps_bsl!=vgpsBsls->end(); ++_it_gps_bsl, ++index) { vgpsCovs = _it_gps_bsl->GetCovariances_ptr(); erase_if(vgpsCovs, CompareIgnoreedClusterMeas<CDnaCovariance>()); } break; case 'Y': vgpsPnts = _it_msr->get()->GetPoints_ptr(); vIndices.clear(); index = 0; // Step 1. Create a vector of measurement indices which are to be removed, and set // the 'ignore' flag for the unwanted GPS point clustered measurements for_each(vgpsPnts->begin(), vgpsPnts->end(), [&vIndices, &index, pvExcludedStns](CDnaGpsPoint& pnt) { if (binary_search(pvExcludedStns->begin(), pvExcludedStns->end(), pnt.GetFirst())) { pnt.SetIgnore(true); vIndices.push_back(index); } index++; }); // Any points to remove? if (vIndices.empty()) continue; splitYmsrs = true; // Step 2. Set the ignore flag for the unwanted covariances using the vector of // indices created above index = 0; for (_it_gps_pnt=vgpsPnts->begin(); _it_gps_pnt!=vgpsPnts->end(); ++_it_gps_pnt, ++index) { // is this cluster measurement ignored? If so, continue as the entire record will be // removed later if (binary_search(vIndices.begin(), vIndices.end(), index)) continue; subindex = index+1; vgpsCovs = _it_gps_pnt->GetCovariances_ptr(); for (_it_gps_cov=vgpsCovs->begin(); _it_gps_cov!=vgpsCovs->end(); ++_it_gps_cov, ++subindex) if (binary_search(vIndices.begin(), vIndices.end(), subindex)) _it_gps_cov->SetIgnore(true); } // Step 3. Remove the 'ignored' cluster measurements, and reset the measurement count erase_if(vgpsPnts, CompareIgnoreedClusterMeas<CDnaGpsPoint>()); // Step 4. Set the total count for the cluster and for each clustered measurement keepCount = static_cast<UINT32>(vgpsPnts->size()); _it_msr->get()->SetTotal(keepCount); if (vgpsPnts->empty()) continue; for_each(vgpsPnts->begin(), vgpsPnts->end(), [&keepCount](CDnaGpsPoint& pnt){ pnt.SetTotal(keepCount); }); // Step 5. Remove the 'ignored' cluster covariances, and reset the measurement count for (_it_gps_pnt=vgpsPnts->begin(); _it_gps_pnt!=vgpsPnts->end(); ++_it_gps_pnt, ++index) { vgpsCovs = _it_gps_pnt->GetCovariances_ptr(); erase_if(vgpsCovs, CompareIgnoreedClusterMeas<CDnaCovariance>()); } break; } } // Step 6. Erase cluster with no measurements erase_if(vClusterMsrs, CompareEmptyClusterMeas<CDnaMeasurement>()); } void dna_import::ExtractAssociatedMsrsConnectedToStns(vdnaMsrPtr* vMeasurements, MsrTally* parsemsrTally, pvstring pvIncludedStns, pvstring pvExcludedStns, const project_settings& p, bool& splitXmsrs, bool& splitYmsrs) { // Create functor to pull measurements connected to used stations // FindMsrsConnectedToStns will find measurements that has any one station // in pvIncludedStns for first, second or third station FindMsrsConnectedToStns<pvstring> msrstoIncludedStnsFunc(pvIncludedStns); vdnaMsrPtr msrsConnectedToStns; // Copy all measurements conected to selected stations // This will pull all measurements tied directly or indirectly to stations in // pvIncludedStns. If a measurement tied to a used station is part of a // cluster, then the whole cluster will be pulled in copy_if(vMeasurements->begin(), vMeasurements->end(), back_inserter(msrsConnectedToStns), msrstoIncludedStnsFunc); // clear the original measurement list vMeasurements->clear(); // Split clusters? if (p.i.split_clusters == 1) // Split the GNSS clusters so that measurements not connected // to the included stations are removed SplitClusterMsrs(msrsConnectedToStns, pvIncludedStns, pvExcludedStns, vMeasurements, splitXmsrs, splitYmsrs); else // Add the measurements wholly connected to the included stations vMeasurements->insert(vMeasurements->end(), msrsConnectedToStns.begin(), msrsConnectedToStns.end()); // Get the additional stations introduced by connected measurements ExtractAssociatedStns(vMeasurements, pvIncludedStns); // Rebuild measurement tally parsemsrTally->CreateTally(*vMeasurements); } void dna_import::ExtractAssociatedMsrsBoundingBox(vdnaMsrPtr* vMeasurements, MsrTally* parsemsrTally, pvstring pvIncludedStns, pvstring pvExcludedStns, const project_settings& p, bool& splitXmsrs, bool& splitYmsrs) { if (p.i.split_clusters == 1) { // Create functor to pull measurements connected to used stations // FindMsrsConnectedToStns will find measurements that has any one station // in pvIncludedStns for first, second or third station FindMsrsConnectedToStns<pvstring> msrstoIncludedStnsFunc(pvIncludedStns); vdnaMsrPtr msrsConnectedToStns; // Copy all measurements conected to selected stations // This will pull all measurements tied directly or indirectly to stations in // pvIncludedStns. If a measurement tied to a used station is part of a // cluster, then the whole cluster will be pulled in copy_if(vMeasurements->begin(), vMeasurements->end(), back_inserter(msrsConnectedToStns), msrstoIncludedStnsFunc); // clear the original measurement list vMeasurements->clear(); // Split the GNSS clusters so that measurements not connected // to the included stations are removed SplitClusterMsrs(msrsConnectedToStns, pvIncludedStns, pvExcludedStns, vMeasurements, splitXmsrs, splitYmsrs); } else { // If a measurement is connected to a station that is outside the box or not on the // selected station list, then delete it FindMsrsConnectedToStns<pvstring> msrstoExcludedStnsFunc(pvExcludedStns); // Delete all measurements not wholly within the box erase_if(vMeasurements, msrstoExcludedStnsFunc); } // Get the reduced set of stations connected to the measurements ExtractAssociatedStns(vMeasurements, pvIncludedStns); // Rebuild measurement tally parsemsrTally->CreateTally(*vMeasurements); } void dna_import::ExtractAssociatedStns_GX(vector<CDnaGpsBaseline>* vGpsBaselines, pvstring pvUsedStns) { string station; vector<CDnaGpsBaseline>::iterator _it_msr(vGpsBaselines->begin()); _it_pair_vstring it_msr_stns; for (_it_msr=vGpsBaselines->begin(); _it_msr!=vGpsBaselines->end(); _it_msr++) { station = _it_msr->GetFirst(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } station = _it_msr->GetTarget(); it_msr_stns = equal_range(pvUsedStns->end(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } } } void dna_import::ExtractAssociatedStns_Y(vector<CDnaGpsPoint>* vGpsPoints, pvstring pvUsedStns) { string station; vector< CDnaGpsPoint >::iterator _it_msr(vGpsPoints->begin()); _it_pair_vstring it_msr_stns; for (_it_msr=vGpsPoints->begin(); _it_msr!=vGpsPoints->end(); _it_msr++) { station = _it_msr->GetFirst(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } } } void dna_import::ExtractAssociatedStns_D(vector<CDnaDirection>* vDirections, pvstring pvUsedStns) { string station; vector<CDnaDirection>::iterator _it_msr(vDirections->begin()); _it_pair_vstring it_msr_stns; for (_it_msr=vDirections->begin(); _it_msr!=vDirections->end(); _it_msr++) { station = _it_msr->GetFirst(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } station = _it_msr->GetTarget(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } } } void dna_import::ExtractAssociatedStns(vdnaMsrPtr* vMeasurements, pvstring pvUsedStns) { _it_vdnamsrptr _it_msr; vector<CDnaDirection>* vdirns; vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsPoint>* vgpsPnts; string station; _it_pair_vstring it_msr_stns; for (_it_msr=vMeasurements->begin(); _it_msr!=vMeasurements->end(); ++_it_msr) { // 1. Handle nested type measurements (D, G, X, Y) separately switch (_it_msr->get()->GetTypeC()) { case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vgpsBsls = _it_msr->get()->GetBaselines_ptr(); ExtractAssociatedStns_GX(vgpsBsls, pvUsedStns); continue; case 'Y': // GPS point cluster vgpsPnts = _it_msr->get()->GetPoints_ptr(); ExtractAssociatedStns_Y(vgpsPnts, pvUsedStns); continue; } if (_it_msr->get()->GetFirst().empty()) { // size_t msr_no(std::distance(vMeasurements->begin(), _it_msr)); throw XMLInteropException("Empty \"First\" station name.", 0); } // 2. All other measurements which have <First> station = _it_msr->get()->GetFirst(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } // Finished with single station measurements switch (_it_msr->get()->GetTypeC()) { case 'H': // Orthometric height case 'R': // Ellipsoidal height case 'I': // Astronomic latitude case 'J': // Astronomic longitude case 'P': // Geodetic latitude case 'Q': // Geodetic longitude continue; } if (_it_msr->get()->GetTarget().empty()) throw XMLInteropException("Empty \"Second\" station name", 0); // 3. All measurements which have <Target> or <Second> station = _it_msr->get()->GetTarget(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } // Dual station measurements... switch (_it_msr->get()->GetTypeC()) { case 'D': // Direction set // now map the directions in the set vdirns = _it_msr->get()->GetDirections_ptr(); ExtractAssociatedStns_D(vdirns, pvUsedStns); continue; case 'B': // Geodetic azimuth case 'K': // Astronomic azimuth case 'C': // Chord dist case 'E': // Ellipsoid arc case 'M': // MSL arc case 'S': // Slope distance case 'L': // Level difference case 'V': // Zenith angle case 'Z': // Vertical angle continue; } if (_it_msr->get()->GetTarget2().empty()) throw XMLInteropException("Empty \"Third\" station name", 0); // 4. All measurements which have <Target2> or <Third> station = _it_msr->get()->GetTarget2(); it_msr_stns = equal_range(pvUsedStns->begin(), pvUsedStns->end(), station); if (it_msr_stns.first == it_msr_stns.second) { pvUsedStns->push_back(station); sort(pvUsedStns->begin(), pvUsedStns->end()); } } } void dna_import::LoadNetworkFiles(pvstn_t binaryStn, pvmsr_t binaryMsr, const project_settings& projectSettings, bool loadSegmentFile) { projectSettings_ = projectSettings; LoadBinaryFiles(binaryStn, binaryMsr); if (loadSegmentFile) LoadSegmentationFile(); } void dna_import::LoadBinaryFiles(pvstn_t binaryStn, pvmsr_t binaryMsr) { g_parsestn_tally.initialise(); g_parsemsr_tally.initialise(); try { // Load binary stations data. Throws runtime_error on failure. dna_io_bst bst; bst.load_bst_file(projectSettings_.i.bst_file, binaryStn, bst_meta_); // Load binary stations data. Throws runtime_error on failure. dna_io_bms bms; bms.load_bms_file(projectSettings_.i.bms_file, binaryMsr, bms_meta_); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::LoadSegmentationFile() { UINT32 blockCount, blockThreshold, minInnerStns; try { // Load segmentation file. Throws runtime_error on failure. dna_io_seg seg; seg.load_seg_file(projectSettings_.i.seg_file, blockCount, blockThreshold, minInnerStns, v_ISL_, v_JSL_, v_CML_, false, 0, 0, 0, 0, 0); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::ImportStnsMsrsFromBlock(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, const project_settings& p) { vstn_t binaryStn; vmsr_t binaryMsr; LoadNetworkFiles(&binaryStn, &binaryMsr, p, true); it_vUINT32 _it_data; dnaStnPtr stnPtr(new CDnaStation(datum_.GetName(), datum_.GetEpoch_s())); vStations->clear(); // get stations on ISL for (_it_data=v_ISL_.at(p.i.import_block_number-1).begin(); _it_data!=v_ISL_.at(p.i.import_block_number-1).end(); ++_it_data) { stnPtr->SetStationRec(binaryStn.at(*_it_data)); vStations->push_back(stnPtr); g_parsestn_tally.addstation(stnPtr->GetConstraints()); stnPtr.reset(new CDnaStation(datum_.GetName(), datum_.GetEpoch_s())); } // get stations on JSL for (_it_data=v_JSL_.at(p.i.import_block_number-1).begin(); _it_data!=v_JSL_.at(p.i.import_block_number-1).end(); ++_it_data) { stnPtr->SetStationRec(binaryStn.at(*_it_data)); vStations->push_back(stnPtr); g_parsestn_tally.addstation(stnPtr->GetConstraints()); stnPtr.reset(new CDnaStation(datum_.GetName(), datum_.GetEpoch_s())); } dnaMsrPtr msrPtr; msrPtr.reset(); vMeasurements->clear(); it_vmsr_t it_msr; UINT32 advanceBy(0), msr_no(0); RemoveNonMeasurements(p.i.import_block_number-1, &binaryMsr); // get stations on CML for (_it_data=v_CML_.at(p.i.import_block_number-1).begin(); _it_data!=v_CML_.at(p.i.import_block_number-1).end(); ++_it_data) { it_msr = binaryMsr.begin() + *_it_data; ResetMeasurementPtr(&msrPtr, binaryMsr.at(*_it_data).measType); msr_no++; // build measurement tally - do determine whether measurements of a particular type // have been supplied switch (it_msr->measType) { case 'A': // Horizontal angle g_parsemsr_tally.A++; break; case 'B': // Geodetic azimuth g_parsemsr_tally.B++; break; case 'C': // Chord dist g_parsemsr_tally.C++; break; case 'D': // Direction set if (it_msr->measStart == xMeas) g_parsemsr_tally.D += it_msr->vectorCount1; break; case 'E': // Ellipsoid arc g_parsemsr_tally.E++; break; case 'G': // GPS Baseline g_parsemsr_tally.G += 3; break; case 'H': // Orthometric height g_parsemsr_tally.H++; break; case 'I': // Astronomic latitude g_parsemsr_tally.I++; break; case 'J': // Astronomic longitude g_parsemsr_tally.J++; break; case 'K': // Astronomic azimuth g_parsemsr_tally.K++; break; case 'L': // Level difference g_parsemsr_tally.L++; break; case 'M': // MSL arc g_parsemsr_tally.M++; break; case 'P': // Geodetic latitude g_parsemsr_tally.P++; break; case 'Q': // Geodetic longitude g_parsemsr_tally.Q++; break; case 'R': // Ellipsoidal height g_parsemsr_tally.R++; break; case 'S': // Slope distance g_parsemsr_tally.S++; break; case 'V': // Zenith angle g_parsemsr_tally.V++; break; case 'X': // GPS Baseline cluster if (it_msr->measStart == xMeas) g_parsemsr_tally.X += it_msr->vectorCount1 * 3; break; case 'Y': // GPS point cluster if (it_msr->measStart == xMeas) g_parsemsr_tally.Y += it_msr->vectorCount1 * 3; break; case 'Z': // Vertical angle g_parsemsr_tally.Z++; break; } if ((advanceBy = msrPtr->SetMeasurementRec(binaryStn, it_msr)) > 0) std::advance(_it_data, advanceBy); vMeasurements->push_back(msrPtr); } } void dna_import::RemoveNonMeasurements(const UINT32& block, pvmsr_t binaryMsr) { if (v_CML_.at(block).size() < 2) return; CompareNonMeasStart<measurement_t, UINT32> measstartCompareFunc(binaryMsr, xMeas); sort(v_CML_.at(block).begin(), v_CML_.at(block).end(), measstartCompareFunc); erase_if(v_CML_.at(block), measstartCompareFunc); CompareMsrFileOrder<measurement_t, UINT32> fileorderCompareFunc(binaryMsr); sort(v_CML_.at(block).begin(), v_CML_.at(block).end(), fileorderCompareFunc); } void dna_import::SignalComplete() { isProcessing_ = false; percentComplete_ = -99.0; // Obtain exclusive use of the input file pointer import_file_mutex.lock(); try { if (ifsInputFILE_ != 0) { if (ifsInputFILE_->good()) ifsInputFILE_->close(); delete ifsInputFILE_; } } catch (const std::ifstream::failure& e) { if (ifsInputFILE_->rdstate() & std::ifstream::eofbit) { ifsInputFILE_ = 0; } throw XMLInteropException(e.what(), 0); } ifsInputFILE_ = 0; // release file pointer mutex import_file_mutex.unlock(); } void dna_import::SignalExceptionParse(string msg, int i) { SignalComplete(); size_t s = msg.find("is not allowed for content model"); if (s != string::npos) msg += "\n - check that the order of elements in the XML file matches the order of the XSD complex type elements."; parseStatus_ = PARSE_EXCEPTION_RAISED; throw XMLInteropException(msg, i); } void dna_import::SignalExceptionParseDNA(const string& message, const string& sBuf, const int& column_no) { stringstream ss; ss << message << endl; if (!sBuf.empty()) ss << " " << sBuf << endl; m_columnNo = column_no + 1; throw XMLInteropException(ss.str(), m_lineNo); } // Name: SignalExceptionInterop // Purpose: Closes all files (if file pointers are passed in) and throws NetSegmentException // Called by: Any // Calls: XMLInteropException() void dna_import::SignalExceptionInterop(string msg, int i, const char *streamType, ...) { if (streamType == NULL) throw XMLInteropException(msg, i); std::ofstream* outstream; std::ifstream* instream; va_list argptr; va_start(argptr, streamType); while (*streamType != '\0') { //ifstream if (*streamType == 'i' ) { instream = va_arg(argptr, std::ifstream*); instream->close(); } //ofstream if (*streamType == 'o' ) { outstream = va_arg(argptr, std::ofstream*); outstream->close(); } streamType++; } throw XMLInteropException(msg, i); } void dna_import::SerialiseDNA(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, const string& stnfilename, const string& msrfilename, const project_settings& p, vifm_t* vinput_file_meta, bool flagUnused) { try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } // Stations std::ofstream dna_stn_file; try { // Create DynAdjust STN file. file_opener(dna_stn_file, stnfilename); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } determineDNASTNFieldParameters<UINT16>("3.01", dsl_, dsw_); determineDNAMSRFieldParameters<UINT16>("3.01", dml_, dmw_); _it_vdnastnptr _it_stn(vStations->begin()); CDnaProjection projection(UTM); try { // print stations // Has the user specified --flag-unused-stations, in which case, do not // print stations marked unused? UINT32 count(0); if (flagUnused) { for_each(vStations->begin(), vStations->end(), [&count](const dnaStnPtr& stn) { if (stn.get()->IsNotUnused()) count++; }); } else count = static_cast<UINT32>(vStations->size()); // Write version line dna_header(dna_stn_file, "3.01", "STN", datum_.GetName(), datum_.GetEpoch_s(), count); // Capture source files string source_files(formatStnMsrFileSourceString<string>(vinput_file_meta, stn_data)); // Write header comment lines about this file dna_comment(dna_stn_file, "File type: Station file"); dna_comment(dna_stn_file, "Project name: " + p.g.network_name); dna_comment(dna_stn_file, "Source files: " + source_files); // print stations // Has the user specified --flag-unused-stations, in wich case, do not // print stations marked unused? if (flagUnused) { for (_it_stn=vStations->begin(); _it_stn!=vStations->end(); _it_stn++) if (_it_stn->get()->IsNotUnused()) _it_stn->get()->WriteDNAXMLStnInitialEstimates(&dna_stn_file, datum_.GetEllipsoidRef(), &projection, dna, &dsw_); } else { // print all stations regardless of whether they are unused or not for (_it_stn=vStations->begin(); _it_stn!=vStations->end(); _it_stn++) _it_stn->get()->WriteDNAXMLStnInitialEstimates(&dna_stn_file, datum_.GetEllipsoidRef(), &projection, dna, &dsw_); } dna_stn_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dna_stn_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dna_stn_file); } // Measurements std::ofstream dna_msr_file; try { // Create DynAdjust MSR file. file_opener(dna_msr_file, msrfilename); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } _it_vdnamsrptr _it_msr(vMeasurements->begin()); try { // Write version line dna_header(dna_msr_file, "3.01", "MSR", datum_.GetName(), datum_.GetEpoch_s(), vMeasurements->size()); // Capture source files string source_files(formatStnMsrFileSourceString<string>(vinput_file_meta, msr_data)); // Write header comment lines about this file dna_comment(dna_msr_file, "File type: Measurement file"); dna_comment(dna_msr_file, "Project name: " + p.g.network_name); dna_comment(dna_msr_file, "Source files: " + source_files); // print measurements for (_it_msr=vMeasurements->begin(); _it_msr!=vMeasurements->end(); _it_msr++) _it_msr->get()->WriteDNAMsr(&dna_msr_file, dmw_, dml_); dna_msr_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dna_msr_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dna_msr_file); } } void dna_import::InitialiseDynaMLFile(const project_settings& p, vifm_t* vinput_file_meta, const string& outfilename, std::ofstream* dynaml_file) { // create combined filename string dynamlfilename(outfilename); size_t dp = string::npos; if ((dp = dynamlfilename.rfind(".")) == string::npos) dynamlfilename += ".xml"; try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { // Create DynaML station file. file_opener(*dynaml_file, dynamlfilename); // write header dynaml_header(*dynaml_file, "Combined File", datum_.GetName(), datum_.GetEpoch_s()); // Capture source files string source_files(formatStnMsrFileSourceString<string>(vinput_file_meta, stn_msr_data)); // Write header comment lines about this file dynaml_comment(*dynaml_file, "File type: Combined station and measurements file"); dynaml_comment(*dynaml_file, "Project name: " + p.g.network_name); dynaml_comment(*dynaml_file, "Source files: " + source_files); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseDynaMLfromBinary(const string& outfilename, const project_settings& p, vifm_t* vinput_file_meta, bool flagUnused) { // Load stations from binary file and serialise to XML std::ifstream bst_file; try { // Load binary stations data. Throws runtime_error on failure. file_opener(bst_file, p.i.bst_file, ios::in | ios::binary, binary, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } std::ofstream dynaml_file; InitialiseDynaMLFile(p, vinput_file_meta, outfilename, &dynaml_file); // Write the stations (from memory) try { SerialiseXmlStn(&bst_file, &dynaml_file); } catch (const ios_base::failure& f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "io", &bst_file, &dynaml_file); } std::ifstream bms_file; try { // Load binary measurements data. Throws runtime_error on failure. file_opener(bms_file, p.i.bms_file, ios::in | ios::binary, binary, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } // Write the measurements (from binary file) try { SerialiseXmlMsr(&bst_file, &bms_file, &dynaml_file); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "iio", &bst_file, &bms_file, &dynaml_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "iio", &bst_file, &bms_file, &dynaml_file); } bst_file.close(); bms_file.close(); dynaml_file << "</DnaXmlFormat>" << endl; dynaml_file.close(); } void dna_import::SerialiseDynaMLfromMemory(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, const string& outfilename, const project_settings& p, vifm_t* vinput_file_meta, bool flagUnused) { // create combined filename string dynamlfilename(outfilename); size_t dp = string::npos; if ((dp = dynamlfilename.rfind(".")) == string::npos) dynamlfilename += ".xml"; try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } std::ofstream dynaml_file; InitialiseDynaMLFile(p, vinput_file_meta, outfilename, &dynaml_file); CDnaProjection projection(UTM); try { // Write the stations (from memory) if (flagUnused) { for_each(vStations->begin(), vStations->end(), [this, &projection, &dynaml_file] (dnaStnPtr stn) { if (stn->IsNotUnused()) stn->WriteDNAXMLStnInitialEstimates(&dynaml_file, datum_.GetEllipsoidRef(), &projection, dynaml); }); } else { for_each(vStations->begin(), vStations->end(), [this, &projection, &dynaml_file] (dnaStnPtr stn) { stn->WriteDNAXMLStnInitialEstimates(&dynaml_file, datum_.GetEllipsoidRef(), &projection, dynaml); }); } // Write the measurements (from memory) for_each(vMeasurements->begin(), vMeasurements->end(), [this, &projection, &dynaml_file] (dnaMsrPtr msr) { msr->WriteDynaMLMsr(&dynaml_file); }); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dynaml_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dynaml_file); } dynaml_file << "</DnaXmlFormat>" << endl; dynaml_file.close(); } void dna_import::InitialiseDynaMLSepStationFile(const project_settings& p, vifm_t* vinput_file_meta, const string& stnfilename, std::ofstream* dynaml_stn_file) { try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { // Create DynaML station file. file_opener(*dynaml_stn_file, stnfilename); // write header dynaml_header(*dynaml_stn_file, "Station File", datum_.GetName(), datum_.GetEpoch_s()); // Capture source files string source_files(formatStnMsrFileSourceString<string>(vinput_file_meta, stn_data)); // Write header comment lines about this file dynaml_comment(*dynaml_stn_file, "File type: Station file"); dynaml_comment(*dynaml_stn_file, "Project name: " + p.g.network_name); dynaml_comment(*dynaml_stn_file, "Source files: " + source_files); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::InitialiseDynaMLSepMeasurementFile(const project_settings& p, vifm_t* vinput_file_meta, const string& msrfilename, std::ofstream* dynaml_msr_file) { try { // Create DynaML measurement file. file_opener(*dynaml_msr_file, msrfilename); // write header dynaml_header(*dynaml_msr_file, "Measurement File", datum_.GetName(), datum_.GetEpoch_s()); // Capture source files string source_files(formatStnMsrFileSourceString<string>(vinput_file_meta, msr_data)); // Write header comment lines about this file dynaml_comment(*dynaml_msr_file, "File type: Measurement file"); dynaml_comment(*dynaml_msr_file, "Project name: " + p.g.network_name); dynaml_comment(*dynaml_msr_file, "Source files: " + source_files); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseDynaMLSepfromBinary(const string& stnfilename, const string& msrfilename, const project_settings& p, vifm_t* vinput_file_meta, bool flagUnused) { // Load stations from binary file and serialise to XML std::ifstream bst_file; try { // Load binary stations data. Throws runtime_error on failure. file_opener(bst_file, p.i.bst_file, ios::in | ios::binary, binary, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } // Create Station file and initialise header std::ofstream dynaml_stn_file; InitialiseDynaMLSepStationFile(p, vinput_file_meta, stnfilename, &dynaml_stn_file); // Write the stations (from binary file) try { SerialiseXmlStn(&bst_file, &dynaml_stn_file); dynaml_stn_file << "</DnaXmlFormat>" << endl; dynaml_stn_file.close(); } catch (const ios_base::failure& f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "io", &bst_file, &dynaml_stn_file); } std::ifstream bms_file; try { // Load binary measurements data. Throws runtime_error on failure. file_opener(bms_file, p.i.bms_file, ios::in | ios::binary, binary, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } // Create Measurement file and initialise header std::ofstream dynaml_msr_file; InitialiseDynaMLSepMeasurementFile(p, vinput_file_meta, msrfilename, &dynaml_msr_file); // Write the measurements (from binary file) try { SerialiseXmlMsr(&bst_file, &bms_file, &dynaml_msr_file); dynaml_msr_file << "</DnaXmlFormat>" << endl; dynaml_msr_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "iio", &bst_file, &bms_file, &dynaml_msr_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "iio", &bst_file, &bms_file, &dynaml_msr_file); } bst_file.close(); bms_file.close(); } void dna_import::SerialiseDynaMLSepfromMemory(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, const string& stnfilename, const string& msrfilename, const project_settings& p, vifm_t* vinput_file_meta, bool flagUnused) { // Create Station file and initialise header std::ofstream dynaml_stn_file; InitialiseDynaMLSepStationFile(p, vinput_file_meta, stnfilename, &dynaml_stn_file); CDnaProjection projection(UTM); // Write the stations (from memory) try { if (flagUnused) { for_each(vStations->begin(), vStations->end(), [this, &projection, &dynaml_stn_file] (dnaStnPtr stn) { if (stn->IsNotUnused()) stn->WriteDNAXMLStnInitialEstimates(&dynaml_stn_file, datum_.GetEllipsoidRef(), &projection, dynaml); }); } else { for_each(vStations->begin(), vStations->end(), [this, &projection, &dynaml_stn_file] (dnaStnPtr stn) { stn->WriteDNAXMLStnInitialEstimates(&dynaml_stn_file, datum_.GetEllipsoidRef(), &projection, dynaml); }); } dynaml_stn_file << "</DnaXmlFormat>" << endl; dynaml_stn_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dynaml_stn_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dynaml_stn_file); } // Create Measurement file and initialise header std::ofstream dynaml_msr_file; InitialiseDynaMLSepMeasurementFile(p, vinput_file_meta, msrfilename, &dynaml_msr_file); // Write the measurements (from memory) try { for_each(vMeasurements->begin(), vMeasurements->end(), [this, &projection, &dynaml_msr_file] (dnaMsrPtr msr) { msr->WriteDynaMLMsr(&dynaml_msr_file); }); dynaml_msr_file << "</DnaXmlFormat>" << endl; dynaml_msr_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dynaml_msr_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dynaml_msr_file); } } void dna_import::SerialiseGeoidData(vdnaStnPtr* vStations, const string& geofilename) { std::ofstream dynaml_geo_file; try { // Create geoid file. Throws runtime_error on failure. file_opener(dynaml_geo_file, geofilename); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } _it_vdnastnptr _it_stn; try { // Write header line dna_comment(dynaml_geo_file, "DNA geoid file."); // Print data to geoid file for (_it_stn=vStations->begin(); _it_stn!=vStations->end(); _it_stn++) _it_stn->get()->WriteGeoidfile(&dynaml_geo_file); dynaml_geo_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dynaml_geo_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dynaml_geo_file); } } void dna_import::SerialiseXmlStn(std::ifstream* ifs_stns, std::ofstream* ofs_dynaml) { try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } station_t stationRecord; dnaStnPtr stnPtr(new CDnaStation(datum_.GetName(), datum_.GetEpoch_s())); stnPtr->SetCoordType(LLH_type); CDnaProjection projection(UTM); // get number of stations UINT32 i, stnCount; ifs_stns->read(reinterpret_cast<char *>(&stnCount), sizeof(UINT32)); for (i=0; i<stnCount; i++) { if (ifs_stns->eof() || !ifs_stns->good()) throw XMLInteropException("SerialiseXMLStn(): Errors were encountered when reading from the binary station file.", 0); ifs_stns->read(reinterpret_cast<char *>(&stationRecord), sizeof(station_t)); stnPtr->SetStationRec(stationRecord); stnPtr->WriteDNAXMLStnInitialEstimates(ofs_dynaml, datum_.GetEllipsoidRef(), &projection, dynaml); } } void dna_import::SerialiseXmlMsr(std::ifstream* ifs_stns, std::ifstream* ifs_msrs, std::ofstream* ofs_dynaml) { try { // Reset the default datum. datum_.SetDatumFromEpsg(m_strProjectDefaultEpsg, m_strProjectDefaultEpoch); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } measurement_t measRecord; dnaMsrPtr msrPtr; msrPtr.reset(); // get number of measurements UINT32 msrCount; ifs_msrs->read(reinterpret_cast<char *>(&msrCount), sizeof(UINT32)); for (UINT32 i=0; i<msrCount; i++) { if (ifs_msrs->eof() || !ifs_msrs->good()) throw XMLInteropException("SerialiseXMLMsr(): Errors were encountered when reading from the binary measurement file.", 0); ifs_msrs->read(reinterpret_cast<char *>(&measRecord), sizeof(measurement_t)); ResetMeasurementPtr(&msrPtr, measRecord.measType); i += msrPtr->SetMeasurementRec(ifs_stns, ifs_msrs, &measRecord); // increment by number of elements read from binary file msrPtr->WriteDynaMLMsr(ofs_dynaml); } } void dna_import::SerialiseBms(const string& bms_filename, vdnaMsrPtr* vMeasurements, vifm_t& vinput_file_meta) { // Calculate number of measurement records m_binaryRecordCount = 0; //m_dbidRecordCount = 0; for_each(vMeasurements->begin(), vMeasurements->end(), [this](dnaMsrPtr msr) { // update database map //msr->SetDatabaseMap_bmsIndex(m_binaryRecordCount); m_binaryRecordCount += msr->CalcBinaryRecordCount(); //m_dbidRecordCount += msr->CalcDbidRecordCount(); }); // the database ID vector is set to the same size as the // binary measurement vector to enable efficient 1:1 lookup // of database IDs m_dbidRecordCount = m_binaryRecordCount; dna_io_bms bms; try { sprintf(bms_meta_.modifiedBy, "%s", __BINARY_NAME__); bms_meta_.binCount = m_binaryRecordCount; bms_meta_.inputFileCount = bms.create_msr_input_file_meta(vinput_file_meta, &(bms_meta_.inputFileMeta)); bms.write_bms_file(bms_filename, vMeasurements, bms_meta_); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseBst(const string& bst_filename, vdnaStnPtr* vStations, pvstring vUnusedStns, vifm_t& vinput_file_meta, bool flagUnused) { dna_io_bst bst; try { sprintf(bst_meta_.modifiedBy, "%s", __BINARY_NAME__); bst_meta_.binCount = static_cast<UINT32>(vStations->size()); bst_meta_.inputFileCount = bst.create_stn_input_file_meta(vinput_file_meta, &(bst_meta_.inputFileMeta)); bst_meta_.reduced = true; bst.write_bst_file(bst_filename, vStations, vUnusedStns, bst_meta_, flagUnused); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } // First item in the file is a UINT32 value - the number of records in the file // All records are of type UINT32 void dna_import::SerialiseDatabaseId(const string& dbid_filename, pvdnaMsrPtr vMeasurements) { std::ofstream dbid_file; try { // Create geoid file. Throws runtime_error on failure. file_opener(dbid_file, dbid_filename, ios::out | ios::binary, binary); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { // Write header line dbid_file.write(reinterpret_cast<char *>(&m_dbidRecordCount), sizeof(UINT32)); // Print data for_each (vMeasurements->begin(), vMeasurements->end(), [&dbid_file](const dnaMsrPtr& msr) { msr->SerialiseDatabaseMap(&dbid_file); }); dbid_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, NULL); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, NULL); } } void dna_import::PrintMeasurementsToStations(string& m2s_file, MsrTally* parsemsrTally, string& bst_file, string& bms_file, string& aml_file, pvASLPtr vAssocStnList) { dna_io_aml aml; vmsrtally v_stnmsrTally; v_aml_pair vAssocMsrList; vstn_t bstBinaryRecords; vmsr_t bmsBinaryRecords; try { // Load binary stations data. Throws runtime_error on failure. dna_io_bst bst; bst.load_bst_file(bst_file, &bstBinaryRecords, bst_meta_); // Load binary measurements data. Throws runtime_error on failure. dna_io_bms bms; bms.load_bms_file(bms_file, &bmsBinaryRecords, bms_meta_); // Load aml file. Throws runtime_error on failure. aml.load_aml_file(aml_file, &vAssocMsrList, &bmsBinaryRecords); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } // Create stns to msrs tally from AML and ASL aml.create_msr_to_stn_tally(vAssocStnList, vAssocMsrList, v_stnmsrTally, bmsBinaryRecords); vUINT32 vStationList(bstBinaryRecords.size()); // initialise vector with 0,1,2,...,n-2,n-1,n initialiseIncrementingIntegerVector<UINT32>(vStationList, static_cast<UINT32>(bstBinaryRecords.size())); // Print measurement to station summary, sort stations if required // if required, sort stations according to original station file order if (projectSettings_.o._sort_stn_file_order) { CompareStnFileOrder<station_t, UINT32> stnorderCompareFunc(&bstBinaryRecords); sort(vStationList.begin(), vStationList.end(), stnorderCompareFunc); } std::ofstream m2s_stream; try { // Create m2s file. Throws runtime_error on failure. file_opener(m2s_stream, m2s_file); // Print formatted header print_file_header(m2s_stream, "DYNADJUST MEASUREMENT TO STATION OUTPUT FILE"); m2s_stream << setw(PRINT_VAR_PAD) << left << "File name:" << system_complete(m2s_file).string() << endl << endl; m2s_stream << setw(PRINT_VAR_PAD) << left << "Associated measurement file: " << system_complete(aml_file).string() << endl; m2s_stream << setw(PRINT_VAR_PAD) << left << "Stations file:" << system_complete(bst_file).string() << endl; m2s_stream << setw(PRINT_VAR_PAD) << left << "Measurements file:" << system_complete(bms_file).string() << endl; // Print station count m2s_stream << endl; m2s_stream << setw(PRINT_VAR_PAD) << left << "No. stations:" << vStationList.size() << endl; m2s_stream << OUTPUTLINE << endl << endl; aml.write_msr_to_stn(m2s_stream, &bstBinaryRecords, &vStationList, v_stnmsrTally, parsemsrTally); m2s_stream.close(); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } // First item in the file is a UINT32 value - the number of records in the file // All records are of type UINT32 void dna_import::SerialiseAml(const string& aml_filename, pvUINT32 vAML) { try { // write the aml file. dna_io_aml aml; aml.write_aml_file(aml_filename, vAML); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseAmlTextFile(const string& bms_filename, const string& aml_filename, pvUINT32 vAML, pvASLPtr vAssocStnList, vdnaStnPtr* vStations) { try { // write the aml file as raw text. dna_io_aml aml; aml.write_aml_file_txt(bms_filename, aml_filename + ".txt", vAML, vAssocStnList, vStations); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } // First item in the file is a UINT32 value - the number of records in the file // All records are of type ASLPtr void dna_import::SerialiseAsl(const string& filename, pvASLPtr vAssocStnList) { try { // write the asl file. dna_io_asl asl; asl.write_asl_file(filename, vAssocStnList); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } // First item in the file is a UINT32 value - the number of records in the file // All records are of type ASLPtr void dna_import::SerialiseAslTextFile(const string& filename, pvASLPtr vAssocStnList, vdnaStnPtr* vStations) { try { // write the ASCII version of the asl file. dna_io_asl asl; asl.write_asl_file_txt(filename + ".txt", vAssocStnList, vStations); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } UINT32 dna_import::RemoveDuplicateStations(vdnaStnPtr* vStations, pvstring vduplicateStations, pv_stringstring_doubledouble_pair vnearbyStations) { size_t old_stn_count(vStations->size()); // A prior sort on name is essential, since the criteria for removing duplicates // is based upon two successive station entries in an ordered vector being equal _it_vdnastnptr _it_stn_newend; // sort vStations on name and if equal, sort on file order sort(vStations->begin(), vStations->end(), CompareStationName<dnaStnPtr>()); vduplicateStations->clear(); EqualStationNameSaveDuplicates<dnaStnPtr, string> duplicateStnCompareFunc(vduplicateStations); _it_stn_newend = unique(vStations->begin(), vStations->end(), duplicateStnCompareFunc); if (_it_stn_newend != vStations->end()) vStations->resize(_it_stn_newend - vStations->begin()); if (!projectSettings_.i.search_nearby_stn) return static_cast<UINT32>(old_stn_count - vStations->size()); // search nearby stations using a radial search // // begin by sorting on latitude sort(vStations->begin(), vStations->end(), CompareLatitude<dnaStnPtr>()); vnearbyStations->clear(); NearbyStation_LowAcc<dnaStnPtr, stringstring_doubledouble_pair, double> nearbyStnLCompareFunc(projectSettings_.i.search_stn_radius, vnearbyStations); NearbyStation_HighAcc<dnaStnPtr, double, stringstring_doubledouble_pair, CDnaEllipsoid> nearbyStnHCompareFunc(projectSettings_.i.search_stn_radius, vnearbyStations, datum_.GetEllipsoid()); // Find all occurrences of nearby stations, using a function appropriate for the search distance if (projectSettings_.i.search_stn_radius < 10.0) copy_if_all_occurrences(vStations->begin(), vStations->end(), nearbyStnLCompareFunc); else copy_if_all_occurrences(vStations->begin(), vStations->end(), nearbyStnHCompareFunc); // sort station pairs by name sort(vnearbyStations->begin(), vnearbyStations->end(), CompareStationPairs<stringstring_doubledouble_pair>()); // sort by station name sort(vStations->begin(), vStations->end()); return static_cast<UINT32>(vnearbyStations->size()); } UINT32 dna_import::FindSimilarMeasurements(vdnaMsrPtr* vMeasurements, vdnaMsrPtr* vSimilarMeasurements) { // sort measurements list by Type then by First station sort(vMeasurements->begin(), vMeasurements->end(), CompareMsr<CDnaMeasurement>()); bool similar; int similar_msrs_found(0); vSimilarMeasurements->clear(); _it_vdnamsrptr _it_msr(vMeasurements->begin() + 1); _it_vdnamsrptr _it_msrprev(vMeasurements->begin()); for (; _it_msr!=vMeasurements->end(); ++_it_msr, ++_it_msrprev) { // different type? if (_it_msr->get()->GetTypeC() != _it_msrprev->get()->GetTypeC()) continue; similar = false; switch (_it_msr->get()->GetTypeC()) { case 'A': // Horizontal angles if (*(static_cast<const CDnaAngle*>(&(*_it_msr->get()))) == *(static_cast<const CDnaAngle*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'C': // Chord dist case 'E': // Ellipsoid arc case 'M': // MSL arc case 'S': // Slope distance if (*(static_cast<const CDnaDistance*>(&(*_it_msr->get()))) == *(static_cast<const CDnaDistance*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'D': // Direction set if (*(static_cast<const CDnaDirectionSet*>(&(*_it_msr->get()))) == *(static_cast<const CDnaDirectionSet*>(&(*_it_msrprev->get())))) { similar_msrs_found += static_cast<UINT32>(_it_msr->get()->GetDirections_ptr()->size()); // Ignore the directions if (projectSettings_.i.ignore_similar_msr) { for_each(_it_msr->get()->GetDirections_ptr()->begin(), _it_msr->get()->GetDirections_ptr()->end(), [this] (CDnaDirection& dir) { dir.SetIgnore(true); }); } } else continue; break; case 'B': // Geodetic azimuth case 'K': // Astronomic azimuth if (*(static_cast<const CDnaAzimuth*>(&(*_it_msr->get()))) == *(static_cast<const CDnaAzimuth*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'I': // Astronomic latitude case 'J': // Astronomic longitude case 'P': // Geodetic latitude case 'Q': // Geodetic longitude if (*(static_cast<const CDnaCoordinate*>(&(*_it_msr->get()))) == *(static_cast<const CDnaCoordinate*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'H': // Orthometric height case 'R': // Ellipsoidal height if (*(static_cast<const CDnaHeight*>(&(*_it_msr->get()))) == *(static_cast<const CDnaHeight*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'L': // Level difference if (*(static_cast<const CDnaHeightDifference*>(&(*_it_msr->get()))) == *(static_cast<const CDnaHeightDifference*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'V': // Zenith angle case 'Z': // Vertical angle if (*(static_cast<const CDnaDirection*>(&(*_it_msr->get()))) == *(static_cast<const CDnaDirection*>(&(*_it_msrprev->get())))) ++similar_msrs_found; else continue; break; case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster if (*(static_cast<const CDnaGpsBaselineCluster*>(&(*_it_msr->get()))) == *(static_cast<const CDnaGpsBaselineCluster*>(&(*_it_msrprev->get())))) { similar_msrs_found += static_cast<UINT32>(_it_msr->get()->GetBaselines_ptr()->size() * 3); // Ignore the baselines if (projectSettings_.i.ignore_similar_msr) { for_each(_it_msr->get()->GetBaselines_ptr()->begin(), _it_msr->get()->GetBaselines_ptr()->end(), [this] (CDnaGpsBaseline& bsl) { bsl.SetIgnore(true); }); } } else continue; break; case 'Y': // GPS point cluster if (*(static_cast<const CDnaGpsPointCluster*>(&(*_it_msr->get()))) == *(static_cast<const CDnaGpsPointCluster*>(&(*_it_msrprev->get())))) { similar_msrs_found += static_cast<UINT32>(_it_msr->get()->GetPoints_ptr()->size() * 3); // Ignore the points if (projectSettings_.i.ignore_similar_msr) { for_each(_it_msr->get()->GetPoints_ptr()->begin(), _it_msr->get()->GetPoints_ptr()->end(), [this] (CDnaGpsPoint& pnt) { pnt.SetIgnore(true); }); } } else continue; break; default: stringstream ss; ss << "FindSimilarMeasurements(): Unknown measurement type: " << _it_msr->get()->GetTypeC() << endl; throw XMLInteropException(ss.str(), 0); } vSimilarMeasurements->push_back(*_it_msr); if (projectSettings_.i.ignore_similar_msr) _it_msr->get()->SetIgnore(true); } return similar_msrs_found; } UINT32 dna_import::FindSimilarGXMeasurements(vdnaMsrPtr* vMeasurements, vdnaMsrPtr* vSimilarMeasurements) { // copy all measurements vdnaMsrPtr vMeasurementsG(*vMeasurements); // Strip non-GX measurements string msrTypes("GX"); CompareNonMeasType<CDnaMeasurement> meastypeCompareFuncGX(msrTypes); erase_if(vMeasurementsG, meastypeCompareFuncGX); msrTypes = "X"; // Copy X measurements vdnaMsrPtr vMeasurementsX(vMeasurementsG); CompareNonMeasType<CDnaMeasurement> meastypeCompareFuncX(msrTypes); erase_if(vMeasurementsX, meastypeCompareFuncX); msrTypes = "G"; meastypeCompareFuncGX.SetComparand(msrTypes); erase_if(vMeasurementsG, meastypeCompareFuncGX); // Don't think the following sorts are needed // sort measurements list by Type then by First station //sort(vMeasurementsG.begin(), vMeasurementsG.end(), CompareMsr<CDnaMeasurement>()); //sort(vMeasurementsX.begin(), vMeasurementsX.end(), CompareMsr<CDnaMeasurement>()); bool similarG(false); int similar_msrs_found(0); vSimilarMeasurements->clear(); _it_vdnamsrptr _it_msrG(vMeasurementsG.begin()); vstring stationsX; vector<CDnaGpsBaseline> *vgpsBslsX, *vgpsBslsG; string epochX, epochG; date dateObsX, dateObsG; stringstream strdiffDays; size_t diffDays; vUINT32 cluster_ids; // For each X Cluster, get the list of stations for (_it_vdnamsrptr _it_msrX(vMeasurementsX.begin()); _it_msrX!=vMeasurementsX.end(); ++_it_msrX) { vgpsBslsX = _it_msrX->get()->GetBaselines_ptr(); GetGXMsrStations<string>(vgpsBslsX, stationsX); sort(stationsX.begin(), stationsX.end()); similarG = false; // Check whether both stations in the G baseline exist // in the list of X Cluster stations for (_it_msrG=vMeasurementsG.begin(); _it_msrG!=vMeasurementsG.end(); ++_it_msrG) { vgpsBslsG = _it_msrG->get()->GetBaselines_ptr(); // Is the first G baseline station in the cluster? if (!binary_search(stationsX.begin(), stationsX.end(), vgpsBslsG->at(0).GetFirst())) // No, then this isn't a "duplicate" continue; // Is the second G baseline station in the cluster? if (!binary_search(stationsX.begin(), stationsX.end(), vgpsBslsG->at(0).GetTarget())) // No, then this isn't a "duplicate" continue; // Okay, both stations are in the cluster... check if this is a "duplicate" // by examining epoch. Here, the assumption is - if the observation epochs of the // X and G measurements are the same, then the X and G measurements have come from // the same source data and are therefore duplicates epochX = _it_msrX->get()->GetEpoch(); epochG = _it_msrG->get()->GetEpoch(); dateObsX = dateFromString<date>(epochX); dateObsG = dateFromString<date>(epochG); days dateDifference = dateObsX - dateObsG; diffDays = abs(dateDifference.days()); //strdiffDays << "Elapsed days: " << dateDifference; //TRACE("%s\n", strdiffDays.str().c_str()); if (diffDays < 5) { ++similar_msrs_found; similarG = true; vSimilarMeasurements->push_back(*_it_msrG); if (projectSettings_.i.ignore_similar_msr) cluster_ids.push_back(_it_msrG->get()->GetClusterID()); } } // Were similar G baselines found for this cluster? if (similarG) vSimilarMeasurements->push_back(*_it_msrX); } // If required, ignore the measurements if (projectSettings_.i.ignore_similar_msr) { sort(cluster_ids.begin(), cluster_ids.end()); for (_it_msrG=vMeasurements->begin(); _it_msrG != vMeasurements->end(); _it_msrG++) IgnoreGXMeasurements(_it_msrG->get(), cluster_ids.begin(), cluster_ids.end()); } return similar_msrs_found; } void dna_import::FullSortandMapStations(vdnaStnPtr* vStations, pv_string_uint32_pair vStnsMap_sortName) { size_t stnCount(vStations->size()); vStnsMap_sortName_.clear(); vStnsMap_sortName_.reserve(stnCount); //stnsMap->clear(); UINT32 stnIndex(0); // sort on station name (by string, not int!!!) // Note that the sort order after this will be the final order sort(vStations->begin(), vStations->end()); // Create the Station-Name / ID map string_uint32_pair stnID; for (stnIndex=0; stnIndex<stnCount; stnIndex++) { stnID.first = vStations->at(stnIndex)->GetName(); stnID.second = stnIndex; vStnsMap_sortName_.push_back(stnID); vStations->at(stnIndex)->SetnameOrder(stnIndex); } // sort on station name (i.e. first of the pair) sort(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), StationNameIDCompareName()); if (vStnsMap_sortName_.size() < stnCount) throw XMLInteropException("FullSortandMapStations(): Could not allocate sufficient memory for the Station map.", 0); *vStnsMap_sortName = vStnsMap_sortName_; } void dna_import::SortStationsForExport(vdnaStnPtr* vStations) { // Sort on original file order sort(vStations->begin(), vStations->end(), CompareStnFileOrder_CDnaStn<CDnaStation>()); } void dna_import::SortandMapStations(vdnaStnPtr* vStations, pv_string_uint32_pair vStnsMap_sortName) { UINT32 stnCount(static_cast<UINT32>(vStations->size())); vStnsMap_sortName->clear(); vStnsMap_sortName->reserve(stnCount); // Sort on station name (by string, not int!!!) sort(vStations->begin(), vStations->end()); // Create the Station-Name / ID map string_uint32_pair stnID; for (UINT32 stnIndex=0; stnIndex<stnCount; stnIndex++) { stnID.first = vStations->at(stnIndex)->GetName(); stnID.second = stnIndex; vStnsMap_sortName->push_back(stnID); vStations->at(stnIndex)->SetnameOrder(stnIndex); } // sort on station name (i.e. first of the pair) sort(vStnsMap_sortName->begin(), vStnsMap_sortName->end(), StationNameIDCompareName()); if (vStnsMap_sortName->size() < stnCount) throw XMLInteropException("SortandMapStations(): Could not allocate sufficient memory for the Station map.", 0); } void dna_import::ReduceStations(vdnaStnPtr* vStations, const CDnaProjection& projection) { // reduce cartesian or projection coordinates to geographic (radians) for_each(vStations->begin(), vStations->end(), [this, &projection](dnaStnPtr stn){ stn->ReduceStations_LLH(datum_.GetEllipsoidRef(), &projection); }); // Try to reduce stations concurrently... //parallel_for_each(vStations->begin(), vStations->end(), // [this, &projection](dnaStnPtr stn){ // stn->ReduceStations_LLH(datum_.GetEllipsoidRef(), &projection); //}); } void dna_import::RenameStations(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, project_settings* p) { if (!exists(p->i.stn_renamingfile)) { string s("The station renaming file cannot be found:\n"); s.append(" ").append(p->i.stn_renamingfile); throw XMLInteropException(s, 0); } // station renaming file // // <--- (20 chars) ---><--- (20 chars) ---><--- (20 chars) ---><--- (20 chars) ---> // PREFERRED NAME ALIAS ALIAS ALIAS ... // // First column is the preferred name // Remaining columns are aliases (which may include the preferred name) // To increase performance, don't provide records where an alias equals the preferred name v_string_vstring_pair stationNames; dna_io_dna dna; dna.read_ren_file(p->i.stn_renamingfile, &stationNames); sort(stationNames.begin(), stationNames.end()); // rename stations in stations vector for_each(vStations->begin(), vStations->end(), [&stationNames](dnaStnPtr& stn) { for (_it_string_vstring_pair it = stationNames.begin(); it != stationNames.end(); ++it) { // search the aliases for this station's name if (binary_search(it->second.begin(), it->second.end(), stn->GetName())) { // This name is one of the aliases, so replace it // with the preferred name and break out (no need to continue) stn->SetName(it->first); break; } } }); _it_vdnamsrptr _it_msr(vMeasurements->begin()); vector<CDnaDirection>* vdirns; vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsPoint>* vgpsPnts; // rename stations in each measurement for (_it_msr=vMeasurements->begin(); _it_msr != vMeasurements->end(); _it_msr++) { // 1. Handle nested type measurements (D, G, X, Y) separately switch (_it_msr->get()->GetTypeC()) { case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vgpsBsls = _it_msr->get()->GetBaselines_ptr(); RenameStationsBsl(vgpsBsls, stationNames); continue; case 'Y': // GPS point cluster vgpsPnts = _it_msr->get()->GetPoints_ptr(); RenameStationsPnt(vgpsPnts, stationNames); continue; case 'D': // GPS point cluster // Rename stations in first direction RenameStationsMsr(_it_msr->get(), stationNames.begin(), stationNames.end()); // Rename stations in all other directions vdirns = _it_msr->get()->GetDirections_ptr(); RenameStationsDir(vdirns, stationNames); continue; } RenameStationsMsr(_it_msr->get(), stationNames.begin(), stationNames.end()); } } void dna_import::RenameStationsBsl(vector<CDnaGpsBaseline>* vGpsBaselines, v_string_vstring_pair& stnRenaming) { for_each(vGpsBaselines->begin(), vGpsBaselines->end(), [this, &stnRenaming] (CDnaGpsBaseline& bsl) { RenameStationsMsr(&bsl, stnRenaming.begin(), stnRenaming.end()); }); } void dna_import::RenameStationsPnt(vector<CDnaGpsPoint>* vGpsPoints, v_string_vstring_pair& stnRenaming) { for_each(vGpsPoints->begin(), vGpsPoints->end(), [this, &stnRenaming] (CDnaGpsPoint& pnt) { RenameStationsMsr(&pnt, stnRenaming.begin(), stnRenaming.end()); }); } void dna_import::RenameStationsDir(vector<CDnaDirection>* vDirections, v_string_vstring_pair& stnRenaming) { for_each(vDirections->begin(), vDirections->end(), [this, &stnRenaming] (CDnaDirection& dir) { RenameStationsMsr(&dir, stnRenaming.begin(), stnRenaming.end()); }); } void dna_import::EditGNSSMsrScalars(vdnaMsrPtr* vMeasurements, project_settings* p) { // Set user-defined GNSS measurement scalars _it_vdnamsrptr _it_msr(vMeasurements->begin()); // Scalar file only makes sense for individual GNSS measurements, not // GNSS baseline or point clusters!!! bool applyScalarFile(false); bool applyVScale(fabs(p->i.vscale - 1.0) > PRECISION_1E5); bool applyPScale(fabs(p->i.pscale - 1.0) > PRECISION_1E5); bool applyLScale(fabs(p->i.lscale - 1.0) > PRECISION_1E5); bool applyHScale(fabs(p->i.hscale - 1.0) > PRECISION_1E5); vscl_t bslScalars; if (!p->i.scalar_file.empty()) { if (!exists(p->i.scalar_file)) { string s("The GNSS scalar file cannot be found:\n"); s.append(" ").append(p->i.scalar_file); throw XMLInteropException(s, 0); } // load up scalars applyScalarFile = true; dna_io_scalar scalar; scalar.load_scalar_file(p->i.scalar_file, &bslScalars); } vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsBaseline>::iterator _it_bsl; vector<CDnaGpsPoint>* vgpsPnts; vector<CDnaGpsPoint>::iterator _it_pnt; // set scalars first for (_it_msr=vMeasurements->begin(); _it_msr != vMeasurements->end(); _it_msr++) { switch (_it_msr->get()->GetTypeC()) { case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster if (applyVScale) (static_cast<CDnaGpsBaselineCluster*>(&(*_it_msr->get())) )->SetVscale(_it_msr->get()->GetVscale() * p->i.vscale); if (applyPScale) (static_cast<CDnaGpsBaselineCluster*>(&(*_it_msr->get())) )->SetPscale(_it_msr->get()->GetPscale() * p->i.pscale); if (applyLScale) (static_cast<CDnaGpsBaselineCluster*>(&(*_it_msr->get())) )->SetLscale(_it_msr->get()->GetLscale() * p->i.lscale); if (applyHScale) (static_cast<CDnaGpsBaselineCluster*>(&(*_it_msr->get())) )->SetHscale(_it_msr->get()->GetVscale() * p->i.hscale); vgpsBsls = _it_msr->get()->GetBaselines_ptr(); for (_it_bsl=vgpsBsls->begin(); _it_bsl!=vgpsBsls->end(); ++_it_bsl) { if (_it_msr->get()->GetTypeC() == 'G') { // Since the only way to associate scaling with measurements in DNA and // DynaML files is to match the from and to stations (unlike GeodeticXML // which allows for a unique ID to be used to identify each measurement), // the scalars file is only applied to baselines at this stage. if (applyScalarFile) { // Find the stations in the list contained in the scalar file. // If the first and second stations match, then apply. } } if (applyVScale) _it_bsl->SetVscale(_it_bsl->GetVscale() * p->i.vscale); if (applyPScale) _it_bsl->SetPscale(_it_bsl->GetPscale() * p->i.pscale); if (applyLScale) _it_bsl->SetLscale(_it_bsl->GetLscale() * p->i.lscale); if (applyHScale) _it_bsl->SetHscale(_it_bsl->GetVscale() * p->i.hscale); } break; case 'Y': // GPS point cluster if (applyVScale) (static_cast<CDnaGpsPointCluster*>(&(*_it_msr->get())) )->SetVscale(_it_msr->get()->GetVscale() * p->i.vscale); if (applyPScale) (static_cast<CDnaGpsPointCluster*>(&(*_it_msr->get())) )->SetPscale(_it_msr->get()->GetPscale() * p->i.pscale); if (applyLScale) (static_cast<CDnaGpsPointCluster*>(&(*_it_msr->get())) )->SetLscale(_it_msr->get()->GetLscale() * p->i.lscale); if (applyHScale) (static_cast<CDnaGpsPointCluster*>(&(*_it_msr->get())) )->SetHscale(_it_msr->get()->GetVscale() * p->i.hscale); vgpsPnts = _it_msr->get()->GetPoints_ptr(); for (_it_pnt=vgpsPnts->begin(); _it_pnt!=vgpsPnts->end(); ++_it_pnt) { if (applyVScale) _it_pnt->SetVscale(_it_pnt->GetVscale() * p->i.vscale); if (applyPScale) _it_pnt->SetPscale(_it_pnt->GetPscale() * p->i.pscale); if (applyLScale) _it_pnt->SetLscale(_it_pnt->GetLscale() * p->i.lscale); if (applyHScale) _it_pnt->SetHscale(_it_pnt->GetHscale() * p->i.hscale); } break; } } } void dna_import::SerialiseMap(const string& stnmap_file) { try { // write the aml file. dna_io_map map; map.write_map_file(stnmap_file, &vStnsMap_sortName_); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseMapTextFile(const string& stnmap_file) { try { // write the aml file as raw text. dna_io_map map; map.write_map_file_txt(stnmap_file + ".txt", &vStnsMap_sortName_); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } } void dna_import::SerialiseDiscontTextFile(const string& discont_file) { std::ofstream discont_outfile; try { string outfileName(discont_file); outfileName.append(".discont"); // Open discontinuity output file. Throws runtime_error on failure. file_opener(discont_outfile, outfileName, ios::out, ascii); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { discont_outfile << setw(14) << left << "file_index" << setw(14) << left << "solution_id" << setw(STATION) << left << "site_name" << setw(14) << "date_start" << setw(14) << "date_end" << setw(24) << "discontinuity_exists" << endl; // Print discontinuity file. Throws runtime_error on failure. for_each(stn_discontinuities_.begin(), stn_discontinuities_.end(), [this, &discont_outfile](discontinuity_tuple& discont) { // use lambda expression discont_outfile << setw(14) << left << discont.file_index << setw(14) << left << discont.solution_id << setw(STATION) << left << discont.site_name << setw(14) << stringFromDate(discont.date_start) << setw(14) << stringFromDate(discont.date_end) << setw(24) << discont.discontinuity_exists << endl; } ); } catch (const runtime_error& e) { SignalExceptionParse(e.what(), 0); } discont_outfile.close(); } void dna_import::SimulateMSR(vdnaStnPtr* vStations, vdnaMsrPtr* vMeasurements, const string& msrfilename, const project_settings& p) { CDnaProjection projection(UTM); try { // reduce geographic or projection coordinates to cartesian for_each(vStations->begin(), vStations->end(), [this, &projection](dnaStnPtr stn){ stn->ReduceStations_XYZ(datum_.GetEllipsoidRef(), &projection); }); } catch (...) { stringstream ss; ss << "SimulateMSR(): An unexpected error occurred when reducing station coordinates."; SignalExceptionInterop(ss.str(), 0, NULL); } // Simulate measurements _it_vdnamsrptr _it_msr; try { for_each(vMeasurements->begin(), vMeasurements->end(), [this, &vStations](dnaMsrPtr _it_msr){ _it_msr->SimulateMsr(vStations, datum_.GetEllipsoidRef()); }); } catch (...) { stringstream ss; ss << "SimulateMSR(): An unexpected error occurred when simulating measurements."; SignalExceptionInterop(ss.str(), 0, NULL); } try { // reduce cartesian coordinates back to geographic for_each(vStations->begin(), vStations->end(), [this, &projection](dnaStnPtr stn){ stn->ReduceStations_LLH(datum_.GetEllipsoidRef(), &projection); }); } catch (...) { stringstream ss; ss << "SimulateMSR(): An unexpected error occurred when reducing station coordinates."; SignalExceptionInterop(ss.str(), 0, NULL); } determineDNAMSRFieldParameters<UINT16>("3.01", dml_, dmw_); // Print simulated measurements std::ofstream dna_msr_file; try { // Create DynAdjust MSR file. file_opener(dna_msr_file, msrfilename); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } try { // Write version line dna_header(dna_msr_file, "3.01", "MSR", datum_.GetName(), datum_.GetEpoch_s(), vMeasurements->size()); // Write header line dna_comment(dna_msr_file, p.g.network_name + " measurement file."); // print measurements for_each(vMeasurements->begin(), vMeasurements->end(), [this, &dna_msr_file](dnaMsrPtr _it_msr){ _it_msr->WriteDNAMsr(&dna_msr_file, dmw_, dml_); }); dna_msr_file.close(); } catch (const std::ifstream::failure f) { SignalExceptionInterop(static_cast<string>(f.what()), 0, "o", &dna_msr_file); } catch (const XMLInteropException &e) { SignalExceptionInterop(static_cast<string>(e.what()), 0, "o", &dna_msr_file); } } void dna_import::MapMeasurementStations(vdnaMsrPtr* vMeasurements, pvASLPtr vAssocStnList, PUINT32 lMapCount, pvstring vUnusedStns, pvUINT32 vIgnoredMsrs) { const size_t mapsize = vStnsMap_sortName_.size(); if (mapsize < 1) throw XMLInteropException("A station map has not been created. Run \"SortStations\" to create a station map.", 0); //ASList.resize(mapsize); g_map_tally.initialise(); ostringstream ss; vector<CDnaDirection>* vdirns; vector<CDnaGpsBaseline>* vgpsBsls; vector<CDnaGpsPoint>* vgpsPnts; // Association list initialisation and variables string at_station_name, to_station_name, to2_station_name; UINT32 at_station_index, to_station_index, to2_station_index; vAssocStnList->clear(); vAssocStnList->resize(vStnsMap_sortName_.size()); size_t index = 0; *lMapCount = 0; _it_vdnamsrptr _it_msr(vMeasurements->begin()); // set map values for (_it_msr=vMeasurements->begin(); _it_msr != vMeasurements->end(); _it_msr++) { index = _it_msr - vMeasurements->begin(); // The following is provided so as to cater for the opportunity to // reintroduce an ignored measurement at a later stage, such as via a GUI. // The only requirement is that a check be made on stations which become // unused as a consequence of ignoring a measurement. if (_it_msr->get()->GetIgnore()) vIgnoredMsrs->push_back(static_cast<UINT32>(std::distance(vMeasurements->begin(), _it_msr))); // 1. Handle nested type measurements (D, G, X, Y) separately switch (_it_msr->get()->GetTypeC()) { case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vgpsBsls = _it_msr->get()->GetBaselines_ptr(); _it_msr->get()->SetStn3Index(static_cast<UINT32>(vgpsBsls->size())); // set number of GpsBaselines MapMeasurementStationsBsl(vgpsBsls, vAssocStnList, lMapCount); continue; case 'Y': // GPS point cluster vgpsPnts = _it_msr->get()->GetPoints_ptr(); _it_msr->get()->SetStn3Index(static_cast<UINT32>(vgpsPnts->size())); // set number of GpsPoints MapMeasurementStationsPnt(vgpsPnts, vAssocStnList, lMapCount); continue; } if (_it_msr->get()->GetFirst().empty()) { //UINT32 msr_no(std::distance(vMeasurements->begin(), _it_msr)); throw XMLInteropException("Empty \"First\" station name.", 0); } // 1. All other measurements which have <First> at_station_name = _it_msr->get()->GetFirst(); // GetFirst() invokes CDnaMeasurement member function it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), at_station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << at_station_name << " for a " << _it_msr->get()->GetTypeC() << " measurement"; // Capture cluster ID switch (_it_msr->get()->GetTypeC()) { case 'X': case 'Y': case 'D': ss << " (cluster ID " << _it_msr->get()->GetClusterID() << ")"; } // Capture 'to' station switch (_it_msr->get()->GetTypeC()) { case 'A': // Horizontal angle case 'B': // Geodetic azimuth case 'C': // Chord dist case 'D': // Direction set case 'E': // Ellipsoid arc case 'K': // Astronomic azimuth case 'L': // Level difference case 'M': // MSL arc case 'S': // Slope distance case 'V': // Zenith angle case 'Z': // Vertical angle ss << " to " << _it_msr->get()->GetTarget(); } ss << " was not found in the list of network stations." << endl << " Please ensure that " << at_station_name << " is included in the input station file."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) at_station_index = it_stnmap_range.first->second; if (at_station_index < 0) throw XMLInteropException("MapMeasurementStations(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the First station.", 0); _it_msr->get()->SetStn1Index(at_station_index); if (!vAssocStnList->at(at_station_index)) vAssocStnList->at(at_station_index).reset(new CAStationList); if (_it_msr->get()->GetTypeC() != 'D') // measurement count for the 'at' station will be incremented in MapDirectionStations vAssocStnList->at(at_station_index).get()->IncrementMsrCount(); // Increment single station measurement counters... switch (_it_msr->get()->GetTypeC()) { case 'H': // Orthometric height g_map_tally.H ++; (*lMapCount)++; continue; case 'R': // Ellipsoidal height g_map_tally.R ++; (*lMapCount)++; continue; case 'I': // Astronomic latitude g_map_tally.I ++; (*lMapCount)++; continue; case 'J': // Astronomic longitude g_map_tally.J ++; (*lMapCount)++; continue; case 'P': // Geodetic latitude g_map_tally.P ++; (*lMapCount)++; continue; case 'Q': // Geodetic longitude g_map_tally.Q ++; (*lMapCount)++; continue; } if (_it_msr->get()->GetTarget().empty()) throw XMLInteropException("Empty \"Second\" station name", 0); // 2. All measurements which have <Target> or <Second> to_station_name = _it_msr->get()->GetTarget(); // GetTarget() invokes specialised class (i.e. CDnaDistance, etc) member function it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), to_station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << to_station_name << " was not loaded from the stations map. Please ensure that " << to_station_name << " is included in the list of network stations."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) to_station_index = it_stnmap_range.first->second; if (to_station_index < 0) throw XMLInteropException("MapMeasurementStations(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); _it_msr->get()->SetStn2Index(to_station_index); if (!vAssocStnList->at(to_station_index)) vAssocStnList->at(to_station_index).reset(new CAStationList); vAssocStnList->at(to_station_index).get()->IncrementMsrCount(); // Dual station measurements... switch (_it_msr->get()->GetTypeC()) { case 'B': // Geodetic azimuth g_map_tally.B ++; (*lMapCount)++; continue; case 'D': // Direction set // now map the directions in the set vdirns = _it_msr->get()->GetDirections_ptr(); _it_msr->get()->SetStn3Index(static_cast<UINT32>(vdirns->size())); MapMeasurementStationsDir(vdirns, vAssocStnList, lMapCount); continue; case 'K': // Astronomic azimuth g_map_tally.K ++; (*lMapCount)++; continue; case 'C': // Chord dist g_map_tally.C ++; (*lMapCount)++; continue; case 'E': // Ellipsoid arc g_map_tally.E ++; (*lMapCount)++; continue; case 'M': // MSL arc g_map_tally.M ++; (*lMapCount)++; continue; case 'S': // Slope distance g_map_tally.S ++; (*lMapCount)++; continue; case 'L': // Level difference g_map_tally.L ++; (*lMapCount)++; continue; case 'V': // Zenith angle g_map_tally.V ++; (*lMapCount)++; continue; case 'Z': // Vertical angle g_map_tally.Z ++; (*lMapCount)++; continue; } if (_it_msr->get()->GetTarget2().empty()) throw XMLInteropException("Empty \"Third\" station name", 0); // 3. All measurements which have <Target2> or <Third> to2_station_name = _it_msr->get()->GetTarget2(); // GetTarget2() invokes specialised class (i.e. CDnaAngle, etc) member function it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), to2_station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << to2_station_name << " was not loaded from the stations map. Please ensure that " << to2_station_name << " is included in the list of network stations."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) to2_station_index = it_stnmap_range.first->second; if (to2_station_index < 0) throw XMLInteropException("MapMeasurementStations(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Third station.", 0); _it_msr->get()->SetStn3Index(to2_station_index); if (!vAssocStnList->at(to2_station_index)) vAssocStnList->at(to2_station_index).reset(new CAStationList); vAssocStnList->at(to2_station_index).get()->IncrementMsrCount(); // at this stage, only 'A' type measurements have a Third switch (_it_msr->get()->GetTypeC()) { case 'A': // Horizontal angles g_map_tally.A ++; (*lMapCount)++; continue; } } vASLPtr::iterator _it_asl(vAssocStnList->begin()), _it_asl_begin(vAssocStnList->begin()); UINT32 d; // find unused stations and store them in a vector, then reset for (; _it_asl!=vAssocStnList->end(); _it_asl++) { if (!_it_asl->get()) // unused station { d = static_cast<UINT32>(std::distance(_it_asl_begin, _it_asl)); vUnusedStns->push_back(vStnsMap_sortName_.at(d).first); _it_asl->reset(new CAStationList(false)); } } } UINT32 dna_import::ComputeMeasurementCount(vdnaMsrPtr* vMeasurements, const vUINT32& vIgnoredMsrs) { MsrTally msr_tally; it_vUINT32_const it_ignmsr; _it_vdnamsrptr _it_msr; vector<CDnaDirection>::iterator _it_dirns; vector<CDnaGpsBaseline>::iterator _it_gpsbsls; vector<CDnaGpsPoint>::iterator _it_gpspts; for (it_ignmsr=vIgnoredMsrs.begin(); it_ignmsr!=vIgnoredMsrs.end(); ++it_ignmsr) { _it_msr = vMeasurements->begin() + *it_ignmsr; // Increment single station measurement counters... switch (_it_msr->get()->GetTypeC()) { case 'A': // Horizontal angle msr_tally.A++; break; case 'B': // Geodetic azimuth msr_tally.B++; break; case 'C': // Chord dist msr_tally.C++; break; case 'D': // Direction set msr_tally.D += static_cast<UINT32>(_it_msr->get()->GetDirections_ptr()->size()); break; case 'E': // Ellipsoid arc msr_tally.E++; break; case 'G': // GPS Baseline (treat as single-baseline cluster) msr_tally.G += static_cast<UINT32>(_it_msr->get()->GetBaselines_ptr()->size() * 3); break; case 'X': // GPS Baseline cluster msr_tally.X += static_cast<UINT32>(_it_msr->get()->GetBaselines_ptr()->size() * 3); break; case 'H': // Orthometric height msr_tally.H++; break; case 'I': // Astronomic latitude msr_tally.I++; break; case 'J': // Astronomic longitude msr_tally.J++; break; case 'K': // Astronomic azimuth msr_tally.K++; break; case 'L': // Level difference msr_tally.L++; break; case 'M': // MSL arc msr_tally.M++; break; case 'P': // Geodetic latitude msr_tally.P++; break; case 'Q': // Geodetic longitude msr_tally.Q++; break; case 'R': // Ellipsoidal height msr_tally.R++; break; case 'S': // Slope distance msr_tally.S++; break; case 'V': // Zenith angle msr_tally.V++; break; case 'Y': // GPS point cluster msr_tally.Y += static_cast<UINT32>(_it_msr->get()->GetPoints_ptr()->size() * 3); break; case 'Z': // Vertical angle msr_tally.Z++; break; default: stringstream ss; ss << "ComputeMeasurementCount(): Unknown measurement type: " << _it_msr->get()->GetTypeC() << endl; throw XMLInteropException(ss.str(), m_lineNo); } } return msr_tally.TotalCount(); } void dna_import::MapMeasurementStationsBsl(vector<CDnaGpsBaseline>* vGpsBaselines, pvASLPtr vAssocStnList, PUINT32 lMapCount) { const size_t mapsize = vStnsMap_sortName_.size(); if (mapsize < 1) throw XMLInteropException("A station map has not been created. Run \"SortStations\" to create a station map.", 0); ostringstream ss; //_it_string_uint32_pair _it_stnmap(vStnsMap_sortName_.end()); vector< CDnaGpsBaseline >::iterator _it_msr(vGpsBaselines->begin()); string station_name; UINT32 station_index, msrs_per_cluster_row; #ifdef _MSDEBUG CAStationList* stnList; #endif // Unique list of stations involved in this cluster vUINT32 msrStations; //msrStations.reserve(vGpsBaselines->size()); for (_it_msr = vGpsBaselines->begin(); _it_msr != vGpsBaselines->end(); _it_msr++) { msrs_per_cluster_row = 3 + static_cast<UINT32>(_it_msr->GetCovariances_ptr()->size() * 3); // <First> station station_name = _it_msr->GetFirst(); it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << station_name << " is referenced in measurement '" << _it_msr->GetType() << "' " << _it_msr->GetFirst() << " - " << _it_msr->GetTarget() << endl; ss << " but is not in the stations map. " << endl; ss << " Please ensure that " << station_name << " is included in the list of stations."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) station_index = it_stnmap_range.first->second; if (station_index < 0) throw XMLInteropException("MapMeasurementStationsBsl(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the First station.", 0); _it_msr->SetStn1Index(station_index); if (!vAssocStnList->at(station_index)) vAssocStnList->at(station_index).reset(new CAStationList); msrStations.push_back(station_index); #ifdef _MSDEBUG stnList = vAssocStnList->at(station_index).get(); #endif // <Second> station station_name = _it_msr->GetTarget(); it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << station_name << " is referenced in measurement '" << _it_msr->GetType() << "' " << _it_msr->GetFirst() << " - " << _it_msr->GetTarget() << endl; ss << " but is not in the stations map. " << endl; ss << " Please ensure that " << station_name << " is included in the list of stations."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) station_index = it_stnmap_range.first->second; if (station_index < 0) throw XMLInteropException("MapMeasurementStationsBsl(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); _it_msr->SetStn2Index(station_index); if (!vAssocStnList->at(station_index)) vAssocStnList->at(station_index).reset(new CAStationList); msrStations.push_back(station_index); #ifdef _MSDEBUG stnList = vAssocStnList->at(station_index).get(); #endif (*lMapCount) += 3; // one per vector component switch (_it_msr->GetTypeC()) { case 'G': g_map_tally.G += 3; break; case 'X': g_map_tally.X += 3; break; } } // Strip duplicates from msrStations, then increment station count for each of the stations tied to this cluster strip_duplicates(msrStations); it_vUINT32 _it_stn; for (_it_stn=msrStations.begin(); _it_stn!=msrStations.end(); ++_it_stn) vAssocStnList->at(*_it_stn).get()->IncrementMsrCount(); if (vGpsBaselines->begin()->GetTypeC() != 'X') return; // set ID for each covariance term. This is for the convenience of assigning covariance terms // to the right index in dnaAdjust vector< CDnaCovariance >::iterator _it_cov; vector< CDnaGpsBaseline >::iterator _it_msr2(vGpsBaselines->begin()); for (_it_msr = vGpsBaselines->begin(); _it_msr != vGpsBaselines->end(); _it_msr++) { _it_msr2 = _it_msr; for (_it_cov = _it_msr->GetCovariances_ptr()->begin(); _it_cov != _it_msr->GetCovariances_ptr()->end(); _it_cov++) { _it_cov->SetStn1Index(_it_msr2->GetStn1Index()); _it_cov->SetStn2Index((++_it_msr2)->GetStn2Index()); } } } void dna_import::MapMeasurementStationsPnt(vector<CDnaGpsPoint>* vGpsPoints, pvASLPtr vAssocStnList, PUINT32 lMapCount) { const size_t mapsize = vStnsMap_sortName_.size(); if (mapsize < 1) throw XMLInteropException("A station map has not been created. Run \"SortStations\" to create a station map.", 0); ostringstream ss; //_it_string_uint32_pair _it_stnmap; vector< CDnaGpsPoint >::iterator _it_msr; string station_name; UINT32 station_index, msrs_per_cluster_row; #ifdef _MSDEBUG CAStationList* stnList; #endif for (_it_msr=vGpsPoints->begin(); _it_msr != vGpsPoints->end(); _it_msr++) { msrs_per_cluster_row = 3 + static_cast<UINT32>(_it_msr->GetCovariances_ptr()->size() * 3); // <First> station station_name = _it_msr->GetFirst(); it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << station_name << " is not in the stations map. Please ensure that " << station_name << " is included in the list of stations."; throw XMLInteropException(ss.str(), 0); } // Increment ASL associated measurement count (i.e. CAStationList.assocMsrs_) station_index = it_stnmap_range.first->second; if (station_index < 0) throw XMLInteropException("MapMeasurementStationsPnt(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the GPS station.", 0); _it_msr->SetStn1Index(station_index); if (!vAssocStnList->at(station_index)) vAssocStnList->at(station_index).reset(new CAStationList); vAssocStnList->at(station_index).get()->IncrementMsrCount(); #ifdef _MSDEBUG stnList = vAssocStnList->at(station_index).get(); #endif (*lMapCount) += 3; // one per vector component g_map_tally.Y += 3; } // set ID for each covariance term. This is for the convenience of assigning covariance terms // to the right index in dnaAdjust vector< CDnaCovariance >::iterator _it_cov; vector< CDnaGpsPoint >::iterator _it_msr2(vGpsPoints->begin()); for (_it_msr = vGpsPoints->begin(); _it_msr != vGpsPoints->end(); _it_msr++) { _it_msr2 = _it_msr; for (_it_cov = _it_msr->GetCovariances_ptr()->begin(); _it_cov != _it_msr->GetCovariances_ptr()->end(); _it_cov++) { ++_it_msr2; _it_cov->SetStn1Index(_it_msr2->GetStn1Index()); } } } void dna_import::MapMeasurementStationsDir(vector<CDnaDirection>* vDirections, pvASLPtr vAssocStnList, PUINT32 lMapCount) { const size_t mapsize = vStnsMap_sortName_.size(); if (mapsize < 1) throw XMLInteropException("A station map has not been created. Run \"SortStations\" to create a station map.", 0); ostringstream ss; //_it_string_uint32_pair _it_stnmap; vector< CDnaDirection >::iterator _it_msr(vDirections->begin()); string at_station_name, to_station_name; UINT32 at_station_index, to_station_index; // Unique list of stations involved in this cluster vUINT32 msrStations; msrStations.reserve(vDirections->size()); for (_it_msr=vDirections->begin(); _it_msr!=vDirections->end(); _it_msr++) { // <First> station. Strictly speaking, this value should not change from // one direction to the next in the set at_station_name = _it_msr->GetFirst(); it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), at_station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << at_station_name << " is not in the stations map. Please ensure that " << at_station_name << " is included in the list of stations."; throw XMLInteropException(ss.str(), 0); } at_station_index = it_stnmap_range.first->second; if (at_station_index < 0) throw XMLInteropException("MapMeasurementStationsDir(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the First station.", 0); // This is needed to initialise the at station index for every // target direction _it_msr->SetStn1Index(at_station_index); msrStations.push_back(at_station_index); // <Second> station to_station_name = _it_msr->GetTarget(); it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), to_station_name, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) { ss.str(""); ss << to_station_name << " was not loaded from the stations map. Please ensure that " << to_station_name << " is included in the list of network stations."; throw XMLInteropException(ss.str(), 0); } to_station_index = it_stnmap_range.first->second; if (to_station_index < 0) throw XMLInteropException("MapMeasurementStationsDir(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Target station.", 0); _it_msr->SetStn2Index(to_station_index); if (!vAssocStnList->at(to_station_index)) vAssocStnList->at(to_station_index).reset(new CAStationList); msrStations.push_back(to_station_index); (*lMapCount)++; g_map_tally.D ++; } // Strip duplicates from msrStations, then increment station count for each of the stations tied to this cluster strip_duplicates(msrStations); for (it_vUINT32 _it_stn=msrStations.begin(); _it_stn!=msrStations.end(); ++_it_stn) vAssocStnList->at(*_it_stn).get()->IncrementMsrCount(); } void dna_import::CompleteAssociationLists(vdnaMsrPtr* vMeasurements, pvASLPtr vAssocStnList, pvUINT32 vAssocMsrList, pvstring vUnusedStns, pvUINT32 vIgnoredMsrs) { CAStationList* currentASL; UINT32 msrstoAllStations = 0; UINT32 currentBmsFileIndex; UINT32 stnIndex, stnmsr_indexAML, msrCount; vASLPtr::iterator _it_asl(vAssocStnList->begin()); #ifdef _MSDEBUG CAStationList* stnList; #endif // Complete ASL (first stage, i.e. IncrementMsrCount, was done in MapMeasurementStations) for (_it_asl=vAssocStnList->begin(); _it_asl!=vAssocStnList->end(); _it_asl++) { if (!_it_asl->get()) // unused station continue; if (_it_asl->get()->IsInvalid()) // unused station continue; #ifdef _MSDEBUG stnList = _it_asl->get(); #endif _it_asl->get()->SetAMLStnIndex(msrstoAllStations); // On first run, msrstoAllStations = 0! // increment total count (for dimension of AML) msrCount = _it_asl->get()->GetAssocMsrCount(); msrstoAllStations += msrCount; } // Now create AML vAssocMsrList->clear(); vAssocMsrList->resize(msrstoAllStations); vector<CDnaDirection>* vDirns; vector<CDnaGpsBaseline>* vGpsBsls; vector<CDnaGpsPoint>* vGpsPnts; // reset ASL #measurements to zero for (_it_asl=vAssocStnList->begin(); _it_asl!=vAssocStnList->end(); _it_asl++) { if (!_it_asl->get()) // unused station continue; if (_it_asl->get()->IsInvalid()) // unused station continue; _it_asl->get()->InitAssocMsrCount(); // initialise all stations to 'invalid', then // set 'valid' upon reading a non-ignored measurement _it_asl->get()->SetInvalid(); } currentBmsFileIndex = 0; _it_vdnamsrptr _it_msr(vMeasurements->begin()); for (_it_msr=vMeasurements->begin(); _it_msr != vMeasurements->end(); _it_msr++) { // 1. Handle nested type measurements (G, X, Y) separately switch (_it_msr->get()->GetTypeC()) { case 'D': // Direction set vDirns = _it_msr->get()->GetDirections_ptr(); CompleteASLDirections(_it_msr, vDirns, vAssocStnList, vAssocMsrList, &currentBmsFileIndex); continue; case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vGpsBsls = _it_msr->get()->GetBaselines_ptr(); CompleteASLGpsBaselines(vGpsBsls, vAssocStnList, vAssocMsrList, &currentBmsFileIndex); continue; case 'Y': // GPS point cluster vGpsPnts = _it_msr->get()->GetPoints_ptr(); CompleteASLGpsPoints(vGpsPnts, vAssocStnList, vAssocMsrList, &currentBmsFileIndex); continue; } // calc AML index for <First> stnIndex = ((CDnaMeasurement*)_it_msr->get())->GetStn1Index(); if (!vAssocStnList->at(stnIndex)) throw XMLInteropException("CompleteAssociationLists(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the First station.", 0); currentASL = vAssocStnList->at(stnIndex).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteAssociationLists(): An error occurred while trying to determine ASL index.", 0); vAssocMsrList->at(stnmsr_indexAML) = currentBmsFileIndex; currentASL->IncrementMsrCount(); if (_it_msr->get()->NotIgnored()) currentASL->SetValid(); // single station measurements switch (_it_msr->get()->GetTypeC()) { case 'H': // Orthometric height case 'R': // Ellipsoidal height case 'I': // Astronomic latitude case 'J': // Astronomic longitude case 'P': // Geodetic latitude case 'Q': // Geodetic longitude currentBmsFileIndex ++; continue; } // calc AML index for <Second> stnIndex = ((CDnaMeasurement*)_it_msr->get())->GetStn2Index(); if (!vAssocStnList->at(stnIndex)) throw XMLInteropException("CompleteAssociationLists(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); currentASL = vAssocStnList->at(stnIndex).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteAssociationLists(): An error occurred while trying to determine ASL index.", 0); vAssocMsrList->at(stnmsr_indexAML) = currentBmsFileIndex; currentASL->IncrementMsrCount(); if (_it_msr->get()->NotIgnored()) currentASL->SetValid(); // dual station measurements switch (_it_msr->get()->GetTypeC()) { case 'B': // Geodetic azimuth case 'K': // Astronomic azimuth case 'C': // Chord dist case 'E': // Ellipsoid arc case 'M': // MSL arc case 'S': // Slope distance case 'L': // Level difference case 'V': // Zenith angle case 'Z': // Vertical angle currentBmsFileIndex ++; continue; } // calc AML index for <Third> stnIndex = ((CDnaMeasurement*)_it_msr->get())->GetStn3Index(); if (!vAssocStnList->at(stnIndex)) throw XMLInteropException("CompleteAssociationLists(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Third station.", 0); currentASL = vAssocStnList->at(stnIndex).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteAssociationLists(): An error occurred while trying to determine ASL index.", 0); vAssocMsrList->at(stnmsr_indexAML) = currentBmsFileIndex; currentASL->IncrementMsrCount(); if (_it_msr->get()->NotIgnored()) currentASL->SetValid(); // triple station measurements switch (_it_msr->get()->GetTypeC()) { case 'A': // Horizontal angles currentBmsFileIndex ++; continue; } } return; } // Find unused stations resulting from ignored measurements and add to the vector // NOTE - this function is not used void dna_import::FindUnusedStationsInIgnoredMeasurements(vdnaMsrPtr* vMeasurements, pvASLPtr vAssocStnList, pvUINT32 vAssocMsrList, pvstring vUnusedStns, pvUINT32 vIgnoredMsrs) { vASLPtr::iterator _it_asl(vAssocStnList->begin()), _it_asl_begin(vAssocStnList->begin()); it_vUINT32 it_ignmsr, _it_stn_newend; vector<CDnaDirection>* vDirns; vector<CDnaDirection>::iterator it_Dirns; vector<CDnaGpsBaseline>* vGpsBsls; vector<CDnaGpsBaseline>::iterator it_GpsBsls; vector<CDnaGpsPoint>* vGpsPnts; vector<CDnaGpsPoint>::iterator it_GpsPnts; vUINT32 vIgnoredMsrStations; // Iterate through the ignored measurement list and build unique list of stations in ignored measurements for (it_ignmsr=vIgnoredMsrs->begin(); it_ignmsr!=vIgnoredMsrs->end(); ++it_ignmsr) { switch (vMeasurements->at(*it_ignmsr)->GetTypeC()) { case 'A': // Horizontal angles vIgnoredMsrStations.push_back(it_Dirns->GetStn3Index()); case 'B': // Geodetic azimuth case 'K': // Astronomic azimuth case 'C': // Chord dist case 'E': // Ellipsoid arc case 'M': // MSL arc case 'S': // Slope distance case 'L': // Level difference case 'V': // Zenith angle case 'Z': // Vertical angle vIgnoredMsrStations.push_back(it_Dirns->GetStn2Index()); case 'H': // Orthometric height case 'R': // Ellipsoidal height case 'I': // Astronomic latitude case 'J': // Astronomic longitude case 'P': // Geodetic latitude case 'Q': // Geodetic longitude vIgnoredMsrStations.push_back(it_Dirns->GetStn1Index()); break; case 'D': // Direction set vDirns = vMeasurements->at(*it_ignmsr)->GetDirections_ptr(); vIgnoredMsrStations.push_back(it_Dirns->GetStn1Index()); vIgnoredMsrStations.push_back(it_Dirns->GetStn2Index()); for (it_Dirns=vDirns->begin(); it_Dirns!=vDirns->end(); ++it_Dirns) vIgnoredMsrStations.push_back(it_Dirns->GetStn2Index()); break; case 'G': // GPS Baseline (treat as single-baseline cluster) case 'X': // GPS Baseline cluster vGpsBsls = vMeasurements->at(*it_ignmsr)->GetBaselines_ptr(); for (it_GpsBsls=vGpsBsls->begin(); it_GpsBsls!=vGpsBsls->end(); ++it_GpsBsls) { vIgnoredMsrStations.push_back(it_GpsBsls->GetStn1Index()); vIgnoredMsrStations.push_back(it_GpsBsls->GetStn2Index()); } break; case 'Y': // GPS point cluster vGpsPnts = vMeasurements->at(*it_ignmsr)->GetPoints_ptr(); for (it_GpsPnts=vGpsPnts->begin(); it_GpsPnts!=vGpsPnts->end(); ++it_GpsPnts) vIgnoredMsrStations.push_back(it_GpsPnts->GetStn1Index()); break; } } //sort(vIgnoredMsrStations.begin(), vIgnoredMsrStations.end()); //_it_stn_newend = unique(vIgnoredMsrStations.begin(), vIgnoredMsrStations.end()); //if (_it_stn_newend != vIgnoredMsrStations.end()) // vIgnoredMsrStations.resize(_it_stn_newend - vIgnoredMsrStations.begin()); strip_duplicates(vIgnoredMsrStations); } void dna_import::CompleteASLDirections(_it_vdnamsrptr _it_msr, vector<CDnaDirection>* vDirections, pvASLPtr vAssocStnList, pvUINT32 vAssocMsrList, PUINT32 currentBmsFileIndex) { ostringstream ss; CAStationList* currentASL; string station_name; UINT32 stn_indexAML, stnmsr_indexAML; const UINT32 msrstoAllStations = static_cast<UINT32>(vAssocMsrList->size()); const UINT32 bmsrIndex(*currentBmsFileIndex); vector< CDnaDirection >::iterator _it_dir(vDirections->begin()); // Unique list of stations involved in this cluster vUINT32 msrStations; msrStations.reserve(vDirections->size() + 1); // calc AML index for <First> stn_indexAML = _it_msr->get()->GetStn1Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLDirections(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the First station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLDirections(): An error occurred while trying to determine ASL index.", 0); vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; if (_it_msr->get()->NotIgnored()) currentASL->SetValid(); // Add to unique list of stations msrStations.push_back(stn_indexAML); // calc AML index for <Second> stn_indexAML = _it_msr->get()->GetStn2Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLDirections(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLDirections(): An error occurred while trying to determine ASL index.", 0); vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; if (_it_msr->get()->NotIgnored()) currentASL->SetValid(); // Add to unique list of stations msrStations.push_back(stn_indexAML); // Increment binary measurement count for Inst->RO, then once per direction (*currentBmsFileIndex)++; // Calc AML index for Station - Target directions for (_it_dir=vDirections->begin(); _it_dir != vDirections->end(); _it_dir++) { // Calc AML index for <Second> stn_indexAML = _it_dir->GetStn2Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLDirections(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLDirections(): An error occurred while trying to determine \ AML index for the Second station.", 0); // All ASL entries are set to invalid on initial run of // CompleteAssociationLists, so this is vital so as to ensure a station // is to be included. if (_it_dir->NotIgnored()) currentASL->SetValid(); // Set binary msr index for all stations in this cluster to the first element of the // cluster in the binary file vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; // To station msrStations.push_back(stn_indexAML); // increment file index for next measurement (*currentBmsFileIndex)++; } // Strip duplicates from msrStations, then increment station count once // for each station associated with this cluster strip_duplicates(msrStations); for (it_vUINT32 _it_stn=msrStations.begin(); _it_stn!=msrStations.end(); ++_it_stn) vAssocStnList->at(*_it_stn).get()->IncrementMsrCount(); } void dna_import::CompleteASLGpsBaselines(vector<CDnaGpsBaseline>* vGpsBaselines, pvASLPtr vAssocStnList, pvUINT32 vAssocMsrList, PUINT32 currentBmsFileIndex) { CAStationList* currentASL; UINT32 stn_indexAML, stnmsr_indexAML; const UINT32 msrstoAllStations = static_cast<UINT32>(vAssocMsrList->size()); const UINT32 bmsrIndex(*currentBmsFileIndex); vector< CDnaGpsBaseline >::iterator _it_msr(vGpsBaselines->begin()); // Unique list of stations involved in this cluster vUINT32 msrStations; msrStations.reserve(vGpsBaselines->size()); for (_it_msr=vGpsBaselines->begin(); _it_msr != vGpsBaselines->end(); _it_msr++) { // Calc AML index for <First> stn_indexAML = _it_msr->GetStn1Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLGpsBaselines(): An invalid index was found in the station \ map while \ntrying to determine ASL index for the First station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLGpsBaselines(): An error occurred while trying to determine the \ AML index for the First station.", 0); if (_it_msr->NotIgnored()) currentASL->SetValid(); // Set binary msr index for all stations in this cluster to the first element of the // cluster in the binary file vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; msrStations.push_back(stn_indexAML); // Calc AML index for <Second> stn_indexAML = _it_msr->GetStn2Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLGpsBaselines(): An invalid index was found in the station map \ while \ntrying to determine ASL index for the Second station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLGpsBaselines(): An error occurred while trying to determine \ AML index for the Second station.", 0); if (_it_msr->NotIgnored()) currentASL->SetValid(); // Set binary msr index for all stations in this cluster to the first element of the // cluster in the binary file vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; msrStations.push_back(stn_indexAML); // add: // - 3 for (X, X var); (Y, Y var, XY covar); (Z, Zvar, XZ, YZ covar), and // - 3 for each covariance (*currentBmsFileIndex) = (*currentBmsFileIndex) + 3 + static_cast<UINT32>(_it_msr->GetCovariances_ptr()->size() * 3); } // Strip duplicates from msrStations, then increment station count for each of the stations tied to this cluster strip_duplicates(msrStations); for (it_vUINT32 _it_stn=msrStations.begin(); _it_stn!=msrStations.end(); ++_it_stn) vAssocStnList->at(*_it_stn).get()->IncrementMsrCount(); } void dna_import::CompleteASLGpsPoints(vector<CDnaGpsPoint>* vGpsPoints, pvASLPtr vAssocStnList, pvUINT32 vAssocMsrList, PUINT32 currentBmsFileIndex) { CAStationList* currentASL; UINT32 stn_indexAML, stnmsr_indexAML; const UINT32 msrstoAllStations = static_cast<UINT32>(vAssocMsrList->size()); const UINT32 bmsrIndex(*currentBmsFileIndex); vector< CDnaGpsPoint >::iterator _it_msr(vGpsPoints->begin()); for (_it_msr=vGpsPoints->begin(); _it_msr != vGpsPoints->end(); _it_msr++) { // Calc AML index for <First> stn_indexAML = _it_msr->GetStn1Index(); if (!vAssocStnList->at(stn_indexAML)) throw XMLInteropException("CompleteASLGpsPoints(): An invalid index was found in the station \ map while \ntrying to determine ASL index for the First station.", 0); currentASL = vAssocStnList->at(stn_indexAML).get(); stnmsr_indexAML = currentASL->GetAMLStnIndex() + currentASL->GetAssocMsrCount(); if (stnmsr_indexAML > msrstoAllStations) throw XMLInteropException("CompleteASLGpsPoints(): An error occurred while trying to determine the \ AML index for the First station.", 0); if (_it_msr->NotIgnored()) currentASL->SetValid(); // Set binary msr index for all stations in this cluster to the first element of the // cluster in the binary file vAssocMsrList->at(stnmsr_indexAML) = bmsrIndex; // Increment the measurement count currentASL->IncrementMsrCount(); // add: // - 3 for (X, X var); (Y, Y var, XY covar); (Z, Zvar, XZ, YZ covar), and // - 3 for each covariance (*currentBmsFileIndex) += 3 + static_cast<UINT32>(_it_msr->GetCovariances_ptr()->size() * 3); } } _PARSE_STATUS_ dna_import::LoadDNAGeoidFile(const string& fileName, vdnaStnPtr* vStations) { std::ifstream geo_file; try { // Load geoid file. Throws runtime_error on failure. file_opener(geo_file, fileName, ios::in, ascii, true); } catch (const runtime_error& e) { SignalExceptionInterop(e.what(), 0, NULL); } string geoidRec, station, nValue, primeMeridian, primeVertical; double value; _it_vdnastnptr _it_stn; m_lineNo = 0; while (geo_file) { if (geo_file.eof()) break; try { getline(geo_file, geoidRec); } catch (...) { if (geo_file.eof()) { geo_file.close(); return parseStatus_; } stringstream ss; ss << "LoadDNAGeoidFile(): Could not read from the geoid file." << endl; m_columnNo = 0; throw XMLInteropException(ss.str(), m_lineNo); } m_lineNo++; if (m_lineNo < 2) continue; // blank or whitespace? if (trimstr(geoidRec).empty()) continue; // Ignore lines with comments if (geoidRec.compare(0, 1, "*") == 0) continue; geoidRec = trimstr(geoidRec); // name try { station = trimstr(geoidRec.substr(0, 40)); } catch (...) { stringstream ss; ss << "LoadDNAGeoidFile(): Could not extract station name from the record: " << endl << " " << geoidRec << endl; m_columnNo = 0; throw XMLInteropException(ss.str(), m_lineNo); } it_stnmap_range = equal_range(vStnsMap_sortName_.begin(), vStnsMap_sortName_.end(), station, StationNameIDCompareName()); if (it_stnmap_range.first == it_stnmap_range.second) continue; // No station exists for this geoid information // N value try { nValue = trimstr(geoidRec.substr(40, 10)); } catch (...) { stringstream ss; ss << "LoadDNAGeoidFile(): Could not extract the N-value from the record: " << endl << " " << geoidRec << endl; m_columnNo = 41; throw XMLInteropException(ss.str(), m_lineNo); } // Deflection in prime meridian try { primeMeridian = trimstr(geoidRec.substr(50, 19)); } catch (...) { stringstream ss; ss << "LoadDNAGeoidFile(): Could not extract the deflection in prime meridian from the record: " << endl << " " << geoidRec << endl; m_columnNo = 51; throw XMLInteropException(ss.str(), m_lineNo); } // Deflection in prime vertical try { primeVertical = trimstr(geoidRec.substr(69)); } catch (...) { stringstream ss; ss << "LoadDNAGeoidFile(): Could not extract the deflection in prime meridian from the record: " << endl << " " << geoidRec << endl; m_columnNo = 70; throw XMLInteropException(ss.str(), m_lineNo); } try { _it_stn = vStations->begin() + it_stnmap_range.first->second; _it_stn->get()->SetgeoidSep(DoubleFromString<float>(nValue)); // correct station height only if orthometric if (_it_stn->get()->GetMyHeightSystem() == ORTHOMETRIC_type_i) { value = DoubleFromString<double>(nValue); _it_stn->get()->SetcurrentHeight_d(_it_stn->get()->GetHeight() + value); //_it_stn->get()->SetHeightSystem(ELLIPSOIDAL_type_i); } // deflection values in the grid file are in seconds, so convert to radians value = DoubleFromString<double>(primeMeridian); _it_stn->get()->SetmeridianDef(SecondstoRadians(value)); value = DoubleFromString<double>(primeVertical); _it_stn->get()->SetverticalDef(SecondstoRadians(value)); } catch (...) { SignalExceptionInterop("Could not extract data for " + station + " from " + fileName + ", ", 0, "i", &geo_file); } } geo_file.close(); return parseStatus_; } } // namespace dynamlinterop } // namespace dynadjust
31.406401
197
0.70832
[ "vector", "model" ]
9cd39f21383245a7b573a3542be33409ded28575
7,746
cc
C++
test/unit_test/options_test.cc
lalo/vowpal_wabbit
c01d22cb2296e737b735d4d570d87bfbbcc513bc
[ "BSD-3-Clause" ]
null
null
null
test/unit_test/options_test.cc
lalo/vowpal_wabbit
c01d22cb2296e737b735d4d570d87bfbbcc513bc
[ "BSD-3-Clause" ]
null
null
null
test/unit_test/options_test.cc
lalo/vowpal_wabbit
c01d22cb2296e737b735d4d570d87bfbbcc513bc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD (revised) // license as described in the file LICENSE. #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> #include "options.h" #include <vector> #include <string> #include <memory> using namespace VW::config; template <typename T> std::shared_ptr<T> to_opt_ptr(option_builder<T>&& builder) { return std::dynamic_pointer_cast<T>(option_builder<T>::finalize(std::move(builder))); } template <typename T> std::shared_ptr<T> to_opt_ptr(option_builder<T>& builder) { return to_opt_ptr(std::move(builder)); } BOOST_AUTO_TEST_CASE(make_option_and_customize) { int loc = 0; auto opt = to_opt_ptr(make_option("opt", loc).default_value(4).help("Help text").keep().short_name("t")); BOOST_CHECK_EQUAL(opt->m_name, "opt"); BOOST_CHECK_EQUAL(opt->default_value_supplied(), true); BOOST_CHECK_EQUAL(opt->default_value(), 4); BOOST_CHECK_EQUAL(opt->m_help, "Help text"); BOOST_CHECK_EQUAL(opt->m_keep, true); BOOST_CHECK_EQUAL(opt->m_short_name, "t"); BOOST_CHECK_EQUAL(opt->m_type_hash, typeid(decltype(loc)).hash_code()); opt->value(5, true); BOOST_CHECK_EQUAL(loc, 5); } BOOST_AUTO_TEST_CASE(make_option_no_loc_and_customize) { auto opt = to_opt_ptr(make_option<int>("opt").default_value(4).help("Help text").keep().short_name("t")); BOOST_CHECK_EQUAL(opt->m_name, "opt"); BOOST_CHECK_EQUAL(opt->default_value_supplied(), true); BOOST_CHECK_EQUAL(opt->default_value(), 4); BOOST_CHECK_EQUAL(opt->m_help, "Help text"); BOOST_CHECK_EQUAL(opt->m_keep, true); BOOST_CHECK_EQUAL(opt->m_short_name, "t"); BOOST_CHECK_EQUAL(opt->m_type_hash, typeid(int).hash_code()); opt->value(5); BOOST_CHECK_EQUAL(opt->value(), 5); } BOOST_AUTO_TEST_CASE(typed_argument_equality) { int int_loc; int int_loc_other; float float_loc; auto arg1 = to_opt_ptr(make_option("int_opt", int_loc).default_value(4).help("Help text").keep().short_name("t")); auto arg2 = to_opt_ptr(make_option("int_opt", int_loc_other).default_value(4).help("Help text").keep().short_name("t")); auto param_3 = to_opt_ptr(make_option("float_opt", float_loc).default_value(3.2f).short_name("f")); base_option* b1 = static_cast<base_option*>(arg1.get()); base_option* b2 = static_cast<base_option*>(arg2.get()); base_option* b3 = static_cast<base_option*>(param_3.get()); BOOST_CHECK(*arg1 == *arg2); BOOST_CHECK(*b1 == *b2); BOOST_CHECK(*b1 != *b3); } BOOST_AUTO_TEST_CASE(create_argument_group) { char loc; std::vector<std::string> loc2; option_group_definition ag("g1"); ag(make_option("opt1", loc).keep()); ag(make_option("opt2", loc)); ag.add(make_option("opt3", loc2)); ag.add(make_option("opt4", loc2).keep()); BOOST_CHECK_EQUAL(ag.m_name, "g1"); BOOST_CHECK_EQUAL(ag.m_options[0]->m_name, "opt1"); BOOST_CHECK_EQUAL(ag.m_options[0]->m_keep, true); BOOST_CHECK_EQUAL(ag.m_options[0]->m_type_hash, typeid(decltype(loc)).hash_code()); BOOST_CHECK_EQUAL(ag.m_options[1]->m_name, "opt2"); BOOST_CHECK_EQUAL(ag.m_options[1]->m_type_hash, typeid(decltype(loc)).hash_code()); BOOST_CHECK_EQUAL(ag.m_options[2]->m_name, "opt3"); BOOST_CHECK_EQUAL(ag.m_options[2]->m_type_hash, typeid(decltype(loc2)).hash_code()); BOOST_CHECK_EQUAL(ag.m_options[3]->m_name, "opt4"); BOOST_CHECK_EQUAL(ag.m_options[3]->m_keep, true); BOOST_CHECK_EQUAL(ag.m_options[3]->m_type_hash, typeid(decltype(loc2)).hash_code()); } BOOST_AUTO_TEST_CASE(name_extraction_from_option_group) { char loc; std::vector<std::string> loc2; option_group_definition ag("g1"); ag(make_option("im_necessary", loc).keep().necessary()); ag(make_option("opt2", loc)); ag.add(make_option("opt3", loc2)); ag.add(make_option("opt4", loc2).keep()); auto name_extractor = options_name_extractor(); // result should always be false bool result = name_extractor.add_parse_and_check_necessary(ag); BOOST_CHECK_EQUAL(name_extractor.generated_name, "im_necessary"); BOOST_CHECK_EQUAL(result, false); // was_supplied will always return false BOOST_CHECK_EQUAL(name_extractor.was_supplied("opt2"), false); BOOST_CHECK_EQUAL(name_extractor.was_supplied("random"), false); // should throw since we validate that reductions should use add_parse_and_check_necessary BOOST_REQUIRE_THROW(name_extractor.add_and_parse(ag), VW::vw_exception); } BOOST_AUTO_TEST_CASE(name_extraction_multi_necessary) { char loc; std::vector<std::string> loc2; option_group_definition ag("g1"); ag(make_option("im_necessary", loc).keep().necessary()); ag(make_option("opt2", loc).necessary()); ag.add(make_option("opt3", loc2)); ag.add(make_option("opt4", loc2).keep()); auto name_extractor = options_name_extractor(); // result should always be false bool result = name_extractor.add_parse_and_check_necessary(ag); BOOST_CHECK_EQUAL(name_extractor.generated_name, "im_necessary_opt2"); BOOST_CHECK_EQUAL(result, false); // was_supplied will always return false BOOST_CHECK_EQUAL(name_extractor.was_supplied("opt2"), false); BOOST_CHECK_EQUAL(name_extractor.was_supplied("random"), false); // should throw since we validate that reductions should use add_parse_and_check_necessary BOOST_REQUIRE_THROW(name_extractor.add_and_parse(ag), VW::vw_exception); } BOOST_AUTO_TEST_CASE(name_extraction_should_throw) { char loc; std::vector<std::string> loc2; option_group_definition ag("g1"); ag(make_option("im_necessary", loc).keep()); ag(make_option("opt2", loc)); ag.add(make_option("opt3", loc2)); ag.add(make_option("opt4", loc2).keep()); auto name_extractor = options_name_extractor(); // should throw since no .necessary() is defined BOOST_REQUIRE_THROW(name_extractor.add_parse_and_check_necessary(ag), VW::vw_exception); // should throw since these methods will never be implemented by options_name_extractor BOOST_REQUIRE_THROW(name_extractor.help({}), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.check_unregistered(), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.get_all_options(), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.get_option("opt2"), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.insert("opt2", "blah"), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.replace("opt2", "blah"), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.get_positional_tokens(), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.tint("nonsense"), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.reset_tint(), VW::vw_exception); BOOST_REQUIRE_THROW(name_extractor.get_collection_of_options(), VW::vw_exception); } BOOST_AUTO_TEST_CASE(name_extraction_recycle) { char loc; std::vector<std::string> loc2; option_group_definition ag("g1"); ag(make_option("im_necessary", loc).keep().necessary()); ag(make_option("opt2", loc).necessary()); ag.add(make_option("opt3", loc2)); ag.add(make_option("opt4", loc2).keep()); auto name_extractor = options_name_extractor(); // result should always be false bool result = name_extractor.add_parse_and_check_necessary(ag); BOOST_CHECK_EQUAL(name_extractor.generated_name, "im_necessary_opt2"); BOOST_CHECK_EQUAL(result, false); option_group_definition ag2("g2"); ag2(make_option("im_necessary_v2", loc).keep().necessary()); ag2(make_option("opt2", loc).necessary()); ag2.add(make_option("opt3", loc2)); ag2.add(make_option("opt4", loc2).keep()); // result should always be false result = name_extractor.add_parse_and_check_necessary(ag2); BOOST_CHECK_EQUAL(name_extractor.generated_name, "im_necessary_v2_opt2"); BOOST_CHECK_EQUAL(result, false); }
37.062201
116
0.750839
[ "vector" ]
9cd3d696989c90c66301acf703886e534dd3d9ee
4,545
cpp
C++
src/demos/mpi/demo_mpibasic.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
1
2015-03-19T16:48:13.000Z
2015-03-19T16:48:13.000Z
src/demos/mpi/demo_mpibasic.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
null
null
null
src/demos/mpi/demo_mpibasic.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
1
2018-10-25T07:05:40.000Z
2018-10-25T07:05:40.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora // ============================================================================= // Demo code about // // - using MPI basic features. // // NOTE! this program should be copied // on multiple hosts of a cluster and executed // using the launcher utility of the MPICH2 // toolchain (ex. mpiexec or wmpiexec.exe). // ============================================================================= #include "physics/ChBody.h" #include "unit_MPI/ChMpi.h" #include <iostream> #include <sstream> #include "mpi.h" using namespace chrono; int main(int argc, char* argv[]) { // Initialize the MPI functionality. Use the CHMPI static functions. CHMPI::Init(argc, argv); // Get infos about how many processes are launched, // and about the ID of this specific process. int numprocs = CHMPI::CommSize(); int myid = CHMPI::CommRank(); if (myid == 0) GetLog() << "Number of processes : " << numprocs << "\n"; if (numprocs < 2) { GetLog() << "Use at least 2 processes! \n"; CHMPI::Finalize(); return 0; } // // TEST 1 - send and receive ChMatrix<> object // if (myid == 0) // sender { ChMatrixDynamic<> mmatr(3, 4); for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) mmatr(i, j) = i * j; GetLog() << "Id 0: sending ChMatrix: " << mmatr << "\n"; CHMPI::SendMatrix(1, mmatr, CHMPI::MPI_STANDARD, false, 0); } if (myid == 1) // receiver { ChMatrixDynamic<> mmatr(3, 4); // must already have the proper size CHMPIstatus mstatus; CHMPI::ReceiveMatrix(0, mmatr, &mstatus, false, 0); GetLog() << "Id 1: received ChMatrix: " << mmatr << "\n"; } // // TEST 2 - send and receive strings // if (myid == 0) // sender { std::stringstream mstrbuf(std::stringstream::in | std::stringstream::out); mstrbuf << "The quick lazy fog jumped on the brown dog."; std::string mstr = mstrbuf.rdbuf()->str(); GetLog() << "Id 0: sending string: " << mstr << "\n"; CHMPI::SendString(1, mstr, CHMPI::MPI_STANDARD, false, 0); } if (myid == 1) // receiver { // std::stringstream mstrbuf2(std::stringstream::in | std::stringstream::out); CHMPIstatus mstatus; std::string mstr; CHMPI::ReceiveString(0, mstr, &mstatus); GetLog() << "Id 1: received string: " << mstr << "\n"; } // // TEST 3 - send and receive whatever serializable chrono object // i.e. objects that implements StreamIN() and StreamOUT() // i.e. objects that can be saved via << and >>. // /* if (myid==0) // sender { std::vector<char> outstream; ChStreamOutBinaryVector outstreamwrapper(&outstream); ChVector<> mv(34,11,45.34); outstreamwrapper << mv; // serialize object to binary stream, in memory. ChBody mybody; outstreamwrapper.AbstractWrite(&mybody); // serialize object to binary stream, in memory. GetLog() << "Id 0: sending serialized ChVector: " << mv << "\n"; CHMPI::SendBuffer(1, outstream, CHMPI::MPI_STANDARD, false,0); } if (myid==1) // receiver { CHMPIstatus mstatus; std::vector<char> instream; ChStreamInBinaryVector instreamwrapper(&instream); CHMPI::ReceiveBuffer(0, instream, &mstatus); ChVector<> mv; instreamwrapper >> mv; // deserialize object from binary stream. ChObj* myobj; instreamwrapper.AbstractReadCreate(&myobj); // deserialize unknown object from binary stream. if (myobj) GetLog() << "Id 1: created obj of type:" << myobj->FactoryNameTag() << "\n"; GetLog() << "Id 1: received serialized ChVector: " << mv << "\n"; } */ // Terminate the MPI functionality. CHMPI::Finalize(); return 0; }
32.234043
105
0.531133
[ "object", "vector" ]
9cd4df07d72524f35606281aadbd3cc48a1eed47
210,921
cc
C++
chrome/browser/password_manager/password_manager_browsertest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/password_manager/password_manager_browsertest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
chrome/browser/password_manager/password_manager_browsertest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/containers/contains.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "build/buildflag.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/password_manager/password_manager_test_base.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/autofill/autofill_popup_controller_impl.h" #include "chrome/browser/ui/autofill/chrome_autofill_client.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/login/login_handler.h" #include "chrome/browser/ui/login/login_handler_test_utils.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/content/browser/content_autofill_driver.h" #include "components/autofill/content/browser/content_autofill_driver_factory.h" #include "components/autofill/content/common/mojom/autofill_driver.mojom-test-utils.h" #include "components/autofill/content/common/mojom/autofill_driver.mojom.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/proto/api_v1.pb.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/form_field_data.h" #include "components/autofill/core/common/mojom/autofill_types.mojom-shared.h" #include "components/autofill/core/common/unique_ids.h" #include "components/password_manager/content/browser/content_password_manager_driver.h" #include "components/password_manager/content/browser/content_password_manager_driver_factory.h" #include "components/password_manager/core/browser/form_parsing/password_field_prediction.h" #include "components/password_manager/core/browser/http_auth_manager.h" #include "components/password_manager/core/browser/http_auth_observer.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_store_interface.h" #include "components/password_manager/core/browser/test_password_store.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/signin/public/base/signin_buildflags.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/test/back_forward_cache_util.h" #include "content/public/test/browser_test.h" #include "content/public/test/prerender_test_util.h" #include "content/public/test/test_utils.h" #include "net/base/filename_util.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/input/web_keyboard_event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/geometry/point.h" #if BUILDFLAG(ENABLE_DICE_SUPPORT) #include "chrome/browser/password_manager/password_manager_signin_intercept_test_helper.h" #include "chrome/browser/signin/dice_web_signin_interceptor.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_mutator.h" #endif // ENABLE_DICE_SUPPORT using autofill::ParsingResult; using base::ASCIIToUTF16; using base::Feature; using testing::_; using testing::ElementsAre; using FieldPrediction = autofill::AutofillQueryResponse::FormSuggestion:: FieldSuggestion::FieldPrediction; namespace password_manager { namespace { class PasswordManagerBrowserTest : public PasswordManagerBrowserTestBase { public: PasswordManagerBrowserTest() { // Turn off waiting for server predictions before filing. It makes filling // behaviour more deterministic. Filling with server predictions is tested // in PasswordFormManager unit tests. password_manager::PasswordFormManager:: set_wait_for_server_predictions_for_filling(false); } ~PasswordManagerBrowserTest() override = default; }; // Test class for testing password manager with the BackForwardCache feature // enabled. More info about the BackForwardCache, see: // http://doc/1YrBKX_eFMA9KoYof-eVThT35jcTqWcH_rRxYbR5RapU class PasswordManagerBackForwardCacheBrowserTest : public PasswordManagerBrowserTest { public: void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); PasswordManagerBrowserTest ::SetUpOnMainThread(); } bool IsGetCredentialsSuccessful() { return "success" == content::EvalJs(WebContents()->GetMainFrame(), R"( new Promise(resolve => { navigator.credentials.get({password: true, unmediated: true }) .then(m => { resolve("success"); }) .catch(()=> { resolve("error"); }); }); )"); } void SetUpCommandLine(base::CommandLine* command_line) override { scoped_feature_list_.InitWithFeaturesAndParameters( {{::features::kBackForwardCache, {{"TimeToLiveInBackForwardCacheInSeconds", "3600"}, {"ignore_outstanding_network_request_for_testing", "true"}}}}, // Allow BackForwardCache for all devices regardless of their memory. {::features::kBackForwardCacheMemoryControls}); PasswordManagerBrowserTest::SetUpCommandLine(command_line); } private: base::test::ScopedFeatureList scoped_feature_list_; }; class MockHttpAuthObserver : public password_manager::HttpAuthObserver { public: MOCK_METHOD(void, OnAutofillDataAvailable, (const std::u16string& username, const std::u16string& password), (override)); MOCK_METHOD(void, OnLoginModelDestroying, (), (override)); }; GURL GetFileURL(const char* filename) { base::ScopedAllowBlockingForTesting allow_blocking; base::FilePath path; base::PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.AppendASCII("password").AppendASCII(filename); CHECK(base::PathExists(path)); return net::FilePathToFileURL(path); } // Handles |request| to "/basic_auth". If "Authorization" header is present, // responds with a non-empty HTTP 200 page (regardless of its value). Otherwise // serves a Basic Auth challenge. std::unique_ptr<net::test_server::HttpResponse> HandleTestAuthRequest( const net::test_server::HttpRequest& request) { if (!base::StartsWith(request.relative_url, "/basic_auth", base::CompareCase::SENSITIVE)) return nullptr; auto http_response = std::make_unique<net::test_server::BasicHttpResponse>(); if (base::Contains(request.headers, "Authorization")) { http_response->set_code(net::HTTP_OK); http_response->set_content("Success!"); } else { http_response->set_code(net::HTTP_UNAUTHORIZED); std::string realm = base::EndsWith(request.relative_url, "/empty_realm", base::CompareCase::SENSITIVE) ? "\"\"" : "\"test realm\""; http_response->AddCustomHeader("WWW-Authenticate", "Basic realm=" + realm); } return http_response; } class ObservingAutofillClient : public autofill::TestAutofillClient, public content::WebContentsUserData<ObservingAutofillClient> { public: ObservingAutofillClient(const ObservingAutofillClient&) = delete; ObservingAutofillClient& operator=(const ObservingAutofillClient&) = delete; // Wait until the autofill popup is shown. void WaitForAutofillPopup() { base::RunLoop run_loop; run_loop_ = &run_loop; run_loop.Run(); DCHECK(!run_loop_); } bool popup_shown() const { return popup_shown_; } void ShowAutofillPopup( const autofill::AutofillClient::PopupOpenArgs& open_args, base::WeakPtr<autofill::AutofillPopupDelegate> delegate) override { if (run_loop_) run_loop_->Quit(); run_loop_ = nullptr; popup_shown_ = true; } private: explicit ObservingAutofillClient(content::WebContents* web_contents) {} friend class content::WebContentsUserData<ObservingAutofillClient>; base::RunLoop* run_loop_ = nullptr; bool popup_shown_ = false; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; WEB_CONTENTS_USER_DATA_KEY_IMPL(ObservingAutofillClient); void TestPromptNotShown(const char* failure_message, content::WebContents* web_contents) { SCOPED_TRACE(testing::Message(failure_message)); NavigationObserver observer(web_contents); std::string fill_and_submit = "document.getElementById('username_failed').value = 'temp';" "document.getElementById('password_failed').value = 'random';" "document.getElementById('failed_form').submit()"; ASSERT_TRUE(content::ExecuteScript(web_contents, fill_and_submit)); observer.Wait(); EXPECT_FALSE(BubbleObserver(web_contents).IsSavePromptShownAutomatically()); } // Generate HTML for a simple password form with the specified action URL. std::string GeneratePasswordFormForAction(const GURL& action_url) { return "<form method='POST' action='" + action_url.spec() + "'" " onsubmit='return true;' id='testform'>" " <input type='password' id='password_field'>" "</form>"; } // Inject an about:blank frame with a password form that uses the specified // action URL into |web_contents|. void InjectBlankFrameWithPasswordForm(content::WebContents* web_contents, const GURL& action_url) { std::string form_html = GeneratePasswordFormForAction(action_url); std::string inject_blank_frame_with_password_form = "var frame = document.createElement('iframe');" "frame.id = 'iframe';" "document.body.appendChild(frame);" "frame.contentDocument.body.innerHTML = \"" + form_html + "\""; ASSERT_TRUE(content::ExecuteScript(web_contents, inject_blank_frame_with_password_form)); } // Inject an iframe with a password form that uses the specified action URL into // |web_contents|. void InjectFrameWithPasswordForm(content::WebContents* web_contents, const GURL& action_url) { std::string form_html = GeneratePasswordFormForAction(action_url); std::string inject_blank_frame_with_password_form = "var ifr = document.createElement('iframe');" "ifr.setAttribute('id', 'iframeResult');" "document.body.appendChild(ifr);" "ifr.contentWindow.document.open();" "ifr.contentWindow.document.write(\"" + form_html + "\");" "ifr.contentWindow.document.close();"; ASSERT_TRUE(content::ExecuteScript(web_contents, inject_blank_frame_with_password_form)); } // Fills in a fake password and submits the form in |frame|, waiting for the // submit navigation to finish. |action_url| is the form action URL to wait // for. void SubmitInjectedPasswordForm(content::WebContents* web_contents, content::RenderFrameHost* frame, const GURL& action_url) { std::string submit_form = "document.getElementById('password_field').value = 'pa55w0rd';" "document.getElementById('testform').submit();"; NavigationObserver observer(web_contents); observer.SetPathToWaitFor(action_url.path()); ASSERT_TRUE(content::ExecuteScript(frame, submit_form)); observer.Wait(); } // Actual tests --------------------------------------------------------------- IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForNormalSubmit) { NavigateToFile("/password/password_form.html"); // Fill a form and submit through a <input type="submit"> button. Nothing // special. NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // Save the password and check the store. BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); bubble_observer.AcceptSavePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "random"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfFormReappeared) { NavigateToFile("/password/failed.html"); TestPromptNotShown("normal form", WebContents()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptIfChangePasswordFormReappearedEmpty) { NavigateToFile("/password/update_form_empty_fields.html"); // Fill a form and submit through a <input type="submit"> button. Nothing // special. NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('password').value = 'old_pass';" "document.getElementById('new_password_1').value = 'new_pass';" "document.getElementById('new_password_2').value = 'new_pass';" "document.getElementById('chg_submit_wo_username_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(BubbleObserver(WebContents()).IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfFormReappearedWithPartsHidden) { NavigateToFile("/password/failed_partly_visible.html"); TestPromptNotShown("partly visible form", WebContents()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfFormReappearedInputOutsideFor) { NavigateToFile("/password/failed_input_outside.html"); TestPromptNotShown("form with input outside", WebContents()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptAfterCredentialsAPIPasswordStore) { NavigateToFile("/password/password_form.html"); // Simulate the Credential Manager API function store() is called and // PasswordManager instance is notified about that. ChromePasswordManagerClient::FromWebContents(WebContents()) ->NotifyStorePasswordCalled(); // Fill a form and submit through a <input type="submit"> button. The // renderer should not send "PasswordFormsParsed" messages after the page // was loaded. NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); BubbleObserver prompt_observer(WebContents()); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForSubmitWithSameDocumentNavigation) { NavigateToFile("/password/password_navigate_before_submit.html"); // Fill a form and submit through a <input type="submit"> button. Nothing // special. The form does an in-page navigation before submitting. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, LoginSuccessWithUnrelatedForm) { // Log in, see a form on the landing page. That form is not related to the // login form (=has different input fields), so we should offer saving the // password. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_unrelated').value = 'temp';" "document.getElementById('password_unrelated').value = 'random';" "document.getElementById('submit_unrelated').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, LoginFailed) { NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_failed').value = 'temp';" "document.getElementById('password_failed').value = 'random';" "document.getElementById('submit_failed').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForSubmitUsingJavaScript) { NavigateToFile("/password/password_form.html"); // Fill a form and submit using <button> that calls submit() on the form. // This should work regardless of the type of element, as long as submit() is // called. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForDynamicForm) { // Adding a PSL matching form is a workaround explained later. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; GURL psl_orogin = embedded_test_server()->GetURL("psl.example.com", "/"); signin_form.signon_realm = psl_orogin.spec(); signin_form.url = psl_orogin; signin_form.username_value = u"unused_username"; signin_form.password_value = u"unused_password"; password_store->AddLogin(signin_form); // Show the dynamic form. ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "example.com", "/password/dynamic_password_form.html"))); ASSERT_TRUE(content::ExecuteScript( WebContents(), "document.getElementById('create_form_button').click();")); // Blink has a timer for 0.3 seconds before it updates the browser with the // new dynamic form. We wait for the form being detected by observing the UI // state. The state changes due to the matching credential saved above. Later // the form submission is definitely noticed by the browser. BubbleObserver(WebContents()).WaitForManagementState(); // Fill the dynamic password form and submit. NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.dynamic_form.username.value = 'tempro';" "document.dynamic_form.password.value = 'random';" "document.dynamic_form.submit()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(BubbleObserver(WebContents()).IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForNavigation) { NavigateToFile("/password/password_form.html"); // Don't fill the password form, just navigate away. Shouldn't prompt. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture( RenderFrameHost(), "window.location.href = 'done.html';")); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForSubFrameNavigation) { NavigateToFile("/password/multi_frames.html"); // If you are filling out a password form in one frame and a different frame // navigates, this should not trigger the infobar. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); observer.SetPathToWaitFor("/password/done.html"); std::string fill = "var first_frame = document.getElementById('first_frame');" "var frame_doc = first_frame.contentDocument;" "frame_doc.getElementById('username_field').value = 'temp';" "frame_doc.getElementById('password_field').value = 'random';"; std::string navigate_frame = "var second_iframe = document.getElementById('second_frame');" "second_iframe.contentWindow.location.href = 'done.html';"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill)); ASSERT_TRUE(content::ExecuteScript(WebContents(), navigate_frame)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForSameFormWithDifferentAction) { // Log in, see a form on the landing page. That form is related to the login // form (has a different action but has same input fields), so we should not // offer saving the password. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_different_action').value = 'temp';" "document.getElementById('password_different_action').value = 'random';" "document.getElementById('submit_different_action').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForActionMutation) { NavigateToFile("/password/password_form_action_mutation.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_action_mutation').value = 'temp';" "document.getElementById('password_action_mutation').value = 'random';" "document.getElementById('submit_action_mutation').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"XHR_FINISHED\"") break; } EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForFormWithEnteredUsername) { // Log in, see a form on the landing page. That form is not related to the // login form but has the same username as was entered previously, so we // should not offer saving the password. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_contains_username').value = 'temp';" "document.getElementById('password_contains_username').value = 'random';" "document.getElementById('submit_contains_username').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForDifferentFormWithEmptyAction) { // Log in, see a form on the landing page. That form is not related to the // signin form. The signin and the form on the landing page have empty // actions, so we should offer saving the password. NavigateToFile("/password/navigate_to_same_url_empty_actions.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username').value = 'temp';" "document.getElementById('password').value = 'random';" "document.getElementById('submit-button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptAfterSubmitWithSubFrameNavigation) { NavigateToFile("/password/multi_frames.html"); // Make sure that we prompt to save password even if a sub-frame navigation // happens first. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); observer.SetPathToWaitFor("/password/done.html"); std::string navigate_frame = "var second_iframe = document.getElementById('second_frame');" "second_iframe.contentWindow.location.href = 'other.html';"; std::string fill_and_submit = "var first_frame = document.getElementById('first_frame');" "var frame_doc = first_frame.contentDocument;" "frame_doc.getElementById('username_field').value = 'temp';" "frame_doc.getElementById('password_field').value = 'random';" "frame_doc.getElementById('input_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), navigate_frame)); ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForFailedLoginFromMainFrameWithMultiFramesSameDocument) { NavigateToFile("/password/multi_frames.html"); // Make sure that we don't prompt to save the password for a failed login // from the main frame with multiple frames in the same page. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_failed').value = 'temp';" "document.getElementById('password_failed').value = 'random';" "document.getElementById('submit_failed').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForFailedLoginFromSubFrameWithMultiFramesSameDocument) { NavigateToFile("/password/multi_frames.html"); // Make sure that we don't prompt to save the password for a failed login // from a sub-frame with multiple frames in the same page. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "var first_frame = document.getElementById('first_frame');" "var frame_doc = first_frame.contentDocument;" "frame_doc.getElementById('username_failed').value = 'temp';" "frame_doc.getElementById('password_failed').value = 'random';" "frame_doc.getElementById('submit_failed').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.SetPathToWaitFor("/password/failed.html"); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForXHRSubmit) { NavigateToFile("/password/password_xhr_submit.html"); // Verify that we show the save password prompt if a form returns false // in its onsubmit handler but instead logs in/navigates via XHR. // Note that calling 'submit()' on a form with javascript doesn't call // the onsubmit handler, so we click the submit button instead. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForXHRSubmitWithoutNavigation) { NavigateToFile("/password/password_xhr_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if XHR without navigation occurs and the form has been filled // out we try and save the password. Note that in general the submission // doesn't need to be via form.submit(), but for testing purposes it's // necessary since we otherwise ignore changes made to the value of these // fields by script. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"XHR_FINISHED\"") break; } EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForXHRSubmitWithoutNavigation_SignupForm) { NavigateToFile("/password/password_xhr_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if XHR without navigation occurs and the form has been filled // out we try and save the password. Note that in general the submission // doesn't need to be via form.submit(), but for testing purposes it's // necessary since we otherwise ignore changes made to the value of these // fields by script. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('signup_username_field').value = 'temp';" "document.getElementById('signup_password_field').value = 'random';" "document.getElementById('confirmation_password_field').value = 'random';" "document.getElementById('signup_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"XHR_FINISHED\"") break; } EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForXHRSubmitWithoutNavigationWithUnfilledForm) { NavigateToFile("/password/password_xhr_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if XHR without navigation occurs and the form has NOT been // filled out we don't prompt. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('username_field').value = 'temp';" "document.getElementById('submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"XHR_FINISHED\"") break; } EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForXHRSubmitWithoutNavigationWithUnfilledForm_SignupForm) { NavigateToFile("/password/password_xhr_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if XHR without navigation occurs and the form has NOT been // filled out we don't prompt. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('signup_username_field').value = 'temp';" "document.getElementById('signup_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"XHR_FINISHED\"") break; } EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForFetchSubmit) { NavigateToFile("/password/password_fetch_submit.html"); // Verify that we show the save password prompt if a form returns false // in its onsubmit handler but instead logs in/navigates via Fetch. // Note that calling 'submit()' on a form with javascript doesn't call // the onsubmit handler, so we click the submit button instead. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForFetchSubmitWithoutNavigation) { NavigateToFile("/password/password_fetch_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if XHR without navigation occurs and the form has been filled // out we try and save the password. Note that in general the submission // doesn't need to be via form.submit(), but for testing purposes it's // necessary since we otherwise ignore changes made to the value of these // fields by script. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"FETCH_FINISHED\"") break; } EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForFetchSubmitWithoutNavigation_SignupForm) { NavigateToFile("/password/password_fetch_submit.html"); // Need to pay attention for a message that Fetch has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if Fetch without navigation occurs and the form has been filled // out we try and save the password. Note that in general the submission // doesn't need to be via form.submit(), but for testing purposes it's // necessary since we otherwise ignore changes made to the value of these // fields by script. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('signup_username_field').value = 'temp';" "document.getElementById('signup_password_field').value = 'random';" "document.getElementById('confirmation_password_field').value = 'random';" "document.getElementById('signup_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"FETCH_FINISHED\"") break; } EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForFetchSubmitWithoutNavigationWithUnfilledForm) { NavigateToFile("/password/password_fetch_submit.html"); // Need to pay attention for a message that Fetch has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if Fetch without navigation occurs and the form has NOT been // filled out we don't prompt. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('username_field').value = 'temp';" "document.getElementById('submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"FETCH_FINISHED\"") break; } EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForFetchSubmitWithoutNavigationWithUnfilledForm_SignupForm) { NavigateToFile("/password/password_fetch_submit.html"); // Need to pay attention for a message that Fetch has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; // Verify that if Fetch without navigation occurs and the form has NOT been // filled out we don't prompt. BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "navigate = false;" "document.getElementById('signup_username_field').value = 'temp';" "document.getElementById('signup_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"FETCH_FINISHED\"") break; } EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfLinkClicked) { NavigateToFile("/password/password_form.html"); // Verify that if the user takes a direct action to leave the page, we don't // prompt to save the password even if the form is already filled out. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_click_link = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('link').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_click_link)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, VerifyPasswordGenerationUpload) { // Disable Autofill requesting access to AddressBook data. This causes // the test to hang on Mac. autofill::test::DisableSystemServices(browser()->profile()->GetPrefs()); // Visit a signup form. NavigateToFile("/password/signup_form.html"); // Enter a password and save it. NavigationObserver first_observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('other_info').value = 'stuff';" "document.getElementById('username_field').value = 'my_username';" "document.getElementById('password_field').value = 'password';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); first_observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); // Now navigate to a login form that has similar HTML markup. NavigateToFile("/password/password_form.html"); // Simulate a user click to force an autofill of the form's DOM value, not // just the suggested value. content::SimulateMouseClick(WebContents(), 0, blink::WebMouseEvent::Button::kLeft); WaitForElementValue("username_field", "my_username"); WaitForElementValue("password_field", "password"); // Submit the form and verify that there is no infobar (as the password // has already been saved). NavigationObserver second_observer(WebContents()); BubbleObserver second_prompt_observer(WebContents()); std::string submit_form = "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), submit_form)); second_observer.Wait(); EXPECT_FALSE(second_prompt_observer.IsSavePromptShownAutomatically()); // Verify that we sent two pings to Autofill. One vote for of PASSWORD for // the current form, and one vote for ACCOUNT_CREATION_PASSWORD on the // original form since it has more than 2 text input fields and was used for // the first time on a different form. base::HistogramBase* upload_histogram = base::StatisticsRecorder::FindHistogram( "PasswordGeneration.UploadStarted"); ASSERT_TRUE(upload_histogram); std::unique_ptr<base::HistogramSamples> snapshot = upload_histogram->SnapshotSamples(); EXPECT_EQ(0, snapshot->GetCount(0 /* failure */)); EXPECT_EQ(2, snapshot->GetCount(1 /* success */)); autofill::test::ReenableSystemServices(); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForSubmitFromIframe) { NavigateToFile("/password/password_submit_from_iframe.html"); // Submit a form in an iframe, then cause the whole page to navigate without a // user gesture. We expect the save password prompt to be shown here, because // some pages use such iframes for login forms. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "var iframe = document.getElementById('test_iframe');" "var iframe_doc = iframe.contentDocument;" "iframe_doc.getElementById('username_field').value = 'temp';" "iframe_doc.getElementById('password_field').value = 'random';" "iframe_doc.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForInputElementWithoutName) { // Check that the prompt is shown for forms where input elements lack the // "name" attribute but the "id" is present. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field_no_name').value = 'temp';" "document.getElementById('password_field_no_name').value = 'random';" "document.getElementById('input_submit_button_no_name').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForInputElementWithoutId) { // Check that the prompt is shown for forms where input elements lack the // "id" attribute but the "name" attribute is present. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementsByName('username_field_no_id')[0].value = 'temp';" "document.getElementsByName('password_field_no_id')[0].value = 'random';" "document.getElementsByName('input_submit_button_no_id')[0].click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForInputElementWithoutIdAndName) { // Check that prompt is shown for forms where the input fields lack both // the "id" and the "name" attributes. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "var form = document.getElementById('testform_elements_no_id_no_name');" "var username = form.children[0];" "username.value = 'temp';" "var password = form.children[1];" "password.value = 'random';" "form.children[2].click()"; // form.children[2] is the submit button. ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); // Check that credentials are stored. WaitForPasswordStore(); CheckThatCredentialsStored("temp", "random"); } // Test for checking that no prompt is shown for URLs with file: scheme. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForFileSchemeURLs) { GURL url = GetFileURL("password_form.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForLandingPageWithHTTPErrorStatusCode) { // Check that no prompt is shown for forms where the landing page has // HTTP status 404. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field_http_error').value = 'temp';" "document.getElementById('password_field_http_error').value = 'random';" "document.getElementById('input_submit_button_http_error').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DeleteFrameBeforeSubmit) { NavigateToFile("/password/multi_frames.html"); NavigationObserver observer(WebContents()); // Make sure we save some password info from an iframe and then destroy it. std::string save_and_remove = "var first_frame = document.getElementById('first_frame');" "var frame_doc = first_frame.contentDocument;" "frame_doc.getElementById('username_field').value = 'temp';" "frame_doc.getElementById('password_field').value = 'random';" "frame_doc.getElementById('input_submit_button').click();" "first_frame.parentNode.removeChild(first_frame);"; // Submit from the main frame, but without navigating through the onsubmit // handler. std::string navigate_frame = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click();" "window.location.href = 'done.html';"; ASSERT_TRUE(content::ExecuteScript(WebContents(), save_and_remove)); ASSERT_TRUE(content::ExecuteScript(WebContents(), navigate_frame)); observer.Wait(); // The only thing we check here is that there is no use-after-free reported. } // Get form data for /password/nonplaceholder_username.html autofill::FormData GetPlaceholderUsernameFormData( password_manager::PasswordForm signin_form) { // Build server predictions autofill::FormData form_data; constexpr autofill::FormRendererId form_id(1); form_data.unique_renderer_id = form_id; form_data.name_attribute = u"testform"; form_data.name = form_data.name_attribute; form_data.action = GURL(signin_form.action.spec() + "password/done.html"); form_data.url = signin_form.url; // Username autofill::FormFieldData username_field; username_field.form_control_type = "text"; username_field.id_attribute = u"username_field"; username_field.name = username_field.id_attribute; username_field.value = u"example@example.com"; username_field.label = username_field.value; username_field.unique_renderer_id = autofill::FieldRendererId(1); form_data.fields.push_back(username_field); // Password autofill::FormFieldData password_field; password_field.form_control_type = "password"; password_field.id_attribute = u"password_field"; password_field.name = password_field.id_attribute; password_field.value = u"htmlPass"; password_field.label = password_field.value; password_field.unique_renderer_id = autofill::FieldRendererId(2); form_data.fields.push_back(password_field); return form_data; } // If there is a username and password with prefilled values, do not overwrite // the password if the username does not look like a placeholder value IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NonPlaceholderPasswordNotOverwritten) { // Save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"example@example.com"; signin_form.password_value = u"savedPass"; password_store->AddLogin(signin_form); password_manager::PasswordFormManager:: set_wait_for_server_predictions_for_filling(true); // Get form data autofill::FormData form_data = GetPlaceholderUsernameFormData(signin_form); // Username bool is_placeholder = false; autofill::FormStructure form_structure(form_data); std::vector<FieldPrediction> username_predictions; FieldPrediction username_prediction; username_prediction.set_type(autofill::USERNAME); username_predictions.push_back(username_prediction); form_structure.field(0)->set_server_predictions(username_predictions); form_structure.field(0)->set_may_use_prefilled_placeholder(is_placeholder); // Password std::vector<FieldPrediction> password_predictions; FieldPrediction password_prediction; password_prediction.set_type(autofill::PASSWORD); password_predictions.push_back(password_prediction); form_structure.field(1)->set_server_predictions(password_predictions); // Navigate to the page NavigateToFile("/password/nonplaceholder_username.html"); // Use autofill predictions autofill::ChromeAutofillClient* autofill_client = autofill::ChromeAutofillClient::FromWebContents(WebContents()); autofill_client->PropagateAutofillPredictions(WebContents()->GetMainFrame(), {&form_structure}); // Check original values before interaction CheckElementValue("username_field", "example@example.com"); CheckElementValue("password_field", "htmlPass"); // Have user interact with the page content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); // Now make sure the fields aren't overwritten CheckElementValue("username_field", "example@example.com"); CheckElementValue("password_field", "htmlPass"); } // If there is a username and password with prefilled values, overwrite the // password if the username looks like a placeholder value IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PlaceholderPasswordOverwritten) { // Save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"example@example.com"; signin_form.password_value = u"savedPass"; password_store->AddLogin(signin_form); password_manager::PasswordFormManager:: set_wait_for_server_predictions_for_filling(true); // Get form data autofill::FormData form_data = GetPlaceholderUsernameFormData(signin_form); // Username bool is_placeholder = true; autofill::FormStructure form_structure(form_data); std::vector<FieldPrediction> username_predictions; FieldPrediction username_prediction; username_prediction.set_type(autofill::USERNAME); username_predictions.push_back(username_prediction); form_structure.field(0)->set_server_predictions(username_predictions); form_structure.field(0)->set_may_use_prefilled_placeholder(is_placeholder); // Password std::vector<FieldPrediction> password_predictions; FieldPrediction password_prediction; password_prediction.set_type(autofill::PASSWORD); password_predictions.push_back(password_prediction); form_structure.field(1)->set_server_predictions(password_predictions); // Navigate to the page NavigateToFile("/password/nonplaceholder_username.html"); // Use autofill predictions autofill::ChromeAutofillClient* autofill_client = autofill::ChromeAutofillClient::FromWebContents(WebContents()); autofill_client->PropagateAutofillPredictions(WebContents()->GetMainFrame(), {&form_structure}); // Check original values before interaction CheckElementValue("username_field", "example@example.com"); CheckElementValue("password_field", "htmlPass"); // Have user interact with the page content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); // Now make sure the fields are overwritten CheckElementValue("username_field", "example@example.com"); WaitForElementValue("password_field", "savedPass"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, UsernameAndPasswordValueAccessible) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"admin"; signin_form.password_value = u"12345"; password_store->AddLogin(signin_form); // Steps from https://crbug.com/337429#c37. // Navigate to the page, click a link that opens a second tab, reload the // first tab and observe that the password is accessible. NavigateToFile("/password/form_and_link.html"); // Click on a link to open a new tab, then switch back to the first one. EXPECT_EQ(1, browser()->tab_strip_model()->count()); std::string click = "document.getElementById('testlink').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), click)); EXPECT_EQ(2, browser()->tab_strip_model()->count()); browser()->tab_strip_model()->ActivateTabAt(0); // Reload the original page to have the saved credentials autofilled. NavigationObserver reload_observer(WebContents()); NavigateToFile("/password/form_and_link.html"); reload_observer.Wait(); // Now check that the username and the password are not accessible yet. CheckElementValue("username_field", ""); CheckElementValue("password_field", ""); // Let the user interact with the page. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); // Wait until that interaction causes the username and the password value to // be revealed. WaitForElementValue("username_field", "admin"); WaitForElementValue("password_field", "12345"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PasswordValueAccessibleOnSubmit) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"admin"; signin_form.password_value = u"random_secret"; password_store->AddLogin(signin_form); NavigateToFile("/password/form_and_link.html"); NavigationObserver submit_observer(WebContents()); // Submit the form via a tap on the submit button. content::SimulateMouseClickOrTapElementWithId(WebContents(), "input_submit_button"); submit_observer.Wait(); std::string query = WebContents()->GetURL().query(); EXPECT_THAT(query, testing::HasSubstr("random_secret")); } // Test fix for crbug.com/338650. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DontPromptForPasswordFormWithDefaultValue) { NavigateToFile("/password/password_form_with_default_value.html"); // Don't prompt if we navigate away even if there is a password value since // it's not coming from the user. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); NavigateToFile("/password/done.html"); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DontPromptForPasswordFormWithReadonlyPasswordField) { NavigateToFile("/password/password_form_with_password_readonly.html"); // Fill a form and submit through a <input type="submit"> button. Nothing // special. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptWhenEnableAutomaticPasswordSavingSwitchIsNotSet) { NavigateToFile("/password/password_form.html"); // Fill a form and submit through a <input type="submit"> button. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Test fix for crbug.com/368690. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptWhenReloading) { NavigateToFile("/password/password_form.html"); std::string fill = "document.getElementById('username_redirect').value = 'temp';" "document.getElementById('password_redirect').value = 'random';"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill)); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); GURL url = embedded_test_server()->GetURL("/password/password_form.html"); NavigateParams params(browser(), url, ::ui::PAGE_TRANSITION_RELOAD); ui_test_utils::NavigateToURL(&params); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } // Test that if a form gets dynamically added between the form parsing and // rendering, and while the main frame still loads, it still is registered, and // thus saving passwords from it works. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, FormsAddedBetweenParsingAndRendering) { NavigateToFile("/password/between_parsing_and_rendering.html"); NavigationObserver observer(WebContents()); std::string submit = "document.getElementById('username').value = 'temp';" "document.getElementById('password').value = 'random';" "document.getElementById('submit-button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), submit)); observer.Wait(); EXPECT_TRUE(BubbleObserver(WebContents()).IsSavePromptShownAutomatically()); } // Test that if a hidden form gets dynamically added between the form parsing // and rendering, it still is registered, and autofilling works. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, HiddenFormAddedBetweenParsingAndRendering) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"admin"; signin_form.password_value = u"12345"; password_store->AddLogin(signin_form); NavigateToFile("/password/between_parsing_and_rendering.html?hidden"); std::string show_form = "document.getElementsByTagName('form')[0].style.display = 'block'"; ASSERT_TRUE(content::ExecuteScript(WebContents(), show_form)); // Wait until the username is filled, to make sure autofill kicked in. WaitForElementValue("username", "admin"); WaitForElementValue("password", "12345"); } // https://crbug.com/713645 // Navigate to a page that can't load some of the subresources. Create a hidden // form when the body is loaded. Make the form visible. Chrome should autofill // the form. // The fact that the form is hidden isn't super important but reproduces the // actual bug. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SlowPageFill) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"admin"; signin_form.password_value = u"12345"; password_store->AddLogin(signin_form); GURL url = embedded_test_server()->GetURL("/password/infinite_password_form.html"); ui_test_utils::NavigateToURLWithDisposition( browser(), url, WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE); // Wait for autofill. BubbleObserver bubble_observer(WebContents()); bubble_observer.WaitForManagementState(); // Show the form and make sure that the password was autofilled. std::string show_form = "document.getElementsByTagName('form')[0].style.display = 'block'"; ASSERT_TRUE(content::ExecuteScript(WebContents(), show_form)); CheckElementValue("username", "admin"); CheckElementValue("password", "12345"); } // Test that if there was no previous page load then the PasswordManagerDriver // does not think that there were SSL errors on the current page. The test opens // a new tab with a URL for which the embedded test server issues a basic auth // challenge. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoLastLoadGoodLastLoad) { // We must use a new test server here because embedded_test_server() is // already started at this point and adding the request handler to it would // not be thread safe. net::EmbeddedTestServer http_test_server; // Teach the embedded server to handle requests by issuing the basic auth // challenge. http_test_server.RegisterRequestHandler( base::BindRepeating(&HandleTestAuthRequest)); ASSERT_TRUE(http_test_server.Start()); LoginPromptBrowserTestObserver login_observer; // We need to register to all sources, because the navigation observer we are // interested in is for a new tab to be opened, and thus does not exist yet. login_observer.Register(content::NotificationService::AllSources()); password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); ASSERT_TRUE(password_store->IsEmpty()); content::NavigationController* nav_controller = &WebContents()->GetController(); WindowedAuthNeededObserver auth_needed_observer(nav_controller); // Navigate to a page requiring HTTP auth. ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), http_test_server.GetURL("/basic_auth"))); auth_needed_observer.Wait(); WindowedAuthSuppliedObserver auth_supplied_observer(nav_controller); // Offer valid credentials on the auth challenge. ASSERT_EQ(1u, login_observer.handlers().size()); LoginHandler* handler = *login_observer.handlers().begin(); ASSERT_TRUE(handler); NavigationObserver nav_observer(WebContents()); // Any username/password will work. handler->SetAuth(u"user", u"pwd"); auth_supplied_observer.Wait(); // The password manager should be working correctly. nav_observer.Wait(); WaitForPasswordStore(); BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); bubble_observer.AcceptSavePrompt(); // Spin the message loop to make sure the password store had a chance to save // the password. WaitForPasswordStore(); EXPECT_FALSE(password_store->IsEmpty()); } // Fill out a form and click a button. The Javascript removes the form, creates // a similar one with another action, fills it out and submits. Chrome can // manage to detect the new one and create a complete matching // PasswordFormManager. Otherwise, the all-but-action matching PFM should be // used. Regardless of the internals the user sees the bubble in 100% cases. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PreferPasswordFormManagerWhichFinishedMatching) { NavigateToFile("/password/create_form_copy_on_submit.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string submit = "document.getElementById('username').value = 'overwrite_me';" "document.getElementById('password').value = 'random';" "document.getElementById('non-form-button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), submit)); observer.Wait(); WaitForPasswordStore(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Tests whether a attempted submission of a malicious credentials gets blocked. // This simulates a case which is described in http://crbug.com/571580. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, NoPromptForSeparateLoginFormWhenSwitchingFromHttpsToHttp) { std::string path = "/password/password_form.html"; GURL https_url(https_test_server().GetURL(path)); ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme)); NavigationObserver form_observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), https_url)); form_observer.Wait(); std::string fill_and_submit_redirect = "document.getElementById('username_redirect').value = 'user';" "document.getElementById('password_redirect').value = 'password';" "document.getElementById('submit_redirect').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit_redirect)); NavigationObserver redirect_observer(WebContents()); redirect_observer.SetPathToWaitFor("/password/redirect.html"); redirect_observer.Wait(); BubbleObserver prompt_observer(WebContents()); prompt_observer.WaitForAutomaticSavePrompt(); // Normally the redirect happens to done.html. Here an attack is simulated // that hijacks the redirect to a attacker controlled page. GURL http_url( embedded_test_server()->GetURL("/password/simple_password.html")); std::string attacker_redirect = "window.location.href = '" + http_url.spec() + "';"; ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), attacker_redirect)); NavigationObserver attacker_observer(WebContents()); attacker_observer.SetPathToWaitFor("/password/simple_password.html"); attacker_observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); std::string fill_and_submit_attacker_form = "document.getElementById('username_field').value = 'attacker_username';" "document.getElementById('password_field').value = 'attacker_password';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE( content::ExecuteScript(WebContents(), fill_and_submit_attacker_form)); NavigationObserver done_observer(WebContents()); done_observer.SetPathToWaitFor("/password/done.html"); done_observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); // Wait for password store and check that credentials are stored. WaitForPasswordStore(); CheckThatCredentialsStored("user", "password"); } // Tests that after HTTP -> HTTPS migration the credential is autofilled. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, HttpMigratedCredentialAutofilled) { // Add an http credential to the password store. GURL https_origin = https_test_server().base_url(); ASSERT_TRUE(https_origin.SchemeIs(url::kHttpsScheme)); GURL::Replacements rep; rep.SetSchemeStr(url::kHttpScheme); GURL http_origin = https_origin.ReplaceComponents(rep); password_manager::PasswordForm http_form; http_form.signon_realm = http_origin.spec(); http_form.url = http_origin; // Assume that the previous action was already HTTPS one matching the current // page. http_form.action = https_origin; http_form.username_value = u"user"; http_form.password_value = u"12345"; password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_store->AddLogin(http_form); NavigationObserver form_observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), https_test_server().GetURL("/password/password_form.html"))); form_observer.Wait(); WaitForPasswordStore(); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("username_field", "user"); WaitForElementValue("password_field", "12345"); } // Tests that obsolete HTTP credentials are moved when a site migrated to HTTPS // and has HSTS enabled. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ObsoleteHttpCredentialMovedOnMigrationToHstsSite) { // Add an http credential to the password store. GURL https_origin = https_test_server().base_url(); ASSERT_TRUE(https_origin.SchemeIs(url::kHttpsScheme)); GURL::Replacements rep; rep.SetSchemeStr(url::kHttpScheme); GURL http_origin = https_origin.ReplaceComponents(rep); password_manager::PasswordForm http_form; http_form.signon_realm = http_origin.spec(); http_form.url = http_origin; http_form.username_value = u"user"; http_form.password_value = u"12345"; password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_store->AddLogin(http_form); // Treat the host of the HTTPS test server as HSTS. AddHSTSHost(https_test_server().host_port_pair().host()); // Navigate to HTTPS page and trigger the migration. NavigationObserver form_observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), https_test_server().GetURL("/password/password_form.html"))); form_observer.Wait(); // Issue the query for HTTPS credentials. WaitForPasswordStore(); // Realize there are no HTTPS credentials and issue the query for HTTP // credentials instead. WaitForPasswordStore(); // Sync with IO thread before continuing. This is necessary, because the // credential migration triggers a query for the HSTS state which gets // executed on the IO thread. The actual task is empty, because only the reply // is relevant. By the time the reply is executed it is guaranteed that the // migration is completed. base::RunLoop run_loop; content::GetIOThreadTaskRunner({})->PostTaskAndReply( FROM_HERE, base::BindOnce([]() {}), run_loop.QuitClosure()); run_loop.Run(); // Migration updates should touch the password store. WaitForPasswordStore(); // Only HTTPS passwords should be present. EXPECT_TRUE( password_store->stored_passwords().at(http_origin.spec()).empty()); EXPECT_FALSE( password_store->stored_passwords().at(https_origin.spec()).empty()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptWhenPasswordFormWithoutUsernameFieldSubmitted) { password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); EXPECT_TRUE(password_store->IsEmpty()); NavigateToFile("/password/form_with_only_password_field.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string submit = "document.getElementById('password').value = 'password';" "document.getElementById('submit-button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); WaitForPasswordStore(); EXPECT_FALSE(password_store->IsEmpty()); } // Test that if a form gets autofilled, then it gets autofilled on re-creation // as well. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ReCreatedFormsGetFilled) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"temp"; signin_form.password_value = u"random"; password_store->AddLogin(signin_form); NavigateToFile("/password/dynamic_password_form.html"); const std::string create_form = "document.getElementById('create_form_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), create_form)); // Wait until the username is filled, to make sure autofill kicked in. WaitForElementValue("username_id", "temp"); // Now the form gets deleted and created again. It should get autofilled // again. const std::string delete_form = "var form = document.getElementById('dynamic_form_id');" "form.parentNode.removeChild(form);"; ASSERT_TRUE(content::ExecuteScript(WebContents(), delete_form)); ASSERT_TRUE(content::ExecuteScript(WebContents(), create_form)); WaitForElementValue("username_id", "temp"); } // Test that if the same dynamic form is created multiple times then all of them // are autofilled. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DuplicateFormsGetFilled) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"temp"; signin_form.password_value = u"random"; password_store->AddLogin(signin_form); NavigateToFile("/password/recurring_dynamic_form.html"); ASSERT_TRUE(content::ExecuteScript(WebContents(), "addForm();")); // Wait until the username is filled, to make sure autofill kicked in. WaitForJsElementValue("document.body.children[0].children[0]", "temp"); WaitForJsElementValue("document.body.children[0].children[1]", "random"); // Add one more form. ASSERT_TRUE(content::ExecuteScript(WebContents(), "addForm();")); // Wait until the username is filled, to make sure autofill kicked in. WaitForJsElementValue("document.body.children[1].children[0]", "temp"); WaitForJsElementValue("document.body.children[1].children[1]", "random"); } // Test that an autofilled credential is deleted then the password manager // doesn't try to resurrect it on navigation. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DeletedPasswordIsNotRevived) { // At first let us save a credential to the password store. password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.action = embedded_test_server()->base_url(); signin_form.username_value = u"admin"; signin_form.password_value = u"1234"; password_store->AddLogin(signin_form); NavigateToFile("/password/password_form.html"); // Let the user interact with the page. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); // Wait until that interaction causes the username and the password value to // be revealed. WaitForElementValue("username_field", "admin"); // Now the credential is removed via the settings or the bubble. password_store->RemoveLogin(signin_form); WaitForPasswordStore(); // Submit the form. It shouldn't revive the credential in the store. NavigationObserver observer(WebContents()); ASSERT_TRUE(content::ExecuteScript( WebContents(), "document.getElementById('input_submit_button').click()")); observer.Wait(); WaitForPasswordStore(); EXPECT_TRUE(password_store->IsEmpty()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForPushStateWhenFormDisappears) { NavigateToFile("/password/password_push_state.html"); // Verify that we show the save password prompt if 'history.pushState()' // is called after form submission is suppressed by, for example, calling // preventDefault() in a form's submit event handler. // Note that calling 'submit()' on a form with javascript doesn't call // the onsubmit handler, so we click the submit button instead. // Also note that the prompt will only show up if the form disappers // after submission NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Similar to the case above, but this time the form persists after // 'history.pushState()'. And save password prompt should not show up // in this case. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForPushStateWhenFormPersists) { NavigateToFile("/password/password_push_state.html"); // Set |should_delete_testform| to false to keep submitted form visible after // history.pushsTate(); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "should_delete_testform = false;" "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } // The password manager should distinguish forms with empty actions. After // successful login, the login form disappears, but the another one shouldn't be // recognized as the login form. The save prompt should appear. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForPushStateWhenFormWithEmptyActionDisappears) { NavigateToFile("/password/password_push_state.html"); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('ea_username_field').value = 'temp';" "document.getElementById('ea_password_field').value = 'random';" "document.getElementById('ea_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Similar to the case above, but this time the form persists after // 'history.pushState()'. The password manager should find the login form even // if the action of the form is empty. Save password prompt should not show up. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForPushStateWhenFormWithEmptyActionPersists) { NavigateToFile("/password/password_push_state.html"); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "should_delete_testform = false;" "document.getElementById('ea_username_field').value = 'temp';" "document.getElementById('ea_password_field').value = 'random';" "document.getElementById('ea_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } // Current and target URLs contain different parameters and references. This // test checks that parameters and references in origins are ignored for // form origin comparison. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, PromptForPushStateWhenFormDisappears_ParametersInOrigins) { NavigateToFile("/password/password_push_state.html?login#r"); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "add_parameters_to_target_url = true;" "document.getElementById('pa_username_field').value = 'temp';" "document.getElementById('pa_password_field').value = 'random';" "document.getElementById('pa_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Similar to the case above, but this time the form persists after // 'history.pushState()'. The password manager should find the login form even // if target and current URLs contain different parameters or references. // Save password prompt should not show up. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForPushStateWhenFormPersists_ParametersInOrigins) { NavigateToFile("/password/password_push_state.html?login#r"); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "should_delete_testform = false;" "add_parameters_to_target_url = true;" "document.getElementById('pa_username_field').value = 'temp';" "document.getElementById('pa_password_field').value = 'random';" "document.getElementById('pa_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, InFrameNavigationDoesNotClearPopupState) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"random123"; password_store->AddLogin(signin_form); NavigateToFile("/password/password_form.html"); // Mock out the AutofillClient so we know how long to wait. Unfortunately // there isn't otherwise a good event to wait on to verify that the popup // would have been shown. password_manager::ContentPasswordManagerDriverFactory* driver_factory = password_manager::ContentPasswordManagerDriverFactory::FromWebContents( WebContents()); ObservingAutofillClient::CreateForWebContents(WebContents()); ObservingAutofillClient* observing_autofill_client = ObservingAutofillClient::FromWebContents(WebContents()); password_manager::ContentPasswordManagerDriver* driver = driver_factory->GetDriverForFrame(WebContents()->GetMainFrame()); driver->GetPasswordAutofillManager()->set_autofill_client( observing_autofill_client); // Trigger in page navigation. std::string in_page_navigate = "location.hash = '#blah';"; ASSERT_TRUE(content::ExecJs(RenderFrameHost(), in_page_navigate, content::EXECUTE_SCRIPT_NO_USER_GESTURE)); // Click on the username field to display the popup. content::SimulateMouseClickOrTapElementWithId(WebContents(), "username_field"); // Make sure the popup would be shown. observing_autofill_client->WaitForAutofillPopup(); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdFormBubbleShown) { NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('chg_username_field').value = 'temp';" "document.getElementById('chg_password_field').value = 'random';" "document.getElementById('chg_new_password_1').value = 'random1';" "document.getElementById('chg_new_password_2').value = 'random1';" "document.getElementById('chg_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdFormPushStateBubbleShown) { NavigateToFile("/password/password_push_state.html"); NavigationObserver observer(WebContents()); observer.set_quit_on_entry_committed(true); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('chg_username_field').value = 'temp';" "document.getElementById('chg_password_field').value = 'random';" "document.getElementById('chg_new_password_1').value = 'random1';" "document.getElementById('chg_new_password_2').value = 'random1';" "document.getElementById('chg_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptOnBack) { // Go to a successful landing page through submitting first, so that it is // reachable through going back, and the remembered page transition is form // submit. There is no need to submit non-empty strings. NavigateToFile("/password/password_form.html"); NavigationObserver dummy_submit_observer(WebContents()); std::string just_submit = "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), just_submit)); dummy_submit_observer.Wait(); // Now go to a page with a form again, fill the form, and go back instead of // submitting it. NavigateToFile("/password/dummy_submit.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); // The (dummy) submit is necessary to provisionally save the typed password. // A user typing in the password field would not need to submit to // provisionally save it, but the script cannot trigger that just by // assigning to the field's value. std::string fill_and_back = "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click();" "window.history.back();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_back)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } // Regression test for http://crbug.com/452306 IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangingTextToPasswordFieldOnSignupForm) { NavigateToFile("/password/signup_form.html"); // In this case, pretend that username_field is actually a password field // that starts as a text field to simulate placeholder. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string change_and_submit = "document.getElementById('other_info').value = 'username';" "document.getElementById('username_field').type = 'password';" "document.getElementById('username_field').value = 'mypass';" "document.getElementById('password_field').value = 'mypass';" "document.getElementById('testform').submit();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), change_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Regression test for http://crbug.com/451631 IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SavingOnManyPasswordFieldsTest) { // Simulate Macy's registration page, which contains the normal 2 password // fields for confirming the new password plus 2 more fields for security // questions and credit card. Make sure that saving works correctly for such // sites. NavigateToFile("/password/many_password_signup_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'username';" "document.getElementById('password_field').value = 'mypass';" "document.getElementById('confirm_field').value = 'mypass';" "document.getElementById('security_answer').value = 'hometown';" "document.getElementById('SSN').value = '1234';" "document.getElementById('testform').submit();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SaveWhenIFrameDestroyedOnFormSubmit) { NavigateToFile("/password/frame_detached_on_submit.html"); // Need to pay attention for a message that XHR has finished since there // is no navigation to wait for. content::DOMMessageQueue message_queue; BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "var iframe = document.getElementById('login_iframe');" "var frame_doc = iframe.contentDocument;" "frame_doc.getElementById('username_field').value = 'temp';" "frame_doc.getElementById('password_field').value = 'random';" "frame_doc.getElementById('submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); std::string message; while (message_queue.WaitForMessage(&message)) { if (message == "\"SUBMISSION_FINISHED\"") break; } EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } // Check that a username and password are filled into forms in iframes // that don't share the security origin with the main frame, but have PSL // matched origins. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PSLMatchedCrossSiteFillTest) { GURL main_frame_url = embedded_test_server()->GetURL( "www.foo.com", "/password/password_form_in_crosssite_iframe.html"); NavigationObserver observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url)); observer.Wait(); // Create an iframe and navigate cross-site. NavigationObserver iframe_observer(WebContents()); iframe_observer.SetPathToWaitFor("/password/crossite_iframe_content.html"); GURL iframe_url = embedded_test_server()->GetURL( "abc.foo.com", "/password/crossite_iframe_content.html"); std::string create_iframe = base::StringPrintf("create_iframe('%s');", iframe_url.spec().c_str()); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), create_iframe)); iframe_observer.Wait(); // Store a password for autofill later. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = iframe_url.DeprecatedGetOriginAsURL().spec(); signin_form.url = iframe_url; signin_form.username_value = u"temp"; signin_form.password_value = u"pa55w0rd"; password_store->AddLogin(signin_form); WaitForPasswordStore(); // Visit the form again. NavigationObserver reload_observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url)); reload_observer.Wait(); NavigationObserver iframe_observer_2(WebContents()); iframe_observer_2.SetPathToWaitFor("/password/crossite_iframe_content.html"); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), create_iframe)); iframe_observer_2.Wait(); // Simulate the user interaction in the iframe which should trigger autofill. // Click in the middle of the frame to avoid the border. content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe"); std::string username_field; std::string password_field; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), "sendMessage('get_username');", &username_field)); ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), "sendMessage('get_password');", &password_field)); // Verify username and password have not been autofilled due to an insecure // origin. EXPECT_TRUE(username_field.empty()); EXPECT_TRUE(password_field.empty()); } // Check that a username and password are not filled in forms in iframes // that don't have PSL matched origins. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PSLUnMatchedCrossSiteFillTest) { GURL main_frame_url = embedded_test_server()->GetURL( "www.foo.com", "/password/password_form_in_crosssite_iframe.html"); NavigationObserver observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url)); observer.Wait(); // Create an iframe and navigate cross-site. NavigationObserver iframe_observer(WebContents()); iframe_observer.SetPathToWaitFor("/password/crossite_iframe_content.html"); GURL iframe_url = embedded_test_server()->GetURL( "www.bar.com", "/password/crossite_iframe_content.html"); std::string create_iframe = base::StringPrintf("create_iframe('%s');", iframe_url.spec().c_str()); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), create_iframe)); iframe_observer.Wait(); // Store a password for autofill later. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = iframe_url.DeprecatedGetOriginAsURL().spec(); signin_form.url = iframe_url; signin_form.username_value = u"temp"; signin_form.password_value = u"pa55w0rd"; password_store->AddLogin(signin_form); WaitForPasswordStore(); // Visit the form again. NavigationObserver reload_observer(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url)); reload_observer.Wait(); NavigationObserver iframe_observer_2(WebContents()); iframe_observer_2.SetPathToWaitFor("/password/crossite_iframe_content.html"); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture(RenderFrameHost(), create_iframe)); iframe_observer_2.Wait(); // Simulate the user interaction in the iframe which should trigger autofill. // Click in the middle of the frame to avoid the border. content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe"); // Verify username is not autofilled std::string empty_username; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), "sendMessage('get_username');", &empty_username)); EXPECT_EQ("", empty_username); // Verify password is not autofilled std::string empty_password; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), "sendMessage('get_password');", &empty_password)); EXPECT_EQ("", empty_password); } // Check that a password form in an iframe of same origin will not be // filled in until user interact with the iframe. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SameOriginIframeAutoFillTest) { // Visit the sign-up form to store a password for autofill later NavigateToFile("/password/password_form_in_same_origin_iframe.html"); NavigationObserver observer(WebContents()); observer.SetPathToWaitFor("/password/done.html"); std::string submit = "var ifrmDoc = document.getElementById('iframe').contentDocument;" "ifrmDoc.getElementById('username_field').value = 'temp';" "ifrmDoc.getElementById('password_field').value = 'pa55w0rd';" "ifrmDoc.getElementById('input_submit_button').click();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), submit)); observer.Wait(); BubbleObserver prompt_observer(WebContents()); prompt_observer.WaitForAutomaticSavePrompt(); prompt_observer.AcceptSavePrompt(); // Visit the form again NavigationObserver reload_observer(WebContents()); NavigateToFile("/password/password_form_in_same_origin_iframe.html"); reload_observer.Wait(); // Verify password and username are not accessible yet. CheckElementValue("iframe", "username_field", ""); CheckElementValue("iframe", "password_field", ""); // Simulate the user interaction in the iframe which should trigger autofill. // Click in the middle of the username to avoid the border. ASSERT_TRUE(content::ExecJs( RenderFrameHost(), "var usernameRect = document.getElementById(" "'iframe').contentDocument.getElementById('username_field')" ".getBoundingClientRect();", content::EXECUTE_SCRIPT_NO_USER_GESTURE)); int y = content::EvalJs(RenderFrameHost(), "usernameRect.top + usernameRect.bottom;", content::EXECUTE_SCRIPT_NO_USER_GESTURE) .ExtractInt(); int x = content::EvalJs(RenderFrameHost(), "usernameRect.left + usernameRect.right;", content::EXECUTE_SCRIPT_NO_USER_GESTURE) .ExtractInt(); content::SimulateMouseClickAt(WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(x / 2, y / 2)); // Verify username and password have been autofilled WaitForElementValue("iframe", "username_field", "temp"); WaitForElementValue("iframe", "password_field", "pa55w0rd"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdNoAccountStored) { NavigateToFile("/password/password_form.html"); // Fill a form and submit through a <input type="submit"> button. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('chg_password_wo_username_field').value = " "'old_pw';" "document.getElementById('chg_new_password_wo_username_1').value = " "'new_pw';" "document.getElementById('chg_new_password_wo_username_2').value = " "'new_pw';" "document.getElementById('chg_submit_wo_username_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // No credentials stored before, so save bubble is shown. EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); // Check that credentials are stored. WaitForPasswordStore(); CheckThatCredentialsStored("", "new_pw"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwd1AccountStored) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = u"pw"; signin_form.username_value = u"temp"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit_change_password = "document.getElementById('chg_password_wo_username_field').value = " "'random';" "document.getElementById('chg_new_password_wo_username_1').value = " "'new_pw';" "document.getElementById('chg_new_password_wo_username_2').value = " "'new_pw';" "document.getElementById('chg_submit_wo_username_button').click()"; ASSERT_TRUE( content::ExecuteScript(WebContents(), fill_and_submit_change_password)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); // We emulate that the user clicks "Update" button. prompt_observer.AcceptUpdatePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "new_pw"); } // This fixture disable autofill. If a password is autofilled, then all the // Javascript changes are discarded and test below would not be able to feed a // new password to the form. class PasswordManagerBrowserTestWithAutofillDisabled : public PasswordManagerBrowserTest { public: PasswordManagerBrowserTestWithAutofillDisabled() { feature_list_.InitAndEnableFeature(features::kFillOnAccountSelect); } private: base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithAutofillDisabled, PasswordOverriddenUpdateBubbleShown) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"pw"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'new_pw';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // The stored password "pw" was overridden with "new_pw", so update prompt is // expected. EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); prompt_observer.AcceptUpdatePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "new_pw"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PasswordNotOverriddenUpdateBubbleNotShown) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"pw"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'pw';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // The stored password "pw" was not overridden, so update prompt is not // expected. EXPECT_FALSE(prompt_observer.IsUpdatePromptShownAutomatically()); CheckThatCredentialsStored("temp", "pw"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, MultiplePasswordsWithPasswordSelectionEnabled) { NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); // It is important that these 3 passwords are different. Because if two of // them are the same, it is going to be treated as a password update and the // dropdown will not be shown. std::string fill_and_submit = "document.getElementById('chg_password_wo_username_field').value = " "'pass1';" "document.getElementById('chg_new_password_wo_username_1').value = " "'pass2';" "document.getElementById('chg_new_password_wo_username_2').value = " "'pass3';" "document.getElementById('chg_submit_wo_username_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // 3 possible passwords are going to be shown in a dropdown when the password // selection feature is enabled. The first one will be selected as the main // password by default. All three will be in the all_possible_passwords // list. The save password prompt is expected. BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); EXPECT_EQ(u"pass1", ManagePasswordsUIController::FromWebContents(WebContents()) ->GetPendingPassword() .password_value); EXPECT_THAT( ManagePasswordsUIController::FromWebContents(WebContents()) ->GetPendingPassword() .all_possible_passwords, ElementsAre( ValueElementPair(u"pass1", u"chg_password_wo_username_field"), ValueElementPair(u"pass2", u"chg_new_password_wo_username_1"), ValueElementPair(u"pass3", u"chg_new_password_wo_username_2"))); bubble_observer.AcceptSavePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("", "pass1"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdWhenTheFormContainNotUsernameTextfield) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = u"pw"; signin_form.username_value = u"temp"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit_change_password = "document.getElementById('chg_text_field').value = '3';" "document.getElementById('chg_password_withtext_field').value" " = 'random';" "document.getElementById('chg_new_password_withtext_username_1').value" " = 'new_pw';" "document.getElementById('chg_new_password_withtext_username_2').value" " = 'new_pw';" "document.getElementById('chg_submit_withtext_button').click()"; ASSERT_TRUE( content::ExecuteScript(WebContents(), fill_and_submit_change_password)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); prompt_observer.AcceptUpdatePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "new_pw"); } // Test whether the password form with the username and password fields having // ambiguity in id attribute gets autofilled correctly. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, AutofillSuggestionsForPasswordFormWithAmbiguousIdAttribute) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having ambiguous Ids for username and // password fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("ambiguous_form", 0 /* elements_index */, "myusername"); WaitForElementValue("ambiguous_form", 1 /* elements_index */, "mypassword"); } // Test whether the password form having username and password fields without // name and id attribute gets autofilled correctly. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, AutofillSuggestionsForPasswordFormWithoutNameOrIdAttribute) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having no Ids for username and password // fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("no_name_id_form", 0 /* elements_index */, "myusername"); WaitForElementValue("no_name_id_form", 1 /* elements_index */, "mypassword"); } // Test whether the change password form having username and password fields // without name and id attribute gets autofilled correctly. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AutofillSuggestionsForChangePwdWithEmptyNames) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having no Ids for username and password // fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("change_pwd_but_no_autocomplete", 0 /* elements_index */, "myusername"); WaitForElementValue("change_pwd_but_no_autocomplete", 1 /* elements_index */, "mypassword"); std::string get_new_password = "window.domAutomationController.send(" " document.getElementById(" " 'change_pwd_but_no_autocomplete').elements[2].value);"; std::string new_password; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), get_new_password, &new_password)); EXPECT_EQ("", new_password); } // Test whether the change password form having username and password fields // with empty names but having |autocomplete='current-password'| gets autofilled // correctly. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, AutofillSuggestionsForChangePwdWithEmptyNamesAndAutocomplete) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having no Ids for username and password // fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("change_pwd", 0 /* elements_index */, "myusername"); WaitForElementValue("change_pwd", 1 /* elements_index */, "mypassword"); std::string get_new_password = "window.domAutomationController.send(" " document.getElementById('change_pwd').elements[2].value);"; std::string new_password; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), get_new_password, &new_password)); EXPECT_EQ("", new_password); } // Test whether the change password form having username and password fields // with empty names but having only new password fields having // |autocomplete='new-password'| atrribute do not get autofilled. IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, AutofillSuggestionsForChangePwdWithEmptyNamesButOnlyNewPwdField) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having no Ids for username and password // fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); std::string get_username = "window.domAutomationController.send(" " document.getElementById(" " 'change_pwd_but_no_old_pwd').elements[0].value);"; std::string actual_username; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), get_username, &actual_username)); EXPECT_EQ("", actual_username); std::string get_new_password = "window.domAutomationController.send(" " document.getElementById(" " 'change_pwd_but_no_old_pwd').elements[1].value);"; std::string new_password; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), get_new_password, &new_password)); EXPECT_EQ("", new_password); std::string get_retype_password = "window.domAutomationController.send(" " document.getElementById(" " 'change_pwd_but_no_old_pwd').elements[2].value);"; std::string retyped_password; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), get_retype_password, &retyped_password)); EXPECT_EQ("", retyped_password); } // When there are multiple HttpAuthObservers (e.g., multiple HTTP auth dialogs // as in http://crbug.com/537823), ensure that credentials from PasswordStore // distributed to them are filtered by the realm. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, BasicAuthSeparateRealms) { // We must use a new test server here because embedded_test_server() is // already started at this point and adding the request handler to it would // not be thread safe. net::EmbeddedTestServer http_test_server; http_test_server.RegisterRequestHandler( base::BindRepeating(&HandleTestAuthRequest)); ASSERT_TRUE(http_test_server.Start()); // Save credentials for "test realm" in the store. password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm creds; creds.scheme = password_manager::PasswordForm::Scheme::kBasic; creds.signon_realm = http_test_server.base_url().spec() + "test realm"; creds.password_value = u"pw"; creds.username_value = u"temp"; password_store->AddLogin(creds); WaitForPasswordStore(); ASSERT_FALSE(password_store->IsEmpty()); // In addition to the HttpAuthObserver created automatically for the HTTP // auth dialog, also create a mock observer, for a different realm. MockHttpAuthObserver mock_login_model_observer; HttpAuthManager* httpauth_manager = ChromePasswordManagerClient::FromWebContents(WebContents()) ->GetHttpAuthManager(); password_manager::PasswordForm other_form(creds); other_form.signon_realm = "https://example.com/other realm"; httpauth_manager->SetObserverAndDeliverCredentials(&mock_login_model_observer, other_form); // The mock observer should not receive the stored credentials. EXPECT_CALL(mock_login_model_observer, OnAutofillDataAvailable(_, _)) .Times(0); // Now wait until the navigation to the test server causes a HTTP auth dialog // to appear. content::NavigationController* nav_controller = &WebContents()->GetController(); WindowedAuthNeededObserver auth_needed_observer(nav_controller); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), http_test_server.GetURL("/basic_auth"))); auth_needed_observer.Wait(); // The auth dialog caused a query to PasswordStore, make sure it was // processed. WaitForPasswordStore(); httpauth_manager->DetachObserver(&mock_login_model_observer); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ProxyAuthFilling) { GURL test_page = embedded_test_server()->GetURL("/auth-basic"); // Save credentials for "testrealm" in the store. password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm creds; creds.scheme = password_manager::PasswordForm::Scheme::kBasic; creds.url = test_page; creds.signon_realm = embedded_test_server()->base_url().spec() + "testrealm"; creds.password_value = u"pw"; creds.username_value = u"temp"; password_store->AddLogin(creds); content::NavigationController* controller = &WebContents()->GetController(); WindowedAuthNeededObserver auth_needed_waiter(controller); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page)); auth_needed_waiter.Wait(); BubbleObserver(WebContents()).WaitForManagementState(); } // Test whether the password form which is loaded as hidden is autofilled // correctly. This happens very often in situations when in order to sign-in the // user clicks a sign-in button and a hidden passsword form becomes visible. // This test differs from AutofillSuggestionsForProblematicPasswordForm in that // the form is hidden and in that test only some fields are hidden. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AutofillSuggestionsHiddenPasswordForm) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the hidden password form and verify whether username and // password is autofilled. NavigateToFile("/password/password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling the password. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("hidden_password_form_username", "myusername"); WaitForElementValue("hidden_password_form_password", "mypassword"); } // Test whether the password form with the problematic invisible password field // gets autofilled correctly. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AutofillSuggestionsForProblematicPasswordForm) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form with a hidden password field and verify // whether username and password is autofilled. NavigateToFile("/password/password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling the password. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("form_with_hidden_password_username", "myusername"); WaitForElementValue("form_with_hidden_password_password", "mypassword"); } // Test whether the password form with the problematic invisible password field // in ambiguous password form gets autofilled correctly. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AutofillSuggestionsForProblematicAmbiguousPasswordForm) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm login_form; login_form.signon_realm = embedded_test_server()->base_url().spec(); login_form.action = embedded_test_server()->GetURL("/password/done.html"); login_form.username_value = u"myusername"; login_form.password_value = u"mypassword"; password_store->AddLogin(login_form); // Now, navigate to the password form having ambiguous Ids for username and // password fields and verify whether username and password is autofilled. NavigateToFile("/password/ambiguous_password_form.html"); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("hidden_password_form", 0 /* elements_index */, "myusername"); WaitForElementValue("hidden_password_form", 2 /* elements_index */, "mypassword"); } // Check that the internals page contains logs from the renderer. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, InternalsPage_Renderer) { // Open the internals page. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("chrome://password-manager-internals"), WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* internals_web_contents = WebContents(); // The renderer is supposed to ask whether logging is available. To avoid // race conditions between the answer "Logging is available" arriving from // the browser and actual logging callsites reached in the renderer, open // first an arbitrary page to ensure that the renderer queries the // availability of logging and has enough time to receive the answer. ui_test_utils::NavigateToURLWithDisposition( browser(), embedded_test_server()->GetURL("/password/done.html"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* forms_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); // Now navigate to another page, containing some forms, so that the renderer // attempts to log. It should be a different page than the current one, // because just reloading the current one sometimes confused the Wait() call // and lead to timeouts (https://crbug.com/804398). NavigationObserver observer(forms_web_contents); ui_test_utils::NavigateToURLWithDisposition( browser(), embedded_test_server()->GetURL("/password/password_form.html"), WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); observer.Wait(); std::string find_logs = "var text = document.getElementById('log-entries').innerText;" "var logs_found = /PasswordAutofillAgent::/.test(text);" "window.domAutomationController.send(logs_found);"; bool logs_found = false; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractBool( internals_web_contents->GetMainFrame(), find_logs, &logs_found)); EXPECT_TRUE(logs_found); } // Check that the internals page contains logs from the browser. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, InternalsPage_Browser) { ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("chrome://password-manager-internals"), WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* internals_web_contents = WebContents(); ui_test_utils::NavigateToURLWithDisposition( browser(), embedded_test_server()->GetURL("/password/password_form.html"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); std::string find_logs = "var text = document.getElementById('log-entries').innerText;" "var logs_found = /PasswordManager::/.test(text);" "window.domAutomationController.send(logs_found);"; bool logs_found = false; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractBool( internals_web_contents->GetMainFrame(), find_logs, &logs_found)); EXPECT_TRUE(logs_found); } // Tests that submitted credentials are saved on a password form without // username element when there are no stored credentials. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PasswordRetryFormSaveNoUsernameCredentials) { // Check that password save bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('retry_password_field').value = 'pw';" "document.getElementById('retry_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); prompt_observer.AcceptSavePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("", "pw"); } // Tests that no bubble shown when a password form without username submitted // and there is stored credentials with the same password. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PasswordRetryFormNoBubbleWhenPasswordTheSame) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"pw"; password_store->AddLogin(signin_form); signin_form.username_value = u"temp1"; signin_form.password_value = u"pw1"; password_store->AddLogin(signin_form); // Check that no password bubble is shown when the submitted password is the // same in one of the stored credentials. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('retry_password_field').value = 'pw';" "document.getElementById('retry_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); EXPECT_FALSE(prompt_observer.IsUpdatePromptShownAutomatically()); } // Tests that the update bubble shown when a password form without username is // submitted and there are stored credentials but with different password. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PasswordRetryFormUpdateBubbleShown) { // At first let us save credentials to the PasswordManager. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"pw"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('retry_password_field').value = 'new_pw';" "document.getElementById('retry_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // The new password "new_pw" is used, so update prompt is expected. EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); prompt_observer.AcceptUpdatePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "new_pw"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoCrashWhenNavigatingWithOpenAccountPicker) { // Save credentials with 'skip_zero_click'. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = u"password"; signin_form.username_value = u"user"; signin_form.url = embedded_test_server()->base_url(); signin_form.skip_zero_click = true; password_store->AddLogin(signin_form); NavigateToFile("/password/password_form.html"); // Call the API to trigger the notification to the client, which raises the // account picker dialog. ASSERT_TRUE(content::ExecuteScript( WebContents(), "navigator.credentials.get({password: true})")); // Navigate while the picker is open. NavigateToFile("/password/password_form.html"); // No crash! } // Tests that the prompt to save the password is still shown if the fields have // the "autocomplete" attribute set off. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForSubmitWithAutocompleteOff) { NavigateToFile("/password/password_autocomplete_off_test.html"); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit = "document.getElementById('username').value = 'temp';" "document.getElementById('password').value = 'random';" "document.getElementById('submit').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); } IN_PROC_BROWSER_TEST_F( PasswordManagerBrowserTest, SkipZeroClickNotToggledAfterSuccessfulSubmissionWithAPI) { // Save credentials with 'skip_zero_click' password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = u"password"; signin_form.username_value = u"user"; signin_form.url = embedded_test_server()->base_url(); signin_form.skip_zero_click = true; password_store->AddLogin(signin_form); NavigateToFile("/password/password_form.html"); // Call the API to trigger the notification to the client. ASSERT_TRUE(content::ExecuteScript( WebContents(), "navigator.credentials.get({password: true, unmediated: true })")); NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit_change_password = "document.getElementById('username_field').value = 'user';" "document.getElementById('password_field').value = 'password';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE( content::ExecuteScript(WebContents(), fill_and_submit_change_password)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); // Verify that the form's 'skip_zero_click' is not updated. auto& passwords_map = password_store->stored_passwords(); ASSERT_EQ(1u, passwords_map.size()); auto& passwords_vector = passwords_map.begin()->second; ASSERT_EQ(1u, passwords_vector.size()); const password_manager::PasswordForm& form = passwords_vector[0]; EXPECT_EQ(u"user", form.username_value); EXPECT_EQ(u"password", form.password_value); EXPECT_TRUE(form.skip_zero_click); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SkipZeroClickNotToggledAfterSuccessfulAutofill) { // Save credentials with 'skip_zero_click' password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = u"password"; signin_form.username_value = u"user"; signin_form.url = embedded_test_server()->base_url(); signin_form.skip_zero_click = true; password_store->AddLogin(signin_form); NavigateToFile("/password/password_form.html"); // No API call. NavigationObserver observer(WebContents()); BubbleObserver prompt_observer(WebContents()); std::string fill_and_submit_change_password = "document.getElementById('username_field').value = 'user';" "document.getElementById('password_field').value = 'password';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE( content::ExecuteScript(WebContents(), fill_and_submit_change_password)); observer.Wait(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); // Verify that the form's 'skip_zero_click' is not updated. auto& passwords_map = password_store->stored_passwords(); ASSERT_EQ(1u, passwords_map.size()); auto& passwords_vector = passwords_map.begin()->second; ASSERT_EQ(1u, passwords_vector.size()); const password_manager::PasswordForm& form = passwords_vector[0]; EXPECT_EQ(u"user", form.username_value); EXPECT_EQ(u"password", form.password_value); EXPECT_TRUE(form.skip_zero_click); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ReattachWebContents) { auto detached_web_contents = content::WebContents::Create( content::WebContents::CreateParams(WebContents()->GetBrowserContext())); NavigationObserver observer(detached_web_contents.get()); detached_web_contents->GetController().LoadURL( embedded_test_server()->GetURL("/password/multi_frames.html"), content::Referrer(), ::ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); observer.Wait(); // Ensure that there is at least one more frame created than just the main // frame. EXPECT_LT(1u, CollectAllRenderFrameHosts(detached_web_contents->GetPrimaryPage()) .size()); auto* tab_strip_model = browser()->tab_strip_model(); // Check that the autofill and password manager driver factories are notified // about all frames, not just the main one. The factories should receive // messages for non-main frames, in particular // AutofillHostMsg_PasswordFormsParsed. If that were the first time the // factories hear about such frames, this would crash. tab_strip_model->AddWebContents(std::move(detached_web_contents), -1, ::ui::PAGE_TRANSITION_AUTO_TOPLEVEL, TabStripModel::ADD_ACTIVE); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, FillWhenFormWithHiddenUsername) { // At first let us save a credential to the password store. password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.url = embedded_test_server()->base_url(); signin_form.username_value = u"current_username"; signin_form.password_value = u"current_username_password"; password_store->AddLogin(signin_form); signin_form.username_value = u"last_used_username"; signin_form.password_value = u"last_used_password"; signin_form.date_last_used = base::Time::Now(); password_store->AddLogin(signin_form); NavigateToFile("/password/hidden_username.html"); // Let the user interact with the page. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); // current_username is hardcoded in the invisible text on the page so // current_username_password should be filled rather than last_used_password. WaitForElementValue("password", "current_username_password"); } // Harness for showing dialogs as part of the DialogBrowserTest suite. // Test params: // - bool popup_views_enabled: whether feature AutofillExpandedPopupViews // is enabled for testing. class PasswordManagerDialogBrowserTest : public SupportsTestDialog<PasswordManagerBrowserTestBase> { public: PasswordManagerDialogBrowserTest() = default; PasswordManagerDialogBrowserTest(const PasswordManagerDialogBrowserTest&) = delete; PasswordManagerDialogBrowserTest& operator=( const PasswordManagerDialogBrowserTest&) = delete; void ShowUi(const std::string& name) override { // Note regarding flakiness: LocationBarBubbleDelegateView::ShowForReason() // uses ShowInactive() unless the bubble is invoked with reason == // USER_GESTURE. This means that, so long as these dialogs are not triggered // by gesture, the dialog does not attempt to take focus, and so should // never _lose_ focus in the test, which could cause flakes when tests are // run in parallel. LocationBarBubbles also dismiss on other events, but // only events in the WebContents. E.g. Rogue mouse clicks should not cause // the dialog to dismiss since they won't be sent via WebContents. // A user gesture is determined in browser_commands.cc by checking // ManagePasswordsUIController::IsAutomaticallyOpeningBubble(), but that's // set and cleared immediately while showing the bubble, so it can't be // checked here. NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); } }; IN_PROC_BROWSER_TEST_F(PasswordManagerDialogBrowserTest, InvokeUi_normal) { ShowAndVerifyUi(); } // Verify that password manager ignores passwords on forms injected into // about:blank frames. See https://crbug.com/756587. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AboutBlankFramesAreIgnored) { // Start from a page without a password form. NavigateToFile("/password/other.html"); // Add a blank iframe and then inject a password form into it. BubbleObserver prompt_observer(WebContents()); GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); InjectBlankFrameWithPasswordForm(WebContents(), submit_url); content::RenderFrameHost* frame = ChildFrameAt(WebContents()->GetMainFrame(), 0); EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL()); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); // Fill in the password and submit the form. This shouldn't bring up a save // password prompt and shouldn't result in a renderer kill. SubmitInjectedPasswordForm(WebContents(), frame, submit_url); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_EQ(submit_url, frame->GetLastCommittedURL()); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); } // Verify that password manager ignores passwords on forms injected into // about:blank popups. See https://crbug.com/756587. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AboutBlankPopupsAreIgnored) { // Start from a page without a password form. NavigateToFile("/password/other.html"); // Open an about:blank popup and inject the password form into it. ui_test_utils::TabAddedWaiter tab_add(browser()); GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); std::string form_html = GeneratePasswordFormForAction(submit_url); std::string open_blank_popup_with_password_form = "var w = window.open('about:blank');" "w.document.body.innerHTML = \"" + form_html + "\";"; ASSERT_TRUE(content::ExecuteScript(WebContents(), open_blank_popup_with_password_form)); tab_add.Wait(); ASSERT_EQ(2, browser()->tab_strip_model()->count()); content::WebContents* newtab = browser()->tab_strip_model()->GetActiveWebContents(); // Submit the password form and check that there was no renderer kill and no BubbleObserver prompt_observer(WebContents()); SubmitInjectedPasswordForm(newtab, newtab->GetMainFrame(), submit_url); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); EXPECT_TRUE(newtab->GetMainFrame()->IsRenderFrameLive()); EXPECT_EQ(submit_url, newtab->GetMainFrame()->GetLastCommittedURL()); } // Verify that previously saved passwords for about:blank frames are not used // for autofill. See https://crbug.com/756587. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ExistingAboutBlankPasswordsAreNotUsed) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.url = GURL(url::kAboutBlankURL); signin_form.signon_realm = "about:"; GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); signin_form.action = submit_url; signin_form.password_value = u"pa55w0rd"; password_store->AddLogin(signin_form); // Start from a page without a password form. NavigateToFile("/password/other.html"); // Inject an about:blank frame with password form. InjectBlankFrameWithPasswordForm(WebContents(), submit_url); content::RenderFrameHost* frame = ChildFrameAt(WebContents()->GetMainFrame(), 0); EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL()); // Simulate user interaction in the iframe which normally triggers // autofill. Click in the middle of the frame to avoid the border. content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe"); // Verify password is not autofilled. Blink has a timer for 0.3 seconds // before it updates the browser with the new dynamic form, so wait long // enough for this timer to fire before checking the password. Note that we // can't wait for any other events here, because when the test passes, there // should be no password manager IPCs sent from the renderer to browser. std::string empty_password; EXPECT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( frame, "setTimeout(function() {" " domAutomationController.send(" " document.getElementById('password_field').value);" "}, 1000);", &empty_password)); EXPECT_EQ("", empty_password); EXPECT_TRUE(frame->IsRenderFrameLive()); } // Verify that there is no renderer kill when filling out a password on a // subframe with a data: URL. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoRendererKillWithDataURLFrames) { // Start from a page without a password form. NavigateToFile("/password/other.html"); // Add a iframe with a data URL that has a password form. BubbleObserver prompt_observer(WebContents()); GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); std::string form_html = GeneratePasswordFormForAction(submit_url); std::string inject_data_frame_with_password_form = "var frame = document.createElement('iframe');\n" "frame.src = \"data:text/html," + form_html + "\";\n" "document.body.appendChild(frame);\n"; ASSERT_TRUE(content::ExecuteScript(WebContents(), inject_data_frame_with_password_form)); EXPECT_TRUE(content::WaitForLoadStop(WebContents())); content::RenderFrameHost* frame = ChildFrameAt(WebContents()->GetMainFrame(), 0); EXPECT_TRUE(frame->GetLastCommittedURL().SchemeIs(url::kDataScheme)); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); // Fill in the password and submit the form. This shouldn't bring up a save // password prompt and shouldn't result in a renderer kill. SubmitInjectedPasswordForm(WebContents(), frame, submit_url); // After navigation, the RenderFrameHost may change. frame = ChildFrameAt(WebContents()->GetMainFrame(), 0); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_EQ(submit_url, frame->GetLastCommittedURL()); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); } // Verify that there is no renderer kill when filling out a password on a // blob: URL. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoRendererKillWithBlobURLFrames) { // Start from a page without a password form. NavigateToFile("/password/other.html"); GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); std::string form_html = GeneratePasswordFormForAction(submit_url); std::string navigate_to_blob_url = "location.href = URL.createObjectURL(new Blob([\"" + form_html + "\"], { type: 'text/html' }));"; NavigationObserver observer(WebContents()); ASSERT_TRUE(content::ExecuteScript(WebContents(), navigate_to_blob_url)); observer.Wait(); // Fill in the password and submit the form. This shouldn't bring up a save // password prompt and shouldn't result in a renderer kill. std::string fill_and_submit = "document.getElementById('password_field').value = 'random';" "document.getElementById('testform').submit();"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); EXPECT_FALSE(BubbleObserver(WebContents()).IsSavePromptAvailable()); } // Test that for HTTP auth (i.e., credentials not put through web forms) the // password manager works even though it should be disabled on the previous // page. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, CorrectEntryForHttpAuth) { // The embedded_test_server() is already started at this point and adding // the request handler to it would not be thread safe. Therefore, use a new // server. net::EmbeddedTestServer http_test_server; // Teach the embedded server to handle requests by issuing the basic auth // challenge. http_test_server.RegisterRequestHandler( base::BindRepeating(&HandleTestAuthRequest)); ASSERT_TRUE(http_test_server.Start()); LoginPromptBrowserTestObserver login_observer; login_observer.Register(content::Source<content::NavigationController>( &WebContents()->GetController())); // Navigate to about:blank first. This is a page where password manager // should not work. ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank"))); content::NavigationController* nav_controller = &WebContents()->GetController(); WindowedAuthNeededObserver auth_needed_observer(nav_controller); // Navigate to a page requiring HTTP auth ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), http_test_server.GetURL("/basic_auth"))); auth_needed_observer.Wait(); NavigationObserver nav_observer(WebContents()); WindowedAuthSuppliedObserver auth_supplied_observer(nav_controller); // Offer valid credentials on the auth challenge. ASSERT_EQ(1u, login_observer.handlers().size()); LoginHandler* handler = *login_observer.handlers().begin(); ASSERT_TRUE(handler); // Any username/password will work. handler->SetAuth(u"user", u"pwd"); auth_supplied_observer.Wait(); // The password manager should be working correctly. nav_observer.Wait(); WaitForPasswordStore(); BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); } // Test that if HTTP auth login (i.e., credentials not put through web forms) // succeeds, and there is a blocklisted entry with the HTML PasswordForm::Scheme // for that origin, then the bubble is shown. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, HTTPAuthRealmAfterHTMLBlocklistedIsNotBlocked) { // The embedded_test_server() is already started at this point and adding // the request handler to it would not be thread safe. Therefore, use a new // server. net::EmbeddedTestServer http_test_server; // Teach the embedded server to handle requests by issuing the basic auth // challenge. http_test_server.RegisterRequestHandler( base::BindRepeating(&HandleTestAuthRequest)); ASSERT_TRUE(http_test_server.Start()); LoginPromptBrowserTestObserver login_observer; login_observer.Register(content::Source<content::NavigationController>( &WebContents()->GetController())); password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm blocked_form; blocked_form.scheme = password_manager::PasswordForm::Scheme::kHtml; blocked_form.signon_realm = http_test_server.base_url().spec(); blocked_form.url = http_test_server.base_url(); blocked_form.blocked_by_user = true; password_store->AddLogin(blocked_form); content::NavigationController* nav_controller = &WebContents()->GetController(); WindowedAuthNeededObserver auth_needed_observer(nav_controller); // Navigate to a page requiring HTTP auth. ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), http_test_server.GetURL("/basic_auth"))); auth_needed_observer.Wait(); NavigationObserver nav_observer(WebContents()); WindowedAuthSuppliedObserver auth_supplied_observer(nav_controller); ASSERT_EQ(1u, login_observer.handlers().size()); LoginHandler* handler = *login_observer.handlers().begin(); ASSERT_TRUE(handler); // Any username/password will work. handler->SetAuth(u"user", u"pwd"); auth_supplied_observer.Wait(); nav_observer.Wait(); WaitForPasswordStore(); EXPECT_TRUE(BubbleObserver(WebContents()).IsSavePromptShownAutomatically()); } // Test that if HTML login succeeds, and there is a blocklisted entry // with the HTTP auth PasswordForm::Scheme (i.e., credentials not put // through web forms) for that origin, then the bubble is shown. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, HTMLLoginAfterHTTPAuthBlocklistedIsNotBlocked) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm blocked_form; blocked_form.scheme = password_manager::PasswordForm::Scheme::kBasic; blocked_form.signon_realm = embedded_test_server()->base_url().spec() + "test realm"; blocked_form.url = embedded_test_server()->base_url(); blocked_form.blocked_by_user = true; password_store->AddLogin(blocked_form); NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'pw';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); } // Tests that "blocklist site" feature works for the basic scenario. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, HTMLLoginAfterHTMLBlocklistedIsBlocklisted) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm blocked_form; blocked_form.scheme = password_manager::PasswordForm::Scheme::kHtml; blocked_form.signon_realm = embedded_test_server()->base_url().spec(); blocked_form.url = embedded_test_server()->base_url(); blocked_form.blocked_by_user = true; password_store->AddLogin(blocked_form); NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'pw';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); BubbleObserver bubble_observer(WebContents()); EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically()); EXPECT_TRUE(bubble_observer.IsSavePromptAvailable()); } // This test emulates what was observed in https://crbug.com/856543: Imagine the // user stores a single username/password pair on origin A, and later submits a // username-less password-reset form on origin B. In the bug, A and B were // PSL-matches (different, but with the same eTLD+1), and Chrome ended up // overwriting the old password with the new one. This test checks that update // bubble is shown instead of silent update. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoSilentOverwriteOnPSLMatch) { // Store a password at origin A. const GURL url_A = embedded_test_server()->GetURL("abc.foo.com", "/"); password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); password_manager::PasswordForm signin_form; signin_form.signon_realm = url_A.DeprecatedGetOriginAsURL().spec(); signin_form.url = url_A; signin_form.username_value = u"user"; signin_form.password_value = u"oldpassword"; password_store->AddLogin(signin_form); WaitForPasswordStore(); // Visit origin B with a form only containing new- and confirmation-password // fields. GURL url_B = embedded_test_server()->GetURL( "www.foo.com", "/password/new_password_form.html"); NavigationObserver observer_B(WebContents()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_B)); observer_B.Wait(); // Fill in the new password and submit. GURL url_done = embedded_test_server()->GetURL("www.foo.com", "/password/done.html"); NavigationObserver observer_done(WebContents()); observer_done.SetPathToWaitFor("/password/done.html"); ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture( RenderFrameHost(), "document.getElementById('new_p').value = 'new password';" "document.getElementById('conf_p').value = 'new password';" "document.getElementById('testform').submit();")); observer_done.Wait(); // Check that the password for origin A was not updated automatically and the // update bubble is shown instead. WaitForPasswordStore(); // Let the navigation take its effect on storing. ASSERT_THAT(password_store->stored_passwords(), ElementsAre(testing::Key(url_A.DeprecatedGetOriginAsURL()))); CheckThatCredentialsStored("user", "oldpassword"); BubbleObserver prompt_observer(WebContents()); EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); // Check that the password is updated correctly if the user clicks Update. prompt_observer.AcceptUpdatePrompt(); WaitForPasswordStore(); // The stored credential has been updated with the new password. const auto& passwords_map = password_store->stored_passwords(); ASSERT_THAT(passwords_map, ElementsAre(testing::Key(url_A.DeprecatedGetOriginAsURL()))); for (const auto& credentials : passwords_map) { ASSERT_THAT(credentials.second, testing::SizeIs(1)); EXPECT_EQ(u"user", credentials.second[0].username_value); EXPECT_EQ(u"new password", credentials.second[0].password_value); } } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoFillGaiaReauthenticationForm) { password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); // Visit Gaia reath page. const GURL url = https_test_server().GetURL("accounts.google.com", "/password/gaia_reath_form.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Expects no requests to the password store. So no filling. EXPECT_EQ(0, password_store->fill_matching_logins_calls()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoFillGaiaWithSkipSavePasswordForm) { password_manager::TestPasswordStore* password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get()); // Visit Gaia form with ssp=1 as query (ssp stands for Skip Save Password). const GURL url = https_test_server().GetURL( "accounts.google.com", "/password/password_form.html?ssp=1"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Expects no requests to the password store. So no filling. EXPECT_EQ(0, password_store->fill_matching_logins_calls()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DeleteCredentialsUpdateDropdow) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); // Start with two logins in the password store. password_manager::PasswordForm admin_form; admin_form.signon_realm = embedded_test_server()->base_url().spec(); admin_form.url = embedded_test_server()->base_url(); admin_form.username_value = u"admin"; admin_form.password_value = u"random_secret"; password_store->AddLogin(admin_form); password_manager::PasswordForm user_form = admin_form; user_form.username_value = u"user"; password_store->AddLogin(user_form); NavigateToFile("/password/password_form.html"); ContentPasswordManagerDriverFactory* factory = ContentPasswordManagerDriverFactory::FromWebContents(WebContents()); autofill::mojom::PasswordManagerDriver* driver = factory->GetDriverForFrame(WebContents()->GetMainFrame()); // Instruct Chrome to show the password dropdown. driver->ShowPasswordSuggestions(base::i18n::LEFT_TO_RIGHT, std::u16string(), 0, gfx::RectF()); autofill::ChromeAutofillClient* autofill_client = autofill::ChromeAutofillClient::FromWebContents(WebContents()); autofill::AutofillPopupController* controller = autofill_client->popup_controller_for_testing().get(); ASSERT_TRUE(controller); // Two credentials and "Manage passwords" should be displayed. EXPECT_EQ(3, controller->GetLineCount()); // Trigger user gesture so that autofill happens. ASSERT_TRUE(content::ExecuteScript( WebContents(), "document.getElementById('username_field').click();")); WaitForElementValue("username_field", "admin"); // Delete one credential. It should not be in the dropdown. password_store->RemoveLogin(admin_form); WaitForPasswordStore(); // Wait for the refetch to finish. EXPECT_FALSE(autofill_client->popup_controller_for_testing()); WaitForPasswordStore(); // Reshow the dropdown. driver->ShowPasswordSuggestions(base::i18n::LEFT_TO_RIGHT, std::u16string(), 0, gfx::RectF()); controller = autofill_client->popup_controller_for_testing().get(); ASSERT_TRUE(controller); EXPECT_EQ(2, controller->GetLineCount()); EXPECT_EQ(u"user", controller->GetSuggestionMainTextAt(0)); EXPECT_NE(u"admin", controller->GetSuggestionMainTextAt(1)); // The username_field should get re-filled with "user" instead of "admin". WaitForElementValue("username_field", "user"); // Delete all the credentials. password_store->RemoveLogin(user_form); WaitForPasswordStore(); // Wait for the refetch to finish. EXPECT_FALSE(autofill_client->popup_controller_for_testing()); WaitForPasswordStore(); // Reshow the dropdown won't work because there is nothing to suggest. driver->ShowPasswordSuggestions(base::i18n::LEFT_TO_RIGHT, std::u16string(), 0, gfx::RectF()); EXPECT_FALSE(autofill_client->popup_controller_for_testing()); WaitForElementValue("username_field", ""); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, FormDynamicallyChanged) { password_manager::PasswordStoreInterface* password_store = PasswordStoreFactory::GetForProfile(browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) .get(); password_manager::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.username_value = u"temp"; signin_form.password_value = u"pw"; password_store->AddLogin(signin_form); // Check that password update bubble is shown. NavigateToFile("/password/simple_password.html"); // Simulate that a script removes username/password elements and adds the // elements identical to them. ASSERT_TRUE(content::ExecuteScriptWithoutUserGesture( RenderFrameHost(), "function replaceElement(id) {" " var elem = document.getElementById(id);" " var parent = elem.parentElement;" " var cloned_elem = elem.cloneNode();" " cloned_elem.value = '';" " parent.removeChild(elem);" " parent.appendChild(cloned_elem);" "}" "replaceElement('username_field');" "replaceElement('password_field');")); // Let the user interact with the page, so that DOM gets modification events, // needed for autofilling fields. content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("username_field", "temp"); WaitForElementValue("password_field", "pw"); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ParserAnnotations) { base::CommandLine::ForCurrentProcess()->AppendSwitch( autofill::switches::kShowAutofillSignatures); NavigateToFile("/password/password_form.html"); const char kGetAnnotation[] = "window.domAutomationController.send(" " document.getElementById('%s').getAttribute('pm_parser_annotation'));"; std::string username_annotation; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), base::StringPrintf(kGetAnnotation, "username_field"), &username_annotation)); EXPECT_EQ("username_element", username_annotation); std::string password_annotation; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), base::StringPrintf(kGetAnnotation, "password_field"), &password_annotation)); EXPECT_EQ("password_element", password_annotation); std::string new_password_annotation; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), base::StringPrintf(kGetAnnotation, "chg_new_password_1"), &new_password_annotation)); EXPECT_EQ("new_password_element", new_password_annotation); std::string cofirmation_password_annotation; ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( RenderFrameHost(), base::StringPrintf(kGetAnnotation, "chg_new_password_2"), &cofirmation_password_annotation)); EXPECT_EQ("confirmation_password_element", cofirmation_password_annotation); } // Test if |PasswordManager.FormVisited.PerProfileType| and // |PasswordManager.FormSubmission.PerProfileType| metrics are recorded as // expected. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ProfileTypeMetricSubmission) { base::HistogramTester histogram_tester; NavigateToFile("/password/simple_password.html"); // Test if visit is properly recorded and submission is not marked. histogram_tester.ExpectUniqueSample( "PasswordManager.FormVisited.PerProfileType", profile_metrics::BrowserProfileType::kRegular, 1); histogram_tester.ExpectTotalCount( "PasswordManager.FormSubmission.PerProfileType", 0); // Fill a form and submit through a <input type="submit"> button. Nothing // special. NavigationObserver observer(WebContents()); constexpr char kFillAndSubmit[] = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), kFillAndSubmit)); observer.Wait(); // Test if submission is properly recorded. histogram_tester.ExpectUniqueSample( "PasswordManager.FormSubmission.PerProfileType", profile_metrics::BrowserProfileType::kRegular, 1); } IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest, SavePasswordOnRestoredPage) { // Navigate to a page with a password form. NavigateToFile("/password/password_form.html"); content::RenderFrameHostWrapper rfh(WebContents()->GetMainFrame()); // Navigate away so that the password form page is stored in the cache. EXPECT_TRUE(NavigateToURL( WebContents(), embedded_test_server()->GetURL("a.com", "/title1.html"))); EXPECT_EQ(rfh->GetLifecycleState(), content::RenderFrameHost::LifecycleState::kInBackForwardCache); // Restore the cached page. WebContents()->GetController().GoBack(); EXPECT_TRUE(WaitForLoadStop(WebContents())); EXPECT_EQ(rfh.get(), WebContents()->GetMainFrame()); // Fill out and submit the password form. NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // Save the password and check the store. BubbleObserver bubble_observer(WebContents()); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); bubble_observer.AcceptSavePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "random"); } // Test that if the credentials API is used, it makes the page ineligible for // caching in the BackForwardCache. // // See where BackForwardCache::DisableForRenderFrameHost is called in // chrome_password_manager_client.cc for explanation. IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest, NotCachedIfCredentialsAPIUsed) { // Navigate to a page with a password form. NavigateToFile("/password/password_form.html"); content::RenderFrameHost* rfh = WebContents()->GetMainFrame(); content::RenderFrameDeletedObserver rfh_deleted_observer(rfh); // Use the password manager API, this should make the page uncacheable. EXPECT_TRUE(IsGetCredentialsSuccessful()); // Navigate away. EXPECT_TRUE(NavigateToURL( WebContents(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // The page should not have been cached. rfh_deleted_observer.WaitUntilDeleted(); } IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest, CredentialsAPIOnlyCalledOnRestoredPage) { // Navigate to a page with a password form. NavigateToFile("/password/password_form.html"); content::RenderFrameHostWrapper rfh(WebContents()->GetMainFrame()); // Navigate away. EXPECT_TRUE(NavigateToURL( WebContents(), embedded_test_server()->GetURL("b.com", "/title1.html"))); EXPECT_EQ(rfh->GetLifecycleState(), content::RenderFrameHost::LifecycleState::kInBackForwardCache); // Restore the cached page. WebContents()->GetController().GoBack(); EXPECT_TRUE(WaitForLoadStop(WebContents())); EXPECT_EQ(rfh.get(), WebContents()->GetMainFrame()); // Make sure the password manager API works. Since it was never connected, it // shouldn't have been affected by the // ContentCredentialManager::DisconnectBinding call in // ChromePasswordManagerClient::DidFinishNavigation, (this GetCredentials call // will establish the mojo connection for the first time). EXPECT_TRUE(IsGetCredentialsSuccessful()); } IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DetectFormSubmissionOnIframe) { // Start from a page without a password form. NavigateToFile("/password/other.html"); // Add a blank iframe and then inject a password form into it. BubbleObserver prompt_observer(WebContents()); GURL current_url(embedded_test_server()->GetURL("/password/other.html")); GURL submit_url(embedded_test_server()->GetURL("/password/done.html")); InjectFrameWithPasswordForm(WebContents(), submit_url); content::RenderFrameHost* frame = ChildFrameAt(WebContents()->GetMainFrame(), 0); EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL()); EXPECT_EQ(submit_url.DeprecatedGetOriginAsURL(), frame->GetLastCommittedOrigin().GetURL()); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_FALSE(prompt_observer.IsSavePromptAvailable()); // Fill in the password and submit the form. This should bring up a save // password prompt and shouldn't result in a renderer kill. SubmitInjectedPasswordForm(WebContents(), frame, submit_url); EXPECT_TRUE(frame->IsRenderFrameLive()); EXPECT_TRUE(prompt_observer.IsSavePromptAvailable()); } #if BUILDFLAG(ENABLE_DICE_SUPPORT) && !BUILDFLAG(IS_CHROMEOS_LACROS) // This test suite only applies to Gaia signin page, and checks that the // signin interception bubble and the password bubbles never conflict. class PasswordManagerBrowserTestWithSigninInterception : public PasswordManagerBrowserTest { public: PasswordManagerBrowserTestWithSigninInterception() : helper_(&https_test_server()) {} void SetUpCommandLine(base::CommandLine* command_line) override { PasswordManagerBrowserTest::SetUpCommandLine(command_line); helper_.SetUpCommandLine(command_line); } void SetUpOnMainThread() override { helper_.SetUpOnMainThread(); PasswordManagerBrowserTest::SetUpOnMainThread(); } void FillAndSubmitGaiaPassword() { NavigationObserver observer(WebContents()); std::string fill_and_submit = base::StringPrintf( "document.getElementById('username_field').value = '%s';" "document.getElementById('password_field').value = 'new_pw';" "document.getElementById('input_submit_button').click()", helper_.gaia_username().c_str()); ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); } // Gaia passwords can only be saved if they are a secondary account. Add // another dummy account in Chrome that acts as the primary. void SetupAccountsForSavingGaiaPassword() { CoreAccountId dummy_account = helper_.AddGaiaAccountToProfile( browser()->profile(), "dummy_email@example.com", "dummy_gaia_id"); IdentityManagerFactory::GetForProfile(browser()->profile()) ->GetPrimaryAccountMutator() ->SetPrimaryAccount(dummy_account, signin::ConsentLevel::kSignin); } protected: PasswordManagerSigninInterceptTestHelper helper_; }; // Checks that password update suppresses signin interception. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception, InterceptionBubbleSuppressedByPasswordUpdate) { Profile* profile = browser()->profile(); helper_.SetupProfilesForInterception(profile); // Prepopulate Gaia credentials to trigger an update bubble. scoped_refptr<password_manager::TestPasswordStore> password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( profile, ServiceAccessType::IMPLICIT_ACCESS) .get()); helper_.StoreGaiaCredentials(password_store); helper_.NavigateToGaiaSigninPage(WebContents()); // The stored password "pw" was overridden with "new_pw", so update prompt is // expected. Use the retry form, to avoid autofill. BubbleObserver prompt_observer(WebContents()); NavigationObserver observer(WebContents()); std::string fill_and_submit = "document.getElementById('retry_password_field').value = 'new_pw';" "document.getElementById('retry_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); EXPECT_TRUE(prompt_observer.IsUpdatePromptShownAutomatically()); // Complete the Gaia signin. CoreAccountId account_id = helper_.AddGaiaAccountToProfile( profile, helper_.gaia_email(), helper_.gaia_id()); // Check that interception does not happen. base::HistogramTester histogram_tester; DiceWebSigninInterceptor* signin_interceptor = helper_.GetSigninInterceptor(profile); signin_interceptor->MaybeInterceptWebSignin(WebContents(), account_id, /*is_new_account=*/true, /*is_sync_signin=*/false); EXPECT_FALSE(signin_interceptor->is_interception_in_progress()); histogram_tester.ExpectUniqueSample( "Signin.Intercept.HeuristicOutcome", SigninInterceptionHeuristicOutcome::kAbortPasswordUpdate, 1); } // Checks that Gaia password can be saved when there is no interception. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception, SaveGaiaPassword) { SetupAccountsForSavingGaiaPassword(); helper_.NavigateToGaiaSigninPage(WebContents()); // Add the new password: triggers the save bubble. BubbleObserver prompt_observer(WebContents()); FillAndSubmitGaiaPassword(); EXPECT_TRUE(prompt_observer.IsSavePromptShownAutomatically()); // Complete the Gaia signin. Profile* profile = browser()->profile(); CoreAccountId account_id = helper_.AddGaiaAccountToProfile( profile, helper_.gaia_email(), helper_.gaia_id()); // Check that interception does not happen. base::HistogramTester histogram_tester; DiceWebSigninInterceptor* signin_interceptor = helper_.GetSigninInterceptor(profile); signin_interceptor->MaybeInterceptWebSignin(WebContents(), account_id, /*is_new_account=*/true, /*is_sync_signin=*/false); EXPECT_FALSE(signin_interceptor->is_interception_in_progress()); histogram_tester.ExpectUniqueSample( "Signin.Intercept.HeuristicOutcome", SigninInterceptionHeuristicOutcome::kAbortProfileCreationDisallowed, 1); } // Checks that signin interception suppresses password save, if the form is // processed before the signin completes. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception, SavePasswordSuppressedBeforeSignin) { Profile* profile = browser()->profile(); helper_.SetupProfilesForInterception(profile); SetupAccountsForSavingGaiaPassword(); helper_.NavigateToGaiaSigninPage(WebContents()); // Add the new password, password bubble not triggered. BubbleObserver prompt_observer(WebContents()); FillAndSubmitGaiaPassword(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); // Complete the Gaia signin. CoreAccountId account_id = helper_.AddGaiaAccountToProfile( profile, helper_.gaia_email(), helper_.gaia_id()); // Check that interception happens. base::HistogramTester histogram_tester; DiceWebSigninInterceptor* signin_interceptor = helper_.GetSigninInterceptor(profile); signin_interceptor->MaybeInterceptWebSignin(WebContents(), account_id, /*is_new_account=*/true, /*is_sync_signin=*/false); EXPECT_TRUE(signin_interceptor->is_interception_in_progress()); } // Checks that signin interception suppresses password save, if the form is // processed after the signin completes. IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception, SavePasswordSuppressedAfterSignin) { Profile* profile = browser()->profile(); helper_.SetupProfilesForInterception(profile); SetupAccountsForSavingGaiaPassword(); helper_.NavigateToGaiaSigninPage(WebContents()); // Complete the Gaia signin. CoreAccountId account_id = helper_.AddGaiaAccountToProfile( profile, helper_.gaia_email(), helper_.gaia_id()); // Check that interception happens. base::HistogramTester histogram_tester; DiceWebSigninInterceptor* signin_interceptor = helper_.GetSigninInterceptor(profile); signin_interceptor->MaybeInterceptWebSignin(WebContents(), account_id, /*is_new_account=*/true, /*is_sync_signin=*/false); EXPECT_TRUE(signin_interceptor->is_interception_in_progress()); // Add the new password, password bubble not triggered. BubbleObserver prompt_observer(WebContents()); FillAndSubmitGaiaPassword(); EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically()); } #endif // ENABLE_DICE_SUPPORT && !BUILDFLAG(IS_CHROMEOS_LACROS) class TestPasswordManagerClient : public ChromePasswordManagerClient { public: static void CreateForWebContentsWithAutofillClient( content::WebContents* contents, autofill::AutofillClient* autofill_client) { if (FromWebContents(contents)) return; contents->SetUserData( UserDataKey(), std::make_unique<TestPasswordManagerClient>(contents, autofill_client)); } TestPasswordManagerClient(content::WebContents* web_contents, autofill::AutofillClient* autofill_client) : ChromePasswordManagerClient(web_contents, autofill_client) {} ~TestPasswordManagerClient() override = default; MOCK_METHOD(void, OnInputEvent, (const blink::WebInputEvent&), (override)); }; MATCHER_P(IsKeyEvent, type, std::string()) { return arg.GetType() == type; } // This is for checking that we don't make unexpected calls to the password // manager driver prior to activation and to permit checking that expected calls // do happen after activation. class MockPrerenderPasswordManagerDriver : public autofill::mojom::PasswordManagerDriverInterceptorForTesting { public: explicit MockPrerenderPasswordManagerDriver( password_manager::ContentPasswordManagerDriver* driver) : impl_(driver->ReceiverForTesting().SwapImplForTesting(this)) { DelegateToImpl(); } MockPrerenderPasswordManagerDriver( const MockPrerenderPasswordManagerDriver&) = delete; MockPrerenderPasswordManagerDriver& operator=( const MockPrerenderPasswordManagerDriver&) = delete; ~MockPrerenderPasswordManagerDriver() override = default; autofill::mojom::PasswordManagerDriver* GetForwardingInterface() override { return impl_; } // autofill::mojom::PasswordManagerDriver MOCK_METHOD(void, PasswordFormsParsed, (const std::vector<autofill::FormData>& form_data), (override)); MOCK_METHOD(void, PasswordFormsRendered, (const std::vector<autofill::FormData>& visible_form_data, bool load_completed), (override)); MOCK_METHOD(void, PasswordFormSubmitted, (const autofill::FormData& form_data), (override)); MOCK_METHOD(void, InformAboutUserInput, (const autofill::FormData& form_data), (override)); MOCK_METHOD( void, DynamicFormSubmission, (autofill::mojom::SubmissionIndicatorEvent submission_indication_event), (override)); MOCK_METHOD(void, PasswordFormCleared, (const autofill::FormData& form_Data), (override)); MOCK_METHOD(void, RecordSavePasswordProgress, (const std::string& log), (override)); MOCK_METHOD(void, UserModifiedPasswordField, (), (override)); MOCK_METHOD(void, UserModifiedNonPasswordField, (autofill::FieldRendererId renderer_id, const std::u16string& field_name, const std::u16string& value), (override)); MOCK_METHOD(void, ShowPasswordSuggestions, (base::i18n::TextDirection text_direction, const std::u16string& typed_username, int options, const gfx::RectF& bounds), (override)); MOCK_METHOD(void, ShowTouchToFill, (), (override)); MOCK_METHOD(void, CheckSafeBrowsingReputation, (const GURL& form_action, const GURL& frame_url), (override)); MOCK_METHOD(void, FocusedInputChanged, (autofill::FieldRendererId focused_field_id, autofill::mojom::FocusedFieldType focused_field_type), (override)); MOCK_METHOD(void, LogFirstFillingResult, (autofill::FormRendererId form_renderer_id, int32_t result), (override)); void DelegateToImpl() { ON_CALL(*this, PasswordFormsParsed) .WillByDefault( [this](const std::vector<autofill::FormData>& form_data) { impl_->PasswordFormsParsed(form_data); RemoveWaitType(WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_PARSED); }); ON_CALL(*this, PasswordFormsRendered) .WillByDefault( [this](const std::vector<autofill::FormData>& visible_form_data, bool load_completed) { impl_->PasswordFormsRendered(visible_form_data, load_completed); RemoveWaitType(WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_RENDERED); }); ON_CALL(*this, PasswordFormSubmitted) .WillByDefault([this](const autofill::FormData& form_data) { impl_->PasswordFormSubmitted(form_data); }); ON_CALL(*this, InformAboutUserInput) .WillByDefault([this](const autofill::FormData& form_data) { impl_->InformAboutUserInput(form_data); }); ON_CALL(*this, DynamicFormSubmission) .WillByDefault([this](autofill::mojom::SubmissionIndicatorEvent submission_indication_event) { impl_->DynamicFormSubmission(submission_indication_event); }); ON_CALL(*this, PasswordFormCleared) .WillByDefault([this](const autofill::FormData& form_Data) { impl_->PasswordFormCleared(form_Data); }); ON_CALL(*this, RecordSavePasswordProgress) .WillByDefault([this](const std::string& log) { impl_->RecordSavePasswordProgress(log); }); ON_CALL(*this, UserModifiedPasswordField).WillByDefault([this]() { impl_->UserModifiedPasswordField(); }); ON_CALL(*this, UserModifiedNonPasswordField) .WillByDefault([this](autofill::FieldRendererId renderer_id, const std::u16string& field_name, const std::u16string& value) { impl_->UserModifiedNonPasswordField(renderer_id, field_name, value); }); ON_CALL(*this, ShowPasswordSuggestions) .WillByDefault([this](base::i18n::TextDirection text_direction, const std::u16string& typed_username, int options, const gfx::RectF& bounds) { impl_->ShowPasswordSuggestions(text_direction, typed_username, options, bounds); }); ON_CALL(*this, ShowTouchToFill).WillByDefault([this]() { impl_->ShowTouchToFill(); }); ON_CALL(*this, CheckSafeBrowsingReputation) .WillByDefault([this](const GURL& form_action, const GURL& frame_url) { impl_->CheckSafeBrowsingReputation(form_action, frame_url); }); ON_CALL(*this, FocusedInputChanged) .WillByDefault( [this](autofill::FieldRendererId focused_field_id, autofill::mojom::FocusedFieldType focused_field_type) { impl_->FocusedInputChanged(focused_field_id, focused_field_type); }); ON_CALL(*this, LogFirstFillingResult) .WillByDefault( [this](autofill::FormRendererId form_renderer_id, int32_t result) { impl_->LogFirstFillingResult(form_renderer_id, result); }); } void WaitForPasswordFormParsedAndRendered() { base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); wait_type_ = WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_PARSED | WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_RENDERED; run_loop.Run(); } private: enum WAIT_FOR_PASSWORD_FORMS { WAIT_FOR_NOTHING = 0, WAIT_FOR_PARSED = 1 << 0, // Waits for PasswordFormsParsed(). WAIT_FOR_RENDERED = 1 << 1, // Waits for PasswordFormsRendered(). }; void RemoveWaitType(uint32_t arrived) { wait_type_ &= ~arrived; if (wait_type_ == WAIT_FOR_NOTHING && quit_closure_) std::move(quit_closure_).Run(); } base::OnceClosure quit_closure_; uint32_t wait_type_ = WAIT_FOR_NOTHING; autofill::mojom::PasswordManagerDriver* impl_ = nullptr; }; class MockPrerenderPasswordManagerDriverInjector : public content::WebContentsObserver { public: explicit MockPrerenderPasswordManagerDriverInjector( content::WebContents* web_contents) : WebContentsObserver(web_contents) {} ~MockPrerenderPasswordManagerDriverInjector() override = default; MockPrerenderPasswordManagerDriver* GetMockForFrame( content::RenderFrameHost* rfh) { return static_cast<MockPrerenderPasswordManagerDriver*>( GetDriverForFrame(rfh)->ReceiverForTesting().impl()); } private: password_manager::ContentPasswordManagerDriver* GetDriverForFrame( content::RenderFrameHost* rfh) { password_manager::ContentPasswordManagerDriverFactory* driver_factory = password_manager::ContentPasswordManagerDriverFactory::FromWebContents( web_contents()); return driver_factory->GetDriverForFrame(rfh); } // content::WebContentsObserver: void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override { auto* rfh = navigation_handle->GetRenderFrameHost(); if (navigation_handle->IsPrerenderedPageActivation() || navigation_handle->IsSameDocument() || rfh->GetLifecycleState() != content::RenderFrameHost::LifecycleState::kPrerendering) { return; } mocks_.push_back(std::make_unique< testing::StrictMock<MockPrerenderPasswordManagerDriver>>( GetDriverForFrame(navigation_handle->GetRenderFrameHost()))); } std::vector< std::unique_ptr<testing::StrictMock<MockPrerenderPasswordManagerDriver>>> mocks_; }; class PasswordManagerPrerenderBrowserTest : public PasswordManagerBrowserTest { public: PasswordManagerPrerenderBrowserTest() : prerender_helper_(base::BindRepeating( &PasswordManagerPrerenderBrowserTest::web_contents, base::Unretained(this))) {} ~PasswordManagerPrerenderBrowserTest() override = default; void SetUp() override { prerender_helper_.SetUp(embedded_test_server()); PasswordManagerBrowserTest::SetUp(); } void SetUpOnMainThread() override { // Register requests handler before the server is started. embedded_test_server()->RegisterRequestHandler( base::BindRepeating(&HandleTestAuthRequest)); PasswordManagerBrowserTest::SetUpOnMainThread(); } content::test::PrerenderTestHelper* prerender_helper() { return &prerender_helper_; } void SendKey(::ui::KeyboardCode key, content::RenderFrameHost* render_frame_host) { blink::WebKeyboardEvent web_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::kNoModifiers, blink::WebInputEvent::GetStaticTimeStampForTests()); content::NativeWebKeyboardEvent event(web_event, gfx::NativeView()); event.windows_key_code = key; render_frame_host->GetRenderWidgetHost()->ForwardKeyboardEvent(event); } // Adds a tab with TestPasswordManagerClient which is a customized // ChromePasswordManagerClient. // Note that it doesn't use CustomManagePasswordsUIController and it's not // useful to test UI. After calling this, // PasswordManagerBrowserTest::WebContents() is not available. void GetNewTabWithTestPasswordManagerClient() { content::WebContents* preexisting_tab = browser()->tab_strip_model()->GetActiveWebContents(); std::unique_ptr<content::WebContents> owned_web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser()->profile())); ASSERT_TRUE(owned_web_contents.get()); // ManagePasswordsUIController needs ChromePasswordManagerClient for // logging. autofill::ChromeAutofillClient::CreateForWebContents( owned_web_contents.get()); TestPasswordManagerClient::CreateForWebContentsWithAutofillClient( owned_web_contents.get(), autofill::ChromeAutofillClient::FromWebContents( owned_web_contents.get())); ASSERT_TRUE( ChromePasswordManagerClient::FromWebContents(owned_web_contents.get())); ManagePasswordsUIController::CreateForWebContents(owned_web_contents.get()); ASSERT_TRUE( ManagePasswordsUIController::FromWebContents(owned_web_contents.get())); ASSERT_FALSE(owned_web_contents.get()->IsLoading()); browser()->tab_strip_model()->AppendWebContents( std::move(owned_web_contents), true); if (preexisting_tab) { browser()->tab_strip_model()->CloseWebContentsAt( 0, TabStripModel::CLOSE_NONE); } } content::WebContents* web_contents() { return browser()->tab_strip_model()->GetActiveWebContents(); } private: content::test::PrerenderTestHelper prerender_helper_; }; // Tests that the prerender doesn't proceed HTTP auth login and once the page // is loaded as the primary page the prompt is shown. As the page is // not loaded from the prerender, it also checks if it's not activated from the // prerender. IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest, ChromePasswordManagerClientInPrerender) { content::NavigationController* nav_controller = &WebContents()->GetController(); LoginPromptBrowserTestObserver login_observer; login_observer.Register( content::Source<content::NavigationController>(nav_controller)); MockPrerenderPasswordManagerDriverInjector injector(WebContents()); GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::test::PrerenderHostRegistryObserver registry_observer( *WebContents()); auto prerender_url = embedded_test_server()->GetURL("/basic_auth"); // Loads a page requiring HTTP auth in the prerender. prerender_helper()->AddPrerenderAsync(prerender_url); // Ensure that the prerender has started. registry_observer.WaitForTrigger(prerender_url); auto prerender_id = prerender_helper()->GetHostForUrl(prerender_url); EXPECT_NE(content::RenderFrameHost::kNoFrameTreeNodeId, prerender_id); content::test::PrerenderHostObserver host_observer(*WebContents(), prerender_id); // PrerenderHost is destroyed by net::INVALID_AUTH_CREDENTIALS and it stops // prerendering. host_observer.WaitForDestroyed(); BubbleObserver bubble_observer(WebContents()); EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically()); WindowedAuthNeededObserver auth_needed_observer(nav_controller); // Navigates the primary page to the URL. prerender_helper()->NavigatePrimaryPage(prerender_url); auth_needed_observer.Wait(); NavigationObserver nav_observer(WebContents()); WindowedAuthSuppliedObserver auth_supplied_observer(nav_controller); // Offer valid credentials on the auth challenge. EXPECT_EQ(1u, login_observer.handlers().size()); LoginHandler* handler = *login_observer.handlers().begin(); EXPECT_TRUE(handler); // Any username/password will work. handler->SetAuth(u"user", u"pwd"); auth_supplied_observer.Wait(); // The password manager should be working correctly. nav_observer.Wait(); WaitForPasswordStore(); EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); // Make sure that the prerender was not activated. EXPECT_FALSE(host_observer.was_activated()); } // Tests that saving password doesn't work in the prerendering. IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest, SavePasswordInPrerender) { MockPrerenderPasswordManagerDriverInjector injector(WebContents()); GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); auto prerender_url = embedded_test_server()->GetURL("/password/password_form.html"); // Loads a page in the prerender. int host_id = prerender_helper()->AddPrerender(prerender_url); content::test::PrerenderHostObserver host_observer(*WebContents(), host_id); content::RenderFrameHost* render_frame_host = prerender_helper()->GetPrerenderedMainFrameHost(host_id); // Fills a form and submits through a <input type="submit"> button. std::string fill_and_submit = "document.getElementById('username_field').value = 'temp';" "document.getElementById('password_field').value = 'random';" "document.getElementById('input_submit_button').click()"; ASSERT_TRUE(content::ExecuteScript(render_frame_host, fill_and_submit)); // Since navigation from a prerendering page is disallowed, prerendering is // canceled. This also means that we should never make any calls to the mocked // driver. Since we've already set an expectation of no calls, this will be // checked implicitly when the injector (and consequently, the mock) is // destroyed. host_observer.WaitForDestroyed(); BubbleObserver bubble_observer(WebContents()); EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically()); // Navigates the primary page to the URL. prerender_helper()->NavigatePrimaryPage(prerender_url); // Makes sure that the page is not from the prerendering. EXPECT_FALSE(host_observer.was_activated()); // After loading the primary page, try to submit the password. NavigationObserver observer(WebContents()); ASSERT_TRUE(content::ExecuteScript(WebContents(), fill_and_submit)); observer.Wait(); // Saves the password and checks the store. EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically()); bubble_observer.AcceptSavePrompt(); WaitForPasswordStore(); CheckThatCredentialsStored("temp", "random"); } // Tests that it defers to bind mojom::CredentialManager in the prerendering. IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest, BindCredentialManagerInPrerender) { MockPrerenderPasswordManagerDriverInjector injector(WebContents()); GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); auto prerender_url = embedded_test_server()->GetURL("/password/credentials.html"); // Loads a page in the prerender. int host_id = prerender_helper()->AddPrerender(prerender_url); content::test::PrerenderHostObserver host_observer(*WebContents(), host_id); // It should not have binding mojom::CredentialManager. EXPECT_FALSE(ChromePasswordManagerClient::FromWebContents(WebContents()) ->has_binding_for_credential_manager()); // Navigates the primary page to the URL. prerender_helper()->NavigatePrimaryPage(prerender_url); // Waits until credentials.get() is handled. base::RunLoop().RunUntilIdle(); // Make sure that the prerender was activated. EXPECT_TRUE(host_observer.was_activated()); // After the page is activated, it gets binding mojom::CredentialManager. EXPECT_TRUE(ChromePasswordManagerClient::FromWebContents(WebContents()) ->has_binding_for_credential_manager()); } // Tests that RenderWidgetHost::InputEventObserver is updated with the // RenderFrameHost that NavigationHandle has when the RenderFrameHost is // activated from the prerendering. IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest, InputWorksAfterPrerenderActivation) { GetNewTabWithTestPasswordManagerClient(); GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); auto prerender_url = embedded_test_server()->GetURL("/password/password_form.html"); // Loads a page in the prerender. int host_id = prerender_helper()->AddPrerender(prerender_url); content::test::PrerenderHostObserver host_observer(*web_contents(), host_id); content::RenderFrameHost* render_frame_host = prerender_helper()->GetPrerenderedMainFrameHost(host_id); // Navigates the primary page to the URL. prerender_helper()->NavigatePrimaryPage(prerender_url); // Makes sure that the page is activated from the prerendering. EXPECT_TRUE(host_observer.was_activated()); base::RunLoop().RunUntilIdle(); // Sets to ignore mouse events. Otherwise, OnInputEvent() could be called // multiple times if the mouse cursor is over on the test window during // testing. web_contents()->GetMainFrame()->GetRenderWidgetHost()->AddMouseEventCallback( base::BindRepeating( [](const blink::WebMouseEvent& event) { return true; })); EXPECT_CALL( *static_cast<TestPasswordManagerClient*>( ChromePasswordManagerClient::FromWebContents(web_contents())), OnInputEvent(IsKeyEvent(blink::WebInputEvent::Type::kRawKeyDown))); // Sends a key event. SendKey(::ui::VKEY_DOWN, render_frame_host); } // Tests that Mojo messages in prerendering are deferred from the render to // the PasswordManagerDriver until activation. IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest, MojoDeferringInPrerender) { GetNewTabWithTestPasswordManagerClient(); MockPrerenderPasswordManagerDriverInjector injector(web_contents()); GURL url = embedded_test_server()->GetURL("/empty.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); auto prerender_url = embedded_test_server()->GetURL("/password/password_form.html"); // Loads a page in the prerender. int host_id = prerender_helper()->AddPrerender(prerender_url); content::test::PrerenderHostObserver host_observer(*web_contents(), host_id); content::RenderFrameHost* render_frame_host = prerender_helper()->GetPrerenderedMainFrameHost(host_id); auto* mock = injector.GetMockForFrame(render_frame_host); testing::Mock::VerifyAndClearExpectations(mock); // We expect that messages will be sent to the driver, post-activation. EXPECT_CALL(*mock, PasswordFormsParsed).Times(1); EXPECT_CALL(*mock, PasswordFormsRendered).Times(1); // Navigates the primary page to the URL. prerender_helper()->NavigatePrimaryPage(prerender_url); // Makes sure that the page is activated from the prerendering. EXPECT_TRUE(host_observer.was_activated()); mock->WaitForPasswordFormParsedAndRendered(); } } // namespace } // namespace password_manager
44.413771
96
0.7406
[ "geometry", "render", "vector" ]
9cd5bba75fdc38ea5c332ba338fc19cf095d9ee6
1,958
hpp
C++
examples/images/ImageTFLiteInfModel.hpp
teyenliu/nodeeditor
a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e
[ "BSD-3-Clause" ]
null
null
null
examples/images/ImageTFLiteInfModel.hpp
teyenliu/nodeeditor
a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e
[ "BSD-3-Clause" ]
null
null
null
examples/images/ImageTFLiteInfModel.hpp
teyenliu/nodeeditor
a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <iostream> #include <QtCore/QObject> #include <QtWidgets/QLabel> #include <QThread> #include <nodes/DataModelRegistry> #include <nodes/NodeDataModel> #include <opencv2/imgproc/imgproc.hpp> #include "ImageShowModel.hpp" #include "PixmapData.hpp" #include "TFLiteTools.hpp" using QtNodes::PortType; using QtNodes::PortIndex; using QtNodes::NodeData; using QtNodes::NodeDataType; using QtNodes::NodeDataModel; using QtNodes::NodeValidationState; class LiteObject:public QObject { Q_OBJECT public: LiteObject() { const QString tflite_file = QString("/usr/local/tf_libs/resources/inception_v3.tflite"); const QString label_file = QString("/usr/local/tf_libs/resources/imagenet_slim_labels.txt"); _tftools = new TFLiteTools(tflite_file, label_file); } ~LiteObject() { if (_tftools != nullptr ) delete _tftools; } signals: void sendResults(const QString &); public slots: void runTask(const QPixmap &); private: TFLiteTools *_tftools; }; /// The model dictates the number of inputs and outputs for the Node. /// In this example it has no logic. class ImageTFLiteInfModel : public ImageShowModel { Q_OBJECT public: ImageTFLiteInfModel(); ~ImageTFLiteInfModel() override { _workerThread.quit(); _workerThread.wait(); } // Threading public slots: void handleResults(const QString &); signals: void triggerTask(const QPixmap &); public: QString caption() const override { return QString("TFLite Inference Display"); } QString name() const override { return QString("ImageTFLiteInfModel"); } public: virtual QString modelName() const override { return QString("TFLite Inference Image"); } void setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) override; protected: bool eventFilter(QObject *object, QEvent *event) override; LiteObject *_liteObj; QThread _workerThread; };
19.58
100
0.717569
[ "object", "model" ]
9cd6205c08a15d702edc1acf4914dd6e6bc24dc1
29,577
cpp
C++
src/polycubed/src/rest_server.cpp
ali919191/polycube
178fe6e9101b27366d607948ec04f78be6d4fa68
[ "ECL-2.0", "Apache-2.0" ]
1
2019-10-02T23:09:42.000Z
2019-10-02T23:09:42.000Z
src/polycubed/src/rest_server.cpp
ricjames11/polycube
2e4f4e2081eca0322e4729434aff897a6cac84fa
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/polycubed/src/rest_server.cpp
ricjames11/polycube
2e4f4e2081eca0322e4729434aff897a6cac84fa
[ "ECL-2.0", "Apache-2.0" ]
1
2019-09-02T10:05:14.000Z
2019-09-02T10:05:14.000Z
/* * Copyright 2017 The Polycube 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 * * 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 "rest_server.h" #include <string> #include <vector> #include <fstream> #include "polycubed_core.h" #include "service_controller.h" #include "version.h" #include "utils/netlink.h" #include "polycube/services/response.h" #include "server/Resources/Data/AbstractFactory.h" #include "server/Server/ResponseGenerator.h" #include "config.h" #include "cubes_dump.h" #include "server/Resources/Endpoint/Hateoas.h" namespace polycube { namespace polycubed { std::string RestServer::whitelist_cert_path; std::string RestServer::blacklist_cert_path; const std::string RestServer::base = "/polycube/v1/"; // start http server for Management APIs // Encapsulate a core object // TODO probably there are best ways... RestServer::RestServer(Pistache::Address addr, PolycubedCore &core) : core(core), host(addr.host()), port(addr.port().toString()), httpEndpoint_(std::make_unique<Pistache::Http::Endpoint>(addr)), logger(spdlog::get("polycubed")) { logger->info("rest server listening on '{0}:{1}'", addr.host(), addr.port()); router_ = std::make_shared<Pistache::Rest::Router>(); } std::shared_ptr<Pistache::Rest::Router> RestServer::get_router() { return router_; } static X509_STORE_CTX *load_certificates(const char *path) { X509_STORE *store; X509_STORE_CTX *ctx; store = X509_STORE_new(); X509_STORE_load_locations(store, nullptr, path); ctx = X509_STORE_CTX_new(); X509_STORE_CTX_init(ctx, store, nullptr, nullptr); return ctx; } #ifndef X509_STORE_get1_cert #define X509_STORE_get1_cert X509_STORE_get1_certs #endif static bool lookup_cert_match(X509_STORE_CTX *ctx, X509 *x) { STACK_OF(X509) * certs; X509 *xtmp = nullptr; int i; bool found = false; /* Lookup all certs with matching subject name */ certs = X509_STORE_get1_cert(ctx, X509_get_subject_name(x)); if (certs == nullptr) return found; /* Look for exact match */ for (i = 0; i < sk_X509_num(certs); i++) { xtmp = sk_X509_value(certs, i); if (!X509_cmp(xtmp, x)) { found = true; break; } } sk_X509_pop_free(certs, X509_free); return found; } int RestServer::client_verify_callback(int preverify_ok, void *ctx) { X509_STORE_CTX *x509_ctx = (X509_STORE_CTX *)ctx; int depth = X509_STORE_CTX_get_error_depth(x509_ctx); if (depth == 0) { X509 *cert = X509_STORE_CTX_get_current_cert(x509_ctx); X509_STORE_CTX *list; // if certificate is on white list we don't care about preverify if (!RestServer::whitelist_cert_path.empty()) { list = load_certificates(RestServer::whitelist_cert_path.c_str()); return lookup_cert_match(list, cert); } // at this point certificate should also pass ca verification, test it if (!preverify_ok) return preverify_ok; // test that the certificate is not on a black list if (!RestServer::blacklist_cert_path.empty()) { list = load_certificates(RestServer::blacklist_cert_path.c_str()); return !lookup_cert_match(list, cert); } } return preverify_ok; } void RestServer::init(size_t thr, size_t max_payload_size, const std::string &server_cert, const std::string &server_key, const std::string &root_ca_cert, const std::string &whitelist_cert_path_, const std::string &blacklist_cert_path_) { logger->debug("rest server will use {0} thread(s)", thr); auto opts = Pistache::Http::Endpoint::options() .threads(thr) .maxPayload(max_payload_size) .flags(Pistache::Tcp::Options::InstallSignalHandler | Pistache::Tcp::Options::ReuseAddr); httpEndpoint_->init(opts); if (!server_cert.empty()) { httpEndpoint_->useSSL(server_cert, server_key); } if (!root_ca_cert.empty() || !whitelist_cert_path_.empty() || !blacklist_cert_path_.empty()) { httpEndpoint_->useSSLAuth(root_ca_cert, "", client_verify_callback); } RestServer::whitelist_cert_path = whitelist_cert_path_; RestServer::blacklist_cert_path = blacklist_cert_path_; setup_routes(); } void RestServer::start() { logger->info("rest server starting ..."); httpEndpoint_->setHandler(Pistache::Rest::Router::handler(router_)); httpEndpoint_->serveThreaded(); } void RestServer::shutdown() { logger->info("shutting down rest server ..."); try { httpEndpoint_->shutdown(); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); } } void RestServer::create_cubes(json &cubes) { /* * This is possible that a cube's port has as peer another port * of a cube that hasn't been created yet. This logic removes all * the peers from the request and sets them after all cubes have * been created. */ auto peers = utils::strip_port_peers(cubes); std::vector<Response> resp = {{ErrorTag::kNoContent, nullptr}}; bool error = false; for (auto &cube : cubes) { auto &s = core.get_service_controller(cube["service-name"]); auto res = s.get_management_interface()->get_service() ->CreateReplaceUpdate(cube["name"], cube, false, true); if (res.size() != 1 || res[0].error_tag != kCreated) { std::string msg; for (auto & r: res) { //logger->debug("- {}", r.message); msg += std::string(r.message) + " "; } throw std::runtime_error("Error creating cube: " + cube["name"].get<std::string>() + msg); } } for (auto &[peer1, peer2] : peers) { core.try_to_set_peer(peer1, peer2); } } void RestServer::load_last_topology() { logger->info("loading cubes from {}", configuration::config.getCubesDumpFile()); std::ifstream topologyFile(configuration::config.getCubesDumpFile()); if (!topologyFile.is_open()) { return; } std::stringstream buffer; buffer << topologyFile.rdbuf(); topologyFile.close(); // parse the file and create and initialize each cube one by one try { json jcubes = json::parse(buffer.str()); logJson(jcubes); create_cubes(jcubes); } catch (const std::exception &e) { logger->error("{0}", e.what()); } } void RestServer::setup_routes() { using Pistache::Rest::Routes::bind; router_->options(base + std::string("/"), bind(&RestServer::root_handler, this)); /* binding root_handler in order to handle get at root. * It's necessary to provide a way to reach the root to the client. * Thanks this the client can explore the service using Hateoas. * * see server/Resources/Endpoint/Hateoas.h */ router_->get(base + std::string("/"), bind(&RestServer::get_root_handler, this)); // servicectrls router_->post(base + std::string("/services"), bind(&RestServer::post_servicectrl, this)); router_->get(base + std::string("/services"), bind(&RestServer::get_servicectrls, this)); router_->get(base + std::string("/services/:name"), bind(&RestServer::get_servicectrl, this)); router_->del(base + std::string("/services/:name"), bind(&RestServer::delete_servicectrl, this)); Hateoas::addRoute("services", base); // cubes router_->get(base + std::string("/cubes"), bind(&RestServer::get_cubes, this)); router_->get(base + std::string("/cubes/:cubeName"), bind(&RestServer::get_cube, this)); router_->post(base + std::string("/cubes"), bind(&RestServer::post_cubes, this)); router_->options(base + std::string("/cubes"), bind(&RestServer::cubes_help, this)); router_->options(base + std::string("/cubes/:cubeName"), bind(&RestServer::cube_help, this)); Hateoas::addRoute("cubes", base); // netdevs router_->get(base + std::string("/netdevs"), bind(&RestServer::get_netdevs, this)); router_->get(base + std::string("/netdevs/:name"), bind(&RestServer::get_netdev, this)); router_->options(base + std::string("/netdevs"), bind(&RestServer::netdevs_help, this)); router_->options(base + std::string("/netdevs/:netdevName"), bind(&RestServer::netdev_help, this)); Hateoas::addRoute("netdevs", base); // version router_->get(base + std::string("/version"), bind(&RestServer::get_version, this)); Hateoas::addRoute("version", base); // connect & disconnect router_->post(base + std::string("/connect"), bind(&RestServer::connect, this)); router_->post(base + std::string("/disconnect"), bind(&RestServer::disconnect, this)); router_->options(base + std::string("/connect"), bind(&RestServer::connect_help, this)); Hateoas::addRoute("connect", base); Hateoas::addRoute("disconnect", base); // attach & detach router_->post(base + std::string("/attach"), bind(&RestServer::attach, this)); router_->post(base + std::string("/detach"), bind(&RestServer::detach, this)); Hateoas::addRoute("attach", base); Hateoas::addRoute("detach", base); // topology router_->get(base + std::string("/topology"), bind(&RestServer::topology, this)); router_->get(base + std::string("/topology/:ifname"), bind(&RestServer::get_if_topology, this)); router_->options(base + std::string("/topology"), bind(&RestServer::topology_help, this)); Hateoas::addRoute("topology", base); router_->addNotFoundHandler(bind(&RestServer::redirect, this)); } void RestServer::logRequest(const Pistache::Rest::Request &request) { // logger->debug("{0} : {1}", request.method(), request.resource()); #ifdef LOG_DEBUG_REQUEST_ logger->debug(request.method() + ": " + request.resource()); logger->debug(request.body()); #endif } void RestServer::logJson(json j) { #ifdef LOG_DEBUG_JSON_ logger->debug("JSON Dump: \n"); logger->debug(j.dump()); #endif } void RestServer::get_root_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { auto js = Hateoas::HateoasSupport_root(request, host, port); Rest::Server::ResponseGenerator::Generate({{kOk, ::strdup(js.dump().c_str())}}, std::move(response)); } void RestServer::root_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { auto help = request.query().get("help").getOrElse("NO_HELP"); if (help == "NO_HELP") { Rest::Server::ResponseGenerator::Generate({{kOk, nullptr}}, std::move(response)); return; } HelpType type; if (help == "NONE") { type = NONE; } else { Rest::Server::ResponseGenerator::Generate({{kBadRequest, nullptr}}, std::move(response)); return; } auto completion = request.query().has("completion"); if (!completion) { return root_help(type, std::move(response)); } else { return root_completion(type, std::move(response)); } } void RestServer::root_help(HelpType help_type, Pistache::Http::ResponseWriter response) { if (help_type == HelpType::NONE) { json j; auto services = core.get_servicectrls_list(); for (auto &it : services) { std::string service_name = it->get_name(); j["params"][service_name]["name"] = service_name; j["params"][service_name]["simpletype"] = "service"; j["params"][service_name]["type"] = "leaf"; j["params"][service_name]["description"] = it->get_description(); j["params"][service_name]["version"] = it->get_version(); j["params"][service_name]["pyang_repo_id"] = it->get_pyang_git_repo_id(); j["params"][service_name]["swagger_codegen_repo_id"] = it->get_swagger_codegen_git_repo_id(); } response.send(Pistache::Http::Code::Ok, j.dump()); } } void RestServer::root_completion(HelpType help_type, Pistache::Http::ResponseWriter response) { if (help_type == HelpType::NONE) { json val = json::array(); // fixed commands val += "connect"; val += "disconnect"; val += "attach"; val += "detach"; val += "services"; val += "cubes"; val += "topology"; val += "netdevs"; // services auto services = core.get_servicectrls_list(); for (auto &it : services) { val += it->get_name(); } // cubes auto cubes =ServiceController::get_all_cubes(); for (auto &it : cubes) { val += it->get_name(); } response.send(Pistache::Http::Code::Ok, val.dump()); } } void RestServer::post_servicectrl(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { json j = json::parse(request.body()); logJson(j); if (j.count("type") == 0) { Rest::Server::ResponseGenerator::Generate( std::vector<Response>{{ErrorTag::kMissingAttribute, strdup("type")}}, std::move(response)); return; } if (j.count("uri") == 0) { Rest::Server::ResponseGenerator::Generate( std::vector<Response>{{ErrorTag::kMissingAttribute, strdup("uri")}}, std::move(response)); return; } if (j.count("name") == 0) { Rest::Server::ResponseGenerator::Generate( std::vector<Response>{{ErrorTag::kMissingAttribute, strdup("name")}}, std::move(response)); return; } // parse type && URI (servicecontroller) auto jtype = j["type"].get<std::string>(); auto uri = j["uri"].get<std::string>(); auto name = j["name"].get<std::string>(); ServiceControllerType type; if (jtype == "lib") { type = ServiceControllerType::LIBRARY; } else if (jtype == "grpc") { type = ServiceControllerType::DAEMON; } else { Rest::Server::ResponseGenerator::Generate( std::vector<Response>{{ErrorTag::kBadAttribute, strdup("type")}}, std::move(response)); return; } core.add_servicectrl(name, type, base, uri); response.send(Pistache::Http::Code::Ok); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_servicectrls(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { std::string retJsonStr = core.get_servicectrls(); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_servicectrl(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { auto name = request.param(":name").as<std::string>(); std::string retJsonStr = core.get_servicectrl(name); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::delete_servicectrl(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { auto name = request.param(":name").as<std::string>(); core.delete_servicectrl(name); response.send(Pistache::Http::Code::No_Content); } catch (const std::invalid_argument &e) { Rest::Server::ResponseGenerator::Generate( std::vector<Response>{{ErrorTag::kDataMissing, nullptr}}, std::move(response)); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_cubes(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { std::string retJsonStr = core.get_cubes(); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_cube(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { auto name = request.param(":cubeName").as<std::string>(); std::string retJsonStr = core.get_cube(name); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::post_cubes(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { json cubes = json::parse(request.body()); logJson(cubes); create_cubes(cubes); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::cubes_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json j = json::object(); auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE" && help != "SHOW") { response.send(Pistache::Http::Code::Bad_Request); return; } json params = json::object(); params["name"]["name"] = "name"; params["name"]["type"] = "key"; params["name"]["simpletype"] = "string"; params["name"]["description"] = "Cube Name"; params["name"]["example"] = "cube0"; j["params"] = params; json j_cubes = json::array(); auto cubes = ServiceController::get_all_cubes(); for (auto &it : cubes) { json j_cube = json::object(); j_cube["cube"] = it->get_name(); j_cubes += j_cube; } j["elements"] = j_cubes; if (help == "NONE") { j["commands"] = {"show"}; } response.send(Pistache::Http::Code::Ok, j.dump()); } void RestServer::cube_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json j = json::object(); auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE") { response.send(Pistache::Http::Code::Bad_Request); return; } j["commands"] = {"show"}; response.send(Pistache::Http::Code::Ok, j.dump()); } void RestServer::get_netdevs(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { std::string retJsonStr = core.get_netdevs(); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_netdev(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { auto name = request.param(":name").as<std::string>(); std::string retJsonStr = core.get_netdev(name); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::netdevs_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json j = json::object(); auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE" && help != "SHOW") { response.send(Pistache::Http::Code::Bad_Request); return; } json params = json::object(); params["name"]["name"] = "name"; params["name"]["type"] = "key"; params["name"]["simpletype"] = "string"; params["name"]["description"] = "Netdev name"; params["name"]["example"] = "eth0"; j["params"] = params; auto netdevs = Netlink::getInstance().get_available_ifaces(); json j_netdevs = json::array(); for (auto &it : netdevs) { json j_netdev = json::object(); j_netdev["netdev"] = it.first; j_netdevs += j_netdev; } j["elements"] = j_netdevs; if (help == "NONE") { j["commands"] = {"show"}; } response.send(Pistache::Http::Code::Ok, j.dump()); } void RestServer::netdev_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json j = json::object(); auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE") { response.send(Pistache::Http::Code::Bad_Request); return; } j["commands"] = {"show"}; response.send(Pistache::Http::Code::Ok, j.dump()); } void RestServer::get_version(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json version = json::object(); version["polycubed"]["version"] = VERSION; response.send(Pistache::Http::Code::Ok, version.dump()); } void RestServer::connect(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); std::string peer1, peer2; nlohmann::json val = nlohmann::json::parse(request.body()); if (val.find("peer1") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Peer 1 is missing"); } peer1 = val.at("peer1"); if (val.find("peer2") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Peer 2 is missing"); } peer2 = val.at("peer2"); try { core.connect(peer1, peer2); response.send(Pistache::Http::Code::Ok); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::disconnect(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); std::string peer1, peer2; nlohmann::json val = nlohmann::json::parse(request.body()); if (val.find("peer1") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Peer 1 is missing"); } peer1 = val.at("peer1"); if (val.find("peer2") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Peer 2 is missing"); } peer2 = val.at("peer2"); try { core.disconnect(peer1, peer2); response.send(Pistache::Http::Code::Ok); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::connect_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE") { response.send(Pistache::Http::Code::Bad_Request); return; } auto completion = request.query().has("completion"); if (completion) { return connect_completion("", std::move(response)); } response.send(Pistache::Http::Code::Ok, "not implemented");; } void RestServer::connect_completion(const std::string &p1, Pistache::Http::ResponseWriter response) { auto ports = core.get_all_ports(); if (!p1.empty()) { std::string p(p1); //ports.erase(p); ports.erase(std::remove(ports.begin(), ports.end(), p1), ports.end()); } json val = ports; response.send(Pistache::Http::Code::Ok, val.dump()); } void RestServer::attach(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); std::string cube, port, position, other; bool position_(false); nlohmann::json val = nlohmann::json::parse(request.body()); if (val.find("cube") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Cube is missing"); return; } cube = val.at("cube"); if (val.find("port") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Port is missing"); return; } port = val.at("port"); position = "auto"; // default value if (val.find("position") != val.end()) { position = val.at("position"); position_ = true; } if (val.find("after") != val.end()) { if (position_) { response.send(Pistache::Http::Code::Bad_Request, "position and after cannot be used together"); return; } position = "after"; other = val.at("after"); } if (val.find("before") != val.end()) { if (position_) { response.send(Pistache::Http::Code::Bad_Request, "position and before cannot be used together"); return; } if (!other.empty()) { response.send(Pistache::Http::Code::Bad_Request, "after and before cannot be used together"); return; } position = "before"; other = val.at("before"); } try { core.attach(cube, port, position, other); response.send(Pistache::Http::Code::Ok); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::detach(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); std::string cube, port; nlohmann::json val = nlohmann::json::parse(request.body()); if (val.find("cube") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Cube is missing"); return; } cube = val.at("cube"); if (val.find("port") == val.end()) { response.send(Pistache::Http::Code::Bad_Request, "Port is missing"); return; } port = val.at("port"); try { core.detach(cube, port); response.send(Pistache::Http::Code::Ok); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::topology(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { std::string retJsonStr = core.topology(); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::get_if_topology(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { logRequest(request); try { auto ifname = request.param(":ifname").as<std::string>(); std::string retJsonStr = core.get_if_topology(ifname); response.send(Pistache::Http::Code::Ok, retJsonStr); } catch (const std::runtime_error &e) { logger->error("{0}", e.what()); response.send(Pistache::Http::Code::Bad_Request, e.what()); } } void RestServer::topology_help(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { json j = json::object(); auto help = request.query().get("help").getOrElse("NO_HELP"); if (help != "NONE") { response.send(Pistache::Http::Code::Bad_Request); return; } j["commands"] = {"show"}; response.send(Pistache::Http::Code::Ok, j.dump()); } void RestServer::redirect(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { if (request.headers().has("Referer") || request.headers().rawList().count("Referer") == 1) { response.send(Pistache::Http::Code::Not_Found, "Cannot find a matching route."); return; } std::string url = request.resource(); if (url.find(base) == std::string::npos) { response.send(Pistache::Http::Code::Not_Found, "Cannot find a matching route."); return; } auto base_length = base.length(); std::string cube_name = url.substr(base_length, url.find('/', base_length) - base_length); const auto &service_name = ServiceController::get_cube_service(cube_name); if (service_name.length() == 0) { response.send(Pistache::Http::Code::Not_Found, "No cube found named " + cube_name); return; } std::string redirect = request.resource() + request.query().as_str(); redirect.insert(base_length, service_name + '/'); auto location = Pistache::Http::Header::Location(redirect); response.headers().add<Pistache::Http::Header::Location>(location); response.send(Pistache::Http::Code::Permanent_Redirect); } const std::string &RestServer::getHost() { return host; } const std::string &RestServer::getPort() { return port; } } // namespace polycubed } // namespace polycube
31.599359
96
0.626264
[ "object", "vector" ]
9cd6821907722002079a00df757768016cac0c01
11,630
cc
C++
src/builtins/builtins.cc
earlymeme/v8
3f9bd13d6131ea64711002ef2e59e53c086cb286
[ "BSD-3-Clause" ]
null
null
null
src/builtins/builtins.cc
earlymeme/v8
3f9bd13d6131ea64711002ef2e59e53c086cb286
[ "BSD-3-Clause" ]
4
2017-04-12T05:55:21.000Z
2017-05-09T12:46:15.000Z
src/builtins/builtins.cc
earlymeme/v8
3f9bd13d6131ea64711002ef2e59e53c086cb286
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/builtins/builtins.h" #include "src/api.h" #include "src/assembler-inl.h" #include "src/builtins/builtins-descriptors.h" #include "src/callable.h" #include "src/isolate.h" #include "src/macro-assembler.h" #include "src/objects-inl.h" #include "src/visitors.h" namespace v8 { namespace internal { // Forward declarations for C++ builtins. #define FORWARD_DECLARE(Name) \ Object* Builtin_##Name(int argc, Object** args, Isolate* isolate); BUILTIN_LIST_C(FORWARD_DECLARE) #undef FORWARD_DECLARE namespace { // TODO(jgruber): Pack in CallDescriptors::Key. struct BuiltinMetadata { const char* name; Builtins::Kind kind; union { Address cpp_entry; // For CPP and API builtins. int8_t parameter_count; // For TFJ builtins. } kind_specific_data; }; // clang-format off #define DECL_CPP(Name, ...) { #Name, Builtins::CPP, \ { FUNCTION_ADDR(Builtin_##Name) }}, #define DECL_API(Name, ...) { #Name, Builtins::API, \ { FUNCTION_ADDR(Builtin_##Name) }}, #ifdef V8_TARGET_BIG_ENDIAN #define DECL_TFJ(Name, Count, ...) { #Name, Builtins::TFJ, \ { reinterpret_cast<Address>(static_cast<uintptr_t>( \ Count) << (kBitsPerByte * (kPointerSize - 1))) }}, #else #define DECL_TFJ(Name, Count, ...) { #Name, Builtins::TFJ, \ { reinterpret_cast<Address>(Count) }}, #endif #define DECL_TFC(Name, ...) { #Name, Builtins::TFC, {} }, #define DECL_TFS(Name, ...) { #Name, Builtins::TFS, {} }, #define DECL_TFH(Name, ...) { #Name, Builtins::TFH, {} }, #define DECL_ASM(Name, ...) { #Name, Builtins::ASM, {} }, const BuiltinMetadata builtin_metadata[] = { BUILTIN_LIST(DECL_CPP, DECL_API, DECL_TFJ, DECL_TFC, DECL_TFS, DECL_TFH, DECL_ASM) }; #undef DECL_CPP #undef DECL_API #undef DECL_TFJ #undef DECL_TFC #undef DECL_TFS #undef DECL_TFH #undef DECL_ASM // clang-format on } // namespace Builtins::Builtins() : initialized_(false) { memset(builtins_, 0, sizeof(builtins_[0]) * builtin_count); } Builtins::~Builtins() {} BailoutId Builtins::GetContinuationBailoutId(Name name) { DCHECK(Builtins::KindOf(name) == TFJ || Builtins::KindOf(name) == TFC); return BailoutId(BailoutId::kFirstBuiltinContinuationId + name); } Builtins::Name Builtins::GetBuiltinFromBailoutId(BailoutId id) { int builtin_index = id.ToInt() - BailoutId::kFirstBuiltinContinuationId; DCHECK(Builtins::KindOf(builtin_index) == TFJ || Builtins::KindOf(builtin_index) == TFC); return static_cast<Name>(builtin_index); } void Builtins::TearDown() { initialized_ = false; } void Builtins::IterateBuiltins(RootVisitor* v) { v->VisitRootPointers(Root::kBuiltins, &builtins_[0], &builtins_[0] + builtin_count); } const char* Builtins::Lookup(byte* pc) { // may be called during initialization (disassembler!) if (initialized_) { for (int i = 0; i < builtin_count; i++) { Code* entry = Code::cast(builtins_[i]); if (entry->contains(pc)) return name(i); } } return NULL; } Handle<Code> Builtins::NewFunctionContext(ScopeType scope_type) { switch (scope_type) { case ScopeType::EVAL_SCOPE: return builtin_handle(kFastNewFunctionContextEval); case ScopeType::FUNCTION_SCOPE: return builtin_handle(kFastNewFunctionContextFunction); default: UNREACHABLE(); } return Handle<Code>::null(); } Handle<Code> Builtins::NonPrimitiveToPrimitive(ToPrimitiveHint hint) { switch (hint) { case ToPrimitiveHint::kDefault: return builtin_handle(kNonPrimitiveToPrimitive_Default); case ToPrimitiveHint::kNumber: return builtin_handle(kNonPrimitiveToPrimitive_Number); case ToPrimitiveHint::kString: return builtin_handle(kNonPrimitiveToPrimitive_String); } UNREACHABLE(); } Handle<Code> Builtins::OrdinaryToPrimitive(OrdinaryToPrimitiveHint hint) { switch (hint) { case OrdinaryToPrimitiveHint::kNumber: return builtin_handle(kOrdinaryToPrimitive_Number); case OrdinaryToPrimitiveHint::kString: return builtin_handle(kOrdinaryToPrimitive_String); } UNREACHABLE(); } void Builtins::set_builtin(int index, HeapObject* builtin) { DCHECK(Builtins::IsBuiltinId(index)); DCHECK(Internals::HasHeapObjectTag(builtin)); // The given builtin may be completely uninitialized thus we cannot check its // type here. builtins_[index] = builtin; } Handle<Code> Builtins::builtin_handle(int index) { DCHECK(IsBuiltinId(index)); return Handle<Code>(reinterpret_cast<Code**>(builtin_address(index))); } // static int Builtins::GetStackParameterCount(Name name) { DCHECK(Builtins::KindOf(name) == TFJ); return builtin_metadata[name].kind_specific_data.parameter_count; } // static Callable Builtins::CallableFor(Isolate* isolate, Name name) { Handle<Code> code( reinterpret_cast<Code**>(isolate->builtins()->builtin_address(name))); CallDescriptors::Key key; switch (name) { // This macro is deliberately crafted so as to emit very little code, // in order to keep binary size of this function under control. #define CASE_OTHER(Name, ...) \ case k##Name: { \ key = Builtin_##Name##_InterfaceDescriptor::key(); \ break; \ } BUILTIN_LIST(IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN, CASE_OTHER, CASE_OTHER, CASE_OTHER, IGNORE_BUILTIN) #undef CASE_OTHER case kConsoleAssert: { return Callable(code, BuiltinDescriptor(isolate)); } case kArrayForEach: { Handle<Code> code = BUILTIN_CODE(isolate, ArrayForEach); return Callable(code, BuiltinDescriptor(isolate)); } case kArrayForEachLoopEagerDeoptContinuation: { Handle<Code> code = BUILTIN_CODE(isolate, ArrayForEachLoopEagerDeoptContinuation); return Callable(code, BuiltinDescriptor(isolate)); } case kArrayForEachLoopLazyDeoptContinuation: { Handle<Code> code = BUILTIN_CODE(isolate, ArrayForEachLoopLazyDeoptContinuation); return Callable(code, BuiltinDescriptor(isolate)); } case kArrayMapLoopEagerDeoptContinuation: { Handle<Code> code = BUILTIN_CODE(isolate, ArrayMapLoopEagerDeoptContinuation); return Callable(code, BuiltinDescriptor(isolate)); } case kArrayMapLoopLazyDeoptContinuation: { Handle<Code> code = BUILTIN_CODE(isolate, ArrayMapLoopLazyDeoptContinuation); return Callable(code, BuiltinDescriptor(isolate)); } default: UNREACHABLE(); } CallInterfaceDescriptor descriptor(isolate, key); return Callable(code, descriptor); } // static const char* Builtins::name(int index) { DCHECK(IsBuiltinId(index)); return builtin_metadata[index].name; } // static Address Builtins::CppEntryOf(int index) { DCHECK(Builtins::HasCppImplementation(index)); return builtin_metadata[index].kind_specific_data.cpp_entry; } // static bool Builtins::IsLazy(int index) { DCHECK(IsBuiltinId(index)); // There are a couple of reasons that builtins can require eager-loading, // i.e. deserialization at isolate creation instead of on-demand. For // instance: // * DeserializeLazy implements lazy loading. // * Immovability requirement. This can only conveniently be guaranteed at // isolate creation (at runtime, we'd have to allocate in LO space). // * To avoid conflicts in SharedFunctionInfo::function_data (Illegal, // HandleApiCall, interpreter entry trampolines). // * Frequent use makes lazy loading unnecessary (CompileLazy). // TODO(wasm): Remove wasm builtins once immovability is no longer required. switch (index) { case kAbort: // Required by wasm. case kArrayForEachLoopEagerDeoptContinuation: // https://crbug.com/v8/6786. case kArrayForEachLoopLazyDeoptContinuation: // https://crbug.com/v8/6786. case kArrayMapLoopEagerDeoptContinuation: // https://crbug.com/v8/6786. case kArrayMapLoopLazyDeoptContinuation: // https://crbug.com/v8/6786. case kCheckOptimizationMarker: case kCompileLazy: case kDeserializeLazy: case kFunctionPrototypeHasInstance: // https://crbug.com/v8/6786. case kHandleApiCall: case kIllegal: case kInterpreterEnterBytecodeAdvance: case kInterpreterEnterBytecodeDispatch: case kInterpreterEntryTrampoline: case kObjectConstructor_ConstructStub: // https://crbug.com/v8/6787. case kProxyConstructor_ConstructStub: // https://crbug.com/v8/6787. case kNumberConstructor_ConstructStub: // https://crbug.com/v8/6787. case kStringConstructor_ConstructStub: // https://crbug.com/v8/6787. case kProxyConstructor: // https://crbug.com/v8/6787. case kRecordWrite: // https://crbug.com/chromium/765301. case kThrowWasmTrapDivByZero: // Required by wasm. case kThrowWasmTrapDivUnrepresentable: // Required by wasm. case kThrowWasmTrapFloatUnrepresentable: // Required by wasm. case kThrowWasmTrapFuncInvalid: // Required by wasm. case kThrowWasmTrapFuncSigMismatch: // Required by wasm. case kThrowWasmTrapMemOutOfBounds: // Required by wasm. case kThrowWasmTrapRemByZero: // Required by wasm. case kThrowWasmTrapUnreachable: // Required by wasm. case kToNumber: // Required by wasm. case kWasmCompileLazy: // Required by wasm. case kWasmStackGuard: // Required by wasm. return false; default: // TODO(6624): Extend to other kinds. return KindOf(index) == TFJ; } UNREACHABLE(); } // static Builtins::Kind Builtins::KindOf(int index) { DCHECK(IsBuiltinId(index)); return builtin_metadata[index].kind; } // static const char* Builtins::KindNameOf(int index) { Kind kind = Builtins::KindOf(index); // clang-format off switch (kind) { case CPP: return "CPP"; case API: return "API"; case TFJ: return "TFJ"; case TFC: return "TFC"; case TFS: return "TFS"; case TFH: return "TFH"; case ASM: return "ASM"; } // clang-format on UNREACHABLE(); } // static bool Builtins::IsCpp(int index) { return Builtins::KindOf(index) == CPP; } // static bool Builtins::HasCppImplementation(int index) { Kind kind = Builtins::KindOf(index); return (kind == CPP || kind == API); } Handle<Code> Builtins::JSConstructStubGeneric() { return FLAG_harmony_restrict_constructor_return ? builtin_handle(kJSConstructStubGenericRestrictedReturn) : builtin_handle(kJSConstructStubGenericUnrestrictedReturn); } // static bool Builtins::AllowDynamicFunction(Isolate* isolate, Handle<JSFunction> target, Handle<JSObject> target_global_proxy) { if (FLAG_allow_unsafe_function_constructor) return true; HandleScopeImplementer* impl = isolate->handle_scope_implementer(); Handle<Context> responsible_context = impl->MicrotaskContextIsLastEnteredContext() ? impl->MicrotaskContext() : impl->LastEnteredContext(); // TODO(jochen): Remove this. if (responsible_context.is_null()) { return true; } if (*responsible_context == target->context()) return true; return isolate->MayAccess(responsible_context, target_global_proxy); } } // namespace internal } // namespace v8
35.457317
80
0.690112
[ "object" ]
9cd98628e788d95fc0f017ccc928aa610df0e9a3
5,269
cpp
C++
test/algorithms/within/within.cpp
jkerkela/geometry
4034ac88b214da0eab8943172eff0f1200b0a6cc
[ "BSL-1.0" ]
1
2020-04-28T15:15:28.000Z
2020-04-28T15:15:28.000Z
test/algorithms/within/within.cpp
jkerkela/geometry
4034ac88b214da0eab8943172eff0f1200b0a6cc
[ "BSL-1.0" ]
2
2017-05-23T08:01:11.000Z
2019-09-06T20:49:05.000Z
test/algorithms/within/within.cpp
jkerkela/geometry
4034ac88b214da0eab8943172eff0f1200b0a6cc
[ "BSL-1.0" ]
8
2015-11-03T14:12:19.000Z
2020-09-22T19:20:54.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland. // This file was modified by Oracle on 2014, 2015, 2016, 2018. // Modifications copyright (c) 2014-2018 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is 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_within.hpp" #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/geometries/multi_linestring.hpp> #include <boost/geometry/geometries/multi_polygon.hpp> template <typename P1, typename P2> void test_point_box() { typedef bg::model::box<P1> box_type1; typedef bg::model::box<P2> box_type2; test_geometry<P1, box_type2>("POINT(1 1)", "BOX(0 0,2 2)", true); test_geometry<P1, box_type2>("POINT(0 0)", "BOX(0 0,2 2)", false); test_geometry<P1, box_type2>("POINT(2 2)", "BOX(0 0,2 2)", false); test_geometry<P1, box_type2>("POINT(0 1)", "BOX(0 0,2 2)", false); test_geometry<P1, box_type2>("POINT(1 0)", "BOX(0 0,2 2)", false); test_geometry<P1, box_type2>("POINT(3 3)", "BOX(1 1,4 4)", true); test_geometry<P2, box_type1>("POINT(3 3)", "BOX(0 0,5 5)", true); test_geometry<box_type1, box_type2>("BOX(1 1,2 2)", "BOX(0 0,3 3)", true); test_geometry<box_type1, box_type2>("BOX(0 0,3 3)", "BOX(1 1,2 2)", false); test_geometry<box_type1, box_type2>("BOX(1 1,3 3)", "BOX(0 0,3 3)", true); test_geometry<box_type1, box_type2>("BOX(3 1,3 3)", "BOX(0 0,3 3)", false); test_geometry<box_type1, box_type2>("BOX(1 1,4 4)", "BOX(0 0,5 5)", true); test_geometry<box_type2, box_type1>("BOX(0 0,5 5)", "BOX(1 1,4 4)", false); /* test_within_code<P, box_type>("POINT(1 1)", "BOX(0 0,2 2)", 1); test_within_code<P, box_type>("POINT(1 0)", "BOX(0 0,2 2)", 0); test_within_code<P, box_type>("POINT(0 1)", "BOX(0 0,2 2)", 0); test_within_code<P, box_type>("POINT(0 3)", "BOX(0 0,2 2)", -1); test_within_code<P, box_type>("POINT(3 3)", "BOX(0 0,2 2)", -1); test_within_code<box_type, box_type>("BOX(1 1,2 2)", "BOX(0 0,3 3)", 1); test_within_code<box_type, box_type>("BOX(0 1,2 2)", "BOX(0 0,3 3)", 0); test_within_code<box_type, box_type>("BOX(1 0,2 2)", "BOX(0 0,3 3)", 0); test_within_code<box_type, box_type>("BOX(1 1,2 3)", "BOX(0 0,3 3)", 0); test_within_code<box_type, box_type>("BOX(1 1,3 2)", "BOX(0 0,3 3)", 0); test_within_code<box_type, box_type>("BOX(1 1,3 4)", "BOX(0 0,3 3)", -1); */ } void test_point_box_3d() { typedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> point_type; typedef boost::geometry::model::box<point_type> box_type; box_type box(point_type(0, 0, 0), point_type(4, 4, 4)); BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 2), box), true); BOOST_CHECK_EQUAL(bg::within(point_type(2, 4, 2), box), false); BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 4), box), false); BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 5), box), false); box_type box2(point_type(2, 2, 2), point_type(3, 3, 3)); BOOST_CHECK_EQUAL(bg::within(box2, box), true); } template <typename P1, typename P2> void test_point_poly() { typedef boost::geometry::model::polygon<P1> poly1; typedef boost::geometry::model::polygon<P2> poly2; test_geometry<P1, poly2>("POINT(3 3)", "POLYGON((0 0,0 5,5 5,5 0,0 0))", true); test_geometry<P2, poly1>("POINT(3 3)", "POLYGON((0 0,0 5,5 5,5 0,0 0))", true); } template <typename P1, typename P2> void test_all() { test_point_box<P1, P2>(); test_point_poly<P1, P2>(); } template <typename P> void test_all() { test_all<P, P>(); } void test_strategy() { // Test by explicitly specifying a strategy typedef bg::model::d2::point_xy<double> point_type; typedef bg::model::box<point_type> box_type; point_type p(3, 3); box_type b(point_type(0, 0), point_type(5, 5)); box_type b0(point_type(0, 0), point_type(5, 0)); bool r = bg::within(p, b, bg::strategy::within::cartesian_point_box()); BOOST_CHECK_EQUAL(r, true); r = bg::within(b, b, bg::strategy::within::box_in_box<box_type, box_type>()); BOOST_CHECK_EQUAL(r, true); r = bg::within(b0, b0, bg::strategy::within::box_in_box<box_type, box_type>()); BOOST_CHECK_EQUAL(r, false); r = bg::within(p, b, bg::strategy::within::point_in_box_by_side<>()); BOOST_CHECK_EQUAL(r, true); } int test_main( int , char* [] ) { typedef boost::geometry::model::d2::point_xy<double> xyd; typedef boost::geometry::model::d2::point_xy<float> xyf; typedef boost::geometry::model::d2::point_xy<int> xyi; typedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> p2d; test_all<xyd, p2d>(); test_all<xyf, p2d>(); test_all<xyi, xyd>(); test_all<xyi>(); test_all<xyd>(); test_point_box_3d(); test_strategy(); return 0; }
35.601351
96
0.653065
[ "geometry", "model" ]
9cda7020ad0f76b337a75b3ead2f92209063e2da
4,708
cpp
C++
test-suite/generated-src/wasm/NativeEnumUsageInterface.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeEnumUsageInterface.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeEnumUsageInterface.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from enum.djinni #include "NativeEnumUsageInterface.hpp" // my header #include "NativeColor.hpp" namespace djinni_generated { em::val NativeEnumUsageInterface::cppProxyMethods() { static const em::val methods = em::val::array(std::vector<std::string> { "e", "o", "l", "s", "m", }); return methods; } int32_t NativeEnumUsageInterface::e(const CppType& self, int32_t w_e) { try { auto r = self->e(::djinni_generated::NativeColor::toCpp(w_e)); return ::djinni_generated::NativeColor::fromCpp(r); } catch(const std::exception& e) { djinni::djinni_throw_native_exception(e); throw; } } em::val NativeEnumUsageInterface::o(const CppType& self, const em::val& w_o) { try { auto r = self->o(::djinni::Optional<std::experimental::optional, ::djinni_generated::NativeColor>::toCpp(w_o)); return ::djinni::Optional<std::experimental::optional, ::djinni_generated::NativeColor>::fromCpp(r); } catch(const std::exception& e) { djinni::djinni_throw_native_exception(e); throw; } } em::val NativeEnumUsageInterface::l(const CppType& self, const em::val& w_l) { try { auto r = self->l(::djinni::List<::djinni_generated::NativeColor>::toCpp(w_l)); return ::djinni::List<::djinni_generated::NativeColor>::fromCpp(r); } catch(const std::exception& e) { djinni::djinni_throw_native_exception(e); throw; } } em::val NativeEnumUsageInterface::s(const CppType& self, const em::val& w_s) { try { auto r = self->s(::djinni::Set<::djinni_generated::NativeColor>::toCpp(w_s)); return ::djinni::Set<::djinni_generated::NativeColor>::fromCpp(r); } catch(const std::exception& e) { djinni::djinni_throw_native_exception(e); throw; } } em::val NativeEnumUsageInterface::m(const CppType& self, const em::val& w_m) { try { auto r = self->m(::djinni::Map<::djinni_generated::NativeColor, ::djinni_generated::NativeColor>::toCpp(w_m)); return ::djinni::Map<::djinni_generated::NativeColor, ::djinni_generated::NativeColor>::fromCpp(r); } catch(const std::exception& e) { djinni::djinni_throw_native_exception(e); throw; } } ::testsuite::color NativeEnumUsageInterface::JsProxy::e(::testsuite::color e) { auto ret = callMethod("e", ::djinni_generated::NativeColor::fromCpp(e)); checkError(ret); return ::djinni_generated::NativeColor::toCpp(ret.as<int32_t>()); } std::experimental::optional<::testsuite::color> NativeEnumUsageInterface::JsProxy::o(std::experimental::optional<::testsuite::color> o) { auto ret = callMethod("o", ::djinni::Optional<std::experimental::optional, ::djinni_generated::NativeColor>::fromCpp(o)); checkError(ret); return ::djinni::Optional<std::experimental::optional, ::djinni_generated::NativeColor>::toCpp(ret); } std::vector<::testsuite::color> NativeEnumUsageInterface::JsProxy::l(const std::vector<::testsuite::color> & l) { auto ret = callMethod("l", ::djinni::List<::djinni_generated::NativeColor>::fromCpp(l)); checkError(ret); return ::djinni::List<::djinni_generated::NativeColor>::toCpp(ret); } std::unordered_set<::testsuite::color> NativeEnumUsageInterface::JsProxy::s(const std::unordered_set<::testsuite::color> & s) { auto ret = callMethod("s", ::djinni::Set<::djinni_generated::NativeColor>::fromCpp(s)); checkError(ret); return ::djinni::Set<::djinni_generated::NativeColor>::toCpp(ret); } std::unordered_map<::testsuite::color, ::testsuite::color> NativeEnumUsageInterface::JsProxy::m(const std::unordered_map<::testsuite::color, ::testsuite::color> & m) { auto ret = callMethod("m", ::djinni::Map<::djinni_generated::NativeColor, ::djinni_generated::NativeColor>::fromCpp(m)); checkError(ret); return ::djinni::Map<::djinni_generated::NativeColor, ::djinni_generated::NativeColor>::toCpp(ret); } EMSCRIPTEN_BINDINGS(testsuite_enum_usage_interface) { ::djinni::DjinniClass_<::testsuite::EnumUsageInterface>("testsuite_EnumUsageInterface", "testsuite.EnumUsageInterface") .smart_ptr<std::shared_ptr<::testsuite::EnumUsageInterface>>("testsuite_EnumUsageInterface") .function("nativeDestroy", &NativeEnumUsageInterface::nativeDestroy) .function("e", NativeEnumUsageInterface::e) .function("o", NativeEnumUsageInterface::o) .function("l", NativeEnumUsageInterface::l) .function("s", NativeEnumUsageInterface::s) .function("m", NativeEnumUsageInterface::m) ; } } // namespace djinni_generated
41.298246
167
0.679057
[ "vector" ]
9ce3a29ce69c0b45600d2b294dc251608c9edd0b
8,628
cpp
C++
dali-toolkit/internal/visuals/color/color-visual.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/visuals/color/color-visual.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/visuals/color/color-visual.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include "color-visual.h" // EXTERNAL INCLUDES #include <dali/devel-api/rendering/renderer-devel.h> #include <dali/integration-api/debug.h> //INTERNAL INCLUDES #include <dali-toolkit/devel-api/visuals/color-visual-actions-devel.h> #include <dali-toolkit/devel-api/visuals/color-visual-properties-devel.h> #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h> #include <dali-toolkit/internal/visuals/visual-base-data-impl.h> #include <dali-toolkit/internal/visuals/visual-factory-cache.h> #include <dali-toolkit/internal/visuals/visual-factory-impl.h> #include <dali-toolkit/internal/visuals/visual-string-constants.h> #include <dali-toolkit/public-api/visuals/color-visual-properties.h> #include <dali-toolkit/public-api/visuals/visual-properties.h> namespace Dali { namespace Toolkit { namespace Internal { ColorVisualPtr ColorVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { ColorVisualPtr colorVisualPtr(new ColorVisual(factoryCache)); colorVisualPtr->SetProperties(properties); colorVisualPtr->Initialize(); return colorVisualPtr; } ColorVisual::ColorVisual(VisualFactoryCache& factoryCache) : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::COLOR), mBlurRadius(0.0f), mBlurRadiusIndex(Property::INVALID_INDEX), mRenderIfTransparent(false), mNeedBlurRadius(false) { } ColorVisual::~ColorVisual() { } void ColorVisual::DoSetProperties(const Property::Map& propertyMap) { // By virtue of DoSetProperties being called last, this will override // anything set by Toolkit::Visual::Property::MIX_COLOR Property::Value* colorValue = propertyMap.Find(Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR); if(colorValue) { Vector4 color; if(colorValue->Get(color)) { Property::Type type = colorValue->GetType(); if(type == Property::VECTOR4) { SetMixColor(color); } else if(type == Property::VECTOR3) { Vector3 color3(color); SetMixColor(color3); } } else { DALI_LOG_ERROR("ColorVisual: mixColor property has incorrect type\n"); } } Property::Value* renderIfTransparentValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME); if(renderIfTransparentValue) { if(!renderIfTransparentValue->Get(mRenderIfTransparent)) { DALI_LOG_ERROR("ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType()); } } Property::Value* blurRadiusValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME); if(blurRadiusValue) { if(!blurRadiusValue->Get(mBlurRadius)) { DALI_LOG_ERROR("ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType()); } } } void ColorVisual::DoSetOnScene(Actor& actor) { // Only add the renderer if it's not fully transparent // We cannot avoid creating a renderer as it's used in the base class if(mRenderIfTransparent || mImpl->mMixColor.a > 0.0f) { actor.AddRenderer(mImpl->mRenderer); } // Color Visual generated and ready to display ResourceReady(Toolkit::Visual::ResourceStatus::READY); } void ColorVisual::DoSetOffScene(Actor& actor) { actor.RemoveRenderer(mImpl->mRenderer); } void ColorVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR); map.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor); map.Insert(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent); if(mImpl->mRenderer && mBlurRadiusIndex != Property::INVALID_INDEX) { // Update values from Renderer float blurRadius = mImpl->mRenderer.GetProperty<float>(mBlurRadiusIndex); map.Insert(Toolkit::DevelColorVisual::Property::BLUR_RADIUS, blurRadius); } else { map.Insert(Toolkit::DevelColorVisual::Property::BLUR_RADIUS, mBlurRadius); } } void ColorVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void ColorVisual::OnSetTransform() { if(mImpl->mRenderer) { mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } void ColorVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible switch(actionId) { case DevelColorVisual::Action::UPDATE_PROPERTY: { const Property::Map* map = attributes.GetMap(); if(map) { DoSetProperties(*map); } break; } } } void ColorVisual::UpdateShader() { if(mImpl->mRenderer) { Shader shader = GetShader(); mImpl->mRenderer.SetShader(shader); } } void ColorVisual::OnInitialize() { Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); Shader shader = GetShader(); mImpl->mRenderer = Renderer::New(geometry, shader); // ColorVisual has it's own index key for mix color - use this instead // of using the new base index to avoid changing existing applications // String keys will get to this property. mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty(Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor)); if(!EqualsZero(mBlurRadius)) { mBlurRadiusIndex = mImpl->mRenderer.RegisterProperty(DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME, mBlurRadius); mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); } // Register transform properties mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } Shader ColorVisual::GetShader() { Shader shader; if(!EqualsZero(mBlurRadius) || mNeedBlurRadius) { shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE); if(!shader) { shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_FRAG.data()); mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader); } } else if(!IsRoundedCornerRequired()) { shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER); if(!shader) { shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_FRAG.data()); mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER, shader); } } else { shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER); if(!shader) { shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data()); mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader); } } return shader; } Dali::Property ColorVisual::OnGetPropertyObject(Dali::Property::Key key) { if(!mImpl->mRenderer) { Handle handle; return Dali::Property(handle, Property::INVALID_INDEX); } if((key.type == Property::Key::INDEX && key.indexKey == DevelColorVisual::Property::BLUR_RADIUS) || (key.type == Property::Key::STRING && key.stringKey == BLUR_RADIUS_NAME)) { mBlurRadiusIndex = mImpl->mRenderer.RegisterProperty(DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME, mBlurRadius); mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); mNeedBlurRadius = true; // Change shader UpdateShader(); return Dali::Property(mImpl->mRenderer, mBlurRadiusIndex); } Handle handle; return Dali::Property(handle, Property::INVALID_INDEX); } } // namespace Internal } // namespace Toolkit } // namespace Dali
31.604396
219
0.738642
[ "geometry", "transform" ]
9ce82ca436d97684e501c9e2be94ba48304a6c67
2,985
cpp
C++
test/generated/PrefixedTypesTest.cpp
Roboauto/fast_ber
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
[ "BSL-1.0" ]
null
null
null
test/generated/PrefixedTypesTest.cpp
Roboauto/fast_ber
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
[ "BSL-1.0" ]
null
null
null
test/generated/PrefixedTypesTest.cpp
Roboauto/fast_ber
089d3a2dfb3c8b14da066791f578fbec86dcf6c6
[ "BSL-1.0" ]
null
null
null
#include "autogen/prefixed_types.hpp" #include "fast_ber/util/BerView.hpp" #include "catch2/catch.hpp" #include <vector> template <typename T, size_t n> bool operator==(std::span<T> l, std::array<uint8_t, n> r) { return std::equal(l.begin(), l.end(), r.begin(), r.end()); } TEST_CASE("Prefixed Types: Encoding, matching 8.14 of X.690") { std::array<uint8_t, 100> buffer_storage = {}; auto buffer = std::span(buffer_storage.data(), buffer_storage.size()); fast_ber::PrefixedTypes::Type1 type1 = "Jones"; fast_ber::PrefixedTypes::Type2 type2 = "Jones"; fast_ber::PrefixedTypes::Type3 type3 = "Jones"; fast_ber::PrefixedTypes::Type4 type4 = "Jones"; fast_ber::PrefixedTypes::Type5 type5 = "Jones"; fast_ber::EncodeResult res = {}; res = fast_ber::encode(buffer, type1); REQUIRE(res.success); REQUIRE(std::span(buffer.data(), 7) == std::array<uint8_t, 7>{0x1A, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); res = fast_ber::encode(std::span(buffer.data(), buffer.size()), type2); REQUIRE(res.success); REQUIRE(std::span(buffer.data(), 7) == std::array<uint8_t, 7>{0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); res = fast_ber::encode(std::span(buffer.data(), buffer.size()), type3); REQUIRE(res.success); REQUIRE(std::span(buffer.data(), 9) == std::array<uint8_t, 9>{0xA2, 0x07, 0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); res = fast_ber::encode(buffer, type4); REQUIRE(res.success); REQUIRE(std::span(buffer.data(), 9) == std::array<uint8_t, 9>{0x67, 0x07, 0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); res = fast_ber::encode(buffer, type5); REQUIRE(res.success); REQUIRE(std::span(buffer.data(), 7) == std::array<uint8_t, 7>{0x82, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); } TEST_CASE("Prefixed Types: Prefixed Types in a Collection") { std::array<uint8_t, 100> buffer_storage = {}; fast_ber::EncodeResult res = {}; auto buffer = std::span(buffer_storage.data(), buffer_storage.size()); fast_ber::PrefixedTypes::Collection collection; collection.type1 = "Jones"; collection.type2 = "Jones"; collection.type3 = "Jones"; collection.type4 = "Jones"; collection.type5 = "Jones"; res = fast_ber::encode(buffer, collection); REQUIRE(res.success); fast_ber::BerViewIterator itr = fast_ber::BerView(buffer).begin(); REQUIRE(itr->ber() == std::array<uint8_t, 7>{0x1A, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); ++itr; REQUIRE(itr->ber() == std::array<uint8_t, 7>{0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); ++itr; REQUIRE(itr->ber() == std::array<uint8_t, 9>{0xA2, 0x07, 0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); ++itr; REQUIRE(itr->ber() == std::array<uint8_t, 9>{0x67, 0x07, 0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); ++itr; REQUIRE(itr->ber() == std::array<uint8_t, 7>{0x82, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73}); }
39.276316
109
0.624791
[ "vector" ]
9ce8a23a2acbc3b1321591f4da7067ea7aa855ea
28,304
cpp
C++
SystemCommon/MiscIntrins.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
SystemCommon/MiscIntrins.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
SystemCommon/MiscIntrins.cpp
mfkiwl/RayRenderer-dp4a
b57696b23c795f0ca1199e8f009b7a12b88da13a
[ "MIT" ]
null
null
null
#include "SystemCommonPch.h" #include "MiscIntrins.h" #include "RuntimeFastPath.h" #include "common/simd/SIMD.hpp" #include "common/simd/SIMD128.hpp" #include "common/simd/SIMD256.hpp" #include "3rdParty/digestpp/algorithm/sha2.hpp" using namespace std::string_view_literals; using common::CheckCPUFeature; using common::MiscIntrins; using common::DigestFuncs; #define LeadZero32Args BOOST_PP_VARIADIC_TO_SEQ(num) #define LeadZero64Args BOOST_PP_VARIADIC_TO_SEQ(num) #define TailZero32Args BOOST_PP_VARIADIC_TO_SEQ(num) #define TailZero64Args BOOST_PP_VARIADIC_TO_SEQ(num) #define PopCount32Args BOOST_PP_VARIADIC_TO_SEQ(num) #define PopCount64Args BOOST_PP_VARIADIC_TO_SEQ(num) #define Hex2StrArgs BOOST_PP_VARIADIC_TO_SEQ(data, size, isCapital) DEFINE_FASTPATH(MiscIntrins, LeadZero32); DEFINE_FASTPATH(MiscIntrins, LeadZero64); DEFINE_FASTPATH(MiscIntrins, TailZero32); DEFINE_FASTPATH(MiscIntrins, TailZero64); DEFINE_FASTPATH(MiscIntrins, PopCount32); DEFINE_FASTPATH(MiscIntrins, PopCount64); DEFINE_FASTPATH(MiscIntrins, Hex2Str); #define Sha256Args BOOST_PP_VARIADIC_TO_SEQ(data, size) DEFINE_FASTPATH(DigestFuncs, Sha256); namespace { using common::fastpath::FuncVarBase; struct NAIVE : FuncVarBase {}; struct COMPILER : FuncVarBase {}; struct OS : FuncVarBase {}; struct SIMD128 { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("sse2"sv); #else return CheckCPUFeature("asimd"sv); #endif } }; struct SIMDSSSE3 { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("ssse3"sv); #else return false; #endif } }; struct LZCNT { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("bmi1"sv) || CheckCPUFeature("lzcnt"sv); #else return false; #endif } }; struct TZCNT { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("bmi1"sv); #else return false; #endif } }; struct POPCNT { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("popcnt"sv); #else return false; #endif } }; struct BMI1 { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("bmi1"sv); #else return false; #endif } }; struct SHANI { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("sha"sv); #else return false; #endif } }; struct SHANIAVX2 { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return CheckCPUFeature("sha"sv) && CheckCPUFeature("avx2"sv); #else return false; #endif } }; struct SHA2 { static bool RuntimeCheck() noexcept { #if COMMON_ARCH_X86 return false; #else return CheckCPUFeature("sha2"sv); #endif } }; } using namespace common::simd; #if COMMON_COMPILER_MSVC DEFINE_FASTPATH_METHOD(LeadZero32, COMPILER) { unsigned long idx = 0; return _BitScanReverse(&idx, num) ? 31 - idx : 32; } DEFINE_FASTPATH_METHOD(LeadZero64, COMPILER) { unsigned long idx = 0; # if COMMON_OSBIT == 64 return _BitScanReverse64(&idx, num) ? 63 - idx : 64; # else const auto lo = static_cast<uint32_t>(num), hi = static_cast<uint32_t>(num >> 32); if (!_BitScanReverse(&idx, hi)) return _BitScanReverse(&idx, lo) ? 63 - idx : 64; else return 31 - idx; # endif } DEFINE_FASTPATH_METHOD(TailZero32, COMPILER) { unsigned long idx = 0; return _BitScanForward(&idx, num) ? idx : 32; } DEFINE_FASTPATH_METHOD(TailZero64, COMPILER) { unsigned long idx = 0; # if COMMON_OSBIT == 64 return _BitScanForward64(&idx, num) ? idx : 64; # else const auto lo = static_cast<uint32_t>(num), hi = static_cast<uint32_t>(num >> 32); if (!_BitScanForward(&idx, lo)) return _BitScanForward(&idx, hi) ? idx + 32 : 64; else return idx; #endif } #elif COMMON_COMPILER_GCC || COMMON_COMPILER_CLANG DEFINE_FASTPATH_METHOD(LeadZero32, COMPILER) { return num == 0 ? 32 : __builtin_clz(num); } DEFINE_FASTPATH_METHOD(LeadZero64, COMPILER) { return num == 0 ? 64 : __builtin_clzll(num); } DEFINE_FASTPATH_METHOD(TailZero32, COMPILER) { return num == 0 ? 32 : __builtin_ctz(num); } DEFINE_FASTPATH_METHOD(TailZero64, COMPILER) { return num == 0 ? 64 : __builtin_ctzll(num); } DEFINE_FASTPATH_METHOD(PopCount32, COMPILER) { return __builtin_popcount(num); } DEFINE_FASTPATH_METHOD(PopCount64, COMPILER) { return __builtin_popcountll(num); } #endif //DEFINE_FASTPATH_METHOD(LeadZero32, NAIVE) //{ //} //DEFINE_FASTPATH_METHOD(LeadZero64, NAIVE) //{ //} //DEFINE_FASTPATH_METHOD(TailZero32, NAIVE) //{ //} //DEFINE_FASTPATH_METHOD(TailZero64, NAIVE) //{ //} DEFINE_FASTPATH_METHOD(PopCount32, NAIVE) { auto tmp = num - ((num >> 1) & 0x55555555u); tmp = (tmp & 0x33333333u) + ((tmp >> 2) & 0x33333333u); tmp = (tmp + (tmp >> 4)) & 0x0f0f0f0fu; return (tmp * 0x01010101u) >> 24; } DEFINE_FASTPATH_METHOD(PopCount64, NAIVE) { auto tmp = num - ((num >> 1) & 0x5555555555555555u); tmp = (tmp & 0x3333333333333333u) + ((tmp >> 2) & 0x3333333333333333u); tmp = (tmp + (tmp >> 4)) & 0x0f0f0f0f0f0f0f0fu; return (tmp * 0x0101010101010101u) >> 56; } DEFINE_FASTPATH_METHOD(Sha256, NAIVE) { std::array<std::byte, 32> output; digestpp::sha256().absorb(data, size) .digest(reinterpret_cast<unsigned char*>(output.data()), 32); return output; } #if (COMMON_COMPILER_MSVC && COMMON_ARCH_X86/* && COMMON_SIMD_LV >= 200*/) || (!COMMON_COMPILER_MSVC && (defined(__LZCNT__) || defined(__BMI__))) #pragma message("Compiling MiscIntrins with LZCNT") DEFINE_FASTPATH_METHOD(LeadZero32, LZCNT) { return _lzcnt_u32(num); } DEFINE_FASTPATH_METHOD(LeadZero64, LZCNT) { # if COMMON_OSBIT == 64 return static_cast<uint32_t>(_lzcnt_u64(num)); # else const auto lo = static_cast<uint32_t>(num), hi = static_cast<uint32_t>(num >> 32); const auto hiCnt = _lzcnt_u32(hi); return hiCnt == 32 ? _lzcnt_u32(lo) + 32 : hiCnt; # endif } #endif #if (COMMON_COMPILER_MSVC && COMMON_ARCH_X86/* && COMMON_SIMD_LV >= 200*/) || (!COMMON_COMPILER_MSVC && defined(__BMI__)) #pragma message("Compiling MiscIntrins with TZCNT") DEFINE_FASTPATH_METHOD(TailZero32, TZCNT) { return _tzcnt_u32(num); } DEFINE_FASTPATH_METHOD(TailZero64, TZCNT) { # if COMMON_OSBIT == 64 return static_cast<uint32_t>(_tzcnt_u64(num)); # else const auto lo = static_cast<uint32_t>(num), hi = static_cast<uint32_t>(num >> 32); const auto loCnt = _tzcnt_u32(lo); return loCnt == 32 ? _tzcnt_u32(hi) + 32 : loCnt; # endif } #endif #if (COMMON_COMPILER_MSVC && COMMON_ARCH_X86/* && COMMON_SIMD_LV >= 42*/) || (!COMMON_COMPILER_MSVC && defined(__POPCNT__)) #pragma message("Compiling MiscIntrins with POPCNT") DEFINE_FASTPATH_METHOD(PopCount32, POPCNT) { return _mm_popcnt_u32(num); } DEFINE_FASTPATH_METHOD(PopCount64, POPCNT) { # if COMMON_OSBIT == 64 return static_cast<uint32_t>(_mm_popcnt_u64(num)); # else const auto lo = static_cast<uint32_t>(num), hi = static_cast<uint32_t>(num >> 32); return _mm_popcnt_u32(lo) + _mm_popcnt_u32(hi); # endif } #endif static void Hex2Str(std::string& ret, const uint8_t* data, size_t size, bool isCapital) { constexpr auto ch = "0123456789abcdef0123456789ABCDEF"; const auto ptr = isCapital ? ch + 16 : ch; for (size_t i = 0; i < size; ++i) { const uint8_t dat = data[i]; ret.push_back(ptr[dat / 16]); ret.push_back(ptr[dat % 16]); } } DEFINE_FASTPATH_METHOD(Hex2Str, NAIVE) { std::string ret; ret.reserve(size * 2); Hex2Str(ret, data, size, isCapital); return ret; } #if (COMMON_ARCH_X86 && COMMON_SIMD_LV >= 31) || (COMMON_ARCH_ARM && COMMON_SIMD_LV >= 10) # if COMMON_ARCH_X86 # define ALGO SIMDSSSE3 # else # define ALGO SIMD128 # endif DEFINE_FASTPATH_METHOD(Hex2Str, ALGO) { alignas(16) constexpr uint8_t strs[] = "0123456789abcdef0123456789ABCDEF"; const U8x16 chars(isCapital ? strs + 16 : strs); std::string ret; ret.reserve(size * 2); ret.resize((size / 8) * 16); auto dst = reinterpret_cast<uint8_t*>(ret.data()); while (size >= 16) { const U8x16 dat(data); const auto loData = dat.And(0x0f), hiData = dat.ShiftRightLogic<4>(); const auto loChar = chars.Shuffle(loData), hiChar = chars.Shuffle(hiData); const auto part0 = hiChar.ZipLo(loChar), part1 = hiChar.ZipHi(loChar); part0.Save(dst), part1.Save(dst + 16); data += 16, size -= 16, dst += 32; } if (size >= 8) { const auto dat = U64x2::LoadLo(reinterpret_cast<const uint64_t*>(data)).As<U8x16>(); const auto loData = dat.And(0x0f), hiData = dat.ShiftRightLogic<4>(); const auto fullData = hiData.ZipLo(loData); const auto fullChar = chars.Shuffle(fullData); fullChar.Save(dst); data += 8, size -= 8, dst += 16; } Hex2Str(ret, data, size, isCapital); return ret; } # undef ALGO #endif alignas(32) constexpr uint32_t SHA256RoundAdders[][4] = { { 0x428A2F98u, 0x71374491u, 0xB5C0FBCFu, 0xE9B5DBA5u }, { 0x3956C25Bu, 0x59F111F1u, 0x923F82A4u, 0xAB1C5ED5u }, { 0xD807AA98u, 0x12835B01u, 0x243185BEu, 0x550C7DC3u }, { 0x72BE5D74u, 0x80DEB1FEu, 0x9BDC06A7u, 0xC19BF174u }, { 0xE49B69C1u, 0xEFBE4786u, 0x0FC19DC6u, 0x240CA1CCu }, { 0x2DE92C6Fu, 0x4A7484AAu, 0x5CB0A9DCu, 0x76F988DAu }, { 0x983E5152u, 0xA831C66Du, 0xB00327C8u, 0xBF597FC7u }, { 0xC6E00BF3u, 0xD5A79147u, 0x06CA6351u, 0x14292967u }, { 0x27B70A85u, 0x2E1B2138u, 0x4D2C6DFCu, 0x53380D13u }, { 0x650A7354u, 0x766A0ABBu, 0x81C2C92Eu, 0x92722C85u }, { 0xA2BFE8A1u, 0xA81A664Bu, 0xC24B8B70u, 0xC76C51A3u }, { 0xD192E819u, 0xD6990624u, 0xF40E3585u, 0x106AA070u }, { 0x19A4C116u, 0x1E376C08u, 0x2748774Cu, 0x34B0BCB5u }, { 0x391C0CB3u, 0x4ED8AA4Au, 0x5B9CCA4Fu, 0x682E6FF3u }, { 0x748F82EEu, 0x78A5636Fu, 0x84C87814u, 0x8CC70208u }, { 0x90BEFFFAu, 0xA4506CEBu, 0xBEF9A3F7u, 0xC67178F2u }, }; constexpr bool SHA256RoundProcControl[][2] = { // { ProcPrev, ProcNext } { false, false }, { true, false }, { true, false }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { true, true }, { false, true }, { false, true }, { false, false }, }; #if (COMMON_ARCH_X86 && COMMON_SIMD_LV >= 41) || (COMMON_ARCH_ARM && COMMON_SIMD_LV >= 100) struct Sha256State { //U32x4 state0(0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a); // ABCD //U32x4 state1(0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19); // EFGH U32x4 State0, State1; Sha256State(U32x4 state0, U32x4 state1) : State0(state0), State1(state1) { } }; // From http://software.intel.com/en-us/articles/intel-sha-extensions written by Sean Gulley. template<typename Calc> forceinline static void VECCALL Sha256Block128(Calc& calc, U32x4 msg0, U32x4 msg1, U32x4 msg2, U32x4 msg3) noexcept // msgs are BE { /* Save current state */ const auto abef_save = calc.State0; const auto cdgh_save = calc.State1; /* Rounds 0-3 */ calc.template Calc< 0>(msg3, msg0, msg1); /* Rounds 4-7 */ calc.template Calc< 1>(msg0, msg1, msg2); /* Rounds 8-11 */ calc.template Calc< 2>(msg1, msg2, msg3); /* Rounds 12-15 */ calc.template Calc< 3>(msg2, msg3, msg0); /* Rounds 16-19 */ calc.template Calc< 4>(msg3, msg0, msg1); /* Rounds 20-23 */ calc.template Calc< 5>(msg0, msg1, msg2); /* Rounds 24-27 */ calc.template Calc< 6>(msg1, msg2, msg3); /* Rounds 28-31 */ calc.template Calc< 7>(msg2, msg3, msg0); /* Rounds 32-35 */ calc.template Calc< 8>(msg3, msg0, msg1); /* Rounds 36-39 */ calc.template Calc< 9>(msg0, msg1, msg2); /* Rounds 40-43 */ calc.template Calc<10>(msg1, msg2, msg3); /* Rounds 44-47 */ calc.template Calc<11>(msg2, msg3, msg0); /* Rounds 48-51 */ calc.template Calc<12>(msg3, msg0, msg1); /* Rounds 52-55 */ calc.template Calc<13>(msg0, msg1, msg2); /* Rounds 56-59 */ calc.template Calc<14>(msg1, msg2, msg3); /* Rounds 60-63 */ calc.template Calc<15>(msg2, msg3, msg0); /* Combine state */ calc.State0 += abef_save; calc.State1 += cdgh_save; } template<typename Calc> inline std::array<std::byte, 32> Sha256Main128(const std::byte* data, const size_t size) noexcept { static_assert(std::is_base_of_v<Sha256State, Calc>); Calc calc; size_t len = size; const uint32_t* __restrict ptr = reinterpret_cast<const uint32_t*>(data); while (len >= 64) { const auto msg0 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg1 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg2 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg3 = U32x4(ptr).SwapEndian(); ptr += 4; Sha256Block128(calc, msg0, msg1, msg2, msg3); len -= 64; } const auto bitsv = U64x2::LoadLo(static_cast<uint64_t>(size) * 8); const auto bitsvBE = bitsv.As<U32x4>().Shuffle<3, 3, 1, 0>(); if (len >= 48) { const auto msg0 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg1 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg2 = U32x4(ptr).SwapEndian(); ptr += 4; auto msg3 = Calc::Load128With80BE(ptr, len % 16); if (len < 56) msg3 |= bitsvBE; Sha256Block128(calc, msg0, msg1, msg2, msg3); if (len >= 56) Sha256Block128(calc, U32x4::AllZero(), U32x4::AllZero(), U32x4::AllZero(), bitsvBE); } else { U32x4 msg0, msg1, msg2, msg3; if (len < 16) { msg0 = Calc::Load128With80BE(ptr, len - 0); ptr += 4; msg1 = U32x4::AllZero(); msg2 = U32x4::AllZero(); msg3 = bitsvBE; } else if (len < 32) { msg0 = U32x4(ptr).SwapEndian(); ptr += 4; msg1 = Calc::Load128With80BE(ptr, len - 16); ptr += 4; msg2 = U32x4::AllZero(); msg3 = bitsvBE; } else // if (len < 48) { msg0 = U32x4(ptr).SwapEndian(); ptr += 4; msg1 = U32x4(ptr).SwapEndian(); ptr += 4; msg2 = Calc::Load128With80BE(ptr, len - 32); ptr += 4; msg3 = bitsvBE; } Sha256Block128(calc, msg0, msg1, msg2, msg3); } return calc.Output(); } # if COMMON_ARCH_X86 && (COMMON_COMPILER_MSVC || defined(__SHA__)) # pragma message("Compiling DigestFuncs with SHA_NI") struct Sha256Round_SHANI : public Sha256State { forceinline static U32x4 Load128With80BE(const uint32_t* data, const size_t len) noexcept { // Expects len < 16 if (len == 0) return U32x4::LoadLo(0x80000000); const auto val = U32x4(data).SwapEndian(); const U8x16 IdxConst(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12); const U8x16 SizeMask(static_cast<char>(len)); // x, x, x, x const auto EndMask = SizeMask.Compare<CompareType::Equal, MaskType::FullEle>(IdxConst); // 00,00,ff,00 or 00,00,00,ff const auto KeepMask = SizeMask.Compare<CompareType::GreaterThan, MaskType::FullEle>(IdxConst); // ff,ff,00,00 or ff,ff,ff,00 const auto EndSigBit = EndMask.As<U16x8>().ShiftLeftLogic<7>().As<U8x16>(); // 00,00,80,7f or 00,00,00,80 const auto SuffixBit = EndSigBit & EndMask; // 00,00,80,00 or 00,00,00,80 return SuffixBit.SelectWith<MaskType::FullEle>(val.As<U8x16>(), KeepMask).As<U32x4>(); } Sha256Round_SHANI() noexcept : Sha256State( { 0x9b05688c, 0x510e527f, 0xbb67ae85, 0x6a09e667 }/*ABEF-rev*/, { 0x5be0cd19, 0x1f83d9ab, 0xa54ff53a, 0x3c6ef372 }/*CDGH-rev*/) { } /* Save state */ forceinline std::array<std::byte, 32> Output() const noexcept { std::array<std::byte, 32> output; // state0: feba // state1: hgdc const U8x16 ReverseMask(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); const auto abef = State0.As<U8x16>().Shuffle(ReverseMask); const auto cdgh = State1.As<U8x16>().Shuffle(ReverseMask); const auto abcd = abef.As<U64x2>().ZipLo(cdgh.As<U64x2>()).As<U8x16>(); const auto efgh = abef.As<U64x2>().ZipHi(cdgh.As<U64x2>()).As<U8x16>(); abcd.Save(reinterpret_cast<uint8_t*>(&output[0])); efgh.Save(reinterpret_cast<uint8_t*>(&output[16])); return output; } // From http://software.intel.com/en-us/articles/intel-sha-extensions written by Sean Gulley. // Modifiled from code previously on https://github.com/mitls/hacl-star/tree/master/experimental/hash with BSD license. template<size_t Round> forceinline void VECCALL Calc([[maybe_unused]] U32x4& prev, U32x4& cur, [[maybe_unused]] U32x4& next) noexcept // msgs are BE { const U32x4 adder(SHA256RoundAdders[Round]); auto msg = cur + adder; State1 = _mm_sha256rnds2_epu32(State1, State0, msg); if constexpr (SHA256RoundProcControl[Round][1]) { const U32x4 tmp = _mm_alignr_epi8(cur, prev, 4); next = _mm_sha256msg2_epu32(next + tmp, cur); } msg = msg.Shuffle<2, 3, 0, 0>(); // _mm_shuffle_epi32(msg, 0x0E); State0 = _mm_sha256rnds2_epu32(State0, State1, msg); if constexpr (SHA256RoundProcControl[Round][0]) { prev = _mm_sha256msg1_epu32(prev, cur); } } }; DEFINE_FASTPATH_METHOD(Sha256, SHANI) { return Sha256Main128<Sha256Round_SHANI>(data, size); } # elif COMMON_ARCH_ARM && defined(__ARM_FEATURE_CRYPTO) # pragma message("Compiling DigestFuncs with SHA2") struct Sha256Round_SHA2 : public Sha256State { forceinline static U32x4 Load128With80BE(const uint32_t* data, const size_t len) noexcept { // Expects len < 16 if (len == 0) return U32x4::LoadLo(0x80000000); const auto val = U32x4(data).SwapEndian(); const U8x16 IdxConst(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12); const U8x16 SizeMask(static_cast<char>(len)); // x, x, x, x const auto EndMask = SizeMask.Compare<CompareType::Equal, MaskType::FullEle>(IdxConst); // 00,00,ff,00 or 00,00,00,ff const auto KeepMask = SizeMask.Compare<CompareType::GreaterThan, MaskType::FullEle>(IdxConst); // ff,ff,00,00 or ff,ff,ff,00 const auto SuffixBit = EndMask.ShiftLeftLogic<7>(); // 00,00,80,00 or 00,00,00,80 return SuffixBit.SelectWith<MaskType::FullEle>(val.As<U8x16>(), KeepMask).As<U32x4>(); } Sha256Round_SHA2() noexcept : Sha256State( { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a }/*ABCD*/, { 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }/*EFGH*/) { } /* Save state */ forceinline std::array<std::byte, 32> Output() const noexcept { std::array<std::byte, 32> output; State0.SwapEndian().As<U8x16>().Save(reinterpret_cast<uint8_t*>(&output[0])); State1.SwapEndian().As<U8x16>().Save(reinterpret_cast<uint8_t*>(&output[16])); return output; } template<size_t Round> forceinline void VECCALL Calc([[maybe_unused]] U32x4& prev, U32x4& cur, [[maybe_unused]] U32x4& next) noexcept // msgs are BE { const U32x4 adder(SHA256RoundAdders[Round]); auto msg = cur + adder; const auto state0 = State0; State0 = vsha256hq_u32 (State0, State1, msg); State1 = vsha256h2q_u32(State1, state0, msg); if constexpr (SHA256RoundProcControl[Round][1]) { next = vsha256su1q_u32(next, prev, cur); } if constexpr (SHA256RoundProcControl[Round][0]) { prev = vsha256su0q_u32(prev, cur); } } }; DEFINE_FASTPATH_METHOD(Sha256, SHA2) { return Sha256Main128<Sha256Round_SHA2>(data, size); } # endif #endif #if COMMON_ARCH_X86 && COMMON_SIMD_LV >= 200 // From http://software.intel.com/en-us/articles/intel-sha-extensions written by Sean Gulley. template<typename Calc> forceinline static void VECCALL Sha256Block256(Calc& calc, U32x8 msg01, U32x8 msg23) noexcept // msgs are BE { /* Save current state */ const auto abef_save = calc.State0; const auto cdgh_save = calc.State1; U32x4 msg0 = msg01.GetLoLane(), msg1 = msg01.GetHiLane(), msg2 = msg23.GetLoLane(), msg3 = msg23.GetHiLane(), msgLo; ///* Rounds 0-3 */ calc.template Calc< 0>(msg3, msg0, msg1); ///* Rounds 4-7 */ calc.template Calc< 1>(msg0, msg1, msg2); /* Rounds 0-7 */ calc.template CalcFFTF< 0>(msg01, msg0); ///* Rounds 8-11 */ calc.template Calc< 2>(msg1, msg2, msg3); ///* Rounds 12-15 */ calc.template Calc< 3>(msg2, msg3, msg0); /* Rounds 8-15 */ calc.template CalcTFTT< 2>(msg23, msg1, msg2, msg0); /* Rounds 16-19 */ calc.template Calc< 4>(msg3, msg0, msg1); /* Rounds 20-23 */ calc.template Calc< 5>(msg0, msg1, msg2); /* Rounds 24-27 */ calc.template Calc< 6>(msg1, msg2, msg3); /* Rounds 28-31 */ calc.template Calc< 7>(msg2, msg3, msg0); /* Rounds 32-35 */ calc.template Calc< 8>(msg3, msg0, msg1); /* Rounds 36-39 */ calc.template Calc< 9>(msg0, msg1, msg2); /* Rounds 40-43 */ calc.template Calc<10>(msg1, msg2, msg3); /* Rounds 44-47 */ calc.template Calc<11>(msg2, msg3, msg0); /* Rounds 48-51 */ calc.template Calc<12>(msg3, msg0, msg1); /* Rounds 52-55 */ calc.template Calc<13>(msg0, msg1, msg2); /* Rounds 56-59 */ calc.template Calc<14>(msg1, msg2, msg3); /* Rounds 60-63 */ calc.template Calc<15>(msg2, msg3, msg0); /* Combine state */ calc.State0 += abef_save; calc.State1 += cdgh_save; } template<typename Calc> inline std::array<std::byte, 32> Sha256Main256(const std::byte* data, const size_t size) noexcept { static_assert(std::is_base_of_v<Sha256State, Calc>); Calc calc; size_t len = size; const uint32_t* __restrict ptr = reinterpret_cast<const uint32_t*>(data); while (len >= 64) { const auto msg01 = U32x8(ptr).SwapEndian(); ptr += 8; const auto msg23 = U32x8(ptr).SwapEndian(); ptr += 8; Sha256Block256(calc, msg01, msg23); len -= 64; } const auto bitsv = U64x2::LoadLo(static_cast<uint64_t>(size) * 8); //const auto bitsvBE = U32x8(U32x4::AllZero(), bitsv.As<U32x4>().Shuffle<3, 3, 1, 0>()); const auto bitsvBE = bitsv.As<U32x4>().Shuffle<3, 3, 1, 0>(); if (len >= 48) { const auto msg01 = U32x8(ptr).SwapEndian(); ptr += 8; const auto msg2 = U32x4(ptr).SwapEndian(); ptr += 4; auto msg3 = Calc::Load128With80BE(ptr, len % 16); if (len < 56) msg3 |= bitsvBE; Sha256Block256(calc, msg01, U32x8(msg2, msg3)); if (len >= 56) Sha256Block256(calc, U32x8::AllZero(), { U32x4::AllZero(), bitsvBE }); } else { U32x8 msg01, msg23; if (len < 16) { const auto msg0 = Calc::Load128With80BE(ptr, len - 0); ptr += 4; msg01 = U32x8::LoadLoLane(msg0); msg23 = U32x8(U32x4::AllZero(), bitsvBE); } else if (len < 32) { const auto msg0 = U32x4(ptr).SwapEndian(); ptr += 4; const auto msg1 = Calc::Load128With80BE(ptr, len - 16); ptr += 4; msg01 = U32x8(msg0, msg1); msg23 = U32x8(U32x4::AllZero(), bitsvBE); } else // if (len < 48) { msg01 = U32x8(ptr).SwapEndian(); ptr += 8; const auto msg2 = Calc::Load128With80BE(ptr, len - 32); ptr += 4; msg23 = U32x8(msg2, bitsvBE); } Sha256Block256(calc, msg01, msg23); } return calc.Output(); } # if COMMON_ARCH_X86 && (COMMON_COMPILER_MSVC || defined(__SHA__)) struct Sha256Round_SHANIAVX2 : public Sha256Round_SHANI { // From http://software.intel.com/en-us/articles/intel-sha-extensions written by Sean Gulley. // Modifiled from code previously on https://github.com/mitls/hacl-star/tree/master/experimental/hash with BSD license. template<size_t Round> forceinline void VECCALL CalcFFTF(const U32x8& msgLH, U32x4& msgL) noexcept // msgs are BE { static_assert(SHA256RoundProcControl[Round][0] == false && SHA256RoundProcControl[Round][1] == false && SHA256RoundProcControl[Round + 1][0] == true && SHA256RoundProcControl[Round + 1][0 + 1] == false); // FF, TF const U32x8 adderLH(SHA256RoundAdders[Round]); auto msgAddLH = msgLH + adderLH; auto msgShufLH = msgAddLH.ShuffleLane<2, 3, 0, 0>(); // _mm256_shuffle_epi32(msgAddLH, 0x0E); State1 = _mm_sha256rnds2_epu32(State1, State0, msgAddLH.GetLoLane()); State0 = _mm_sha256rnds2_epu32(State0, State1, msgShufLH.GetLoLane()); State1 = _mm_sha256rnds2_epu32(State1, State0, msgAddLH.GetHiLane()); State0 = _mm_sha256rnds2_epu32(State0, State1, msgShufLH.GetHiLane()); msgL = _mm_sha256msg1_epu32(msgLH.GetLoLane(), msgLH.GetHiLane()); } template<size_t Round> forceinline void VECCALL CalcTFTT(const U32x8& msgLH, U32x4& msgP, U32x4& msgL, U32x4& msgN) noexcept // msgs are BE { static_assert(SHA256RoundProcControl[Round][0] == true && SHA256RoundProcControl[Round][1] == false && SHA256RoundProcControl[Round + 1][0] == true && SHA256RoundProcControl[Round + 1][0 + 1] == true); // TF, TT const U32x8 adderLH(SHA256RoundAdders[Round]); auto msgAddLH = msgLH + adderLH; auto msgShufLH = msgAddLH.ShuffleLane<2, 3, 0, 0>(); // _mm256_shuffle_epi32(msgAddLH, 0x0E); State1 = _mm_sha256rnds2_epu32(State1, State0, msgAddLH.GetLoLane()); State0 = _mm_sha256rnds2_epu32(State0, State1, msgShufLH.GetLoLane()); State1 = _mm_sha256rnds2_epu32(State1, State0, msgAddLH.GetHiLane()); State0 = _mm_sha256rnds2_epu32(State0, State1, msgShufLH.GetHiLane()); const U32x4 msgLo = msgLH.GetLoLane(), msgHi = msgLH.GetHiLane(); const U32x4 tmp = _mm_alignr_epi8(msgHi, msgLo, 4); msgP = _mm_sha256msg1_epu32(msgP, msgLo); msgN = _mm_sha256msg2_epu32(msgN + tmp, msgHi); msgL = _mm_sha256msg1_epu32(msgLo, msgHi); } }; DEFINE_FASTPATH_METHOD(Sha256, SHANIAVX2) { return Sha256Main256<Sha256Round_SHANIAVX2>(data, size); } # endif #endif namespace common { common::span<const MiscIntrins::PathInfo> MiscIntrins::GetSupportMap() noexcept { static auto list = []() { std::vector<PathInfo> ret; RegistFuncVars(MiscIntrins, LeadZero32, LZCNT, COMPILER); RegistFuncVars(MiscIntrins, LeadZero64, LZCNT, COMPILER); RegistFuncVars(MiscIntrins, TailZero32, TZCNT, COMPILER); RegistFuncVars(MiscIntrins, TailZero64, TZCNT, COMPILER); RegistFuncVars(MiscIntrins, PopCount32, POPCNT, COMPILER, NAIVE); RegistFuncVars(MiscIntrins, PopCount64, POPCNT, COMPILER, NAIVE); RegistFuncVars(MiscIntrins, Hex2Str, SIMDSSSE3, SIMD128, NAIVE); return ret; }(); return list; } MiscIntrins::MiscIntrins(common::span<const VarItem> requests) noexcept { Init(requests); } MiscIntrins::~MiscIntrins() {} bool MiscIntrins::IsComplete() const noexcept { return LeadZero32 && LeadZero64 && TailZero32 && TailZero64 && PopCount32 && PopCount64 && Hex2Str; } const MiscIntrins MiscIntrin; common::span<const DigestFuncs::PathInfo> DigestFuncs::GetSupportMap() noexcept { static auto list = []() { std::vector<PathInfo> ret; RegistFuncVars(DigestFuncs, Sha256, SHANIAVX2, SHA2, SHANI, NAIVE); return ret; }(); return list; } DigestFuncs::DigestFuncs(common::span<const VarItem> requests) noexcept { Init(requests); } DigestFuncs::~DigestFuncs() {} bool DigestFuncs::IsComplete() const noexcept { return Sha256; } const DigestFuncs DigestFunc; }
33.456265
145
0.639097
[ "vector" ]
9cea3ad4b9003178d9d64885e3e970a4bba1b996
5,113
cpp
C++
third_party/antlr4-runtime/tree/xpath/XPath.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
5
2021-03-25T09:20:21.000Z
2021-12-14T09:44:50.000Z
third_party/antlr4-runtime/tree/xpath/XPath.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
third_party/antlr4-runtime/tree/xpath/XPath.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
1
2022-03-19T17:02:21.000Z
2022-03-19T17:02:21.000Z
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #include "XPathLexer.h" #include "XPathLexerErrorListener.h" #include "XPathElement.h" #include "XPathWildcardAnywhereElement.h" #include "XPathWildcardElement.h" #include "XPathTokenAnywhereElement.h" #include "XPathTokenElement.h" #include "XPathRuleAnywhereElement.h" #include "XPathRuleElement.h" #include "XPath.h" using namespace antlr4; using namespace antlr4::tree; using namespace antlr4::tree::xpath; const std::string XPath::WILDCARD = "*"; const std::string XPath::NOT = "!"; XPath::XPath(Parser *parser, const std::string &path) { _parser = parser; _path = path; } std::vector<std::unique_ptr<XPathElement>> XPath::split(const std::string &path) { ANTLRInputStream in(path); XPathLexer lexer(&in); lexer.removeErrorListeners(); XPathLexerErrorListener listener; lexer.addErrorListener(&listener); CommonTokenStream tokenStream(&lexer); try { tokenStream.fill(); } catch (LexerNoViableAltException &) { size_t pos = lexer.getCharPositionInLine(); std::string msg = "Invalid tokens or characters at index " + std::to_string(pos) + " in path '" + path + "'"; throw IllegalArgumentException(msg); } std::vector<Token *> tokens = tokenStream.getTokens(); std::vector<std::unique_ptr<XPathElement>> elements; size_t n = tokens.size(); size_t i = 0; bool done = false; while (!done && i < n) { Token *el = tokens[i]; Token *next = nullptr; switch (el->getType()) { case XPathLexer::ROOT: case XPathLexer::ANYWHERE: { bool anywhere = el->getType() == XPathLexer::ANYWHERE; i++; next = tokens[i]; bool invert = next->getType() == XPathLexer::BANG; if (invert) { i++; next = tokens[i]; } std::unique_ptr<XPathElement> pathElement = getXPathElement(next, anywhere); pathElement->setInvert(invert); elements.push_back(std::move(pathElement)); i++; break; } case XPathLexer::TOKEN_REF: case XPathLexer::RULE_REF: case XPathLexer::WILDCARD: elements.push_back(getXPathElement(el, false)); i++; break; case Token::EOF: done = true; break; default : throw IllegalArgumentException("Unknown path element " + el->toString()); } } return elements; } std::unique_ptr<XPathElement> XPath::getXPathElement(Token *wordToken, bool anywhere) { if (wordToken->getType() == Token::EOF) { throw IllegalArgumentException("Missing path element at end of path"); } std::string word = wordToken->getText(); size_t ttype = _parser->getTokenType(word); ssize_t ruleIndex = _parser->getRuleIndex(word); switch (wordToken->getType()) { case XPathLexer::WILDCARD : if (anywhere) return std::unique_ptr<XPathWildcardAnywhereElement>(new XPathWildcardAnywhereElement()); return std::unique_ptr<XPathWildcardElement>(new XPathWildcardElement()); case XPathLexer::TOKEN_REF: case XPathLexer::STRING : if (ttype == Token::INVALID_TYPE) { throw IllegalArgumentException(word + " at index " + std::to_string(wordToken->getStartIndex()) + " isn't a valid token name"); } if (anywhere) return std::unique_ptr<XPathTokenAnywhereElement>(new XPathTokenAnywhereElement(word, (int)ttype)); return std::unique_ptr<XPathTokenElement>(new XPathTokenElement(word, (int)ttype)); default : if (ruleIndex == -1) { throw IllegalArgumentException(word + " at index " + std::to_string(wordToken->getStartIndex()) + " isn't a valid rule name"); } if (anywhere) return std::unique_ptr<XPathRuleAnywhereElement>(new XPathRuleAnywhereElement(word, (int)ruleIndex)); return std::unique_ptr<XPathRuleElement>(new XPathRuleElement(word, (int)ruleIndex)); } } static ParserRuleContext dummyRoot; std::vector<ParseTree *> XPath::findAll(ParseTree *tree, std::string const& xpath, Parser *parser) { XPath p(parser, xpath); return p.evaluate(tree); } std::vector<ParseTree *> XPath::evaluate(ParseTree *t) { dummyRoot.children = { t }; // don't set t's parent. std::vector<ParseTree *> work = { &dummyRoot }; size_t i = 0; std::vector<std::unique_ptr<XPathElement>> elements = split(_path); while (i < elements.size()) { std::vector<ParseTree *> next; for (auto node : work) { if (!node->children.empty()) { // only try to match next element if it has children // e.g., //func/*/stat might have a token node for which // we can't go looking for stat nodes. auto matching = elements[i]->evaluate(node); next.insert(next.end(), matching.begin(), matching.end()); } } i++; work = next; } return work; }
32.987097
136
0.642676
[ "vector" ]
9cea8b70e86002621a29fb6102f888b78071cbcb
13,646
hpp
C++
OREData/ored/utilities/log.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
OREData/ored/utilities/log.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
OREData/ored/utilities/log.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
1
2022-02-07T02:04:10.000Z
2022-02-07T02:04:10.000Z
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file ored/utilities/log.hpp \brief Classes and functions for log message handling. \ingroup utilities */ #pragma once // accumulated 'filter' for 'external' DEBUG_MASK #define ORE_ALERT 1 // 00000001 1 = 2^1-1 #define ORE_CRITICAL 2 // 00000010 3 = 2^2-1 #define ORE_ERROR 4 // 00000100 7 #define ORE_WARNING 8 // 00001000 15 #define ORE_NOTICE 16 // 00010000 31 #define ORE_DEBUG 32 // 00100000 63 = 2^6-1 #define ORE_DATA 64 // 01000000 127 #define ORE_MEMORY 128 // 10000000 255 #include <fstream> #include <iostream> #include <string> #include <time.h> #include <boost/algorithm/string.hpp> #include <boost/shared_ptr.hpp> #include <map> #include <ql/qldefines.hpp> #include <queue> #ifndef BOOST_MSVC #include <unistd.h> #endif #include <iomanip> #include <ql/patterns/singleton.hpp> #include <sstream> #include <ored/utilities/osutils.hpp> namespace ore { namespace data { using std::string; //! The Base Custom Log Handler class /*! This base log handler class can be used to define your own custom handler and then registered with the Log class. Once registered it will recieve all log messages as soon as they occur via it's log() method \ingroup utilities \see Log */ class Logger { public: //! Desctructor virtual ~Logger() {} //! The Log call back function /*! This function will be called every time a log message is produced. \param level the log level \param s the log message */ virtual void log(unsigned level, const string& s) = 0; //! Returns the Logger name const string& name() { return name_; } protected: //! Constructor /*! Implementations must provide a logger name \param name the logger name */ Logger(const string& name) : name_(name) {} private: string name_; }; //! Stderr Logger /*! This logger writes each log message out to stderr (std::cerr) \ingroup utilities \see Log */ class StderrLogger : public Logger { public: //! the name "StderrLogger" static const string name; //! Constructor /*! This logger writes all logs to stderr. If alertOnly is set to true, it will only write alerts. */ StderrLogger(bool alertOnly = false) : Logger(name), alertOnly_(alertOnly) {} //! Desctructor virtual ~StderrLogger() {} //! The log callback that writes to stderr virtual void log(unsigned l, const string& s) { if (!alertOnly_ || l == ORE_ALERT) std::cerr << s << std::endl; } private: bool alertOnly_; }; //! FileLogger /*! This logger writes each log message out to the given file. The file is flushed, but not closed, after each log message. \ingroup utilities \see Log */ class FileLogger : public Logger { public: //! the name "FileLogger" static const string name; //! Constructor /*! Construct a file logger using the given filename, this filename is passed to std::fostream::open() and this constructor will throw an exception if the file is not opened (e.g. if the filename is invalid) \param filename the log filename */ FileLogger(const string& filename); //! Desctructor virtual ~FileLogger(); //! The log callback virtual void log(unsigned, const string&); private: string filename_; std::fstream fout_; }; //! BufferLogger /*! This logger stores each log message in an internal buffer, it can then be probed for log messages at a later point. Log messages are always returned in a FIFO order. Typical usage to display log messages would be <pre> while (bLogger.hasNext()) { MsgBox("Log Message", bLogger.next()); } </pre> \ingroup utilities \see Log */ class BufferLogger : public Logger { public: //! the name "BufferLogger" static const string name; //! Constructor BufferLogger(unsigned minLevel = ORE_DATA) : Logger(name), minLevel_(minLevel) {} //! Desctructor virtual ~BufferLogger() {} //! The log callback virtual void log(unsigned, const string&); //! Checks if Logger has new messages /*! \return True if this BufferLogger has any new log messages */ bool hasNext(); //! Retreive new messages /*! Retreive the next new message from the buffer, this will throw if the buffer is empty. Messages are returned in a FIFO order. Messages are deleted from the buffer once returned. \return The next message */ string next(); private: std::queue<string> buffer_; unsigned minLevel_; }; //! Global static Log class /*! The Global Log class gets registered with individual loggers and recieves application log messages. Once a message is recieved, it is imediatly dispatched to each of the registered loggers, the order in which the loggers are called is not guarenteed. Logging is done by the calling thread and the LOG call blocks until all the loggers have returned. At start up, the Log class has no loggers and so will ignore any LOG() messages until it is configured. To configure the Log class to log to a file "/tmp/my_log.txt" <pre> Log::instance().removeAllLoggers(); Log::instance().registerLogger(boost::shared_ptr<Logger>(new FileLogger("/tmp/my_log.txt"))); </pre> To change the Log class to only use a BufferLogger the user must call <pre> Log::instance().removeAllLoggers(); Log::instance().registerLogger(boost::shared_ptr<Logger>(new BufferLogger)); </pre> and then to retreive log messages from the buffer and print them to stdout the user must call: <pre> std::cout << "Begin Log Messages:" << std::endl; boost::shared_ptr<BufferLogger> bl = boost::dynamic_pointer_cast<BufferLogger> (Log::instance().logger(BufferLogger::name)); while (bl.hasNext()) std::cout << bl.next() << std::endl; std::cout << "End Log Messages." << std::endl; </pre> \ingroup utilities */ class Log : public QuantLib::Singleton<Log> { friend class QuantLib::Singleton<Log>; public: //! Add a new Logger. /*! Adds a new logger to the Log class, the logger will be stored by it's Logger::name(). This method will throw if a logger with the same name is already registered. \param logger the logger to add */ void registerLogger(const boost::shared_ptr<Logger>& logger); //! Retrieve a Logger. /*! Retrieve a Logger by it's name, for example to retrieve the StderrLogger (assuming it is registered) <pre> boost::shared_ptr<Logger> slogger = Log::instance().logger(StderrLogger::name); </pre> */ boost::shared_ptr<Logger>& logger(const string& name); //! Remove a Logger /*! Remove a logger by name \param name the logger name */ void removeLogger(const string& name); //! Remove all loggers /*! Removes all loggers. If called, all subsiquent log messages will be ignored. */ void removeAllLoggers(); //! macro utility function - do not use directly void header(unsigned m, const char* filename, int lineNo); //! macro utility function - do not use directly std::ostream& logStream() { return ls_; } //! macro utility function - do not use directly void log(unsigned m); // Avoid a large number of warnings in VS by adding 0 != bool filter(unsigned mask) { return 0 != (mask & mask_); } unsigned mask() { return mask_; } void setMask(unsigned mask) { mask_ = mask; } bool enabled() { return enabled_; } void switchOn() { enabled_ = true; } void switchOff() { enabled_ = false; } private: Log(); std::map<string, boost::shared_ptr<Logger>> loggers_; bool enabled_; unsigned mask_; std::ostringstream ls_; }; /*! Main Logging macro, do not use this directly, use on of the below 6 macros instead */ #define MLOG(mask, text) \ if (ore::data::Log::instance().enabled() && ore::data::Log::instance().filter(mask)) { \ ore::data::Log::instance().header(mask, __FILE__, __LINE__); \ ore::data::Log::instance().logStream() << text; \ ore::data::Log::instance().log(mask); \ } //! Logging Macro (Level = Alert) #define ALOG(text) MLOG(ORE_ALERT, text); //! Logging Macro (Level = Critical) #define CLOG(text) MLOG(ORE_CRITICAL, text) //! Logging Macro (Level = Error) #define ELOG(text) MLOG(ORE_ERROR, text) //! Logging Macro (Level = Warning) #define WLOG(text) MLOG(ORE_WARNING, text) //! Logging Macro (Level = Notice) #define LOG(text) MLOG(ORE_NOTICE, text) //! Logging Macro (Level = Debug) #define DLOG(text) MLOG(ORE_DEBUG, text) //! Logging Macro (Level = Data) #define TLOG(text) MLOG(ORE_DATA, text) //! Logging macro specifically for logging memory usage #define MEM_LOG \ if (ore::data::Log::instance().enabled() && ore::data::Log::instance().filter(ORE_MEMORY)) { \ ore::data::Log::instance().header(ORE_MEMORY, __FILE__, __LINE__); \ ore::data::Log::instance().logStream() << std::to_string(ore::data::os::getPeakMemoryUsageBytes()) << "|"; \ ore::data::Log::instance().logStream() << std::to_string(ore::data::os::getMemoryUsageBytes()); \ ore::data::Log::instance().log(ORE_MEMORY); \ } //! LoggerStream class that is a std::ostream replacment that will log each line /*! LoggerStream is a simple wrapper around a string stream, it has an explicit cast std::ostream& method so it can be used in place of any std::ostream, this can be used with QuantExt methods that take a std::ostream& for logging purposes. Once the stream falls out of focus, it's desstructor will take the buffered log messages and pass them the main ore::data::Log::instance(). Note the following - The timestamps for each log message will correspond to when the LoggerStream desstructor has been called, this may not correspond to the actual time the event occured. - The filename and linenumber in the ore::data::Log() have to be explicitly passed to the LoggerStream, as such the log messages will not correspond to any references in QuantExt (or any other library). The LoggerStream relies on falling out of scope to trigger the logging, as such they should not be created using the new operator. The proper usage is to use the macro LOGGERSTREAM and DLOGGERSTREAM, if a function takes a std::ostream& as a parameter, use the macro instead. \code{.cpp} void function(int x, int y, std::ostream& out); void main () { // call function function (3, 4, LOGGERSTREAM); // All logging will be completed before this line } \endcode */ class LoggerStream { public: LoggerStream(unsigned mask, const char* filename, unsigned lineNo); //! destructor - this is when the logging takes place. ~LoggerStream(); //! cast this LoggerStream as a ostream& operator std::ostream&() { return ss_; } private: unsigned mask_; const char* filename_; unsigned lineNo_; std::stringstream ss_; }; #define LOGGERSTREAM ((std::ostream&)ore::data::LoggerStream(ORE_NOTICE, __FILE__, __LINE__)) #define DLOGGERSTREAM ((std::ostream&)ore::data::LoggerStream(ORE_DEBUG, __FILE__, __LINE__)) //! Utility class for having structured Error messages // This can be used directly in log messages, e.g. // ALOG(StructuredTradeErrorMessage(trade->id(), trade->tradeType(), "Error Parsing Trade", "Invalid XML Node foo")); // And in the log file you will get // // .... StructuredErrorMessage { "errorType":"Trade", "tradeId":"foo", "tradeType":"SWAP" } class StructuredErrorMessage { public: static constexpr const char* name = "StructuredErrorMessage"; //! return a string for the log file std::string msg() const { return string(name) + string(" ") + json(); } protected: // This should return a structured string, ideally in JSON, and should contain a field // errorType virtual std::string json() const = 0; // utility function to delimate string for json, handles \" and \\ and control characters std::string jsonify (const std::string& s) const; }; inline std::ostream& operator<<(std::ostream& out, const StructuredErrorMessage& sem) { return out << sem.msg(); } } // namespace data } // namespace ore
34.200501
120
0.652132
[ "model" ]
9ceaf08d64f76d4e9ca19ee9c56162779a1164e5
1,949
cpp
C++
src/rendering/lighting/SpotLight.cpp
WorldWideWebster/GameEngine
d0ff4ff08d327ef8408c88c9c9fe25aed4801f3a
[ "MIT" ]
null
null
null
src/rendering/lighting/SpotLight.cpp
WorldWideWebster/GameEngine
d0ff4ff08d327ef8408c88c9c9fe25aed4801f3a
[ "MIT" ]
1
2019-03-10T03:08:03.000Z
2019-03-10T03:08:03.000Z
src/rendering/lighting/SpotLight.cpp
WorldWideWebster/OpenGL-Stuff
d0ff4ff08d327ef8408c88c9c9fe25aed4801f3a
[ "MIT" ]
null
null
null
// // Created by Sean on 8/16/2019. // #include "SpotLight.h" SpotLight::SpotLight(std::string ID) : Light(ID), DirectionalLight(ID), PointLight(ID) { this->m_cutOff = glm::cos(glm::radians(32.5f)); this->m_outerCutOff = glm::cos(glm::radians(45.0f)); } SpotLight::SpotLight(float cutOff, float outerCutOff, std::string ID) : Light(ID), DirectionalLight(ID), PointLight(ID) { this->m_cutOff = cutOff; this->m_outerCutOff = outerCutOff; } SpotLight::SpotLight(float cutOff, float outerCutOff, glm::vec3 direction, glm::vec3 color, std::string ID) : Light(ID), DirectionalLight(direction, color, ID), PointLight(ID) { this->m_cutOff = cutOff; this->m_outerCutOff = outerCutOff; } SpotLight::SpotLight(float cutOff, float outerCutOff, glm::vec3 position, float constant, float linear, float quadratic, glm::vec3 color, std::string ID) : Light(ID), DirectionalLight(ID), PointLight(position, constant, linear, quadratic, color, ID) { this->m_cutOff = cutOff; this->m_outerCutOff = outerCutOff; } SpotLight::SpotLight(float cutOff, float outerCutOff, glm::vec3 position, glm::vec3 direction, float constant, float linear, float quadratic, glm::vec3 color, std::string ID): Light(ID), DirectionalLight(direction, color, ID), PointLight(position, constant, linear, quadratic, color, ID) { this->m_cutOff = cutOff; this->m_outerCutOff = outerCutOff; } void SpotLight::render(Shader *targetShader) { DirectionalLight::render(targetShader); PointLight::render(targetShader); targetShader->setFloat("spotLights[0].cutOff", this->m_cutOff); targetShader->setFloat("spotLights[0].outerCutOff", this->m_outerCutOff); } void SpotLight::setcutOff(float cutOff) { this->m_cutOff = cutOff; } void SpotLight::setOuterCutOff(float outerCutOff) { this->m_outerCutOff = outerCutOff; } float SpotLight::getcutOff(void) { return this->m_cutOff; } float SpotLight::getOuterCutOff(void) { return this->m_outerCutOff; }
27.069444
119
0.735249
[ "render" ]
9cefb95743a598b5f0b03855de30396ace0c6f5e
1,285
cpp
C++
Engine/src/Components/boxcollider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
1
2019-01-02T15:35:05.000Z
2019-01-02T15:35:05.000Z
Engine/src/Components/boxcollider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
2
2018-11-11T21:29:05.000Z
2019-01-02T15:34:10.000Z
Engine/src/Components/boxcollider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
null
null
null
#include "boxcollider.h" namespace Ossium { REGISTER_COMPONENT(BoxCollider); void BoxCollider::SetupShape() { shape.SetAsBox(PTM(width / 2.0f), PTM(height / 2.0f)); shape.m_centroid = offset; } const b2Shape& BoxCollider::GetShape() { return shape; } const b2PolygonShape& BoxCollider::GetPolygonShape() { return shape; } void BoxCollider::Render(Renderer& renderer) { #ifdef OSSIUM_EDITOR Ossium::Rect box = { .x = (GetTransform()->GetWorldPosition().x - (width / 2)) + offset.x, .y = (GetTransform()->GetWorldPosition().y - (height / 2)) + offset.y, .w = width, .h = height }; box.Draw(renderer, Ossium::Colors::GREEN); #endif // OSSIUM_EDITOR } /* TODO: rebuild physics body void BoxCollider::SetWidth(float width) { this->width = width; shape.SetAsBox(PTM(width / 2.0f), PTM(height / 2.0f)); } void BoxCollider::SetHeight(float height) { this->height = height; shape.SetAsBox(PTM(width / 2.0f), PTM(height / 2.0f)); } float BoxCollider::GetWidth() { return width; } float BoxCollider::GetHeight() { return height; } */ }
21.779661
82
0.564202
[ "render", "shape" ]
9cf034863e85c2d1434eda45e0b1e606999b3bac
14,393
cpp
C++
libraries/avatars-renderer/src/avatars-renderer/Head.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
3
2019-01-27T14:49:35.000Z
2020-01-15T18:49:11.000Z
libraries/avatars-renderer/src/avatars-renderer/Head.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
libraries/avatars-renderer/src/avatars-renderer/Head.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
2
2019-06-13T22:25:13.000Z
2022-01-31T15:17:55.000Z
// // Head.cpp // interface/src/avatar // // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Head.h" #include <glm/gtx/quaternion.hpp> #include <gpu/Batch.h> #include <NodeList.h> #include <DependencyManager.h> #include <GeometryUtil.h> #include <trackers/FaceTracker.h> #include <trackers/EyeTracker.h> #include <Rig.h> #include "Logging.h" #include "Avatar.h" using namespace std; static bool disableEyelidAdjustment { false }; Head::Head(Avatar* owningAvatar) : HeadData(owningAvatar), _leftEyeLookAtID(DependencyManager::get<GeometryCache>()->allocateID()), _rightEyeLookAtID(DependencyManager::get<GeometryCache>()->allocateID()) { } void Head::init() { } void Head::reset() { _baseYaw = _basePitch = _baseRoll = 0.0f; } void Head::simulate(float deltaTime) { const float NORMAL_HZ = 60.0f; // the update rate the constant values were tuned for // grab the audio loudness from the owning avatar, if we have one float audioLoudness = _owningAvatar ? _owningAvatar->getAudioLoudness() : 0.0f; // Update audio trailing average for rendering facial animations const float AUDIO_AVERAGING_SECS = 0.05f; const float AUDIO_LONG_TERM_AVERAGING_SECS = 30.0f; _averageLoudness = glm::mix(_averageLoudness, audioLoudness, glm::min(deltaTime / AUDIO_AVERAGING_SECS, 1.0f)); if (_longTermAverageLoudness == -1.0f) { _longTermAverageLoudness = _averageLoudness; } else { _longTermAverageLoudness = glm::mix(_longTermAverageLoudness, _averageLoudness, glm::min(deltaTime / AUDIO_LONG_TERM_AVERAGING_SECS, 1.0f)); } if (!_isEyeTrackerConnected) { // Update eye saccades const float AVERAGE_MICROSACCADE_INTERVAL = 1.0f; const float AVERAGE_SACCADE_INTERVAL = 6.0f; const float MICROSACCADE_MAGNITUDE = 0.002f; const float SACCADE_MAGNITUDE = 0.04f; const float NOMINAL_FRAME_RATE = 60.0f; if (randFloat() < deltaTime / AVERAGE_MICROSACCADE_INTERVAL) { _saccadeTarget = MICROSACCADE_MAGNITUDE * randVector(); } else if (randFloat() < deltaTime / AVERAGE_SACCADE_INTERVAL) { _saccadeTarget = SACCADE_MAGNITUDE * randVector(); } _saccade += (_saccadeTarget - _saccade) * pow(0.5f, NOMINAL_FRAME_RATE * deltaTime); } else { _saccade = glm::vec3(); } const float BLINK_SPEED = 10.0f; const float BLINK_SPEED_VARIABILITY = 1.0f; const float BLINK_START_VARIABILITY = 0.25f; const float FULLY_OPEN = 0.0f; const float FULLY_CLOSED = 1.0f; if (getHasProceduralBlinkFaceMovement()) { // Detect transition from talking to not; force blink after that and a delay bool forceBlink = false; const float TALKING_LOUDNESS = 100.0f; const float BLINK_AFTER_TALKING = 0.25f; _timeWithoutTalking += deltaTime; if ((_averageLoudness - _longTermAverageLoudness) > TALKING_LOUDNESS) { _timeWithoutTalking = 0.0f; } else if (_timeWithoutTalking - deltaTime < BLINK_AFTER_TALKING && _timeWithoutTalking >= BLINK_AFTER_TALKING) { forceBlink = true; } if (_leftEyeBlinkVelocity == 0.0f && _rightEyeBlinkVelocity == 0.0f) { // no blinking when brows are raised; blink less with increasing loudness const float BASE_BLINK_RATE = 15.0f / 60.0f; const float ROOT_LOUDNESS_TO_BLINK_INTERVAL = 0.25f; if (forceBlink || (_browAudioLift < EPSILON && shouldDo(glm::max(1.0f, sqrt(fabs(_averageLoudness - _longTermAverageLoudness)) * ROOT_LOUDNESS_TO_BLINK_INTERVAL) / BASE_BLINK_RATE, deltaTime))) { _leftEyeBlinkVelocity = BLINK_SPEED + randFloat() * BLINK_SPEED_VARIABILITY; _rightEyeBlinkVelocity = BLINK_SPEED + randFloat() * BLINK_SPEED_VARIABILITY; if (randFloat() < 0.5f) { _leftEyeBlink = BLINK_START_VARIABILITY; } else { _rightEyeBlink = BLINK_START_VARIABILITY; } } } else { _leftEyeBlink = glm::clamp(_leftEyeBlink + _leftEyeBlinkVelocity * deltaTime, FULLY_OPEN, FULLY_CLOSED); _rightEyeBlink = glm::clamp(_rightEyeBlink + _rightEyeBlinkVelocity * deltaTime, FULLY_OPEN, FULLY_CLOSED); if (_leftEyeBlink == FULLY_CLOSED) { _leftEyeBlinkVelocity = -BLINK_SPEED; } else if (_leftEyeBlink == FULLY_OPEN) { _leftEyeBlinkVelocity = 0.0f; } if (_rightEyeBlink == FULLY_CLOSED) { _rightEyeBlinkVelocity = -BLINK_SPEED; } else if (_rightEyeBlink == FULLY_OPEN) { _rightEyeBlinkVelocity = 0.0f; } } } else { _rightEyeBlink = FULLY_OPEN; _leftEyeBlink = FULLY_OPEN; } // use data to update fake Faceshift blendshape coefficients if (getHasAudioEnabledFaceMovement()) { // Update audio attack data for facial animation (eyebrows and mouth) float audioAttackAveragingRate = (10.0f - deltaTime * NORMAL_HZ) / 10.0f; // --> 0.9 at 60 Hz _audioAttack = audioAttackAveragingRate * _audioAttack + (1.0f - audioAttackAveragingRate) * fabs((audioLoudness - _longTermAverageLoudness) - _lastLoudness); _lastLoudness = (audioLoudness - _longTermAverageLoudness); const float BROW_LIFT_THRESHOLD = 100.0f; if (_audioAttack > BROW_LIFT_THRESHOLD) { _browAudioLift += sqrtf(_audioAttack) * 0.01f; } _browAudioLift = glm::clamp(_browAudioLift *= 0.7f, 0.0f, 1.0f); calculateMouthShapes(deltaTime); } else { _audioJawOpen = 0.0f; _browAudioLift = 0.0f; _mouth2 = 0.0f; _mouth3 = 0.0f; _mouth4 = 0.0f; _mouthTime = 0.0f; } FaceTracker::updateFakeCoefficients(_leftEyeBlink, _rightEyeBlink, _browAudioLift, _audioJawOpen, _mouth2, _mouth3, _mouth4, _transientBlendshapeCoefficients); if (getHasProceduralEyeFaceMovement()) { applyEyelidOffset(getOrientation()); } _leftEyePosition = _rightEyePosition = getPosition(); if (_owningAvatar) { auto skeletonModel = static_cast<Avatar*>(_owningAvatar)->getSkeletonModel(); if (skeletonModel) { skeletonModel->getEyePositions(_leftEyePosition, _rightEyePosition); } } _eyePosition = 0.5f * (_leftEyePosition + _rightEyePosition); } void Head::calculateMouthShapes(float deltaTime) { const float JAW_OPEN_SCALE = 0.015f; const float JAW_OPEN_RATE = 0.9f; const float JAW_CLOSE_RATE = 0.90f; const float TIMESTEP_CONSTANT = 0.0032f; const float MMMM_POWER = 0.10f; const float SMILE_POWER = 0.10f; const float FUNNEL_POWER = 0.35f; const float MMMM_SPEED = 2.685f; const float SMILE_SPEED = 1.0f; const float FUNNEL_SPEED = 2.335f; const float STOP_GAIN = 5.0f; const float NORMAL_HZ = 60.0f; // the update rate the constant values were tuned for float deltaTimeRatio = deltaTime / (1.0f / NORMAL_HZ); // From the change in loudness, decide how much to open or close the jaw float audioDelta = sqrtf(glm::max(_averageLoudness - _longTermAverageLoudness, 0.0f)) * JAW_OPEN_SCALE; if (audioDelta > _audioJawOpen) { _audioJawOpen += (audioDelta - _audioJawOpen) * JAW_OPEN_RATE * deltaTimeRatio; } else { _audioJawOpen *= powf(JAW_CLOSE_RATE, deltaTimeRatio); } _audioJawOpen = glm::clamp(_audioJawOpen, 0.0f, 1.0f); float trailingAudioJawOpenRatio = (100.0f - deltaTime * NORMAL_HZ) / 100.0f; // --> 0.99 at 60 Hz _trailingAudioJawOpen = glm::mix(_trailingAudioJawOpen, _audioJawOpen, trailingAudioJawOpenRatio); // truncate _mouthTime when mouth goes quiet to prevent floating point error on increment const float SILENT_TRAILING_JAW_OPEN = 0.0002f; const float MAX_SILENT_MOUTH_TIME = 10.0f; if (_trailingAudioJawOpen < SILENT_TRAILING_JAW_OPEN && _mouthTime > MAX_SILENT_MOUTH_TIME) { _mouthTime = 0.0f; } // Advance time at a rate proportional to loudness, and move the mouth shapes through // a cycle at differing speeds to create a continuous random blend of shapes. _mouthTime += sqrtf(_averageLoudness) * TIMESTEP_CONSTANT * deltaTimeRatio; _mouth2 = (sinf(_mouthTime * MMMM_SPEED) + 1.0f) * MMMM_POWER * glm::min(1.0f, _trailingAudioJawOpen * STOP_GAIN); _mouth3 = (sinf(_mouthTime * FUNNEL_SPEED) + 1.0f) * FUNNEL_POWER * glm::min(1.0f, _trailingAudioJawOpen * STOP_GAIN); _mouth4 = (sinf(_mouthTime * SMILE_SPEED) + 1.0f) * SMILE_POWER * glm::min(1.0f, _trailingAudioJawOpen * STOP_GAIN); } void Head::applyEyelidOffset(glm::quat headOrientation) { // Adjusts the eyelid blendshape coefficients so that the eyelid follows the iris as the head pitches. bool isBlinking = (_rightEyeBlinkVelocity != 0.0f && _rightEyeBlinkVelocity != 0.0f); if (disableEyelidAdjustment || isBlinking) { return; } const float EYE_PITCH_TO_COEFFICIENT = 3.5f; // Empirically determined const float MAX_EYELID_OFFSET = 1.5f; const float BLINK_DOWN_MULTIPLIER = 0.25f; const float OPEN_DOWN_MULTIPLIER = 0.3f; const float BROW_UP_MULTIPLIER = 0.5f; glm::vec3 lookAt = glm::normalize(getLookAtPosition() - _eyePosition); glm::vec3 headUp = headOrientation * Vectors::UNIT_Y; float eyePitch = (PI / 2.0f) - acos(glm::dot(lookAt, headUp)); float eyelidOffset = glm::clamp(abs(eyePitch * EYE_PITCH_TO_COEFFICIENT), 0.0f, MAX_EYELID_OFFSET); float blinkUpCoefficient = -eyelidOffset; float blinkDownCoefficient = BLINK_DOWN_MULTIPLIER * eyelidOffset; float openUpCoefficient = eyelidOffset; float openDownCoefficient = OPEN_DOWN_MULTIPLIER * eyelidOffset; float browsUpCoefficient = BROW_UP_MULTIPLIER * eyelidOffset; float browsDownCoefficient = 0.0f; bool isLookingUp = (eyePitch > 0); if (isLookingUp) { for (int i = 0; i < 2; i++) { _transientBlendshapeCoefficients[EYE_BLINK_INDICES[i]] = blinkUpCoefficient; _transientBlendshapeCoefficients[EYE_OPEN_INDICES[i]] = openUpCoefficient; _transientBlendshapeCoefficients[BROWS_U_INDICES[i]] = browsUpCoefficient; } } else { for (int i = 0; i < 2; i++) { _transientBlendshapeCoefficients[EYE_BLINK_INDICES[i]] = blinkDownCoefficient; _transientBlendshapeCoefficients[EYE_OPEN_INDICES[i]] = openDownCoefficient; _transientBlendshapeCoefficients[BROWS_U_INDICES[i]] = browsDownCoefficient; } } } void Head::relax(float deltaTime) { // restore rotation, lean to neutral positions const float LEAN_RELAXATION_PERIOD = 0.25f; // seconds float relaxationFactor = 1.0f - glm::min(deltaTime / LEAN_RELAXATION_PERIOD, 1.0f); _deltaYaw *= relaxationFactor; _deltaPitch *= relaxationFactor; _deltaRoll *= relaxationFactor; } void Head::setScale (float scale) { if (_scale == scale) { return; } _scale = scale; } glm::quat Head::getFinalOrientationInWorldFrame() const { return _owningAvatar->getWorldOrientation() * getFinalOrientationInLocalFrame(); } glm::quat Head::getFinalOrientationInLocalFrame() const { return glm::quat(glm::radians(glm::vec3(getFinalPitch(), getFinalYaw(), getFinalRoll() ))); } // Everyone else's head keeps track of a lookAtPosition that everybody sees the same, and refers to where that head // is looking in model space -- e.g., at someone's eyeball, or between their eyes, or mouth, etc. Everyon's Interface // will have the same value for the lookAtPosition of any given head. // // Everyone else's head also keeps track of a correctedLookAtPosition that may be different for the same head within // different Interfaces. If that head is not looking at me, the correctedLookAtPosition is the same as the lookAtPosition. // However, if that head is looking at me, then I will attempt to adjust the lookAtPosition by the difference between // my (singular) eye position and my actual camera position. This adjustment is used on their eyeballs during rendering // (and also on any lookAt vector display for that head, during rendering). Note that: // 1. this adjustment can be made directly to the other head's eyeball joints, because we won't be send their joint information to others. // 2. the corrected position is a separate ivar, so the common/uncorrected value is still available // // There is a pun here: The two lookAtPositions will always be the same for my own avatar in my own Interface, because I // will not be looking at myself. (Even in a mirror, I will be looking at the camera.) glm::vec3 Head::getCorrectedLookAtPosition() { if (isLookingAtMe()) { return _correctedLookAtPosition; } else { return getLookAtPosition(); } } void Head::setCorrectedLookAtPosition(const glm::vec3& correctedLookAtPosition) { if (!isLookingAtMe()) { _lookingAtMeStarted = usecTimestampNow(); } _isLookingAtMe = true; _wasLastLookingAtMe = usecTimestampNow(); _correctedLookAtPosition = correctedLookAtPosition; } bool Head::isLookingAtMe() { // Allow for outages such as may be encountered during avatar movement quint64 now = usecTimestampNow(); const quint64 LOOKING_AT_ME_GAP_ALLOWED = (5 * 1000 * 1000) / 60; // n frames, in microseconds return _isLookingAtMe || (now - _wasLastLookingAtMe) < LOOKING_AT_ME_GAP_ALLOWED; } glm::quat Head::getEyeRotation(const glm::vec3& eyePosition) const { glm::quat orientation = getOrientation(); glm::vec3 lookAtDelta = _lookAtPosition - eyePosition; return rotationBetween(orientation * IDENTITY_FORWARD, lookAtDelta + glm::length(lookAtDelta) * _saccade) * orientation; } float Head::getFinalYaw() const { return glm::clamp(_baseYaw + _deltaYaw, MIN_HEAD_YAW, MAX_HEAD_YAW); } float Head::getFinalPitch() const { return glm::clamp(_basePitch + _deltaPitch, MIN_HEAD_PITCH, MAX_HEAD_PITCH); } float Head::getFinalRoll() const { return glm::clamp(_baseRoll + _deltaRoll, MIN_HEAD_ROLL, MAX_HEAD_ROLL); }
41.962099
148
0.691795
[ "vector", "model" ]
9cf3752e07ed560f1024a1cce0e0e7da6bbbb5ab
564
hpp
C++
libs/boost_1_72_0/boost/python/detail/scope.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/python/detail/scope.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/python/detail/scope.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright David Abrahams 2002. // 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 SCOPE_DWA2002927_HPP #define SCOPE_DWA2002927_HPP #include <boost/python/detail/config.hpp> namespace boost { namespace python { namespace detail { void BOOST_PYTHON_DECL scope_setattr_doc(char const *name, object const &obj, char const *doc); } } // namespace python } // namespace boost #endif // SCOPE_DWA2002927_HPP
25.636364
77
0.716312
[ "object" ]
9cf5c3717370b0eaf1d6ea7e4f12aea6b7f6d120
20,924
cc
C++
include/protobuf/core/framework/versions.pb.cc
gluonhq/libnd4j
6be4678caf6f820f5b0fd1a5392c0941936f2e43
[ "Apache-2.0" ]
null
null
null
include/protobuf/core/framework/versions.pb.cc
gluonhq/libnd4j
6be4678caf6f820f5b0fd1a5392c0941936f2e43
[ "Apache-2.0" ]
null
null
null
include/protobuf/core/framework/versions.pb.cc
gluonhq/libnd4j
6be4678caf6f820f5b0fd1a5392c0941936f2e43
[ "Apache-2.0" ]
1
2022-03-25T06:48:25.000Z
2022-03-25T06:48:25.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/versions.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "versions.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace tensorflow { class VersionDefDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<VersionDef> _instance; } _VersionDef_default_instance_; namespace protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[1]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { NULL, NULL, 0, -1, -1, -1, -1, NULL, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(VersionDef, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(VersionDef, producer_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(VersionDef, min_consumer_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(VersionDef, bad_consumers_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(VersionDef)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_VersionDef_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "tensorflow/core/framework/versions.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } } // namespace void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); _VersionDef_default_instance_._instance.DefaultConstruct(); ::google::protobuf::internal::OnShutdownDestroyMessage( &_VersionDef_default_instance_);} void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } namespace { void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n(tensorflow/core/framework/versions.pro" "to\022\ntensorflow\"K\n\nVersionDef\022\020\n\010producer" "\030\001 \001(\005\022\024\n\014min_consumer\030\002 \001(\005\022\025\n\rbad_cons" "umers\030\003 \003(\005B/\n\030org.tensorflow.frameworkB" "\016VersionsProtosP\001\370\001\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 188); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "tensorflow/core/framework/versions.proto", &protobuf_RegisterTypes); } } // anonymous namespace void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int VersionDef::kProducerFieldNumber; const int VersionDef::kMinConsumerFieldNumber; const int VersionDef::kBadConsumersFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 VersionDef::VersionDef() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:tensorflow.VersionDef) } VersionDef::VersionDef(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), bad_consumers_(arena) { protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::InitDefaults(); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:tensorflow.VersionDef) } VersionDef::VersionDef(const VersionDef& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), bad_consumers_(from.bad_consumers_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&producer_, &from.producer_, static_cast<size_t>(reinterpret_cast<char*>(&min_consumer_) - reinterpret_cast<char*>(&producer_)) + sizeof(min_consumer_)); // @@protoc_insertion_point(copy_constructor:tensorflow.VersionDef) } void VersionDef::SharedCtor() { ::memset(&producer_, 0, static_cast<size_t>( reinterpret_cast<char*>(&min_consumer_) - reinterpret_cast<char*>(&producer_)) + sizeof(min_consumer_)); _cached_size_ = 0; } VersionDef::~VersionDef() { // @@protoc_insertion_point(destructor:tensorflow.VersionDef) SharedDtor(); } void VersionDef::SharedDtor() { ::google::protobuf::Arena* arena = GetArenaNoVirtual(); GOOGLE_DCHECK(arena == NULL); if (arena != NULL) { return; } } void VersionDef::ArenaDtor(void* object) { VersionDef* _this = reinterpret_cast< VersionDef* >(object); (void)_this; } void VersionDef::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void VersionDef::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* VersionDef::descriptor() { protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const VersionDef& VersionDef::default_instance() { protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::InitDefaults(); return *internal_default_instance(); } VersionDef* VersionDef::New(::google::protobuf::Arena* arena) const { return ::google::protobuf::Arena::CreateMessage<VersionDef>(arena); } void VersionDef::Clear() { // @@protoc_insertion_point(message_clear_start:tensorflow.VersionDef) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; bad_consumers_.Clear(); ::memset(&producer_, 0, static_cast<size_t>( reinterpret_cast<char*>(&min_consumer_) - reinterpret_cast<char*>(&producer_)) + sizeof(min_consumer_)); _internal_metadata_.Clear(); } bool VersionDef::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:tensorflow.VersionDef) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 producer = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &producer_))); } else { goto handle_unusual; } break; } // int32 min_consumer = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &min_consumer_))); } else { goto handle_unusual; } break; } // repeated int32 bad_consumers = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_bad_consumers()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 1, 26u, input, this->mutable_bad_consumers()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:tensorflow.VersionDef) return true; failure: // @@protoc_insertion_point(parse_failure:tensorflow.VersionDef) return false; #undef DO_ } void VersionDef::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:tensorflow.VersionDef) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 producer = 1; if (this->producer() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->producer(), output); } // int32 min_consumer = 2; if (this->min_consumer() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->min_consumer(), output); } // repeated int32 bad_consumers = 3; if (this->bad_consumers_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _bad_consumers_cached_byte_size_)); } for (int i = 0, n = this->bad_consumers_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( this->bad_consumers(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:tensorflow.VersionDef) } ::google::protobuf::uint8* VersionDef::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:tensorflow.VersionDef) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 producer = 1; if (this->producer() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->producer(), target); } // int32 min_consumer = 2; if (this->min_consumer() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->min_consumer(), target); } // repeated int32 bad_consumers = 3; if (this->bad_consumers_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::uint32>( _bad_consumers_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt32NoTagToArray(this->bad_consumers_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:tensorflow.VersionDef) return target; } size_t VersionDef::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:tensorflow.VersionDef) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int32 bad_consumers = 3; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int32Size(this->bad_consumers_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _bad_consumers_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // int32 producer = 1; if (this->producer() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->producer()); } // int32 min_consumer = 2; if (this->min_consumer() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->min_consumer()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void VersionDef::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:tensorflow.VersionDef) GOOGLE_DCHECK_NE(&from, this); const VersionDef* source = ::google::protobuf::internal::DynamicCastToGenerated<const VersionDef>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.VersionDef) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.VersionDef) MergeFrom(*source); } } void VersionDef::MergeFrom(const VersionDef& from) { // @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.VersionDef) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; bad_consumers_.MergeFrom(from.bad_consumers_); if (from.producer() != 0) { set_producer(from.producer()); } if (from.min_consumer() != 0) { set_min_consumer(from.min_consumer()); } } void VersionDef::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:tensorflow.VersionDef) if (&from == this) return; Clear(); MergeFrom(from); } void VersionDef::CopyFrom(const VersionDef& from) { // @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.VersionDef) if (&from == this) return; Clear(); MergeFrom(from); } bool VersionDef::IsInitialized() const { return true; } void VersionDef::Swap(VersionDef* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { VersionDef* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void VersionDef::UnsafeArenaSwap(VersionDef* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void VersionDef::InternalSwap(VersionDef* other) { using std::swap; bad_consumers_.InternalSwap(&other->bad_consumers_); swap(producer_, other->producer_); swap(min_consumer_, other->min_consumer_); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata VersionDef::GetMetadata() const { protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_tensorflow_2fcore_2fframework_2fversions_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // VersionDef // int32 producer = 1; void VersionDef::clear_producer() { producer_ = 0; } ::google::protobuf::int32 VersionDef::producer() const { // @@protoc_insertion_point(field_get:tensorflow.VersionDef.producer) return producer_; } void VersionDef::set_producer(::google::protobuf::int32 value) { producer_ = value; // @@protoc_insertion_point(field_set:tensorflow.VersionDef.producer) } // int32 min_consumer = 2; void VersionDef::clear_min_consumer() { min_consumer_ = 0; } ::google::protobuf::int32 VersionDef::min_consumer() const { // @@protoc_insertion_point(field_get:tensorflow.VersionDef.min_consumer) return min_consumer_; } void VersionDef::set_min_consumer(::google::protobuf::int32 value) { min_consumer_ = value; // @@protoc_insertion_point(field_set:tensorflow.VersionDef.min_consumer) } // repeated int32 bad_consumers = 3; int VersionDef::bad_consumers_size() const { return bad_consumers_.size(); } void VersionDef::clear_bad_consumers() { bad_consumers_.Clear(); } ::google::protobuf::int32 VersionDef::bad_consumers(int index) const { // @@protoc_insertion_point(field_get:tensorflow.VersionDef.bad_consumers) return bad_consumers_.Get(index); } void VersionDef::set_bad_consumers(int index, ::google::protobuf::int32 value) { bad_consumers_.Set(index, value); // @@protoc_insertion_point(field_set:tensorflow.VersionDef.bad_consumers) } void VersionDef::add_bad_consumers(::google::protobuf::int32 value) { bad_consumers_.Add(value); // @@protoc_insertion_point(field_add:tensorflow.VersionDef.bad_consumers) } const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& VersionDef::bad_consumers() const { // @@protoc_insertion_point(field_list:tensorflow.VersionDef.bad_consumers) return bad_consumers_; } ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* VersionDef::mutable_bad_consumers() { // @@protoc_insertion_point(field_mutable_list:tensorflow.VersionDef.bad_consumers) return &bad_consumers_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace tensorflow // @@protoc_insertion_point(global_scope)
36.452962
168
0.725435
[ "object" ]
9cf640abdedd4f8a407b408b58ed5812234f091f
91,714
cpp
C++
platform/common/gbcpu.cpp
PMArkive/GameYob
d3518656c1abeb138d265f2b23de376d435ae335
[ "MIT" ]
1
2021-09-10T17:20:34.000Z
2021-09-10T17:20:34.000Z
platform/common/gbcpu.cpp
PMArkive/GameYob
d3518656c1abeb138d265f2b23de376d435ae335
[ "MIT" ]
null
null
null
platform/common/gbcpu.cpp
PMArkive/GameYob
d3518656c1abeb138d265f2b23de376d435ae335
[ "MIT" ]
null
null
null
#include <stddef.h> #include <stdio.h> #ifdef DS #include <nds.h> #endif #ifndef DS #include <string.h> #endif #include "mmu.h" #include "gbgfx.h" #include "soundengine.h" #include "gameboy.h" #include "main.h" #ifdef CPU_DEBUG #include "debugger.h" #endif #define FLAG_Z 0x80 #define FLAG_N 0x40 #define FLAG_H 0x20 #define FLAG_C 0x10 #define setZFlag() locF |= 0x80 #define clearZFlag() locF &= 0x7F #define setNFlag() locF |= 0x40 #define clearNFlag() locF &= 0xBF #define setHFlag() locF |= 0x20 #define clearHFlag() locF &= 0xDF #define setCFlag() locF |= 0x10 #define clearCFlag() locF &= 0xEF #define carrySet() (locF & 0x10) #define zeroSet() (locF & 0x80) #define negativeSet() (locF & 0x40) #define halfSet() (locF & 0x20) #define numberedGbReg(n) ((u8 *) &g_gbRegs + reg8Offsets[n]) #define carryBit() (locF & 0x10 ? 1 : 0) const u8 opCycles[0x100] #ifdef DS DTCM_DATA #endif = { /* Low nybble -> */ /* High nybble v */ /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F */ /* 0X */ 4,12, 8, 8, 4, 4, 8, 4,20, 8, 8, 8, 4, 4, 8, 4, /* 1X */ 4,12, 8, 8, 4, 4, 8, 4,12, 8, 8, 8, 4, 4, 8, 4, /* 2X */ 12,12, 8, 8, 4, 4, 8, 4,12, 8, 8, 8, 4, 4, 8, 4, /* 3X */ 12,12, 8, 8,12,12,12, 4,12, 8, 8, 8, 4, 4, 8, 4, /* 4X */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 5X */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 6X */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 7X */ 8, 8, 8, 8, 8, 8, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, /* 8X */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 9X */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* AX */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* BX */ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* CX */ 20,12,16,16,24,16, 8,16,20,16,16, 0,24,24, 8,16, /* DX */ 20,12,16,99,24,16, 8,16,20,16,16,99,24,99, 8,16, /* EX */ 12,12, 8,99,99,16, 8,16,16, 4,16,99,99,99, 8,16, /* FX */ 12,12, 8, 4,99,16, 8,16,12, 8,16, 4,99,99, 8,16 /* opcodes that have 99 cycles are undefined, but don't hang on them */ }; const u8 CBopCycles[0x100] #ifdef DS DTCM_DATA #endif = { /* Low nybble -> */ /* High nybble v */ /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F */ /* 0X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* 1X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* 2X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* 3X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* 4X */ 8, 8, 8, 8, 8, 8,12, 8, 8, 8, 8, 8, 8, 8,12, 8, /* 5X */ 8, 8, 8, 8, 8, 8,12, 8, 8, 8, 8, 8, 8, 8,12, 8, /* 6X */ 8, 8, 8, 8, 8, 8,12, 8, 8, 8, 8, 8, 8, 8,12, 8, /* 7X */ 8, 8, 8, 8, 8, 8,12, 8, 8, 8, 8, 8, 8, 8,12, 8, /* 8X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* 9X */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* AX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* BX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* CX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* DX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* EX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8, /* FX */ 8, 8, 8, 8, 8, 8,16, 8, 8, 8, 8, 8, 8, 8,16, 8 }; /* struct Registers Gameboy::g_gbRegs; #ifdef DS DTCM_BSS #endif ; int DTCM_BSS Gameboy::halt; */ void Gameboy::enableInterrupts() { ime = 1; if (ioRam[0x0f] & ioRam[0xff]) cyclesToExecute = -1; } void Gameboy::disableInterrupts() { ime = 0; } int Gameboy::handleInterrupts(unsigned int interruptTriggered) { const u16 isrVectors[] = { 0x40, 0x48, 0x50, 0x58, 0x60 }; /* Halt state is always reset */ halt = 0; /* Avoid processing irqs */ if (!ime) { return 0; } ime = 0; #ifdef SPEEDHAX quickWrite(--g_gbRegs.sp.w, g_gbRegs.pc.b.h); quickWrite(--g_gbRegs.sp.w, g_gbRegs.pc.b.l); #else writeMemory(--g_gbRegs.sp.w, g_gbRegs.pc.b.h); writeMemory(--g_gbRegs.sp.w, g_gbRegs.pc.b.l); #endif /* __builtin_ffs returns the first bit set plus one */ int irqNo = __builtin_ffs(interruptTriggered) - 1; /* Jump to the vector */ g_gbRegs.pc.w = isrVectors[irqNo]; /* Clear the IF bit */ ioRam[0x0F] &= ~(1<<irqNo); /* The interrupt prologue takes 20 cycles, take it into account */ return 20; } const u8 reg8Offsets[] #ifdef DS DTCM_DATA #endif = { offsetof(struct Registers, bc.b.h), offsetof(struct Registers, bc.b.l), offsetof(struct Registers, de.b.h), offsetof(struct Registers, de.b.l), offsetof(struct Registers, hl.b.h), offsetof(struct Registers, hl.b.l), 0, offsetof(struct Registers, af.b.h) }; #define setPC(val) { g_gbRegs.pc.w = (val); pcAddr = &memory[(g_gbRegs.pc.w)>>12][(g_gbRegs.pc.w)&0xfff]; firstPcAddr=pcAddr;} #define getPC() (g_gbRegs.pc.w+(pcAddr-firstPcAddr)) #define readPC() *(pcAddr++) #define readPC_noinc() (*pcAddr) #define readPC16() ((*pcAddr) | ((*(pcAddr+1))<<8)); pcAddr += 2 #define readPC16_noinc() ((*pcAddr) | ((*(pcAddr+1))<<8)) #define OP_JR(cond) \ if (cond) { \ setPC((getPC()+(s8)readPC_noinc()+1)&0xffff); \ } \ else { \ pcAddr++; \ totalCycles -= 4; \ } struct Registers g_gbRegs #ifdef DS DTCM_BSS #endif ; int cyclesToExecute #ifdef DS DTCM_BSS #endif ; u8* haltBugAddr #ifdef DS DTCM_BSS #endif = NULL; u8* firstPcAddr #ifdef DS DTCM_BSS #endif ; int Gameboy::runOpcode(int cycles) { cyclesToExecute = cycles; // Having these commonly-used registers in local variables should improve speed register u8* pcAddr; pcAddr = memory[g_gbRegs.pc.w>>12]+(g_gbRegs.pc.w&0xfff); firstPcAddr = pcAddr; int locSP=g_gbRegs.sp.w; int locF =g_gbRegs.af.b.l; register int totalCycles=0; while (totalCycles < cyclesToExecute) { #ifdef CPU_DEBUG setPC(getPC()); g_gbRegs.sp.w = locSP; g_gbRegs.af.b.l = locF; runDebugger(this, g_gbRegs); #endif u8 opcode = *pcAddr; pcAddr++; totalCycles += opCycles[opcode]; switch(opcode) { // 8-bit loads case 0x06: // LD B, n 8 case 0x0E: // LD C, n 8 case 0x16: // LD D, n 8 case 0x1E: // LD E, n 8 case 0x26: // LD H, n 8 case 0x2E: // LD L, n 8 (*numberedGbReg(opcode>>3)) = readPC(); break; case 0x3E: // LD A, n 8 g_gbRegs.af.b.h = readPC(); break; /* These are equivalent to NOPs. */ case 0x7F: // LD A, A 4 case 0x40: // LD B, B 4 case 0x49: // LD C, C 4 case 0x52: // LD D, D 4 case 0x5B: // LD E, E 4 case 0x64: // LD H, H 4 case 0x6D: // LD L, L 4 break; case 0x78: // LD A, B 4 g_gbRegs.af.b.h = g_gbRegs.bc.b.h; break; case 0x79: // LD A, C 4 g_gbRegs.af.b.h = g_gbRegs.bc.b.l; break; case 0x7A: // LD A, D 4 g_gbRegs.af.b.h = g_gbRegs.de.b.h; break; case 0x7B: // LD A, E 4 g_gbRegs.af.b.h = g_gbRegs.de.b.l; break; case 0x7C: // LD A, H 4 g_gbRegs.af.b.h = g_gbRegs.hl.b.h; break; case 0x7D: // LD A, L 4 g_gbRegs.af.b.h = g_gbRegs.hl.b.l; break; case 0x41: // LD B, C 4 case 0x42: // LD B, D 4 case 0x43: // LD B, E 4 case 0x44: // LD B, H 4 case 0x45: // LD B, L 4 case 0x48: // LD C, B 4 case 0x4A: // LD C, D 4 case 0x4B: // LD C, E 4 case 0x4C: // LD C, H 4 case 0x4D: // LD C, L 4 case 0x50: // LD D, B 4 case 0x51: // LD D, C 4 case 0x53: // LD D, E 4 case 0x54: // LD D, H 4 case 0x55: // LD D, L 4 case 0x58: // LD E, B 4 case 0x59: // LD E, C 4 case 0x5A: // LD E, D 4 case 0x5C: // LD E, H 4 case 0x5D: // LD E, L 4 case 0x60: // LD H, B 4 case 0x61: // LD H, C 4 case 0x62: // LD H, D 4 case 0x63: // LD H, E 4 case 0x65: // LD H, L 4 case 0x68: // LD L, B 4 case 0x69: // LD L, C 4 case 0x6A: // LD L, D 4 case 0x6B: // LD L, E 4 case 0x6C: // LD L, H 4 (*numberedGbReg((opcode>>3)&7)) = *numberedGbReg(opcode&7); break; case 0x47: // LD B, A 4 g_gbRegs.bc.b.h = g_gbRegs.af.b.h; break; case 0x4F: // LD C, A 4 g_gbRegs.bc.b.l = g_gbRegs.af.b.h; break; case 0x57: // LD D, A 4 g_gbRegs.de.b.h = g_gbRegs.af.b.h; break; case 0x5F: // LD E, A 4 g_gbRegs.de.b.l = g_gbRegs.af.b.h; break; case 0x67: // LD H, A 4 g_gbRegs.hl.b.h = g_gbRegs.af.b.h; break; case 0x6F: // LD L, A 4 g_gbRegs.hl.b.l = g_gbRegs.af.b.h; break; case 0x7E: // LD A, (hl) 8 g_gbRegs.af.b.h = readMemory(g_gbRegs.hl.w); break; case 0x46: // LD B, (hl) 8 case 0x4E: // LD C, (hl) 8 case 0x56: // LD D, (hl) 8 case 0x5E: // LD E, (hl) 8 case 0x66: // LD H, (hl) 8 case 0x6E: // LD L, (hl) 8 (*numberedGbReg((opcode>>3)&7)) = readMemory(g_gbRegs.hl.w); break; case 0x77: // LD (hl), A 8 writeMemory(g_gbRegs.hl.w, g_gbRegs.af.b.h); break; case 0x70: // LD (hl), B 8 case 0x71: // LD (hl), C 8 case 0x72: // LD (hl), D 8 case 0x73: // LD (hl), E 8 case 0x74: // LD (hl), H 8 case 0x75: // LD (hl), L 8 writeMemory(g_gbRegs.hl.w, *numberedGbReg(opcode&7)); break; case 0x36: // LD (hl), n 12 writeMemory(g_gbRegs.hl.w, readPC_noinc()); pcAddr++; break; case 0x0A: // LD A, (BC) 8 g_gbRegs.af.b.h = readMemory(g_gbRegs.bc.w); break; case 0x1A: // LD A, (de) 8 g_gbRegs.af.b.h = readMemory(g_gbRegs.de.w); break; case 0xFA: // LD A, (nn) 16 g_gbRegs.af.b.h = readMemory(readPC16_noinc()); pcAddr += 2; break; case 0x02: // LD (BC), A 8 writeMemory(g_gbRegs.bc.w, g_gbRegs.af.b.h); break; case 0x12: // LD (de), A 8 writeMemory(g_gbRegs.de.w, g_gbRegs.af.b.h); break; case 0xEA: // LD (nn), A 16 writeMemory(readPC16_noinc(), g_gbRegs.af.b.h); pcAddr += 2; break; case 0xF2: // LDH A, (C) 8 g_gbRegs.af.b.h = readIO(g_gbRegs.bc.b.l); break; case 0xE2: // LDH (C), A 8 writeIO(g_gbRegs.bc.b.l, g_gbRegs.af.b.h); break; case 0x3A: // LDD A, (hl) 8 g_gbRegs.af.b.h = readMemory(g_gbRegs.hl.w--); break; case 0x32: // LDD (hl), A 8 writeMemory(g_gbRegs.hl.w--, g_gbRegs.af.b.h); break; case 0x2A: // LDI A, (hl) 8 g_gbRegs.af.b.h = readMemory(g_gbRegs.hl.w++); break; case 0x22: // LDI (hl), A 8 writeMemory(g_gbRegs.hl.w++, g_gbRegs.af.b.h); break; case 0xE0: // LDH (n), A 12 writeIO(readPC_noinc(), g_gbRegs.af.b.h); pcAddr++; break; case 0xF0: // LDH A, (n) 12 g_gbRegs.af.b.h = readIO(readPC_noinc()); pcAddr++; break; // 16-bit loads case 0x01: // LD BC, nn 12 g_gbRegs.bc.w = readPC16(); break; case 0x11: // LD de, nn 12 g_gbRegs.de.w = readPC16(); break; case 0x21: // LD hl, nn 12 g_gbRegs.hl.w = readPC16(); break; case 0x31: // LD SP, nn 12 locSP = readPC16(); break; case 0xF9: // LD SP, hl 8 locSP = g_gbRegs.hl.w; break; case 0xF8: // LDHL SP, n 12 { locF = 0; int val = readPC(); if (((locSP&0xFF)+val) > 0xFF) setCFlag(); if ((locSP&0xF)+(val&0xF) > 0xF) setHFlag(); g_gbRegs.hl.w = locSP+(s8)val; break; } case 0x08: // LD (nn), SP 20 { int val = readPC16(); writeMemory(val, locSP & 0xFF); writeMemory(val+1, (locSP) >> 8); break; } case 0xF5: // PUSH AF #ifdef SPEEDHAX quickWrite(--locSP, g_gbRegs.af.b.h); quickWrite(--locSP, locF); #else writeMemory(--locSP, g_gbRegs.af.b.h); writeMemory(--locSP, locF); #endif break; // Some games use the stack in exotic ways. // Better to use writeMemory than writeMemory. case 0xC5: // PUSH BC 16 #ifdef SPEEDHAX quickWrite(--locSP, g_gbRegs.bc.b.h); quickWrite(--locSP, g_gbRegs.bc.b.l); #else writeMemory(--locSP, g_gbRegs.bc.b.h); writeMemory(--locSP, g_gbRegs.bc.b.l); #endif break; case 0xD5: // PUSH de 16 #ifdef SPEEDHAX quickWrite(--locSP, g_gbRegs.de.b.h); quickWrite(--locSP, g_gbRegs.de.b.l); #else writeMemory(--locSP, g_gbRegs.de.b.h); writeMemory(--locSP, g_gbRegs.de.b.l); #endif break; case 0xE5: // PUSH hl 16 #ifdef SPEEDHAX quickWrite(--locSP, g_gbRegs.hl.b.h); quickWrite(--locSP, g_gbRegs.hl.b.l); #else writeMemory(--locSP, g_gbRegs.hl.b.h); writeMemory(--locSP, g_gbRegs.hl.b.l); #endif break; case 0xF1: // POP AF 12 locF = quickRead(locSP++) & 0xF0; g_gbRegs.af.b.h = quickRead(locSP++); break; case 0xC1: // POP BC 12 g_gbRegs.bc.w = quickRead16(locSP); locSP += 2; break; case 0xD1: // POP de 12 g_gbRegs.de.w = quickRead16(locSP); locSP += 2; break; case 0xE1: // POP hl 12 g_gbRegs.hl.w = quickRead16(locSP); locSP += 2; break; // 8-bit arithmetic case 0x87: // ADD A, A 4 { locF = 0; u8 r = g_gbRegs.af.b.h; if (r + r > 0xFF) setCFlag(); if ((r & 0xF) + (r & 0xF) > 0xF) setHFlag(); g_gbRegs.af.b.h += r; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x80: // ADD A, B 4 case 0x81: // ADD A, C 4 case 0x82: // ADD A, D 4 case 0x83: // ADD A, E 4 case 0x84: // ADD A, H 4 case 0x85: // ADD A, L 4 { locF = 0; u8 r = *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h + r > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (r & 0xF) > 0xF) setHFlag(); g_gbRegs.af.b.h += r; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x86: // ADD A, (hl) 8 { locF = 0; int val = readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h + val > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (val & 0xF) > 0xF) setHFlag(); g_gbRegs.af.b.h += val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0xC6: // ADD A, n 8 { locF = 0; int val = readPC(); if (g_gbRegs.af.b.h + val > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (val & 0xF) > 0xF) setHFlag(); g_gbRegs.af.b.h += val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x8F: // ADC A, A 4 { int val = carryBit(); locF = 0; u8 r = g_gbRegs.af.b.h; if (r + r + val > 0xFF) setCFlag(); if ((r & 0xF) + (r & 0xF) + val > 0xF) setHFlag(); g_gbRegs.af.b.h += r + val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x88: // ADC A, B 4 case 0x89: // ADC A, C 4 case 0x8A: // ADC A, D 4 case 0x8B: // ADC A, E 4 case 0x8C: // ADC A, H 4 case 0x8D: // ADC A, L 4 { int val = carryBit(); locF = 0; u8 r = *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h + r + val > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (r & 0xF) + val > 0xF) setHFlag(); g_gbRegs.af.b.h += r + val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x8E: // ADC A, (hl) 8 { int val = readMemory(g_gbRegs.hl.w); int val2 = carryBit(); locF = 0; if (g_gbRegs.af.b.h + val + val2 > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (val & 0xF) + val2 > 0xF) setHFlag(); g_gbRegs.af.b.h += val + val2; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0xCE: // ADC A, n 8 { int val = readPC(); int val2 = carryBit(); locF = 0; if (g_gbRegs.af.b.h + val + val2 > 0xFF) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) + (val & 0xF) + val2 > 0xF) setHFlag(); g_gbRegs.af.b.h += val + val2; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x97: // SUB A, A 4 { g_gbRegs.af.b.h = 0; clearCFlag(); clearHFlag(); setZFlag(); setNFlag(); break; } case 0x90: // SUB A, B 4 case 0x91: // SUB A, C 4 case 0x92: // SUB A, D 4 case 0x93: // SUB A, E 4 case 0x94: // SUB A, H 4 case 0x95: // SUB A, L 4 { locF = FLAG_N; u8 r = *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h < r) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (r & 0xF)) setHFlag(); g_gbRegs.af.b.h -= r; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x96: // SUB A, (hl) 8 { locF = FLAG_N; int val = readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h < val) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)) setHFlag(); g_gbRegs.af.b.h -= val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0xD6: // SUB A, n 8 { locF = FLAG_N; int val = readPC(); if (g_gbRegs.af.b.h < val) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)) setHFlag(); g_gbRegs.af.b.h -= val; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x9F: // SBC A, A 4 { u8 r = g_gbRegs.af.b.h; int val2 = carryBit(); locF = FLAG_N; if (val2 /* != 0 */) { setCFlag(); setHFlag(); } g_gbRegs.af.b.h -= (r + val2); if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x98: // SBC A, B 4 case 0x99: // SBC A, C 4 case 0x9A: // SBC A, D 4 case 0x9B: // SBC A, E 4 case 0x9C: // SBC A, H 4 case 0x9D: // SBC A, L 4 { u8 r = *numberedGbReg(opcode&7); int val2 = carryBit(); locF = FLAG_N; if (g_gbRegs.af.b.h < r + val2) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (r & 0xF) + val2) setHFlag(); g_gbRegs.af.b.h -= (r + val2); if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0x9E: // SBC A, (hl) 8 { int val2 = carryBit(); int val = readMemory(g_gbRegs.hl.w); locF = FLAG_N; if (g_gbRegs.af.b.h < val + val2) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)+val2) setHFlag(); g_gbRegs.af.b.h -= val + val2; if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0xde: // SBC A, n 4 { int val = readPC(); int val2 = carryBit(); locF = FLAG_N; if (g_gbRegs.af.b.h <val + val2) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)+val2) setHFlag(); g_gbRegs.af.b.h -= (val + val2); if (g_gbRegs.af.b.h == 0) setZFlag(); break; } case 0xA7: // AND A, A 4 locF = FLAG_H; if (g_gbRegs.af.b.h == 0) locF |= FLAG_Z; break; case 0xA0: // AND A, B 4 case 0xA1: // AND A, C 4 case 0xA2: // AND A, D 4 case 0xA3: // AND A, E 4 case 0xA4: // AND A, H 4 case 0xA5: // AND A, L 4 locF = FLAG_H; g_gbRegs.af.b.h &= *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xA6: // AND A, (hl) 8 locF = FLAG_H; g_gbRegs.af.b.h &= readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xE6: // AND A, n 8 locF = FLAG_H; g_gbRegs.af.b.h &= readPC(); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xB7: // OR A, A 4 locF = 0; if (g_gbRegs.af.b.h == 0) locF |= FLAG_Z; break; case 0xB0: // OR A, B 4 case 0xB1: // OR A, C 4 case 0xB2: // OR A, D 4 case 0xB3: // OR A, E 4 case 0xB4: // OR A, H 4 case 0xB5: // OR A, L 4 locF = 0; g_gbRegs.af.b.h |= *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xB6: // OR A, (hl) 8 locF = 0; g_gbRegs.af.b.h |= readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xF6: // OR A, n 4 locF = 0; g_gbRegs.af.b.h |= readPC(); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xAF: // XOR A, A 4 g_gbRegs.af.b.h = 0; locF = FLAG_Z; break; case 0xA8: // XOR A, B 4 case 0xA9: // XOR A, C 4 case 0xAA: // XOR A, D 4 case 0xAB: // XOR A, E 4 case 0xAC: // XOR A, H 4 case 0xAD: // XOR A, L 4 locF = 0; g_gbRegs.af.b.h ^= *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xAE: // XOR A, (hl) 8 locF = 0; g_gbRegs.af.b.h ^= readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xEE: // XOR A, n 8 locF = 0; g_gbRegs.af.b.h ^= readPC(); if (g_gbRegs.af.b.h == 0) setZFlag(); break; case 0xBF: // CP A 4 { clearCFlag(); clearHFlag(); setZFlag(); setNFlag(); break; } case 0xB8: // CP B 4 case 0xB9: // CP C 4 case 0xBA: // CP D 4 case 0xBB: // CP E 4 case 0xBC: // CP H 4 case 0xBD: // CP L 4 { locF = FLAG_N; u8 r = *numberedGbReg(opcode&7); if (g_gbRegs.af.b.h < r) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (r & 0xF)) setHFlag(); if (g_gbRegs.af.b.h - r == 0) setZFlag(); break; } case 0xBE: // CP (hl) 8 { locF = FLAG_N; int val = readMemory(g_gbRegs.hl.w); if (g_gbRegs.af.b.h < val) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)) setHFlag(); if (g_gbRegs.af.b.h - val == 0) setZFlag(); break; } case 0xFE: // CP n 8 { locF = FLAG_N; int val = readPC(); if (g_gbRegs.af.b.h < val) setCFlag(); if ((g_gbRegs.af.b.h & 0xF) < (val & 0xF)) setHFlag(); if (g_gbRegs.af.b.h - val == 0) setZFlag(); break; } case 0x3C: // INC A 4 { locF &= FLAG_C; g_gbRegs.af.b.h++; if (g_gbRegs.af.b.h == 0) setZFlag(); if ((g_gbRegs.af.b.h & 0xF) == 0) setHFlag(); break; } case 0x04: // INC B 4 case 0x0C: // INC C 4 case 0x14: // INC D 4 case 0x1C: // INC E 4 case 0x24: // INC H 4 case 0x2C: // INC L 4 { locF &= FLAG_C; u8* reg = numberedGbReg(opcode>>3); (*reg)++; u8 r = *reg; if (r == 0) setZFlag(); if ((r & 0xF) == 0) setHFlag(); break; } case 0x34: // INC (hl) 12 { locF &= FLAG_C; u8 val = readMemory(g_gbRegs.hl.w)+1; writeMemory(g_gbRegs.hl.w, val); if (val == 0) setZFlag(); if ((val & 0xF) == 0) setHFlag(); break; } case 0x3D: // DEC A 4 { locF &= FLAG_C; g_gbRegs.af.b.h--; if (g_gbRegs.af.b.h == 0) setZFlag(); if ((g_gbRegs.af.b.h & 0xF) == 0xF) setHFlag(); setNFlag(); break; } case 0x05: // DEC B 4 case 0x0D: // DEC C 4 case 0x15: // DEC D 4 case 0x1D: // DEC E 4 case 0x25: // DEC H 4 case 0x2D: // DEC L 4 { locF &= FLAG_C; u8 *reg = numberedGbReg(opcode>>3); (*reg)--; u8 r = *reg; if (r == 0) setZFlag(); if ((r & 0xF) == 0xF) setHFlag(); setNFlag(); break; } case 0x35: // DEC (hl) 12 { locF &= FLAG_C; u8 val = readMemory(g_gbRegs.hl.w)-1; writeMemory(g_gbRegs.hl.w, val); if (val == 0) setZFlag(); if ((val & 0xF) == 0xF) setHFlag(); setNFlag(); break; } // 16-bit Arithmetic case 0x09: // ADD hl, BC 8 locF &= FLAG_Z; if (g_gbRegs.hl.w + g_gbRegs.bc.w > 0xFFFF) setCFlag(); if ((g_gbRegs.hl.w & 0xFFF) + (g_gbRegs.bc.w & 0xFFF) > 0xFFF) setHFlag(); g_gbRegs.hl.w += g_gbRegs.bc.w; break; case 0x19: // ADD hl, de 8 locF &= FLAG_Z; if (g_gbRegs.hl.w + g_gbRegs.de.w > 0xFFFF) setCFlag(); if ((g_gbRegs.hl.w & 0xFFF) + (g_gbRegs.de.w & 0xFFF) > 0xFFF) setHFlag(); g_gbRegs.hl.w += g_gbRegs.de.w; break; case 0x29: // ADD hl, hl 8 locF &= FLAG_Z; if (g_gbRegs.hl.w + g_gbRegs.hl.w > 0xFFFF) setCFlag(); if ((g_gbRegs.hl.w & 0xFFF) + (g_gbRegs.hl.w & 0xFFF) > 0xFFF) setHFlag(); g_gbRegs.hl.w += g_gbRegs.hl.w; break; case 0x39: // ADD hl, SP 8 locF &= FLAG_Z; if (g_gbRegs.hl.w + locSP > 0xFFFF) setCFlag(); if ((g_gbRegs.hl.w & 0xFFF) + (locSP & 0xFFF) > 0xFFF) setHFlag(); g_gbRegs.hl.w += locSP; break; case 0xE8: // ADD SP, n 16 { locF = 0; int val = readPC(); if (((locSP&0xFF)+val) > 0xFF) setCFlag(); if ((locSP&0xF)+(val&0xF) > 0xF) setHFlag(); locSP += (s8)val; break; } case 0x03: // INC BC 8 g_gbRegs.bc.w++; break; case 0x13: // INC de 8 g_gbRegs.de.w++; break; case 0x23: // INC hl 8 g_gbRegs.hl.w++; break; case 0x33: // INC SP 8 locSP++; break; case 0x0B: // DEC BC 8 g_gbRegs.bc.w--; break; case 0x1B: // DEC de 8 g_gbRegs.de.w--; break; case 0x2B: // DEC hl 8 g_gbRegs.hl.w--; break; case 0x3B: // DEC SP 8 locSP--; break; case 0x27: // DAA 4 { int a = g_gbRegs.af.b.h; if (!negativeSet()) { if (halfSet() || (a & 0xF) > 9) a += 0x06; if (carrySet() || a > 0x9F) a += 0x60; } else { if (halfSet()) a = (a - 6) & 0xFF; if (carrySet()) a -= 0x60; } locF &= ~(0x20 | 0x80); if ((a & 0x100) == 0x100) setCFlag(); a &= 0xFF; if (a == 0) setZFlag(); g_gbRegs.af.b.h = a; } break; case 0x2F: // CPL 4 g_gbRegs.af.b.h = ~g_gbRegs.af.b.h; setNFlag(); setHFlag(); break; case 0x3F: // CCF 4 if (carrySet()) clearCFlag(); else setCFlag(); clearNFlag(); clearHFlag(); break; case 0x37: // SCF 4 setCFlag(); clearNFlag(); clearHFlag(); break; case 0x00: // NOP 4 break; case 0x76: // HALT 4 if (!ime) { if (gbMode == CGB) break; else { // DI + Halt bug // Fixes smurfs if (haltBugAddr == NULL) { haltBugAddr = pcAddr-1; // Write over 'halt' to produce the effect. *haltBugAddr = *pcAddr; pcAddr--; cyclesToExecute = totalCycles+1; // 'halt' will be restored after the opcode is executed. } break; } } halt = 1; goto end; case 0x10: // STOP 4 if (ioRam[0x4D] & 1 && gbMode == CGB) { if (ioRam[0x4D] & 0x80) setDoubleSpeed(0); else setDoubleSpeed(1); ioRam[0x4D] &= ~1; } else { halt = 2; goto end; } pcAddr++; break; case 0xF3: // DI 4 disableInterrupts(); break; case 0xFB: // EI 4 enableInterrupts(); break; case 0x07: // RLCA 4 { locF = 0; int val = g_gbRegs.af.b.h; g_gbRegs.af.b.h <<= 1; if (val & 0x80) { setCFlag(); g_gbRegs.af.b.h |= 1; } break; } case 0x17: // RLA 4 { int val = (g_gbRegs.af.b.h & 0x80); g_gbRegs.af.b.h <<= 1; g_gbRegs.af.b.h |= carryBit(); locF = 0; if (val) setCFlag(); break; } case 0x0F: // RRCA 4 { locF = 0; int val = g_gbRegs.af.b.h; g_gbRegs.af.b.h >>= 1; if ((val & 1)) { setCFlag(); g_gbRegs.af.b.h |= 0x80; } break; } case 0x1F: // RRA 4 { int val = g_gbRegs.af.b.h & 1; g_gbRegs.af.b.h >>= 1; g_gbRegs.af.b.h |= (carryBit() << 7); locF = 0; if (val) setCFlag(); break; } case 0xC3: // JP 16 setPC(readPC16_noinc()); break; case 0xC2: // JP NZ, nn 16/12 if (!zeroSet()) { setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 4; break; } case 0xCA: // JP Z, nn 16/12 if (zeroSet()) { setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 4; break; } case 0xD2: // JP NC, nn 16/12 if (!carrySet()) { setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 4; break; } case 0xDA: // JP C, nn 12 if (carrySet()) { setPC(readPC16_noinc()); break; } else { totalCycles -= 4; pcAddr += 2; break; } case 0xE9: // JP (hl) 4 setPC(g_gbRegs.hl.w); break; case 0x18: // JR n 12 OP_JR(true); break; case 0x20: // JR NZ n 8/12 OP_JR(!zeroSet()); break; case 0x28: // JR Z, n 8/12 OP_JR(zeroSet()); break; case 0x30: // JR NC, n 8/12 OP_JR(!carrySet()); break; case 0x38: // JR C, n 8/12 OP_JR(carrySet()); break; case 0xCD: // CALL nn 24 { int val = getPC() + 2; #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(readPC16_noinc()); break; } case 0xC4: // CALL NZ, nn 12/24 if (!zeroSet()) { int val = getPC() + 2; #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 12; break; } case 0xCC: // CALL Z, nn 12/24 if (zeroSet()) { int val = getPC() + 2; #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 12; break; } case 0xD4: // CALL NC, nn 12/24 if (!carrySet()) { int val = getPC() + 2; #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 12; break; } case 0xDC: // CALL C, nn 12/24 if (carrySet()) { int val = getPC() + 2; #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(readPC16_noinc()); break; } else { pcAddr += 2; totalCycles -= 12; break; } case 0xC7: // RST 00H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x0); } break; case 0xCF: // RST 08H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x8); break; } case 0xD7: // RST 10H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x10); } break; case 0xDF: // RST 18H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x18); } break; case 0xE7: // RST 20H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x20); } break; case 0xEF: // RST 28H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x28); } break; case 0xF7: // RST 30H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x30); } break; case 0xFF: // RST 38H 16 { u16 val = getPC(); #ifdef SPEEDHAX quickWrite(--locSP, (val) >> 8); quickWrite(--locSP, (val & 0xFF)); #else writeMemory(--locSP, (val) >> 8); writeMemory(--locSP, (val & 0xFF)); #endif setPC(0x38); } break; case 0xC9: // RET 16 setPC(quickRead16(locSP)); locSP += 2; break; case 0xC0: // RET NZ 8/20 if (!zeroSet()) { setPC(quickRead16(locSP)); locSP += 2; break; } else { totalCycles -= 12; break; } case 0xC8: // RET Z 8/20 if (zeroSet()) { setPC(quickRead16(locSP)); locSP += 2; break; } else { totalCycles -= 16; break; } case 0xD0: // RET NC 8/20 if (!carrySet()) { setPC(quickRead16(locSP)); locSP += 2; break; } else { totalCycles -= 16; break; } case 0xD8: // RET C 8/20 if (carrySet()) { setPC(quickRead16(locSP)); locSP += 2; break; } else { totalCycles -= 16; break; } case 0xD9: // RETI 16 setPC(quickRead16(locSP)); locSP += 2; enableInterrupts(); break; case 0xCB: opcode = readPC(); totalCycles += CBopCycles[opcode]; switch(opcode) { case 0x37: // SWAP A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; int val = r >> 4; r <<= 4; r |= val; if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x30: // SWAP B 8 case 0x31: // SWAP C 8 case 0x32: // SWAP D 8 case 0x33: // SWAP E 8 case 0x34: // SWAP H 8 case 0x35: // SWAP L 8 { locF = 0; u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; int val = r >> 4; r <<= 4; r |= val; if (r == 0) setZFlag(); *reg = r; break; } case 0x36: // SWAP (hl) 16 { locF = 0; int val = readMemory(g_gbRegs.hl.w); int val2 = val >> 4; val <<= 4; val |= val2; writeMemory(g_gbRegs.hl.w, val); if (val == 0) setZFlag(); break; } case 0x07: // RLC A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; r <<= 1; if (((g_gbRegs.af.b.h) & 0x80) != 0) { setCFlag(); r |= 1; } if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x00: // RLC B 8 case 0x01: // RLC C 8 case 0x02: // RLC D 8 case 0x03: // RLC E 8 case 0x04: // RLC H 8 case 0x05: // RLC L 8 { locF = 0; u8 *reg = numberedGbReg(opcode); u8 r = *reg; r <<= 1; if (((*reg) & 0x80) != 0) { setCFlag(); r |= 1; } if (r == 0) setZFlag(); *reg = r; break; } case 0x06: // RLC (hl) 16 { locF = 0; int val = readMemory(g_gbRegs.hl.w); int val2 = val; val2 <<= 1; if ((val & 0x80) != 0) { setCFlag(); val2 |= 1; } if (val2 == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val2); break; } case 0x17: // RL A 8 { u8 r = g_gbRegs.af.b.h; int val = (r & 0x80); r <<= 1; r |= carryBit(); locF = 0; if (val) setCFlag(); if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x10: // RL B 8 case 0x11: // RL C 8 case 0x12: // RL D 8 case 0x13: // RL E 8 case 0x14: // RL H 8 case 0x15: // RL L 8 { u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; int val = (r & 0x80); r <<= 1; r |= carryBit(); locF = 0; if (val) setCFlag(); if (r == 0) setZFlag(); *reg = r; break; } case 0x16: // RL (hl) 16 { u8 val2 = readMemory(g_gbRegs.hl.w); int val = (val2 & 0x80); val2 <<= 1; val2 |= carryBit(); locF = 0; if (val) setCFlag(); if (val2 == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val2); break; } case 0x0F: // RRC A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; int val = r; r >>= 1; if (val&1) { setCFlag(); r |= 0x80; } if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x08: // RRC B 8 case 0x09: // RRC C 8 case 0x0A: // RRC D 8 case 0x0B: // RRC E 8 case 0x0C: // RRC H 8 case 0x0D: // RRC L 8 { locF = 0; u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; int val = r; r >>= 1; if (val&1) { setCFlag(); r |= 0x80; } if (r == 0) setZFlag(); *reg = r; break; } case 0x0E: // RRC (hl) 16 { locF = 0; u8 val2 = readMemory(g_gbRegs.hl.w); int val = val2; val2 >>= 1; if ((val & 1) != 0) { setCFlag(); val2 |= 0x80; } if (val2 == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val2); break; } case 0x1F: // RR A 8 { u8 r = g_gbRegs.af.b.h; int val = r & 1; r >>= 1; r |= carryBit() << 7; locF = 0; if (val) setCFlag(); if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x18: // RR B 8 case 0x19: // RR C 8 case 0x1A: // RR D 8 case 0x1B: // RR E 8 case 0x1C: // RR H 8 case 0x1D: // RR L 8 { u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; int val = r & 1; r >>= 1; r |= carryBit() << 7; locF = 0; if (val) setCFlag(); if (r == 0) setZFlag(); *reg = r; break; } case 0x1E: // RR (hl) 16 { u8 val2 = readMemory(g_gbRegs.hl.w); int val = val2 & 1; val2 >>= 1; val2 |= carryBit() << 7; locF = 0; if (val) setCFlag(); if (val2 == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val2); break; } case 0x27: // SLA A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; int val = (r & 0x80); r <<= 1; if (val) setCFlag(); if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x20: // SLA B 8 case 0x21: // SLA C 8 case 0x22: // SLA D 8 case 0x23: // SLA E 8 case 0x24: // SLA H 8 case 0x25: // SLA L 8 { locF = 0; u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; int val = (r & 0x80); r <<= 1; if (val) setCFlag(); if (r == 0) setZFlag(); *reg = r; break; } case 0x26: // SLA (hl) 16 { locF = 0; u8 val2 = readMemory(g_gbRegs.hl.w); int val = (val2 & 0x80); val2 <<= 1; if (val) setCFlag(); if (val2 == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val2); break; } case 0x2F: // SRA A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; if (r & 1) setCFlag(); r >>= 1; if (r & 0x40) r |= 0x80; if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x28: // SRA B 8 case 0x29: // SRA C 8 case 0x2A: // SRA D 8 case 0x2B: // SRA E 8 case 0x2C: // SRA H 8 case 0x2D: // SRA L 8 { locF = 0; u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; if (r & 1) setCFlag(); r >>= 1; if (r & 0x40) r |= 0x80; if (r == 0) setZFlag(); *reg = r; break; } case 0x2E: // SRA (hl) 16 { locF = 0; int val = readMemory(g_gbRegs.hl.w); if (val & 1) setCFlag(); val >>= 1; if (val & 0x40) val |= 0x80; if (val == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val); break; } case 0x3F: // SRL A 8 { locF = 0; u8 r = g_gbRegs.af.b.h; if (r & 1) setCFlag(); r >>= 1; if (r == 0) setZFlag(); g_gbRegs.af.b.h = r; break; } case 0x38: // SRL B 8 case 0x39: // SRL C 8 case 0x3A: // SRL D 8 case 0x3B: // SRL E 8 case 0x3C: // SRL H 8 case 0x3D: // SRL L 8 { locF = 0; u8 *reg = numberedGbReg(opcode&7); u8 r = *reg; if (r & 1) setCFlag(); r >>= 1; if (r == 0) setZFlag(); *reg = r; break; } case 0x3E: // SRL (hl) 16 { locF = 0; int val = readMemory(g_gbRegs.hl.w); if (val & 1) setCFlag(); val >>= 1; if (val == 0) setZFlag(); writeMemory(g_gbRegs.hl.w, val); break; } case 0x47: // BIT 0, A case 0x4F: // BIT 1, A case 0x57: // BIT 2, A case 0x5F: // BIT 3, A case 0x67: // BIT 4, A case 0x6F: // BIT 5, A case 0x77: // BIT 6, A case 0x7F: // BIT 7, A { if (((g_gbRegs.af.b.h) & (1<<((opcode>>3)&7))) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; } case 0x40: // BIT 0, B 8 case 0x41: // BIT 0, C 8 case 0x42: // BIT 0, D 8 case 0x43: // BIT 0, E 8 case 0x44: // BIT 0, H 8 case 0x45: // BIT 0, L 8 if (((*numberedGbReg(opcode&7)) & 1) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x48: // BIT 1, B case 0x49: // BIT 1, C case 0x4A: // BIT 1, D case 0x4B: // BIT 1, E case 0x4C: // BIT 1, H case 0x4D: // BIT 1, L if (((*numberedGbReg(opcode&7)) & 2) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x50: // BIT 2, B case 0x51: // BIT 2, C case 0x52: // BIT 2, D case 0x53: // BIT 2, E case 0x54: // BIT 2, H case 0x55: // BIT 2, L if (((*numberedGbReg(opcode&7)) & 4) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x58: // BIT 3, B case 0x59: // BIT 3, C case 0x5A: // BIT 3, D case 0x5B: // BIT 3, E case 0x5C: // BIT 3, H case 0x5D: // BIT 3, L if (((*numberedGbReg(opcode&7)) & 8) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x60: // BIT 4, B case 0x61: // BIT 4, C case 0x62: // BIT 4, D case 0x63: // BIT 4, E case 0x64: // BIT 4, H case 0x65: // BIT 4, L if (((*numberedGbReg(opcode&7)) & 0x10) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x68: // BIT 5, B case 0x69: // BIT 5, C case 0x6A: // BIT 5, D case 0x6B: // BIT 5, E case 0x6C: // BIT 5, H case 0x6D: // BIT 5, L if (((*numberedGbReg(opcode&7)) & 0x20) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x70: // BIT 6, B case 0x71: // BIT 6, C case 0x72: // BIT 6, D case 0x73: // BIT 6, E case 0x74: // BIT 6, H case 0x75: // BIT 6, L if (((*numberedGbReg(opcode&7)) & 0x40) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x78: // BIT 7, B case 0x79: // BIT 7, C case 0x7A: // BIT 7, D case 0x7B: // BIT 7, E case 0x7C: // BIT 7, H case 0x7D: // BIT 7, L if (((*numberedGbReg(opcode&7)) & 0x80) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x46: // BIT 0, (hl) 12 if ((readMemory(g_gbRegs.hl.w) & 0x1) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x4E: // BIT 1, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x2) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x56: // BIT 2, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x4) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x5E: // BIT 3, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x8) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x66: // BIT 4, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x10) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x6E: // BIT 5, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x20) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x76: // BIT 6, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x40) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0x7E: // BIT 7, (hl) if ((readMemory(g_gbRegs.hl.w) & 0x80) == 0) setZFlag(); else clearZFlag(); clearNFlag(); setHFlag(); break; case 0xC0: // SET 0, B g_gbRegs.bc.b.h |= 1; break; case 0xC1: // SET 0, C g_gbRegs.bc.b.l |= 1; break; case 0xC2: // SET 0, D g_gbRegs.de.b.h |= 1; break; case 0xC3: // SET 0, E g_gbRegs.de.b.l |= 1; break; case 0xC4: // SET 0, H g_gbRegs.hl.b.h |= 1; break; case 0xC5: // SET 0, L g_gbRegs.hl.b.l |= 1; break; case 0xC6: // SET 0, (hl) 16 { int val = readMemory(g_gbRegs.hl.w); val |= 1; writeMemory(g_gbRegs.hl.w, val); break; } case 0xC7: // SET 0, A g_gbRegs.af.b.h |= 1; break; case 0xC8: // SET 1, B g_gbRegs.bc.b.h |= 2; break; case 0xC9: // SET 1, C g_gbRegs.bc.b.l |= 2; break; case 0xCA: // SET 1, D g_gbRegs.de.b.h |= 2; break; case 0xCB: // SET 1, E g_gbRegs.de.b.l |= 2; break; case 0xCC: // SET 1, H g_gbRegs.hl.b.h |= 2; break; case 0xCD: // SET 1, L g_gbRegs.hl.b.l |= 2; break; case 0xCE: // SET 1, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 2; writeMemory(g_gbRegs.hl.w, val); break; } case 0xCF: // SET 1, A g_gbRegs.af.b.h |= 2; break; case 0xD0: // SET 2, B g_gbRegs.bc.b.h |= 4; break; case 0xD1: // SET 2, C g_gbRegs.bc.b.l |= 4; break; case 0xD2: // SET 2, D g_gbRegs.de.b.h |= 4; break; case 0xD3: // SET 2, E g_gbRegs.de.b.l |= 4; break; case 0xD4: // SET 2, H g_gbRegs.hl.b.h |= 4; break; case 0xD5: // SET 2, L g_gbRegs.hl.b.l |= 4; break; case 0xD6: // SET 2, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 4; writeMemory(g_gbRegs.hl.w, val); break; } case 0xD7: // SET 2, A g_gbRegs.af.b.h |= 4; break; case 0xD8: // SET 3, B g_gbRegs.bc.b.h |= 8; break; case 0xD9: // SET 3, C g_gbRegs.bc.b.l |= 8; break; case 0xDA: // SET 3, D g_gbRegs.de.b.h |= 8; break; case 0xDB: // SET 3, E g_gbRegs.de.b.l |= 8; break; case 0xDC: // SET 3, H g_gbRegs.hl.b.h |= 8; break; case 0xDD: // SET 3, L g_gbRegs.hl.b.l |= 8; break; case 0xDE: // SET 3, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 8; writeMemory(g_gbRegs.hl.w, val); break; } case 0xDF: // SET 3, A g_gbRegs.af.b.h |= 8; break; case 0xE0: // SET 4, B g_gbRegs.bc.b.h |= 0x10; break; case 0xE1: // SET 4, C g_gbRegs.bc.b.l |= 0x10; break; case 0xE2: // SET 4, D g_gbRegs.de.b.h |= 0x10; break; case 0xE3: // SET 4, E g_gbRegs.de.b.l |= 0x10; break; case 0xE4: // SET 4, H g_gbRegs.hl.b.h |= 0x10; break; case 0xE5: // SET 4, L g_gbRegs.hl.b.l |= 0x10; break; case 0xE6: // SET 4, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 0x10; writeMemory(g_gbRegs.hl.w, val); break; } case 0xE7: // SET 4, A g_gbRegs.af.b.h |= 0x10; break; case 0xE8: // SET 5, B g_gbRegs.bc.b.h |= 0x20; break; case 0xE9: // SET 5, C g_gbRegs.bc.b.l |= 0x20; break; case 0xEA: // SET 5, D g_gbRegs.de.b.h |= 0x20; break; case 0xEB: // SET 5, E g_gbRegs.de.b.l |= 0x20; break; case 0xEC: // SET 5, H g_gbRegs.hl.b.h |= 0x20; break; case 0xED: // SET 5, L g_gbRegs.hl.b.l |= 0x20; break; case 0xEE: // SET 5, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 0x20; writeMemory(g_gbRegs.hl.w, val); break; } case 0xEF: // SET 5, A g_gbRegs.af.b.h |= 0x20; break; case 0xF0: // SET 6, B g_gbRegs.bc.b.h |= 0x40; break; case 0xF1: // SET 6, C g_gbRegs.bc.b.l |= 0x40; break; case 0xF2: // SET 6, D g_gbRegs.de.b.h |= 0x40; break; case 0xF3: // SET 6, E g_gbRegs.de.b.l |= 0x40; break; case 0xF4: // SET 6, H g_gbRegs.hl.b.h |= 0x40; break; case 0xF5: // SET 6, L g_gbRegs.hl.b.l |= 0x40; break; case 0xF6: // SET 6, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 0x40; writeMemory(g_gbRegs.hl.w, val); break; } case 0xF7: // SET 6, A g_gbRegs.af.b.h |= 0x40; break; case 0xF8: // SET 7, B g_gbRegs.bc.b.h |= 0x80; break; case 0xF9: // SET 7, C g_gbRegs.bc.b.l |= 0x80; break; case 0xFA: // SET 7, D g_gbRegs.de.b.h |= 0x80; break; case 0xFB: // SET 7, E g_gbRegs.de.b.l |= 0x80; break; case 0xFC: // SET 7, H g_gbRegs.hl.b.h |= 0x80; break; case 0xFD: // SET 7, L g_gbRegs.hl.b.l |= 0x80; break; case 0xFE: // SET 7, (hl) { int val = readMemory(g_gbRegs.hl.w); val |= 0x80; writeMemory(g_gbRegs.hl.w, val); break; } case 0xFF: // SET 7, A g_gbRegs.af.b.h |= 0x80; break; case 0x80: // RES 0, B g_gbRegs.bc.b.h &= 0xFE; break; case 0x81: // RES 0, C g_gbRegs.bc.b.l &= 0xFE; break; case 0x82: // RES 0, D g_gbRegs.de.b.h &= 0xFE; break; case 0x83: // RES 0, E g_gbRegs.de.b.l &= 0xFE; break; case 0x84: // RES 0, H g_gbRegs.hl.b.h &= 0xFE; break; case 0x85: // RES 0, L g_gbRegs.hl.b.l &= 0xFE; break; case 0x86: // RES 0, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xFE; writeMemory(g_gbRegs.hl.w, val); break; } case 0x87: // RES 0, A g_gbRegs.af.b.h &= 0xFE; break; case 0x88: // RES 1, B g_gbRegs.bc.b.h &= 0xFD; break; case 0x89: // RES 1, C g_gbRegs.bc.b.l &= 0xFD; break; case 0x8A: // RES 1, D g_gbRegs.de.b.h &= 0xFD; break; case 0x8B: // RES 1, E g_gbRegs.de.b.l &= 0xFD; break; case 0x8C: // RES 1, H g_gbRegs.hl.b.h &= 0xFD; break; case 0x8D: // RES 1, L g_gbRegs.hl.b.l &= 0xFD; break; case 0x8E: // RES 1, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xFD; writeMemory(g_gbRegs.hl.w, val); break; } case 0x8F: // RES 1, A g_gbRegs.af.b.h &= 0xFD; break; case 0x90: // RES 2, B g_gbRegs.bc.b.h &= 0xFB; break; case 0x91: // RES 2, C g_gbRegs.bc.b.l &= 0xFB; break; case 0x92: // RES 2, D g_gbRegs.de.b.h &= 0xFB; break; case 0x93: // RES 2, E g_gbRegs.de.b.l &= 0xFB; break; case 0x94: // RES 2, H g_gbRegs.hl.b.h &= 0xFB; break; case 0x95: // RES 2, L g_gbRegs.hl.b.l &= 0xFB; break; case 0x96: // RES 2, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xFB; writeMemory(g_gbRegs.hl.w, val); break; } case 0x97: // RES 2, A g_gbRegs.af.b.h &= 0xFB; break; case 0x98: // RES 3, B g_gbRegs.bc.b.h &= 0xF7; break; case 0x99: // RES 3, C g_gbRegs.bc.b.l &= 0xF7; break; case 0x9A: // RES 3, D g_gbRegs.de.b.h &= 0xF7; break; case 0x9B: // RES 3, E g_gbRegs.de.b.l &= 0xF7; break; case 0x9C: // RES 3, H g_gbRegs.hl.b.h &= 0xF7; break; case 0x9D: // RES 3, L g_gbRegs.hl.b.l &= 0xF7; break; case 0x9E: // RES 3, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xF7; writeMemory(g_gbRegs.hl.w, val); break; } case 0x9F: // RES 3, A g_gbRegs.af.b.h &= 0xF7; break; case 0xA0: // RES 4, B g_gbRegs.bc.b.h &= 0xEF; break; case 0xA1: // RES 4, C g_gbRegs.bc.b.l &= 0xEF; break; case 0xA2: // RES 4, D g_gbRegs.de.b.h &= 0xEF; break; case 0xA3: // RES 4, E g_gbRegs.de.b.l &= 0xEF; break; case 0xA4: // RES 4, H g_gbRegs.hl.b.h &= 0xEF; break; case 0xA5: // RES 4, L g_gbRegs.hl.b.l &= 0xEF; break; case 0xA6: // RES 4, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xEF; writeMemory(g_gbRegs.hl.w, val); break; } case 0xA7: // RES 4, A g_gbRegs.af.b.h &= 0xEF; break; case 0xA8: // RES 5, B g_gbRegs.bc.b.h &= 0xDF; break; case 0xA9: // RES 5, C g_gbRegs.bc.b.l &= 0xDF; break; case 0xAA: // RES 5, D g_gbRegs.de.b.h &= 0xDF; break; case 0xAB: // RES 5, E g_gbRegs.de.b.l &= 0xDF; break; case 0xAC: // RES 5, H g_gbRegs.hl.b.h &= 0xDF; break; case 0xAD: // RES 5, L g_gbRegs.hl.b.l &= 0xDF; break; case 0xAE: // RES 5, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xDF; writeMemory(g_gbRegs.hl.w, val); break; } case 0xAF: // RES 5, A g_gbRegs.af.b.h &= 0xDF; break; case 0xB0: // RES 6, B g_gbRegs.bc.b.h &= 0xBF; break; case 0xB1: // RES 6, C g_gbRegs.bc.b.l &= 0xBF; break; case 0xB2: // RES 6, D g_gbRegs.de.b.h &= 0xBF; break; case 0xB3: // RES 6, E g_gbRegs.de.b.l &= 0xBF; break; case 0xB4: // RES 6, H g_gbRegs.hl.b.h &= 0xBF; break; case 0xB5: // RES 6, L g_gbRegs.hl.b.l &= 0xBF; break; case 0xB6: // RES 6, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0xBF; writeMemory(g_gbRegs.hl.w, val); break; } case 0xB7: // RES 6, A g_gbRegs.af.b.h &= 0xBF; break; case 0xB8: // RES 7, B g_gbRegs.bc.b.h &= 0x7F; break; case 0xB9: // RES 7, C g_gbRegs.bc.b.l &= 0x7F; break; case 0xBA: // RES 7, D g_gbRegs.de.b.h &= 0x7F; break; case 0xBB: // RES 7, E g_gbRegs.de.b.l &= 0x7F; break; case 0xBC: // RES 7, H g_gbRegs.hl.b.h &= 0x7F; break; case 0xBD: // RES 7, L g_gbRegs.hl.b.l &= 0x7F; break; case 0xBE: // RES 7, (hl) { int val = readMemory(g_gbRegs.hl.w); val &= 0x7F; writeMemory(g_gbRegs.hl.w, val); break; } case 0xBF: // RES 7, A g_gbRegs.af.b.h &= 0x7F; break; default: break; } break; default: break; } } end: if (haltBugAddr != NULL) { *haltBugAddr = 0x76; haltBugAddr = NULL; } g_gbRegs.af.b.l = locF; g_gbRegs.pc.w += (pcAddr-firstPcAddr); g_gbRegs.sp.w = locSP; return totalCycles; }
36.351169
127
0.296203
[ "vector" ]
9cf7c25a9792c590cec686dfeea0d14467fdb626
36,875
cpp
C++
SimTKcommon/Mechanics/src/Rotation.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
SimTKcommon/Mechanics/src/Rotation.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
SimTKcommon/Mechanics/src/Rotation.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2005-14 Stanford University and the Authors. * * Authors: Paul Mitiguy, Michael Sherman * * Contributors: * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /**@file * Implementations of non-inline methods associated with Rotation class. */ #include "SimTKcommon/basics.h" #include "SimTKcommon/internal/Rotation.h" #include <cmath> #include <utility> //------------------------------------------------------------------------------ namespace SimTK { //------------------------------------------------------------------------------ // Set Rotation for ANY two-angle ij rotation sequence (i,j = X,Y,Z) //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromTwoAnglesTwoAxes ( BodyOrSpaceType bodyOrSpace, RealP angle1, const CoordinateAxis& axis1In, RealP angle2, const CoordinateAxis& axis2In ) { // Non-const CoordinateAxes in case we have to switch axes CoordinateAxis axis1 = axis1In; CoordinateAxis axis2 = axis2In; // If axis2 is same as axis1, efficiently calculate with a one-angle, // one-axis rotation. if( axis1.isSameAxis(axis2) ) { return setRotationFromAngleAboutAxis( angle1+angle2, axis1 ); } // If using a SpaceRotationSequence, switch order of axes and angles. if( bodyOrSpace == SpaceRotationSequence ) { std::swap(angle1,angle2); std::swap(axis1,axis2); } // If using a reverse cyclical, negate the signs of the angles if( axis1.isReverseCyclical(axis2) ) { angle1 = -angle1; angle2 = -angle2; } // Calculate the sines and cosines (some hardware can do this more // efficiently as one Taylor series). const RealP c1 = std::cos( angle1 ), s1 = std::sin( angle1 ); const RealP c2 = std::cos( angle2 ), s2 = std::sin( angle2 ); // All calculations are based on a body-fixed forward-cyclical rotation // sequence. return setTwoAngleTwoAxesBodyFixedForwardCyclicalRotation( c1,s1,axis1, c2,s2,axis2 ); } //------------------------------------------------------------------------------ // Set Rotation for ANY three-angle ijk rotation sequence where (i,j,k = X,Y,Z) //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromThreeAnglesThreeAxes ( BodyOrSpaceType bodyOrSpace, RealP angle1, const CoordinateAxis& axis1In, RealP angle2, const CoordinateAxis& axis2, RealP angle3, const CoordinateAxis& axis3In ) { // Non-const CoordinateAxes in case we have to switch axes. CoordinateAxis axis1 = axis1In; CoordinateAxis axis3 = axis3In; // If axis2 is same as axis1 or axis3, efficiently calculate with a // two-angle, two-axis rotation. if( axis2.isSameAxis(axis1) ) return setRotationFromTwoAnglesTwoAxes(bodyOrSpace, angle1+angle2, axis1, angle3,axis3); if( axis2.isSameAxis(axis3) ) return setRotationFromTwoAnglesTwoAxes(bodyOrSpace, angle1,axis1, angle2+angle3, axis3); // If using a SpaceRotationSequence, switch order of the axes and angles. if( bodyOrSpace == SpaceRotationSequence ) { std::swap(angle1,angle3); std::swap(axis1,axis3); } // If using a reverse cyclical, negate the signs of the angles. if( axis1.isReverseCyclical(axis2) ) { angle1 = -angle1; angle2 = -angle2; angle3 = -angle3; } // Calculate the sines and cosines (some hardware can do this more // efficiently as one Taylor series). const RealP c1 = std::cos( angle1 ), s1 = std::sin( angle1 ); const RealP c2 = std::cos( angle2 ), s2 = std::sin( angle2 ); const RealP c3 = std::cos( angle3 ), s3 = std::sin( angle3 ); // All calculations are based on a body-fixed rotation sequence. // Determine whether this is a BodyXYX or BodyXYZ type of rotation sequence. if( axis1.isSameAxis(axis3) ) setThreeAngleTwoAxesBodyFixedForwardCyclicalRotation (c1,s1,axis1, c2,s2,axis2, c3,s3); else setThreeAngleThreeAxesBodyFixedForwardCyclicalRotation (c1,s1,axis1, c2,s2,axis2, c3,s3,axis3); return *this; } //------------------------------------------------------------------------------ // Calculate angle for ANY X or Y or Z rotation sequence //------------------------------------------------------------------------------ template <class P> P Rotation_<P>::convertOneAxisRotationToOneAngle(const CoordinateAxis& axis1) const { // Get proper indices into Rotation matrix const CoordinateAxis axis2 = axis1.getNextAxis(); const CoordinateAxis axis3 = axis2.getNextAxis(); const int j = int( axis2 ); const int k = int( axis3 ); const Mat33P& R = asMat33(); const RealP sinTheta = ( R[k][j] - R[j][k] ) / 2; const RealP cosTheta = ( R[j][j] + R[k][k] ) / 2; return std::atan2( sinTheta, cosTheta ); } //------------------------------------------------------------------------------ // Calculate angles for ANY two-angle ij rotation sequence (i,j = X,Y,Z) //------------------------------------------------------------------------------ template <class P> Vec<2,P> Rotation_<P>::convertTwoAxesRotationToTwoAngles ( BodyOrSpaceType bodyOrSpace, const CoordinateAxis& axis1In, const CoordinateAxis& axis2In ) const { // Non-const CoordinateAxes in case we have to switch axes CoordinateAxis axis1 = axis1In; CoordinateAxis axis2 = axis2In; // If axis2 is same as axis1, efficiently calculate with a one-axis, // one-angle method. if( axis1.isSameAxis(axis2) ) { const RealP theta = convertOneAxisRotationToOneAngle(axis1) / 2; return Vec<2,P>(theta,theta); } // If using a SpaceRotationSequence, switch the order of the axes (later // switch the angles). if( bodyOrSpace == SpaceRotationSequence ) std::swap(axis1,axis2); // All calculations are based on a body-fixed rotation sequence Vec<2,P> ans = convertTwoAxesBodyFixedRotationToTwoAngles( axis1, axis2 ); // If using a SpaceRotationSequence, switch the angles now. if( bodyOrSpace == SpaceRotationSequence ) std::swap( ans[0], ans[1] ); return ans; } //------------------------------------------------------------------------------ // Calculate angles for ANY 3-angle ijk rotation sequence where (i,j,k = X,Y,Z) //------------------------------------------------------------------------------ template <class P> Vec<3,P> Rotation_<P>::convertThreeAxesRotationToThreeAngles ( BodyOrSpaceType bodyOrSpace, const CoordinateAxis& axis1In, const CoordinateAxis& axis2, const CoordinateAxis& axis3In ) const { // Non-const CoordinateAxes in case we have to switch axes. CoordinateAxis axis1 = axis1In; CoordinateAxis axis3 = axis3In; // If all axes are same, efficiently calculate with a one-axis, one-angle // method. if( axis1.areAllSameAxes(axis2,axis3) ) { RealP theta = convertOneAxisRotationToOneAngle(axis1) / 3; return Vec3P(theta,theta,theta); } // If axis2 is same as axis1, efficiently calculate with a two-angle, // two-axis rotation. if( axis2.isSameAxis(axis1) ) { const Vec2P xz = convertTwoAxesRotationToTwoAngles (bodyOrSpace,axis1,axis3); const RealP theta = xz[0] / 2; return Vec3P( theta, theta, xz[1] ); } // If axis2 is same as axis3, efficiently calculate with a two-angle, // two-axis rotation. if( axis2.isSameAxis(axis3) ) { const Vec2P xz = convertTwoAxesRotationToTwoAngles (bodyOrSpace,axis1,axis3); const RealP theta = xz[1] / 2; return Vec3P( xz[0], theta, theta); } // If using a SpaceRotationSequence, switch the order of the axes (later // switch the angles). if( bodyOrSpace == SpaceRotationSequence ) std::swap(axis1,axis3); // All calculations are based on a body-fixed rotation sequence. // Determine whether this is a BodyXYX or BodyXYZ type of rotation sequence. Vec3P ans = axis1.isSameAxis(axis3) ? convertTwoAxesBodyFixedRotationToThreeAngles(axis1, axis2) : convertThreeAxesBodyFixedRotationToThreeAngles(axis1, axis2, axis3); // If using a SpaceRotationSequence, switch the angles now. if( bodyOrSpace == SpaceRotationSequence ) std::swap(ans[0], ans[2]); return ans; } //------------------------------------------------------------------------------ // Set Rotation ONLY for two-angle, two-axes, body-fixed, ij rotation sequence // where i != j. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setTwoAngleTwoAxesBodyFixedForwardCyclicalRotation ( RealP cosAngle1, RealP sinAngle1, const CoordinateAxis& axis1, RealP cosAngle2, RealP sinAngle2, const CoordinateAxis& axis2 ) { // Ensure this method has proper arguments assert( axis1.isDifferentAxis( axis2 ) ); CoordinateAxis axis3 = axis1.getThirdAxis( axis2 ); const int i = int( axis1 ); const int j = int( axis2 ); const int k = int( axis3 ); Mat33P& R = *this; R[i][i] = cosAngle2; R[i][j] = 0; R[i][k] = sinAngle2; R[j][i] = sinAngle2 * sinAngle1; R[j][j] = cosAngle1; R[j][k] = -sinAngle1 * cosAngle2; R[k][i] = -sinAngle2 * cosAngle1; R[k][j] = sinAngle1; R[k][k] = cosAngle1 * cosAngle2; return *this; } //------------------------------------------------------------------------------ // Set Rotation ONLY for three-angle, two-axes, body-fixed, iji rotation // sequence where i != j. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setThreeAngleTwoAxesBodyFixedForwardCyclicalRotation ( RealP cosAngle1, RealP sinAngle1, const CoordinateAxis& axis1, RealP cosAngle2, RealP sinAngle2, const CoordinateAxis& axis2, RealP cosAngle3, RealP sinAngle3 ) { // Ensure this method has proper arguments assert( axis1.isDifferentAxis( axis2 ) ); // Repeated calculations (for efficiency) RealP s1c3 = sinAngle1 * cosAngle3; RealP s3c1 = sinAngle3 * cosAngle1; RealP s1s3 = sinAngle1 * sinAngle3; RealP c1c3 = cosAngle1 * cosAngle3; CoordinateAxis axis3 = axis1.getThirdAxis( axis2 ); const int i = int( axis1 ); const int j = int( axis2 ); const int k = int( axis3 ); Mat33P& R = *this; R[i][i] = cosAngle2; R[i][j] = sinAngle2 * sinAngle3; R[i][k] = sinAngle2 * cosAngle3; R[j][i] = sinAngle1 * sinAngle2; R[j][j] = c1c3 - cosAngle2 * s1s3; R[j][k] = -s3c1 - cosAngle2 * s1c3; R[k][i] = -sinAngle2 * cosAngle1; R[k][j] = s1c3 + cosAngle2 * s3c1; R[k][k] = -s1s3 + cosAngle2 * c1c3; return *this; } //------------------------------------------------------------------------------ // Set Rotation ONLY for three-angle, three-axes, body-fixed, ijk rotation // sequence where i != j != k. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setThreeAngleThreeAxesBodyFixedForwardCyclicalRotation ( RealP cosAngle1, RealP sinAngle1, const CoordinateAxis& axis1, RealP cosAngle2, RealP sinAngle2, const CoordinateAxis& axis2, RealP cosAngle3, RealP sinAngle3, const CoordinateAxis& axis3 ) { // Ensure this method has proper arguments assert( axis1.areAllDifferentAxes(axis2,axis3) ); // Repeated calculations (for efficiency) RealP s1c3 = sinAngle1 * cosAngle3; RealP s3c1 = sinAngle3 * cosAngle1; RealP s1s3 = sinAngle1 * sinAngle3; RealP c1c3 = cosAngle1 * cosAngle3; const int i = int(axis1); const int j = int(axis2); const int k = int(axis3); Mat33P& R = *this; R[i][i] = cosAngle2 * cosAngle3; R[i][j] = -sinAngle3 * cosAngle2; R[i][k] = sinAngle2; R[j][i] = s3c1 + sinAngle2 * s1c3; R[j][j] = c1c3 - sinAngle2 * s1s3; R[j][k] = -sinAngle1 * cosAngle2; R[k][i] = s1s3 - sinAngle2 * c1c3; R[k][j] = s1c3 + sinAngle2 * s3c1; R[k][k] = cosAngle1 * cosAngle2; return *this; } //------------------------------------------------------------------------------ // Calculate angles ONLY for a two-angle, two-axes, body-fixed, ij rotation // sequence where i != j. //------------------------------------------------------------------------------ template <class P> Vec<2,P> Rotation_<P>::convertTwoAxesBodyFixedRotationToTwoAngles ( const CoordinateAxis& axis1, const CoordinateAxis& axis2 ) const { // Ensure this method has proper arguments assert( axis1.isDifferentAxis( axis2 ) ); CoordinateAxis axis3 = axis1.getThirdAxis(axis2); const int i = int(axis1); const int j = int(axis2); const int k = int(axis3); const Mat33P& R = asMat33(); // Can use either direct method (fast) or all matrix elements with the // overhead of two additional square roots (possibly more accurate). const RealP sinTheta1Direct = R[k][j]; const RealP signSinTheta1 = sinTheta1Direct > 0 ? RealP(1) : RealP(-1); const RealP sinTheta1Alternate = signSinTheta1 * std::sqrt( square(R[j][i]) + square(R[j][k]) ); const RealP sinTheta1 = ( sinTheta1Direct + sinTheta1Alternate ) / 2; const RealP cosTheta1Direct = R[j][j]; const RealP signCosTheta1 = cosTheta1Direct > 0 ? RealP(1) : RealP(-1); const RealP cosTheta1Alternate = signCosTheta1 * std::sqrt( square(R[k][i]) + square(R[k][k]) ); const RealP cosTheta1 = ( cosTheta1Direct + cosTheta1Alternate ) / 2; RealP theta1 = std::atan2( sinTheta1, cosTheta1 ); // Repeat for theta2 const RealP sinTheta2Direct = R[i][k]; const RealP signSinTheta2 = sinTheta2Direct > 0 ? RealP(1) : RealP(-1); const RealP sinTheta2Alternate = signSinTheta2 * std::sqrt( square(R[j][i]) + square(R[k][i]) ); const RealP sinTheta2 = ( sinTheta2Direct + sinTheta2Alternate ) / 2; const RealP cosTheta2Direct = R[i][i]; const RealP signCosTheta2 = cosTheta2Direct > 0 ? RealP(1) : RealP(-1); const RealP cosTheta2Alternate = signCosTheta2 * std::sqrt( square(R[j][k]) + square(R[k][k]) ); const RealP cosTheta2 = ( cosTheta2Direct + cosTheta2Alternate ) / 2; RealP theta2 = std::atan2( sinTheta2, cosTheta2 ); // If using a reverse cyclical, negate the signs of the angles if( axis1.isReverseCyclical(axis2) ) { theta1 = -theta1; theta2 = -theta2; } // Return values have the following ranges: // -pi <= theta1 <= +pi // -pi <= theta2 <= +pi return Vec2P( theta1, theta2 ); } //------------------------------------------------------------------------------ // Calculate angles ONLY for a three-angle, two-axes, body-fixed, iji rotation // sequence where i != j. //------------------------------------------------------------------------------ template <class P> Vec<3,P> Rotation_<P>::convertTwoAxesBodyFixedRotationToThreeAngles ( const CoordinateAxis& axis1, const CoordinateAxis& axis2 ) const { // Ensure this method has proper arguments. assert( axis1.isDifferentAxis( axis2 ) ); CoordinateAxis axis3 = axis1.getThirdAxis( axis2 ); const int i = int( axis1 ); const int j = int( axis2 ); const int k = int( axis3 ); // Need to know if using a forward or reverse cyclical. RealP plusMinus = 1.0, minusPlus = -1.0; if( axis1.isReverseCyclical(axis2) ) { plusMinus = -1.0, minusPlus = 1.0; } // Shortcut to the elements of the rotation matrix. const Mat33P& R = asMat33(); // Calculate theta2 using lots of information in the rotation matrix. const RealP Rsum = std::sqrt( ( square(R[i][j]) + square(R[i][k]) + square(R[j][i]) + square(R[k][i])) / 2 ); // Rsum = abs(sin(theta2)) is inherently positive. const RealP theta2 = std::atan2( Rsum, R[i][i] ); RealP theta1, theta3; // There is a "singularity" when sin(theta2) == 0 if( Rsum > 4*Eps ) { theta1 = std::atan2( R[j][i], minusPlus*R[k][i] ); theta3 = std::atan2( R[i][j], plusMinus*R[i][k] ); } else if( R[i][i] > 0 ) { const RealP spos = plusMinus*R[k][j] + minusPlus*R[j][k]; // 2*sin(theta1 + theta3) const RealP cpos = R[j][j] + R[k][k]; // 2*cos(theta1 + theta3) const RealP theta1PlusTheta3 = std::atan2( spos, cpos ); theta1 = theta1PlusTheta3; // Arbitrary split theta3 = 0; // Arbitrary split } else { const RealP sneg = plusMinus*R[k][j] + plusMinus*R[j][k]; // 2*sin(theta1 - theta3) const RealP cneg = R[j][j] - R[k][k]; // 2*cos(theta1 - theta3) const RealP theta1MinusTheta3 = std::atan2( sneg, cneg ); theta1 = theta1MinusTheta3; // Arbitrary split theta3 = 0; // Arbitrary split } // Return values have the following ranges: // -pi <= theta1 <= +pi // 0 <= theta2 <= +pi (Rsum is inherently positive) // -pi <= theta3 <= +pi return Vec3P( theta1, theta2, theta3 ); } //------------------------------------------------------------------------------ // Calculate angles ONLY for a three-angle, three-axes, body-fixed, ijk rotation // sequence where i != j and j != k. //------------------------------------------------------------------------------ template <class P> Vec<3,P> Rotation_<P>::convertThreeAxesBodyFixedRotationToThreeAngles ( const CoordinateAxis& axis1, const CoordinateAxis& axis2, const CoordinateAxis& axis3 ) const { // Ensure this method has proper arguments. assert( axis1.areAllDifferentAxes(axis2,axis3) ); const int i = int(axis1); const int j = int(axis2); const int k = int(axis3); // Need to know if using a forward or reverse cyclical. RealP plusMinus = 1.0, minusPlus = -1.0; if( axis1.isReverseCyclical(axis2) ) { plusMinus = -1.0, minusPlus = 1.0; } // Shortcut to the elements of the rotation matrix. const Mat33P& R = asMat33(); // Calculate theta2 using lots of information in the rotation matrix. RealP Rsum = std::sqrt(( square(R[i][i]) + square(R[i][j]) + square(R[j][k]) + square(R[k][k])) / 2); // Rsum = abs(cos(theta2)) is inherently positive. RealP theta2 = std::atan2( plusMinus*R[i][k], Rsum ); RealP theta1, theta3; // There is a "singularity" when cos(theta2) == 0 if( Rsum > 4*Eps ) { theta1 = std::atan2( minusPlus*R[j][k], R[k][k] ); theta3 = std::atan2( minusPlus*R[i][j], R[i][i] ); } else if( plusMinus*R[i][k] > 0 ) { const RealP spos = R[j][i] + plusMinus*R[k][j]; // 2*sin(theta1 + plusMinus*theta3) const RealP cpos = R[j][j] + minusPlus*R[k][i]; // 2*cos(theta1 + plusMinus*theta3) const RealP theta1PlusMinusTheta3 = std::atan2( spos, cpos ); theta1 = theta1PlusMinusTheta3; // Arbitrary split theta3 = 0; // Arbitrary split } else { const RealP sneg = plusMinus*(R[k][j] + minusPlus*R[j][i]); // 2*sin(theta1 + minusPlus*theta3) const RealP cneg = R[j][j] + plusMinus*R[k][i]; // 2*cos(theta1 + minusPlus*theta3) const RealP theta1MinusPlusTheta3 = std::atan2( sneg, cneg ); theta1 = theta1MinusPlusTheta3; // Arbitrary split theta3 = 0; // Arbitrary split } // Return values have the following ranges: // -pi <= theta1 <= +pi // -pi/2 <= theta2 <= +pi/2 (Rsum is inherently positive) // -pi <= theta3 <= +pi return Vec3P( theta1, theta2, theta3 ); } //------------------------------------------------------------------------------ // Calculate R_AB by knowing one of B's unit vector expressed in A. // Note: The other vectors are perpendicular (but somewhat arbitrarily so). //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromOneAxis(const UnitVec3P& uveci, CoordinateAxis axisi) { // Find a unit vector that is perpendicular to uveci. const UnitVec3P uvecj = uveci.perp(); // Find another unit vector that is perpendicular to both uveci and uvecj. const UnitVec3P uveck = UnitVec3P( cross( uveci, uvecj ) ); // Determine which of the axes this corresponds to. CoordinateAxis axisj = axisi.getNextAxis(); CoordinateAxis axisk = axisj.getNextAxis(); // Fill in the correct elements of the Rotation matrix. setRotationColFromUnitVecTrustMe( int(axisi), uveci ); setRotationColFromUnitVecTrustMe( int(axisj), uvecj ); setRotationColFromUnitVecTrustMe( int(axisk), uveck ); return *this; } //------------------------------------------------------------------------------ // Calculate A.RotationMatrix.B by knowing one of B's unit vectors expressed in // A and another vector that may be perpendicular. If the 2nd vector is not // perpendicular, no worries - we'll make it so it is perpendicular. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromTwoAxes ( const UnitVec3P& uveci, const CoordinateAxis& axisi, const Vec3P& vecjApprox, const CoordinateAxis& axisjApprox ) { // Ensure vecjApprox is not a zero vector and the axes are not the same. RealP magnitudeOfVecjApprox = vecjApprox.normSqr(); if( magnitudeOfVecjApprox==0 || axisi.isSameAxis(axisjApprox) ) return setRotationFromOneAxis( uveci, axisi ); // Create a unit vector that is perpendicular to both uveci and vecjApprox. Vec3P veck = cross( uveci, vecjApprox ); // Make sure (a x b) is not too close to the zero vector (vectors are nearly // parallel). Since |a x b| = |a|*|b|*sin(theta), it is easy to determine // when sin(theta) = |a x b| / (|a| * |b|) is small. In other words, // sin(theta) = |a x b| / (|a| * |b|) where |a| = 1 (since uveci is a unit // vector). I use SqrtEps (which is approx 1e-8 in double) which means // that the angle between the vectors is less than 1e-8 rads = 6e-7 deg. RealP magnitudeOfVeck = veck.normSqr(); // Magnitude of the cross product. if( magnitudeOfVeck < SimTK::SqrtEps * magnitudeOfVecjApprox ) return setRotationFromOneAxis( uveci, axisi ); // Find a unit vector that is perpendicular to both uveci and vecjApprox. UnitVec3P uveck = UnitVec3P( veck ); // Compute the unit vector perpendicular to both uveci and uveck. UnitVec3P uvecj = UnitVec3P( cross( uveck, uveci ) ); // Determine which of the axes this corresponds to CoordinateAxis axisj = axisi.getNextAxis(); CoordinateAxis axisk = axisj.getNextAxis(); // If axisj is axisjApprox, all is good, otherwise switch axisj and axisk // and negate the k'th axis. if( axisj.isDifferentAxis(axisjApprox) ) { std::swap( axisj, axisk ); uveck = -uveck; } // Fill in the correct elements of the Rotation matrix setRotationColFromUnitVecTrustMe( int(axisi), uveci ); setRotationColFromUnitVecTrustMe( int(axisj), uvecj ); setRotationColFromUnitVecTrustMe( int(axisk), uveck ); return *this; } //------------------------------------------------------------------------------ // Set this rotation matrix from the associated quaternion. (29 flops) //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromQuaternion( const Quaternion_<P>& q ) { const RealP q00=q[0]*q[0], q11=q[1]*q[1], q22=q[2]*q[2], q33=q[3]*q[3]; const RealP q01=q[0]*q[1], q02=q[0]*q[2], q03=q[0]*q[3]; const RealP q12=q[1]*q[2], q13=q[1]*q[3], q23=q[2]*q[3]; const RealP q00mq11 = q00-q11, q22mq33 = q22-q33; Mat33P::operator=(Mat33P(q00+q11-q22-q33, 2*(q12-q03) , 2*(q13+q02), 2*(q12+q03) ,q00mq11+q22mq33, 2*(q23-q01), 2*(q13-q02) , 2*(q23+q01) ,q00mq11-q22mq33)); return *this; } //------------------------------------------------------------------------------ // Convert this Rotation matrix to the equivalent quaternion. // // We use a modification of Richard Spurrier's method: Spurrier, R.A., "Comment // on 'Singularity-Free Extraction of a Quaternion from a Direction-Cosine // Matrix'", J. Spacecraft and Rockets, 15(4):255, 1977. Our modification // avoids all but one square root and divide. In each of the four cases we // compute 4q[m]*q where m is the "max" element, with // m=0 if the trace is larger than any diagonal or // m=i if the i,i element is the largest diagonal and larger than the trace. // Then when we normalize at the end the scalar 4q[m] evaporates leaving us // with a perfectly normalized quaternion. // // The returned quaternion can be interpreted as a rotation angle a about a unit // vector v=[vx vy vz] like this: q = [ cos(a/2) sin(a/2)*v ] // We canonicalize the returned quaternion by insisting that // cos(a/2) >= 0, meaning that -180 < a <= 180. // // This takes about 40 flops. //------------------------------------------------------------------------------ template <class P> Quaternion_<P> Rotation_<P>::convertRotationToQuaternion() const { const Mat33P& R = asMat33(); // Stores the return values [cos(theta/2), lambda1*sin(theta/2), // lambda2*sin(theta/2), lambda3*sin(theta/2)] Vec4P q; // Check if the trace is larger than any diagonal const RealP tr = R.trace(); if( tr >= R(0,0) && tr >= R(1,1) && tr >= R(2,2) ) { q[0] = 1 + tr; q[1] = R(2,1) - R(1,2); q[2] = R(0,2) - R(2,0); q[3] = R(1,0) - R(0,1); // Check if R(0,0) is largest along the diagonal } else if( R(0,0) >= R(1,1) && R(0,0) >= R(2,2) ) { q[0] = R(2,1) - R(1,2); q[1] = 1 - (tr - 2*R(0,0)); q[2] = R(0,1)+R(1,0); q[3] = R(0,2)+R(2,0); // Check if R(1,1) is largest along the diagonal } else if( R(1,1) >= R(2,2) ) { q[0] = R(0,2) - R(2,0); q[1] = R(0,1) + R(1,0); q[2] = 1 - (tr - 2*R(1,1)); q[3] = R(1,2) + R(2,1); // R(2,2) is largest along the diagonal } else { q[0] = R(1,0) - R(0,1); q[1] = R(0,2) + R(2,0); q[2] = R(1,2) + R(2,1); q[3] = 1 - (tr - 2*R(2,2)); } RealP scale = q.norm(); if( q[0] < 0 ) scale = -scale; // canonicalize return Quaternion_<P>(q/scale, true); // prevent re-normalization } //------------------------------------------------------------------------------ // Determine whether "this" Rotation matrix is nearly identical to the one // passed in (R) within a specified "pointing angle error". If "this" and "R" // are nearly identical, transpose(this) * R = closeToIdentity matrix. After // finding the equivalent angle-axis for closeToIdentityMatrix, check the angle // to see if it is less than okPointingAngleErrorRads. //------------------------------------------------------------------------------ template <class P> bool Rotation_<P>::isSameRotationToWithinAngle (const Rotation_<P>& R, RealP okPointingAngleErrorRads ) const { // The absolute minimum pointing error is 0 if "this" and R are identical. // The absolute maximum pointing error should be Pi (to machine precision). assert( 0 <= okPointingAngleErrorRads && okPointingAngleErrorRads <= Pi); const Rotation_<P> closeToIdentityMatrix = ~(*this) * R; const Vec4P angleAxisEquivalent = closeToIdentityMatrix.convertRotationToAngleAxis(); const RealP pointingError = std::abs( angleAxisEquivalent[0] ); return pointingError <= okPointingAngleErrorRads; } //------------------------------------------------------------------------------ // This method is a poor man's orthogonalization from the supplied matrix to // make a legitimate rotation. This is done by conversion to quaternions and // back to Rotation and may not produce the closest rotation. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromApproximateMat33( const Mat33P& m ) { // First, create a Rotation from the given Mat33P const Rotation_<P> approximateRotation(m, true); const Quaternion_<P> q = approximateRotation.convertRotationToQuaternion(); this->setRotationFromQuaternion( q ); return *this; } //------------------------------------------------------------------------------ // Note: It may be slightly more efficient to set this matrix directly rather // than via the quaternion. //------------------------------------------------------------------------------ template <class P> Rotation_<P>& Rotation_<P>::setRotationFromAngleAboutUnitVector ( RealP angleInRad, const UnitVec3P& unitVector ) { QuaternionP q; q.setQuaternionFromAngleAxis( angleInRad, unitVector ); return setRotationFromQuaternion( q ); } //------------------------------------------------------------------------------ // Use sneaky tricks from Featherstone to rotate a symmetric dyadic // matrix. Consider the current Rotation matrix to be R_AB. We want // to return S_AA=R_AB*S_BB*R_BA. Would be 90 flops for 3x3s, 75 // since we only need six elements in final result. Here we'll get // it done in 57 flops. // Consider S=[ a d e ] // [ d b f ] // [ e f c ] // // First, factor S into S=L+D+vx with v=~[-f e 0] (x means cross // product matrix): // [a-c d 0] [c 0 0] [ 0 0 e] // L = [ d b-c 0] D = [0 c 0] vx = [ 0 0 f] // [2e 2f 0] [0 0 c] [-e -f 0] // (4 flops to calculate L) // // A cross product matrix identity says R*vx*~R=(R*v)x, so: // S'=R*S*~R = R*L*~R + D + (R*v)x. // Let Y'=R*L, Z=Y'*~R. We only need the lower triangle of Z and a // 2x2 square of Y'. // // Don't-care's below are marked "-". Reminder: square bracket [i] // index of a matrix means "row i", round bracket (j) means "col j". // // [ - - 0 ] // Y' = [ Y00 Y01 0 ] Y = [ R[1]*L(0) R[1]*L(1) ] 20 flops // [ Y10 Y11 0 ] [ R[2]*L(0) R[2]*L(1) ] // // Z = [ Z00 - - ] // [ Y[0]*~R[0] Y[0]*~R[1] - ] 15 flops (use only 2 // [ Y[1]*~R[0] Y[1]*~R[1] Y[1]*~R[2] ] elements of R's rows) // // Z00 = (L00+L11)-(Z11+Z22) 3 flops ( because rotation preserves trace) // // [R01*e-R00*f] [ 0 - - ] // R*v =[R11*e-R10*f] (R*v)x = [ Rv[2] 0 - ] // [R21*e-R20*f] [-Rv[1] Rv[0] 0 ] // (R*v is 9 flops) // // [ Z00 + c - - ] // S' = [ Z10 + Rv[2] Z11 + c - ] // [ Z20 - Rv[1] Z21 + Rv[0] Z22 + c ] // // which takes 6 more flops. Total 6+9Rv+18Z+20Y+4L=57. // // (I actually looked at the generated code in VC++ 2005 and Intel C++ // version 11.1 and counted exactly 57 inline flops.) // // NOTE: there are two implementations of this routine that have // to be kept in sync -- this one and the identical one for // InverseRotation right below. //------------------------------------------------------------------------------ template <class P> SymMat<3,P> Rotation_<P>::reexpressSymMat33(const SymMat33P& S_BB) const { const RealP a=S_BB(0,0), b=S_BB(1,1), c=S_BB(2,2); const RealP d=S_BB(1,0), e=S_BB(2,0), f=S_BB(2,1); const Mat33P& R = this->asMat33(); const Mat32P& RR = R.template getSubMat<3,2>(0,0); //first two columns of R const Mat32P L( a-c , d, d , b-c, 2*e , 2*f ); const Mat22P Y( R[1]*L(0), R[1]*L(1), R[2]*L(0), R[2]*L(1) ); const RealP Z10 = Y[0]*~RR[0], Z11 = Y[0]*~RR[1], Z20 = Y[1]*~RR[0], Z21 = Y[1]*~RR[1], Z22= Y[1]*~RR[2]; const RealP Z00 = (L(0,0)+L(1,1)) - (Z11+Z22); const Vec3P Rv( R(0,1)*e-R(0,0)*f, R(1,1)*e-R(1,0)*f, R(2,1)*e-R(2,0)*f ); return SymMat33P( Z00 + c, Z10 + Rv[2], Z11 + c, Z20 - Rv[1], Z21 + Rv[0], Z22 + c ); } // See above method for details. This method is identical except that // the layout of the matrix used to store the rotation matrix has // changed. Note that all the indexing here is identical to the normal // case above; but the rotation matrix elements are drawn from different // memory locations so that the net effect is to use the transpose of // the original rotation from which this was created. template <class P> SymMat<3,P> InverseRotation_<P>::reexpressSymMat33(const SymMat<3,P>& S_BB) const { const P a=S_BB(0,0), b=S_BB(1,1), c=S_BB(2,2); const P d=S_BB(1,0), e=S_BB(2,0), f=S_BB(2,1); // Note reversal of row and column spacing here (normal is 3,1). const Mat<3,3,P,1,3>& R = this->asMat33(); // RR is just the first two columns of R. const Mat<3,2,P,1,3>& RR = R.template getSubMat<3,2>(0,0); const Mat32P L( a-c , d, d , b-c, 2*e , 2*f ); const Mat22P Y( R[1]*L(0), R[1]*L(1), R[2]*L(0), R[2]*L(1) ); const P Z10 = Y[0]*~RR[0], Z11 = Y[0]*~RR[1], Z20 = Y[1]*~RR[0], Z21 = Y[1]*~RR[1], Z22= Y[1]*~RR[2]; const P Z00 = (L(0,0)+L(1,1)) - (Z11+Z22); const Vec3P Rv( R(0,1)*e-R(0,0)*f, R(1,1)*e-R(1,0)*f, R(2,1)*e-R(2,0)*f ); return SymMat<3,P>( Z00 + c, Z10 + Rv[2], Z11 + c, Z20 - Rv[1], Z21 + Rv[0], Z22 + c ); } // Make sure there are instantiations for all the non-inline methods. template class Rotation_<float>; template class Rotation_<double>; template class InverseRotation_<float>; template class InverseRotation_<double>; //------------------------------------------------------------------------------ template <class P> std::ostream& operator<<( std::ostream& o, const Rotation_<P>& m ) { return o << m.asMat33(); } template <class P> std::ostream& operator<<( std::ostream& o, const InverseRotation_<P>& m ) { return o << Rotation_<P>(m); } template SimTK_SimTKCOMMON_EXPORT std::ostream& operator<<(std::ostream&, const Rotation_<float>&); template SimTK_SimTKCOMMON_EXPORT std::ostream& operator<<(std::ostream&, const Rotation_<double>&); template SimTK_SimTKCOMMON_EXPORT std::ostream& operator<<(std::ostream&, const InverseRotation_<float>&); template SimTK_SimTKCOMMON_EXPORT std::ostream& operator<<(std::ostream&, const InverseRotation_<double>&); //------------------------------------------------------------------------------ } // End of namespace SimTK
42.385057
104
0.558346
[ "vector" ]
9cf82ed5f9e994cc36f5a2e371a7e837c2c0f24f
34,909
cc
C++
tensorflow/compiler/plugin/poplar/tests/deferred_visitor_test.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
2
2021-03-08T23:32:06.000Z
2022-01-13T03:43:49.000Z
tensorflow/compiler/plugin/poplar/tests/deferred_visitor_test.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/plugin/poplar/tests/deferred_visitor_test.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 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 <poplar/Device.hpp> #include <poplar/replication_factor.hpp> #include <poplin/codelets.hpp> #include <popnn/codelets.hpp> #include <popops/codelets.hpp> #include <poprand/RandomGen.hpp> #include <poprand/codelets.hpp> #include "absl/memory/memory.h" #include "tensorflow/compiler/plugin/poplar/driver/compiler_resources.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/allocation_finder.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/convolution_classifier.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/copy_inserter.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/forward_allocation.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/inplace_finder.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/module_flatten.h" #include "tensorflow/compiler/plugin/poplar/driver/passes/sharding_pass.h" #include "tensorflow/compiler/plugin/poplar/driver/tensor.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/util.h" #include "tensorflow/compiler/plugin/poplar/driver/visitors/entry_visitor.h" #include "tensorflow/compiler/xla/service/call_graph.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_dce.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_memory_scheduler.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/hlo_pass_fix.h" #include "tensorflow/compiler/xla/service/hlo_pass_pipeline.h" #include "tensorflow/compiler/xla/service/hlo_runner.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/core/lib/core/status_test_util.h" namespace xla { namespace poplarplugin { namespace { class DeferredVisitorTest : public HloTestBase {}; std::unique_ptr<CompilerResources> GetMockResources(HloModule* module, bool merge_infeeds) { auto resources = absl::make_unique<CompilerResources>( poplar::OptionFlags(), poplar::OptionFlags(), poplar::OptionFlags(), false, false, false, false, merge_infeeds, 1, 0, 0, 0, 0, 1, 64, module, IpuOptions::FloatingPointBehaviour(), false, "", false, false, false, poplar::OptionFlags(), 0, false); resources->streams_indices.InitializeIndexTensors(*resources, {}); resources->module_call_graph = CallGraph::Build(module); resources->main_graph = absl::make_unique<poplar::Graph>( poplar::Device::createCPUDevice(), poplar::replication_factor(1)); poplin::addCodelets(*resources->main_graph); popnn::addCodelets(*resources->main_graph); popops::addCodelets(*resources->main_graph); poprand::addCodelets(*resources->main_graph); return std::move(resources); } HloPassPipeline GetMockPipeline(CompilerResources& resources) { HloPassPipeline pipeline("mock_pipeline"); pipeline.AddPass<ModuleFlatten>(resources.annotations); pipeline.AddPass<CopyInserter>(); pipeline.AddPass<InplaceFinder>(); pipeline.AddPass<ShardingPass>(); pipeline.AddPass<HloDCE>(); pipeline.AddPass<ConvolutionClassifier>(resources.annotations); pipeline.AddPass<AllocationFinder>(resources.annotations); pipeline.AddPass<HloPassFix<ForwardAllocation>>(resources.annotations); pipeline.AddPass<HloMemoryScheduler>( [](const BufferValue& buffer) { return ShapeUtil::ByteSizeOf(buffer.shape(), 1); }, ComputationSchedulerToModuleScheduler(DefaultMemoryScheduler)); return pipeline; } TEST_F(DeferredVisitorTest, TestDeferredAllocation) { const string& hlo_string = R"( HloModule module _pop_op_conv_biasadd (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } ENTRY cluster (arg0.1: (f32[1,4,4,2], f32[2], f32[1,1,2,2])) -> f32[1,4,4,2] { arg = (f32[1,4,4,2], f32[2], f32[1,1,2,2]) parameter(0) gte0 = f32[1,4,4,2] get-tuple-element(arg), index=0 gte2 = f32[1,1,2,2] get-tuple-element(arg), index=2 convolution.5 = f32[1,4,4,2] convolution( gte0, gte2), window={size=1x1}, dim_labels=b01f_01io->b01f gte1 = f32[2] get-tuple-element(arg), index=1 ROOT fusion = f32[1,4,4,2] fusion(convolution.5, gte1), kind=kCustom, calls=_pop_op_conv_biasadd, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); // Verify that gte1 has a tensor and all the deferred allocations have that // tensor too. auto tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto root = entry_computation->root_instruction(); auto gte1 = root->operand(1); auto arg = gte1->operand(0); poplar::Tensor root_tensor = FindInstructionInput(tensor_map, *resources.get(), root, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[0]; poplar::Tensor arg_tensor = FindInstructionOutputs(tensor_map, *resources.get(), arg)[1]; EXPECT_EQ(root_tensor, gte1_tensor); EXPECT_EQ(gte1_tensor, arg_tensor); } TEST_F(DeferredVisitorTest, TestDeferredAllocationNestedTuple) { const string& hlo_string = R"( HloModule module _pop_op_conv_biasadd (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } ENTRY cluster (arg0.1: ((f32[1,4,4,2], f32[2], f32[1,1,2,2]))) -> f32[1,4,4,2] { arg = ((f32[1,4,4,2], f32[2], f32[1,1,2,2])) parameter(0) gte = (f32[1,4,4,2], f32[2], f32[1,1,2,2]) get-tuple-element(arg), index=0 gte0 = f32[1,4,4,2] get-tuple-element(gte), index=0 gte2 = f32[1,1,2,2] get-tuple-element(gte), index=2 convolution.5 = f32[1,4,4,2] convolution(gte0, gte2), window={size=1x1}, dim_labels=b01f_01io->b01f gte1 = f32[2] get-tuple-element(gte), index=1 ROOT fusion = f32[1,4,4,2] fusion(convolution.5, gte1), kind=kCustom, calls=_pop_op_conv_biasadd, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); // Verify that gte1 has a tensor and all the deferred allocations have that // tensor too. auto tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto root = entry_computation->root_instruction(); auto gte1 = root->operand(1); auto gte = gte1->operand(0); auto arg = gte->operand(0); poplar::Tensor root_tensor = FindInstructionInput(tensor_map, *resources.get(), root, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[0]; poplar::Tensor gte_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte)[1]; poplar::Tensor arg_tensor = FindInstructionOutputs(tensor_map, *resources.get(), arg)[1]; EXPECT_EQ(root_tensor, gte1_tensor); EXPECT_EQ(gte1_tensor, gte_tensor); EXPECT_EQ(gte_tensor, arg_tensor); } TEST_F(DeferredVisitorTest, TestDeferredAllocationDoubleNestedTuple) { const string& hlo_string = R"( HloModule module _pop_op_conv_biasadd (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } ENTRY cluster (arg0.1: ((f32[1,4,4,2], (f32[2], f32[1,1,2,2])))) -> f32[1,4,4,2] { arg = ((f32[1,4,4,2], (f32[2], f32[1,1,2,2]))) parameter(0) gte = (f32[1,4,4,2], (f32[2], f32[1,1,2,2])) get-tuple-element(arg), index=0 gte0 = f32[1,4,4,2] get-tuple-element(gte), index=0 gte1 = (f32[2], f32[1,1,2,2]) get-tuple-element(gte), index=1 gte1.1 = f32[1,1,2,2] get-tuple-element(gte1), index=1 convolution.5 = f32[1,4,4,2] convolution(gte0, gte1.1), window={size=1x1}, dim_labels=b01f_01io->b01f gte1.0 = f32[2] get-tuple-element(gte1), index=0 ROOT fusion = f32[1,4,4,2] fusion(convolution.5, gte1.0), kind=kCustom, calls=_pop_op_conv_biasadd, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); // Verify that gte1.0 has a tensor and all the deferred allocations have that // tensor too. auto tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto root = entry_computation->root_instruction(); auto gte1_0 = root->operand(1); auto gte1 = gte1_0->operand(0); auto gte = gte1->operand(0); auto arg = gte->operand(0); poplar::Tensor root_tensor = FindInstructionInput(tensor_map, *resources.get(), root, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_0_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1_0)[0]; poplar::Tensor gte1_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[0]; poplar::Tensor gte_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte)[1]; poplar::Tensor arg_tensor = FindInstructionOutputs(tensor_map, *resources.get(), arg)[1]; EXPECT_EQ(root_tensor, gte1_0_tensor); EXPECT_EQ(gte1_0_tensor, gte1_tensor); EXPECT_EQ(gte1_tensor, gte_tensor); EXPECT_EQ(gte_tensor, arg_tensor); } TEST_F(DeferredVisitorTest, TestDeferredAllocationMultipleDeferredAllocationsNestedTuple) { const string& hlo_string = R"( HloModule module _pop_op_conv_biasadd (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } _pop_op_conv_biasadd.1 (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } ENTRY cluster (arg0.1: ((((f32[1,4,4,2], f32[1,4,4,2]), (f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]))))) -> (f32[1,4,4,2], f32[1,4,4,2]) { arg = (((f32[1,4,4,2], f32[1,4,4,2]), (f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]))) parameter(0) gte = ((f32[1,4,4,2], f32[1,4,4,2]), (f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2])) get-tuple-element(arg), index=0 gte0 = (f32[1,4,4,2], f32[1,4,4,2]) get-tuple-element(gte), index=0 gte0.0 = f32[1,4,4,2] get-tuple-element(gte0), index=0 gte1 = (f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]) get-tuple-element(gte), index=1 gte1.1 = f32[1,1,2,2] get-tuple-element(gte1), index=1 convolution.0 = f32[1,4,4,2] convolution(gte0.0, gte1.1), window={size=1x1}, dim_labels=b01f_01io->b01f gte1.0 = f32[2] get-tuple-element((f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]) gte1), index=0 fusion.0 = f32[1,4,4,2] fusion(convolution.0, gte1.0), kind=kCustom, calls=_pop_op_conv_biasadd, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" gte0.1 = f32[1,4,4,2] get-tuple-element(gte0), index=1 gte1.3 = f32[1,1,2,2] get-tuple-element((f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]) gte1), index=3 convolution.1 = f32[1,4,4,2] convolution(gte0.1, gte1.3), window={size=1x1}, dim_labels=b01f_01io->b01f gte1.2 = f32[2] get-tuple-element((f32[2], f32[1,1,2,2], f32[2], f32[1,1,2,2]) gte1), index=2 fusion.1 = f32[1,4,4,2] fusion(convolution.1, gte1.2), kind=kCustom, calls=_pop_op_conv_biasadd.1, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" ROOT tuple = (f32[1,4,4,2], f32[1,4,4,2]) tuple(fusion.0, fusion.1) } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); auto tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto root_tuple = entry_computation->root_instruction(); // Verify that gte1.0 has a tensor and all the deferred allocations have that // tensor too. auto fusion_0 = root_tuple->operand(0); auto gte1_0 = fusion_0->operand(1); auto gte1 = gte1_0->operand(0); auto gte = gte1->operand(0); auto arg = gte->operand(0); poplar::Tensor fusion_0_input_one_tensor = FindInstructionInput(tensor_map, *resources.get(), fusion_0, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_0_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1_0)[0]; poplar::Tensor gte1_tensor_zero = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[0]; poplar::Tensor gte_tensor_two = FindInstructionOutputs(tensor_map, *resources.get(), gte)[2]; poplar::Tensor arg_tensor_two = FindInstructionOutputs(tensor_map, *resources.get(), arg)[2]; EXPECT_EQ(fusion_0_input_one_tensor, gte1_0_tensor); EXPECT_EQ(gte1_0_tensor, gte1_tensor_zero); EXPECT_EQ(gte1_tensor_zero, gte_tensor_two); EXPECT_EQ(gte_tensor_two, arg_tensor_two); // Verify that gte1.2 has a tensor and all the deferred allocations have that // tensor too. auto fusion_1 = root_tuple->operand(1); auto gte1_2 = fusion_1->operand(1); EXPECT_EQ(gte1, gte1_2->operand(0)); poplar::Tensor fusion_1_input_one_tensor = FindInstructionInput(tensor_map, *resources.get(), fusion_1, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_2_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1_2)[0]; poplar::Tensor gte1_tensor_two = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[2]; poplar::Tensor gte_tensor_four = FindInstructionOutputs(tensor_map, *resources.get(), gte)[4]; poplar::Tensor arg_tensor_four = FindInstructionOutputs(tensor_map, *resources.get(), arg)[4]; EXPECT_EQ(fusion_1_input_one_tensor, gte1_2_tensor); EXPECT_EQ(gte1_2_tensor, gte1_tensor_two); EXPECT_EQ(gte1_tensor_two, gte_tensor_four); EXPECT_EQ(gte_tensor_four, arg_tensor_four); } TEST_F(DeferredVisitorTest, TestDeferredAllocationNestedTupleInfeed) { const string& hlo_string = R"( HloModule module _pop_op_conv_biasadd (arg_0: f32[1,4,4,2], arg_1: f32[2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2] parameter(0) arg_1 = f32[2] parameter(1) broadcast.6.clone = f32[1,4,4,2] broadcast(arg_1), dimensions={3} ROOT add.7.clone = f32[1,4,4,2] add(arg_0, broadcast.6.clone) } ENTRY cluster (arg: f32[1,1,2,2]) -> f32[1,4,4,2] { arg = f32[1,1,2,2] parameter(0) after-all = token[] after-all() infeed = ((f32[1,4,4,2], f32[2]), token[]) infeed(token[] after-all), infeed_config="\010\001\022\005feed5\"\002\001\001" gte = (f32[1,4,4,2], f32[2]) get-tuple-element(((f32[1,4,4,2], f32[2]), token[]) infeed), index=0 gte0 = f32[1,4,4,2] get-tuple-element((f32[1,4,4,2], f32[2]) gte), index=0 convolution.5 = f32[1,4,4,2] convolution(gte0, arg), window={size=1x1}, dim_labels=b01f_01io->b01f gte1 = f32[2] get-tuple-element((f32[1,4,4,2], f32[2]) gte), index=1 ROOT fusion = f32[1,4,4,2] fusion(convolution.5, gte1), kind=kCustom, calls=_pop_op_conv_biasadd, backend_config="{\"fusionConfig\":{\"inplaceOperands\":[\"0\"]}}" } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); // Verify that gte1 has a tensor and all the deferred allocations have that // tensor too. auto tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto root = entry_computation->root_instruction(); auto gte1 = root->operand(1); auto gte = gte1->operand(0); auto infeed = gte->operand(0); poplar::Tensor root_tensor = FindInstructionInput(tensor_map, *resources.get(), root, 1, visitor.GetMutableSequence(), false) .ValueOrDie(); poplar::Tensor gte1_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte1)[0]; poplar::Tensor gte_tensor = FindInstructionOutputs(tensor_map, *resources.get(), gte)[1]; poplar::Tensor infeed_tensor = FindInstructionOutputs(tensor_map, *resources.get(), infeed)[1]; EXPECT_EQ(root_tensor, gte1_tensor); EXPECT_EQ(gte1_tensor, gte_tensor); EXPECT_EQ(gte_tensor, infeed_tensor); } TEST_F(DeferredVisitorTest, TestDeferredAllocationLoopsInputWithLayout) { const string& hlo_string = R"( HloModule module while_Sum-reduction.13 (x.14: f32[], y.15: f32[]) -> f32[] { x.14 = f32[] parameter(0) y.15 = f32[] parameter(1) ROOT add.16 = f32[] add(x.14, y.15) } _functionalize_body_1__.17 (arg_tuple.18: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) { arg_tuple.18 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) get-tuple-element.21 = f32[] get-tuple-element(arg_tuple.18), index=2 get-tuple-element.19 = s32[] get-tuple-element(arg_tuple.18), index=0 constant.26 = s32[] constant(1) add.27 = s32[] add(get-tuple-element.19, constant.26) get-tuple-element.20 = s32[] get-tuple-element(arg_tuple.18), index=1 constant.30 = s32[] constant(2) add.31 = s32[] add(get-tuple-element.20, constant.30) get-tuple-element.24 = f32[1,4,4,2] get-tuple-element(arg_tuple.18), index=5 get-tuple-element.25 = f32[1,1,2,2] get-tuple-element(arg_tuple.18), index=6 convolution.48 = f32[1,4,4,2] convolution(get-tuple-element.24, get-tuple-element.25), window={size=1x1}, dim_labels=b01f_01io->b01f get-tuple-element.23 = f32[2] get-tuple-element(arg_tuple.18), index=4 constant.33 = f32[] constant(0.1) broadcast.34 = f32[2] broadcast(constant.33), dimensions={} constant.32 = f32[2] constant({16, 16}) multiply.35 = f32[2] multiply(broadcast.34, constant.32) subtract.36 = f32[2] subtract(get-tuple-element.23, multiply.35) broadcast.49 = f32[1,4,4,2] broadcast(subtract.36), dimensions={3} add.50 = f32[1,4,4,2] add(convolution.48, broadcast.49) convert.51 = f32[1,4,4,2] convert(add.50) constant.52 = f32[] constant(0) convert.53 = f32[] convert(constant.52) reduce.54 = f32[] reduce(convert.51, convert.53), dimensions={0,1,2,3}, to_apply=while_Sum-reduction.13 convert.55 = f32[] convert(reduce.54) get-tuple-element.22 = s32[] get-tuple-element(arg_tuple.18), index=3 tuple.56 = (f32[2]) tuple(f32[2] subtract.36) get-tuple-element.57 = f32[2] get-tuple-element((f32[2]) tuple.56), index=0 constant.40 = f32[] constant(0.1) broadcast.41 = f32[1,4,4,2] broadcast(constant.40), dimensions={} constant.28 = f32[] constant(1) broadcast.29 = f32[1,4,4,2] broadcast(constant.28), dimensions={} reverse.38 = f32[1,1,2,2] reverse(get-tuple-element.25), dimensions={0,1} convolution.39 = f32[1,4,4,2] convolution(broadcast.29, reverse.38), window={size=1x1}, dim_labels=b01f_01oi->b01f multiply.42 = f32[1,4,4,2] multiply(broadcast.41, convolution.39) subtract.43 = f32[1,4,4,2] subtract(get-tuple-element.24, multiply.42) tuple.58 = (f32[1,4,4,2]) tuple(subtract.43) get-tuple-element.59 = f32[1,4,4,2] get-tuple-element(tuple.58), index=0 constant.44 = f32[] constant(0.1) broadcast.45 = f32[1,1,2,2] broadcast(constant.44), dimensions={} convolution.37 = f32[1,1,2,2] convolution(get-tuple-element.24, broadcast.29), window={size=4x4}, dim_labels=f01b_i01o->01bf multiply.46 = f32[1,1,2,2] multiply(broadcast.45, convolution.37) subtract.47 = f32[1,1,2,2] subtract(get-tuple-element.25, multiply.46) tuple.60 = (f32[1,1,2,2]) tuple(subtract.47) get-tuple-element.61 = f32[1,1,2,2] get-tuple-element(tuple.60), index=0 ROOT tuple.62 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) tuple(add.27, add.31, convert.55, get-tuple-element.22, get-tuple-element.57, get-tuple-element.59, get-tuple-element.61) } _functionalize_cond_1__.63 (arg_tuple.64: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> (pred[]) { arg_tuple.64 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) get-tuple-element.67 = f32[] get-tuple-element(arg_tuple.64), index=2 get-tuple-element.69 = f32[2] get-tuple-element(arg_tuple.64), index=4 get-tuple-element.70 = f32[1,4,4,2] get-tuple-element(arg_tuple.64), index=5 get-tuple-element.71 = f32[1,1,2,2] get-tuple-element(arg_tuple.64), index=6 get-tuple-element.65 = s32[] get-tuple-element(arg_tuple.64), index=0 get-tuple-element.68 = s32[] get-tuple-element(arg_tuple.64), index=3 less-than.74 = pred[] compare(get-tuple-element.65, get-tuple-element.68), direction=LT get-tuple-element.66 = s32[] get-tuple-element(arg_tuple.64), index=1 constant.72 = s32[] constant(2) less-than.73 = pred[] compare(get-tuple-element.66, constant.72), direction=LT and.75 = pred[] and(pred[] less-than.74, pred[] less-than.73) ROOT tuple.76 = (pred[]) tuple(pred[] and.75) } cond_wrapper.77 (inputs.78: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> pred[] { inputs.78 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) call.79 = (pred[]) call(inputs.78), to_apply=_functionalize_cond_1__.63 ROOT get-tuple-element.80 = pred[] get-tuple-element((pred[]) call.79), index=0 } ENTRY cluster_4790582643659166751_f15n_0__.98 (arg0.1: f32[1,4,4,2], arg1.2: f32[2], arg2.3: f32[1,1,2,2]) -> (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) { constant1 = s32[] constant(0) constant2 = f32[] constant(10) constant3 = s32[] constant(10) arg1.2 = f32[2] parameter(1) arg0.1 = f32[1,4,4,2] parameter(0) arg2.3 = f32[1,1,2,2] parameter(2) tuple.12 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) tuple(constant1, constant1, constant2, constant3, arg1.2, arg0.1, arg2.3) ROOT while.81 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) while(tuple.12), condition=cond_wrapper.77, body=_functionalize_body_1__.17 } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto resources = GetMockResources(module.get(), false); HloPassPipeline pipeline = GetMockPipeline(*resources.get()); EXPECT_TRUE(pipeline.Run(module.get()).ValueOrDie()); auto entry_computation = module->entry_computation(); EntryVisitor visitor(*resources.get(), entry_computation); TF_EXPECT_OK(entry_computation->Accept(&visitor)); // Check that the two last inputs to the loop are the same tensor - these // parameters have allocation targets in the entry computation and inside the // loop - but because they already have a layout at the callsite we just use // that rather than creating a new layout and copying. auto entry_tensor_map = resources->tensor_maps.GetTensorMapForComputation( entry_computation->name()); auto entry_root_instruction = entry_computation->root_instruction(); auto entry_loop_input_tensors = FindInstructionOutputs( entry_tensor_map, *resources.get(), entry_root_instruction->operand(0)); auto entry_loop_tensors = FindInstructionOutputs( entry_tensor_map, *resources.get(), entry_root_instruction); auto loop_body = entry_root_instruction->while_body(); auto loop_tensor_map = resources->tensor_maps.GetTensorMapForComputation(loop_body->name()); EXPECT_EQ(loop_body->num_parameters(), 1); auto loop_tuple = loop_body->parameter_instruction(0); auto loop_tuple_tensors = FindInstructionOutputs(loop_tensor_map, *resources.get(), loop_tuple); // Check the tensors. auto num_inputs = CountShapes(loop_tuple->shape()); EXPECT_EQ(entry_loop_tensors.size(), num_inputs); EXPECT_EQ(entry_loop_input_tensors.size(), loop_tuple_tensors.size()); EXPECT_EQ(entry_loop_input_tensors[0], loop_tuple_tensors[0]); // Duplicate operand gets reallocated. EXPECT_NE(entry_loop_input_tensors[1], loop_tuple_tensors[1]); EXPECT_EQ(entry_loop_input_tensors[2], loop_tuple_tensors[2]); EXPECT_EQ(entry_loop_input_tensors[3], loop_tuple_tensors[3]); EXPECT_EQ(entry_loop_input_tensors[4], loop_tuple_tensors[4]); EXPECT_EQ(entry_loop_input_tensors[5], loop_tuple_tensors[5]); EXPECT_EQ(entry_loop_input_tensors[6], loop_tuple_tensors[6]); EXPECT_EQ(entry_loop_tensors.size(), loop_tuple_tensors.size()); EXPECT_EQ(entry_loop_tensors, loop_tuple_tensors); } TEST_F(DeferredVisitorTest, TestDeferredAllocationInsideLoops) { const string& hlo_string = R"( HloModule module while_Sum-reduction.13 (x.14: f32[], y.15: f32[]) -> f32[] { x.14 = f32[] parameter(0) y.15 = f32[] parameter(1) ROOT add.16 = f32[] add(x.14, y.15) } _functionalize_body_1__.17 (arg_tuple.18: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) { arg_tuple.18 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) get-tuple-element.21 = f32[] get-tuple-element(arg_tuple.18), index=2 get-tuple-element.19 = s32[] get-tuple-element(arg_tuple.18), index=0 constant.26 = s32[] constant(1) add.27 = s32[] add(get-tuple-element.19, constant.26) get-tuple-element.20 = s32[] get-tuple-element(arg_tuple.18), index=1 constant.30 = s32[] constant(1) add.31 = s32[] add(get-tuple-element.20, constant.30) get-tuple-element.24 = f32[1,4,4,2] get-tuple-element(arg_tuple.18), index=5 get-tuple-element.25 = f32[1,1,2,2] get-tuple-element(arg_tuple.18), index=6 convolution.48 = f32[1,4,4,2] convolution(get-tuple-element.24, get-tuple-element.25), window={size=1x1}, dim_labels=b01f_01io->b01f get-tuple-element.23 = f32[2] get-tuple-element(arg_tuple.18), index=4 constant.33 = f32[] constant(0.1) broadcast.34 = f32[2] broadcast(constant.33), dimensions={} constant.32 = f32[2] constant({16, 16}) multiply.35 = f32[2] multiply(broadcast.34, constant.32) subtract.36 = f32[2] subtract(get-tuple-element.23, multiply.35) broadcast.49 = f32[1,4,4,2] broadcast(subtract.36), dimensions={3} add.50 = f32[1,4,4,2] add(convolution.48, broadcast.49) convert.51 = f32[1,4,4,2] convert(add.50) constant.52 = f32[] constant(0) convert.53 = f32[] convert(constant.52) reduce.54 = f32[] reduce(convert.51, convert.53), dimensions={0,1,2,3}, to_apply=while_Sum-reduction.13 convert.55 = f32[] convert(reduce.54) get-tuple-element.22 = s32[] get-tuple-element(arg_tuple.18), index=3 tuple.56 = (f32[2]) tuple(f32[2] subtract.36) get-tuple-element.57 = f32[2] get-tuple-element((f32[2]) tuple.56), index=0 constant.40 = f32[] constant(0.1) broadcast.41 = f32[1,4,4,2] broadcast(constant.40), dimensions={} constant.28 = f32[] constant(1) broadcast.29 = f32[1,4,4,2] broadcast(constant.28), dimensions={} reverse.38 = f32[1,1,2,2] reverse(get-tuple-element.25), dimensions={0,1} convolution.39 = f32[1,4,4,2] convolution(broadcast.29, reverse.38), window={size=1x1}, dim_labels=b01f_01oi->b01f multiply.42 = f32[1,4,4,2] multiply(broadcast.41, convolution.39) subtract.43 = f32[1,4,4,2] subtract(get-tuple-element.24, multiply.42) tuple.58 = (f32[1,4,4,2]) tuple(subtract.43) get-tuple-element.59 = f32[1,4,4,2] get-tuple-element(tuple.58), index=0 constant.44 = f32[] constant(0.1) broadcast.45 = f32[1,1,2,2] broadcast(constant.44), dimensions={} convolution.37 = f32[1,1,2,2] convolution(get-tuple-element.24, broadcast.29), window={size=4x4}, dim_labels=f01b_i01o->01bf multiply.46 = f32[1,1,2,2] multiply(broadcast.45, convolution.37) subtract.47 = f32[1,1,2,2] subtract(get-tuple-element.25, multiply.46) tuple.60 = (f32[1,1,2,2]) tuple(subtract.47) get-tuple-element.61 = f32[1,1,2,2] get-tuple-element(tuple.60), index=0 ROOT tuple.62 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) tuple(add.27, add.31, convert.55, get-tuple-element.22, get-tuple-element.57, get-tuple-element.59, get-tuple-element.61) } _functionalize_cond_1__.63 (arg_tuple.64: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> (pred[]) { arg_tuple.64 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) get-tuple-element.67 = f32[] get-tuple-element(arg_tuple.64), index=2 get-tuple-element.69 = f32[2] get-tuple-element(arg_tuple.64), index=4 get-tuple-element.70 = f32[1,4,4,2] get-tuple-element(arg_tuple.64), index=5 get-tuple-element.71 = f32[1,1,2,2] get-tuple-element(arg_tuple.64), index=6 get-tuple-element.65 = s32[] get-tuple-element(arg_tuple.64), index=0 get-tuple-element.68 = s32[] get-tuple-element(arg_tuple.64), index=3 less-than.74 = pred[] compare(get-tuple-element.65, get-tuple-element.68), direction=LT get-tuple-element.66 = s32[] get-tuple-element(arg_tuple.64), index=1 constant.72 = s32[] constant(2) less-than.73 = pred[] compare(get-tuple-element.66, constant.72), direction=LT and.75 = pred[] and(pred[] less-than.74, pred[] less-than.73) ROOT tuple.76 = (pred[]) tuple(pred[] and.75) } cond_wrapper.77 (inputs.78: (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2])) -> pred[] { inputs.78 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) parameter(0) call.79 = (pred[]) call(inputs.78), to_apply=_functionalize_cond_1__.63 ROOT get-tuple-element.80 = pred[] get-tuple-element((pred[]) call.79), index=0 } ENTRY cluster_4790582643659166751_f15n_0__.98 (arg0.1: f32[1,4,4,2], arg1.2: f32[2], arg2.3: f32[1,1,2,2]) -> (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) { constant.4 = s32[] constant(0) constant.5 = s32[] constant(0) constant.6 = f32[] constant(0) constant.7 = s32[] constant(10) constant.8 = s32[] constant(0) constant.9 = s32[] constant(0) constant.10 = f32[] constant(0) constant.11 = s32[] constant(10) arg1.2 = f32[2] parameter(1) arg0.1 = f32[1,4,4,2] parameter(0) arg2.3 = f32[1,1,2,2] parameter(2) tuple.12 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) tuple(constant.8, constant.9, constant.10, constant.11, arg1.2, arg0.1, arg2.3) ROOT while.81 = (s32[], s32[], f32[], s32[], f32[2], f32[1,4,4,2], f32[1,1,2,2]) while(tuple.12), condition=cond_wrapper.77, body=_functionalize_body_1__.17 } )"; std::unique_ptr<HloModule> module = ParseAndReturnVerifiedModule(hlo_string).ConsumeValueOrDie(); auto layout_d4 = LayoutUtil::MakeLayout({3, 2, 1, 0}); Array4D<float> input_arr({ // clang-format off { // i0=0 { // i1=0 { 1, 2}, // i2=0 { 3, 4}, // i2=1 { 5, 6}, // i2=2 { 7, 8}, // i2=3 }, { // i1=1 { 9, 10}, // i2=0 {11, 12}, // i2=1 {13, 14}, // i2=2 {15, 16}, // i2=3 }, { // i1=2 {17, 18}, // i2=0 {19, 20}, // i2=1 {21, 22}, // i2=2 {23, 24}, // i2=3 }, { // i1=3 {25, 26}, // i2=0 {27, 28}, // i2=1 {29, 30}, // i2=2 {31, 32}, // i2=3 }, }, // clang-format on }); auto input_literal = LiteralUtil::CreateR4FromArray4DWithLayout<float>(input_arr, layout_d4); auto biases = LiteralUtil::CreateR1<float>({-100, 100}); Array4D<float> weights_arr({ // clang-format off { // i0=0 { // i1=0 {1, 2}, // i2=0 {3, 4}, // i2=1 }, }, // clang-format on }); auto weights_literal = LiteralUtil::CreateR4FromArray4DWithLayout<float>(weights_arr, layout_d4); auto result = ExecuteAndTransfer(std::move(module), {&input_literal, &biases, &weights_literal}); auto result_tuple = result.DecomposeTuple(); // Expect correct value for the biases. EXPECT_EQ(result_tuple[4], LiteralUtil::CreateR1<float>({-103.2, 96.8})); } } // namespace } // namespace poplarplugin } // namespace xla
49.941345
204
0.687559
[ "shape" ]
9cf9bdceb86bd3d5727026dafbf4a8c422974b3a
993
hpp
C++
src/assembly/nodes/InstrGroupNode.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
src/assembly/nodes/InstrGroupNode.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
src/assembly/nodes/InstrGroupNode.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // // © 2020 Shockazoid, Inc. All Rights Reserved. // #ifndef __h3o_InstrGroupNode__ #define __h3o_InstrGroupNode__ #include "BlockNode.hpp" #include "../../vm/InstrGroup.hpp" #include "../../vm/opcodes.hpp" namespace hydro { class InstrGroupNode : public BlockNode { protected: InstrGroup *_group; std::vector<VM_Object *> _slots; std::vector<VM_Object *> _upvalues; public: bool returnsValue{false}; InstrGroupNode(InstrGroup *group); virtual ~InstrGroupNode(); virtual void build(Chunk *chunk) override; InstrGroup *group() const { return _group; } }; } // namespace hydro #endif /* __h3o_InstrGroupNode__ */
23.642857
54
0.540785
[ "vector" ]
9cfa2b99a0982d36e81324a1fc8cc3fb8821264c
1,380
hpp
C++
Dynamic Programming/KnapsackProblem.hpp
Acamol/Algorithms-in-CPP
3c890a53078971653b13bf2bfd0aeb9efc05fe44
[ "MIT" ]
null
null
null
Dynamic Programming/KnapsackProblem.hpp
Acamol/Algorithms-in-CPP
3c890a53078971653b13bf2bfd0aeb9efc05fe44
[ "MIT" ]
1
2018-09-12T13:12:27.000Z
2018-09-12T13:12:27.000Z
Dynamic Programming/KnapsackProblem.hpp
Acamol/Algorithms-in-CPP
3c890a53078971653b13bf2bfd0aeb9efc05fe44
[ "MIT" ]
null
null
null
/* The definition of the Knapsack Problem can be found here: https://en.wikipedia.org/wiki/Knapsack_problem This algorithm solves the 1-dimensional problem using Dynamic Programming. The actual algorithm is the method Knapsack::chooseBoxes. Time and space complexity: O(nW), when n is the number of boxes and W is the knapsack's maximum weight. */ #ifndef __KNAPSACK_PROBLEM_HPP__ #define __KNAPSACK_PROBLEM_HPP__ #include <vector> class Knapsack { public: // first is value, second is weight typedef std::pair<unsigned int, unsigned int> Box; explicit Knapsack(std::size_t maxWeight); // Given a set of boxes, each with a weight and a value, determines the // boxes to include in a collection so that the total weight is less than // or equal to a given limit and the total value is as large as possible. void chooseBoxes(const std::vector<Box>& set); // Returns a copy of the boxes inside the knapsack. std::vector<Box> getBoxes() const; // Empties the knapsack. void clear(); // Returns the number of boxes. std::size_t size() const; private: const std::size_t maxWeight; // the max weight of boxes the knapsack can hold std::size_t weight; // the current total weight of boxes inside the knapsack std::vector<Box> boxes; // the boxes inside the knapsack }; #endif // !__KNAPSACK_PROBLEM_HPP__
30.666667
79
0.723188
[ "vector" ]
9cfa4f2791ddb72bd59bf592b0884db49652be8a
3,357
cpp
C++
test/database/main_odbc_oracle1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
39
2015-12-09T09:28:46.000Z
2021-11-16T12:57:25.000Z
test/database/main_odbc_oracle1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
1
2020-10-17T02:23:42.000Z
2020-10-17T02:23:42.000Z
test/database/main_odbc_oracle1.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
8
2018-05-29T12:48:13.000Z
2022-02-27T01:45:57.000Z
#include <ccxx/ccxx.h> #include <iostream> using namespace std; #include <stdio.h> #include <string.h> #include <stdlib.h> #define OTL_ODBC // Compile OTL 4.0/ODBC #define ODBCVER 0x0250 // ODBC Version # needs to be downgraded // to 2.5 because the SQLite ODBC driver seems // to run slower when ODBC 3.x functions // used (performance is not as good as with // ODBC 2.5 function calls) // #define OTL_ODBC_UNIX // uncomment this line if UnixODBC is used #include <ccxx/otlv4.h> // include the OTL 4.0 header file otl_connect db; // connect object void insert() // insert rows into table { otl_stream o(50, // stream buffer size "insert into test_tab values(:f1<int>,:f2<char[31]>)", // SQL statement db // connect object ); char tmp[32]; for(int i=1;i<=100;++i){ #if defined(_MSC_VER) #if (_MSC_VER >= 1400) // VC++ 8.0 or higher sprintf_s(tmp,sizeof(tmp),"Name%d",i); #else sprintf(tmp,"Name%d",i); #endif #else sprintf(tmp,"Name%d",i); #endif o<<i<<tmp; } } void update(const int af1) // insert rows into table { otl_stream o(1, // buffer size "UPDATE test_tab " " SET f2=:f2<char[31]> " " WHERE f1=:f1<int>", // UPDATE statement db // connect object ); o<<"Name changed"<<af1; o<<otl_null()<<af1+1; // set f2 to NULL // there is no need to flush the stream buffer here // because the buffer size is 1: the stream flushes // the buffer every time the buffer gets full } void select(const int af1) { otl_stream i(50, // buffer size may be > 1 "select * from test_tab " "where f1>=:f11<int> " " and f1<=:f12<int>*2", // SELECT statement db // connect object ); // create select stream int f1; char f2[31]; i<<af1<<af1; // Writing input values into the stream while(!i.eof()){ // while not end-of-data i>>f1; cout<<"f1="<<f1<<", f2="; i>>f2; if(i.is_null()) cout<<"NULL"; else cout<<f2; cout<<endl; } } int main() { otl_connect::otl_initialize(); // initialize ODBC environment try{ db.rlogon("scott/tiger@sqlite"); otl_cursor::direct_exec ( db, "drop table test_tab", otl_exception::disabled // disable OTL exceptions ); // drop table otl_cursor::direct_exec ( db, "create table test_tab(f1 int, f2 varchar(30))" ); // create table insert(); // insert records into the table update(10); // update records in the table select(8); // select records from the table } catch(otl_exception& p){ // intercept OTL exceptions cerr<<p.msg<<endl; // print out error message cerr<<p.stm_text<<endl; // print out SQL that caused the error cerr<<p.sqlstate<<endl; // print out SQLSTATE message cerr<<p.var_info<<endl; // print out the variable that caused the error } db.logoff(); // disconnect from the database return 0; }
25.823077
79
0.540959
[ "object" ]
9cfdba6e7a88b074e510b21ad241e466d6456d40
8,773
cpp
C++
src/game/server/swarm/asw_simple_grub.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/server/swarm/asw_simple_grub.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/server/swarm/asw_simple_grub.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
#include "cbase.h" #include "asw_simple_grub.h" #include "asw_trace_filter_melee.h" #include "te_effect_dispatch.h" #include "asw_util_shared.h" #include "asw_marine.h" #include "asw_marine_resource.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define SWARM_GRUB_MODEL "models/swarm/Grubs/Grub.mdl" LINK_ENTITY_TO_CLASS( asw_grub, CASW_Simple_Grub ); PRECACHE_REGISTER( asw_grub ); BEGIN_DATADESC( CASW_Simple_Grub ) DEFINE_ENTITYFUNC(GrubTouch), END_DATADESC() extern ConVar asw_debug_simple_alien; //IMPLEMENT_SERVERCLASS_ST(CASW_Simple_Grub, DT_ASW_Simple_Drone) //END_SEND_TABLE() // ========================================= // Creation // ========================================= CASW_Simple_Grub::CASW_Simple_Grub() { m_bSkipGravity = false; } CASW_Simple_Grub::~CASW_Simple_Grub() { } void CASW_Simple_Grub::Spawn(void) { BaseClass::Spawn(); SetCollisionGroup( ASW_COLLISION_GROUP_GRUBS ); SetModel( SWARM_GRUB_MODEL ); SetHullType( HULL_TINY ); AddSolidFlags(FSOLID_TRIGGER); UTIL_SetSize(this, Vector(-12,-12, 0), Vector(12, 12, 12)); SetTouch( &CASW_Simple_Grub::GrubTouch ); m_iHealth = 1; SetBlocksLOS(false); } void CASW_Simple_Grub::GrubTouch( CBaseEntity *pOther ) { if (!pOther) return; if (pOther->Classify() == CLASS_ASW_MARINE && pOther->GetAbsVelocity().Length() > 100) { Vector xydiff = GetAbsOrigin() - pOther->GetAbsOrigin(); xydiff.z = 0; if (xydiff.Length() < 20) { CTakeDamageInfo dmg(pOther, pOther, Vector(0, 0, -1), GetAbsOrigin() + Vector(0, 0, 1), 20, DMG_CRUSH); TakeDamage(dmg); } } } void CASW_Simple_Grub::Precache() { BaseClass::Precache(); PrecacheModel( SWARM_GRUB_MODEL ); PrecacheModel( "Models/Swarm/Grubs/GrubGib4.mdl" ); PrecacheScriptSound("ASW_Grub.Pain"); PrecacheScriptSound("ASW_Parasite.Attack"); PrecacheScriptSound("ASW_Parasite.Idle"); PrecacheParticleSystem( "grub_death" ); PrecacheParticleSystem( "grub_death_fire" ); } // ========================================= // Anims // ========================================= void CASW_Simple_Grub::PlayRunningAnimation() { ResetSequence(LookupSequence("CrawlA")); m_flPlaybackRate = 1.25f; } void CASW_Simple_Grub::PlayFallingAnimation() { ResetSequence(LookupSequence("Jump")); m_flPlaybackRate = 1.25f; } void CASW_Simple_Grub::PlayAttackingAnimation() { ResetSequence(LookupSequence("CrawlA")); m_flPlaybackRate = 1.25f; } // ========================================= // Sounds // ========================================= void CASW_Simple_Grub::PainSound( const CTakeDamageInfo &info ) { if (gpGlobals->curtime > m_fNextPainSound) { EmitSound("ASW_Grub.Pain"); m_fNextPainSound = gpGlobals->curtime + 0.5f; } } void CASW_Simple_Grub::AlertSound() { } void CASW_Simple_Grub::DeathSound( const CTakeDamageInfo &info ) { } void CASW_Simple_Grub::AttackSound() { } // ========================================= // Gibbing // ========================================= bool CASW_Simple_Grub::ShouldGib( const CTakeDamageInfo &info ) { return true; } bool CASW_Simple_Grub::CorpseGib( const CTakeDamageInfo &info ) { CEffectData data; data.m_vOrigin = WorldSpaceCenter(); data.m_vNormal = data.m_vOrigin - info.GetDamagePosition(); VectorNormalize( data.m_vNormal ); data.m_flScale = RemapVal( m_iHealth, 0, -500, 1, 3 ); data.m_flScale = clamp( data.m_flScale, 1, 3 ); data.m_fFlags = (IsOnFire() || (info.GetDamageType() & DMG_BURN)) ? ASW_GIBFLAG_ON_FIRE : 0; CPASFilter filter( data.m_vOrigin ); filter.SetIgnorePredictionCull(true); DispatchEffect( filter, 0.0, "GrubGib", data ); //DispatchEffect( "GrubGib", data ); return true; } // ========================================= // Movement // ========================================= float CASW_Simple_Grub::GetIdealSpeed() const { return 100.0f; } void CASW_Simple_Grub::AlienThink() { float delta = gpGlobals->curtime - m_fLastThinkTime; BaseClass::AlienThink(); UpdatePitch(delta); /* if (GetEnemy() && GetAbsOrigin().DistTo(GetEnemy()->GetAbsOrigin()) < 800) { // check if a marine is standing on us trace_t tr; UTIL_TraceLine( GetAbsOrigin() - Vector(5, 5, -1), GetAbsOrigin() + Vector(5, 5, 5), MASK_SOLID, this, COLLISION_GROUP_PLAYER, &tr ); if (tr.fraction < 1 && tr.m_pEnt) { if (tr.m_pEnt->Classify() == CLASS_ASW_MARINE) { CTakeDamageInfo dmg(tr.m_pEnt, tr.m_pEnt, Vector(0, 0, -1), GetAbsOrigin() + Vector(0, 0, 1), 20, DMG_CRUSH); TakeDamage(dmg); } } // think more frequently so we don't miss a player stomping on us SetNextThink( gpGlobals->curtime + 0.025f ); }*/ } void CASW_Simple_Grub::UpdatePitch(float delta) { float current = UTIL_AngleMod( GetLocalAngles()[PITCH] ); float ideal = UTIL_AngleMod( GetIdealPitch() ); float dt = MIN( 0.2, delta ); float newPitch = ASW_ClampYaw( GetPitchSpeed(), current, ideal, dt ); if (newPitch != current) { QAngle angles = GetLocalAngles(); angles[PITCH] = newPitch; SetLocalAngles( angles ); } } float CASW_Simple_Grub::GetPitchSpeed() const { return 2000.0f; } float CASW_Simple_Grub::GetIdealPitch() { if (m_bSkipGravity) // we're climbing return -90; return 0; } float CASW_Simple_Grub::GetFaceEnemyDistance() const { return 50.0f; } float CASW_Simple_Grub::GetZigZagChaseDistance() const { return 50.0f; } bool CASW_Simple_Grub::ApplyGravity(Vector &vecTarget, float deltatime) { if (m_bSkipGravity) { if (asw_debug_simple_alien.GetBool()) Msg("Skipping grav\n"); return false; } return BaseClass::ApplyGravity(vecTarget, deltatime); } // run towards the target like a normal simple alien, but if he hit some geometry, try to climb up over it // todo: perform move could check if gravity was skipped and switch us to a climbing anim instead of a running bool CASW_Simple_Grub::TryMove(const Vector &vecSrc, Vector &vecTarget, float deltatime, bool bStepMove) { m_bSkipGravity = false; // do a trace to the dest Ray_t ray; trace_t trace; CTraceFilterSimple traceFilter(this, GetCollisionGroup() ); ray.Init( vecSrc, vecTarget, GetHullMins(), GetHullMaxs() ); enginetrace->TraceRay( ray, MASK_NPCSOLID, &traceFilter, &trace ); if (trace.startsolid) { // doh, we're stuck in something! // todo: move us to a safe spot? wait for push out phys props? if (asw_debug_simple_alien.GetBool()) Msg("CASW_Simple_Grub stuck!\n"); m_MoveFailure.trace = trace; m_MoveFailure.vecStartPos = vecSrc; m_MoveFailure.vecTargetPos = vecTarget; return false; } if (trace.fraction < 0.1f) // barely/didn't move { // try and do a 'stepped up' move to the target if (!bStepMove) { Vector vecStepSrc = vecSrc; vecStepSrc.z += 24; Vector vecStepTarget = vecTarget; vecTarget.z += 24; if (TryMove(vecStepSrc, vecStepTarget, deltatime, true)) { vecTarget = vecStepTarget; return true; } } // if we collide with geometry, try to climb up over it if (trace.m_pEnt && trace.m_pEnt->IsWorld() && GetEnemy() && !bStepMove) { // check our enemy is on the other side of this obstruction Vector vecEnemyDiff = GetEnemy()->GetAbsOrigin() - GetAbsOrigin(); vecEnemyDiff.NormalizeInPlace(); if (vecEnemyDiff.Dot(trace.plane.normal) < 0) { Vector vecClimbSrc = vecSrc; Vector vecClimbTarget = vecSrc; vecClimbTarget.z += GetIdealSpeed() * deltatime * 0.7f; // 70% speed when climbing... if (TryMove(vecClimbSrc, vecClimbTarget, deltatime, true)) { m_bSkipGravity = true; if (asw_debug_simple_alien.GetBool()) Msg("Setting skip grav, moved %f z=%f\n", GetIdealSpeed() * deltatime * 0.7f, vecClimbTarget.z); // 70% speed when climbing... vecTarget = vecClimbTarget; return true; } } } m_MoveFailure.trace = trace; m_MoveFailure.vecStartPos = vecSrc; m_MoveFailure.vecTargetPos = vecTarget; return false; } else if (trace.fraction < 1) // we hit something early, but we did move { // we hit something early m_MoveFailure.trace = trace; m_MoveFailure.vecStartPos = vecSrc; m_MoveFailure.vecTargetPos = vecTarget; vecTarget = trace.endpos; } return true; } void CASW_Simple_Grub::Event_Killed( const CTakeDamageInfo &info ) { CASW_Marine *pMarine = dynamic_cast<CASW_Marine*>(info.GetAttacker()); if (pMarine && pMarine->GetMarineResource()) { pMarine->GetMarineResource()->m_iGrubKills++; } BaseClass::Event_Killed(info); }
25.955621
136
0.651886
[ "geometry", "vector" ]
9cfe08e90a6c23c470d7f2165055be563ce6621c
25,226
cc
C++
src/ui/app_list/views/apps_grid_view.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/ui/app_list/views/apps_grid_view.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/ui/app_list/views/apps_grid_view.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// 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 "ui/app_list/views/apps_grid_view.h" #include <algorithm> #include "ui/app_list/apps_grid_view_delegate.h" #include "ui/app_list/pagination_model.h" #include "ui/app_list/views/app_list_item_view.h" #include "ui/app_list/views/page_switcher.h" #include "ui/app_list/views/pulsing_block_view.h" #include "ui/base/animation/animation.h" #include "ui/base/events/event.h" #include "ui/views/border.h" #include "ui/views/view_model_utils.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/root_window.h" #endif namespace { // Padding space in pixels for fixed layout. const int kLeftRightPadding = 20; const int kTopPadding = 1; // Padding space in pixels between pages. const int kPagePadding = 40; // Preferred tile size when showing in fixed layout. const int kPreferredTileWidth = 88; const int kPreferredTileHeight = 98; // Width in pixels of the area on the sides that triggers a page flip. const int kPageFlipZoneSize = 40; // Delay in milliseconds to do the page flip. const int kPageFlipDelayInMs = 1000; // How many pages on either side of the selected one we prerender. const int kPrerenderPages = 1; // RowMoveAnimationDelegate is used when moving an item into a different row. // Before running the animation, the item's layer is re-created and kept in // the original position, then the item is moved to just before its target // position and opacity set to 0. When the animation runs, this delegate moves // the layer and fades it out while fading in the item at the same time. class RowMoveAnimationDelegate : public views::BoundsAnimator::OwnedAnimationDelegate { public: RowMoveAnimationDelegate(views::View* view, ui::Layer* layer, const gfx::Rect& layer_target) : view_(view), layer_(layer), layer_start_(layer ? layer->bounds() : gfx::Rect()), layer_target_(layer_target) { } virtual ~RowMoveAnimationDelegate() {} // ui::AnimationDelegate overrides: virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(animation->GetCurrentValue()); view_->layer()->ScheduleDraw(); if (layer_) { layer_->SetOpacity(1 - animation->GetCurrentValue()); layer_->SetBounds(animation->CurrentValueBetween(layer_start_, layer_target_)); layer_->ScheduleDraw(); } } virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(1.0f); view_->layer()->ScheduleDraw(); } virtual void AnimationCanceled(const ui::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(1.0f); view_->layer()->ScheduleDraw(); } private: // The view that needs to be wrapped. Owned by views hierarchy. views::View* view_; scoped_ptr<ui::Layer> layer_; const gfx::Rect layer_start_; const gfx::Rect layer_target_; DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate); }; } // namespace namespace app_list { AppsGridView::AppsGridView(AppsGridViewDelegate* delegate, PaginationModel* pagination_model) : model_(NULL), delegate_(delegate), pagination_model_(pagination_model), page_switcher_view_(new PageSwitcher(pagination_model)), cols_(0), rows_per_page_(0), selected_view_(NULL), drag_view_(NULL), drag_pointer_(NONE), page_flip_target_(-1), page_flip_delay_in_ms_(kPageFlipDelayInMs), bounds_animator_(this) { pagination_model_->AddObserver(this); AddChildView(page_switcher_view_); } AppsGridView::~AppsGridView() { if (model_) { model_->RemoveObserver(this); model_->apps()->RemoveObserver(this); } pagination_model_->RemoveObserver(this); } void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) { icon_size_.SetSize(icon_size, icon_size); cols_ = cols; rows_per_page_ = rows_per_page; set_border(views::Border::CreateEmptyBorder(kTopPadding, kLeftRightPadding, 0, kLeftRightPadding)); } void AppsGridView::SetModel(AppListModel* model) { if (model_) { model_->RemoveObserver(this); model_->apps()->RemoveObserver(this); } model_ = model; if (model_) { model_->AddObserver(this); model_->apps()->AddObserver(this); } Update(); } void AppsGridView::SetSelectedView(views::View* view) { if (IsSelectedView(view) || IsDraggedView(view)) return; Index index = GetIndexOfView(view); if (IsValidIndex(index)) SetSelectedItemByIndex(index); } void AppsGridView::ClearSelectedView(views::View* view) { if (view && IsSelectedView(view)) { selected_view_->SchedulePaint(); selected_view_ = NULL; } } bool AppsGridView::IsSelectedView(const views::View* view) const { return selected_view_ == view; } void AppsGridView::EnsureViewVisible(const views::View* view) { if (pagination_model_->has_transition()) return; Index index = GetIndexOfView(view); if (IsValidIndex(index)) pagination_model_->SelectPage(index.page, false); } void AppsGridView::InitiateDrag(views::View* view, Pointer pointer, const ui::LocatedEvent& event) { if (drag_view_ || pulsing_blocks_model_.view_size()) return; drag_view_ = view; drag_start_ = event.location(); } void AppsGridView::UpdateDrag(views::View* view, Pointer pointer, const ui::LocatedEvent& event) { if (!dragging() && drag_view_ && ExceededDragThreshold(event.location() - drag_start_)) { drag_pointer_ = pointer; // Move the view to the front so that it appears on top of other views. ReorderChildView(drag_view_, -1); bounds_animator_.StopAnimatingView(drag_view_); } if (drag_pointer_ != pointer) return; ExtractDragLocation(event, &last_drag_point_); const Index last_drop_target = drop_target_; CalculateDropTarget(last_drag_point_, false); MaybeStartPageFlipTimer(last_drag_point_); gfx::Point page_switcher_point(last_drag_point_); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); page_switcher_view_->UpdateUIForDragPoint(page_switcher_point); if (last_drop_target != drop_target_) AnimateToIdealBounds(); drag_view_->SetPosition( gfx::PointAtOffsetFromOrigin(last_drag_point_ - drag_start_)); } void AppsGridView::EndDrag(bool cancel) { if (!cancel && dragging() && drag_view_) { CalculateDropTarget(last_drag_point_, true); if (IsValidIndex(drop_target_)) MoveItemInModel(drag_view_, drop_target_); } drag_pointer_ = NONE; drop_target_ = Index(); if (drag_view_) { drag_view_ = NULL; AnimateToIdealBounds(); } page_flip_timer_.Stop(); page_flip_target_ = -1; } bool AppsGridView::IsDraggedView(const views::View* view) const { return drag_view_ == view; } void AppsGridView::Prerender(int page_index) { Layout(); int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page()); int end = std::min(view_model_.view_size(), (page_index + 1 + kPrerenderPages) * tiles_per_page()); for (int i = start; i < end; i++) { AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i)); v->Prerender(); } } gfx::Size AppsGridView::GetPreferredSize() { const gfx::Insets insets(GetInsets()); const gfx::Size tile_size = gfx::Size(kPreferredTileWidth, kPreferredTileHeight); const int page_switcher_height = page_switcher_view_->GetPreferredSize().height(); return gfx::Size( tile_size.width() * cols_ + insets.width(), tile_size.height() * rows_per_page_ + page_switcher_height + insets.height()); } void AppsGridView::Layout() { if (bounds_animator_.IsAnimating()) bounds_animator_.Cancel(); CalculateIdealBounds(); for (int i = 0; i < view_model_.view_size(); ++i) { views::View* view = view_model_.view_at(i); if (view != drag_view_) view->SetBoundsRect(view_model_.ideal_bounds(i)); } views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_); const int page_switcher_height = page_switcher_view_->GetPreferredSize().height(); gfx::Rect rect(GetContentsBounds()); rect.set_y(rect.bottom() - page_switcher_height); rect.set_height(page_switcher_height); page_switcher_view_->SetBoundsRect(rect); } bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) { bool handled = false; if (selected_view_) handled = selected_view_->OnKeyPressed(event); if (!handled) { switch (event.key_code()) { case ui::VKEY_LEFT: MoveSelected(0, -1); return true; case ui::VKEY_RIGHT: MoveSelected(0, 1); return true; case ui::VKEY_UP: MoveSelected(0, -cols_); return true; case ui::VKEY_DOWN: MoveSelected(0, cols_); return true; case ui::VKEY_PRIOR: { MoveSelected(-1, 0); return true; } case ui::VKEY_NEXT: { MoveSelected(1, 0); return true; } default: break; } } return handled; } bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) { bool handled = false; if (selected_view_) handled = selected_view_->OnKeyReleased(event); return handled; } void AppsGridView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (!is_add && parent == this) { if (selected_view_ == child) selected_view_ = NULL; if (drag_view_ == child) EndDrag(true); bounds_animator_.StopAnimatingView(child); } } void AppsGridView::Update() { DCHECK(!selected_view_ && !drag_view_); view_model_.Clear(); if (model_ && model_->apps()->item_count()) ListItemsAdded(0, model_->apps()->item_count()); } void AppsGridView::UpdatePaging() { if (!view_model_.view_size() || !tiles_per_page()) { pagination_model_->SetTotalPages(0); return; } pagination_model_->SetTotalPages( (view_model_.view_size() - 1) / tiles_per_page() + 1); } void AppsGridView::UpdatePulsingBlockViews() { const int available_slots = tiles_per_page() - model_->apps()->item_count() % tiles_per_page(); const int desired = model_->status() == AppListModel::STATUS_SYNCING ? available_slots : 0; if (pulsing_blocks_model_.view_size() == desired) return; while (pulsing_blocks_model_.view_size() > desired) { views::View* view = pulsing_blocks_model_.view_at(0); pulsing_blocks_model_.Remove(0); delete view; } while (pulsing_blocks_model_.view_size() < desired) { views::View* view = new PulsingBlockView( gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true); pulsing_blocks_model_.Add(view, 0); AddChildView(view); } } views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) { DCHECK_LT(index, model_->apps()->item_count()); AppListItemView* view = new AppListItemView(this, model_->apps()->GetItemAt(index)); view->SetIconSize(icon_size_); #if defined(USE_AURA) view->SetPaintToLayer(true); view->SetFillsBoundsOpaquely(false); #endif return view; } void AppsGridView::SetSelectedItemByIndex(const Index& index) { if (GetIndexOfView(selected_view_) == index) return; views::View* new_selection = GetViewAtIndex(index); if (!new_selection) return; // Keep current selection. if (selected_view_) selected_view_->SchedulePaint(); EnsureViewVisible(new_selection); selected_view_ = new_selection; selected_view_->SchedulePaint(); selected_view_->NotifyAccessibilityEvent( ui::AccessibilityTypes::EVENT_FOCUS, true); } bool AppsGridView::IsValidIndex(const Index& index) const { return index.page >= 0 && index.page < pagination_model_->total_pages() && index.slot >= 0 && index.slot < tiles_per_page() && index.page * tiles_per_page() + index.slot < view_model_.view_size(); } AppsGridView::Index AppsGridView::GetIndexOfView( const views::View* view) const { const int model_index = view_model_.GetIndexOfView(view); if (model_index == -1) return Index(); return Index(model_index / tiles_per_page(), model_index % tiles_per_page()); } views::View* AppsGridView::GetViewAtIndex(const Index& index) const { if (!IsValidIndex(index)) return NULL; const int model_index = index.page * tiles_per_page() + index.slot; return view_model_.view_at(model_index); } void AppsGridView::MoveSelected(int page_delta, int slot_delta) { if (!selected_view_) return SetSelectedItemByIndex(Index(pagination_model_->selected_page(), 0)); const Index& selected = GetIndexOfView(selected_view_); int target_slot = selected.slot + slot_delta; if (target_slot < 0) { page_delta += (target_slot + 1) / tiles_per_page() - 1; if (selected.page > 0) target_slot = tiles_per_page() + (target_slot + 1) % tiles_per_page() - 1; } else if (target_slot >= tiles_per_page()) { page_delta += target_slot / tiles_per_page(); if (selected.page < pagination_model_->total_pages() - 1) target_slot %= tiles_per_page(); } int target_page = std::min(pagination_model_->total_pages() - 1, std::max(selected.page + page_delta, 0)); SetSelectedItemByIndex(Index(target_page, target_slot)); } void AppsGridView::CalculateIdealBounds() { gfx::Rect rect(GetContentsBounds()); if (rect.IsEmpty()) return; gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight); gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_, tile_size.height() * rows_per_page_)); grid_rect.Intersect(rect); // Page width including padding pixels. A tile.x + page_width means the same // tile slot in the next page. const int page_width = grid_rect.width() + kPagePadding; // If there is a transition, calculates offset for current and target page. const int current_page = pagination_model_->selected_page(); const PaginationModel::Transition& transition = pagination_model_->transition(); const bool is_valid = pagination_model_->is_valid_page(transition.target_page); // Transition to right means negative offset. const int dir = transition.target_page > current_page ? -1 : 1; const int transition_offset = is_valid ? transition.progress * page_width * dir : 0; const int total_views = view_model_.view_size() + pulsing_blocks_model_.view_size(); int slot_index = 0; for (int i = 0; i < total_views; ++i) { if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) continue; int page = slot_index / tiles_per_page(); int slot = slot_index % tiles_per_page(); if (drop_target_.page == page && drop_target_.slot == slot) { ++slot_index; page = slot_index / tiles_per_page(); slot = slot_index % tiles_per_page(); } // Decides an x_offset for current item. int x_offset = 0; if (page < current_page) x_offset = -page_width; else if (page > current_page) x_offset = page_width; if (is_valid) { if (page == current_page || page == transition.target_page) x_offset += transition_offset; } const int row = slot / cols_; const int col = slot % cols_; gfx::Rect tile_slot( gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset, grid_rect.y() + row * tile_size.height()), tile_size); if (i < view_model_.view_size()) { view_model_.set_ideal_bounds(i, tile_slot); } else { pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(), tile_slot); } ++slot_index; } } void AppsGridView::AnimateToIdealBounds() { const gfx::Rect visible_bounds(GetVisibleBounds()); CalculateIdealBounds(); for (int i = 0; i < view_model_.view_size(); ++i) { views::View* view = view_model_.view_at(i); if (view == drag_view_) continue; const gfx::Rect& target = view_model_.ideal_bounds(i); if (bounds_animator_.GetTargetBounds(view) == target) continue; const gfx::Rect& current = view->bounds(); const bool current_visible = visible_bounds.Intersects(current); const bool target_visible = visible_bounds.Intersects(target); const bool visible = current_visible || target_visible; const int y_diff = target.y() - current.y(); if (visible && y_diff && y_diff % kPreferredTileHeight == 0) { AnimationBetweenRows(view, current_visible, current, target_visible, target); } else { bounds_animator_.AnimateViewTo(view, target); } } } void AppsGridView::AnimationBetweenRows(views::View* view, bool animate_current, const gfx::Rect& current, bool animate_target, const gfx::Rect& target) { // Determine page of |current| and |target|. -1 means in the left invisible // page, 0 is the center visible page and 1 means in the right invisible page. const int current_page = current.x() < 0 ? -1 : current.x() >= width() ? 1 : 0; const int target_page = target.x() < 0 ? -1 : target.x() >= width() ? 1 : 0; const int dir = current_page < target_page || (current_page == target_page && current.y() < target.y()) ? 1 : -1; #if defined(USE_AURA) scoped_ptr<ui::Layer> layer; if (animate_current) { layer.reset(view->RecreateLayer()); layer->SuppressPaint(); view->SetFillsBoundsOpaquely(false); view->layer()->SetOpacity(0.f); } gfx::Rect current_out(current); current_out.Offset(dir * kPreferredTileWidth, 0); #endif gfx::Rect target_in(target); if (animate_target) target_in.Offset(-dir * kPreferredTileWidth, 0); view->SetBoundsRect(target_in); bounds_animator_.AnimateViewTo(view, target); #if defined(USE_AURA) bounds_animator_.SetAnimationDelegate( view, new RowMoveAnimationDelegate(view, layer.release(), current_out), true); #endif } void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event, gfx::Point* drag_point) { #if defined(USE_AURA) // Use root location of |event| instead of location in |drag_view_|'s // coordinates because |drag_view_| has a scale transform and location // could have integer round error and causes jitter. *drag_point = event.root_location(); // GetWidget() could be NULL for tests. if (GetWidget()) { aura::Window::ConvertPointToTarget( GetWidget()->GetNativeWindow()->GetRootWindow(), GetWidget()->GetNativeWindow(), drag_point); } views::View::ConvertPointFromWidget(this, drag_point); #else // For non-aura, root location is not clearly defined but |drag_view_| does // not have the scale transform. So no round error would be introduced and // it's okay to use View::ConvertPointToTarget. *drag_point = event.location(); views::View::ConvertPointToTarget(drag_view_, this, drag_point); #endif } void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point, bool use_page_button_hovering) { const int current_page = pagination_model_->selected_page(); if (use_page_button_hovering && page_switcher_view_->bounds().Contains(drag_point)) { gfx::Point page_switcher_point(drag_point); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); int page = page_switcher_view_->GetPageForPoint(page_switcher_point); if (pagination_model_->is_valid_page(page)) { drop_target_.page = page; drop_target_.slot = tiles_per_page() - 1; } } else { const int drop_row = drag_point.y() / kPreferredTileHeight; const int drop_col = std::min(cols_ - 1, drag_point.x() / kPreferredTileWidth); drop_target_.page = current_page; drop_target_.slot = std::max(0, std::min( tiles_per_page() - 1, drop_row * cols_ + drop_col)); } // Limits to the last possible slot on last page. if (drop_target_.page == pagination_model_->total_pages() - 1) { drop_target_.slot = std::min( (view_model_.view_size() - 1) % tiles_per_page(), drop_target_.slot); } } void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) { int new_page_flip_target = -1; if (page_switcher_view_->bounds().Contains(drag_point)) { gfx::Point page_switcher_point(drag_point); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); new_page_flip_target = page_switcher_view_->GetPageForPoint(page_switcher_point); } // TODO(xiyuan): Fix this for RTL. if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize) new_page_flip_target = pagination_model_->selected_page() - 1; if (new_page_flip_target == -1 && drag_point.x() > width() - kPageFlipZoneSize) { new_page_flip_target = pagination_model_->selected_page() + 1; } if (new_page_flip_target == page_flip_target_) return; if (pagination_model_->is_valid_page(new_page_flip_target)) { page_flip_target_ = new_page_flip_target; page_flip_timer_.Stop(); if (page_flip_target_ != pagination_model_->selected_page()) { page_flip_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_), this, &AppsGridView::OnPageFlipTimer); } } else { page_flip_target_ = -1; page_flip_timer_.Stop(); } } void AppsGridView::OnPageFlipTimer() { DCHECK(pagination_model_->is_valid_page(page_flip_target_)); pagination_model_->SelectPage(page_flip_target_, true); } void AppsGridView::MoveItemInModel(views::View* item_view, const Index& target) { int current_model_index = view_model_.GetIndexOfView(item_view); DCHECK_GE(current_model_index, 0); int target_model_index = target.page * tiles_per_page() + target.slot; if (target_model_index == current_model_index) return; model_->apps()->RemoveObserver(this); model_->apps()->Move(current_model_index, target_model_index); view_model_.Move(current_model_index, target_model_index); model_->apps()->AddObserver(this); if (pagination_model_->selected_page() != target.page) pagination_model_->SelectPage(target.page, false); } void AppsGridView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (dragging()) return; if (sender->GetClassName() != AppListItemView::kViewClassName) return; if (delegate_) { delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->model(), event.flags()); } } void AppsGridView::ListItemsAdded(size_t start, size_t count) { EndDrag(true); for (size_t i = start; i < start + count; ++i) { views::View* view = CreateViewForItemAtIndex(i); view_model_.Add(view, i); AddChildView(view); } UpdatePaging(); UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::ListItemsRemoved(size_t start, size_t count) { EndDrag(true); for (size_t i = 0; i < count; ++i) { views::View* view = view_model_.view_at(start); view_model_.Remove(start); delete view; } UpdatePaging(); UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::ListItemMoved(size_t index, size_t target_index) { EndDrag(true); view_model_.Move(index, target_index); UpdatePaging(); AnimateToIdealBounds(); } void AppsGridView::ListItemsChanged(size_t start, size_t count) { NOTREACHED(); } void AppsGridView::TotalPagesChanged() { } void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) { if (dragging()) { CalculateDropTarget(last_drag_point_, true); Layout(); MaybeStartPageFlipTimer(last_drag_point_); } else { ClearSelectedView(selected_view_); Layout(); } } void AppsGridView::TransitionChanged() { // Update layout for valid page transition only since over-scroll no longer // animates app icons. const PaginationModel::Transition& transition = pagination_model_->transition(); if (pagination_model_->is_valid_page(transition.target_page)) Layout(); } void AppsGridView::OnAppListModelStatusChanged() { UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } } // namespace app_list
31.181706
80
0.670974
[ "model", "transform" ]
9cfe1916a4a442f65bac0c9060880f30f432e4eb
24,945
inl
C++
dev/Code/CryEngine/RenderDll/XRenderD3D9/DeviceManager/DeviceManager_D3D11.inl
raghnarx/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Code/CryEngine/RenderDll/XRenderD3D9/DeviceManager/DeviceManager_D3D11.inl
29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
null
null
null
dev/Code/CryEngine/RenderDll/XRenderD3D9/DeviceManager/DeviceManager_D3D11.inl
29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard
1c52b941dcb7d94341fcf21275fe71ff67173ada
[ "AML" ]
4
2019-08-05T07:25:46.000Z
2020-12-07T05:12:55.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution(the "License").All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file.Do not * remove or modify any license notices.This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. //============================================================================= #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION #define DEVICEMANAGER_D3D11_INL_SECTION_1 1 #define DEVICEMANAGER_D3D11_INL_SECTION_2 2 #define DEVICEMANAGER_D3D11_INL_SECTION_3 3 #define DEVICEMANAGER_D3D11_INL_SECTION_4 4 #define DEVICEMANAGER_D3D11_INL_SECTION_5 5 #define DEVICEMANAGER_D3D11_INL_SECTION_6 6 #define DEVICEMANAGER_D3D11_INL_SECTION_7 7 #define DEVICEMANAGER_D3D11_INL_SECTION_8 8 #endif #ifdef DEVMAN_USE_STAGING_POOL D3DResource* CDeviceManager::AllocateStagingResource(D3DResource* pForTex, bool bUpload) { D3D11_TEXTURE2D_DESC Desc; memset(&Desc, 0, sizeof(Desc)); ((D3DTexture*)pForTex)->GetDesc(&Desc); Desc.Usage = bUpload ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_STAGING; Desc.CPUAccessFlags = bUpload ? D3D11_CPU_ACCESS_WRITE : D3D11_CPU_ACCESS_READ; Desc.BindFlags = bUpload ? D3D11_BIND_SHADER_RESOURCE : 0; #if defined(AZ_PLATFORM_APPLE_OSX) // For metal when we do a subresource copy we render to the texture so need to set the render target flag Desc.BindFlags |= D3D11_BIND_RENDER_TARGET; //todo: Remove this for mac too #endif // BindFlags play a part in matching the descriptions. Only search after we have finished // modifying the description. StagingPoolVec::iterator it = std::find(m_stagingPool.begin(), m_stagingPool.end(), Desc); if (it == m_stagingPool.end()) { D3DTexture* pStagingTexture = NULL; gcpRendD3D->GetDevice().CreateTexture2D(&Desc, NULL, &pStagingTexture); #ifndef _RELEASE if (pStagingTexture) { D3D11_TEXTURE2D_DESC stagingDesc; memset(&stagingDesc, 0, sizeof(stagingDesc)); pStagingTexture->GetDesc(&stagingDesc); stagingDesc.Usage = bUpload ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_STAGING; stagingDesc.CPUAccessFlags = bUpload ? D3D11_CPU_ACCESS_WRITE : D3D11_CPU_ACCESS_READ; stagingDesc.BindFlags = bUpload ? D3D11_BIND_SHADER_RESOURCE : 0; #if defined(AZ_PLATFORM_APPLE_OSX) // For metal when we do a subresource copy we render to the texture so need to set the render target flag stagingDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; //todo: Remove this for mac too #endif if (memcmp(&stagingDesc, &Desc, sizeof(Desc)) != 0) { __debugbreak(); } } #endif return pStagingTexture; } else { D3DTexture* pStagingResource = NULL; pStagingResource = it->pStagingTexture; m_stagingPool.erase(it); return pStagingResource; } } void CDeviceManager::ReleaseStagingResource(D3DResource* pStagingRes) { D3D11_TEXTURE2D_DESC Desc; memset(&Desc, 0, sizeof(Desc)); ((D3DTexture*)pStagingRes)->GetDesc(&Desc); StagingTextureDef def; def.desc = Desc; def.pStagingTexture = (D3DTexture*)pStagingRes; m_stagingPool.push_back(def); } #endif //============================================================================= int32 CDeviceTexture::Release() { int32 nRef = Cleanup(); if (nRef <= 0 && !m_bNoDelete) { delete this; } return nRef; } void CDeviceTexture::Unbind() { for (uint32 i = 0; i < MAX_TMU; i++) { if (CTexture::s_TexStages[i].m_DevTexture == this) { CTexture::s_TexStages[i].m_DevTexture = NULL; ID3D11ShaderResourceView* RV = NULL; gcpRendD3D->GetDeviceContext().PSSetShaderResources(i, 1, &RV); } } } void CDeviceTexture::DownloadToStagingResource(uint32 nSubRes, StagingHook cbTransfer) { D3DResource* pStagingResource; if (!(pStagingResource = m_pStagingResource[0])) { pStagingResource = gcpRendD3D->m_DevMan.AllocateStagingResource(m_pD3DTexture, FALSE); } assert(pStagingResource); #if defined(DEVICE_SUPPORTS_D3D11_1) gcpRendD3D->GetDeviceContext().CopySubresourceRegion1(pStagingResource, nSubRes, 0, 0, 0, m_pD3DTexture, nSubRes, NULL, D3D11_COPY_NO_OVERWRITE); #else gcpRendD3D->GetDeviceContext().CopySubresourceRegion (pStagingResource, nSubRes, 0, 0, 0, m_pD3DTexture, nSubRes, NULL); #endif D3D11_MAPPED_SUBRESOURCE lrct; HRESULT hr = gcpRendD3D->GetDeviceContext().Map(pStagingResource, nSubRes, D3D11_MAP_READ, 0, &lrct); if (S_OK == hr) { const bool update = cbTransfer(lrct.pData, lrct.RowPitch, lrct.DepthPitch); gcpRendD3D->GetDeviceContext().Unmap(pStagingResource, nSubRes); } if (!(m_pStagingResource[0])) { gcpRendD3D->m_DevMan.ReleaseStagingResource(pStagingResource); } } void CDeviceTexture::DownloadToStagingResource(uint32 nSubRes) { assert(m_pStagingResource[0]); #if defined(DEVICE_SUPPORTS_D3D11_1) gcpRendD3D->GetDeviceContext().CopySubresourceRegion1(m_pStagingResource[0], nSubRes, 0, 0, 0, m_pD3DTexture, nSubRes, NULL, D3D11_COPY_NO_OVERWRITE); #else gcpRendD3D->GetDeviceContext().CopySubresourceRegion (m_pStagingResource[0], nSubRes, 0, 0, 0, m_pD3DTexture, nSubRes, NULL); #endif } void CDeviceTexture::UploadFromStagingResource(const uint32 nSubRes, StagingHook cbTransfer) { D3DResource* pStagingResource; if (!(pStagingResource = m_pStagingResource[1])) { pStagingResource = gcpRendD3D->m_DevMan.AllocateStagingResource(m_pD3DTexture, TRUE); } assert(pStagingResource); D3D11_MAPPED_SUBRESOURCE lrct; HRESULT hr = gcpRendD3D->GetDeviceContext().Map(pStagingResource, nSubRes, D3D11_MAP_WRITE_DISCARD, 0, &lrct); if (S_OK == hr) { const bool update = cbTransfer(lrct.pData, lrct.RowPitch, lrct.DepthPitch); gcpRendD3D->GetDeviceContext().Unmap(pStagingResource, 0); if (update) { #if defined(DEVICE_SUPPORTS_D3D11_1) gcpRendD3D->GetDeviceContext().CopySubresourceRegion1(m_pD3DTexture, nSubRes, 0, 0, 0, pStagingResource, nSubRes, NULL, D3D11_COPY_NO_OVERWRITE); #else gcpRendD3D->GetDeviceContext().CopySubresourceRegion (m_pD3DTexture, nSubRes, 0, 0, 0, pStagingResource, nSubRes, NULL); #endif } } if (!(m_pStagingResource[1])) { gcpRendD3D->m_DevMan.ReleaseStagingResource(pStagingResource); } } void CDeviceTexture::UploadFromStagingResource(const uint32 nSubRes) { assert(m_pStagingResource[1]); #if defined(DEVICE_SUPPORTS_D3D11_1) gcpRendD3D->GetDeviceContext().CopySubresourceRegion1(m_pD3DTexture, nSubRes, 0, 0, 0, m_pStagingResource[1], nSubRes, NULL, D3D11_COPY_NO_OVERWRITE); #else gcpRendD3D->GetDeviceContext().CopySubresourceRegion (m_pD3DTexture, nSubRes, 0, 0, 0, m_pStagingResource[1], nSubRes, NULL); #endif } void CDeviceTexture::AccessCurrStagingResource(uint32 nSubRes, bool forUpload, StagingHook cbTransfer) { D3D11_MAPPED_SUBRESOURCE lrct; HRESULT hr = gcpRendD3D->GetDeviceContext().Map(m_pStagingResource[forUpload], nSubRes, forUpload ? D3D11_MAP_WRITE : D3D11_MAP_READ, 0, &lrct); if (S_OK == hr) { const bool update = cbTransfer(lrct.pData, lrct.RowPitch, lrct.DepthPitch); gcpRendD3D->GetDeviceContext().Unmap(m_pStagingResource[forUpload], nSubRes); } } //============================================================================= HRESULT CDeviceManager::Create2DTexture(const string& textureName, uint32 nWidth, uint32 nHeight, uint32 nMips, uint32 nArraySize, uint32 nUsage, const ColorF& cClearValue, D3DFormat Format, D3DPOOL Pool, LPDEVICETEXTURE* ppDevTexture, STextureInfo* pTI, bool bShouldBeCreated, int32 nESRAMOffset) { HRESULT hr = S_OK; CDeviceTexture* pDeviceTexture = 0;//*/ new CDeviceTexture(); D3DTexture* pD3DTex = NULL; uint32 nBindFlags = D3D11_BIND_SHADER_RESOURCE; if (nUsage & USAGE_DEPTH_STENCIL) { nBindFlags |= D3D11_BIND_DEPTH_STENCIL; } else if (nUsage & USAGE_RENDER_TARGET) { nBindFlags |= D3D11_BIND_RENDER_TARGET; } #if defined(AZ_PLATFORM_APPLE_IOS) if (nUsage & USAGE_MEMORYLESS) { nBindFlags |= D3D11_BIND_MEMORYLESS; } #endif if (nUsage & USAGE_UNORDERED_ACCESS) { nBindFlags |= D3D11_BIND_UNORDERED_ACCESS; } uint32 nMiscFlags = 0; if (nUsage & USAGE_AUTOGENMIPS) { nMiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; } D3D11_TEXTURE2D_DESC Desc; ZeroStruct(Desc); Desc.Width = nWidth; Desc.Height = nHeight; Desc.MipLevels = nMips; Desc.Format = Format; Desc.ArraySize = nArraySize; Desc.BindFlags = nBindFlags; Desc.CPUAccessFlags = (nUsage & USAGE_DYNAMIC) ? D3D11_CPU_ACCESS_WRITE : 0; Desc.Usage = (nUsage & USAGE_DYNAMIC) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; Desc.Usage = (nUsage & USAGE_STAGING) ? D3D11_USAGE_STAGING : Desc.Usage; Desc.SampleDesc.Count = pTI ? pTI->m_nMSAASamples : 1; Desc.SampleDesc.Quality = pTI ? pTI->m_nMSAAQuality : 0; // AntonK: supported only by DX11 feature set // needs to be enabled for pure DX11 context if (nUsage & USAGE_STREAMING) { nMiscFlags |= D3D11_RESOURCE_MISC_RESOURCE_CLAMP; } //if (nUsage & USAGE_STREAMING) // Desc.CPUAccessFlags |= D3D11_CPU_ACCESS_READ; Desc.MiscFlags = nMiscFlags; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_1 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif D3D11_SUBRESOURCE_DATA* pSRD = NULL; D3D11_SUBRESOURCE_DATA SRD[20]; if (pTI && pTI->m_pData) { pSRD = &SRD[0]; for (int i = 0; i < nMips; i++) { SRD[i].pSysMem = pTI->m_pData[i].pSysMem; SRD[i].SysMemPitch = pTI->m_pData[i].SysMemPitch; SRD[i].SysMemSlicePitch = pTI->m_pData[i].SysMemSlicePitch; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_2 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif } } #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_3 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif hr = gcpRendD3D->GetDevice().CreateTexture2D(&Desc, pSRD, &pD3DTex); if (SUCCEEDED(hr) && pDeviceTexture == 0) { pDeviceTexture = new CDeviceTexture(); } if (SUCCEEDED(hr) && pD3DTex) { pDeviceTexture->m_pD3DTexture = pD3DTex; if (!pDeviceTexture->m_nBaseAllocatedSize) { pDeviceTexture->m_nBaseAllocatedSize = CDeviceTexture::TextureDataSize(nWidth, nHeight, 1, nMips, 1, CTexture::TexFormatFromDeviceFormat(Format)); // Register the VRAM allocation with the driller pDeviceTexture->TrackTextureMemory(nUsage, textureName.c_str()); } if (nUsage & USAGE_STAGE_ACCESS) { if (nUsage & USAGE_CPU_READ) { pDeviceTexture->m_pStagingResource[0] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, FALSE); } if (nUsage & USAGE_CPU_WRITE) { pDeviceTexture->m_pStagingResource[1] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, TRUE); } } } else { SAFE_DELETE(pDeviceTexture); } *ppDevTexture = pDeviceTexture; return hr; } HRESULT CDeviceManager::CreateCubeTexture(const string& textureName, uint32 nSize, uint32 nMips, uint32 nArraySize, uint32 nUsage, const ColorF& cClearValue, D3DFormat Format, D3DPOOL Pool, LPDEVICETEXTURE* ppDevTexture, STextureInfo* pTI, bool bShouldBeCreated) { HRESULT hr = S_OK; CDeviceTexture* pDeviceTexture = 0;//new CDeviceTexture(); D3DCubeTexture* pD3DTex = NULL; uint32 nBindFlags = D3D11_BIND_SHADER_RESOURCE; uint32 nMiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; if (nUsage & USAGE_DEPTH_STENCIL) { nBindFlags |= D3D11_BIND_DEPTH_STENCIL; } else if (nUsage & USAGE_RENDER_TARGET) { nBindFlags |= D3D11_BIND_RENDER_TARGET; } #if defined(AZ_PLATFORM_APPLE_IOS) if (nUsage & USAGE_MEMORYLESS) { nBindFlags |= D3D11_BIND_MEMORYLESS; } #endif if (nUsage & USAGE_AUTOGENMIPS) { nMiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; } D3D11_TEXTURE2D_DESC Desc; ZeroStruct(Desc); Desc.Width = nSize; Desc.Height = nSize; Desc.MipLevels = nMips; Desc.Format = Format; Desc.ArraySize = nArraySize * 6; Desc.BindFlags |= nBindFlags; Desc.CPUAccessFlags = (nUsage & USAGE_DYNAMIC) ? D3D11_CPU_ACCESS_WRITE : 0; Desc.Usage = (nUsage & USAGE_DYNAMIC) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; Desc.SampleDesc.Count = 1; Desc.SampleDesc.Quality = 0; Desc.MiscFlags = nMiscFlags; // AntonK: supported only by DX11 feature set // needs to be enabled for pure DX11 context //if(nUsage & USAGE_STREAMING) //Desc.MiscFlags |= D3D11_RESOURCE_MISC_RESOURCE_CLAMP; D3D11_SUBRESOURCE_DATA* pSRD = NULL; D3D11_SUBRESOURCE_DATA SRD[g_nD3D10MaxSupportedSubres]; if (pTI && pTI->m_pData) { pSRD = &SRD[0]; for (int j = 0; j < 6; j++) { for (int i = 0; i < nMips; i++) { int nSubresInd = j * nMips + i; SRD[nSubresInd].pSysMem = pTI->m_pData[nSubresInd].pSysMem; SRD[nSubresInd].SysMemPitch = pTI->m_pData[nSubresInd].SysMemPitch; SRD[nSubresInd].SysMemSlicePitch = pTI->m_pData[nSubresInd].SysMemSlicePitch; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_4 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif } } } #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_5 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif hr = gcpRendD3D->GetDevice().CreateTexture2D(&Desc, pSRD, &pD3DTex); if (SUCCEEDED(hr) && pDeviceTexture == 0) { pDeviceTexture = new CDeviceTexture(); } if (SUCCEEDED(hr) && pD3DTex) { pDeviceTexture->m_pD3DTexture = pD3DTex; pDeviceTexture->m_bCube = true; if (!pDeviceTexture->m_nBaseAllocatedSize) { pDeviceTexture->m_nBaseAllocatedSize = CDeviceTexture::TextureDataSize(nSize, nSize, 1, nMips, 1, CTexture::TexFormatFromDeviceFormat(Format)) * 6; // Register the VRAM allocation with the driller pDeviceTexture->TrackTextureMemory(nUsage, textureName.c_str()); } if (nUsage & USAGE_STAGE_ACCESS) { if (nUsage & USAGE_CPU_READ) { pDeviceTexture->m_pStagingResource[0] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, FALSE); } if (nUsage & USAGE_CPU_WRITE) { pDeviceTexture->m_pStagingResource[1] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, TRUE); } } } else { SAFE_DELETE(pDeviceTexture); } *ppDevTexture = pDeviceTexture; return hr; } HRESULT CDeviceManager::CreateVolumeTexture(const string& textureName, uint32 nWidth, uint32 nHeight, uint32 nDepth, uint32 nMips, uint32 nUsage, const ColorF& cClearValue, D3DFormat Format, D3DPOOL Pool, LPDEVICETEXTURE* ppDevTexture, STextureInfo* pTI) { HRESULT hr = S_OK; CDeviceTexture* pDeviceTexture = new CDeviceTexture(); D3DVolumeTexture* pD3DTex = NULL; uint32 nBindFlags = D3D11_BIND_SHADER_RESOURCE; if (nUsage & USAGE_DEPTH_STENCIL) { nBindFlags |= D3D11_BIND_DEPTH_STENCIL; } else if (nUsage & USAGE_RENDER_TARGET) { nBindFlags |= D3D11_BIND_RENDER_TARGET; } #if defined(AZ_PLATFORM_APPLE_IOS) if (nUsage & USAGE_MEMORYLESS) { nBindFlags |= D3D11_BIND_MEMORYLESS; } #endif if (nUsage & USAGE_UNORDERED_ACCESS) { nBindFlags |= D3D11_BIND_UNORDERED_ACCESS; } D3D11_TEXTURE3D_DESC Desc; ZeroStruct(Desc); Desc.Width = nWidth; Desc.Height = nHeight; Desc.Depth = nDepth; Desc.MipLevels = nMips; Desc.Format = (nUsage & USAGE_UAV_RWTEXTURE) ? CTexture::ConvertToTypelessFmt(Format) : Format; Desc.BindFlags = nBindFlags; Desc.CPUAccessFlags = 0; Desc.Usage = (nUsage & USAGE_DYNAMIC) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; Desc.Usage = (nUsage & USAGE_STAGING) ? D3D11_USAGE_STAGING : Desc.Usage; Desc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA* pSRD = NULL; D3D11_SUBRESOURCE_DATA SRD[20] = { D3D11_SUBRESOURCE_DATA() }; if (pTI && pTI->m_pData) { pSRD = &SRD[0]; for (int i = 0; i < nMips; i++) { SRD[i].pSysMem = pTI->m_pData[i].pSysMem; SRD[i].SysMemPitch = pTI->m_pData[i].SysMemPitch; SRD[i].SysMemSlicePitch = pTI->m_pData[i].SysMemSlicePitch; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_6 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif } } hr = gcpRendD3D->GetDevice().CreateTexture3D(&Desc, pSRD, &pD3DTex); if (SUCCEEDED(hr) && pD3DTex) { pDeviceTexture->m_pD3DTexture = pD3DTex; if (!pDeviceTexture->m_nBaseAllocatedSize) { pDeviceTexture->m_nBaseAllocatedSize = CDeviceTexture::TextureDataSize(nWidth, nHeight, nDepth, nMips, 1, CTexture::TexFormatFromDeviceFormat(Format)); // Register the VRAM allocation with the driller pDeviceTexture->TrackTextureMemory(nUsage, textureName.c_str()); } if (nUsage & USAGE_STAGE_ACCESS) { if (nUsage & USAGE_CPU_READ) { pDeviceTexture->m_pStagingResource[0] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, FALSE); } if (nUsage & USAGE_CPU_WRITE) { pDeviceTexture->m_pStagingResource[1] = gcpRendD3D->m_DevMan.AllocateStagingResource(pDeviceTexture->m_pD3DTexture, TRUE); } } } else { SAFE_DELETE(pDeviceTexture); } *ppDevTexture = pDeviceTexture; return hr; } HRESULT CDeviceManager::CreateBuffer( uint32 nSize , uint32 elemSize , int32 nUsage , int32 nBindFlags , D3DBuffer** ppBuff) { FUNCTION_PROFILER(gEnv->pSystem, PROFILE_RENDERER); HRESULT hr = S_OK; # ifndef _RELEASE // ToDo verify that the usage and bindflags are correctly set (e.g certain // bit groups are mutually exclusive). # endif D3D11_BUFFER_DESC BufDesc; ZeroStruct(BufDesc); #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_7 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif #endif BufDesc.ByteWidth = nSize * elemSize; int nD3DUsage = D3D11_USAGE_DEFAULT; nD3DUsage = (nUsage & USAGE_DYNAMIC) ? D3D11_USAGE_DYNAMIC : nD3DUsage; nD3DUsage = (nUsage & USAGE_IMMUTABLE) ? D3D11_USAGE_IMMUTABLE : nD3DUsage; nD3DUsage = (nUsage & USAGE_STAGING) ? D3D11_USAGE_STAGING : nD3DUsage; #if defined(CRY_USE_METAL) nD3DUsage = (nUsage & USAGE_TRANSIENT) ? D3D11_USAGE_TRANSIENT : nD3DUsage; #if BUFFER_USE_STAGED_UPDATES == 0 // Igor: direct access usage is allowed only if staged updates logic is off. CRY_ASSERT(!(nUsage & USAGE_DIRECT_ACCESS) || !(nUsage & USAGE_STAGING)); nD3DUsage = (nUsage & USAGE_DIRECT_ACCESS) ? D3D11_USAGE_DIRECT_ACCESS : nD3DUsage; if ((nUsage & USAGE_DIRECT_ACCESS) && (nUsage & USAGE_STAGING)) { CryFatalError("staging buffers not supported if BUFFER_USE_STAGED_UPDATES not defined"); } #endif // BUFFER_USE_STAGED_UPDATES == 0 #endif // CRY_USE_METAL BufDesc.Usage = (D3D11_USAGE)nD3DUsage; # if !defined(OPENGL) if (BufDesc.Usage != D3D11_USAGE_STAGING) # endif { switch (nBindFlags) { case BIND_VERTEX_BUFFER: BufDesc.BindFlags |= D3D11_BIND_VERTEX_BUFFER; break; case BIND_INDEX_BUFFER: BufDesc.BindFlags |= D3D11_BIND_INDEX_BUFFER; break; case BIND_CONSTANT_BUFFER: BufDesc.BindFlags |= D3D11_BIND_CONSTANT_BUFFER; break; case BIND_SHADER_RESOURCE: case BIND_UNORDERED_ACCESS: if (nBindFlags & BIND_SHADER_RESOURCE) { BufDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } if (nBindFlags & BIND_UNORDERED_ACCESS) { BufDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } break; case BIND_STREAM_OUTPUT: case BIND_RENDER_TARGET: case BIND_DEPTH_STENCIL: CryFatalError("trying to create (currently) unsupported buffer type"); break; default: CryFatalError("trying to create unknown buffer type"); break; } } # if !defined(OPENGL) else { BufDesc.BindFlags = 0; } # endif BufDesc.MiscFlags = 0; BufDesc.CPUAccessFlags = 0; if (BufDesc.Usage != D3D11_USAGE_DEFAULT && BufDesc.Usage != D3D11_USAGE_IMMUTABLE) { BufDesc.CPUAccessFlags = (nUsage & USAGE_CPU_WRITE) ? D3D11_CPU_ACCESS_WRITE : 0; BufDesc.CPUAccessFlags |= (nUsage & USAGE_CPU_READ) ? D3D11_CPU_ACCESS_READ : 0; } if (nBindFlags & BIND_UNORDERED_ACCESS) { BufDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; } hr = gcpRendD3D->GetDevice().CreateBuffer(&BufDesc, NULL, ppBuff); CHECK_HRESULT(hr); Render::Debug::VRAMAllocationSubcategory subcategory = Render::Debug::VRAM_SUBCATEGORY_BUFFER_OTHER_BUFFER; if (BufDesc.Usage & D3D11_BIND_VERTEX_BUFFER) { subcategory = Render::Debug::VRAM_SUBCATEGORY_BUFFER_VERTEX_BUFFER; } else if (BufDesc.Usage & D3D11_BIND_INDEX_BUFFER) { subcategory = Render::Debug::VRAM_SUBCATEGORY_BUFFER_INDEX_BUFFER; } else if (BufDesc.Usage & D3D11_BIND_CONSTANT_BUFFER) { subcategory = Render::Debug::VRAM_SUBCATEGORY_BUFFER_CONSTANT_BUFFER; } void* address = static_cast<void*>(*ppBuff); size_t byteSize = BufDesc.ByteWidth; EBUS_EVENT(Render::Debug::VRAMDrillerBus, RegisterAllocation, address, byteSize, "CDeviceManager::CreateBuffer", Render::Debug::VRAM_CATEGORY_BUFFER, subcategory); return hr; } void CDeviceManager::ExtractBasePointer(D3DBuffer* buffer, uint8*& base_ptr) { // Confetti BEGIN: Igor Lobanchikov #if defined(CRY_USE_METAL) && (BUFFER_USE_STAGED_UPDATES == 0) base_ptr = (uint8*)DXMETALGetBufferStorage(buffer); #else # if BUFFER_ENABLE_DIRECT_ACCESS #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION DEVICEMANAGER_D3D11_INL_SECTION_8 #if defined(AZ_PLATFORM_XENIA) #include "Xenia/DeviceManager_D3D11_inl_xenia.inl" #elif defined(AZ_PLATFORM_PROVO) #include "Provo/DeviceManager_D3D11_inl_provo.inl" #endif # endif # else base_ptr = NULL; # endif #endif // Confetti End: Igor Lobanchikov }
33.438338
262
0.679936
[ "render" ]
14065e009e938c5f2eab935911c3d9868f938118
1,049
cpp
C++
leetcode-problems/medium/253-meeting-room-ii.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/253-meeting-room-ii.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/253-meeting-room-ii.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
// // Created by Siddhant on 2019-11-13. // #include "iostream" #include "vector" #include "string" #include "algorithm" #include <queue> using namespace std; int minMeetingRooms(vector<vector<int>> &intervals) { //sort sort(intervals.begin(), intervals.end(), [](const std::vector<int> &a, const std::vector<int> &b) { return a[1] < b[1]; }); // divide in rooms priority_queue<int, std::vector<int>, greater<int> > min_heap; for (int i = 0; i < intervals.size(); ++i) { if(min_heap.empty()){ min_heap.push(intervals[i][1]); continue; } int f = min_heap.top(); if(f <= intervals[i][0]){ min_heap.pop(); min_heap.push(intervals[i][1]); }else{ min_heap.push(intervals[i][1]); } } return min_heap.size(); } int main() { vector<vector<int>> v = {{2,15},{36,45},{9,29},{16,23},{4,9}}; cout << "min rooms required : " << minMeetingRooms(v); return 0; }
19.792453
67
0.528122
[ "vector" ]
140e8202c9aaf459a7df334d0db6139513329ee9
37,745
cpp
C++
src/zoinode.cpp
flo071/zoin-1
88b479f42c9ecc368dc3dab19b3acf3154e5816b
[ "MIT" ]
2
2020-01-06T16:53:41.000Z
2020-02-13T17:52:19.000Z
src/zoinode.cpp
flo071/zoin-1
88b479f42c9ecc368dc3dab19b3acf3154e5816b
[ "MIT" ]
null
null
null
src/zoinode.cpp
flo071/zoin-1
88b479f42c9ecc368dc3dab19b3acf3154e5816b
[ "MIT" ]
1
2018-11-04T17:53:47.000Z
2018-11-04T17:53:47.000Z
// Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activezoinode.h" #include "consensus/validation.h" #include "darksend.h" #include "init.h" //#include "governance.h" #include "zoinode.h" #include "zoinode-payments.h" #include "zoinode-sync.h" #include "zoinodeman.h" #include "util.h" #include <boost/lexical_cast.hpp> CZoinode::CZoinode() : vin(), addr(), pubKeyCollateralAddress(), pubKeyZoinode(), lastPing(), vchSig(), sigTime(GetAdjustedTime()), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(0), nActiveState(ZOINODE_ENABLED), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(PROTOCOL_VERSION), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} CZoinode::CZoinode(CService addrNew, CTxIn vinNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyZoinodeNew, int nProtocolVersionIn) : vin(vinNew), addr(addrNew), pubKeyCollateralAddress(pubKeyCollateralAddressNew), pubKeyZoinode(pubKeyZoinodeNew), lastPing(), vchSig(), sigTime(GetAdjustedTime()), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(0), nActiveState(ZOINODE_ENABLED), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(nProtocolVersionIn), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} CZoinode::CZoinode(const CZoinode &other) : vin(other.vin), addr(other.addr), pubKeyCollateralAddress(other.pubKeyCollateralAddress), pubKeyZoinode(other.pubKeyZoinode), lastPing(other.lastPing), vchSig(other.vchSig), sigTime(other.sigTime), nLastDsq(other.nLastDsq), nTimeLastChecked(other.nTimeLastChecked), nTimeLastPaid(other.nTimeLastPaid), nTimeLastWatchdogVote(other.nTimeLastWatchdogVote), nActiveState(other.nActiveState), nCacheCollateralBlock(other.nCacheCollateralBlock), nBlockLastPaid(other.nBlockLastPaid), nProtocolVersion(other.nProtocolVersion), nPoSeBanScore(other.nPoSeBanScore), nPoSeBanHeight(other.nPoSeBanHeight), fAllowMixingTx(other.fAllowMixingTx), fUnitTest(other.fUnitTest) {} CZoinode::CZoinode(const CZoinodeBroadcast &mnb) : vin(mnb.vin), addr(mnb.addr), pubKeyCollateralAddress(mnb.pubKeyCollateralAddress), pubKeyZoinode(mnb.pubKeyZoinode), lastPing(mnb.lastPing), vchSig(mnb.vchSig), sigTime(mnb.sigTime), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(mnb.sigTime), nActiveState(mnb.nActiveState), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(mnb.nProtocolVersion), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} //CSporkManager sporkManager; // // When a new zoinode broadcast is sent, update our information // bool CZoinode::UpdateFromNewBroadcast(CZoinodeBroadcast &mnb) { if (mnb.sigTime <= sigTime && !mnb.fRecovery) return false; pubKeyZoinode = mnb.pubKeyZoinode; sigTime = mnb.sigTime; vchSig = mnb.vchSig; nProtocolVersion = mnb.nProtocolVersion; addr = mnb.addr; nPoSeBanScore = 0; nPoSeBanHeight = 0; nTimeLastChecked = 0; int nDos = 0; if (mnb.lastPing == CZoinodePing() || (mnb.lastPing != CZoinodePing() && mnb.lastPing.CheckAndUpdate(this, true, nDos))) { lastPing = mnb.lastPing; mnodeman.mapSeenZoinodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } // if it matches our Zoinode privkey... if (fZoiNode && pubKeyZoinode == activeZoinode.pubKeyZoinode) { nPoSeBanScore = -ZOINODE_POSE_BAN_MAX_SCORE; if (nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... activeZoinode.ManageState(); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from LogPrintf("CZoinode::UpdateFromNewBroadcast -- wrong PROTOCOL_VERSION, re-activate your MN: message nProtocolVersion=%d PROTOCOL_VERSION=%d\n", nProtocolVersion, PROTOCOL_VERSION); return false; } } return true; } // // Deterministically calculate a given "score" for a Zoinode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // arith_uint256 CZoinode::CalculateScore(const uint256 &blockHash) { uint256 aux = ArithToUint256(UintToArith256(vin.prevout.hash) + vin.prevout.n); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << blockHash; arith_uint256 hash2 = UintToArith256(ss.GetHash()); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << blockHash; ss2 << aux; arith_uint256 hash3 = UintToArith256(ss2.GetHash()); return (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); } void CZoinode::Check(bool fForce) { LOCK(cs); if (ShutdownRequested()) return; if (!fForce && (GetTime() - nTimeLastChecked < ZOINODE_CHECK_SECONDS)) return; nTimeLastChecked = GetTime(); LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state\n", vin.prevout.ToStringShort(), GetStateString()); //once spent, stop doing the checks if (IsOutpointSpent()) return; int nHeight = 0; if (!fUnitTest) { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; CCoins coins; if (!pcoinsTip->GetCoins(vin.prevout.hash, coins) || (unsigned int) vin.prevout.n >= coins.vout.size() || coins.vout[vin.prevout.n].IsNull()) { nActiveState = ZOINODE_OUTPOINT_SPENT; LogPrint("zoinode", "CZoinode::Check -- Failed to find Zoinode UTXO, zoinode=%s\n", vin.prevout.ToStringShort()); return; } nHeight = chainActive.Height(); } if (IsPoSeBanned()) { if (nHeight < nPoSeBanHeight) return; // too early? // Otherwise give it a chance to proceed further to do all the usual checks and to change its state. // Zoinode still will be on the edge and can be banned back easily if it keeps ignoring mnverify // or connect attempts. Will require few mnverify messages to strengthen its position in mn list. LogPrintf("CZoinode::Check -- Zoinode %s is unbanned and back in list now\n", vin.prevout.ToStringShort()); DecreasePoSeBanScore(); } else if (nPoSeBanScore >= ZOINODE_POSE_BAN_MAX_SCORE) { nActiveState = ZOINODE_POSE_BAN; // ban for the whole payment cycle nPoSeBanHeight = nHeight + mnodeman.size(); LogPrintf("CZoinode::Check -- Zoinode %s is banned till block %d now\n", vin.prevout.ToStringShort(), nPoSeBanHeight); return; } int nActiveStatePrev = nActiveState; bool fOurZoinode = fZoiNode && activeZoinode.pubKeyZoinode == pubKeyZoinode; // zoinode doesn't meet payment protocol requirements ... bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinZoinodePaymentsProto() || // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... (fOurZoinode && nProtocolVersion < PROTOCOL_VERSION); if (fRequireUpdate) { nActiveState = ZOINODE_UPDATE_REQUIRED; if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } // keep old zoinodes on start, give them a chance to receive updates... bool fWaitForPing = !zoinodeSync.IsZoinodeListSynced() && !IsPingedWithin(ZOINODE_MIN_MNP_SECONDS); if (fWaitForPing && !fOurZoinode) { // ...but if it was already expired before the initial check - return right away if (IsExpired() || IsWatchdogExpired() || IsNewStartRequired()) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state, waiting for ping\n", vin.prevout.ToStringShort(), GetStateString()); return; } } // don't expire if we are still in "waiting for ping" mode unless it's our own zoinode if (!fWaitForPing || fOurZoinode) { if (!IsPingedWithin(ZOINODE_NEW_START_REQUIRED_SECONDS)) { nActiveState = ZOINODE_NEW_START_REQUIRED; if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } bool fWatchdogActive = zoinodeSync.IsSynced() && mnodeman.IsWatchdogActive(); bool fWatchdogExpired = (fWatchdogActive && ((GetTime() - nTimeLastWatchdogVote) > ZOINODE_WATCHDOG_MAX_SECONDS)); // LogPrint("zoinode", "CZoinode::Check -- outpoint=%s, nTimeLastWatchdogVote=%d, GetTime()=%d, fWatchdogExpired=%d\n", // vin.prevout.ToStringShort(), nTimeLastWatchdogVote, GetTime(), fWatchdogExpired); if (fWatchdogExpired) { nActiveState = ZOINODE_WATCHDOG_EXPIRED; if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } if (!IsPingedWithin(ZOINODE_EXPIRATION_SECONDS)) { nActiveState = ZOINODE_EXPIRED; if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } } if (lastPing.sigTime - sigTime < ZOINODE_MIN_MNP_SECONDS) { nActiveState = ZOINODE_PRE_ENABLED; if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } nActiveState = ZOINODE_ENABLED; // OK if (nActiveStatePrev != nActiveState) { LogPrint("zoinode", "CZoinode::Check -- Zoinode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } } bool CZoinode::IsValidNetAddr() { return IsValidNetAddr(addr); } bool CZoinode::IsValidForPayment() { if (nActiveState == ZOINODE_ENABLED) { return true; } // if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) && // (nActiveState == ZOINODE_WATCHDOG_EXPIRED)) { // return true; // } return false; } bool CZoinode::IsValidNetAddr(CService addrIn) { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkIDString() == CBaseChainParams::REGTEST || (addrIn.IsIPv4() && IsReachable(addrIn) && addrIn.IsRoutable()); } zoinode_info_t CZoinode::GetInfo() { zoinode_info_t info; info.vin = vin; info.addr = addr; info.pubKeyCollateralAddress = pubKeyCollateralAddress; info.pubKeyZoinode = pubKeyZoinode; info.sigTime = sigTime; info.nLastDsq = nLastDsq; info.nTimeLastChecked = nTimeLastChecked; info.nTimeLastPaid = nTimeLastPaid; info.nTimeLastWatchdogVote = nTimeLastWatchdogVote; info.nTimeLastPing = lastPing.sigTime; info.nActiveState = nActiveState; info.nProtocolVersion = nProtocolVersion; info.fInfoValid = true; return info; } std::string CZoinode::StateToString(int nStateIn) { switch (nStateIn) { case ZOINODE_PRE_ENABLED: return "PRE_ENABLED"; case ZOINODE_ENABLED: return "ENABLED"; case ZOINODE_EXPIRED: return "EXPIRED"; case ZOINODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case ZOINODE_UPDATE_REQUIRED: return "UPDATE_REQUIRED"; case ZOINODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED"; case ZOINODE_NEW_START_REQUIRED: return "NEW_START_REQUIRED"; case ZOINODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } std::string CZoinode::GetStateString() const { return StateToString(nActiveState); } std::string CZoinode::GetStatus() const { // TODO: return smth a bit more human readable here return GetStateString(); } std::string CZoinode::ToString() const { std::string str; str += "zoinode{"; str += addr.ToString(); str += " "; str += std::to_string(nProtocolVersion); str += " "; str += vin.prevout.ToStringShort(); str += " "; str += CBitcoinAddress(pubKeyCollateralAddress.GetID()).ToString(); str += " "; str += std::to_string(lastPing == CZoinodePing() ? sigTime : lastPing.sigTime); str += " "; str += std::to_string(lastPing == CZoinodePing() ? 0 : lastPing.sigTime - sigTime); str += " "; str += std::to_string(nBlockLastPaid); str += "}\n"; return str; } int CZoinode::GetCollateralAge() { int nHeight; { TRY_LOCK(cs_main, lockMain); if (!lockMain || !chainActive.Tip()) return -1; nHeight = chainActive.Height(); } if (nCacheCollateralBlock == 0) { int nInputAge = GetInputAge(vin); if (nInputAge > 0) { nCacheCollateralBlock = nHeight - nInputAge; } else { return nInputAge; } } return nHeight - nCacheCollateralBlock; } void CZoinode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack) { if (!pindex) { LogPrintf("CZoinode::UpdateLastPaid pindex is NULL\n"); return; } const CBlockIndex *BlockReading = pindex; CScript mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); LogPrint("zoinode", "CZoinode::UpdateLastPaidBlock -- searching for block with payment to %s\n", vin.prevout.ToStringShort()); LOCK(cs_mapZoinodeBlocks); for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) { // LogPrintf("mnpayments.mapZoinodeBlocks.count(BlockReading->nHeight)=%s\n", mnpayments.mapZoinodeBlocks.count(BlockReading->nHeight)); // LogPrintf("mnpayments.mapZoinodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)=%s\n", mnpayments.mapZoinodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)); if (mnpayments.mapZoinodeBlocks.count(BlockReading->nHeight) && mnpayments.mapZoinodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { // LogPrintf("i=%s, BlockReading->nHeight=%s\n", i, BlockReading->nHeight); CBlock block; if (!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) // shouldn't really happen { LogPrintf("ReadBlockFromDisk failed\n"); continue; } CAmount nZoinodePayment = GetZoinodePayment(BlockReading->nHeight, block.vtx[0].GetValueOut()); BOOST_FOREACH(CTxOut txout, block.vtx[0].vout) if (mnpayee == txout.scriptPubKey && nZoinodePayment == txout.nValue) { nBlockLastPaid = BlockReading->nHeight; nTimeLastPaid = BlockReading->nTime; LogPrint("zoinode", "CZoinode::UpdateLastPaidBlock -- searching for block with payment to %s -- found new %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); return; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } // Last payment for this zoinode wasn't found in latest mnpayments blocks // or it was found in mnpayments blocks but wasn't found in the blockchain. // LogPrint("zoinode", "CZoinode::UpdateLastPaidBlock -- searching for block with payment to %s -- keeping old %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); } bool CZoinodeBroadcast::Create(std::string strService, std::string strKeyZoinode, std::string strTxHash, std::string strOutputIndex, std::string &strErrorRet, CZoinodeBroadcast &mnbRet, bool fOffline) { LogPrintf("CZoinodeBroadcast::Create\n"); CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyZoinodeNew; CKey keyZoinodeNew; //need correct blocks to send ping if (!fOffline && !zoinodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Zoinode"; LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); return false; } //TODO if (!darkSendSigner.GetKeysFromSecret(strKeyZoinode, keyZoinodeNew, pubKeyZoinodeNew)) { strErrorRet = strprintf("Invalid zoinode key %s", strKeyZoinode); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!pwalletMain->GetZoinodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for zoinode %s", strTxHash, strOutputIndex, strService); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); return false; } CService service = CService(strService); int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (service.GetPort() != mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for zoinode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); return false; } } else if (service.GetPort() == mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for zoinode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); return false; } return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyZoinodeNew, pubKeyZoinodeNew, strErrorRet, mnbRet); } bool CZoinodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyZoinodeNew, CPubKey pubKeyZoinodeNew, std::string &strErrorRet, CZoinodeBroadcast &mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("zoinode", "CZoinodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyZoinodeNew.GetID() = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyZoinodeNew.GetID().ToString()); CZoinodePing mnp(txin); if (!mnp.Sign(keyZoinodeNew, pubKeyZoinodeNew)) { strErrorRet = strprintf("Failed to sign ping, zoinode=%s", txin.prevout.ToStringShort()); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CZoinodeBroadcast(); return false; } mnbRet = CZoinodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyZoinodeNew, PROTOCOL_VERSION); if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address, zoinode=%s", txin.prevout.ToStringShort()); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CZoinodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, zoinode=%s", txin.prevout.ToStringShort()); LogPrintf("CZoinodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CZoinodeBroadcast(); return false; } return true; } bool CZoinodeBroadcast::SimpleCheck(int &nDos) { nDos = 0; // make sure addr is valid if (!IsValidNetAddr()) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- Invalid addr, rejected: zoinode=%s addr=%s\n", vin.prevout.ToStringShort(), addr.ToString()); return false; } // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- Signature rejected, too far into the future: zoinode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } // empty ping or incorrect sigTime/unknown blockhash if (lastPing == CZoinodePing() || !lastPing.SimpleCheck(nDos)) { // one of us is probably forked or smth, just mark it as expired and check the rest of the rules nActiveState = ZOINODE_EXPIRED; } if (nProtocolVersion < mnpayments.GetMinZoinodePaymentsProto()) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- ignoring outdated Zoinode: zoinode=%s nProtocolVersion=%d\n", vin.prevout.ToStringShort(), nProtocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- pubKeyCollateralAddress has the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyZoinode.GetID()); if (pubkeyScript2.size() != 25) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- pubKeyZoinode has the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrintf("CZoinodeBroadcast::SimpleCheck -- Ignore Not Empty ScriptSig %s\n", vin.ToString()); nDos = 100; return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (addr.GetPort() != mainnetDefaultPort) return false; } else if (addr.GetPort() == mainnetDefaultPort) return false; return true; } bool CZoinodeBroadcast::Update(CZoinode *pmn, int &nDos) { nDos = 0; if (pmn->sigTime == sigTime && !fRecovery) { // mapSeenZoinodeBroadcast in CZoinodeMan::CheckMnbAndUpdateZoinodeList should filter legit duplicates // but this still can happen if we just started, which is ok, just do nothing here. return false; } // this broadcast is older than the one that we already have - it's bad and should never happen // unless someone is doing something fishy if (pmn->sigTime > sigTime) { LogPrintf("CZoinodeBroadcast::Update -- Bad sigTime %d (existing broadcast is at %d) for Zoinode %s %s\n", sigTime, pmn->sigTime, vin.prevout.ToStringShort(), addr.ToString()); return false; } pmn->Check(); // zoinode is banned by PoSe if (pmn->IsPoSeBanned()) { LogPrintf("CZoinodeBroadcast::Update -- Banned by PoSe, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } // IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match if (pmn->pubKeyCollateralAddress != pubKeyCollateralAddress) { LogPrintf("CZoinodeBroadcast::Update -- Got mismatched pubKeyCollateralAddress and vin\n"); nDos = 33; return false; } if (!CheckSignature(nDos)) { LogPrintf("CZoinodeBroadcast::Update -- CheckSignature() failed, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } // if ther was no zoinode broadcast recently or if it matches our Zoinode privkey... if (!pmn->IsBroadcastedWithin(ZOINODE_MIN_MNB_SECONDS) || (fZoiNode && pubKeyZoinode == activeZoinode.pubKeyZoinode)) { // take the newest entry LogPrintf("CZoinodeBroadcast::Update -- Got UPDATED Zoinode entry: addr=%s\n", addr.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); RelayZoiNode(); } zoinodeSync.AddedZoinodeList(); } return true; } bool CZoinodeBroadcast::CheckOutpoint(int &nDos) { // we are a zoinode with the same vin (i.e. already activated) and this mnb is ours (matches our Zoinode privkey) // so nothing to do here for us if (fZoiNode && vin.prevout == activeZoinode.vin.prevout && pubKeyZoinode == activeZoinode.pubKeyZoinode) { return false; } if (!CheckSignature(nDos)) { LogPrintf("CZoinodeBroadcast::CheckOutpoint -- CheckSignature() failed, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later LogPrint("zoinode", "CZoinodeBroadcast::CheckOutpoint -- Failed to aquire lock, addr=%s", addr.ToString()); mnodeman.mapSeenZoinodeBroadcast.erase(GetHash()); return false; } CCoins coins; if (!pcoinsTip->GetCoins(vin.prevout.hash, coins) || (unsigned int) vin.prevout.n >= coins.vout.size() || coins.vout[vin.prevout.n].IsNull()) { LogPrint("zoinode", "CZoinodeBroadcast::CheckOutpoint -- Failed to find Zoinode UTXO, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } if (coins.vout[vin.prevout.n].nValue != ZOINODE_COIN_REQUIRED * COIN) { LogPrint("zoinode", "CZoinodeBroadcast::CheckOutpoint -- Zoinode UTXO should have 25000 ZOI, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } if (chainActive.Height() - coins.nHeight + 1 < Params().GetConsensus().nZoinodeMinimumConfirmations) { LogPrintf("CZoinodeBroadcast::CheckOutpoint -- Zoinode UTXO must have at least %d confirmations, zoinode=%s\n", Params().GetConsensus().nZoinodeMinimumConfirmations, vin.prevout.ToStringShort()); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenZoinodeBroadcast.erase(GetHash()); return false; } } LogPrint("zoinode", "CZoinodeBroadcast::CheckOutpoint -- Zoinode UTXO verified\n"); // make sure the vout that was signed is related to the transaction that spawned the Zoinode // - this is expensive, so it's only done once per Zoinode if (!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubKeyCollateralAddress)) { LogPrintf("CZoinodeMan::CheckOutpoint -- Got mismatched pubKeyCollateralAddress and vin\n"); nDos = 33; return false; } // verify that sig time is legit in past // should be at least not earlier than block when 25000 ZOI tx got nZoinodeMinimumConfirmations uint256 hashBlock = uint256(); CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, Params().GetConsensus(), hashBlock, true); { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex *pMNIndex = (*mi).second; // block for 25000 ZOI tx -> 1 confirmation CBlockIndex *pConfIndex = chainActive[pMNIndex->nHeight + Params().GetConsensus().nZoinodeMinimumConfirmations - 1]; // block where tx got nZoinodeMinimumConfirmations if (pConfIndex->GetBlockTime() > sigTime) { LogPrintf("CZoinodeBroadcast::CheckOutpoint -- Bad sigTime %d (%d conf block is at %d) for Zoinode %s %s\n", sigTime, Params().GetConsensus().nZoinodeMinimumConfirmations, pConfIndex->GetBlockTime(), vin.prevout.ToStringShort(), addr.ToString()); return false; } } } return true; } bool CZoinodeBroadcast::Sign(CKey &keyCollateralAddress) { std::string strError; std::string strMessage; sigTime = GetAdjustedTime(); strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyZoinode.GetID().ToString() + boost::lexical_cast<std::string>(nProtocolVersion); if (!darkSendSigner.SignMessage(strMessage, vchSig, keyCollateralAddress)) { LogPrintf("CZoinodeBroadcast::Sign -- SignMessage() failed\n"); return false; } if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CZoinodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CZoinodeBroadcast::CheckSignature(int &nDos) { std::string strMessage; std::string strError = ""; nDos = 0; strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyZoinode.GetID().ToString() + boost::lexical_cast<std::string>(nProtocolVersion); LogPrint("zoinode", "CZoinodeBroadcast::CheckSignature -- strMessage: %s pubKeyCollateralAddress address: %s sig: %s\n", strMessage, CBitcoinAddress(pubKeyCollateralAddress.GetID()).ToString(), EncodeBase64(&vchSig[0], vchSig.size())); if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CZoinodeBroadcast::CheckSignature -- Got bad Zoinode announce signature, error: %s\n", strError); nDos = 100; return false; } return true; } void CZoinodeBroadcast::RelayZoiNode() { LogPrintf("CZoinodeBroadcast::RelayZoiNode\n"); CInv inv(MSG_ZOINODE_ANNOUNCE, GetHash()); RelayInv(inv); } CZoinodePing::CZoinodePing(CTxIn &vinNew) { LOCK(cs_main); if (!chainActive.Tip() || chainActive.Height() < 12) return; vin = vinNew; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector < unsigned char > (); } bool CZoinodePing::Sign(CKey &keyZoinode, CPubKey &pubKeyZoinode) { std::string strError; std::string strZoiNodeSignMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); if (!darkSendSigner.SignMessage(strMessage, vchSig, keyZoinode)) { LogPrintf("CZoinodePing::Sign -- SignMessage() failed\n"); return false; } if (!darkSendSigner.VerifyMessage(pubKeyZoinode, vchSig, strMessage, strError)) { LogPrintf("CZoinodePing::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CZoinodePing::CheckSignature(CPubKey &pubKeyZoinode, int &nDos) { std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); std::string strError = ""; nDos = 0; if (!darkSendSigner.VerifyMessage(pubKeyZoinode, vchSig, strMessage, strError)) { LogPrintf("CZoinodePing::CheckSignature -- Got bad Zoinode ping signature, zoinode=%s, error: %s\n", vin.prevout.ToStringShort(), strError); nDos = 33; return false; } return true; } bool CZoinodePing::SimpleCheck(int &nDos) { // don't ban by default nDos = 0; if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CZoinodePing::SimpleCheck -- Signature rejected, too far into the future, zoinode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } { // LOCK(cs_main); AssertLockHeld(cs_main); BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi == mapBlockIndex.end()) { LogPrint("zoinode", "CZoinodePing::SimpleCheck -- Zoinode ping is invalid, unknown block hash: zoinode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString()); // maybe we stuck or forked so we shouldn't ban this node, just fail to accept this ping // TODO: or should we also request this block? return false; } } LogPrint("zoinode", "CZoinodePing::SimpleCheck -- Zoinode ping verified: zoinode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); return true; } bool CZoinodePing::CheckAndUpdate(CZoinode *pmn, bool fFromNewBroadcast, int &nDos) { // don't ban by default nDos = 0; if (!SimpleCheck(nDos)) { return false; } if (pmn == NULL) { LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- Couldn't find Zoinode entry, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } if (!fFromNewBroadcast) { if (pmn->IsUpdateRequired()) { LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- zoinode protocol is outdated, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } if (pmn->IsNewStartRequired()) { LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- zoinode is completely expired, new start is required, zoinode=%s\n", vin.prevout.ToStringShort()); return false; } } { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(blockHash); if ((*mi).second && (*mi).second->nHeight < chainActive.Height() - 24) { LogPrintf("CZoinodePing::CheckAndUpdate -- Zoinode ping is invalid, block hash is too old: zoinode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString()); // nDos = 1; return false; } } LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- New ping: zoinode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); // LogPrintf("mnping - Found corresponding mn for vin: %s\n", vin.prevout.ToStringShort()); // update only if there is no known ping for this zoinode or // last ping was more then ZOINODE_MIN_MNP_SECONDS-60 ago comparing to this one if (pmn->IsPingedWithin(ZOINODE_MIN_MNP_SECONDS - 60, sigTime)) { LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- Zoinode ping arrived too early, zoinode=%s\n", vin.prevout.ToStringShort()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } if (!CheckSignature(pmn->pubKeyZoinode, nDos)) return false; // so, ping seems to be ok // if we are still syncing and there was no known ping for this mn for quite a while // (NOTE: assuming that ZOINODE_EXPIRATION_SECONDS/2 should be enough to finish mn list sync) if (!zoinodeSync.IsZoinodeListSynced() && !pmn->IsPingedWithin(ZOINODE_EXPIRATION_SECONDS / 2)) { // let's bump sync timeout LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- bumping sync timeout, zoinode=%s\n", vin.prevout.ToStringShort()); zoinodeSync.AddedZoinodeList(); } // let's store this ping as the last one LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- Zoinode ping accepted, zoinode=%s\n", vin.prevout.ToStringShort()); pmn->lastPing = *this; // and update zoinodeman.mapSeenZoinodeBroadcast.lastPing which is probably outdated CZoinodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenZoinodeBroadcast.count(hash)) { mnodeman.mapSeenZoinodeBroadcast[hash].second.lastPing = *this; } pmn->Check(true); // force update, ignoring cache if (!pmn->IsEnabled()) return false; LogPrint("zoinode", "CZoinodePing::CheckAndUpdate -- Zoinode ping acceepted and relayed, zoinode=%s\n", vin.prevout.ToStringShort()); Relay(); return true; } void CZoinodePing::Relay() { CInv inv(MSG_ZOINODE_PING, GetHash()); RelayInv(inv); } //void CZoinode::AddGovernanceVote(uint256 nGovernanceObjectHash) //{ // if(mapGovernanceObjectsVotedOn.count(nGovernanceObjectHash)) { // mapGovernanceObjectsVotedOn[nGovernanceObjectHash]++; // } else { // mapGovernanceObjectsVotedOn.insert(std::make_pair(nGovernanceObjectHash, 1)); // } //} //void CZoinode::RemoveGovernanceObject(uint256 nGovernanceObjectHash) //{ // std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.find(nGovernanceObjectHash); // if(it == mapGovernanceObjectsVotedOn.end()) { // return; // } // mapGovernanceObjectsVotedOn.erase(it); //} void CZoinode::UpdateWatchdogVoteTime() { LOCK(cs); nTimeLastWatchdogVote = GetTime(); } /** * FLAG GOVERNANCE ITEMS AS DIRTY * * - When zoinode come and go on the network, we must flag the items they voted on to recalc it's cached flags * */ //void CZoinode::FlagGovernanceItemsAsDirty() //{ // std::vector<uint256> vecDirty; // { // std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.begin(); // while(it != mapGovernanceObjectsVotedOn.end()) { // vecDirty.push_back(it->first); // ++it; // } // } // for(size_t i = 0; i < vecDirty.size(); ++i) { // zoinodeman.AddDirtyGovernanceObjectHash(vecDirty[i]); // } //}
39.773446
241
0.658074
[ "vector" ]
1411f19b75d6163389f90e8cef4801a5191119e8
8,650
cpp
C++
FrameworkLib/NewtonJoints.cpp
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
FrameworkLib/NewtonJoints.cpp
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
FrameworkLib/NewtonJoints.cpp
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
#include "NewtonJoints.h" #include <Newton.h> #define MIN_JOINT_PIN_LENGTH 50.0f #define DG_MAX_BOUND ( 1.0e15f ) #define DG_MIN_BOUND ( -DG_MAX_BOUND ) void CustomBallAndSocketWithFriction::SubmitConstraints(dFloat timestep, int threadIndex) { CustomBallAndSocket::SubmitConstraints(timestep, threadIndex); dVector omega0(0.0f, 0.0f, 0.0f, 0.0f); dVector omega1(0.0f, 0.0f, 0.0f, 0.0f); // get the omega vector NewtonBodyGetOmega(m_body0, &omega0[0]); if(m_body1) { NewtonBodyGetOmega(m_body1, &omega1[0]); } dVector relOmega(omega0 - omega1); dFloat omegaMag = dSqrt(relOmega % relOmega); if(omegaMag > 0.1f) { // tell newton to used this the friction of the omega vector to apply the rolling friction dMatrix basis(dGrammSchmidt(relOmega)); NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[2][0]); NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[1][0]); NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[0][0]); // calculate the acceleration to stop the ball in one time step dFloat invTimestep = (timestep > 0.0f) ? 1.0f / timestep : 1.0f; // override the desired acceleration, with the desired acceleration for full stop. NewtonUserJointSetRowAcceleration(m_joint, -omegaMag * invTimestep); // set the friction limit proportional the sphere Inertia NewtonUserJointSetRowMinimumFriction(m_joint, -m_dryFriction); NewtonUserJointSetRowMaximumFriction(m_joint, m_dryFriction); } else { // when omega is too low this is correct but the small angle approximation theorem. dMatrix basis(dGetIdentityMatrix()); for(int i = 0; i < 3; i++) { NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[i][0]); NewtonUserJointSetRowMinimumFriction(m_joint, -m_dryFriction); NewtonUserJointSetRowMaximumFriction(m_joint, m_dryFriction); } } } CustomLimitBallAndSocketWithFriction::CustomLimitBallAndSocketWithFriction(const dMatrix& pinAndPivotFrame, NewtonBody* const child, NewtonBody* const parent) :CustomBallAndSocket(pinAndPivotFrame, child, parent) , m_rotationOffset(dGetIdentityMatrix()) { SetConeAngle(0.0f); SetTwistAngle(0.0f, 0.0f); SetFriction(0.0f); } CustomLimitBallAndSocketWithFriction::CustomLimitBallAndSocketWithFriction(const dMatrix& childPinAndPivotFrame, NewtonBody* const child, const dMatrix& parentPinAndPivotFrame, NewtonBody* const parent) :CustomBallAndSocket(childPinAndPivotFrame, child, parent) , m_rotationOffset(childPinAndPivotFrame * parentPinAndPivotFrame.Inverse()) { SetConeAngle(0.0f); SetTwistAngle(0.0f, 0.0f); SetFriction(0.0f); dMatrix matrix; CalculateLocalMatrix(parentPinAndPivotFrame, matrix, m_localMatrix1); } CustomLimitBallAndSocketWithFriction::~CustomLimitBallAndSocketWithFriction() { } void CustomLimitBallAndSocketWithFriction::SetConeAngle(dFloat angle) { m_coneAngle = angle; m_coneAngleCos = dCos(angle); m_coneAngleSin = dSin(angle); m_coneAngleHalfCos = dCos(angle * 0.5f); m_coneAngleHalfSin = dSin(angle * 0.5f); } void CustomLimitBallAndSocketWithFriction::SetTwistAngle(dFloat minAngle, dFloat maxAngle) { m_minTwistAngle = minAngle; m_maxTwistAngle = maxAngle; } void CustomLimitBallAndSocketWithFriction::SetFriction(dFloat friction) { m_friction = friction; } dFloat CustomLimitBallAndSocketWithFriction::GetConeAngle() const { return m_coneAngle; } void CustomLimitBallAndSocketWithFriction::GetTwistAngle(dFloat& minAngle, dFloat& maxAngle) const { minAngle = m_minTwistAngle; maxAngle = m_maxTwistAngle; } dFloat CustomLimitBallAndSocketWithFriction::GetFriction() const { return m_friction; } void CustomLimitBallAndSocketWithFriction::GetInfo(NewtonJointRecord* const info) const { CustomBallAndSocket::GetInfo(info); info->m_minAngularDof[0] = m_minTwistAngle; info->m_maxAngularDof[0] = m_maxTwistAngle; info->m_minAngularDof[1] = -m_coneAngle; info->m_maxAngularDof[1] = m_coneAngle; info->m_minAngularDof[2] = -m_coneAngle; info->m_maxAngularDof[2] = m_coneAngle; strcpy(info->m_descriptionType, "limitballsocket"); } void CustomLimitBallAndSocketWithFriction::SubmitConstraints(dFloat timestep, int threadIndex) { dMatrix matrix0; dMatrix matrix1; // calculate the position of the pivot point and the Jacobian direction vectors, in global space. CalculateGlobalMatrix(m_localMatrix0, m_localMatrix1, matrix0, matrix1); const dVector& p0 = matrix0.m_posit; const dVector& p1 = matrix1.m_posit; // So we create a position matrix... // and then we restrict MOVEMENT... // along all three orthonormal directions??? // Restrict the movement on the pivot point along all tree orthonormal direction NewtonUserJointAddLinearRow(m_joint, &p0[0], &p1[0], &matrix1.m_front[0]); NewtonUserJointAddLinearRow(m_joint, &p0[0], &p1[0], &matrix1.m_up[0]); NewtonUserJointAddLinearRow(m_joint, &p0[0], &p1[0], &matrix1.m_right[0]); matrix1 = m_rotationOffset * matrix1; // This submits the twist limit constraints... dMatrix localMatrix(matrix0 * matrix1.Inverse()); dFloat pitchAngle = -dAtan2(localMatrix[1][2], localMatrix[2][2]); bool twistConstrained = true; bool coneConstrained = true; if((m_maxTwistAngle - m_minTwistAngle) < 1.0e-4f) { dMatrix base(dPitchMatrix(pitchAngle) * matrix0); dVector q0(p1 + matrix0.m_up.Scale(MIN_JOINT_PIN_LENGTH)); dVector q1(p1 + base.m_up.Scale(MIN_JOINT_PIN_LENGTH)); NewtonUserJointAddLinearRow(m_joint, &q0[0], &q1[0], &base.m_right[0]); } else { if(pitchAngle > m_maxTwistAngle) { pitchAngle -= m_maxTwistAngle; dMatrix base(dPitchMatrix(pitchAngle) * matrix0); dVector q0(p1 + matrix0.m_up.Scale(MIN_JOINT_PIN_LENGTH)); dVector q1(p1 + base.m_up.Scale(MIN_JOINT_PIN_LENGTH)); NewtonUserJointAddLinearRow(m_joint, &q0[0], &q1[0], &base.m_right[0]); NewtonUserJointSetRowMinimumFriction(m_joint, -0.0f); } else if(pitchAngle < m_minTwistAngle) { pitchAngle -= m_minTwistAngle; dMatrix base(dPitchMatrix(pitchAngle) * matrix0); dVector q0(p1 + matrix0.m_up.Scale(MIN_JOINT_PIN_LENGTH)); dVector q1(p1 + base.m_up.Scale(MIN_JOINT_PIN_LENGTH)); NewtonUserJointAddLinearRow(m_joint, &q0[0], &q1[0], &base.m_right[0]); NewtonUserJointSetRowMaximumFriction(m_joint, 0.0f); } else { twistConstrained = false; } } // This submits the cone limit constraints... const dVector& coneDir0 = matrix0.m_front; const dVector& coneDir1 = matrix1.m_front; dVector r0(p0 + coneDir0.Scale(MIN_JOINT_PIN_LENGTH)); dVector r1(p1 + coneDir1.Scale(MIN_JOINT_PIN_LENGTH)); // construct an orthogonal coordinate system with these two vectors dVector lateralDir(coneDir0 * coneDir1); dFloat mag2; mag2 = lateralDir % lateralDir; if(dAbs(mag2) < 1.0e-4f) { if(m_coneAngleSin < 1.0e-4f) { NewtonUserJointAddLinearRow(m_joint, &r0[0], &r1[0], &matrix0.m_up[0]); NewtonUserJointAddLinearRow(m_joint, &r0[0], &r1[0], &matrix0.m_right[0]); } } else { dFloat cosAngle; cosAngle = coneDir0 % coneDir1; if(cosAngle < m_coneAngleCos) { lateralDir = lateralDir.Scale(1.0f / dSqrt(mag2)); dQuaternion rot(m_coneAngleHalfCos, lateralDir.m_x * m_coneAngleHalfSin, lateralDir.m_y * m_coneAngleHalfSin, lateralDir.m_z * m_coneAngleHalfSin); r1 = p1 + rot.UnrotateVector(r1 - p1); NewtonUserJointAddLinearRow(m_joint, &r0[0], &r1[0], &lateralDir[0]); dVector longitudinalDir(lateralDir * matrix0.m_front); NewtonUserJointAddLinearRow(m_joint, &r0[0], &r1[0], &longitudinalDir[0]); NewtonUserJointSetRowMinimumFriction(m_joint, -0.0f); } else { coneConstrained = false; } } if(!twistConstrained && !coneConstrained && m_friction > 0.01f) { dVector omega0(0.0f, 0.0f, 0.0f, 0.0f); dVector omega1(0.0f, 0.0f, 0.0f, 0.0f); // get the omega vector NewtonBodyGetOmega(m_body0, &omega0[0]); if(m_body1) { NewtonBodyGetOmega(m_body1, &omega1[0]); } dVector relOmega(omega0 - omega1); dFloat omegaMag = dSqrt(relOmega % relOmega); if(omegaMag > 0.1f) { // tell newton to used this the friction of the omega vector to apply the rolling friction dMatrix basis(dGrammSchmidt(relOmega)); for(int i = 0; i < 3; i++) { NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[i][0]); NewtonUserJointSetRowMinimumFriction(m_joint, -m_friction); NewtonUserJointSetRowMaximumFriction(m_joint, m_friction); } } else { // when omega is too low this is correct but the small angle approximation theorem. dMatrix basis(dGetIdentityMatrix()); for(int i = 0; i < 3; i++) { NewtonUserJointAddAngularRow(m_joint, 0.0f, &basis[i][0]); NewtonUserJointSetRowMinimumFriction(m_joint, -m_friction); NewtonUserJointSetRowMaximumFriction(m_joint, m_friction); } } } }
32.889734
202
0.750751
[ "vector" ]
1415021d369dcae78c07c1b2975ddf6780350dce
7,950
cpp
C++
test/testShape.cpp
Ji2z/thorvg
cc9b5669e5d1bfb9cfe2e39058a16d093443bcf7
[ "MIT" ]
187
2020-08-24T04:45:30.000Z
2022-03-30T20:14:21.000Z
test/testShape.cpp
Ji2z/thorvg
cc9b5669e5d1bfb9cfe2e39058a16d093443bcf7
[ "MIT" ]
666
2020-09-10T06:45:14.000Z
2022-03-30T07:11:16.000Z
test/testShape.cpp
JSUYA/thorvg
46bdc8f1dc86f7ede5b066e30f96a97b0f9ff30f
[ "MIT" ]
57
2020-08-24T05:15:41.000Z
2022-03-22T11:15:25.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <thorvg.h> #include "catch.hpp" using namespace tvg; TEST_CASE("Shape Creation", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); REQUIRE(shape->identifier() == Shape::identifier()); REQUIRE(shape->identifier() != Picture::identifier()); REQUIRE(shape->identifier() != Scene::identifier()); } TEST_CASE("Appending Commands", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); REQUIRE(shape->close() == Result::Success); REQUIRE(shape->moveTo(100, 100) == Result::Success); REQUIRE(shape->moveTo(99999999.0f, -99999999.0f) == Result::Success); REQUIRE(shape->moveTo(0, 0) == Result::Success); REQUIRE(shape->lineTo(120, 140) == Result::Success); REQUIRE(shape->lineTo(99999999.0f, -99999999.0f) == Result::Success); REQUIRE(shape->lineTo(0, 0) == Result::Success); REQUIRE(shape->cubicTo(0, 0, 0, 0, 0, 0) == Result::Success); REQUIRE(shape->cubicTo(0, 0, 99999999.0f, -99999999.0f, 0, 0) == Result::Success); REQUIRE(shape->cubicTo(0, 0, 99999999.0f, -99999999.0f, 99999999.0f, -99999999.0f) == Result::Success); REQUIRE(shape->cubicTo(99999999.0f, -99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, -99999999.0f) == Result::Success); REQUIRE(shape->close() == Result::Success); REQUIRE(shape->reset() == Result::Success); REQUIRE(shape->reset() == Result::Success); } TEST_CASE("Appending Shapes", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); REQUIRE(shape->moveTo(100, 100) == Result::Success); REQUIRE(shape->lineTo(120, 140) == Result::Success); REQUIRE(shape->appendRect(0, 0, 0, 0, 0, 0) == Result::Success); REQUIRE(shape->appendRect(0, 0,99999999.0f, -99999999.0f, 0, 0) == Result::Success); REQUIRE(shape->appendRect(0, 0, 0, 0, -99999999.0f, 99999999.0f) == Result::Success); REQUIRE(shape->appendRect(99999999.0f, -99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, -99999999.0f) == Result::Success); REQUIRE(shape->appendCircle(0, 0, 0, 0) == Result::Success); REQUIRE(shape->appendCircle(-99999999.0f, 99999999.0f, 0, 0) == Result::Success); REQUIRE(shape->appendCircle(-99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f) == Result::Success); REQUIRE(shape->appendArc(0, 0, 0, 0, 0, false) == Result::Success); REQUIRE(shape->appendArc(0, 0, 0, 0, 0, true) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, 0, 0, 0, false) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, 0, 0, 0, true) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, 0, false) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, 0, true) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, -400, false) == Result::Success); REQUIRE(shape->appendArc(-99999999.0f, 99999999.0f, -99999999.0f, 99999999.0f, 400, true) == Result::Success); } TEST_CASE("Appending Pathes", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); //Negative cases REQUIRE(shape->appendPath(nullptr, 0, nullptr, 0) == Result::InvalidArguments); REQUIRE(shape->appendPath(nullptr, 100, nullptr, 0) == Result::InvalidArguments); REQUIRE(shape->appendPath(nullptr, 0, nullptr, 100) == Result::InvalidArguments); PathCommand cmds[5] = { PathCommand::Close, PathCommand::MoveTo, PathCommand::LineTo, PathCommand::CubicTo, PathCommand::Close }; Point pts[5] = { {100, 100}, {200, 200}, {10, 10}, {20, 20}, {30, 30} }; REQUIRE(shape->appendPath(cmds, 0, pts, 5) == Result::InvalidArguments); REQUIRE(shape->appendPath(cmds, 5, pts, 0) == Result::InvalidArguments); REQUIRE(shape->appendPath(cmds, 5, pts, 5) == Result::Success); const PathCommand* cmds2; REQUIRE(shape->pathCommands(&cmds2) == 5); const Point* pts2; REQUIRE(shape->pathCoords(&pts2) == 5); for (int i = 0; i < 5; ++i) { REQUIRE(cmds2[i] == cmds[i]); REQUIRE(pts[i].x == pts2[i].x); REQUIRE(pts[i].y == pts2[i].y); } shape->reset(); REQUIRE(shape->pathCommands(nullptr) == 0); REQUIRE(shape->pathCoords(nullptr) == 0); } TEST_CASE("Stroking", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); //Stroke Width REQUIRE(shape->stroke(0) == Result::Success); REQUIRE(shape->strokeWidth() == 0); REQUIRE(shape->stroke(300) == Result::Success); REQUIRE(shape->strokeWidth() == 300); //Stroke Color uint8_t r, g, b, a; REQUIRE(shape->stroke(0, 50, 100, 200) == Result::Success); REQUIRE(shape->strokeColor(nullptr, nullptr, &b, nullptr) == Result::Success); REQUIRE(b == 100); REQUIRE(shape->strokeColor(&r, &g, &b, &a) == Result::Success); REQUIRE(r == 0); REQUIRE(g == 50); REQUIRE(b == 100); REQUIRE(a == 200); REQUIRE(shape->strokeColor(nullptr, nullptr, nullptr, nullptr) == Result::Success); //Stroke Dash float dashPattern[3] = {0, 1.5f, 2.22f}; REQUIRE(shape->stroke(dashPattern, 3) == Result::InvalidArguments); float dashPattern2[3] = {1.0f, 1.5f, 2.22f}; REQUIRE(shape->stroke(dashPattern2, 3) == Result::Success); const float* dashPattern3; REQUIRE(shape->strokeDash(nullptr) == 3); REQUIRE(shape->strokeDash(&dashPattern3) == 3); REQUIRE(dashPattern3[0] == 1.0f); REQUIRE(dashPattern3[1] == 1.5f); REQUIRE(dashPattern3[2] == 2.22f); REQUIRE(shape->stroke(nullptr, 0) == Result::Success); //Stroke Cap REQUIRE(shape->strokeCap() == StrokeCap::Square); REQUIRE(shape->stroke(StrokeCap::Round) == Result::Success); REQUIRE(shape->stroke(StrokeCap::Butt) == Result::Success); REQUIRE(shape->strokeCap() == StrokeCap::Butt); //Stroke Join REQUIRE(shape->strokeJoin() == StrokeJoin::Bevel); REQUIRE(shape->stroke(StrokeJoin::Miter) == Result::Success); REQUIRE(shape->stroke(StrokeJoin::Round) == Result::Success); REQUIRE(shape->strokeJoin() == StrokeJoin::Round); } TEST_CASE("Shape Filling", "[tvgShape]") { auto shape = Shape::gen(); REQUIRE(shape); //Fill Color uint8_t r, g, b, a; REQUIRE(shape->fill(255, 100, 50, 5) == Result::Success); REQUIRE(shape->fillColor(&r, nullptr, &b, nullptr) == Result::Success); REQUIRE(r == 255); REQUIRE(b == 50); REQUIRE(shape->fillColor(&r, &g, &b, &a) == Result::Success); REQUIRE(g == 100); REQUIRE(a == 5); //Fill Rule REQUIRE(shape->fillRule() == FillRule::Winding); REQUIRE(shape->fill(FillRule::EvenOdd) == Result::Success); REQUIRE(shape->fillRule() == FillRule::EvenOdd); }
38.038278
131
0.650818
[ "shape" ]
1416ff7f6411d14a56dac998b49686818137c31e
5,202
cpp
C++
src/plugins/opengl/src/shader_opengl.cpp
tcoxon/halley
490d2699090bfd677c5a00f53f2f12c19c198f7c
[ "Apache-2.0" ]
null
null
null
src/plugins/opengl/src/shader_opengl.cpp
tcoxon/halley
490d2699090bfd677c5a00f53f2f12c19c198f7c
[ "Apache-2.0" ]
null
null
null
src/plugins/opengl/src/shader_opengl.cpp
tcoxon/halley
490d2699090bfd677c5a00f53f2f12c19c198f7c
[ "Apache-2.0" ]
null
null
null
#include <cstring> #include "halley/support/exception.h" #include "halley/support/console.h" #include "shader_opengl.h" #include "halley/core/graphics/material/material_definition.h" #include "gl_utils.h" #include "halley_gl.h" using namespace Halley; static ShaderOpenGL* currentShader = nullptr; #ifdef _MSC_VER #pragma warning(disable: 4996) #endif ShaderOpenGL::ShaderOpenGL(const ShaderDefinition& definition) { id = glCreateProgram(); glCheckError(); name = definition.name; setAttributes(definition.vertexAttributes); loadShaders(definition.shaders); compile(); } ShaderOpenGL::~ShaderOpenGL() { destroy(); } void ShaderOpenGL::bind() { if (this != currentShader) { if (!ready) { compile(); } glUseProgram(id); glCheckError(); currentShader = this; } } void ShaderOpenGL::unbind() { currentShader = nullptr; glUseProgram(0); glCheckError(); } static GLuint loadShader(const Bytes& src, GLenum type, String name) { // Create shader GLuint shader = glCreateShader(type); glCheckError(); // Load source size_t len = src.size(); GLchar* buffer = new GLchar[len + 1]; memcpy(buffer, src.data(), src.size()); buffer[len] = 0; const char* cbuf = buffer; glShaderSource(shader, 1, &cbuf, nullptr); glCheckError(); // Compile source glCompileShader(shader); glCheckError(); delete[] buffer; // Check result // Seriously, GL? All this crap to retrieve an info log? int result; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); glCheckError(); if (result == GL_FALSE) { int infolen; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infolen); glCheckError(); char* log = new char[infolen]; glGetShaderInfoLog(shader, infolen, &infolen, log); String msg = String("Error compiling shader \"" + name + "\":\n") + log; delete[] log; glCheckError(); throw Exception(msg); } return shader; } void ShaderOpenGL::loadShaders(const std::map<ShaderType, Bytes>& sources) { for (auto& s: sources) { auto type = s.first; int glType = 0; switch (type) { case ShaderType::Vertex: glType = GL_VERTEX_SHADER; break; case ShaderType::Pixel: glType = GL_FRAGMENT_SHADER; break; #ifdef WITH_OPENGL case ShaderType::Geometry: glType = GL_GEOMETRY_SHADER; break; #endif default: throw Exception("Unsupported shader type: " + toString(type)); } shaders.push_back(loadShader(s.second, glType, name + "/" + toString(type))); } } void ShaderOpenGL::compile() { if (!ready) { // Create program for (size_t i = 0; i<shaders.size(); i++) { glAttachShader(id, shaders[i]); glCheckError(); } glLinkProgram(id); glCheckError(); // Collect log int infolen; glGetProgramiv(id, GL_INFO_LOG_LENGTH, &infolen); glCheckError(); char* logRaw = new char[infolen + 1]; glGetProgramInfoLog(id, infolen, &infolen, logRaw); logRaw[infolen] = 0; String log = logRaw; delete[] logRaw; glCheckError(); // Verify result int result; glGetProgramiv(id, GL_LINK_STATUS, &result); glCheckError(); if (result == GL_FALSE) { throw Exception("Error loading shader: " + log); } else if (infolen > 0) { std::cout << ConsoleColour(Console::YELLOW) << "\nIn shader \"" << name << "\":\n==========\n" << log << "\n==========" << ConsoleColour() << std::endl; } uniformLocations.clear(); attributeLocations.clear(); ready = true; } } void ShaderOpenGL::destroy() { if (ready) { glCheckError(); unbind(); ready = false; for (size_t i = 0; i < shaders.size(); i++) { glDetachShader(id, shaders[i]); glCheckError(); glDeleteShader(shaders[i]); glCheckError(); } } if (id != 0) { glDeleteProgram(id); glCheckError(); id = 0; } } void ShaderOpenGL::setUniformBlockBinding(unsigned int blockIndex, unsigned int binding) { glUniformBlockBinding(id, blockIndex, binding); glCheckError(); } int ShaderOpenGL::getUniformLocation(const String& name, ShaderType stage) { if (stage != ShaderType::Combined) { // OpenGL doesn't support per-stage bindings return -1; } auto i = uniformLocations.find(name); if (i != uniformLocations.end()) { return int(i->second); } unsigned int result = glGetUniformLocation(id, name.c_str()); glCheckError(); uniformLocations[name] = result; return int(result); } int ShaderOpenGL::getBlockLocation(const String& name, ShaderType stage) { if (stage != ShaderType::Combined) { // OpenGL doesn't support per-stage bindings return -1; } auto i = blockLocations.find(name); if (i != blockLocations.end()) { return int(i->second); } unsigned int result = glGetUniformBlockIndex(id, name.c_str()); glCheckError(); blockLocations[name] = result; return int(result); } int ShaderOpenGL::getAttributeLocation(const String& name) { auto i = attributeLocations.find(name); if (i != attributeLocations.end()) { return int(i->second); } unsigned int result = glGetAttribLocation(id, name.c_str()); glCheckError(); attributeLocations[name] = result; return int(result); } void ShaderOpenGL::setAttributes(const Vector<MaterialAttribute>& attributes) { for (auto& attribute : attributes) { glBindAttribLocation(id, attribute.location, attribute.name.c_str()); glCheckError(); } }
21.495868
155
0.68762
[ "geometry", "vector" ]
1417805f823d1e7e75cdca34c40edb163dc6b313
12,769
cpp
C++
src/lib/crypto/rsa_ossl.cpp
andrey-utkin/rnp
4a2d42d9591ecf7428a738247181c988f6fc0ff2
[ "Apache-2.0" ]
null
null
null
src/lib/crypto/rsa_ossl.cpp
andrey-utkin/rnp
4a2d42d9591ecf7428a738247181c988f6fc0ff2
[ "Apache-2.0" ]
null
null
null
src/lib/crypto/rsa_ossl.cpp
andrey-utkin/rnp
4a2d42d9591ecf7428a738247181c988f6fc0ff2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021, [Ribose Inc](https://www.ribose.com). * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <cstring> #include "crypto/rsa.h" #include "hash.h" #include "config.h" #include "utils.h" #include "bn.h" #include <openssl/rsa.h> #include <openssl/err.h> #include <openssl/evp.h> static RSA * rsa_load_public_key(const pgp_rsa_key_t *key) { RSA * rsa = NULL; bignum_t *n = mpi2bn(&key->n); bignum_t *e = mpi2bn(&key->e); if (!n || !e) { RNP_LOG("out of memory"); goto done; } rsa = RSA_new(); if (!rsa) { RNP_LOG("Out of memory"); goto done; } if (RSA_set0_key(rsa, n, e, NULL) != 1) { RNP_LOG("Public key load error: %lu", ERR_peek_last_error()); RSA_free(rsa); rsa = NULL; goto done; } done: /* OpenSSL set0 function transfers ownership of bignums */ if (!rsa) { bn_free(n); bn_free(e); } return rsa; } static RSA * rsa_load_secret_key(const pgp_rsa_key_t *key) { RSA * rsa = NULL; bignum_t *n = mpi2bn(&key->n); bignum_t *e = mpi2bn(&key->e); bignum_t *p = mpi2bn(&key->p); bignum_t *q = mpi2bn(&key->q); bignum_t *d = mpi2bn(&key->d); if (!n || !p || !q || !e || !d) { RNP_LOG("out of memory"); goto done; } rsa = RSA_new(); if (!rsa) { RNP_LOG("Out of memory"); goto done; } if (RSA_set0_key(rsa, n, e, d) != 1) { RNP_LOG("Secret key load error: %lu", ERR_peek_last_error()); RSA_free(rsa); rsa = NULL; goto done; } /* OpenSSL has p < q, as we do */ if (RSA_set0_factors(rsa, p, q) != 1) { RNP_LOG("Factors load error: %lu", ERR_peek_last_error()); RSA_free(rsa); rsa = NULL; goto done; } done: /* OpenSSL set0 function transfers ownership of bignums */ if (!rsa) { bn_free(n); bn_free(p); bn_free(q); bn_free(e); bn_free(d); } return rsa; } static EVP_PKEY_CTX * rsa_init_context(const pgp_rsa_key_t *key, bool secret) { EVP_PKEY *evpkey = EVP_PKEY_new(); if (!evpkey) { RNP_LOG("allocation failed"); return NULL; } EVP_PKEY_CTX *ctx = NULL; RSA * rsakey = secret ? rsa_load_secret_key(key) : rsa_load_public_key(key); if (!rsakey) { goto done; } if (EVP_PKEY_set1_RSA(evpkey, rsakey) <= 0) { RNP_LOG("Failed to set key: %lu", ERR_peek_last_error()); goto done; } ctx = EVP_PKEY_CTX_new(evpkey, NULL); if (!ctx) { RNP_LOG("Context allocation failed: %lu", ERR_peek_last_error()); } done: RSA_free(rsakey); EVP_PKEY_free(evpkey); return ctx; } rnp_result_t rsa_validate_key(rnp::RNG *rng, const pgp_rsa_key_t *key, bool secret) { if (secret) { EVP_PKEY_CTX *ctx = rsa_init_context(key, secret); if (!ctx) { return RNP_ERROR_GENERIC; } int res = EVP_PKEY_check(ctx); if (res < 0) { RNP_LOG("Key validation error: %lu", ERR_peek_last_error()); } EVP_PKEY_CTX_free(ctx); return res > 0 ? RNP_SUCCESS : RNP_ERROR_GENERIC; } /* OpenSSL 1.1.1 doesn't have RSA public key check function, so let's do some checks */ rnp_result_t ret = RNP_ERROR_GENERIC; bignum_t * n = mpi2bn(&key->n); bignum_t * e = mpi2bn(&key->e); if (!n || !e) { RNP_LOG("out of memory"); ret = RNP_ERROR_OUT_OF_MEMORY; goto done; } if ((BN_num_bits(n) < 512) || !BN_is_odd(n) || (BN_num_bits(e) < 2) || !BN_is_odd(e)) { goto done; } ret = RNP_SUCCESS; done: bn_free(n); bn_free(e); return ret; } static bool rsa_setup_context(EVP_PKEY_CTX *ctx, pgp_hash_alg_t hash_alg = PGP_HASH_UNKNOWN) { if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) { RNP_LOG("Failed to set padding: %lu", ERR_peek_last_error()); return false; } if (hash_alg == PGP_HASH_UNKNOWN) { return true; } const char *hash_name = rnp::Hash::name_backend(hash_alg); if (!hash_name) { RNP_LOG("Unknown hash: %d", (int) hash_alg); return false; } const EVP_MD *hash_tp = EVP_get_digestbyname(hash_name); if (!hash_tp) { RNP_LOG("Error creating hash object for '%s'", hash_name); return false; } if (EVP_PKEY_CTX_set_signature_md(ctx, hash_tp) <= 0) { RNP_LOG("Failed to set digest: %lu", ERR_peek_last_error()); return false; } return true; } rnp_result_t rsa_encrypt_pkcs1(rnp::RNG * rng, pgp_rsa_encrypted_t *out, const uint8_t * in, size_t in_len, const pgp_rsa_key_t *key) { rnp_result_t ret = RNP_ERROR_GENERIC; EVP_PKEY_CTX *ctx = rsa_init_context(key, false); if (!ctx) { return ret; } if (EVP_PKEY_encrypt_init(ctx) <= 0) { RNP_LOG("Failed to initialize encryption: %lu", ERR_peek_last_error()); goto done; } if (!rsa_setup_context(ctx)) { goto done; } out->m.len = sizeof(out->m.mpi); if (EVP_PKEY_encrypt(ctx, out->m.mpi, &out->m.len, in, in_len) <= 0) { RNP_LOG("Encryption failed: %lu", ERR_peek_last_error()); out->m.len = 0; goto done; } ret = RNP_SUCCESS; done: EVP_PKEY_CTX_free(ctx); return ret; } rnp_result_t rsa_verify_pkcs1(const pgp_rsa_signature_t *sig, pgp_hash_alg_t hash_alg, const uint8_t * hash, size_t hash_len, const pgp_rsa_key_t * key) { rnp_result_t ret = RNP_ERROR_SIGNATURE_INVALID; EVP_PKEY_CTX *ctx = rsa_init_context(key, false); if (!ctx) { return ret; } if (EVP_PKEY_verify_init(ctx) <= 0) { RNP_LOG("Failed to initialize verification: %lu", ERR_peek_last_error()); goto done; } if (!rsa_setup_context(ctx, hash_alg)) { goto done; } int res; if (sig->s.len < key->n.len) { /* OpenSSL doesn't like signatures smaller then N */ pgp_mpi_t sn; sn.len = key->n.len; size_t diff = key->n.len - sig->s.len; memset(sn.mpi, 0, diff); memcpy(&sn.mpi[diff], sig->s.mpi, sig->s.len); res = EVP_PKEY_verify(ctx, sn.mpi, sn.len, hash, hash_len); } else { res = EVP_PKEY_verify(ctx, sig->s.mpi, sig->s.len, hash, hash_len); } if (res > 0) { ret = RNP_SUCCESS; } else { RNP_LOG("RSA verification failure: %s", ERR_reason_error_string(ERR_peek_last_error())); } done: EVP_PKEY_CTX_free(ctx); return ret; } rnp_result_t rsa_sign_pkcs1(rnp::RNG * rng, pgp_rsa_signature_t *sig, pgp_hash_alg_t hash_alg, const uint8_t * hash, size_t hash_len, const pgp_rsa_key_t *key) { rnp_result_t ret = RNP_ERROR_GENERIC; if (mpi_bytes(&key->q) == 0) { RNP_LOG("private key not set"); return ret; } EVP_PKEY_CTX *ctx = rsa_init_context(key, true); if (!ctx) { return ret; } if (EVP_PKEY_sign_init(ctx) <= 0) { RNP_LOG("Failed to initialize signing: %lu", ERR_peek_last_error()); goto done; } if (!rsa_setup_context(ctx, hash_alg)) { goto done; } sig->s.len = PGP_MPINT_SIZE; if (EVP_PKEY_sign(ctx, sig->s.mpi, &sig->s.len, hash, hash_len) <= 0) { RNP_LOG("Encryption failed: %lu", ERR_peek_last_error()); sig->s.len = 0; goto done; } ret = RNP_SUCCESS; done: EVP_PKEY_CTX_free(ctx); return ret; } rnp_result_t rsa_decrypt_pkcs1(rnp::RNG * rng, uint8_t * out, size_t * out_len, const pgp_rsa_encrypted_t *in, const pgp_rsa_key_t * key) { rnp_result_t ret = RNP_ERROR_GENERIC; if (mpi_bytes(&key->q) == 0) { RNP_LOG("private key not set"); return ret; } EVP_PKEY_CTX *ctx = rsa_init_context(key, true); if (!ctx) { return ret; } if (EVP_PKEY_decrypt_init(ctx) <= 0) { RNP_LOG("Failed to initialize encryption: %lu", ERR_peek_last_error()); goto done; } if (!rsa_setup_context(ctx)) { goto done; } *out_len = PGP_MPINT_SIZE; if (EVP_PKEY_decrypt(ctx, out, out_len, in->m.mpi, in->m.len) <= 0) { RNP_LOG("Encryption failed: %lu", ERR_peek_last_error()); *out_len = 0; goto done; } ret = RNP_SUCCESS; done: EVP_PKEY_CTX_free(ctx); return ret; } rnp_result_t rsa_generate(rnp::RNG *rng, pgp_rsa_key_t *key, size_t numbits) { if ((numbits < 1024) || (numbits > PGP_MPINT_BITS)) { return RNP_ERROR_BAD_PARAMETERS; } rnp_result_t ret = RNP_ERROR_GENERIC; RSA * rsa = NULL; EVP_PKEY * pkey = NULL; EVP_PKEY_CTX *ctx = NULL; bignum_t * u = NULL; bignum_t * nq = NULL; BN_CTX * bnctx = NULL; ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); if (!ctx) { RNP_LOG("Failed to create ctx: %lu", ERR_peek_last_error()); return ret; } if (EVP_PKEY_keygen_init(ctx) <= 0) { RNP_LOG("Failed to init keygen: %lu", ERR_peek_last_error()); goto done; } if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, numbits) <= 0) { RNP_LOG("Failed to set rsa bits: %lu", ERR_peek_last_error()); goto done; } if (EVP_PKEY_keygen(ctx, &pkey) <= 0) { RNP_LOG("RSA keygen failed: %lu", ERR_peek_last_error()); goto done; } rsa = EVP_PKEY_get0_RSA(pkey); if (!rsa) { RNP_LOG("Failed to retrieve RSA key: %lu", ERR_peek_last_error()); goto done; } if (RSA_check_key(rsa) != 1) { RNP_LOG("Key validation error: %lu", ERR_peek_last_error()); goto done; } const bignum_t *n; const bignum_t *e; const bignum_t *p; const bignum_t *q; const bignum_t *d; n = RSA_get0_n(rsa); e = RSA_get0_e(rsa); d = RSA_get0_d(rsa); p = RSA_get0_p(rsa); q = RSA_get0_q(rsa); if (!n || !e || !d || !p || !q) { ret = RNP_ERROR_OUT_OF_MEMORY; goto done; } /* OpenSSL doesn't care whether p < q */ if (BN_cmp(p, q) > 0) { const bignum_t *tmp = p; p = q; q = tmp; } /* we need to calculate u, since we need inverse of p mod q, while OpenSSL has inverse of q * mod p, and doesn't care of p < q */ bnctx = BN_CTX_new(); u = BN_new(); nq = BN_new(); if (!ctx || !u || !nq) { ret = RNP_ERROR_OUT_OF_MEMORY; goto done; } BN_with_flags(nq, q, BN_FLG_CONSTTIME); /* calculate inverse of p mod q */ if (!BN_mod_inverse(u, p, nq, bnctx)) { bn_free(nq); RNP_LOG("Failed to calculate u"); ret = RNP_ERROR_BAD_STATE; goto done; } bn_free(nq); bn2mpi(n, &key->n); bn2mpi(e, &key->e); bn2mpi(p, &key->p); bn2mpi(q, &key->q); bn2mpi(d, &key->d); bn2mpi(u, &key->u); ret = RNP_SUCCESS; done: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); BN_CTX_free(bnctx); bn_free(u); return ret; }
28.954649
95
0.58039
[ "object" ]
141990326b5c5d19136630f29a8cfd0262da7ba8
1,194
cpp
C++
835/B[ The number on the board ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
835/B[ The number on the board ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
835/B[ The number on the board ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define sd(x) scanf("%d",&x) #define su(x) scanf("%u",&x) #define slld(x) scanf("%lld",&x) #define sc(x) scanf("%c",&x) #define ss(x) scanf("%s",x) #define sf(x) scanf("%f",&x) #define slf(x) scanf("%lf",&x) #define ll long long int #define mod(x,n) (x+n)%n #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define Mod 1000000007 char S[100007]; int coun[17]; int ceils(int x, int y) { if(x%y==0) return x/y; return x/y+1; } int main() { // freopen("input_file_name.in","r",stdin); // freopen("output_file_name.out","w",stdout); int i,j,k,l,m,n,x,y,z,a=0,b,r; // ll i,j,k,l,m,n,x,y,z,a,b,r; sd(k); ss(S); n = strlen(S); x = 0; for(i=0;i<n;i++) { x += (S[i]-&#39;0&#39;); coun[S[i]-&#39;0&#39;]++; } if(x>=k) { printf("0\n"); return 0; } x = k-x; for(i=0;i<9 && x>0;i++) { l = ceils(x,(9-i)); m = min(l,coun[i]); a += m; x -= m*(9-i); } printf("%d\n", a ); return 0; }
17.304348
47
0.51005
[ "vector" ]
141ba8b4d7a7cbde734395d5d7fc91bba639ab05
11,068
cxx
C++
Imaging/Morphological/vtkImageNonMaximumSuppression.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
Imaging/Morphological/vtkImageNonMaximumSuppression.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
4
2018-10-25T09:46:11.000Z
2019-01-17T16:49:17.000Z
Imaging/Morphological/vtkImageNonMaximumSuppression.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
4
2016-09-08T02:11:00.000Z
2019-08-15T02:38:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkImageNonMaximumSuppression.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageNonMaximumSuppression.h" #include "vtkDataArray.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" #include <cmath> vtkStandardNewMacro(vtkImageNonMaximumSuppression); //---------------------------------------------------------------------------- // Construct an instance of vtkImageNonMaximumSuppression filter. vtkImageNonMaximumSuppression::vtkImageNonMaximumSuppression() { this->Dimensionality= 2; this->HandleBoundaries = 1; this->SetNumberOfInputPorts(2); } //---------------------------------------------------------------------------- // This method is passed a region that holds the image extent of this filters // input, and changes the region to hold the image extent of this filters // output. int vtkImageNonMaximumSuppression::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); int extent[6]; int idx; inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),extent); if ( ! this->HandleBoundaries) { // shrink output image extent. for (idx = 0; idx < this->Dimensionality; ++idx) { extent[idx*2] += 1; extent[idx*2+1] -= 1; } } outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),extent,6); return 1; } //---------------------------------------------------------------------------- // This method computes the input extent necessary to generate the output. int vtkImageNonMaximumSuppression::RequestUpdateExtent ( vtkInformation * vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* inInfo2 = inputVector[1]->GetInformationObject(0); int *wholeExtent; int idx; // get the whole image for input 2 int inExt[6]; outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt); wholeExtent = inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()); inInfo2->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); // grow input image extent for input 0 for (idx = 0; idx < this->Dimensionality; ++idx) { inExt[idx*2] -= 1; inExt[idx*2+1] += 1; if (this->HandleBoundaries) { // we must clip extent with whole extent if we hanlde boundaries. if (inExt[idx*2] < wholeExtent[idx*2]) { inExt[idx*2] = wholeExtent[idx*2]; } if (inExt[idx*2 + 1] > wholeExtent[idx*2 + 1]) { inExt[idx*2 + 1] = wholeExtent[idx*2 + 1]; } } } inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),inExt,6); return 1; } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. // Handles the two input operations template <class T> void vtkImageNonMaximumSuppressionExecute(vtkImageNonMaximumSuppression *self, vtkImageData *in1Data, T *in1Ptr, vtkImageData *in2Data, T *in2Ptr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxC, idxX, idxY, idxZ; int maxC, maxX, maxY, maxZ; vtkIdType inIncX, inIncY, inIncZ; vtkIdType in2IncX, in2IncY, in2IncZ; vtkIdType outIncX, outIncY, outIncZ; unsigned long count = 0; unsigned long target; int useZMin, useZMax, useYMin, useYMax, useXMin, useXMax; double d, normalizeFactor, vector[3], *ratio; int neighborA, neighborB; int *wholeExtent; vtkIdType inIncs[3]; int axesNum; vector[0] = 0.0; vector[1] = 0.0; vector[2] = 0.0; // find the region to loop over maxC = outData->GetNumberOfScalarComponents(); maxX = outExt[1] - outExt[0]; maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = static_cast<unsigned long>((maxZ+1)*(maxY+1)/50.0); target++; // Get the dimensionality of the gradient. axesNum = self->GetDimensionality(); // get some other info we need in1Data->GetIncrements(inIncs); wholeExtent = in1Data->GetExtent(); // Get increments to march through data in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); in2Data->GetContinuousIncrements(outExt, in2IncX, in2IncY, in2IncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // Gradient is computed with data spacing (world coordinates) ratio = in2Data->GetSpacing(); // Loop through output pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { useZMin = ((idxZ + outExt[4]) <= wholeExtent[4]) ? 0 : -inIncs[2]; useZMax = ((idxZ + outExt[4]) >= wholeExtent[5]) ? 0 : inIncs[2]; for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++) { useYMin = ((idxY + outExt[2]) <= wholeExtent[2]) ? 0 : -inIncs[1]; useYMax = ((idxY + outExt[2]) >= wholeExtent[3]) ? 0 : inIncs[1]; if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } for (idxX = 0; idxX <= maxX; idxX++) { useXMin = ((idxX + outExt[0]) <= wholeExtent[0]) ? 0 : -inIncs[0]; useXMax = ((idxX + outExt[0]) >= wholeExtent[1]) ? 0 : inIncs[0]; // calculate the neighbors d = vector[0] = static_cast<double>(*in2Ptr) * ratio[0]; normalizeFactor = (d * d); d = vector[1] = static_cast<double>(in2Ptr[1]) * ratio[1]; normalizeFactor += (d * d); if (axesNum == 3) { d = vector[2] = static_cast<double>(in2Ptr[2]) * ratio[2]; normalizeFactor += (d * d); } if (normalizeFactor != 0.0) { normalizeFactor = 1.0 / sqrt(normalizeFactor); } // Vector points positive along this idx? // (can point along multiple axes) d = vector[0] * normalizeFactor; if (d > 0.5) { neighborA = useXMax; neighborB = useXMin; } else if (d < -0.5) { neighborB = useXMax; neighborA = useXMin; } else { neighborA = 0; neighborB = 0; } d = vector[1] * normalizeFactor; if (d > 0.5) { neighborA += useYMax; neighborB += useYMin; } else if (d < -0.5) { neighborB += useYMax; neighborA += useYMin; } if (axesNum == 3) { d = vector[2] * normalizeFactor; if (d > 0.5) { neighborA += useZMax; neighborB += useZMin; } else if (d < -0.5) { neighborB += useZMax; neighborA += useZMin; } } // now process the components for (idxC = 0; idxC < maxC; idxC++) { // Pixel operation // Set Output Magnitude if (in1Ptr[neighborA] > *in1Ptr || in1Ptr[neighborB] > *in1Ptr) { *outPtr = 0; } else { *outPtr = *in1Ptr; // also check for them being equal is neighbor with larger ptr if ((neighborA > neighborB)&&(in1Ptr[neighborA] == *in1Ptr)) { *outPtr = 0; } else if ((neighborB > neighborA)&&(in1Ptr[neighborB] == *in1Ptr)) { *outPtr = 0; } } outPtr++; in1Ptr++; } in2Ptr += axesNum; } outPtr += outIncY; in1Ptr += inIncY; in2Ptr += in2IncY; } outPtr += outIncZ; in1Ptr += inIncZ; in2Ptr += in2IncZ; } } //---------------------------------------------------------------------------- // This method is passed a input and output regions, and executes the filter // algorithm to fill the output from the inputs. // It just executes a switch statement to call the correct function for // the regions data types. void vtkImageNonMaximumSuppression::ThreadedRequestData( vtkInformation * vtkNotUsed( request ), vtkInformationVector ** vtkNotUsed( inputVector ), vtkInformationVector * vtkNotUsed( outputVector ), vtkImageData ***inData, vtkImageData **outData, int outExt[6], int id) { void *in1Ptr; void *in2Ptr; void *outPtr; if (id == 0) { if (outData[0]->GetPointData()->GetScalars()) { outData[0]->GetPointData()->GetScalars()->SetName("SuppressedMaximum"); } } in1Ptr = inData[0][0]->GetScalarPointerForExtent(outExt); in2Ptr = inData[1][0]->GetScalarPointerForExtent(outExt); outPtr = outData[0]->GetScalarPointerForExtent(outExt); // this filter expects that input is the same type as output. if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType() || inData[1][0]->GetScalarType() != outData[0]->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData[0][0]->GetScalarType() << ", must match out ScalarType " << outData[0]->GetScalarType()); return; } switch (inData[0][0]->GetScalarType()) { vtkTemplateMacro( vtkImageNonMaximumSuppressionExecute(this, inData[0][0], static_cast<VTK_TT *>(in1Ptr), inData[1][0], static_cast<VTK_TT *>(in2Ptr), outData[0], static_cast<VTK_TT *>(outPtr), outExt, id)); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } void vtkImageNonMaximumSuppression::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Dimensionality: " << this->Dimensionality << "\n"; os << indent << "HandleBoundaries: " << (this->HandleBoundaries ? "On\n" : "Off\n"); }
31.804598
86
0.565685
[ "vector" ]
141dc7b8a191ed108a159e59989b492e5f3d2fb4
16,402
cpp
C++
libs/polygon/test/polygon_segment_test.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/polygon/test/polygon_segment_test.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/polygon/test/polygon_segment_test.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// Boost.Polygon library polygon_segment_test.cpp file // Copyright Andrii Sydorchuk 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <algorithm> #include <list> #define BOOST_TEST_MODULE POLYGON_SEGMENT_TEST #include <boost/mpl/list.hpp> #include <boost/test/test_case_template.hpp> #include "boost/polygon/polygon.hpp" using namespace boost::polygon; typedef boost::mpl::list<int> test_types; BOOST_AUTO_TEST_CASE_TEMPLATE(segment_data_test, T, test_types) { typedef point_data<T> point_type; typedef segment_data<T> segment_type; point_type point1(1, 2); point_type point2(3, 4); segment_type segment1(point1, point2); segment_type segment2 = segment1; BOOST_CHECK(segment1.low() == point1); BOOST_CHECK(segment1.high() == point2); BOOST_CHECK(segment1.get(LOW) == point1); BOOST_CHECK(segment1.get(HIGH) == point2); BOOST_CHECK(segment1 == segment2); BOOST_CHECK(!(segment1 != segment2)); BOOST_CHECK(!(segment1 < segment2)); BOOST_CHECK(!(segment1 > segment1)); BOOST_CHECK(segment1 <= segment2); BOOST_CHECK(segment1 >= segment2); segment1.low(point2); segment1.high(point1); BOOST_CHECK(segment1.low() == point2); BOOST_CHECK(segment1.high() == point1); BOOST_CHECK(!(segment1 == segment2)); BOOST_CHECK(segment1 != segment2); segment2.set(LOW, point2); segment2.set(HIGH, point1); BOOST_CHECK(segment1 == segment2); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_traits_test, T, test_types) { typedef point_data<T> point_type; typedef segment_data<T> segment_type; point_type point1(1, 2); point_type point2(3, 4); segment_type segment = segment_mutable_traits<segment_type>::construct(point1, point2); BOOST_CHECK(segment_traits<segment_type>::get(segment, LOW) == point1); BOOST_CHECK(segment_traits<segment_type>::get(segment, HIGH) == point2); segment_mutable_traits<segment_type>::set(segment, LOW, point2); segment_mutable_traits<segment_type>::set(segment, HIGH, point1); BOOST_CHECK(segment_traits<segment_type>::get(segment, LOW) == point2); BOOST_CHECK(segment_traits<segment_type>::get(segment, HIGH) == point1); } template <typename T> struct Segment { point_data<T> p0; point_data<T> p1; }; namespace boost { namespace polygon { template <typename T> struct geometry_concept< Segment<T> > { typedef segment_concept type; }; template <typename T> struct segment_traits< Segment<T> > { typedef T coordinate_type; typedef point_data<T> point_type; static point_type get(const Segment<T>& segment, direction_1d dir) { return dir.to_int() ? segment.p1 : segment.p0; } }; template <typename T> struct segment_mutable_traits< Segment<T> > { typedef point_data<T> point_type; static inline void set(Segment<T>& segment, direction_1d dir, const point_type& point) { if (dir.to_int()) { segment.p1 = point; } else { segment.p0 = point; } } static inline Segment<T> construct(const point_type& point1, const point_type& point2) { Segment<T> segment; segment.p0 = point1; segment.p1 = point2; return segment; } }; } } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test1, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(1, 2); point_type point2(3, 4); point_type point3(2, 3); segment_type segment1 = construct<segment_type>(point1, point2); BOOST_CHECK(segment1.p0 == point1); BOOST_CHECK(segment1.p1 == point2); BOOST_CHECK(get(segment1, LOW) == point1); BOOST_CHECK(low(segment1) == point1); BOOST_CHECK(get(segment1, HIGH) == point2); BOOST_CHECK(high(segment1) == point2); BOOST_CHECK(center(segment1) == point3); set(segment1, LOW, point2); set(segment1, HIGH, point1); BOOST_CHECK(segment1.p0 == point2); BOOST_CHECK(segment1.p1 == point1); BOOST_CHECK(get(segment1, LOW) == point2); BOOST_CHECK(get(segment1, HIGH) == point1); low(segment1, point1); high(segment1, point2); BOOST_CHECK(segment1.p0 == point1); BOOST_CHECK(segment1.p1 == point2); segment_data<T> segment2 = copy_construct< segment_data<T> >(segment1); BOOST_CHECK(segment1.p0 == segment2.low()); BOOST_CHECK(segment1.p1 == segment2.high()); BOOST_CHECK(equivalence(segment1, segment2)); segment_data<T> segment3 = construct< segment_data<T> >(point2, point1); assign(segment1, segment3); BOOST_CHECK(segment1.p0 == point2); BOOST_CHECK(segment1.p1 == point1); BOOST_CHECK(!equivalence(segment1, segment2)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test2, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(1, 2); point_type point2(2, 4); point_type point3(0, 0); point_type point4(5, 10); point_type point5(1, 3); point_type point6(2, 3); point_type point7(100, 201); point_type point8(100, 200); point_type point9(100, 199); segment_type segment1 = construct<segment_type>(point1, point2); segment_type segment2 = construct<segment_type>(point2, point1); segment_type segment3 = construct<segment_type>(point1, point5); BOOST_CHECK(orientation(segment1, point1) == 0); BOOST_CHECK(orientation(segment1, point2) == 0); BOOST_CHECK(orientation(segment1, point3) == 0); BOOST_CHECK(orientation(segment1, point4) == 0); BOOST_CHECK(orientation(segment1, point5) == 1); BOOST_CHECK(orientation(segment2, point5) == -1); BOOST_CHECK(orientation(segment1, point6) == -1); BOOST_CHECK(orientation(segment2, point6) == 1); BOOST_CHECK(orientation(segment1, point7) == 1); BOOST_CHECK(orientation(segment2, point7) == -1); BOOST_CHECK(orientation(segment1, point8) == 0); BOOST_CHECK(orientation(segment1, point9) == -1); BOOST_CHECK(orientation(segment2, point9) == 1); BOOST_CHECK(orientation(segment3, point6) == -1); BOOST_CHECK(orientation(segment3, point3) == 1); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test3, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; segment_type segment1 = construct<segment_type>(point_type(0, 0), point_type(1, 2)); segment_type segment2 = construct<segment_type>(point_type(0, 0), point_type(2, 4)); segment_type segment3 = construct<segment_type>(point_type(0, 0), point_type(2, 3)); segment_type segment4 = construct<segment_type>(point_type(0, 0), point_type(2, 5)); segment_type segment5 = construct<segment_type>(point_type(0, 2), point_type(2, 0)); BOOST_CHECK(orientation(segment1, segment2) == 0); BOOST_CHECK(orientation(segment1, segment3) == -1); BOOST_CHECK(orientation(segment3, segment1) == 1); BOOST_CHECK(orientation(segment1, segment4) == 1); BOOST_CHECK(orientation(segment4, segment1) == -1); BOOST_CHECK(orientation(segment1, segment5) == -1); BOOST_CHECK(orientation(segment5, segment1) == 1); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test4, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(1, 2); point_type point2(3, 6); point_type point3(2, 4); point_type point4(4, 8); point_type point5(0, 0); segment_type segment = construct<segment_type>(point1, point2); BOOST_CHECK(contains(segment, point1, true)); BOOST_CHECK(contains(segment, point2, true)); BOOST_CHECK(!contains(segment, point1, false)); BOOST_CHECK(!contains(segment, point2, false)); BOOST_CHECK(contains(segment, point3, false)); BOOST_CHECK(!contains(segment, point4, true)); BOOST_CHECK(!contains(segment, point5, true)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test5, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(0, 0); point_type point2(10, 0); point_type point3(5, 0); point_type point4(-1, 0); point_type point5(11, 0); segment_type segment = construct<segment_type>(point1, point2); BOOST_CHECK(contains(segment, point1, true)); BOOST_CHECK(contains(segment, point2, true)); BOOST_CHECK(!contains(segment, point1, false)); BOOST_CHECK(!contains(segment, point2, false)); BOOST_CHECK(contains(segment, point3, false)); BOOST_CHECK(!contains(segment, point4, true)); BOOST_CHECK(!contains(segment, point5, true)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test6, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(0, 0); point_type point2(1, 2); point_type point3(2, 4); point_type point4(3, 6); point_type point5(4, 8); point_type point6(5, 10); segment_type segment1 = construct<segment_type>(point2, point5); segment_type segment2 = construct<segment_type>(point3, point4); segment_type segment3 = construct<segment_type>(point1, point3); segment_type segment4 = construct<segment_type>(point4, point6); BOOST_CHECK(contains(segment1, segment2, false)); BOOST_CHECK(!contains(segment2, segment1, true)); BOOST_CHECK(!contains(segment1, segment3, true)); BOOST_CHECK(!contains(segment1, segment4, true)); BOOST_CHECK(contains(segment1, segment1, true)); BOOST_CHECK(!contains(segment1, segment1, false)); } template<typename T> struct Transformer { void scale(T& x, T& y) const { x *= 2; y *= 2; } void transform(T& x, T& y) const { T tmp = x; x = y; y = tmp; } }; BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test7, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(1, 2); point_type point2(4, 6); segment_type segment1 = construct<segment_type>(point1, point2); scale_up(segment1, 3); BOOST_CHECK(low(segment1) == point_type(3, 6)); BOOST_CHECK(high(segment1) == point_type(12, 18)); scale_down(segment1, 3); BOOST_CHECK(low(segment1) == point1); BOOST_CHECK(high(segment1) == point2); BOOST_CHECK(length(segment1) == 5); move(segment1, HORIZONTAL, 1); move(segment1, VERTICAL, 2); BOOST_CHECK(low(segment1) == point_type(2, 4)); BOOST_CHECK(high(segment1) == point_type(5, 8)); BOOST_CHECK(length(segment1) == 5); convolve(segment1, point_type(1, 2)); BOOST_CHECK(low(segment1) == point_type(3, 6)); BOOST_CHECK(high(segment1) == point_type(6, 10)); deconvolve(segment1, point_type(2, 4)); BOOST_CHECK(low(segment1) == point1); BOOST_CHECK(high(segment1) == point2); scale(segment1, Transformer<T>()); BOOST_CHECK(low(segment1) == point_type(2, 4)); BOOST_CHECK(high(segment1) == point_type(8, 12)); transform(segment1, Transformer<T>()); BOOST_CHECK(low(segment1) == point_type(4, 2)); BOOST_CHECK(high(segment1) == point_type(12, 8)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test8, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; segment_type segment1 = construct<segment_type>(point_type(0, 0), point_type(1, 2)); segment_type segment2 = construct<segment_type>(point_type(1, 2), point_type(2, 4)); segment_type segment3 = construct<segment_type>(point_type(2, 4), point_type(0, 4)); segment_type segment4 = construct<segment_type>(point_type(0, 4), point_type(0, 0)); BOOST_CHECK(abuts(segment1, segment2, HIGH)); BOOST_CHECK(abuts(segment2, segment3, HIGH)); BOOST_CHECK(abuts(segment3, segment4, HIGH)); BOOST_CHECK(abuts(segment4, segment1, HIGH)); BOOST_CHECK(!abuts(segment1, segment2, LOW)); BOOST_CHECK(!abuts(segment2, segment3, LOW)); BOOST_CHECK(!abuts(segment3, segment4, LOW)); BOOST_CHECK(!abuts(segment4, segment1, LOW)); BOOST_CHECK(abuts(segment2, segment1)); BOOST_CHECK(abuts(segment3, segment2)); BOOST_CHECK(abuts(segment4, segment3)); BOOST_CHECK(abuts(segment1, segment4)); BOOST_CHECK(!abuts(segment1, segment3)); BOOST_CHECK(!abuts(segment2, segment4)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test9, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; segment_type segment1 = construct<segment_type>(point_type(0, 0), point_type(2, 2)); segment_type segment2 = construct<segment_type>(point_type(1, 1), point_type(3, 3)); segment_type segment3 = construct<segment_type>(point_type(2, 2), point_type(-1, -1)); segment_type segment4 = construct<segment_type>(point_type(1, 3), point_type(3, 1)); segment_type segment5 = construct<segment_type>(point_type(2, 2), point_type(1, 3)); BOOST_CHECK(intersects(segment1, segment2, false)); BOOST_CHECK(intersects(segment1, segment2, true)); BOOST_CHECK(intersects(segment1, segment3, false)); BOOST_CHECK(intersects(segment1, segment3, true)); BOOST_CHECK(intersects(segment2, segment3, false)); BOOST_CHECK(intersects(segment2, segment3, true)); BOOST_CHECK(intersects(segment4, segment3, false)); BOOST_CHECK(intersects(segment4, segment3, true)); BOOST_CHECK(intersects(segment4, segment2, false)); BOOST_CHECK(intersects(segment4, segment2, true)); BOOST_CHECK(!intersects(segment3, segment5, false)); BOOST_CHECK(intersects(segment3, segment5, true)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test10, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; segment_type segment1 = construct<segment_type>(point_type(0, 0), point_type(0, 2)); segment_type segment2 = construct<segment_type>(point_type(0, 1), point_type(0, 3)); segment_type segment3 = construct<segment_type>(point_type(0, 1), point_type(0, 2)); segment_type segment4 = construct<segment_type>(point_type(0, 2), point_type(0, 3)); segment_type segment5 = construct<segment_type>(point_type(0, 2), point_type(2, 2)); segment_type segment6 = construct<segment_type>(point_type(0, 1), point_type(1, 1)); BOOST_CHECK(intersects(segment1, segment1, false)); BOOST_CHECK(intersects(segment1, segment1, true)); BOOST_CHECK(intersects(segment1, segment2, false)); BOOST_CHECK(intersects(segment1, segment2, true)); BOOST_CHECK(intersects(segment1, segment3, false)); BOOST_CHECK(intersects(segment1, segment3, true)); BOOST_CHECK(intersects(segment2, segment3, false)); BOOST_CHECK(intersects(segment2, segment3, true)); BOOST_CHECK(!intersects(segment1, segment4, false)); BOOST_CHECK(intersects(segment1, segment4, true)); BOOST_CHECK(!intersects(segment1, segment5, false)); BOOST_CHECK(intersects(segment1, segment5, true)); BOOST_CHECK(intersects(segment1, segment6, false)); BOOST_CHECK(intersects(segment1, segment6, true)); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test11, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; point_type point1(1, 2); point_type point2(7, 10); segment_type segment1 = construct<segment_type>(point1, point2); BOOST_CHECK(euclidean_distance(segment1, point1) == 0.0); BOOST_CHECK(euclidean_distance(segment1, point2) == 0.0); BOOST_CHECK(euclidean_distance(segment1, point_type(10, 14)) == 5.0); BOOST_CHECK(euclidean_distance(segment1, point_type(-3, -1)) == 5.0); BOOST_CHECK(euclidean_distance(segment1, point_type(0, 9)) == 5.0); BOOST_CHECK(euclidean_distance(segment1, point_type(8, 3)) == 5.0); } BOOST_AUTO_TEST_CASE_TEMPLATE(segment_concept_test12, T, test_types) { typedef point_data<T> point_type; typedef Segment<T> segment_type; segment_type segment1 = construct<segment_type>(point_type(0, 0), point_type(3, 4)); segment_type segment2 = construct<segment_type>(point_type(2, 0), point_type(0, 2)); segment_type segment3 = construct<segment_type>(point_type(1, -7), point_type(10, 5)); segment_type segment4 = construct<segment_type>(point_type(7, 7), point_type(10, 11)); BOOST_CHECK(euclidean_distance(segment1, segment2) == 0.0); BOOST_CHECK(euclidean_distance(segment1, segment3) == 5.0); BOOST_CHECK(euclidean_distance(segment1, segment4) == 5.0); }
37.967593
93
0.715157
[ "transform" ]
141f059ba31ef9381787d1b6ada62025308b3a1b
10,492
cpp
C++
2006/samples/graphics/DrawOrder/layerDialog.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2006/samples/graphics/DrawOrder/layerDialog.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2006/samples/graphics/DrawOrder/layerDialog.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// // // (C) Copyright 2002-2003 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // layerDialog.cpp : implementation file #include "stdafx.h" #include "layerDialog.h" #include <string.h> #include "util.h" #include "accmd.h" // layerDialog dialog IMPLEMENT_DYNAMIC(layerDialog, CDialog) //constructor layerDialog::layerDialog(CWnd* pParent /*=NULL*/) : CDialog(layerDialog::IDD, pParent) { /*void*/ } //destructor layerDialog::~layerDialog() { /*void*/ } //data exchange void layerDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LAYERLIST, m_layerList); DDX_Control(pDX, IDC_BUTTON_ENTORDER, m_entOrderBtn); DDX_Control(pDX, IDC_BUTTON_LAYERORDER, m_layerOrderBtn); } BEGIN_MESSAGE_MAP(layerDialog, CDialog) ON_BN_CLICKED(IDCLOSE, OnBnClickedClose) ON_BN_CLICKED(IDC_BUTTON_ENTORDER, OnBnClickedButtonEntorder) ON_BN_CLICKED(IDC_BUTTON_LAYERORDER, OnBnClickedButtonLayerorder) ON_BN_CLICKED(IDC_BUTTON_APPLY, OnBnClickedButtonApply) ON_BN_CLICKED(IDC_BUTTONOK, OnBnClickedButtonok) ON_LBN_SELCHANGE(IDC_LAYERLIST, OnLbnSelchangeLayerlist) END_MESSAGE_MAP() //This function display the layer order in CDraglistbox. //"layers" is an array of layerIds. iRepeats is an interger array which indicate //if the draworders of entities on a certain layer are continuous. For example, if //iRepeat.at(0) is 0, the draworders of entities on layers.at(0) are continous. If iRepeat.at(0) //is greater than 0, draworders of entities on layers.at(0) are not continuous and the layer name //of layers.at(0) displayed in the list box will have a "*" prefix and postfix. bool layerDialog::displayLayerOrder(AcDbObjectIdArray &layers, CUIntArray* iRepeats) { //Clear the current display m_layerList.ResetContent(); //if iRepeat is NULL, just list the layers' names in the array, "layers". if (iRepeats == NULL) { for (int i = 0; i < layers.length(); i++) { AcDbObject* pLayer; if (Acad::eOk == acdbOpenObject(pLayer, layers.at(i), AcDb::kForRead)) { const char* name; AcDbLayerTableRecord::cast(pLayer)->getName(name); char newName[260]; strcpy(newName, " "); strcat(newName, name); strcat(newName, " "); m_layerList.AddString(newName); } pLayer->close(); } // You can't drag any item beyond the last item in CDragListbox by default. //This sample workaroud this problem by appending an empty string to the end of layer list. m_layerList.AddString(""); return true; } else //if iRepeats != NULL { for (int i = 0; i < layers.length(); i++) { AcDbObject* pLayer; if (Acad::eOk == acdbOpenObject(pLayer, layers.at(i), AcDb::kForRead)) { const char* name; AcDbLayerTableRecord::cast(pLayer)->getName(name); //iRepeats->GetAt(i) > 0 indicates the draworders of entities on layers.at(i) are not continuous if (iRepeats->GetAt(i) > 0) { char newName[kNameLength]; //prefix "*" strcpy(newName, "*"); strcat(newName, name); //postfix "*" strcat(newName, "*"); m_layerList.AddString(newName); }else //if iRepeat->GetAt(i)==0, the draworders of entities on layers.at(i) are continous { char newName[kNameLength]; //prefix " " strcpy(newName, " "); strcat(newName, name); //postfix " " strcat(newName, " "); m_layerList.AddString(newName); } } pLayer->close(); } m_layerList.AddString(""); return true; } } //This function is to let tooltip control to handle messages first. This is used to display tooltips on buttons BOOL layerDialog::PreTranslateMessage(MSG* pMsg) { m_tooltipCtrl.RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } // onInitDialog event handling BOOL layerDialog::OnInitDialog( ) { CDialog::OnInitDialog(); //Create tooltips m_tooltipCtrl.Create(this); m_tooltipCtrl.SetMaxTipWidth(300); m_tooltipCtrl.Activate(true); m_tooltipCtrl.AddTool(&m_entOrderBtn, _T("\r\n Sort the layer list by the order \r\n entities appear in the drawing \r\n")); m_tooltipCtrl.AddTool(&m_layerOrderBtn, _T("\r\n Sort the layer list by the \r\n order in the layer table. \r\n")); //Displayer all the layers in the order in the layer table m_layerList.SubclassDlgItem(IDC_LAYERLIST, this); AcDbObjectIdArray arrAllLayers; if(getAllLayers(arrAllLayers)) if(displayLayerOrder(arrAllLayers, NULL)) return true; return false; } //Button,"cancel",is clicked void layerDialog::OnBnClickedClose() { OnCancel(); } //Button,"Sort By Entity Order", is clicked void layerDialog::OnBnClickedButtonEntorder() { Acad::ErrorStatus es ; AcDbObjectIdArray ents; AcDbObjectIdArray layers; CUIntArray iRepeat; AcDbSortentsTable *pSortTab = NULL; //Get the AcDbSortEntsTable object if(getOrCreateSortEntsDictionary(pSortTab)) { //Get the draw order of all the entities es = pSortTab->getFullDrawOrder(ents); pSortTab->close(); pSortTab = NULL; if(es == Acad::eOk) { if(ents.isEmpty() == Adesk::kFalse) { //Iterate through all the entities for(int i = 0; i < ents.length(); i++) { AcDbEntity* pEnt; acdbOpenObject(pEnt,ents.at(i),AcDb::kForRead); //If the array "layers" is empty, append the entity's layerId to array "layers" //and append 0 to array "iRepeats" if(layers.isEmpty() == true) { layers.append(pEnt->layerId()); iRepeat.Add(0); } else //if layers.isEmpty() == false { //If the entity's layerId is the same as the layerId of last entity, go to the next entity. if( pEnt->layerId() == layers.last()) continue; int index; //If the entity's layerId is not the same as the last entity, but it's appeared before, change the //corresponding item in array "iRepeat" to 1 to indicate the draworders of entities on that layer are //not continuous if(Adesk::kTrue == layers.find( pEnt->layerId(), index)) { iRepeat.SetAt(index, 1); }else //If the entity's layerId hasn't appear before, append it to the array ,"layers" { layers.append(pEnt->layerId()); iRepeat.Add(0); } } pEnt->close(); } } } //Display the layer order in the dragListBox. displayLayerOrder(layers, &iRepeat); } } //Button, "Sort By Layer Table" is clicked void layerDialog::OnBnClickedButtonLayerorder() { AcDbObjectIdArray arrAllLayers; //Get all the layerIds in the layer table getAllLayers(arrAllLayers); //Display all the layers in the order in layer table. displayLayerOrder(arrAllLayers,NULL); } //Button, "Apply", is clicked void layerDialog::OnBnClickedButtonApply() { //redraw entities based on the layer order in the dragListBox ApplyLayerOrder(); //Refresh the layer list in the dragListBox. refreshList(); return; } //Button,"OK" , is clicked void layerDialog::OnBnClickedButtonok() { //redraw entities based on the layer order in the dragListBox ApplyLayerOrder(); OnOK(); } //If the last item in the dragListBox(the empty string) is selected, //deselect it and select the last layer name in stead. void layerDialog::OnLbnSelchangeLayerlist() { if(m_layerList.GetCurSel()==m_layerList.GetCount()-1) { m_layerList.SetCurSel(m_layerList.GetCount()-2); } } //Refresh the layer list in the dragBox after reordering the entities based on //layer order. This is to change the prefix and postfix from "*" to " " since //the draworders of entities on all the layers should be continuous by now. bool layerDialog::refreshList(void) { CStringArray arrItems; for(int i=0;i<m_layerList.GetCount();i++) { CString sItem; m_layerList.GetText(i,sItem); if(sItem[0]=='*') sItem.Replace('*',' '); arrItems.Add(sItem); } //Clear current display and display the updated names. m_layerList.ResetContent(); for(int i=0;i<arrItems.GetCount();i++) { m_layerList.AddString(arrItems.GetAt(i)); } return true; } //redraw all entities based on the order of the layers in the dragListBox void layerDialog::ApplyLayerOrder(void) { AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase(); Acad::ErrorStatus es ; if(pDb) { AcDbObjectIdArray AllEnts; //Iterate through the layer names in the dragListBox for (int i = 0; i < m_layerList.GetCount()-1; i++) { AcDbObjectIdArray entsOnLayer; CString str; char* layerName; m_layerList.GetText(i, str); //Remove prefix and postfix if there is any if(str[0] == ' ' || str[0] == '*') str = str.Mid(1, str.GetLength() - 2); layerName = str.GetBuffer(str.GetLength()); //Get all the entities on the layer if(getAllEntitiesOnLayer(layerName, entsOnLayer)) //Append all the entities on the layer to array, "AllEnts" AllEnts.append(entsOnLayer); str.ReleaseBuffer(); } //Get the AcDbSortEntsTable AcDbSortentsTable *pSortTab = NULL; if(getOrCreateSortEntsDictionary(pSortTab)) { //Use setRelativeDrawOrder method to set the entities' draworders based on the layer they reside es = pSortTab->setRelativeDrawOrder(AllEnts); } pSortTab->close(); pSortTab = NULL; //Regen to update the screen. ads_regen(); return; } }
27.978667
127
0.67623
[ "object" ]
141fb0a3e358cf5b5c6f67985b4b01463485a28a
46,365
cpp
C++
src/rpc/aggregate_signature_test.cpp
blockchaingate/fabcoin
ae69201eb9f73e3bb82d7332f84a99f242d171b2
[ "MIT" ]
26
2018-04-24T00:33:11.000Z
2022-03-26T15:46:04.000Z
src/rpc/aggregate_signature_test.cpp
blockchaingate/fabcoin
ae69201eb9f73e3bb82d7332f84a99f242d171b2
[ "MIT" ]
4
2018-07-17T13:33:26.000Z
2018-08-27T07:10:49.000Z
src/rpc/aggregate_signature_test.cpp
blockchaingate/fabcoin
ae69201eb9f73e3bb82d7332f84a99f242d171b2
[ "MIT" ]
22
2018-04-24T00:33:31.000Z
2022-02-03T09:40:26.000Z
// Copyright (c) 2018 FA Enterprise system // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "crypto/sha3.h" #include "../aggregate_schnorr_signature.h" #include "utilstrencodings.h" #include "encodings_crypto.h" #include <primitives/transaction.h> #include <core_io.h> #include <coins.h> #include <txmempool.h> #include <validation.h> #include <univalue.h> #include <iostream> #include <mutex> void avoidCompilerWarningsDefinedButNotUsedAggregateSignature() { (void) FetchSCARShardPublicKeysInternalPointer; } extern CTxMemPool mempool; std::vector<SignatureAggregate> currentSigners; SignatureAggregate currentAggregator; static std::mutex aggregateSignatureLock; extern UniValue getlogfile(const JSONRPCRequest& request); void splitString(const std::string& input, const std::string& delimiters, std::vector<std::string>& output) { output.clear(); std::string current; for (unsigned i = 0; i < input.size(); i ++) { char currentChar = input[i]; if (delimiters.find(currentChar) != std::string::npos) { if (current.size() > 0) { output.push_back(current); } current.clear(); continue; } current.push_back(currentChar); } if (current.size() > 0) { output.push_back(current); } } bool getVectorOfStringsFromBase64List( const std::string& input, std::vector<std::string>& output, std::stringstream* commentsOnFailure ) { std::string decoded = DecodeBase64(input); splitString(decoded, ", ", output); return true; } //Attempts to recognize the input encoding (comma delimited string vs base64 encoded comma delimited string). bool getVectorOfStrings(const UniValue& input, std::vector<std::string>& output, std::stringstream* commentsOnFailure) { output.clear(); if (!input.isStr()) { if (commentsOnFailure != 0) { *commentsOnFailure << "Failed to extract base64 encoded vectors: input univalue is not a string. Input: " << input.write() << ". "; } return false; } std::string inputString = input.get_str(); if (inputString == "") return true; std::vector<std::string> candidateOutputNoBase64; std::vector<std::string> candidateOutputBase64; bool goodBase64 = getVectorOfStringsFromBase64List(inputString, candidateOutputBase64, commentsOnFailure); splitString(inputString, ", ", candidateOutputNoBase64); if (!goodBase64) { output = candidateOutputNoBase64; return true; } //Both the base64 and regular encoding are valid. Return whichever resulted in more entries. if (candidateOutputBase64.size() >= candidateOutputNoBase64.size()) { output = candidateOutputBase64; return true; } output = candidateOutputNoBase64; return true; } //Expected input: comma/space separated list of hex. To do: auto recognize & decode other encodings. bool getVectorsUnsigned( const UniValue& input, std::vector<std::vector<unsigned char> >& output, std::stringstream* commentsOnFailure ) { output.clear(); if (!input.isStr()) { if (commentsOnFailure != 0) { *commentsOnFailure << "Failed to extract base64 encoded vectors: input univalue is not a string. Input: " << input.write() << ". "; } return false; } std::string inputString = input.get_str(); if (inputString == "") { return true; } std::vector<std::string> outputStrings; splitString(inputString, ", ", outputStrings); output.resize(outputStrings.size()); for (unsigned i = 0; i < outputStrings.size(); i ++) { if (!Encodings::fromHex(outputStrings[i], output[i], commentsOnFailure)) { if (commentsOnFailure != nullptr) { *commentsOnFailure << "Failed to extract vector of unsigned chars from index " << i << ".\n"; } return false; } } return true; } void appendSignerStateToUniValue(UniValue& output) { UniValue signerKeyPairs; signerKeyPairs.setArray(); for (unsigned i = 0; i < currentSigners.size(); i ++) { //std::cout << "DEBUG: Computing uni value for signer: " << i << std::endl; signerKeyPairs.push_back(currentSigners[i].toUniValueTransitionState__SENSITIVE()); } output.pushKV("signers", signerKeyPairs); } std::string toStringVector(const std::vector<std::string>& input) { std::stringstream out; out << "("; for (unsigned i = 0; i < input.size(); i ++) { out << input[i]; if (i + 1 != input.size()) out << ", "; } out << ")"; return out.str(); } bool getBitmap(const UniValue input, std::vector<bool>& output, std::stringstream* commentsOnFailure) { if (!input.isStr()) { if (commentsOnFailure != 0) *commentsOnFailure << "Failed to read bitmap: I expected string as input, got instead: " << input.write(); return false; } const std::string& inputString = input.get_str(); //std::cout << "DEBUG: reading bitmap from: " << inputString; output.resize(inputString.size()); for (unsigned i = 0; i < inputString.size(); i ++) { output[i] = false; if (inputString[i] == '1') output[i] = true; } return true; } bool getVectorOfEllipticCurveElements(const UniValue& input, std::vector<PublicKeyKanban>& output, std::stringstream* commentsOnFailure) { std::vector<std::string> inputVector; if (! getVectorOfStrings(input, inputVector, commentsOnFailure)) { return false; } output.resize(inputVector.size()); for (unsigned i = 0; i < inputVector.size(); i ++) { if (inputVector[i] == "" || inputVector[i] == "(uninitialized)") { continue; } if (!output[i].MakeFromStringRecognizeFormat(inputVector[i], commentsOnFailure)) { if (commentsOnFailure != 0) { *commentsOnFailure << "Failed to convert element index " << i << " (" << i + 1 << " out of " << inputVector.size() << ") to elliptic curve element (used for public keys, commitments, ...). Input vector: " << toStringVector(inputVector) << ". "; } return false; } } return true; } bool getVectorOfSecp256k1Scalars(const UniValue& input, std::vector<PrivateKeyKanban>& output, std::stringstream* commentsOnFailure) { std::vector<std::string> inputVector; if (!getVectorOfStrings(input, inputVector, commentsOnFailure)) { return false; } //std::cout << "DEBUG: HIGHLIGHT: got to here in gettting secp256k1 vectors. " << std::endl; output.resize(inputVector.size()); for (unsigned i = 0; i < inputVector.size(); i ++) { if (!output[i].MakeFromBase58DetectCheck(inputVector[i], commentsOnFailure)) { if (inputVector[i] == "" || inputVector[i] == "(uninitialized)") { continue; } if (commentsOnFailure != 0) { *commentsOnFailure << "Failed to convert element index " << i << " (" << i + 1 << " out of " << inputVector.size() << ") to secp256k1 scalar (used for private keys, nonces, ...). Input vector: " << toStringVector(inputVector) << ". "; } return false; } } return true; } UniValue testaggregatesignaturegeneratepublic(UniValue& result, std::vector<PrivateKeyKanban>& desiredPrivateKeys) { std::lock_guard<std::mutex> lockGuard1(aggregateSignatureLock); std::stringstream errorStream; currentSigners.resize(desiredPrivateKeys.size()); for (unsigned i = 0; i < currentSigners.size(); i ++) { currentSigners[i].ResetNoPrivateKeyGeneration(false, true); currentSigners[i].myPrivateKey__KEEP_SECRET = desiredPrivateKeys[i]; if (!currentSigners[i].myPrivateKey__KEEP_SECRET.ComputePublicKey(currentSigners[i].myPublicKey, &errorStream)) { errorStream << "Faled to generate public key index " << i << " (" << i + 1 << " out of " << currentSigners.size() << "). The private key seed was: " << currentSigners[i].myPrivateKey__KEEP_SECRET.ToHexNonConst(); result.pushKV("error", errorStream.str()); return result; } } std::sort(currentSigners.begin(), currentSigners.end(), SignatureAggregate::leftHasSmallerPublicKey); currentAggregator.ResetGeneratePrivateKey(true, false); currentAggregator.allPublicKeys.clear(); for (unsigned i = 0; i < currentSigners.size(); i ++) { currentAggregator.allPublicKeys.push_back(currentSigners[i].myPublicKey); } if (!currentAggregator.InitializePublicKeys(currentAggregator.allPublicKeys, &errorStream)) { errorStream << "Failed to initialize aggregator's public keys. "; result.pushKV("error", errorStream.str()); return result; } for (unsigned i = 0; i < currentSigners.size(); i ++) { if (!currentSigners[i].InitializePublicKeys(currentAggregator.allPublicKeys, &errorStream)) { errorStream << "Failed to initialize signer inded " << i << "."; result.pushKV("error", errorStream.str()); return result; } } appendSignerStateToUniValue(result); result.pushKV("aggregator", currentAggregator.toUniValueTransitionState__SENSITIVE()); return result; } UniValue testaggregatesignatureinitialize(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "testaggregatesignatureinitialize (desiredPrivateKeysBase64)\n" "\nTests schnorr aggregate signature initialization." "\nTo be documented further.\n" ); std::vector<PrivateKeyKanban> desiredPublicKeys; std::stringstream errorStream; UniValue result; result.setObject(); result.pushKV("input", request.params[0]); //std::cout << "DEBUG: GOT to here. First parameter: " << request.params[0].write() << std::endl; if (!getVectorOfSecp256k1Scalars(request.params[0], desiredPublicKeys, &errorStream)) { errorStream << "Failed to read the desired private keys from: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } return testaggregatesignaturegeneratepublic(result, desiredPublicKeys); } UniValue testaggregatesignaturegenerateprivatekeys(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw std::runtime_error( "testaggregatesignaturegenerateprivatekeys (numberOfSigners)\n" "\nTests schnorr aggregate signature initialization." "\nTo be documented further.\n" ); } UniValue result; result.setObject(); result.pushKV("input", request.params); int numPrivateKeys = - 1; std::stringstream errorStream; if (request.params[0].isNum()) { numPrivateKeys = request.params[0].get_int(); } else if (request.params[0].isStr()) { std::stringstream converter(request.params[0].get_str()); converter >> numPrivateKeys; } else { errorStream << "Failed to extract number of public keys from your input. "; result.pushKV("error", errorStream.str()); return result; } if (numPrivateKeys < 1 || numPrivateKeys > 256) { errorStream << "The number of private keys is expected to be a number between 1 and 256. " << "Your input was: " << numPrivateKeys << "."; result.pushKV("error", errorStream.str()); return result; } std::vector<PrivateKeyKanban> desiredPrivateKeys; desiredPrivateKeys.resize(numPrivateKeys); for (unsigned i = 0; i < desiredPrivateKeys.size(); i ++) { if (!desiredPrivateKeys[i].GenerateRandomSecurely()) { errorStream << "Failed to generate public key index " << i << " (" << i + 1 << " out of " << numPrivateKeys << "). " << "This means the random generator is not working: perhaps something is wrong with the crypto library? "; result.pushKV("error", errorStream.str()); return result; } } if (numPrivateKeys < 15) { std::sort( desiredPrivateKeys.begin(), desiredPrivateKeys.end(), PrivateKeyKanban::leftSmallerThanRightByPublicKeyCompressed ); } UniValue privateKeyArray; privateKeyArray.setArray(); for (unsigned i = 0; i < desiredPrivateKeys.size(); i ++) { privateKeyArray.push_back(desiredPrivateKeys[i].ToBase58NonConstFABMainnetPrefix()); } result.pushKV("privateKeys", privateKeyArray); return result; } UniValue testaggregateverificationcomplete(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 2) throw std::runtime_error( "testaggregateverificationcomplete(...)\n" "\nTests schnorr aggregate signature aggregation. Available in -testkanban mode only." "\nTo be documented further.\n" ); UniValue result; result.setObject(); result.pushKV("input", request.params); std::stringstream errorStream; SignatureAggregate theVerifier; theVerifier.currentState = theVerifier.stateVerifyingAggregateSignatures; if (!request.params[0].isStr()) { errorStream << "The first argument (signatureComplete), is not a string, as expected. Instead, it is: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } if (!request.params[1].isStr()) { errorStream << "The second argument (messageHex), is not a string, as expected. Instead, it is: " << request.params[1].write(); result.pushKV("error", errorStream.str()); return result; } std::vector<unsigned char> decodedMessageVector; if (!Encodings::fromHex(request.params[1].get_str(), decodedMessageVector, &errorStream)) { errorStream << "Failed to hex-decode your input: " << request.params[1].write(); result.pushKV("error", errorStream.str()); return result; } std::string decodedMessage((const char*)decodedMessageVector.data(), decodedMessageVector.size()); std::vector<unsigned char> decodedCompleteSignature; if (!Encodings::fromHex(request.params[0].get_str(), decodedCompleteSignature, &errorStream)) { errorStream << "Failed to hex-decode your input: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } bool resultBool = theVerifier.VerifyFromSignatureComplete(decodedCompleteSignature, decodedMessage, &errorStream); result.pushKV("result", resultBool); if (resultBool) { result.pushKV("resultHTML", "<b style='color:green'>Verified</b>"); } else { result.pushKV("resultHTML", "<b style='color:red'>Failed</b>"); } if (!resultBool) { result.pushKV("verifier", theVerifier.toUniValueTransitionState__SENSITIVE()); result.pushKV("reason", errorStream.str()); } return result; } UniValue testaggregatesignatureverification(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) { throw std::runtime_error( "testaggregatesignatureaggregation ( ...)\n" "\nTests schnorr aggregate signature aggregation. Available in -testkanban mode only." "\nTo be documented further.\n" ); } std::lock_guard<std::mutex> guard1(aggregateSignatureLock); UniValue result; result.setObject(); result.pushKV("input", request.params); std::stringstream errorStream; if (!request.params[0].isStr()) { result.pushKV("error", "The first parameter expected to be a string (hex-encoded message). "); return result; } if (!request.params[1].isStr()) { result.pushKV("error", "The second parameter expected to be a string (hex-encoded signature bytes)."); return result; } if (!request.params[2].isStr()) { result.pushKV("error", "The fourth parameter expected to be a string (hex-encoded then comma-separated public keys)."); return result; } std::string messageHex = request.params[0].get_str(); std::vector<unsigned char> messageBytes; std::string signatureHex = request.params[1].get_str(); std::vector<unsigned char> signatureBytes; std::vector<std::vector<unsigned char> > publicKeyBytes; if (!Encodings::fromHex(messageHex, messageBytes, &errorStream)) { errorStream << "Failed to hex-decode your message: " << messageHex; result.pushKV("error", errorStream.str()); return result; } if (!Encodings::fromHex(signatureHex, signatureBytes, &errorStream)) { errorStream << "Failed to hex-decode your signature bytes: " << signatureHex; result.pushKV("error", errorStream.str()); return result; } if (!getVectorsUnsigned(request.params[2], publicKeyBytes, &errorStream) ) { errorStream << "Failed to read signature serialization. "; result.pushKV("error", errorStream.str()); return result; } SignatureAggregate theVerifier; theVerifier.flagIsAggregator = true; theVerifier.currentState = theVerifier.stateVerifyingAggregateSignatures; bool resultBool = theVerifier.VerifyMessageSignatureUncompressedPublicKeysDeserialized( messageBytes, signatureBytes, publicKeyBytes, &errorStream, true ); result.pushKV("result", resultBool); if (resultBool) { result.pushKV("resultHTML", "<b style='color:green'>Verified</b>"); } else { result.pushKV("resultHTML", "<b style='color:red'>Failed</b>"); } if (!resultBool) { result.pushKV("verifier", theVerifier.toUniValueTransitionState__SENSITIVE()); result.pushKV("aggregator", currentAggregator.toUniValueTransitionState__SENSITIVE()); result.pushKV("reason", errorStream.str()); } return result; } UniValue testaggregatesignatureaggregation(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "testaggregatesignatureaggregation ( solutionsBase58CheckThenCommaSeparatedThenBase64Encoded)\n" "\nTests schnorr aggregate signature aggregation. Available in -testkanban mode only." "\nTo be documented further.\n" ); std::lock_guard<std::mutex> guard1(aggregateSignatureLock); UniValue result; result.setObject(); result.pushKV("input", request.params); std::stringstream errorStream; std::vector<PrivateKeyKanban> inputSolutions; if (!getVectorOfSecp256k1Scalars(request.params[0], inputSolutions, & errorStream)) { errorStream << "Failed to read solutions. "; result.pushKV("error", errorStream.str()); return result; } if (!currentAggregator.TransitionSignerState4or5ToState6(inputSolutions, &errorStream)) { errorStream << "Failed to aggregate the solutions. "; result.pushKV("error", errorStream.str()); return result; } currentAggregator.ComputeCompleteSignature(); result.pushKV("aggregator", currentAggregator.toUniValueTransitionState__SENSITIVE()); return result; } UniValue testaggregatesignaturesolutions(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 4) throw std::runtime_error( "testaggregatesignaturesolutions ( committedSignersBitmap, challengeBase58CheckEncoded, aggregateCommitmentHex, aggregatePublicKeyHex)\n" "\nTests schnorr aggregate signature solutions. Available in -testkanban mode only." "\nTo be documented further.\n" ); std::lock_guard<std::mutex> guard1(aggregateSignatureLock); UniValue result; result.setObject(); result.pushKV("input", request.params); PrivateKeyKanban inputChallenge; PublicKeyKanban inputAggregateKey; PublicKeyKanban inputAggregateCommitment; std::stringstream errorStream; std::vector<bool> inputBitmap; if (!getBitmap(request.params[0], inputBitmap, &errorStream)) { result.pushKV("error", errorStream.str()); return result; } if (!inputChallenge.MakeFromUniValueRecognizeFormat(request.params[1], &errorStream)) { errorStream << "Failed to read input challenge"; result.pushKV("error", errorStream.str()); return result; } //std::cout << "DEBUG: Read challenge: " << inputChallenge.ToBase58Check() << " from input: " << request.params[1].write() << std::endl; if (!inputAggregateCommitment.MakeFromUniValueRecognizeFormat(request.params[2], &errorStream)) { errorStream << "Failed to read input aggregate commitment"; result.pushKV("error", errorStream.str()); return result; } if (!inputAggregateKey.MakeFromUniValueRecognizeFormat(request.params[3], &errorStream)) { errorStream << "Failed to read input aggregate public key"; result.pushKV("error", errorStream.str()); return result; } //std::cout << "DEBUG: got to before transitioning signers" << std::endl; for (unsigned i = 0; i < currentSigners.size(); i ++) { if (!currentSigners[i].TransitionSignerState3or4ToState5 (inputBitmap, inputChallenge, inputAggregateCommitment, inputAggregateKey, &errorStream) ) { errorStream << "Failed to transition the state of signer " << i << " (" << i + 1 << " out of " << currentSigners.size() << "). "; result.pushKV("error", errorStream.str()); return result; } } //std::cout << "DEBUG: got to after transitioning signers" << std::endl; appendSignerStateToUniValue(result); return result; } UniValue testaggregatesignaturechallenge(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 2) throw std::runtime_error( "testaggregatesignaturechallenge (committedBitmap, commitmentsCommaSeparatedThenBase64Encoded)\n" "\nTests schnorr aggregate signature challenge. Available in -testkanban mode only." "\nTo be documented further.\n" ); std::lock_guard<std::mutex> guard1(aggregateSignatureLock); UniValue result; result.setObject(); result.pushKV("input", request.params); std::vector<PublicKeyKanban> theCommitments; std::stringstream errorStream, comments; //std::cout << "DEBUG: got to before elliptic curve elts. " << std::endl; if (!getVectorOfEllipticCurveElements(request.params[1], theCommitments, &errorStream)) { errorStream << "Failed to extract commitments from your input: " << request.params[1].write(); result.pushKV("error", errorStream.str()); return result; } if (currentSigners.size() < theCommitments.size()) { errorStream << "Currently, I have " << currentSigners.size() << " signers but I got more commitments: " << theCommitments.size(); result.pushKV("error", errorStream.str()); return result; } if (theCommitments.size() == 0) { errorStream << "0 commitments not allowed"; result.pushKV("error", errorStream.str()); return result; } if (currentSigners.size() > theCommitments.size()) { comments << "Got fewer commitments: " << theCommitments.size() << " than signers: " << currentSigners.size() << ". I am assuming the commitments belong to the first " << theCommitments.size() << " signers. "; } std::vector<bool> committedSigners; //std::cout << "DEBUG: got to before getbitmap. " << std::endl; if (!getBitmap(request.params[0], committedSigners, &errorStream)) { errorStream << "Failed to extract bitmap from the first argument: " << request.params[0].write() << ". "; result.pushKV("error", errorStream.str()); return result; } //std::cout << "DEBUG: got to after getbitmap. " << std::endl; theCommitments.resize(currentSigners.size()); if (!currentAggregator.TransitionSignerState2or3ToState4(theCommitments, committedSigners, nullptr, &errorStream)) { errorStream << "Aggregation of commitments failed. "; result.pushKV("error", errorStream.str()); if (comments.str() != "") { result.pushKV("comments", comments.str()); } return result; } if (comments.str() != "") { result.pushKV("comments", comments.str()); } result.pushKV("aggregator", currentAggregator.toUniValueTransitionState__SENSITIVE()); //std::cout << "DEBUG: got to before retun result. " << std::endl; return result; } UniValue testaggregatesignaturecommit(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "testaggregatesignaturecommit(messageHex, desiredNoncesCommaSeparatedBase64)\n" "\nTests schnorr aggregate signature commitment. Available in -testkanban mode only." "\nTo be documented further.\n" ); } std::lock_guard<std::mutex> guard1(aggregateSignatureLock); UniValue result; result.setObject(); result.pushKV("input", request.params); if (!request.params[0].isStr()) { result.pushKV("error", "Parameter 0 expected to be a hex-encoded string."); return result; } std::string messageHex = request.params[0].get_str(); std::string theMessage; std::stringstream errorStream; if (!Encodings::fromHex(messageHex, theMessage, &errorStream)) { errorStream << "Failed to hex-decode your message: " << messageHex << ". "; result.pushKV("error", errorStream.str()); return result; } std::vector<std::string> inputNonces; if (request.params.size() == 2) { if (!getVectorOfStrings(request.params[1], inputNonces, &errorStream)) { errorStream << "Failed to extract vector of string from: " << request.params[1].write(); result.pushKV("error", errorStream.str()); return result; } } UniValue signersReport; signersReport.setArray(); //compute commitments: for (unsigned i = 0; i < currentSigners.size(); i ++) { PrivateKeyKanban nonceParser; PrivateKeyKanban* desiredNonce = 0; if (i < inputNonces.size()) { if (!nonceParser.MakeFromBase58DetectCheck(inputNonces[i], &errorStream)) { errorStream << "Failed to read nonce index: " << i; result.pushKV("error", errorStream.str()); return result; } desiredNonce = &nonceParser; } if (!currentSigners[i].TransitionSignerState1or2ToState3(theMessage, &errorStream, desiredNonce)) { errorStream << "Signer " << i << " failed to transition from state 1 to state 3. "; result.pushKV("error", errorStream.str()); return result; } signersReport.push_back(currentSigners[i].toUniValueTransitionState__SENSITIVE()); } result.pushKV("signers", signersReport); if (!currentAggregator.TransitionAggregatorState1ToState2(theMessage, &errorStream)) { errorStream << "Failed to transition the aggregator from state 1 to state 2."; result.pushKV("error", errorStream.str()); return result; } result.pushKV("aggregator", currentAggregator.toUniValueTransitionState__SENSITIVE()); return result; } enum signatureType { signatureEcdsaDoubleSha256, signatureSchnorrSha3, }; UniValue testsignature(const JSONRPCRequest& request, signatureType theSignatureType) { UniValue result(UniValue::VOBJ); result.pushKV("input", request.params); std::stringstream errorStream; if (request.params.size() != 2 && request.params.size() != 3) { errorStream << "Function expects 2 or 3 arguments, got " << request.params.size() << " instead. "; result.pushKV("error", errorStream.str()); return result; } PrivateKeyKanban thePrivateKey; if (!thePrivateKey.MakeFromUniValueRecognizeFormat(request.params[0], &errorStream)) { errorStream << "Failed to convert input to secret (private key)"; result.pushKV("error", errorStream.str()); return result; } if (!request.params[1].isStr()) { errorStream << "Expected second argument to be a string, instead got: " << request.params[1].write(); result.pushKV("error", errorStream.str()); return result; } std::string message; if (!Encodings::fromHex(request.params[1].get_str(), message, &errorStream)) { errorStream << "Failed to hex-decode the message: " << request.params[2].write(); result.pushKV("error", errorStream.str()); return result; } PrivateKeyKanban nonce; bool hasNonce = (request.params.size() == 3); if (hasNonce) hasNonce = request.params[2].isStr(); if (hasNonce) hasNonce = (request.params[2].get_str() != ""); if (hasNonce) { if (!nonce.MakeFromUniValueRecognizeFormat(request.params[2], &errorStream)) { result.pushKV("error", errorStream.str()); return result; } } if (theSignatureType == signatureSchnorrSha3) { result.pushKV("signatureType", "SchnorrSha3"); SignatureSchnorr output; if (hasNonce) { output.Sign(thePrivateKey, message, &nonce, &result); } else { output.Sign(thePrivateKey, message, nullptr, &result); } result.pushKV("challengeHex", output.challenge.ToHexCompressed()); result.pushKV("solutionBase58Check", output.solution.ToBase58CheckNonConst()); result.pushKV("signatureBase58", output.ToBase58()); result.pushKV("signatureBase58Check", output.ToBase58Check()); } if (theSignatureType == signatureEcdsaDoubleSha256) { result.pushKV("signatureType", "ECDSADoubleSha256"); SignatureECDSA output; output.messageImplied = std::vector<unsigned char> (message.begin(), message.end()); std::stringstream commentsSensitive; output.SignSha256Squared(thePrivateKey, &commentsSensitive); result.pushKV("challengeHex", output.challengeR.ToHexNonConst()); result.pushKV("solutionBase58Check", output.solutionsS.ToBase58CheckNonConst()); result.pushKV("signature", HexStr(output.signatureBytes)); } result.pushKV("privateKeyBase58Check", thePrivateKey.ToBase58CheckNonConst()); return result; } UniValue testschnorrverification(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw std::runtime_error( "testschnorrverification ( message )\n" "\nTests schnorr signature verification. Available in -testkanban mode only." "\nTo be documented further.\n" ); UniValue result; result.setObject(); result.pushKV("input", request.params); SignatureSchnorr theSignature; std::stringstream errorStream; if (!theSignature.MakeFromUniValueRecognizeFormat(request.params[0], &errorStream)) { errorStream << "Failed to read signature from: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } if (!theSignature.publicKeyImplied.MakeFromUniValueRecognizeFormat(request.params[1], &errorStream)) { errorStream << "Failed to read public key from: " << request.params[1].write() << ". "; result.pushKV("error", errorStream.str()); return result; } if (!request.params[2].isStr()) { errorStream << "Expected string for the third argument (the message), instead I got: " << request.params[2].write(); result.pushKV("error", errorStream.str()); return result; } if (!Encodings::fromHex(request.params[2].get_str(), theSignature.messageImplied, &errorStream)) { errorStream << "Failed to hex-decode the message: " << request.params[2].write(); result.pushKV("error", errorStream.str()); return result; } result.pushKV("challengeHex", theSignature.challenge.ToHexCompressed()); result.pushKV("solutionBase58Check", theSignature.solution.ToBase58CheckNonConst()); result.pushKV("publicKeyHex", theSignature.publicKeyImplied.ToHexCompressed()); bool verificationResult = theSignature.Verify(&errorStream); result.pushKV("result", verificationResult); if (verificationResult) { result.pushKV("resultHTML", "<b style = 'color:green'>Verified</b>"); } else { result.pushKV("resultHTML", "<b style = 'color:red'>Failed</b>"); } return result; } UniValue testecdsaverification(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw std::runtime_error( "testecdsaverification ( message )\n" "\nTests ecdsa signature verification. Available in -testkanban mode only." "\nTo be documented further.\n" ); UniValue result; result.setObject(); result.pushKV("input", request.params); SignatureECDSA theSignature; std::stringstream errorStream; if (!request.params[0].isStr()) { errorStream << "First argument is expected to be a string, instead it is: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } std::string signatureBytes = request.params[0].get_str(); if (!theSignature.MakeFromBytes(std::vector<unsigned char>(signatureBytes.begin(), signatureBytes.end()) , &errorStream)) { errorStream << "Failed to read signature from: " << request.params[0].write(); result.pushKV("error", errorStream.str()); return result; } if (!theSignature.publicKeyImplied.MakeFromUniValueRecognizeFormat(request.params[1], &errorStream)) { errorStream << "Failed to read public key from: " << request.params[1].write() << ". "; result.pushKV("error", errorStream.str()); return result; } if (!request.params[2].isStr()) { errorStream << "Expected string for the third argument (the message), instead I got: " << request.params[2].write(); result.pushKV("error", errorStream.str()); return result; } if (!Encodings::fromHex(request.params[2].get_str(), theSignature.messageImplied, &errorStream)) { errorStream << "Failed to hex-decode the message: " << request.params[2].write(); result.pushKV("error", errorStream.str()); return result; } result.pushKV("challengeHex", theSignature.challengeR.ToHexNonConst()); result.pushKV("solutionBase58Check", theSignature.solutionsS.ToBase58CheckNonConst()); result.pushKV("publicKeyHex", theSignature.publicKeyImplied.ToHexCompressed()); bool verificationResult = theSignature.Verify(&errorStream); result.pushKV("result", verificationResult); if (verificationResult) { result.pushKV("resultHTML", "<b style = 'color:green'>Verified</b>"); } else { result.pushKV("resultHTML", "<b style = 'color:red'>Failed</b>"); } return result; } UniValue testschnorrsignature(const JSONRPCRequest& request) { if (request.fHelp) throw std::runtime_error( "testschnorrsignature ( message )\n" "\nTests schnorr signature. Available in -testkanban mode only." "\nTo be documented further.\n" ); return testsignature(request, signatureSchnorrSha3); } UniValue testecdsasignature(const JSONRPCRequest& request) { if (request.fHelp) throw std::runtime_error( "testschnorrsignature ( message )\n" "\nTests schnorr signature. Available in -testkanban mode only." "\nTo be documented further.\n" ); return testsignature(request, signatureEcdsaDoubleSha256); } UniValue testshathree(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "testshathree ( message )\n" "\nTests sha3 hash function. Available in -testkanban mode only." "\nTo be documented further.\n" ); std::string message = DecodeBase64(request.params[0].get_str() ); Sha3 theSha3; UniValue result(UniValue::VOBJ); result.pushKV("sha3_256", Encodings::toHexString(theSha3.computeSha3_256(message))); result.pushKV("keccak_256", Encodings::toHexString(theSha3.computeKeccak3_256(message))); return result; } UniValue testprivatekeygeneration(const JSONRPCRequest& request) { if (request.fHelp) throw std::runtime_error( "testprivatekeygeneration ( privatekey )\n" "\nTests private key generation. Available in -regtest only." "\nTo be documented further.\n" ); PrivateKeyKanban thePrivateKey; thePrivateKey.GenerateRandomSecurely(); UniValue result(UniValue::VOBJ); result.pushKV("privateKeyHex", thePrivateKey.ToHexNonConst()); result.pushKV("privateKeyBase58WithoutCheck", thePrivateKey.ToBase58NonConst()); result.pushKV("privateKeyBase58Check", thePrivateKey.ToBase58CheckNonConst()); return result; } UniValue testpublickeyfromprivate(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "testpublickeyfromprivate ( privatekey )\n" "\nTests public key generation. Available in -testkanban mode only." "\nTo be documented further.\n" ); UniValue result(UniValue::VOBJ); PrivateKeyKanban thePrivateKey; std::stringstream errorStream; if (!thePrivateKey.MakeFromUniValueRecognizeFormat(request.params[0], &errorStream)) { result.pushKV("error", errorStream.str()); return result; } PublicKeyKanban thePublicKey; if (!thePrivateKey.ComputePublicKey(thePublicKey, &errorStream)) { result.pushKV("error", errorStream.str()); return result; } //std::cout << "DEBUG: Public key computed: " << thePublicKey.ToHexCompressedWithLength() << std::endl; result.pushKV("secretHex", thePrivateKey.ToHexNonConst()); result.pushKV("privateKeyBase58Check", thePrivateKey.ToBase58CheckNonConst()); result.pushKV("publicKeyHexCompressed", thePublicKey.ToHexCompressed()); result.pushKV("input", request.params); return result; } UniValue insertaggregatesignature(const JSONRPCRequest& request) { std::stringstream errorStream; if (request.fHelp || request.params.size() != 2) { errorStream << "insertaggregatesignature not fully documented yet. \n" << "Inputs: rawtransaction (hexstring), rawAggregateSignatureHex (hex string). \n"; throw std::runtime_error(errorStream.str()); } if (!request.params[0].isStr()) { errorStream << "First pararameter is expected to be a hex string, got: " << request.params[0].write() << " instead. "; throw JSONRPCError(RPC_INVALID_PARAMETER, errorStream.str()); } if (!request.params[1].isStr()) { errorStream << "Third pararameter is expected to be a hex string, got: " << request.params[2].write() << " instead. "; throw JSONRPCError(RPC_INVALID_PARAMETER, errorStream.str()); } std::string inputRawTransaction = request.params[0].get_str(); std::string aggregateSignatureHex = request.params[1].get_str(); UniValue result; result.setObject(); CMutableTransaction transactionWithoutSignatures; if (!DecodeHexTx(transactionWithoutSignatures, inputRawTransaction, true)) { errorStream << "Failed to decode your input to raw transaction. Your input: " << inputRawTransaction << ". "; throw JSONRPCError(RPC_DESERIALIZATION_ERROR, errorStream.str()); } std::vector<unsigned char> aggregateSignatureBytes; if (!Encodings::fromHex(aggregateSignatureHex, aggregateSignatureBytes, &errorStream)) { errorStream << "Failed to decode your raw aggregate signature. Your input: " << aggregateSignatureHex << ". "; throw JSONRPCError(RPC_DESERIALIZATION_ERROR, errorStream.str()); } if (!DecodeHexTx(transactionWithoutSignatures, inputRawTransaction, true)) { errorStream << "Failed to decode your input to raw transaction. Your input: " << request.params[0].write() << ". "; throw JSONRPCError(RPC_DESERIALIZATION_ERROR, errorStream.str()); } result.pushKV("inputRawTransaction", inputRawTransaction); result.pushKV("inputTransactionDecodedAndRecoded", EncodeHexTx(transactionWithoutSignatures)); PrecomputedTransactionDatA dataBeforeSignature(transactionWithoutSignatures); std::stringstream commentsStream; // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view for (const CTxIn& txin : transactionWithoutSignatures.vin) { view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail. } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } for (unsigned int i = 0; i < transactionWithoutSignatures.vin.size(); i++) { CTxIn& currentInput = transactionWithoutSignatures.vin[i]; const Coin& coin = view.AccessCoin(currentInput.prevout); if (coin.IsSpent()) { errorStream << "Input " << currentInput.ToString() << " not found or already spent. <br>"; result.pushKV("comments", commentsStream.str()); result.pushKV("error", errorStream.str()); return result; } commentsStream << "Input coin: " << currentInput.ToString() << " is unspent as expected. <br>"; //const CScript& prevPubKey = coin.out.scriptPubKey; //const CAmount& amount = coin.out.nValue; if (!coin.out.scriptPubKey.IsPayToAggregateSignature()) { commentsStream << "Found unspent UTXO but it is not an aggregate one: " << currentInput.ToString(); continue; } commentsStream << "Found unspent aggregate UTXO: " << currentInput.ToString(); currentInput.scriptSig << aggregateSignatureBytes; } PrecomputedTransactionDatA dataAfterSignature(transactionWithoutSignatures); result.pushKV("precomputedTransactionDataBeforeSignature", dataBeforeSignature.ToString()); result.pushKV("precomputedTransactionDataAfterSignature", dataAfterSignature.ToString()); result.pushKV("comments", commentsStream.str()); result.pushKV("hex", EncodeHexTx(transactionWithoutSignatures)); return result; } static const CRPCCommand testCommands[] = { // category name actor (function) okSafe argNames // -------- -------------------------------------------- ------------------------------------------- -------- --------------------- { "test", "testprivatekeygeneration", &testprivatekeygeneration, true, {} }, { "test", "testpublickeyfromprivate", &testpublickeyfromprivate, true, {"privatekey"} }, { "test", "testshathree", &testshathree, true, {"message"} }, { "test", "testschnorrsignature", &testschnorrsignature, true, {"secret", "message", "nonce"} }, { "test", "testschnorrverification", &testschnorrverification, true, {"publickey", "message", "signature"} }, { "test", "testecdsasignature", &testecdsasignature, true, {"secret", "message", "nonce"} }, { "test", "testecdsaverification", &testecdsaverification, true, {"publickey", "message", "signature"} }, { "test", "testaggregatesignaturegenerateprivatekeys", &testaggregatesignaturegenerateprivatekeys, true, {"numberOfSigners"} }, { "test", "testaggregatesignatureinitialize", &testaggregatesignatureinitialize, true, {"publicKeys"} }, { "test", "testaggregatesignaturecommit", &testaggregatesignaturecommit, true, {"message", "desiredNoncesCommaSeparatedBase64"} }, { "test", "testaggregatesignaturechallenge", &testaggregatesignaturechallenge, true, {"committedSignersBitmap", "commitments"} }, { "test", "testaggregatesignaturesolutions", &testaggregatesignaturesolutions, true, {"committedSignersBitmap", "challenge", "aggregateCommitment", "aggregatePublicKey"} }, { "test", "testaggregatesignatureaggregation", &testaggregatesignatureaggregation, true, {"solutions"} }, { "test", "testaggregatesignatureverification", &testaggregatesignatureverification, true, {"signature", "committedSignersBitmap", "publicKeys", "message"} }, { "test", "testaggregateverificationcomplete", &testaggregateverificationcomplete, true, {"signatureComplete", "messageBase64"} }, { "test", "insertaggregatesignature", &insertaggregatesignature, true, {"hexstring", "number", "hexstring"} }, { "test", "getlogfile", &getlogfile, true, {"string"} }, }; void RegisterTestCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(testCommands); vcidx++) t.appendCommand(testCommands[vcidx].name, &testCommands[vcidx]); }
44.753861
202
0.647881
[ "vector" ]
1420ddcc2ed4bebc9836b2f5b469edaa7a111ac3
1,766
cpp
C++
demos/testNd_uniform_mfsa.cpp
poluyan/mveqf
f1bc6f5fc2d6b3c52bbe8d4a2e3cd23686dc8df8
[ "Apache-2.0" ]
null
null
null
demos/testNd_uniform_mfsa.cpp
poluyan/mveqf
f1bc6f5fc2d6b3c52bbe8d4a2e3cd23686dc8df8
[ "Apache-2.0" ]
null
null
null
demos/testNd_uniform_mfsa.cpp
poluyan/mveqf
f1bc6f5fc2d6b3c52bbe8d4a2e3cd23686dc8df8
[ "Apache-2.0" ]
1
2019-02-06T15:25:26.000Z
2019-02-06T15:25:26.000Z
#include <iostream> #include <vector> #include <random> #include <mveqf/implicit_mfsa.h> int main() { std::mt19937_64 generator; generator.seed(1); std::uniform_int_distribution<int> dim_distr(10, 20); std::uniform_int_distribution<int> grid_distr(1, 20); std::uniform_real_distribution<float> bounds(-100.0f, 100.0f); size_t dimension = dim_distr(generator); std::vector<size_t> grid(dimension); for(auto & i : grid) i = grid_distr(generator); std::vector<float> lb(dimension); // lower bound std::vector<float> ub(dimension); // upper bound for(size_t i = 0; i != dimension; i++) { auto lower = bounds(generator); auto upper = bounds(generator); while(lower > upper) { lower = bounds(generator); upper = bounds(generator); } lb[i] = lower; ub[i] = upper; } auto sample = std::make_shared<mveqf::mfsa::MFSA<std::uint8_t>>(); sample->set_dimension(dimension); size_t nsamples = 2000; for(size_t i = 0; i != nsamples; i++) { std::vector<std::uint8_t> point(dimension); for(size_t j = 0; j != point.size(); j++) { std::uniform_int_distribution<int> grid_distr(0, grid[j] - 1); point[j] = grid_distr(generator); } if(!sample->search(point)) sample->insert(point); } mveqf::ImplicitQuantileMFSA<std::uint8_t, float> mveqfunc(lb, ub, grid); mveqfunc.set_sample_shared_and_fill_count(sample); std::uniform_real_distribution<float> ureal01(0.0f, 1.0f); std::vector<float> values01(dimension); std::vector<float> sampled(dimension); size_t nsampled = 100; for(size_t i = 0; i != nsampled; i++) { for(auto & j : values01) j = ureal01(generator); mveqfunc.transform(values01, sampled); for(const auto & j : sampled) std::cout << std::fixed << j << '\t'; std::cout << std::endl; } }
24.873239
73
0.673273
[ "vector", "transform" ]
1421411756fb51d5baab609e218f92e3392d66e6
7,134
cc
C++
libcef/renderer/content_renderer_client.cc
appjs/cef3
18c0c9a7cb2990e656de950be53d2e5079a1f490
[ "BSD-3-Clause" ]
2
2015-04-05T11:14:57.000Z
2015-04-19T15:42:23.000Z
libcef/renderer/content_renderer_client.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
null
null
null
libcef/renderer/content_renderer_client.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "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 "libcef/renderer/content_renderer_client.h" #include "libcef/common/cef_messages.h" #include "libcef/common/content_client.h" #include "libcef/renderer/browser_impl.h" #include "libcef/renderer/render_process_observer.h" #include "libcef/renderer/thread_util.h" #include "libcef/renderer/v8_impl.h" #include "content/common/child_thread.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "ipc/ipc_sync_channel.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebPrerenderingSupport.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebPrerendererClient.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "v8/include/v8.h" namespace { // Stub implementation of WebKit::WebPrerenderingSupport. class CefPrerenderingSupport : public WebKit::WebPrerenderingSupport { public: virtual ~CefPrerenderingSupport() {} private: virtual void add(const WebKit::WebPrerender& prerender) OVERRIDE {} virtual void cancel(const WebKit::WebPrerender& prerender) OVERRIDE {} virtual void abandon(const WebKit::WebPrerender& prerender) OVERRIDE {} }; // Stub implementation of WebKit::WebPrerendererClient. class CefPrerendererClient : public content::RenderViewObserver, public WebKit::WebPrerendererClient { public: explicit CefPrerendererClient(content::RenderView* render_view) : content::RenderViewObserver(render_view) { DCHECK(render_view); render_view->GetWebView()->setPrerendererClient(this); } private: virtual ~CefPrerendererClient() {} virtual void willAddPrerender(WebKit::WebPrerender* prerender) OVERRIDE {} }; } // namespace struct CefContentRendererClient::SchemeInfo { std::string scheme_name; bool is_local; bool is_display_isolated; }; CefContentRendererClient::CefContentRendererClient() { } CefContentRendererClient::~CefContentRendererClient() { } // static CefContentRendererClient* CefContentRendererClient::Get() { return static_cast<CefContentRendererClient*>( content::GetContentClient()->renderer()); } CefRefPtr<CefBrowserImpl> CefContentRendererClient::GetBrowserForView( content::RenderView* view) { CEF_REQUIRE_RT_RETURN(NULL); BrowserMap::const_iterator it = browsers_.find(view); if (it != browsers_.end()) return it->second; return NULL; } CefRefPtr<CefBrowserImpl> CefContentRendererClient::GetBrowserForMainFrame( WebKit::WebFrame* frame) { CEF_REQUIRE_RT_RETURN(NULL); BrowserMap::const_iterator it = browsers_.begin(); for (; it != browsers_.end(); ++it) { content::RenderView* render_view = it->second->render_view(); if (render_view && render_view->GetWebView() && render_view->GetWebView()->mainFrame() == frame) { return it->second; } } return NULL; } void CefContentRendererClient::OnBrowserDestroyed(CefBrowserImpl* browser) { BrowserMap::iterator it = browsers_.begin(); for (; it != browsers_.end(); ++it) { if (it->second.get() == browser) { browsers_.erase(it); return; } } // No browser was found in the map. NOTREACHED(); } void CefContentRendererClient::AddCustomScheme( const std::string& scheme_name, bool is_local, bool is_display_isolated) { SchemeInfo info = {scheme_name, is_local, is_display_isolated}; scheme_info_list_.push_back(info); } void CefContentRendererClient::RegisterCustomSchemes() { if (scheme_info_list_.empty()) return; SchemeInfoList::const_iterator it = scheme_info_list_.begin(); for (; it != scheme_info_list_.end(); ++it) { const SchemeInfo& info = *it; if (info.is_local) { WebKit::WebSecurityPolicy::registerURLSchemeAsLocal( WebKit::WebString::fromUTF8(info.scheme_name)); } if (info.is_display_isolated) { WebKit::WebSecurityPolicy::registerURLSchemeAsDisplayIsolated( WebKit::WebString::fromUTF8(info.scheme_name)); } } } void CefContentRendererClient::RenderThreadStarted() { render_loop_ = base::MessageLoopProxy::current(); observer_.reset(new CefRenderProcessObserver()); content::RenderThread* thread = content::RenderThread::Get(); thread->AddObserver(observer_.get()); WebKit::WebPrerenderingSupport::initialize(new CefPrerenderingSupport()); thread->Send(new CefProcessHostMsg_RenderThreadStarted); // Notify the render process handler. CefRefPtr<CefApp> application = CefContentClient::Get()->application(); if (application.get()) { CefRefPtr<CefRenderProcessHandler> handler = application->GetRenderProcessHandler(); if (handler.get()) handler->OnRenderThreadCreated(); } } void CefContentRendererClient::RenderViewCreated( content::RenderView* render_view) { CefRefPtr<CefBrowserImpl> browser = new CefBrowserImpl(render_view); browsers_.insert(std::make_pair(render_view, browser)); new CefPrerendererClient(render_view); } void CefContentRendererClient::DidCreateScriptContext( WebKit::WebFrame* frame, v8::Handle<v8::Context> context, int extension_group, int world_id) { // Notify the render process handler. CefRefPtr<CefApp> application = CefContentClient::Get()->application(); if (!application.get()) return; CefRefPtr<CefRenderProcessHandler> handler = application->GetRenderProcessHandler(); if (!handler.get()) return; CefRefPtr<CefBrowserImpl> browserPtr = CefBrowserImpl::GetBrowserForMainFrame(frame->top()); DCHECK(browserPtr.get()); if (!browserPtr.get()) return; CefRefPtr<CefFrameImpl> framePtr = browserPtr->GetWebFrameImpl(frame); v8::HandleScope handle_scope; v8::Context::Scope scope(context); CefRefPtr<CefV8Context> contextPtr(new CefV8ContextImpl(context)); handler->OnContextCreated(browserPtr.get(), framePtr.get(), contextPtr); } void CefContentRendererClient::WillReleaseScriptContext( WebKit::WebFrame* frame, v8::Handle<v8::Context> context, int world_id) { // Notify the render process handler. CefRefPtr<CefApp> application = CefContentClient::Get()->application(); if (!application.get()) return; CefRefPtr<CefRenderProcessHandler> handler = application->GetRenderProcessHandler(); if (!handler.get()) return; CefRefPtr<CefBrowserImpl> browserPtr = CefBrowserImpl::GetBrowserForMainFrame(frame->top()); DCHECK(browserPtr.get()); if (!browserPtr.get()) return; CefRefPtr<CefFrameImpl> framePtr = browserPtr->GetWebFrameImpl(frame); v8::HandleScope handle_scope; v8::Context::Scope scope(context); CefRefPtr<CefV8Context> contextPtr(new CefV8ContextImpl(context)); handler->OnContextReleased(browserPtr.get(), framePtr.get(), contextPtr); }
31.566372
86
0.745444
[ "render" ]
14232de561fb30b2b19b371b3b2cfe606eafde22
56,861
cpp
C++
src/audio/AppleAudioDevice.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
null
null
null
src/audio/AppleAudioDevice.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
null
null
null
src/audio/AppleAudioDevice.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
null
null
null
// // AppleAudioDevice.cpp // Created by Douglas Scott on 11/12/13. // // #include "AppleAudioDevice.h" #include <AudioUnit/AudioUnit.h> #include <MacTypes.h> #include <pthread.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <ugens.h> #include <sndlibsupport.h> // RTcmix header #include <RTSemaphore.h> #include <new> #include <syslog.h> #ifdef STANDALONE #include <CoreAudio/CoreAudio.h> #include <CoreAudio/AudioHardware.h> #include <CoreFoundation/CFRunLoop.h> // Test code to see if it is useful to make sure HW and render threads do not // access the circular buffer at the same time. Does not seem to be necessary. #define LOCK_IO 1 // OSX runs the rendering code in its own thread #define RENDER_IN_CALLBACK 0 // This is true for OSX. #define OUTPUT_CALLBACK_FIRST 1 #else /* IOS */ #define LOCK_IO 0 /* never for iOS */ #define RENDER_IN_CALLBACK 1 #define OUTPUT_CALLBACK_FIRST 0 #endif #if LOCK_IO #include <Lockable.h> #endif #define DEBUG 0 #if DEBUG > 0 #if !defined(IOSDEV) #define DERROR(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__) #define DPRINT(fmt, ...) printf(fmt, ## __VA_ARGS__) #define ENTER(fun) printf("Entering " #fun "\n"); #if DEBUG > 1 #define DPRINT1(fmt, ...) printf(fmt, ## __VA_ARGS__) #else #define DPRINT1(fmt, ...) #endif #else /* IOS */ #define DERROR(fmt, ...) syslog(LOG_ERR, fmt, ## __VA_ARGS__) #define DPRINT(fmt, ...) syslog(LOG_NOTICE, fmt, ## __VA_ARGS__) #define ENTER(fun) syslog(LOG_NOTICE, "Entering " #fun "\n"); #if DEBUG > 1 #define DPRINT1(fmt, ...) syslog(LOG_NOTICE, fmt, ## __VA_ARGS__) #else #define DPRINT1(fmt, ...) #endif #endif /* IOS */ #else /* DEBUG !> 0 */ #define ENTER(fun) #define DPRINT(fmt, ...) #define DPRINT1(fmt, ...) #if !defined(IOSDEV) #define DERROR(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__) #else #define DERROR(fmt, ...) syslog(LOG_ERR, fmt, ## __VA_ARGS__) #endif #endif // Utilities inline int max(int x, int y) { return (x >= y) ? x : y; } inline int min(int x, int y) { return (x < y) ? x : y; } inline int inAvailable(int filled, int size) { return size - filled; } const int kOutputBus = 0; const int kInputBus = 1; static const int REC = 0, PLAY = 1; static const char *errToString(OSStatus err); #ifdef STANDALONE static AudioDeviceID findDeviceID(const char *devName, AudioDeviceID *devList, int devCount, Boolean isInput); #endif struct AppleAudioDevice::Impl { Impl(); ~Impl(); #ifdef STANDALONE AudioDeviceID *deviceIDs; // Queried on system. int deviceCount; // Queried on system. char *deviceName; // Passed in by user. AudioDeviceID deviceID; Float64 savedDeviceSampleRate; // For reset #endif struct Port { int streamIndex; // Which stream int streamCount; // How many streams open int streamChannel; // 1st chan of first stream SInt32 *channelMap; // Channel map int channelMapCount; // number of channels in the map AudioBufferList *streamDesc; unsigned int deviceBufFrames; // hw buf length float *audioBuffer; // circ. buffer int audioBufFrames; // length of audioBuffers int audioBufChannels; // channels in audioBuffers int virtualChannels; // what is reported publically (may vary based on mono-stereo) int inLoc, outLoc; // circ. buffer indices int audioBufFilled; // audioBuffer samples available #if LOCK_IO Lockable lock; #endif int getFrames(void *, int, int); int sendFrames(void *, int, int); } port[2]; AudioStreamBasicDescription deviceFormat; // format AudioStreamBasicDescription clientFormat; // format int bufferSampleFormat; int frameCount; bool gotFormatNotification; bool paused; bool stopping; bool recording; // Used by OSX code bool playing; // Used by OSX code int inputFramesAvailable; pthread_t renderThread; RTSemaphore * renderSema; int underflowCount; AudioUnit audioUnit; AudioBufferList *inputBufferList; AudioBufferList * createInputBufferList(int inChannelCount, bool inInterleaved); void setBufferList(AudioBufferList *inList); void destroyInputBufferList(AudioBufferList *inList); int startRenderThread(AppleAudioDevice *parent); void stopRenderThread(); inline int outputDeviceChannels() const; static OSStatus audioUnitInputCallback(void *inUserData, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); static OSStatus audioUnitRenderCallback(void *inUserData, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); static void * renderProcess(void *context); static void propertyListenerProc(void *inRefCon, AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement); }; // I/O Functions int AppleAudioDevice::Impl::Port::getFrames(void *frameBuffer, int inFrameCount, int inFrameChans) { const int bufFrames = audioBufFrames; int bufLoc = 0; float **fFrameBuffer = (float **) frameBuffer; // non-interleaved DPRINT1("AppleAudioDevice::doGetFrames: inFrameCount = %d REC filled = %d\n", inFrameCount, audioBufFilled); #if LOCK_IO lock.lock(); #endif int streamsToCopy = 0; #ifdef STANDALONE assert(inFrameCount <= audioBufFilled); #else if (inFrameCount <= audioBufFilled) // For IOS, we need to handle the case where there is no audio to pull. #endif streamsToCopy = inFrameChans < streamCount ? inFrameChans : streamCount; DPRINT("AppleAudioDevice::doGetFrames: Copying %d non-interleaved internal bufs into %d-channel user frame\n", streamsToCopy, inFrameChans); int stream; for (stream = 0; stream < streamsToCopy; ++stream) { // Offset into serially-ordered, multi-channel non-interleaved buf. register float *buf = &audioBuffer[stream * bufFrames]; float *frame = fFrameBuffer[stream]; bufLoc = outLoc; DPRINT1("\tstream %d: raw offset into mono internal buffer: %ld (%d * %d)\n", stream, buf - &audioBuffer[0], stream, bufFrames); DPRINT1("\tread internal (already-offset) buf starting at outLoc %d\n", bufLoc); // Write each monaural frame from circ. buffer into a non-interleaved output frame. for (int out=0; out < inFrameCount; ++out) { if (bufLoc >= bufFrames) bufLoc -= bufFrames; // wrap frame[out] = buf[bufLoc++]; } } // Zero out any remaining frame channels for (; stream < inFrameChans; ++stream) { DPRINT("Zeroing user frame channel %d\n", stream); memset(fFrameBuffer[stream], 0, inFrameCount * sizeof(float)); } outLoc = bufLoc; audioBufFilled -= inFrameCount; #if LOCK_IO lock.unlock(); #endif DPRINT1("\tREC Filled now %d\n", audioBufFilled); DPRINT1("\tREC bufLoc ended at %d. Returning frameCount = %d\n", bufLoc, inFrameCount); return inFrameCount; } int AppleAudioDevice::Impl::Port::sendFrames(void *frameBuffer, int frameCount, int frameChans) { float **fFrameBuffer = (float **) frameBuffer; // non-interleaved const int bufFrames = audioBufFrames; int loc = 0; DPRINT("AppleAudioDevice::doSendFrames: frameCount = %d, PLAY filled = %d\n", frameCount, audioBufFilled); DPRINT("AppleAudioDevice::doSendFrames: Copying %d channel user frame into %d non-interleaved internal buf channels\n", frameChans, streamCount); #if LOCK_IO lock.lock(); #endif for (int stream = 0; stream < streamCount; ++stream) { loc = inLoc; float *frame = fFrameBuffer[stream]; // Offset into serially-ordered, multi-channel non-interleaved buf. float *buf = &audioBuffer[stream * bufFrames]; if (stream < frameChans) { // Write each non-interleaved input frame into circular buf. for (int in=0; in < frameCount; ++in) { if (loc >= bufFrames) loc -= bufFrames; // wrap buf[loc++] = frame[in]; } } else { DPRINT("Zeroing internal buf channel %d\n", stream); for (int in=0; in < frameCount; ++in) { if (loc >= bufFrames) loc -= bufFrames; // wrap buf[loc++] = 0.0f; } } } audioBufFilled += frameCount; inLoc = loc; #if LOCK_IO lock.unlock(); #endif DPRINT1("\tPLAY Filled now %d\n", audioBufFilled); DPRINT1("\tPLAY inLoc ended at %d. Returning frameCount = %d\n", inLoc, frameCount); return frameCount; } AppleAudioDevice::Impl::Impl() : #if defined(STANDALONE) deviceIDs(NULL), deviceName(NULL), deviceID(0), savedDeviceSampleRate(0.0), #endif renderThread(NULL), renderSema(NULL), underflowCount(0) { gotFormatNotification = false; paused = false; stopping = false; recording = false; playing = false; inputFramesAvailable = 0; inputBufferList = NULL; for (int n = REC; n <= PLAY; ++n) { port[n].streamIndex = 0; port[n].streamCount = 0; // Indicates that we are using the default. port[n].streamChannel = 0; port[n].channelMap = NULL; port[n].channelMapCount = 0; port[n].streamDesc = NULL; port[n].deviceBufFrames = 0; port[n].audioBufFrames = 0; port[n].audioBufChannels = 0; port[n].virtualChannels = 0; port[n].audioBuffer = NULL; port[n].inLoc = port[n].outLoc = 0; port[n].audioBufFilled = 0; } } AppleAudioDevice::Impl::~Impl() { delete [] port[REC].channelMap; delete [] port[PLAY].channelMap; delete [] (char *) port[REC].streamDesc; delete [] port[REC].audioBuffer; delete [] (char *) port[PLAY].streamDesc; delete [] port[PLAY].audioBuffer; #if defined(STANDALONE) delete [] deviceIDs; delete [] deviceName; #endif delete renderSema; destroyInputBufferList(inputBufferList); } AudioBufferList * AppleAudioDevice::Impl::createInputBufferList(int inChannelCount, bool inInterleaved) { Impl::Port *port = &this->port[REC]; int numBuffers = (inInterleaved) ? 1 : inChannelCount; int byteSize = sizeof(AudioBufferList) + (numBuffers - 1) * sizeof(AudioBufferList); void *rawmem = new char[byteSize]; DPRINT("AppleAudioDevice::Impl::createInputBufferList creating AudioBufferList with %d %d-channel buffers\n", numBuffers, port->audioBufChannels); AudioBufferList *newList = new (rawmem) AudioBufferList; newList->mNumberBuffers = numBuffers; // Set up constant values for each buffer from our port's state for (int n = 0; n < numBuffers; ++n) { newList->mBuffers[n].mNumberChannels = port->audioBufChannels; } return newList; } void AppleAudioDevice::Impl::setBufferList(AudioBufferList *inList) { Impl::Port *port = &this->port[REC]; // Point each buffer's data pointer at the appropriate offset into our port audioBuffer and set the byte size. for (int n = 0; n < inList->mNumberBuffers; ++n) { DPRINT1("\tbuffer[%d] mData set to stream frame offset %d, local offset %d, length %d\n", n, n * port->audioBufFrames, port->inLoc, port->deviceBufFrames); inList->mBuffers[n].mData = (void *) &port->audioBuffer[(n * port->audioBufFrames) + port->inLoc]; inList->mBuffers[n].mDataByteSize = port->deviceBufFrames * sizeof(float); } } void AppleAudioDevice::Impl::destroyInputBufferList(AudioBufferList *inList) { // delete in reverse of how we created it inList->~AudioBufferList(); char *rawmem = (char *) inList; delete [] rawmem; } void * AppleAudioDevice::Impl::renderProcess(void *context) { AppleAudioDevice *device = (AppleAudioDevice *) context; AppleAudioDevice::Impl *impl = device->_impl; if (setpriority(PRIO_PROCESS, 0, -20) != 0) { // perror("AppleAudioDevice::Impl::renderProcess: Failed to set priority of thread."); } while (true) { DPRINT("AppleAudioDevice::Impl::renderProcess waiting...\n"); impl->renderSema->wait(); if (impl->stopping) { DPRINT("AppleAudioDevice::Impl::renderProcess woke to stop -- breaking out\n"); break; } #if DEBUG > 0 if (impl->underflowCount > 0) { DPRINT("\nAppleAudioDevice::Impl::renderProcess woke up -- underflow count %d -- running slice\n", impl->underflowCount); --impl->underflowCount; } else { DPRINT("\nAppleAudioDevice::Impl::renderProcess woke up -- running slice\n"); } #endif bool ret = device->runCallback(); if (ret == false) { DPRINT("AppleAudioDevice: renderProcess: run callback returned false -- breaking out\n"); break; } } DPRINT("AppleAudioDevice: renderProcess: calling stop callback\n"); device->stopCallback(); DPRINT("AppleAudioDevice: renderProcess exiting\n"); return NULL; } OSStatus AppleAudioDevice::Impl::audioUnitInputCallback(void *inUserData, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { AppleAudioDevice *device = (AppleAudioDevice *) inUserData; Impl *impl = device->_impl; Port *port = &impl->port[REC]; OSStatus result = noErr; DPRINT("\nAppleAudioDevice: top of audioUnitInputCallback: inBusNumber: %d inNumberFrames: %u\n", (int)inBusNumber, (unsigned)inNumberFrames); assert (inBusNumber == kInputBus); assert (impl->recording); #if LOCK_IO if (!port->lock.tryLock()) { DPRINT("AppleAudioDevice: record section skipped due to block on render thread\n"); return noErr; } #endif DPRINT("\tCopying directly into port's audioBuffer via AudioBuffer\n"); // We supply our own AudioBufferList for input. Its buffers point into our port's buffer impl->setBufferList(impl->inputBufferList); // Pull audio from hardware into our AudioBufferList result = AudioUnitRender(impl->audioUnit, ioActionFlags, inTimeStamp, kInputBus, inNumberFrames, impl->inputBufferList); if (result != noErr) { DERROR("ERROR: audioUnitInputCallback: AudioUnitRender failed with status %d\n", (int)result); return result; } // If we are only recording, we are done here except for notifying the RTcmix rendering thread, or running the render. port->audioBufFilled += inNumberFrames; port->inLoc = (port->inLoc + inNumberFrames) % (port->audioBufFrames * port->audioBufChannels); DPRINT1("\tREC Filled = %d\n", port->audioBufFilled); DPRINT1("\tREC inLoc ended at %d\n", port->inLoc); #if LOCK_IO port->lock.unlock(); #endif // If we are only recording and not playing, we wake the render thread (or run the render call) here. // Otherwise, if we are playing as well, and the output callback did not precede us, we wait to do the render there. if (!impl->playing) { impl->frameCount += inNumberFrames; #if RENDER_IN_CALLBACK DPRINT("\tRunning render callback inline\n"); bool ret = device->runCallback(); if (ret == false) { DPRINT("\tRun callback returned false -- calling stop callback\n"); device->stopCallback(); } #else #if !OUTPUT_CALLBACK_FIRST DPRINT("\tWaking render thread\n"); impl->renderSema->post(); #endif #endif } #if OUTPUT_CALLBACK_FIRST DPRINT("\tWaking render thread\n"); impl->renderSema->post(); #endif return result; } OSStatus AppleAudioDevice::Impl::audioUnitRenderCallback(void *inUserData, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { AppleAudioDevice *device = (AppleAudioDevice *) inUserData; Impl *impl = device->_impl; int framesAdvanced = 0; Port *port; DPRINT("\nAppleAudioDevice: top of audioUnitRenderCallback: inBusNumber: %d inNumberFrames: %u\n", (int)inBusNumber, (unsigned)inNumberFrames); assert (inBusNumber == kOutputBus); if (impl->playing) { // Copy audio from our rendered buffer(s) into ioData to be written to the hardware port = &impl->port[PLAY]; #if LOCK_IO if (!port->lock.tryLock()) { DPRINT("AppleAudioDevice: playback section skipped due to block on render thread\n"); goto End; } #endif // const int framesToWrite = port->deviceBufFrames; // NOTE TO ME: Cannot guarantee that we will have space for deviceBufFrames worth of audio in output const int framesToWrite = inNumberFrames; const int destchans = 1; // non-interleaved output - change this if we use interleaved const int srcchans = port->audioBufChannels; const int bufLen = port->audioBufFrames * srcchans; int framesAvail = port->audioBufFilled; DPRINT("AppleAudioDevice: playback section (out buffer %d)\n", port->streamIndex); DPRINT1("framesAvail (Filled) = %d\n", framesAvail); if (framesAvail < framesToWrite) { #if DEBUG > 0 if ((impl->underflowCount %4) == 0) { DERROR("AppleAudioDevice (playback): framesAvail (%d) < needed (%d) -- UNDERFLOW\n", framesAvail, framesToWrite); DPRINT("\tzeroing input buffer and going on\n"); } ++impl->underflowCount; #endif for (int stream = 0; stream < port->streamCount; ++stream) { memset(&port->audioBuffer[stream * port->audioBufFrames], 0, bufLen * sizeof(float)); } framesAvail = framesToWrite; port->audioBufFilled += framesToWrite; } #if RENDER_IN_CALLBACK // If we are running inTraverse synchronously, we run it before we copy the data to the port's audio buffers #if OUTPUT_CALLBACK_FIRST if (!impl->recording) #endif { DPRINT("\tRunning render callback inline\n"); bool ret = device->runCallback(); if (ret == false) { DPRINT("\tRun callback returned false -- calling stop callback\n"); device->stopCallback(); } } #endif /* RENDER_IN_CALLBACK */ DPRINT1("\tPLAY outLoc begins at %d (out of %d)\n", port->outLoc, bufLen); int framesDone = 0; // Audio data has been written into port->audioBuffer during doSendFrames. // Treat it as circular buffer. // Copy that audio into the ioData buffer pointers. Channel counts always match. while (framesDone < framesToWrite) { int bufLoc = port->outLoc; DPRINT("\tLooping for %d (%d-channel) stream%s\n", port->streamCount, destchans, port->streamCount > 1 ? "s" : ""); for (int stream = 0; stream < port->streamCount; ++stream) { const int strIdx = stream + port->streamIndex; register float *src = &port->audioBuffer[stream * port->audioBufFrames]; register float *dest = (float *) ioData->mBuffers[strIdx].mData; bufLoc = port->outLoc; for (int n = 0; n < framesToWrite; ++n) { if (bufLoc == bufLen) // wrap bufLoc = 0; for (int ch = 0; ch < destchans; ++ch) { dest[ch] = src[bufLoc++]; } dest += destchans; } } port->audioBufFilled -= framesToWrite; port->outLoc = bufLoc; framesDone += framesToWrite; framesAdvanced = framesDone; #if LOCK_IO port->lock.unlock(); #endif } DPRINT1("\tPLAY Filled = %d\n", port->audioBufFilled); DPRINT1("\tPLAY bufLoc ended at %d\n", port->outLoc); } impl->frameCount += framesAdvanced; #if OUTPUT_CALLBACK_FIRST if (!impl->recording) #endif { #if !RENDER_IN_CALLBACK DPRINT("\tWaking render thread\n"); impl->renderSema->post(); #endif } End: DPRINT("AppleAudioDevice: leaving audioUnitRenderCallback\n\n"); return noErr; } union Prop { Float64 f64; Float32 f32; UInt32 uint; SInt32 sint; AudioStreamBasicDescription desc; }; #if DEBUG > 0 static const char *scopeToName(AudioUnitScope scope) { switch (scope) { case kAudioUnitScope_Input: return "Input"; case kAudioUnitScope_Output: return "Output"; default: return "Other"; } } static const char *elementToName(AudioUnitElement element) { switch (element) { case 0: return "Output"; case 1: return "Input"; default: return "Other"; } } #endif void AppleAudioDevice::Impl::propertyListenerProc(void *inRefCon, AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement) { DPRINT1(">>>> propertyListenerProc called for prop %d, scope: %s, bus: %s\n", (int)inID, scopeToName(inScope), elementToName(inElement)); AppleAudioDevice *device = (AppleAudioDevice *) inRefCon; Impl *impl = device->_impl; Prop theProp; UInt32 size = sizeof(theProp); OSStatus status = AudioUnitGetProperty(impl->audioUnit, inID, inScope, inElement, &theProp, &size); if (status != noErr) { DERROR(">>>> AppleAudioDevice: failed to retrieve property during listener proc: error %d\n", (int)status); return; } bool needToStop = false; switch (inID) { case kAudioUnitProperty_SampleRate: DPRINT(">>>> AppleAudioDevice: got sample rate notification: %f\n", theProp.f64); if (device->isRunning() && theProp.f64 != device->getSamplingRate()) { needToStop = true; } impl->gotFormatNotification = true; break; case kAudioUnitProperty_StreamFormat: #ifdef STANDALONE case kAudioDevicePropertyStreamFormat: #endif if (!impl->gotFormatNotification && ((inScope == kAudioUnitScope_Output && inElement == 0) || (inScope == kAudioUnitScope_Input && inElement == 1))) { DPRINT(">>>> AppleAudioDevice: got hardware stream format notification -- sr = %f\n", theProp.desc.mSampleRate); impl->gotFormatNotification = true; } if (device->isRunning() && theProp.desc.mSampleRate != device->getSamplingRate()) { needToStop = true; } break; #ifdef STANDALONE case kAudioDevicePropertyBufferFrameSize: DPRINT(">>>> AppleAudioDevice: got buffer frame size notification: %u\n", (unsigned)theProp.uint); if (device->isRunning() && theProp.uint != impl->port[!impl->recording].deviceBufFrames) { needToStop = true; } break; #endif case kAudioUnitProperty_LastRenderError: DPRINT(">>>> AppleAudioDevice: got render error notification: %d\n", (int)theProp.sint); break; } if (needToStop) { fprintf(stderr, "Device format changed - stopping\n"); syslog(LOG_ALERT, "Device format changed - stopping\n"); device->error("Device format changed - stopping"); device->stop(); } } int AppleAudioDevice::Impl::startRenderThread(AppleAudioDevice *parent) { DPRINT("\tAppleAudioDevice::Impl::startRenderThread: starting thread\n"); pthread_attr_t attr; pthread_attr_init(&attr); int status = pthread_attr_setschedpolicy(&attr, SCHED_RR); if (status != 0) { DERROR("startRenderThread: Failed to set scheduling policy\n"); } status = pthread_create(&renderThread, &attr, renderProcess, parent); pthread_attr_destroy(&attr); if (status < 0) { DERROR("Failed to create render thread"); } return status; } void AppleAudioDevice::Impl::stopRenderThread() { assert(renderThread != 0); // should not get called again! stopping = true; DPRINT("AppleAudioDevice::Impl::stopRenderThread: posting to semaphore for thread\n"); renderSema->post(); // wake up, it's time to die DPRINT("AppleAudioDevice::Impl::stopRenderThread: waiting for thread to finish\n"); if (pthread_join(renderThread, NULL) == -1) { DERROR("AppleAudioDevice::Impl::stopRenderThread: terminating thread!\n"); pthread_cancel(renderThread); renderThread = 0; } DPRINT("\tAppleAudioDevice::Impl::stopRenderThread: thread done\n"); } // Main class implementation AppleAudioDevice::AppleAudioDevice(const char *desc) : _impl(new Impl) { parseDeviceDescription(desc); } AppleAudioDevice::~AppleAudioDevice() { //DPRINT("AppleAudioDevice::~AppleAudioDevice()\n"); close(); AudioUnitUninitialize(_impl->audioUnit); AudioComponentInstanceDispose(_impl->audioUnit); delete _impl; } int AppleAudioDevice::doOpen(int mode) { ENTER(AppleAudioDevice::doOpen()); AppleAudioDevice::Impl *impl = _impl; OSStatus status; if (mode & Passive) { return error("AppleAudioDevice do not support passive device mode"); } impl->gotFormatNotification = false; impl->recording = ((mode & Record) != 0); impl->playing = ((mode & Playback) != 0); // Describe audio component AudioComponentDescription desc; desc.componentType = kAudioUnitType_Output; #ifdef IOS desc.componentSubType = kAudioUnitSubType_RemoteIO; // iOS #else desc.componentSubType = kAudioUnitSubType_HALOutput; // OSX #endif desc.componentFlags = 0; desc.componentFlagsMask = 0; desc.componentManufacturer = kAudioUnitManufacturer_Apple; AudioComponent comp = AudioComponentFindNext(NULL, &desc); status = AudioComponentInstanceNew(comp, &impl->audioUnit); if (status != noErr) { return appleError("Unable to create the output audio unit", status); } // Enable IO for playback and/or record. This is done before setting the (OSX) device. UInt32 enableInput = impl->recording; UInt32 enableOutput = impl->playing; status = AudioUnitSetProperty(impl->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &enableInput, sizeof(enableInput)); if (status != noErr) { return appleError("Unable to Enable/Disable input I/O on audio unit", status); } status = AudioUnitSetProperty(impl->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &enableOutput, sizeof(enableOutput)); if (status != noErr) { return appleError("Unable to Enable/Disable output I/O on audio unit", status); } #ifdef STANDALONE // Set the device for the HAL Audio Unit Boolean isInput = impl->recording && !impl->playing; AudioDeviceID devID = ::findDeviceID(impl->deviceName, impl->deviceIDs, impl->deviceCount, isInput); if (devID == 0) { char msg[64]; snprintf(msg, 64, "No matching device found for '%s'\n", impl->deviceName); return error(msg); } status = AudioUnitSetProperty(impl->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &devID, sizeof(devID)); if (status != noErr) { return appleError("Unable to set hardware device on audio unit", status); } // Set up property listeners status = AudioUnitAddPropertyListener(impl->audioUnit, kAudioDevicePropertyBufferFrameSize, Impl::propertyListenerProc, this); if (status != noErr) { return appleError("Unable to set BufferFrameSize listener on audio unit", status); } status = AudioUnitAddPropertyListener(impl->audioUnit, kAudioDevicePropertyStreamFormat, Impl::propertyListenerProc, this); if (status != noErr) { return appleError("Unable to set Device StreamFormat listener on audio unit", status); } #endif status = AudioUnitAddPropertyListener(impl->audioUnit, kAudioUnitProperty_SampleRate, Impl::propertyListenerProc, this); if (status != noErr) { return appleError("Unable to set SampleRate listener on audio unit", status); } status = AudioUnitAddPropertyListener(impl->audioUnit, kAudioUnitProperty_StreamFormat, Impl::propertyListenerProc, this); if (status != noErr) { return appleError("Unable to set AU StreamFormat listener on audio unit", status); } status = AudioUnitAddPropertyListener(impl->audioUnit, kAudioUnitProperty_LastRenderError, Impl::propertyListenerProc, this); if (status != noErr) { return appleError("Unable to set LastRenderError listener on audio unit", status); } // Get HW format and set I/O callback for each direction. if (impl->recording) { UInt32 size = sizeof(AudioStreamBasicDescription); status = AudioUnitGetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, // HW side kInputBus, &impl->deviceFormat, &size); if (status != noErr) return appleError("Cannot read input HW stream format", status); DPRINT("input HW format: sr %f fmt %d flags 0x%x fpp %d cpf %d bpc %d bpp %d bpf %d\n", impl->deviceFormat.mSampleRate, (int)impl->deviceFormat.mFormatID, (unsigned)impl->deviceFormat.mFormatFlags, (int)impl->deviceFormat.mFramesPerPacket, (int)impl->deviceFormat.mChannelsPerFrame, (int)impl->deviceFormat.mBitsPerChannel, (int)impl->deviceFormat.mBytesPerPacket, (int)impl->deviceFormat.mBytesPerFrame); AURenderCallbackStruct proc = { Impl::audioUnitInputCallback, this }; status = AudioUnitSetProperty(impl->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, kInputBus, &proc, sizeof(AURenderCallbackStruct)); if (status != noErr) { return appleError("Unable to set input callback", status); } } if (impl->playing) { UInt32 size = sizeof(AudioStreamBasicDescription); status = AudioUnitGetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, // HW side kOutputBus, &impl->deviceFormat, &size); if (status != noErr) return appleError("Cannot read output HW stream format", status); DPRINT("output HW format: sr %f fmt %d flags 0x%x fpp %d cpf %d bpc %d bpp %d bpf %d\n", impl->deviceFormat.mSampleRate, (int)impl->deviceFormat.mFormatID, (unsigned)impl->deviceFormat.mFormatFlags, (int)impl->deviceFormat.mFramesPerPacket, (int)impl->deviceFormat.mChannelsPerFrame, (int)impl->deviceFormat.mBitsPerChannel, (int)impl->deviceFormat.mBytesPerPacket, (int)impl->deviceFormat.mBytesPerFrame); AURenderCallbackStruct proc = { Impl::audioUnitRenderCallback, this }; status = AudioUnitSetProperty(impl->audioUnit, kAudioUnitProperty_SetRenderCallback, #ifdef STANDALONE /* DAS TESTING */ kAudioUnitScope_Global, #else kAudioUnitScope_Input, #endif kOutputBus, &proc, sizeof(AURenderCallbackStruct)); if (status != noErr) { return appleError("Unable to set output callback", status); } } return 0; } int AppleAudioDevice::doClose() { ENTER(AppleAudioDevice::doClose()); int status = 0; AURenderCallbackStruct proc = { NULL, NULL }; if (_impl->recording) { (void) AudioUnitSetProperty(_impl->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, kInputBus, &proc, sizeof(AURenderCallbackStruct)); } if (_impl->playing) { (void) AudioUnitSetProperty(_impl->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, kOutputBus, &proc, sizeof(AURenderCallbackStruct)); } #ifdef STANDALONE if (_impl->savedDeviceSampleRate != 0.0) { DPRINT("AppleAudioDevice::doClose: restoring original sampling rate\n"); setAudioHardwareRate(&_impl->savedDeviceSampleRate); } #endif _impl->frameCount = 0; return status; } int AppleAudioDevice::doStart() { ENTER(AppleAudioDevice::doStart()); _impl->stopping = false; // Pre-fill the input buffers int preBuffers = _impl->port[!_impl->recording].audioBufFrames / _impl->port[!_impl->recording].deviceBufFrames - 1; DPRINT("AppleAudioDevice::doStart: prerolling %d slices\n", preBuffers-1); for (int prebuf = 1; prebuf < preBuffers; ++prebuf) { runCallback(); } #if !RENDER_IN_CALLBACK // Start up the render thread _impl->startRenderThread(this); #endif // Start the Audio I/O Unit OSStatus err = AudioOutputUnitStart(_impl->audioUnit); int status = (err == noErr) ? 0 : -1; if (status == -1) appleError("AppleAudioDevice::doStart: failed to start audio unit", status); return status; } int AppleAudioDevice::doPause(bool pause) { _impl->paused = pause; return error("AppleAudioDevice: pause not yet implemented"); } int AppleAudioDevice::doStop() { ENTER(AppleAudioDevice::doStop()); #if !RENDER_IN_CALLBACK _impl->stopRenderThread(); #endif OSStatus err = AudioOutputUnitStop(_impl->audioUnit); int status = (err == noErr) ? 0 : -1; if (status == -1) appleError("AppleAudioDevice::doStop: failed to stop audio unit", status); return status; } #ifdef STANDALONE //static OSStatus DeviceListenerProc(AudioObjectID inObjectID, // UInt32 inNumberAddresses, // const AudioObjectPropertyAddress inAddresses[], // void* inClientData) //{ // for (UInt32 n = 0; n < inNumberAddresses; ++n) { // const AudioObjectPropertyAddress &addr = inAddresses[n]; // DPRINT("DeviceListenerProc: got property change for %u\n", inAddresses[n].mSelector); // } // return noErr; //} // int AppleAudioDevice::setAudioHardwareRate(double *sampleRate) { UInt32 devID = 0; OSStatus status; Boolean isInput = (!_impl->playing) ? TRUE : FALSE; UInt32 size = sizeof(devID); status = AudioUnitGetProperty(_impl->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, // Should not matter &devID, &size); if (status != noErr) { return appleError("Unable to get hardware device from audio unit", status); } // AudioObjectPropertyAddress addr = { kAudioDevicePropertyNominalSampleRate, // kAudioObjectPropertyScopeGlobal, // kAudioObjectPropertyElementMaster }; // status = AudioObjectAddPropertyListener(devID, &addr, DeviceListenerProc, this); // if (status != noErr) { // return appleError("Unable to add property listener to the hardware device", status); // } double newSampleRate = *sampleRate; // Don't do any of this work if the rates do not differ! if (_impl->deviceFormat.mSampleRate != newSampleRate) { // Save original for restore when closing (good OSX software practice) _impl->savedDeviceSampleRate = _impl->deviceFormat.mSampleRate; // Test whether or not audio format property is writable. Boolean writeable = FALSE; size = sizeof(writeable); status = AudioDeviceGetPropertyInfo(devID, 0, isInput, kAudioDevicePropertyStreamFormat, &size, &writeable); if (status != kAudioHardwareNoError) { return appleError("Can't get device format writeable property", status); } if (writeable) { // Try to set new sample rate on hardware // Default all values to device's defaults then set our sample rate. AudioStreamBasicDescription requestedFormat; size = sizeof(requestedFormat); status = AudioDeviceGetProperty(devID, 0, isInput, kAudioDevicePropertyStreamFormat, &size, &requestedFormat); if (status != kAudioHardwareNoError) { return appleError("Can't get device format", status); } DPRINT("Attempting to change HW sample rate from %f to %f\n", _impl->deviceFormat.mSampleRate, newSampleRate); requestedFormat.mSampleRate = newSampleRate; size = sizeof(requestedFormat); OSStatus err = AudioDeviceSetProperty(devID, NULL, 0, isInput, kAudioDevicePropertyStreamFormat, size, (void *)&requestedFormat); switch (err) { case noErr: { int waitCount = 20; while (_impl->gotFormatNotification == false && --waitCount >= 0) { DPRINT("Waiting for notification from hardware...\n"); CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false); } if (waitCount >= 0) { DPRINT("Got it.\n"); } else { DPRINT("Hmm. Timed out!\n"); } _impl->gotFormatNotification = false; // reset } break; case kAudioDeviceUnsupportedFormatError: DPRINT("AudioDevice returned '%s' for sample rate %f so we wont use it\n", errToString(err), newSampleRate); break; default: return appleError("Can't set audio hardware format", err); } // Retrieve settings to see what we got, and compare with request. AudioStreamBasicDescription actualFormat; size = sizeof(actualFormat); DPRINT("Retrieving hardware format\n"); err = AudioDeviceGetProperty(devID, 0, isInput, kAudioDevicePropertyStreamFormat, &size, &actualFormat); if (err != kAudioHardwareNoError) { return appleError("Can't retrieve audio hardware format", status); } if (actualFormat.mSampleRate != newSampleRate) { DPRINT("Unable to set sample rate -- overriding with %f\n", actualFormat.mSampleRate); *sampleRate = actualFormat.mSampleRate; } else { DPRINT("Audio hardware sample rate now set to %f\n", actualFormat.mSampleRate); } // Store this because we do not retrieve fomrmat again. _impl->deviceFormat.mSampleRate = actualFormat.mSampleRate; } else { printf("Note: This HW's audio format is not writable\n"); syslog(LOG_ALERT, "Note: This HW's audio format is not writable\n"); } } return noErr; } #endif /* STANDALONE */ int AppleAudioDevice::doSetFormat(int fmt, int chans, double srate) { ENTER(AppleAudioDevice::doSetFormat()); _impl->bufferSampleFormat = MUS_GET_FORMAT(fmt); // Sanity check, because we do the conversion to float ourselves. if (_impl->bufferSampleFormat != MUS_BFLOAT && _impl->bufferSampleFormat != MUS_LFLOAT) return error("Only float audio buffers supported at this time."); OSStatus status; #ifdef STANDALONE // Attempt to set hardware sample rate, and return whatever was set. status = setAudioHardwareRate(&srate); if (status != 0) return status; #endif // Describe client format: Non-interleaved floating point for both input and output _impl->clientFormat.mSampleRate = srate; _impl->clientFormat.mFormatID = kAudioFormatLinearPCM; _impl->clientFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved; _impl->clientFormat.mFramesPerPacket = 1; _impl->clientFormat.mChannelsPerFrame = chans; _impl->clientFormat.mBitsPerChannel = 32; _impl->clientFormat.mBytesPerPacket = 4; _impl->clientFormat.mBytesPerFrame = 4; // describes one noninterleaved channel UInt32 ioChannels = _impl->clientFormat.mChannelsPerFrame; if (_impl->recording) { Impl::Port *port = &_impl->port[REC]; // kInputBus is the input side of the AU status = AudioUnitSetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, // client side kInputBus, &_impl->clientFormat, sizeof(AudioStreamBasicDescription)); if (status != noErr) return appleError("Cannot set input stream format", status); // For input, we use the channelMap just as it was created. It will have as many // channels as the user has chosen to pull from the input hardware. if (port->channelMap != NULL) { if (port->channelMapCount != _impl->clientFormat.mChannelsPerFrame) { return error("Input channel specification does not match requested number of channels"); } status = AudioUnitSetProperty(_impl->audioUnit, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, // client side kInputBus, port->channelMap, sizeof(SInt32) * port->channelMapCount); if (status != noErr) return appleError("Cannot set input channel map", status); } #if DEBUG > 0 AudioStreamBasicDescription format; UInt32 size = sizeof(format); status = AudioUnitGetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, // client side kInputBus, &format, &size); if (status != noErr) return appleError("Cannot read input dev stream format", status); DPRINT("input client format: sr %f fmt %d flags 0x%x fpp %d cpf %d bpc %d bpp %d bpf %d\n", format.mSampleRate, (int)format.mFormatID, (unsigned)format.mFormatFlags, (int)format.mFramesPerPacket, (int)format.mChannelsPerFrame, (int)format.mBitsPerChannel, (int)format.mBytesPerPacket, (int)format.mBytesPerFrame); #endif // Always noninterleaved, so stream count == channel count. Each stream is 1-channel if (port->streamCount == 0) port->streamCount = ioChannels; port->audioBufChannels = 1; // Always report our channel count to be what we were configured for. We do all channel // matching ourselves during doGetFrames and doSendFrames. port->virtualChannels = chans; // We create a buffer equal to the internal HW channel count. } if (_impl->playing) { Impl::Port *port = &_impl->port[PLAY]; status = AudioUnitSetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, // client side kOutputBus, &_impl->clientFormat, sizeof(AudioStreamBasicDescription)); if (status != noErr) return appleError("Cannot set output stream format", status); if (port->channelMap != NULL) { if (port->channelMapCount != _impl->clientFormat.mChannelsPerFrame) { return error("Output channel specification does not match requested number of channels"); } // For output, the channel map needs to have as many slots as there are hardware channels. UInt32 hwChans = _impl->deviceFormat.mChannelsPerFrame; UInt32 mapSlot = 0; SInt32 *localMap = new SInt32[_impl->deviceFormat.mChannelsPerFrame]; memset(localMap, 0xff, sizeof(SInt32) * hwChans); // set all to -1 DPRINT("output channelMap: "); for (UInt32 chan = 0; chan < hwChans; ++chan) { if (mapSlot < port->channelMapCount && port->channelMap[mapSlot] == chan) { localMap[chan] = mapSlot++; } DPRINT("%d, ", localMap[chan]); } DPRINT("\n"); status = AudioUnitSetProperty(_impl->audioUnit, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Input, // client side kOutputBus, localMap, sizeof(SInt32) * hwChans); delete [] localMap; if (status != noErr) return appleError("Cannot set output channel map", status); } #if DEBUG > 0 AudioStreamBasicDescription format; UInt32 size = sizeof(format); status = AudioUnitGetProperty(_impl->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, // client side kOutputBus, &format, &size); if (status != noErr) return appleError("Cannot read output dev stream format", status); DPRINT("output client format: sr %f fmt %d flags 0x%x fpp %d cpf %d bpc %d bpp %d bpf %d\n", format.mSampleRate, (int)format.mFormatID, (unsigned)format.mFormatFlags, (int)format.mFramesPerPacket, (int)format.mChannelsPerFrame, (int)format.mBitsPerChannel, (int)format.mBytesPerPacket, (int)format.mBytesPerFrame); #endif // Always noninterleaved, so stream count == channel count. Each stream is 1-channel if (port->streamCount == 0) port->streamCount = ioChannels; port->audioBufChannels = 1; // Always report our channel count to be what we were configured for. We do all channel // matching ourselves during doGetFrames and doSendFrames. port->virtualChannels = chans; // We create a buffer equal to the internal HW channel count. } int deviceFormat = NATIVE_FLOAT_FMT | MUS_NORMALIZED | MUS_NON_INTERLEAVED; setDeviceParams(deviceFormat, chans, _impl->clientFormat.mSampleRate); return 0; } int AppleAudioDevice::doSetQueueSize(int *pWriteSize, int *pCount) { ENTER(AppleAudioDevice::doSetQueueSize()); OSStatus status; UInt32 reqQueueFrames = *pWriteSize; UInt32 propSize; #ifdef STANDALONE // set max buffer slice size status = AudioUnitSetProperty(_impl->audioUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &reqQueueFrames, sizeof(reqQueueFrames)); if (status != noErr) return appleError("Cannot set buffer frame size on audio unit", status); // get value back UInt32 devBufferFrameSize = 0; propSize = sizeof(devBufferFrameSize); status = AudioUnitGetProperty(_impl->audioUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &devBufferFrameSize, &propSize); if (status != noErr) return appleError("Cannot get buffer frame size from audio unit", status); DPRINT("AUHal's device returned buffer frame size = %u\n", (unsigned)devBufferFrameSize); #else // for iOS UInt32 devBufferFrameSize = reqQueueFrames; #endif // set the max equal to the device value so we don't ever exceed this. status = AudioUnitSetProperty(_impl->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &devBufferFrameSize, sizeof(reqQueueFrames)); if (status != noErr) return appleError("Cannot set max frames per slice on audio unit", status); // Get the property value back from audio device. We are going to use this value to allocate buffers accordingly UInt32 auQueueFrames = 0; propSize = sizeof(auQueueFrames); status = AudioUnitGetProperty(_impl->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &auQueueFrames, &propSize); if (status != noErr) return appleError("Cannot get max frames per slice on audio unit", status); const int startDir = _impl->recording ? REC : PLAY; const int endDir = _impl->playing ? PLAY : REC; for (int dir = startDir; dir <= endDir; ++dir) { Impl::Port *port = &_impl->port[dir]; port->deviceBufFrames = auQueueFrames; DPRINT("Device buffer length is %d frames, user req was %d frames\n", (int)port->deviceBufFrames, (int)reqQueueFrames); port->audioBufFrames = *pCount * port->deviceBufFrames; // Notify caller of any change. *pWriteSize = port->audioBufFrames / *pCount; *pCount = port->audioBufFrames / port->deviceBufFrames; DPRINT("%s port buflen: %d frames. circ buffer %d frames\n", dir == REC ? "Input" : "Output", port->deviceBufFrames, port->audioBufFrames); DPRINT("\tBuffer configured for %d channels of audio\n", port->audioBufChannels * port->streamCount); int buflen = port->audioBufFrames * port->audioBufChannels * port->streamCount; delete [] port->audioBuffer; port->audioBuffer = new float[buflen]; if (port->audioBuffer == NULL) return error("Memory allocation failure for AppleAudioDevice buffer!"); memset(port->audioBuffer, 0, sizeof(float) * buflen); if (dir == REC) port->audioBufFilled = port->audioBufFrames; // rec buffer set to empty port->inLoc = 0; port->outLoc = 0; } if (_impl->recording) { _impl->inputBufferList = _impl->createInputBufferList(getDeviceChannels(), isDeviceInterleaved()); } status = AudioUnitInitialize(_impl->audioUnit); if (status != noErr) return appleError("Cannot initialize the output audio unit", status); // Create our semaphore and signal it once so render runs first. _impl->renderSema = new RTSemaphore(0); _impl->renderSema->post(); return 0; } int AppleAudioDevice::getRecordDeviceChannels() const { return _impl->port[REC].virtualChannels; } int AppleAudioDevice::getPlaybackDeviceChannels() const { return _impl->port[PLAY].virtualChannels; } int AppleAudioDevice::doGetFrames(void *frameBuffer, int frameCount) { const int frameChans = getFrameChannels(); Impl::Port *port = &_impl->port[REC]; return port->getFrames(frameBuffer, frameCount, frameChans); } int AppleAudioDevice::doSendFrames(void *frameBuffer, int frameCount) { const int frameChans = getFrameChannels(); Impl::Port *port = &_impl->port[PLAY]; int ret = port->sendFrames(frameBuffer, frameCount, frameChans); #if DEBUG > 0 if (_impl->underflowCount > 0) { --_impl->underflowCount; DPRINT("AppleAudioDevice::Impl::doSendFrames: underflow count -> %d -- filled now %d\n", _impl->underflowCount, port->audioBufFilled); } #endif return ret; } int AppleAudioDevice::doGetFrameCount() const { return _impl->frameCount; } int AppleAudioDevice::appleError(const char *msg, int status) { return error(msg, errToString(status)); } // Methods used for identification and creation bool AppleAudioDevice::recognize(const char *desc) { return true; } AudioDevice *AppleAudioDevice::create(const char *inputDesc, const char *outputDesc, int mode) { return new AppleAudioDevice(inputDesc ? inputDesc : outputDesc); } static const char * errToString(OSStatus err) { const char *errstring; switch (err) { case kAudioUnitErr_InvalidProperty: errstring = ": Invalid Property"; break; case kAudioUnitErr_InvalidParameter: errstring = ": Invalid Parameter"; break; case kAudioUnitErr_InvalidElement: errstring = ": Invalid Element"; break; case kAudioUnitErr_NoConnection: errstring = ": No Connection"; break; case kAudioUnitErr_FailedInitialization: errstring = ": Failed Initialization"; break; case kAudioUnitErr_TooManyFramesToProcess: errstring = ": Too Many Frames To Process"; break; case kAudioUnitErr_FormatNotSupported: errstring = ": Format Not Supported"; break; case kAudioUnitErr_PropertyNotWritable: errstring = ": Property Not Writable"; break; case kAudioUnitErr_InvalidPropertyValue: errstring = ": Invalid Property Value"; break; case kAudioUnitErr_PropertyNotInUse: errstring = ": Property Not In Use"; break; case kAudioUnitErr_Uninitialized: case kAudioUnitErr_InvalidScope: case kAudioUnitErr_CannotDoInCurrentContext: case kAudioUnitErr_Initialized: case kAudioUnitErr_InvalidOfflineRender: case kAudioUnitErr_Unauthorized: case kAudioUnitErr_InvalidFile: errstring = ": Audio Error"; break; #ifdef STANDALONE case kAudioHardwareNoError: errstring = ": No error"; break; case kAudioHardwareNotRunningError: errstring = ": Hardware not running"; break; case kAudioHardwareUnspecifiedError: errstring = ": Unspecified error"; break; case kAudioHardwareUnknownPropertyError: errstring = ": Unknown hardware property"; break; case kAudioDeviceUnsupportedFormatError: errstring = ": Unsupported audio format"; break; case kAudioHardwareBadPropertySizeError: errstring = ": Bad hardware propery size"; break; case kAudioHardwareIllegalOperationError: errstring = ": Illegal operation"; break; #endif default: errstring = ": Unknown error"; } return errstring; } #ifdef STANDALONE static OSStatus getDeviceList(AudioDeviceID **devList, int *devCount) { UInt32 size; OSStatus err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, NULL); if (err != kAudioHardwareNoError) { DERROR("Can't get hardware device list property info.\n"); return err; } *devCount = size / sizeof(AudioDeviceID); *devList = new AudioDeviceID[*devCount]; err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, *devList); if (err != kAudioHardwareNoError) { DERROR("Can't get hardware device list.\n"); return err; } return 0; } static AudioDeviceID findDeviceID(const char *devName, AudioDeviceID *devList, int devCount, Boolean isInput) { AudioDeviceID devID = 0; UInt32 size = sizeof(devID); if (!strcasecmp(devName, "default")) { OSStatus err = AudioHardwareGetProperty( isInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, &size, (void *) &devID); if (err != kAudioHardwareNoError || devID == kAudioDeviceUnknown) { DERROR("Cannot find default OSX device\n"); return 0; } return devID; } for (int dev = 0; dev < devCount && devID == 0; ++dev) { /* // In near future, switch to newer API here, like this: AudioObjectPropertyAddress property_address = { kAudioObjectPropertyName, // mSelector isInput ? kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput, // mScope kAudioObjectPropertyElementMaster // mElement }; CFStringRef theName = nil; UInt32 dataSize = sizeof(property_address); OSStatus err = AudioObjectGetPropertyData(devList[dev], &property_address, 0, // inQualifierDataSize NULL, // inQualifierData &dataSize, &theName); */ OSStatus err = AudioDeviceGetPropertyInfo(devList[dev], 0, isInput, kAudioDevicePropertyDeviceName, &size, NULL); if (err != kAudioHardwareNoError) { DERROR("findDeviceID: Can't get device name property info for device %u\n", devList[dev]); continue; } char *name = new char[64 + size + 1]; // XXX Dont trust property size anymore! err = AudioDeviceGetProperty(devList[dev], 0, isInput, kAudioDevicePropertyDeviceName, &size, name); if (err != kAudioHardwareNoError) { DERROR("findDeviceID: Can't get device name property for device %u.\n", (unsigned)devList[dev]); delete [] name; continue; } DPRINT("Checking device %d -- name: \"%s\"\n", dev, name); // For now, we must match the case as well because strcasestr() does not exist. if (strstr(name, devName) != NULL) { DPRINT("MATCH FOUND\n"); devID = devList[dev]; } delete [] name; } return devID; } void AppleAudioDevice::parseDeviceDescription(const char *inDesc) { ::getDeviceList(&_impl->deviceIDs, &_impl->deviceCount); if (inDesc != NULL) { char *substr = strchr(inDesc, ':'); if (substr == NULL) { // Descriptor is just the device name _impl->deviceName = new char[strlen(inDesc) + 1]; strcpy(_impl->deviceName, inDesc); } else { // Extract device name size_t nameLen = (size_t) substr - (size_t) inDesc; _impl->deviceName = new char[nameLen + 1]; strncpy(_impl->deviceName, inDesc, nameLen); _impl->deviceName[nameLen] = '\0'; ++substr; // skip ':' // Extract input and output stream selecters char *insubstr = NULL, *outsubstr = NULL; if ((outsubstr = strchr(substr, ',')) != NULL) { ++outsubstr; // skip ',' insubstr = substr; insubstr[(size_t) outsubstr - (size_t) insubstr - 1] = '\0'; } else { insubstr = outsubstr = substr; } // Now parse stream selecters and set up channel mapping if necessary const char *selecters[2] = { insubstr, outsubstr }; int chanFirst = 0, chanLast = 0; for (int dir = REC; dir <= PLAY; ++dir) { if (selecters[dir] == NULL) { // Do nothing; use defaults. } else if (strchr(selecters[dir], '-') == NULL) { // Parse non-range selecter (single digit) chanFirst = (int) strtol(selecters[dir], NULL, 0); } else { // Parse selecter of form "X-Y" int idx0, idx1; int found = sscanf(selecters[dir], "%d-%d", &idx0, &idx1); if (found == 2 && idx1 >= idx0) { chanFirst = idx0; chanLast = idx1; _impl->port[dir].streamCount = idx1 - idx0 + 1; } else { DERROR("Could not parse device descriptor \"%s\"\n", inDesc); break; } } if (chanFirst != 0 || chanLast != 0) { int requestedChannels = (_impl->port[dir].streamCount > 0) ? _impl->port[dir].streamCount : 1; _impl->port[dir].channelMap = new SInt32[requestedChannels]; _impl->port[dir].channelMapCount = requestedChannels; for (int n = 0; n < requestedChannels; ++n) { _impl->port[dir].channelMap[n] = chanFirst + n; } } } DPRINT("requested input streamCount = %d\n", _impl->port[REC].streamCount); if (_impl->port[REC].channelMap) { DPRINT("\tmapping hardware channel %d to our channel 0, etc.\n", _impl->port[REC].channelMap[0]); } DPRINT("requested output streamCount = %d\n", _impl->port[PLAY].streamCount); if (_impl->port[PLAY].channelMap) { DPRINT("\tmapping our channel 0 to hardware channel %d, etc.\n", _impl->port[PLAY].channelMap[0]); } } // Treat old-stye device name as "default" (handled below). if (!strcmp(_impl->deviceName, "OSXHW")) { delete [] _impl->deviceName; _impl->deviceName = NULL; } } if (_impl->deviceName == NULL) { _impl->deviceName = new char[strlen("default") + 1]; strcpy(_impl->deviceName, "default"); } } #else void AppleAudioDevice::parseDeviceDescription(const char *inDesc) { } #endif
34.862661
146
0.67964
[ "render" ]
142a5d3b1f7483bd548eb0a377e70ced5e9f2a19
2,831
hpp
C++
modcc/lexer.hpp
kabicm/arbor
cfab5fd6a2e6a211c097659c96dcc098ee806e68
[ "BSD-3-Clause" ]
null
null
null
modcc/lexer.hpp
kabicm/arbor
cfab5fd6a2e6a211c097659c96dcc098ee806e68
[ "BSD-3-Clause" ]
null
null
null
modcc/lexer.hpp
kabicm/arbor
cfab5fd6a2e6a211c097659c96dcc098ee806e68
[ "BSD-3-Clause" ]
null
null
null
#pragma once // inspiration was taken from the Digital Mars D compiler // github.com/D-Programming-Language/dmd #include <map> #include <string> #include <unordered_map> #include <vector> #include "location.hpp" #include "error.hpp" #include "token.hpp" // status of the lexer enum class lexerStatus { error, // lexer has encounterd a problem happy // lexer is in a good place }; // associativity of an operator enum class associativityKind { left, right }; bool is_keyword(Token const& t); // class that implements the lexer // takes a range of characters as input parameters class Lexer { public: Lexer(const char* begin, const char* end) : begin_(begin), end_(end), current_(begin), line_(begin), location_() { if(begin_>end_) { throw std::out_of_range("Lexer(begin, end) : begin>end"); } initialize_token_maps(); binop_prec_init(); } Lexer(std::vector<char> const& v) : Lexer(v.data(), v.data()+v.size()) {} Lexer(std::string const& s) : buffer_(s.data(), s.data()+s.size()+1) { begin_ = buffer_.data(); end_ = buffer_.data() + buffer_.size(); current_ = begin_; line_ = begin_; initialize_token_maps(); binop_prec_init(); } // get the next token Token parse(); void get_token() { token_ = parse(); } // return the next token in the stream without advancing the current position Token peek(); // scan a number from the stream Token number(); // scan an identifier string from the stream std::string identifier(); // scan a character from the stream char character(); Location location() {return location_;} // binary operator precedence static std::map<tok, int> binop_prec_; lexerStatus status() {return status_;} const std::string& error_message() {return error_string_;}; static int binop_precedence(tok tok); static associativityKind operator_associativity(tok token); protected: // buffer used for short-lived parsers std::vector<char> buffer_; // generate lookup tables (hash maps) for keywords void keywords_init(); void token_strings_init(); void binop_prec_init(); // helper for determining if an identifier string matches a keyword tok get_identifier_type(std::string const& identifier); const char *begin_, *end_;// pointer to start and 1 past the end of the buffer const char *current_; // pointer to current character const char *line_; // pointer to start of current line Location location_; // current location (line,column) in buffer lexerStatus status_ = lexerStatus::happy; std::string error_string_; Token token_; };
24.196581
82
0.643236
[ "vector" ]
142b219da02899729fa8a1619040bdec71fb43a2
7,926
cpp
C++
Boss2D/addon/tesseract-3.05.02_for_boss/cube/word_unigrams.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/tesseract-3.05.02_for_boss/cube/word_unigrams.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/tesseract-3.05.02_for_boss/cube/word_unigrams.cpp
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
/********************************************************************** * File: word_unigrams.cpp * Description: Implementation of the Word Unigrams Class * Author: Ahmad Abdulkader * Created: 2008 * * (C) Copyright 2008, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <math.h> #include <string> #include <vector> #include <algorithm> #include BOSS_TESSERACT_U_const_h //original-code:"const.h" #include BOSS_TESSERACT_U_cube_utils_h //original-code:"cube_utils.h" #include BOSS_TESSERACT_U_ndminx_h //original-code:"ndminx.h" #include BOSS_TESSERACT_U_word_unigrams_h //original-code:"word_unigrams.h" namespace tesseract { WordUnigrams::WordUnigrams() { costs_ = NULL; words_ = NULL; word_cnt_ = 0; } WordUnigrams::~WordUnigrams() { if (words_ != NULL) { if (words_[0] != NULL) { delete []words_[0]; } delete []words_; words_ = NULL; } if (costs_ != NULL) { delete []costs_; } } /** * Load the word-list and unigrams from file and create an object * The word list is assumed to be sorted in lexicographic order. */ WordUnigrams *WordUnigrams::Create(const string &data_file_path, const string &lang) { string file_name; string str; file_name = data_file_path + lang; file_name += ".cube.word-freq"; // load the string into memory if (CubeUtils::ReadFileToString(file_name, &str) == false) { return NULL; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(str, "\r\n \t", &str_vec); if (str_vec.size() < 2) { return NULL; } // allocate memory WordUnigrams *word_unigrams_obj = new WordUnigrams(); int full_len = str.length(); int word_cnt = str_vec.size() / 2; word_unigrams_obj->words_ = new char*[word_cnt]; word_unigrams_obj->costs_ = new int[word_cnt]; word_unigrams_obj->words_[0] = new char[full_len]; // construct sorted list of words and costs word_unigrams_obj->word_cnt_ = 0; char *char_buff = word_unigrams_obj->words_[0]; word_cnt = 0; int max_cost = 0; for (int wrd = 0; wrd < str_vec.size(); wrd += 2) { word_unigrams_obj->words_[word_cnt] = char_buff; strcpy(char_buff, str_vec[wrd].c_str()); char_buff += (str_vec[wrd].length() + 1); if (sscanf(str_vec[wrd + 1].c_str(), "%d", word_unigrams_obj->costs_ + word_cnt) != 1) { fprintf(stderr, "Cube ERROR (WordUnigrams::Create): error reading " "word unigram data.\n"); delete word_unigrams_obj; return NULL; } // update max cost max_cost = MAX(max_cost, word_unigrams_obj->costs_[word_cnt]); word_cnt++; } word_unigrams_obj->word_cnt_ = word_cnt; // compute the not-in-list-cost by assuming that a word not in the list // [ahmadab]: This can be computed as follows: // - Given that the distribution of words follow Zipf's law: // (F = K / (rank ^ S)), where s is slightly > 1.0 // - Number of words in the list is N // - The mean frequency of a word that did not appear in the list is the // area under the rest of the Zipf's curve divided by 2 (the mean) // - The area would be the bound integral from N to infinity = // (K * S) / (N ^ (S + 1)) ~= K / (N ^ 2) // - Given that cost = -LOG(prob), the cost of an unlisted word would be // = max_cost + 2*LOG(N) word_unigrams_obj->not_in_list_cost_ = max_cost + (2 * CubeUtils::Prob2Cost(1.0 / word_cnt)); // success return word_unigrams_obj; } /** * Split input into space-separated tokens, strip trailing punctuation * from each, determine case properties, call UTF-8 flavor of cost * function on each word, and aggregate all into single mean word * cost. */ int WordUnigrams::Cost(const char_32 *key_str32, LangModel *lang_mod, CharSet *char_set) const { if (!key_str32) return 0; // convert string to UTF8 to split into space-separated words string key_str; CubeUtils::UTF32ToUTF8(key_str32, &key_str); vector<string> words; CubeUtils::SplitStringUsing(key_str, " \t", &words); // no words => no cost if (words.empty()) { return 0; } // aggregate the costs of all the words int cost = 0; for (int word_idx = 0; word_idx < words.size(); word_idx++) { // convert each word back to UTF32 for analyzing case and punctuation string_32 str32; CubeUtils::UTF8ToUTF32(words[word_idx].c_str(), &str32); int len = CubeUtils::StrLen(str32.c_str()); // strip all trailing punctuation string clean_str; int clean_len = len; bool trunc = false; while (clean_len > 0 && lang_mod->IsTrailingPunc(str32.c_str()[clean_len - 1])) { --clean_len; trunc = true; } // If either the original string was not truncated (no trailing // punctuation) or the entire string was removed (all characters // are trailing punctuation), evaluate original word as is; // otherwise, copy all but the trailing punctuation characters char_32 *clean_str32 = NULL; if (clean_len == 0 || !trunc) { clean_str32 = CubeUtils::StrDup(str32.c_str()); } else { clean_str32 = new char_32[clean_len + 1]; for (int i = 0; i < clean_len; ++i) { clean_str32[i] = str32[i]; } clean_str32[clean_len] = '\0'; } ASSERT_HOST(clean_str32 != NULL); string str8; CubeUtils::UTF32ToUTF8(clean_str32, &str8); int word_cost = CostInternal(str8.c_str()); // if case invariant, get costs of all-upper-case and all-lower-case // versions and return the min cost if (clean_len >= kMinLengthNumOrCaseInvariant && CubeUtils::IsCaseInvariant(clean_str32, char_set)) { char_32 *lower_32 = CubeUtils::ToLower(clean_str32, char_set); if (lower_32) { string lower_8; CubeUtils::UTF32ToUTF8(lower_32, &lower_8); word_cost = MIN(word_cost, CostInternal(lower_8.c_str())); delete [] lower_32; } char_32 *upper_32 = CubeUtils::ToUpper(clean_str32, char_set); if (upper_32) { string upper_8; CubeUtils::UTF32ToUTF8(upper_32, &upper_8); word_cost = MIN(word_cost, CostInternal(upper_8.c_str())); delete [] upper_32; } } if (clean_len >= kMinLengthNumOrCaseInvariant) { // if characters are all numeric, incur 0 word cost bool is_numeric = true; for (int i = 0; i < clean_len; ++i) { if (!lang_mod->IsDigit(clean_str32[i])) is_numeric = false; } if (is_numeric) word_cost = 0; } delete [] clean_str32; cost += word_cost; } // word_idx // return the mean cost return static_cast<int>(cost / static_cast<double>(words.size())); } /** * Search for UTF-8 string using binary search of sorted words_ array. */ int WordUnigrams::CostInternal(const char *key_str) const { if (strlen(key_str) == 0) return not_in_list_cost_; int hi = word_cnt_ - 1; int lo = 0; while (lo <= hi) { int current = (hi + lo) / 2; int comp = strcmp(key_str, words_[current]); // a match if (comp == 0) { return costs_[current]; } if (comp < 0) { // go lower hi = current - 1; } else { // go higher lo = current + 1; } } return not_in_list_cost_; } } // namespace tesseract
31.328063
76
0.635125
[ "object", "vector" ]
142c821f7725f11b4c973d93bc077e027f701085
4,008
cc
C++
Code/Components/Synthesis/synthesis/current/parallel/ParallelAccessor.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Synthesis/synthesis/current/parallel/ParallelAccessor.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Synthesis/synthesis/current/parallel/ParallelAccessor.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file /// @brief accessor returned by parallel write iterator /// @details We could've moved this class to accessors as it bears no /// parallelism. However, at this stage it is used only here and therefore some methods /// we don't need here are left without implementation. The main functionality of this class /// is to provide cached mechanism for rotated uvw and associated delays for the client (worker) /// side. At the server side this is done by the table iterator. /// /// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Max Voronkov <maxim.voronkov@csiro.au> /// #include <parallel/ParallelAccessor.h> #include <askap/AskapError.h> namespace askap { namespace synthesis { /// @brief constructor /// @param[in] cacheSize uvw-machine cache size /// @param[in] tolerance pointing direction tolerance in radians, exceeding /// which leads to initialisation of a new UVW machine and recompute of the rotated uvws/delays ParallelAccessor::ParallelAccessor(size_t cacheSize, double tolerance) : accessors::DataAccessorStub(false), itsRotatedUVW(cacheSize, tolerance) {} /// @brief uvw after rotation /// @details This method calls UVWMachine to rotate baseline coordinates /// for a new tangent point. Delays corresponding to this correction are /// returned by a separate method. /// @param[in] tangentPoint tangent point to rotate the coordinates to /// @return uvw after rotation to the new coordinate system for each row const casa::Vector<casa::RigidVector<casa::Double, 3> >& ParallelAccessor::rotatedUVW(const casa::MDirection &tangentPoint) const { return itsRotatedUVW.uvw(*this, tangentPoint); } /// @brief delay associated with uvw rotation /// @details This is a companion method to rotatedUVW. It returns delays corresponding /// to the baseline coordinate rotation. An additional delay corresponding to the /// translation in the tangent plane can also be applied using the image /// centre parameter. Set it to tangent point to apply no extra translation. /// @param[in] tangentPoint tangent point to rotate the coordinates to /// @param[in] imageCentre image centre (additional translation is done if imageCentre!=tangentPoint) /// @return delays corresponding to the uvw rotation for each row const casa::Vector<casa::Double>& ParallelAccessor::uvwRotationDelay( const casa::MDirection &tangentPoint, const casa::MDirection &imageCentre) const { return itsRotatedUVW.delays(*this,tangentPoint,imageCentre); } /// Velocity for each channel /// @return a reference to vector containing velocities for each /// spectral channel (vector size is nChannel). Velocities /// are given as Doubles, the frame/units are specified by /// the DataSource object (via IDataConverter). const casa::Vector<casa::Double>& ParallelAccessor::velocity() const { ASKAPTHROW(AskapError, "ParallelAccessor::velocity() has not been implemented"); } } // namespace synthesis } // namespace askap
45.033708
108
0.742016
[ "object", "vector" ]
28a46876909152bfe3205e946ec91a23ca035226
11,111
hpp
C++
Siv3D/src/Siv3D-Platform/OpenGLES3/Siv3D/Renderer3D/GLES3/GLES3Renderer3DCommand.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
709
2016-03-19T07:55:58.000Z
2022-03-31T08:02:22.000Z
Siv3D/src/Siv3D-Platform/OpenGLES3/Siv3D/Renderer3D/GLES3/GLES3Renderer3DCommand.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
415
2017-05-21T05:05:02.000Z
2022-03-29T16:08:27.000Z
Siv3D/src/Siv3D-Platform/OpenGLES3/Siv3D/Renderer3D/GLES3/GLES3Renderer3DCommand.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
123
2016-03-19T12:47:08.000Z
2022-03-25T03:47:51.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Common.hpp> # include <Siv3D/Array.hpp> # include <Siv3D/Optional.hpp> # include <Siv3D/HashTable.hpp> # include <Siv3D/BlendState.hpp> # include <Siv3D/RasterizerState.hpp> # include <Siv3D/SamplerState.hpp> # include <Siv3D/DepthStencilState.hpp> # include <Siv3D/RenderTexture.hpp> # include <Siv3D/ShaderStage.hpp> # include <Siv3D/ConstantBuffer.hpp> # include <Siv3D/VertexShader.hpp> # include <Siv3D/PixelShader.hpp> # include <Siv3D/2DShapes.hpp> # include <Siv3D/Mesh.hpp> # include <Siv3D/Graphics3D.hpp> # include <Siv3D/PhongMaterial.hpp> # include <Siv3D/Renderer2D/CurrentBatchStateChanges.hpp> # include <Siv3D/Renderer3D/VertexLine3D.hpp> namespace s3d { enum class GLES3Renderer3DCommandType : uint32 { Null, UpdateLine3DBuffers, Draw, DrawLine3D, BlendState, RasterizerState, DepthStencilState, VSSamplerState0, VSSamplerState1, VSSamplerState2, VSSamplerState3, VSSamplerState4, VSSamplerState5, VSSamplerState6, VSSamplerState7, PSSamplerState0, PSSamplerState1, PSSamplerState2, PSSamplerState3, PSSamplerState4, PSSamplerState5, PSSamplerState6, PSSamplerState7, ScissorRect, Viewport, SetRT, InputLayout, SetVS, SetPS, CameraTransform, EyePosition, LocalTransform, SetConstantBuffer, VSTexture0, VSTexture1, VSTexture2, VSTexture3, VSTexture4, VSTexture5, VSTexture6, VSTexture7, PSTexture0, PSTexture1, PSTexture2, PSTexture3, PSTexture4, PSTexture5, PSTexture6, PSTexture7, SetMesh, SetGlobalAmbientColor, SetSunDirection, SetSunColor, SIZE_, }; static_assert(FromEnum(GLES3Renderer3DCommandType::SIZE_) < 64); struct GLES3Renderer3DCommand { GLES3Renderer3DCommandType type = GLES3Renderer3DCommandType::Null; uint32 index = 0; GLES3Renderer3DCommand() = default; constexpr GLES3Renderer3DCommand(GLES3Renderer3DCommandType _type, uint32 _index) noexcept : type(_type) , index(_index) {} }; struct GLES3Draw3DCommand { uint32 startIndex = 0; uint32 indexCount = 0; uint32 instanceCount = 0; }; struct GLES3DrawLine3DCommand { uint32 indexCount = 0; }; struct GLES3ConstantBuffer3DCommand { ShaderStage stage = ShaderStage::Vertex; uint32 slot = 0; uint32 offset = 0; uint32 num_vectors = 0; uint32 cbBaseIndex = 0; ConstantBufferBase cbBase; }; enum class GLES3InputLayout3D { Mesh, Line3D, }; class GLES3Renderer3DCommandManager { private: // commands Array<GLES3Renderer3DCommand> m_commands; CurrentBatchStateChanges<GLES3Renderer3DCommandType> m_changes; // buffer Array<GLES3Draw3DCommand> m_draws; Array<GLES3DrawLine3DCommand> m_drawLine3Ds; //Array<uint32> m_nullDraws; Array<PhongMaterialInternal> m_drawPhongMaterials; Array<BlendState> m_blendStates = { BlendState::Default3D }; Array<RasterizerState> m_rasterizerStates = { RasterizerState::Default3D }; Array<DepthStencilState> m_depthStencilStates = { DepthStencilState::Default3D }; std::array<Array<SamplerState>, SamplerState::MaxSamplerCount> m_vsSamplerStates; std::array<Array<SamplerState>, SamplerState::MaxSamplerCount> m_psSamplerStates; Array<Rect> m_scissorRects = { Rect{0} }; Array<Optional<Rect>> m_viewports = { none }; //Array<std::array<Float4, 3>> m_sdfParams = { { Float4{ 0.5f, 0.5f, 0.0f, 0.0f }, Float4{ 0.0f, 0.0f, 0.0f, 1.0f }, Float4{ 0.0f, 0.0f, 0.0f, 0.5f } } }; Array<Optional<RenderTexture>> m_RTs = { none }; Array<VertexShader::IDType> m_VSs; Array<PixelShader::IDType> m_PSs; Array<Mat4x4> m_cameraTransforms = { Mat4x4::Identity() }; Array<Float3> m_eyePositions = { Float3{ 0.0f, 0.0f, 0.0f } }; Array<Mat4x4> m_localTransforms = { Mat4x4::Identity() }; Array<__m128> m_constants; Array<GLES3ConstantBuffer3DCommand> m_constantBufferCommands; std::array<Array<Texture::IDType>, SamplerState::MaxSamplerCount> m_vsTextures; std::array<Array<Texture::IDType>, SamplerState::MaxSamplerCount> m_psTextures; Array<GLES3InputLayout3D> m_inputLayouts = { GLES3InputLayout3D::Mesh }; Array<Mesh::IDType> m_meshes; Array<Float3> m_globalAmbientColors = { Graphics3D::DefaultGlobalAmbientColor.rgb() }; Array<Float3> m_sunDirections = { Graphics3D::DefaultSunDirection }; Array<Float3> m_sunColors = { Graphics3D::DefaultSunColor.rgb() }; // current GLES3DrawLine3DCommand m_currentDrawLine3D; BlendState m_currentBlendState = m_blendStates.back(); RasterizerState m_currentRasterizerState = m_rasterizerStates.back(); DepthStencilState m_currentDepthStencilState = m_depthStencilStates.back(); std::array<SamplerState, SamplerState::MaxSamplerCount> m_currentVSSamplerStates; std::array<SamplerState, SamplerState::MaxSamplerCount> m_currentPSSamplerStates; Rect m_currentScissorRect = m_scissorRects.back(); Optional<Rect> m_currentViewport = m_viewports.back(); //std::array<Float4, 3> m_currentSDFParams = m_sdfParams.back(); Optional<RenderTexture> m_currentRT = m_RTs.back(); VertexShader::IDType m_currentVS = VertexShader::IDType::InvalidValue(); PixelShader::IDType m_currentPS = PixelShader::IDType::InvalidValue(); Mat4x4 m_currentCameraTransform = m_cameraTransforms.back(); Float3 m_currentEyePosition = m_eyePositions.back(); Mat4x4 m_currentLocalTransform = m_localTransforms.back(); std::array<Texture::IDType, SamplerState::MaxSamplerCount> m_currentVSTextures; std::array<Texture::IDType, SamplerState::MaxSamplerCount> m_currentPSTextures; GLES3InputLayout3D m_currentInputLayout = m_inputLayouts.back(); Mesh::IDType m_currentMesh; Float3 m_currentGlobalAmbientColor = m_globalAmbientColors.back(); Float3 m_currentSunDirection = m_sunDirections.back(); Float3 m_currentSunColor = m_sunColors.back(); // reserved HashTable<VertexShader::IDType, VertexShader> m_reservedVSs; HashTable<PixelShader::IDType, PixelShader> m_reservedPSs; HashTable<Texture::IDType, Texture> m_reservedTextures; HashTable<Mesh::IDType, Mesh> m_reservedMeshes; public: GLES3Renderer3DCommandManager(); void reset(); void flush(); bool hasDraw() const noexcept; const Array<GLES3Renderer3DCommand>& getCommands() const noexcept; void pushUpdateLine3DBuffers(uint32 batchIndex); void pushDraw(uint32 startIndex, uint32 indexCount, const PhongMaterialInternal& material, uint32 instanceCount); const GLES3Draw3DCommand& getDraw(uint32 index) const noexcept; const PhongMaterialInternal& getDrawPhongMaterial(uint32 index) const noexcept; void pushDrawLine3D(VertexLine3D::IndexType indexCount); const GLES3DrawLine3DCommand& getDrawLine3D(uint32 index) const noexcept; //void pushNullVertices(uint32 count); //uint32 getNullDraw(uint32 index) const noexcept; void pushBlendState(const BlendState& state); const BlendState& getBlendState(uint32 index) const; const BlendState& getCurrentBlendState() const; void pushRasterizerState(const RasterizerState& state); const RasterizerState& getRasterizerState(uint32 index) const; const RasterizerState& getCurrentRasterizerState() const; void pushDepthStencilState(const DepthStencilState& state); const DepthStencilState& getDepthStencilState(uint32 index) const; const DepthStencilState& getCurrentDepthStencilState() const; void pushVSSamplerState(const SamplerState& state, uint32 slot); const SamplerState& getVSSamplerState(uint32 slot, uint32 index) const; const SamplerState& getVSCurrentSamplerState(uint32 slot) const; void pushPSSamplerState(const SamplerState& state, uint32 slot); const SamplerState& getPSSamplerState(uint32 slot, uint32 index) const; const SamplerState& getPSCurrentSamplerState(uint32 slot) const; void pushScissorRect(const Rect& state); const Rect& getScissorRect(uint32 index) const; const Rect& getCurrentScissorRect() const; void pushViewport(const Optional<Rect>& state); const Optional<Rect>& getViewport(uint32 index) const; const Optional<Rect>& getCurrentViewport() const; //void pushSDFParameters(const std::array<Float4, 3>& state); //const std::array<Float4, 3>& getSDFParameters(uint32 index) const; //const std::array<Float4, 3>& getCurrentSDFParameters() const; void pushInputLayout(GLES3InputLayout3D state); const GLES3InputLayout3D& getInputLayout(uint32 index) const; const GLES3InputLayout3D& getCurrentInputLayout() const; void pushStandardVS(const VertexShader::IDType& id); void pushCustomVS(const VertexShader& vs); const VertexShader::IDType& getVS(uint32 index) const; void pushStandardPS(const PixelShader::IDType& id); void pushCustomPS(const PixelShader& ps); const PixelShader::IDType& getPS(uint32 index) const; void pushCameraTransform(const Mat4x4& state); const Mat4x4& getCurrentCameraTransform() const; const Mat4x4& getCameraTransform(uint32 index) const; void pushEyePosition(const Float3& state); const Float3& getCurrentEyePosition() const; const Float3& getEyePosition(uint32 index) const; void pushLocalTransform(const Mat4x4& state); const Mat4x4& getCurrentLocalTransform() const; const Mat4x4& getLocalTransform(uint32 index) const; void pushConstantBuffer(ShaderStage stage, uint32 slot, const ConstantBufferBase& buffer, const float* data, uint32 num_vectors); GLES3ConstantBuffer3DCommand& getConstantBuffer(uint32 index); const __m128* getConstantBufferPtr(uint32 offset) const; void pushVSTextureUnbind(uint32 slot); void pushVSTexture(uint32 slot, const Texture& texture); const Texture::IDType& getVSTexture(uint32 slot, uint32 index) const; const std::array<Texture::IDType, SamplerState::MaxSamplerCount>& getCurrentVSTextures() const; void pushPSTextureUnbind(uint32 slot); void pushPSTexture(uint32 slot, const Texture& texture); const Texture::IDType& getPSTexture(uint32 slot, uint32 index) const; const std::array<Texture::IDType, SamplerState::MaxSamplerCount>& getCurrentPSTextures() const; void pushRT(const Optional<RenderTexture>& rt); const Optional<RenderTexture>& getRT(uint32 index) const; const Optional<RenderTexture>& getCurrentRT() const; void pushMeshUnbind(); void pushMesh(const Mesh& mesh); const Mesh::IDType& getMesh(uint32 index) const; const Mesh::IDType& getCurrentMesh() const; void pushGlobalAmbientColor(const Float3& state); const Float3& getCurrentGlobalAmbientColor() const; const Float3& getGlobalAmbientColor(uint32 index) const; void pushSunDirection(const Float3& state); const Float3& getCurrentSunDirection() const; const Float3& getSunDirection(uint32 index) const; void pushSunColor(const Float3& state); const Float3& getCurrentSunColor() const; const Float3& getSunColor(uint32 index) const; }; }
29.708556
156
0.758888
[ "mesh" ]
28aa9397b98bbbf3f88eb7724cce4819cd3ef017
907
cpp
C++
TImKiem/h.cpp
daothaison/algorithm-vi
59ee4046eae2aea97c7f85d7bd64f85f12d84598
[ "Apache-2.0" ]
null
null
null
TImKiem/h.cpp
daothaison/algorithm-vi
59ee4046eae2aea97c7f85d7bd64f85f12d84598
[ "Apache-2.0" ]
null
null
null
TImKiem/h.cpp
daothaison/algorithm-vi
59ee4046eae2aea97c7f85d7bd64f85f12d84598
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> using namespace std; long hashCode(string s){ long code=0; for(int i=0;i <s.size(); i++){ code+= s[i]*pow(2,i); } return code; } class HashTable{ public: vector<string> table[101]; int SIZE=101; void put(string s){ table[hashCode(s)%SIZE].push_back(s); } int find(string s){ long index= hashCode(s)%SIZE; int len= table[index].size(); if(len==0) return 0; for(int i=0;i< len;i++){ if(s==table[index][i]) return 1; } return 0; } }; int n; HashTable map; void input(){ cout<<"Nhap so phan tu: "; cin>>n; string s; for(int i=0;i< n;i++){ cin>>s; map.put(s); } } main(){ input(); string data; cout<<"Nhap tu khoa can tim: "; cin>>data; if(map.find(data)) cout<<"Co "<<data<<" trong bang bam"<<endl; else cout<<"Khong co "<<data<<endl; }
17.784314
46
0.556781
[ "vector" ]
28ab7c2b1d06e05641769dabfb2be461bdc8af42
897
cpp
C++
CodeChef/Easy/E0056.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
CodeChef/Easy/E0056.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
CodeChef/Easy/E0056.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
// Problem Code: PCYCLE #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<vector<int>> permutationCycles(vector<int> A){ int i, j; vector<bool> visited(A.size()); vector<vector<int>> cycles(1); i = j = 0; while(true){ cycles[j].push_back(i+1); if(visited[i]){ i = distance(visited.begin(), find(visited.begin(), visited.end(), false)); if(i == visited.size()) break; cycles.push_back(vector<int>()); j++; }else{ visited[i] = true; i = A[i] - 1; } } return cycles; } int main(){ int N, num; vector<int> A; vector<vector<int>> cycles; cin >> N; for(int i=0 ; i<N ; i++){ cin >> num; A.push_back(num); } cycles = permutationCycles(A); cout << cycles.size() << endl; for(int i=0 ; i<cycles.size() ; i++){ for(int j=0 ; j<cycles[i].size() ; j++) cout << cycles[i][j] << " "; cout << endl; } return 0; }
19.085106
78
0.586399
[ "vector" ]
28ab9a28bd3a2905924eb2fc2bc03ea291190dc1
47,793
cpp
C++
gdal/frmts/pcidsk/sdk/core/cpcidskfile.cpp
mihadyuk/gdal
d4627981715b82ff368547ef00ef26e0b9207048
[ "MIT" ]
6
2017-05-12T08:18:27.000Z
2022-01-17T17:16:11.000Z
gdal/frmts/pcidsk/sdk/core/cpcidskfile.cpp
mihadyuk/gdal
d4627981715b82ff368547ef00ef26e0b9207048
[ "MIT" ]
1
2019-03-07T15:25:14.000Z
2019-03-07T15:25:14.000Z
gdal/frmts/pcidsk/sdk/core/cpcidskfile.cpp
mihadyuk/gdal
d4627981715b82ff368547ef00ef26e0b9207048
[ "MIT" ]
2
2017-01-18T16:28:58.000Z
2021-09-03T21:40:43.000Z
/****************************************************************************** * * Purpose: Implementation of the CPCIDSKFile class. * ****************************************************************************** * Copyright (c) 2009 * PCI Geomatics, 50 West Wilmot Street, Richmond Hill, Ont, Canada * * 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 "pcidsk_file.h" #include "pcidsk_exception.h" #include "pcidsk_channel.h" #include "pcidsk_segment.h" #include "core/mutexholder.h" #include "core/pcidsk_utils.h" #include "core/cpcidskfile.h" // Channel types #include "channel/cbandinterleavedchannel.h" #include "channel/cpixelinterleavedchannel.h" #include "channel/ctiledchannel.h" #include "channel/cexternalchannel.h" // Segment types #include "segment/cpcidskgeoref.h" #include "segment/cpcidskpct.h" #include "segment/cpcidskvectorsegment.h" #include "segment/metadatasegment.h" #include "segment/sysblockmap.h" #include "segment/cpcidskrpcmodel.h" #include "segment/cpcidskgcp2segment.h" #include "segment/cpcidskbitmap.h" #include "segment/cpcidsk_tex.h" #include "segment/cpcidsk_array.h" #include "segment/cpcidskapmodel.h" #include "segment/cpcidskads40model.h" #include "segment/cpcidsktoutinmodel.h" #include "segment/cpcidskpolymodel.h" #include "segment/cpcidskbinarysegment.h" #include "core/clinksegment.h" #include <cassert> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <iostream> using namespace PCIDSK; /************************************************************************/ /* CPCIDSKFile() */ /************************************************************************/ CPCIDSKFile::CPCIDSKFile( std::string filename ) { io_handle = NULL; io_mutex = NULL; updatable = false; base_filename = filename; /* -------------------------------------------------------------------- */ /* Initialize the metadata object, but do not try to load till */ /* needed. */ /* -------------------------------------------------------------------- */ metadata.Initialize( this, "FIL", 0 ); } /************************************************************************/ /* ~CPCIDSKFile() */ /************************************************************************/ CPCIDSKFile::~CPCIDSKFile() { Synchronize(); /* -------------------------------------------------------------------- */ /* Cleanup last block buffer. */ /* -------------------------------------------------------------------- */ if( last_block_data != NULL ) { last_block_index = -1; free( last_block_data ); last_block_data = NULL; delete last_block_mutex; } /* -------------------------------------------------------------------- */ /* Cleanup channels and segments. */ /* -------------------------------------------------------------------- */ size_t i; for( i = 0; i < channels.size(); i++ ) { delete channels[i]; channels[i] = NULL; } for( i = 0; i < segments.size(); i++ ) { delete segments[i]; segments[i] = NULL; } /* -------------------------------------------------------------------- */ /* Close and cleanup IO stuff. */ /* -------------------------------------------------------------------- */ { MutexHolder oHolder( io_mutex ); if( io_handle ) { interfaces.io->Close( io_handle ); io_handle = NULL; } } size_t i_file; for( i_file=0; i_file < file_list.size(); i_file++ ) { delete file_list[i_file].io_mutex; file_list[i_file].io_mutex = NULL; interfaces.io->Close( file_list[i_file].io_handle ); file_list[i_file].io_handle = NULL; } for( i_file=0; i_file < edb_file_list.size(); i_file++ ) { delete edb_file_list[i_file].io_mutex; edb_file_list[i_file].io_mutex = NULL; delete edb_file_list[i_file].file; edb_file_list[i_file].file = NULL; } delete io_mutex; } /************************************************************************/ /* Synchronize() */ /************************************************************************/ void CPCIDSKFile::Synchronize() { if( !GetUpdatable() ) return; /* -------------------------------------------------------------------- */ /* Flush out last line caching stuff for pixel interleaved data. */ /* -------------------------------------------------------------------- */ FlushBlock(); /* -------------------------------------------------------------------- */ /* Synchronize all channels. */ /* -------------------------------------------------------------------- */ size_t i; for( i = 0; i < channels.size(); i++ ) channels[i]->Synchronize(); /* -------------------------------------------------------------------- */ /* Synchronize all segments we have instantiated. */ /* -------------------------------------------------------------------- */ for( i = 0; i < segments.size(); i++ ) { if( segments[i] != NULL ) segments[i]->Synchronize(); } /* -------------------------------------------------------------------- */ /* Ensure the file is synhronized to disk. */ /* -------------------------------------------------------------------- */ MutexHolder oHolder( io_mutex ); interfaces.io->Flush( io_handle ); } /************************************************************************/ /* GetChannel() */ /************************************************************************/ PCIDSKChannel *CPCIDSKFile::GetChannel( int band ) { if( band < 1 || band > channel_count ) ThrowPCIDSKException( "Out of range band (%d) requested.", band ); return channels[band-1]; } /************************************************************************/ /* GetSegment() */ /************************************************************************/ PCIDSK::PCIDSKSegment *CPCIDSKFile::GetSegment( int segment ) { /* -------------------------------------------------------------------- */ /* Is this a valid segment? */ /* -------------------------------------------------------------------- */ if( segment < 1 || segment > segment_count ) return NULL; const char *segment_pointer = segment_pointers.buffer + (segment-1) * 32; if( segment_pointer[0] != 'A' && segment_pointer[0] != 'L' ) return NULL; /* -------------------------------------------------------------------- */ /* Do we already have a corresponding object? */ /* -------------------------------------------------------------------- */ if( segments[segment] != NULL ) return segments[segment]; /* -------------------------------------------------------------------- */ /* Instantiate per the type. */ /* -------------------------------------------------------------------- */ int segment_type = segment_pointers.GetInt((segment-1)*32+1,3); PCIDSKSegment *segobj = NULL; switch( segment_type ) { case SEG_GEO: segobj = new CPCIDSKGeoref( this, segment, segment_pointer ); break; case SEG_PCT: segobj = new CPCIDSK_PCT( this, segment, segment_pointer ); break; case SEG_VEC: segobj = new CPCIDSKVectorSegment( this, segment, segment_pointer ); break; case SEG_BIT: segobj = new CPCIDSKBitmap( this, segment, segment_pointer ); break; case SEG_TEX: segobj = new CPCIDSK_TEX( this, segment, segment_pointer ); break; case SEG_SYS: if( strncmp(segment_pointer + 4, "SysBMDir",8) == 0 ) segobj = new SysBlockMap( this, segment, segment_pointer ); else if( strncmp(segment_pointer + 4, "METADATA",8) == 0 ) segobj = new MetadataSegment( this, segment, segment_pointer ); else if (strncmp(segment_pointer + 4, "Link ", 8) == 0) segobj = new CLinkSegment(this, segment, segment_pointer); else segobj = new CPCIDSKSegment( this, segment, segment_pointer ); break; case SEG_GCP2: segobj = new CPCIDSKGCP2Segment(this, segment, segment_pointer); break; case SEG_ORB: segobj = new CPCIDSKEphemerisSegment(this, segment, segment_pointer); break; case SEG_ARR: segobj = new CPCIDSK_ARRAY(this, segment, segment_pointer); break; case SEG_BIN: if (!strncmp(segment_pointer + 4, "RFMODEL ", 8)) { segobj = new CPCIDSKRPCModelSegment( this, segment, segment_pointer ); } else if (!strncmp(segment_pointer + 4, "APMODEL ", 8)) { segobj = new CPCIDSKAPModelSegment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "ADSMODEL", 8)) { segobj = new CPCIDSKADS40ModelSegment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "POLYMDL ", 8)) { segobj = new CPCIDSKBinarySegment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "TPSMODEL", 8)) { segobj = new CPCIDSKGCP2Segment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "MODEL ", 8)) { segobj = new CPCIDSKToutinModelSegment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "MMSPB ", 8)) { segobj = new CPCIDSKBinarySegment(this, segment, segment_pointer); } else if (!strncmp(segment_pointer + 4, "MMADS ", 8)) { segobj = new CPCIDSKBinarySegment(this, segment, segment_pointer); } break; } if (segobj == NULL) segobj = new CPCIDSKSegment( this, segment, segment_pointer ); segments[segment] = segobj; return segobj; } /************************************************************************/ /* GetSegment() */ /* */ /* Find segment by type/name. */ /************************************************************************/ PCIDSK::PCIDSKSegment *CPCIDSKFile::GetSegment( int type, std::string name, int previous ) { int i; char type_str[4]; name += " "; // white space pad name. //we want the 3 less significant digit only in case type is too big // Note : that happen with SEG_VEC_TABLE that is equal to 65652 in GDB. //see function BuildChildrenLayer in jtfile.cpp, the call on GDBSegNext //in the loop on gasTypeTable can create issue in PCIDSKSegNext //(in pcic/gdbfrtms/pcidskopen.cpp) sprintf( type_str, "%03d", (type % 1000) ); for( i = previous; i < segment_count; i++ ) { if( type != SEG_UNKNOWN && strncmp(segment_pointers.buffer+i*32+1,type_str,3) != 0 ) continue; if( name != " " && strncmp(segment_pointers.buffer+i*32+4,name.c_str(),8) != 0 ) continue; // Ignore deleted segments. if (*(segment_pointers.buffer + i * 32 + 0) == 'D') continue; return GetSegment(i+1); } return NULL; } /************************************************************************/ /* GetSegments() */ /************************************************************************/ std::vector<PCIDSK::PCIDSKSegment *> CPCIDSKFile::GetSegments() { PCIDSK::ThrowPCIDSKException( "Objects list access not implemented yet." ); std::vector<PCIDSK::PCIDSKSegment *> list; return list; } /************************************************************************/ /* InitializeFromHeader() */ /************************************************************************/ void CPCIDSKFile::InitializeFromHeader() { /* -------------------------------------------------------------------- */ /* Process the file header. */ /* -------------------------------------------------------------------- */ PCIDSKBuffer fh(512); ReadFromFile( fh.buffer, 0, 512 ); width = atoi(fh.Get(384,8)); height = atoi(fh.Get(392,8)); channel_count = atoi(fh.Get(376,8)); file_size = fh.GetUInt64(16,16); uint64 ih_start_block = atouint64(fh.Get(336,16)); uint64 image_start_block = atouint64(fh.Get(304,16)); fh.Get(360,8,interleaving); uint64 image_offset = (image_start_block-1) * 512; block_size = 0; last_block_index = -1; last_block_dirty = 0; last_block_data = NULL; last_block_mutex = NULL; /* -------------------------------------------------------------------- */ /* Load the segment pointers into a PCIDSKBuffer. For now we */ /* try to avoid doing too much other processing on them. */ /* -------------------------------------------------------------------- */ int segment_block_count = atoi(fh.Get(456,8)); segment_count = (segment_block_count * 512) / 32; segment_pointers.SetSize( segment_block_count * 512 ); segment_pointers_offset = atouint64(fh.Get(440,16)) * 512 - 512; ReadFromFile( segment_pointers.buffer, segment_pointers_offset, segment_block_count * 512 ); segments.resize( segment_count + 1 ); /* -------------------------------------------------------------------- */ /* Get the number of each channel type - only used for some */ /* interleaving cases. */ /* -------------------------------------------------------------------- */ int count_8u = 0, count_16s = 0, count_16u = 0, count_32r = 0; int count_c16u = 0, count_c16s = 0, count_c32r = 0; if (strcmp(fh.Get(464,4), " ") == 0) { count_8u = channel_count; } else { count_8u = atoi(fh.Get(464,4)); count_16s = atoi(fh.Get(468,4)); count_16u = atoi(fh.Get(472,4)); count_32r = atoi(fh.Get(476,4)); count_c16u = atoi(fh.Get(480,4)); count_c16s = atoi(fh.Get(484,4)); count_c32r = atoi(fh.Get(488,4)); } /* -------------------------------------------------------------------- */ /* for pixel interleaved files we need to compute the length of */ /* a scanline padded out to a 512 byte boundary. */ /* -------------------------------------------------------------------- */ if( interleaving == "PIXEL" ) { first_line_offset = image_offset; pixel_group_size = count_8u + count_16s*2 + count_16u*2 + count_32r*4; block_size = pixel_group_size * width; if( block_size % 512 != 0 ) block_size += 512 - (block_size % 512); last_block_data = malloc((size_t) block_size); if( last_block_data == NULL ) ThrowPCIDSKException( "Allocating %d bytes for scanline buffer failed.", (int) block_size ); last_block_mutex = interfaces.CreateMutex(); image_offset = 0; } /* -------------------------------------------------------------------- */ /* Initialize the list of channels. */ /* -------------------------------------------------------------------- */ int channelnum; for( channelnum = 1; channelnum <= channel_count; channelnum++ ) { PCIDSKBuffer ih(1024); PCIDSKChannel *channel = NULL; uint64 ih_offset = (ih_start_block-1)*512 + (channelnum-1)*1024; ReadFromFile( ih.buffer, ih_offset, 1024 ); // fetch the filename, if there is one. std::string filename; ih.Get(64,64,filename); // adjust it relative to the path of the pcidsk file. filename = MergeRelativePath( interfaces.io, base_filename, filename ); // work out channel type from header eChanType pixel_type; const char *pixel_type_string = ih.Get( 160, 8 ); pixel_type = GetDataTypeFromName(pixel_type_string); // if we didn't get channel type in header, work out from counts (old). // Check this only if we don't have complex channels: if (strncmp(pixel_type_string," ",8) == 0 ) { assert( count_c32r == 0 && count_c16u == 0 && count_c16s == 0 ); if( channelnum <= count_8u ) pixel_type = CHN_8U; else if( channelnum <= count_8u + count_16s ) pixel_type = CHN_16S; else if( channelnum <= count_8u + count_16s + count_16u ) pixel_type = CHN_16U; else pixel_type = CHN_32R; } if( interleaving == "BAND" ) { channel = new CBandInterleavedChannel( ih, ih_offset, fh, channelnum, this, image_offset, pixel_type ); image_offset += (int64)DataTypeSize(channel->GetType()) * (int64)width * (int64)height; } else if( interleaving == "PIXEL" ) { channel = new CPixelInterleavedChannel( ih, ih_offset, fh, channelnum, this, (int) image_offset, pixel_type ); image_offset += DataTypeSize(pixel_type); } else if( interleaving == "FILE" && strncmp(filename.c_str(),"/SIS=",5) == 0 ) { channel = new CTiledChannel( ih, ih_offset, fh, channelnum, this, pixel_type ); } else if( interleaving == "FILE" && filename != "" && strncmp(((const char*)ih.buffer)+250, " ", 8 ) != 0 ) { channel = new CExternalChannel( ih, ih_offset, fh, filename, channelnum, this, pixel_type ); } else if( interleaving == "FILE" ) { channel = new CBandInterleavedChannel( ih, ih_offset, fh, channelnum, this, 0, pixel_type ); } else ThrowPCIDSKException( "Unsupported interleaving:%s", interleaving.c_str() ); channels.push_back( channel ); } } /************************************************************************/ /* ReadFromFile() */ /************************************************************************/ void CPCIDSKFile::ReadFromFile( void *buffer, uint64 offset, uint64 size ) { MutexHolder oHolder( io_mutex ); interfaces.io->Seek( io_handle, offset, SEEK_SET ); if( interfaces.io->Read( buffer, 1, size, io_handle ) != size ) ThrowPCIDSKException( "PCIDSKFile:Failed to read %d bytes at %d.", (int) size, (int) offset ); } /************************************************************************/ /* WriteToFile() */ /************************************************************************/ void CPCIDSKFile::WriteToFile( const void *buffer, uint64 offset, uint64 size ) { if( !GetUpdatable() ) throw PCIDSKException( "File not open for update in WriteToFile()" ); MutexHolder oHolder( io_mutex ); interfaces.io->Seek( io_handle, offset, SEEK_SET ); if( interfaces.io->Write( buffer, 1, size, io_handle ) != size ) ThrowPCIDSKException( "PCIDSKFile:Failed to write %d bytes at %d.", (int) size, (int) offset ); } /************************************************************************/ /* ReadAndLockBlock() */ /************************************************************************/ void *CPCIDSKFile::ReadAndLockBlock( int block_index, int win_xoff, int win_xsize ) { if( last_block_data == NULL ) ThrowPCIDSKException( "ReadAndLockBlock() called on a file that is not pixel interleaved." ); /* -------------------------------------------------------------------- */ /* Default, and validate windowing. */ /* -------------------------------------------------------------------- */ if( win_xoff == -1 && win_xsize == -1 ) { win_xoff = 0; win_xsize = GetWidth(); } if( win_xoff < 0 || win_xoff+win_xsize > GetWidth() ) { ThrowPCIDSKException( "CPCIDSKFile::ReadAndLockBlock(): Illegal window - xoff=%d, xsize=%d", win_xoff, win_xsize ); } if( block_index == last_block_index && win_xoff == last_block_xoff && win_xsize == last_block_xsize ) { last_block_mutex->Acquire(); return last_block_data; } /* -------------------------------------------------------------------- */ /* Flush any dirty writable data. */ /* -------------------------------------------------------------------- */ FlushBlock(); /* -------------------------------------------------------------------- */ /* Read the requested window. */ /* -------------------------------------------------------------------- */ last_block_mutex->Acquire(); ReadFromFile( last_block_data, first_line_offset + block_index*block_size + win_xoff * pixel_group_size, pixel_group_size * win_xsize ); last_block_index = block_index; last_block_xoff = win_xoff; last_block_xsize = win_xsize; return last_block_data; } /************************************************************************/ /* UnlockBlock() */ /************************************************************************/ void CPCIDSKFile::UnlockBlock( bool mark_dirty ) { if( last_block_mutex == NULL ) return; last_block_dirty |= mark_dirty; last_block_mutex->Release(); } /************************************************************************/ /* WriteBlock() */ /************************************************************************/ void CPCIDSKFile::WriteBlock( int block_index, void *buffer ) { if( !GetUpdatable() ) throw PCIDSKException( "File not open for update in WriteBlock()" ); if( last_block_data == NULL ) ThrowPCIDSKException( "WriteBlock() called on a file that is not pixel interleaved." ); WriteToFile( buffer, first_line_offset + block_index*block_size, block_size ); } /************************************************************************/ /* FlushBlock() */ /************************************************************************/ void CPCIDSKFile::FlushBlock() { if( last_block_dirty ) { last_block_mutex->Acquire(); if( last_block_dirty ) // is it still dirty? { WriteBlock( last_block_index, last_block_data ); last_block_dirty = 0; } last_block_mutex->Release(); } } /************************************************************************/ /* GetEDBFileDetails() */ /************************************************************************/ bool CPCIDSKFile::GetEDBFileDetails( EDBFile** file_p, Mutex **io_mutex_p, std::string filename ) { *file_p = NULL; *io_mutex_p = NULL; /* -------------------------------------------------------------------- */ /* Does the file exist already in our file list? */ /* -------------------------------------------------------------------- */ unsigned int i; for( i = 0; i < edb_file_list.size(); i++ ) { if( edb_file_list[i].filename == filename ) { *file_p = edb_file_list[i].file; *io_mutex_p = edb_file_list[i].io_mutex; return edb_file_list[i].writable; } } /* -------------------------------------------------------------------- */ /* If not, we need to try and open the file. Eventually we */ /* will need better rules about read or update access. */ /* -------------------------------------------------------------------- */ ProtectedEDBFile new_file; new_file.file = NULL; new_file.writable = false; if( GetUpdatable() ) { try { new_file.file = interfaces.OpenEDB( filename, "r+" ); new_file.writable = true; } catch( PCIDSK::PCIDSKException ex ) {} catch( std::exception ex ) {} } if( new_file.file == NULL ) new_file.file = interfaces.OpenEDB( filename, "r" ); if( new_file.file == NULL ) ThrowPCIDSKException( "Unable to open file '%s'.", filename.c_str() ); /* -------------------------------------------------------------------- */ /* Push the new file into the list of files managed for this */ /* PCIDSK file. */ /* -------------------------------------------------------------------- */ new_file.io_mutex = interfaces.CreateMutex(); new_file.filename = filename; edb_file_list.push_back( new_file ); *file_p = edb_file_list[edb_file_list.size()-1].file; *io_mutex_p = edb_file_list[edb_file_list.size()-1].io_mutex; return new_file.writable; } /************************************************************************/ /* GetIODetails() */ /************************************************************************/ void CPCIDSKFile::GetIODetails( void ***io_handle_pp, Mutex ***io_mutex_pp, std::string filename, bool writable ) { *io_handle_pp = NULL; *io_mutex_pp = NULL; /* -------------------------------------------------------------------- */ /* Does this reference the PCIDSK file itself? */ /* -------------------------------------------------------------------- */ if( filename.size() == 0 ) { *io_handle_pp = &io_handle; *io_mutex_pp = &io_mutex; return; } /* -------------------------------------------------------------------- */ /* Does the file exist already in our file list? */ /* -------------------------------------------------------------------- */ unsigned int i; for( i = 0; i < file_list.size(); i++ ) { if( file_list[i].filename == filename && (!writable || file_list[i].writable) ) { *io_handle_pp = &(file_list[i].io_handle); *io_mutex_pp = &(file_list[i].io_mutex); return; } } /* -------------------------------------------------------------------- */ /* If not, we need to try and open the file. Eventually we */ /* will need better rules about read or update access. */ /* -------------------------------------------------------------------- */ ProtectedFile new_file; if( writable ) new_file.io_handle = interfaces.io->Open( filename, "r+" ); else new_file.io_handle = interfaces.io->Open( filename, "r" ); if( new_file.io_handle == NULL ) ThrowPCIDSKException( "Unable to open file '%s'.", filename.c_str() ); /* -------------------------------------------------------------------- */ /* Push the new file into the list of files managed for this */ /* PCIDSK file. */ /* -------------------------------------------------------------------- */ new_file.io_mutex = interfaces.CreateMutex(); new_file.filename = filename; new_file.writable = writable; file_list.push_back( new_file ); *io_handle_pp = &(file_list[file_list.size()-1].io_handle); *io_mutex_pp = &(file_list[file_list.size()-1].io_mutex); } /************************************************************************/ /* DeleteSegment() */ /************************************************************************/ void CPCIDSKFile::DeleteSegment( int segment ) { /* -------------------------------------------------------------------- */ /* Is this an existing segment? */ /* -------------------------------------------------------------------- */ PCIDSKSegment *poSeg = GetSegment( segment ); if( poSeg == NULL ) ThrowPCIDSKException( "DeleteSegment(%d) failed, segment does not exist.", segment ); /* -------------------------------------------------------------------- */ /* Wipe associated metadata. */ /* -------------------------------------------------------------------- */ std::vector<std::string> md_keys = poSeg->GetMetadataKeys(); unsigned int i; for( i = 0; i < md_keys.size(); i++ ) poSeg->SetMetadataValue( md_keys[i], "" ); /* -------------------------------------------------------------------- */ /* Remove the segment object from the segment object cache. I */ /* hope the application is not retaining any references to this */ /* segment! */ /* -------------------------------------------------------------------- */ segments[segment] = NULL; delete poSeg; /* -------------------------------------------------------------------- */ /* Mark the segment pointer as deleted. */ /* -------------------------------------------------------------------- */ segment_pointers.buffer[(segment-1)*32] = 'D'; // write the updated segment pointer back to the file. WriteToFile( segment_pointers.buffer + (segment-1)*32, segment_pointers_offset + (segment-1)*32, 32 ); } /************************************************************************/ /* CreateSegment() */ /************************************************************************/ int CPCIDSKFile::CreateSegment( std::string name, std::string description, eSegType seg_type, int data_blocks ) { /* -------------------------------------------------------------------- */ /* Set the size of fixed length segments. */ /* -------------------------------------------------------------------- */ int expected_data_blocks = 0; bool prezero = false; switch( seg_type ) { case SEG_LUT: expected_data_blocks = 2; break; case SEG_PCT: expected_data_blocks = 6; break; case SEG_SIG: expected_data_blocks = 12; break; case SEG_GCP2: // expected_data_blocks = 67; // Change seg type to new GCP segment type expected_data_blocks = 129; break; case SEG_GEO: expected_data_blocks = 6; break; case SEG_TEX: expected_data_blocks = 64; prezero = true; break; case SEG_BIT: { uint64 bytes = ((width * (uint64) height) + 7) / 8; expected_data_blocks = (int) ((bytes + 511) / 512); prezero = true; } break; default: break; } if( data_blocks == 0 && expected_data_blocks != 0 ) data_blocks = expected_data_blocks; /* -------------------------------------------------------------------- */ /* Find an empty Segment Pointer. For System segments we start */ /* at the end, instead of the beginning to avoid using up */ /* segment numbers that the user would notice. */ /* -------------------------------------------------------------------- */ int segment = 1; int64 seg_start = -1; PCIDSKBuffer segptr( 32 ); if( seg_type == SEG_SYS ) { for( segment=segment_count; segment >= 1; segment-- ) { memcpy( segptr.buffer, segment_pointers.buffer+(segment-1)*32, 32); uint64 this_seg_size = segptr.GetUInt64(23,9); char flag = (char) segptr.buffer[0]; if( flag == 'D' && (uint64) data_blocks+2 == this_seg_size && this_seg_size > 0 ) seg_start = segptr.GetUInt64(12,11) - 1; else if( flag == ' ' ) seg_start = 0; else if( flag && this_seg_size == 0 ) seg_start = 0; if( seg_start != -1 ) break; } } else { for( segment=1; segment <= segment_count; segment++ ) { memcpy( segptr.buffer, segment_pointers.buffer+(segment-1)*32, 32); uint64 this_seg_size = segptr.GetUInt64(23,9); char flag = (char) segptr.buffer[0]; if( flag == 'D' && (uint64) data_blocks+2 == this_seg_size && this_seg_size > 0 ) seg_start = segptr.GetUInt64(12,11) - 1; else if( flag == ' ' ) seg_start = 0; else if( flag && this_seg_size == 0 ) seg_start = 0; if( seg_start != -1 ) break; } } if( segment > segment_count ) ThrowPCIDSKException( "All %d segment pointers in use.", segment_count); /* -------------------------------------------------------------------- */ /* If the segment does not have a data area already, identify */ /* it's location at the end of the file, and extend the file to */ /* the desired length. */ /* -------------------------------------------------------------------- */ if( seg_start == 0 ) { seg_start = GetFileSize(); ExtendFile( data_blocks + 2, prezero ); } /* -------------------------------------------------------------------- */ /* Update the segment pointer information. */ /* -------------------------------------------------------------------- */ // SP1.1 - Flag segptr.Put( "A", 0, 1 ); // SP1.2 - Type segptr.Put( (int) seg_type, 1, 3 ); // SP1.3 - Name segptr.Put( name.c_str(), 4, 8 ); // SP1.4 - start block segptr.Put( (uint64) (seg_start + 1), 12, 11 ); // SP1.5 - data blocks. segptr.Put( data_blocks+2, 23, 9 ); // Update in memory copy of segment pointers. memcpy( segment_pointers.buffer+(segment-1)*32, segptr.buffer, 32); // Update on disk. WriteToFile( segptr.buffer, segment_pointers_offset + (segment-1)*32, 32 ); /* -------------------------------------------------------------------- */ /* Prepare segment header. */ /* -------------------------------------------------------------------- */ PCIDSKBuffer sh(1024); char current_time[17]; GetCurrentDateTime( current_time ); sh.Put( " ", 0, 1024 ); // SH1 - segment content description sh.Put( description.c_str(), 0, 64 ); // SH3 - Creation time/date sh.Put( current_time, 128, 16 ); // SH4 - Last Update time/date sh.Put( current_time, 144, 16 ); /* -------------------------------------------------------------------- */ /* Write segment header. */ /* -------------------------------------------------------------------- */ WriteToFile( sh.buffer, seg_start * 512, 1024 ); /* -------------------------------------------------------------------- */ /* Initialize the newly created segment. */ /* -------------------------------------------------------------------- */ PCIDSKSegment *seg_obj = GetSegment( segment ); seg_obj->Initialize(); return segment; } /************************************************************************/ /* ExtendFile() */ /************************************************************************/ void CPCIDSKFile::ExtendFile( uint64 blocks_requested, bool prezero ) { if( prezero ) { std::vector<uint8> zeros; uint64 blocks_to_zero = blocks_requested; zeros.resize( 512 * 32 ); while( blocks_to_zero > 0 ) { uint64 this_time = blocks_to_zero; if( this_time > 32 ) this_time = 32; WriteToFile( &(zeros[0]), file_size * 512, this_time*512 ); blocks_to_zero -= this_time; file_size += this_time; } } else { WriteToFile( "\0", (file_size + blocks_requested) * 512 - 1, 1 ); file_size += blocks_requested; } PCIDSKBuffer fh3( 16 ); fh3.Put( file_size, 0, 16 ); WriteToFile( fh3.buffer, 16, 16 ); } /************************************************************************/ /* ExtendSegment() */ /************************************************************************/ void CPCIDSKFile::ExtendSegment( int segment, uint64 blocks_requested, bool prezero ) { // for now we take it for granted that the segment is valid and at th // end of the file - later we should support moving it. ExtendFile( blocks_requested, prezero ); // Update the block count. segment_pointers.Put( segment_pointers.GetUInt64((segment-1)*32+23,9) + blocks_requested, (segment-1)*32+23, 9 ); // write the updated segment pointer back to the file. WriteToFile( segment_pointers.buffer + (segment-1)*32, segment_pointers_offset + (segment-1)*32, 32 ); } /************************************************************************/ /* MoveSegmentToEOF() */ /************************************************************************/ void CPCIDSKFile::MoveSegmentToEOF( int segment ) { int segptr_off = (segment - 1) * 32; uint64 seg_start, seg_size; uint64 new_seg_start; seg_start = segment_pointers.GetUInt64( segptr_off + 12, 11 ); seg_size = segment_pointers.GetUInt64( segptr_off + 23, 9 ); // Are we already at the end of the file? if( (seg_start + seg_size - 1) == file_size ) return; new_seg_start = file_size + 1; // Grow the file to hold the segment at the end. ExtendFile( seg_size, false ); // Move the segment data to the new location. uint8 copy_buf[16384]; uint64 srcoff, dstoff, bytes_to_go; bytes_to_go = seg_size * 512; srcoff = (seg_start - 1) * 512; dstoff = (new_seg_start - 1) * 512; while( bytes_to_go > 0 ) { uint64 bytes_this_chunk = sizeof(copy_buf); if( bytes_to_go < bytes_this_chunk ) bytes_this_chunk = bytes_to_go; ReadFromFile( copy_buf, srcoff, bytes_this_chunk ); WriteToFile( copy_buf, dstoff, bytes_this_chunk ); srcoff += bytes_this_chunk; dstoff += bytes_this_chunk; bytes_to_go -= bytes_this_chunk; } // Update segment pointer in memory and on disk. segment_pointers.Put( new_seg_start, segptr_off + 12, 11 ); WriteToFile( segment_pointers.buffer + segptr_off, segment_pointers_offset + segptr_off, 32 ); // Update the segments own information. if( segments[segment] != NULL ) { CPCIDSKSegment *seg = dynamic_cast<CPCIDSKSegment *>( segments[segment] ); seg->LoadSegmentPointer( segment_pointers.buffer + segptr_off ); } } /************************************************************************/ /* CreateOverviews() */ /************************************************************************/ /* const char *pszResampling; Can be "NEAREST" for Nearest Neighbour resampling (the fastest), "AVERAGE" for block averaging or "MODE" for block mode. This establishing the type of resampling to be applied when preparing the decimated overviews. Other methods can be set as well, but not all applications might support a given overview generation method. */ void CPCIDSKFile::CreateOverviews( int chan_count, int *chan_list, int factor, std::string resampling ) { std::vector<int> default_chan_list; /* -------------------------------------------------------------------- */ /* Default to processing all bands. */ /* -------------------------------------------------------------------- */ if( chan_count == 0 ) { chan_count = channel_count; default_chan_list.resize( chan_count ); for( int i = 0; i < chan_count; i++ ) default_chan_list[i] = i+1; chan_list = &(default_chan_list[0]); } /* -------------------------------------------------------------------- */ /* Work out the creation options that should apply for the */ /* overview. */ /* -------------------------------------------------------------------- */ std::string layout = GetMetadataValue( "_DBLayout" ); int blocksize = 127; std::string compression = "NONE"; if( strncmp( layout.c_str(), "TILED", 5 ) == 0 ) { ParseTileFormat( layout, blocksize, compression ); } /* -------------------------------------------------------------------- */ /* Make sure we have a blockmap segment for managing the tiled */ /* layers. */ /* -------------------------------------------------------------------- */ PCIDSKSegment *bm_seg = GetSegment( SEG_SYS, "SysBMDir" ); SysBlockMap *bm; if( bm_seg == NULL ) { CreateSegment( "SysBMDir", "System Block Map Directory - Do not modify.", SEG_SYS, 0 ); bm_seg = GetSegment( SEG_SYS, "SysBMDir" ); bm = dynamic_cast<SysBlockMap *>(bm_seg); bm->Initialize(); } else bm = dynamic_cast<SysBlockMap *>(bm_seg); /* ==================================================================== */ /* Loop over the channels. */ /* ==================================================================== */ for( int chan_index = 0; chan_index < chan_count; chan_index++ ) { int channel_number = chan_list[chan_index]; PCIDSKChannel *channel = GetChannel( channel_number ); /* -------------------------------------------------------------------- */ /* Figure out if the given overview level already exists */ /* for a given channel; if it does, skip creating it. */ /* -------------------------------------------------------------------- */ bool overview_exists = false; for( int i = channel->GetOverviewCount()-1; i >= 0; i-- ) { PCIDSKChannel *overview = channel->GetOverview( i ); if( overview->GetWidth() == channel->GetWidth() / factor && overview->GetHeight() == channel->GetHeight() / factor ) { overview_exists = true; } } if (overview_exists == false) { /* -------------------------------------------------------------------- */ /* Create the overview as a tiled image layer. */ /* -------------------------------------------------------------------- */ int virtual_image = bm->CreateVirtualImageFile( channel->GetWidth() / factor, channel->GetHeight() / factor, blocksize, blocksize, channel->GetType(), compression ); /* -------------------------------------------------------------------- */ /* Attach reference to this overview as metadata. */ /* -------------------------------------------------------------------- */ char overview_md_value[128]; char overview_md_key[128]; sprintf( overview_md_key, "_Overview_%d", factor ); sprintf( overview_md_value, "%d 0 %s",virtual_image,resampling.c_str()); channel->SetMetadataValue( overview_md_key, overview_md_value ); } /* -------------------------------------------------------------------- */ /* Force channel to invalidate it's loaded overview list. */ /* -------------------------------------------------------------------- */ dynamic_cast<CPCIDSKChannel *>(channel)->InvalidateOverviewInfo(); } }
36.399848
101
0.422217
[ "object", "vector", "model" ]
28b07e12b6fb8a8fadf72d5f43c94f89577cf311
2,311
cpp
C++
Engine/src/ModuleWindow.cpp
JoanMarcBardes/Master-Engine
2e36395d3a6c147389372a261f60fa76d12ce55c
[ "MIT" ]
null
null
null
Engine/src/ModuleWindow.cpp
JoanMarcBardes/Master-Engine
2e36395d3a6c147389372a261f60fa76d12ce55c
[ "MIT" ]
null
null
null
Engine/src/ModuleWindow.cpp
JoanMarcBardes/Master-Engine
2e36395d3a6c147389372a261f60fa76d12ce55c
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleWindow.h" #include "ModuleEditorCamera.h" #include "DebugLeaks.h" ModuleWindow::ModuleWindow() { } // Destructor ModuleWindow::~ModuleWindow() { } // Called before render is available bool ModuleWindow::Init() { LOG("Init SDL window & surface"); bool ret = true; if(SDL_Init(SDL_INIT_VIDEO) < 0) { LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Create window SDL_DisplayMode DM; SDL_GetCurrentDisplayMode(0, &DM); width = DM.w * 0.95f; height = DM.h * 0.95f; Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; if(FULLSCREEN == true) { flags |= SDL_WINDOW_FULLSCREEN; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); // desired version SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // we want a double buffer SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // we want to have a depth buffer with 24 bits SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // we want to have a stencil buffer with 8 bits window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); if(window == NULL) { LOG("Window could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Get window surface screen_surface = SDL_GetWindowSurface(window); } } return ret; } // Called every draw update update_status ModuleWindow::Update() { int width, height; SDL_GetWindowSize(App->window->window, &width, &height); App->window->SetWidthHeight(width, height); return UPDATE_CONTINUE; } // Called before quitting bool ModuleWindow::CleanUp() { LOG("Destroying SDL window and quitting all SDL systems"); //Destroy window if(window != NULL) { SDL_DestroyWindow(window); } //Quit SDL subsystems SDL_Quit(); return true; } void ModuleWindow::SetWidthHeight(const int w, const int h) { width = w; height = h; App->editorCamera->WindowResized(width, height); SDL_SetWindowSize(window, width, height); } void ModuleWindow::SetTitle(const char* newTitle) { SDL_SetWindowTitle(window, newTitle); }
22.436893
107
0.728256
[ "render" ]
28b64ac7f8f2b37d93444d63087a4dae2b10516d
17,279
cpp
C++
src/dailyworkparser.cpp
EnderXenocide/DailyWork
7a6384ec7d692b2ebdbb466b2e83b5f6ac164e28
[ "Apache-2.0" ]
null
null
null
src/dailyworkparser.cpp
EnderXenocide/DailyWork
7a6384ec7d692b2ebdbb466b2e83b5f6ac164e28
[ "Apache-2.0" ]
null
null
null
src/dailyworkparser.cpp
EnderXenocide/DailyWork
7a6384ec7d692b2ebdbb466b2e83b5f6ac164e28
[ "Apache-2.0" ]
null
null
null
#include "dailyworkparser.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include <fstream> #include <sstream> #include <iostream> #include "easylogging++.h" DailyWorkParser::DailyWorkParser() { modified = false; jsonFile = JSON_FILE; } DailyWorkParser::~DailyWorkParser() { } void DailyWorkParser::StatusBarMessageCallback(CallbackMessageInfo cb) { m_cbMessageInfo = cb; } void DailyWorkParser::DialogMessageCallback(CallbackMessageInfo cb) { m_cbDialog = cb; } int DailyWorkParser::Parse() { // const char* json = "{\"dailywork\":[ {\"date\":\"2015-07-24\",\"work\":\"rien\"}," // "{\"date\":\"2015-07-23\",\"work\":\"nothing\"}," // "{\"date\":\"2015-07-22\",\"work\":\"niet\"} ] }"; modified = false; int retour = 0; LOG(INFO) << "Parse file " << jsonFile; std::ifstream ifs(jsonFile); if(ifs) { std::stringstream ss; ss << ifs.rdbuf(); ifs.close(); if(document.Parse<0>(ss.str().c_str()).HasParseError()) { ParseErrorCode parseErrorCode = document.GetParseError(); wxString strErreur = wxString::Format(_("Error reading file (offset %u): %s\n"), (unsigned)document.GetErrorOffset(), GetParseError_En(parseErrorCode)); LOG(ERROR) << strErreur; m_cbMessageInfo(strErreur); retour = -1; } } else { LOG(ERROR) << _("File not found"); m_cbMessageInfo(_("File not found")); retour = -1; } TestAndUpdate(); if (modified) { wxString msg = wxString::Format(_("File updated to version %d"),JSON_VERSION_SCHEMA); LOG(INFO) << msg; m_cbDialog(msg); } return retour; } int DailyWorkParser::UpdateWork(const wxDateTime& date, wxString work, wxString format) { if(date.IsValid()) { std::string sdate = ToDWDate(date).ToStdString(); Value &array = document[JSON_ITEMS]; for (SizeType i = 0; i < array.Size(); i++) { if (array[i][JSON_DATE].GetString()==sdate) { SetWorkFromItem(array[i], work, format); return 0; } } LOG(DEBUG) << "Date not found :" << sdate; } LOG(DEBUG) << "Update impossible"; return -1; } int DailyWorkParser::Save() { return SaveAs(jsonFile); } int DailyWorkParser::SaveAs(wxString filename) { wxString msg = "Save"; if (filename != jsonFile) msg += " as "+filename; LOG(INFO) << msg; FILE* fp = fopen(filename, "wb"); // non-Windows use "w" char writeBuffer[65536]; FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); Writer<FileWriteStream> writer(os); document.Accept(writer); fclose(fp); modified = false; return 0; } wxDateTime DailyWorkParser::GetDateFromItem(int itemIndex) { const Value& item = document[JSON_ITEMS][itemIndex]; if (item.IsObject()) { return DWToDate(item[JSON_DATE].GetString()); } else { return wxDateTime((time_t)-1); } } wxString DailyWorkParser::GetWorkFromDate(const wxDateTime& date) { if ( date.IsValid() ) { std::string sdate = ToDWDate(date).ToStdString(); Value &array = document[JSON_ITEMS]; for (SizeType i = 0; i < array.Size(); i++) { if (array[i][JSON_DATE].GetString()==sdate) { return GetWorkFromItem(array[i]); } } LOG(DEBUG) << "Date not found :" << sdate; } else { LOG(DEBUG) << "Invalid Date"; } return ""; } wxString DailyWorkParser::GetWorkFromItem(const Value& item) { return item[JSON_WORK].GetString(); } /* * Ex : Transfome une date en 2015-12-31 * */ wxString DailyWorkParser::ToDWDate(const wxDateTime& date) const { return wxString::Format(JSON_DATE_FORMAT, date.GetYear(), date.GetMonth()+1, date.GetDay()); } /* * Ex : Transfome une date 2015-12-31 en 31/12/2015 * */ wxString DailyWorkParser::ToTreeDate(const wxDateTime& date) const { // std::sscanf(aDWDate.c_str(), JSON_DATE_FORMAT, &year, &month, &day); return wxString::Format(TREE_DATE_FORMAT, date.GetDay(), date.GetMonth()+1, date.GetYear()); } int DailyWorkParser::SetWorkFromItem(Value& item, wxString work, wxString format) { assert(item.IsObject()); std::string utf8 = work.ToUTF8().data(); item[JSON_WORK].SetString(utf8.data(), utf8.size(), document.GetAllocator()); if ((format!=JSON_WORK_FORMAT_HTML) && (format!=JSON_WORK_FORMAT_TEXT)) format = JSON_WORK_FORMAT_TEXT; item[JSON_WORK_FORMAT].SetString(format.data(), format.size(), document.GetAllocator()); LOG(DEBUG ) << "Edit modified ("<< format <<") :" << utf8; modified = true; return 0; } wxDateTime DailyWorkParser::DWToDate(const wxString DWDate) const { wxDateTime date; // if (!date.ParseISODate(DWDate)) { if (!date.ParseFormat(DWDate, JSON_DATE_FORMAT_EXT, wxDateTime::Today())) { LOG(ERROR) << "Can't convert " << DWDate << "to date"; } return date; } int DailyWorkParser::DeleteItem(wxDateTime date) { if (date.IsValid()) { std::string sdate = ToDWDate(date).ToStdString(); Value & array = document[JSON_ITEMS]; for (Value::ConstValueIterator itr = array.Begin(); itr != array.End(); itr++) { if (itr->FindMember(JSON_DATE)->value.GetString()==sdate) { array.Erase(itr); LOG(INFO) << "Delete date " << sdate; modified = true; return 0; } } } return 1; //non supprimé } void DailyWorkParser::AddItem(const wxDateTime& date, wxString work, wxString format) { std::string DWDate = ToDWDate(date).ToStdString(); std::string utf8Work = work.ToUTF8().data(); LOG(INFO) << "Add Date " << DWDate; Document::AllocatorType& allocator = document.GetAllocator(); Value value(kObjectType); Value valueString(kStringType); valueString.SetString(DWDate.data(), DWDate.size(), document.GetAllocator()); value.AddMember(JSON_DATE, valueString, allocator); valueString.SetString(utf8Work.data(), utf8Work.size(), document.GetAllocator()); value.AddMember(JSON_WORK, valueString, allocator); valueString.SetString(format.data(), format.size(), document.GetAllocator()); value.AddMember(JSON_WORK_FORMAT, valueString, allocator); Value &array = document[JSON_ITEMS]; array.PushBack(value, allocator); modified = true; //return array[array.Size()-1];//todo valid ? // static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; // LOG(INFO) << "Type of member is " << kTypeNames[value.GetType()]; } SizeType DailyWorkParser::CountItems() { return document[JSON_ITEMS].Size(); } SizeType DailyWorkParser::CountFavorites() { return document[JSON_FAVORITES].Size(); } wxString DailyWorkParser::GetFavorite(int itemIndex) { const Value& item = document[JSON_FAVORITES][itemIndex]; if (item.IsString()) { return wxString::FromUTF8(item.GetString()); } else { return ""; } } /* * Doublon avec TestAndUpdate() ? * */ void DailyWorkParser::New() { document.SetObject(); Document::AllocatorType& allocator = document.GetAllocator(); Value items(kArrayType); document.AddMember(JSON_ITEMS, items, allocator); document.AddMember(JSON_FAVORITES, items, allocator); document.AddMember(JSON_EXCLUDED_DAYS, items, allocator); Value version(JSON_VERSION_SCHEMA); document.AddMember(JSON_VERSION, version, allocator); modified = true; } void DailyWorkParser::TestAndUpdate() { Document::AllocatorType& allocator = document.GetAllocator(); if (document.IsNull()) document.SetObject(); if (!document.HasMember(JSON_ITEMS)) { Value items(kArrayType); document.AddMember(JSON_ITEMS, items, allocator); modified = true; } if (!document.HasMember(JSON_VERSION)) { Value items(JSON_VERSION_SCHEMA); document.AddMember(JSON_VERSION, items, allocator); modified = true; } version = document[JSON_VERSION].GetInt(); if (version<JSON_VERSION_SCHEMA) { document[JSON_VERSION].SetInt(JSON_VERSION_SCHEMA); //passage à la version n° JSON_VERSION_SCHEMA modified = true; } // if (version<4) { Value & items = document[JSON_ITEMS]; for (Value::ValueIterator itr = items.Begin(); itr != items.End(); itr++) { if (!itr->HasMember(JSON_WORK_FORMAT)) { Value format(kStringType); format.SetString(JSON_WORK_FORMAT_TEXT, strlen(JSON_WORK_FORMAT_TEXT), allocator); itr->AddMember(JSON_WORK_FORMAT, format, allocator); modified = true; } } // } if (!document.HasMember(JSON_FAVORITES)) { Value favorites(kArrayType); document.AddMember(JSON_FAVORITES, favorites, allocator); modified = true; } if (!document.HasMember(JSON_EXCLUDED_DAYS)) { Value excludedDays(kArrayType); document.AddMember(JSON_EXCLUDED_DAYS, excludedDays, allocator); modified = true; } } bool DailyWorkParser::AddToFavorites(wxString text) { std::string utf8Text = text.ToUTF8().data(); if (IsInFavorites(text)) { LOG(INFO) << "Can't add existing favorite <" << utf8Text <<">"; return false; } LOG(INFO) << "Add favorite <" << utf8Text <<">"; Document::AllocatorType& allocator = document.GetAllocator(); Value valueString(kStringType); valueString.SetString(utf8Text.c_str(), utf8Text.size(), document.GetAllocator()); Value &array = document[JSON_FAVORITES]; array.PushBack(valueString, allocator); modified = true; return true; } int DailyWorkParser::DeleteFavorite(wxString text) { std::string utf8Text = text.ToUTF8().data(); Value &array = document[JSON_FAVORITES]; for (Value::ConstValueIterator itr = array.Begin(); itr != array.End(); itr++) { if (itr->GetString()==utf8Text) { array.Erase(itr); LOG(INFO) << "Delete favorite <" << utf8Text <<">"; modified = true; return 0; } } LOG(DEBUG) << "Favorite <" << utf8Text <<"> not found"; return -1; } bool DailyWorkParser::IsInFavorites(wxString text) { std::string utf8Text = text.ToUTF8().data(); Value &array = document[JSON_FAVORITES]; for (Value::ConstValueIterator itr = array.Begin(); itr != array.End(); itr++) { if (itr->GetString()==utf8Text) { return true; } } return false; } int DailyWorkParser::SearchInDates(const wxString text, MapFind &results) { std::string utf8Text = text.ToUTF8().data(); Value &array = document[JSON_ITEMS]; for (Value::ConstValueIterator itr = array.Begin(); itr != array.End(); itr++) { Value::ConstMemberIterator mitrString = itr->FindMember(JSON_WORK); if ( mitrString != itr->MemberEnd() ) { std::string str = mitrString->value.GetString(); //std::size_t idx = str.find(utf8Text); //case sensitive std::size_t idx = findStringIC(str, utf8Text); if(idx != std::string::npos){ Value::ConstMemberIterator mitrDate = itr->FindMember(JSON_DATE); if ( mitrDate != itr->MemberEnd() ) { wxDateTime date = DWToDate(mitrDate->value.GetString()); std::string line = GetLine(str, idx); Result result(date, wxString::FromUTF8(wxString(line))); results.insert(result); } } // for(std::size_t pos = 0;pos != std::string::npos && pos < str.size();++pos){ // std::size_t idx = str.find(utf8Text,pos); // if(pos != std::string::npos){ // std::cout << sub_str << " trouvé dans " << str // << " à la position " << idx << std::endl; // } // pos = idx + 1; // } } } return results.size(); } /// Try to find in the Haystack the Needle - ignore case // http://stackoverflow.com/users/195527/cc std::size_t DailyWorkParser::findStringIC(const std::string &strHaystack, const std::string &strNeedle) const { std::string strHaystackUC = strHaystack; for (auto & c: strHaystackUC) c = toupper(c); std::string strNeedleUC = strNeedle; for (auto & c: strNeedleUC) c = toupper(c); return strHaystackUC.find(strNeedleUC); //case sensitive } std::string DailyWorkParser::GetLine(const std::string &str, std::size_t idx) const { //std::string upperstr = str. std::size_t idxFirstCR = str.find_last_of('\n', idx); //cherche un retour à la ligne avant idx if (idxFirstCR != std::string::npos) { // un retour à la ligne trouvé std::size_t len; std::size_t pos; std::size_t idxLastCR = str.find_first_of('\n', idx+1); // cherche un retour à la ligne après idx if (idxFirstCR<idx) // retour à la ligne trouvé avant idx pos = idxFirstCR+1; else pos = 0; //idx sest sur la première igne return (it != strHaystack.end() ); if ( idxLastCR != std::string::npos) // retour à la ligne trouvé après idx len = idxLastCR-pos; else len = std::string::npos; // recupère reste de la chaine return str.substr(pos, len); } else return str; // renvoie str qui est sur une ligne } int DailyWorkParser::GetExcludedDays(ExcludedDays &ed) { Value &array = document[JSON_EXCLUDED_DAYS]; ed.Clear(); LOG(INFO) << "Get Excluded Days : "; for (Value::ConstValueIterator itr = array.Begin(); itr != array.End(); itr++) { std::string day = itr->GetString(); if (day=="monday") ed.monday = true; else if (day=="tuesday") ed.tuesday = true; else if (day=="wednesday") ed.wednesday = true; else if (day=="thursday") ed.thursday = true; else if (day=="saturday") ed.saturday = true; else if (day=="sunday") ed.sunday = true; LOG(INFO) << day; } if (!ed.IsValid()) { ed.DefaultValidate(); return 0; } return -1; } int DailyWorkParser::SetExcludedDays(ExcludedDays ed) { Value &array = document[JSON_EXCLUDED_DAYS]; array.Clear(); ed.AutoValid(); std::string listeExcludeDays; Document::AllocatorType& allocator = document.GetAllocator(); Value valueString(kStringType); if (ed.monday) { std::string text = "monday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = text+" "; } if (ed.tuesday) { std::string text = "tuesday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = listeExcludeDays+text+" "; }; if (ed.wednesday) { std::string text = "wednesday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = listeExcludeDays+text+" "; }; if (ed.thursday) { std::string text = "thursday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = listeExcludeDays+text+" "; }; if (ed.saturday) { std::string text = "saturday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = listeExcludeDays+text+" "; }; if (ed.sunday) { std::string text = "sunday"; valueString.SetString(text.c_str(), text.size(), allocator); array.PushBack(valueString, allocator); modified = true; listeExcludeDays = listeExcludeDays+text+" "; LOG(INFO) << "Set Excluded Days : "<< listeExcludeDays; }; return -1; } /* std::string utf8Text = text.ToUTF8().data(); if (IsInFavorites(text)) { LOG(INFO) << "Pas d'ajout du favoris <" << utf8Text <<"> déja éxistant"; return false; } LOG(INFO) << "Ajoute le favoris <" << utf8Text <<">"; Document::AllocatorType& allocator = document.GetAllocator(); Value valueString(kStringType); valueString.SetString(utf8Text.c_str(), utf8Text.size(), document.GetAllocator()); Value &array = document[JSON_FAVORITES]; array.PushBack(valueString, allocator); modified = true; return true; */
33.748047
109
0.597315
[ "object" ]
28b943406491049bd246b9dfd3fbc276ce649331
68,403
cpp
C++
src/ide.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
219
2017-07-28T17:25:14.000Z
2022-03-17T23:03:17.000Z
src/ide.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
729
2017-08-10T14:42:30.000Z
2022-03-31T23:14:09.000Z
src/ide.cpp
jkelroy/SAM
3c05e55ec7d9e31f33e06f17fa6fb41bb19f04db
[ "BSD-3-Clause" ]
109
2017-09-16T00:52:54.000Z
2022-03-31T18:05:05.000Z
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <chrono> #include <wx/splitter.h> #include <wx/notebook.h> #include <wx/busyinfo.h> #include <wx/wfstream.h> #include <wx/datstrm.h> #include <wx/dir.h> #include <wx/filename.h> #include <wx/txtstrm.h> #include <wx/wfstream.h> #include <wx/gbsizer.h> #include <wx/tokenzr.h> #include <wex/exttext.h> #include <wex/lkscript.h> #include <wex/metro.h> #include <wex/uiform.h> #include <wex/utils.h> #include <wex/extgrid.h> #include <wex/csv.h> #include <lk/lex.h> #include <lk/parse.h> #include <ssc/sscapi.h> #include "ide.h" #include "main.h" #include "equations.h" #include "inputpage.h" #include "invoke.h" #include "widgets.h" #include "reports.h" #include "defmgr.h" enum { ID_STARTUP_EDITOR = wxID_HIGHEST+124, ID_STARTUP_SAVE, ID_STARTUP_FIND, ID_STARTUP_HELP, ID_STARTUP_RESTART }; BEGIN_EVENT_TABLE( ScriptPanel, wxPanel ) EVT_BUTTON( ID_STARTUP_SAVE, ScriptPanel::OnCommand ) EVT_BUTTON( ID_STARTUP_FIND, ScriptPanel::OnCommand ) EVT_BUTTON( ID_STARTUP_HELP, ScriptPanel::OnCommand ) EVT_BUTTON( ID_STARTUP_RESTART, ScriptPanel::OnCommand ) END_EVENT_TABLE() ScriptPanel::ScriptPanel( wxWindow *parent, const wxString &script_file_name ) : wxPanel( parent ), m_fileName( script_file_name ) { wxBoxSizer *sz_startup_tools = new wxBoxSizer( wxHORIZONTAL ); sz_startup_tools->Add( new wxButton( this, ID_STARTUP_SAVE, "Save"), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_STARTUP_FIND, "Find..."), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_STARTUP_HELP, "Help"), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_STARTUP_RESTART, "Restart SAM"), 0, wxALL|wxEXPAND, 2 ); m_scriptCtrl = new wxLKScriptCtrl( this, ID_STARTUP_EDITOR ); wxBoxSizer *sz_startup_main = new wxBoxSizer( wxVERTICAL ); sz_startup_main->Add( sz_startup_tools, 0, wxALL|wxEXPAND, 2 ); sz_startup_main->Add( m_scriptCtrl, 1, wxALL|wxEXPAND, 0 ); SetSizer( sz_startup_main ); m_scriptCtrl->RegisterLibrary( invoke_general_funcs(), "General Functions", 0 ); if (!m_scriptCtrl->ReadAscii( SamApp::GetRuntimePath() + "/" + m_fileName ) ) wxMessageBox("Error loading " + m_fileName, "notice", wxOK, this); } void ScriptPanel::AddLibrary( lk::fcall_t *lib, const wxString &name ) { m_scriptCtrl->RegisterLibrary( lib, name ); } void ScriptPanel::OnCommand( wxCommandEvent &evt ) { switch( evt.GetId() ) { case ID_STARTUP_SAVE: { wxBusyInfo savemsg( "Writing " + m_fileName + " to disk" ); wxYield(); wxMilliSleep(300); if ( !m_scriptCtrl->WriteAscii( SamApp::GetRuntimePath() + "/" + m_fileName )) wxMessageBox("Error writing " + m_fileName + " to disk" , "notice", wxOK, this); break; } case ID_STARTUP_FIND: m_scriptCtrl->ShowFindReplaceDialog(); break; case ID_STARTUP_HELP: m_scriptCtrl->ShowHelpDialog( this ); break; case ID_STARTUP_RESTART: { if ( m_scriptCtrl->IsModified() && wxYES == wxMessageBox( m_fileName + " is modified. Save first?", "Query", wxYES_NO, this) ) m_scriptCtrl->WriteAscii( SamApp::GetRuntimePath() + "/" + m_fileName ); wxBusyInfo restartmsg( "Restarting SAM... messages in debug output screen" ); wxYield(); wxMilliSleep(300); SamApp::Restart(); } break; } } /* enum { ID_SIMULATIONS_EDITOR = wxID_HIGHEST+495, ID_SIMULATIONS_LIST, ID_SIMULATIONS_SAVE, ID_SIMULATIONS_NEW, ID_SIMULATIONS_FIND, ID_SIMULATIONS_HELP }; BEGIN_EVENT_TABLE( SimulationScriptPanel, wxPanel ) EVT_CHOICE( ID_SIMULATIONS_LIST, SimulationScriptPanel::OnCommand ) EVT_BUTTON( ID_SIMULATIONS_SAVE, SimulationScriptPanel::OnCommand ) EVT_BUTTON( ID_SIMULATIONS_NEW, SimulationScriptPanel::OnCommand ) EVT_BUTTON( ID_SIMULATIONS_FIND, SimulationScriptPanel::OnCommand ) EVT_BUTTON( ID_SIMULATIONS_HELP, SimulationScriptPanel::OnCommand ) END_EVENT_TABLE() extern lk::fcall_t *invoke_simulation_stubs(); SimulationScriptPanel::SimulationScriptPanel( wxWindow *parent ) : wxPanel( parent ) { m_scriptCtrl = new wxLKScriptCtrl( this, ID_SIMULATIONS_EDITOR ); m_scriptCtrl->RegisterLibrary( invoke_simulation_stubs(), "Simulation Functions", 0 ); m_simList = new wxChoice( this, ID_SIMULATIONS_LIST ); RefreshList(); if ( m_simList->GetCount() > 0 ) { m_simList->SetSelection( 0 ); m_currentFile = SamApp::GetRuntimePath() + "/simulations/" + m_simList->GetStringSelection(); m_scriptCtrl->ReadAscii( m_currentFile ); } wxBoxSizer *sz_startup_tools = new wxBoxSizer( wxHORIZONTAL ); sz_startup_tools->Add( m_simList, 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_SIMULATIONS_NEW, "New"), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_SIMULATIONS_SAVE, "Save"), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_SIMULATIONS_FIND, "Find..."), 0, wxALL|wxEXPAND, 2 ); sz_startup_tools->Add( new wxButton( this, ID_SIMULATIONS_HELP, "Help"), 0, wxALL|wxEXPAND, 2 ); wxBoxSizer *sz_startup_main = new wxBoxSizer( wxVERTICAL ); sz_startup_main->Add( sz_startup_tools, 0, wxALL|wxEXPAND, 2 ); sz_startup_main->Add( m_scriptCtrl, 1, wxALL|wxEXPAND, 0 ); SetSizer( sz_startup_main ); } void SimulationScriptPanel::RefreshList() { wxString sel = m_simList->GetStringSelection(); m_simList->Clear(); wxDir dir( SamApp::GetRuntimePath() + "/simulations" ); if ( dir.IsOpened() ) { wxString file; bool has_more = dir.GetFirst( &file, "*.sim", wxDIR_FILES ); while( has_more ) { m_simList->Append( file ); has_more = dir.GetNext( &file ); } } m_simList->SetStringSelection( sel ); } void SimulationScriptPanel::SaveCurrent() { wxBusyInfo savemsg( "Writing to disk: " + wxFileName(m_currentFile).GetName() ); wxYield(); wxMilliSleep(100); if ( !m_scriptCtrl->WriteAscii( m_currentFile )) wxMessageBox("Error writing to disk:\n\n" + m_currentFile, "notice", wxOK, this); } void SimulationScriptPanel::OnCommand( wxCommandEvent &evt ) { switch( evt.GetId() ) { case ID_SIMULATIONS_LIST: SaveCurrent(); m_currentFile = SamApp::GetRuntimePath() + "/simulations/" + m_simList->GetStringSelection(); m_scriptCtrl->ReadAscii( m_currentFile ); break; case ID_SIMULATIONS_SAVE: SaveCurrent(); break; case ID_SIMULATIONS_FIND: m_scriptCtrl->ShowFindReplaceDialog(); break; case ID_SIMULATIONS_HELP: m_scriptCtrl->ShowHelpDialog( this ); break; case ID_SIMULATIONS_NEW: { wxString name = wxGetTextFromUser("Enter name of simulation file:", "query", wxEmptyString, this ); if ( name.IsEmpty() ) return; wxString path = SamApp::GetRuntimePath() + "/simulations/" + name + ".sim"; if ( wxFileExists( path ) ) { wxMessageBox("that one already exists", "notice", wxOK, this); return; } wxFile ff( path, wxFile::write ); if (ff.IsOpened() ) { ff.Write( "on_simulate{'<<tech-or-financing-name>>'} = define() {\n\tlog('simulation info');\n\treturn true;\n};\n"); ff.Close(); SaveCurrent(); RefreshList(); m_simList->SetStringSelection( name + ".sim" ); m_currentFile = path; m_scriptCtrl->ReadAscii( path ); } else wxMessageBox("error creating new simulation file"); } break; } } */ enum { ID_SSC_MOD = wxID_HIGHEST, ID_APPLY_VTL, ID_APPLY_LAST_DOT }; class RemapDialog : public wxDialog { UIEditorPanel *m_ui; wxExtGridCtrl *m_grid; wxChoice *m_sscMod; wxExtGridCtrl *m_sscVars; AFSearchListBox *m_vtlList; StringHash m_vtlMap; public: RemapDialog( wxWindow *parent, const wxString &title, UIEditorPanel *ui ) : wxDialog( parent, wxID_ANY, title, wxDefaultPosition, wxScaleSize(610, 550), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER ), m_ui( ui ) { wxNotebook *notebook = new wxNotebook( this, wxID_ANY ); m_grid = new wxExtGridCtrl( notebook, wxID_ANY ); m_grid->CreateGrid( 10, 2 ); m_grid->SetColLabelValue( 0, "Old name" ); m_grid->SetColLabelValue( 1, "New name" ); m_grid->SetColSize( 0, 250 ); m_grid->SetColSize( 1, 250 ); notebook->AddPage( m_grid, "Name Mapping" ); wxPanel *panel_ssc = new wxPanel( notebook, wxID_ANY ); m_sscMod = new wxChoice( panel_ssc, ID_SSC_MOD ); int idx=0; while (const ssc_entry_t p_entry = ::ssc_module_entry(idx++)) m_sscMod->Append( ::ssc_entry_name(p_entry) ); m_sscVars = new wxExtGridCtrl( panel_ssc, wxID_ANY ); m_sscVars->CreateGrid( 1, 1); wxBoxSizer *sizer_ssc = new wxBoxSizer( wxVERTICAL ); sizer_ssc->Add( m_sscMod, 0, wxALL|wxEXPAND, 3 ); sizer_ssc->Add( m_sscVars, 1, wxALL|wxEXPAND, 0 ); panel_ssc->SetSizer( sizer_ssc ); notebook->AddPage( panel_ssc, "SSC Modules" ); wxBusyInfo info("loading vtl maps..."); m_vtlList = new AFSearchListBox( notebook, wxID_ANY ); wxArrayString files; wxDir::GetAllFiles( SamApp::GetRuntimePath() + "/vtl", &files, "*.csv" ); for( size_t i=0;i<files.size();i++) { wxCSVData csv; csv.ReadFile( files[i] ); for( size_t j=0;j<csv.NumRows();j++ ) m_vtlMap[ csv(j,0) ] = csv(j,1); } files.Clear(); for( StringHash::iterator it = m_vtlMap.begin(); it != m_vtlMap.end(); ++it ) { files.Add( it->first + " --> " + it->second ); } m_vtlList->Append( files ); notebook->AddPage( m_vtlList, "VTL" ); wxBoxSizer *sizer_buttons = new wxBoxSizer( wxHORIZONTAL ); sizer_buttons->Add( new wxButton( this, wxID_OPEN, "Read" ), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->Add( new wxButton( this, wxID_SAVE, "Write" ), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->Add( new wxButton( this, wxID_REFRESH, "Reload" ), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->Add( new wxButton( this, ID_APPLY_VTL, "Apply VTL"), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->Add( new wxButton( this, ID_APPLY_LAST_DOT, "Apply last dot"), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->AddStretchSpacer(); sizer_buttons->Add( new wxButton( this, wxID_APPLY, "Apply changes" ), 0, wxALL|wxEXPAND, 2 ); sizer_buttons->Add( new wxButton( this, wxID_CLOSE, "Close" ), 0, wxALL|wxEXPAND, 2 ); wxBoxSizer *sizer_main = new wxBoxSizer( wxVERTICAL ); sizer_main->Add( notebook, 1, wxALL|wxEXPAND, 0 ); sizer_main->Add( sizer_buttons, 0, wxALL|wxEXPAND, 2 ); SetSizer( sizer_main ); LoadVariables(); } void LoadVariables( ) { wxArrayString list = m_ui->GetVars()->ListAll(); m_grid->ClearGrid(); m_grid->ResizeGrid( list.size(), 2 ); for( size_t i=0;i<list.size();i++ ) { m_grid->SetCellValue( i, 0, list[i] ); m_grid->SetCellBackgroundColour( i, 1, *wxWHITE ); } } void LoadSSCTable() { wxString cm_name = m_sscMod->GetStringSelection(); ssc_module_t p_mod = ::ssc_module_create( (const char*)cm_name.c_str() ); if ( p_mod == 0 ) { wxMessageBox("Could not create a module of type: " + cm_name ); return; } std::vector<wxArrayString> vartab; int idx=0; while( const ssc_info_t p_inf = ssc_module_var_info( p_mod, idx++ ) ) { int var_type = ssc_info_var_type( p_inf ); // SSC_INPUT, SSC_OUTPUT, SSC_INOUT int data_type = ssc_info_data_type( p_inf ); // SSC_STRING, SSC_NUMBER, SSC_ARRAY, SSC_MATRIX wxArrayString row; switch( var_type ) { case SSC_INPUT: row.Add("SSC_INPUT"); break; case SSC_OUTPUT: row.Add("SSC_OUTPUT"); break; case SSC_INOUT: row.Add("SSC_INOUT"); break; default: row.Add("<!unknown>"); break; } switch( data_type ) { case SSC_STRING: row.Add("SSC_STRING"); break; case SSC_NUMBER: row.Add("SSC_NUMBER"); break; case SSC_ARRAY: row.Add("SSC_ARRAY"); break; case SSC_MATRIX: row.Add("SSC_MATRIX"); break; default: row.Add("<!unknown>"); break; } row.Add( ssc_info_name( p_inf ) ); row.Add( ssc_info_label( p_inf ) ); row.Add( ssc_info_units( p_inf ) ); row.Add( ssc_info_meta( p_inf ) ); row.Add( ssc_info_group( p_inf ) ); row.Add( ssc_info_required( p_inf ) ); row.Add( ssc_info_constraints( p_inf ) ); vartab.push_back(row); } int nrows = (int)vartab.size(); int ncols = 9; m_sscVars->Freeze(); m_sscVars->ResizeGrid( nrows, ncols); m_sscVars->SetColLabelValue( 0, "TYPE" ); m_sscVars->SetColLabelValue( 1, "DATA" ); m_sscVars->SetColLabelValue( 2, "NAME" ); m_sscVars->SetColLabelValue( 3, "LABEL" ); m_sscVars->SetColLabelValue( 4, "UNITS" ); m_sscVars->SetColLabelValue( 5, "META" ); m_sscVars->SetColLabelValue( 6, "GROUP" ); m_sscVars->SetColLabelValue( 7, "REQUIRE" ); m_sscVars->SetColLabelValue( 8, "CONSTRAINT" ); for (int r=0;r<nrows;r++) for (int c=0;c<ncols;c++) m_sscVars->SetCellValue( r, c, vartab[r][c] ); m_sscVars->AutoSizeColumns(false); m_sscVars->Thaw(); ::ssc_module_free( p_mod ); } void OnCommand( wxCommandEvent &evt ) { switch( evt.GetId() ) { case ID_SSC_MOD: LoadSSCTable(); break; case wxID_OPEN: { wxFileDialog dlg( this, "Read csv file", wxEmptyString, wxEmptyString, "CSV Files (*.csv)|*.csv", wxFD_OPEN ); if ( dlg.ShowModal() != wxID_OK ) return; wxCSVData csv; if ( !csv.ReadFile( dlg.GetPath() ) ) { wxMessageBox("failed to read csv file"); return; } size_t nr = csv.NumRows(); size_t nc = csv.NumCols(); if ( nr == 0 ) nr = 1; if ( nc != 2 ) nc = 2; m_grid->ResizeGrid( nr,2 ); for( size_t i=0;i<nr;i++) { m_grid->SetCellValue( i, 0, csv(i,0) ); m_grid->SetCellValue( i, 1, csv(i,1) ); } } break; case wxID_REFRESH: LoadVariables(); break; case wxID_SAVE: { wxFileDialog dlg( this, "Write csv file", wxEmptyString, wxEmptyString, "CSV Files (*.csv)|*.csv", wxFD_SAVE|wxFD_OVERWRITE_PROMPT ); if ( dlg.ShowModal() != wxID_OK ) return; wxCSVData csv; for( int i=0;i<m_grid->GetNumberRows();i++ ) { csv(i,0) = m_grid->GetCellValue( i, 0 ); csv(i,1) = m_grid->GetCellValue( i, 1 ); } if ( !csv.WriteFile( dlg.GetPath() )) wxMessageBox("failed to write csv file"); } break; case ID_APPLY_VTL: for( size_t i=0;i<(size_t)m_grid->GetNumberRows();i++) { wxString ssc = m_vtlMap[ m_grid->GetCellValue(i,0) ]; if ( !ssc.IsEmpty() ) { m_grid->SetCellValue( i, 1, ssc ); m_grid->SetCellBackgroundColour( i, 1, wxColour(255,213,226) ); } } break; case ID_APPLY_LAST_DOT: for( size_t i=0;i<(size_t)m_grid->GetNumberRows();i++) { if (m_grid->GetCellValue(i,1).IsEmpty()) { wxString ssc = m_grid->GetCellValue(i,0); if ( !ssc.IsEmpty() ) { size_t pos = ssc.find_last_of("."); if ( pos > 0 ) { ssc = ssc.Mid( pos+1); m_grid->SetCellValue( i, 1, ssc ); m_grid->SetCellBackgroundColour( i, 1, wxColour(255,213,226) ); } } } } break; case wxID_APPLY: { m_ui->GetPropertyEditor()->SetObject( 0 ); m_ui->VarInfoToForm( wxEmptyString ); m_ui->LoadVarList( ); wxUIFormData *form = m_ui->GetFormData(); VarDatabase *vars = m_ui->GetVars(); wxString result; wxString cb = m_ui->GetCallbacks(); wxString eqn = m_ui->GetEquations(); int n_cbreps = 0, n_eqnreps = 0; for( int i=0;i<m_grid->GetNumberRows();i++ ) { wxString sold = m_grid->GetCellValue(i,0); wxString snew = m_grid->GetCellValue(i,1); if ( sold.IsEmpty() || snew.IsEmpty() ) continue; result += sold + " -> " + snew; // change name of object in form and variable table if ( wxUIObject *obj = form->Find( sold ) ) { obj->SetName( snew ); result += " (form ok)"; } if ( vars->Rename( sold, snew ) ) result += " (var ok)"; n_cbreps += cb.Replace( "'" + sold + "'", "'" + snew + "'" ); n_cbreps += cb.Replace( "\"" + sold + "\"", "'" + snew + "'" ); n_cbreps += cb.Replace( "${" + sold + "}", "${" + snew + "}" ); n_eqnreps += eqn.Replace( "'" + sold + "'", "'" + snew + "'" ); n_eqnreps += eqn.Replace( "\"" + sold + "\"", "'" + snew + "'" ); n_eqnreps += eqn.Replace( "${" + sold + "}", "${" + snew + "}" ); result += "\n"; } m_ui->SetCallbacks( cb ); m_ui->SetEquations(eqn); wxShowTextMessageDialog( wxString::Format("textual replacements\n\tcallbacks: %d equations: %d\n\n", n_cbreps, n_eqnreps ) + result, "Remapping result", this ); LoadVariables(); m_ui->LoadVarList(); m_ui->GetDesigner()->Refresh(); break; } case wxID_CLOSE: if ( IsModal() ) EndModal( wxID_CANCEL ); else Close(); break; } } DECLARE_EVENT_TABLE(); }; BEGIN_EVENT_TABLE( RemapDialog, wxDialog ) EVT_BUTTON( wxID_APPLY, RemapDialog::OnCommand ) EVT_BUTTON( wxID_CLOSE, RemapDialog::OnCommand ) EVT_BUTTON( wxID_SAVE, RemapDialog::OnCommand ) EVT_BUTTON( wxID_OPEN, RemapDialog::OnCommand ) EVT_CHOICE( ID_SSC_MOD, RemapDialog::OnCommand ) EVT_BUTTON( ID_APPLY_VTL, RemapDialog::OnCommand ) EVT_BUTTON( ID_APPLY_LAST_DOT, RemapDialog::OnCommand ) EVT_BUTTON( wxID_REFRESH, RemapDialog::OnCommand ) END_EVENT_TABLE() static bool ShowTableEditor( VarInfoLookup &vi ) { wxDialog dlg( NULL, wxID_ANY, "Edit labels", wxDefaultPosition, wxScaleSize(600, 750), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER ); wxExtGridCtrl *grid = new wxExtGridCtrl( &dlg, wxID_ANY ); grid->EnableCopyPaste( true ); grid->CreateGrid( vi.size(), 4 ); grid->SetColLabelValue( 0, "Variable" ); grid->SetColLabelValue( 1, "Label" ); grid->SetColLabelValue( 2, "Units" ); grid->SetColLabelValue( 3, "Group" ); wxArrayString list = vi.ListAll(); list.Sort(); for( size_t i=0;i<list.size();i++ ) { grid->SetCellValue( i, 0, list[i] ); grid->SetCellBackgroundColour( i, 0, wxColour(230,230,230) ); grid->SetCellValue( i, 1, vi.Label( list[i] ) ); grid->SetCellValue( i, 2, vi.Units( list[i] ) ); grid->SetCellValue( i, 3, vi.Group( list[i] ) ); } grid->SetColLabelSize( wxGRID_AUTOSIZE ); grid->AutoSize(); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); sizer->Add( grid, 1, wxALL|wxEXPAND, 0 ); sizer->Add( dlg.CreateButtonSizer( wxOK|wxCANCEL ), 0, wxALL|wxEXPAND, 10 ); dlg.SetSizer( sizer ); if ( wxID_OK == dlg.ShowModal() ) { int nupd = 0; for ( int i=0;i<grid->GetNumberRows(); i++ ) { if ( VarInfo *pv = vi.Lookup( grid->GetCellValue( i, 0 ) ) ) { pv->Label = grid->GetCellValue( i, 1 ); pv->Units = grid->GetCellValue( i, 2 ); pv->Group = grid->GetCellValue( i, 3 ); nupd++; } } wxMessageBox( wxString::Format("%d variables updated", nupd) ); return true; } else return false; } enum { ID_FORM_EDITOR = wxID_HIGHEST + 231, ID_CALLBACK_EDITOR, ID_EQUATION_EDITOR, ID_FORM_LIST, ID_FORM_LIST_REFRESH, ID_FORM_ADD, ID_FORM_ADD_TEXT, ID_FORM_SAVE, ID_FORM_SAVE_ALL, ID_FORM_LOAD_ALL, ID_FORM_DELETE, ID_FORM_DELETE_TEXT, ID_FORM_SAVE_TEXT, ID_FORM_LOAD_TEXT, ID_FORM_SAVE_ALL_TEXT, ID_FORM_LOAD_ALL_TEXT, ID_VAR_REMAP, ID_VAR_SYNC, ID_VAR_ADD, ID_VAR_DELETE, ID_VAR_GROUP_MULTIPLE, ID_VAR_TABLE_EDIT, ID_VAR_LIST, ID_VAR_NAME, ID_VAR_TYPE, ID_VAR_LABEL, ID_VAR_UNITS, ID_VAR_GROUP, ID_VAR_INDEX_LABELS, ID_VAR_DEFAULT_VALUE, ID_VAR_UIOBJECT, ID_VAR_FL_HIDELABELS, ID_VAR_FL_PARAMETRIC, ID_VAR_FL_INDICATOR, ID_VAR_FL_CALCULATED, ID_VAR_FL_LIBRARY, ID_VAR_FL_CHANGEMODEL, ID_CALLBACK_FIND, ID_CALLBACK_CHECK, ID_CALLBACK_GOTO, ID_CALLBACK_HELP, ID_CALLBACK_GOTO_1, ID_CALLBACK_GOTO_100 = ID_CALLBACK_GOTO_1 + 100, ID_EQUATION_FIND, ID_EQUATION_SCAN, ID_EQUATION_HELP, ID_VAR_CHECK_ALL, ID_VAR_CHECK_NONE, ID_VAR_CHECK_SEL, ID_VAR_STORE, ID_VAR_LOAD, ID_TEXT_FIND, }; BEGIN_EVENT_TABLE( UIEditorPanel, wxPanel ) EVT_BUTTON( ID_TEXT_FIND, UIEditorPanel::OnTextFind ) EVT_LISTBOX( ID_FORM_LIST, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_FORM_LIST_REFRESH, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_FORM_ADD, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_FORM_SAVE, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_FORM_DELETE, UIEditorPanel::OnCommand ) EVT_BUTTON(ID_FORM_SAVE_ALL, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_LOAD_ALL, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_ADD_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_DELETE_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_SAVE_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_LOAD_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_SAVE_ALL_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON(ID_FORM_LOAD_ALL_TEXT, UIEditorPanel::OnCommand) EVT_BUTTON( ID_VAR_SYNC, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_REMAP, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_ADD, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_DELETE, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_GROUP_MULTIPLE, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_TABLE_EDIT, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_CHECK_ALL, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_CHECK_NONE, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_CHECK_SEL, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_STORE, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_VAR_LOAD, UIEditorPanel::OnCommand ) EVT_LISTBOX( ID_VAR_LIST, UIEditorPanel::OnCommand ) EVT_TEXT_ENTER( ID_VAR_NAME, UIEditorPanel::OnCommand ) EVT_TEXT_ENTER( ID_VAR_LABEL, UIEditorPanel::OnCommand ) EVT_TEXT_ENTER( ID_VAR_UNITS, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_CALLBACK_FIND, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_CALLBACK_CHECK, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_CALLBACK_GOTO, UIEditorPanel::OnCommand ) EVT_MENU_RANGE( ID_CALLBACK_GOTO_1, ID_CALLBACK_GOTO_100, UIEditorPanel::OnCallbackGoto ) EVT_BUTTON( ID_CALLBACK_HELP, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_EQUATION_FIND, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_EQUATION_SCAN, UIEditorPanel::OnCommand ) EVT_BUTTON( ID_EQUATION_HELP, UIEditorPanel::OnCommand ) EVT_UIFORM_SELECT( ID_FORM_EDITOR, UIEditorPanel::OnFormSelectObject ) END_EVENT_TABLE() static void fcall_technology_stub( lk::invoke_t &cxt ) { LK_DOC( "technology", "Return the current technology option name", "(void):string" ); } static void fcall_financing_stub( lk::invoke_t &cxt ) { LK_DOC( "financing", "Return the current financing option name", "(void):string" ); } static lk::fcall_t* invoke_equation_stubs() { static const lk::fcall_t vec[] = { fcall_technology_stub, fcall_financing_stub, 0 }; return (lk::fcall_t*)vec; } UIEditorPanel::UIEditorPanel( wxWindow *parent ) : wxPanel( parent ), m_exForm( &m_ipd.Variables() ) { wxBoxSizer *sz_form_tools = new wxBoxSizer( wxHORIZONTAL ); sz_form_tools->Add( new wxButton( this, ID_TEXT_FIND, "Search", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_FORM_LIST_REFRESH, "Refresh list", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); // sz_form_tools->Add(new wxButton(this, ID_FORM_ADD, "Add...", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); sz_form_tools->Add(new wxButton(this, ID_FORM_ADD_TEXT, "Add...", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add( new wxButton( this, ID_FORM_SAVE, "Save", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add(new wxButton(this, ID_FORM_SAVE_TEXT, "Save", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add( new wxButton( this, ID_FORM_DELETE, "Delete", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_FORM_DELETE_TEXT, "Delete", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); // sz_form_tools->Add(new wxButton(this, ID_FORM_SAVE_ALL, "Save all", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add(new wxButton(this, ID_FORM_LOAD_ALL, "Load all", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add(new wxButton(this, ID_FORM_SAVE_TEXT, "Save text", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add(new wxButton(this, ID_FORM_LOAD_TEXT, "Load text", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add(new wxButton(this, ID_FORM_SAVE_ALL_TEXT, "Save all text", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); // sz_form_tools->Add(new wxButton(this, ID_FORM_LOAD_ALL_TEXT, "Load all text", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL | wxEXPAND, 2); sz_form_tools->AddStretchSpacer(); sz_form_tools->Add( new wxButton( this, ID_VAR_REMAP, "Remap", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_SYNC, "Sync", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_ADD, "Add", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_DELETE, "Delete", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_GROUP_MULTIPLE, "Set group...", wxDefaultPosition,wxDefaultSize, wxBU_EXACTFIT),0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_TABLE_EDIT, "Table editor...", wxDefaultPosition,wxDefaultSize, wxBU_EXACTFIT),0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_CHECK_ALL, "Chk all", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_CHECK_NONE, "Chk none", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_CHECK_SEL, "Chk sel", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_STORE, "Store", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); sz_form_tools->Add( new wxButton( this, ID_VAR_LOAD, "Load", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), 0, wxALL|wxEXPAND, 2 ); m_uiPropEditor = new wxUIPropertyEditor( this, wxID_ANY ); m_formList = new wxListBox( this, ID_FORM_LIST, wxDefaultPosition, wxScaleSize(300, 300), 0, 0, wxLB_SINGLE|wxBORDER_NONE ); wxBoxSizer *sz_form_left = new wxBoxSizer( wxVERTICAL ); sz_form_left->Add( new wxStaticText( this, wxID_ANY, "UI Forms" ), 0, wxALL, 4 ); sz_form_left->Add( m_formList, 1, wxALL|wxEXPAND, 2 ); sz_form_left->Add( new wxStaticText( this, wxID_ANY, "Object Properties" ), 0, wxALL, 4 ); sz_form_left->Add( m_uiPropEditor, 1, wxALL|wxEXPAND, 2 ); m_varList = new wxCheckListBox( this, ID_VAR_LIST, wxDefaultPosition, wxDefaultSize, 0, 0, wxLB_SINGLE|wxBORDER_NONE ); m_varName = new wxExtTextCtrl( this, ID_VAR_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); m_varType = new wxChoice( this, ID_VAR_TYPE, wxDefaultPosition, wxDefaultSize, 7, vv_strtypes ); m_varLabel = new wxExtTextCtrl( this, ID_VAR_LABEL, wxEmptyString ); m_varUnits = new wxExtTextCtrl( this, ID_VAR_UNITS, wxEmptyString ); m_varGroup = new wxExtTextCtrl( this, ID_VAR_GROUP, wxEmptyString ); m_varIndexLabels = new wxExtTextCtrl( this, ID_VAR_INDEX_LABELS, wxEmptyString ); m_varDefaultValue = new wxExtTextCtrl( this, ID_VAR_DEFAULT_VALUE, wxEmptyString ); m_varFlagHideLabels = new wxCheckBox( this, ID_VAR_FL_HIDELABELS, "Hide labels?" ); m_varFlagParametric = new wxCheckBox( this, ID_VAR_FL_PARAMETRIC, "Parametric?" ); m_varFlagIndicator = new wxCheckBox( this, ID_VAR_FL_INDICATOR, "Indicator?" ); m_varFlagCalculated = new wxCheckBox( this, ID_VAR_FL_CALCULATED, "Calculated?" ); m_varFlagLibrary = new wxCheckBox(this, ID_VAR_FL_LIBRARY, "Library?"); m_varFlagChangeModel = new wxCheckBox(this, ID_VAR_FL_CHANGEMODEL, "Change Model?"); std::vector<wxUIObject*> ctrls = wxUIObjectTypeProvider::GetTypes(); wxArrayString UIObjs; for (size_t i = 0; i<ctrls.size(); i++) UIObjs.Add(ctrls[i]->GetTypeName()); UIObjs.Add(VUIOBJ_NONE); // default editor associated with variable m_varUIObject = new wxChoice(this, ID_VAR_UIOBJECT, wxDefaultPosition, wxDefaultSize, UIObjs); wxGridBagSizer *sz_var_fields = new wxGridBagSizer(1,1); sz_var_fields->SetFlexibleDirection( wxHORIZONTAL ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Name:" ), wxGBPosition(0,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varName, wxGBPosition(0, 1), wxGBSpan(1,2), wxALL|wxEXPAND, 2 ); sz_var_fields->Add( m_varType, wxGBPosition(0, 3), wxDefaultSpan, wxALL|wxEXPAND, 2 ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Label:" ), wxGBPosition(1,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varLabel, wxGBPosition(1, 1), wxGBSpan(1,3), wxALL|wxEXPAND, 2 ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Units:" ), wxGBPosition(2,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varUnits, wxGBPosition(2, 1), wxGBSpan(1,3), wxALL|wxEXPAND, 2 ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Group:" ), wxGBPosition(3,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varGroup, wxGBPosition(3, 1), wxGBSpan(1,3), wxALL|wxEXPAND, 2 ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Index Labels:" ), wxGBPosition(4,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varIndexLabels, wxGBPosition(4, 1), wxGBSpan(1,3), wxALL|wxEXPAND, 2 ); sz_var_fields->Add( new wxStaticText( this, wxID_ANY, "Default Value:" ), wxGBPosition(5,0), wxDefaultSpan, wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varDefaultValue, wxGBPosition(5, 1), wxGBSpan(1,3), wxALL|wxEXPAND, 2 ); sz_var_fields->Add(new wxStaticText(this, wxID_ANY, "UIObject:"), wxGBPosition(6, 0), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 3); sz_var_fields->Add(m_varUIObject, wxGBPosition(6, 1), wxGBSpan(1, 3), wxALL | wxEXPAND, 2); sz_var_fields->Add(m_varFlagHideLabels, wxGBPosition(7, 0), wxGBSpan(1, 1), wxALL | wxALIGN_CENTER_VERTICAL, 3); sz_var_fields->Add( m_varFlagParametric, wxGBPosition(7,1), wxGBSpan(1,1), wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varFlagIndicator, wxGBPosition(8,0), wxGBSpan(1,1), wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varFlagCalculated, wxGBPosition(8,1), wxGBSpan(1,1), wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add( m_varFlagLibrary, wxGBPosition(9,1), wxGBSpan(1,1), wxALL|wxALIGN_CENTER_VERTICAL, 3 ); sz_var_fields->Add(m_varFlagChangeModel, wxGBPosition(9, 0), wxGBSpan(1, 1), wxALL | wxALIGN_CENTER_VERTICAL, 3); sz_var_fields->AddGrowableCol( 1 ); wxBoxSizer *sz_var_main = new wxBoxSizer( wxVERTICAL ); sz_var_main->Add( new wxStaticText( this, wxID_ANY, "Variables" ), 0, wxALL, 4 ); sz_var_main->Add( m_varList, 1, wxALL|wxEXPAND, 2 ); sz_var_main->Add( sz_var_fields,1, wxALL|wxEXPAND, 0 ); wxSplitterWindow *center_split = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); m_uiFormEditor = new wxUIFormDesigner( center_split, ID_FORM_EDITOR ); m_uiFormEditor->SetBackgroundColour( wxColour(120,120,120) ); m_uiFormEditor->SetCopyBuffer( &m_uiCopyBuffer ); wxPanel *scripts_panel = new wxPanel( center_split ); wxBoxSizer *sz_callback_tools = new wxBoxSizer( wxHORIZONTAL ); sz_callback_tools->Add( new wxStaticText( scripts_panel, wxID_ANY, "Callbacks"), 0, wxALL|wxALIGN_CENTER_VERTICAL, 2 ); sz_callback_tools->AddSpacer(5); sz_callback_tools->Add( new wxButton( scripts_panel, ID_CALLBACK_FIND, "Find..." ), 0, wxALL|wxEXPAND, 2 ); sz_callback_tools->Add( new wxButton( scripts_panel, ID_CALLBACK_CHECK, "Check code" ), 0, wxALL|wxEXPAND, 2 ); sz_callback_tools->Add( new wxButton( scripts_panel, ID_CALLBACK_GOTO, "Goto..." ), 0, wxALL|wxEXPAND, 2 ); sz_callback_tools->Add( new wxButton( scripts_panel, ID_CALLBACK_HELP, "Help" ), 0, wxALL|wxEXPAND, 2 ); sz_callback_tools->AddStretchSpacer(); m_callbackScript = new wxLKScriptCtrl( scripts_panel, ID_CALLBACK_EDITOR ); // by default registers all LK stdlib functions m_callbackScript->RegisterLibrary( invoke_general_funcs(), "Callback UI Functions" ); m_callbackScript->RegisterLibrary( invoke_casecallback_funcs(), "Callback UI Functions" ); m_callbackScript->RegisterLibrary( invoke_uicallback_funcs(), "Callback UI Functions" ); m_callbackScript->RegisterLibrary( invoke_ssc_funcs(), "SSC Functions" ); wxBoxSizer *sz_scripts_left = new wxBoxSizer( wxVERTICAL ); sz_scripts_left->Add( sz_callback_tools, 0, wxALL|wxEXPAND, 2 ); sz_scripts_left->Add( m_callbackScript, 1, wxALL|wxEXPAND, 0 ); wxBoxSizer *sz_equation_tools = new wxBoxSizer( wxHORIZONTAL ); sz_equation_tools->Add( new wxStaticText( scripts_panel, wxID_ANY, "Equations"), 0, wxALL|wxALIGN_CENTER_VERTICAL, 2 ); sz_equation_tools->AddSpacer(5); sz_equation_tools->Add( new wxButton( scripts_panel, ID_EQUATION_FIND, "Find..." ), 0, wxALL|wxEXPAND, 2 ); sz_equation_tools->Add( new wxButton( scripts_panel, ID_EQUATION_SCAN, "Scan" ), 0, wxALL|wxEXPAND, 2 ); sz_equation_tools->Add( new wxButton( scripts_panel, ID_EQUATION_HELP, "Help" ), 0, wxALL|wxEXPAND, 2 ); sz_equation_tools->AddStretchSpacer(); m_equationScript = new wxLKScriptCtrl( scripts_panel, ID_EQUATION_EDITOR, wxDefaultPosition, wxDefaultSize, wxLK_STDLIB_BASIC | wxLK_STDLIB_SYSIO | wxLK_STDLIB_STRING | wxLK_STDLIB_MATH | wxLK_STDLIB_WXUI ); m_equationScript->RegisterLibrary( invoke_equation_stubs(), "Case Information", 0 ); m_equationScript->RegisterLibrary( invoke_ssc_funcs(), "SSC Functions", 0 ); m_equationScript->RegisterLibrary( invoke_equation_funcs(), "Additional Equation Functions", 0 ); wxBoxSizer *sz_scripts_right = new wxBoxSizer( wxVERTICAL ); sz_scripts_right->Add( sz_equation_tools, 0, wxALL|wxEXPAND, 2 ); sz_scripts_right->Add( m_equationScript, 1, wxALL|wxEXPAND, 0 ); wxBoxSizer *sz_scripts_main = new wxBoxSizer( wxHORIZONTAL ); sz_scripts_main->Add( sz_scripts_left, 1, wxALL|wxEXPAND, 0 ); sz_scripts_main->Add( sz_scripts_right, 1, wxALL|wxEXPAND, 0 ); scripts_panel->SetSizer( sz_scripts_main ); center_split->SplitHorizontally( m_uiFormEditor, scripts_panel, (int)(-400*wxGetScreenHDScale()) ); center_split->SetSashGravity( 1.0 ); center_split->SetMinimumPaneSize( 20 ); wxBoxSizer *sz_form_main = new wxBoxSizer( wxHORIZONTAL ); sz_form_main->Add( sz_form_left, 0, wxALL|wxEXPAND, 0 ); sz_form_main->Add( center_split, 1, wxALL|wxEXPAND, 4 ); sz_form_main->Add( sz_var_main, 0, wxALL|wxEXPAND, 0 ); m_uiFormEditor->SetPropertyEditor( m_uiPropEditor ); m_uiFormEditor->SetFormData( &m_exForm ); wxBoxSizer *sz_form_top = new wxBoxSizer( wxVERTICAL ); sz_form_top->Add( sz_form_tools, 0, wxALL|wxEXPAND, 2 ); sz_form_top->Add( sz_form_main, 1, wxALL|wxEXPAND, 0 ); this->SetSizer( sz_form_top ); LoadFormList(); LoadVarList(); VarInfoToForm( wxEmptyString ); } void UIEditorPanel::LoadFormList( const wxString &sel ) { wxArrayString list; wxDir dir( SamApp::GetRuntimePath() + "/ui" ); if ( dir.IsOpened() ) { wxString file; #ifdef UI_BINARY bool has_more = dir.GetFirst( &file, "*.ui", wxDIR_FILES ); #else bool has_more = dir.GetFirst(&file, "*.txt", wxDIR_FILES); #endif while( has_more ) { wxFileName fn( file ); list.Add( fn.GetName() ); has_more = dir.GetNext( &file ); } } list.Sort(); m_formList->Freeze(); m_formList->Clear(); m_formList->Append( list ); m_formList->Thaw(); if ( !sel.IsEmpty() ) m_formList->SetStringSelection( sel ); } void UIEditorPanel::OnCallbackGoto( wxCommandEvent &evt ) { int idx = evt.GetId() - ID_CALLBACK_GOTO_1; if ( idx >= 0 && idx < (int)m_callbackGotoList.Count() ) { int pos = m_callbackScript->FindText( 0, m_callbackScript->GetLength(), m_callbackGotoList[idx], 0 ); if ( pos >= 0 ) { m_callbackScript->SetSelection( pos, pos+m_callbackGotoList[idx].Len() ); } else { wxString text = "\n" + m_callbackGotoList[idx] + "\n\tmsgbox('test');\n};\n"; m_callbackScript->AppendText( text ); m_callbackScript->SetSelection( m_callbackScript->GetLength()-text.Len()-1, text.Len() ); } m_callbackScript->EnsureCaretVisible(); } } ExFormData::ExFormData( VarDatabase *vdb ) : m_vdb(vdb) { } ExFormData::~ExFormData() { m_vdb = 0; } bool ExFormData::GetMetaData( const wxString &name, wxString *label, wxString *units, wxColour *colour ) { if ( !m_vdb ) return false; if ( VarInfo *vv = m_vdb->Lookup( name ) ) { if (vv->Flags & VF_HIDE_LABELS) return false; *label = vv->Label; *units = vv->Units; if ( vv->Flags & VF_CALCULATED || vv->Flags & VF_INDICATOR ) *colour = *wxBLUE; else *colour = *wxBLACK; return true; } return false; } #define SEARCH( TT, MESSG ) if ( (TT).Lower().Find( text ) >= 0 ) tc->AppendText( MESSG + wxString("\n") ) void UIEditorPanel::OnTextFind( wxCommandEvent & ) { wxString text = wxGetTextFromUser( "Enter text to search for:", "Query", wxEmptyString, this ); if ( text.IsEmpty() ) return; wxDialog *dialog = new wxDialog( this, wxID_ANY, "Searching for: '" + text + "'", wxDefaultPosition, wxScaleSize( 550, 400 ), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER ); wxTextCtrl *tc = new wxTextCtrl( dialog, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE ); wxGauge *gau = new wxGauge( dialog, wxID_ANY, 1 ); wxSizer *sz = new wxBoxSizer( wxVERTICAL ); sz->Add( gau, 0, wxALL|wxEXPAND, 0 ); sz->Add( tc, 1, wxALL|wxEXPAND, 0 ); sz->Add( dialog->CreateButtonSizer( wxOK ), 0, wxALL|wxEXPAND, 5 ); dialog->SetSizer( sz ); dialog->CenterOnParent(); dialog->Show(); wxSafeYield( 0, true ); // scan through all forms, variables, everything searching for this text text.MakeLower(); wxArrayString files; wxString ui_path = SamApp::GetRuntimePath() + "/ui/"; #ifdef UI_BINARY wxDir::GetAllFiles(ui_path, &files, "*.ui"); #else wxDir::GetAllFiles(ui_path, &files, "*.txt"); #endif InputPageData ipd; gau->SetRange( files.size() ); for( size_t ii=0;ii<files.size();ii++ ) { gau->SetValue( ii ); ipd.Clear(); wxFFileInputStream is( files[ii], "r"); bool bff = is.IsOk(); #ifdef UI_BINARY bool bread = ipd.Read(is, ui_path); #else bool bread = ipd.Read_text(is, ui_path); #endif if (bff && bread) { wxFileName ff(files[ii]); wxString name(ff.GetName()); ipd.Form().SetName(name); // form and associated data loaded, now search everything we can think of SEARCH(name, "form: " + name); wxUIFormData& form = ipd.Form(); size_t n; wxUIObject** objs = form.GetObjects(&n); for (size_t i = 0; i < n; i++) { SEARCH(objs[i]->GetTypeName(), "form object: " + name + ".object{" + objs[i]->GetName() + "} = " + objs[i]->GetTypeName()); SEARCH(objs[i]->GetName(), "form object: " + name + ".object{" + objs[i]->GetName() + "}"); wxArrayString props = objs[i]->Properties(); for (size_t k = 0; k < props.size(); k++) { wxString pstr(objs[i]->Property(props[k]).AsString()); wxString prefix(name + ".object{" + objs[i]->GetName() + "}." + props[k]); SEARCH(props[k], prefix); SEARCH(pstr, prefix + ": " + pstr); } } VarDatabase& vdb = ipd.Variables(); for (VarDatabase::iterator it = vdb.begin(); it != vdb.end(); ++it) { wxString prefix(name + ".variable{" + it->first + "}"); SEARCH(it->first, prefix); SEARCH(it->second->Label, prefix + ".label: " + it->second->Label); SEARCH(it->second->Units, prefix + ".units: " + it->second->Units); SEARCH(it->second->Group, prefix + ".group: " + it->second->Group); SEARCH(it->second->DefaultValue.AsString(), prefix + ".default: " + it->second->DefaultValue.AsString()); } wxArrayString lines = wxStringTokenize(ipd.EqnScript(), "\n", wxTOKEN_RET_EMPTY_ALL); for (size_t i = 0; i < lines.size(); i++) SEARCH(lines[i], name + wxString::Format(".script[%d]: ", (int)(i + 1)) + lines[i]); lines = wxStringTokenize(ipd.CbScript(), "\n", wxTOKEN_RET_EMPTY_ALL); for (size_t i = 0; i < lines.size(); i++) SEARCH(lines[i], name + wxString::Format(".callback[%d]: ", (int)(i + 1)) + lines[i]); } else // form read failed tc->AppendText("Error reading " + files[ii]); } gau->SetValue(0); } void UIEditorPanel::OnCommand( wxCommandEvent &evt ) { switch( evt.GetId() ) { case ID_FORM_LIST: if ( !m_formName.IsEmpty() ) { SyncFormUIToDataBeforeWriting(); #ifdef UI_BINARY Write( m_formName ); #else Write_text(m_formName); #endif } #ifdef UI_BINARY if (!Load( m_formList->GetStringSelection() )) #else if (!Load_text(m_formList->GetStringSelection())) #endif wxMessageBox("error loading form: " + m_formList->GetStringSelection(), "notice", wxOK, this ); break; case ID_FORM_LIST_REFRESH: LoadFormList(); break; case ID_FORM_ADD: { wxString name = wxGetTextFromUser( "Enter new form name:", "query", wxEmptyString, this ); if ( name.IsEmpty() ) return; if ( wxFileExists(SamApp::GetRuntimePath() + "/ui/" + name + ".ui" ) ) { wxMessageBox("that form already exists.", "notice", wxOK, this); return; } m_uiFormEditor->SetFormData( 0 ) ; m_exForm.DeleteAll(); m_ipd.Clear(); m_callbackScript->SetText( wxEmptyString ); m_equationScript->SetText( wxEmptyString ); Write( name ); if ( !Load( name ) ) wxMessageBox("error loading newly created form: " + name, "notice", wxOK, this ); LoadFormList( name ); VarInfoToForm( wxEmptyString ); } break; case ID_FORM_DELETE: { wxString form = m_formList->GetStringSelection(); if ( wxYES == wxMessageBox( "really delete .ui for: " + form + " ? cannot undo!", "query", wxYES_NO, this ) ) { wxString ff = SamApp::GetRuntimePath() + "/ui/" + form + ".ui"; if ( wxFileExists( ff ) ) wxRemoveFile( ff ); m_formName.Clear(); m_exForm.DeleteAll(); m_ipd.Clear(); m_uiFormEditor->SetFormData( &m_exForm ); m_uiFormEditor->Refresh(); m_callbackScript->Clear(); m_equationScript->Clear(); LoadFormList(); LoadVarList(); VarInfoToForm( wxEmptyString ); } } break; case ID_FORM_SAVE: { wxBusyInfo info( "Saving form and variable data: " + m_formName ); wxYield(); wxMilliSleep( 300 ); SyncFormUIToDataBeforeWriting(); if (!Write( m_formName )) wxMessageBox("error writing form: " + m_formName, "notice", wxOK, this ); } break; case ID_FORM_SAVE_ALL: { // std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); size_t forms_saved = 0; wxDir dir(SamApp::GetRuntimePath() + "/ui"); if (dir.IsOpened()) { wxString file; bool has_more = dir.GetFirst(&file, "*.txt", wxDIR_FILES); while (has_more) { wxString form_name = wxFileName(file).GetName(); wxLogStatus("saving UI .txt as binary: " + form_name); if (!Write(form_name)) wxLogStatus(" --> error saving .txt as binary for " + form_name); else forms_saved++; has_more = dir.GetNext(&file); } } dir.Close(); // auto end = std::chrono::system_clock::now(); // auto diff = std::chrono::duration_cast <std::chrono::milliseconds> (end - start).count(); // wxString ui_time(std::to_string(diff) + "ms "); // wxLogStatus(wxString::Format(" %d text ui forms saved as binary in %s", (int)forms_saved, (const char*)ui_time.c_str())); } break; case ID_FORM_LOAD_ALL: { // std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); size_t forms_loaded = 0; wxDir dir(SamApp::GetRuntimePath() + "/ui"); if (dir.IsOpened()) { wxString file; bool has_more = dir.GetFirst(&file, "*.ui", wxDIR_FILES); while (has_more) { wxString form_name = wxFileName(file).GetName(); wxLogStatus("loading .ui as binary: " + form_name); if (!Load(form_name)) wxLogStatus(" --> error loading as binary for " + form_name); else forms_loaded++; has_more = dir.GetNext(&file); } } dir.Close(); // auto end = std::chrono::system_clock::now(); // auto diff = std::chrono::duration_cast <std::chrono::milliseconds> (end - start).count(); // wxString ui_time(std::to_string(diff) + "ms "); // wxLogStatus(wxString::Format(" %d forms loaded as binary in %s", (int)forms_loaded, (const char*)ui_time.c_str())); } break; case ID_FORM_ADD_TEXT: { wxString name = wxGetTextFromUser("Enter new form name:", "query", wxEmptyString, this); if (name.IsEmpty()) return; if (wxFileExists(SamApp::GetRuntimePath() + "/ui/" + name + ".txt")) { wxMessageBox("that form already exists.", "notice", wxOK, this); return; } m_uiFormEditor->SetFormData(0); m_exForm.DeleteAll(); m_ipd.Clear(); m_callbackScript->SetText(wxEmptyString); m_equationScript->SetText(wxEmptyString); Write_text(name); if (!Load_text(name)) wxMessageBox("error loading newly created form: " + name, "notice", wxOK, this); LoadFormList(name); VarInfoToForm(wxEmptyString); } break; case ID_FORM_DELETE_TEXT: { wxString form = m_formList->GetStringSelection(); if (wxYES == wxMessageBox("really delete .txt for: " + form + " ? cannot undo!", "query", wxYES_NO, this)) { wxString ff = SamApp::GetRuntimePath() + "/ui/" + form + ".txt"; if (wxFileExists(ff)) wxRemoveFile(ff); m_formName.Clear(); m_exForm.DeleteAll(); m_ipd.Clear(); m_uiFormEditor->SetFormData(&m_exForm); m_uiFormEditor->Refresh(); m_callbackScript->Clear(); m_equationScript->Clear(); LoadFormList(); LoadVarList(); VarInfoToForm(wxEmptyString); } } break; case ID_FORM_SAVE_TEXT: { wxBusyInfo info("Saving form and variable data: " + m_formName); wxYield(); wxMilliSleep(300); SyncFormUIToDataBeforeWriting(); if (!Write_text(m_formName)) wxMessageBox("error writing form: " + m_formName, "notice", wxOK, this); } break; case ID_FORM_LOAD_TEXT: { if (m_formName.IsEmpty()) m_formName = m_formList->GetStringSelection(); wxBusyInfo info("Loading form and variable data: " + m_formName); wxYield(); wxMilliSleep(300); if (!Load_text(m_formList->GetStringSelection())) wxMessageBox("error loading form: " + m_formName, "notice", wxOK, this); } break; case ID_FORM_SAVE_ALL_TEXT: { // std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); size_t forms_saved = 0; wxDir dir(SamApp::GetRuntimePath() + "/ui"); if (dir.IsOpened()) { wxString file; bool has_more = dir.GetFirst(&file, "*.ui", wxDIR_FILES); while (has_more) { wxString form_name = wxFileName(file).GetName(); if (!Load(form_name)) { wxLogStatus(" --> error loading .ui for " + wxFileName(file).GetName()); continue; } SyncFormUIToDataBeforeWriting(); wxLogStatus("saving .ui as text: " + form_name); if (!Write_text(form_name)) wxLogStatus(" --> error saving .ui as text for " + form_name); else forms_saved++; has_more = dir.GetNext(&file); } } dir.Close(); // auto end = std::chrono::system_clock::now(); // auto diff = std::chrono::duration_cast <std::chrono::milliseconds> (end - start).count(); // wxString ui_time(std::to_string(diff) + "ms "); // wxLogStatus(wxString::Format(" %d binary ui forms saved as text in %s" , (int) forms_saved, (const char*)ui_time.c_str())); } break; case ID_FORM_LOAD_ALL_TEXT: { // std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); size_t forms_loaded = 0; wxDir dir(SamApp::GetRuntimePath() + "/ui"); if (dir.IsOpened()) { wxString file; bool has_more = dir.GetFirst(&file, "*.txt", wxDIR_FILES); while (has_more) { wxString form_name = wxFileName(file).GetName(); wxLogStatus("loading .txt as text: " + form_name); if (!Load_text(form_name)) wxLogStatus(" --> error loading as text for " + form_name); else forms_loaded++; has_more = dir.GetNext(&file); } } dir.Close(); // auto end = std::chrono::system_clock::now(); // auto diff = std::chrono::duration_cast <std::chrono::milliseconds> (end - start).count(); // wxString ui_time(std::to_string(diff) + "ms "); // wxLogStatus(wxString::Format(" %d forms loaded as text in %s", (int)forms_loaded, (const char*)ui_time.c_str())); } break; case ID_VAR_REMAP: { RemapDialog *rdlg = new RemapDialog( this, "Remap variable names", this ); rdlg->Show(); } break; case ID_VAR_SYNC: { std::vector<wxUIObject*> objects = m_exForm.GetObjects(); for( size_t i=0;i<objects.size();i++ ) { wxString type = objects[i]->GetTypeName(); wxString name = objects[i]->GetName(); VarInfo *vi = NULL; if ( m_ipd.Variables().Lookup( name ) == 0 ) { if ( type == "Numeric" ) vi = m_ipd.Variables().Create( name, VV_NUMBER ); else if ( type == "Choice" ) vi = m_ipd.Variables().Create(name, VV_NUMBER); else if ( type == "ListBox" ) vi = m_ipd.Variables().Create(name, VV_STRING); else if ( type == "RadioChoice" ) vi = m_ipd.Variables().Create(name, VV_NUMBER); else if (type == "TextEntry") vi = m_ipd.Variables().Create(name, VV_STRING); else if (type == "MultilineText") vi = m_ipd.Variables().Create(name, VV_STRING); else if (type == "Slider") vi = m_ipd.Variables().Create(name, VV_NUMBER); else if ( type == "CheckBox" ) vi = m_ipd.Variables().Create(name, VV_NUMBER); else if ( type == "RadioChoice" ) vi = m_ipd.Variables().Create(name, VV_NUMBER); else if ( type == "Slider" ) vi = m_ipd.Variables().Create(name, VV_NUMBER); else if ( type == "SchedNumeric" ) vi = m_ipd.Variables().Create(name, VV_ARRAY); else if ( type == "TOUSchedule" ) vi = m_ipd.Variables().Create(name, VV_STRING); else if ( type == "PTLayout" ) vi = m_ipd.Variables().Create(name, VV_TABLE); else if ( type == "MaterialProperties" ) vi = m_ipd.Variables().Create(name, VV_MATRIX); else if ( type == "TroughLoop" ) vi = m_ipd.Variables().Create(name, VV_ARRAY); else if ( type == "MonthlyFactor" ) vi = m_ipd.Variables().Create(name, VV_ARRAY); else if ( type == "SearchListBox" ) vi = m_ipd.Variables().Create(name, VV_STRING); else if (type == "DataArray") vi = m_ipd.Variables().Create(name, VV_ARRAY); else if (type == "DataLifetimeArray") vi = m_ipd.Variables().Create(name, VV_ARRAY); else if (type == "StringArray") vi = m_ipd.Variables().Create(name, VV_STRING); else if (type == "DataMatrix") vi = m_ipd.Variables().Create(name, VV_MATRIX); else if (type == "DataLifetimeMatrix") vi = m_ipd.Variables().Create(name, VV_MATRIX); else if (type == "ShadingFactors") vi = m_ipd.Variables().Create(name, VV_TABLE); else if ( type == "ValueMatrix" ) vi = m_ipd.Variables().Create(name, VV_MATRIX); else if ( type == "MonthByHourFactors" ) vi = m_ipd.Variables().Create(name, VV_MATRIX); else if ( type == "LossAdjustment" ) vi = m_ipd.Variables().Create(name, VV_TABLE); else if (type == "DiurnalPeriod") vi = m_ipd.Variables().Create(name, VV_MATRIX); // extend this list in the future for additional controls if (vi) vi->UIObject = type; // set UIObject field for subsequent editing } // else // { // for updating existing varible UIObjects - one time - performed 5/6/14 and checked in SAMnt rev 383 // vi = m_ipd.Variables().Lookup(name); // if (vi) vi->UIObject = type; // } } LoadVarList( m_varList->GetStringSelection() ); } break; case ID_VAR_ADD: { wxString name = wxGetTextFromUser( "Enter new variable name", "query", wxEmptyString, this); if ( !name.IsEmpty() ) { VarInfo *vv = m_ipd.Variables().Lookup( name ); if ( vv ) FormToVarInfo( ); else m_ipd.Variables().Create( name, VV_INVALID ); LoadVarList( name ); VarInfoToForm( name ); } } break; case ID_VAR_TABLE_EDIT: if ( ShowTableEditor( m_ipd.Variables() ) ) VarInfoToForm( m_curVarName ); break; case ID_VAR_GROUP_MULTIPLE: { wxArrayString checked; for( size_t i=0;i<m_varList->GetCount();i++ ) if ( m_varList->IsChecked( i ) ) checked.Add( m_varList->GetString( i ) ); if (checked.size() == 0) { wxMessageBox( "No variables checked for multiple group edits"); return; } wxString group = wxGetTextFromUser("Enter group value:", "Change multiple variables", m_ipd.Variables().Group(m_varList->GetStringSelection())); if ( group.IsEmpty() && wxNO == wxMessageBox("Erase group field from checked variables?", "Query", wxYES_NO) ) return; for( size_t i=0;i<checked.size();i++ ) if ( VarInfo *vv=m_ipd.Variables().Lookup( checked[i] ) ) vv->Group = group; if ( checked.Index( m_curVarName ) != wxNOT_FOUND ) VarInfoToForm( m_curVarName ); } break; case ID_VAR_DELETE: { // delete selected item m_ipd.Variables().Delete( m_varList->GetStringSelection() ); m_varList->Delete( m_varList->GetSelection() ); // delete any checked items wxArrayString checked; for( size_t i=0;i<m_varList->GetCount();i++ ) if ( m_varList->IsChecked( i ) ) checked.Add( m_varList->GetString( i ) ); for( size_t i=0;i<checked.size();i++ ) { m_varList->Delete( m_varList->FindString( checked[i] ) ); m_ipd.Variables().Delete( checked[i] ); } VarInfoToForm( wxEmptyString ); } break; case ID_VAR_LIST: FormToVarInfo( ); // save the current var VarInfoToForm( m_varList->GetStringSelection() ); // switch to the new var break; case ID_VAR_NAME: if ( !m_curVarName.IsEmpty() ) { wxString old_name = m_curVarName; wxString new_name = m_varName->GetValue(); if ( m_ipd.Variables().Lookup( new_name ) ) { wxMessageBox("that variable already exists: " + new_name, "notice", wxOK, this ); m_varName->ChangeValue( old_name ); m_varName->SelectAll(); return; } if ( m_ipd.Variables().Rename( old_name, new_name ) ) { m_curVarName = new_name; LoadVarList( new_name ); } else wxMessageBox("failed to rename: " + old_name + " --> " + new_name ); } break; case ID_VAR_LABEL: case ID_VAR_UNITS: m_uiFormEditor->Refresh(); break; case ID_CALLBACK_FIND: m_callbackScript->ShowFindReplaceDialog(); break; case ID_CALLBACK_CHECK: { lk::input_string in( m_callbackScript->GetText() ); lk::parser parse( in ); lk::node_t *root = parse.script(); if ( parse.error_count() == 0 ) wxMessageBox("callback script parsed ok.", "notice", wxOK, this ); else { wxString text; for( int i=0;i<parse.error_count();i++ ) text += parse.error( i ) + "\n"; ::wxShowTextMessageDialog( text, "errors", this ); } if( root != 0 ) delete root; } break; case ID_CALLBACK_GOTO: { m_callbackGotoList.Clear(); wxMenu menu; int id = ID_CALLBACK_GOTO_1; m_callbackGotoList.Add( "on_load{'" + m_formName + "'} = define() {" ); menu.Append( id++, "form->on_load" ); std::vector<wxUIObject*> objs = m_exForm.GetObjects(); for( size_t i=0;i<objs.size();i++ ) { wxString type = objs[i]->GetTypeName(); if ( type == "Button" || type == "CheckBox" || type == "RadioChoice" || type == "Choice" ) { m_callbackGotoList.Add( "on_change{'" + objs[i]->GetName() + "'} = define() {" ); menu.Append(id++, objs[i]->GetName() + "->on_change" ); } } PopupMenu( &menu ); } break; case ID_CALLBACK_HELP: m_callbackScript->ShowHelpDialog( this ); break; case ID_EQUATION_FIND: m_equationScript->ShowFindReplaceDialog(); break; case ID_EQUATION_HELP: m_equationScript->ShowHelpDialog( this ); break; case ID_EQUATION_SCAN: { wxArrayString errors; EqnDatabase db; bool ok = db.LoadScript( m_equationScript->GetText(), &errors ); wxString text; if ( ok ) { std::vector<EqnData*> list = db.GetEquations(); text << list.size() << " equations resolved ok \n\n"; for( size_t i=0;i<list.size();i++ ) { text << "-------------------------------------------------------------------------------\n"; text << "[" << i << "] outputs: " << wxJoin( list[i]->outputs, ';' ) << "\n"; text << "[" << i << "] inputs: " << wxJoin( list[i]->inputs, ';' ) << "\n"; wxString str; lk::pretty_print( str, list[i]->tree, 0 ); text << str << "\n\n"; } } else { text << errors.size() << " errors when scanning equations\n"; text << wxJoin(errors, '\n'); } wxShowTextMessageDialog( text, "equation scan", this, wxScaleSize(800,700) ); } break; case ID_VAR_CHECK_ALL: case ID_VAR_CHECK_NONE: for( size_t i=0;i<m_varList->GetCount();i++) m_varList->Check( i, evt.GetId() == ID_VAR_CHECK_ALL ); break; case ID_VAR_CHECK_SEL: for( size_t i=0;i<m_varList->GetCount();i++) m_varList->Check( i, m_uiFormEditor->GetEditor()->IsSelected( m_varList->GetString( i ) ) ); break; case ID_VAR_STORE: m_varCopyBuffer.clear(); for( size_t i=0;i<m_varList->GetCount();i++ ) { if ( !m_varList->IsChecked( i ) ) continue; if ( VarInfo *vi = m_ipd.Variables().Lookup( m_varList->GetString(i) ) ) m_varCopyBuffer.Add( m_varList->GetString(i), new VarInfo( *vi ) ); } break; case ID_VAR_LOAD: { wxArrayString err; for( VarInfoHash::iterator it = m_varCopyBuffer.begin(); it != m_varCopyBuffer.end(); ++it ) { if( m_ipd.Variables().Lookup( it->first ) == 0 ) m_ipd.Variables().Add( it->first, new VarInfo( *(it->second) ) ); else err.Add( it->first ); } VarInfoToForm( wxEmptyString ); LoadVarList( m_varList->GetStringSelection() ); wxShowTextMessageDialog( "Conflicts?\n" + wxJoin(err, '\n') + "\nLoaded:\n" + wxJoin( m_varCopyBuffer.ListAll(), '\n' ) ); } break; } } void UIEditorPanel::SyncFormUIToDataBeforeWriting() { FormToVarInfo( ); // sync any updates to the var before writing } void UIEditorPanel::OnFormSelectObject( wxUIFormEvent &evt ) { if ( wxUIObject *obj = evt.GetUIObject() ) { wxString name = obj->GetName(); if (m_ipd.Variables().Lookup( name ) ) { FormToVarInfo( ); // save the current var m_varList->SetStringSelection( name ); VarInfoToForm( name ); } } } void UIEditorPanel::FormToVarInfo( ) { VarInfo *vv = m_ipd.Variables().Lookup( m_curVarName ); if ( !vv ) return; vv->Type = m_varType->GetSelection(); vv->Label = m_varLabel->GetValue(); vv->Units = m_varUnits->GetValue(); vv->Group = m_varGroup->GetValue(); vv->IndexLabels = wxSplit( m_varIndexLabels->GetValue(), ',' ); vv->Flags = 0; if( m_varFlagHideLabels->GetValue() ) vv->Flags |= VF_HIDE_LABELS; if( m_varFlagParametric->GetValue() ) vv->Flags |= VF_PARAMETRIC; if( m_varFlagIndicator->GetValue() ) vv->Flags |= VF_INDICATOR; if( m_varFlagCalculated->GetValue() ) vv->Flags |= VF_CALCULATED; if (m_varFlagLibrary->GetValue()) vv->Flags |= VF_LIBRARY; if (m_varFlagChangeModel->GetValue()) vv->Flags |= VF_CHANGE_MODEL; vv->DefaultValue.SetType( vv->Type ); VarValue::Parse( vv->Type, m_varDefaultValue->GetValue(), vv->DefaultValue ); vv->UIObject = m_varUIObject->GetString((m_varUIObject->GetCurrentSelection())); } void UIEditorPanel::VarInfoToForm( const wxString &name ) { if ( VarInfo *vv = m_ipd.Variables().Lookup( name ) ) { m_curVarName = name; m_varName->ChangeValue( m_curVarName ); m_varType->SetSelection( vv->Type ); int ndx = m_varUIObject->GetStrings().Index(vv->UIObject); if (ndx != wxNOT_FOUND) m_varUIObject->SetSelection( ndx ); else { ndx = m_varUIObject->GetStrings().Index(VUIOBJ_NONE); if (ndx != wxNOT_FOUND) m_varUIObject->SetSelection(ndx); else m_varUIObject->SetSelection(0); } m_varLabel->ChangeValue(vv->Label); m_varUnits->ChangeValue( vv->Units ); m_varGroup->ChangeValue( vv->Group ); m_varIndexLabels->ChangeValue( wxJoin( vv->IndexLabels, ',' ) ); m_varFlagHideLabels->SetValue(( vv->Flags & VF_HIDE_LABELS ) > 0); m_varFlagParametric->SetValue(( vv->Flags & VF_PARAMETRIC ) > 0); m_varFlagIndicator->SetValue(( vv->Flags & VF_INDICATOR ) > 0); m_varFlagCalculated->SetValue(( vv->Flags & VF_CALCULATED ) > 0); m_varFlagLibrary->SetValue((vv->Flags & VF_LIBRARY) > 0); m_varFlagChangeModel->SetValue((vv->Flags & VF_CHANGE_MODEL) > 0); m_varDefaultValue->SetValue(vv->DefaultValue.AsString(';') ); } else { m_curVarName.Clear(); // m_curVarName was not a valid variable m_varName->ChangeValue( wxEmptyString ); m_varType->SetSelection( 0 ); int ndx = m_varUIObject->GetStrings().Index(VUIOBJ_NONE); if (ndx != wxNOT_FOUND) m_varUIObject->SetSelection(ndx); else m_varUIObject->SetSelection(0); m_varLabel->ChangeValue(wxEmptyString); m_varUnits->ChangeValue( wxEmptyString ); m_varGroup->ChangeValue( wxEmptyString ); m_varIndexLabels->ChangeValue( wxEmptyString ); m_varFlagHideLabels->SetValue( false ); m_varFlagParametric->SetValue( false ); m_varFlagIndicator->SetValue( false ); m_varFlagCalculated->SetValue( false ); m_varFlagLibrary->SetValue(false); m_varFlagChangeModel->SetValue(false); m_varDefaultValue->SetValue( wxEmptyString ); } bool en = !m_curVarName.IsEmpty(); m_varName->Enable( en ); m_varType->Enable(en); m_varUIObject->Enable(en); m_varLabel->Enable(en); m_varUnits->Enable( en ); m_varGroup->Enable( en ); m_varIndexLabels->Enable( en ); m_varDefaultValue->Enable( en ); m_varFlagHideLabels->Enable( en ); m_varFlagParametric->Enable( en ); m_varFlagIndicator->Enable( en ); m_varFlagCalculated->Enable( en ); m_varFlagLibrary->Enable(en); m_varFlagChangeModel->Enable(en); } void UIEditorPanel::LoadVarList( const wxString &sel ) { m_varList->Freeze(); m_varList->Clear(); wxArrayString list = m_ipd.Variables().ListAll(); list.Sort(); m_varList->Append( list ); m_varList->Thaw(); if ( !sel.IsEmpty() ) m_varList->SetStringSelection( sel ); } bool UIEditorPanel::Write( const wxString &name ) { bool ok = true; m_ipd.Form().Copy( m_exForm ); m_ipd.Form().SetName( name ); // note: ipd.Variables() already up-to-date m_ipd.CbScript() = m_callbackScript->GetText(); m_ipd.EqnScript() = m_equationScript->GetText(); wxFFileOutputStream ff(SamApp::GetRuntimePath() + "/ui/" + name + ".ui"); if ( ff.IsOk() ) m_ipd.Write( ff ); else ok = false; return ok; } bool UIEditorPanel::Write_text(const wxString &name) { bool ok = true; m_ipd.Form().Copy(m_exForm); m_ipd.Form().SetName(name); // note: ipd.Variables() already up-to-date m_ipd.CbScript() = m_callbackScript->GetText(); m_ipd.EqnScript() = m_equationScript->GetText(); wxString ui_path = SamApp::GetRuntimePath() + "/ui/" + name; wxFFileOutputStream ff(ui_path + ".txt", "w"); if (ff.IsOk()) m_ipd.Write_text(ff, ui_path); else ok = false; return ok; } bool UIEditorPanel::Load( const wxString &name ) { m_uiFormEditor->SetFormData( 0 ); m_uiFormEditor->Refresh(); m_formName.Clear(); m_ipd.Clear(); bool ok = true; wxString file = SamApp::GetRuntimePath() + "/ui/" + name + ".ui"; if ( wxFileExists( file ) ) { wxFFileInputStream ff( file ); if ( ff.IsOk() && m_ipd.Read( ff ) ) { m_ipd.Form().SetName( name ); m_exForm.Copy( m_ipd.Form() ); m_uiFormEditor->SetFormData( &m_exForm ); m_uiFormEditor->Refresh(); m_formName = name; LoadVarList(); VarInfoToForm( wxEmptyString ); m_callbackScript->SetText( m_ipd.CbScript() ); m_equationScript->SetText( m_ipd.EqnScript() ); } else ok = false; } return ok; } bool UIEditorPanel::Load_text(const wxString &name) { m_uiFormEditor->SetFormData(0); m_uiFormEditor->Refresh(); m_formName.Clear(); m_ipd.Clear(); bool ok = true; wxString ui_path = SamApp::GetRuntimePath() + "/ui/" ; wxString file = ui_path + name + ".txt"; if (wxFileExists(file)) { wxFFileInputStream ff(file, "r"); bool bff = ff.IsOk(); bool bread = m_ipd.Read_text(ff, ui_path); if (bff && bread) // if (ff.IsOk() && m_ipd.Read_text(ff)) { m_ipd.Form().SetName(name); m_exForm.Copy(m_ipd.Form()); m_uiFormEditor->SetFormData(&m_exForm); m_uiFormEditor->Refresh(); m_formName = name; LoadVarList(); VarInfoToForm(wxEmptyString); m_callbackScript->SetText(m_ipd.CbScript()); m_equationScript->SetText(m_ipd.EqnScript()); } else ok = false; } return ok; } static IDEWindow *g_ideWin=0; void ShowIDEWindow() { if ( !g_ideWin ) { g_ideWin = new IDEWindow( SamApp::Window() ); } g_ideWin->Show(); g_ideWin->Raise(); } BEGIN_EVENT_TABLE( IDEWindow, wxFrame ) EVT_CLOSE( IDEWindow::OnClose ) END_EVENT_TABLE() IDEWindow::IDEWindow( wxWindow *parent ) : wxFrame(parent, wxID_ANY, "SAM Development Environment", wxDefaultPosition, wxScaleSize(1150,900) ) { #ifdef __WXMSW__ SetIcon( wxICON( appicon ) ); #endif m_notebook = new wxMetroNotebook( this ); m_startupPanel = new ScriptPanel( m_notebook, "startup.lk" ); m_startupPanel->AddLibrary( invoke_config_funcs(), "Config Functions" ); m_notebook->AddPage( m_startupPanel, "Startup" ); m_uiPanel = new UIEditorPanel( m_notebook ); m_notebook->AddPage( m_uiPanel, "User Interface" ); m_metricsPanel = new ScriptPanel( m_notebook, "metrics.lk" ); m_metricsPanel->AddLibrary( invoke_casecallback_funcs(), "Case callbacks" ); m_metricsPanel->AddLibrary( invoke_resultscallback_funcs(), "Results callbacks" ); m_notebook->AddPage( m_metricsPanel, "Metrics" ); m_cashFlowPanel = new ScriptPanel( m_notebook, "cashflow.lk" ); m_cashFlowPanel->AddLibrary(invoke_casecallback_funcs(), "Case callbacks"); m_cashFlowPanel->AddLibrary( invoke_resultscallback_funcs(), "Results callbacks" ); m_notebook->AddPage(m_cashFlowPanel, "Cashflows"); m_autoGraphPanel = new ScriptPanel( m_notebook, "autographs.lk" ); m_autoGraphPanel->AddLibrary( invoke_casecallback_funcs(), "Case callbacks" ); m_autoGraphPanel->AddLibrary( invoke_resultscallback_funcs(), "Results callbacks" ); m_notebook->AddPage( m_autoGraphPanel, "Autographs" ); m_lossDiagramPanel = new ScriptPanel( m_notebook, "lossdiag.lk" ); m_lossDiagramPanel->AddLibrary( invoke_casecallback_funcs(), "Case callbacks" ); m_lossDiagramPanel->AddLibrary( invoke_lossdiag_funcs(), "Loss diagrams" ); m_notebook->AddPage( m_lossDiagramPanel, "Loss diagrams" ); m_reportEditorPanel = new SamReportWindow( m_notebook ); m_notebook->AddPage( m_reportEditorPanel, "Reports" ); m_defaultsMgr = new DefaultsManager( m_notebook ); m_notebook->AddPage( m_defaultsMgr, "Defaults manager" ); m_versionPanel = new ScriptPanel( m_notebook, "versions.lk" ); m_versionPanel->AddLibrary( VersionUpgrade::invoke_functions(), "Version Upgrade" ); m_notebook->AddPage( m_versionPanel, "Version upgrade" ); m_notebook->Refresh(); } IDEWindow::~IDEWindow() { g_ideWin = 0; } void IDEWindow::OnClose( wxCloseEvent &evt ) { Hide(); evt.Veto(); }
33.253768
168
0.692557
[ "object", "vector", "model" ]
28b9ecd7dcc383ef181ec700eb49c1afd4186fb7
1,080
cpp
C++
ProjectEuler/C++/PalindromicSums.cpp
dfm066/Programming
53d28460cd40b966cca1d4695d9dc6792ced4c6f
[ "MIT" ]
null
null
null
ProjectEuler/C++/PalindromicSums.cpp
dfm066/Programming
53d28460cd40b966cca1d4695d9dc6792ced4c6f
[ "MIT" ]
null
null
null
ProjectEuler/C++/PalindromicSums.cpp
dfm066/Programming
53d28460cd40b966cca1d4695d9dc6792ced4c6f
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <iostream> #include <numeric> #include <unordered_set> #include <vector> // #include "utils.h" using namespace std; template <typename I> bool isPalindrome(I num) { string x = to_string(num); for (int i = 0, j = x.size() - 1; i < j; ++i, --j) { if (x[i] != x[j]) return false; } return true; } long long problem_125(long long limit) { unordered_set<long long> ans; int range = floor(sqrt(limit)); vector<long long> squares(range + 1); generate(squares.begin(), squares.end(), [n = -1]() mutable { n++; return n * n; }); transform(squares.begin(), prev(squares.end()), next(squares.begin()), next(squares.begin()), std::plus<>{}); for (int i = 0; i < squares.size(); ++i) { for (int j = i + 2; j < squares.size(); ++j) { long long sum = squares[j] - squares[i]; if (sum < limit && isPalindrome(sum)) { ans.insert(sum); } } } return accumulate(ans.begin(), ans.end(), (long long)0); } int main() { cout << problem_125(100000000); return 0; }
23.478261
72
0.586111
[ "vector", "transform" ]
28bea213628db7f79bb46caf5d8ca68b0db5e74f
3,515
cpp
C++
source/json/h2_node.cpp
lingjf/jp
e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8
[ "Apache-2.0" ]
null
null
null
source/json/h2_node.cpp
lingjf/jp
e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8
[ "Apache-2.0" ]
null
null
null
source/json/h2_node.cpp
lingjf/jp
e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8
[ "Apache-2.0" ]
null
null
null
struct h2_json_node { static constexpr int t_absent = 0; static constexpr int t_null = 1; static constexpr int t_boolean = 2; static constexpr int t_number = 3; static constexpr int t_string = 4; static constexpr int t_array = 6; static constexpr int t_object = 7; int type = t_absent; int index = 0; h2_string key_string; h2_string value_string; double value_double = 0; bool value_boolean = false; h2_list children, x; /* array or object */ h2_json_node(int index_ = 0) : index(index_) {} ~h2_json_node() { h2_list_for_each_entry (p, children, h2_json_node, x) { p->x.out(); delete p; } } int size() const { return children.count(); } h2_json_node* get(int index) const { if (index < 0) index = children.count() + index; h2_list_for_each_entry_i(p, i, children, h2_json_node, x) if (i == index) return p; return nullptr; } h2_json_node* get(const h2_string& name, bool caseless) const { h2_list_for_each_entry (p, children, h2_json_node, x) if (p->key_string.equals(name, caseless)) return p; return nullptr; } bool is_null() const { return t_null == type; } bool is_bool() const { return t_boolean == type; } bool is_number() const { return t_number == type; } bool is_string() const { return t_string == type; } bool is_array() const { return t_array == type; } bool is_object() const { return t_object == type; } h2_string quote_if(int quote) const { switch (quote) { case 1: return "'"; case 2: return "\""; case 3: return "\\\""; default: return ""; } } h2_string format_value(int quote) const { switch (type) { case t_null: return "null"; case t_boolean: return value_boolean ? "true" : "false"; case t_number: return (value_double - ::floor(value_double) == 0) ? std::to_string((long long)value_double).c_str() : std::to_string(value_double).c_str(); case t_string: return quote_if(quote) + value_string + quote_if(quote); case t_array: case t_object: default: return ""; } } void format(int& _type, h2_string& _key, h2_string& _value, int quote = 0) const { _type = type; if (key_string.size()) _key = quote_if(quote) + key_string + quote_if(quote); _value = format_value(quote); } h2_lines format(bool fold, int quote = 0, size_t depth = 0, int next = 0) const { h2_lines lines; h2_line line; line.indent(depth * 2); if (key_string.size()) line.push_back(quote_if(quote) + key_string + quote_if(quote) + ": "); if (is_array() || is_object()) { h2_lines children_lines; h2_list_for_each_entry_i(p, i, children, h2_json_node, x) children_lines += p->format(fold, quote, depth + 1, children.count() - i - 1); line.push_back(is_array() ? "[" : "{"); if (fold && children_lines.foldable()) { line += children_lines.folds(); } else { lines.push_back(line), line.clear(); lines += children_lines; line.indent(depth * 2); } line.push_back(is_array() ? "]" : "}"); } else { line.push_back(format_value(quote)); } if (line.size()) { if (next) line.push_back(", "); lines.push_back(line), line.clear(); } return lines; } };
30.833333
164
0.587482
[ "object" ]
28bf165f08e856474d6fee71edd07fcbae904db2
41,295
cpp
C++
lib/Basics/VelocyPackHelper.cpp
dolfly/arangodb
b3ee17672e19e48db97c5dafce5978ba0a272fb5
[ "Apache-2.0" ]
null
null
null
lib/Basics/VelocyPackHelper.cpp
dolfly/arangodb
b3ee17672e19e48db97c5dafce5978ba0a272fb5
[ "Apache-2.0" ]
null
null
null
lib/Basics/VelocyPackHelper.cpp
dolfly/arangodb
b3ee17672e19e48db97c5dafce5978ba0a272fb5
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "VelocyPackHelper.h" #include "Basics/Exceptions.h" #include "Basics/OpenFilesTracker.h" #include "Basics/StaticStrings.h" #include "Basics/StringBuffer.h" #include "Basics/StringRef.h" #include "Basics/StringUtils.h" #include "Basics/Utf8Helper.h" #include "Basics/VPackStringBufferAdapter.h" #include "Basics/conversions.h" #include "Basics/files.h" #include "Basics/hashes.h" #include "Basics/tri-strings.h" #include "Logger/Logger.h" #include <velocypack/AttributeTranslator.h> #include <velocypack/Collection.h> #include <velocypack/Dumper.h> #include <velocypack/Options.h> #include <velocypack/Slice.h> #include <velocypack/velocypack-aliases.h> #include <velocypack/velocypack-common.h> extern "C" { unsigned long long XXH64(const void* input, size_t length, unsigned long long seed); } using namespace arangodb; using VelocyPackHelper = arangodb::basics::VelocyPackHelper; static std::unique_ptr<VPackAttributeTranslator> Translator; static std::unique_ptr<VPackAttributeExcludeHandler> ExcludeHandler; static std::unique_ptr<VPackCustomTypeHandler> CustomTypeHandler; // statically computed table of type weights // the weight for type MinKey must be lowest, the weight for type MaxKey must be highest // the table contains a special value -50 to indicate that the value is an external which must be resolved further // the type Custom has the same weight as the String type, because the Custom type is used to store _id (which is a string) static int8_t const TypeWeights[256] = { 0 /* 0x00 */, 4 /* 0x01 */, 4 /* 0x02 */, 4 /* 0x03 */, 4 /* 0x04 */, 4 /* 0x05 */, 4 /* 0x06 */, 4 /* 0x07 */, 4 /* 0x08 */, 4 /* 0x09 */, 5 /* 0x0a */, 5 /* 0x0b */, 5 /* 0x0c */, 5 /* 0x0d */, 5 /* 0x0e */, 5 /* 0x0f */, 5 /* 0x10 */, 5 /* 0x11 */, 5 /* 0x12 */, 4 /* 0x13 */, 5 /* 0x14 */, 0 /* 0x15 */, 0 /* 0x16 */, -1 /* 0x17 */, 0 /* 0x18 */, 1 /* 0x19 */, 1 /* 0x1a */, 2 /* 0x1b */, 2 /* 0x1c */, -50 /* 0x1d */, -99 /* 0x1e */, 99 /* 0x1f */, 2 /* 0x20 */, 2 /* 0x21 */, 2 /* 0x22 */, 2 /* 0x23 */, 2 /* 0x24 */, 2 /* 0x25 */, 2 /* 0x26 */, 2 /* 0x27 */, 2 /* 0x28 */, 2 /* 0x29 */, 2 /* 0x2a */, 2 /* 0x2b */, 2 /* 0x2c */, 2 /* 0x2d */, 2 /* 0x2e */, 2 /* 0x2f */, 2 /* 0x30 */, 2 /* 0x31 */, 2 /* 0x32 */, 2 /* 0x33 */, 2 /* 0x34 */, 2 /* 0x35 */, 2 /* 0x36 */, 2 /* 0x37 */, 2 /* 0x38 */, 2 /* 0x39 */, 2 /* 0x3a */, 2 /* 0x3b */, 2 /* 0x3c */, 2 /* 0x3d */, 2 /* 0x3e */, 2 /* 0x3f */, 3 /* 0x40 */, 3 /* 0x41 */, 3 /* 0x42 */, 3 /* 0x43 */, 3 /* 0x44 */, 3 /* 0x45 */, 3 /* 0x46 */, 3 /* 0x47 */, 3 /* 0x48 */, 3 /* 0x49 */, 3 /* 0x4a */, 3 /* 0x4b */, 3 /* 0x4c */, 3 /* 0x4d */, 3 /* 0x4e */, 3 /* 0x4f */, 3 /* 0x50 */, 3 /* 0x51 */, 3 /* 0x52 */, 3 /* 0x53 */, 3 /* 0x54 */, 3 /* 0x55 */, 3 /* 0x56 */, 3 /* 0x57 */, 3 /* 0x58 */, 3 /* 0x59 */, 3 /* 0x5a */, 3 /* 0x5b */, 3 /* 0x5c */, 3 /* 0x5d */, 3 /* 0x5e */, 3 /* 0x5f */, 3 /* 0x60 */, 3 /* 0x61 */, 3 /* 0x62 */, 3 /* 0x63 */, 3 /* 0x64 */, 3 /* 0x65 */, 3 /* 0x66 */, 3 /* 0x67 */, 3 /* 0x68 */, 3 /* 0x69 */, 3 /* 0x6a */, 3 /* 0x6b */, 3 /* 0x6c */, 3 /* 0x6d */, 3 /* 0x6e */, 3 /* 0x6f */, 3 /* 0x70 */, 3 /* 0x71 */, 3 /* 0x72 */, 3 /* 0x73 */, 3 /* 0x74 */, 3 /* 0x75 */, 3 /* 0x76 */, 3 /* 0x77 */, 3 /* 0x78 */, 3 /* 0x79 */, 3 /* 0x7a */, 3 /* 0x7b */, 3 /* 0x7c */, 3 /* 0x7d */, 3 /* 0x7e */, 3 /* 0x7f */, 3 /* 0x80 */, 3 /* 0x81 */, 3 /* 0x82 */, 3 /* 0x83 */, 3 /* 0x84 */, 3 /* 0x85 */, 3 /* 0x86 */, 3 /* 0x87 */, 3 /* 0x88 */, 3 /* 0x89 */, 3 /* 0x8a */, 3 /* 0x8b */, 3 /* 0x8c */, 3 /* 0x8d */, 3 /* 0x8e */, 3 /* 0x8f */, 3 /* 0x90 */, 3 /* 0x91 */, 3 /* 0x92 */, 3 /* 0x93 */, 3 /* 0x94 */, 3 /* 0x95 */, 3 /* 0x96 */, 3 /* 0x97 */, 3 /* 0x98 */, 3 /* 0x99 */, 3 /* 0x9a */, 3 /* 0x9b */, 3 /* 0x9c */, 3 /* 0x9d */, 3 /* 0x9e */, 3 /* 0x9f */, 3 /* 0xa0 */, 3 /* 0xa1 */, 3 /* 0xa2 */, 3 /* 0xa3 */, 3 /* 0xa4 */, 3 /* 0xa5 */, 3 /* 0xa6 */, 3 /* 0xa7 */, 3 /* 0xa8 */, 3 /* 0xa9 */, 3 /* 0xaa */, 3 /* 0xab */, 3 /* 0xac */, 3 /* 0xad */, 3 /* 0xae */, 3 /* 0xaf */, 3 /* 0xb0 */, 3 /* 0xb1 */, 3 /* 0xb2 */, 3 /* 0xb3 */, 3 /* 0xb4 */, 3 /* 0xb5 */, 3 /* 0xb6 */, 3 /* 0xb7 */, 3 /* 0xb8 */, 3 /* 0xb9 */, 3 /* 0xba */, 3 /* 0xbb */, 3 /* 0xbc */, 3 /* 0xbd */, 3 /* 0xbe */, 3 /* 0xbf */, 3 /* 0xc0 */, 3 /* 0xc1 */, 3 /* 0xc2 */, 3 /* 0xc3 */, 3 /* 0xc4 */, 3 /* 0xc5 */, 3 /* 0xc6 */, 3 /* 0xc7 */, 2 /* 0xc8 */, 2 /* 0xc9 */, 2 /* 0xca */, 2 /* 0xcb */, 2 /* 0xcc */, 2 /* 0xcd */, 2 /* 0xce */, 2 /* 0xcf */, 2 /* 0xd0 */, 2 /* 0xd1 */, 2 /* 0xd2 */, 2 /* 0xd3 */, 2 /* 0xd4 */, 2 /* 0xd5 */, 2 /* 0xd6 */, 2 /* 0xd7 */, 0 /* 0xd8 */, 0 /* 0xd9 */, 0 /* 0xda */, 0 /* 0xdb */, 0 /* 0xdc */, 0 /* 0xdd */, 0 /* 0xde */, 0 /* 0xdf */, 0 /* 0xe0 */, 0 /* 0xe1 */, 0 /* 0xe2 */, 0 /* 0xe3 */, 0 /* 0xe4 */, 0 /* 0xe5 */, 0 /* 0xe6 */, 0 /* 0xe7 */, 0 /* 0xe8 */, 0 /* 0xe9 */, 0 /* 0xea */, 0 /* 0xeb */, 0 /* 0xec */, 0 /* 0xed */, 0 /* 0xee */, 0 /* 0xef */, 3 /* 0xf0 */, 3 /* 0xf1 */, 3 /* 0xf2 */, 3 /* 0xf3 */, 3 /* 0xf4 */, 3 /* 0xf5 */, 3 /* 0xf6 */, 3 /* 0xf7 */, 3 /* 0xf8 */, 3 /* 0xf9 */, 3 /* 0xfa */, 3 /* 0xfb */, 3 /* 0xfc */, 3 /* 0xfd */, 3 /* 0xfe */, 3 /* 0xff */, }; // a default custom type handler that prevents throwing exceptions when // custom types are encountered during Slice.toJson() and family struct DefaultCustomTypeHandler final : public VPackCustomTypeHandler { void dump(VPackSlice const&, VPackDumper* dumper, VPackSlice const&) override { LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "DefaultCustomTypeHandler called"; dumper->appendString("hello from CustomTypeHandler"); } std::string toString(VPackSlice const&, VPackOptions const*, VPackSlice const&) override { LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "DefaultCustomTypeHandler called"; return "hello from CustomTypeHandler"; } }; // attribute exclude handler for skipping over system attributes struct SystemAttributeExcludeHandler final : public VPackAttributeExcludeHandler { bool shouldExclude(VPackSlice const& key, int nesting) override final { VPackValueLength keyLength; char const* p = key.getString(keyLength); if (p == nullptr || *p != '_' || keyLength < 3 || keyLength > 5 || nesting > 0) { // keep attribute return true; } // exclude these attributes (but not _key!) if ((keyLength == 3 && memcmp(p, "_id", static_cast<size_t>(keyLength)) == 0) || (keyLength == 4 && memcmp(p, "_rev", static_cast<size_t>(keyLength)) == 0) || (keyLength == 3 && memcmp(p, "_to", static_cast<size_t>(keyLength)) == 0) || (keyLength == 5 && memcmp(p, "_from", static_cast<size_t>(keyLength)) == 0)) { return true; } // keep attribute return false; } }; /// @brief static initializer for all VPack values void VelocyPackHelper::initialize() { LOG_TOPIC(TRACE, arangodb::Logger::FIXME) << "initializing vpack"; // initialize attribute translator Translator.reset(new VPackAttributeTranslator); // these attribute names will be translated into short integer values Translator->add(StaticStrings::KeyString, KeyAttribute - AttributeBase); Translator->add(StaticStrings::RevString, RevAttribute - AttributeBase); Translator->add(StaticStrings::IdString, IdAttribute - AttributeBase); Translator->add(StaticStrings::FromString, FromAttribute - AttributeBase); Translator->add(StaticStrings::ToString, ToAttribute - AttributeBase); Translator->seal(); // set the attribute translator in the global options VPackOptions::Defaults.attributeTranslator = Translator.get(); VPackOptions::Defaults.unsupportedTypeBehavior = VPackOptions::ConvertUnsupportedType; CustomTypeHandler.reset(new DefaultCustomTypeHandler); VPackOptions::Defaults.customTypeHandler = CustomTypeHandler.get(); VPackOptions::Defaults.escapeUnicode = false; // false here, but will be set // when converting to JSON for // HTTP xfer // run quick selfs test with the attribute translator TRI_ASSERT( VPackSlice(Translator->translate(StaticStrings::KeyString)).getUInt() == KeyAttribute - AttributeBase); TRI_ASSERT( VPackSlice(Translator->translate(StaticStrings::RevString)).getUInt() == RevAttribute - AttributeBase); TRI_ASSERT( VPackSlice(Translator->translate(StaticStrings::IdString)).getUInt() == IdAttribute - AttributeBase); TRI_ASSERT( VPackSlice(Translator->translate(StaticStrings::FromString)).getUInt() == FromAttribute - AttributeBase); TRI_ASSERT( VPackSlice(Translator->translate(StaticStrings::ToString)).getUInt() == ToAttribute - AttributeBase); TRI_ASSERT(VPackSlice(Translator->translate(KeyAttribute - AttributeBase)) .copyString() == StaticStrings::KeyString); TRI_ASSERT(VPackSlice(Translator->translate(RevAttribute - AttributeBase)) .copyString() == StaticStrings::RevString); TRI_ASSERT(VPackSlice(Translator->translate(IdAttribute - AttributeBase)) .copyString() == StaticStrings::IdString); TRI_ASSERT(VPackSlice(Translator->translate(FromAttribute - AttributeBase)) .copyString() == StaticStrings::FromString); TRI_ASSERT(VPackSlice(Translator->translate(ToAttribute - AttributeBase)) .copyString() == StaticStrings::ToString); // initialize exclude handler for system attributes ExcludeHandler.reset(new SystemAttributeExcludeHandler); } //////////////////////////////////////////////////////////////////////////////// /// @brief turn off assembler optimizations in vpack //////////////////////////////////////////////////////////////////////////////// void VelocyPackHelper::disableAssemblerFunctions() { arangodb::velocypack::disableAssemblerFunctions(); } //////////////////////////////////////////////////////////////////////////////// /// @brief return the (global) attribute exclude handler instance //////////////////////////////////////////////////////////////////////////////// arangodb::velocypack::AttributeExcludeHandler* VelocyPackHelper::getExcludeHandler() { return ExcludeHandler.get(); } //////////////////////////////////////////////////////////////////////////////// /// @brief return the (global) attribute translator instance //////////////////////////////////////////////////////////////////////////////// arangodb::velocypack::AttributeTranslator* VelocyPackHelper::getTranslator() { return Translator.get(); } bool VelocyPackHelper::AttributeSorterUTF8::operator()( std::string const& l, std::string const& r) const { // use UTF-8-based comparison of attribute names return TRI_compare_utf8(l.c_str(), l.size(), r.c_str(), r.size()) < 0; } bool VelocyPackHelper::AttributeSorterBinary::operator()( std::string const& l, std::string const& r) const { // use binary comparison of attribute names size_t cmpLength = (std::min)(l.size(), r.size()); int res = memcmp(l.c_str(), r.c_str(), cmpLength); if (res < 0) { return true; } if (res == 0) { return l.size() < r.size(); } return false; } size_t VelocyPackHelper::VPackHash::operator()(VPackSlice const& slice) const { return static_cast<size_t>(slice.normalizedHash()); }; size_t VelocyPackHelper::VPackStringHash::operator()( VPackSlice const& slice) const noexcept { return static_cast<size_t>(slice.hashString()); }; size_t VelocyPackHelper::VPackKeyHash::operator()( VPackSlice const& slice) const { return static_cast<size_t>(slice.get(StaticStrings::KeyString).hashString()); }; bool VelocyPackHelper::VPackEqual::operator()(VPackSlice const& lhs, VPackSlice const& rhs) const { return VelocyPackHelper::compare(lhs, rhs, false, _options) == 0; }; bool VelocyPackHelper::VPackStringEqual::operator()(VPackSlice const& lhs, VPackSlice const& rhs) const noexcept { auto const lh = lhs.head(); auto const rh = rhs.head(); if (lh != rh) { return false; } VPackValueLength size; if (lh == 0xbf) { // long UTF-8 String size = static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(lhs.begin() + 1)); if (size != static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(rhs.begin() + 1))) { return false; } return (memcmp(lhs.start() + 1 + 8, rhs.start() + 1 + 8, static_cast<size_t>(size)) == 0); } size = static_cast<VPackValueLength>(lh - 0x40); return (memcmp(lhs.start() + 1, rhs.start() + 1, static_cast<size_t>(size)) == 0); }; bool VelocyPackHelper::VPackIdEqual::operator()(VPackSlice const& lhs, VPackSlice const& rhs) const { if (lhs.get(StaticStrings::IdString) != rhs.get(StaticStrings::IdString)) { // short-cut, we are in a different collection return false; } // Same collection now actually compare the key VPackSlice lhsKey = lhs.get(StaticStrings::KeyString); VPackSlice rhsKey = rhs.get(StaticStrings::KeyString); auto const lh = lhsKey.head(); auto const rh = rhsKey.head(); if (lh != rh) { return false; } VPackValueLength size; if (lh == 0xbf) { // long UTF-8 String size = static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(lhsKey.begin() + 1)); if (size != static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(rhsKey.begin() + 1))) { return false; } return (memcmp(lhsKey.start() + 1 + 8, rhsKey.start() + 1 + 8, static_cast<size_t>(size)) == 0); } size = static_cast<VPackValueLength>(lh - 0x40); return (memcmp(lhsKey.start() + 1, rhsKey.start() + 1, static_cast<size_t>(size)) == 0); }; bool VelocyPackHelper::VPackHashedStringEqual::operator()(basics::VPackHashedSlice const& lhs, basics::VPackHashedSlice const& rhs) const noexcept { auto const lh = lhs.slice.head(); auto const rh = rhs.slice.head(); if (lh != rh) { return false; } VPackValueLength size; if (lh == 0xbf) { // long UTF-8 String size = static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(lhs.slice.begin() + 1)); if (size != static_cast<VPackValueLength>( velocypack::readIntegerFixed<VPackValueLength, 8>(rhs.slice.begin() + 1))) { return false; } return (memcmp(lhs.slice.start() + 1 + 8, rhs.slice.start() + 1 + 8, static_cast<size_t>(size)) == 0); } size = static_cast<VPackValueLength>(lh - 0x40); return (memcmp(lhs.slice.start() + 1, rhs.slice.start() + 1, static_cast<size_t>(size)) == 0); }; static inline int8_t TypeWeight(VPackSlice& slice) { again: int8_t w = TypeWeights[slice.head()]; if (w == -50) { slice = slice.resolveExternal(); goto again; } return w; } int VelocyPackHelper::compareNumberValues(VPackValueType lhsType, VPackSlice lhs, VPackSlice rhs) { if (lhsType == rhs.type()) { // both types are equal if (lhsType == VPackValueType::Int || lhsType == VPackValueType::SmallInt) { // use exact comparisons. no need to cast to double int64_t l = lhs.getIntUnchecked(); int64_t r = rhs.getIntUnchecked(); if (l == r) { return 0; } return (l < r ? -1 : 1); } if (lhsType == VPackValueType::UInt) { // use exact comparisons. no need to cast to double uint64_t l = lhs.getUIntUnchecked(); uint64_t r = rhs.getUIntUnchecked(); if (l == r) { return 0; } return (l < r ? -1 : 1); } // fallthrough to double comparison } double left = lhs.getNumericValue<double>(); double right = rhs.getNumericValue<double>(); if (left == right) { return 0; } return (left < right ? -1 : 1); } ////////////////////////////////////////////////////////////////////////////// /// @brief compares two VelocyPack string values ////////////////////////////////////////////////////////////////////////////// int VelocyPackHelper::compareStringValues(char const* left, VPackValueLength nl, char const* right, VPackValueLength nr, bool useUTF8) { int res; if (useUTF8) { res = TRI_compare_utf8(left, static_cast<size_t>(nl), right, static_cast<size_t>(nr)); } else { size_t len = static_cast<size_t>(nl < nr ? nl : nr); res = memcmp(left, right, len); } if (res < 0) { return -1; } if (res > 0) { return 1; } // res == 0 if (nl == nr) { return 0; } // res == 0, but different string lengths return nl < nr ? -1 : 1; } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a boolean sub-element, or a default if it is does not exist //////////////////////////////////////////////////////////////////////////////// bool VelocyPackHelper::getBooleanValue(VPackSlice const& slice, char const* name, bool defaultValue) { TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { return defaultValue; } VPackSlice const& sub = slice.get(name); if (sub.isBoolean()) { return sub.getBool(); } return defaultValue; } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a string sub-element, or throws if <name> does not exist /// or it is not a string //////////////////////////////////////////////////////////////////////////////// std::string VelocyPackHelper::checkAndGetStringValue(VPackSlice const& slice, char const* name) { TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { std::string msg = "The attribute '" + std::string(name) + "' was not found."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } VPackSlice const sub = slice.get(name); if (!sub.isString()) { std::string msg = "The attribute '" + std::string(name) + "' is not a string."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } return sub.copyString(); } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a string sub-element, or throws if <name> does not exist /// or it is not a string //////////////////////////////////////////////////////////////////////////////// std::string VelocyPackHelper::checkAndGetStringValue(VPackSlice const& slice, std::string const& name) { TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { std::string msg = "The attribute '" + name + "' was not found."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } VPackSlice const sub = slice.get(name); if (!sub.isString()) { std::string msg = "The attribute '" + name + "' is not a string."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } return sub.copyString(); } void VelocyPackHelper::ensureStringValue(VPackSlice const& slice, std::string const& name) { TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { std::string msg = "The attribute '" + name + "' was not found."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } VPackSlice const sub = slice.get(name); if (!sub.isString()) { std::string msg = "The attribute '" + name + "' is not a string."; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, msg); } } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a string value, or the default value if it is not a string //////////////////////////////////////////////////////////////////////////////// std::string VelocyPackHelper::getStringValue(VPackSlice const& slice, std::string const& defaultValue) { if (!slice.isString()) { return defaultValue; } return slice.copyString(); } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a string sub-element, or the default value if it does not /// exist /// or it is not a string //////////////////////////////////////////////////////////////////////////////// std::string VelocyPackHelper::getStringValue(VPackSlice slice, char const* name, std::string const& defaultValue) { if (slice.isExternal()) { slice = VPackSlice(slice.getExternal()); } TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { return defaultValue; } VPackSlice const sub = slice.get(name); if (!sub.isString()) { return defaultValue; } return sub.copyString(); } //////////////////////////////////////////////////////////////////////////////// /// @brief returns a string sub-element, or the default value if it does not /// exist /// or it is not a string //////////////////////////////////////////////////////////////////////////////// std::string VelocyPackHelper::getStringValue(VPackSlice slice, std::string const& name, std::string const& defaultValue) { if (slice.isExternal()) { slice = VPackSlice(slice.getExternal()); } TRI_ASSERT(slice.isObject()); if (!slice.hasKey(name)) { return defaultValue; } VPackSlice const sub = slice.get(name); if (!sub.isString()) { return defaultValue; } return sub.copyString(); } uint64_t VelocyPackHelper::stringUInt64(VPackSlice const& slice) { if (slice.isString()) { return arangodb::basics::StringUtils::uint64(slice.copyString()); } if (slice.isNumber()) { return slice.getNumericValue<uint64_t>(); } return 0; } //////////////////////////////////////////////////////////////////////////////// /// @brief parses a json file to VelocyPack //////////////////////////////////////////////////////////////////////////////// std::shared_ptr<VPackBuilder> VelocyPackHelper::velocyPackFromFile( std::string const& path) { size_t length; char* content = TRI_SlurpFile(TRI_UNKNOWN_MEM_ZONE, path.c_str(), &length); if (content != nullptr) { // The Parser might throw; std::shared_ptr<VPackBuilder> b; try { auto b = VPackParser::fromJson(reinterpret_cast<uint8_t const*>(content), length); TRI_Free(TRI_UNKNOWN_MEM_ZONE, content); return b; } catch (...) { TRI_Free(TRI_UNKNOWN_MEM_ZONE, content); throw; } } THROW_ARANGO_EXCEPTION(TRI_errno()); } static bool PrintVelocyPack(int fd, VPackSlice const& slice, bool appendNewline) { if (slice.isNone()) { // sanity check return false; } arangodb::basics::StringBuffer buffer(TRI_UNKNOWN_MEM_ZONE); arangodb::basics::VPackStringBufferAdapter bufferAdapter( buffer.stringBuffer()); try { VPackDumper dumper(&bufferAdapter); dumper.dump(slice); } catch (...) { // Writing failed return false; } if (buffer.length() == 0) { // should not happen return false; } if (appendNewline) { // add the newline here so we only need one write operation in the ideal // case buffer.appendChar('\n'); } char const* p = buffer.begin(); size_t n = buffer.length(); while (0 < n) { ssize_t m = TRI_WRITE(fd, p, (TRI_write_t)n); if (m <= 0) { return false; } n -= m; p += m; } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief writes a VelocyPack to a file //////////////////////////////////////////////////////////////////////////////// bool VelocyPackHelper::velocyPackToFile(std::string const& filename, VPackSlice const& slice, bool syncFile) { std::string const tmp = filename + ".tmp"; // remove a potentially existing temporary file if (TRI_ExistsFile(tmp.c_str())) { TRI_UnlinkFile(tmp.c_str()); } int fd = TRI_TRACKED_CREATE_FILE(tmp.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR | TRI_O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (fd < 0) { TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "cannot create json file '" << tmp << "': " << TRI_LAST_ERROR_STR; return false; } if (!PrintVelocyPack(fd, slice, true)) { TRI_TRACKED_CLOSE_FILE(fd); TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "cannot write to json file '" << tmp << "': " << TRI_LAST_ERROR_STR; TRI_UnlinkFile(tmp.c_str()); return false; } if (syncFile) { LOG_TOPIC(TRACE, arangodb::Logger::FIXME) << "syncing tmp file '" << tmp << "'"; if (!TRI_fsync(fd)) { TRI_TRACKED_CLOSE_FILE(fd); TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "cannot sync saved json '" << tmp << "': " << TRI_LAST_ERROR_STR; TRI_UnlinkFile(tmp.c_str()); return false; } } int res = TRI_TRACKED_CLOSE_FILE(fd); if (res < 0) { TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "cannot close saved file '" << tmp << "': " << TRI_LAST_ERROR_STR; TRI_UnlinkFile(tmp.c_str()); return false; } res = TRI_RenameFile(tmp.c_str(), filename.c_str()); if (res != TRI_ERROR_NO_ERROR) { TRI_set_errno(res); LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "cannot rename saved file '" << tmp << "' to '" << filename << "': " << TRI_LAST_ERROR_STR; TRI_UnlinkFile(tmp.c_str()); return false; } return true; } int VelocyPackHelper::compare(VPackSlice lhs, VPackSlice rhs, bool useUTF8, VPackOptions const* options, VPackSlice const* lhsBase, VPackSlice const* rhsBase) { { // will resolve externals and modify both lhs & rhs... int8_t lWeight = TypeWeight(lhs); int8_t rWeight = TypeWeight(rhs); if (lWeight < rWeight) { return -1; } if (lWeight > rWeight) { return 1; } TRI_ASSERT(lWeight == rWeight); } // lhs and rhs have equal weights // note that the following code would be redundant because it was already // checked that lhs & rhs have the same TypeWeight, which is 0 for none. // and for TypeWeight 0 we always return value 0 // if (lhs.isNone() || rhs.isNone()) { // // if rhs is none. we cannot be sure here that both are nones. // // there can also exist the situation that lhs is a none and rhs is a // // null value // // (or vice versa). Anyway, the compare value is the same for both, // return 0; // } auto lhsType = lhs.type(); switch (lhsType) { case VPackValueType::Null: return 0; case VPackValueType::Bool: { bool left = lhs.getBoolean(); bool right = rhs.getBoolean(); if (left == right) { return 0; } if (!left) { return -1; } return 1; } case VPackValueType::Double: case VPackValueType::Int: case VPackValueType::UInt: case VPackValueType::SmallInt: { return compareNumberValues(lhsType, lhs, rhs); } case VPackValueType::String: { VPackValueLength nl; char const* left = lhs.getString(nl); TRI_ASSERT(left != nullptr); VPackValueLength nr; char const* right = rhs.getString(nr); TRI_ASSERT(right != nullptr); return compareStringValues(left, nl, right, nr, useUTF8); } case VPackValueType::Custom: { if (lhsBase == nullptr || rhsBase == nullptr || options == nullptr || options->customTypeHandler == nullptr) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "Could not extract custom attribute."); } std::string lhsString(options->customTypeHandler->toString(lhs, options, *lhsBase)); char const* left = lhsString.data(); VPackValueLength nl = lhsString.size(); TRI_ASSERT(left != nullptr); std::string rhsString(options->customTypeHandler->toString(rhs, options, *rhsBase)); char const* right = rhsString.data(); VPackValueLength nr = rhsString.size(); TRI_ASSERT(right != nullptr); return compareStringValues(left, nl, right, nr, useUTF8); } case VPackValueType::Array: { VPackArrayIterator al(lhs); VPackArrayIterator ar(rhs); VPackValueLength const n = (std::max)(al.size(), ar.size()); for (VPackValueLength i = 0; i < n; ++i) { VPackSlice lhsValue; VPackSlice rhsValue; if (i < al.size()) { lhsValue = al.value(); al.next(); } if (i < ar.size()) { rhsValue = ar.value(); ar.next(); } int result = compare(lhsValue, rhsValue, useUTF8, options, &lhs, &rhs); if (result != 0) { return result; } } return 0; } case VPackValueType::Object: { if (useUTF8) { // must sort attributes by proper UTF8 values // this is expensive std::set<std::string, AttributeSorterUTF8> keys; VPackCollection::keys(lhs, keys); VPackCollection::keys(rhs, keys); for (auto const& key : keys) { VPackSlice lhsValue = lhs.get(key).resolveExternal(); if (lhsValue.isNone()) { // not present => null lhsValue = VPackSlice::nullSlice(); } VPackSlice rhsValue = rhs.get(key).resolveExternal(); if (rhsValue.isNone()) { // not present => null rhsValue = VPackSlice::nullSlice(); } int result = compare(lhsValue, rhsValue, useUTF8, options, &lhs, &rhs); if (result != 0) { return result; } } } else { // no UTF8-awareness is required here. do a quick and dirty comparison std::set<std::string> keys; VPackCollection::unorderedKeys(lhs, keys); VPackCollection::unorderedKeys(rhs, keys); for (auto const& key : keys) { VPackSlice lhsValue = lhs.get(key).resolveExternal(); if (lhsValue.isNone()) { // not present => null lhsValue = VPackSlice::nullSlice(); } VPackSlice rhsValue = rhs.get(key).resolveExternal(); if (rhsValue.isNone()) { // not present => null rhsValue = VPackSlice::nullSlice(); } int result = compare(lhsValue, rhsValue, useUTF8, options, &lhs, &rhs); if (result != 0) { return result; } } } return 0; } case VPackValueType::Illegal: case VPackValueType::MinKey: case VPackValueType::MaxKey: case VPackValueType::None: // uncommon cases are compared at the end return 0; default: // Contains all other ValueTypes of VelocyPack. // They are not used in ArangoDB so this cannot occur TRI_ASSERT(false); return 0; } } VPackBuilder VelocyPackHelper::merge(VPackSlice const& lhs, VPackSlice const& rhs, bool nullMeansRemove, bool mergeObjects) { return VPackCollection::merge(lhs, rhs, mergeObjects, nullMeansRemove); } double VelocyPackHelper::toDouble(VPackSlice const& slice, bool& failed) { TRI_ASSERT(!slice.isNone()); failed = false; switch (slice.type()) { case VPackValueType::None: case VPackValueType::Null: return 0.0; case VPackValueType::Bool: return (slice.getBoolean() ? 1.0 : 0.0); case VPackValueType::Double: case VPackValueType::Int: case VPackValueType::UInt: case VPackValueType::SmallInt: return slice.getNumericValue<double>(); case VPackValueType::String: { std::string tmp(slice.copyString()); try { // try converting string to number return std::stod(tmp); } catch (...) { if (tmp.empty()) { return 0.0; } // conversion failed } break; } case VPackValueType::Array: { VPackValueLength const n = slice.length(); if (n == 0) { return 0.0; } else if (n == 1) { return VelocyPackHelper::toDouble(slice.at(0).resolveExternal(), failed); } break; } case VPackValueType::External: { return VelocyPackHelper::toDouble(slice.resolveExternal(), failed); } case VPackValueType::Illegal: case VPackValueType::Object: case VPackValueType::UTCDate: case VPackValueType::MinKey: case VPackValueType::MaxKey: case VPackValueType::Binary: case VPackValueType::BCD: case VPackValueType::Custom: break; } failed = true; return 0.0; } // modify a VPack double value in place void VelocyPackHelper::patchDouble(VPackSlice slice, double value) { TRI_ASSERT(slice.isDouble()); // get pointer to the start of the value uint8_t* p = const_cast<uint8_t*>(slice.begin()); // skip one byte for the header and overwrite #ifndef TRI_UNALIGNED_ACCESS // some architectures do not support unaligned writes, then copy bytewise uint64_t dv; memcpy(&dv, &value, sizeof(double)); VPackValueLength vSize = sizeof(double); for (uint64_t x = dv; vSize > 0; vSize--) { *(++p) = x & 0xff; x >>= 8; } #else // other platforms support unaligned writes *reinterpret_cast<double*>(p + 1) = value; #endif } #ifndef USE_ENTERPRISE uint64_t VelocyPackHelper::hashByAttributes( VPackSlice slice, std::vector<std::string> const& attributes, bool docComplete, int& error, std::string const& key) { uint64_t hash = TRI_FnvHashBlockInitial(); error = TRI_ERROR_NO_ERROR; slice = slice.resolveExternal(); if (slice.isObject()) { for (auto const& attr : attributes) { VPackSlice sub = slice.get(attr).resolveExternal(); VPackBuilder temporaryBuilder; if (sub.isNone()) { if (attr == StaticStrings::KeyString && !key.empty()) { temporaryBuilder.add(VPackValue(key)); sub = temporaryBuilder.slice(); } else { if (!docComplete) { error = TRI_ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN; } // Null is equal to None/not present sub = VPackSlice::nullSlice(); } } hash = sub.normalizedHash(hash); } } else if (slice.isString() && attributes.size() == 1 && attributes[0] == StaticStrings::KeyString) { arangodb::StringRef subKey(slice); size_t pos = subKey.find('/'); if (pos != std::string::npos) { // We have an _id. Split it. subKey = subKey.substr(pos + 1); VPackBuilder temporaryBuilder; temporaryBuilder.add(VPackValuePair(subKey.data(), subKey.length(), VPackValueType::String)); VPackSlice tmp = temporaryBuilder.slice(); hash = tmp.normalizedHash(hash); } else { hash = slice.normalizedHash(hash); } } return hash; } #endif bool VelocyPackHelper::hasNonClientTypes(VPackSlice input, bool checkExternals, bool checkCustom) { if (input.isExternal()) { return checkExternals; } else if (input.isCustom()) { return checkCustom; } else if (input.isObject()) { for (auto const& it : VPackObjectIterator(input, true)) { if (hasNonClientTypes(it.value, checkExternals, checkCustom)) { return true; } } } else if (input.isArray()) { for (auto const& it : VPackArrayIterator(input)) { if (hasNonClientTypes(it, checkExternals, checkCustom)) { return true; } } } return false; } void VelocyPackHelper::sanitizeNonClientTypes(VPackSlice input, VPackSlice base, VPackBuilder& output, VPackOptions const* options, bool sanitizeExternals, bool sanitizeCustom) { if (sanitizeExternals && input.isExternal()) { // recursively resolve externals sanitizeNonClientTypes(input.resolveExternal(), base, output, options, sanitizeExternals, sanitizeCustom); } else if (sanitizeCustom && input.isCustom()) { if (options == nullptr || options->customTypeHandler == nullptr) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "cannot sanitize vpack without custom type handler"); } std::string custom = options->customTypeHandler->toString(input, options, base); output.add(VPackValue(custom)); } else if (input.isObject()) { output.openObject(); for (auto const& it : VPackObjectIterator(input)) { VPackValueLength l; char const* p = it.key.getString(l); output.add(VPackValuePair(p, l, VPackValueType::String)); sanitizeNonClientTypes(it.value, input, output, options, sanitizeExternals, sanitizeCustom); } output.close(); } else if (input.isArray()) { output.openArray(); for (auto const& it : VPackArrayIterator(input)) { sanitizeNonClientTypes(it, input, output, options, sanitizeExternals, sanitizeCustom); } output.close(); } else { output.add(input); } } VPackBuffer<uint8_t> VelocyPackHelper::sanitizeNonClientTypesChecked( VPackSlice input, VPackOptions const* options, bool sanitizeExternals, bool sanitizeCustom) { VPackBuffer<uint8_t> buffer; VPackBuilder builder(buffer, options); bool resolveExt = true; if (sanitizeExternals) { resolveExt = hasNonClientTypes(input, sanitizeExternals, sanitizeCustom); } if (resolveExt) { // resolve buffer.reserve(input.byteSize()); // reserve space already sanitizeNonClientTypes(input, VPackSlice::noneSlice(), builder, options, sanitizeExternals, sanitizeCustom); } else { builder.add(input); } return buffer; // elided } /// @brief extract the collection id from VelocyPack uint64_t VelocyPackHelper::extractIdValue(VPackSlice const& slice) { if (!slice.isObject()) { return 0; } VPackSlice id = slice.get("id"); if (id.isNone()) { // pre-3.1 compatibility id = slice.get("cid"); } if (id.isString()) { // string cid, e.g. "9988488" return StringUtils::uint64(id.copyString()); } else if (id.isNumber()) { // numeric cid, e.g. 9988488 return id.getNumericValue<uint64_t>(); } else if (!id.isNone()) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, "invalid value for 'id' attribute"); } TRI_ASSERT(id.isNone()); return 0; } arangodb::LoggerStream& operator<<(arangodb::LoggerStream& logger, VPackSlice const& slice) { size_t const cutoff = 100; std::string sliceStr(slice.toJson()); bool longer = sliceStr.size() > cutoff; if (longer) { logger << sliceStr.substr(cutoff) << "..."; } else { logger << sliceStr; } return logger; }
36.674067
136
0.564693
[ "object", "vector" ]
28c221dcff3469d46e851f63b0965eaf9c92329c
10,343
cpp
C++
BOSS/source/BuildOrderPlot.cpp
jccari/UABIntegral
5ea69309fd75ad6b6a9ed42d55aa1b27fa79bf30
[ "MIT" ]
523
2015-01-06T16:02:16.000Z
2022-03-30T22:54:13.000Z
source/BuildOrderPlot.cpp
lionax/BOSS
07d61299ba20d97f50a4b78195363ad20c32dd9b
[ "MIT" ]
40
2015-02-03T18:54:02.000Z
2021-11-02T15:18:07.000Z
source/BuildOrderPlot.cpp
lionax/BOSS
07d61299ba20d97f50a4b78195363ad20c32dd9b
[ "MIT" ]
233
2015-01-17T05:50:52.000Z
2022-03-30T22:52:08.000Z
#include "BuildOrderPlot.h" #include "Eval.h" using namespace BOSS; BuildOrderPlot::BuildOrderPlot(const GameState & initialState, const BuildOrder & buildOrder) : _initialState(initialState) , _buildOrder(buildOrder) , _boxHeight(20) , _boxHeightBuffer(3) , _maxLayer(0) , _maxFinishTime(0) { calculateStartEndTimes(); calculatePlot(); } void BuildOrderPlot::calculateStartEndTimes() { GameState state(_initialState); BOSS_ASSERT(_buildOrder.isLegalFromState(state), "Build order isn't legal!"); for (size_t i(0); i < _buildOrder.size(); ++i) { const ActionType & type = _buildOrder[i]; state.doAction(type); _startTimes.push_back(state.getCurrentFrame()); FrameCountType finish = state.getCurrentFrame() + type.buildTime(); if (type.isBuilding() && !type.isAddon() && !type.isMorphed()) { finish += Constants::BUILDING_PLACEMENT; } _finishTimes.push_back(finish); _maxFinishTime = std::max(_maxFinishTime, finish); _armyValues.push_back(Eval::ArmyTotalResourceSum(state)); std::pair<int, int> mineralsBefore(state.getCurrentFrame(), state.getMinerals() + type.mineralPrice()); std::pair<int, int> mineralsAfter(state.getCurrentFrame(), state.getMinerals()); std::pair<int, int> gasBefore(state.getCurrentFrame(), state.getGas() + type.gasPrice()); std::pair<int, int> gasAfter(state.getCurrentFrame(), state.getGas()); _minerals.push_back(mineralsBefore); _minerals.push_back(mineralsAfter); _gas.push_back(gasBefore); _gas.push_back(gasAfter); } } void BuildOrderPlot::calculatePlot() { _layers = std::vector<int>(_startTimes.size(), -1); // determine the layers for each action for (size_t i(0); i < _startTimes.size(); ++i) { FrameCountType start = _startTimes[i]; FrameCountType finish = _finishTimes[i]; std::vector<int> layerOverlap; // loop through everything up to this action and see which layers it can't be in for (size_t j(0); j < i; ++j) { if (start < _finishTimes[j]) { layerOverlap.push_back(_layers[j]); } } // find a layer we can assign to this value int layerTest = 0; while (true) { if (std::find(layerOverlap.begin(), layerOverlap.end(), layerTest) == layerOverlap.end()) { _layers[i] = layerTest; if (layerTest > _maxLayer) { _maxLayer = layerTest; } break; } layerTest++; } } for (size_t i(0); i < _buildOrder.size(); ++i) { Position topLeft(_startTimes[i], _layers[i] * (_boxHeight + _boxHeightBuffer)); Position bottomRight(_finishTimes[i], topLeft.y() + _boxHeight); _rectangles.push_back(Rectangle(_buildOrder[i].getShortName(), topLeft, bottomRight)); } } void BuildOrderPlot::addPlot(const BuildOrderPlot & plot) { _otherPlots.push_back(plot); } void BuildOrderPlot::writeResourcePlot(const std::string & filename) { std::string noext = RemoveFileExtension(filename); std::stringstream mineralss; for (size_t i(0); i < _minerals.size(); ++i) { mineralss << _minerals[i].first << " " << _minerals[i].second/Constants::RESOURCE_SCALE << std::endl; } std::stringstream gasss; for (size_t i(0); i < _gas.size(); ++i) { gasss << _gas[i].first << " " << _gas[i].second/Constants::RESOURCE_SCALE << std::endl; } WriteGnuPlot(noext + "_minerals", mineralss.str(), " with lines "); WriteGnuPlot(noext + "_gas", gasss.str(), " with lines "); } void BuildOrderPlot::writeRectanglePlot(const std::string & filename) { std::stringstream ss; int maxY = (_maxLayer + 1) * (_boxHeight + _boxHeightBuffer) + 15; for (size_t p(0); p < _otherPlots.size(); ++p) { maxY += (_otherPlots[p]._maxLayer + 2) * (_boxHeight + _boxHeightBuffer) + 15; } //ss << "set title \"Title Goes Here\"" << std::endl; //ss << "set xlabel \"Time (frames)\"" << std::endl; ss << "set style rect fc lt -1 fs transparent solid 0.15" << std::endl; ss << "set xrange [" << -(_maxFinishTime*.03) << ":" << 1.03*_maxFinishTime << "]" << std::endl; ss << "set yrange [-15:" << maxY << "]" << std::endl; ss << "unset ytics" << std::endl; ss << "set grid xtics" << std::endl; ss << "set nokey" << std::endl; //ss << "set size ratio " << (0.05 * _maxLayer) << std::endl; ss << "set terminal wxt size 960,300" << std::endl; ss << "plotHeight = " << 1000 << std::endl; ss << "boxHeight = " << _boxHeight << std::endl; ss << "boxHeightBuffer = " << _boxHeightBuffer << std::endl; ss << "boxWidthScale = " << 1.0 << std::endl; for (size_t i(0); i < _buildOrder.size(); ++i) { const Rectangle & rect = _rectangles[i]; const int rectWidth = (rect.bottomRight.x() - rect.topLeft.x()); const int rectCenterX = rect.bottomRight.x() - (rectWidth / 2); std::stringstream pos; pos << "(boxWidthScale * " << rectCenterX << "),"; pos << "((boxHeight + boxHeightBuffer) * " << _layers[i] << " + boxHeight/2)"; ss << "set object " << (i+1) << " rect at "; ss << pos.str(); ss << " size "; ss << "(boxWidthScale * " << (rectWidth) << "),"; ss << "(boxHeight) "; //ss << "(boxWidthScale * " << _finishTimes[i] << "),"; //ss << "((boxHeight + boxHeightBuffer) * " << _layers[i] << " + boxHeight) "; ss << "lw 1"; if (_buildOrder[i].isWorker()) { ss << " fc rgb \"cyan\""; } else if (_buildOrder[i].isSupplyProvider()) { ss << " fc rgb \"gold\""; } else if (_buildOrder[i].isRefinery()) { ss << " fc rgb \"green\""; } else if (_buildOrder[i].isBuilding()) { ss << " fc rgb \"brown\""; } else if (_buildOrder[i].isUpgrade()) { ss << " fc rgb \"purple\""; } else if (_buildOrder[i].isTech()) { ss << " fc rgb \"magenta\""; } ss << std::endl; ss << "set label " << (i+1) << " at " << pos.str() << " \"" << _buildOrder[i].getShortName() << "\" front center"; ss << std::endl; } int currentLayer = _maxLayer + 2; int currentObject = _buildOrder.size(); for (size_t p(0); p < _otherPlots.size(); ++p) { const BuildOrder & buildOrder = _otherPlots[p]._buildOrder; for (size_t i(0); i < buildOrder.size(); ++i) { const Rectangle & rect = _otherPlots[p]._rectangles[i]; const int rectWidth = (rect.bottomRight.x() - rect.topLeft.x()); const int rectCenterX = rect.bottomRight.x() - (rectWidth / 2); std::stringstream pos; pos << "(boxWidthScale * " << rectCenterX << "),"; pos << "((boxHeight + boxHeightBuffer) * " << (_otherPlots[p]._layers[i] + currentLayer) << " + boxHeight/2)"; ss << "set object " << (currentObject+i+1) << " rect at "; ss << pos.str(); ss << " size "; ss << "(boxWidthScale * " << (rectWidth) << "),"; ss << "(boxHeight) "; //ss << "(boxWidthScale * " << _finishTimes[i] << "),"; //ss << "((boxHeight + boxHeightBuffer) * " << _layers[i] << " + boxHeight) "; ss << "lw 1"; if (buildOrder[i].isWorker()) { ss << " fc rgb \"cyan\""; } else if (buildOrder[i].isSupplyProvider()) { ss << " fc rgb \"gold\""; } else if (buildOrder[i].isRefinery()) { ss << " fc rgb \"green\""; } else if (buildOrder[i].isBuilding()) { ss << " fc rgb \"brown\""; } else if (buildOrder[i].isUpgrade()) { ss << " fc rgb \"purple\""; } else if (buildOrder[i].isTech()) { ss << " fc rgb \"magenta\""; } ss << std::endl; ss << "set label " << (currentObject+i+1) << " at " << pos.str() << " \"" << buildOrder[i].getShortName() << "\" front center"; ss << std::endl; } currentLayer += _otherPlots[p]._maxLayer + 2; currentObject += buildOrder.size(); } ss << "plot -10000" << std::endl; std::ofstream out(filename); out << ss.str(); out.close(); } void BuildOrderPlot::writeArmyValuePlot(const std::string & filename) { std::stringstream datass; for (size_t i(0); i < _buildOrder.size(); ++i) { datass << _startTimes[i] << " " << _armyValues[i]/Constants::RESOURCE_SCALE << std::endl; } WriteGnuPlot(filename, datass.str(), " with steps"); } void BuildOrderPlot::WriteGnuPlot(const std::string & filename, const std::string & data, const std::string & args) { std::string file = RemoveFileExtension(GetFileNameFromPath(filename)); std::string noext = RemoveFileExtension(filename); std::ofstream dataout(noext + "_data.txt"); dataout << data; dataout.close(); std::stringstream ss; ss << "set xlabel \"Time (frames)\"" << std::endl; ss << "set ylabel \"Resource Over Time\"" << std::endl; ss << "plot \"" << (file + "_data.txt") << "\" " << args << std::endl; std::ofstream out(noext + ".gpl"); out << ss.str(); out.close(); } std::string BuildOrderPlot::GetFileNameFromPath(const std::string & path) { std::string temp(path); const size_t last_slash_idx = temp.find_last_of("\\/"); if (std::string::npos != last_slash_idx) { temp.erase(0, last_slash_idx + 1); } return temp; } std::string BuildOrderPlot::RemoveFileExtension(const std::string & path) { std::string temp(path); const size_t period_idx = temp.rfind('.'); if (std::string::npos != period_idx) { temp.erase(period_idx); } return temp; }
31.629969
139
0.538142
[ "object", "vector", "solid" ]
28c2ed298413015719208f70b9d8bac27b113c88
8,987
cpp
C++
disc-fe/test/evaluator_tests/normals.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
disc-fe/test/evaluator_tests/normals.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
disc-fe/test/evaluator_tests/normals.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
// @HEADER // *********************************************************************** // // Panzer: A partial differential equation assembly // engine for strongly coupled complex multiphysics systems // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and // Eric C. Cyr (eccyr@sandia.gov) // *********************************************************************** // @HEADER #include <Teuchos_ConfigDefs.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_TimeMonitor.hpp> using Teuchos::RCP; using Teuchos::rcp; #include "Teuchos_DefaultComm.hpp" #include "Teuchos_GlobalMPISession.hpp" #include "Teuchos_DefaultMpiComm.hpp" #include "Teuchos_OpaqueWrapper.hpp" #include "Kokkos_View_Fad.hpp" #include "PanzerDiscFE_config.hpp" #include "Panzer_IntegrationRule.hpp" #include "Panzer_CellData.hpp" #include "Panzer_Workset.hpp" #include "Panzer_Traits.hpp" #include "Panzer_CommonArrayFactories.hpp" #include "Panzer_Normals.hpp" #include "Phalanx_FieldManager.hpp" #include "Epetra_MpiComm.h" #include "Epetra_Comm.h" // for making explicit instantiated tests easier #define UNIT_TEST_GROUP(TYPE) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT(normals,test2d,TYPE) namespace panzer { TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL(normals,test2d,EvalType) { // build global (or serial communicator) #ifdef HAVE_MPI Teuchos::RCP<Epetra_Comm> eComm = Teuchos::rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else Teuchos::RCP<Epetra_Comm> eComm = Teuchos::rcp(new Epetra_SerialComm()); #endif using Teuchos::RCP; using Teuchos::rcp; using Teuchos::rcp_dynamic_cast; // panzer::pauseToAttach(); // build a dummy workset ////////////////////////////////////////////////////////// // typedef Kokkos::DynRankView<double,PHX::Device> FieldArray; int numCells = 2, numVerts = 4, dim = 2; Teuchos::RCP<panzer::Workset> workset = Teuchos::rcp(new panzer::Workset); // FieldArray & coords = workset->cell_vertex_coordinates; // coords.resize(numCells,numVerts,dim); MDFieldArrayFactory af("",true); workset->cell_vertex_coordinates = af.buildStaticArray<double,Cell,NODE,Dim>("coords",numCells,numVerts,dim); Workset::CellCoordArray coords = workset->cell_vertex_coordinates; Kokkos::parallel_for(1, KOKKOS_LAMBDA (int) { coords(0,0,0) = 1.0; coords(0,0,1) = 0.0; coords(0,1,0) = 1.0; coords(0,1,1) = 1.0; coords(0,2,0) = 0.0; coords(0,2,1) = 1.0; coords(0,3,0) = 0.0; coords(0,3,1) = 0.0; coords(1,0,0) = 1.0; coords(1,0,1) = 1.0; coords(1,1,0) = 2.0; coords(1,1,1) = 2.0; coords(1,2,0) = 1.0; coords(1,2,1) = 3.0; coords(1,3,0) = 0.0; coords(1,3,1) = 2.0; }); Teuchos::RCP<shards::CellTopology> topo = Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData< shards::Quadrilateral<4> >())); int quadOrder = 5; panzer::CellData cellData(2,1,topo); Teuchos::RCP<panzer::IntegrationRule> quadRule = Teuchos::rcp(new panzer::IntegrationRule(quadOrder,cellData)); out << "num quad points = " << quadRule->num_points << std::endl; Teuchos::RCP<panzer::IntegrationValues2<double> > quadValues = Teuchos::rcp(new panzer::IntegrationValues2<double>("",true)); quadValues->setupArrays(quadRule); quadValues->evaluateValues(coords); workset->cell_local_ids.push_back(0); workset->cell_local_ids.push_back(1); workset->num_cells = numCells; workset->block_id = "eblock-0_0"; workset->ir_degrees = Teuchos::rcp(new std::vector<int>); workset->ir_degrees->push_back(quadRule->cubature_degree); workset->int_rules.push_back(quadValues); Teuchos::RCP<PHX::FieldManager<panzer::Traits> > fm = Teuchos::rcp(new PHX::FieldManager<panzer::Traits>); // typedef panzer::Traits::Residual EvalType; typedef Sacado::ScalarValue<typename EvalType::ScalarT> ScalarValue; Teuchos::RCP<PHX::MDField<typename EvalType::ScalarT,panzer::Cell,panzer::Point,panzer::Dim> > normalsPtr; { Teuchos::ParameterList p; p.set("Name","Norms"); p.set("IR",quadRule); p.set("Side ID",1); RCP<panzer::Normals<EvalType,panzer::Traits> > normEval = rcp(new panzer::Normals<EvalType,panzer::Traits>(p)); RCP<PHX::Evaluator<panzer::Traits> > eval = normEval; fm->registerEvaluator<EvalType>(eval); fm->requireField<EvalType>(normEval->getFieldTag()); const PHX::FieldTag & ft = normEval->getFieldTag(); normalsPtr = rcp(new PHX::MDField<typename EvalType::ScalarT,panzer::Cell,panzer::Point,panzer::Dim>(ft.name(),quadRule->dl_vector)); } PHX::MDField<typename EvalType::ScalarT,panzer::Cell,panzer::Point,panzer::Dim> & normals = *normalsPtr; panzer::Traits::SD setupData; { auto worksets = rcp(new std::vector<panzer::Workset>); worksets->push_back(*workset); setupData.worksets_ = worksets; } std::vector<PHX::index_size_type> derivative_dimensions; derivative_dimensions.push_back(4); fm->setKokkosExtendedDataTypeDimensions<panzer::Traits::Jacobian>(derivative_dimensions); #ifdef Panzer_BUILD_HESSIAN_SUPPORT fm->setKokkosExtendedDataTypeDimensions<panzer::Traits::Hessian>(derivative_dimensions); #endif fm->postRegistrationSetup(setupData); panzer::Traits::PED preEvalData; fm->preEvaluate<EvalType>(preEvalData); fm->evaluateFields<EvalType>(*workset); fm->postEvaluate<EvalType>(0); fm->getFieldData<EvalType>(normals); TEST_EQUALITY(normals.rank(),3); TEST_EQUALITY(static_cast<int>(normals.size()),numCells*quadRule->num_points*dim); auto normals_v = normals.get_static_view(); auto normals_h = Kokkos::create_mirror_view ( normals_v); Kokkos::deep_copy(normals_h, normals_v); normals.print(out,false); for(int i=0;i<numCells;i++) { // useful for checking if normals are consistent: transformation is // affine! double nx0 = ScalarValue::eval(normals_h(i,0,0)); double ny0 = ScalarValue::eval(normals_h(i,0,1)); for(int v=0;v<quadRule->num_points;v++) { double nx = ScalarValue::eval(normals_h(i,v,0)); double ny = ScalarValue::eval(normals_h(i,v,1)); TEST_FLOATING_EQUALITY(nx*nx+ny*ny,1.0,1e-15); // check point consistency TEST_FLOATING_EQUALITY(nx,nx0,1e-15); TEST_FLOATING_EQUALITY(ny,ny0,1e-15); } } // check cell 0 { double nx = ScalarValue::eval(normals_h(0,0,0)); double ny = ScalarValue::eval(normals_h(0,0,1)); TEST_FLOATING_EQUALITY(nx,0.0,1e-15); TEST_FLOATING_EQUALITY(ny,1.0,1e-15); } // check cell 1 { double nx = ScalarValue::eval(normals_h(1,0,0)); double ny = ScalarValue::eval(normals_h(1,0,1)); double sqrt2 = std::sqrt(2.0); TEST_FLOATING_EQUALITY(nx,1.0/sqrt2,1e-15); TEST_FLOATING_EQUALITY(ny,1.0/sqrt2,1e-15); } } typedef Traits::Residual ResidualType; typedef Traits::Jacobian JacobianType; UNIT_TEST_GROUP(ResidualType) UNIT_TEST_GROUP(JacobianType) #ifdef Panzer_BUILD_HESSIAN_SUPPORT typedef Traits::Hessian HessianType; UNIT_TEST_GROUP(HessianType) #endif }
37.60251
128
0.683988
[ "vector" ]
28c3037a42826069beb44fbbc0bc15ad96874d72
10,014
cc
C++
chrome/browser/win/ui_automation_util.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/win/ui_automation_util.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/win/ui_automation_util.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/win/ui_automation_util.h" #include <algorithm> #include <iterator> #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/win/scoped_variant.h" base::string16 GetCachedBstrValue(IUIAutomationElement* element, PROPERTYID property_id) { HRESULT result = S_OK; base::win::ScopedVariant var; result = element->GetCachedPropertyValueEx(property_id, TRUE, var.Receive()); if (FAILED(result)) return base::string16(); if (V_VT(var.ptr()) != VT_BSTR) { LOG_IF(ERROR, V_VT(var.ptr()) != VT_UNKNOWN) << __func__ << " property is not a BSTR: " << V_VT(var.ptr()); return base::string16(); } return base::string16(V_BSTR(var.ptr())); } bool GetCachedBoolValue(IUIAutomationElement* element, PROPERTYID property_id) { #if DCHECK_IS_ON() base::win::ScopedVariant var; if (FAILED(element->GetCachedPropertyValueEx(property_id, TRUE, var.Receive()))) { return false; } if (V_VT(var.ptr()) != VT_BOOL) { LOG_IF(ERROR, V_VT(var.ptr()) != VT_UNKNOWN) << __func__ << " property is not a BOOL: " << V_VT(var.ptr()); return false; } return V_BOOL(var.ptr()) != 0; #else // DCHECK_IS_ON() return false; #endif // !DCHECK_IS_ON() } int32_t GetCachedInt32Value(IUIAutomationElement* element, PROPERTYID property_id) { #if DCHECK_IS_ON() base::win::ScopedVariant var; if (FAILED(element->GetCachedPropertyValueEx(property_id, TRUE, var.Receive()))) { return false; } if (V_VT(var.ptr()) != VT_I4) { LOG_IF(ERROR, V_VT(var.ptr()) != VT_UNKNOWN) << __func__ << " property is not an I4: " << V_VT(var.ptr()); return false; } return V_I4(var.ptr()); #else // DCHECK_IS_ON() return 0; #endif // !DCHECK_IS_ON() } std::vector<int32_t> GetCachedInt32ArrayValue(IUIAutomationElement* element, PROPERTYID property_id) { std::vector<int32_t> values; #if DCHECK_IS_ON() base::win::ScopedVariant var; if (FAILED(element->GetCachedPropertyValueEx(property_id, TRUE, var.Receive()))) { return values; } if (V_VT(var.ptr()) != (VT_I4 | VT_ARRAY)) { LOG_IF(ERROR, V_VT(var.ptr()) != VT_UNKNOWN) << __func__ << " property is not an I4 array: " << V_VT(var.ptr()); return values; } SAFEARRAY* array = V_ARRAY(var.ptr()); if (SafeArrayGetDim(array) != 1) return values; long lower_bound = 0; long upper_bound = 0; SafeArrayGetLBound(array, 1, &lower_bound); SafeArrayGetUBound(array, 1, &upper_bound); if (lower_bound || upper_bound <= lower_bound) return values; int32_t* data = nullptr; SafeArrayAccessData(array, reinterpret_cast<void**>(&data)); values.assign(data, data + upper_bound + 1); SafeArrayUnaccessData(array); #endif // DCHECK_IS_ON() return values; } std::string IntArrayToString(const std::vector<int32_t>& values) { #if DCHECK_IS_ON() std::vector<std::string> value_strings; std::transform(values.begin(), values.end(), std::back_inserter(value_strings), &base::IntToString); return base::JoinString(value_strings, ", "); #else // DCHECK_IS_ON() return std::string(); #endif // !DCHECK_IS_ON() } const char* GetEventName(EVENTID event_id) { #if DCHECK_IS_ON() switch (event_id) { case UIA_ToolTipOpenedEventId: return "UIA_ToolTipOpenedEventId"; case UIA_ToolTipClosedEventId: return "UIA_ToolTipClosedEventId"; case UIA_StructureChangedEventId: return "UIA_StructureChangedEventId"; case UIA_MenuOpenedEventId: return "UIA_MenuOpenedEventId"; case UIA_AutomationPropertyChangedEventId: return "UIA_AutomationPropertyChangedEventId"; case UIA_AutomationFocusChangedEventId: return "UIA_AutomationFocusChangedEventId"; case UIA_AsyncContentLoadedEventId: return "UIA_AsyncContentLoadedEventId"; case UIA_MenuClosedEventId: return "UIA_MenuClosedEventId"; case UIA_LayoutInvalidatedEventId: return "UIA_LayoutInvalidatedEventId"; case UIA_Invoke_InvokedEventId: return "UIA_Invoke_InvokedEventId"; case UIA_SelectionItem_ElementAddedToSelectionEventId: return "UIA_SelectionItem_ElementAddedToSelectionEventId"; case UIA_SelectionItem_ElementRemovedFromSelectionEventId: return "UIA_SelectionItem_ElementRemovedFromSelectionEventId"; case UIA_SelectionItem_ElementSelectedEventId: return "UIA_SelectionItem_ElementSelectedEventId"; case UIA_Selection_InvalidatedEventId: return "UIA_Selection_InvalidatedEventId"; case UIA_Text_TextSelectionChangedEventId: return "UIA_Text_TextSelectionChangedEventId"; case UIA_Text_TextChangedEventId: return "UIA_Text_TextChangedEventId"; case UIA_Window_WindowOpenedEventId: return "UIA_Window_WindowOpenedEventId"; case UIA_Window_WindowClosedEventId: return "UIA_Window_WindowClosedEventId"; case UIA_MenuModeStartEventId: return "UIA_MenuModeStartEventId"; case UIA_MenuModeEndEventId: return "UIA_MenuModeEndEventId"; case UIA_InputReachedTargetEventId: return "UIA_InputReachedTargetEventId"; case UIA_InputReachedOtherElementEventId: return "UIA_InputReachedOtherElementEventId"; case UIA_InputDiscardedEventId: return "UIA_InputDiscardedEventId"; case UIA_SystemAlertEventId: return "UIA_SystemAlertEventId"; case UIA_LiveRegionChangedEventId: return "UIA_LiveRegionChangedEventId"; case UIA_HostedFragmentRootsInvalidatedEventId: return "UIA_HostedFragmentRootsInvalidatedEventId"; case UIA_Drag_DragStartEventId: return "UIA_Drag_DragStartEventId"; case UIA_Drag_DragCancelEventId: return "UIA_Drag_DragCancelEventId"; case UIA_Drag_DragCompleteEventId: return "UIA_Drag_DragCompleteEventId"; case UIA_DropTarget_DragEnterEventId: return "UIA_DropTarget_DragEnterEventId"; case UIA_DropTarget_DragLeaveEventId: return "UIA_DropTarget_DragLeaveEventId"; case UIA_DropTarget_DroppedEventId: return "UIA_DropTarget_DroppedEventId"; case UIA_TextEdit_TextChangedEventId: return "UIA_TextEdit_TextChangedEventId"; case UIA_TextEdit_ConversionTargetChangedEventId: return "UIA_TextEdit_ConversionTargetChangedEventId"; } #endif // DCHECK_IS_ON() return ""; } const char* GetControlType(long control_type) { #if DCHECK_IS_ON() switch (control_type) { case UIA_ButtonControlTypeId: return "UIA_ButtonControlTypeId"; case UIA_CalendarControlTypeId: return "UIA_CalendarControlTypeId"; case UIA_CheckBoxControlTypeId: return "UIA_CheckBoxControlTypeId"; case UIA_ComboBoxControlTypeId: return "UIA_ComboBoxControlTypeId"; case UIA_EditControlTypeId: return "UIA_EditControlTypeId"; case UIA_HyperlinkControlTypeId: return "UIA_HyperlinkControlTypeId"; case UIA_ImageControlTypeId: return "UIA_ImageControlTypeId"; case UIA_ListItemControlTypeId: return "UIA_ListItemControlTypeId"; case UIA_ListControlTypeId: return "UIA_ListControlTypeId"; case UIA_MenuControlTypeId: return "UIA_MenuControlTypeId"; case UIA_MenuBarControlTypeId: return "UIA_MenuBarControlTypeId"; case UIA_MenuItemControlTypeId: return "UIA_MenuItemControlTypeId"; case UIA_ProgressBarControlTypeId: return "UIA_ProgressBarControlTypeId"; case UIA_RadioButtonControlTypeId: return "UIA_RadioButtonControlTypeId"; case UIA_ScrollBarControlTypeId: return "UIA_ScrollBarControlTypeId"; case UIA_SliderControlTypeId: return "UIA_SliderControlTypeId"; case UIA_SpinnerControlTypeId: return "UIA_SpinnerControlTypeId"; case UIA_StatusBarControlTypeId: return "UIA_StatusBarControlTypeId"; case UIA_TabControlTypeId: return "UIA_TabControlTypeId"; case UIA_TabItemControlTypeId: return "UIA_TabItemControlTypeId"; case UIA_TextControlTypeId: return "UIA_TextControlTypeId"; case UIA_ToolBarControlTypeId: return "UIA_ToolBarControlTypeId"; case UIA_ToolTipControlTypeId: return "UIA_ToolTipControlTypeId"; case UIA_TreeControlTypeId: return "UIA_TreeControlTypeId"; case UIA_TreeItemControlTypeId: return "UIA_TreeItemControlTypeId"; case UIA_CustomControlTypeId: return "UIA_CustomControlTypeId"; case UIA_GroupControlTypeId: return "UIA_GroupControlTypeId"; case UIA_ThumbControlTypeId: return "UIA_ThumbControlTypeId"; case UIA_DataGridControlTypeId: return "UIA_DataGridControlTypeId"; case UIA_DataItemControlTypeId: return "UIA_DataItemControlTypeId"; case UIA_DocumentControlTypeId: return "UIA_DocumentControlTypeId"; case UIA_SplitButtonControlTypeId: return "UIA_SplitButtonControlTypeId"; case UIA_WindowControlTypeId: return "UIA_WindowControlTypeId"; case UIA_PaneControlTypeId: return "UIA_PaneControlTypeId"; case UIA_HeaderControlTypeId: return "UIA_HeaderControlTypeId"; case UIA_HeaderItemControlTypeId: return "UIA_HeaderItemControlTypeId"; case UIA_TableControlTypeId: return "UIA_TableControlTypeId"; case UIA_TitleBarControlTypeId: return "UIA_TitleBarControlTypeId"; case UIA_SeparatorControlTypeId: return "UIA_SeparatorControlTypeId"; case UIA_SemanticZoomControlTypeId: return "UIA_SemanticZoomControlTypeId"; case UIA_AppBarControlTypeId: return "UIA_AppBarControlTypeId"; } #endif // DCHECK_IS_ON() return ""; }
35.013986
80
0.725185
[ "vector", "transform" ]
28c3bba3b5a5c566afafb8f0c32049cd34761f8b
24,333
cpp
C++
MNE/disp/helpers/chinfomodel.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
2
2017-04-20T20:21:16.000Z
2017-04-26T16:30:25.000Z
MNE/disp/helpers/chinfomodel.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
null
null
null
MNE/disp/helpers/chinfomodel.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
1
2017-04-23T15:55:31.000Z
2017-04-23T15:55:31.000Z
//============================================================================================================= /** * @file chinfomodel.cpp * @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * Jens Haueisen <jens.haueisen@tu-ilmenau.de> * @version 1.0 * @date November, 2014 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh, Matti Hamalainen and Jens Haueisen. 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 MNE-CPP authors 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. * * * @brief This class represents the channel info model of the model/view framework of mne_browse application. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "chinfomodel.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= ChInfoModel::ChInfoModel(FiffInfo::SPtr& pFiffInfo, QObject *parent) : QAbstractTableModel(parent) , m_pFiffInfo(pFiffInfo) { } //************************************************************************************************************* ChInfoModel::ChInfoModel(QObject *parent) : QAbstractTableModel(parent) , m_pFiffInfo(FiffInfo::SPtr(new FiffInfo)) { } //************************************************************************************************************* //virtual functions int ChInfoModel::rowCount(const QModelIndex & /*parent*/) const { //Return number of stored evoked sets if(!m_pFiffInfo->chs.size()==0) return m_pFiffInfo->chs.size(); else return 0; } //************************************************************************************************************* int ChInfoModel::columnCount(const QModelIndex & /*parent*/) const { return 13; } //************************************************************************************************************* QVariant ChInfoModel::headerData(int section, Qt::Orientation orientation, int role) const { if(role != Qt::DisplayRole && role != Qt::TextAlignmentRole) return QVariant(); switch(role) { case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; case Qt::DisplayRole: { //Return the number and description/comment of the fiff evoked data in the set as vertical header if(orientation == Qt::Vertical) if(section<m_pFiffInfo->chs.size()) return QString("Ch %1").arg(section); //Return the horizontal header if(orientation == Qt::Horizontal) { switch(section) { case 0: return QString("%1").arg("Data number"); break; case 1: return QString("%1").arg("Original name"); break; case 2: return QString("%1").arg("Alias"); break; case 3: return QString("%1").arg("Mapped layout name"); break; case 4: return QString("%1").arg("Channel kind"); break; case 5: return QString("%1").arg("MEG type"); break; case 6: return QString("%1").arg("Unit"); break; case 7: return QString("%1").arg("Position"); break; case 8: return QString("%1").arg("Digitizer (cm)"); break; case 9: return QString("%1").arg("Active filter"); break; case 10: return QString("%1").arg("Coil Type"); break; case 11: return QString("%1").arg("Bad channel"); break; case 12: return QString("%1").arg("# of Compensators"); break; } } } } return QVariant(); } //************************************************************************************************************* QVariant ChInfoModel::data(const QModelIndex &index, int role) const { if(index.row() >= m_pFiffInfo->chs.size()) return QVariant(); if (index.isValid()) { //******** first column (channel number - corresponds to row in fiff data matrix) ******** if(index.column()==0) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(index.row()); return v; case ChInfoModelRoles::GetChNumber: v.setValue(index.row()); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** second column (original channel name) ******** if(index.column()==1) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(QString("%1").arg(m_pFiffInfo->chs.at(index.row()).ch_name)); return v; case ChInfoModelRoles::GetOrigChName: v.setValue(QString("%1").arg(m_pFiffInfo->chs.at(index.row()).ch_name)); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** third column (channel alias) ******** if(index.column()==2) { QVariant v; switch(role) { case Qt::DisplayRole: if(index.row()<m_aliasNames.size()) v.setValue(QString("%1").arg(m_aliasNames.at(index.row()))); return v; case ChInfoModelRoles::GetChAlias: if(index.row()<m_aliasNames.size()) v.setValue(QString("%1").arg(m_aliasNames.at(index.row()))); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** fourth column (mapped layout channel name) ******** if(index.column()==3) { QVariant v; switch(role) { case Qt::DisplayRole: if(index.row()<m_mappedLayoutChNames.size()) v.setValue(QString("%1").arg(m_mappedLayoutChNames.at(index.row()))); return v; case ChInfoModelRoles::GetMappedLayoutChName: if(index.row()<m_mappedLayoutChNames.size()) v.setValue(QString("%1").arg(m_mappedLayoutChNames.at(index.row()))); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** fifth column (channel kind - MEG, EEG, etc) ******** if(index.column()==4) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(QString("%1").arg(m_pFiffInfo->chs.at(index.row()).kind)); return v; case ChInfoModelRoles::GetChKind: v.setValue(m_pFiffInfo->chs.at(index.row()).kind); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** sixth column (MEG type) ******** if(index.column()==5) { QVariant v; v.setValue(QString("%1").arg("non_MEG")); if(m_pFiffInfo->chs.at(index.row()).kind == FIFFV_MEG_CH) { qint32 unit = m_pFiffInfo->chs.at(index.row()).unit; if(unit == FIFF_UNIT_T_M) v.setValue(QString("MEG_grad")); else if(unit == FIFF_UNIT_T) v.setValue(QString("MEG_mag")); } switch(role) { case Qt::DisplayRole: return v; case ChInfoModelRoles::GetMEGType: return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** seventh column (channel unit) ******** if(index.column()==6) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(QString("%1").arg(m_pFiffInfo->chs.at(index.row()).unit)); return v; case ChInfoModelRoles::GetChUnit: v.setValue(m_pFiffInfo->chs.at(index.row()).unit); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** eigth column (channel layout position) ******** if(index.column()==7) { QVariant v; QPointF point = m_layoutMap[m_mappedLayoutChNames.at(index.row())]; switch(role) { case Qt::DisplayRole: v.setValue(QString("(%1|%2)").arg(point.x()).arg(point.y())); return v; case ChInfoModelRoles::GetChPosition: v.setValue(point); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** ninth column (channel digitizer position) ******** if(index.column()==8) { QVariant v; QVector3D point3D( m_pFiffInfo->chs.at(index.row()).chpos.r0[0] * 100, //convert to cm m_pFiffInfo->chs.at(index.row()).chpos.r0[1] * 100, m_pFiffInfo->chs.at(index.row()).chpos.r0[2] * 100 ); switch(role) { case Qt::DisplayRole: v.setValue(QString("(%1|%2|%3)").arg(point3D.x()).arg(point3D.y()).arg(point3D.z())); return v; case ChInfoModelRoles::GetChDigitizer: v.setValue(point3D); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** tenth column (active channel filter type) ******** if(index.column()==9) { QVariant v; // //Check if mne operator is a filter operator // QSharedPointer<MNEOperator> operatorPtr = m_assignedOperators.value(index.row(), QSharedPointer<MNEOperator>(new MNEOperator())); // QSharedPointer<FilterOperator> filterOperator; switch(role) { case Qt::DisplayRole: { return v; } // if(operatorPtr->m_OperatorType == MNEOperator::FILTER) { // filterOperator = operatorPtr.staticCast<FilterOperator>(); // } // else { // v.setValue(QString("%1").arg("none")); // return v; // } // switch(filterOperator->m_Type) { // case FilterOperator::LPF: { // v.setValue(QString("%1 | %2").arg("LP").arg(filterOperator->m_dCenterFreq*m_pFiffInfo->sfreq/2)); // return v; // } // case FilterOperator::HPF: { // v.setValue(QString("%1 | %2").arg("HP").arg(filterOperator->m_dCenterFreq*m_pFiffInfo->sfreq/2)); // return v; // } // case FilterOperator::BPF: { // double fsample = m_pFiffInfo->sfreq; // double low = (filterOperator->m_dCenterFreq*fsample/2) - (filterOperator->m_dBandwidth*fsample/4); // /4 because we also need to devide by 2 to get the nyquist freq // double high = (filterOperator->m_dCenterFreq*fsample/2) + (filterOperator->m_dBandwidth*fsample/4); // v.setValue(QString("%1 | %2 | %3").arg("BP").arg(low).arg(high)); // return v; // } // case FilterOperator::NOTCH: { // double fsample = m_pFiffInfo->sfreq; // double low = (filterOperator->m_dCenterFreq*fsample/2) - (filterOperator->m_dBandwidth*fsample/4); // double high = (filterOperator->m_dCenterFreq*fsample/2) + (filterOperator->m_dBandwidth*fsample/4); // v.setValue(QString("%1 | %2 | %3").arg("NOTCH").arg(low).arg(high)); // return v; // } // } // } // case ChInfoModelRoles::GetChActiveFilter: { // if(operatorPtr->m_OperatorType == MNEOperator::FILTER) { // filterOperator = operatorPtr.staticCast<FilterOperator>(); // } // else { // v.setValue(QString("%1").arg("none")); // return v; // } // v.setValue(operatorPtr); // return v; // } case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } } //******** eleventh column (coil type) ******** if(index.column()==10) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(QString("%1").arg(m_pFiffInfo->chs.at(index.row()).chpos.coil_type)); return v; case ChInfoModelRoles::GetChCoilType: v.setValue(m_pFiffInfo->chs.at(index.row()).chpos.coil_type); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** twelve column (channel bad) ******** if(index.column()==11) { QVariant v; bool isBad = false; QString chName = m_pFiffInfo->chs.at(index.row()).ch_name; switch(role) { case Qt::DisplayRole: isBad = m_pFiffInfo->bads.contains(chName); v.setValue(isBad); return v; case ChInfoModelRoles::GetIsBad: isBad = m_pFiffInfo->bads.contains(chName); v.setValue(isBad); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check //******** twelve column (compensators bad) ******** if(index.column()==12) { QVariant v; switch(role) { case Qt::DisplayRole: v.setValue(m_pFiffInfo->comps.size()); return v; case Qt::TextAlignmentRole: return Qt::AlignHCenter + Qt::AlignVCenter; } }//end column check } // end index.valid() check return QVariant(); } //************************************************************************************************************* bool ChInfoModel::insertRows(int position, int span, const QModelIndex & parent) { Q_UNUSED(position); Q_UNUSED(span); Q_UNUSED(parent); return true; } //************************************************************************************************************* bool ChInfoModel::removeRows(int position, int span, const QModelIndex & parent) { Q_UNUSED(position); Q_UNUSED(span); Q_UNUSED(parent); return true; } //************************************************************************************************************* Qt::ItemFlags ChInfoModel::flags(const QModelIndex & index) const { Q_UNUSED(index); return Qt::ItemIsEnabled | Qt::ItemIsSelectable /*| Qt::ItemIsEditable*/; } //************************************************************************************************************* bool ChInfoModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(index); Q_UNUSED(value); Q_UNUSED(role); return true; } //************************************************************************************************************* void ChInfoModel::fiffInfoChanged(FiffInfo::SPtr& pFiffInfo) { beginResetModel(); m_pFiffInfo = pFiffInfo; m_aliasNames = m_pFiffInfo->ch_names; m_mappedLayoutChNames = m_pFiffInfo->ch_names; mapLayoutToChannels(); endResetModel(); emit dataChanged(createIndex(0,0), createIndex(rowCount(), columnCount())); } //************************************************************************************************************* void ChInfoModel::assignedOperatorsChanged(const QMap<int,QSharedPointer<MNEOperator> > &assignedOperators) { beginResetModel(); m_assignedOperators = assignedOperators; endResetModel(); emit dataChanged(createIndex(0,0), createIndex(rowCount(), columnCount())); } //************************************************************************************************************* void ChInfoModel::layoutChanged(const QMap<QString,QPointF> &layoutMap) { beginResetModel(); m_layoutMap = layoutMap; m_aliasNames = m_pFiffInfo->ch_names; m_mappedLayoutChNames = m_pFiffInfo->ch_names; mapLayoutToChannels(); endResetModel(); emit dataChanged(createIndex(0,0), createIndex(rowCount(), columnCount())); } //************************************************************************************************************* const QStringList & ChInfoModel::getMappedChannelsList() { return m_mappedLayoutChNames; } //************************************************************************************************************* int ChInfoModel::getIndexFromOrigChName(QString chName) { return m_pFiffInfo->ch_names.indexOf(chName); } //************************************************************************************************************* int ChInfoModel::getIndexFromMappedChName(QString chName) { return m_mappedLayoutChNames.indexOf(chName); } //************************************************************************************************************* QStringList ChInfoModel::getBadChannelList() { return m_pFiffInfo->bads; } //************************************************************************************************************* void ChInfoModel::mapLayoutToChannels() { //TODO: Move this to layout loader in MNE-CPP Utils? //Map channels to layout QList<FiffChInfo> channelList = m_pFiffInfo->chs; for(int i = 0; i<channelList.size(); i++) { //Get current channel information FiffChInfo chInfo = channelList.at(i); QString chName = chInfo.ch_name; QRegExp regExpRemove; bool flagOk = false; switch(chInfo.kind) { case FIFFV_MEG_CH: //Scan for MEG string and other characters regExpRemove = QRegExp("(MEG|-|_|/|\| )"); chName.remove(regExpRemove); //After cleaning the string try to convert the residual to an int number flagOk = false; m_mappedLayoutChNames.replace(i, QString("%1 %2").arg("MEG").arg(chName)); break; case FIFFV_EEG_CH: { //Scan for EEG string and other characters regExpRemove = QRegExp("(EEG|-|_|/|\| )"); chName.remove(regExpRemove); //After cleaning the string try to convert the residual to an int number flagOk = false; m_mappedLayoutChNames.replace(i, QString("%1 %2").arg("EEG").arg(chName)); break; } } } //end fiff chs emit channelsMappedToLayout(m_mappedLayoutChNames); } //************************************************************************************************************* void ChInfoModel::clearModel() { beginResetModel(); m_pFiffInfo = FiffInfo::SPtr(new FiffInfo); m_layoutMap.clear(); m_aliasNames.clear(); m_mappedLayoutChNames.clear(); endResetModel(); qDebug("ChInfoModel cleared."); }
35.995562
195
0.440225
[ "model" ]
28c42595421386fadd4b5c3cfb91738fe9ef6479
1,078
cpp
C++
src/Source/Chunks/Shex/Tokens/ImmediateConstantBufferDeclarationToken.cpp
tgjones/slimshader-cpp
a1833e2eccf32cccfe33aa7613772503eca963ee
[ "MIT" ]
20
2015-03-29T02:14:03.000Z
2021-11-14T12:27:02.000Z
src/Source/Chunks/Shex/Tokens/ImmediateConstantBufferDeclarationToken.cpp
tgjones/slimshader-cpp
a1833e2eccf32cccfe33aa7613772503eca963ee
[ "MIT" ]
null
null
null
src/Source/Chunks/Shex/Tokens/ImmediateConstantBufferDeclarationToken.cpp
tgjones/slimshader-cpp
a1833e2eccf32cccfe33aa7613772503eca963ee
[ "MIT" ]
12
2015-05-04T06:39:10.000Z
2022-02-23T06:48:04.000Z
#include "PCH.h" #include "ImmediateConstantBufferDeclarationToken.h" #include "Decoder.h" using namespace std; using namespace SlimShader; shared_ptr<ImmediateConstantBufferDeclarationToken> ImmediateConstantBufferDeclarationToken::Parse(BytecodeReader& reader) { auto token0 = reader.ReadUInt32(); auto length = reader.ReadUInt32() - 2; auto result = shared_ptr<ImmediateConstantBufferDeclarationToken>(new ImmediateConstantBufferDeclarationToken()); result->_declarationLength = length; for (uint32_t i = 0; i < length; i++) result->_data.push_back(Number::Parse(reader, NumberType::Unknown)); return result; } const vector<Number>& ImmediateConstantBufferDeclarationToken::GetData() const { return _data; } void ImmediateConstantBufferDeclarationToken::Print(std::ostream& out) const { out << "dcl_immediateConstantBuffer { "; for (size_t i = 0; i < _data.size(); i += 4) { if (i > 0) out << ",\n" << string(30, ' '); out << "{ " << _data[i] << ", " << _data[i + 1] << ", " << _data[i + 2] << ", " << _data[i + 3] << "}"; } out << " }"; }
28.368421
122
0.691095
[ "vector" ]
28c578b2de963180af2a5b792264d6e0abf63a71
25,191
cpp
C++
ReactQt/runtime/src/reactflexlayout.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
15
2018-03-11T23:50:11.000Z
2021-12-24T08:41:05.000Z
ReactQt/runtime/src/reactflexlayout.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
ReactQt/runtime/src/reactflexlayout.cpp
dmgctrl/react-native-linux
3b05fb169f0242a9c6084064c26bccecf2a4aefa
[ "CC-BY-4.0", "BSD-3-Clause" ]
2
2018-04-14T19:47:35.000Z
2020-07-30T21:48:29.000Z
/** * Copyright (C) 2016, Canonical Ltd. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Author: Justin McPherson <justin.mcpherson@canonical.com> * */ #include <QQuickItem> extern "C" { #include "Layout.h" } #include "reactattachedproperties.h" #include "reactflexlayout.h" #include "reactvaluecoercion.h" namespace { static QMap<QString, ReactFlexLayout::Direction> directions{{"row", ReactFlexLayout::DirectionRow}, {"column", ReactFlexLayout::DirectionColumn}}; static QMap<QString, ReactFlexLayout::Alignment> alignments{{"flex-start", ReactFlexLayout::AlignmentFlexStart}, {"flex-end", ReactFlexLayout::AlignmentFlexEnd}, {"center", ReactFlexLayout::AlignmentCenter}, {"stretch", ReactFlexLayout::AlignmentStretch}}; static QMap<QString, ReactFlexLayout::Justify> justifys{{"flex-start", ReactFlexLayout::JustifyFlexStart}, {"flex-end", ReactFlexLayout::JustifyFlexEnd}, {"center", ReactFlexLayout::JustifyCenter}, {"space-between", ReactFlexLayout::JustifySpaceBetween}, {"space-around", ReactFlexLayout::JustifySpaceAround}}; static QMap<QString, ReactFlexLayout::Position> positions{{"absolute", ReactFlexLayout::PositionAbsolute}, {"relative", ReactFlexLayout::PositionRelative}}; static QMap<QString, ReactFlexLayout::Wrap> wraps{{"wrap", ReactFlexLayout::WrapYes}, {"nowrap", ReactFlexLayout::WrapNo}}; } class FlexPropertyHandler { public: FlexPropertyHandler() { const QMetaObject& metaObject = ReactFlexLayout::staticMetaObject; const int propertyCount = metaObject.propertyCount(); for (int i = metaObject.propertyOffset(); i < propertyCount; ++i) { QMetaProperty p = metaObject.property(i); m_properties.insert(p.name(), p); } } void applyProperties(ReactFlexLayout* fl, const QVariantMap& properties) { for (auto it = properties.constBegin(); it != properties.constEnd(); ++it) { QMap<QString, QMetaProperty>::iterator pi = m_properties.find(it.key()); if (pi != m_properties.end()) { pi.value().write(fl, reactCoerceValue(it.value(), pi.value().userType(), &m_coercions)); } } } QMap<int, coerce_function> m_coercions{ {qMetaTypeId<ReactFlexLayout::Direction>(), [](const QVariant& value) { Q_ASSERT(value.canConvert<QString>()); return directions[value.toString()]; }}, {qMetaTypeId<ReactFlexLayout::Alignment>(), [](const QVariant& value) { Q_ASSERT(value.canConvert<QString>()); return alignments[value.toString()]; }}, {qMetaTypeId<ReactFlexLayout::Justify>(), [](const QVariant& value) { Q_ASSERT(value.canConvert<QString>()); return justifys[value.toString()]; }}, {qMetaTypeId<ReactFlexLayout::Position>(), [](const QVariant& value) { Q_ASSERT(value.canConvert<QString>()); return positions[value.toString()]; }}, {qMetaTypeId<ReactFlexLayout::Wrap>(), [](const QVariant& value) { Q_ASSERT(value.canConvert<QString>()); return wraps[value.toString()]; }}, }; QMap<QString, QMetaProperty> m_properties; }; Q_GLOBAL_STATIC(FlexPropertyHandler, flexPropertyHandler); QDebug operator<<(QDebug debug, const ReactFlexLayoutPrivate* p); namespace { enum { CSS_HORIZONTAL = CSS_BOTTOM + 1, CSS_VERTICAL, CSS_PROP_COUNT }; } class ReactFlexLayoutPrivate { Q_DECLARE_PUBLIC(ReactFlexLayout) public: ReactFlexLayoutPrivate(ReactFlexLayout* q) : q_ptr(q), cssNode(new_css_node()) { cssNode->context = this; cssNode->get_child = ReactFlexLayoutPrivate::getChild; cssNode->is_dirty = ReactFlexLayoutPrivate::isDirty; } ~ReactFlexLayoutPrivate() { free_css_node(cssNode); } void updateMargin(ReactFlexLayoutPrivate* p) { if (!isUndefined(p->margin[CSS_LEFT])) { p->cssNode->style.margin[CSS_LEFT] = p->margin[CSS_LEFT]; } else if (!isUndefined(p->margin[CSS_HORIZONTAL])) { p->cssNode->style.margin[CSS_LEFT] = p->margin[CSS_HORIZONTAL]; } if (!isUndefined(p->margin[CSS_RIGHT])) { p->cssNode->style.margin[CSS_RIGHT] = p->margin[CSS_RIGHT]; } else if (!isUndefined(p->margin[CSS_HORIZONTAL])) { p->cssNode->style.margin[CSS_RIGHT] = p->margin[CSS_HORIZONTAL]; } if (!isUndefined(p->margin[CSS_TOP])) { p->cssNode->style.margin[CSS_TOP] = p->margin[CSS_TOP]; } else if (!isUndefined(p->margin[CSS_VERTICAL])) { p->cssNode->style.margin[CSS_TOP] = p->margin[CSS_VERTICAL]; } if (!isUndefined(p->margin[CSS_BOTTOM])) { p->cssNode->style.margin[CSS_BOTTOM] = p->margin[CSS_BOTTOM]; } else if (!isUndefined(p->margin[CSS_VERTICAL])) { p->cssNode->style.margin[CSS_BOTTOM] = p->margin[CSS_VERTICAL]; } } void updatePadding(ReactFlexLayoutPrivate* p) { if (!isUndefined(p->padding[CSS_LEFT])) { p->cssNode->style.padding[CSS_LEFT] = p->padding[CSS_LEFT]; } else if (!isUndefined(p->padding[CSS_HORIZONTAL])) { p->cssNode->style.padding[CSS_LEFT] = p->padding[CSS_HORIZONTAL]; } if (!isUndefined(p->padding[CSS_RIGHT])) { p->cssNode->style.padding[CSS_RIGHT] = p->padding[CSS_RIGHT]; } else if (!isUndefined(p->padding[CSS_HORIZONTAL])) { p->cssNode->style.padding[CSS_RIGHT] = p->padding[CSS_HORIZONTAL]; } if (!isUndefined(p->padding[CSS_TOP])) { p->cssNode->style.padding[CSS_TOP] = p->padding[CSS_TOP]; } else if (!isUndefined(p->padding[CSS_VERTICAL])) { p->cssNode->style.padding[CSS_TOP] = p->padding[CSS_VERTICAL]; } if (!isUndefined(p->padding[CSS_BOTTOM])) { p->cssNode->style.padding[CSS_BOTTOM] = p->padding[CSS_BOTTOM]; } else if (!isUndefined(p->padding[CSS_VERTICAL])) { p->cssNode->style.padding[CSS_BOTTOM] = p->padding[CSS_VERTICAL]; } } void prepareLayout(ReactFlexLayoutPrivate* p) { p->cssNode->children_count = p->children.size(); updateMargin(p); updatePadding(p); if (p->qmlAnchors) { p->cssNode->style.dimensions[CSS_WIDTH] = p->item->width(); p->cssNode->style.dimensions[CSS_HEIGHT] = p->item->height(); } if (p->qmlImplicitWidth) { p->cssNode->style.dimensions[CSS_WIDTH] = QQmlProperty(p->item, "implicitWidth").read().value<double>(); } if (p->qmlImplicitHeight) { p->cssNode->style.dimensions[CSS_HEIGHT] = QQmlProperty(p->item, "implicitHeight").read().value<double>(); } for (auto& c : p->children) { prepareLayout(ReactFlexLayoutPrivate::get(ReactFlexLayout::get(c))); } } void setDirty(bool dirty) { // qDebug() << __PRETTY_FUNCTION__ << this << "old" << dirty << "new" << dirty; this->dirty = dirty; if (!dirty) return; // dont reset parent if (parentItem != nullptr) { ReactFlexLayout* pl = ReactFlexLayout::get(parentItem, false); if (pl != nullptr) pl->setDirty(dirty); } } void local_print_node(int tab) { for (int i = 0; i < tab; ++i) printf(" "); printf("%d:(%s(%p) - (%f,%f, %fx%f)\n", ReactAttachedProperties::get(item)->tag(), item->metaObject()->className(), (void*)item, item->x(), item->y(), item->width(), item->height()); if (qmlImplicitHeight || qmlImplicitWidth) { for (int i = 0; i < tab; ++i) printf(" "); printf("item has using implicitWidth=%f, implictHeight=%f\n", QQmlProperty(item, "implictWidth").read().value<double>(), QQmlProperty(item, "implictHeight").read().value<double>()); } for (int i = 0; i < tab + 2; ++i) printf(" "); print_css_node(cssNode, (css_print_options_t)(CSS_PRINT_LAYOUT | CSS_PRINT_STYLE)); for (QQuickItem* c : children /*item->childItems()*/) { ReactFlexLayoutPrivate::get(ReactFlexLayout::get(c))->local_print_node(tab + 2); } fflush(stdout); } void layout() { // called only at top level // qDebug() << __PRETTY_FUNCTION__ << this; if (!dirty) return; prepareLayout(this); // qDebug() << __PRETTY_FUNCTION__ << "After prepareLayout"; // local_print_node(0); layoutNode(cssNode, CSS_UNDEFINED, CSS_UNDEFINED, CSS_DIRECTION_INHERIT); // qDebug() << __PRETTY_FUNCTION__ << "After layoutNode"; // local_print_node(0); applyLayout(); // qDebug() << __PRETTY_FUNCTION__ << "After applyLayout"; // local_print_node(0); } void setMeasureFunction(const measure_function& measureFunction) { this->measureFunction = measureFunction; cssNode->measure = measureFunction ? measure : nullptr; } static ReactFlexLayoutPrivate* get(ReactFlexLayout* rfl) { return rfl->d_func(); } static css_node_t* getChild(void* context, int i) { const QList<QQuickItem*>& childItems = static_cast<ReactFlexLayoutPrivate*>(context)->children; return ReactFlexLayoutPrivate::get(ReactFlexLayout::get(childItems.at(i)))->cssNode; } static bool isDirty(void* context) { return static_cast<ReactFlexLayoutPrivate*>(context)->dirty; } static css_dim_t measure(void* context, float width, css_measure_mode_t widthMode, float height, css_measure_mode_t heightMode) { ReactFlexLayoutPrivate* p = static_cast<ReactFlexLayoutPrivate*>(context); if (!p->measureFunction) { qCritical() << "measure set without measure function?!"; return {}; } flex_dimensions df = p->measureFunction(width, FlexMeasureMode(widthMode), height, FlexMeasureMode(heightMode)); return {float(df.first), float(df.second)}; } bool qmlAnchors; bool qmlImplicitWidth; bool qmlImplicitHeight; bool dirty; float padding[CSS_PROP_COUNT]; float margin[CSS_PROP_COUNT]; QQuickItem* item; QQuickItem* parentItem; QList<QQuickItem*> children; css_node_t* cssNode; measure_function measureFunction; ReactFlexLayout* q_ptr; private: void applyLayout() { // qDebug() << __PRETTY_FUNCTION__ << this << cssNode->layout.should_update; if (!cssNode->layout.should_update) { return; } cssNode->layout.should_update = false; dirty = false; if (!qmlAnchors) { item->setX(cssNode->layout.position[CSS_LEFT]); item->setY(cssNode->layout.position[CSS_TOP]); item->setWidth(cssNode->layout.dimensions[CSS_WIDTH]); item->setHeight(cssNode->layout.dimensions[CSS_HEIGHT]); } for (auto& c : children) { ReactFlexLayoutPrivate::get(ReactFlexLayout::get(c))->applyLayout(); } cssNode->layout.position[CSS_LEFT] = 0; cssNode->layout.position[CSS_TOP] = 0; cssNode->layout.dimensions[CSS_WIDTH] = CSS_UNDEFINED; cssNode->layout.dimensions[CSS_HEIGHT] = CSS_UNDEFINED; } }; QDebug operator<<(QDebug debug, const ReactFlexLayoutPrivate* p) { QDebugStateSaver s(debug); debug.nospace() << "ReactFlexLayoutPrivate(this=" << (void*)p << ", tag=" << ReactAttachedProperties::get(p->item)->tag() << ", dirty=" << p->dirty << ", item=" << p->item << ", parent=" << p->parentItem << ", layout={" << p->cssNode->layout.position[CSS_LEFT] << " " << p->cssNode->layout.position[CSS_TOP] << " " << p->cssNode->layout.dimensions[CSS_WIDTH] << " " << p->cssNode->layout.dimensions[CSS_HEIGHT] << "})"; return debug; } ReactFlexLayout::ReactFlexLayout(QObject* parent) : QObject(parent), d_ptr(new ReactFlexLayoutPrivate(this)) { Q_D(ReactFlexLayout); d->qmlAnchors = false; d->qmlImplicitWidth = false; d->qmlImplicitHeight = false; d->dirty = false; for (int i = 0; i < CSS_PROP_COUNT; ++i) { d->margin[i] = CSS_UNDEFINED; d->padding[i] = CSS_UNDEFINED; } d->item = qobject_cast<QQuickItem*>(parent); d->parentItem = nullptr; if (d->item == nullptr) { qCritical() << "Flex layout only applies to visual items"; } } ReactFlexLayout::~ReactFlexLayout() {} bool ReactFlexLayout::qmlAnchors() const { return d_func()->qmlAnchors; } void ReactFlexLayout::setQmlAnchors(bool qmlAnchors) { Q_D(ReactFlexLayout); if (d->qmlAnchors == qmlAnchors) return; d->qmlAnchors = qmlAnchors; } bool ReactFlexLayout::qmlImplicitWidth() const { return d_func()->qmlImplicitWidth; } void ReactFlexLayout::setQmlImplicitWidth(bool qmlImplicitWidth) { Q_D(ReactFlexLayout); if (d->qmlImplicitWidth == qmlImplicitWidth) return; d->qmlImplicitWidth = qmlImplicitWidth; } bool ReactFlexLayout::qmlImplicitHeight() const { return d_func()->qmlImplicitHeight; } void ReactFlexLayout::setQmlImplicitHeight(bool qmlImplicitHeight) { Q_D(ReactFlexLayout); if (d->qmlImplicitHeight == qmlImplicitHeight) return; d->qmlImplicitHeight = qmlImplicitHeight; } bool ReactFlexLayout::isDirty() { return d_func()->dirty; } void ReactFlexLayout::setDirty(bool dirty) { Q_D(ReactFlexLayout); if (d->dirty == dirty) return; d->setDirty(dirty); } double ReactFlexLayout::flex() const { return d_func()->cssNode->style.flex; } void ReactFlexLayout::setFlex(double flex) { Q_D(ReactFlexLayout); if (d->cssNode->style.flex == flex) // XXX: return; d->cssNode->style.flex = flex; setDirty(true); Q_EMIT flexChanged(); } ReactFlexLayout::Direction ReactFlexLayout::flexDirection() const { return (ReactFlexLayout::Direction)d_func()->cssNode->style.flex_direction; } void ReactFlexLayout::setFlexDirection(Direction direction) { Q_D(ReactFlexLayout); if (d->cssNode->style.flex_direction == (css_flex_direction_t)direction) return; d->cssNode->style.flex_direction = (css_flex_direction_t)direction; setDirty(true); Q_EMIT flexDirectionChanged(); } ReactFlexLayout::Justify ReactFlexLayout::justifyContent() const { return (ReactFlexLayout::Justify)d_func()->cssNode->style.justify_content; } void ReactFlexLayout::setJustifyContent(Justify justify) { Q_D(ReactFlexLayout); if (d->cssNode->style.justify_content == (css_justify_t)justify) return; d->cssNode->style.justify_content = (css_justify_t)justify; setDirty(true); Q_EMIT justifyContentChanged(); } ReactFlexLayout::Alignment ReactFlexLayout::selfAlignment() const { return (ReactFlexLayout::Alignment)d_func()->cssNode->style.align_self; } void ReactFlexLayout::setSelfAlignment(Alignment alignment) { Q_D(ReactFlexLayout); if (d->cssNode->style.align_self == (css_align_t)alignment) return; d->cssNode->style.align_self = (css_align_t)alignment; setDirty(true); Q_EMIT selfAlignmentChanged(); } ReactFlexLayout::Alignment ReactFlexLayout::alignItems() const { return (ReactFlexLayout::Alignment)d_func()->cssNode->style.align_items; } void ReactFlexLayout::setAlignItems(Alignment alignment) { Q_D(ReactFlexLayout); if (d->cssNode->style.align_items == (css_align_t)alignment) return; d->cssNode->style.align_items = (css_align_t)alignment; setDirty(true); Q_EMIT alignItemsChanged(); } ReactFlexLayout::Position ReactFlexLayout::position() const { return (ReactFlexLayout::Position)d_func()->cssNode->style.position_type; } void ReactFlexLayout::setPosition(Position position) { Q_D(ReactFlexLayout); if (d->cssNode->style.position_type == (css_position_type_t)position) return; d->cssNode->style.position_type = (css_position_type_t)position; setDirty(true); Q_EMIT positionChanged(); } ReactFlexLayout::Wrap ReactFlexLayout::wrap() const { return (ReactFlexLayout::Wrap)d_func()->cssNode->style.flex_wrap; } void ReactFlexLayout::setWrap(Wrap wrap) { Q_D(ReactFlexLayout); if (d->cssNode->style.flex_wrap == (css_wrap_type_t)wrap) return; d->cssNode->style.flex_wrap = (css_wrap_type_t)wrap; setDirty(true); Q_EMIT wrapChanged(); } double ReactFlexLayout::top() const { return d_func()->cssNode->style.position[CSS_TOP]; } void ReactFlexLayout::setTop(double top) { Q_D(ReactFlexLayout); if (d->cssNode->style.position[CSS_TOP] == top) return; d->cssNode->style.position[CSS_TOP] = top; setDirty(true); Q_EMIT topChanged(); } double ReactFlexLayout::right() const { return d_func()->cssNode->style.position[CSS_RIGHT]; } void ReactFlexLayout::setRight(double right) { Q_D(ReactFlexLayout); if (d->cssNode->style.position[CSS_RIGHT] == right) return; d->cssNode->style.position[CSS_RIGHT] = right; setDirty(true); Q_EMIT rightChanged(); } double ReactFlexLayout::bottom() const { return d_func()->cssNode->style.position[CSS_BOTTOM]; } void ReactFlexLayout::setBottom(double bottom) { Q_D(ReactFlexLayout); if (d->cssNode->style.position[CSS_BOTTOM] == bottom) return; d->cssNode->style.position[CSS_BOTTOM] = bottom; setDirty(true); Q_EMIT bottomChanged(); } double ReactFlexLayout::left() const { return d_func()->cssNode->style.position[CSS_LEFT]; } void ReactFlexLayout::setLeft(double left) { Q_D(ReactFlexLayout); if (d->cssNode->style.position[CSS_LEFT] == left) return; d->cssNode->style.position[CSS_LEFT] = left; setDirty(true); Q_EMIT leftChanged(); } double ReactFlexLayout::width() const { return d_func()->cssNode->style.dimensions[CSS_WIDTH]; } void ReactFlexLayout::setWidth(double width) { Q_D(ReactFlexLayout); if (d->cssNode->style.dimensions[CSS_WIDTH] == width) return; d->cssNode->style.dimensions[CSS_WIDTH] = width; setDirty(true); Q_EMIT widthChanged(); } double ReactFlexLayout::height() const { return d_func()->cssNode->style.dimensions[CSS_HEIGHT]; } void ReactFlexLayout::setHeight(double height) { Q_D(ReactFlexLayout); if (d->cssNode->style.dimensions[CSS_HEIGHT] == height) return; d->cssNode->style.dimensions[CSS_HEIGHT] = height; setDirty(true); Q_EMIT heightChanged(); } double ReactFlexLayout::padding() const { return d_func()->cssNode->style.padding[CSS_TOP]; // XXX: } void ReactFlexLayout::setPadding(double padding) { Q_D(ReactFlexLayout); d->cssNode->style.padding[CSS_TOP] = d->cssNode->style.padding[CSS_LEFT] = d->cssNode->style.padding[CSS_BOTTOM] = d->cssNode->style.padding[CSS_RIGHT] = padding; setDirty(true); } double ReactFlexLayout::paddingVertical() const { return d_func()->padding[CSS_VERTICAL]; } void ReactFlexLayout::setPaddingVertical(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_VERTICAL] = padding; setDirty(true); } double ReactFlexLayout::paddingHorizontal() const { return d_func()->padding[CSS_HORIZONTAL]; } void ReactFlexLayout::setPaddingHorizontal(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_HORIZONTAL] = padding; setDirty(true); } double ReactFlexLayout::paddingTop() const { return d_func()->padding[CSS_TOP]; } void ReactFlexLayout::setPaddingTop(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_TOP] = padding; setDirty(true); } double ReactFlexLayout::paddingLeft() const { return d_func()->padding[CSS_LEFT]; } void ReactFlexLayout::setPaddingLeft(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_LEFT] = padding; setDirty(true); } double ReactFlexLayout::paddingBottom() const { return d_func()->padding[CSS_BOTTOM]; } void ReactFlexLayout::setPaddingBottom(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_BOTTOM] = padding; setDirty(true); } double ReactFlexLayout::paddingRight() const { return d_func()->padding[CSS_RIGHT]; } void ReactFlexLayout::setPaddingRight(double padding) { Q_D(ReactFlexLayout); d->padding[CSS_RIGHT] = padding; setDirty(true); } double ReactFlexLayout::margin() const { return d_func()->cssNode->style.margin[CSS_TOP]; // XXX: } void ReactFlexLayout::setMargin(double margin) { Q_D(ReactFlexLayout); d->cssNode->style.margin[CSS_TOP] = d->cssNode->style.margin[CSS_LEFT] = d->cssNode->style.margin[CSS_BOTTOM] = d->cssNode->style.margin[CSS_RIGHT] = margin; setDirty(true); } double ReactFlexLayout::marginVertical() const { return d_func()->margin[CSS_VERTICAL]; } void ReactFlexLayout::setMarginVertical(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_VERTICAL] = margin; setDirty(true); } double ReactFlexLayout::marginHorizontal() const { return d_func()->margin[CSS_HORIZONTAL]; } void ReactFlexLayout::setMarginHorizontal(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_HORIZONTAL] = margin; setDirty(true); } double ReactFlexLayout::marginTop() const { return d_func()->margin[CSS_TOP]; } void ReactFlexLayout::setMarginTop(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_TOP] = margin; setDirty(true); } double ReactFlexLayout::marginLeft() const { return d_func()->margin[CSS_LEFT]; } void ReactFlexLayout::setMarginLeft(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_LEFT] = margin; setDirty(true); } double ReactFlexLayout::marginBottom() const { return d_func()->margin[CSS_BOTTOM]; } void ReactFlexLayout::setMarginBottom(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_BOTTOM] = margin; setDirty(true); } double ReactFlexLayout::marginRight() const { return d_func()->margin[CSS_RIGHT]; } void ReactFlexLayout::setMarginRight(double margin) { Q_D(ReactFlexLayout); d->margin[CSS_RIGHT] = margin; setDirty(true); } measure_function ReactFlexLayout::measureFunction() const { return d_func()->measureFunction; } void ReactFlexLayout::setMeasureFunction(const measure_function& measureFunction) { d_func()->setMeasureFunction(measureFunction); } QQuickItem* ReactFlexLayout::parentItem() const { return d_func()->parentItem; } void ReactFlexLayout::setParentItem(QQuickItem* parentItem) { Q_D(ReactFlexLayout); d->parentItem = parentItem; } void ReactFlexLayout::insertChild(int position, QQuickItem* child) { Q_D(ReactFlexLayout); d->children.insert(position, child); } int ReactFlexLayout::getChildIndex(QQuickItem* child) { Q_D(ReactFlexLayout); int index = d->children.indexOf(child); Q_ASSERT(index >= 0); return index; } QList<QQuickItem*> ReactFlexLayout::removeChildren(const QList<int>& children) { Q_D(ReactFlexLayout); QList<QQuickItem*> removable; std::transform(children.begin(), children.end(), std::back_inserter(removable), [=](int index) { return d->children.at(index); }); d->children.erase(std::remove_if(d->children.begin(), d->children.end(), [=](QQuickItem* item) { return removable.contains(item); }), d->children.end()); return removable; } void ReactFlexLayout::applyLayoutProperties(const QVariantMap& properties) { flexPropertyHandler()->applyProperties(this, properties); } void ReactFlexLayout::polish(QQuickItem* item) { ReactFlexLayout* rfl = ReactFlexLayout::get(item, false); if (rfl == nullptr) { qCritical() << "Attempting to start Flex layout on non-flex item!"; return; } ReactFlexLayoutPrivate::get(rfl)->layout(); } ReactFlexLayout* ReactFlexLayout::get(QQuickItem* item, bool create) { return qobject_cast<ReactFlexLayout*>(qmlAttachedPropertiesObject<ReactFlexLayout>(item, create)); } ReactFlexLayout* ReactFlexLayout::qmlAttachedProperties(QObject* object) { return new ReactFlexLayout(object); }
33.059055
120
0.642928
[ "object", "transform" ]
28c8bc1cea35e1a3ba1e578cb21ffcb5d37cd5cc
668
cpp
C++
ACM/Youzu2020/F_sort.cpp
AixMoon/LearnigRepo
ee98fb352735e2b4f97304847b6c0311bc30195e
[ "MIT" ]
11
2020-05-02T20:06:07.000Z
2021-06-24T10:01:29.000Z
ACM/Youzu2020/F_sort.cpp
AixMoon/LearnigRepo
ee98fb352735e2b4f97304847b6c0311bc30195e
[ "MIT" ]
null
null
null
ACM/Youzu2020/F_sort.cpp
AixMoon/LearnigRepo
ee98fb352735e2b4f97304847b6c0311bc30195e
[ "MIT" ]
6
2020-06-04T04:29:28.000Z
2020-11-15T08:15:01.000Z
#include <algorithm> #include <iostream> #include <queue> #include <sstream> #include <string.h> #include <string> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); vector<string> s; int num = 0; string t; int len; cin >> len; while (len--) { cin >> t; s.push_back(t); } sort(s.begin(), s.end()); for (int i = 0; i < s.size() - 1; i++) { if (s[i + 1].find(s[i]) == string::npos) { if (s[i].size() > 3) { if (s[i].substr(s[i].size() - 4) == ".eoj") { num++; } } } } string tmp = s[s.size() - 1]; if (tmp.size() > 3) { if (tmp.substr(tmp.size() - 4) == ".eoj") { num++; } } cout << num; }
17.578947
49
0.519461
[ "vector" ]
28c8d17e150f240ed246f39619c6d4c83a19e2fd
12,779
hpp
C++
lib/alice/include/alice/cli.hpp
hriener/esop_synthesis
811d7fa36e1ae7b8bc2418ef751d14ac15809bf9
[ "MIT" ]
3
2018-01-06T14:10:10.000Z
2018-01-20T10:29:47.000Z
lib/alice/include/alice/cli.hpp
hriener/esop_synthesis
811d7fa36e1ae7b8bc2418ef751d14ac15809bf9
[ "MIT" ]
null
null
null
lib/alice/include/alice/cli.hpp
hriener/esop_synthesis
811d7fa36e1ae7b8bc2418ef751d14ac15809bf9
[ "MIT" ]
null
null
null
/* alice: C++ command shell library * Copyright (C) 2017-2018 EPFL * * 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. */ /* \file cli.hpp \brief The main entry method for the CLI \author Mathias Soeken */ #pragma once #include <chrono> #include <fstream> #include <memory> #include <regex> #include <string> #include <CLI11.hpp> #include <fmt/format.h> #include "command.hpp" #include "detail/logging.hpp" #include "readline.hpp" #include "commands/alias.hpp" #include "commands/convert.hpp" #include "commands/current.hpp" #include "commands/help.hpp" #include "commands/print.hpp" #include "commands/ps.hpp" #include "commands/quit.hpp" #include "commands/read_io.hpp" #include "commands/set.hpp" #include "commands/show.hpp" #include "commands/store.hpp" #include "commands/write_io.hpp" namespace alice { /*! \brief CLI main class The stores of a CLI are passed as type arguments to ``cli``. For example, if the CLI has stores for Graphs and Trees which are handled by classes ``graph`` and ``tree``, respectively, the class instantiation is ``cli<graph, tree>``. */ template<class... S> class cli { public: /*! \brief Default constructor Initializes the CLI with a prefix that is used as a command prefix in stand-alone application mode and as a module name when build as Python module. The constructor will add the default commands to the CLI. If no store type is specified, then no store-related command will be added. \param prefix Either command prefix or module name (depending on build mode) */ explicit cli( const std::string& prefix ) : env( std::make_shared<environment>() ), prefix( prefix ) { /* for each type in S ... */ []( ... ) {}( ( env->add_store<S>(), 0 )... ); set_category( "General" ); insert_command( "alias", std::make_shared<alias_command>( env ) ); insert_command( "help", std::make_shared<help_command>( env ) ); insert_command( "quit", std::make_shared<quit_command>( env ) ); insert_command( "set", std::make_shared<set_command>( env ) ); if ( sizeof...( S ) ) { insert_command( "convert", std::make_shared<convert_command<S...>>( env ) ); insert_command( "current", std::make_shared<current_command<S...>>( env ) ); insert_command( "print", std::make_shared<print_command<S...>>( env ) ); insert_command( "ps", std::make_shared<ps_command<S...>>( env ) ); insert_command( "show", std::make_shared<show_command<S...>>( env ) ); insert_command( "store", std::make_shared<store_command<S...>>( env ) ); } opts.add_option( "-c,--command", command, "process semicolon-separated list of commands" ); opts.add_option( "-f,--filename", file, "process file with new-line separated list of commands" ); opts.add_flag( "-e,--echo", "echo the command if read from command line or file" ); opts.add_flag( "-n,--counter", "show a counter in the prefix" ); opts.add_flag( "-i,--interactive", "continue in interactive mode after processing commands (in command or file mode)" ); opts.add_option( "-l,--log", logname, "logs the execution and stores many statistical information" ); } /*! \brief Sets the current category This category will be used as category for all commands that are added afterwards, until this method is called again with a different argument. The categories are used in the ``help`` command to organize the commands. The macros :c:macro:`ALICE_COMMAND` and :c:macro:`ALICE_ADD_COMMAND` will automatically call this method. \param _category Category name */ void set_category( const std::string& _category ) { category = _category; } /*! \brief Inserts a command Inserts a command (as a shared pointer) to the CLI. The macro :c:macro:`ALICE_ADD_COMMAND` will automatically call this method with a convention that a command with name ``<name>`` must be called ``<name>_command``. \param name Name of the command \param cmd Shared pointer to a command instance */ void insert_command( const std::string& name, const std::shared_ptr<command>& cmd ) { env->_categories[category].push_back( name ); env->_commands[name] = cmd; } /*! \brief Inserts a read command Inserts a read command for a given file tag. The name of the command can be arbitrary but the default convention is to prefix it with ``read_``. The macro :c:macro:`ALICE_ADD_FILE_TYPE` together :c:macro:`ALICE_READ_FILE` will automatically add a read command called ``read_<tagname>``. \param name Name of the command \param label Label for the file type (used in help string) */ template<typename Tag> void insert_read_command( const std::string& name, const std::string& label ) { insert_command( name, std::make_shared<read_io_command<Tag, S...>>( env, label ) ); } /*! \brief Inserts a write command Inserts a writ command for a given file tag. The name of the command can be arbitrary but the default convention is to prefix it with ``write_``. The macro :c:macro:`ALICE_ADD_FILE_TYPE` together :c:macro:`ALICE_WRITE_FILE` will automatically add a write command called ``write_<tagname>``. \param name Name of the command \param label Label for the file type (used in help string) */ template<typename Tag> void insert_write_command( const std::string& name, const std::string& label ) { insert_command( name, std::make_shared<write_io_command<Tag, S...>>( env, label ) ); } /*! \brief Runs the shell This function is only used if the CLI is used in stand-alone mode, not when used as Python module. The values ``argc`` and ``argv`` can be taken from the ``main`` function. For some flags, such as ``-f`` and ``-c``, the CLI will read commands from a file or the command line, respectively, and then stop (unless flag ``-i`` is set). Otherwise, the CLI will enter a loop that accepts commands as user inputer. \param argc Number of arguments (incl. program name, like ``argc`` in ``main``) \param argv Argument values (like ``argv`` in ``main``) */ int run( int argc, char** argv ) { try { opts.parse( argc, argv ); } catch ( const CLI::CallForHelp& e ) { env->out() << opts.help(); return 1; } catch ( const CLI::ParseError& e ) { env->out() << "[e] " << e.what() << std::endl; return 2; } read_aliases(); if ( opts.count( "-l" ) ) { env->log = true; env->logger.start( logname ); } if ( opts.count( "-c" ) ) { auto split = detail::split_with_quotes<';'>( command ); std::string batch_string; std::string abc_opts; for ( auto& line : split ) { detail::trim( line ); if ( opts.count( "-e" ) ) { env->out() << get_prefix() << line << std::endl; } if ( !execute_line( preprocess_alias( line ) ) ) { return 1; } if ( env->quit ) { break; } } } else if ( opts.count( "-f" ) ) { process_file( file, opts.count( "-e" ) ); if ( !opts.count( "-i" ) ) { env->quit = true; } } if ( ( !opts.count( "-c" ) && !opts.count( "-f" ) ) || ( !env->quit && opts.count( "-i" ) ) ) { auto& rl = readline_wrapper::instance(); rl.init( env ); std::string line; while ( !env->quit && rl.read_command_line( get_prefix(), line ) ) { execute_line( preprocess_alias( line ) ); rl.add_to_history( line ); } } if ( env->log ) { env->logger.stop(); } return 0; } /*! \ifcond PRIVATE */ private: bool execute_line( const std::string& line ) { /* at this point we can assume that line is trimmed */ /* ignore comments and empty lines */ if ( line.empty() || line[0] == '#' ) { return false; } /* split commands if line contains a semi-colon */ const auto lines = detail::split_with_quotes<';'>( line ); /* if more than one command is detected recurse on each part */ if ( lines.size() > 1u ) { auto result = true; for ( const auto& cline : lines ) { result = result && execute_line( preprocess_alias( cline ) ); } return result; } /* escape to shell */ if ( line[0] == '!' ) { const auto now = std::chrono::system_clock::now(); const auto result = detail::execute_program( line.substr( 1u ) ); env->out() << result.second; if ( !result.second.empty() && result.second.back() != '\n' ) { env->out() << '%' << std::endl; } if ( env->log ) { nlohmann::json log = {{"status", result.first}, {"output", result.second}}; env->logger.log( log, line, now ); } return true; } /* read commands from file */ if ( line[0] == '<' ) { auto filename = line.substr( 1u ); detail::trim( filename ); process_file( filename, opts.count( "-e" ) ); return true; } auto vline = detail::split_with_quotes<' '>( line ); const auto it = env->commands().find( vline.front() ); if ( it != env->commands().end() ) { const auto now = std::chrono::system_clock::now(); const auto result = it->second->run( vline ); if ( result && env->log ) { env->logger.log( it->second->log(), line, now ); } return result; } else { env->err() << "[e] unknown command: " << vline.front() << std::endl; return false; } return true; } bool process_file( const std::string& filename, bool echo, bool error_on_not_found = true ) { std::ifstream in( filename.c_str(), std::ifstream::in ); if ( !in.good() ) { if ( error_on_not_found ) { env->out() << "[e] file " << filename << " not found" << std::endl; } return true; } std::string line; while ( getline( in, line ) ) { detail::trim( line ); if ( echo ) { env->out() << get_prefix() << line << std::endl; } execute_line( preprocess_alias( line ) ); if ( env->quit ) { /* quit */ return true; } } /* do not quit */ return false; } std::string get_prefix() { if ( opts.count( "-n" ) ) { return prefix + fmt::format( " {}> ", counter++ ); } else { return prefix + "> "; } } void read_aliases() { #if defined(ALICE_ENV_HOME) #define ALICE_STRINGIFY(x) #x #define ALICE_TOSTRING(x) ALICE_STRINGIFY(x) std::string env = ALICE_TOSTRING( ALICE_ENV_HOME ); if ( env.empty() ) { return;} if ( auto* path = std::getenv( env.c_str() ) ) { std::string alias_path = fmt::format( "{}/alias", path ); process_file( alias_path, false, false ); } #endif } std::string preprocess_alias( const std::string& line ) { std::smatch m; for ( const auto& p : env->aliases() ) { if ( std::regex_match( line, m, std::regex( p.first ) ) ) { std::vector<std::string> matches( m.size() - 1u ); for ( auto i = 0u; i < matches.size(); ++i ) { matches[i] = std::string( m[i + 1] ); } const auto str = detail::trim_copy( detail::format_with_vector( p.second, matches ) ); return preprocess_alias( str ); } } return line; } public: environment::ptr env; private: std::string prefix; CLI::App opts; std::string category; std::string command, file, logname; unsigned counter{1u}; /*! \endcond */ }; }
27.780435
124
0.609281
[ "vector" ]
28c90a3da8f6d38757cda5b4bf0da3dc45bc04fc
5,104
cpp
C++
src/lib/statistics/attribute_statistics.cpp
Dencrash/hyrise
3169a81961f32f30b2ee12a0b73d992e99a9bdd4
[ "MIT" ]
null
null
null
src/lib/statistics/attribute_statistics.cpp
Dencrash/hyrise
3169a81961f32f30b2ee12a0b73d992e99a9bdd4
[ "MIT" ]
null
null
null
src/lib/statistics/attribute_statistics.cpp
Dencrash/hyrise
3169a81961f32f30b2ee12a0b73d992e99a9bdd4
[ "MIT" ]
null
null
null
#include "attribute_statistics.hpp" #include <memory> #include "resolve_type.hpp" #include "statistics/statistics_objects/abstract_histogram.hpp" #include "statistics/statistics_objects/generic_histogram.hpp" #include "statistics/statistics_objects/min_max_filter.hpp" #include "statistics/statistics_objects/range_filter.hpp" namespace opossum { template <typename T> AttributeStatistics<T>::AttributeStatistics() : BaseAttributeStatistics(data_type_from_type<T>()) {} template <typename T> void AttributeStatistics<T>::set_statistics_object(const std::shared_ptr<AbstractStatisticsObject>& statistics_object) { // We allow call patterns like `c.set_statistics_object(o.scaled(0.1f))` where `o.scaled()` might return nullptr // because, e.g., scaling is not possible for `o`. if (!statistics_object) { return; } if (const auto histogram_object = std::dynamic_pointer_cast<AbstractHistogram<T>>(statistics_object)) { histogram = histogram_object; } else if (const auto min_max_object = std::dynamic_pointer_cast<MinMaxFilter<T>>(statistics_object)) { min_max_filter = min_max_object; } else if (const auto null_value_ratio_object = std::dynamic_pointer_cast<NullValueRatioStatistics>(statistics_object)) { null_value_ratio = null_value_ratio_object; } else { if constexpr (std::is_arithmetic_v< T>) { // NOLINT clang-tidy is crazy and sees a "potentially unintended semicolon" here... if (const auto range_object = std::dynamic_pointer_cast<RangeFilter<T>>(statistics_object)) { range_filter = range_object; return; } } Fail("Statistics object type not yet supported."); } } template <typename T> std::shared_ptr<BaseAttributeStatistics> AttributeStatistics<T>::scaled(const Selectivity selectivity) const { const auto statistics = std::make_shared<AttributeStatistics<T>>(); if (histogram) { statistics->set_statistics_object(histogram->scaled(selectivity)); } if (null_value_ratio) { statistics->set_statistics_object(null_value_ratio->scaled(selectivity)); } if (min_max_filter) { statistics->set_statistics_object(min_max_filter->scaled(selectivity)); } // NOLINTNEXTLINE clang-tidy is crazy and sees a "potentially unintended semicolon" here... if constexpr (std::is_arithmetic_v<T>) { if (range_filter) { statistics->set_statistics_object(range_filter->scaled(selectivity)); } } return statistics; } template <typename T> std::string AttributeStatistics<T>::range_strings() const { if constexpr (std::is_arithmetic_v<T>) { if (range_filter) { return range_filter->range_strings(); } } return ""; } template <typename T> std::shared_ptr<BaseAttributeStatistics> AttributeStatistics<T>::sliced( const PredicateCondition predicate_condition, const AllTypeVariant& variant_value, const std::optional<AllTypeVariant>& variant_value2) const { const auto statistics = std::make_shared<AttributeStatistics<T>>(); if (histogram) { statistics->set_statistics_object(histogram->sliced(predicate_condition, variant_value, variant_value2)); } if (null_value_ratio) { statistics->set_statistics_object(null_value_ratio->sliced(predicate_condition, variant_value, variant_value2)); } if (min_max_filter) { statistics->set_statistics_object(min_max_filter->sliced(predicate_condition, variant_value, variant_value2)); } // NOLINTNEXTLINE clang-tidy is crazy and sees a "potentially unintended semicolon" here... if constexpr (std::is_arithmetic_v<T>) { if (range_filter) { statistics->set_statistics_object(range_filter->sliced(predicate_condition, variant_value, variant_value2)); } } return statistics; } template <typename T> std::shared_ptr<BaseAttributeStatistics> AttributeStatistics<T>::pruned( const size_t num_values_pruned, const PredicateCondition predicate_condition, const AllTypeVariant& variant_value, const std::optional<AllTypeVariant>& variant_value2) const { const auto statistics = std::make_shared<AttributeStatistics<T>>(); if (histogram) { statistics->set_statistics_object( histogram->pruned(num_values_pruned, predicate_condition, variant_value, variant_value2)); } if (null_value_ratio) { // As the null value ratio statistics have no absolute row counts, we cannot prune here. Create an unmodified copy. statistics->set_statistics_object(std::make_shared<NullValueRatioStatistics>(null_value_ratio->ratio)); } // As pruning is on a table-level granularity, it does not make too much sense to implement pruning on chunk-level // statistics such as the filters below. if (min_max_filter) { Fail("Pruning not implemented for min/max filters"); } // NOLINTNEXTLINE clang-tidy is crazy and sees a "potentially unintended semicolon" here... if constexpr (std::is_arithmetic_v<T>) { if (range_filter) { Fail("Pruning not implemented for range filters"); } } return statistics; } EXPLICITLY_INSTANTIATE_DATA_TYPES(AttributeStatistics); } // namespace opossum
34.958904
120
0.749216
[ "object" ]
28d119382ec101063d76923441485a5c204aba43
1,795
cpp
C++
app/src/source/EnemyManager.cpp
Jonathan-source/DV1570
59be89d554094481922db494b01a3ed5d9e1983b
[ "MIT" ]
null
null
null
app/src/source/EnemyManager.cpp
Jonathan-source/DV1570
59be89d554094481922db494b01a3ed5d9e1983b
[ "MIT" ]
null
null
null
app/src/source/EnemyManager.cpp
Jonathan-source/DV1570
59be89d554094481922db494b01a3ed5d9e1983b
[ "MIT" ]
null
null
null
#include "pch.h" #include "EnemyManager.h" EnemyManager::EnemyManager(Player* playerTarget, const std::vector<std::vector<Node*>>& grid) :currentSpawnIndex(0) , m_playerTarget(playerTarget) , m_grid(grid) , m_waveCount(0) { } EnemyManager::~EnemyManager() { for (auto enemy : m_enemies) { delete enemy; } } std::vector<Enemy*>& EnemyManager::GetEnemies() { return m_enemies; } std::vector<Vector3>& EnemyManager::GetSpawnPoints() { return m_spawnPoints; } void EnemyManager::AddSpawnPoint(Vector3 spawnPoint) { m_spawnPoints.push_back(spawnPoint); } void EnemyManager::SpawnEnemy(EnemyType enemyType) { switch (enemyType) { case EnemyType::DEFAULT: { const auto enemy = new Enemy; currentSpawnIndex = ++currentSpawnIndex % m_spawnPoints.size(); enemy->SetPosition(m_spawnPoints[currentSpawnIndex]); enemy->SetPlayerTarget(m_playerTarget); enemy->SetGrid(m_grid); m_enemies.push_back(enemy); } break; case EnemyType::TYPE1: break; case EnemyType::TYPE2: break; default: break; } } void EnemyManager::SpawnWave(int numOfEnemies) { for(int i = 0; i < numOfEnemies; i++) { SpawnEnemy(EnemyType::DEFAULT); } } void EnemyManager::UpdateEnemies() { // Update & Move Enemies for (int i = 0; i < m_enemies.size(); i++) { m_enemies.at(i)->Update(); m_enemies.at(i)->Move(m_enemies.at(i)->GetVelocity(), GetFrameTime(), m_enemies.at(i)->GetRunSpeed()); if (m_enemies.at(i)->GetHealth() <= 0) { delete m_enemies.at(i); m_enemies.erase(m_enemies.begin() + i); } } // Generate new wave if all enemies are gone if(m_enemies.empty()) { SpawnWave(++m_waveCount * 2); } } void EnemyManager::RenderEnemies() const { for (const auto enemy : m_enemies) { DrawModel(enemy->GetModel(), enemy->GetPosition(), 1, WHITE); } }
18.894737
104
0.694708
[ "vector" ]
28d62ce40c265fb8f963d4e6430521c4a67d203f
16,743
cc
C++
stig/indy/disk/util/disk_util.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
null
null
null
stig/indy/disk/util/disk_util.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
null
null
null
stig/indy/disk/util/disk_util.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
1
2020-01-03T20:13:50.000Z
2020-01-03T20:13:50.000Z
/* <stig/indy/disk/util/disk_util.cc> TODO Copyright 2010-2014 Stig LLC 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 <iostream> #include <sstream> #include <syslog.h> #include <stig/indy/disk/util/device_util.h> #include <stig/indy/disk/util/disk_util.h> using namespace std; using namespace chrono; using namespace Base; using namespace Stig::Indy::Disk::Util; TDiskUtil::TDiskUtil(Base::TScheduler *scheduler, TDiskController *controller, const Base::TOpt<std::string> &instance_filter, bool do_fsync, const TCacheCb &cache_cb, bool do_corruption_check) : Scheduler(scheduler), Controller(controller), CacheCb(cache_cb) { TDeviceUtil::ForEachDevice([this, &instance_filter, do_corruption_check, do_fsync](const char *path) { TDeviceUtil::TStigDevice device_info; string path_to_device = "/dev/"; path_to_device += path; bool ret = TDeviceUtil::ProbeDevice(path_to_device.c_str(), device_info); AllDeviceSet.emplace(path_to_device); if (ret && (!instance_filter || device_info.VolumeId.GetInstanceName() == *instance_filter)) { StigDeviceMap.emplace(path_to_device, device_info); auto ret = VolumeById.find(device_info.VolumeId); if (ret != VolumeById.end()) { auto &volume = ret->second; /* this is where we check that all the devices in a volume have the same description of said volume */ /* TODO: above */ std::unique_ptr<TDevice> new_device(new TPersistentDevice(Controller, path_to_device.c_str(), path, device_info.LogicalBlockSize, /* logical block size */ device_info.PhysicalBlockSize, /* physical block size */ device_info.NumLogicalBlockExposed, /* num logical block */ do_fsync, do_corruption_check)); volume->AddDevice(new_device.get(), device_info.VolumeDeviceNumber); PersistentDeviceSet.insert(std::move(new_device)); } else { if (device_info.ReplicationFactor <= 0) { throw std::runtime_error("Replication factor must be >= 1"); } if ((device_info.StripeSizeKB * 1024) % Util::PhysicalBlockSize != 0) { throw std::runtime_error("Stripe size must be a multiple of 64K"); } if (device_info.NumDevicesInVolume % device_info.ReplicationFactor != 0) { syslog(LOG_ERR, "The number of devices [%ld] in a volume must be a multiple of the replication factor [%ld]", device_info.NumDevicesInVolume, device_info.ReplicationFactor); throw std::runtime_error("The number of devices in a volume must be a multiple of the replication factor"); } std::unique_ptr<TVolume> volume(new TVolume(TVolume::TDesc{ device_info.VolumeStrategy == 1UL ? TVolume::TDesc::Striped : TVolume::TDesc::Chained, TDevice::TDesc { TDevice::TDesc::TKind::SSD, /* TODO */ device_info.LogicalBlockSize, /* LogicalBlockSize */ device_info.PhysicalBlockSize, /* PhysicalBlockSize*/ device_info.NumLogicalBlockExposed, /* NumLogicalBlock */ device_info.LogicalBlockSize * device_info.NumLogicalBlockExposed /* Capacity */ }, device_info.VolumeSpeed == 1UL ? TVolume::TDesc::TStorageSpeed::Fast : TVolume::TDesc::TStorageSpeed::Slow, /* storage speed */ device_info.ReplicationFactor, /* replication factor */ device_info.NumDevicesInVolume / device_info.ReplicationFactor, /* the number of logical extents */ (device_info.StripeSizeKB * 1024) / device_info.LogicalBlockSize, /* num logical block per stripe */ device_info.MinDiscardBlocks, /* MinDiscardAllocBlocks */ 0.85 /* HighUtilizationThreshold */ }, CacheCb, Scheduler)); std::unique_ptr<TDevice> new_device(new TPersistentDevice(Controller, path_to_device.c_str(), path, device_info.LogicalBlockSize, /* logical block size */ device_info.PhysicalBlockSize, /* physical block size */ device_info.NumLogicalBlockExposed, /* num logical block exposed */ do_fsync, do_corruption_check)); volume->AddDevice(new_device.get(), device_info.VolumeDeviceNumber); VolumeById.emplace(device_info.VolumeId, std::move(volume)); PersistentDeviceSet.insert(std::move(new_device)); } } return true; }); /* for each volume, initialize it with the logical extent set's we've collected. */ for (const auto &vol : VolumeById) { string instance_name(vol.first.InstanceName); TExtentSet extent_set; const size_t num_devices = vol.second->GetNumDevices(); for (TVolume::TDeviceCollection::TCursor csr(vol.second->GetDeviceCollection()); csr; ++csr) { const TPersistentDevice *device = dynamic_cast<TPersistentDevice *>(&*csr); assert(device); auto ret = StigDeviceMap.find(std::string(device->GetDevicePath())); assert(ret != StigDeviceMap.end()); const auto &device_info = ret->second; /* this is where we check that the description of the volume stored in the device matches what we've collected */ if (device_info.NumDevicesInVolume != num_devices) { syslog(LOG_ERR, "Missing device(s) for volume, found [%ld], expected [%ld]", num_devices, device_info.NumDevicesInVolume); } extent_set.insert(TLogicalExtent{device_info.LogicalExtentStart, device_info.LogicalExtentSize}); } vol.second->Init(extent_set); auto vol_man = VolumeManagerByInstance.find(instance_name); if (vol_man == VolumeManagerByInstance.end()) { VolumeManagerByInstance.emplace(instance_name, std::unique_ptr<TVolumeManager>(new TVolumeManager(Scheduler))); } auto &volume_manager = VolumeManagerByInstance.find(instance_name)->second; volume_manager->AddExistingVolume(vol.second.get(), vol.first.Id); } } void TDiskUtil::List(std::stringstream &ss) const { assert(this); ss << "Volumes:" << endl; for (const auto &vol : VolumeById) { ss << "ID: " << vol.first.Id << "\t" << vol.first.InstanceName << "\t" << vol.second->GetNumDevices() << endl; for (TVolume::TDeviceCollection::TCursor csr(vol.second->GetDeviceCollection()); csr; ++csr) { ss << "\tdevice" << endl; } } } void TDiskUtil::CreateVolume(const std::string &instance_name, const size_t num_devices, const std::set<std::string> &device_set, const TVolume::TDesc::TKind kind, const size_t replication_factor, const size_t stripe_size_in_kb, const TVolume::TDesc::TStorageSpeed storage_speed, bool do_fsync) { assert(this); const size_t logical_block_size = 512; /* TODO */ const size_t physical_block_size = 512; /* TODO */ size_t discard_support_count = 0UL; size_t discard_gran = 0UL; /* figure out our discard granularity and support */ for (const auto &dev_name : device_set) { const size_t discard_max_bytes = TDeviceUtil::GetDiscardMaxBytes(dev_name); const size_t discard_granularity = TDeviceUtil::GetDiscardGranularity(dev_name); if (discard_support_count == 0) { discard_gran = discard_granularity; } else { if (discard_granularity != discard_gran) { throw std::runtime_error("All devices in a volume must have the same discard granularity"); } } discard_support_count += (discard_max_bytes > 0UL && discard_granularity > 0UL) ? 1UL : 0UL; } if (discard_support_count != device_set.size() && discard_support_count != 0) { throw std::runtime_error("All devices in a volume must support or not support discard. Please do not mix and match."); } const size_t num_blocks_required_for_discard = static_cast<size_t>(ceil(static_cast<double>(discard_gran) / Util::PhysicalBlockSize)); if (discard_support_count > 0) { const size_t num_bytes_required_for_discard = num_blocks_required_for_discard * Util::PhysicalBlockSize; if ((stripe_size_in_kb * 1024) % num_bytes_required_for_discard != 0) { throw std::runtime_error("Stripe size must be a multiple of ceil(discard_granularity / StigBlockSize) * StigBlockSize"); } } if (instance_name.size() < 1 || instance_name.size() > MaxInstanceNameSize) { throw std::runtime_error("Instance name must be of size >= 1 and <= 24"); } if (num_devices != device_set.size()) { throw std::runtime_error("Number of devices provided does not match"); } if (num_devices == 0) { throw std::runtime_error("Cannot create new volume with 0 devices"); } if (num_devices % replication_factor != 0) { throw std::runtime_error("Number of devices must be a multiple of the replication factor"); } if (((stripe_size_in_kb * 1024) % (Util::PhysicalBlockSize * 8UL) != 0)) { stringstream ss; ss << "Stripe size must be a multiple of 8 * PhysicalBlockSize(" << Util::PhysicalBlockSize << ") bytes. [" << (8 * Util::PhysicalBlockSize / 1024) << "KB]"; throw std::runtime_error(ss.str()); } if (replication_factor == 0) { throw std::runtime_error("Replication factor must be >= 1"); } /* find the minimum number of logical blocks supported amongst the set, then round down to a multiple of the block size, and subtract the super block. */ size_t min_logical_blocks = -1; for (const auto &dev_path : device_set) { /* TODO: some devices won't use this path, figure out how to handle all devices. */ string path_to_device_info = TDeviceUtil::GetPathToPartitionInfo(dev_path) + "size"; Base::TFd size_fd; try { size_fd = open(path_to_device_info.c_str(), O_RDONLY); } catch (const std::exception &ex) { syslog(LOG_ERR, "Can't open size file [%s], error: [%s]", path_to_device_info.c_str(), ex.what()); throw; } char size_max_bytes[64]; char *ptr = size_max_bytes; Base::IfLt0(pread(size_fd, size_max_bytes, 64, 0)); size_t num_logical_blocks = strtol(ptr, &ptr, 10); min_logical_blocks = std::min(min_logical_blocks, num_logical_blocks); } const size_t num_logical_per_stig_physical = Util::PhysicalBlockSize / logical_block_size; /* take off 1 for the super block */ min_logical_blocks = ((min_logical_blocks / num_logical_per_stig_physical) - 1) * num_logical_per_stig_physical; /* round down to the striping factor if they want to use one */ switch (kind) { case TVolume::TDesc::Striped: { min_logical_blocks = (((min_logical_blocks * logical_block_size) / (stripe_size_in_kb * 1024)) * (stripe_size_in_kb * 1024)) / logical_block_size; break; } case TVolume::TDesc::Chained: { break; } default: { throw std::logic_error("Unhandled volume strategy"); } } auto device_iter = device_set.begin(); TDeviceUtil::TStigDevice new_device_info; std::unique_ptr<TVolume> volume(new TVolume(TVolume::TDesc{ kind, TDevice::TDesc { TDevice::TDesc::TKind::SSD, /* TODO */ logical_block_size, 512, /* PhysicalBlockSize*/ min_logical_blocks, /* NumLogicalBlock */ min_logical_blocks * logical_block_size /* Capacity */ }, storage_speed, replication_factor, num_devices / replication_factor, (stripe_size_in_kb * 1024) / logical_block_size, /* num logical block per stripe */ num_blocks_required_for_discard, /* MinDiscardAllocBlocks */ 0.85 /* HighUtilizationThreshold */ }, CacheCb, Scheduler)); auto vol_man = VolumeManagerByInstance.find(instance_name); if (vol_man == VolumeManagerByInstance.end()) { VolumeManagerByInstance.emplace(instance_name, std::unique_ptr<TVolumeManager>(new TVolumeManager(Scheduler))); } auto &volume_manager = VolumeManagerByInstance.find(instance_name)->second; size_t volume_id_num = volume_manager->RequestNewVolumeId(); size_t device_num = 0UL; for (const auto &dev_path : device_set) { string path_to_device = "/dev/" + dev_path; std::unique_ptr<TDevice> new_device(new TPersistentDevice(Controller, path_to_device.c_str(), dev_path.c_str(), logical_block_size, /* logical block size */ 512, /* physical block size */ min_logical_blocks, /* num logical block */ do_fsync, true)); volume->AddDevice(new_device.get(), device_num); ++device_num; PersistentDeviceSet.insert(std::move(new_device)); } volume_manager->AddNewVolume(volume.get()); const std::vector<TLogicalExtent> &extent_vec = volume->GetLogicalExtentVec(); TVolumeId vol_id; vol_id.Id = volume_id_num; memset(vol_id.InstanceName, 0, MaxInstanceNameSize); memcpy(vol_id.InstanceName, instance_name.c_str(), instance_name.size()); VolumeById.emplace(vol_id, std::move(volume)); new_device_info.VolumeId = vol_id; new_device_info.NumDevicesInVolume = num_devices; new_device_info.ReplicationFactor = replication_factor; switch (kind) { case TVolume::TDesc::Striped: { new_device_info.VolumeStrategy = 1UL; new_device_info.StripeSizeKB = stripe_size_in_kb; break; } case TVolume::TDesc::Chained: { new_device_info.VolumeStrategy = 2UL; new_device_info.StripeSizeKB = 0UL; break; } default: { throw std::logic_error("Unhandled volume strategy"); } } switch (storage_speed) { case TVolume::TDesc::TStorageSpeed::Fast: { new_device_info.VolumeSpeed = 1UL; break; } case TVolume::TDesc::TStorageSpeed::Slow: { new_device_info.VolumeSpeed = 2UL; break; } default: { throw std::logic_error("Unhandled volume speed"); } } new_device_info.LogicalBlockSize = logical_block_size; new_device_info.PhysicalBlockSize = physical_block_size; new_device_info.NumLogicalBlockExposed = min_logical_blocks; new_device_info.MinDiscardBlocks = std::max(8UL, num_blocks_required_for_discard); for (size_t i = 0; i < num_devices; ++i, ++device_iter) { new_device_info.VolumeDeviceNumber = i; new_device_info.LogicalExtentStart = extent_vec[i / replication_factor].Start; new_device_info.LogicalExtentSize = extent_vec[i / replication_factor].Span; assert(device_iter != device_set.end()); string path_to_device = "/dev/"; path_to_device += *device_iter; TDeviceUtil::ModifyDevice(path_to_device.c_str(), new_device_info); } syslog(LOG_INFO, "Creating volume with [%ld] devices for volume id [%s, %ld]", num_devices, instance_name.c_str(), volume_id_num); } TVolumeManager *TDiskUtil::GetVolumeManager(const std::string &instance_name) const { assert(this); auto ret = VolumeManagerByInstance.find(instance_name); if (ret == VolumeManagerByInstance.end()) { throw std::runtime_error("No volume(s) for given instance name. Please use the stig disk manager to create one."); } return ret->second.get(); }
49.389381
161
0.637162
[ "vector" ]
28d7ad87b3ddca35c5d5c5d211eb62bed3373f85
2,166
hh
C++
oglrap/RendererBase.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
oglrap/RendererBase.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
oglrap/RendererBase.hh
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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. */ #pragma once #include <cstddef> #include "plog/Severity.h" class Prog ; /** RendererBase ============== Base class of both geometry(Renderer) and event(Rdr) renderers that handles the mechanics of compiling and linking of the shader source code. NB ShaderBase would be a better name, in light of transform feedback (and maybe compute shaders in future). **/ #include "OGLRAP_API_EXPORT.hh" class OGLRAP_API RendererBase { public: static const plog::Severity LEVEL ; public: RendererBase(const char* tag, const char* dir=NULL, const char* incl_path=NULL, bool ubo=false); const char* getName() const ; unsigned getIndex() const ; const char* getShaderTag() const ; const char* getShaderDir() const ; const char* getInclPath() const ; void setIndexBBox(unsigned index, bool bbox=false); void setVerbosity(unsigned verbosity); void setNoFrag(bool nofrag); public: void make_shader(); public: // split the make, for transform feedback where need to setup varyings between create and link void create_shader(); void link_shader(); protected: Prog* m_shader ; int m_program ; unsigned m_verbosity ; private: const char* m_shaderdir ; const char* m_shadertag ; const char* m_incl_path ; unsigned m_index ; bool m_bbox ; const char* m_name ; };
28.88
102
0.6759
[ "geometry", "transform" ]
28da1c77a561d15f1588fa9f6c0716775ca093a5
2,319
cpp
C++
source/shape/ShapeGatherV2.cpp
loveltyoic/MNN
ff405a307819a7228e0d1fc02c00c68021745b0a
[ "Apache-2.0" ]
1
2019-08-09T03:16:49.000Z
2019-08-09T03:16:49.000Z
source/shape/ShapeGatherV2.cpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
null
null
null
source/shape/ShapeGatherV2.cpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
1
2021-01-15T06:28:11.000Z
2021-01-15T06:28:11.000Z
// // ShapeGatherV2.cpp // MNN // // Created by MNN on 2019/01/10. // Copyright © 2018, Alibaba Group Holding Limited // #include "Macro.h" #include "SizeComputer.hpp" namespace MNN { class GatherV2Computer : public SizeComputer { virtual bool onComputeSize(const MNN::Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) const override { auto params = inputs[0]; auto indices = inputs[1]; MNN_ASSERT(indices->getType().code == halide_type_int); int axis = 0; if (inputs.size() == 3) { auto axis_tensor = inputs[2]; // copy data from device to host if needed if (!axis_tensor->host<int32_t>() && axis_tensor->deviceId()) { std::shared_ptr<Tensor> tmp(Tensor::createHostTensorFromDevice(axis_tensor, true)); axis = tmp->host<int32_t>()[0]; } else { axis = axis_tensor->host<int32_t>()[0]; } } MNN_ASSERT(axis > -params->buffer().dimensions && axis < params->buffer().dimensions); if (axis < 0) { axis = params->buffer().dimensions + axis; } const int gather_dim_size = params->buffer().dim[axis].extent; MNN_ASSERT(gather_dim_size <= std::numeric_limits<int32_t>::max()); const int numDimensions = params->buffer().dimensions + indices->buffer().dimensions - 1; MNN_ASSERT(axis <= numDimensions); std::vector<int> result_shape; for (int i = 0; i < axis; i++) { result_shape.push_back(params->buffer().dim[i].extent); } for (int i = 0; i < indices->buffer().dimensions; i++) { result_shape.push_back(indices->buffer().dim[i].extent); } for (int i = axis + 1; i < params->buffer().dimensions; i++) { result_shape.push_back(params->buffer().dim[i].extent); } outputs[0]->buffer().dimensions = (int)result_shape.size(); outputs[0]->buffer().type = params->buffer().type; for (int i = 0; i < result_shape.size(); i++) { outputs[0]->buffer().dim[i].extent = result_shape.at(i); } return true; } }; REGISTER_SHAPE(GatherV2Computer, OpType_GatherV2); } // namespace MNN
34.102941
99
0.570073
[ "vector" ]
28dac25010f22463913be5b31a568957bff5b074
39,115
hpp
C++
include/librealsense2/hpp/rs_frame.hpp
alipek/librealsense
8c35ed0c8464a9a484c9c08eab323092e57e9821
[ "Apache-2.0" ]
1
2021-05-05T17:46:11.000Z
2021-05-05T17:46:11.000Z
include/librealsense2/hpp/rs_frame.hpp
alipek/librealsense
8c35ed0c8464a9a484c9c08eab323092e57e9821
[ "Apache-2.0" ]
null
null
null
include/librealsense2/hpp/rs_frame.hpp
alipek/librealsense
8c35ed0c8464a9a484c9c08eab323092e57e9821
[ "Apache-2.0" ]
1
2021-05-13T06:08:38.000Z
2021-05-13T06:08:38.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #ifndef LIBREALSENSE_RS2_FRAME_HPP #define LIBREALSENSE_RS2_FRAME_HPP #include "rs_types.hpp" namespace rs2 { class frame_source; class frame_queue; class syncer; class processing_block; class pointcloud; class sensor; class frame; class pipeline_profile; class points; class video_stream_profile; class stream_profile { public: /** * Class to store the profile of stream */ stream_profile() : _profile(nullptr) {} /** * Return the specific stream index * \return int - stream index */ int stream_index() const { return _index; } /** * Return the stream type * \return rs2_stream - stream type */ rs2_stream stream_type() const { return _type; } /** * Return the stream format * \return rs2_format - stream format */ rs2_format format() const { return _format; } /** * Return the stream frame per second * \return int - frame rate */ int fps() const { return _framerate; } /** * Return the assigned unique index when the stream was created * \return int - unique id */ int unique_id() const { return _uid; } /** * Clone the current profile and change the type, index and format to input parameters * \param[in] type - will change the stream type from the cloned profile. * \param[in] index - will change the stream index from the cloned profile. * \param[in] format - will change the stream format from the cloned profile. * \return stream_profile - return the cloned stream profile. */ stream_profile clone(rs2_stream type, int index, rs2_format format) const { rs2_error* e = nullptr; auto ref = rs2_clone_stream_profile(_profile, type, index, format, &e); error::handle(e); stream_profile res(ref); res._clone = std::shared_ptr<rs2_stream_profile>(ref, [](rs2_stream_profile* r) { rs2_delete_stream_profile(r); }); return res; } /** * Comparison operator, compare if two stream profiles are the same * \param[in] rhs - stream profile to compare with. * \return bool - true or false. */ bool operator==(const stream_profile& rhs) { return stream_index() == rhs.stream_index() && stream_type() == rhs.stream_type() && format() == rhs.format() && fps() == rhs.fps(); } /** * Template function, checking if the instance belongs to specific class type * \return bool - true or false. */ template<class T> bool is() const { T extension(*this); return extension; } /** * Template function, casting the instance as another class type * \return class instance - pointer or null. */ template<class T> T as() const { T extension(*this); return extension; } /** * Return the string of stream name * \return string - stream name. */ std::string stream_name() const { std::stringstream ss; ss << rs2_stream_to_string(stream_type()); if (stream_index() != 0) ss << " " << stream_index(); return ss.str(); } /** * Checks if stream profile is marked/assigned as default, meaning that the profile will be selected when the user requests stream configuration using wildcards (RS2_DEPTH, -1,-1,... * \return bool - true or false. */ bool is_default() const { return _default; } /** * Checks if the profile is valid * \return bool - true or false. */ operator bool() const { return _profile != nullptr; } /** * Get back the internal stream profile instance * \return rs2_stream_profile* - internal implementation of the profile class */ const rs2_stream_profile* get() const { return _profile; } /** Operator implement, return the internal stream profile instance. * \return rs2_stream_profile* - internal instance to communicate with real implementation. */ /** * Get the extrinsic transformation between two profiles (representing physical sensors) * \param[in] stream_profile to - the stream profile (another sensor) to be based to return the extrinsic * \return rs2_stream_profile* - internal instance to communicate with real implementation. */ rs2_extrinsics get_extrinsics_to(const stream_profile& to) const { rs2_error* e = nullptr; rs2_extrinsics res; rs2_get_extrinsics(get(), to.get(), &res, &e); error::handle(e); return res; } /** * Assign extrinsic transformation parameters to a specific profile (sensor). The extrinsic information is generally available as part of the camera calibration, and librealsense is responsible for retrieving and assigning these parameters where appropriate. * This specific function is intended for synthetic/mock-up (software) devices for which the parameters are produced and injected by the user. * \param[in] stream_profile to - which stream profile to be registered with the extrinsic. * \param[in] rs2_extrinsics extrinsics - the extrinsics to be registered. */ void register_extrinsics_to(const stream_profile& to, rs2_extrinsics extrinsics) { rs2_error* e = nullptr; rs2_register_extrinsics(get(), to.get(), extrinsics, &e); error::handle(e); } bool is_cloned() { return bool(_clone); } explicit stream_profile(const rs2_stream_profile* profile) : _profile(profile) { rs2_error* e = nullptr; rs2_get_stream_profile_data(_profile, &_type, &_format, &_index, &_uid, &_framerate, &e); error::handle(e); _default = !!(rs2_is_stream_profile_default(_profile, &e)); error::handle(e); } operator const rs2_stream_profile*() { return _profile; } explicit operator std::shared_ptr<rs2_stream_profile>() { return _clone; } protected: friend class rs2::sensor; friend class rs2::frame; friend class rs2::pipeline_profile; friend class rs2::video_stream_profile; const rs2_stream_profile* _profile; std::shared_ptr<rs2_stream_profile> _clone; int _index = 0; int _uid = 0; int _framerate = 0; rs2_format _format = RS2_FORMAT_ANY; rs2_stream _type = RS2_STREAM_ANY; bool _default = false; }; class video_stream_profile : public stream_profile { public: /** * Stream profile instance which contains additional video attributes * \param[in] stream_profile sp - assign exisiting stream_profile to this instance. */ explicit video_stream_profile(const stream_profile& sp) : stream_profile(sp) { rs2_error* e = nullptr; if ((rs2_stream_profile_is(sp.get(), RS2_EXTENSION_VIDEO_PROFILE, &e) == 0 && !e)) { _profile = nullptr; } error::handle(e); if (_profile) { rs2_get_video_stream_resolution(_profile, &_width, &_height, &e); error::handle(e); } } int width() const { return _width; } int height() const { return _height; } /** * Get stream profile instrinsics attributes * \return rs2_intrinsics - stream intrinsics. */ rs2_intrinsics get_intrinsics() const { rs2_error* e = nullptr; rs2_intrinsics intr; rs2_get_video_stream_intrinsics(_profile, &intr, &e); error::handle(e); return intr; } bool operator==(const video_stream_profile& other) const { return (((stream_profile&)*this)==other && width() == other.width() && height() == other.height()); } using stream_profile::clone; /** * Clone current profile and change the type, index and format to input parameters * \param[in] type - will change the stream type from the cloned profile. * \param[in] index - will change the stream index from the cloned profile. * \param[in] format - will change the stream format from the cloned profile. * \param[in] width - will change the width of the profile * \param[in] height - will change the height of the profile * \param[in] intr - will change the intrinsics of the profile * \return stream_profile - return the cloned stream profile. */ stream_profile clone(rs2_stream type, int index, rs2_format format, int width, int height, const rs2_intrinsics& intr) const { rs2_error* e = nullptr; auto ref = rs2_clone_video_stream_profile(_profile, type, index, format, width, height, &intr, &e); error::handle(e); stream_profile res(ref); res._clone = std::shared_ptr<rs2_stream_profile>(ref, [](rs2_stream_profile* r) { rs2_delete_stream_profile(r); }); return res; } private: int _width = 0; int _height = 0; }; class motion_stream_profile : public stream_profile { public: /** * Stream profile instance which contains IMU-specific intrinsics. * \param[in] stream_profile sp - assign exisiting stream_profile to this instance. */ explicit motion_stream_profile(const stream_profile& sp) : stream_profile(sp) { rs2_error* e = nullptr; if ((rs2_stream_profile_is(sp.get(), RS2_EXTENSION_MOTION_PROFILE, &e) == 0 && !e)) { _profile = nullptr; } error::handle(e); } /** * Returns scale/bias/covariances of a the motion sensors * \return rs2_motion_device_intrtinsic - stream motion intrinsics */ rs2_motion_device_intrinsic get_motion_intrinsics() const { rs2_error* e = nullptr; rs2_motion_device_intrinsic intrin; rs2_get_motion_intrinsics(_profile, &intrin, &e); error::handle(e); return intrin; } }; class pose_stream_profile : public stream_profile { public: /** * Stream profile instance with an explicit pose extension type. * \param[in] stream_profile sp - assign exisiting stream_profile to this instance. */ explicit pose_stream_profile(const stream_profile& sp) : stream_profile(sp) { rs2_error* e = nullptr; if ((rs2_stream_profile_is(sp.get(), RS2_EXTENSION_POSE_PROFILE, &e) == 0 && !e)) { _profile = nullptr; } error::handle(e); } }; /** Interface for frame filtering functionality */ class filter_interface { public: virtual rs2::frame process(rs2::frame frame) const = 0; virtual ~filter_interface() = default; }; class frame { public: /** * Base class for multiple frame extensions */ frame() : frame_ref(nullptr) {} /** * Base class for multiple frame extensions with internal frame handle * \param[in] rs2_frame frame_ref - internal frame instance */ frame(rs2_frame* ref) : frame_ref(ref) { #ifdef _DEBUG if (ref) { rs2_error* e = nullptr; auto r = rs2_get_frame_number(ref, &e); if (!e) frame_number = r; auto s = rs2_get_frame_stream_profile(ref, &e); if (!e) profile = stream_profile(s); } else { frame_number = 0; profile = stream_profile(); } #endif } /** * Change the internal frame handle to the one in parameter, then put the other frame internal frame handle to nullptr * \param[in] frame other - another frame instance to be pointed to */ frame(frame&& other) noexcept : frame_ref(other.frame_ref) { other.frame_ref = nullptr; #ifdef _DEBUG frame_number = other.frame_number; profile = other.profile; #endif } /** * Change the internal frame handle to the one in parameter, the function exchange the internal frame handle. * \param[in] frame other - another frame instance to be pointed to */ frame& operator=(frame other) { swap(other); return *this; } /** * Set the internal frame handle to the one in parameter, the function create additional reference if internal reference exist. * \param[in] frame other - another frame instance to be pointed to */ frame(const frame& other) : frame_ref(other.frame_ref) { if (frame_ref) add_ref(); #ifdef _DEBUG frame_number = other.frame_number; profile = other.profile; #endif } /** * Swap the internal frame handle with the one in parameter * \param[in] frame other - another frame instance to be swaped */ void swap(frame& other) { std::swap(frame_ref, other.frame_ref); #ifdef _DEBUG std::swap(frame_number, other.frame_number); std::swap(profile, other.profile); #endif } /** * releases the frame handle */ ~frame() { if (frame_ref) { rs2_release_frame(frame_ref); } } /** * keep the frame, otherwise if no refernce to the frame, the frame will be released. */ void keep() { rs2_keep_frame(frame_ref); } /** * Parenthesis operator check if internal frame handle is valid. * \return bool - true or false. */ operator bool() const { return frame_ref != nullptr; } rs2_sensor* get_sensor() { rs2_error* e = nullptr; auto r = rs2_get_frame_sensor(frame_ref, &e); error::handle(e); return r; } /** * retrieve the time at which the frame was captured * During the frame's lifetime it receives timestamps both at the device and host levels. * The different timestamps are gathered and managed under the frame's Metadata attributes. * Chronologically the list of timestamps comprises of: * SENSOR_TIMESTAMP - Device clock. For video sensors designates the middle of exposure. Requires metadata support. * FRAME_TIMESTAMP - Device clock. Stamped at the beginning of frame readout and transfer. Requires metadata support. * BACKEND_TIMESTAMP - Host (EPOCH) clock in Kernel space. Frame transfer from USB Controller to the USB Driver. * TIME_OF_ARRIVAL - Host (EPOCH) clock in User space. Frame transfer from the USB Driver to Librealsense. * * During runtime the SDK dynamically selects the most correct representaion, based on both device and host capabilities: * In case the frame metadata is not configured: * - The function call provides the TIME_OF_ARRIVAL stamp. * In case the metadata is available the function returns: * - `HW Timestamp` (FRAME_TIMESTAMP), or * - `Global Timestamp` Host-corrected derivative of `HW Timestamp` required for multi-sensor/device synchronization * - The user can select between the unmodified and the host-calculated Hardware Timestamp by toggling * the `RS2_OPTION_GLOBAL_TIME_ENABLED` option. * To query which of the three alternatives is active use `get_frame_timestamp_domain()` function call * \return the timestamp of the frame, in milliseconds according to the elaborated flow */ double get_timestamp() const { rs2_error* e = nullptr; auto r = rs2_get_frame_timestamp(frame_ref, &e); error::handle(e); return r; } /** retrieve the timestamp domain * \return timestamp domain (clock name) for timestamp values */ rs2_timestamp_domain get_frame_timestamp_domain() const { rs2_error* e = nullptr; auto r = rs2_get_frame_timestamp_domain(frame_ref, &e); error::handle(e); return r; } /** retrieve the current value of a single frame_metadata * \param[in] frame_metadata the frame_metadata whose value should be retrieved * \return the value of the frame_metadata */ rs2_metadata_type get_frame_metadata(rs2_frame_metadata_value frame_metadata) const { rs2_error* e = nullptr; auto r = rs2_get_frame_metadata(frame_ref, frame_metadata, &e); error::handle(e); return r; } /** determine if the device allows a specific metadata to be queried * \param[in] frame_metadata the frame_metadata to check for support * \return true if the frame_metadata can be queried */ bool supports_frame_metadata(rs2_frame_metadata_value frame_metadata) const { rs2_error* e = nullptr; auto r = rs2_supports_frame_metadata(frame_ref, frame_metadata, &e); error::handle(e); return r != 0; } /** * retrieve frame number (from frame handle) * \return the frame number of the frame, in milliseconds since the device was started */ unsigned long long get_frame_number() const { rs2_error* e = nullptr; auto r = rs2_get_frame_number(frame_ref, &e); error::handle(e); return r; } /** * retrieve data size from frame handle * \return the number of bytes in frame */ const int get_data_size() const { rs2_error* e = nullptr; auto r = rs2_get_frame_data_size(frame_ref, &e); error::handle(e); return r; } /** * retrieve data from frame handle * \return the pointer to the start of the frame data */ const void* get_data() const { rs2_error* e = nullptr; auto r = rs2_get_frame_data(frame_ref, &e); error::handle(e); return r; } /** * retrieve stream profile from frame handle * \return stream_profile - the pointer to the stream profile */ stream_profile get_profile() const { rs2_error* e = nullptr; auto s = rs2_get_frame_stream_profile(frame_ref, &e); error::handle(e); return stream_profile(s); } /** * Template function, checking if current instance is the type of another class * \return bool - true or false. */ template<class T> bool is() const { T extension(*this); return extension; } /** * Template function, cast current instance as the type of another class * \return class instance. */ template<class T> T as() const { T extension(*this); return extension; } /** * Retrieve back the internal frame handle * \return rs2_frame - internal frame handle. */ rs2_frame* get() const { return frame_ref; } explicit operator rs2_frame*() { return frame_ref; } frame apply_filter(filter_interface& filter) { return filter.process(*this); } protected: /** * add additional reference to a frame without duplicating frame data * \param[out] result new frame reference, release by destructor * \return true if cloning was successful */ void add_ref() const { rs2_error* e = nullptr; rs2_frame_add_ref(frame_ref, &e); error::handle(e); } void reset() { if (frame_ref) { rs2_release_frame(frame_ref); } frame_ref = nullptr; } private: friend class rs2::frame_source; friend class rs2::frame_queue; friend class rs2::syncer; friend class rs2::processing_block; friend class rs2::pointcloud; friend class rs2::points; rs2_frame* frame_ref; #ifdef _DEBUG stream_profile profile; unsigned long long frame_number = 0; #endif }; class video_frame : public frame { public: /** * Extends the frame class with additional video related attributes and functions * \param[in] frame - existing frame instance */ video_frame(const frame& f) : frame(f) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_VIDEO_FRAME, &e) == 0 && !e)) { reset(); } error::handle(e); } /** * returns image width in pixels * \return frame width in pixels */ int get_width() const { rs2_error* e = nullptr; auto r = rs2_get_frame_width(get(), &e); error::handle(e); return r; } /** * returns image height in pixels * \return frame height in pixels */ int get_height() const { rs2_error* e = nullptr; auto r = rs2_get_frame_height(get(), &e); error::handle(e); return r; } /** * retrieve frame stride, meaning the actual line width in memory in bytes (not the logical image width) * \return stride in bytes */ int get_stride_in_bytes() const { rs2_error* e = nullptr; auto r = rs2_get_frame_stride_in_bytes(get(), &e); error::handle(e); return r; } /** * retrieve bits per pixel * \return number of bits per one pixel */ int get_bits_per_pixel() const { rs2_error* e = nullptr; auto r = rs2_get_frame_bits_per_pixel(get(), &e); error::handle(e); return r; } /** * retrieve bytes per pixel * \return number of bytes per one pixel */ int get_bytes_per_pixel() const { return get_bits_per_pixel() / 8; } /** * Calculate the rectangle size on the specific target * \param[in] frame Left or right camera frame of size 256x144 * \param[out] rec_sides The four rectangle side sizes in pixels with the order of top, bottom, left, and right * \return true if succeeded */ bool extract_target_dimensions(rs2_calib_target_type calib_type, float* target_dims, unsigned int target_dims_size) const { rs2_error* e = nullptr; rs2_extract_target_dimensions(get(), calib_type, target_dims, target_dims_size, &e); error::handle(e); return (e == nullptr); } }; struct vertex { float x, y, z; operator const float*() const { return &x; } }; struct texture_coordinate { float u, v; operator const float*() const { return &u; } }; class points : public frame { public: /** * Extends the frame class with additional point cloud related attributes and functions */ points() : frame(), _size(0) {} /** * Extends the frame class with additional point cloud related attributes and functions * \param[in] frame - existing frame instance */ points(const frame& f) : frame(f), _size(0) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_POINTS, &e) == 0 && !e)) { reset(); } error::handle(e); if (get()) { _size = rs2_get_frame_points_count(get(), &e); error::handle(e); } } /** * Retrieve the vertices of the point cloud * \param[in] vertex* - pointer of vertex sturcture */ const vertex* get_vertices() const { rs2_error* e = nullptr; auto res = rs2_get_frame_vertices(get(), &e); error::handle(e); return (const vertex*)res; } /** * Export the point cloud to a PLY file * \param[in] string fname - file name of the PLY to be saved * \param[in] video_frame texture - the texture for the PLY. */ void export_to_ply(const std::string& fname, video_frame texture) { rs2_frame* ptr = nullptr; std::swap(texture.frame_ref, ptr); rs2_error* e = nullptr; rs2_export_to_ply(get(), fname.c_str(), ptr, &e); error::handle(e); } /** * Retrieve the texture coordinates (uv map) for the point cloud * \return texture_coordinate* - pointer of texture coordinates. */ const texture_coordinate* get_texture_coordinates() const { rs2_error* e = nullptr; auto res = rs2_get_frame_texture_coordinates(get(), &e); error::handle(e); return (const texture_coordinate*)res; } size_t size() const { return _size; } private: size_t _size; }; class depth_frame : public video_frame { public: /** * Extends the video_frame class with additional depth related attributes and functions * \param[in] frame - existing frame instance */ depth_frame(const frame& f) : video_frame(f) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_DEPTH_FRAME, &e) == 0 && !e)) { reset(); } error::handle(e); } /** * Provide the depth in meters at the given pixel * \param[in] int x - pixel's x coordinate. * \param[in] int y - pixel's y coordinate. * \return float - depth in metric units at given pixel */ float get_distance(int x, int y) const { rs2_error * e = nullptr; auto r = rs2_depth_frame_get_distance(get(), x, y, &e); error::handle(e); return r; } /** * Provide the scaling factor to use when converting from get_data() units to meters * \return float - depth, in meters, per 1 unit stored in the frame data */ float get_units() const { rs2_error * e = nullptr; auto r = rs2_depth_frame_get_units( get(), &e ); error::handle( e ); return r; } }; class disparity_frame : public depth_frame { public: /** * Extend depth_frame class with additional disparity related attributes/functions * \param[in] frame - existing frame instance */ disparity_frame(const frame& f) : depth_frame(f) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_DISPARITY_FRAME, &e) == 0 && !e)) { reset(); } error::handle(e); } /** * Retrieve the distance between the two IR sensors. * \return float - baseline. */ float get_baseline(void) const { rs2_error * e = nullptr; auto r = rs2_depth_stereo_frame_get_baseline(get(), &e); error::handle(e); return r; } }; class motion_frame : public frame { public: /** * Extends the frame class with additional motion related attributes and functions * \param[in] frame - existing frame instance */ motion_frame(const frame& f) : frame(f) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_MOTION_FRAME, &e) == 0 && !e)) { reset(); } error::handle(e); } /** * Retrieve the motion data from IMU sensor * \return rs2_vector - 3D vector in Euclidean coordinate space. */ rs2_vector get_motion_data() const { auto data = reinterpret_cast<const float*>(get_data()); return rs2_vector{ data[0], data[1], data[2] }; } }; class pose_frame : public frame { public: /** * Extends the frame class with additional pose related attributes and functions * \param[in] frame - existing frame instance */ pose_frame(const frame& f) : frame(f) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_POSE_FRAME, &e) == 0 && !e)) { reset(); } error::handle(e); } /** * Retrieve the pose data from T2xx position tracking sensor * \return rs2_pose - orientation and velocity data. */ rs2_pose get_pose_data() const { rs2_pose pose_data; rs2_error* e = nullptr; rs2_pose_frame_get_pose_data(get(), &pose_data, &e); error::handle(e); return pose_data; } }; class frameset : public frame { public: /** * Extends the frame class with additional frameset related attributes and functions */ frameset() :_size(0) {}; /** * Extends the frame class with additional frameset related attributes and functions * \param[in] frame - existing frame instance */ frameset(const frame& f) : frame(f), _size(0) { rs2_error* e = nullptr; if (!f || (rs2_is_frame_extendable_to(f.get(), RS2_EXTENSION_COMPOSITE_FRAME, &e) == 0 && !e)) { reset(); // TODO - consider explicit constructor to move resultion to compile time } error::handle(e); if (get()) { _size = rs2_embedded_frames_count(get(), &e); error::handle(e); } } /** * Retrieve the first frame of a specific stream and optionally with a specific format. If no frame is found, return an empty frame instance. * \param[in] rs2_stream s - frame to be retrieved from this stream type. * \param[in] rs2_format f - frame to be retrieved from this format type. * \return frame - first found frame with s stream type. */ frame first_or_default(rs2_stream s, rs2_format f = RS2_FORMAT_ANY) const { frame result; foreach_rs([&result, s, f](frame frm) { if (!result && frm.get_profile().stream_type() == s && (f == RS2_FORMAT_ANY || f == frm.get_profile().format())) { result = std::move(frm); } }); return result; } /** * Retrieve the first frame of a specific stream type and optionally with a specific format. If no frame is found, an error will be thrown. * \param[in] rs2_stream s - frame to be retrieved from this stream type. * \param[in] rs2_format f - frame to be retrieved from this format type. * \return frame - first found frame with s stream type. */ frame first(rs2_stream s, rs2_format f = RS2_FORMAT_ANY) const { auto frm = first_or_default(s, f); if (!frm) throw error("Frame of requested stream type was not found!"); return frm; } /** * Retrieve the first depth frame, if no frame is found, return an empty frame instance. * \return depth_frame - first found depth frame. */ depth_frame get_depth_frame() const { auto f = first_or_default(RS2_STREAM_DEPTH, RS2_FORMAT_Z16); return f.as<depth_frame>(); } /** * Retrieve the first color frame, if no frame is found, search for the color frame from IR stream. If one still can't be found, return an empty frame instance. * \return video_frame - first found color frame. */ video_frame get_color_frame() const { auto f = first_or_default(RS2_STREAM_COLOR); if (!f) { auto ir = first_or_default(RS2_STREAM_INFRARED); if (ir && ir.get_profile().format() == RS2_FORMAT_RGB8) f = ir; } return f; } /** * Retrieve the first infrared frame, if no frame is found, return an empty frame instance. * \param[in] size_t index * \return video_frame - first found infrared frame. */ video_frame get_infrared_frame(const size_t index = 0) const { frame f; if (!index) { f = first_or_default(RS2_STREAM_INFRARED); } else { foreach_rs([&f, index](const frame& frm) { if (frm.get_profile().stream_type() == RS2_STREAM_INFRARED && frm.get_profile().stream_index() == index) f = frm; }); } return f; } /** * Retrieve the fisheye monochrome video frame * \param[in] size_t index * \return video_frame - the fisheye frame denoted by index. */ video_frame get_fisheye_frame(const size_t index = 0) const { frame f; if (!index) { f = first_or_default(RS2_STREAM_FISHEYE); } else { foreach_rs([&f, index](const frame& frm) { if (frm.get_profile().stream_type() == RS2_STREAM_FISHEYE && frm.get_profile().stream_index() == index) f = frm; }); } return f; } /** * Retrieve the pose frame * \param[in] size_t index * \return pose_frame - the sensor's positional data */ pose_frame get_pose_frame(const size_t index = 0) const { frame f; if (!index) { f = first_or_default(RS2_STREAM_POSE); } else { foreach_rs([&f, index](const frame& frm) { if (frm.get_profile().stream_type() == RS2_STREAM_POSE && frm.get_profile().stream_index() == index) f = frm; }); } return f.as<pose_frame>(); } /** * Return the size of the frameset * \return size_t - frameset size. */ size_t size() const { return _size; } /** * Template function, extract internal frame handles from the frameset and invoke the action function * \param[in] action - instance with () operator implemented will be invoke after frame extraction. */ template<class T> void foreach_rs(T action) const { rs2_error* e = nullptr; auto count = size(); for (size_t i = 0; i < count; i++) { auto fref = rs2_extract_frame(get(), (int)i, &e); error::handle(e); action(frame(fref)); } } /** * Bracket operator retrieves back the frame from frameset using arrary notation * \param[in] index - index of array to retrieve data back. * \return frame - retrieved frame. */ frame operator[](size_t index) const { rs2_error* e = nullptr; if (index < size()) { auto fref = rs2_extract_frame(get(), (int)index, &e); error::handle(e); return frame(fref); } throw error("Requested index is out of range!"); } class iterator : public std::iterator<std::forward_iterator_tag, frame> { public: iterator(const frameset* owner, size_t index = 0) : _index(index), _owner(owner) {} iterator& operator++() { ++_index; return *this; } bool operator==(const iterator& other) const { return _index == other._index; } bool operator!=(const iterator& other) const { return !(*this == other); } frame operator*() { return (*_owner)[_index]; } private: size_t _index = 0; const frameset* _owner; }; iterator begin() const { return iterator(this); } iterator end() const { return iterator(this, size()); } private: size_t _size; }; template<class T> class frame_callback : public rs2_frame_callback { T on_frame_function; public: explicit frame_callback(T on_frame) : on_frame_function(on_frame) {} void on_frame(rs2_frame* fref) override { on_frame_function(frame{ fref }); } void release() override { delete this; } }; } #endif // LIBREALSENSE_RS2_FRAME_HPP
33.403074
265
0.546414
[ "vector", "3d" ]
28df3c86d49e84203f231f8fad366fb6bcdacff9
2,736
cpp
C++
net.ssa/xr_3da/xrGame/UIZoneMap.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
xr_3da/xrGame/UIZoneMap.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
xr_3da/xrGame/UIZoneMap.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
#include "stdafx.h" #include "uizonemap.h" #include "hudmanager.h" #include "InfoPortion.h" #include "Pda.h" #include "Grenade.h" #include "level.h" #include "game_cl_base.h" #include "actor.h" #include "ai_space.h" #include "game_graph.h" #include "ui/UIMap.h" #include "ui/UIXmlInit.h" ////////////////////////////////////////////////////////////////////////// CUIZoneMap::CUIZoneMap() {} CUIZoneMap::~CUIZoneMap() { } void CUIZoneMap::Init() { CInifile& gameLtx = *pGameIni; CUIXml uiXml; bool xml_result = uiXml.Init(CONFIG_PATH, UI_PATH, "zone_map.xml"); R_ASSERT3(xml_result, "xml file not found", "zone_map.xml"); // load map backgroundwwwwwwwwwwwww CUIXmlInit xml_init; xml_init.InitStatic (uiXml, "minimap:background", 0, &m_background); if(IsGameTypeSingle()){ xml_init.InitStatic (uiXml, "minimap:background:dist_text", 0, &m_pointerDistanceText); m_background.AttachChild (&m_pointerDistanceText); } xml_init.InitStatic(uiXml, "minimap:level_frame", 0, &m_clipFrame); xml_init.InitStatic(uiXml, "minimap:center", 0, &m_center); m_activeMap = xr_new<CUIMiniMap>(); m_activeMap->SetAutoDelete (true); m_activeMap->Init(Level().name(),gameLtx,"hud\\default"); m_clipFrame.AttachChild (m_activeMap); Frect r; m_clipFrame.GetAbsoluteRect (r); m_activeMap->SetClipRect ( r ); Fvector2 wnd_size; float zoom_factor = float(m_clipFrame.GetWndRect().width())/100.0f; wnd_size.x = m_activeMap->BoundRect().width()*zoom_factor; wnd_size.y = m_activeMap->BoundRect().height()*zoom_factor; m_activeMap->SetWndSize(wnd_size); // m_activeMap->SetZoomFactor( float(m_clipFrame.GetWndRect().width())/100.0f ); m_activeMap->EnableHeading (true); xml_init.InitStatic (uiXml, "minimap:compass", 0, &m_compass); // m_background.AttachChild(&m_compass); m_clipFrame.AttachChild (&m_center); m_center.SetWndPos (m_clipFrame.GetWidth()/2,m_clipFrame.GetHeight()/2); } void CUIZoneMap::Render () { m_clipFrame.Draw (); m_background.Draw (); m_compass.Draw (); } void CUIZoneMap::SetHeading (float angle) { m_activeMap->SetHeading(angle); m_compass.SetHeading(angle); }; void CUIZoneMap::UpdateRadar (Fvector pos) { m_clipFrame.Update(); m_background.Update(); m_activeMap->SetActivePoint( pos ); if(IsGameTypeSingle()){ if(m_activeMap->GetPointerDistance()>0.5f){ string64 str; sprintf (str,"%.1f m.",m_activeMap->GetPointerDistance()); m_pointerDistanceText.SetText(str); }else{ m_pointerDistanceText.SetText(""); } } } bool CUIZoneMap::ZoomIn() { return true; } bool CUIZoneMap::ZoomOut() { return true; }
23.791304
92
0.669591
[ "render" ]
28e17ee52a5d0928f7fc79057e4f39a96cfc983d
7,134
cpp
C++
dev/Code/Sandbox/Editor/PropertiesPanel.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/Sandbox/Editor/PropertiesPanel.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/PropertiesPanel.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : implementation file #include "StdAfx.h" #include "PropertiesPanel.h" #include "Controls/PropertyCtrl.h" #include "QtUtilWin.h" #define HEIGHT_OFFSET 4 #define HEIGHT_ADD 4 ///////////////////////////////////////////////////////////////////////////// // CPropertiesPanel dialog CPropertiesPanel::CPropertiesPanel(CWnd* pParent) : CDialog(CPropertiesPanel::IDD, pParent) , m_multiSelect(false) , m_titleAdjust(0) { m_pWndProps.reset(new CPropertyCtrl()); Create(IDD, pParent); } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPropertiesPanel) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPropertiesPanel, CDialog) //{{AFX_MSG_MAP(CPropertiesPanel) ON_WM_DESTROY() ON_WM_KILLFOCUS() ON_WM_SIZE() //}}AFX_MSG_MAP ON_WM_LBUTTONDOWN() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPropertiesPanel message handlers BOOL CPropertiesPanel::OnInitDialog() { CDialog::OnInitDialog(); ModifyStyleEx(0, WS_EX_CLIENTEDGE); CRect rc; GetClientRect(rc); CStatic* pStatic = (CStatic*)GetDlgItem(IDC_CHILD_CONTROL); if (pStatic != NULL) { pStatic->GetClientRect(rc); m_pWndProps->Create(WS_CHILD | WS_VISIBLE, rc, pStatic); m_pWndProps->ModifyStyleEx(0, WS_EX_CLIENTEDGE); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CPropertiesPanel::SetMultiSelect(bool bEnable) { if (bEnable == m_multiSelect) { return; } m_multiSelect = bEnable; if (m_pWndProps->m_hWnd) { m_pWndProps->SetDisplayOnlyModified(bEnable); m_pWndProps->ReloadValues(); } } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::ResizeToFitProperties() { CRect rc; GetWindowRect(rc); int h = m_pWndProps->GetVisibleHeight() + HEIGHT_ADD; if (h > 400) { h = 400; } SetWindowPos(NULL, 0, 0, rc.Width(), h + HEIGHT_OFFSET * 2 + 4, SWP_NOMOVE); } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::DeleteVars() { if (!m_pWndProps->m_hWnd) { return; } m_pWndProps->DeleteAllItems(); m_updateCallbacks.clear(); m_varBlock = 0; } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::SetVarBlock(class CVarBlock* vb, const UpdateCallback& updCallback, const bool resizeToFit) { assert(vb); if (!m_pWndProps->m_hWnd) { return; } m_varBlock = vb; // Must first clear any selection in properties window. m_pWndProps->ClearSelection(); m_pWndProps->DeleteAllItems(); m_varBlock = vb; m_pWndProps->AddVarBlock(m_varBlock); m_pWndProps->SetUpdateCallback(functor(*this, &CPropertiesPanel::OnPropertyChanged)); m_pWndProps->ExpandAll(); if (resizeToFit) { ResizeToFitProperties(); } m_multiSelect = false; m_pWndProps->SetDisplayOnlyModified(false); // When new object set all previous callbacks freed. m_updateCallbacks.clear(); if (updCallback) { stl::push_back_unique(m_updateCallbacks, updCallback); } } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::AddVars(CVarBlock* vb, const UpdateCallback& updCallback) { assert(vb); if (!m_pWndProps->m_hWnd) { return; } //m_pWndProps->DeleteAllItems(); bool bNewBlock = false; // Make a clone of properties. if (!m_varBlock) { // Must first clear any selection in properties window. m_pWndProps->ClearSelection(); m_pWndProps->DeleteAllItems(); m_varBlock = vb->Clone(true); m_pWndProps->AddVarBlock(m_varBlock); bNewBlock = true; } m_varBlock->Wire(vb); //CVarBlock *propVB = m_varBlock->Clone(true); //propVB->Wire( m_varBlock ); //m_pWndProps->AddVarBlock( propVB ); if (bNewBlock) { m_pWndProps->SetUpdateCallback(functor(*this, &CPropertiesPanel::OnPropertyChanged)); m_pWndProps->ExpandAll(); ResizeToFitProperties(); m_multiSelect = false; m_pWndProps->SetDisplayOnlyModified(false); // When new object set all previous callbacks freed. m_updateCallbacks.clear(); } else { m_multiSelect = true; m_pWndProps->SetDisplayOnlyModified(true); } if (updCallback) { stl::push_back_unique(m_updateCallbacks, updCallback); } } void CPropertiesPanel::OnDestroy() { CDialog::OnDestroy(); } void CPropertiesPanel::OnKillFocus(CWnd* pNewWnd) { CDialog::OnKillFocus(pNewWnd); } void CPropertiesPanel::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); CStatic* pStatic = (CStatic*)GetDlgItem(IDC_CHILD_CONTROL); if (pStatic != NULL) { pStatic->SetWindowPos(this, 0, 0, cx, cy, SWP_NOZORDER); } if (m_pWndProps->m_hWnd) { m_pWndProps->SetWindowPos(this, 0, m_titleAdjust, cx, cy - m_titleAdjust, SWP_NOZORDER); } } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::OnPropertyChanged(IVariable* pVar) { std::list<UpdateCallback>::iterator iter; for (iter = m_updateCallbacks.begin(); iter != m_updateCallbacks.end(); ++iter) { (*iter)(pVar); } } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::UpdateVarBlock(CVarBlock* pVars) { m_pWndProps->UpdateVarBlock(pVars); } ////////////////////////////////////////////////////////////////////////// void CPropertiesPanel::SetTitle(const char* title) { CStatic* pStatic = (CStatic*)GetDlgItem(IDC_CHILD_CONTROL); if (pStatic != NULL) { CString paddedTitle(title); paddedTitle = " " + paddedTitle; if (title == NULL) { m_titleAdjust = 0; } else { CClientDC dc(pStatic); CRect rc; dc.DrawText(paddedTitle.GetString(), &rc, DT_CALCRECT); m_titleAdjust = rc.bottom; } pStatic->SetWindowText(paddedTitle.GetString()); } }
25.3879
114
0.591814
[ "object" ]
28e1e1525f783e7f2e2fd068019efe658d816e21
2,094
cpp
C++
src/async/smtp/MCSMTPOperation.cpp
woolie/mailcore2
3e6d6cdefe5cb56d30b1c28d8cc290ca2f37737d
[ "BSD-3-Clause" ]
2
2015-01-24T20:00:48.000Z
2016-10-06T05:20:51.000Z
src/async/smtp/MCSMTPOperation.cpp
woolie/mailcore2
3e6d6cdefe5cb56d30b1c28d8cc290ca2f37737d
[ "BSD-3-Clause" ]
1
2022-03-01T13:01:39.000Z
2022-03-01T13:01:39.000Z
src/async/smtp/MCSMTPOperation.cpp
isabella232/mailcore2
9db22f9c4627086d1d91e09327f195683e9f6451
[ "BSD-3-Clause" ]
1
2022-03-01T11:52:17.000Z
2022-03-01T11:52:17.000Z
// // MCSMTPOperation.cpp // mailcore2 // // Created by DINH Viêt Hoà on 1/11/13. // Copyright (c) 2013 MailCore. All rights reserved. // #include "MCSMTPOperation.h" #include <stdlib.h> #include "MCSMTPAsyncSession.h" #include "MCSMTPOperationCallback.h" using namespace mailcore; SMTPOperation::SMTPOperation() { mSession = NULL; mError = ErrorNone; mSmtpCallback = NULL; } SMTPOperation::~SMTPOperation() { MC_SAFE_RELEASE(mSession); } void SMTPOperation::setSession(SMTPAsyncSession * session) { MC_SAFE_REPLACE_RETAIN(SMTPAsyncSession, mSession, session); #if __APPLE__ dispatch_queue_t queue; if (session != NULL) { queue = session->dispatchQueue(); } else { queue = dispatch_get_main_queue(); } setCallbackDispatchQueue(queue); #endif } SMTPAsyncSession * SMTPOperation::session() { return mSession; } void SMTPOperation::start() { mSession->runOperation(this); } void SMTPOperation::setSmtpCallback(SMTPOperationCallback * callback) { mSmtpCallback = callback; } SMTPOperationCallback * SMTPOperation::smtpCallback() { return mSmtpCallback; } void SMTPOperation::setError(ErrorCode error) { mError = error; } ErrorCode SMTPOperation::error() { return mError; } struct progressContext { unsigned int current; unsigned int maximum; }; void SMTPOperation::bodyProgress(SMTPSession * session, unsigned int current, unsigned int maximum) { struct progressContext * context = (struct progressContext *) calloc(sizeof(* context), 1); context->current = current; context->maximum = maximum; retain(); performMethodOnCallbackThread((Object::Method) &SMTPOperation::bodyProgressOnMainThread, context); } void SMTPOperation::bodyProgressOnMainThread(void * ctx) { if (isCancelled()) { release(); return; } struct progressContext * context = (struct progressContext *) ctx; if (mSmtpCallback != NULL) { mSmtpCallback->bodyProgress(this, context->current, context->maximum); } free(context); release(); }
20.134615
102
0.697708
[ "object" ]
28e202b50b2076b6d8247c61ff47f840638a2883
6,815
cpp
C++
src/OramDeterministic.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
9
2020-08-01T22:00:47.000Z
2021-11-08T09:44:18.000Z
src/OramDeterministic.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
null
null
null
src/OramDeterministic.cpp
young-du/PathORAM
23d18b23153adf2e4a689e26d4bd05dc7db2497e
[ "MIT" ]
5
2020-06-24T19:23:57.000Z
2022-01-24T14:52:48.000Z
// // // #include "OramDeterministic.h" #include <iostream> #include <string> #include <sstream> #include <cmath> #include <bitset> using namespace std; OramDeterministic::OramDeterministic(UntrustedStorageInterface* storage, RandForOramInterface* rand_gen, int bucket_size, int num_blocks) { this->G = 0; this->storage = storage; this->rand_gen = rand_gen; this->bucket_size = bucket_size; this->num_blocks = num_blocks; this->num_levels = ceil(log10(num_blocks) / log10(2)) + 1; this->num_buckets = pow(2, num_levels)-1; if (this->num_buckets*this->bucket_size < this->num_blocks) //deal with precision loss { throw new runtime_error("Not enough space for the actual number of blocks."); } this->num_leaves = pow(2, num_levels-1); Bucket::resetState(); Bucket::setMaxSize(bucket_size); this->rand_gen->setBound(num_leaves); this->storage->setCapacity(num_buckets); this->position_map = new int[this->num_blocks]; this->stash = vector<Block>(); for (int i = 0; i < this->num_blocks; i++){ position_map[i] = rand_gen->getRandomLeaf(); } // Initialize all blocks in all buckets as empty. for(int i = 0; i < num_buckets; i++){ Bucket init_bkt = Bucket(); for(int j = 0; j < bucket_size; j++){ init_bkt.addBlock(Block()); } storage->WriteBucket(i, Bucket(init_bkt)); } } int* OramDeterministic::access(Operation op, int blockIndex, int *newdata) { int *data = new int[Block::BLOCK_SIZE]; int oldLeaf = position_map[blockIndex]; position_map[blockIndex] = rand_gen->getRandomLeaf(); Block *targetBlock = NULL; for (int i = 0; i < num_levels; i++) { vector<Block> blocks = storage->ReadBucket(P(oldLeaf, i)).getBlocks(); Bucket write_back = Bucket(); for (Block b: blocks) { if (b.index != blockIndex) { write_back.addBlock(Block(b)); } else { targetBlock = new Block(b); write_back.addBlock(Block()); } } storage->WriteBucket(P(oldLeaf, i), &write_back); } if (op == Operation::WRITE) { if (targetBlock == NULL) { Block newBlock = Block(position_map[blockIndex], blockIndex, newdata); stash.push_back(newBlock); } else { for (int i = 0; i < Block::BLOCK_SIZE; i++) { targetBlock->data[i] = newdata[i]; } stash.push_back(Block(*targetBlock)); } } else { if (targetBlock == NULL) { data = NULL; } else { for (int i = 0; i < Block::BLOCK_SIZE; i++) { data[i] = targetBlock->data[i]; } stash.push_back(Block(*targetBlock)); } } /* Eviction steps: Two paths will be evicted and re-written as determined by ReverseBits */ for (int repeat = 0; repeat < 2; repeat++) { int g = ReverseBits(this->G, num_levels - 1); this->G = this->G + 1; for (int l = 0; l < num_levels; l++) { vector<Block> blocks = vector<Block>(); /* Read blocks on current level in the path and write to stash */ try { blocks = storage->ReadBucket(P(g, l)).getBlocks(); } catch (exception& e) { cout << e.what() << endl; } for (Block b : blocks) { if (b.index != -1) { stash.push_back(Block(b)); } } } /* Re-write blocks from the stash to current path whenever possible, starting at the deepest level */ for (int l = num_levels - 1; l >= 0; l--) { vector<int> bid_evicted = vector<int>(); Bucket bucket = Bucket(); int Pxl = P(g, l); int counter = 0; for (Block b_instash : stash) { if (counter >= bucket_size) { break; } Block be_evicted = Block(b_instash); if (Pxl == P(position_map[be_evicted.index], l)) { bucket.addBlock(be_evicted); bid_evicted.push_back(be_evicted.index); counter++; } } //remove from the stash for(int i = 0; i < bid_evicted.size(); i++) { for(int j=0; j<stash.size(); j++) { Block b_instash = stash.at(j); if(b_instash.index == bid_evicted.at(i)) { this->stash.erase(this->stash.begin() + j); } } } while (counter < bucket_size) { bucket.addBlock(Block()); //dummy block counter++; } storage->WriteBucket(Pxl, bucket); } } return data; } int OramDeterministic::ReverseBits(int g, int bits_length) { /* INPUT: Integers g and bits_length. OUTPUT: Integer reverse of length bits_length consisting of reversed bits of g. To be used to traverse the leaves and run eviction in reverse lexicographical order. */ int g_mod = g%num_leaves; int reverse = 0; while(g_mod) { reverse <<= 1; reverse |= g_mod & 1; g_mod >>= 1; bits_length--; } reverse <<= bits_length; return reverse; } int OramDeterministic::P(int leaf, int level) { /* * This function should be deterministic. * INPUT: leaf in range 0 to num_leaves - 1, level in range 0 to num_levels - 1. * OUTPUT: Returns the location in the storage of the bucket which is at the input level and leaf. */ return (1<<level) - 1 + (leaf >> (this->num_levels - level - 1)); } /* The below functions are to access various parameters, as described by their names. INPUT: No input OUTPUT: Value of internal variables given in the name. */ int *OramDeterministic::getPositionMap() { return this->position_map; } vector<Block> OramDeterministic::getStash() { return this->stash; } int OramDeterministic::globalG() { return this->G; } int OramDeterministic::getStashSize() { return (this->stash).size(); } int OramDeterministic::getNumLeaves() { return this->num_leaves; } int OramDeterministic::getNumLevels() { return this->num_levels; } int OramDeterministic::getNumBlocks() { return this->num_blocks; } int OramDeterministic::getNumBuckets() { return this->num_buckets; }
27.369478
104
0.537931
[ "vector" ]
28e26ba6c2e43837f4fa777fb265e7da490fb040
524
cpp
C++
Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; typedef long long ll; typedef vector <int> vi; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int tc; cin >> tc; cpp_int n, ans; while(tc--){ cin >> n; ans = 24 + n * (-18 + n * (23 + n * (-6 + n))); ans /= 24; cout << ans << "\n"; } return 0; }
23.818182
55
0.551527
[ "vector" ]
28e49026707fd3f1c5270c829a66cdf3375a2cb1
13,619
cpp
C++
Plugins/WebSocket/Source/WebSocket/Private/WebSocketBase.cpp
dr-munns/UEWebsocket
9429ebfde6ded90e380c92b6fac54bb04bbee5a2
[ "MIT" ]
null
null
null
Plugins/WebSocket/Source/WebSocket/Private/WebSocketBase.cpp
dr-munns/UEWebsocket
9429ebfde6ded90e380c92b6fac54bb04bbee5a2
[ "MIT" ]
null
null
null
Plugins/WebSocket/Source/WebSocket/Private/WebSocketBase.cpp
dr-munns/UEWebsocket
9429ebfde6ded90e380c92b6fac54bb04bbee5a2
[ "MIT" ]
null
null
null
/* * uewebsocket - unreal engine 4 websocket plugin * * Copyright (C) 2017 feiwu <feixuwu@outlook.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation: * version 2.1 of the License. * * 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 "WebSocket.h" #include <iostream> #include <vector> #include "WebSocketBase.h" #include "WebSocketContext.h" #if PLATFORM_UWP #elif PLATFORM_HTML5 #elif PLATFORM_WINDOWS #include "PreWindowsApi.h" #include "libwebsockets.h" #include "PostWindowsApi.h" #else #include "libwebsockets.h" #endif #if PLATFORM_UWP using namespace concurrency; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Networking::Sockets; using namespace Windows::Security::Cryptography::Certificates; using namespace Windows::Storage::Streams; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Web; FUWPSocketHelper::FUWPSocketHelper():Parent(0) { } FUWPSocketHelper::~FUWPSocketHelper() { Parent = 0; } void FUWPSocketHelper::SetParent(int64 p) { Parent = p; } void FUWPSocketHelper::MessageReceived(Windows::Networking::Sockets::MessageWebSocket^ sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs^ args) { if (Parent != 0) { UWebSocketBase* p = (UWebSocketBase*)Parent; p->MessageReceived(sender, args); } } void FUWPSocketHelper::OnUWPClosed(Windows::Networking::Sockets::IWebSocket^ sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^ args) { if (Parent != 0) { UWebSocketBase* p = (UWebSocketBase*)Parent; p->OnUWPClosed(sender, args); } } #elif PLATFORM_HTML5 void FHtml5SocketHelper::Tick(float DeltaTime) { if (mHostWebSocket == nullptr) { return; } if (mHostWebSocket->mIsError) { return; } if (mHostWebSocket->mWebSocketRef < 0) { return; } // check connect char szError[128] = { 0 }; int checkError = SocketError(mHostWebSocket->mWebSocketRef, szError, (int)sizeof(szError) - 1); if ( (checkError == 0) && !mHostWebSocket->mConnectSuccess && SocketState(mHostWebSocket->mWebSocketRef) ) { mHostWebSocket->mConnectSuccess = true; mHostWebSocket->OnConnectComplete.Broadcast(); } if(checkError != 0) { mHostWebSocket->mIsError = true; if (!mHostWebSocket->mConnectSuccess) { FString strError = UTF8_TO_TCHAR(szError); mHostWebSocket->OnConnectError.Broadcast(strError); } else { mHostWebSocket->OnClosed.Broadcast(); } return; } // check data receive int iRecvLen = SocketRecvLength(mHostWebSocket->mWebSocketRef); if (iRecvLen > 0) { char* pData = new char[iRecvLen + 1]; SocketRecv(mHostWebSocket->mWebSocketRef, pData, iRecvLen); pData[iRecvLen] = (char)0; mHostWebSocket->ProcessRead((const char*)pData, (int)iRecvLen); delete[]pData; } } bool FHtml5SocketHelper::IsTickable() const { return true; } TStatId FHtml5SocketHelper::GetStatId() const { return TStatId(); } #endif SendQueueEntry::SendQueueEntry(bool _binary, const uint8 *indata, size_t datalen) : binary(_binary), data(LWS_PRE, 0), datalen(datalen) { data.insert(data.end(), indata, indata + datalen); } UWebSocketBase::UWebSocketBase() { #if PLATFORM_UWP messageWebSocket = nullptr; uwpSocketHelper = ref new FUWPSocketHelper(); uwpSocketHelper->SetParent( (int64)this); #elif PLATFORM_HTML5 mWebSocketRef = -1; mConnectSuccess = false; mIsError = false; #else mlws = nullptr; closing = false; #endif } #if PLATFORM_UWP #elif PLATFORM_HTML5 #else // accessor helpers to get the lws pointer if the lws context is alive. struct lws_context * UWebSocketBase::GetLWSContext() const { UWebSocketContext *ptr = mWebSocketContext.Get(); if (ptr) { return ptr->GetContext(); } return nullptr; } struct lws * UWebSocketBase::GetLWS() const { if (mlws && GetLWSContext()) { return mlws; } return nullptr; } #endif void UWebSocketBase::BeginDestroy() { Super::BeginDestroy(); #if PLATFORM_UWP uwpSocketHelper->SetParent(0); uwpSocketHelper = nullptr; if (messageWebSocket != nullptr) { delete messageWebSocket; messageWebSocket = nullptr; } #elif PLATFORM_HTML5 mHtml5SocketHelper.UnBind(); #else auto tmp = GetLWS(); if (tmp) { mlws = nullptr; lws_set_wsi_user(tmp, NULL); lws_callback_on_writable(tmp); } #endif } #if PLATFORM_UWP void UWebSocketBase::MessageReceived(Windows::Networking::Sockets::MessageWebSocket^ sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs^ args) { Windows::ApplicationModel::Core::CoreApplication::MainView->Dispatcher->RunAsync( Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]() { DataReader^ reader = args->GetDataReader(); reader->UnicodeEncoding = UnicodeEncoding::Utf8; try { String^ read = reader->ReadString(reader->UnconsumedBufferLength); FString strData(read->Data(), read->Length()); OnReceiveData.Broadcast(strData); } catch (Exception^ ex) { } delete reader; })); } void UWebSocketBase::OnUWPClosed(Windows::Networking::Sockets::IWebSocket^ sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^ args) { Windows::ApplicationModel::Core::CoreApplication::MainView->Dispatcher->RunAsync( Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() { OnClosed.Broadcast(); })); } Concurrency::task<void> UWebSocketBase::ConnectAsync(Platform::String^ uriString) { Uri^ server = nullptr; try { server = ref new Uri(uriString); } catch (NullReferenceException^) { return task_from_result(); } catch (InvalidArgumentException^) { return task_from_result(); } messageWebSocket = ref new MessageWebSocket(); messageWebSocket->Control->MessageType = SocketMessageType::Utf8; messageWebSocket->MessageReceived += ref new TypedEventHandler< MessageWebSocket^, MessageWebSocketMessageReceivedEventArgs^>(uwpSocketHelper, &FUWPSocketHelper::MessageReceived); messageWebSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(uwpSocketHelper, &FUWPSocketHelper::OnUWPClosed); return create_task(messageWebSocket->ConnectAsync(server)) .then([this](task<void> previousTask) { try { previousTask.get(); } catch (Exception^ ex) { delete messageWebSocket; messageWebSocket = nullptr; return; } messageWriter = ref new DataWriter(messageWebSocket->OutputStream); }); } Concurrency::task<void> UWebSocketBase::SendAsync(Platform::String^ message) { if (message == "") { return task_from_result(); } messageWriter->WriteString(message); return create_task(messageWriter->StoreAsync()) .then([this](task<unsigned int> previousTask) { try { previousTask.get(); } catch (Exception^ ex) { return; } }); } #endif bool UWebSocketBase::IsConnected() { return GetLWS() != nullptr; } bool UWebSocketBase::Connect(const FString& uri, const TMap<FString, FString>& headers, const FWebSocketConnectOptions options) { if (uri.IsEmpty() || IsConnected()) { return false; } #if PLATFORM_UWP ConnectAsync(ref new String(*uri)).then([this]() { Windows::ApplicationModel::Core::CoreApplication::MainView->Dispatcher->RunAsync( Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() { if (messageWebSocket != nullptr) { OnConnectComplete.Broadcast(); } else { OnConnectError.Broadcast(TEXT("connect error")); } })); }); return true; #elif PLATFORM_HTML5 mHtml5SocketHelper.Bind(this); std::string strUrl = TCHAR_TO_UTF8(*uri); mWebSocketRef = SocketCreate(strUrl.c_str()); return true; #else struct lws_context* lwsContext = GetLWSContext(); if (!lwsContext) { return false; } int ssl_options = (options.bAllowSelfSigned ? LCCSCF_ALLOW_SELFSIGNED : 0) | (options.bSkipServerCertHostnameCheck ? LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK : 0) | (options.bAllowExpired ? LCCSCF_ALLOW_EXPIRED : 0); int bUseSSL = false; int iPos = uri.Find(TEXT(":")); if (iPos == INDEX_NONE) { //UE_LOG(WebSocket, Error, TEXT("Invalid Websocket address:%s"), *uri); return false; } FString strProtocol = uri.Left(iPos); if (strProtocol.ToUpper() != TEXT("WS") && strProtocol.ToUpper() != TEXT("WSS")) { //UE_LOG(WebSocket, Error, TEXT("Invalid Protol:%s"), *strProtocol); return false; } if (strProtocol.ToUpper() == TEXT("WSS")) { bUseSSL = true; } FString strHost; FString strPath = TEXT("/"); FString strNextParse = uri.Mid(iPos + 3); iPos = strNextParse.Find("/"); if (iPos != INDEX_NONE) { strHost = strNextParse.Left(iPos); strPath = strNextParse.Mid(iPos); } else { strHost = strNextParse; } FString strAddress = strHost; int iPort = 80; iPos = strAddress.Find(":"); if (iPos != INDEX_NONE) { strAddress = strHost.Left(iPos); iPort = FCString::Atoi(*strHost.Mid(iPos + 1)); } else { if (bUseSSL) { iPort = 443; } } struct lws_client_connect_info connectInfo; memset(&connectInfo, 0, sizeof(connectInfo)); std::string stdAddress = TCHAR_TO_UTF8(*strAddress); std::string stdPath = TCHAR_TO_UTF8(*strPath); std::string stdHost = TCHAR_TO_UTF8(*strHost);; connectInfo.context = lwsContext; connectInfo.address = stdAddress.c_str(); connectInfo.port = iPort; connectInfo.ssl_connection = ssl_options | (bUseSSL ? LCCSCF_USE_SSL : 0); connectInfo.path = stdPath.c_str(); connectInfo.host = stdHost.c_str(); connectInfo.origin = stdHost.c_str(); connectInfo.ietf_version_or_minus_one = -1; connectInfo.userdata = this; // allow lws to temporarily set mlws, so that callbacks work during the connect phase. connectInfo.pwsi = &mlws; mlws = lws_client_connect_via_info(&connectInfo); //mlws = lws_client_connect_extended(mlwsContext, TCHAR_TO_UTF8(*strAddress), iPort, iUseSSL, TCHAR_TO_UTF8(*strPath), TCHAR_TO_UTF8(*strHost), TCHAR_TO_UTF8(*strHost), NULL, -1, (void*)this); if (mlws == nullptr) { UE_LOG(WebSocket, Error, TEXT("create client connect fail")); return false; } mHeaderMap = headers; return true; #endif } void UWebSocketBase::SendText(const FString& data) { #if PLATFORM_UWP SendAsync(ref new String(*data)).then([this]() { }); #elif PLATFORM_HTML5 std::string strData = TCHAR_TO_UTF8(*data); SocketSend(mWebSocketRef, strData.c_str(), (int)strData.size() ); #else auto lws = GetLWS(); if (lws) { FTCHARToUTF8 utf8(*data); mSendQueue.AddTail(SendQueueEntry(false, (const unsigned char*)utf8.Get(), utf8.Length())); lws_callback_on_writable(lws); } else { UE_LOG(WebSocket, Error, TEXT("the socket is closed, SendText fail")); } #endif } void UWebSocketBase::SendBinary(const TArray<uint8>& data) { #if PLATFORM_UWP #elif PLATFORM_HTML5 #else auto lws = GetLWS(); if (lws) { mSendQueue.AddTail(SendQueueEntry(true, data.GetData(), data.Num())); lws_callback_on_writable(lws); } else { UE_LOG(WebSocket, Error, TEXT("the socket is closed, SendBinary fail")); } #endif } void UWebSocketBase::ProcessWriteable() { #if PLATFORM_UWP #elif PLATFORM_HTML5 #else while (mSendQueue.Num() > 0) { auto &entry = mSendQueue.GetHead()->GetValue(); lws_write(mlws, &entry.data[LWS_PRE], entry.datalen, entry.binary ? LWS_WRITE_BINARY : LWS_WRITE_TEXT); mSendQueue.RemoveNode(mSendQueue.GetHead(), true); if (mSendQueue.Num() > 0 && lws_partial_buffered(mlws)) { lws_callback_on_writable(mlws); return; } } #endif } void UWebSocketBase::ProcessRead(const char* in, int len, bool binary) { if (!binary) { FString strData = UTF8_TO_TCHAR(in); OnReceiveData.Broadcast(strData); } else { TArray<uint8> binData((const uint8*)in, len); OnReceiveBinary.Broadcast(binData); } } bool UWebSocketBase::ProcessHeader(unsigned char** p, unsigned char* end) { #if PLATFORM_UWP #elif PLATFORM_HTML5 #else if (mHeaderMap.Num() == 0) { return true; } for (auto& it : mHeaderMap) { std::string strKey = TCHAR_TO_UTF8(*(it.Key) ); std::string strValue = TCHAR_TO_UTF8(*(it.Value)); if (strKey.length() == 0 || strValue.length() == 0) { continue; } strKey += ":"; if (lws_add_http_header_by_name(mlws, (const unsigned char*)strKey.c_str(), (const unsigned char*)strValue.c_str(), (int)strValue.size(), p, end)) { return false; } } #endif return true; } void UWebSocketBase::Close() { #if PLATFORM_UWP if (messageWriter != nullptr) { messageWriter->DetachStream(); delete messageWriter; messageWriter = nullptr; } #elif PLATFORM_HTML5 SocketClose(mWebSocketRef); mWebSocketRef = -1; OnClosed.Broadcast(); #else auto lws = GetLWS(); if (lws) { closing = true; lws_callback_on_writable(lws); } #endif } void UWebSocketBase::Cleanlws() { #if PLATFORM_UWP #elif PLATFORM_HTML5 #else auto lws = GetLWS(); if (lws) { lws_set_wsi_user(mlws, NULL); } mlws = nullptr; closing = false; #endif }
21.895498
193
0.720464
[ "vector" ]
28ead8a9737d89f1900f2cd6c149d6fe846fa743
10,113
cc
C++
ash/login/ui/auth_icon_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ash/login/ui/auth_icon_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ash/login/ui/auth_icon_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 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 "ash/login/ui/auth_icon_view.h" #include "ash/login/ui/horizontal_image_sequence_animation_decoder.h" #include "ash/style/ash_color_provider.h" #include "ui/base/resource/resource_bundle.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/paint_throbber.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_types.h" #include "ui/views/border.h" #include "ui/views/layout/fill_layout.h" namespace ash { namespace { struct ShakeAnimationStep { int x_offset; int duration_ms; }; constexpr int kAuthIconSizeDp = 32; constexpr int kIconBorderDp = 10; constexpr int kAuthIconViewDp = kAuthIconSizeDp + 2 * kIconBorderDp; constexpr int kProgressAnimationStrokeWidth = 3; // This determines how frequently we paint the progress spinner. // 1 frame / 30 msec = about 30 frames per second // 30 fps seems to be smooth enough to look good without excessive painting. constexpr base::TimeDelta kProgressFrameDuration = base::Milliseconds(30); // How long the nudge animation takes to scale up and fade out. constexpr base::TimeDelta kNudgeAnimationScalingDuration = base::Milliseconds(2000); // How long the delay between the repeating nudge animation takes in between // cycles. constexpr base::TimeDelta kNudgeAnimationDelayDuration = base::Milliseconds(1000); // How opaque the nudge animation will reset the view to. constexpr float kOpacityReset = 0.5; // Size that nudge animation scales view up and down by. constexpr SkScalar kTransformScaleUpSize = 3; // The interpolation of transform fails when scaling all the way down to 0. constexpr SkScalar kTransformScaleDownSize = 0.01; // See spec: // https://carbon.googleplex.com/cr-os-motion-work/pages/sign-in/undefined/e05c4091-eea2-4c5a-a6f8-38fd37953e7b#a929eb9f-2840-4b37-be52-97d96ca2aafa constexpr ShakeAnimationStep kShakeAnimationSteps[] = { {-5, 83}, {8, 83}, {-7, 66}, {7, 66}, {-7, 66}, {7, 66}, {-3, 83}}; SkColor GetColor(AuthIconView::Color color) { switch (color) { case AuthIconView::Color::kPrimary: return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary); case AuthIconView::Color::kDisabled: return AshColorProvider::Get()->GetDisabledColor( GetColor(AuthIconView::Color::kPrimary)); case AuthIconView::Color::kError: // TODO(crbug.com/1233614): Either find a system color to match the color // in the Fingerprint animation png sequence, or upload new png files with // the right color. return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorAlert); case AuthIconView::Color::kPositive: return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPositive); } } } // namespace AuthIconView::AuthIconView() { SetLayoutManager(std::make_unique<views::FillLayout>()); icon_ = AddChildView(std::make_unique<AnimatedRoundedImageView>( gfx::Size(kAuthIconSizeDp, kAuthIconSizeDp), /*corner_radius=*/0)); icon_->SetBorder(views::CreateEmptyBorder(gfx::Insets(kIconBorderDp))); // Set up layer to allow for animation. icon_->SetPaintToLayer(); icon_->layer()->SetFillsBoundsOpaquely(false); icon_->layer()->GetAnimator()->set_preemption_strategy( ui::LayerAnimator::PreemptionStrategy::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); } AuthIconView::~AuthIconView() = default; void AuthIconView::SetIcon(const gfx::VectorIcon& icon, Color color) { icon_->SetImage( gfx::CreateVectorIcon(icon, kAuthIconSizeDp, GetColor(color))); } void AuthIconView::SetCircleImage(int size, SkColor color) { gfx::ImageSkia circle_icon = gfx::CanvasImageSource::MakeImageSkia<CircleImageSource>(size, color); icon_->SetImage(circle_icon); } void AuthIconView::SetAnimation(int animation_resource_id, base::TimeDelta duration, int num_frames) { icon_->SetAnimationDecoder( std::make_unique<HorizontalImageSequenceAnimationDecoder>( *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( animation_resource_id), duration, num_frames), AnimatedRoundedImageView::Playback::kSingle); } void AuthIconView::RunErrorShakeAnimation() { StopAnimating(); auto transform_sequence = std::make_unique<ui::LayerAnimationSequence>(); gfx::Transform transform; for (const ShakeAnimationStep& step : kShakeAnimationSteps) { transform.Translate(step.x_offset, /*y=*/0); auto element = ui::LayerAnimationElement::CreateTransformElement( transform, base::Milliseconds(step.duration_ms)); element->set_tween_type(gfx::Tween::Type::EASE_IN_OUT_2); transform_sequence->AddElement(std::move(element)); } // Animator takes ownership of transform_sequence. icon_->layer()->GetAnimator()->StartAnimation(transform_sequence.release()); } void AuthIconView::RunNudgeAnimation() { StopAnimating(); // Create two separate animation sequences and run in parallel. auto opacity_sequence = std::make_unique<ui::LayerAnimationSequence>(); auto transform_sequence = std::make_unique<ui::LayerAnimationSequence>(); // Fade out view by gradually setting opacity to 0. auto element = ui::LayerAnimationElement::CreateOpacityElement( 0, kNudgeAnimationScalingDuration); element->set_tween_type(gfx::Tween::Type::ACCEL_0_80_DECEL_80); opacity_sequence->AddElement(std::move(element)); // Reset opacity so that |opacity_sequence| can be repeated. element = ui::LayerAnimationElement::CreateOpacityElement(kOpacityReset, base::TimeDelta()); opacity_sequence->AddElement(std::move(element)); element = ui::LayerAnimationElement::CreatePauseElement( 0, kNudgeAnimationDelayDuration); opacity_sequence->AddElement(std::move(element)); opacity_sequence->set_is_repeating(true); // Every time it scales, translate by |center_offset| so that the view scales // outward from center point. auto center_offset = gfx::Vector2d(CalculatePreferredSize().width() / 2.0, CalculatePreferredSize().height() / 2.0); gfx::Transform transform; transform.Translate(center_offset); // Make view larger. transform.Scale(/*x=*/kTransformScaleUpSize, /*y=*/kTransformScaleUpSize); transform.Translate(-center_offset); element = ui::LayerAnimationElement::CreateTransformElement( transform, kNudgeAnimationScalingDuration); element->set_tween_type(gfx::Tween::Type::ACCEL_0_40_DECEL_100); transform_sequence->AddElement(std::move(element)); transform = gfx::Transform(); transform.Translate(center_offset); // Make view smaller. transform.Scale(/*x=*/kTransformScaleDownSize, /*y=*/kTransformScaleDownSize); transform.Translate(-center_offset); element = ui::LayerAnimationElement::CreateTransformElement( transform, base::TimeDelta()); transform_sequence->AddElement(std::move(element)); element = ui::LayerAnimationElement::CreatePauseElement( 0, kNudgeAnimationDelayDuration); transform_sequence->AddElement(std::move(element)); transform_sequence->set_is_repeating(true); // Animator takes ownership of opacity_sequence and transform_sequence. icon_->layer()->GetAnimator()->StartAnimation(opacity_sequence.release()); icon_->layer()->GetAnimator()->StartAnimation(transform_sequence.release()); } void AuthIconView::StartProgressAnimation() { // Progress animation already running. if (progress_animation_timer_.IsRunning()) return; progress_animation_start_time_ = base::TimeTicks::Now(); progress_animation_timer_.Start( FROM_HERE, kProgressFrameDuration, base::BindRepeating(&AuthIconView::SchedulePaint, base::Unretained(this))); SchedulePaint(); } void AuthIconView::StopProgressAnimation() { // Progress already stopped. if (!progress_animation_timer_.IsRunning()) return; progress_animation_timer_.Stop(); SchedulePaint(); } void AuthIconView::StopAnimating() { icon_->layer()->GetAnimator()->StopAnimating(); } void AuthIconView::OnPaint(gfx::Canvas* canvas) { // Draw the icon first. views::View::OnPaint(canvas); // Draw the progress spinner on top if it's currently running. if (progress_animation_timer_.IsRunning()) { SkColor color = AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kProgressBarColorForeground); base::TimeDelta elapsed_time = base::TimeTicks::Now() - progress_animation_start_time_; gfx::PaintThrobberSpinning(canvas, GetContentsBounds(), color, elapsed_time, kProgressAnimationStrokeWidth); } } gfx::Size AuthIconView::CalculatePreferredSize() const { return gfx::Size(kAuthIconViewDp, kAuthIconViewDp); } void AuthIconView::OnGestureEvent(ui::GestureEvent* event) { if (event->type() != ui::ET_GESTURE_TAP && event->type() != ui::ET_GESTURE_TAP_DOWN) return; if (on_tap_or_click_callback_) { on_tap_or_click_callback_.Run(); } } bool AuthIconView::OnMousePressed(const ui::MouseEvent& event) { if (on_tap_or_click_callback_) { on_tap_or_click_callback_.Run(); return true; } return false; } AuthIconView::CircleImageSource::CircleImageSource(int size, SkColor color) : gfx::CanvasImageSource(gfx::Size(size, size)), color_(color) {} void AuthIconView::CircleImageSource::Draw(gfx::Canvas* canvas) { float radius = size().width() / 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setAntiAlias(true); flags.setColor(color_); canvas->DrawCircle(gfx::PointF(radius, radius), radius, flags); } } // namespace ash
37.455556
148
0.734105
[ "geometry", "transform" ]
28ef48a1334bee235a084ba350b538deb2d6eefb
2,735
cpp
C++
Online Judges/UVA/231---Testing-the-CATCHER.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/231---Testing-the-CATCHER.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/231---Testing-the-CATCHER.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; #define rep(i,p,n) for( i = p; i<n;i++) #define lld long long int #define pb push_back #define VI vector<int> #define VL vector<long long int> #define VD vector<double> #define pi pair<int,int> #define mp make_pair #define Clear(a,b) memset(a,b,sizeof(a)) #define inf 32778 template<class T>inline bool read(T &x) { int c=getchar(); int sgn=1; while(~c&&c<'0'||c>'9') { if(c=='-')sgn=-1; c=getchar(); } for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())x=x*10+c-'0'; x*=sgn; return ~c; } int dp[103][32780]; int arr[103]; int dir[103][32780]; int n,total,w; void reset() { int i,j; rep(i,0,n+2) { rep(j,0,total+2) { dir[i][j]=-1; dp[i][j]=-1; } } rep(i,0,n+2) dp[i][32778]=-1; } int solve(int ind, int tot) { if(ind>=n) return 0; if(dp[ind][tot]!=-1) return dp[ind][tot]; int ret1=0; int ret2=0; //cout<<ind<<" "<<tot<<endl; if(tot>arr[ind]) { ret1 = solve(ind+1,arr[ind])+1; } ret2 = solve(ind+1,tot); if(ret1>=ret2) { dir[ind][tot]=1; return dp[ind][tot]=ret1; } else { dir[ind][tot]=2; return dp[ind][tot]=ret2; } } void printSol() { int i,j; i=0;j=arr[i]; vector<int> sol; while(dir[i][j]!=-1 && i<n && j<=total) { cout<<i<<" "<<j<<" "<<dir[i][j]<<endl; if(dir[i][j]==1) { sol.pb(arr[i]); j= arr[i]; i++; } else { i++; } } printf("%d\n",sol.size()); rep(i,0,sol.size()) { printf("%d\n",sol[i]); } return ; } bool cmp(int a, int b) { return a>b; } int main() { //freopen("inp.txt","r",stdin); int a,b,i,val,temp; int cnt=1; bool flag=0; while(1) { int Max = -23; int ind=0; while(scanf("%d",&val)==1) { if(temp==-1 && val==-1) { flag=1; break; } else if(val==-1) { temp=-1; break; } else { arr[ind++]=val; Max = max(Max,val); } temp=val; } if(flag) break; // sort(arr,arr+ind,cmp); n = ind; total = Max; reset(); int ret = solve(0,inf); if(cnt>1) printf("\n"); printf("Test #%d:\n maximum possible interceptions: %d\n",cnt++,ret); //printSol(); } return 0; }
15.451977
78
0.412066
[ "vector" ]
28f06b590a542d56fdbcae81fb14e73e19b748ea
519
cpp
C++
atcoder/yahoo_procon2017_qual_b.cpp
Doarakko/competitive-programming
5ae78c501664af08a3f16c81dbd54c68310adec8
[ "MIT" ]
1
2017-07-11T16:47:29.000Z
2017-07-11T16:47:29.000Z
atcoder/yahoo_procon2017_qual_b.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
1
2021-02-07T09:10:26.000Z
2021-02-07T09:10:26.000Z
atcoder/yahoo_procon2017_qual_b.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { long long n, k; vector<long long> v; long long x; long long sum, num; //入力 cin >> n >> k; for (int i = 0; i < n; i++) { cin >> x; v.push_back(x); } //昇順ソート sort(v.begin(), v.end()); //初期化 sum = 0; num = k - 1; //k個の商品を額の大きい順に落札 for (int i = 0; i < k; i++, num--) { sum += v[num] + i; } cout << sum << endl; return 0; }
16.741935
40
0.452794
[ "vector" ]
28f919103b9df8cc8a2659d0a493b996e07065d9
8,990
cpp
C++
Sources/Internal/UI/Scene3D/Private/UIEntityMarkerTest.unittest.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Sources/Internal/UI/Scene3D/Private/UIEntityMarkerTest.unittest.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/UI/Scene3D/Private/UIEntityMarkerTest.unittest.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#include "UnitTests/UnitTests.h" #include "Base/BaseTypes.h" #include "Base/RefPtr.h" #include "Base/ScopedPtr.h" #include "Engine/Engine.h" #include "Render/Highlevel/Camera.h" #include "Scene3D/Components/CameraComponent.h" #include "Scene3D/Components/TransformComponent.h" #include "Scene3D/Scene.h" #include "UI/Scene3D/UIEntityMarkerComponent.h" #include "UI/Scene3D/UIEntityMarkersContainerComponent.h" #include "UI/Scene3D/UIEntityMarkerSystem.h" #include "UI/UI3DView.h" #include "UI/UIControl.h" #include "UI/UIControlSystem.h" #include "UI/UIScreen.h" DAVA_TESTCLASS (UIEntityMarkerTest) { BEGIN_FILES_COVERED_BY_TESTS() FIND_FILES_IN_TARGET(DavaFramework) DECLARE_COVERED_FILES("UIEntityMarkerComponent.cpp") DECLARE_COVERED_FILES("UIEntityMarkerSystem.cpp") END_FILES_COVERED_BY_TESTS(); DAVA::RefPtr<DAVA::Scene> scene; DAVA::RefPtr<DAVA::Camera> camera; DAVA::RefPtr<DAVA::UI3DView> ui3dView; DAVA::RefPtr<DAVA::UIControl> c1; DAVA::RefPtr<DAVA::UIControl> c2; DAVA::RefPtr<DAVA::UIControl> markers; DAVA::RefPtr<DAVA::UIEntityMarkersContainerComponent> emcc; DAVA::RefPtr<DAVA::Entity> CreateEntity(const DAVA::FastName& name, const DAVA::Vector3& position) { using namespace DAVA; RefPtr<Entity> entity(new Entity()); entity->SetName(name); Matrix4 m; m.BuildTranslation(position); TransformComponent* transform = entity->GetComponent<TransformComponent>(); transform->SetLocalTransform(m); return entity; } DAVA::RefPtr<DAVA::UIControl> CreateControl(DAVA::Entity * entity) { using namespace DAVA; RefPtr<UIControl> control(new UIControl()); control->SetName(entity->GetFullName()); UIEntityMarkerComponent* emc = control->GetOrCreateComponent<UIEntityMarkerComponent>(); emc->SetTargetEntity(entity); return control; } void SetUp(const DAVA::String& testName) override { using namespace DAVA; scene.Set(new Scene()); RefPtr<Entity> e1 = CreateEntity(FastName("ENTITY_ONE"), Vector3(-1.f, -1.f, -1.f)); scene->AddNode(e1.Get()); RefPtr<Entity> e2 = CreateEntity(FastName("ENTITY_TWO"), Vector3(1.f, 1.f, 1.f)); scene->AddNode(e2.Get()); camera.Set(new Camera()); camera->SetupPerspective(70.f, 1.0, 0.5f, 2500.f); camera->SetLeft(Vector3(1, 0, 0)); camera->SetUp(Vector3(0, 0, 1.f)); camera->SetTarget(Vector3(0, 0, 0)); camera->SetPosition(Vector3(0, -2, 0)); RefPtr<Entity> cameraEntity(new Entity()); cameraEntity->AddComponent(new CameraComponent(camera.Get())); scene->AddNode(cameraEntity.Get()); scene->AddCamera(camera.Get()); scene->SetCurrentCamera(camera.Get()); ui3dView.Set(new UI3DView(Rect(0, 0, 500, 500))); ui3dView->SetScene(scene.Get()); c1 = CreateControl(e1.Get()); c2 = CreateControl(e2.Get()); markers.Set(new UIControl(Rect(0, 0, 500, 500))); emcc = markers->GetOrCreateComponent<UIEntityMarkersContainerComponent>(); markers->AddControl(c1.Get()); markers->AddControl(c2.Get()); RefPtr<UIScreen> screen(new UIScreen()); screen->AddControl(ui3dView.Get()); screen->AddControl(markers.Get()); DAVA::GetEngineContext()->uiControlSystem->SetScreen(screen.Get()); SystemsUpdate(0.f); } void TearDown(const DAVA::String& testName) override { c1 = nullptr; c2 = nullptr; markers = nullptr; ui3dView = nullptr; camera = nullptr; scene = nullptr; } void SystemsUpdate(DAVA::float32 delta) { DAVA::GetEngineContext()->uiControlSystem->UpdateWithCustomTime(delta); } DAVA_TEST (ComponentTest) { using namespace DAVA; RefPtr<UIControl> c3 = c1->SafeClone(); TEST_VERIFY(c3->GetComponent<UIEntityMarkerComponent>()); RefPtr<UIControl> c4(new UIControl()); c1->AddControl(c4.Get()); c4->GetOrCreateComponent<UIEntityMarkerComponent>(); TEST_VERIFY(c4->GetComponentCount<UIEntityMarkerComponent>() == 1); c4->RemoveComponent<UIEntityMarkerComponent>(); TEST_VERIFY(c4->GetComponentCount<UIEntityMarkerComponent>() == 0); } DAVA_TEST (PositionTest) { using namespace DAVA; const struct { RefPtr<UIControl> c; Vector2 data; float32 eps; } testData[] = { { c1, { -107.f, 607.f }, 0.1f }, { c2, { 369.f, 131.f }, 0.1f } }; emcc->SetSyncPositionEnabled(true); SystemsUpdate(0.f); for (const auto& test : testData) { Vector2 pos = test.c->GetPosition(); TEST_VERIFY(FLOAT_EQUAL_EPS(pos.x, test.data.x, test.eps)); TEST_VERIFY(FLOAT_EQUAL_EPS(pos.y, test.data.y, test.eps)); } } DAVA_TEST (ScaleTest) { using namespace DAVA; const struct { Vector3 camPos; struct { RefPtr<UIControl> c; Vector2 value; float32 eps; } data[2]; } testData[] = { { { 0.f, -2.f, 0.f }, { { c1, { .57f, .57f }, .01f }, { c2, { .3f, .3f }, .01f } } }, { { -1.f, -1.f, -1.f }, { { c1, { 2.f, 2.f }, .01f }, { c2, { .28f, .28f }, .01f } } }, { { 0.f, 10.f, 0.f }, { { c1, { .1f, .1f }, .01f }, { c2, { .1f, .1f }, .01f } } } }; emcc->SetSyncScaleEnabled(true); for (const auto& test : testData) { camera->SetPosition(test.camPos); SystemsUpdate(0.f); for (const auto& d : test.data) { Vector2 scale = d.c->GetScale(); TEST_VERIFY(FLOAT_EQUAL_EPS(scale.x, d.value.x, d.eps)); TEST_VERIFY(FLOAT_EQUAL_EPS(scale.y, d.value.y, d.eps)); } } } DAVA_TEST (OrderTest) { using namespace DAVA; const struct { Vector3 camPos; List<RefPtr<UIControl>> order; // Last element in list will be top on screen } testData[] = { { { 0.f, -2.f, 0.f }, { c2, c1 } }, { { 0.f, 2.f, 0.f }, { c1, c2 } } }; emcc->SetSyncOrderEnabled(true); emcc->SetOrderMode(UIEntityMarkersContainerComponent::OrderMode::NearFront); for (const auto& test : testData) { camera->SetPosition(test.camPos); SystemsUpdate(0.f); TEST_VERIFY(std::equal(test.order.begin(), test.order.end(), markers->GetChildren().begin())); } emcc->SetOrderMode(UIEntityMarkersContainerComponent::OrderMode::NearBack); for (const auto& test : testData) { camera->SetPosition(test.camPos); SystemsUpdate(0.f); TEST_VERIFY(std::equal(test.order.begin(), test.order.end(), markers->GetChildren().rbegin())); } } DAVA_TEST (VisibilityTest) { using namespace DAVA; const struct { Vector3 camPos; Map<RefPtr<UIControl>, bool> data; } testData[] = { { { 0.f, -2.f, 0.f }, { { c1, true }, { c2, true } } }, { { 0.f, -.5f, 0.f }, { { c1, false }, { c2, true } } }, { { 0.f, .5f, 0.f }, { { c1, true }, { c2, false } } } }; emcc->SetSyncVisibilityEnabled(true); for (const auto& test : testData) { camera->SetPosition(test.camPos); SystemsUpdate(0.f); for (auto& pair : test.data) { TEST_VERIFY(pair.first->GetVisibilityFlag() == pair.second); } } } DAVA_TEST (CustomStrategyTest) { using namespace DAVA; emcc->SetUseCustomStrategy(true); emcc->SetCustomStrategy([](UIControl* c, UIEntityMarkersContainerComponent* container, UIEntityMarkerComponent* marker) { TEST_VERIFY(c != nullptr); TEST_VERIFY(container != nullptr); TEST_VERIFY(marker != nullptr); }); SystemsUpdate(0.f); } DAVA_TEST (AddRemoveComponents) { using namespace DAVA; markers->RemoveComponent<UIEntityMarkersContainerComponent>(); TEST_VERIFY(markers->GetComponent<UIEntityMarkersContainerComponent>() == nullptr); markers->GetOrCreateComponent<UIEntityMarkersContainerComponent>(); TEST_VERIFY(markers->GetComponent<UIEntityMarkersContainerComponent>() != nullptr); c1->RemoveComponent<UIEntityMarkerComponent>(); TEST_VERIFY(c1->GetComponent<UIEntityMarkerComponent>() == nullptr); c1->GetOrCreateComponent<UIEntityMarkerComponent>(); TEST_VERIFY(c1->GetComponent<UIEntityMarkerComponent>() != nullptr); } };
32.690909
129
0.584316
[ "render", "transform" ]
28f9d4c9aca0003f1d781dc62ebbd77c794f9212
50,743
cpp
C++
src/pxUtil.cpp
madanwork/pxCore
4009500ad3cee46c492ada8230d6c6d6a6d4825b
[ "Apache-2.0" ]
null
null
null
src/pxUtil.cpp
madanwork/pxCore
4009500ad3cee46c492ada8230d6c6d6a6d4825b
[ "Apache-2.0" ]
2
2017-12-08T14:22:28.000Z
2018-02-15T03:28:31.000Z
src/pxUtil.cpp
madanwork/pxCore
4009500ad3cee46c492ada8230d6c6d6a6d4825b
[ "Apache-2.0" ]
2
2017-02-24T10:47:32.000Z
2017-04-12T02:30:26.000Z
/* pxCore Copyright 2005-2018 John Robinson 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. */ // pxUtil.cpp #ifndef WIN32 #include <unistd.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <png.h> #include "rtLog.h" #include "pxCore.h" #include "pxOffscreen.h" #include "pxUtil.h" #include <openssl/md5.h> #define SUPPORT_PNG #define SUPPORT_JPG #include "rtRef.h" #include "rtObject.h" #include <stdio.h> #include <string.h> #include <float.h> //#define STB_IMAGE_WRITE_IMPLEMENTATION //#include "stb_image_write.h" #define NANOSVG_ALL_COLOR_KEYWORDS // Include full list of color keywords. #define NANOSVG_IMPLEMENTATION // Expands implementation #include "nanosvg.h" #define NANOSVGRAST_IMPLEMENTATION #include "nanosvgrast.h" #ifdef SAFE_FREE #undef SAFE_FREE #endif #define SAFE_FREE(x) do { free(x); (x) = NULL; } while(0) pxImageType getImageType( const uint8_t* data, size_t len ); //fwd class NSVGrasterizerEx { public: NSVGrasterizerEx() { rast = nsvgCreateRasterizer(); } // ctor ~NSVGrasterizerEx() { nsvgDeleteRasterizer(rast); } // dtor NSVGrasterizer *getPtr() { return rast; }; private: NSVGrasterizer *rast; }; // CLASS; static NSVGrasterizerEx rast; static rtMutex rastMutex; // Assume alpha is not premultiplied rtError pxLoadImage(const char *imageData, size_t imageDataSize, pxOffscreen &o, int32_t w /* = 0 */, int32_t h /* = 0 */, float sx /* = 1.0f */, float sy /* = 1.0f */) { pxImageType imgType = getImageType( (const uint8_t*) imageData, imageDataSize); rtError retVal = RT_FAIL; switch(imgType) { case PX_IMAGE_PNG: { retVal = pxLoadPNGImage(imageData, imageDataSize, o); } break; case PX_IMAGE_JPG: { #ifdef ENABLE_LIBJPEG_TURBO retVal = pxLoadJPGImageTurbo(imageData, imageDataSize, o); if (retVal != RT_OK) { retVal = pxLoadJPGImage(imageData, imageDataSize, o); } #else retVal = pxLoadJPGImage(imageData, imageDataSize, o); #endif //ENABLE_LIBJPEG_TURBO } break; case PX_IMAGE_SVG: default: { retVal = pxLoadSVGImage(imageData, imageDataSize, o, w, h, sx, sy); } break; }//SWITCH if (retVal != RT_OK) { rtLogError("ERROR: pxLoadImage() - failed" ); return retVal; } // TODO more sane image type detection and flow if (o.mPixelFormat != RT_DEFAULT_PIX) { o.swizzleTo(RT_DEFAULT_PIX); } return retVal; } // APNG looks like a PNG with extra chunks ... can fallback to display static PNG rtError pxLoadAImage(const char* imageData, size_t imageDataSize, pxTimedOffscreenSequence &s) { // Load as PNG... rtError retVal = pxLoadAPNGImage(imageData, imageDataSize, s); if (retVal != RT_OK) // Failed ... trying as JPG (why?) { #if 0 rtLogError("ERROR: pxLoadAPNGImage() - failed to load APNG ... " ); return retVal; #else pxOffscreen o; #ifdef ENABLE_LIBJPEG_TURBO retVal = pxLoadJPGImageTurbo(imageData, imageDataSize, o); if (retVal != RT_OK) { retVal = pxLoadJPGImage(imageData, imageDataSize, o); } #else retVal = pxLoadJPGImage(imageData, imageDataSize, o); #endif //ENABLE_LIBJPEG_TURBO s.init(); s.addBuffer(o,0); #endif // 0 } return retVal; } // TODO Detection needs to be improved... // Handling jpeg as fallback now rtError pxLoadImage(const char *filename, pxOffscreen &b, int32_t w /* = 0 */, int32_t h /* = 0 */, float sx /* = 1.0f */, float sy /* = 1.0f */) { rtData d; rtError e = rtLoadFile(filename, d); if (e == RT_OK) return pxLoadImage((const char *)d.data(), d.length(), b); else { e = RT_RESOURCE_NOT_FOUND; rtLogError("Could not load image file %s.", filename); } return e; } rtError pxStoreImage(const char *filename, pxOffscreen &b) { return pxStorePNGImage(filename, b); } bool pxIsPNGImage(rtData d) { return (getImageType( (const uint8_t*) d.data(), d.length()) == PX_IMAGE_PNG); } bool pxIsPNGImage(const char *imageData, size_t imageDataSize) { return (getImageType( (const uint8_t*) imageData, imageDataSize) == PX_IMAGE_PNG); } rtError pxLoadPNGImage(const char *filename, pxOffscreen &o) { rtData d; rtError e = rtLoadFile(filename, d); if (e == RT_OK) { // TODO get rid of the cast e = pxLoadPNGImage((const char *)d.data(), d.length(), o); } else { rtLogError("Failed to load image file, %s.", filename); } return e; } /* structure to store PNG image bytes */ struct mem_encode { char *buffer; size_t size; }; // TODO change this to using rtData more directly void my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { /* with libpng15 next line causes pointer deference error; use libpng12 */ struct mem_encode *p = (struct mem_encode *)png_get_io_ptr(png_ptr); /* was png_ptr->io_ptr */ size_t nsize = p->size + length; /* allocate or grow buffer */ if (p->buffer) p->buffer = (char *)realloc(p->buffer, nsize); else p->buffer = (char *)malloc(nsize); if (!p->buffer) png_error(png_ptr, "Write Error"); /* copy new bytes to end of buffer */ memcpy(p->buffer + p->size, data, length); p->size += length; } // TODO rewrite this... rtError pxStorePNGImage(pxOffscreen &b, rtData &pngData) { if (b.mPixelFormat != RT_PIX_RGBA) { // TODO should not need swizzle... libpng should have // have options to deal with this b.swizzleTo(RT_PIX_RGBA); // needed for PNG encoder } png_structp png_ptr; png_infop info_ptr; png_bytep *row_pointers; struct mem_encode state; state.buffer = NULL; state.size = 0; { // initialize stuff png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { rtLogError("FATAL: png_create_write_struct() - FAILED"); return RT_FAIL; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); rtLogError("FATAL: png_create_info_struct() - FAILED"); return RT_FAIL; } if (!setjmp(png_jmpbuf(png_ptr))) { png_set_write_fn(png_ptr, &state, my_png_write_data, NULL); // write header if (!setjmp(png_jmpbuf(png_ptr))) { #if 0 png_byte color_type = (grayscale?PNG_COLOR_MASK_ALPHA:0) | (alpha?PNG_COLOR_MASK_ALPHA:0); #endif png_set_IHDR(png_ptr, info_ptr, b.width(), b.height(), 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); // setjmp() ... needed for 'libpng' error handling... // write bytes if (!setjmp(png_jmpbuf(png_ptr))) { row_pointers = (png_bytep *)malloc(sizeof(png_bytep) * b.height()); if (row_pointers) { for (int y = 0; y < b.height(); y++) { row_pointers[y] = (png_byte *)b.scanline(y); } png_write_image(png_ptr, row_pointers); // end write if (!setjmp(png_jmpbuf(png_ptr))) { png_write_end(png_ptr, NULL); } free(row_pointers); } //ENDIF - row_pointers } } } png_destroy_write_struct(&png_ptr, &info_ptr); } pngData.init((uint8_t *)state.buffer, state.size); if (state.buffer) free(state.buffer); return RT_OK; } rtError pxStorePNGImage(const char *filename, pxOffscreen &b, bool /*grayscale*/, bool /*alpha*/) { png_structp png_ptr; png_infop info_ptr; png_bytep *row_pointers; // create file rtFilePointer fp(fopen(filename, "wb")); if (fp) { // initialize stuff png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { rtLogError("FATAL: png_create_write_struct() - FAILED"); return RT_FAIL; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); rtLogError("FATAL: png_create_info_struct() - FAILED"); return RT_FAIL; } if (!setjmp(png_jmpbuf(png_ptr))) { png_init_io(png_ptr, fp.getPtr()); // write header if (!setjmp(png_jmpbuf(png_ptr))) { #if 0 png_byte color_type = (grayscale?PNG_COLOR_MASK_ALPHA:0) | (alpha?PNG_COLOR_MASK_ALPHA:0); #endif // png_set_bgr(png_ptr); png_set_IHDR(png_ptr, info_ptr, b.width(), b.height(), 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); // setjmp() ... needed for 'libpng' error handling... // write bytes if (!setjmp(png_jmpbuf(png_ptr))) { row_pointers = (png_bytep *)malloc(sizeof(png_bytep) * b.height()); if (row_pointers) { for (int y = 0; y < b.height(); y++) { row_pointers[y] = (png_byte *)b.scanline(y); } png_write_image(png_ptr, row_pointers); // end write if (!setjmp(png_jmpbuf(png_ptr))) { png_write_end(png_ptr, NULL); } free(row_pointers); } //ENDIF - row_pointers } } } png_destroy_write_struct(&png_ptr, &info_ptr); #if 0 // cleanup heap allocation for (y=0; y<height; y++) { free(row_pointers[y]); } #endif // free(row_pointers); } return RT_OK; } // JPEG Support /* * example.c * * This file illustrates how to use the IJG code as a subroutine library * to read or write JPEG image files. You should look at this code in * conjunction with the documentation file libjpeg.txt. * * This code will not do anything useful as-is, but it may be helpful as a * skeleton for constructing routines that call the JPEG library. * * We present these routines in the same coding style used in the JPEG code * (ANSI function definitions, etc); but you are of course free to code your * routines in a different style if you prefer. */ #include <stdio.h> /* * Include file for users of JPEG library. * You will need to have included system headers that define at least * the typedefs FILE and size_t before you can include jpeglib.h. * (stdio.h is sufficient on ANSI-conforming systems.) * You may also wish to include "jerror.h". */ #include "jpeglib.h" /* * <setjmp.h> is used for the optional error recovery mechanism shown in * the second part of the example. */ #include <setjmp.h> #if 0 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/ /* This half of the example shows how to feed data into the JPEG compressor. * We present a minimal version that does not worry about refinements such * as error recovery (the JPEG code will just exit() if it gets an error). */ /* * IMAGE DATA FORMATS: * * The standard input image format is a rectangular array of pixels, with * each pixel having the same number of "component" values (color channels). * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars). * If you are working with color data, then the color values for each pixel * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit * RGB color. * * For this example, we'll assume that this data structure matches the way * our application has stored the image in memory, so we can just pass a * pointer to our image buffer. In particular, let's say that the image is * RGB color and is described by: */ extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */ extern int image_height; /* Number of rows in image */ extern int image_width; /* Number of columns in image */ /* * Sample routine for JPEG compression. We assume that the target file name * and a compression quality factor are passed in. */ GLOBAL(void) write_JPEG_file (char * filename, int quality) { /* This struct contains the JPEG compression parameters and pointers to * working space (which is allocated as needed by the JPEG library). * It is possible to have several such structures, representing multiple * compression/decompression processes, in existence at once. We refer * to any one struct (and its associated working data) as a "JPEG object". */ struct jpeg_compress_struct cinfo; /* This struct represents a JPEG error handler. It is declared separately * because applications often want to supply a specialized error handler * (see the second half of this file for an example). But here we just * take the easy way out and use the standard error handler, which will * print a message on stderr and call exit() if compression fails. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ struct jpeg_error_mgr jerr; /* More stuff */ FILE * outfile; /* target file */ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ int row_stride; /* physical row width in image buffer */ /* Step 1: allocate and initialize JPEG compression object */ /* We have to set up the error handler first, in case the initialization * step fails. (Unlikely, but it could happen if you are out of memory.) * This routine fills in the contents of struct jerr, and returns jerr's * address which we place into the link field in cinfo. */ cinfo.err = jpeg_std_error(&jerr); /* Now we can initialize the JPEG compression object. */ jpeg_create_compress(&cinfo); /* Step 2: specify data destination (eg, a file) */ /* Note: steps 2 and 3 can be done in either order. */ /* Here we use the library-supplied code to send compressed data to a * stdio stream. You can also write your own code to do something else. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that * requires it in order to write binary files. */ if ((outfile = fopen(filename, "wb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_dest(&cinfo, outfile); /* Step 3: set parameters for compression */ /* First we supply a description of the input image. * Four fields of the cinfo struct must be filled in: */ cinfo.image_width = image_width; /* image width and height, in pixels */ cinfo.image_height = image_height; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ /* Now use the library's routine to set default compression parameters. * (You must set at least cinfo.in_color_space before calling this, * since the defaults depend on the source color space.) */ jpeg_set_defaults(&cinfo); /* Now you can set any non-default parameters you wish to. * Here we just illustrate the use of quality (quantization table) scaling: */ jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); /* Step 4: Start compressor */ /* TRUE ensures that we will write a complete interchange-JPEG file. * Pass TRUE unless you are very sure of what you're doing. */ jpeg_start_compress(&cinfo, TRUE); /* Step 5: while (scan lines remain to be written) */ /* jpeg_write_scanlines(...); */ /* Here we use the library's state variable cinfo.next_scanline as the * loop counter, so that we don't have to keep track ourselves. * To keep things simple, we pass one scanline per call; you can pass * more if you wish, though. */ row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */ while (cinfo.next_scanline < cinfo.image_height) { /* jpeg_write_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could pass * more than one scanline at a time if that's more convenient. */ row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } /* Step 6: Finish compression */ jpeg_finish_compress(&cinfo); /* After finish_compress, we can close the output file. */ fclose(outfile); /* Step 7: release JPEG compression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_compress(&cinfo); /* And we're done! */ } /* * SOME FINE POINTS: * * In the above loop, we ignored the return value of jpeg_write_scanlines, * which is the number of scanlines actually written. We could get away * with this because we were only relying on the value of cinfo.next_scanline, * which will be incremented correctly. If you maintain additional loop * variables then you should be careful to increment them properly. * Actually, for output to a stdio stream you needn't worry, because * then jpeg_write_scanlines will write all the lines passed (or else exit * with a fatal error). Partial writes can only occur if you use a data * destination module that can demand suspension of the compressor. * (If you don't know what that's for, you don't need it.) * * If the compressor requires full-image buffers (for entropy-coding * optimization or a multi-scan JPEG file), it will create temporary * files for anything that doesn't fit within the maximum-memory setting. * (Note that temp files are NOT needed if you use the default parameters.) * On some systems you may need to set up a signal handler to ensure that * temporary files are deleted if the program is interrupted. See libjpeg.txt. * * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG * files to be compatible with everyone else's. If you cannot readily read * your data in that order, you'll need an intermediate array to hold the * image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top * source data using the JPEG code's internal virtual-array mechanisms. */ #endif /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/ /* This half of the example shows how to read data from the JPEG decompressor. * It's a bit more refined than the above, in that we show: * (a) how to modify the JPEG library's standard error-reporting behavior; * (b) how to allocate workspace using the library's memory manager. * * Just to make this example a little different from the first one, we'll * assume that we do not intend to put the whole image into an in-memory * buffer, but to send it line-by-line someplace else. We need a one- * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG * memory manager allocate it for us. This approach is actually quite useful * because we don't need to remember to deallocate the buffer separately: it * will go away automatically when the JPEG object is cleaned up. */ /* * ERROR HANDLING: * * The JPEG library's standard error handler (jerror.c) is divided into * several "methods" which you can override individually. This lets you * adjust the behavior without duplicating a lot of code, which you might * have to update with each future release. * * Our example here shows how to override the "error_exit" method so that * control is returned to the library's caller when a fatal error occurs, * rather than calling exit() as the standard error_exit method does. * * We use C's setjmp/longjmp facility to return control. This means that the * routine which calls the JPEG library must first execute a setjmp() call to * establish the return point. We want the replacement error_exit to do a * longjmp(). But we need to make the setjmp buffer accessible to the * error_exit routine. To do this, we make a private extension of the * standard JPEG error handler object. (If we were using C++, we'd say we * were making a subclass of the regular error handler.) * * Here's the extended error handler struct: */ struct my_error_mgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; typedef struct my_error_mgr *my_error_ptr; /* * Here's the routine that will replace the standard error_exit method: */ METHODDEF(void) my_error_exit(j_common_ptr cinfo) { /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ my_error_ptr myerr = (my_error_ptr)cinfo->err; /* Always display the message. */ /* We could postpone this until after returning, if we chose. */ (*cinfo->err->output_message)(cinfo); /* Return control to the setjmp point */ longjmp(myerr->setjmp_buffer, 1); } /* * SOME FINE POINTS: * * In the above code, we ignored the return value of jpeg_read_scanlines, * which is the number of scanlines actually read. We could get away with * this because we asked for only one line at a time and we weren't using * a suspending data source. See libjpeg.txt for more info. * * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress(); * we should have done it beforehand to ensure that the space would be * counted against the JPEG max_memory setting. In some systems the above * code would risk an out-of-memory error. However in general we don't * know the output image dimensions before jpeg_start_decompress(), unless we * call jpeg_calc_output_dimensions(). See libjpeg.txt for more about this. * * Scanlines are returned in the same order as they appear in the JPEG file, * which is standardly top-to-bottom. If you must emit data bottom-to-top, * you can use one of the virtual arrays provided by the JPEG memory manager * to invert the data. See wrbmp.c for an example. * * As with compression, some operating modes may require temporary files. * On some systems you may need to set up a signal handler to ensure that * temporary files are deleted if the program is interrupted. See libjpeg.txt. */ bool pxIsJPGImage(const char *imageData, size_t imageDataSize) { return (getImageType( (const uint8_t*) imageData, imageDataSize) == PX_IMAGE_JPG); } rtError pxLoadJPGImage(const char *filename, pxOffscreen &o) { rtData d; rtError e = rtLoadFile(filename, d); if (e == RT_OK) { #ifdef ENABLE_LIBJPEG_TURBO rtError retVal = pxLoadJPGImageTurbo((const char *)d.data(), d.length(), o); if (retVal != RT_OK) { retVal = pxLoadJPGImage((const char *)d.data(), d.length(), o); } return retVal; #else return pxLoadJPGImage((const char *)d.data(), d.length(), o); #endif //ENABLE_LIBJPEG_TURBO } else rtLogError("Could not load JPG file: %s", filename); return e; } #ifdef ENABLE_LIBJPEG_TURBO extern "C" { #include <turbojpeg.h> } rtError pxLoadJPGImageTurbo(const char *buf, size_t buflen, pxOffscreen &o) { rtLogDebug("using pxLoadJPGImageTurbo"); if (!buf) { rtLogError("NULL buffer passed into pxLoadJPGImageTurbo"); return RT_FAIL; } tjhandle jpegDecompressor = tjInitDecompress(); int width, height, jpegSubsamp, jpegColorspace; tjDecompressHeader3(jpegDecompressor, (unsigned char *)buf, buflen, &width, &height, &jpegSubsamp, &jpegColorspace); //int colorComponent = 3; if (jpegColorspace == TJCS_GRAY) { //colorComponent = 1; tjDestroy(jpegDecompressor); return RT_FAIL;// TODO : add grayscale support for libjpeg turbo. falling back to libjpeg for now } // limit memory usage to resolution 4096x4096 if (((size_t)width * height) > ((size_t)4096 * 4096)) { rtLogError("Error libjpeg-turbo: image too large"); tjDestroy(jpegDecompressor); return RT_FAIL; } unsigned char *imageBuffer = tjAlloc(width * height * 3); if (!imageBuffer) { rtLogError("Error allocating libjpeg-turbo buffer"); tjDestroy(jpegDecompressor); return RT_FAIL; } int result = tjDecompress2(jpegDecompressor, (unsigned char *)buf, buflen, imageBuffer, width, 0, height, TJPF_RGB /*(colorComponent == 3) ? TJPF_RGB : jpegColorspace*/, TJFLAG_FASTDCT); if (result != 0) { rtLogError("Error decompressing using libjpeg turbo"); tjFree(imageBuffer); tjDestroy(jpegDecompressor); return RT_FAIL; } o.init(width, height); int scanlinen = 0; unsigned int bufferIndex = 0; while (scanlinen < height) { pxPixel *p = o.scanline(scanlinen++); { char *b = (char *)&imageBuffer[bufferIndex]; char *bend = b + (width * 3); while (b < bend) { p->r = b[0]; p->g = b[1]; p->b = b[2]; p->a = 255; b += 3; // next pixel bufferIndex += 3; p++; } } } o.mPixelFormat = RT_PIX_ARGB; tjFree(imageBuffer); tjDestroy(jpegDecompressor); /* And we're done! */ return RT_OK; } #endif //ENABLE_LIBJPEG_TURBO rtError pxLoadJPGImage(const char *buf, size_t buflen, pxOffscreen &o) { if (!buf) { rtLogError("NULL buffer passed into pxLoadJPGImage"); return RT_FAIL; } /* This struct contains the JPEG decompression parameters and pointers to * working space (which is allocated as needed by the JPEG library). */ struct jpeg_decompress_struct cinfo; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ struct my_error_mgr jerr; /* More stuff */ // FILE * infile; /* source file */ JSAMPARRAY buffer; /* Output row buffer */ int row_stride; /* physical row width in output buffer */ /* In this example we want to open the input file before doing anything else, * so that the setjmp() error recovery below can assume the file is open. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that * requires it in order to read binary files. */ /* Step 1: allocate and initialize JPEG decompression object */ /* We set up the normal JPEG error routines, then override error_exit. */ cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = my_error_exit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress(&cinfo); // fclose(infile); return RT_FAIL; } /* Now we can initialize the JPEG decompression object. */ jpeg_create_decompress(&cinfo); /* Step 2: specify data source (eg, a file) */ jpeg_mem_src(&cinfo, (unsigned char *)buf, buflen); /* Step 3: read file parameters with jpeg_read_header() */ (void)jpeg_read_header(&cinfo, TRUE); cinfo.out_color_space = JCS_RGB; /* We can ignore the return value from jpeg_read_header since * (a) suspension is not possible with the stdio data source, and * (b) we passed TRUE to reject a tables-only JPEG file as an error. * See libjpeg.txt for more info. */ /* Step 4: set parameters for decompression */ /* In this example, we don't need to change any of the defaults set by * jpeg_read_header(), so we do nothing here. */ /* Step 5: Start decompressor */ (void)jpeg_start_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ /* We may need to do some setup of our own at this point before reading * the data. After jpeg_start_decompress() we have the correct scaled * output image dimensions available, as well as the output colormap * if we asked for color quantization. * In this example, we need to make an output work buffer of the right size. */ /* JSAMPLEs per row in output buffer */ row_stride = cinfo.output_width * cinfo.output_components; /* Make a one-row-high sample array that will go away when done with image */ buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1); o.init(cinfo.output_width, cinfo.output_height); /* Step 6: while (scan lines remain to be read) */ /* jpeg_read_scanlines(...); */ /* Here we use the library's state variable cinfo.output_scanline as the * loop counter, so that we don't have to keep track ourselves. */ int scanlinen = 0; while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could ask for * more than one scanline at a time if that's more convenient. */ (void)jpeg_read_scanlines(&cinfo, buffer, 1); /* Assume put_scanline_someplace wants a pointer and sample count. */ pxPixel *p = o.scanline(scanlinen++); { char *b = (char *)buffer[0]; char *bend = b + (cinfo.output_width * 3); while (b < bend) { p->r = b[0]; p->g = b[1]; p->b = b[2]; p->a = 255; b += 3; // next pixel p++; } } } o.mPixelFormat = RT_PIX_ARGB; /* Step 7: Finish decompression */ (void)jpeg_finish_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ /* Step 8: Release JPEG decompression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_decompress(&cinfo); /* After finish_decompress, we can close the input file. * Here we postpone it until after no more JPEG errors are possible, * so as to simplify the setjmp error logic above. (Actually, I don't * think that jpeg_destroy can do an error exit, but why assume anything...) */ //fclose(infile); /* At this point you may want to check to see whether any corrupt-data * warnings occurred (test whether jerr.pub.num_warnings is nonzero). */ /* And we're done! */ return RT_OK; } rtError pxStoreSVGImage(const char* /*filename*/, pxBuffer& /*b*/) { return RT_FAIL; } // NOT SUPPORTED rtError pxLoadSVGImage(const char* buf, size_t buflen, pxOffscreen& o, int w /* = 0 */, int h /* = 0 */, float sx /* = 1.0f */, float sy /* = 1.0f */) { rtMutexLockGuard autoLock(rastMutex); if (rast.getPtr() == NULL) { rtLogError("SVG: No rasterizer available \n"); return RT_FAIL; } if (buf == NULL || buflen == 0 ) { rtLogError("SVG: Bad args.\n"); return RT_FAIL; } if (sx <= 0.0f || sy <= 0.0f) { rtLogError("SVG: Bad image scale sx: %f sy: %f\n", sx, sy); return RT_FAIL; } // NOTE: 'nanosvg' is *destructive* to the SVG source buffer // // Pass it a copy ! // void *buf_copy = malloc(buflen); memcpy(buf_copy, buf, buflen); NSVGimage *image = nsvgParse( (char *) buf_copy, "px", 96.0f); // 96 dpi (suggested default) free(buf_copy); // clean-up if (image == NULL) { rtLogError("SVG: Could not init decode SVG.\n"); return RT_FAIL; } int image_w = (int)image->width; // parsed SVG image dimensions int image_h = (int)image->height; // parsed SVG image dimensions if (image_w == 0 || image_h == 0) { nsvgDelete(image); rtLogError("SVG: Bad image dimensions WxH: %d x %d\n", image_w, image_h); return RT_FAIL; } // Dimensions WxH ... *only* if no Scale XY if( (sx == 1.0f && sy == 1.0f) && (w > 0 && h > 0) ) // <<< Use WxH only if no scale. Scale takes precedence { float ratioW = (float) w / (float) image_w; float ratioH = (float) h / (float) image_h; sx = sy = (ratioW < ratioH) ? ratioW : ratioH; // MIN() } o.initWithColor( (image_w * sx), (image_h * sy), pxClear); // default sized nsvgRasterizeFull(rast.getPtr(), image, 0, 0, sx, sy, (unsigned char*) o.base(), o.width(), o.height(), o.width() *4); nsvgDelete(image); return RT_OK; } rtError pxLoadSVGImage(const char *filename, pxOffscreen &o, int w /* = 0 */, int h /* = 0 */, float sx /* = 1.0f */, float sy /* = 1.0f */) { rtData d; rtError e = rtLoadFile(filename, d); if (e == RT_OK) { // TODO get rid of the cast e = pxLoadSVGImage((const char *)d.data(), d.length(), o, w, h, sx, sy); } else { rtLogError("Failed to load image file, %s.", filename); } return e; } rtError pxStoreJPGImage(char * /*filename*/, pxBuffer & /*b*/) { return RT_FAIL; // NOT SUPPORTED } struct PngStruct { PngStruct(char *data, size_t dataSize) : imageData(data), imageDataSize(dataSize), readPosition(0) { } char *imageData; size_t imageDataSize; int readPosition; }; void readPngData(png_structp pngPtr, png_bytep data, png_size_t length) { png_voidp a = png_get_io_ptr(pngPtr); PngStruct *pngStruct = (PngStruct *)a; memcpy((char *)data, pngStruct->imageData + pngStruct->readPosition, length); pngStruct->readPosition += length; } rtError pxLoadPNGImage(const char *imageData, size_t imageDataSize, pxOffscreen &o) { rtError e = RT_FAIL; png_structp png_ptr; png_infop info_ptr; // int number_of_passes; png_bytep *row_pointers; PngStruct pngStruct((char *)imageData, imageDataSize); if (!imageData) { rtLogError("FATAL: Invalid arguments - imageData = NULL"); return e; } if (imageDataSize < 8) { rtLogError("FATAL: Invalid arguments - imageDataSize < 8"); return e; } unsigned char header[8]; // 8 is the maximum size that can be checked // open file and test for it being a png memcpy(header, imageData, 8); pngStruct.readPosition += 8; // test PNG header if (png_sig_cmp(header, 0, 8) != 0) { // TODO Improve Detection of different image types // Fail quietly so we fallback to JPG // rtLogError("FATAL: Invalid PNG header"); return RT_FAIL; } // initialize stuff png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { rtLogError("FATAL: png_create_read_struct() - failed !"); return e; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); rtLogError("FATAL: png_create_info_struct() - failed !"); return e; } if (!setjmp(png_jmpbuf(png_ptr))) { png_set_read_fn(png_ptr, (png_voidp)&pngStruct, readPngData); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); int width = png_get_image_width(png_ptr, info_ptr); int height = png_get_image_height(png_ptr, info_ptr); png_byte color_type = png_get_color_type(png_ptr, info_ptr); png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr); if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); } if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); } if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); } //png_set_bgr(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); o.init(width, height); // number_of_passes = png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); // read file if (!setjmp(png_jmpbuf(png_ptr))) { row_pointers = (png_bytep *)malloc(sizeof(png_bytep) * height); if (row_pointers) { for (int y = 0; y < height; y++) { row_pointers[y] = (png_byte *)o.scanline(y); } png_read_image(png_ptr, row_pointers); free(row_pointers); } e = RT_OK; } else { e = RT_FAIL; } } else { e = RT_FAIL; } if (e == RT_OK) { o.mPixelFormat = RT_PIX_RGBA; } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return e; } void pxTimedOffscreenSequence::init() { mTotalTime = 0; mNumPlays = 0; mSequence.clear(); } void pxTimedOffscreenSequence::addBuffer(pxBuffer &b, double d) { entry e; e.mOffscreen.init(b.width(), b.height()); b.blit(e.mOffscreen); e.mDuration = d; mSequence.push_back(e); mTotalTime += d; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include "png.h" //#define PNG_APNG_SUPPORTED #ifdef PNG_APNG_SUPPORTED void BlendOver(unsigned char **rows_dst, unsigned char **rows_src, unsigned int x, unsigned int y, unsigned int w, unsigned int h) { unsigned int i, j; int u, v, al; for (j = 0; j < h; j++) { unsigned char *sp = rows_src[j]; unsigned char *dp = rows_dst[j + y] + x * 4; for (i = 0; i < w; i++, sp += 4, dp += 4) { if (sp[3] == 255) memcpy(dp, sp, 4); else if (sp[3] != 0) { if (dp[3] != 0) { u = sp[3] * 255; v = (255 - sp[3]) * dp[3]; al = u + v; dp[0] = (sp[0] * u + dp[0] * v) / al; dp[1] = (sp[1] * u + dp[1] * v) / al; dp[2] = (sp[2] * u + dp[2] * v) / al; dp[3] = al / 255; } else memcpy(dp, sp, 4); } } } } #endif rtError pxLoadAPNGImage(const char *imageData, size_t imageDataSize, pxTimedOffscreenSequence &s) { if (!imageData) { rtLogError("FATAL: Invalid arguments - imageData = NULL"); return RT_FAIL; } if (imageDataSize < 8) { rtLogError("FATAL: Invalid arguments - imageDataSize < 8"); return RT_FAIL; } s.init(); PngStruct pngStruct((char *)imageData, imageDataSize); unsigned char header[8]; // 8 is the maximum size that can be checked // test for it being a png memcpy(header, imageData, 8); pngStruct.readPosition += 8; // test PNG header if (png_sig_cmp(header, 0, 8) != 0) { // TODO Improve Detection of different image types // rtLogError("FATAL: Invalid PNG header"); return RT_FAIL; } //unsigned int width, height, channels, rowbytes, size, i, j; unsigned int width, height, i, j; unsigned long size, rowbytes; png_bytepp rows_image; png_bytepp rows_frame; unsigned char *p_image; unsigned char *p_frame; unsigned char *p_temp; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); if (png_ptr && info_ptr) { if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return RT_FAIL; } png_set_read_fn(png_ptr, (png_voidp)&pngStruct, readPngData); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); png_set_expand(png_ptr); png_set_strip_16(png_ptr); png_set_palette_to_rgb(png_ptr); png_set_gray_to_rgb(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); (void)png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); //channels = png_get_channels(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); size = height * rowbytes; p_image = (unsigned char *)malloc(size); p_frame = (unsigned char *)malloc(size); p_temp = (unsigned char *)malloc(size); rows_image = (png_bytepp)malloc(height * sizeof(png_bytep)); rows_frame = (png_bytepp)malloc(height * sizeof(png_bytep)); if (p_image && p_frame && p_temp && rows_image && rows_frame) { png_uint_32 frames = 1; png_uint_32 x0 = 0; png_uint_32 y0 = 0; png_uint_32 w0 = width; png_uint_32 h0 = height; unsigned int first = 0; unsigned short delay_num = 1; unsigned short delay_den = 10; #ifdef PNG_APNG_SUPPORTED png_uint_32 plays = 0; unsigned char dop = 0; unsigned char bop = 0; first = (png_get_first_frame_is_hidden(png_ptr, info_ptr) != 0) ? 1 : 0; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) png_get_acTL(png_ptr, info_ptr, &frames, &plays); s.setNumPlays(plays); #endif for (j = 0; j < height; j++) rows_image[j] = p_image + j * rowbytes; for (j = 0; j < height; j++) rows_frame[j] = p_frame + j * rowbytes; for (i = 0; i < frames; i++) { #ifdef PNG_APNG_SUPPORTED if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) { png_read_frame_head(png_ptr, info_ptr); png_get_next_frame_fcTL(png_ptr, info_ptr, &w0, &h0, &x0, &y0, &delay_num, &delay_den, &dop, &bop); if (!delay_den) delay_den = 100; } if (i == first) { bop = PNG_BLEND_OP_SOURCE; if (dop == PNG_DISPOSE_OP_PREVIOUS) dop = PNG_DISPOSE_OP_BACKGROUND; } #endif png_read_image(png_ptr, rows_frame); #ifdef PNG_APNG_SUPPORTED if (dop == PNG_DISPOSE_OP_PREVIOUS) memcpy(p_temp, p_image, size); if (bop == PNG_BLEND_OP_OVER) BlendOver(rows_image, rows_frame, x0, y0, w0, h0); else #endif for (j = 0; j < h0; j++) memcpy(rows_image[j + y0] + x0 * 4, rows_frame[j], w0 * 4); // TODO Extra copy of frame going on here if (i >= first) { pxOffscreen o; o.init(width, height); for (uint32_t i = 0; i < height; i++) { memcpy(o.scanline(i), rows_image[i], width * 4); } s.addBuffer(o, (double)delay_num / (double)delay_den); } #ifdef PNG_APNG_SUPPORTED if (dop == PNG_DISPOSE_OP_PREVIOUS) memcpy(p_image, p_temp, size); else if (dop == PNG_DISPOSE_OP_BACKGROUND) for (j = 0; j < h0; j++) memset(rows_image[j + y0] + x0 * 4, 0, w0 * 4); #endif } png_read_end(png_ptr, info_ptr); } free(rows_frame); free(rows_image); free(p_temp); free(p_frame); free(p_image); } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return RT_OK; } rtString imageType2str(pxImageType t) { switch(t) { case PX_IMAGE_JPG: return rtString("PX_IMAGE_JPG"); case PX_IMAGE_PNG: return rtString("PX_IMAGE_PNG"); case PX_IMAGE_GIF: return rtString("PX_IMAGE_GIF"); case PX_IMAGE_TIFF: return rtString("PX_IMAGE_TIFF"); case PX_IMAGE_BMP: return rtString("PX_IMAGE_BMP"); case PX_IMAGE_WEBP: return rtString("PX_IMAGE_WEBP"); case PX_IMAGE_ICO: return rtString("PX_IMAGE_ICO"); case PX_IMAGE_SVG: return rtString("PX_IMAGE_SVG"); default: case PX_IMAGE_INVALID: return rtString("PX_IMAGE_INVALID"); } } pxImageType getImageType( const uint8_t* data, size_t len ) { if ( data == NULL ) return PX_IMAGE_INVALID; if ( len < 16 ) return PX_IMAGE_INVALID; // .jpg: FF D8 FF // .png: 89 50 4E 47 0D 0A 1A 0A // .gif: GIF87a // GIF89a // .tiff: 49 49 2A 00 // 4D 4D 00 2A // .bmp: BM // .webp: RIFF ???? WEBP // .ico 00 00 01 00 // 00 00 02 00 ( cursor files ) switch ( data[0] ) { case (uint8_t)'\xFF': return ( !strncmp( (const char*)data, "\xFF\xD8\xFF", 3 )) ? PX_IMAGE_JPG : PX_IMAGE_INVALID; case (uint8_t)'\x89': return ( !strncmp( (const char*)data, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 )) ? PX_IMAGE_PNG : PX_IMAGE_INVALID; case 'G': return ( !strncmp( (const char*)data, "GIF87a", 6 ) || !strncmp( (const char*)data, "GIF89a", 6 ) ) ? PX_IMAGE_GIF : PX_IMAGE_INVALID; case 'I': return ( !strncmp( (const char*)data, "\x49\x49\x2A\x00", 4 )) ? PX_IMAGE_TIFF : PX_IMAGE_INVALID; case 'M': return ( !strncmp( (const char*)data, "\x4D\x4D\x00\x2A", 4 )) ? PX_IMAGE_TIFF : PX_IMAGE_INVALID; case 'B': return (( data[1] == 'M' )) ? PX_IMAGE_BMP : PX_IMAGE_INVALID; case 'R': if ( strncmp( (const char*)data, "RIFF", 4 )) return PX_IMAGE_INVALID; if ( strncmp( (const char*)(data+8), "WEBP", 4 )) return PX_IMAGE_INVALID; return PX_IMAGE_WEBP; case '\0': if ( !strncmp( (const char*)data, "\x00\x00\x01\x00", 4 )) return PX_IMAGE_ICO; if ( !strncmp( (const char*)data, "\x00\x00\x02\x00", 4 )) return PX_IMAGE_ICO; return PX_IMAGE_INVALID; default: return PX_IMAGE_INVALID; } } static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static char *decoding_table = NULL; static int mod_table[] = {0, 2, 1}; void build_decoding_table() { decoding_table = (char*)malloc(256); for (int i = 0; i < 64; i++) decoding_table[(unsigned char) encoding_table[i]] = i; } void base64_cleanup() { if(decoding_table) { free(decoding_table); decoding_table = NULL; } } // ENCODE char *base64_encode(const unsigned char *data, size_t input_length, size_t *output_length) { if(output_length == NULL) { return NULL; } if(data == NULL) { output_length = 0; return NULL; } if(input_length == 0) { output_length = 0; return NULL; } *output_length = 4 * ((input_length + 2) / 3); char *encoded_data = (char *)malloc(*output_length); if (encoded_data == NULL) return NULL; for (uint32_t i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0; uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++) encoded_data[*output_length - 1 - i] = '='; return encoded_data; } rtError base64_encode(const unsigned char *data, size_t input_length, rtString& s) { size_t output_length = 0; char *ans = base64_encode(data, input_length, &output_length); if(ans != NULL) { s.init( (const char*) ans, output_length); free(ans); return RT_OK; } else { return RT_FAIL; } } rtError base64_encode(rtData& d, rtString& s) { return base64_encode( (const unsigned char *) d.data(), d.length(), s); } // DECODE unsigned char *base64_decode(const unsigned char *data, size_t input_length, size_t *output_length) { if (data == NULL) { return NULL; } if (output_length == NULL) { return NULL; } if ((input_length == 0) || (input_length % 4 != 0)) { return NULL; } if (output_length) *output_length = input_length / 4 * 3; if (data[input_length - 1] == '=') (*output_length)--; if (data[input_length - 2] == '=') (*output_length)--; unsigned char *decoded_data = (unsigned char*)malloc(*output_length); if (decoded_data == NULL) { return NULL; } if (decoding_table == NULL) { build_decoding_table(); } for (uint32_t i = 0, j = 0; i < input_length;) { uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } return decoded_data; } rtError base64_decode(const unsigned char *data, size_t input_length, rtData& d) { size_t output_length = 0; unsigned char *ans = base64_decode(data, input_length, &output_length); if(ans) { d.init((const uint8_t*) ans, output_length); free(ans); return RT_OK; } else { return RT_FAIL; } } //void testBase64() //{ // rtString in1 = "VGVzdGluZzEyMw=="; // "Testing123" in Base64 // rtData out1; // // base64_decode( (const unsigned char *) in1.cString(), in1.length(), out1); // // rtString txt = "Testing123"; // rtData in2( (const uint8_t*) txt.cString(), txt.length()); // rtString out2; // // base64_encode( in2, out2 ); // // if(memcmp(out1.data(), in2.data(), out1.length()) == 0) // { // printf("OK"); // } //} rtError base64_decode(rtString& s, rtData& d) { // testBase64(); return base64_decode( (const unsigned char *) s.cString(), s.length(), d); } rtString md5sum(rtString &d) { unsigned char md5_result[MD5_DIGEST_LENGTH]; // binary unsigned char str_result[MD5_DIGEST_LENGTH*2 + 1]; // char string MD5( (const unsigned char *) d.cString(), d.length(), (unsigned char *) &md5_result[0] ); for(int i=0; i < MD5_DIGEST_LENGTH; i++) { sprintf( (char *) &str_result[i*2], "%02X", md5_result[i]); // sprintf() ... will null terminate } return rtString( (char *) str_result); }
28.36389
188
0.638748
[ "object" ]
28fabac302fc87ec8e933921db72442918e2dae9
25,659
cpp
C++
core/globals.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/globals.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/globals.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
1
2019-01-13T00:44:17.000Z
2019-01-13T00:44:17.000Z
/*************************************************************************/ /* globals.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "globals.h" #include "os/dir_access.h" #include "os/file_access.h" #include "os/keyboard.h" #include "io/marshalls.h" #include "bind/core_bind.h" #include "os/os.h" #include "io/file_access_pack.h" #include "io/file_access_network.h" #include "variant_parser.h" GlobalConfig *GlobalConfig::singleton=NULL; GlobalConfig *GlobalConfig::get_singleton() { return singleton; } String GlobalConfig::get_resource_path() const { return resource_path; }; String GlobalConfig::localize_path(const String& p_path) const { if (resource_path=="") return p_path; //not initialied yet if (p_path.begins_with("res://") || p_path.begins_with("user://") || (p_path.is_abs_path() && !p_path.begins_with(resource_path))) return p_path.simplify_path(); DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String path = p_path.replace("\\","/").simplify_path(); if (dir->change_dir(path)==OK) { String cwd = dir->get_current_dir(); cwd = cwd.replace("\\","/"); memdelete(dir); if (!cwd.begins_with(resource_path)) { return p_path; }; return cwd.replace_first(resource_path, "res:/"); } else { memdelete(dir); int sep = path.find_last("/"); if (sep == -1) { return "res://"+path; }; String parent = path.substr(0, sep); String plocal = localize_path(parent); if (plocal == "") { return ""; }; return plocal + path.substr(sep, path.size() - sep); }; } void GlobalConfig::set_initial_value(const String& p_name, const Variant & p_value) { ERR_FAIL_COND(!props.has(p_name)); props[p_name].initial=p_value; } String GlobalConfig::globalize_path(const String& p_path) const { if (p_path.begins_with("res://")) { if (resource_path != "") { return p_path.replace("res:/",resource_path); }; return p_path.replace("res://", ""); }; return p_path; } bool GlobalConfig::_set(const StringName& p_name, const Variant& p_value) { _THREAD_SAFE_METHOD_ if (p_value.get_type()==Variant::NIL) props.erase(p_name); else { if (props.has(p_name)) { if (!props[p_name].overrided) props[p_name].variant=p_value; if (props[p_name].order>=NO_ORDER_BASE && registering_order) { props[p_name].order=last_order++; } } else { props[p_name]=VariantContainer(p_value,last_order++ + (registering_order?0:NO_ORDER_BASE)); } } if (!disable_platform_override) { String s=String(p_name); int sl = s.find("/"); int p = s.find("."); if (p!=-1 && sl!=-1 && p < sl) { Vector<String> ps = s.substr(0,sl).split("."); String prop=s.substr(sl,s.length()-sl); for(int i=1;i<ps.size();i++) { if (ps[i]==OS::get_singleton()->get_name()) { String fullprop=ps[0]+prop; set(fullprop,p_value); props[fullprop].overrided=true; } } } } return true; } bool GlobalConfig::_get(const StringName& p_name,Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (!props.has(p_name)) return false; r_ret=props[p_name].variant; return true; } struct _VCSort { String name; Variant::Type type; int order; int flags; bool operator<(const _VCSort& p_vcs) const{ return order==p_vcs.order?name<p_vcs.name:order< p_vcs.order; } }; void GlobalConfig::_get_property_list(List<PropertyInfo> *p_list) const { _THREAD_SAFE_METHOD_ Set<_VCSort> vclist; for(Map<StringName,VariantContainer>::Element *E=props.front();E;E=E->next()) { const VariantContainer *v=&E->get(); if (v->hide_from_editor) continue; _VCSort vc; vc.name=E->key(); vc.order=v->order; vc.type=v->variant.get_type(); if (vc.name.begins_with("input/") || vc.name.begins_with("import/") || vc.name.begins_with("export/") || vc.name.begins_with("/remap") || vc.name.begins_with("/locale") || vc.name.begins_with("/autoload")) vc.flags=PROPERTY_USAGE_STORAGE; else vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; vclist.insert(vc); } for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) { if (custom_prop_info.has(E->get().name)) { PropertyInfo pi=custom_prop_info[E->get().name]; pi.name=E->get().name; pi.usage=E->get().flags; p_list->push_back( pi ); } else p_list->push_back( PropertyInfo(E->get().type, E->get().name,PROPERTY_HINT_NONE,"",E->get().flags) ); } } bool GlobalConfig::_load_resource_pack(const String& p_pack) { if (PackedData::get_singleton()->is_disabled()) return false; bool ok = PackedData::get_singleton()->add_pack(p_pack)==OK; if (!ok) return false; //if data.pck is found, all directory access will be from here DirAccess::make_default<DirAccessPack>(DirAccess::ACCESS_RESOURCES); using_datapack=true; return true; } Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) { //an absolute mess of a function, must be cleaned up and reorganized somehow at some point //_load_settings(p_path+"/override.cfg"); if (p_main_pack!="") { bool ok = _load_resource_pack(p_main_pack); ERR_FAIL_COND_V(!ok,ERR_CANT_OPEN); if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { _load_settings("res://override.cfg"); } return OK; } if (OS::get_singleton()->get_executable_path()!="") { if (_load_resource_pack(OS::get_singleton()->get_executable_path())) { if (p_path!="") { resource_path=p_path; } else { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); resource_path=d->get_current_dir(); memdelete(d); } if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { _load_settings("res://override.cfg"); } return OK; } } if (FileAccessNetworkClient::get_singleton()) { if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { _load_settings("res://override.cfg"); } return OK; } if (OS::get_singleton()->get_resource_dir()!="") { //OS will call Globals->get_resource_path which will be empty if not overriden! //if the OS would rather use somewhere else, then it will not be empty. resource_path=OS::get_singleton()->get_resource_dir().replace("\\","/"); if (resource_path.length() && resource_path[ resource_path.length()-1]=='/') resource_path=resource_path.substr(0,resource_path.length()-1); // chop end print_line("has res dir: "+resource_path); if (!_load_resource_pack("res://data.pck")) _load_resource_pack("res://data.zip"); // make sure this is load from the resource path print_line("exists engine cfg? "+itos(FileAccess::exists("/engine.cfg"))); if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { print_line("loaded engine.cfg"); _load_settings("res://override.cfg"); } return OK; } DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (!d) { resource_path = p_path; } else { d->change_dir(p_path); String candidate = d->get_current_dir(); String current_dir = d->get_current_dir(); String exec_name = OS::get_singleton()->get_executable_path().get_file().basename(); bool found = false; bool first_time=true; while(true) { //try to load settings in ascending through dirs shape! //tries to open pack, but only first time if (first_time && (_load_resource_pack(current_dir+"/"+exec_name+".pck") || _load_resource_pack(current_dir+"/"+exec_name+".zip") )) { if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { _load_settings("res://override.cfg"); found=true; } break; } else if (first_time && (_load_resource_pack(current_dir+"/data.pck") || _load_resource_pack(current_dir+"/data.zip") )) { if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { _load_settings("res://override.cfg"); found=true; } break; } else if (_load_settings(current_dir+"/engine.cfg")==OK || _load_settings_binary(current_dir+"/engine.cfb")==OK) { _load_settings(current_dir+"/override.cfg"); candidate=current_dir; found=true; break; } d->change_dir(".."); if (d->get_current_dir()==current_dir) break; //not doing anything useful current_dir=d->get_current_dir(); first_time=false; } resource_path=candidate; resource_path = resource_path.replace("\\","/"); // windows path to unix path just in case memdelete(d); if (!found) return ERR_FILE_NOT_FOUND; }; if (resource_path.length() && resource_path[ resource_path.length()-1]=='/') resource_path=resource_path.substr(0,resource_path.length()-1); // chop end return OK; } bool GlobalConfig::has(String p_var) const { _THREAD_SAFE_METHOD_ return props.has(p_var); } void GlobalConfig::set_registering_order(bool p_enable) { registering_order=p_enable; } Error GlobalConfig::_load_settings_binary(const String p_path) { Error err; FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); if (err!=OK) { return err; } uint8_t hdr[4]; f->get_buffer(hdr,4); if (hdr[0]!='E'|| hdr[1]!='C' || hdr[2]!='F' || hdr[3]!='G') { memdelete(f); ERR_EXPLAIN("Corrupted header in binary engine.cfb (not ECFG)"); ERR_FAIL_V(ERR_FILE_CORRUPT;) } set_registering_order(false); uint32_t count=f->get_32(); for(uint32_t i=0;i<count;i++) { uint32_t slen=f->get_32(); CharString cs; cs.resize(slen+1); cs[slen]=0; f->get_buffer((uint8_t*)cs.ptr(),slen); String key; key.parse_utf8(cs.ptr()); uint32_t vlen=f->get_32(); Vector<uint8_t> d; d.resize(vlen); f->get_buffer(d.ptr(),vlen); Variant value; Error err = decode_variant(value,d.ptr(),d.size()); ERR_EXPLAIN("Error decoding property: "+key); ERR_CONTINUE(err!=OK); set(key,value); } set_registering_order(true); return OK; } Error GlobalConfig::_load_settings(const String p_path) { Error err; FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); if (!f) return ERR_CANT_OPEN; VariantParser::StreamFile stream; stream.f=f; String assign; Variant value; VariantParser::Tag next_tag; int lines=0; String error_text; String section; while(true) { assign=Variant(); next_tag.fields.clear(); next_tag.name=String(); err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); if (err==ERR_FILE_EOF) { memdelete(f); return OK; } else if (err!=OK) { ERR_PRINTS("GlobalConfig::load - "+p_path+":"+itos(lines)+" error: "+error_text); memdelete(f); return err; } if (assign!=String()) { set(section+"/"+assign,value); } else if (next_tag.name!=String()) { section=next_tag.name; } } memdelete(f); return OK; } int GlobalConfig::get_order(const String& p_name) const { ERR_FAIL_COND_V(!props.has(p_name),-1); return props[p_name].order; } void GlobalConfig::set_order(const String& p_name, int p_order){ ERR_FAIL_COND(!props.has(p_name)); props[p_name].order=p_order; } void GlobalConfig::clear(const String& p_name) { ERR_FAIL_COND(!props.has(p_name)); props.erase(p_name); } Error GlobalConfig::save() { return save_custom(get_resource_path()+"/engine.cfg"); } Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) { Error err; FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err); if (err!=OK) { ERR_EXPLAIN("Coudln't save engine.cfb at "+p_file); ERR_FAIL_COND_V(err,err) } uint8_t hdr[4]={'E','C','F','G'}; file->store_buffer(hdr,4); int count=0; for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) { for(List<String>::Element *F=E->get().front();F;F=F->next()) { count++; } } file->store_32(count); //store how many properties are saved for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) { for(List<String>::Element *F=E->get().front();F;F=F->next()) { String key = F->get(); if (E->key()!="") key=E->key()+"/"+key; Variant value; if (p_custom.has(key)) value=p_custom[key]; else value = get(key); file->store_32(key.length()); file->store_string(key); int len; Error err = encode_variant(value,NULL,len); if (err!=OK) memdelete(file); ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA ); Vector<uint8_t> buff; buff.resize(len); err = encode_variant(value,&buff[0],len); if (err!=OK) memdelete(file); ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA ); file->store_32(len); file->store_buffer(buff.ptr(),buff.size()); } } file->close(); memdelete(file); return OK; } Error GlobalConfig::_save_settings_text(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) { Error err; FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err); if (err) { ERR_EXPLAIN("Coudln't save engine.cfg - "+p_file); ERR_FAIL_COND_V(err,err) } for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) { if (E!=props.front()) file->store_string("\n"); if (E->key()!="") file->store_string("["+E->key()+"]\n\n"); for(List<String>::Element *F=E->get().front();F;F=F->next()) { String key = F->get(); if (E->key()!="") key=E->key()+"/"+key; Variant value; if (p_custom.has(key)) value=p_custom[key]; else value = get(key); String vstr; VariantWriter::write_to_string(value,vstr); file->store_string(F->get()+"="+vstr+"\n"); } } file->close(); memdelete(file); return OK; } Error GlobalConfig::_save_custom_bnd(const String &p_file) { // add other params as dictionary and array? return save_custom(p_file); }; Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,const Set<String>& p_ignore_masks) { ERR_FAIL_COND_V(p_path=="",ERR_INVALID_PARAMETER); Set<_VCSort> vclist; for(Map<StringName,VariantContainer>::Element *G=props.front();G;G=G->next()) { const VariantContainer *v=&G->get(); if (v->hide_from_editor) continue; if (p_custom.has(G->key())) continue; bool discard=false; for(const Set<String>::Element *E=p_ignore_masks.front();E;E=E->next()) { if ( String(G->key()).match(E->get())) { discard=true; break; } } if (discard) continue; _VCSort vc; vc.name=G->key();//*k; vc.order=v->order; vc.type=v->variant.get_type(); vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; if (v->variant==v->initial) continue; vclist.insert(vc); } for(const Map<String,Variant>::Element *E=p_custom.front();E;E=E->next()) { _VCSort vc; vc.name=E->key(); vc.order=0xFFFFFFF; vc.type=E->get().get_type(); vc.flags=PROPERTY_USAGE_STORAGE; vclist.insert(vc); } Map<String,List<String> > props; for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) { String category = E->get().name; String name = E->get().name; int div = category.find("/"); if (div<0) category=""; else { category=category.substr(0,div); name=name.substr(div+1,name.size()); } props[category].push_back(name); } if (p_path.ends_with(".cfg")) return _save_settings_text(p_path,props,p_custom); else if (p_path.ends_with(".cfb")) return _save_settings_binary(p_path,props,p_custom); else { ERR_EXPLAIN("Unknown config file format: "+p_path); ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); } return OK; #if 0 Error err = file->open(dst_file,FileAccess::WRITE); if (err) { memdelete(file); ERR_EXPLAIN("Coudln't save engine.cfg"); ERR_FAIL_COND_V(err,err) } for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) { if (E!=props.front()) file->store_string("\n"); if (E->key()!="") file->store_string("["+E->key()+"]\n\n"); for(List<String>::Element *F=E->get().front();F;F=F->next()) { String key = F->get(); if (E->key()!="") key=E->key()+"/"+key; Variant value; if (p_custom.has(key)) value=p_custom[key]; else value = get(key); file->store_string(F->get()+"="+_encode_variant(value)+"\n"); } } file->close(); memdelete(file); return OK; #endif } Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default) { if (GlobalConfig::get_singleton()->has(p_var)) { GlobalConfig::get_singleton()->set_initial_value(p_var,p_default); return GlobalConfig::get_singleton()->get(p_var); } GlobalConfig::get_singleton()->set(p_var,p_default); GlobalConfig::get_singleton()->set_initial_value(p_var,p_default); return p_default; } void GlobalConfig::add_singleton(const Singleton &p_singleton) { singletons.push_back(p_singleton); singleton_ptrs[p_singleton.name]=p_singleton.ptr; } Object* GlobalConfig::get_singleton_object(const String& p_name) const { const Map<StringName,Object*>::Element *E=singleton_ptrs.find(p_name); if (!E) return NULL; else return E->get(); }; bool GlobalConfig::has_singleton(const String& p_name) const { return get_singleton_object(p_name) != NULL; }; void GlobalConfig::get_singletons(List<Singleton> *p_singletons) { for(List<Singleton>::Element *E=singletons.front();E;E=E->next()) p_singletons->push_back(E->get()); } Vector<String> GlobalConfig::get_optimizer_presets() const { List<PropertyInfo> pi; GlobalConfig::get_singleton()->get_property_list(&pi); Vector<String> names; for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) { if (!E->get().name.begins_with("optimizer_presets/")) continue; names.push_back(E->get().name.get_slicec('/',1)); } names.sort(); return names; } void GlobalConfig::_add_property_info_bind(const Dictionary& p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); PropertyInfo pinfo; pinfo.name = p_info["name"]; ERR_FAIL_COND(!props.has(pinfo.name)); pinfo.type = Variant::Type(p_info["type"].operator int()); ERR_FAIL_INDEX(pinfo.type, Variant::VARIANT_MAX); if (p_info.has("hint")) pinfo.hint = PropertyHint(p_info["hint"].operator int()); if (p_info.has("hint_string")) pinfo.hint_string = p_info["hint_string"]; set_custom_property_info(pinfo.name, pinfo); } void GlobalConfig::set_custom_property_info(const String& p_prop,const PropertyInfo& p_info) { ERR_FAIL_COND(!props.has(p_prop)); custom_prop_info[p_prop]=p_info; custom_prop_info[p_prop].name=p_prop; } void GlobalConfig::set_disable_platform_override(bool p_disable) { disable_platform_override=p_disable; } bool GlobalConfig::is_using_datapack() const { return using_datapack; } bool GlobalConfig::property_can_revert(const String& p_name) { if (!props.has(p_name)) return false; return props[p_name].initial!=props[p_name].variant; } Variant GlobalConfig::property_get_revert(const String& p_name) { if (!props.has(p_name)) return Variant(); return props[p_name].initial; } void GlobalConfig::_bind_methods() { ClassDB::bind_method(_MD("has","name"),&GlobalConfig::has); ClassDB::bind_method(_MD("set_order","name","pos"),&GlobalConfig::set_order); ClassDB::bind_method(_MD("get_order","name"),&GlobalConfig::get_order); ClassDB::bind_method(_MD("set_initial_value","name","value"),&GlobalConfig::set_initial_value); ClassDB::bind_method(_MD("add_property_info", "hint"),&GlobalConfig::_add_property_info_bind); ClassDB::bind_method(_MD("clear","name"),&GlobalConfig::clear); ClassDB::bind_method(_MD("localize_path","path"),&GlobalConfig::localize_path); ClassDB::bind_method(_MD("globalize_path","path"),&GlobalConfig::globalize_path); ClassDB::bind_method(_MD("save"),&GlobalConfig::save); ClassDB::bind_method(_MD("has_singleton","name"),&GlobalConfig::has_singleton); ClassDB::bind_method(_MD("get_singleton","name"),&GlobalConfig::get_singleton_object); ClassDB::bind_method(_MD("load_resource_pack","pack"),&GlobalConfig::_load_resource_pack); ClassDB::bind_method(_MD("property_can_revert","name"),&GlobalConfig::property_can_revert); ClassDB::bind_method(_MD("property_get_revert","name"),&GlobalConfig::property_get_revert); ClassDB::bind_method(_MD("save_custom","file"),&GlobalConfig::_save_custom_bnd); } GlobalConfig::GlobalConfig() { singleton=this; last_order=0; disable_platform_override=false; registering_order=true; Array va; InputEvent key; key.type=InputEvent::KEY; InputEvent joyb; joyb.type=InputEvent::JOYPAD_BUTTON; GLOBAL_DEF("application/name","" ); GLOBAL_DEF("application/main_scene",""); custom_prop_info["application/main_scene"]=PropertyInfo(Variant::STRING,"application/main_scene",PROPERTY_HINT_FILE,"tscn,scn,xscn,xml,res"); GLOBAL_DEF("application/disable_stdout",false); GLOBAL_DEF("application/use_shared_user_dir",true); key.key.scancode=KEY_RETURN; va.push_back(key); key.key.scancode=KEY_ENTER; va.push_back(key); key.key.scancode=KEY_SPACE; va.push_back(key); joyb.joy_button.button_index=JOY_BUTTON_0; va.push_back(joyb); GLOBAL_DEF("input/ui_accept",va); input_presets.push_back("input/ui_accept"); va=Array(); key.key.scancode=KEY_SPACE; va.push_back(key); joyb.joy_button.button_index=JOY_BUTTON_3; va.push_back(joyb); GLOBAL_DEF("input/ui_select",va); input_presets.push_back("input/ui_select"); va=Array(); key.key.scancode=KEY_ESCAPE; va.push_back(key); joyb.joy_button.button_index=JOY_BUTTON_1; va.push_back(joyb); GLOBAL_DEF("input/ui_cancel",va); input_presets.push_back("input/ui_cancel"); va=Array(); key.key.scancode=KEY_TAB; va.push_back(key); GLOBAL_DEF("input/ui_focus_next",va); input_presets.push_back("input/ui_focus_next"); va=Array(); key.key.scancode=KEY_TAB; key.key.mod.shift=true; va.push_back(key); GLOBAL_DEF("input/ui_focus_prev",va); input_presets.push_back("input/ui_focus_prev"); key.key.mod.shift=false; va=Array(); key.key.scancode=KEY_LEFT; va.push_back(key); joyb.joy_button.button_index=JOY_DPAD_LEFT; va.push_back(joyb); GLOBAL_DEF("input/ui_left",va); input_presets.push_back("input/ui_left"); va=Array(); key.key.scancode=KEY_RIGHT; va.push_back(key); joyb.joy_button.button_index=JOY_DPAD_RIGHT; va.push_back(joyb); GLOBAL_DEF("input/ui_right",va); input_presets.push_back("input/ui_right"); va=Array(); key.key.scancode=KEY_UP; va.push_back(key); joyb.joy_button.button_index=JOY_DPAD_UP; va.push_back(joyb); GLOBAL_DEF("input/ui_up",va); input_presets.push_back("input/ui_up"); va=Array(); key.key.scancode=KEY_DOWN; va.push_back(key); joyb.joy_button.button_index=JOY_DPAD_DOWN; va.push_back(joyb); GLOBAL_DEF("input/ui_down",va); input_presets.push_back("input/ui_down"); va=Array(); key.key.scancode=KEY_PAGEUP; va.push_back(key); GLOBAL_DEF("input/ui_page_up",va); input_presets.push_back("input/ui_page_up"); va=Array(); key.key.scancode=KEY_PAGEDOWN; va.push_back(key); GLOBAL_DEF("input/ui_page_down",va); input_presets.push_back("input/ui_page_down"); // GLOBAL_DEF("display/handheld/orientation", "landscape"); custom_prop_info["display/handheld/orientation"]=PropertyInfo(Variant::STRING,"display/handheld/orientation",PROPERTY_HINT_ENUM,"landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor"); custom_prop_info["rendering/threads/thread_model"]=PropertyInfo(Variant::INT,"rendering/threads/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded"); custom_prop_info["physics/2d/thread_model"]=PropertyInfo(Variant::INT,"physics/2d/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded"); GLOBAL_DEF("debug/profiler/max_functions",16384); using_datapack=false; } GlobalConfig::~GlobalConfig() { singleton=NULL; }
24.863372
226
0.674071
[ "object", "shape", "vector" ]
28fca9383118f9652c708c3998eab4fa8681d3ab
16,012
cpp
C++
src/LSSS/Open_Protocol2.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
196
2018-05-25T11:41:56.000Z
2022-03-12T05:49:50.000Z
src/LSSS/Open_Protocol2.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
49
2018-07-17T15:49:41.000Z
2021-01-19T11:35:31.000Z
src/LSSS/Open_Protocol2.cpp
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
[ "BSD-2-Clause" ]
90
2018-05-25T11:41:42.000Z
2022-03-23T19:15:10.000Z
/* Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom. Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. All rights reserved */ #include <iomanip> #include <iostream> using namespace std; #include "Math/Matrix.h" #include "Open_Protocol2.h" #include "Tools/Crypto.h" #include "config.h" Open_Protocol2::Open_Protocol2() { sha256.resize(3); for (unsigned int i= 0; i < 3; i++) { SHA256_Init(&sha256[i]); // Counts the number opens in each connection, so we do a check every so often open_cnt[i]= 0; // This is a string of stuff which we will eventually hash hss[i]= ""; } } Open_Protocol2::~Open_Protocol2() { for (int i= 0; i < 3; i++) { if (open_cnt[i] > 0) { cerr << "Problem cleaning up Open_Protocol object.\n"; cerr << "Data is still hanging around for connection " << i << endl; abort(); } } } void Open_Protocol2::Open_Bit(word &dv, const aBit &v, Player &P) { vector<string> o(P.nplayers()); // No need to resize buff as we know it is big enough for one bit for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { buff.get_buffer()[0]= (uint8_t) v.get_value(); v.get_MAC(i).output(buff.get_buffer() + 1); o[i]= string((char *) buff.get_buffer(), 1 + gf2n::size()); } } P.Send_Distinct_And_Receive(o, 2); dv= v.get_value(); gf2n M; for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { char c= o[i].c_str()[0]; M.input(o[i], 1); dv= dv ^ ((unsigned int) c); if (c == 1) { M.add(aBit::get_Delta()); } if (M != v.get_Key(i)) { throw OT_error(); } } } } void Open_Protocol2::Open_Bit(word &dv, const Share2 &v, Player &P, int connection, int num) { if (num != 8 && num != 1) { throw not_implemented(); } unsigned long max_len= num * Share2::SD.M.row_dim(); buff.resize(max_len); uint8_t v8; for (unsigned int p= 0; p < P.nplayers(); p++) { if (Share2::SD.OpenC[P.whoami()][p] == 1 && p != P.whoami()) { unsigned int length= 0; for (unsigned int k= 0; k < v.a.size(); k++) { if (Share2::SD.RCt[P.whoami()][p][k] == 1) { if (num == 8) { memcpy(buff.get_buffer() + length, &v.a[k], sizeof(word)); length+= sizeof(word); } else { v8= (uint8_t) v.a[k]; memcpy(buff.get_buffer() + length, &v8, 1); length+= 1; } } } P.send_to_player(p, buff.get_buffer(), length, connection); } } unsigned int p= P.whoami(), len; const uint8_t *P_sbuff= 0; vector<word> vs(Share2::SD.ReconS[p].size(), -1); int c= 0; for (unsigned int j= 0; j < P.nplayers(); j++) { if (Share2::SD.OpenC[j][p] == 1 && j != p) { P_sbuff= P.receive_from_player(j, len, connection, false); } unsigned int length= 0; for (unsigned int k= 0; k < Share2::SD.M.shares_per_player(j); k++) { if (j == p) { vs[c]= v.a[k]; c++; } else if (Share2::SD.RCt[j][p][k] == 1) { if (num == 8) { vs[c]= *(word *) (P_sbuff + length); length+= sizeof(word); } else { vs[c]= *(char *) (P_sbuff + length); length+= 1; } c++; } } } dv= dot_product(vs, Share2::SD.ReconS[p]); vector<word> ssv(Share2::SD.ReconSS[p].size()); Mul(ssv, Share2::SD.ReconSS[p], vs); // Prepare to hash into the state unsigned int length= 0; if (num == 8) { for (unsigned int j= 0; j < ssv.size(); j++) { memcpy(buff.get_buffer() + length, &ssv[j], sizeof(word)); length+= sizeof(word); } } else { for (unsigned int j= 0; j < ssv.size(); j++) { v8= (uint8_t) ssv[j]; memcpy(buff.get_buffer() + length, &v8, 1); length+= 1; } } hss[connection]+= string((char *) buff.get_buffer(), length); // Hash into the state if (hss[connection].size() > 10000) { SHA256_Update(&sha256[connection], hss[connection].c_str(), hss[connection].size()); hss[connection]= ""; } open_cnt[connection]+= 1; if (open_cnt[connection] > open_check_gap) { RunOpenCheck(P, "", connection); } } void Open_Protocol2::Open_BitVector(word &dv, const aBitVector &v, Player &P) { vector<word> vec(sreg_bitl); Open_Bits(vec, v.internal_rep(), P); dv= 0; for (int i= sreg_bitl - 1; i >= 0; i--) { dv<<= 1; dv+= vec[i]; } } void Open_Protocol2::Open_To_All(vector<word> &values, const vector<Share2> &S, Player &P, int connection) { values.resize(S.size()); // Get rid of tiresome segfault errors unsigned long max_len= S.size() * sizeof(word) * Share2::SD.M.row_dim(); buff.resize(max_len); for (unsigned int p= 0; p < P.nplayers(); p++) { if (Share2::SD.OpenC[P.whoami()][p] == 1 && p != P.whoami()) { unsigned int length= 0; for (unsigned int k= 0; k < S[0].a.size(); k++) { for (unsigned int i= 0; i < S.size(); i++) { if (Share2::SD.RCt[P.whoami()][p][k] == 1) { memcpy(buff.get_buffer() + length, &S[i].a[k], sizeof(word)); length+= sizeof(word); } } } P.send_to_player(p, buff.get_buffer(), length, connection); } } unsigned int p= P.whoami(), len; const uint8_t *P_sbuff= 0; vector<vector<word>> vs(Share2::SD.ReconS[p].size(), vector<word>(S.size())); int c= 0; for (unsigned int j= 0; j < P.nplayers(); j++) { if (Share2::SD.OpenC[j][p] == 1 && j != p) { P_sbuff= P.receive_from_player(j, len, connection); } unsigned int length= 0; for (unsigned int k= 0; k < Share2::SD.M.shares_per_player(j); k++) { if (j == p) { for (unsigned int i= 0; i < S.size(); i++) { vs[c][i]= S[i].a[k]; } c++; } else if (Share2::SD.RCt[j][p][k] == 1) { for (unsigned int i= 0; i < S.size(); i++) { vs[c][i]= *(word *) (P_sbuff + length); length+= sizeof(word); } c++; } } } dot_product(values, Share2::SD.ReconS[p], vs); vector<vector<word>> ssv(Share2::SD.ReconSS[p].size(), vector<word>(vs[0].size())); Mul(ssv, Share2::SD.ReconSS[p], vs); // Prepare to hash into the state unsigned int length= 0; for (unsigned int i= 0; i < S.size(); i++) { for (unsigned int j= 0; j < ssv.size(); j++) { memcpy(buff.get_buffer() + length, &ssv[j][i], sizeof(word)); length+= sizeof(word); } } hss[connection]+= string((char *) buff.get_buffer(), length); // Hash into the state if (hss[connection].size() > 10000) { SHA256_Update(&sha256[connection], hss[connection].c_str(), hss[connection].size()); hss[connection]= ""; } open_cnt[connection]+= values.size(); if (open_cnt[connection] > open_check_gap) { RunOpenCheck(P, "", connection); } } /* We run it on the connection c as other connection might have * some opening still to do */ void Open_Protocol2::RunOpenCheck(Player &P, const string &aux, int connection, bool verbose) { // Do a final hash if stuff left over if (hss[connection].size() > 0) { SHA256_Update(&sha256[connection], hss[connection].c_str(), hss[connection].size()); hss[connection]= ""; } unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_Final(hash, &sha256[connection]); string ss((char *) hash, SHA256_DIGEST_LENGTH); if (verbose) { printf("Open Check: Sending : %d : ", P.whoami()); for (unsigned int i= 0; i < SHA256_DIGEST_LENGTH; i++) { printf("%02x", (uint8_t) ss.c_str()[i]); } printf("\n"); printf("%lu %d\n", ss.size(), SHA256_DIGEST_LENGTH); } P.send_all(ss, connection, verbose); for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { string is; P.receive_from_player(i, is, connection, verbose); if (verbose) { printf("Open Check: Received : %d : ", i); for (unsigned int i= 0; i < SHA256_DIGEST_LENGTH; i++) { printf("%02x", (uint8_t) is.c_str()[i]); } printf("\n"); printf("%lu %d\n", is.size(), SHA256_DIGEST_LENGTH); } if (is != ss) { throw hash_fail(); } } } SHA256_Init(&sha256[connection]); // Now deal with the auxillary string if (aux.size() != 0) { if (verbose) { printf("Auxillary Check: Sending : %d : ", P.whoami()); for (unsigned int i= 0; i < aux.size(); i++) { printf("%02x", (uint8_t) aux.c_str()[i]); } printf("\n"); } P.send_all(aux, connection, verbose); for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { string is; P.receive_from_player(i, is, connection, verbose); if (verbose) { printf("Auxillary Check: Received : %d : ", i); for (unsigned int i= 0; i < is.size(); i++) { printf("%02x", (uint8_t) is.c_str()[i]); } printf("\n"); } if (is != aux) { throw inconsistent_inputs(); } } } } open_cnt[connection]= 0; } void Open_Protocol2::Open_Bits_To(vector<word> &values, unsigned int j, const vector<aBit> &v, Player &P) { unsigned long max_len= v.size() * (1 + gf2n::size()); buff.resize(max_len); if (j != P.whoami()) { unsigned int pos= 0; for (unsigned int t= 0; t < v.size(); t++) { buff.get_buffer()[pos]= (uint8_t) v[t].get_value(); pos++; pos+= v[t].get_MAC(j).output(buff.get_buffer() + pos); } P.send_to_player(j, buff.get_buffer(), pos, 2); } else { values.resize(v.size()); for (unsigned int t= 0; t < v.size(); t++) { values[t]= v[t].get_value(); } gf2n M; for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { string ss; unsigned int len; const uint8_t *P_buff= P.receive_from_player(i, len, 2); unsigned int pos= 0; for (unsigned int t= 0; t < v.size(); t++) { uint8_t c= P_buff[pos]; pos++; pos+= M.input(P_buff + pos); values[t]= values[t] ^ ((unsigned int) c); if (c == 1) { M.add(aBit::get_Delta()); } if (M != v[t].get_Key(i)) { throw OT_error(); } } } } } } void Open_Protocol2::Open_Bits_To(vector<word> &values, unsigned int j, const vector<Share2> &v, Player &P) { unsigned long max_len= v.size() * Share2::SD.M.row_dim() * sizeof(word); buff.resize(max_len); unsigned int p= P.whoami(); if (j != p) { unsigned int length= 0; for (unsigned int k= 0; k < Share2::SD.M.shares_per_player(P.whoami()); k++) { for (unsigned int i= 0; i < v.size(); i++) { memcpy(buff.get_buffer() + length, &v[i].a[k], sizeof(word)); length+= sizeof(word); } } P.send_to_player(j, buff.get_buffer(), length, 2); } else { const uint8_t *P_sbuff= 0; unsigned int length; vector<vector<word>> shares(Share2::SD.Parity[0].size(), vector<word>(v.size())); int c= 0; for (unsigned int j= 0; j < P.nplayers(); j++) { if (j != p) { P_sbuff= P.receive_from_player(j, length, 2); } length= 0; for (unsigned int k= 0; k < Share2::SD.M.shares_per_player(j); k++) { if (j == p) { for (unsigned int i= 0; i < v.size(); i++) { shares[c][i]= v[i].a[k]; } } else { for (unsigned int i= 0; i < v.size(); i++) { memcpy(&shares[c][i], P_sbuff + length, sizeof(word)); length+= sizeof(word); } } c++; } } // We now have the matrix of shares. So check parity and reconstruct the secret values.resize(v.size()); vector<vector<word>> check(Share2::SD.Parity.size(), vector<word>(v.size())); Mul(check, Share2::SD.Parity, shares); for (unsigned int i= 0; i < v.size(); i++) { for (unsigned int j= Share2::SD.M.col_dim(); j < check.size(); j++) { if (check[j][i] != 0) { throw receiving_error(); } } values[i]= 0; for (unsigned int j= 0; j < Share2::SD.M.col_dim(); j++) { values[i]^= check[j][i]; } } } } void Open_Protocol2::Open_Bits(vector<word> &dv, const vector<aBit> &v, Player &P) { dv.resize(v.size()); unsigned long max_len= (1 + gf2n::size()) * v.size(); buff.resize(max_len); vector<string> o(P.nplayers()); for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { unsigned int pos= 0; for (unsigned int t= 0; t < v.size(); t++) { buff.get_buffer()[pos]= (uint8_t) v[t].get_value(); pos++; pos+= v[t].get_MAC(i).output(buff.get_buffer() + pos); } o[i]= string((char *) buff.get_buffer(), pos); } } P.Send_Distinct_And_Receive(o, 2); for (unsigned int t= 0; t < v.size(); t++) { dv[t]= v[t].get_value(); } gf2n M; for (unsigned int i= 0; i < P.nplayers(); i++) { if (i != P.whoami()) { unsigned int pos= 0; for (unsigned int t= 0; t < v.size(); t++) { char c= o[i].c_str()[pos]; pos++; pos+= M.input(o[i], pos); dv[t]= dv[t] ^ ((word) c); if (c == 1) { M.add(aBit::get_Delta()); } if (M != v[t].get_Key(i)) { throw OT_error(); } } } } }
27.993007
110
0.451661
[ "object", "vector" ]
28ff1dba68d93ae887e8dbbeb58b613299fd6bf9
9,288
cpp
C++
src/bgwidgets.cpp
BastiaanOlij/omnis.xcomp.bgwidgets
4d512b45195b82c9ee3d31835684daa70073279b
[ "MIT" ]
1
2022-03-14T10:51:14.000Z
2022-03-14T10:51:14.000Z
src/bgwidgets.cpp
BastiaanOlij/omnis.xcomp.bgwidgets
4d512b45195b82c9ee3d31835684daa70073279b
[ "MIT" ]
null
null
null
src/bgwidgets.cpp
BastiaanOlij/omnis.xcomp.bgwidgets
4d512b45195b82c9ee3d31835684daa70073279b
[ "MIT" ]
1
2018-09-13T05:06:48.000Z
2018-09-13T05:06:48.000Z
#include "bgwidgets.h" #include "RadiusRect.h" #include "donut.h" #include "polygon.h" // Your generic object constructor bgwidget::bgwidget(HWND pHwnd, bool pUseHwnd) { mHwnd = pHwnd; mUseHwnd = pUseHwnd; }; // Generic destruction bgwidget::~bgwidget() { // just a placeholder }; void bgwidget::invalidate() { if (mUseHwnd) { WNDinvalidateRect(mHwnd, NULL); } else { ECOinvalBackObj(); }; }; // can we assign this property? qbool bgwidget::propCanAssign(qlong pPropId) { // just a placeholder return 0L; }; // set a property value qbool bgwidget::setProperty(qlong pPropId, EXTfldval * pSetVal) { // just a placeholder return 0L; }; // get a property value qbool bgwidget::getProperty(qlong pPropId, EXTfldval * pRetVal) { // just a placeholder return 0L; }; void bgwidget::UpdateProperty(qlong pPropId) { if (mUseHwnd) { ECOupdatePropInsp(mHwnd, pPropId); }; }; // You need to paint your control void bgwidget::paint(HDC hdc, qrect* pArea) { // just a placeholder }; // Component library entry point (name as declared in resource 31000 ) extern "C" LRESULT OMNISWNDPROC bgwidgetsWndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam, EXTCompInfo* eci) { // Initialize callback tables - THIS MUST BE DONE ECOsetupCallbacks(hwnd, eci); switch (Msg) { // WM_ERASEBKGND - we don't erase the background for background objects case WM_ERASEBKGND: { return 1L; }; break; // ECM_BOBJ_EXERASE - is sent to our component when Omnis wants to know if our background objects background needs to be excluded from clearing case ECM_BOBJ_EXERASE: return 1L; // ECM_PRINT - background objects get this instead of the WM_PAINT as they are painted directly on the main window case ECM_PRINT: { // First find the object in the libraries chain of objects WNDpaintStruct* paintStruct = (WNDpaintStruct*)lParam; bgwidget* object = (bgwidget*)ECOfindObject(eci, hwnd); // and if its good, call the paint function if (object != NULL) { object->paint(paintStruct->hdc, &paintStruct->rcPaint); return qtrue; }; }; break; // ECM_GETVERSION ask for version info case ECM_GETVERSION: { qshort major = OMNISSDK; qshort minor = 4; return ECOreturnVersion(major, minor); } break; // ECM_OBJCONSTRUCT - this is a message to create a new object. case ECM_OBJCONSTRUCT: { // Allocate a new object, for now always assume its radiusrect bgwidget* object = NULL; switch (eci->mCompId) { case RADIUSRECT_ID: { object = new radiusrect(hwnd, !(wParam & ECM_WFLAG_NOHWND)); // printf("Created radiusrect object %p\n",object); }; break; case DONUT_ID: { object = new donut(hwnd, !(wParam & ECM_WFLAG_NOHWND)); // printf("Created donut object %p\n",object); }; break; case POLYGON_ID: { object = new polygon(hwnd, !(wParam & ECM_WFLAG_NOHWND)); // printf("Created polygon object %p\n",object); }; break; default: break; }; if (object != NULL) { // and insert into a chain of objects. The OMNIS library will maintain this chain ECOinsertObject( eci, hwnd, (void*)object ); return qtrue; }; }; break; // ECM_OBJDESTRUCT - this is a message to inform you to delete the object case ECM_OBJDESTRUCT: { // First find the object in the libraries chain of objects, // this call if ok also removes the object from the chain. bgwidget* object = (bgwidget*)ECOremoveObject( eci, hwnd ); if ( NULL!=object ) { // printf("Destruct object %p\n",object); // Now you can delete the object you previous allocated // Note: The hwnd passed on ECM_OBJCONSTRUCT should not be deleted, as // it was created and will be destroyed by OMNIS delete object; // note, our destructor is declared virtual so this will call the correct destructor }; return qtrue; }; break; // ECM_CONNECT - this message is sent once per OMNIS session and should not be confused // with ECM_OBJCONSTRUCT which is sent once per object. ECM_CONNECT can be used if load other libraries // once or other general global actions that need to be done only once. // // For most components this can be removed - see other BLYTH component examples case ECM_CONNECT: { return EXT_FLAG_LOADED | EXT_FLAG_BCOMPONENTS | EXT_FLAG_ALWAYS_USABLE | EXT_FLAG_REMAINLOADED; // Return external flags }; break; // ECM_DISCONNECT - this message is sent only once when the OMNIS session is ending and should not be confused // with ECM_OBJDESTRUCT which is sent once per object. ECM_DISCONNECT can be used to free other libraries // loaded on ECM_CONNECT or other general global actions that need to be done only once. // // For most components this can be removed - see other BLYTH component examples case ECM_DISCONNECT: { return qtrue; }; break; // ECM_GETCOMPLIBINFO - this is sent by OMNIS to find out the name of the library, and // the number of components this library supports case ECM_GETCOMPLIBINFO: { return ECOreturnCompInfo( gInstLib, eci, LIB_RES_NAME, OBJECT_COUNT ); }; break; // ECM_GETCOMPICON - this is sent by OMNIS to get an icon for the OMNIS component store and // external component browser. You need to always supply an icon in your resource file. case ECM_GETCOMPICON: { // OMNIS will call you once per component for an icon. // GENERIC_ICON is defined in the header and included in the resource file switch (eci->mCompId) { case RADIUSRECT_ID: { return ECOreturnIcon(gInstLib, eci, RADIUSRECT_ICON); }; break; case DONUT_ID: { return ECOreturnIcon(gInstLib, eci, DONUT_ICON); }; break; case POLYGON_ID: { return ECOreturnIcon(gInstLib, eci, POLYGON_ICON); }; break; }; return qfalse; }; break; // ECM_GETCOMPID - this message is sent by OMNIS to get information about each component in this library // wParam is a number from 1 to the number of components return on the ECM_GETCOMPLIBINFO message. // // For each call you should return the internal object ID and the type of object it is. // The object id will be used for other calls such as ECM_GETCOMPICON // // The object type is for example : cObjType_Basic - a basic window object or // cRepObjType_Basic - a basic report object. // There are others - see BLYTH examples and headers case ECM_GETCOMPID: { switch (wParam) { case 1: { return ECOreturnCompID( gInstLib, eci, RADIUSRECT_ID, cObjType_Basic ); }; break; case 2: { return ECOreturnCompID( gInstLib, eci, DONUT_ID, cObjType_Basic ); }; break; case 3: { return ECOreturnCompID( gInstLib, eci, POLYGON_ID, cObjType_Basic ); }; break; default: break; }; return 0L; }; break; //////////////////////////////////////////////////////////////////////// // stuff for properties case ECM_GETPROPNAME: { switch (eci->mCompId) { case RADIUSRECT_ID: { return ECOreturnProperties(gInstLib, eci, RadiusRectProperties, 4 + rrectlast - 1); // add our 4 build in properties to our count }; break; case DONUT_ID: { return ECOreturnProperties(gInstLib, eci, DonutProperties, donutLast - 1); }; break; case POLYGON_ID: { return ECOreturnProperties(gInstLib, eci, PolygonProperties, 4 + polygonLast - 1); // add our 4 build in properties to our count }; break; default: break; }; }; break; case ECM_PROPERTYCANASSIGN: { bgwidget* object = (bgwidget*)ECOfindObject(eci, hwnd); if (object != NULL) { return object->propCanAssign(ECOgetId(eci)); }; }; break; case ECM_SETPROPERTY: { bgwidget* object = (bgwidget*)ECOfindObject(eci, hwnd); if (object != NULL) { EXTParamInfo* param = ECOfindParamNum( eci, 1 ); if ( param ) { EXTfldval fval( (qfldval)param->mData ); qbool result = object->setProperty(ECOgetId(eci), &fval); if (result == 1L) { return 1L; }; }; }; }; break; case ECM_GETPROPERTY: { bgwidget* object = (bgwidget*)ECOfindObject(eci, hwnd); if (object != NULL) { EXTfldval fval; qbool result = object->getProperty(ECOgetId(eci), &fval); if (result == 1L) { ECOaddParam(eci,&fval); return 1L; }; }; }; break; case ECM_ISUNICODE: { #ifdef isunicode return qtrue; #else return qfalse; #endif }; break; }; // As a final result this must ALWAYS be called. It handles all other messages that this component // decides to ignore. return WNDdefWindowProc(hwnd,Msg,wParam,lParam,eci); };
34.527881
149
0.629199
[ "object" ]
e9004afc9c15eb446b6be3c4b9b81c23a3897df9
8,040
hpp
C++
src/chunk.hpp
anima-libera/qwy2
4875caf8035c5fb60e12eaba787d29017ffa0ed8
[ "Apache-2.0" ]
null
null
null
src/chunk.hpp
anima-libera/qwy2
4875caf8035c5fb60e12eaba787d29017ffa0ed8
[ "Apache-2.0" ]
null
null
null
src/chunk.hpp
anima-libera/qwy2
4875caf8035c5fb60e12eaba787d29017ffa0ed8
[ "Apache-2.0" ]
null
null
null
#ifndef QWY2_HEADER_CHUNK_ #define QWY2_HEADER_CHUNK_ #include "coords.hpp" #include "mesh.hpp" #include "shaders/classic/classic.hpp" #include <glm/vec3.hpp> #include <vector> #include <array> #include <unordered_map> #include <optional> #include <variant> #include <future> #include <tuple> namespace qwy2 { /* The length of the edges of the chunks, in blocks. * It must be odd, and should be at least 15 or something. */ extern unsigned int g_chunk_side; /* Returns the coords of the block at the center of the chunk given by chunk_coords. */ BlockCoords chunk_center_coords(ChunkCoords chunk_coords); /* Returns the coords of the block at the negativeward corner of the given chunk. */ BlockCoords chunk_most_negativeward_block_coords(ChunkCoords chunk_coords); /* Returns the coords of the block at the positiveward corner of the given chunk. */ BlockCoords chunk_most_positiveward_block_coords(ChunkCoords chunk_coords); /* Returns the block rect that contains exactly the blocks of the chunk given by chunk_coords. */ BlockRect chunk_rect(ChunkCoords chunk_coords); /* Returns the chunk-level coords of the chunk that contains the block at the given coords. */ ChunkCoords containing_chunk_coords(BlockCoords coords); /* Returns the chunk-level coords of the chunk that contains the point at the given coords. */ ChunkCoords containing_chunk_coords(glm::vec3 coords); /* Returns the chunk rect of all the chunks that intersect with the given block rect. */ ChunkRect containing_chunk_rect(BlockRect block_rect); /* Grid of values, one value per block, for one chunk. * As this is mostly a pointer to the data, passing it by value does not copy the data. */ template<typename FieldValueType> class ChunkField { public: using ValueType = FieldValueType; public: ChunkCoords chunk_coords; private: ValueType* data; public: ChunkField(); ChunkField(ChunkCoords chunk_coords); ~ChunkField(); ValueType& operator[](BlockCoords coords); ValueType const& operator[](BlockCoords coords) const; }; /* The PTG field (Plain Terrain Generation) * is the data generated by the first step of terrain generation. */ using PtgFieldValue = int; using ChunkPtgField = ChunkField<PtgFieldValue>; /* The PTT field (Plain Terrain Typing) * is the data generated by the second step of terrain generation. */ using BlockTypeId = unsigned int; using PttFieldValue = BlockTypeId; using ChunkPttField = ChunkField<PttFieldValue>; class Block { public: BlockTypeId type_id; public: bool is_air() const; }; /* The B field is the actual grid of blocks contained by the chunk. */ using BFieldValue = Block; using ChunkBField = ChunkField<BFieldValue>; /* Holds one type of field for 3x3x3 cube of chunks. * It represents the neighborhood of the chunk at the center * and allows access to values as if it were a bigger kind of chunk. */ template<typename ChunkFieldType> class ChunkNeighborhood { public: using FieldType = ChunkFieldType; using ValueType = typename FieldType::ValueType; private: std::array<FieldType, 3*3*3> field_table; public: ChunkNeighborhood(); ValueType& operator[](BlockCoords coords); ValueType const& operator[](BlockCoords coords) const; friend class ChunkGrid; }; using ChunkMeshData = std::vector<VertexDataClassic>; class Nature; /* Generates the PTG field of the chunk at the given chunk-level coords. * Can be called in isolation, given that the nature is not modified before it returns. */ ChunkPtgField generate_chunk_ptg_field( ChunkCoords chunk_coords, Nature const& nature); /* Generates the PTT field of the chunk at the given chunk-level coords, * using the PTG field of the nearby chunks. * Can be called in isolation, given that the nature is not modified before it returns. */ ChunkPttField generate_chunk_ptt_field( ChunkCoords chunk_coords, ChunkNeighborhood<ChunkPtgField> const chunk_neighborhood_ptg_field, Nature const& nature); /* Generates the B field of the chunk at the given chunk-level coords, * using the PTT field of the nearby chunks. * Can be called in isolation, given that the nature is not modified before it returns. */ ChunkBField generate_chunk_b_field( ChunkCoords chunk_coords, ChunkNeighborhood<ChunkPttField> const chunk_neighborhood_ptt_field, Nature const& nature); /* Generates the mesh data of the chunk at the given chunk-level coords, * using the B field of the nearby chunks. * Can be called in isolation, given that the nature is not modified before it returns. */ ChunkMeshData* generate_chunk_complete_mesh( ChunkCoords chunk_coords, ChunkNeighborhood<ChunkBField> const chunk_neighborhood_b_field, Nature const& nature); template <typename ComponentType> using ChunkComponentGrid = std::unordered_map<ChunkCoords, ComponentType, ChunkCoords::Hash>; class ChunkGrid { private: public: ChunkComponentGrid<ChunkPtgField> ptg_field; ChunkComponentGrid<ChunkPttField> ptt_field; ChunkComponentGrid<ChunkBField> b_field; ChunkComponentGrid<Mesh<VertexDataClassic>> mesh; public: bool has_ptg_field(ChunkCoords chunk_coords) const; bool has_ptt_field(ChunkCoords chunk_coords) const; bool has_b_field(ChunkCoords chunk_coords) const; bool has_complete_mesh(ChunkCoords chunk_coords) const; bool has_ptg_field_neighborhood(ChunkCoords center_chunk_coords) const; bool has_ptt_field_neighborhood(ChunkCoords center_chunk_coords) const; bool has_b_field_neighborhood(ChunkCoords center_chunk_coords) const; ChunkNeighborhood<ChunkPtgField> const get_ptg_field_neighborhood(ChunkCoords center_chunk_coords) const; ChunkNeighborhood<ChunkPttField> const get_ptt_field_neighborhood(ChunkCoords center_chunk_coords) const; ChunkNeighborhood<ChunkBField> const get_b_field_neighborhood(ChunkCoords center_chunk_coords) const; bool block_is_air_or_unloaded(BlockCoords coords) const; friend class ChunkGenerationManager; }; using SomeChunkData = std::variant<ChunkPtgField, ChunkPttField, ChunkBField, ChunkMeshData*>; enum class ChunkGeneratingStep { PTG_FIELD, PTT_FIELD, B_FIELD, MESH, }; class ChunkGeneratingData { public: ChunkCoords chunk_coords; ChunkGeneratingStep step; std::future<SomeChunkData> future; }; class ThreadPool; /* An instance of this class should get to manage the process of generating chunks. */ class ChunkGenerationManager { public: /* The thread pool to which to give generation tasks. Not owend. */ ThreadPool* thread_pool; /* The grid of chunks in which to generate chunks. Not owend. */ ChunkGrid* chunk_grid; /* The block-level coords that should be at the center of the generated zone. */ glm::vec3 generation_center; /* The radius (in blocks) of the generated zone. */ float generation_radius; bool generation_enabled; /* The data that are undergoing generation (possibly in an other thread). */ std::vector<std::optional<ChunkGeneratingData>> generating_data_vector; public: ChunkGenerationManager(); /* Should be called at every game loop iteration. */ void manage(Nature const& nature); private: /* Does the given chunk needs to have the given generation step to be started ? * Returning false means that the given step is already done or on its way. */ bool needs_generation_step(ChunkCoords chunk_coords, ChunkGeneratingStep step) const; /* Some generation steps require other generation steps to be completed before. * This function takes a generation step A that we would like to be able to do at some point, * and returns a generation step B that can be done now and is required to get to A. * If the given generation step A can be done now, then it is returned. * The given generation step A should not be already done or on its way. * It can return an empty optional due to some last required step to already be on its way, * thus making waiting the only thing we can do in regards to the given step A. */ std::optional<std::pair<ChunkCoords, ChunkGeneratingStep>> required_generation_step( ChunkCoords chunk_coords, ChunkGeneratingStep step) const; }; } /* qwy2 */ #endif /* QWY2_HEADER_CHUNK_ */
32.816327
97
0.786194
[ "mesh", "vector" ]
e90487065992552220a0bb61b854864f2adf471c
11,547
cpp
C++
externals/wasm-compiler/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
[ "MIT" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
squirrel-explorer/eagleeye-ios
9569e1d3cf2759490557337dd940e88907517052
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
squirrel-explorer/eagleeye-ios
9569e1d3cf2759490557337dd940e88907517052
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===-- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // \file // This file implements a TargetTransformInfo analysis pass specific to the // AMDGPU target machine. It uses the target's detailed information to provide // more precise answers to certain TTI queries, while letting the target // independent and default TTI implementations handle the rest. // //===----------------------------------------------------------------------===// #include "AMDGPUTargetTransformInfo.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/CodeGen/BasicTTIImpl.h" #include "llvm/IR/Module.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/Debug.h" #include "llvm/Target/CostTable.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; #define DEBUG_TYPE "AMDGPUtti" void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) { UP.Threshold = 300; // Twice the default. UP.MaxCount = UINT_MAX; UP.Partial = true; // TODO: Do we want runtime unrolling? for (const BasicBlock *BB : L->getBlocks()) { const DataLayout &DL = BB->getModule()->getDataLayout(); for (const Instruction &I : *BB) { const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); if (!GEP || GEP->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) continue; const Value *Ptr = GEP->getPointerOperand(); const AllocaInst *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL)); if (Alloca) { // We want to do whatever we can to limit the number of alloca // instructions that make it through to the code generator. allocas // require us to use indirect addressing, which is slow and prone to // compiler bugs. If this loop does an address calculation on an // alloca ptr, then we want to use a higher than normal loop unroll // threshold. This will give SROA a better chance to eliminate these // allocas. // // Don't use the maximum allowed value here as it will make some // programs way too big. UP.Threshold = 800; } } } } unsigned AMDGPUTTIImpl::getNumberOfRegisters(bool Vec) { if (Vec) return 0; // Number of VGPRs on SI. if (ST->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) return 256; return 4 * 128; // XXX - 4 channels. Should these count as vector instead? } unsigned AMDGPUTTIImpl::getRegisterBitWidth(bool Vector) { return Vector ? 0 : 32; } unsigned AMDGPUTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { switch (AddrSpace) { case AMDGPUAS::GLOBAL_ADDRESS: case AMDGPUAS::CONSTANT_ADDRESS: case AMDGPUAS::FLAT_ADDRESS: return 128; case AMDGPUAS::LOCAL_ADDRESS: case AMDGPUAS::REGION_ADDRESS: return 64; case AMDGPUAS::PRIVATE_ADDRESS: return 8 * ST->getMaxPrivateElementSize(); default: if (ST->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS && (AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) return 128; llvm_unreachable("unhandled address space"); } } unsigned AMDGPUTTIImpl::getMaxInterleaveFactor(unsigned VF) { // Semi-arbitrary large amount. return 64; } int AMDGPUTTIImpl::getArithmeticInstrCost( unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args ) { EVT OrigTy = TLI->getValueType(DL, Ty); if (!OrigTy.isSimple()) { return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo); } // Legalize the type. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); int ISD = TLI->InstructionOpcodeToISD(Opcode); // Because we don't have any legal vector operations, but the legal types, we // need to account for split vectors. unsigned NElts = LT.second.isVector() ? LT.second.getVectorNumElements() : 1; MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; switch (ISD) { case ISD::SHL: case ISD::SRL: case ISD::SRA: { if (SLT == MVT::i64) return get64BitInstrCost() * LT.first * NElts; // i32 return getFullRateInstrCost() * LT.first * NElts; } case ISD::ADD: case ISD::SUB: case ISD::AND: case ISD::OR: case ISD::XOR: { if (SLT == MVT::i64){ // and, or and xor are typically split into 2 VALU instructions. return 2 * getFullRateInstrCost() * LT.first * NElts; } return LT.first * NElts * getFullRateInstrCost(); } case ISD::MUL: { const int QuarterRateCost = getQuarterRateInstrCost(); if (SLT == MVT::i64) { const int FullRateCost = getFullRateInstrCost(); return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; } // i32 return QuarterRateCost * NElts * LT.first; } case ISD::FADD: case ISD::FSUB: case ISD::FMUL: if (SLT == MVT::f64) return LT.first * NElts * get64BitInstrCost(); if (SLT == MVT::f32 || SLT == MVT::f16) return LT.first * NElts * getFullRateInstrCost(); break; case ISD::FDIV: case ISD::FREM: // FIXME: frem should be handled separately. The fdiv in it is most of it, // but the current lowering is also not entirely correct. if (SLT == MVT::f64) { int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost(); // Add cost of workaround. if (ST->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) Cost += 3 * getFullRateInstrCost(); return LT.first * Cost * NElts; } // Assuming no fp32 denormals lowering. if (SLT == MVT::f32 || SLT == MVT::f16) { assert(!ST->hasFP32Denormals() && "will change when supported"); int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost(); return LT.first * NElts * Cost; } break; default: break; } return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo); } unsigned AMDGPUTTIImpl::getCFInstrCost(unsigned Opcode) { // XXX - For some reason this isn't called for switch. switch (Opcode) { case Instruction::Br: case Instruction::Ret: return 10; default: return BaseT::getCFInstrCost(Opcode); } } int AMDGPUTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, unsigned Index) { switch (Opcode) { case Instruction::ExtractElement: case Instruction::InsertElement: // Extracts are just reads of a subregister, so are free. Inserts are // considered free because we don't want to have any cost for scalarizing // operations, and we don't have to copy into a different register class. // Dynamic indexing isn't free and is best avoided. return Index == ~0u ? 2 : 0; default: return BaseT::getVectorInstrCost(Opcode, ValTy, Index); } } static bool isIntrinsicSourceOfDivergence(const TargetIntrinsicInfo *TII, const IntrinsicInst *I) { switch (I->getIntrinsicID()) { default: return false; case Intrinsic::not_intrinsic: // This means we have an intrinsic that isn't defined in // IntrinsicsAMDGPU.td break; case Intrinsic::amdgcn_workitem_id_x: case Intrinsic::amdgcn_workitem_id_y: case Intrinsic::amdgcn_workitem_id_z: case Intrinsic::amdgcn_interp_mov: case Intrinsic::amdgcn_interp_p1: case Intrinsic::amdgcn_interp_p2: case Intrinsic::amdgcn_mbcnt_hi: case Intrinsic::amdgcn_mbcnt_lo: case Intrinsic::r600_read_tidig_x: case Intrinsic::r600_read_tidig_y: case Intrinsic::r600_read_tidig_z: case Intrinsic::amdgcn_image_atomic_swap: case Intrinsic::amdgcn_image_atomic_add: case Intrinsic::amdgcn_image_atomic_sub: case Intrinsic::amdgcn_image_atomic_smin: case Intrinsic::amdgcn_image_atomic_umin: case Intrinsic::amdgcn_image_atomic_smax: case Intrinsic::amdgcn_image_atomic_umax: case Intrinsic::amdgcn_image_atomic_and: case Intrinsic::amdgcn_image_atomic_or: case Intrinsic::amdgcn_image_atomic_xor: case Intrinsic::amdgcn_image_atomic_inc: case Intrinsic::amdgcn_image_atomic_dec: case Intrinsic::amdgcn_image_atomic_cmpswap: case Intrinsic::amdgcn_buffer_atomic_swap: case Intrinsic::amdgcn_buffer_atomic_add: case Intrinsic::amdgcn_buffer_atomic_sub: case Intrinsic::amdgcn_buffer_atomic_smin: case Intrinsic::amdgcn_buffer_atomic_umin: case Intrinsic::amdgcn_buffer_atomic_smax: case Intrinsic::amdgcn_buffer_atomic_umax: case Intrinsic::amdgcn_buffer_atomic_and: case Intrinsic::amdgcn_buffer_atomic_or: case Intrinsic::amdgcn_buffer_atomic_xor: case Intrinsic::amdgcn_buffer_atomic_cmpswap: case Intrinsic::amdgcn_ps_live: return true; } StringRef Name = I->getCalledFunction()->getName(); switch (TII->lookupName((const char *)Name.bytes_begin(), Name.size())) { default: return false; case AMDGPUIntrinsic::SI_fs_interp: case AMDGPUIntrinsic::SI_fs_constant: return true; } } static bool isArgPassedInSGPR(const Argument *A) { const Function *F = A->getParent(); // Arguments to compute shaders are never a source of divergence. if (!AMDGPU::isShader(F->getCallingConv())) return true; // For non-compute shaders, SGPR inputs are marked with either inreg or byval. if (F->getAttributes().hasAttribute(A->getArgNo() + 1, Attribute::InReg) || F->getAttributes().hasAttribute(A->getArgNo() + 1, Attribute::ByVal)) return true; // Everything else is in VGPRs. return false; } /// /// \returns true if the result of the value could potentially be /// different across workitems in a wavefront. bool AMDGPUTTIImpl::isSourceOfDivergence(const Value *V) const { if (const Argument *A = dyn_cast<Argument>(V)) return !isArgPassedInSGPR(A); // Loads from the private address space are divergent, because threads // can execute the load instruction with the same inputs and get different // results. // // All other loads are not divergent, because if threads issue loads with the // same arguments, they will always get the same result. if (const LoadInst *Load = dyn_cast<LoadInst>(V)) return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS; // Atomics are divergent because they are executed sequentially: when an // atomic operation refers to the same address in each thread, then each // thread after the first sees the value written by the previous thread as // original value. if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) return true; if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { const TargetMachine &TM = getTLI()->getTargetMachine(); return isIntrinsicSourceOfDivergence(TM.getIntrinsicInfo(), Intrinsic); } // Assume all function calls are a source of divergence. if (isa<CallInst>(V) || isa<InvokeInst>(V)) return true; return false; }
33.86217
80
0.685113
[ "vector" ]
e904ac1bf26c773a8ad9ba7660d6970af7225881
25,144
cpp
C++
SierraChart/Client.cpp
tedmarcin/SierraChartZorroPlugin
964d7c70b9846635013203c3cea36a1671f851d3
[ "MIT" ]
1
2021-03-26T17:40:55.000Z
2021-03-26T17:40:55.000Z
SierraChart/Client.cpp
tedmarcin/SierraChartZorroPlugin
964d7c70b9846635013203c3cea36a1671f851d3
[ "MIT" ]
null
null
null
SierraChart/Client.cpp
tedmarcin/SierraChartZorroPlugin
964d7c70b9846635013203c3cea36a1671f851d3
[ "MIT" ]
null
null
null
#include "Engine.h" #include <algorithm> namespace asio = boost::asio; namespace cro = std::chrono; using boost::system::error_code; using asio::ip::tcp; #undef max using namespace DTC; using namespace DTCTools; client::client(socket_config config) : b( [&](const std::string& error_msg) {err(error_msg); }, [&]() {zt_print_errors(); }, conf ), conf(config), io(), ctx(asio::ssl::context::tlsv12_client), timeout(io), next_heartbeat(io), ssl_shutdown_timer(io), io_keepalive(io), reg_socket(io), tls_socket(reg_socket, ctx), stopped(false), errors_ready(false), inflate_mode(false) { ctx.set_options(boost::asio::ssl::context::default_workarounds); tls_socket.set_verify_mode(asio::ssl::verify_none); err("#Launching thread..."); t = std::make_unique<std::thread>(std::thread([&]() { ssl_shutdown_timer.expires_at(cro::steady_clock::now()); io_keepalive.expires_at(cro::steady_clock::time_point::max()); io_keepalive.async_wait([](const error_code ec_ignored) {}); io.run(); })); } client::~client() { err("#Joining thread..."); stop(); std::this_thread::sleep_for(cro::milliseconds(200)); io_keepalive.expires_at(cro::steady_clock::now()); if (t->joinable()) t->join(); t.reset(); } int client::zt_BrokerLogin(char* Accounts) { if (!can_connect()) { err("Connect failure."); return 0; } if (!can_login()) { err("Login failure."); return 0; } if (!can_confirm_trade_account(Accounts)) { err("Confirm tradeaccount failure."); return 0; } if (!can_sync_account_balance()) { err("Sync balance failure."); return 0; } if (!can_sync_orders_hist()) {err("Sync hist orders failure."); return 0; } if (!can_sync_orders_open()) { err("Sync open orders failure."); return 0; } if (!can_sync_positions()) { err("Sync positions failure."); return 0; } // These are just some tests to check if SC has implemented futures and options listing. // As of Jan 2019, futures implemented but not options. //print_exchanges(); //print_symbols_for_underlying("F.US.EP", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("F.US.EDA", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("F.US.JY6", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("ES", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("DY", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("B6", SECURITY_TYPE_FUTURES); //print_symbols_for_underlying("J7", SECURITY_TYPE_FUTURES); return 1; } int client::zt_BrokerHistory2(DTC::s_SecurityDefinitionResponse* def, DATE tStart, DATE tEnd, int nTickMinutes, int nTicks, T6* ticks) { if (!can_connect()) { err("Connect failure."); return 0; } if (!can_login()) { err("Login failure."); return 0; } if (!is_historical()) { err("Cannot get historical data from a non-historical socket."); stop(); return 0; } if (is_hist_integer()) { err("Integer historical data not supported."); stop(); return 0; } return can_get_history(def, tStart, tEnd, nTickMinutes, nTicks, ticks); } bool client::is_historical() { return maybe_post_return([&]()->bool { if (server_settings.GetHistoricalPriceDataSupported()) return true; else return false; }); } bool client::is_hist_integer() { return maybe_post_return([&]()->bool { if (server_settings.GetUseIntegerPriceOrderMessages()) return true; else return false; }); } bool client::has_security_definitions() { return maybe_post_return([&]()->bool { if (server_settings.GetSecurityDefinitionsSupported()) return true; else return false; }); } void emulate_session_volume(T6* pt6, const int& nEntries) { // We will now emulate session volume. // From oldest to newest ticks, volume will increase from zero. // From a zorro script, bar volume is acquired by measuring changes in this value. // If the change is negative, this means you are reading a different "session". // But since it restarted at zero, assume that the given value is the bar's value. // Example: // 10000 // 10100 change is 100, bar volume is 100 // 10250 change is 150, bar volume is 150 // 135 change is -10115. We are reading a new session, bar volume is 135. // 200 change is 65, bar volume is 65 // ... and so on. float lastvol = 0; const float max = pow((float)10, (float)10); // arbitrary high float number, 10^10 for (int i = (nEntries - 1); i >= 0; i--) { if (max < (lastvol + pt6[i].fVol)) // need a session volume reset { lastvol = 0; } pt6[i].fVol = (lastvol += pt6[i].fVol); } } //#include <fstream> // std::ofstream //void save_to_file(T6* pt6, const int& nEntries) //{ // static int i = 0; // std::string filename = ".\\test" + std::to_string(++i) + ".t6"; // // std::ofstream ofs; // ofs.open(filename, std::ofstream::out | std::ofstream::app); // // ofs.write((const char*)pt6, nEntries); // // ofs.close(); //} #define IGNORE_MAX_DAYS //HACK int client::can_get_history(DTC::s_SecurityDefinitionResponse* def, DATE tStart, DATE tEnd, int nTickMinutes, int nTicks, T6* pt6) { if (stopped) return 0; // we are logged in to historical server. s_HistoricalPriceDataRequest rq; int seconds_bar = 0; int max_days = 0; bool do_time_shift = false; switch (nTickMinutes) { case 0: rq.RecordInterval = INTERVAL_TICK; max_days = 7; // time = occurance of tick break; case 1: rq.RecordInterval = INTERVAL_1_MINUTE; max_days = 62; seconds_bar = 60; // zorro: 1M bar CLOSE, sierra: bar OPEN do_time_shift = true; break; case 1440: rq.RecordInterval = INTERVAL_1_DAY; max_days = 7000; seconds_bar = 1440 * 60; // zorro: daily bar OPEN, sierra: bar OPEN break; default: err("Error: Only tick and 1M historical data supported!"); stop(); return 0; } rq.StartDateTime = convertDate_1sec64bit(tStart); rq.EndDateTime = convertDate_1sec64bit(tEnd); #ifndef IGNORE_MAX_DAYS rq.StartDateTime = std::max(rq.StartDateTime, rq.EndDateTime - (max_days * 24 * 60 * 60)); #endif rq.SetSymbol(def->GetSymbol()); rq.SetExchange(def->GetExchange()); if(conf.zlib) rq.UseZLibCompression = 1; else rq.UseZLibCompression = 0; if (dividend_adjusted)rq.RequestDividendAdjustedStockData = 1; else rq.RequestDividendAdjustedStockData = 0; rq.RequestID = rid.get_request_id(rq); b.expect(sol_HistoricalPriceData_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { stop(); return 0; } // Note: the DTC protocol necessarily delivers historical data // from oldest to newest. // Thus, our approach: // 1) Read the input in the reverse order (.rbegin to .rend) // 2) If a tick is outside the date range, skip it. // 3) Output is from i=0 to (max - 1), direct to zorro T6 memory. return maybe_post_return([&]()->int { s_HistoricalPriceDataResponseHeader& hdr = h_header; if (hdr.GetNoRecordsToReturn()) { stop(); return 0; } else if ( !hdr.GetRecordInterval() && // header indicates ticks (!server_settings.GetUseIntegerPriceOrderMessages()) && // prices are in double h_ticks.size() // The server indeed supplied ticks (NOT ALWAYS THE CASE!!!!) ) { float value; auto dq_reit = h_ticks.rbegin(); int i = 0; // T6 index for (; (dq_reit != h_ticks.rend()) && (i < HISTORY_MAXIMUM_TICKS); dq_reit++){ auto vec_reit = dq_reit->rbegin(); for (; (vec_reit != dq_reit->rend()) && (i < HISTORY_MAXIMUM_TICKS); vec_reit++) { // Here we skip invalid entries up front DATE t = convertTime(vec_reit->GetDateTime()); if (t<tStart || t>tEnd) continue; // we are cleared to make an entry value = (float)vec_reit->GetPrice(); if (vec_reit->GetAtBidOrAsk() == AT_BID) value *= -1; pt6[i].time = t; pt6[i].fHigh = value; pt6[i].fLow = value; pt6[i].fOpen = value; pt6[i].fClose = value; pt6[i].fVal = 0; // not used if (voltype == VOLTYPE_SESSION_VOLUME) pt6[i].fVol = (float)vec_reit->GetVolume(); // real volume this tick (to be converted to session volume) else if (voltype == VOLTYPE_SESSION_NUMTRADES) pt6[i].fVol = (float)1; // tick volume this tick (to be converted to session tick frequency) else pt6[i].fVol = 0; // We only increment the T6 index if we are satisfied with our entry. i++; } } const int t6_qty = i; emulate_session_volume(pt6, t6_qty); return t6_qty; } else if ( !hdr.GetRecordInterval() && // header indicates ticks (!server_settings.GetUseIntegerPriceOrderMessages()) && // prices are in double h_bars.size() // The server actually gave us bars instead!!! ) { float value; auto dq_reit = h_bars.rbegin(); int i = 0; // T6 index for (; (dq_reit != h_bars.rend()) && (i < HISTORY_MAXIMUM_TICKS); dq_reit++) { auto vec_reit = dq_reit->rbegin(); for (; (vec_reit != dq_reit->rend()) && (i < HISTORY_MAXIMUM_TICKS); vec_reit++) { // Here we skip invalid entries up front DATE t = convertTime(vec_reit->GetStartDateTime()); if (t<tStart || t>tEnd) continue; // we are cleared to make an entry value = (float)vec_reit->GetLastPrice(); if (!value) value = (float)vec_reit->GetOpenPrice(); if (!value) continue; // nothing to do!!! // sanity check: is one volume being used and not the other? if(!vec_reit->GetAskVolume() && vec_reit->GetBidVolume()) // AT_BID value *= -1; pt6[i].time = t; pt6[i].fHigh = value; pt6[i].fLow = value; pt6[i].fOpen = value; pt6[i].fClose = value; pt6[i].fVal = 0; // not used if (voltype == VOLTYPE_SESSION_VOLUME) pt6[i].fVol = (float)vec_reit->GetVolume(); // real volume this tick (to be converted to session volume) else if (voltype == VOLTYPE_SESSION_NUMTRADES) pt6[i].fVol = (float)1; // tick volume this tick (to be converted to session tick frequency) else pt6[i].fVol = 0; // We only increment the T6 index if we are satisfied with our entry. i++; } } const int t6_qty = i; emulate_session_volume(pt6, t6_qty); return t6_qty; } else if ( hdr.GetRecordInterval() && // header indicates bars (!server_settings.GetUseIntegerPriceOrderMessages()) // prices are in double ) { auto dq_reit = h_bars.rbegin(); int i = 0; // T6 index for (; (dq_reit != h_bars.rend()) && (i < HISTORY_MAXIMUM_TICKS); dq_reit++) { auto vec_reit = dq_reit->rbegin(); for (; (vec_reit != dq_reit->rend()) && (i < HISTORY_MAXIMUM_TICKS); vec_reit++) { // Here we skip invalid entries up front // zorro: bar close, sierra: bar open int64_t dt = vec_reit->GetStartDateTime(); // dt is the moment the first tick is received in a bar. Unit: seconds dt /= seconds_bar; // now it's rounded down (minutes for 1M). So we are at the beginning of the bar. dt *= seconds_bar; // back to seconds, beginning of the bar. if (do_time_shift) { dt += seconds_bar; // end of bar, per Zorro } DATE t = convertTime(dt); if (t<tStart || t>tEnd) continue; pt6[i].time = t; pt6[i].fOpen = (float)vec_reit->GetOpenPrice(); pt6[i].fHigh = (float)vec_reit->GetHighPrice(); pt6[i].fLow = (float)vec_reit->GetLowPrice(); pt6[i].fClose = (float)vec_reit->GetLastPrice(); pt6[i].fVal = 0; //not used if (voltype == VOLTYPE_SESSION_VOLUME) pt6[i].fVol = (float)vec_reit->GetVolume(); // real volume this bar (to be converted to session volume) else if (voltype == VOLTYPE_SESSION_NUMTRADES) pt6[i].fVol = (float)vec_reit->GetNumTrades(); // tick volume this bar (to be converted to session tick frequency) else pt6[i].fVol = 0; // We only increment the T6 index if we are satisfied with our entry. i++; } } const int t6_qty = i; //save_to_file(pt6, t6_qty); emulate_session_volume(pt6, t6_qty); return t6_qty; } else { err("An unknown historical data type may have been received."); stop(); return 0; } }); } int client::zt_BrokerAsset(char* ZorroAsset, double *pPrice, double *pSpread, double *pVolume, double *pPip, double *pPipCost, double *pLotAmount, double *pMarginCost, double *pRollLong, double *pRollShort) { s_SecurityDefinitionResponse* def = can_define(ZorroAsset); if (!def) { err("Asset: " + (std::string)ZorroAsset + " not defined"); return 0; } // subscribe if needed if (!pPrice) { err("Subscribing to Symbol " + (std::string)def->Symbol + "..."); if (!can_subscribe(def)) { err((std::string)def->Symbol + ": subscription failed."); return 0; } else // good { if (can_subscribe_market_depth(def)) err("Market depth subscribed"); else err("No market depth"); return 1; } } // otherwise output asset status else { if (!can_update(def, pPrice, pSpread, pVolume, pPip, pPipCost, pLotAmount, pMarginCost, pRollLong, pRollShort)) { err("Cannot update info for Symbol " + (std::string)def->Symbol); return 0; } else // good return 1; } } int client::zt_BrokerAccount(char* Account, double *pBalance, double *pTradeVal, double *pMarginVal) { if (Account) tradeaccount_selected = Account; if (!tradeaccount_selected.size()) tradeaccount_selected = tradeaccount_main; return maybe_post_return([&]() ->int { per_trade_account& pta = m_pta.find(tradeaccount_selected)->second; s_AccountBalanceUpdate& a = pta.balance; if ( !a.GetNoAccountBalances() && // not a simulated account !(patch & PATCH_BALANCE_EQUITY) // balance/equity override is not enabled ) { if (pBalance) *pBalance = a.GetCashBalance(); if (pTradeVal) *pTradeVal = a.GetSecuritiesValue() - a.GetCashBalance(); if (pMarginVal) *pMarginVal = a.GetMarginRequirement(); } return 1; }); } bool client::can_connect() { // our connection sequence is synchronous because asynchronous is completely unnecessary. tcp::resolver r(io); tcp::resolver::results_type endpoints = r.resolve(conf.host, conf.port); bool out = false; for (auto endpoint : endpoints) { { std::string str = "#Trying endpoint " + endpoint.host_name() + ":" + endpoint.service_name(); if (conf.ssl) str += " (TLS 1.2)"; else str += " (unencrypted)"; err(str); } error_code ec; reg_socket.connect(endpoint, ec); if (reg_socket.is_open() && (!ec)) { out = true; break; } else if (ec) { err(ec.message()); } reg_socket.close(); // if there are multiple endpoints, need to close socket before trying next one. } if (!out) { stop(); return false; } if (conf.ssl) { error_code ec; tls_socket.handshake(asio::ssl::stream_base::handshake_type::client, ec); if (ec) { err(ec.message()); stop(); return false; } } return true; } bool client::can_login() { b.expect(sol_LogonResponse); write_async(conf.logon_request); timeout_do(); // launch async timeout read_do(); // launch async reader auto ret = b.block_is_good(); if (!ret) return false; // logged in. heartbeat_do(); // launch heartbeats return true; } bool client::can_confirm_trade_account(char* Accounts) { s_TradeAccountsRequest rq; rq.RequestID = rid.get_request_id(rq); b.expect(sol_TradeAccountsResponse_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { err("Block error: confirm trade accounts"); return 0; } // so far so good return maybe_post_return([&]() { bool match = false; std::deque<std::string> ta_list; // get list of trade accounts, move matching one to front for (auto it = trade_accounts.begin(); it != trade_accounts.end(); ++it) { std::string ta = it->GetTradeAccount(); if (ta == "") { continue; } else if (ta == conf.tradeaccount) { match = true; ta_list.push_front(ta); this_ta = ta; m_pta[ta] = per_trade_account(); // map a blank pta entry. } else // not our tradeaccount { ta_list.push_back(ta); m_pta[ta] = per_trade_account(); // map a blank pta entry. } } // char* Accounts points to an array of 1024 elements // First, we will print the list of accounts using the below vector, using commas. // Then each comma will be converted to a null terminator. // Finally, 1024 elmeents will be copied to Accounts. std::vector<char> str; str.reserve(1024); for (const auto& ta : ta_list) { if (str.size()) str.push_back(','); for (const auto& ch : ta) { str.push_back(ch); } } str.resize(1024, 0); // fill the rest with zeros if (ta_list.size()) { err("TradeAccounts detected: " + ((std::string)str.data())); } else { err("No TradeAccounts detected"); } if (match) { err("Using: " + conf.tradeaccount); for (auto& ch : str) { if (ch == ',') ch = '\0'; } memcpy_s(Accounts, 1024, str.data(), str.size()); return true; } else { err("No matching TradeAccounts found"); return false; } }); } bool client::can_sync_account_balance() { s_AccountBalanceRequest rq; rq.RequestID = rid.get_request_id(rq); b.expect(sol_AccountBalanceUpdate_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { err("Failed to confirm account balance."); return 0; } return maybe_post_return([&]() -> bool { per_trade_account& pta = m_pta.find(tradeaccount_main)->second; if (pta.balance.GetNoAccountBalances()) { err("Warning: no balance for this account!"); return true; } else if (((std::string)pta.balance.GetTradeAccount()) == conf.tradeaccount) { err("Balance synchronized."); return true; } else { err("Warning: no balance confirmed for this account!"); return true; } }); } bool client::can_sync_orders_hist() { s_HistoricalOrderFillsRequest rq; rq.RequestID = rid.get_request_id(rq); rq.NumberOfDays = 365; // Server: "NumberOfDays or StartDateTime fields must be non-zero." rq.SetTradeAccount(conf.tradeaccount.c_str()); b.expect(sol_HistoricalOrderFillResponse_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { err("Failed to confirm historical orders"); return 0; } return maybe_post_return([&]() -> bool { per_trade_account& pta = m_pta.find(tradeaccount_main)->second; int found = 0; for (auto a : pta.orders_hist) { std::string ta = a.GetTradeAccount(); if ( (ta == conf.tradeaccount) && (a.GetRequestID() == rq.RequestID) && !a.GetNoOrderFills() ) found++; } err((std::to_string(found) + " historical orders detected.").c_str()); return true; }); } bool client::can_sync_orders_open() { s_OpenOrdersRequest rq; rq.RequestAllOrders = 1; rq.SetTradeAccount(tradeaccount_main.c_str()); rq.RequestID = rid.get_request_id(rq); b.expect(sol_OrderUpdate_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { err("Failed to confirm open orders"); return 0; } return maybe_post_return ([&]() -> bool { per_trade_account& pta = m_pta.find(tradeaccount_main)->second; int found = 0; for (auto a : pta.orders_open) { std::string ta = a.GetTradeAccount(); if ( (ta == conf.tradeaccount) && (a.GetRequestID() == rq.RequestID) && ((std::string)a.GetSymbol()).size() ) found++; } err((std::to_string(found) + " open orders detected.").c_str()); return true; }); } bool client::can_sync_positions() { s_CurrentPositionsRequest rq; rq.RequestID = rid.get_request_id(rq); b.expect(sol_PositionUpdate_RequestID, rq.RequestID); write_async(rq); if (!b.block_is_good()) { err("Failed to confirm open positions"); return 0; } return maybe_post_return([&]()->bool { per_trade_account& pta = m_pta.find(tradeaccount_main)->second; int found = 0; for (auto a : pta.positions) { std::string ta = a.GetTradeAccount(); if ( (ta == conf.tradeaccount) && (a.GetRequestID() == rq.RequestID) && !a.GetNoPositions() ) found++; } err((std::to_string(found) + " open positions detected.").c_str()); return true; }); } void client::timeout_adjust() { if (stopped) return; timeout.expires_at(cro::steady_clock::now() + cro::milliseconds(conf.timeout_ms)); } void client::timeout_do() { if (stopped) return; timeout_adjust(); timeout.async_wait([&](const boost::system::error_code& ec) {timeout_handler(ec); }); } void client::timeout_handler(const boost::system::error_code& ec) { if (stopped) return; // is now greater than timeout point? If so, stop. if (cro::steady_clock::now() > timeout.expiry()) { std::ostringstream oss; oss << "Timed out."; err(oss.str()); stop(); return; } // No problems detected. Restart loop. timeout_do(); } void client::read_do() { if (stopped) return; // Elements are being moved from the front of this vector. // The remaining allocations are implementation-defined. if (cv_from_socket.size() < (READ_BUFFER_SIZE / 2)) cv_from_socket.resize(READ_BUFFER_SIZE); //cv_from_socket.resize(1); //if (conf.ssl) asio::async_read(tls_socket, //_some if (conf.ssl) tls_socket.async_read_some( //_some asio::buffer(cv_from_socket.data(), cv_from_socket.size()), [&](const error_code& ec, size_t sz) {read_handler(ec, sz); }); //else asio::async_read(reg_socket, //_some else reg_socket.async_read_some( //_some asio::buffer(cv_from_socket.data(), cv_from_socket.size()), [&](const error_code& ec, size_t sz) {read_handler(ec, sz); }); } void client::read_handler(const error_code& ec, size_t sz) { if (stopped) return; if (ec) { std::ostringstream oss; oss << "#Read error: " << ec.message(); // This is too verbose for historical connections err(oss.str()); stop(); return; } if (!sz) read_do(); timeout_adjust(); // move elements to raw queue // ref: https://stackoverflow.com/questions/15004517/moving-elements-from-stdvector-to-another-one cv_queue_raw.insert(cv_queue_raw.end(), std::make_move_iterator(cv_from_socket.begin()), std::make_move_iterator(cv_from_socket.begin() + sz) ); cv_from_socket.erase(cv_from_socket.begin(), cv_from_socket.begin() + sz); std::vector<char>* input = NULL; // read buffers until there is nothing left to read for (;;) { // do we need to inflate the raw buffer? if (inflate_mode) { input = &cv_queue_inflated; if (cv_queue_raw.size()) { try { if (!inf) inf = std::make_unique<Inflator>(); else if (inf->is_done()) { err("#resetting zlib"); inf.reset(); inf = std::make_unique<Inflator>(); } inf->inf(cv_queue_raw, scratch_buffer); cv_queue_raw.clear(); //move all elements from out to inflated queue auto it = std::next(scratch_buffer.begin(), scratch_buffer.size()); std::move(scratch_buffer.begin(), it, std::back_inserter(cv_queue_inflated)); // ## scratch_buffer.erase(scratch_buffer.begin(), it); } catch (const std::runtime_error& rte) { err(rte.what()); stop(); return; } } } else input = &cv_queue_raw; if (input->size() < sizeof(s_Header)) break; // nothing to do. size_t msg_size = ((s_Header*)(input->data()))->Size; if (input->size() < msg_size) break; // nothing to do // move the message to its own char vector, and receive it. std::vector<char> msg; msg.insert(msg.end(), std::make_move_iterator(input->begin()), std::make_move_iterator(input->begin() + msg_size) ); input->erase(input->begin(), input->begin() + msg_size); receive(msg); } read_do(); } void client::heartbeat_do() { if (stopped) return; if (!conf.hb_interval_s) return; next_heartbeat.expires_at(cro::steady_clock::now() + cro::seconds(conf.hb_interval_s)); next_heartbeat.async_wait([&](const error_code& ec) {heartbeat_handler(ec); }); } void client::heartbeat_handler(const error_code& ec) { if (stopped) return; if (ec) { std::ostringstream oss; oss << "Heartbeat error: " << ec.message(); err(oss.str()); stop(); return; } s_Heartbeat hb; write_async(hb); heartbeat_do(); } void client::stop() { b.unblock(false); if (stopped) return; stopped = true; timeout.cancel(); next_heartbeat.cancel(); if (!conf.ssl) reg_socket.close(); else { ssl_shutdown_timer.expires_at(cro::steady_clock::now() + cro::milliseconds(5)); tls_socket.lowest_layer().cancel(); tls_socket.async_shutdown([this](const error_code& ignored_ec) {}); ssl_shutdown_timer.async_wait([&](const error_code& ignored_ec) { tls_socket.lowest_layer().close(); }); } } void client::zt_print_errors() { if (zt_id != std::this_thread::get_id()) return; // safety check if (!errors_ready) return; std::deque<std::string> outs; auto fu = post_use_future(io, [&]() -> int { std::swap(outs, errors); errors_ready = false; return 0; }); fu.get(); // block for post completion for (const auto& out : outs) { BrokerError(out.c_str()); } } void client::BackendError(const std::string& error_msg) { errors.push_back(error_msg); errors_ready = true; } void client::err(const std::string& error_msg) { std::string msg; if (error_msg[0] == '#') msg = "#" + std::to_string((int)conf.id) + ": " + error_msg.substr(1); else msg = std::to_string((int)conf.id) + ": " + error_msg; if (zt_id == std::this_thread::get_id()) BrokerError(msg.c_str()); else BackendError(msg); }
26.80597
206
0.664691
[ "vector" ]
e905e34c96539f975f345540bce5445b3574f47f
57,978
cpp
C++
frameworks/src/core/components/test/unittest/common/event_bubble_tdd_test.cpp
openharmony/ace_engine_lite
9b26a0aa86d31ede7717fa51deb5e0be8b963a6f
[ "Apache-2.0" ]
null
null
null
frameworks/src/core/components/test/unittest/common/event_bubble_tdd_test.cpp
openharmony/ace_engine_lite
9b26a0aa86d31ede7717fa51deb5e0be8b963a6f
[ "Apache-2.0" ]
null
null
null
frameworks/src/core/components/test/unittest/common/event_bubble_tdd_test.cpp
openharmony/ace_engine_lite
9b26a0aa86d31ede7717fa51deb5e0be8b963a6f
[ "Apache-2.0" ]
1
2021-09-13T11:12:42.000Z
2021-09-13T11:12:42.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "event_bubble_tdd_test.h" #include <unistd.h> #include "flex_layout.h" #include "ui_list.h" #include "wrapper/js.h" namespace OHOS { namespace ACELite { const char BUNDLE_CLICK_BUBBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { click: _vm.handleClick3 } }, [\n" " _c('div', { staticClass: ['pane'], onBubbleEvents: { click: _vm.handleClick2 } }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'CLICK ME' },\n" " onBubbleEvents: { click: _vm.handleClick1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 240\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleClick1: function () {\n" " this.logs.push('handleClick1');\n" " },\n" " handleClick2: function () {\n" " this.logs.push('handleClick2');\n" " },\n" " handleClick3: function () {\n" " this.logs.push('handleClick3');\n" " }\n" " });\n" "})();"; const char BUNDLE_LONG_PRESS_BUBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { longpress: _vm.handleLongPress3 } }, " "[\n" " _c('div', { staticClass: ['pane'], onBubbleEvents: { longpress: _vm.handleLongPress2 } }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'LONG PRESS ME' },\n" " onBubbleEvents: { longpress: _vm.handleLongPress1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 300\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleLongPress1: function () {\n" " this.logs.push('handleLongPress1');\n" " },\n" " handleLongPress2: function () {\n" " this.logs.push('handleLongPress2');\n" " },\n" " handleLongPress3: function () {\n" " this.logs.push('handleLongPress3');\n" " }\n" " });\n" "})();"; const char BUNDLE_SWIPE_BUBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { swipe: _vm.handleSwipe3 } }, [\n" " _c('div', { staticClass: ['pane'], onBubbleEvents: { swipe: _vm.handleSwipe2 } }, [\n" " _c('div', {\n" " staticClass: ['box'],\n" " onBubbleEvents: { swipe: _vm.handleSwipe1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " box: {\n" " width: 200,\n" " height: 200,\n" " backgroundColor: '#0f0'\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleSwipe1: function () {\n" " this.logs.push('handleSwipe1');\n" " },\n" " handleSwipe2: function () {\n" " this.logs.push('handleSwipe2');\n" " },\n" " handleSwipe3: function () {\n" " this.logs.push('handleSwipe3');\n" " }\n" " });\n" "})();"; const char BUNDLE_CLICK_DEFAULT_BUBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { click: _vm.handleClick3 } }, [\n" " _c('div', { staticClass: ['pane'] }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'CLICK ME' },\n" " onBubbleEvents: { click: _vm.handleClick1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 240\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleClick1: function () {\n" " this.logs.push('handleClick1');\n" " },\n" " handleClick2: function () {\n" " this.logs.push('handleClick2');\n" " },\n" " handleClick3: function () {\n" " this.logs.push('handleClick3');\n" " }\n" " });\n" "})();"; const char BUNDLE_LONG_PRESS_DEFAULT_BUBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { longpress: _vm.handleLongPress3 } }, " "[\n" " _c('div', { staticClass: ['pane'] }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'LONG PRESS ME' },\n" " onBubbleEvents: { longpress: _vm.handleLongPress1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 300\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleLongPress1: function () {\n" " this.logs.push('handleLongPress1');\n" " },\n" " handleLongPress2: function () {\n" " this.logs.push('handleLongPress2');\n" " },\n" " handleLongPress3: function () {\n" " this.logs.push('handleLongPress3');\n" " }\n" " });\n" "})();"; const char BUNDLE_SWIPE_DEFAULT_BUBBLE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { swipe: _vm.handleSwipe3 } }, [\n" " _c('div', { staticClass: ['pane'] }, [\n" " _c('div', {\n" " staticClass: ['box'],\n" " onBubbleEvents: { swipe: _vm.handleSwipe1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " box: {\n" " width: 200,\n" " height: 200,\n" " backgroundColor: '#0f0'\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleSwipe1: function () {\n" " this.logs.push('handleSwipe1');\n" " },\n" " handleSwipe2: function () {\n" " this.logs.push('handleSwipe2');\n" " },\n" " handleSwipe3: function () {\n" " this.logs.push('handleSwipe3');\n" " }\n" " });\n" "})();"; const char BUNDLE_CLICK_STOP_PROPAGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { click: _vm.handleClick3 } }, [\n" " _c('div', { staticClass: ['pane'], catchBubbleEvents: { click: _vm.handleClick2 } }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'CLICK ME' },\n" " onBubbleEvents: { click: _vm.handleClick1 }\n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 240\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleClick1: function () {\n" " this.logs.push('handleClick1');\n" " },\n" " handleClick2: function () {\n" " this.logs.push('handleClick2');\n" " },\n" " handleClick3: function () {\n" " this.logs.push('handleClick3');\n" " }\n" " });\n" "})();"; const char BUNDLE_LONG_PRESS_STOP_PROPAGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { longpress: _vm.handleLongPress3 } }, " "[\n" " _c('div', { staticClass: ['pane'], catchBubbleEvents: { longpress: _vm.handleLongPress2 } }, [\n" " _c('input', {\n" " staticClass: ['button'],\n" " attrs: { type: 'button', value: 'LONG PRESS ME' },\n" " onBubbleEvents: { longpress: _vm.handleLongPress1 }\n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " button: {\n" " width: 240\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleLongPress1: function () {\n" " this.logs.push('handleLongPress1');\n" " },\n" " handleLongPress2: function () {\n" " this.logs.push('handleLongPress2');\n" " },\n" " handleLongPress3: function () {\n" " this.logs.push('handleLongPress3');\n" " }\n" " });\n" "})();"; const char BUNDLE_SWIPE_STOP_PROPAGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { swipe: _vm.handleSwipe3 } }, [\n" " _c('div', { staticClass: ['pane'], catchBubbleEvents: { swipe: _vm.handleSwipe2 } }, [\n" " _c('div', {\n" " staticClass: ['box'],\n" " onBubbleEvents: { swipe: _vm.handleSwipe1 } \n" " })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " pane: {\n" " backgroundColor: '#f00',\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " width: '70%',\n" " height: '70%'\n" " },\n" " box: {\n" " width: 200,\n" " height: 200,\n" " backgroundColor: '#0f0'\n" " }\n" " }\n" " },\n" " data: {\n" " logs: []\n" " },\n" " handleSwipe1: function () {\n" " this.logs.push('handleSwipe1');\n" " },\n" " handleSwipe2: function () {\n" " this.logs.push('handleSwipe2');\n" " },\n" " handleSwipe3: function () {\n" " this.logs.push('handleSwipe3');\n" " }\n" " });\n" "})();"; const char BUNDLE_CLICK_DELEGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { click: _vm.handleClick } }, [\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'red', value: 'red' } }),\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'green', value: 'green' } }),\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'blue', value: 'blue' } })\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%',\n" " },\n" " button: {\n" " borderRadius: 0,\n" " width: 150\n" " }\n" " }\n" " },\n" " data: {\n" " bgColor: '#f00'\n" " },\n" " handleClick: function(event) {\n" " if (event.target === this.$refs.red) {\n" " this.bgColor = '#f00';\n" " } else if (event.target === this.$refs.green) {\n" " this.bgColor = '#0f0';\n" " } else if (event.target === this.$refs.blue) {\n" " this.bgColor = '#00f';\n" " } else {\n" " console.log('Unknown element.');\n" " }\n" " }\n" " });\n" "})();"; const char BUNDLE_LONG_PRESS_DELEGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { longpress: _vm.handleLongPress } }, [\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'red', value: 'red' } }),\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'green', value: 'green' } }),\n" " _c('input', { staticClass: ['button'], attrs: { type: 'button', ref: 'blue', value: 'blue' } })\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%',\n" " },\n" " button: {\n" " borderRadius: 0,\n" " width: 150\n" " }\n" " }\n" " },\n" " data: {\n" " bgColor: '#f00'\n" " },\n" " handleLongPress: function(event) {\n" " if (event.target === this.$refs.red) {\n" " this.bgColor = '#f00';\n" " } else if (event.target === this.$refs.green) {\n" " this.bgColor = '#0f0';\n" " } else if (event.target === this.$refs.blue) {\n" " this.bgColor = '#00f';\n" " } else {\n" " console.log('Unknown element.');\n" " }\n" " }\n" " });\n" "})();"; const char BUNDLE_SWIPE_DELEGATION[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['container'], onBubbleEvents: { swipe: _vm.handleSwipe } }, [\n" " _c('div', { staticClass: ['box', 'box--red'], attrs: { ref: 'red' } }, [\n" " _c('text', { staticClass: ['title'], attrs: { value: 'red'} })\n" " ]),\n" " _c('div', { staticClass: ['box', 'box--green'], attrs: { ref: 'green' } }, [\n" " _c('text', { staticClass: ['title'], attrs: { value: 'green'} })\n" " ]),\n" " _c('div', { staticClass: ['box', 'box--blue'], attrs: { ref: 'blue' } }, [\n" " _c('text', { staticClass: ['title'], attrs: { value: 'blue'} })\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " box: {\n" " width: '50%',\n" " height: 100,\n" " justifyContent: 'center',\n" " alignItems: 'center'\n" " },\n" " 'box--red': {\n" " backgroundColor: '#f00'\n" " },\n" " 'box--green': {\n" " backgroundColor: '#0f0'\n" " },\n" " 'box--blue': {\n" " backgroundColor: '#00f'\n" " },\n" " title: {\n" " color: '#fff'\n" " }\n" " }\n" " },\n" " data: {\n" " text: 'none'\n" " },\n" " handleSwipe: function(event) {\n" " if (event.target === this.$refs.red) {\n" " this.text = 'red';\n" " } else if (event.target === this.$refs.green) {\n" " this.text = 'green';\n" " } else if (event.target === this.$refs.blue) {\n" " this.text = 'blue';\n" " } else {\n" " console.log('Unknown element.');\n" " }\n" " }\n" " });\n" "})();"; const char BUNDLE_CLICK_PRESSURE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('text', { attrs: { value: function() { return _vm.count; } } })\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " box: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " }\n" " },\n" " data: {\n" " count: 0\n" " },\n" " handle: function() {\n" " this.count++;\n" " }\n" " });\n" "})();"; const char BUNDLE_LONG_PRESS_PRESSURE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { longpress: _vm.handle } }, [\n" " _c('text', { attrs: { value: function() { return _vm.count; } } })\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " box: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " }\n" " },\n" " data: {\n" " count: 0\n" " },\n" " handle: function() {\n" " this.count++;\n" " }\n" " });\n" "})();"; const char BUNDLE_SWIPE_PRESSURE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { swipe: _vm.handle } }, [\n" " _c('text', { attrs: { value: function() { return _vm.count; } } })\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " box: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " }\n" " },\n" " data: {\n" " count: 0\n" " },\n" " handle: function() {\n" " this.count++;\n" " }\n" " });\n" "})();"; const char BUNDLE_CLICK_PRESSURE2[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('div', { staticClass: ['box'], onBubbleEvents: { click: _vm.handle } }, [\n" " _c('text', { attrs: { value: function() { return _vm.count; } } })\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ])\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " box: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '100%',\n" " width: '100%'\n" " },\n" " }\n" " },\n" " data: {\n" " count: 0\n" " },\n" " handle: function() {\n" " this.count++;\n" " }\n" " });\n" "})();"; const char BUBBLE_PREVENT_DOUBLE_SWIPE[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c(\n" " 'div',\n" " {\n" " staticClass: ['container'],\n" " onBubbleEvents: { swipe: _vm.handleDivSwipe },\n" " attrs: { ref: 'box' }\n" " },\n" " [\n" " _c('text', { attrs: { value: 'Header' } }),\n" " _c(\n" " 'list',\n" " {\n" " staticClass: ['list'],\n" " catchBubbleEvents: { swipe: _vm.handleListSwipe },\n" " attrs: { ref: 'list' }\n" " },\n" " [\n" " _l(\n" " function () {\n" " return _vm.dataSource;\n" " },\n" " function (item, $idx) {\n" " return _c('list-item', { staticClass: ['list-item'] }, [\n" " _c('text', {\n" " staticClass: ['title'],\n" " attrs: {\n" " value: function () {\n" " return item.title;\n" " }\n" " }\n" " })\n" " ]);\n" " }\n" " )\n" " ]\n" " ),\n" " _c('text', { attrs: { value: 'Footer' } }),\n" " ]\n" " );\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " container: {\n" " flexDirection: 'column',\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " height: '200%',\n" " width: '100%'\n" " },\n" " list: {\n" " backgroundColor: 'blanchedalmond',\n" " width: '80%',\n" " height: 400\n" " },\n" " 'list-item': {\n" " width: '100%',\n" " height: 200,\n" " justifyContent: 'center',\n" " alignItems: 'center'\n" " },\n" " },\n" " },\n" " data: {\n" " dataSource: [\n" " { title: 'Item 1' },\n" " { title: 'Item 2' },\n" " { title: 'Item 3' },\n" " { title: 'Item 4' },\n" " { title: 'Item 5' }\n" " ],\n" " divSwipe: false,\n" " listSwipe: false\n" " },\n" " handleDivSwipe: function () {\n" " this.divSwipe = true;\n" " },\n" " handleListSwipe: function () {\n" " this.listSwipe = true;\n" " }\n" " });\n" "})();\n"; constexpr uint8_t NUM_TWO = 2; constexpr uint8_t NUM_THREE = 3; void EventBubbleTddTest::EventBubbleTest001() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_BUBBBLE, strlen(BUNDLE_CLICK_BUBBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; Click(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_THREE); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleClick1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleClick2"); free(content); content = JSArray::GetString(logs, NUM_TWO); EXPECT_STREQ(content, "handleClick3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest002() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_LONG_PRESS_BUBBLE, strlen(BUNDLE_LONG_PRESS_BUBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; LongPress(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_THREE); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleLongPress1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleLongPress2"); free(content); content = JSArray::GetString(logs, NUM_TWO); EXPECT_STREQ(content, "handleLongPress3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest003() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_SWIPE_BUBBLE, strlen(BUNDLE_SWIPE_BUBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t halfDistance = 50; const uint16_t startX = centerX - halfDistance; const uint16_t endX = centerX + halfDistance; Swipe(startX, centerY, endX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_THREE); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleSwipe1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleSwipe2"); free(content); content = JSArray::GetString(logs, NUM_TWO); EXPECT_STREQ(content, "handleSwipe3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest004() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_DEFAULT_BUBBLE, strlen(BUNDLE_CLICK_DEFAULT_BUBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; Click(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleClick1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleClick3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest005() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_LONG_PRESS_DEFAULT_BUBBLE, strlen(BUNDLE_LONG_PRESS_DEFAULT_BUBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; LongPress(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleLongPress1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleLongPress3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest006() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_SWIPE_DEFAULT_BUBBLE, strlen(BUNDLE_SWIPE_DEFAULT_BUBBLE)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t halfDistance = 50; const uint16_t startX = centerX - halfDistance; const uint16_t endX = centerX + halfDistance; Swipe(startX, centerY, endX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleSwipe1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleSwipe3"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest007() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_STOP_PROPAGATION, strlen(BUNDLE_CLICK_STOP_PROPAGATION)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; Click(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleClick1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleClick2"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest008() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_LONG_PRESS_STOP_PROPAGATION, strlen(BUNDLE_LONG_PRESS_STOP_PROPAGATION)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; LongPress(centerX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleLongPress1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleLongPress2"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest009() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_SWIPE_STOP_PROPAGATION, strlen(BUNDLE_SWIPE_STOP_PROPAGATION)); const char *propLogs = "logs"; JSValue logs = JSObject::Get(page, propLogs); EXPECT_EQ(JSArray::Length(logs), 0); const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t halfDistance = 50; const uint16_t startX = centerX - halfDistance; const uint16_t endX = centerX + halfDistance; Swipe(startX, centerY, endX, centerY); EXPECT_EQ(JSArray::Length(logs), NUM_TWO); char *content = JSArray::GetString(logs, 0); EXPECT_STREQ(content, "handleSwipe1"); free(content); content = JSArray::GetString(logs, 1); EXPECT_STREQ(content, "handleSwipe2"); free(content); content = nullptr; JSRelease(logs); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest010() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_DELEGATION, strlen(BUNDLE_CLICK_DELEGATION)); const char *propBgColor = "bgColor"; const char *bgRed = "#f00"; const char *bgGreen = "#0f0"; const char *bgBlue = "#00f"; const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t distance = 100; // click green button Click(centerX, centerY); char *content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, bgGreen); free(content); // click blue button Click(centerX + distance, centerY); content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, bgBlue); free(content); // click red button Click(centerX - distance, centerY); content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, bgRed); free(content); content = nullptr; DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest011() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_LONG_PRESS_DELEGATION, strlen(BUNDLE_LONG_PRESS_DELEGATION)); // click green button const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t distance = 100; LongPress(centerX, centerY); const char *propBgColor = "bgColor"; char *content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, "#0f0"); free(content); // click blue button LongPress(centerX + distance, centerY); content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, "#00f"); free(content); // click red button LongPress(centerX - distance, centerY); content = JSObject::GetString(page, propBgColor); EXPECT_STREQ(content, "#f00"); free(content); content = nullptr; DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest012() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_SWIPE_DELEGATION, strlen(BUNDLE_SWIPE_DELEGATION)); const char *propText = "text"; const char *textRed = "red"; const char *textGreen = "green"; const char *textBlue = "blue"; const uint16_t greenX = GetHorizontalResolution() / NUM_TWO; const uint16_t greenY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t boxHeight = 100; constexpr uint16_t halfDistance = 50; const uint16_t startX = greenX - halfDistance; const uint16_t endX = greenX + halfDistance; const uint16_t redY = greenY - boxHeight; const uint16_t blueY = greenY + boxHeight; Swipe(startX, redY, endX, redY); char *content = JSObject::GetString(page, propText); EXPECT_STREQ(content, textRed); free(content); Swipe(startX, greenY, endX, greenY); content = JSObject::GetString(page, propText); EXPECT_STREQ(content, textGreen); free(content); Swipe(startX, blueY, endX, blueY); content = JSObject::GetString(page, propText); EXPECT_STREQ(content, textBlue); free(content); content = nullptr; DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest013() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_PRESSURE, strlen(BUNDLE_CLICK_PRESSURE)); const char *propCount = "count"; const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint8_t diffCount = 20; Click(centerX, centerY); uint32_t count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount); Click(centerX, centerY); count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * NUM_TWO); Click(centerX, centerY); count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * NUM_THREE); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest014() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_LONG_PRESS_PRESSURE, strlen(BUNDLE_LONG_PRESS_PRESSURE)); const char *propCount = "count"; const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint8_t diffCount = 20; LongPress(centerX, centerY); uint32_t count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount); LongPress(centerX, centerY); count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * NUM_TWO); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest015() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_SWIPE_PRESSURE, strlen(BUNDLE_SWIPE_PRESSURE)); const char *propCount = "count"; const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint16_t halfDistance = 50; const uint16_t startX = centerX - halfDistance; const uint16_t endX = centerX + halfDistance; constexpr uint8_t diffCount = 20; Swipe(startX, centerY, endX, centerY); uint32_t count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount); Swipe(startX, centerY, endX, centerY); count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * NUM_TWO); Swipe(startX, centerY, endX, centerY); count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * NUM_THREE); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest016() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUNDLE_CLICK_PRESSURE2, strlen(BUNDLE_CLICK_PRESSURE2)); const char *propCount = "count"; const uint16_t centerX = GetHorizontalResolution() / NUM_TWO; const uint16_t centerY = GetVerticalResolution() / NUM_TWO; constexpr uint8_t times = 10; constexpr uint8_t diffCount = 20; for (uint8_t idx = 0; idx < times; ++idx) { Click(centerX, centerY); } uint32_t count = static_cast<uint32_t>(JSObject::GetNumber(page, propCount)); EXPECT_EQ(count, diffCount * times); DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::EventBubbleTest017() { TDD_CASE_BEGIN(); JSValue page = CreatePage(BUBBLE_PREVENT_DOUBLE_SWIPE, strlen(BUBBLE_PREVENT_DOUBLE_SWIPE)); FlexLayout *container = reinterpret_cast<FlexLayout *>(GetViewByRef(page, "box")); EXPECT_TRUE(container != nullptr); if (container != nullptr) { int16_t prevContainerY = container->GetOrigRect().GetY(); UIList *list = reinterpret_cast<UIList *>(GetViewByRef(page, "list")); EXPECT_TRUE(list != nullptr); if (list != nullptr) { Rect rect = list->GetOrigRect(); int16_t diffY = 100; int16_t x = rect.GetLeft() + rect.GetWidth() / NUM_TWO; int16_t startY = rect.GetTop() + rect.GetHeight() - diffY; int16_t endY = rect.GetTop() + diffY; Swipe(x, startY, x, endY); EXPECT_FALSE(JSObject::GetBoolean(page, "divSwipe")); EXPECT_TRUE(JSObject::GetBoolean(page, "listSwipe")); EXPECT_EQ(container->GetOrigRect().GetY(), prevContainerY); } } DestroyPage(page); TDD_CASE_END(); } void EventBubbleTddTest::RunTests() { EventBubbleTest001(); EventBubbleTest002(); EventBubbleTest003(); EventBubbleTest004(); EventBubbleTest005(); EventBubbleTest006(); EventBubbleTest007(); EventBubbleTest008(); EventBubbleTest009(); EventBubbleTest010(); EventBubbleTest011(); EventBubbleTest012(); EventBubbleTest013(); EventBubbleTest014(); EventBubbleTest015(); EventBubbleTest016(); EventBubbleTest017(); } #ifdef TDD_ASSERTIONS /* * * @tc.name: EventBubbleTest001 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest001, TestSize.Level0) { EventBubbleTddTest::EventBubbleTest001(); } /* * * @tc.name: EventBubbleTest002 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest002, TestSize.Level0) { EventBubbleTddTest::EventBubbleTest002(); } /* * * @tc.name: EventBubbleTest003 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest003, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest003(); } /* * * @tc.name: EventBubbleTest004 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest004, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest004(); } /* * * @tc.name: EventBubbleTest005 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest005, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest005(); } /* * * @tc.name: EventBubbleTest006 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest006, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest006(); } /* * * @tc.name: EventBubbleTest007 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest007, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest007(); } /* * * @tc.name: EventBubbleTest008 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest008, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest008(); } /* * * @tc.name: EventBubbleTest009 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest009, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest009(); } /* * * @tc.name: EventBubbleTest010 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest010, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest010(); } /* * * @tc.name: EventBubbleTest011 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest011, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest011(); } /* * * @tc.name: EventBubbleTest012 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest012, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest012(); } /* * * @tc.name: EventBubbleTest013 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest013, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest013(); } /* * * @tc.name: EventBubbleTest014 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest014, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest014(); } /* * * @tc.name: EventBubbleTest015 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest015, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest015(); } /* * * @tc.name: EventBubbleTest016 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest016, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest016(); } /* * * @tc.name: EventBubbleTest017 * @tc.desc: Verify event bubble. * @tc.require: AR000F3PDN */ HWTEST_F(EventBubbleTddTest, EventBubbleTest017, TestSize.Level1) { EventBubbleTddTest::EventBubbleTest017(); } #endif // TDD_ASSERTIONS } // namespace ACELite } // namespace OHOS
35.482252
116
0.503415
[ "render" ]
e90a48bb4420fc631b3d6bca104772ae5a6e6cf2
3,689
cpp
C++
drivers/serveravailability/watchdog/power.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/serveravailability/watchdog/power.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/serveravailability/watchdog/power.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1991 - 2001 Microsoft Corporation Module Name: ##### ##### ## # ## ##### ##### #### ##### ##### ## ## ## ## ## ### ## ## ## ## ## # ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## # # ## ##### ##### ## ## ## ## ## ##### ## ## ### ### ## #### ## ##### ##### ## ## ## ### ### ## ## ## ## ## # ## ## ## ##### ## ## ##### ## ## ## #### ## ## Abstract: This module process all power management IRPs. Author: Wesley Witt (wesw) 1-Oct-2001 Environment: Kernel mode only. Notes: --*/ #include "internal.h" #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE,WdPower) #endif NTSTATUS WdPower( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) /*++ Routine Description: Arguments: DeviceObject - a pointer to the object that represents the device that I/O is to be done on. Irp - a pointer to the I/O Request Packet for this request. Return Value: --*/ { NTSTATUS Status = STATUS_SUCCESS; PDEVICE_EXTENSION DeviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); ULONG TimeoutValue; switch (IrpSp->MinorFunction) { case IRP_MN_WAIT_WAKE: case IRP_MN_POWER_SEQUENCE: case IRP_MN_QUERY_POWER: Status = STATUS_SUCCESS; break; case IRP_MN_SET_POWER: switch (IrpSp->Parameters.Power.State.SystemState) { case PowerSystemSleeping1: // // The system is being suspended // WdHandlerStopTimer( DeviceExtension ); break; case PowerSystemHibernate: // // The system is hibernating // WdHandlerStopTimer( DeviceExtension ); break; case PowerSystemWorking: // // The system is waking up from suspend/hibernate // WdHandlerStartTimer( DeviceExtension ); break; case PowerSystemShutdown: // // The system is shutting down normally // if (ShutdownCountTime > MIN_TIMEOUT_VALUE) { TimeoutValue = ShutdownCountTime; } else { TimeoutValue = (ULONG)DeviceExtension->MaxCount; } WdHandlerSetTimeoutValue( DeviceExtension, TimeoutValue, TRUE ); switch (IrpSp->Parameters.Power.ShutdownType) { case PowerActionShutdownOff: TimeoutValue = 1; break; case PowerActionShutdownReset: TimeoutValue = 0; break; } WdHandlerSetTriggerAction( DeviceExtension, TimeoutValue ); break; } Status = STATUS_SUCCESS; break; default: Status = Irp->IoStatus.Status; break; } Irp->IoStatus.Status = Status; PoStartNextPowerIrp(Irp); IoSkipCurrentIrpStackLocation( Irp ); return PoCallDriver( DeviceExtension->TargetObject, Irp ); }
28.160305
91
0.443752
[ "object" ]
e90b83127f1ed8c8b62d6a398179250fbbfb76fa
10,940
cpp
C++
inference-engine/thirdparty/fluid/modules/gapi/src/compiler/gmodelbuilder.cpp
shinh/dldt
693ab4e79a428e0801f17f4511b129a3fa8f4a62
[ "Apache-2.0" ]
1
2021-02-20T21:48:36.000Z
2021-02-20T21:48:36.000Z
inference-engine/thirdparty/fluid/modules/gapi/src/compiler/gmodelbuilder.cpp
erinpark33/dldt
edd86d090592f7779f4dbb2681546e1f4e81284f
[ "Apache-2.0" ]
null
null
null
inference-engine/thirdparty/fluid/modules/gapi/src/compiler/gmodelbuilder.cpp
erinpark33/dldt
edd86d090592f7779f4dbb2681546e1f4e81284f
[ "Apache-2.0" ]
1
2018-12-14T07:52:51.000Z
2018-12-14T07:52:51.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018-2019 Intel Corporation //////////////////////////////////////////////////////////////////////////////// // // FIXME: "I personally hate this file" // - Dmitry // //////////////////////////////////////////////////////////////////////////////// #include "precomp.hpp" #include <utility> // tuple #include <stack> // stack #include <vector> // vector #include <unordered_set> // unordered_set #include <type_traits> // is_same #include <ade/util/zip_range.hpp> // util::indexed #include "api/gapi_priv.hpp" // GOrigin #include "api/gproto_priv.hpp" // descriptor_of and other GProtoArg-related #include "api/gcall_priv.hpp" #include "api/gnode_priv.hpp" #include "compiler/gmodelbuilder.hpp" namespace { // TODO: move to helpers and cover with internal tests? template<typename T> struct GVisited { typedef std::unordered_set<T> VTs; bool visited(const T& t) const { return m_visited.find(t) != m_visited.end(); } void visit (const T& t) { m_visited.insert(t); } const VTs& visited() const { return m_visited; } private: VTs m_visited; }; template<typename T, typename U = T> struct GVisitedTracker: protected GVisited<T> { typedef std::vector<U> TUs; void visit(const T& t, const U& u) { GVisited<T>::visit(t); m_tracked.push_back(u); } const TUs& tracked() const { return m_tracked; } using GVisited<T>::visited; private: TUs m_tracked; }; } // namespace cv::gimpl::Unrolled cv::gimpl::unrollExpr(const GProtoArgs &ins, const GProtoArgs &outs) { // FIXME: Who's gonna check if ins/outs are not EMPTY? // FIXME: operator== for GObjects? (test if the same object or not) using GObjId = const cv::GOrigin*; GVisitedTracker<const GNode::Priv*, cv::GNode> ops; GVisited<GObjId> reached_sources; cv::GOriginSet origins; // Cache input argument objects for a faster look-up // While the only reliable way to identify a Data object is Origin // (multiple data objects may refer to the same Origin as result of // multuple yield() calls), input objects can be uniquely identified // by its `priv` address. Here we rely on this to verify if the expression // we unroll actually matches the protocol specified to us by user. std::unordered_set<GObjId> in_objs_p; for (const auto& in_obj : ins) { // Objects are guarnateed to remain alive while this method // is working, so it is safe to keep pointers here and below in_objs_p.insert(&proto::origin_of(in_obj)); } // Recursive expression traversal std::stack<cv::GProtoArg> data_objs(std::deque<cv::GProtoArg>(outs.begin(), outs.end())); while (!data_objs.empty()) { const auto obj = data_objs.top(); const auto &obj_p = proto::origin_of(obj); data_objs.pop(); const auto &origin = obj_p; origins.insert(origin); // TODO: Put Object description here later on // If this Object is listed in the protocol, don't dive deeper (even // if it is in fact a result of operation). Our computation is // bounded by this data slot, so terminate this recursion path early. if (in_objs_p.find(&obj_p) != in_objs_p.end()) { reached_sources.visit(&obj_p); continue; } const cv::GNode &node = origin.node; switch (node.shape()) { case cv::GNode::NodeShape::EMPTY: // TODO: Own exception type? util::throw_error(std::logic_error("Empty node reached!")); break; case cv::GNode::NodeShape::PARAM: case cv::GNode::NodeShape::CONST_BOUNDED: // No preceding operation to this data object - so the data object is either a GComputation // parameter or a constant (compile-time) value // Record it to check if protocol matches expression tree later if (!reached_sources.visited(&obj_p)) reached_sources.visit(&obj_p); break; case cv::GNode::NodeShape::CALL: if (!ops.visited(&node.priv())) { // This operation hasn't been visited yet - mark it so, // then add its operands to stack to continue recursion. ops.visit(&node.priv(), node); const cv::GCall& call = origin.node.call(); const cv::GCall::Priv& call_p = call.priv(); // Put the outputs object description of the node // so that they are not lost if they are not consumed by other operations for (const auto &it : ade::util::indexed(call_p.m_k.outShapes)) { std::size_t port = ade::util::index(it); GShape shape = ade::util::value(it); GOrigin org { shape, node, port}; origins.insert(org); } for (const auto &arg : call_p.m_args) { if (proto::is_dynamic(arg)) { data_objs.push(proto::rewrap(arg)); // Dive deeper } } } break; default: // Unsupported node shape GAPI_Assert(false); break; } } // Check if protocol mentions data_objs which weren't reached during traversal const auto missing_reached_sources = [&reached_sources](GObjId p) { return reached_sources.visited().find(p) == reached_sources.visited().end(); }; if (ade::util::any_of(in_objs_p, missing_reached_sources)) { // TODO: Own exception type or a return code? util::throw_error(std::logic_error("Data object listed in Protocol " "wasn\'t reached during unroll")); } // Check if there endpoint (parameter) data_objs which are not listed in protocol const auto missing_in_proto = [&in_objs_p](GObjId p) { return p->node.shape() != cv::GNode::NodeShape::CONST_BOUNDED && in_objs_p.find(p) == in_objs_p.end(); }; if (ade::util::any_of(reached_sources.visited(), missing_in_proto)) { // TODO: Own exception type or a return code? util::throw_error(std::logic_error("Data object reached during unroll " "wasn\'t found in Protocol")); } return cv::gimpl::Unrolled{ops.tracked(), origins}; } cv::gimpl::GModelBuilder::GModelBuilder(ade::Graph &g) : m_g(g) { } cv::gimpl::GModelBuilder::ProtoSlots cv::gimpl::GModelBuilder::put(const GProtoArgs &ins, const GProtoArgs &outs) { const auto unrolled = cv::gimpl::unrollExpr(ins, outs); // First, put all operations and its arguments into graph. for (const auto &op_expr_node : unrolled.all_ops) { GAPI_Assert(op_expr_node.shape() == GNode::NodeShape::CALL); const GCall& call = op_expr_node.call(); const GCall::Priv& call_p = call.priv(); ade::NodeHandle call_h = put_OpNode(op_expr_node); for (const auto &it : ade::util::indexed(call_p.m_args)) { const auto in_port = ade::util::index(it); const auto& in_arg = ade::util::value(it); if (proto::is_dynamic(in_arg)) { ade::NodeHandle data_h = put_DataNode(proto::origin_of(in_arg)); cv::gimpl::GModel::linkIn(m_g, call_h, data_h, in_port); } } } // Then iterate via all "origins", instantiate (if not yet) Data graph nodes // and connect these nodes with their producers in graph for (const auto &origin : unrolled.all_data) { const cv::GNode& prod = origin.node; GAPI_Assert(prod.shape() != cv::GNode::NodeShape::EMPTY); ade::NodeHandle data_h = put_DataNode(origin); if (prod.shape() == cv::GNode::NodeShape::CALL) { ade::NodeHandle call_h = put_OpNode(prod); cv::gimpl::GModel::linkOut(m_g, call_h, data_h, origin.port); } } // Mark graph data nodes as INPUTs and OUTPUTs respectively (according to the protocol) for (const auto &arg : ins) { ade::NodeHandle nh = put_DataNode(proto::origin_of(arg)); m_g.metadata(nh).get<Data>().storage = Data::Storage::INPUT; } for (const auto &arg : outs) { ade::NodeHandle nh = put_DataNode(proto::origin_of(arg)); m_g.metadata(nh).get<Data>().storage = Data::Storage::OUTPUT; } // And, finally, store data object layout in meta m_g.metadata().set(Layout{m_graph_data}); // After graph is generated, specify which data objects are actually // computation entry/exit points. using NodeDescr = std::pair<std::vector<RcDesc>, std::vector<ade::NodeHandle> >; const auto get_proto_slots = [&](const GProtoArgs &proto) -> NodeDescr { NodeDescr slots; slots.first.reserve(proto.size()); slots.second.reserve(proto.size()); for (const auto &arg : proto) { ade::NodeHandle nh = put_DataNode(proto::origin_of(arg)); const auto &desc = m_g.metadata(nh).get<Data>(); //These extra empty {} are to please GCC (-Wmissing-field-initializers) slots.first.push_back(RcDesc{desc.rc, desc.shape, {}}); slots.second.push_back(nh); } return slots; }; auto in_slots = get_proto_slots(ins); auto out_slots = get_proto_slots(outs); return ProtoSlots{in_slots.first, out_slots.first, in_slots.second, out_slots.second}; } ade::NodeHandle cv::gimpl::GModelBuilder::put_OpNode(const cv::GNode &node) { const auto& node_p = node.priv(); const auto it = m_graph_ops.find(&node_p); if (it == m_graph_ops.end()) { GAPI_Assert(node.shape() == GNode::NodeShape::CALL); const auto &call_p = node.call().priv(); auto nh = cv::gimpl::GModel::mkOpNode(m_g, call_p.m_k, call_p.m_args, node_p.m_island); m_graph_ops[&node_p] = nh; return nh; } else return it->second; } // FIXME: rename to get_DataNode (and same for Op) ade::NodeHandle cv::gimpl::GModelBuilder::put_DataNode(const GOrigin &origin) { const auto it = m_graph_data.find(origin); if (it == m_graph_data.end()) { auto nh = cv::gimpl::GModel::mkDataNode(m_g, origin); m_graph_data[origin] = nh; return nh; } else return it->second; }
35.751634
103
0.587934
[ "object", "shape", "vector" ]