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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
abc21d602e79c9f7a517cea4006533343d639167 | 1,031 | hpp | C++ | HomeFries/AAPLHashBytes.hpp | bgerstle/HomeFries | 0d28e22e60f7046c5e80bf7371754a9d41c589be | [
"MIT"
] | null | null | null | HomeFries/AAPLHashBytes.hpp | bgerstle/HomeFries | 0d28e22e60f7046c5e80bf7371754a9d41c589be | [
"MIT"
] | null | null | null | HomeFries/AAPLHashBytes.hpp | bgerstle/HomeFries | 0d28e22e60f7046c5e80bf7371754a9d41c589be | [
"MIT"
] | null | null | null | #import <Foundation/Foundation.h>
// extracted apple implementation
// http://opensource.apple.com/source/CF/CF-550/CFUtilities.c
#define ELF_STEP(B) T1 = (H << 4) + B; T2 = T1 & 0xF0000000; if (T2) T1 ^= (T2 >> 24); T1 &= (~T2); H = T1;
static NSUInteger AAPLHashBytes(uint8_t *bytes, CFIndex length) {
/* The ELF hash algorithm, used in the ELF object file format */
UInt32 H = 0, T1, T2;
CFIndex rem = length;
while (3 < rem) {
ELF_STEP(bytes[length - rem]);
ELF_STEP(bytes[length - rem + 1]);
ELF_STEP(bytes[length - rem + 2]);
ELF_STEP(bytes[length - rem + 3]);
rem -= 4;
}
switch (rem) {
case 3: ELF_STEP(bytes[length - 3]);
case 2: ELF_STEP(bytes[length - 2]);
case 1: ELF_STEP(bytes[length - 1]);
case 0: ;
}
return H;
}
#undef ELF_STEP
template <typename T, typename R=NSUInteger>
inline R AAPLHash(T x) {
#if 0
return [[NSData dataWithBytesNoCopy:&x length:sizeof(T) freeWhenDone:NO] hash];
#else
return AAPLHashBytes((uint8_t*)&x, sizeof(T));
#endif
}
| 28.638889 | 107 | 0.637245 | [
"object"
] |
abc819d1d3cccc49852460013d68856547470c3f | 2,604 | cc | C++ | testing/config_desktop.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | null | null | null | testing/config_desktop.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | null | null | null | testing/config_desktop.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google
//
// 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 "testing/config_desktop.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include "app/src/include/firebase/internal/mutex.h"
#include "flatbuffers/idl.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "testing/config.h"
#include "testing/testdata_config_generated.h"
namespace firebase {
namespace testing {
namespace cppsdk {
// We keep this raw data in order to be able to return it back for merge.
static uint8_t* g_test_data_config = nullptr;
// Mutex to make sure we don't delete the pointer while someone else is reading.
static Mutex testing_mutex; // NOLINT
// List of all the test data we've used so far, so we can clean it up later.
// (we can't delete it when it's replaced because old threads might still
// be looking at it.)
static std::vector<uint8_t*> g_all_test_data; // NOLINT
const ConfigRow* ConfigGet(const char* fake) {
MutexLock lock(testing_mutex);
if (g_test_data_config == nullptr) {
ADD_FAILURE() << "No test data at all";
assert(false);
return nullptr;
}
const TestDataConfig* config = GetTestDataConfig(g_test_data_config);
// LookupByKey() does not work because the data passed in may not conform. So
// we just iterate over the test data.
for (const ConfigRow* row : *(config->config())) {
if (strcmp(row->fake()->c_str(), fake) == 0) {
return row;
}
}
return nullptr;
}
namespace internal {
void ConfigSetImpl(const uint8_t* test_data_binary,
flatbuffers::uoffset_t size) {
MutexLock lock(testing_mutex);
if (test_data_binary != nullptr && size > 0) {
g_test_data_config = new uint8_t[size];
memcpy(g_test_data_config, test_data_binary, size);
g_all_test_data.push_back(g_test_data_config);
} else {
g_test_data_config = nullptr;
for (int i = 0; i < g_all_test_data.size(); i++) {
delete[] g_all_test_data[i];
}
g_all_test_data.clear();
}
}
} // namespace internal
} // namespace cppsdk
} // namespace testing
} // namespace firebase
| 31.756098 | 80 | 0.712366 | [
"vector"
] |
abc918266d35577f232c48a5bec3c43e1bd1cd2f | 4,362 | cxx | C++ | Libs/Widgets/GUI/MidasCommunityTreeItem.cxx | midasplatform/MidasClient | 728d4a5969691b54b7d0efd2dbad5a4df85d1a0e | [
"Apache-2.0"
] | null | null | null | Libs/Widgets/GUI/MidasCommunityTreeItem.cxx | midasplatform/MidasClient | 728d4a5969691b54b7d0efd2dbad5a4df85d1a0e | [
"Apache-2.0"
] | null | null | null | Libs/Widgets/GUI/MidasCommunityTreeItem.cxx | midasplatform/MidasClient | 728d4a5969691b54b7d0efd2dbad5a4df85d1a0e | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2011 Kitware Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "MidasCommunityTreeItem.h"
#include "MidasCollectionTreeItem.h"
#include "midasStandardIncludes.h"
#include "MidasTreeModel.h"
#include <mdoCommunity.h>
#include <iostream>
#include <QPixmap>
#include <QStyle>
#include <QModelIndex>
MidasCommunityTreeItem::MidasCommunityTreeItem(const QList<QVariant> & itemData, MidasTreeModel* model,
MidasTreeItem* parent)
: MidasTreeItem(itemData, model, parent)
{
m_Community = NULL;
}
MidasCommunityTreeItem::~MidasCommunityTreeItem()
{
}
void MidasCommunityTreeItem::SetCommunity(mdo::Community* community)
{
m_Community = community;
}
int MidasCommunityTreeItem::GetType() const
{
return midasResourceType::COMMUNITY;
}
int MidasCommunityTreeItem::GetId() const
{
return this->m_Community->GetId();
}
std::string MidasCommunityTreeItem::GetUuid() const
{
return m_Community->GetUuid();
}
void MidasCommunityTreeItem::Populate(QModelIndex parent)
{
if( !m_Community )
{
std::cerr << "Community not set" << std::endl;
return;
}
// Add the collections for the community
std::vector<mdo::Collection *>::const_iterator itCol = m_Community->GetCollections().begin();
int row = 0;
while( itCol != m_Community->GetCollections().end() )
{
QList<QVariant> name;
name << (*itCol)->GetName().c_str();
MidasCollectionTreeItem* collection = new MidasCollectionTreeItem(name, m_Model, this);
collection->SetClientResource(m_ClientResource);
collection->SetCollection(*itCol);
this->AppendChild(collection);
QModelIndex index = m_Model->index(row, 0, parent);
m_Model->RegisterResource( (*itCol)->GetUuid(), index);
if( this->IsDynamicFetch() )
{
collection->SetFetchedChildren(false);
collection->SetDynamicFetch(true);
}
else
{
collection->Populate(index);
}
if( (*itCol)->IsDirty() )
{
collection->SetDecorationRole(MidasTreeItem::Dirty);
}
itCol++;
row++;
}
// Add the subcommunities for the community
std::vector<mdo::Community *>::const_iterator itCom = m_Community->GetCommunities().begin();
while( itCom != m_Community->GetCommunities().end() )
{
QList<QVariant> name;
name << (*itCom)->GetName().c_str();
MidasCommunityTreeItem* community = new MidasCommunityTreeItem(name, m_Model, this);
community->SetClientResource(m_ClientResource);
community->SetCommunity(*itCom);
this->AppendChild(community);
QModelIndex index = m_Model->index(row, 0, parent);
m_Model->RegisterResource( (*itCom)->GetUuid(), index);
if( this->IsDynamicFetch() )
{
community->SetDynamicFetch(true);
}
if( !m_ClientResource ) // server gives us subcommunities and collections;
// client only gives top level
{
community->Populate(index);
}
if( (*itCom)->IsDirty() )
{
community->SetDecorationRole(MidasTreeItem::Dirty);
}
itCom++;
row++;
}
if( !this->IsDynamicFetch() )
{
this->SetFetchedChildren( true );
}
}
void MidasCommunityTreeItem::UpdateDisplayName()
{
QVariant name = this->GetCommunity()->GetName().c_str();
this->SetData(name, 0);
}
void MidasCommunityTreeItem::RemoveFromTree()
{
}
mdo::Community * MidasCommunityTreeItem::GetCommunity() const
{
return m_Community;
}
mdo::Object * MidasCommunityTreeItem::GetObject() const
{
return m_Community;
}
bool MidasCommunityTreeItem::ResourceIsFetched() const
{
return m_Community->IsFetched();
}
| 26.925926 | 103 | 0.651994 | [
"object",
"vector",
"model"
] |
abcf7f12578bf9825d0527ddd1f0c63c6d64dbc5 | 10,654 | hpp | C++ | include/Newtonsoft/Json/Utilities/BidirectionalDictionary_2.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Utilities/BidirectionalDictionary_2.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Utilities/BidirectionalDictionary_2.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IDictionary`2<TKey, TValue>
template<typename TKey, typename TValue>
class IDictionary_2;
// Forward declaring type: IEqualityComparer`1<T>
template<typename T>
class IEqualityComparer_1;
}
// Completed forward declares
// Type namespace: Newtonsoft.Json.Utilities
namespace Newtonsoft::Json::Utilities {
// Forward declaring type: BidirectionalDictionary`2<TFirst, TSecond>
template<typename TFirst, typename TSecond>
class BidirectionalDictionary_2;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::Newtonsoft::Json::Utilities::BidirectionalDictionary_2, "Newtonsoft.Json.Utilities", "BidirectionalDictionary`2");
// Type namespace: Newtonsoft.Json.Utilities
namespace Newtonsoft::Json::Utilities {
// WARNING Size may be invalid!
// Autogenerated type: Newtonsoft.Json.Utilities.BidirectionalDictionary`2
// [TokenAttribute] Offset: FFFFFFFF
// [PreserveAttribute] Offset: 122B468
template<typename TFirst, typename TSecond>
class BidirectionalDictionary_2 : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private readonly System.Collections.Generic.IDictionary`2<TFirst,TSecond> _firstToSecond
// Size: 0x8
// Offset: 0x0
::System::Collections::Generic::IDictionary_2<TFirst, TSecond>* firstToSecond;
// Field size check
static_assert(sizeof(::System::Collections::Generic::IDictionary_2<TFirst, TSecond>*) == 0x8);
// private readonly System.Collections.Generic.IDictionary`2<TSecond,TFirst> _secondToFirst
// Size: 0x8
// Offset: 0x0
::System::Collections::Generic::IDictionary_2<TSecond, TFirst>* secondToFirst;
// Field size check
static_assert(sizeof(::System::Collections::Generic::IDictionary_2<TSecond, TFirst>*) == 0x8);
// private readonly System.String _duplicateFirstErrorMessage
// Size: 0x8
// Offset: 0x0
::StringW duplicateFirstErrorMessage;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private readonly System.String _duplicateSecondErrorMessage
// Size: 0x8
// Offset: 0x0
::StringW duplicateSecondErrorMessage;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
public:
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.IDictionary`2<TFirst,TSecond> _firstToSecond
::System::Collections::Generic::IDictionary_2<TFirst, TSecond>*& dyn__firstToSecond() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::dyn__firstToSecond");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_firstToSecond"))->offset;
return *reinterpret_cast<::System::Collections::Generic::IDictionary_2<TFirst, TSecond>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.IDictionary`2<TSecond,TFirst> _secondToFirst
::System::Collections::Generic::IDictionary_2<TSecond, TFirst>*& dyn__secondToFirst() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::dyn__secondToFirst");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_secondToFirst"))->offset;
return *reinterpret_cast<::System::Collections::Generic::IDictionary_2<TSecond, TFirst>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.String _duplicateFirstErrorMessage
::StringW& dyn__duplicateFirstErrorMessage() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::dyn__duplicateFirstErrorMessage");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_duplicateFirstErrorMessage"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.String _duplicateSecondErrorMessage
::StringW& dyn__duplicateSecondErrorMessage() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::dyn__duplicateSecondErrorMessage");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_duplicateSecondErrorMessage"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// public System.Void .ctor(System.Collections.Generic.IEqualityComparer`1<TFirst> firstEqualityComparer, System.Collections.Generic.IEqualityComparer`1<TSecond> secondEqualityComparer)
// Offset: 0xFFFFFFFFFFFFFFFF
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BidirectionalDictionary_2<TFirst, TSecond>* New_ctor(::System::Collections::Generic::IEqualityComparer_1<TFirst>* firstEqualityComparer, ::System::Collections::Generic::IEqualityComparer_1<TSecond>* secondEqualityComparer) {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BidirectionalDictionary_2<TFirst, TSecond>*, creationType>(firstEqualityComparer, secondEqualityComparer)));
}
// public System.Void .ctor(System.Collections.Generic.IEqualityComparer`1<TFirst> firstEqualityComparer, System.Collections.Generic.IEqualityComparer`1<TSecond> secondEqualityComparer, System.String duplicateFirstErrorMessage, System.String duplicateSecondErrorMessage)
// Offset: 0xFFFFFFFFFFFFFFFF
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BidirectionalDictionary_2<TFirst, TSecond>* New_ctor(::System::Collections::Generic::IEqualityComparer_1<TFirst>* firstEqualityComparer, ::System::Collections::Generic::IEqualityComparer_1<TSecond>* secondEqualityComparer, ::StringW duplicateFirstErrorMessage, ::StringW duplicateSecondErrorMessage) {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BidirectionalDictionary_2<TFirst, TSecond>*, creationType>(firstEqualityComparer, secondEqualityComparer, duplicateFirstErrorMessage, duplicateSecondErrorMessage)));
}
// public System.Void Set(TFirst first, TSecond second)
// Offset: 0xFFFFFFFFFFFFFFFF
void Set(TFirst first, TSecond second) {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::Set");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Set", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(first), ::il2cpp_utils::ExtractType(second)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, first, second);
}
// public System.Boolean TryGetByFirst(TFirst first, out TSecond second)
// Offset: 0xFFFFFFFFFFFFFFFF
bool TryGetByFirst(TFirst first, ByRef<TSecond> second) {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::TryGetByFirst");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryGetByFirst", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(first), ::il2cpp_utils::ExtractIndependentType<TSecond&>()})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, first, byref(second));
}
// public System.Boolean TryGetBySecond(TSecond second, out TFirst first)
// Offset: 0xFFFFFFFFFFFFFFFF
bool TryGetBySecond(TSecond second, ByRef<TFirst> first) {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::TryGetBySecond");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryGetBySecond", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(second), ::il2cpp_utils::ExtractIndependentType<TFirst&>()})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, second, byref(first));
}
// public System.Void .ctor()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BidirectionalDictionary_2<TFirst, TSecond>* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Utilities::BidirectionalDictionary_2::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BidirectionalDictionary_2<TFirst, TSecond>*, creationType>()));
}
}; // Newtonsoft.Json.Utilities.BidirectionalDictionary`2
// Could not write size check! Type: Newtonsoft.Json.Utilities.BidirectionalDictionary`2 is generic, or has no fields that are valid for size checks!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 68.294872 | 312 | 0.759715 | [
"object",
"vector"
] |
abd1e0b329e91e60198418b32b52ff2bd206ede4 | 11,072 | cpp | C++ | FireworksParticleSystem/CustomModel.cpp | TRBrown/Work_Examples | 34b0d8a1eb51488f36ca8141a4eea89a2ff7c17f | [
"MIT"
] | null | null | null | FireworksParticleSystem/CustomModel.cpp | TRBrown/Work_Examples | 34b0d8a1eb51488f36ca8141a4eea89a2ff7c17f | [
"MIT"
] | null | null | null | FireworksParticleSystem/CustomModel.cpp | TRBrown/Work_Examples | 34b0d8a1eb51488f36ca8141a4eea89a2ff7c17f | [
"MIT"
] | null | null | null | #include "DXUT.h"
#include "CustomModel.h"
IDirect3DVertexDeclaration9* CustomModel::NMapVertex::Decl = 0;
CustomModel::CustomModel(std::string strMesh, std::string strFX, IDirect3DDevice9* pd3dDevice)
{
m_sMeshFN = strMesh;
m_sFXFN = strFX;
m_pD3dDevice = pd3dDevice;
m_bError = false;
Loadmodel();
Loadfx();
}
CustomModel::CustomModel(std::string strMesh, IDirect3DDevice9* pd3dDevice)
{
m_sMeshFN = strMesh;
m_pD3dDevice = pd3dDevice;
m_bError = false;
Loadmodel();
}
CustomModel::CustomModel(IDirect3DDevice9* pd3dDevice)
{
m_pD3dDevice = pd3dDevice;
m_bError = false;
//Init Vertex Declarations
D3DVERTEXELEMENT9 NMapVertexElements[] =
{
{0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
{0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};
hr = m_pD3dDevice->CreateVertexDeclaration(NMapVertexElements, &NMapVertex::Decl);
}
CustomModel::CustomModel(const CustomModel & rhs)
{
m_sMeshFN = rhs.m_sMeshFN;
m_sFXFN = rhs.m_sFXFN;
m_pD3dDevice = rhs.m_pD3dDevice;
m_bError = false;
Loadmodel();
Loadfx();
m_pLight1 = rhs.m_pLight1;
m_mScale = rhs.m_mScale;
m_mRotationX = rhs.m_mRotationX;
m_mRotationY = rhs.m_mRotationY;
m_mRotationZ = rhs.m_mRotationZ;
m_mTranslation = rhs.m_mTranslation;
m_mWorld = rhs.m_mWorld;
m_mView = rhs.m_mView;
m_mProjection = rhs.m_mProjection;
}
CustomModel::~CustomModel()
{
m_pMesh->Release();
m_pMesh = 0;
m_pNormalmapTex->Release();
m_pNormalmapTex = 0;
for( UINT i = 0; i < m_dNumMaterials; i++ )
SAFE_RELEASE( m_pMeshTextures[i] );
SAFE_DELETE_ARRAY( m_pMeshTextures );
m_pMeshTextures = 0;
SAFE_DELETE_ARRAY( m_pMeshMaterials );
m_pMeshMaterials = 0;
if( m_pEffect != 0 )
m_pEffect->Release();
m_pEffect = 0;
}
void CustomModel::Loadmodel()
{
IDirect3DTexture9* m_pDefaultTex; // A default texture
ID3DXBuffer* m_pMaterialBuffer;
m_dNumMaterials = NULL;
ID3DXMesh* tempMesh = 0;
ID3DXMesh* clonedmesh = 0;
D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE];
UINT numElems = 0;
ID3DXBuffer* cleanbuffer = 0;
//Load Normal Map
int size = MultiByteToWideChar(CP_ACP, 0, m_sNormalMapFN.c_str(), -1, 0, 0);
m_pWNormalMapFN = (wchar_t*)malloc(size * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, m_sNormalMapFN.c_str(), -1, m_pWNormalMapFN, size);
if( FAILED( hr = D3DXCreateTextureFromFile(m_pD3dDevice, m_pWNormalMapFN, &m_pNormalmapTex)))
{
m_bError = true;
}
//Creates a default texture of white
hr = m_pD3dDevice->CreateTexture( 1, 1, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &m_pDefaultTex, NULL );
D3DLOCKED_RECT lr;
m_pDefaultTex->LockRect( 0, &lr, NULL, 0 );
*( LPDWORD )lr.pBits = D3DCOLOR_RGBA( 255, 255, 255, 255 );
m_pDefaultTex->UnlockRect( 0 );
//Load Mesh
size = MultiByteToWideChar(CP_ACP, 0, m_sMeshFN.c_str(), -1, 0, 0);
m_pWMeshFN = (wchar_t*)malloc(size * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, m_sMeshFN.c_str(), -1, m_pWMeshFN, size);
//TNB basis Vectors
//Load Mesh into temp
if( FAILED( hr = D3DXLoadMeshFromX(m_pWMeshFN, D3DXMESH_SYSTEMMEM,
m_pD3dDevice, NULL,
&m_pMaterialBuffer,NULL, &m_dNumMaterials,
&tempMesh)) )
{
const WCHAR* test = DXGetErrorString(hr);
m_bError = true;
}
hr = NMapVertex::Decl->GetDeclaration(elems, &numElems);
hr = tempMesh->CloneMesh(D3DXMESH_MANAGED, elems, m_pD3dDevice, &clonedmesh);
//Mesh Clean
DWORD* adjacency = new DWORD[3 * clonedmesh->GetNumFaces()];
DWORD* adjacencyOut = new DWORD[3 * clonedmesh->GetNumFaces()];
hr = clonedmesh->GenerateAdjacency( 1e-4f, adjacency );
tempMesh->Release();
tempMesh = 0;
//tempmesh is now cleaned :/
hr = D3DXCleanMesh( D3DXCLEAN_BOWTIES, clonedmesh, adjacency, &tempMesh, adjacencyOut, &cleanbuffer );
//End Mesh clean
hr = D3DXComputeTangentFrameEx(tempMesh,
D3DDECLUSAGE_TEXCOORD, 0,
D3DDECLUSAGE_BINORMAL, 0,
D3DDECLUSAGE_TANGENT, 0,
D3DDECLUSAGE_NORMAL, 0,
0,
adjacencyOut,
0.01f, 0.25f, 0.01f,
&m_pMesh,
0);
D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)m_pMaterialBuffer->GetBufferPointer();
m_pMeshMaterials = new D3DMATERIAL9[m_dNumMaterials];
m_pMeshTextures = new LPDIRECT3DTEXTURE9[m_dNumMaterials];
//load the materials and textures into the texture buffer
for (DWORD i=0; i<m_dNumMaterials; i++)
{
// Copy the material
m_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;
// Create the texture if it exists - it may not
m_pMeshTextures[i] = NULL;
// Get a path to the texture
if( d3dxMaterials[i].pTextureFilename != NULL )
{
char fnTemp[MAX_PATH];
strcpy_s(fnTemp, m_pCModelLocation);
strcat_s(fnTemp,d3dxMaterials[i].pTextureFilename);
WCHAR wszBuf[MAX_PATH];
MultiByteToWideChar( CP_ACP, 0, fnTemp, -1, wszBuf, MAX_PATH );
wszBuf[MAX_PATH - 1] = L'\0';
// Load the texture
D3DXCreateTextureFromFile( m_pD3dDevice, wszBuf, &m_pMeshTextures[i] );
}
else
{
// Use the default texture
m_pMeshTextures[i] = m_pDefaultTex;
m_pMeshTextures[i]->AddRef();
}
}
//
DWORD numFaces = m_pMesh->GetNumFaces();
m_pFaces = new FaceVertexs[numFaces];
CUSTOMVERTEX *pVertices;
WORD* pIndices;
m_pMesh->LockIndexBuffer(D3DLOCK_READONLY, (VOID**)&pIndices);
m_pMesh->LockVertexBuffer(D3DLOCK_READONLY,(VOID**)&pVertices);
for ( DWORD face = 0; face < numFaces ; face++ )
{
m_pFaces[face].vert1 = pVertices[pIndices[3*face+0]].POSITION;
m_pFaces[face].vert2 = pVertices[pIndices[3*face+1]].POSITION;
m_pFaces[face].vert3 = pVertices[pIndices[3*face+2]].POSITION;
}
m_pMesh->UnlockVertexBuffer();
m_pMesh->UnlockIndexBuffer();
//Object cleanup
m_pMaterialBuffer->Release();
m_pMaterialBuffer = 0;
m_pDefaultTex->Release();
m_pDefaultTex = 0;
tempMesh->Release();
tempMesh = 0;
clonedmesh->Release();
clonedmesh = 0;
if(cleanbuffer != 0)
{
cleanbuffer->Release();
cleanbuffer = 0;
}
delete [] adjacency;
delete [] adjacencyOut;
if(NMapVertex::Decl != 0)
{
NMapVertex::Decl->Release();
NMapVertex::Decl = 0;
}
};
void CustomModel::Loadfx()
{
int size = MultiByteToWideChar(CP_ACP, 0, m_sFXFN.c_str(), -1, 0, 0);
m_pWFXFN = (wchar_t*)_malloca(size * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, m_sFXFN.c_str(), -1, m_pWFXFN, size);
if( FAILED( hr = D3DXCreateEffectFromFile( m_pD3dDevice, m_pWFXFN, NULL, NULL,
D3DXSHADER_DEBUG, NULL, &m_pEffect, NULL ) ) )
{
m_bError = true;
}
};
void CustomModel::AssignParameters(D3DLIGHT9& light1, D3DLIGHT9& light2, const D3DXVECTOR3 *eye, const D3DMATRIX *view, const D3DMATRIX *proj)
{
m_pLight1 = &light1;
m_pLight2 = &light2;
m_mView = *view;
m_mProjection = *proj;
D3DXMATRIX mViewProjection = m_mView * m_mProjection;
D3DXMATRIX mWorldViewProjection = m_mWorld * mViewProjection;
D3DXMATRIX worldinverse;
//Effect parameter Block
m_pEffect->BeginParameterBlock();
D3DXVECTOR4 diff1v4( m_pLight1->Diffuse.r, m_pLight1->Diffuse.g, m_pLight1->Diffuse.b, m_pLight1->Diffuse.a );
D3DXVECTOR4 spec1v4( m_pLight1->Specular.r, m_pLight1->Specular.g, m_pLight1->Specular.b, m_pLight1->Specular.a );
D3DXVECTOR4 amb1v4( m_pLight1->Ambient.r, m_pLight1->Ambient.g, m_pLight1->Ambient.b, m_pLight1->Ambient.a );
D3DXVECTOR4 vec1Pos( m_pLight1->Position.x, m_pLight1->Position.y, m_pLight1->Position.z, 0.0f );
D3DXVECTOR4 diff2v4( m_pLight2->Diffuse.r, m_pLight2->Diffuse.g, m_pLight2->Diffuse.b, m_pLight2->Diffuse.a );
D3DXVECTOR4 spec2v4( m_pLight2->Specular.r, m_pLight2->Specular.g, m_pLight2->Specular.b, m_pLight2->Specular.a );
D3DXVECTOR4 amb2v4( m_pLight2->Ambient.r, m_pLight2->Ambient.g, m_pLight2->Ambient.b, m_pLight2->Ambient.a );
D3DXVECTOR4 vec2Dir( m_pLight2->Direction.x, m_pLight2->Direction.y, m_pLight2->Direction.z, 0.0f );
D3DXMatrixInverse(&worldinverse, 0, &m_mWorld);
D3DXVECTOR4 eyev4( eye->x, eye->y, eye->z, 1.0f );
m_pEffect->SetMatrix( "wMat", &m_mWorld);
m_pEffect->SetMatrix( "wvpMat", &mWorldViewProjection);
m_pEffect->SetMatrix( "wInvMat", &worldinverse);
m_pEffect->SetVector("vecLight1Pos",&vec1Pos);
m_pEffect->SetVector("vecLight1Amb",&amb1v4);
m_pEffect->SetVector("vecLight1Spec",&spec1v4);
m_pEffect->SetVector("vecLight1Diff",&diff1v4);
m_pEffect->SetVector("vecLight2Dir",&vec2Dir);
m_pEffect->SetVector("vecLight2Amb",&amb2v4);
m_pEffect->SetVector("vecLight2Spec",&spec2v4);
m_pEffect->SetVector("vecLight2Diff",&diff2v4);
m_pEffect->SetVector("vecEye",&eyev4);
m_hParameters = m_pEffect->EndParameterBlock();
}
void CustomModel::update()
{
D3DXMatrixTranslation(&m_mTranslation, m_v4Position.x, m_v4Position.y, m_v4Position.z);
//Matrix
D3DMATRIX RotationA = m_mRotationX * m_mRotationY * m_mRotationZ;
m_mWorld = m_mScale * RotationA * m_mTranslation;
}
void CustomModel::render()
{
unsigned int numOfPasses = 1;
unsigned int passIndex;
if( m_pEffect != NULL )
{
//Technique binds
D3DXHANDLE hTechnique = m_pEffect->GetTechniqueByName( "effect" );
m_pEffect->SetTechnique( hTechnique );
m_pEffect->ApplyParameterBlock( m_hParameters );
//Begin Effect/Shader
///////////////////////////////////
m_pEffect->Begin( &numOfPasses, 0 ); // start an active technique
// loop through all render passes in technique
for(passIndex = 0; passIndex < numOfPasses; ++passIndex)
{
m_pEffect->BeginPass(passIndex); // begin a pass, within active technique
for (DWORD i=0; i<m_dNumMaterials; i++)
{
// Set the material and texture for this subset
m_pD3dDevice->SetMaterial(&m_pMeshMaterials[i]);
m_pD3dDevice->SetTexture(0, m_pMeshTextures[i]);
m_pD3dDevice->SetTexture(1, m_pNormalmapTex);
D3DXVECTOR4 matDiff4( m_pMeshMaterials[i].Diffuse.r, m_pMeshMaterials[i].Diffuse.g, m_pMeshMaterials[i].Diffuse.b, m_pMeshMaterials[i].Diffuse.a );
m_pEffect->SetVector("matDiff",&matDiff4);
D3DXVECTOR4 matAmb4( m_pMeshMaterials[i].Ambient.r, m_pMeshMaterials[i].Ambient.g, m_pMeshMaterials[i].Ambient.b, m_pMeshMaterials[i].Ambient.a );
m_pEffect->SetVector("matAmb",&matAmb4);
D3DXVECTOR4 matSpec4( m_pMeshMaterials[i].Specular.r, m_pMeshMaterials[i].Specular.g, m_pMeshMaterials[i].Specular.b, m_pMeshMaterials[i].Specular.a );
m_pEffect->SetVector("matSpec",&matSpec4);
D3DXVECTOR4 matEmiss4( m_pMeshMaterials[i].Emissive.r, m_pMeshMaterials[i].Emissive.g, m_pMeshMaterials[i].Emissive.b, m_pMeshMaterials[i].Emissive.a );
m_pEffect->SetVector("matEmiss",&matEmiss4);
float matPower = m_pMeshMaterials[i].Power;
m_pEffect->SetFloat("matPower",matPower);
m_pEffect->CommitChanges();
// Draw the mesh subset
m_pMesh->DrawSubset( i );
}
m_pEffect->EndPass(); // signal end of rendering current pass
}
m_pEffect->End(); // signal end of rendering current technique
m_pEffect->DeleteParameterBlock( m_hParameters );
}
}; | 29.291005 | 157 | 0.725343 | [
"mesh",
"render",
"object"
] |
abd43b414a005e26e754bacaa5dd3935e2ef287a | 1,056 | cc | C++ | test/test-logreg.cc | cloudera/madlibport | e1a47822fbb69899fe602ef71c56f6c6dacc1340 | [
"Apache-2.0"
] | 10 | 2015-01-01T09:13:57.000Z | 2018-01-30T02:55:46.000Z | test/test-logreg.cc | cloudera/madlibport | e1a47822fbb69899fe602ef71c56f6c6dacc1340 | [
"Apache-2.0"
] | null | null | null | test/test-logreg.cc | cloudera/madlibport | e1a47822fbb69899fe602ef71c56f6c6dacc1340 | [
"Apache-2.0"
] | 4 | 2015-10-16T12:17:55.000Z | 2020-12-12T10:33:18.000Z | #include <cstdio>
#include "test-macros.h"
#include "bismarck-common.h"
template <class T>
T* BismarckAllocate(void* ignore, size_t len) {
return new T[len];
}
#include "logreg-inl.h"
using namespace hazy;
/*! Check that we're linked and can call a function :)
*/
int TEST_Logrinit() {
bismarck::bytea model;
bismarck::BismarckLogr<void*>::Init(NULL, &model);
EXPECT_EQ(model.str == NULL, true);
EXPECT_EQ(model.len, 0);
return 1;
}
/*! Allocate a simple model and take a few steps
*/
int TEST_LogrAlloc() {
//double mod[3] = {0, 0, 0};
double exa[3] = {1, 2, 1};
bismarck::bytea model;
bismarck::BismarckLogr<void*>::Init(NULL, &model);
bismarck::bytea ex = {(char*)exa, 3*sizeof(double)};
for (int k = 0; k < 100; k ++) {
bismarck::BismarckLogr<void*>::Step(NULL, ex, true, &model, 0.2, 0);
}
EXPECT_NEAR(bismarck::_LogrPredict<void*>(NULL, ex, model), 1.0, 0.05);
// next step shouldn't do anything since we use hinge loss
return 1;
}
int main() {
RUNTEST(TEST_Logrinit);
RUNTEST(TEST_LogrAlloc);
}
| 21.12 | 73 | 0.652462 | [
"model"
] |
abd6f39446076710b436ea42c9d2421a20d365bb | 3,583 | cpp | C++ | QuantExt/qle/models/exactbachelierimpliedvolatility.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | QuantExt/qle/models/exactbachelierimpliedvolatility.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | QuantExt/qle/models/exactbachelierimpliedvolatility.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2020 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.
*/
#include <qle/models/exactbachelierimpliedvolatility.hpp>
#include <ql/math/comparison.hpp>
#include <boost/math/distributions/normal.hpp>
namespace QuantExt {
using namespace QuantLib;
namespace {
static boost::math::normal_distribution<double> normal_dist;
Real phi(const Real x) { return boost::math::pdf(normal_dist, x); }
Real Phi(const Real x) { return boost::math::cdf(normal_dist, x); }
Real PhiTilde(const Real x) { return Phi(x) + phi(x) / x; }
Real inversePhiTilde(const Real PhiTildeStar) {
QL_REQUIRE(PhiTildeStar < 0.0, "inversePhiTilde(" << PhiTildeStar << "): negative argument required");
Real xbar;
if (PhiTildeStar < -0.001882039271) {
Real g = 1.0 / (PhiTildeStar - 0.5);
Real xibar = (0.032114372355 - g * g * (0.016969777977 - g * g * (2.6207332461E-3 - 9.6066952861E-5 * g * g))) /
(1.0 - g * g * (0.6635646938 - g * g * (0.14528712196 - 0.010472855461 * g * g)));
xbar = g * (0.3989422804014326 + xibar * g * g);
} else {
Real h = std::sqrt(-std::log(-PhiTildeStar));
xbar = (9.4883409779 - h * (9.6320903635 - h * (0.58556997323 + 2.1464093351 * h))) /
(1.0 - h * (0.65174820867 + h * (1.5120247828 + 6.6437847132E-5 * h)));
}
Real q = (PhiTilde(xbar) - PhiTildeStar) / phi(xbar);
Real xstar =
xbar + 3.0 * q * xbar * xbar * (2.0 - q * xbar * (2.0 + xbar * xbar)) /
(6.0 + q * xbar * (-12.0 + xbar * (6.0 * q + xbar * (-6.0 + q * xbar * (3.0 + xbar * xbar)))));
return xstar;
}
} // namespace
Real exactBachelierImpliedVolatility(Option::Type optionType, Real strike, Real forward, Real tte, Real bachelierPrice,
Real discount) {
Real theta = optionType == Option::Call ? 1.0 : -1.0;
// compound bechelierPrice, so that effectively discount = 1
bachelierPrice /= discount;
// handle case strike = forward
if (std::abs(strike - forward) < 1E-15) {
return bachelierPrice / (std::sqrt(tte) * phi(0.0));
}
// handle case strike != forward
Real timeValue = bachelierPrice - std::max(theta * (forward - strike), 0.0);
if (std::abs(timeValue) < 1E-15)
return 0.0;
QL_REQUIRE(timeValue > 0.0, "exactBachelierImpliedVolatility(theta="
<< theta << ",strike=" << strike << ",forward=" << forward << ",tte=" << tte
<< ",price=" << bachelierPrice << "): option price implies negative time value ("
<< timeValue << ")");
Real PhiTildeStar = -std::abs(timeValue / (strike - forward));
Real xstar = inversePhiTilde(PhiTildeStar);
Real impliedVol = std::abs((strike - forward) / (xstar * std::sqrt(tte)));
return impliedVol;
}
} // namespace QuantExt
| 38.117021 | 120 | 0.622383 | [
"model"
] |
abd77aeb5b18c23e4ddbc96c66759b3abe505314 | 2,541 | cpp | C++ | gearoenix/vulkan/sampler/gx-vk-smp-sampler.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/vulkan/sampler/gx-vk-smp-sampler.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/vulkan/sampler/gx-vk-smp-sampler.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #include "gx-vk-smp-sampler.hpp"
#ifdef GX_USE_VULKAN
#include "../../system/gx-sys-log.hpp"
#include "../device/gx-vk-dev-logical.hpp"
#include "../gx-vk-check.hpp"
gearoenix::vulkan::sampler::Sampler::Sampler(
std::shared_ptr<device::Logical> ld,
const render::texture::SamplerInfo& sampler_info) noexcept
: logical_device(std::move(ld))
{
VkSamplerCreateInfo info;
GX_SET_ZERO(info)
info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
info.magFilter = convert(sampler_info.mag_filter);
info.minFilter = convert(sampler_info.min_filter);
info.addressModeU = convert(sampler_info.wrap_r);
info.addressModeV = convert(sampler_info.wrap_s);
info.addressModeW = convert(sampler_info.wrap_t);
// TODO check for anisotropy support in device
info.anisotropyEnable = sampler_info.anisotropic_level == 0 ? VK_FALSE : VK_TRUE;
info.maxAnisotropy = sampler_info.anisotropic_level;
info.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
info.unnormalizedCoordinates = VK_FALSE;
info.compareEnable = VK_FALSE;
info.compareOp = VK_COMPARE_OP_ALWAYS;
info.mipmapMode = sampler_info.needs_mipmap() ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
info.mipLodBias = 0.0f;
info.minLod = 0.0f;
info.maxLod = 0.0f;
GX_VK_CHK_L(vkCreateSampler(logical_device->get_vulkan_data(), &info, nullptr, &vulkan_data))
}
gearoenix::vulkan::sampler::Sampler::~Sampler() noexcept
{
Loader::vkDestroySampler(logical_device->get_vulkan_data(), vulkan_data, nullptr);
}
VkFilter gearoenix::vulkan::sampler::Sampler::convert(const render::texture::Filter filter) noexcept
{
switch (filter) {
case render::texture::Filter::Linear:
case render::texture::Filter::LinearMipmapLinear:
case render::texture::Filter::LinearMipmapNearest:
return VK_FILTER_LINEAR;
case render::texture::Filter::Nearest:
case render::texture::Filter::NearestMipmapLinear:
case render::texture::Filter::NearestMipmapNearest:
return VK_FILTER_NEAREST;
default:
GX_UNIMPLEMENTED
}
}
VkSamplerAddressMode gearoenix::vulkan::sampler::Sampler::convert(const render::texture::Wrap wrap) noexcept
{
switch (wrap) {
case render::texture::Wrap::Repeat:
return VK_SAMPLER_ADDRESS_MODE_REPEAT;
case render::texture::Wrap::ClampToEdge:
return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
case render::texture::Wrap::Mirror:
return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
}
GX_UNEXPECTED
}
#endif | 37.367647 | 115 | 0.738686 | [
"render"
] |
abd815a2e1166399ee03abfc56643839dd6ff738 | 9,626 | cpp | C++ | YorozuyaGSLib/source/CMoveMapLimitInfoListDetail.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/CMoveMapLimitInfoListDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/CMoveMapLimitInfoListDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <CMoveMapLimitInfoListDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_ptr CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_next(nullptr);
Info::CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_clbk CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_user(nullptr);
Info::CMoveMapLimitInfoListCleanUp4_ptr CMoveMapLimitInfoListCleanUp4_next(nullptr);
Info::CMoveMapLimitInfoListCleanUp4_clbk CMoveMapLimitInfoListCleanUp4_user(nullptr);
Info::CMoveMapLimitInfoListGet6_ptr CMoveMapLimitInfoListGet6_next(nullptr);
Info::CMoveMapLimitInfoListGet6_clbk CMoveMapLimitInfoListGet6_user(nullptr);
Info::CMoveMapLimitInfoListInit8_ptr CMoveMapLimitInfoListInit8_next(nullptr);
Info::CMoveMapLimitInfoListInit8_clbk CMoveMapLimitInfoListInit8_user(nullptr);
Info::CMoveMapLimitInfoListLoad10_ptr CMoveMapLimitInfoListLoad10_next(nullptr);
Info::CMoveMapLimitInfoListLoad10_clbk CMoveMapLimitInfoListLoad10_user(nullptr);
Info::CMoveMapLimitInfoListLogIn12_ptr CMoveMapLimitInfoListLogIn12_next(nullptr);
Info::CMoveMapLimitInfoListLogIn12_clbk CMoveMapLimitInfoListLogIn12_user(nullptr);
Info::CMoveMapLimitInfoListLogOut14_ptr CMoveMapLimitInfoListLogOut14_next(nullptr);
Info::CMoveMapLimitInfoListLogOut14_clbk CMoveMapLimitInfoListLogOut14_user(nullptr);
Info::CMoveMapLimitInfoListLoop16_ptr CMoveMapLimitInfoListLoop16_next(nullptr);
Info::CMoveMapLimitInfoListLoop16_clbk CMoveMapLimitInfoListLoop16_user(nullptr);
Info::CMoveMapLimitInfoListRequest18_ptr CMoveMapLimitInfoListRequest18_next(nullptr);
Info::CMoveMapLimitInfoListRequest18_clbk CMoveMapLimitInfoListRequest18_user(nullptr);
Info::CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_ptr CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_next(nullptr);
Info::CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_clbk CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_user(nullptr);
void CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_wrapper(struct CMoveMapLimitInfoList* _this)
{
CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_user(_this, CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_next);
};
void CMoveMapLimitInfoListCleanUp4_wrapper(struct CMoveMapLimitInfoList* _this)
{
CMoveMapLimitInfoListCleanUp4_user(_this, CMoveMapLimitInfoListCleanUp4_next);
};
struct CMoveMapLimitInfo* CMoveMapLimitInfoListGet6_wrapper(struct CMoveMapLimitInfoList* _this, int iLimitType, int iMapInx, unsigned int dwStoreRecordIndex)
{
return CMoveMapLimitInfoListGet6_user(_this, iLimitType, iMapInx, dwStoreRecordIndex, CMoveMapLimitInfoListGet6_next);
};
bool CMoveMapLimitInfoListInit8_wrapper(struct CMoveMapLimitInfoList* _this, struct std::vector<int,std::allocator<int> >* vecRightTypeList)
{
return CMoveMapLimitInfoListInit8_user(_this, vecRightTypeList, CMoveMapLimitInfoListInit8_next);
};
void CMoveMapLimitInfoListLoad10_wrapper(struct CMoveMapLimitInfoList* _this, struct CPlayer* pkPlayer, struct CMoveMapLimitRightInfo* pkRight)
{
CMoveMapLimitInfoListLoad10_user(_this, pkPlayer, pkRight, CMoveMapLimitInfoListLoad10_next);
};
void CMoveMapLimitInfoListLogIn12_wrapper(struct CMoveMapLimitInfoList* _this, struct CPlayer* pkPlayer, struct CMoveMapLimitRightInfo* pkRight)
{
CMoveMapLimitInfoListLogIn12_user(_this, pkPlayer, pkRight, CMoveMapLimitInfoListLogIn12_next);
};
void CMoveMapLimitInfoListLogOut14_wrapper(struct CMoveMapLimitInfoList* _this, struct CPlayer* pkPlayer, struct CMoveMapLimitRightInfo* pkRight)
{
CMoveMapLimitInfoListLogOut14_user(_this, pkPlayer, pkRight, CMoveMapLimitInfoListLogOut14_next);
};
void CMoveMapLimitInfoListLoop16_wrapper(struct CMoveMapLimitInfoList* _this)
{
CMoveMapLimitInfoListLoop16_user(_this, CMoveMapLimitInfoListLoop16_next);
};
char CMoveMapLimitInfoListRequest18_wrapper(struct CMoveMapLimitInfoList* _this, int iLimitType, int iRequetType, int iMapInx, unsigned int dwStoreRecordIndex, int iUserInx, char* pRequest, struct CMoveMapLimitRightInfo* pkRight)
{
return CMoveMapLimitInfoListRequest18_user(_this, iLimitType, iRequetType, iMapInx, dwStoreRecordIndex, iUserInx, pRequest, pkRight, CMoveMapLimitInfoListRequest18_next);
};
void CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_wrapper(struct CMoveMapLimitInfoList* _this)
{
CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_user(_this, CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_next);
};
::std::array<hook_record, 10> CMoveMapLimitInfoList_functions =
{
_hook_record {
(LPVOID)0x1403a1dc0L,
(LPVOID *)&CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_user,
(LPVOID *)&CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListctor_CMoveMapLimitInfoList2_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)())&CMoveMapLimitInfoList::ctor_CMoveMapLimitInfoList)
},
_hook_record {
(LPVOID)0x1403a6290L,
(LPVOID *)&CMoveMapLimitInfoListCleanUp4_user,
(LPVOID *)&CMoveMapLimitInfoListCleanUp4_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListCleanUp4_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)())&CMoveMapLimitInfoList::CleanUp)
},
_hook_record {
(LPVOID)0x1403a6020L,
(LPVOID *)&CMoveMapLimitInfoListGet6_user,
(LPVOID *)&CMoveMapLimitInfoListGet6_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListGet6_wrapper),
(LPVOID)cast_pointer_function((struct CMoveMapLimitInfo*(CMoveMapLimitInfoList::*)(int, int, unsigned int))&CMoveMapLimitInfoList::Get)
},
_hook_record {
(LPVOID)0x1403a4ff0L,
(LPVOID *)&CMoveMapLimitInfoListInit8_user,
(LPVOID *)&CMoveMapLimitInfoListInit8_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListInit8_wrapper),
(LPVOID)cast_pointer_function((bool(CMoveMapLimitInfoList::*)(struct std::vector<int,std::allocator<int> >*))&CMoveMapLimitInfoList::Init)
},
_hook_record {
(LPVOID)0x1403a58f0L,
(LPVOID *)&CMoveMapLimitInfoListLoad10_user,
(LPVOID *)&CMoveMapLimitInfoListLoad10_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListLoad10_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)(struct CPlayer*, struct CMoveMapLimitRightInfo*))&CMoveMapLimitInfoList::Load)
},
_hook_record {
(LPVOID)0x1403a5b20L,
(LPVOID *)&CMoveMapLimitInfoListLogIn12_user,
(LPVOID *)&CMoveMapLimitInfoListLogIn12_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListLogIn12_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)(struct CPlayer*, struct CMoveMapLimitRightInfo*))&CMoveMapLimitInfoList::LogIn)
},
_hook_record {
(LPVOID)0x1403a5d50L,
(LPVOID *)&CMoveMapLimitInfoListLogOut14_user,
(LPVOID *)&CMoveMapLimitInfoListLogOut14_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListLogOut14_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)(struct CPlayer*, struct CMoveMapLimitRightInfo*))&CMoveMapLimitInfoList::LogOut)
},
_hook_record {
(LPVOID)0x1403a54d0L,
(LPVOID *)&CMoveMapLimitInfoListLoop16_user,
(LPVOID *)&CMoveMapLimitInfoListLoop16_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListLoop16_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)())&CMoveMapLimitInfoList::Loop)
},
_hook_record {
(LPVOID)0x1403a5f80L,
(LPVOID *)&CMoveMapLimitInfoListRequest18_user,
(LPVOID *)&CMoveMapLimitInfoListRequest18_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListRequest18_wrapper),
(LPVOID)cast_pointer_function((char(CMoveMapLimitInfoList::*)(int, int, int, unsigned int, int, char*, struct CMoveMapLimitRightInfo*))&CMoveMapLimitInfoList::Request)
},
_hook_record {
(LPVOID)0x1403a1fa0L,
(LPVOID *)&CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_user,
(LPVOID *)&CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_next,
(LPVOID)cast_pointer_function(CMoveMapLimitInfoListdtor_CMoveMapLimitInfoList20_wrapper),
(LPVOID)cast_pointer_function((void(CMoveMapLimitInfoList::*)())&CMoveMapLimitInfoList::dtor_CMoveMapLimitInfoList)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
| 60.924051 | 237 | 0.716289 | [
"vector"
] |
abdb59a188c28cf8ba3b74aace99fcdb9a2450ec | 1,102 | hpp | C++ | src/level/level.hpp | tevoran/haeschen-und-woelfchen | 4d993f9bfbe1c767292ff00cf980830ca8b9c913 | [
"BSD-2-Clause"
] | 2 | 2021-06-11T18:58:42.000Z | 2021-06-11T19:09:30.000Z | src/level/level.hpp | tevoran/haeschen-und-woelfchen | 4d993f9bfbe1c767292ff00cf980830ca8b9c913 | [
"BSD-2-Clause"
] | null | null | null | src/level/level.hpp | tevoran/haeschen-und-woelfchen | 4d993f9bfbe1c767292ff00cf980830ca8b9c913 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <huw.hpp>
#define ABFALL 1
#define NEON_L 2
#define NEON_M 3
#define NEON_R 4
#define NEON 5
#define TAUBE 6
#define GHETTO 7
#define WOLF 8
#define HASE 9
#define LEVEL_X 20
#define LEVEL_Y 11
namespace huw
{
class level
{
private:
huw::game *m_game=NULL;
bool activated=false;
public:
std::vector<huw::sprite> abfall;
std::vector<huw::sprite> neon_l;
std::vector<huw::sprite> neon_m;
std::vector<huw::sprite> neon_r;
std::vector<huw::sprite> neon;
std::vector<huw::sprite> ghetto;
//gegner
std::vector<huw::sprite> taube;
std::vector<huw::sprite> taube_tot;
std::vector<bool> taube_richtung;
std::vector<bool> taube_alive;
bool m_game_over=false;
public:
level(uint8_t level[11][20], huw::game *game, huw::player& player);
void render();
void enemy_update();
void collision(huw::player& player);
bool check_coll(huw::player& player, std::vector<huw::sprite> &objects, bool onlyHase=false);
bool done(huw::player& player);
bool game_over(huw::player& player);
};
void level_scripts(int current_level, huw::game& game);
} | 20.407407 | 95 | 0.703267 | [
"render",
"vector"
] |
abdc462fa265851fb1d1fd888c019256a1bf8850 | 4,918 | cpp | C++ | ecs/src/v2/model/ListServerGroupsResult.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ecs/src/v2/model/ListServerGroupsResult.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ecs/src/v2/model/ListServerGroupsResult.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ecs/v2/model/ListServerGroupsResult.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ecs {
namespace V2 {
namespace Model {
ListServerGroupsResult::ListServerGroupsResult()
{
id_ = "";
idIsSet_ = false;
membersIsSet_ = false;
metadataIsSet_ = false;
name_ = "";
nameIsSet_ = false;
policiesIsSet_ = false;
}
ListServerGroupsResult::~ListServerGroupsResult() = default;
void ListServerGroupsResult::validate()
{
}
web::json::value ListServerGroupsResult::toJson() const
{
web::json::value val = web::json::value::object();
if(idIsSet_) {
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_);
}
if(membersIsSet_) {
val[utility::conversions::to_string_t("members")] = ModelBase::toJson(members_);
}
if(metadataIsSet_) {
val[utility::conversions::to_string_t("metadata")] = ModelBase::toJson(metadata_);
}
if(nameIsSet_) {
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_);
}
if(policiesIsSet_) {
val[utility::conversions::to_string_t("policies")] = ModelBase::toJson(policies_);
}
return val;
}
bool ListServerGroupsResult::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("members"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("members"));
if(!fieldValue.is_null())
{
std::vector<std::string> refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setMembers(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("metadata"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("metadata"));
if(!fieldValue.is_null())
{
std::map<std::string, std::string> refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setMetadata(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("name"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setName(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("policies"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("policies"));
if(!fieldValue.is_null())
{
std::vector<std::string> refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPolicies(refVal);
}
}
return ok;
}
std::string ListServerGroupsResult::getId() const
{
return id_;
}
void ListServerGroupsResult::setId(const std::string& value)
{
id_ = value;
idIsSet_ = true;
}
bool ListServerGroupsResult::idIsSet() const
{
return idIsSet_;
}
void ListServerGroupsResult::unsetid()
{
idIsSet_ = false;
}
std::vector<std::string>& ListServerGroupsResult::getMembers()
{
return members_;
}
void ListServerGroupsResult::setMembers(const std::vector<std::string>& value)
{
members_ = value;
membersIsSet_ = true;
}
bool ListServerGroupsResult::membersIsSet() const
{
return membersIsSet_;
}
void ListServerGroupsResult::unsetmembers()
{
membersIsSet_ = false;
}
std::map<std::string, std::string>& ListServerGroupsResult::getMetadata()
{
return metadata_;
}
void ListServerGroupsResult::setMetadata(const std::map<std::string, std::string>& value)
{
metadata_ = value;
metadataIsSet_ = true;
}
bool ListServerGroupsResult::metadataIsSet() const
{
return metadataIsSet_;
}
void ListServerGroupsResult::unsetmetadata()
{
metadataIsSet_ = false;
}
std::string ListServerGroupsResult::getName() const
{
return name_;
}
void ListServerGroupsResult::setName(const std::string& value)
{
name_ = value;
nameIsSet_ = true;
}
bool ListServerGroupsResult::nameIsSet() const
{
return nameIsSet_;
}
void ListServerGroupsResult::unsetname()
{
nameIsSet_ = false;
}
std::vector<std::string>& ListServerGroupsResult::getPolicies()
{
return policies_;
}
void ListServerGroupsResult::setPolicies(const std::vector<std::string>& value)
{
policies_ = value;
policiesIsSet_ = true;
}
bool ListServerGroupsResult::policiesIsSet() const
{
return policiesIsSet_;
}
void ListServerGroupsResult::unsetpolicies()
{
policiesIsSet_ = false;
}
}
}
}
}
}
| 22.456621 | 99 | 0.652501 | [
"object",
"vector",
"model"
] |
abdf13be95947fcadccc73fd199ff04b5c73c72e | 11,054 | cpp | C++ | tutorial/allocators.cpp | ggerganov/dynamix | 7530d2d6a39a0824410f2535ab5fc95d3821488f | [
"MIT"
] | 580 | 2016-06-26T20:44:17.000Z | 2022-03-30T01:26:51.000Z | tutorial/allocators.cpp | ggerganov/dynamix | 7530d2d6a39a0824410f2535ab5fc95d3821488f | [
"MIT"
] | 35 | 2016-06-28T11:15:49.000Z | 2022-01-28T14:03:30.000Z | tutorial/allocators.cpp | ggerganov/dynamix | 7530d2d6a39a0824410f2535ab5fc95d3821488f | [
"MIT"
] | 52 | 2016-06-26T19:49:24.000Z | 2022-01-25T18:18:31.000Z | // DynaMix
// Copyright (c) 2013-2019 Borislav Stanimirov, Zahary Karadjov
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/MIT
//
#include <iostream>
#include <dynamix/dynamix.hpp>
using namespace std;
//[allocators_global
/*`
DynaMix allows you to set custom allocators for the persistent pieces of
memory the library may require.
The library allocates some memory on initialization, which happens at a global
scope -- before the entry point of a program. It also has some allocations which
are for instances with a very short lifetime. Currently those are not covered by
the allocators.
What you can control with the custom allocators is the new memory allocated for
`dynamix::object`
instances - their internal mixin data. You can assign a global allocator
to the library and you can also set individual allocators per mixin type.
First let's see how you can create a global allocator. Let's assume you have
a couple of functions of your own that allocate and deallocate memory in some
way specific to your needs:
*/
char* allocate(size_t size);
void deallocate(char* buffer);
/*`
To create a global allocator, you need to create a class derived from
`domain_allocator` and override its virtual methods.
*/
class custom_allocator : public dynamix::domain_allocator
{
/*`
The first two methods allocate a buffer for the mixin data pointers. Every
object has pointers to its mixins within it. This is the array of such
pointers. The class `domain_allocator` has a static constant member --
`mixin_data_size` -- which you should use to see the size of a single
element in that array.
The methods also have arguments referring to the object for which the mixin
data is being allocated. We won't be using it in this simple example.
*/
virtual char* alloc_mixin_data(size_t count, const dynamix::object*) override
{
return allocate(count * mixin_data_size);
}
virtual void dealloc_mixin_data(char* ptr, size_t, const dynamix::object*) override
{
deallocate(ptr);
}
/*`
The other two methods you need to overload allocate and deallocate the
memory for an actual mixin class instance. As you may have already read, the
buffer allocated for a mixin instance is bigger than needed because the
library stores a pointer to the owning object immediately before the memory
used by the mixin instance.
That's why this function is not as simple as the one for the mixin data
array. It has to conform to the mixin (and also `object` pointer) alignment.
*/
virtual std::pair<char*, size_t> alloc_mixin(const dynamix::mixin_type_info& info, const dynamix::object*) override
{
/*`
The users are strongly advised to use the static method
`domain_allocator::mem_size_for_mixin`. It will appropriately
calculate how much memory is needed for the mixin instance such that
there is enough room at the beginning for the pointer to the owning
object and the memory alignment is respected.
*/
size_t size = mem_size_for_mixin(info.size, info.alignment);
char* buffer = allocate(size);
/*`
After you allocate the buffer you should take care of the other return
value - the mixin offset. It calculates the offset of the actual
mixin instance memory within the buffer, such that there is room for
the owning object pointer in before it and all alignments are
respected.
You are encouraged to use the static method
`domain_allocator::mixin_offset` for this purpose.
*/
size_t offset = mixin_offset(buffer, info.alignment);
return std::make_pair(buffer, offset);
}
/*`
The mixin instance deallocation method can be trivial
*/
virtual void dealloc_mixin(char* ptr, size_t, const dynamix::mixin_type_info&, const dynamix::object*) override
{
deallocate(ptr);
}
//]
};
//[allocators_mixin
/*`
As we mentioned before, you can have an allocator specific for a mixin type.
A common case for such use is to have a per-frame allocator -- one that has a
preallocated buffer which is used much like a stack, with its pointer reset at
the end of each simulation frame (or at the beginning each new one). Let's
create such an allocator.
First, a mixin instance allocator is not necessarily bound to a concrete mixin
type. You can have the same instance of such an allocator set for many mixins
(which would be a common use of a per-frame allocator), but for our example
let's create one that *is* bound to an instance. We will make it a template
class because the code for each mixin type will be the same.
A mixin instance allocator needs to be derived from the class `mixin_allocator`.
You then need to overload its two virtual methods which are exactly the same
as the mixin instance allocation/deallocation methods in `domain_allocator`.
*/
template <typename Mixin>
class per_frame_allocator : public dynamix::mixin_allocator
{
private:
static const size_t NUM_IN_PAGE = 1000;
size_t _num_allocations; // number of "living" instances allocated
const size_t mixin_buf_size; // the size of a single mixin instance buffer
vector<char*> _pages; // use pages of data where each page can store NUM_IN_PAGE instances
size_t _page_byte_index; // index within a memory "page"
const size_t page_size; // size in bytes of a page
public:
// some way to obtain the instance
static per_frame_allocator& instance()
{
static per_frame_allocator i;
return i;
}
per_frame_allocator()
: _num_allocations(0)
, mixin_buf_size(
mem_size_for_mixin(
sizeof(Mixin),
std::alignment_of<Mixin>::value))
, page_size(mixin_buf_size * NUM_IN_PAGE)
{
new_memory_page();
}
void new_memory_page()
{
char* page = new char[page_size];
_pages.push_back(page);
_page_byte_index = 0;
}
virtual std::pair<char*, size_t> alloc_mixin(const dynamix::mixin_type_info& info, const dynamix::object*) override
{
if(_page_byte_index == NUM_IN_PAGE)
{
// if we don't have space in our current page, create a new one
new_memory_page();
}
char* buffer = _pages.back() + _page_byte_index * mixin_buf_size;
// again calculate the offset using this static member function
size_t offset = mixin_offset(buffer, info.alignment);
++_page_byte_index;
++_num_allocations;
return std::make_pair(buffer, offset);
}
virtual void dealloc_mixin(char* buf, size_t, const dynamix::mixin_type_info&, const dynamix::object*) override
{
#if !defined(NDEBUG)
// in debug mode check if the mixin is within any of our pages
bool found = false;
for (size_t i = 0; i < _pages.size(); ++i)
{
const char* page_begin = _pages[i];
const char* page_end = page_begin + page_size;
if (buf >= page_begin && buf < page_end)
{
found = true;
break;
}
}
// deallocating memory, which hasn't been allocated from that allocator
I_DYNAMIX_ASSERT(found);
#else
I_DYNAMIX_MAYBE_UNUSED(buf);
#endif
// no actual deallocation to be done
// just decrement our living instances counter
--_num_allocations;
}
// function to be called once each frame that resets the allocator
void reset()
{
I_DYNAMIX_ASSERT(_num_allocations == 0); // premature reset
for(size_t i=1; i<_pages.size(); ++i)
{
delete[] _pages[i];
}
_pages.resize(1);
_page_byte_index = 0;
}
};
/*`
Now this class can be set as a mixin allocator for a given mixin type. A side
effect of the fact that it's bound to the type is that it keeps mixin instances
in a continuous buffer. With some changes (to take care of potential holes in
the buffer) such an allocator can be used by a subsystem that works through
mixins relying on them being in a continuous buffer to avoid cache misses.
To illustrate a usage for our mixin allocator, let's imagine we have a game. If
a character in our game dies, it will be destroyed at the end of the current
frame and should stop responding to any messages. We can create a mixin called
`dead_character` which implements all those the messages with a higher priority
than the rest of the mixins. Since every object that has a `dead_character` mixin
will be destroyed by the end of the frame, it will be safe to use the per-frame
allocator for it.
First let's create the mixin class and sample messages:
*/
class dead_character
{
public:
void die() {}
// ...
};
DYNAMIX_MESSAGE_0(void, die);
DYNAMIX_DEFINE_MESSAGE(die);
//...
/*`
Now we define the mixin so that it uses the allocator, we just need to add it
with "`&`" to the mixin feature list, just like we add messages. There are two
ways to do so. The first one would be to do it like this:
DYNAMIX_DEFINE_MIXIN(dead_character, ... & dynamix::priority(1, die_msg)
& dynamix::allocator<per_frame_allocator<dead_character>>());
This will create the instance of the allocator internally and we won't be able
to get it. Since in our case we do care about the instance because we want to
call its `reset` method, we could use an alternative way, by just adding
an actual instance of the allocator to the feature list:
*/
DYNAMIX_DEFINE_MIXIN(dead_character, /*...*/ dynamix::priority(1, die_msg)
& per_frame_allocator<dead_character>::instance());
/*`
If we share a mixin instance allocator between multiple mixins, the second way
is also the way to go.
*/
//]
int main()
{
//[allocators_global_use
/*`
To use the custom global allocator you need to instantiate it and then set
it with `set_global_allocator`. Unlike the mutation rules, the
responsibility for the allocator instance is yours. You need to make sure
that the lifetime of the instance is at least as long as the lifetime of
all objects in the system.
Unfortunately this means that if you have global or static objects, you need
to create a new pointer that is, in a way, a memory leak. If you do not have
global or static objects, it should be safe for it to just be a local
variable in your program's entry point function.
*/
custom_allocator alloc;
dynamix::set_global_allocator(&alloc);
//]
//[allocators_mixin_use
/*`
Now all mixin allocations and deallocations will pass through our mixin
allocator:
*/
dynamix::object o;
dynamix::mutate(o)
.add<dead_character>();
dynamix::mutate(o)
.remove<dead_character>();
// safe because we've destroyed all instances of dead_character
per_frame_allocator<dead_character>::instance().reset();
//]
return 0;
}
char* allocate(size_t size)
{
return new char[size];
}
void deallocate(char* buffer)
{
delete[] buffer;
}
//[tutorial_allocators
//` %{allocators_global}
//` %{allocators_global_use}
//` %{allocators_mixin}
//` %{allocators_mixin_use}
//]
| 32.416422 | 119 | 0.717297 | [
"object",
"vector"
] |
abe2dd33436d01848d5207f26153ad4e829bfbb6 | 27,216 | cpp | C++ | mlir/parsers/qasm3/visitor_handlers/classical_types_handler.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | null | null | null | mlir/parsers/qasm3/visitor_handlers/classical_types_handler.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | null | null | null | mlir/parsers/qasm3/visitor_handlers/classical_types_handler.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | null | null | null |
#include "expression_handler.hpp"
#include "qasm3_visitor.hpp"
namespace qcor {
// classicalDeclarationStatement
// : ( classicalDeclaration | constantDeclaration ) SEMICOLON
// ;
// constantDeclaration
// : 'const' equalsAssignmentList
// ;
// singleDesignatorDeclaration
// : singleDesignatorType designator ( identifierList | equalsAssignmentList
// )
// ;
// doubleDesignatorDeclaration
// : doubleDesignatorType doubleDesignator ( identifierList |
// equalsAssignmentList )
// ;
// noDesignatorDeclaration
// : noDesignatorType ( identifierList | equalsAssignmentList )
// ;
// bitDeclaration
// : bitType (indexIdentifierList | indexEqualsAssignmentList )
// ;
// classicalDeclaration
// : singleDesignatorDeclaration
// | doubleDesignatorDeclaration
// | noDesignatorDeclaration
// | bitDeclaration
// ;
//
// classicalAssignment
// : indexIdentifier assignmentOperator ( expression | indexIdentifier )
// ;
//
// Examples:
// const layers = 22;
// const layers2 = layers / 2;
// const t = layers * 3;
// const d = 1.2;
// const tt = d * 33.3;
// int[32] i = 10;
// const mypi = pi / 2;
// float[32] f;
// float[64] ff = 3.14;
antlrcpp::Any qasm3_visitor::visitConstantDeclaration(
qasm3Parser::ConstantDeclarationContext* context) {
auto ass_list = context->equalsAssignmentList();
auto location = get_location(builder, file_name, context);
for (int i = 0; i < ass_list->Identifier().size(); i++) {
auto var_name = ass_list->Identifier(i)->getText();
if (var_name == "pi") {
printErrorMessage("pi is already defined in OPENQASM 3.", context);
}
auto equals_expr = ass_list->equalsExpression(i);
mlir::OpBuilder tmp_builder(builder.getContext());
qasm3_expression_generator exp_generator(builder, symbol_table, file_name);
exp_generator.visit(equals_expr);
auto expr_value = exp_generator.current_value;
auto value_type = expr_value.getType();
symbol_table.evaluate_const_global(
var_name, equals_expr->expression()->getText(), value_type,
m_module.getRegion().getBlocks().front(), location);
}
return 0;
}
antlrcpp::Any qasm3_visitor::visitSingleDesignatorDeclaration(
qasm3Parser::SingleDesignatorDeclarationContext* context) {
auto location = get_location(builder, file_name, context);
auto type = context->singleDesignatorType()->getText();
auto designator_expr = context->designator()->expression();
uint64_t width_idx = symbol_table.evaluate_constant_integer_expression(
designator_expr->getText());
mlir::Attribute init_attr;
mlir::Type value_type;
if (type == "int") {
value_type = builder.getIntegerType(width_idx);
init_attr = mlir::IntegerAttr::get(value_type, 0);
} else if (type == "uint") {
value_type = builder.getIntegerType(width_idx, false);
init_attr = mlir::IntegerAttr::get(value_type, 0);
} else if (type == "float") {
if (width_idx == 16) {
value_type = mlir::FloatType::getF16(builder.getContext());
init_attr = mlir::FloatAttr::get(value_type, 0.0);
} else if (width_idx == 32) {
value_type = mlir::FloatType::getF32(builder.getContext());
init_attr = mlir::FloatAttr::get(value_type, 0.0);
} else if (width_idx == 64) {
value_type = mlir::FloatType::getF64(builder.getContext());
init_attr = mlir::FloatAttr::get(value_type, 0.0);
} else {
printErrorMessage("we only support 16, 32, and 64 floating point types.",
context);
}
} else {
printErrorMessage("We do not currently support this type: " + type,
context);
}
// THis can now be either an identifierList or an equalsAssignementList
std::vector<std::string> variable_names;
std::vector<mlir::Value> initial_values;
if (auto id_list = context->identifierList()) {
for (auto id : id_list->Identifier()) {
variable_names.push_back(id->getText());
initial_values.push_back(
builder.create<mlir::ConstantOp>(location, init_attr));
}
} else {
auto equals_list = context->equalsAssignmentList();
for (auto id : equals_list->Identifier()) {
variable_names.push_back(id->getText());
}
for (auto eq_expr : equals_list->equalsExpression()) {
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name, value_type);
equals_exp_generator.visit(eq_expr->expression());
initial_values.push_back(equals_exp_generator.current_value);
}
}
// Store the initial values
for (int i = 0; i < variable_names.size(); i++) {
auto variable = variable_names[i];
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, value_type);
mlir::Value allocation = builder.create<mlir::AllocaOp>(location, mem_type);
auto init = initial_values[i];
if (type == "int" &&
value_type.getIntOrFloatBitWidth() <
initial_values[i].getType().getIntOrFloatBitWidth()) {
init = builder.create<mlir::TruncateIOp>(location, init, value_type);
}
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, init, allocation);
// Save the allocation, the store op
symbol_table.add_symbol(variable, allocation);
}
return 0;
}
antlrcpp::Any qasm3_visitor::visitNoDesignatorDeclaration(
qasm3Parser::NoDesignatorDeclarationContext* context) {
auto location = get_location(builder, file_name, context);
// can be no designator
// basically can be
// bool b;
// bool b = 1;
// bool b = bool(bit)
if (context->noDesignatorType()->getText() == "bool") {
auto eq_ass_list = context->equalsAssignmentList();
std::vector<std::string> var_names;
std::vector<mlir::Value> initial_values;
mlir::Type value_type = builder.getIntegerType(1);
if (eq_ass_list) {
for (int i = 0; i < eq_ass_list->equalsExpression().size(); i++) {
auto eq_expr = eq_ass_list->equalsExpression(i);
var_names.push_back(eq_ass_list->Identifier(i)->getText());
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name, value_type);
equals_exp_generator.visit(eq_expr->expression());
initial_values.push_back(equals_exp_generator.current_value);
}
} else {
// uninitialized, just set to false;
for (int i = 0; i < context->identifierList()->Identifier().size(); i++) {
var_names.push_back(
context->identifierList()->Identifier(i)->getText());
initial_values.push_back(get_or_create_constant_integer_value(
0, location, builder.getIntegerType(1), symbol_table, builder));
}
}
for (int i = 0; i < var_names.size(); i++) {
auto variable = var_names[i];
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, value_type);
mlir::Value allocation =
builder.create<mlir::AllocaOp>(location, mem_type);
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, initial_values[i], allocation);
// get_or_create_constant_index_value(0, location, 64, symbol_table,
// builder));
// Save the allocation, the store op
symbol_table.add_symbol(variable, allocation);
}
} else if (context->noDesignatorType()->getText().find("int") !=
std::string::npos) {
// THis can now be either an identifierList or an equalsAssignementList
mlir::Attribute init_attr;
mlir::Type value_type;
std::string type = context->noDesignatorType()->getText();
auto bit_width = (type == "int" || type == "uint") ? 32 : 64;
if (context->noDesignatorType()->getText().find("u") != std::string::npos) {
value_type = builder.getIntegerType(bit_width, false);
} else {
value_type = builder.getIntegerType(bit_width);
}
init_attr = mlir::IntegerAttr::get(value_type, 0);
std::vector<std::string> variable_names;
std::vector<mlir::Value> initial_values;
if (auto id_list = context->identifierList()) {
for (auto id : id_list->Identifier()) {
variable_names.push_back(id->getText());
initial_values.push_back(
builder.create<mlir::ConstantOp>(location, init_attr));
}
} else {
auto equals_list = context->equalsAssignmentList();
for (auto id : equals_list->Identifier()) {
variable_names.push_back(id->getText());
}
for (auto eq_expr : equals_list->equalsExpression()) {
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name, value_type);
equals_exp_generator.visit(eq_expr->expression());
initial_values.push_back(equals_exp_generator.current_value);
}
}
// Store the initial values
for (int i = 0; i < variable_names.size(); i++) {
auto variable = variable_names[i];
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, value_type);
mlir::Value allocation =
builder.create<mlir::AllocaOp>(location, mem_type);
auto init = initial_values[i];
if (value_type.getIntOrFloatBitWidth() <
initial_values[i].getType().getIntOrFloatBitWidth()) {
init = builder.create<mlir::TruncateIOp>(location, init, value_type);
}
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, init, allocation);
// Save the allocation, the store op
symbol_table.add_symbol(variable, allocation);
}
} else if (context->noDesignatorType()->getText() == "float") {
// THis can now be either an identifierList or an equalsAssignementList
mlir::Attribute init_attr;
mlir::Type value_type;
value_type = builder.getF32Type();
init_attr = mlir::FloatAttr::get(value_type, 0);
std::vector<std::string> variable_names;
std::vector<mlir::Value> initial_values;
if (auto id_list = context->identifierList()) {
for (auto id : id_list->Identifier()) {
variable_names.push_back(id->getText());
initial_values.push_back(
builder.create<mlir::ConstantOp>(location, init_attr));
}
} else {
auto equals_list = context->equalsAssignmentList();
for (auto id : equals_list->Identifier()) {
variable_names.push_back(id->getText());
}
for (auto eq_expr : equals_list->equalsExpression()) {
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name, value_type);
equals_exp_generator.visit(eq_expr->expression());
initial_values.push_back(equals_exp_generator.current_value);
}
}
// Store the initial values
for (int i = 0; i < variable_names.size(); i++) {
auto variable = variable_names[i];
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, value_type);
mlir::Value allocation =
builder.create<mlir::AllocaOp>(location, mem_type);
auto init = initial_values[i];
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, init, allocation);
// Save the allocation, the store op
symbol_table.add_symbol(variable, allocation);
}
} else if (context->noDesignatorType()->getText() == "double") {
// THis can now be either an identifierList or an equalsAssignementList
mlir::Attribute init_attr;
mlir::Type value_type;
value_type = builder.getF64Type();
init_attr = mlir::FloatAttr::get(value_type, 0);
std::vector<std::string> variable_names;
std::vector<mlir::Value> initial_values;
if (auto id_list = context->identifierList()) {
for (auto id : id_list->Identifier()) {
variable_names.push_back(id->getText());
initial_values.push_back(
builder.create<mlir::ConstantOp>(location, init_attr));
}
} else {
auto equals_list = context->equalsAssignmentList();
for (auto id : equals_list->Identifier()) {
variable_names.push_back(id->getText());
}
for (auto eq_expr : equals_list->equalsExpression()) {
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name, value_type);
equals_exp_generator.visit(eq_expr->expression());
initial_values.push_back(equals_exp_generator.current_value);
}
}
// Store the initial values
for (int i = 0; i < variable_names.size(); i++) {
auto variable = variable_names[i];
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, value_type);
mlir::Value allocation =
builder.create<mlir::AllocaOp>(location, mem_type);
auto init = initial_values[i];
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, init, allocation);
// Save the allocation, the store op
symbol_table.add_symbol(variable, allocation);
}
} else {
printErrorMessage("We do not yet support this no designator type: " +
context->noDesignatorType()->getText(),
context);
}
return 0;
}
antlrcpp::Any qasm3_visitor::visitBitDeclaration(
qasm3Parser::BitDeclarationContext* context) {
// bitDeclaration
// : bitType (indexIdentifierList | indexEqualsAssignmentList )
// ;
// indexIdentifier
// : Identifier rangeDefinition
// | Identifier ( LBRACKET expressionList RBRACKET )?
// | indexIdentifier '||' indexIdentifier
// ;
// indexIdentifierList
// : ( indexIdentifier COMMA )* indexIdentifier
// ;
// indexEqualsAssignmentList
// : ( indexIdentifier equalsExpression COMMA)* indexIdentifier
// equalsExpression
// ;
auto location = get_location(builder, file_name, context);
// First case is indexIdentifierList, no initialization
std::size_t size = 1;
if (auto index_ident_list = context->indexIdentifierList()) {
for (auto idx_identifier : index_ident_list->indexIdentifier()) {
auto var_name = idx_identifier->Identifier()->getText();
auto exp_list = idx_identifier->expressionList();
if (exp_list) {
size = symbol_table.evaluate_constant_integer_expression(
exp_list->expression(0)->getText());
}
std::vector<mlir::Value> init_values, init_indices;
for (std::size_t i = 0; i < size; i++) {
init_values.push_back(get_or_create_constant_integer_value(
0, location, builder.getI1Type(), symbol_table, builder));
init_indices.push_back(get_or_create_constant_index_value(
i, location, 64, symbol_table, builder));
}
if (size == 1) {
llvm::ArrayRef<int64_t> shaperef{};
auto mem_type = mlir::MemRefType::get(shaperef, builder.getI1Type());
mlir::Value allocation =
builder.create<mlir::AllocaOp>(location, mem_type);
// Store the value to the 0th index of this storeop
builder.create<mlir::StoreOp>(location, init_values[0], allocation);
symbol_table.add_symbol(var_name, allocation);
} else {
auto allocation = allocate_1d_memory_and_initialize(
location, size, builder.getI1Type(), init_values,
llvm::makeArrayRef(init_indices));
symbol_table.add_symbol(var_name, allocation);
}
}
} else {
// Second case is indexEqualsAssignmentList, so bits with initialization
auto index_equals_list = context->indexEqualsAssignmentList();
for (int i = 0; i < index_equals_list->indexIdentifier().size(); i++) {
auto first_index_equals = index_equals_list->indexIdentifier(i);
auto var_name = first_index_equals->Identifier()->getText();
std::size_t size = 1;
if (auto index_expr_list = first_index_equals->expressionList()) {
size = symbol_table.evaluate_constant_integer_expression(
first_index_equals->expressionList()->expression(0)->getText());
}
auto equals_expr =
index_equals_list->equalsExpression()[i]->expression()->getText();
equals_expr = equals_expr.substr(1, equals_expr.length() - 2);
// This can only be a string-like representation of 0s and 1s
if (size != equals_expr.length()) {
printErrorMessage(
"Invalid initial string assignment for bit array, sizes do not "
"match.",
context);
}
std::vector<mlir::Value> initial_values, indices;
for (int j = 0; j < size; j++) {
initial_values.push_back(get_or_create_constant_integer_value(
equals_expr[j] == '1' ? 1 : 0, location, result_type, symbol_table,
builder));
indices.push_back(get_or_create_constant_index_value(
j, location, 64, symbol_table, builder));
}
auto allocation = allocate_1d_memory_and_initialize(
location, size, builder.getI1Type(), initial_values,
llvm::makeArrayRef(indices));
symbol_table.add_symbol(var_name, allocation);
}
}
return 0;
}
antlrcpp::Any qasm3_visitor::visitClassicalAssignment(
qasm3Parser::ClassicalAssignmentContext* context) {
auto location = get_location(builder, file_name, context);
// classicalAssignment
// : indexIdentifier assignmentOperator ( expression | indexIdentifier )
// ;
// assignmentOperator
// : EQUALS
// | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '~=' | '^=' | '<<=' |
// '>>='
// ;
auto var_name = context->indexIdentifier(0)->Identifier()->getText();
auto ass_op = context->assignmentOperator(); // :)
// Make sure this is a valid symbol
if (!symbol_table.has_symbol(var_name)) {
printErrorMessage("invalid variable name in classical assignement: " +
var_name + ", " + ass_op->getText(),
context);
}
// Make sure rhs is an expression
if (!context->expression()) {
printErrorMessage(
"We only can handle classicalAssignment expressions at this time, "
"no "
"indexIdentifiers.",
context);
}
// If the lhs is a const variable, throw an error
if (!symbol_table.is_variable_mutable(var_name)) {
printErrorMessage(
"Cannot change variable " + var_name + ", it has been marked const.",
context);
}
// Get the LHS symbol
auto lhs = symbol_table.get_symbol(var_name);
if (!lhs.getType().isa<mlir::MemRefType>()) {
printErrorMessage("LHS in classical assignment must be a MemRefType.",
context);
}
// auto width = lhs.getType()
// .cast<mlir::MemRefType>()
// .getElementType()
// .getIntOrFloatBitWidth();
// Get the RHS value
qasm3_expression_generator exp_generator(
builder, symbol_table, file_name,
lhs.getType().cast<mlir::MemRefType>().getElementType());
exp_generator.visit(context->expression());
auto rhs = exp_generator.current_value;
// Could be somethign like
// bit = subroutine_call(params) qbits...
if (auto call_op = rhs.getDefiningOp<mlir::CallOp>()) {
int bit_idx = 0;
bool we_have_lhs_idx = false;
mlir::Value v;
if (auto index_list = context->indexIdentifier(0)->expressionList()) {
// Need to extract element from bit array to set it
// auto idx_str = index_list->expression(0)->getText();
// bit_idx = std::stoi(idx_str);
we_have_lhs_idx = true;
qasm3_expression_generator equals_exp_generator(builder, symbol_table,
file_name);
equals_exp_generator.visit(index_list->expression(0));
v = equals_exp_generator.current_value;
} else {
v = get_or_create_constant_index_value(0, location, 64, symbol_table,
builder);
}
// Scenarios:
// memref<type> = call ... -> memref<type>
// memref<Nxtype> = call ... -> type (like bit)
// memref<Nxtype> = call ... -> memref<Mxtype>, N has to equal M
if (lhs.getType().cast<mlir::MemRefType>().getRank() != 0) {
auto lhs_shape = lhs.getType().cast<mlir::MemRefType>().getShape()[0];
if (rhs.getType().isa<mlir::MemRefType>()) {
auto rhs_shape = rhs.getType().cast<mlir::MemRefType>().getShape()[0];
if (lhs_shape != rhs_shape) {
printErrorMessage(
"return value from subroutine call does not have the correct "
"memref "
"shape.",
context, {lhs, rhs});
}
for (int i = 0; i < lhs_shape; i++) {
mlir::Value pos = get_or_create_constant_integer_value(
i, location, builder.getIntegerType(64), symbol_table, builder);
auto load = builder.create<mlir::LoadOp>(location, rhs, pos);
builder.create<mlir::StoreOp>(
location, load, lhs,
llvm::makeArrayRef(std::vector<mlir::Value>{pos}));
}
} else {
if (lhs_shape != 1 && !we_have_lhs_idx) {
printErrorMessage("rhs and lhs memref shapes do not match.", context,
{lhs, rhs});
}
builder.create<mlir::StoreOp>(
location, rhs, lhs,
llvm::makeArrayRef(std::vector<mlir::Value>{v}));
}
} else {
builder.create<mlir::StoreOp>(location, rhs, lhs);
}
return 0;
}
// Create a 0 index value for our Load and Store Ops
// llvm::ArrayRef<mlir::Value> zero_index(get_or_create_constant_index_value(
// 0, location, 64, symbol_table, builder));
// Get the lhs and rhs types
auto lhs_type = lhs.getType().cast<mlir::MemRefType>().getElementType();
mlir::Type rhs_type = rhs.getType();
mlir::Value load_result_rhs = rhs;
if (rhs_type.isa<mlir::MemRefType>()) {
// if rhs is a memref, let's load its 0th index value
rhs_type = rhs_type.cast<mlir::MemRefType>().getElementType();
auto load_rhs =
builder.create<mlir::LoadOp>(location, rhs); //, zero_index);
load_result_rhs = load_rhs.result();
}
// Load the LHS value
auto load = builder.create<mlir::LoadOp>(location, lhs); //, zero_index);
auto load_result = load.result();
// Check what the assignment op is...
mlir::Value current_value;
auto assignment_op = ass_op->getText();
if (assignment_op == "+=") {
// If either are floats, use float addition
if (lhs_type.isa<mlir::FloatType>() || rhs_type.isa<mlir::FloatType>()) {
current_value =
builder.create<mlir::AddFOp>(location, load_result, load_result_rhs);
} else if (lhs_type.isa<mlir::IntegerType>() &&
rhs_type.isa<mlir::IntegerType>()) {
// Else both must be integers to perform integer addition
current_value =
builder.create<mlir::AddIOp>(location, load_result, load_result_rhs);
} else {
printErrorMessage("Could not perform += for values of these types.",
context, {lhs, rhs});
}
// Store the added value to the lhs
llvm::ArrayRef<mlir::Value> zero_index2(get_or_create_constant_index_value(
0, location, 64, symbol_table, builder));
builder.create<mlir::StoreOp>(location, current_value,
lhs); //, zero_index2);
} else if (assignment_op == "-=") {
// If either are floats, use float subtraction
if (lhs_type.isa<mlir::FloatType>() || rhs_type.isa<mlir::FloatType>()) {
current_value =
builder.create<mlir::SubFOp>(location, load_result, load_result_rhs);
} else if (lhs_type.isa<mlir::IntegerType>() &&
rhs_type.isa<mlir::IntegerType>()) {
// Else both must be integers to perform integer subtraction
current_value =
builder.create<mlir::SubIOp>(location, load_result, load_result_rhs);
} else {
printErrorMessage("Could not perform -= for values of these types.",
context, {lhs, rhs});
}
// // Store the added value to the lhs
// llvm::ArrayRef<mlir::Value>
// zero_index2(get_or_create_constant_index_value(
// 0, location, 64, symbol_table, builder));
builder.create<mlir::StoreOp>(location, current_value,
lhs); //, zero_index2);
} else if (assignment_op == "*=") {
// If either are floats, use float multiplication
if (lhs_type.isa<mlir::FloatType>() || rhs_type.isa<mlir::FloatType>()) {
current_value =
builder.create<mlir::MulFOp>(location, load_result, load_result_rhs);
} else if (lhs_type.isa<mlir::IntegerType>() &&
rhs_type.isa<mlir::IntegerType>()) {
// Else both must be integers to perform integer subtraction
current_value =
builder.create<mlir::MulIOp>(location, load_result, load_result_rhs);
} else {
printErrorMessage("Could not perform *= for values of these types.",
context, {lhs, rhs});
}
// Store the added value to the lhs
builder.create<mlir::StoreOp>(location, current_value, lhs);
} else if (assignment_op == "/=") {
if (lhs_type.isa<mlir::FloatType>() || rhs_type.isa<mlir::FloatType>()) {
if (!lhs_type.isa<mlir::FloatType>()) {
load_result =
builder.create<mlir::SIToFPOp>(location, load_result, rhs_type);
} else if (!rhs_type.isa<mlir::FloatType>()) {
load_result_rhs =
builder.create<mlir::SIToFPOp>(location, load_result_rhs, lhs_type);
}
current_value =
builder.create<mlir::DivFOp>(location, load_result, load_result_rhs);
} else if (lhs_type.isa<mlir::IntegerType>() &&
rhs_type.isa<mlir::IntegerType>()) {
current_value = builder.create<mlir::UnsignedDivIOp>(
location, load_result, load_result_rhs);
} else {
printErrorMessage("Could not perform /= for values of these types.",
context, {lhs, rhs});
}
builder.create<mlir::StoreOp>(location, current_value, lhs);
} else if (assignment_op == "^=") {
current_value =
builder.create<mlir::XOrOp>(location, load_result, load_result_rhs);
// llvm::ArrayRef<mlir::Value>
// zero_index2(get_or_create_constant_index_value( 0, location, 64,
// symbol_table, builder));
builder.create<mlir::StoreOp>(location, current_value,
lhs); //, zero_index2);
} else if (assignment_op == "=") {
// FIXME This assumes we have a memref<1x??> = memref<1x??>
// what if we have multiple elements in the memref???
builder.create<mlir::StoreOp>(location, load_result_rhs, lhs);
} else {
printErrorMessage(ass_op->getText() + " not yet supported for this type.",
context);
}
return 0;
}
} // namespace qcor | 38.332394 | 80 | 0.636574 | [
"shape",
"vector"
] |
abe38c8404f59bda6bc416fed9340b9315cd06a0 | 10,006 | cpp | C++ | Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryNativeTabFolder.h"
#include "berryNativeTabItem.h"
#include "berryQCTabBar.h"
#include <internal/berryQtControlWidget.h>
#include <internal/berryWorkbenchPlugin.h>
#include <berryIQtStyleManager.h>
#include <berryShell.h>
#include <berryConstants.h>
#include <berryPlatform.h>
#include <berryPlatformUI.h>
#include <berryLog.h>
#include <QFrame>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QKeyEvent>
namespace berry
{
AbstractTabItem* NativeTabFolder::GetTab(int index)
{
return tabControl->getTab(index);
}
void NativeTabFolder::TabSelectionChanged(int index)
{
this->FireEvent(TabFolderEvent::EVENT_TAB_SELECTED, tabControl->getTab(index));
}
void NativeTabFolder::DragStarted(const QPoint& location)
{
this->HandleDragStarted(location);
}
void NativeTabFolder::ViewFormDestroyed(QObject*)
{
viewForm = nullptr;
content = nullptr;
}
NativeTabFolder::NativeTabFolder(QWidget* parent)
: QObject(parent)
{
content = nullptr;
viewForm = new QtControlWidget(parent, nullptr);
viewForm->setObjectName("ViewForm");
viewForm->installEventFilter(this);
auto layout = new QVBoxLayout(viewForm);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
viewForm->setLayout(layout);
connect(viewForm, SIGNAL(destroyed(QObject*)), this, SLOT(ViewFormDestroyed(QObject*)));
auto topControls = new QWidget(viewForm);
topControls->setMinimumSize(0, 24);
topControls->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
layout->addWidget(topControls);
auto topLayout = new QHBoxLayout(topControls);
topLayout->setContentsMargins(0, 0, 0, 0);
topLayout->setSpacing(0);
tabControl = new QCTabBar(topControls);
tabControl->installEventFilter(this);
tabControl->setMinimumSize(0, 25);
tabControl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
topLayout->addWidget(tabControl);
auto topRightControls = new QFrame(topControls);
topRightControls->setObjectName("TabTopRightControls");
topRightControls->setMinimumSize(6, 25);
topRightControls->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
topLayout->addWidget(topRightControls);
contentFrame = new QFrame(viewForm);
contentFrame->setObjectName("ViewFormContentFrame");
contentFrame->installEventFilter(this);
contentFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
auto contentFrameLayout = new QVBoxLayout(contentFrame);
contentFrameLayout->setContentsMargins(0,0,0,0);
contentFrameLayout->setSpacing(0);
//contentFrame->setLayout(layout);
layout->addWidget(contentFrame);
this->connect(tabControl, SIGNAL(currentChanged(int)), this,
SLOT(TabSelectionChanged(int)));
this->connect(tabControl, SIGNAL(dragStarted(const QPoint&)), this,
SLOT(DragStarted(const QPoint&)));
//std::cout << "Created: viewForm <-- " << qPrintable(parent->objectName());
//for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget())
// std::cout << " <-- " << qPrintable(parent->objectName());
//std::cout << std::endl;
//parent = viewForm;
//std::cout << "Created control: QCTabBar <-- " << qPrintable(parent->objectName());
//for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget())
// std::cout << " <-- " << qPrintable(parent->objectName());
//std::cout << std::endl;
//attachListeners(control, false);
// viewForm = new ViewForm(control, SWT.FLAT);
// attachListeners(viewForm, false);
// systemToolbar = new StandardSystemToolbar(viewForm, true, false, true, true, true);
// systemToolbar.addListener(systemToolbarListener);
// viewForm.setTopRight(systemToolbar.getControl());
//
// topCenter = new ProxyControl(viewForm);
// topCenterCache = new SizeCache();
//
// title = new CLabel(viewForm, SWT.LEFT);
// attachListeners(title, false);
// viewForm.setTopLeft(title);
ctkServiceReference serviceRef = WorkbenchPlugin::GetDefault()->GetPluginContext()->getServiceReference<IQtStyleManager>();
if (serviceRef)
{
skinManager = WorkbenchPlugin::GetDefault()->GetPluginContext()->getService<IQtStyleManager>(serviceRef);
}
}
NativeTabFolder::~NativeTabFolder()
{
if (!PlatformUI::GetWorkbench()->IsClosing())
{
BERRY_DEBUG << "Deleting viewForm";
if (content != nullptr)
{
content->setParent(nullptr);
}
viewForm->deleteLater();
}
}
bool NativeTabFolder::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
this->HandleMousePress(mouseEvent->pos());
}
return QObject::eventFilter(watched, event);
}
void NativeTabFolder::UpdateColors()
{
QString tabStyle = this->GetActive() == 1 ? skinManager->GetActiveTabStylesheet() : skinManager->GetTabStylesheet();
//tabControl->setStyleSheet(tabSkin);
//contentFrame->setStyleSheet(tabSkin);
viewForm->setStyleSheet(tabStyle);
}
void NativeTabFolder::SetActive(int activeState)
{
AbstractTabFolder::SetActive(activeState);
this->UpdateColors();
}
void NativeTabFolder::CloseButtonClicked(AbstractTabItem* item)
{
this->FireEvent(TabFolderEvent::EVENT_CLOSE, item);
}
QSize NativeTabFolder::ComputeSize(int /*widthHint*/, int /*heightHint*/)
{
return QSize(50,50);
}
AbstractTabItem* NativeTabFolder::Add(int index, int flags)
{
auto item = new NativeTabItem(this, index, flags);
return item;
}
void NativeTabFolder::Move(int from, int to)
{
int tabCount = tabControl->count();
if (to > tabCount) to = tabCount;
tabControl->moveAbstractTab(from, to);
}
void NativeTabFolder::Layout(bool flushCache)
{
AbstractTabFolder::Layout(flushCache);
// QRect rect1 = tabControl->geometry();
// QRect rect2 = viewForm->geometry();
// std::cout << "QCTabBar geometry is: x=" << rect1.x() << ", y=" << rect1.y() << ", width=" << rect1.width() << ", height=" << rect1.height() << std::endl;
// std::cout << "ViewForm geometry is: " << rect2.x() << ", y=" << rect2.y() << ", width=" << rect2.width() << ", height=" << rect2.height() << std::endl;
// Rectangle oldBounds = viewForm.getBounds();
// Rectangle newBounds = control.getClientArea();
//
// viewForm.setBounds(newBounds);
//
// if (Util.equals(oldBounds, newBounds))
// {
// viewForm.layout(flushCache);
// }
}
QPoint NativeTabFolder::GetPaneMenuLocation()
{
return AbstractTabFolder::GetPaneMenuLocation();
//return systemToolbar.getPaneMenuLocation();
}
void NativeTabFolder::SetState(int state)
{
AbstractTabFolder::SetState(state);
//systemToolbar.setState(state);
}
QRect NativeTabFolder::GetClientArea()
{
if (content == nullptr)
{
return QRect();
}
return content->geometry();
}
QList<AbstractTabItem*> NativeTabFolder::GetItems()
{
return tabControl->getTabs();
}
void NativeTabFolder::SetSelection(AbstractTabItem* toSelect)
{
if (toSelect == nullptr)
{
return;
}
tabControl->setCurrentTab(toSelect);
}
void NativeTabFolder::SetSelectedInfo(const PartInfo& /*info*/)
{
// if (!Util.equals(title.getText(), info.title))
// {
// title.setText(info.title);
// }
// if (title.getImage() != info.image)
// {
// title.setImage(info.image);
// }
}
QRect NativeTabFolder::GetTabArea()
{
return tabControl->geometry();
// Rectangle bounds = control.getBounds();
//
// Rectangle clientArea = control.getClientArea();
//
// bounds.x = 0;
// bounds.y = 0;
// Geometry.expand(bounds, 0, 0, -(clientArea.height + clientArea.y), 0);
//
// return Geometry.toDisplay(control.getParent(), bounds);
}
QWidget* NativeTabFolder::GetControl()
{
return viewForm;
}
bool NativeTabFolder::IsOnBorder(const QPoint& /*globalPos*/)
{
// Point localPos = getControl().toControl(globalPos);
//
// Rectangle clientArea = getClientArea();
// return localPos.y > clientArea.y && localPos.y < clientArea.y
// + clientArea.height;
return false;
}
AbstractTabItem* NativeTabFolder::GetSelection()
{
return tabControl->getCurrentTab();
}
QWidget* NativeTabFolder::GetContentParent()
{
return contentFrame;
}
void NativeTabFolder::SetContent(QWidget* newContent)
{
//viewForm.setContent(newContent);
if (content != nullptr)
{
contentFrame->layout()->removeWidget(content);
disconnect(content);
}
content = newContent;
content->installEventFilter(this);
//((QBoxLayout*)contentFrame->layout())->addWidget(content, 1);
contentFrame->layout()->addWidget(content);
}
QCTabBar* NativeTabFolder::GetTabFolder()
{
return tabControl;
}
void NativeTabFolder::SetSelectedTitle(const QString& /*newTitle*/)
{
//title.setText(newTitle);
}
void NativeTabFolder::SetSelectedImage(const QPixmap* /*image*/)
{
//title.setImage(image);
}
AbstractTabItem* NativeTabFolder::GetItem(const QPoint& toFind)
{
QPoint localPoint = tabControl->mapFromGlobal(toFind);
int index = tabControl->tabAt(localPoint);
if (index < 0)
return nullptr;
return tabControl->getTab(index);
}
void NativeTabFolder::EnablePaneMenu(bool /*enabled*/)
{
//systemToolbar.enablePaneMenu(enabled);
}
}
| 27.489011 | 158 | 0.673796 | [
"geometry"
] |
743af15f53f7c3364c0d163c2bd2d6ee45eb75ca | 1,155 | hxx | C++ | Code/Tools/Standalone/Source/Driller/Replica/ReplicaTreeViewModel.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Code/Tools/Standalone/Source/Driller/Replica/ReplicaTreeViewModel.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Code/Tools/Standalone/Source/Driller/Replica/ReplicaTreeViewModel.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef DRILLER_REPLICA_REPLICATREEVIEWMODELS_H
#define DRILLER_REPLICA_REPLICATREEVIEWMODELS_H
#if !defined(Q_MOC_RUN)
#include <QAbstractItemModel>
#include "Source/Driller/Replica/ReplicaDisplayHelpers.h"
#endif
namespace Driller
{
class ReplicaTreeViewModel
: public QAbstractItemModel
{
Q_OBJECT
protected:
ReplicaTreeViewModel(QObject* parent = nullptr);
public:
AZ_CLASS_ALLOCATOR(ReplicaTreeViewModel,AZ::SystemAllocator,0);
virtual ~ReplicaTreeViewModel();
int rowCount(const QModelIndex& parentIndex = QModelIndex()) const override;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
QModelIndex parent(const QModelIndex& index) const;
protected:
virtual int GetRootRowCount() const = 0;
virtual const BaseDisplayHelper* FindDisplayHelperAtRoot(int row) const = 0;
};
}
#endif
| 24.574468 | 100 | 0.719481 | [
"3d"
] |
743c61372f5290e1762e330d1dba9910d7a1501b | 723 | cpp | C++ | data/dailyCodingProblem184.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | 2 | 2020-09-04T20:56:23.000Z | 2021-06-11T07:42:26.000Z | data/dailyCodingProblem184.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | data/dailyCodingProblem184.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Given n numbers, find the greatest common denominator between them.
For example, given the numbers [42, 56, 14], return 14.
*/
int gcd(int a, int b, unordered_map<string, int>& seen){
if(b == 0) return a;
string find_string = to_string(a) + "$" + to_string(b);
if(seen.find(find_string) != seen.end()) return seen[find_string];
int ans = gcd(b, a%b, seen);
seen[find_string] = ans;
return ans;
}
int greatestCommonDenominator(vector<int> arr){
int ans = 0;
unordered_map<string, int> seen;
for(int i : arr){
ans = gcd(i, ans, seen);
}
return ans;
}
// main function
int main(){
cout << greatestCommonDenominator({42, 56, 14}) << "\n";
return 0;
} | 20.083333 | 67 | 0.658368 | [
"vector"
] |
74455c5162471aae5f98361cc7f02c47ec9b953f | 3,154 | hpp | C++ | core/shuffle_combiner_factory.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | 1 | 2019-01-23T02:10:10.000Z | 2019-01-23T02:10:10.000Z | core/shuffle_combiner_factory.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | core/shuffle_combiner_factory.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 Husky Team
//
// 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 <mutex>
#include <unordered_map>
#include <utility>
#include <vector>
#include "core/shuffler.hpp"
namespace husky {
class ShuffleCombinerSetBase {
public:
virtual ~ShuffleCombinerSetBase() {}
};
template <typename KeyT, typename MsgT>
class ShuffleCombinerSet : public ShuffleCombinerSetBase {
public:
std::vector<ShuffleCombiner<std::pair<KeyT, MsgT>>> data;
};
class ShuffleCombinerFactory {
public:
template <typename KeyT, typename MsgT>
static std::vector<ShuffleCombiner<std::pair<KeyT, MsgT>>>* create_shuffle_combiner(size_t channel_id,
size_t local_id,
size_t num_local_threads,
size_t num_global_threads) {
// double-checked locking
if (shuffle_combiners_map.find(channel_id) == shuffle_combiners_map.end()) {
std::lock_guard<std::mutex> lock(shuffle_combiners_map_mutex);
if (shuffle_combiners_map.find(channel_id) == shuffle_combiners_map.end()) {
ShuffleCombinerSet<KeyT, MsgT>* shuffle_combiner_set = new ShuffleCombinerSet<KeyT, MsgT>();
shuffle_combiner_set->data.resize(num_local_threads);
for (auto& s : shuffle_combiner_set->data) {
s.init(num_global_threads);
}
ShuffleCombinerFactory::num_local_threads.insert(std::make_pair(channel_id, num_local_threads));
shuffle_combiners_map.insert(std::make_pair(channel_id, shuffle_combiner_set));
}
}
auto& data = dynamic_cast<ShuffleCombinerSet<KeyT, MsgT>*>(shuffle_combiners_map[channel_id])->data;
// data[local_id].init();
return &data;
}
static void remove_shuffle_combiner(size_t channel_id) {
std::lock_guard<std::mutex> lock(shuffle_combiners_map_mutex);
num_local_threads[channel_id] -= 1;
if (num_local_threads[channel_id] == 0) {
delete shuffle_combiners_map[channel_id];
shuffle_combiners_map.erase(channel_id);
num_local_threads.erase(channel_id);
}
}
protected:
static std::unordered_map<size_t, ShuffleCombinerSetBase*> shuffle_combiners_map;
static std::mutex shuffle_combiners_map_mutex;
static std::unordered_map<size_t, size_t> num_local_threads;
};
} // namespace husky
| 39.924051 | 116 | 0.642993 | [
"vector"
] |
744eb02deecef5cebddcb016cf853c8424cfca3a | 5,299 | hpp | C++ | atomics/Average.hpp | ksuryakrishna/Blind_and_Lighting_Controller | 008f1fb734a3c6a1e5598b42de687ca1c4583bc9 | [
"MIT"
] | null | null | null | atomics/Average.hpp | ksuryakrishna/Blind_and_Lighting_Controller | 008f1fb734a3c6a1e5598b42de687ca1c4583bc9 | [
"MIT"
] | null | null | null | atomics/Average.hpp | ksuryakrishna/Blind_and_Lighting_Controller | 008f1fb734a3c6a1e5598b42de687ca1c4583bc9 | [
"MIT"
] | 1 | 2020-05-31T10:51:41.000Z | 2020-05-31T10:51:41.000Z | /*
* By: Harish & Surya Krishna
* ARSLab - Carleton University
*/
#ifndef BOOST_SIMULATION_PDEVS_AVERAGE_HPP
#define BOOST_SIMULATION_PDEVS_AVERAGE_HPP
#include <cadmium/modeling/ports.hpp>
#include <cadmium/modeling/message_bag.hpp>
#include <limits>
#include <math.h>
#include <assert.h>
#include <memory>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <algorithm>
#include <limits>
#include <random>
using namespace cadmium;
using namespace std;
//Port definition
struct Avg_Room {
//Output ports
struct light_intensity : public out_port<float> { };
struct occupy : public out_port<bool> { };
//Input ports
struct Room1 : public in_port<float> { };
struct Room2 : public in_port<float> { };
struct Room3 : public in_port<float> { };
struct Room4 : public in_port<float> { };
struct occ1 : public in_port<bool> { };
struct occ2 : public in_port<bool> { };
struct occ3 : public in_port<bool> { };
struct occ4 : public in_port<bool> { };
};
template<typename TIME>
class Avg_Sens {
using defs=Avg_Room; // putting definitions in context
public:
//Parameters to be overwriten when instantiating the atomic model
// default constructor
Avg_Sens() noexcept{
state.r_1 = 0.0;
state.r_2 = 0.0;
state.r_3 = 0.0;
state.r_4 = 0.0;
state.occ_1 = 0;
state.occ_2 = 0;
state.occ_3 = 0;
state.occ_4 = 0;
state.light = 0.0;
state.occ = 0;
}
// state definition
struct state_type{
bool type;
float r_1;
float r_2;
float r_3;
float r_4;
bool occ_1;
bool occ_2;
bool occ_3;
bool occ_4;
bool occ;
float light;
};
state_type state;
// ports definition
using input_ports=std::tuple<typename defs::Room1, typename defs::Room2, typename defs::Room3, typename defs::Room4, typename defs::occ1, typename defs::occ2, typename defs::occ3, typename defs::occ4>;
using output_ports=std::tuple<typename defs::light_intensity, typename defs::occupy>;
// internal transition
void internal_transition() {
state.type = false;
//Do nothing...
}
// external transition
void external_transition(TIME e, typename make_message_bags<input_ports>::type mbs) {
for(const auto &x : get_messages<typename defs::Room1>(mbs))
state.r_1 = x;
for(const auto &x : get_messages<typename defs::Room2>(mbs))
state.r_2 = x;
for(const auto &x : get_messages<typename defs::Room3>(mbs))
state.r_3 = x;
for(const auto &x : get_messages<typename defs::Room4>(mbs))
state.r_4 = x;
for(const auto &x : get_messages<typename defs::occ1>(mbs))
state.occ_1 = x;
for(const auto &x : get_messages<typename defs::occ2>(mbs))
state.occ_2 = x;
for(const auto &x : get_messages<typename defs::occ3>(mbs))
state.occ_3 = x;
for(const auto &x : get_messages<typename defs::occ4>(mbs))
state.occ_4 = x;
if(state.occ_1 || state.occ_2 || state.occ_3 || state.occ_4)
state.occ = 1;
state.light = 0.25 * (state.r_1 + state.r_2 + state.r_3 + state.r_4);
state.type = true;
}
// confluence transition
void confluence_transition(TIME e, typename make_message_bags<input_ports>::type mbs) {
internal_transition();
external_transition(TIME(), std::move(mbs));
}
// output function
typename make_message_bags<output_ports>::type output() const {
typename make_message_bags<output_ports>::type bags;
get_messages<typename defs::light_intensity>(bags).push_back(state.light);
get_messages<typename defs::occupy>(bags).push_back(state.occ);
return bags;
}
// time_advance function
TIME time_advance() const {
if(state.type)
return TIME("00:00:01");
return std::numeric_limits<TIME>::infinity();
}
friend std::ostringstream& operator<<(std::ostringstream& os, const typename Avg_Sens<TIME>::state_type& i) {
os << "Current state: " << i.light;
return os;
}
};
#endif // BOOST_SIMULATION_PDEVS_AVERAGE_HPP | 32.913043 | 214 | 0.513682 | [
"model"
] |
745301fe86809d5b1e967bb9dff21be0cb0e64be | 1,960 | cpp | C++ | source/common/mesh/Material.cpp | MoaazZaki/coolGameEngine | 2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae | [
"MIT"
] | 2 | 2021-01-18T20:51:54.000Z | 2021-11-01T08:41:38.000Z | source/common/mesh/Material.cpp | MoaazZaki/coolGameEngine | 2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae | [
"MIT"
] | null | null | null | source/common/mesh/Material.cpp | MoaazZaki/coolGameEngine | 2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae | [
"MIT"
] | null | null | null | #include "Material.hpp"
#include <vector>
// pairing the values with their names and giving them size
famm::Material::Material(ShaderProgram* shader){
s = shader;
}
void famm::Material::updateProperty(std::string name , float value)
{
UniformScalar[locationMap[name]] = value;
}
void famm::Material::updateProperty(std::string name , glm::vec2 value)
{
UniformVector2[locationMap[name]] = value;
}
void famm::Material::updateProperty(std::string name , glm::vec3 value)
{
UniformVector3[locationMap[name]] = value;
}
void famm::Material::updateProperty(std::string name , glm::vec4 value)
{
UniformVector4[locationMap[name]] = value;
}
void famm::Material::updateProperty(std::string name , glm::mat4 value)
{
UniformMatrix4[locationMap[name]] = value;
}
// filling the scalar vector
void famm::Material::addProperty(std::string name, float variable)
{
GLuint location = s->getUniformLocation(name);
locationMap[name] = location;
UniformScalar[location]= variable;
}
// filling vector(2) vector
void famm::Material::addProperty(std::string name, glm::vec2 variable)
{
GLuint location = s->getUniformLocation(name);
locationMap[name] = location;
UniformVector2[location] = variable;
}
// filling vector(3) vector
void famm::Material::addProperty(std::string name, glm::vec3 variable)
{
GLuint location = s->getUniformLocation(name);
locationMap[name] = location;
UniformVector3[location] = variable;
}
void famm::Material::addProperty(std::string name, glm::vec4 variable)
{
GLuint location = s->getUniformLocation(name);
locationMap[name] = location;
UniformVector4[location] = variable;
}
void famm::Material::addProperty(std::string name, glm::mat4 variable)
{
GLuint location = s->getUniformLocation(name);
locationMap[name] = location;
UniformMatrix4[location] = variable;
}
void famm::Material::addTextureSampler(Texture2D* texture, Sampler* sampler)
{
materialTextures.push_back(std::make_pair(texture, sampler));
} | 25.128205 | 76 | 0.746939 | [
"vector"
] |
74545887d50e1da0e8d713c6b80b24dee6faa4c7 | 1,454 | cpp | C++ | merkle-hellman-knapsack/encryption.cpp | ruthussanketh/cryptography | 853111c8b6be58013b41bd10a2322890afdbf21c | [
"CC0-1.0"
] | 2 | 2021-06-08T17:46:08.000Z | 2021-09-13T15:19:36.000Z | merkle-hellman-knapsack/encryption.cpp | ruthussanketh/cryptography | 853111c8b6be58013b41bd10a2322890afdbf21c | [
"CC0-1.0"
] | null | null | null | merkle-hellman-knapsack/encryption.cpp | ruthussanketh/cryptography | 853111c8b6be58013b41bd10a2322890afdbf21c | [
"CC0-1.0"
] | 1 | 2020-12-15T12:38:25.000Z | 2020-12-15T12:38:25.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Public_Weights {
public:
int weight;
};
class Plaintext {
public:
int plaintext;
};
int MerkleHellmanEncrypt(vector<Public_Weights>PublicWeights, vector<Plaintext>xPlaintext)
{
int ciphertext=0;
unsigned size = PublicWeights.size();
for (unsigned i=0;i<size;i++) {
ciphertext += PublicWeights[i].weight*xPlaintext[i].plaintext;
}
return ciphertext;
}
int main()
{
int n, a, b, C;
cout<<"Enter the number of weights - ";
cin>>n;
std::vector<Public_Weights>public_weights_vector (n);
std::vector<Plaintext>plaintext_vector (n);
for (unsigned i=0; i<public_weights_vector.size(); i++)
{
cout<<"Weight "<<i+1<<" - ";
cin>>a;
public_weights_vector[i].weight=a;
}
while(1)
{
cout<<"\nEnter the binary plaintext sequence - ";
cin>>b;
for (unsigned i = 0; i<plaintext_vector.size(); i++)
{
int digit = b%10;
b /= 10;
if (digit!=1 && digit!=0)
{
cout<<"\nPlaintext must be a binary integer.";
exit(0);
}
else
{
plaintext_vector[plaintext_vector.size()-1-i].plaintext = digit;
}
}
C = MerkleHellmanEncrypt(public_weights_vector, plaintext_vector);
cout<<"\nThe ciphertext is - "<<C<<"\n";
}
}
| 22.369231 | 91 | 0.568776 | [
"vector"
] |
745d7c7832eed4f897d444f61a01f16b0580d5ba | 18,708 | cpp | C++ | Dx12Core/Src/GraphicsDevice.cpp | Impulse21/GraphicsLearning-Dx12 | bbe165f6a75408505c1dbab3b5030dcdd31cceb8 | [
"MIT"
] | 1 | 2022-03-26T00:57:06.000Z | 2022-03-26T00:57:06.000Z | Dx12Core/Src/GraphicsDevice.cpp | Impulse21/GraphicsLearning-Dx12 | bbe165f6a75408505c1dbab3b5030dcdd31cceb8 | [
"MIT"
] | null | null | null | Dx12Core/Src/GraphicsDevice.cpp | Impulse21/GraphicsLearning-Dx12 | bbe165f6a75408505c1dbab3b5030dcdd31cceb8 | [
"MIT"
] | null | null | null | #include "Dx12Core/GraphicsDevice.h"
#include "Dx12Core/Dx12Queue.h"
#include "Dx12DescriptorHeap.h"
using namespace Dx12Core;
Dx12Core::GraphicsDevice::GraphicsDevice(GraphicsDeviceDesc desc, Dx12Context& context)
: m_context(context)
, m_desc(std::move(desc))
{
this->m_queues[static_cast<size_t>(CommandQueue::Graphics)]
= std::make_unique<Dx12Queue>(this->m_context, D3D12_COMMAND_LIST_TYPE_DIRECT);
if (this->m_desc.EnableComputeQueue)
{
this->m_queues[static_cast<size_t>(CommandQueue::Compute)]
= std::make_unique<Dx12Queue>(this->m_context, D3D12_COMMAND_LIST_TYPE_COMPUTE);
}
if (this->m_desc.EnableCopyQueue)
{
this->m_queues[static_cast<size_t>(CommandQueue::Copy)]
= std::make_unique<Dx12Queue>(this->m_context, D3D12_COMMAND_LIST_TYPE_COPY);
}
this->m_renderTargetViewHeap =
std::make_unique<StaticDescriptorHeap>(
this->m_context,
D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
desc.RenderTargetViewHeapSize);
this->m_depthStencilViewHeap =
std::make_unique<StaticDescriptorHeap>(
this->m_context,
D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
desc.DepthStencilViewHeapSize);
this->m_shaderResourceViewHeap=
std::make_unique<StaticDescriptorHeap>(
this->m_context,
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
desc.DepthStencilViewHeapSize,
true);
}
Dx12Core::GraphicsDevice::~GraphicsDevice()
{
this->WaitForIdle();
this->m_swapChainTextures.clear();
this->m_context.Device5.Reset();
this->m_context.Device2.Reset();
this->m_context.Device.Reset();
}
void Dx12Core::GraphicsDevice::InitializeSwapcChain(SwapChainDesc const& swapChainDesc)
{
assert(swapChainDesc.WindowHandle);
if (!swapChainDesc.WindowHandle)
{
LOG_CORE_ERROR("Invalid window handle");
throw std::runtime_error("Invalid Window Error");
}
DXGI_SWAP_CHAIN_DESC1 dx12Desc = {};
dx12Desc.Width = swapChainDesc.Width;
dx12Desc.Height = swapChainDesc.Height;
dx12Desc.Format = swapChainDesc.Format;
dx12Desc.SampleDesc.Count = 1;
dx12Desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
dx12Desc.BufferCount = swapChainDesc.NumBuffers;
dx12Desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
dx12Desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
RefCountPtr<IDXGISwapChain1> tmpSwapChain;
ThrowIfFailed(
this->m_context.Factory->CreateSwapChainForHwnd(
this->m_queues[D3D12_COMMAND_LIST_TYPE_DIRECT]->GetNative(),
swapChainDesc.WindowHandle,
&dx12Desc,
nullptr,
nullptr,
&tmpSwapChain));
ThrowIfFailed(
tmpSwapChain->QueryInterface(&this->m_swapChain));
this->m_swapChainDesc = swapChainDesc;
this->m_frames.resize(this->m_swapChainDesc.NumBuffers);
this->InitializeRenderTargets();
}
ICommandContext& Dx12Core::GraphicsDevice::BeginContext()
{
std::scoped_lock(this->m_commandListMutex);
ContextId contextId = this->m_activeContext++;
assert(contextId < MAX_COMMAND_CONTEXT);
if (!this->m_commandContexts[contextId])
{
this->m_commandContexts[contextId] =
std::make_unique<Dx12CommandContext>(
this->m_context.Device2,
D3D12_COMMAND_LIST_TYPE_DIRECT,
std::wstring(L"Command List: ") + std::to_wstring(contextId));
}
else
{
this->m_commandContexts[contextId]->Reset(this->GetGfxQueue()->GetLastCompletedFence());
}
this->m_commandContexts[contextId]->BindHeaps({ this->m_shaderResourceViewHeap.get(), this->m_samplerHeap.get() });
return *this->m_commandContexts[contextId];
}
uint64_t Dx12Core::GraphicsDevice::Submit(bool waitForCompletion)
{
std::scoped_lock(this->m_commandListMutex);
ContextId cmdLast = this->m_activeContext;
this->m_activeContext = 0;
this->m_commandListsToExecute.resize(cmdLast);
for (ContextId i = 0; i < cmdLast; i++)
{
Dx12CommandContext& context = *this->m_commandContexts[i];
context.Close();
this->m_commandListsToExecute[i] = context.GetInternal();
}
uint64_t fence = this->GetGfxQueue()->ExecuteCommandLists(this->m_commandListsToExecute);
for (ContextId i = 0; i < cmdLast; i++)
{
auto trackedResources = this->m_commandContexts[i]->Executed(fence);
this->GetCurrentFrame().ReferencedResources.push_back(trackedResources);
}
if (waitForCompletion)
{
this->GetGfxQueue()->WaitForFence(fence);
}
return fence;
}
void Dx12Core::GraphicsDevice::BeginFrame()
{
uint32_t bufferIndex = this->GetCurrentBackBufferIndex();
Frame& frame = this->GetCurrentFrame();
this->GetGfxQueue()->WaitForFence(frame.FrameFence);
frame.ReferencedResources.clear();
}
void Dx12Core::GraphicsDevice::Present()
{
this->m_swapChain->Present(0, 0);
this->GetCurrentFrame().FrameFence = this->GetGfxQueue()->IncrementFence();
this->m_frame = (this->m_frame + 1) % this->m_swapChainDesc.NumBuffers;
}
void Dx12Core::GraphicsDevice::WaitForIdle() const
{
for (auto& queue : this->m_queues)
{
if (queue)
{
queue->WaitForIdle();
}
}
}
DescriptorIndex Dx12Core::GraphicsDevice::GetDescritporIndex(ITexture* texture) const
{
Texture* internal = SafeCast<Texture*>(texture);
return internal->Srv.GetIndex();
}
DescriptorIndex Dx12Core::GraphicsDevice::GetDescritporIndex(IBuffer* buffer) const
{
Buffer* internal = SafeCast<Buffer*>(buffer);
return internal->Srv.GetIndex();
}
TextureHandle Dx12Core::GraphicsDevice::CreateTexture(TextureDesc desc)
{
// Use unique ptr here to ensure safety until we are able to pass this over to the texture handle
std::unique_ptr<Texture> internal = std::make_unique<Texture>(this, desc);
D3D12_CLEAR_VALUE optimizedClearValue = {};
if (desc.OptmizedClearValue.has_value())
{
optimizedClearValue.Format = desc.Format;
optimizedClearValue.DepthStencil = desc.OptmizedClearValue.value().DepthStencil;
}
D3D12_RESOURCE_FLAGS resourceFlags = D3D12_RESOURCE_FLAG_NONE;
if (BindFlags::DepthStencil == (desc.Bindings | BindFlags::DepthStencil))
{
resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
}
ThrowIfFailed(
this->m_context.Device2->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Tex2D(
desc.Format, desc.Width, desc.Height,
desc.ArraySize,
desc.MipLevels,
1,
0,
resourceFlags),
desc.InitialState,
desc.OptmizedClearValue.has_value() ? &optimizedClearValue : nullptr,
IID_PPV_ARGS(&internal->D3DResource)
));
std::wstring debugName(desc.DebugName.begin(), desc.DebugName.end());
internal->D3DResource->SetName(debugName.c_str());
// Create Views
if (BindFlags::DepthStencil == (desc.Bindings | BindFlags::DepthStencil))
{
internal->Dsv = this->m_depthStencilViewHeap->AllocateDescriptor();
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
dsvDesc.Format = desc.Format;
dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; // TODO: use desc.
dsvDesc.Texture2D.MipSlice = 0;
dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
this->m_context.Device2->CreateDepthStencilView(
internal->D3DResource,
&dsvDesc,
internal->Dsv.GetCpuHandle());
}
else if (BindFlags::ShaderResource == (desc.Bindings | BindFlags::ShaderResource))
{
internal->Srv = this->m_shaderResourceViewHeap->AllocateDescriptor();
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = desc.Format; // TODO: handle SRGB format
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
if (desc.Dimension == TextureDimension::TextureCube)
{
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; // Only 2D textures are supported (this was checked in the calling function).
srvDesc.TextureCube.MipLevels = desc.MipLevels;
srvDesc.TextureCube.MostDetailedMip = 0;
}
else
{
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; // Only 2D textures are supported (this was checked in the calling function).
srvDesc.Texture2D.MipLevels = internal->GetDesc().MipLevels;
}
this->m_context.Device2->CreateShaderResourceView(
internal->D3DResource,
&srvDesc,
internal->Srv.GetCpuHandle());
}
return TextureHandle::Create(internal.release());
}
TextureHandle Dx12Core::GraphicsDevice::CreateTextureFromNative(TextureDesc desc, RefCountPtr<ID3D12Resource> native)
{
// Use unique ptr here to ensure safety until we are able to pass this over to the texture handle
std::unique_ptr<Texture> internal = std::make_unique<Texture>(this, desc);
internal->D3DResource = native;
if ((internal->GetDesc().Bindings & BindFlags::RenderTarget) == BindFlags::RenderTarget)
{
internal->Rtv = this->m_renderTargetViewHeap->AllocateDescriptor();
this->m_context.Device2->CreateRenderTargetView(internal->D3DResource, nullptr, internal->Rtv.GetCpuHandle());
}
std::wstring debugName(internal->GetDesc().DebugName.begin(), internal->GetDesc().DebugName.end());
internal->D3DResource->SetName(debugName.c_str());
return TextureHandle::Create(internal.release());
}
BufferHandle Dx12Core::GraphicsDevice::CreateBuffer(BufferDesc desc)
{
D3D12_RESOURCE_FLAGS resourceFlags = D3D12_RESOURCE_FLAG_NONE;
if ((desc.BindFlags | BindFlags::UnorderedAccess) == BindFlags::UnorderedAccess)
{
resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
}
std::unique_ptr<Buffer> internal = std::make_unique<Buffer>(std::move(desc));
// Create a committed resource for the GPU resource in a default heap.
ThrowIfFailed(
this->m_context.Device2->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(internal->GetDesc().SizeInBytes, resourceFlags),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&internal->D3DResource)));
internal->D3DResource->SetName(internal->GetDesc().DebugName.c_str());
if (BindFlags::VertexBuffer == (internal->GetDesc().BindFlags | BindFlags::VertexBuffer))
{
internal->VertexView = {};
auto& view = internal->VertexView;
view.BufferLocation = internal->D3DResource->GetGPUVirtualAddress();
view.StrideInBytes = internal->GetDesc().StrideInBytes;
view.SizeInBytes = internal->GetDesc().SizeInBytes;
}
else if (BindFlags::IndexBuffer == (internal->GetDesc().BindFlags | BindFlags::IndexBuffer))
{
auto& view = internal->IndexView;
view.BufferLocation = internal->D3DResource->GetGPUVirtualAddress();
view.Format = internal->GetDesc().StrideInBytes == sizeof(uint32_t)
? DXGI_FORMAT_R32_UINT
: DXGI_FORMAT_R16_UINT;
view.SizeInBytes = internal->GetDesc().SizeInBytes;
}
else if (BindFlags::ShaderResource == (internal->GetDesc().BindFlags | BindFlags::ShaderResource))
{
internal->Srv = this->m_shaderResourceViewHeap->AllocateDescriptor();
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Buffer.FirstElement = 0;
srvDesc.Buffer.NumElements = internal->GetDesc().SizeInBytes/ internal->GetDesc().StrideInBytes;
srvDesc.Buffer.StructureByteStride = internal->GetDesc().StrideInBytes;
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
this->m_context.Device2->CreateShaderResourceView(
internal->D3DResource,
&srvDesc,
internal->Srv.GetCpuHandle());
}
return BufferHandle::Create(internal.release());
}
ShaderHandle Dx12Core::GraphicsDevice::CreateShader(ShaderDesc const& desc, const void* binary, size_t binarySize)
{
Shader* internal = new Shader(desc, binary, binarySize);
// TODO: Shader Reflection data
return ShaderHandle::Create(internal);
}
GraphicsPipelineHandle Dx12Core::GraphicsDevice::CreateGraphicPipeline(GraphicsPipelineDesc desc)
{
struct PipelineStateStream
{
CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature;
CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT InputLayout;
CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType;
CD3DX12_PIPELINE_STATE_STREAM_VS VS;
CD3DX12_PIPELINE_STATE_STREAM_PS PS;
CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState;
CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL DepthStencilState;
CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState;
CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat;
CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats;
} pipelineStateStream;
RootSignatureHandle rootSig =
desc.UseShaderParameters
? this->CreateRootSignature(
desc.ShaderParameters.Flags,
desc.ShaderParameters.Binding,
desc.ShaderParameters.Bindless)
: this->CreateRootSignature(desc.RootSignatureDesc);
pipelineStateStream.pRootSignature = rootSig->D3DRootSignature;
// TODO:
// pipelineStateStream.InputLayout = { inputLayout, _countof(inputLayout) };
pipelineStateStream.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
pipelineStateStream.VS = CD3DX12_SHADER_BYTECODE(desc.VS->GetByteCode().data(), desc.VS->GetByteCode().size());
pipelineStateStream.PS = CD3DX12_SHADER_BYTECODE(desc.PS->GetByteCode().data(), desc.PS->GetByteCode().size());
pipelineStateStream.InputLayout = { desc.InputLayout.data(), static_cast<UINT>(desc.InputLayout.size()) };
D3D12_RT_FORMAT_ARRAY rtvFormats = {};
rtvFormats.NumRenderTargets = std::min(8U, (UINT)desc.RenderState.RtvFormats.size());
for (int i = 0; i < rtvFormats.NumRenderTargets; i < i++)
{
rtvFormats.RTFormats[i] = desc.RenderState.RtvFormats[i];
}
pipelineStateStream.RTVFormats = rtvFormats;
if (desc.RenderState.DsvFormat != DXGI_FORMAT_UNKNOWN)
{
pipelineStateStream.DSVFormat = desc.RenderState.DsvFormat;
}
if (desc.RenderState.RasterizerState)
{
pipelineStateStream.RasterizerState = *desc.RenderState.RasterizerState;
}
if (desc.RenderState.DepthStencilState)
{
pipelineStateStream.DepthStencilState = *desc.RenderState.DepthStencilState;
}
if (desc.RenderState.BlendState)
{
pipelineStateStream.BlendState = *desc.RenderState.BlendState;
}
D3D12_PIPELINE_STATE_STREAM_DESC pipelineStateStreamDesc =
{
sizeof(PipelineStateStream),
&pipelineStateStream
};
RefCountPtr<ID3D12PipelineState> pipelineState;
ThrowIfFailed(
this->m_context.Device2->CreatePipelineState(
&pipelineStateStreamDesc,
IID_PPV_ARGS(&pipelineState)));
auto graphicsPipelineState = std::make_unique<GraphicsPipeline>(std::move(desc));
graphicsPipelineState->D3DPipelineState = pipelineState;
graphicsPipelineState->RootSignature = rootSig;
if (desc.UseShaderParameters && desc.ShaderParameters.Bindless)
{
graphicsPipelineState->HasBindlessParamaters = true;
graphicsPipelineState->bindlessResourceTable = this->m_shaderResourceViewHeap->GetGpuHandle();
}
return GraphicsPipelineHandle::Create(graphicsPipelineState.release());
}
RootSignatureHandle Dx12Core::GraphicsDevice::CreateRootSignature(RootSignatureDesc& desc)
{
auto d3dRootSig = this->CreateD3DRootSignature(std::move(desc.BuildDx12Desc()));
std::unique_ptr<RootSignature> rootSignature = std::make_unique<RootSignature>(d3dRootSig);
return RootSignatureHandle::Create(rootSignature.release());
}
RootSignatureHandle Dx12Core::GraphicsDevice::CreateRootSignature(
D3D12_ROOT_SIGNATURE_FLAGS flags,
ShaderParameterLayout* shaderParameter,
BindlessShaderParameterLayout* bindlessLayout)
{
std::vector<CD3DX12_ROOT_PARAMETER1> parameters;
std::vector<CD3DX12_STATIC_SAMPLER_DESC> staticSamplers;
if (shaderParameter)
{
// Memcopy, yes please
parameters.resize(shaderParameter->Parameters.size());
std::memcpy(parameters.data(), shaderParameter->Parameters.data(), sizeof(CD3DX12_ROOT_PARAMETER1) * parameters.size());
staticSamplers.resize(shaderParameter->StaticSamplers.size());
std::memcpy(staticSamplers.data(), shaderParameter->StaticSamplers.data(), sizeof(CD3DX12_STATIC_SAMPLER_DESC) * staticSamplers.size());
}
uint32_t bindlessRootParameterOffset = 0;
std::vector<CD3DX12_DESCRIPTOR_RANGE1> descriptorRanges;
if (bindlessLayout)
{
constexpr D3D12_DESCRIPTOR_RANGE_FLAGS flags =
D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
bindlessRootParameterOffset = static_cast<uint32_t>(parameters.size());
descriptorRanges.reserve(bindlessLayout->Parameters.size());
for (auto& param : bindlessLayout->Parameters)
{
assert(param.Type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, "Not Tested");
CD3DX12_DESCRIPTOR_RANGE1& range = descriptorRanges.emplace_back();
range.Init(
param.Type,
bindlessLayout->MaxCapacity,
param.BaseShaderRegister,
param.RegisterSpace,
flags,
bindlessLayout->FirstSlot);
}
CD3DX12_ROOT_PARAMETER1& parameter = parameters.emplace_back();
parameter.InitAsDescriptorTable(
descriptorRanges.size(),
descriptorRanges.data(),
bindlessLayout->Visibility);
}
D3D12_ROOT_SIGNATURE_DESC1 desc = {};
desc.NumParameters = static_cast<UINT>(parameters.size());
desc.pParameters = parameters.data();
desc.NumStaticSamplers = static_cast<UINT>(staticSamplers.size());
desc.pStaticSamplers = staticSamplers.data();
desc.Flags = flags;
auto d3dRootSig = this->CreateD3DRootSignature(std::move(desc));
std::unique_ptr<RootSignature> rootSignature = std::make_unique<RootSignature>(d3dRootSig);
rootSignature->BindlessRootParameterOffset = bindlessRootParameterOffset;
return RootSignatureHandle::Create(rootSignature.release());
}
RefCountPtr<ID3D12RootSignature> Dx12Core::GraphicsDevice::CreateD3DRootSignature(D3D12_ROOT_SIGNATURE_DESC1&& rootSigDesc)
{
D3D12_VERSIONED_ROOT_SIGNATURE_DESC dx12RootSigDesc = {};
dx12RootSigDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
dx12RootSigDesc.Desc_1_1 = rootSigDesc;
// Serialize the root signature
RefCountPtr<ID3DBlob> serializedRootSignatureBlob;
RefCountPtr<ID3DBlob> errorBlob;
ThrowIfFailed(
::D3DX12SerializeVersionedRootSignature(
&dx12RootSigDesc,
this->m_context.FeatureDataRootSignature.HighestVersion,
&serializedRootSignatureBlob,
&errorBlob));
// Create the root signature.
RefCountPtr<ID3D12RootSignature> dx12RootSig = nullptr;
ThrowIfFailed(
this->m_context.Device2->CreateRootSignature(
0,
serializedRootSignatureBlob->GetBufferPointer(),
serializedRootSignatureBlob->GetBufferSize(),
IID_PPV_ARGS(&dx12RootSig)));
return dx12RootSig;
}
void Dx12Core::GraphicsDevice::InitializeRenderTargets()
{
this->m_swapChainTextures.resize(this->m_swapChainDesc.NumBuffers);
for (UINT i = 0; i < this->m_swapChainDesc.NumBuffers; i++)
{
RefCountPtr<ID3D12Resource> backBuffer;
ThrowIfFailed(
this->m_swapChain->GetBuffer(i, IID_PPV_ARGS(&backBuffer)));
auto textureDesc = TextureDesc();
textureDesc.Dimension = TextureDimension::Texture2D;
textureDesc.Format = this->m_swapChainDesc.Format;
textureDesc.Width = this->m_swapChainDesc.Width;
textureDesc.Height = this->m_swapChainDesc.Height;
textureDesc.Bindings = BindFlags::RenderTarget;
this->m_swapChainTextures[i] = this->CreateTextureFromNative(textureDesc, backBuffer);
}
}
| 32.994709 | 138 | 0.779827 | [
"vector"
] |
745f53185ff80fadf622db73f4df9adaed153e5d | 13,212 | cpp | C++ | CESystem/CollisionSystem.cpp | infaldez/CESystem | 7b2f562f0e6f2511fcb4d834a9cc76816bce0ed3 | [
"Unlicense"
] | null | null | null | CESystem/CollisionSystem.cpp | infaldez/CESystem | 7b2f562f0e6f2511fcb4d834a9cc76816bce0ed3 | [
"Unlicense"
] | null | null | null | CESystem/CollisionSystem.cpp | infaldez/CESystem | 7b2f562f0e6f2511fcb4d834a9cc76816bce0ed3 | [
"Unlicense"
] | null | null | null | #include "CollisionSystem.h"
#include <SFML\Graphics.hpp>
#include "Entity.h"
#include "componentDamage.h"
#include "ComponentHealth.h"
#include "ComponentPosition.h"
#include "ComponentAABB.h"
#include "ComponentEvent.h"
#include <unordered_map>
#include <algorithm>
#include <iostream>
/*
TODO
- entities can occupy more than 4 grids
- refactor everything
ISSUES
- different sized grid_rows and grid_colums cause issues
- two moving objects cause weird collisions
- sliding is slower when going right or down
*/
#define SCREENSIZE 5000
#define GRID_ROWS 8
#define GRID_COLUMNS 8
#define GRID_COUNT GRID_ROWS * GRID_COLUMNS
CollisionSystem::CollisionSystem()
{
//initialize gridMap
for (int i = 0; i < GRID_COUNT; ++i)
{
this->gridMap.insert(std::pair<int, std::vector<Entity*>>(i, std::vector<Entity*>()));
}
}
CollisionSystem::~CollisionSystem()
{
}
float sweepTestAABB(Entity* ent1, Entity* ent2, float& normalx, float& normaly)
{
// Entity 1 AABB positions and movement
ComponentPosition* posA = ent1->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentAABB* boxA = ent1->getComponent<ComponentAABB>(components::COMPONENT_AABB);
ComponentMovement* movA = ent1->getComponent<ComponentMovement>(components::COMPONENT_MOVEMENT);
// Entity 2 AABB positions
ComponentPosition* posB = ent2->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentAABB* boxB = ent2->getComponent<ComponentAABB>(components::COMPONENT_AABB);
sf::Vector2f pos2 = posB->getPosition();
sf::Vector2f Ea = boxA->getExtents();
sf::Vector2f A0 = boxA->getPosition(posA->getPreviousPosition());
sf::Vector2f A1 = boxA->getPosition(posA->getPosition());
sf::Vector2f Eb = boxB->getExtents();
sf::Vector2f B0 = boxB->getPosition(posB->getPreviousPosition());
sf::Vector2f B1 = boxB->getPosition(posB->getPosition());
float u0 = 0.0f;
float u1 = 1.0f;
sf::Vector2f va = movA->getVelocity();
sf::Vector2f u_0; // Entry time (x,y)
sf::Vector2f u_1; // Exit time (x,y)
float xEntryDistance, xExitDistance, yEntryDistance, yExitDistance;
// Get the distance of entry and exit points
if (va.x > 0.0f)
{
xEntryDistance = B0.x - (A0.x + Ea.x);
xExitDistance = (B0.x + Eb.x) - A0.x;
}
else
{
xEntryDistance = (B0.x + Eb.x) - A0.x;
xExitDistance = B0.x - (A0.x + Ea.x);
}
if (va.y > 0.0f)
{
yEntryDistance = B0.y - (A0.y + Ea.y);
yExitDistance = (B0.y + Eb.y) - A0.y;
}
else
{
yEntryDistance = (B0.y + Eb.y) - A0.y;
yExitDistance = B0.y - (A0.y + Ea.y);
}
// Get the time of collision entry and exit
if (va.x <= 0.0001f && va.x >= -0.0001)
{
u_0.x = std::numeric_limits<float>::infinity();
u_1.x = std::numeric_limits<float>::infinity();
}
else
{
u_0.x = xEntryDistance / va.x;
u_1.x = xExitDistance / va.x;
}
if (va.y <= 0.0001f && va.y >= -0.0001)
{
u_0.y = std::numeric_limits<float>::infinity();
u_1.y = std::numeric_limits<float>::infinity();
}
else
{
u_0.y = yEntryDistance / va.y;
u_1.y = yExitDistance / va.y;
}
float entryTime = std::max(u_0.x, u_0.y);
float exitTime = std::min(u_1.x, u_1.y);
if (entryTime == std::numeric_limits<float>::infinity())
entryTime = std::min(u_0.x, u_0.y);
if (exitTime == std::numeric_limits<float>::infinity())
exitTime = std::max(u_1.x, u_1.y);
// Check if collision did not happen
if (entryTime > exitTime || entryTime == std::numeric_limits<float>::infinity() || exitTime == std::numeric_limits<float>::infinity())
{
normalx = normaly = 0.0f;
return 1.0f;
}
else
{
if (u_0.x > u_0.y && u_0.x != std::numeric_limits<float>::infinity() || u_0.y == std::numeric_limits<float>::infinity())
{
if (xEntryDistance < 0.0f)
{
normalx = 1.0f;
normaly = 0.0f;
}
else
{
normalx = -1.0f;
normaly = 0.0f;
}
}
else
{
if (yEntryDistance < 0.0f)
{
normalx = 0.0f;
normaly = 1.0f;
}
else
{
normalx = 0.0f;
normaly = -1.0f;
}
}
return entryTime;
}
}
// Return the corner coordinates of the grid
int getGridCoord1(sf::Vector2i pos)
{
pos.x = pos.x / (SCREENSIZE / GRID_COLUMNS);
pos.y = pos.y / (SCREENSIZE / GRID_ROWS);
return pos.x + pos.y * GRID_ROWS;
}
int getGridCoord2(sf::Vector2i pos, sf::Vector2i size)
{
int x = (pos.x + size.x) / (SCREENSIZE / GRID_COLUMNS);
int y = pos.y / (SCREENSIZE / GRID_ROWS);
return x + y * GRID_ROWS;
}
int getGridCoord3(sf::Vector2i pos, sf::Vector2i size)
{
int x = (pos.x + size.x) / (SCREENSIZE / GRID_COLUMNS);
int y = (pos.y + size.y) / (SCREENSIZE / GRID_ROWS);
return x + y * GRID_ROWS;
}
int getGridCoord4(sf::Vector2i pos, sf::Vector2i size)
{
int x = pos.x / (SCREENSIZE / GRID_COLUMNS);
int y = (pos.y + size.y) / (SCREENSIZE / GRID_ROWS);
return x + y * GRID_ROWS;
}
std::vector<int> CollisionSystem::getGridPositions(sf::Vector2i position, sf::Vector2i size)
{
std::vector<int> positions;
positions.push_back(getGridCoord1(position));
positions.push_back(getGridCoord2(position, size));
positions.push_back(getGridCoord3(position, size));
positions.push_back(getGridCoord4(position, size));
return positions;
}
void CollisionSystem::createCollisionMap(std::vector<std::unique_ptr<Entity>>& entityList)
{
for (std::size_t i = 0; i != entityList.size(); ++i)
{
if (entityList.at(i)->componentKey[components::COMPONENT_COLLISION] == true &&
entityList.at(i)->componentKey[components::COMPONENT_AABB] == true &&
entityList.at(i)->componentKey[components::COMPONENT_POSITION] == true)
{
Entity* ent = entityList.at(i).get();
ComponentPosition* cPosition = ent->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentAABB* cAABB = ent->getComponent<ComponentAABB>(components::COMPONENT_AABB);
sf::Vector2i pos = (sf::Vector2i)cPosition->getPosition();
sf::Vector2i offset = (sf::Vector2i)cAABB->getOffsetPosition();
sf::Vector2i size = (sf::Vector2i)cAABB->getExtents();
pos += offset;
std::vector<int> positions = getGridPositions(pos, size);
if (positions[0] < GRID_COUNT &&
positions[0] >= 0)
gridMap.find(positions[0])->second.push_back(ent);
if (positions[1] != positions[0] &&
positions[1] < GRID_COUNT &&
positions[1] >= 0)
gridMap.find(positions[1])->second.push_back(ent);
if (positions[2] != positions[1] &&
positions[2] != positions[3] &&
positions[2] < GRID_COUNT &&
positions[2] >= 0)
gridMap.find(positions[2])->second.push_back(ent);
if (positions[3] != positions[0] &&
positions[3] < GRID_COUNT &&
positions[3] >= 0)
gridMap.find(positions[3])->second.push_back(ent);
}
}
}
void CollisionSystem::clearCollisionMap()
{
for (auto it = gridMap.begin(); it != gridMap.end(); ++it)
it->second.clear();
}
sf::Vector2f getNearestDisplacement(Entity* ent1, Entity* ent2)
{
sf::Vector2f pos1 = ent1->getComponent<ComponentPosition>(components::COMPONENT_POSITION)->getPosition();
sf::Vector2f pos2 = ent2->getComponent<ComponentPosition>(components::COMPONENT_POSITION)->getPosition();
sf::Vector2f size1 = ent1->getComponent<ComponentAABB>(components::COMPONENT_AABB)->getExtents();
sf::Vector2f size2 = ent2->getComponent<ComponentAABB>(components::COMPONENT_AABB)->getExtents();
sf::Vector2f nearestPoint = pos1;
sf::Vector2f center1(pos1.x + (size1.x / 2), pos1.y + (size1.y / 2));
sf::Vector2f center2(pos2.x + (size2.x / 2), pos2.y + (size2.y / 2));
//center distance x, y
float cdx = fabs(center1.x - center2.x);
float cdy = fabs(center1.y - center2.y);
float overlapx = ((size1.x + size2.x) / 2) - cdx;
float overlapy = ((size1.y + size2.y) / 2) - cdy;
if (overlapx * overlapx < overlapy * overlapy)
{
if (center1.x > center2.x)
nearestPoint.x = pos1.x + overlapx;
else
nearestPoint.x = pos1.x - overlapx;
}
else
{
if (center1.y > center2.y)
nearestPoint.y = pos1.y + overlapy;
else
nearestPoint.y = pos1.y - overlapy;
}
return nearestPoint;
}
bool aabbCheck(Entity* ent1, Entity* ent2)
{
// Entity 1 AABB positions
ComponentPosition* posA = ent1->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentAABB* aabbA = ent1->getComponent<ComponentAABB>(components::COMPONENT_AABB);
sf::Vector2f pos1 = posA->getPosition();
sf::Vector2f colPos1 = aabbA->getPosition(pos1);
sf::Vector2f size1 = aabbA->getExtents();
// Entity 2 AABB positions
ComponentPosition* posB = ent2->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentAABB* aabbB = ent2->getComponent<ComponentAABB>(components::COMPONENT_AABB);
sf::Vector2f pos2 = posB->getPosition();
sf::Vector2f size2 = aabbB->getExtents();
sf::Vector2f colPos2 = aabbB->getPosition(pos2);
// Check if there's AABB overlap
if (colPos1.x < colPos2.x + size2.x &&
colPos1.x + size1.x > colPos2.x &&
colPos1.y < colPos2.y + size2.y &&
colPos1.y + size1.y > colPos2.y)
return true;
return false;
}
bool checkGroup(Entity* ent1, Entity* ent2)
{
auto c1 = ent1->getComponent<ComponentCollision>(components::COMPONENT_COLLISION);
auto c2 = ent2->getComponent<ComponentCollision>(components::COMPONENT_COLLISION);
if (c1->belongsToGroup() || c2->belongsToGroup())
{
for (auto g : c1->getGroups())
{
for (auto g2 : c2->getGroups())
{
if (g == g2)
{
return true;
}
}
}
return false;
}
if (!c1->belongsToGroup() && !c2->belongsToGroup())
return true;
}
struct impactData
{
impactData(int aPos, float eTime) : arrayPos(aPos), entryTime(eTime){}
int arrayPos;
float entryTime;
};
void CollisionSystem::runSystem(std::vector<std::unique_ptr<Entity>>& entityList)
{
clearCollisionMap();
createCollisionMap(entityList);
for (auto it = gridMap.begin(); it != gridMap.end(); ++it)
{
for (std::size_t i = 0; i != it->second.size(); ++i)
{
std::vector<impactData> timeOfImpact; // first = j, second = entryTime, normalx, normaly
Entity* ent1 = it->second.at(i);
if (ent1->componentKey[components::COMPONENT_MOVEMENT] == true)
{
for (std::size_t j = 0; j != it->second.size(); ++j)
{
if (j != i)
{
Entity* ent2 = it->second.at(j);
if (aabbCheck(ent1, ent2) && checkGroup(ent1, ent2))
{
// Do a sweep test and push the results into timeOfImpact
float entryTime, normalx, normaly;
entryTime = sweepTestAABB(ent1, ent2, normalx, normaly);
timeOfImpact.push_back(impactData(j, entryTime));
}
}
}
/*
Sort the impacts by entryTime, smallest first
*/
if (timeOfImpact.size() > 1)
{
std::sort(timeOfImpact.begin(), timeOfImpact.end(), [](const impactData &a, const impactData &b) {
return a.entryTime < b.entryTime;
});
}
for (auto toi_it : timeOfImpact)
{
// ent1
ComponentPosition* posA = ent1->getComponent<ComponentPosition>(components::COMPONENT_POSITION);
ComponentMovement* movA = ent1->getComponent<ComponentMovement>(components::COMPONENT_MOVEMENT);
ComponentCollision* colA = ent1->getComponent<ComponentCollision>(components::COMPONENT_COLLISION);
sf::Vector2f oldpos1 = posA->getPreviousPosition();
sf::Vector2f v = movA->getVelocity();
// ent2
Entity* ent2 = it->second.at(toi_it.arrayPos);
ComponentCollision* colB = ent2->getComponent<ComponentCollision>(components::COMPONENT_COLLISION);
if (aabbCheck(ent1, ent2))
{
// Run collision events
if (ent1->componentKey[components::COMPONENT_EVENT] == true){
ent1->getComponent<ComponentEvent>(components::COMPONENT_EVENT)->runCollisionEvents(ent1, ent2, entityList);
}
/*if (ent2->componentKey[components::COMPONENT_EVENT] == true){
ent2->getComponent<ComponentEvent>(components::COMPONENT_EVENT)->runCollisionEvents(ent2, ent1, entityList);
}*/
// if both A and B are solid do collision things
if (colA->getFlag(collisionType::SOLID) && colB->getFlag(collisionType::SOLID))
{
// if only A is moving
if (ent2->componentKey[components::COMPONENT_MOVEMENT] == false)
{
float normalx;
float normaly;
float entryTime = sweepTestAABB(ent1, ent2, normalx, normaly);
oldpos1.x += v.x * entryTime;
oldpos1.y += v.y * entryTime;
float dotproduct = (v.x * normaly + v.y * normalx) + (1.0f - entryTime);
if (dotproduct != 1)
{
if (fabs(v.x) >= 0.0001f)
oldpos1.x = oldpos1.x + (dotproduct * normaly);
if (fabs(v.y) >= 0.0001f)
oldpos1.y = oldpos1.y + (dotproduct * normalx);
// set position twice so that suggested(current) and previous position are same.
posA->setPosition(oldpos1);
posA->setPosition(oldpos1);
}
else
{
// set position twice
posA->setPosition(oldpos1);
posA->setPosition(oldpos1);
}
float xv = dotproduct * normaly;
float yv = dotproduct * normalx;
if (timeOfImpact.size() > 1)
movA->setVelocity(sf::Vector2f(xv, yv));
}
else // Both A and B are moving
{
posA->setPosition(getNearestDisplacement(ent1, ent2));
}
}
}
}
}
}
}
} | 28.110638 | 135 | 0.661066 | [
"vector",
"solid"
] |
7462a7dcca35fd088b5c0ae76d1a8530349edab3 | 7,488 | cpp | C++ | client/skeletonReceiver/src/midi/midiTrigger.cpp | ofZach/piano | 017e2065330701a58f81ba0f41262622aa37d7d1 | [
"MIT"
] | 2 | 2015-02-02T17:38:08.000Z | 2015-06-08T19:02:08.000Z | client/skeletonReceiver/src/midi/midiTrigger.cpp | ofZach/piano | 017e2065330701a58f81ba0f41262622aa37d7d1 | [
"MIT"
] | 10 | 2015-01-20T16:38:53.000Z | 2015-04-21T16:18:19.000Z | client/skeletonReceiver/src/midi/midiTrigger.cpp | ofZach/piano | 017e2065330701a58f81ba0f41262622aa37d7d1 | [
"MIT"
] | null | null | null | #include "midiTrigger.h"
#pragma mark - Interface
midiTrigger::midiTrigger() : _settings() {
}
void midiTrigger::setMidiOut(shared_ptr<ofxMidiOut> midiOut) {
_midiOut = midiOut;
}
shared_ptr<ofxMidiOut> midiTrigger::getMidiOut() {
return _midiOut;
}
void midiTrigger::reset() {
for(const auto& note : getSettings().notes) {
getMidiOut()->sendNoteOff(getSettings().channel, note);
}
}
#pragma mark - Util
float NormalizedHeight(kinectSkeleton& sk, int name, int side) {
if(sk.skeletonHeight == 0) {
return 0;
} else {
ofPoint p = sk.getPoint(name, side);
ofPoint f = sk.getPoint(::foot, side);
return ofMap(p.distance(f), 0, sk.skeletonHeight * 1.25, 0, 1);
}
}
template <typename T>
T ExtractNote(const vector<T>& notes, float perc) {
float mx = notes.size() - 1;
return notes[ofClamp(perc * mx, 0, mx)];
}
int ExtractNote(const midiTrigger::Settings &settings, float perc) {
return ExtractNote(settings.notes, perc);
}
void AllNotesOff(ofxMidiOut& midiOut) {
for(int channel = 1; channel <= 16; channel++) {
for(int note = 0; note <= 127; note++) {
midiOut.sendNoteOff(channel, note);
}
}
}
int OtherSide(int side) {
return (side == ::left ? ::right : ::left);
}
bool GreatestLength(ofPoint a, ofPoint b) {
return a.lengthSquared() > b.lengthSquared();
}
#pragma mark - Grabbed Note
grabbedNote::grabbedNote() : _triggered(false), _currentNote(0) {
}
void grabbedNote::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
float extendThreshHi = 0.8;
float extendThreshLow = 0.7;
float extendPerc = sk.armRightExtendedPct;
float height = ofMap(NormalizedHeight(sk, ::hand, ::right), 0.3, 1, 0, 1);
int note = ExtractNote(getSettings(), height);
ofVec3f acc = body.accel[SKELETOR::Instance()->rightEnumsToIndex[::hand]];
float sum = acc.x + acc.y + acc.z;
bool shouldTrig = sum < -3 && extendPerc > extendThreshHi;
bool shouldStop = extendPerc < extendThreshLow;
if(shouldTrig && !_triggered) {
getMidiOut()->sendNoteOn(getSettings().channel, note);
_triggered = true;
_currentNote = note;
} else if(shouldStop && _triggered) {
getMidiOut()->sendNoteOff(getSettings().channel, note);
_triggered = false;
_currentNote = 0;
} else if(_triggered && _currentNote != note) {
getMidiOut()->sendNoteOn(getSettings().channel, note);
getMidiOut()->sendNoteOff(getSettings().channel, _currentNote);
_currentNote = note;
}
}
#pragma mark - Grid Note
gridNote::gridNote() : _triggered(false), _currentNote(0), _lastTrigger(0) {
}
void gridNote::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
float extendPerc;
ofVec3f handVel;
if(getSettings().side == ::left) {
extendPerc = sk.armLeftExtendedPct;
handVel = body.velocity[SKELETOR::Instance()->leftEnumsToIndex[::hand]];
} else {
extendPerc = sk.armRightExtendedPct;
handVel = body.velocity[SKELETOR::Instance()->rightEnumsToIndex[::hand]];
}
float extendThresh = 0.65;
bool shouldTrig = extendPerc > extendThresh;
int note = ExtractNote(getSettings(), NormalizedHeight(sk, ::hand, getSettings().side));
int vel = ofMap(handVel.length(), 0, 40, 40, 120);
auto now = ofGetElapsedTimeMillis();
unsigned long long timeThresh = 100;
bool timeOk = (now - _lastTrigger) > timeThresh;
if(shouldTrig && note != _currentNote && timeOk) {
getMidiOut()->sendNoteOn(getSettings().channel, note, vel);
getMidiOut()->sendNoteOff(getSettings().channel, _currentNote);
_triggered = true;
_currentNote = note;
_lastTrigger = now;
} else if(!shouldTrig && _triggered) {
getMidiOut()->sendNoteOff(getSettings().channel, _currentNote);
_triggered = false;
_currentNote = 0;
_lastTrigger = now;
}
}
#pragma mark - Accordian Note
accordianNote::accordianNote() : _triggered(false), _currentNote(0), _lastDist(0) {
getSettings().notes.resize(2);
}
void accordianNote::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
float dist = ofMap(sk.getLeftPoint(::hand).distance(sk.getRightPoint(::hand)), 0, sk.skeletonHeight, 0, 1);
float onThresh = 0.5;
float retrigThresh = 0.0004;
int note = dist > _lastDist ? getSettings().notes[0] : getSettings().notes[1];
if(dist > onThresh) {
if(!_triggered) {
getMidiOut()->sendNoteOn(getSettings().channel, note);
} else if(note != _currentNote && abs(_lastDist - dist) > retrigThresh) {
getMidiOut()->sendNoteOn(getSettings().channel, note);
getMidiOut()->sendNoteOff(getSettings().channel, _currentNote);
}
_currentNote = note;
_triggered = true;
_lastDist = dist;
} else if(_triggered) {
getMidiOut()->sendNoteOff(getSettings().channel, _currentNote);
_currentNote = 0;
_lastDist = 0;
_triggered = false;
}
}
#pragma mark - Leg CC
legCC::legCC() : _accumulator(0) {
}
void legCC::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
vector<ofPoint> acc;
acc.push_back(body.accel[SKELETOR::Instance()->leftEnumsToIndex[::foot]]);
acc.push_back(body.accel[SKELETOR::Instance()->leftEnumsToIndex[::knee]]);
acc.push_back(body.accel[SKELETOR::Instance()->leftEnumsToIndex[::hip]]);
acc.push_back(body.accel[SKELETOR::Instance()->rightEnumsToIndex[::foot]]);
acc.push_back(body.accel[SKELETOR::Instance()->rightEnumsToIndex[::knee]]);
acc.push_back(body.accel[SKELETOR::Instance()->rightEnumsToIndex[::hip]]);
ofSort(acc, GreatestLength);
float greatest = acc.front().length();
float amt = ofMap(greatest, 0, sk.skeletonHeight / 32., 0, 1, true);
_accumulator = ofLerp(_accumulator, amt, 0.07);
getMidiOut()->sendControlChange(1, 1, _accumulator * 127);
}
#pragma mark - Stomp
stompNote::stompNote() {
reset();
}
void stompNote::reset() {
_primed = false;
_ignoredFrameCount = 0;
}
void stompNote::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
float primeThresh = 0.7;
float triggerThresh = 0.5;
int framesToWait = 40; // number of frames to wait for a negative acceleration
size_t idx = SKELETOR::Instance()->getPointIndex(::foot, getSettings().side);
size_t opp = SKELETOR::Instance()->getPointIndex(::foot, OtherSide(getSettings().side));
float footDiff = ofMap(sk.pts[idx].y - sk.pts[opp].y, 0, sk.skeletonHeight / 10., 0, 1, true);
if(!_primed && footDiff > primeThresh) {
_primed = true;
if(getSettings().notes.size() > 1) {
getMidiOut()->sendNoteOn(getSettings().channel, getSettings().notes[1]);
}
} else if(_primed) {
float acc = body.accel[idx].y;
if(footDiff < triggerThresh) {
int velocity = ofMap(acc, -0.1, -4, 80, 100);
getMidiOut()->sendNoteOn(getSettings().channel, getSettings().notes.front(), velocity);
reset();
}
}
}
#pragma mark - Ass Note
dropDatNote::dropDatNote() : _primed(false), _ignoredFrameCount(0) {
}
void dropDatNote::reset() {
}
void dropDatNote::update(kinectBody &body) {
kinectSkeleton& sk = body.getLastSkeleton();
float primeThresh = 0.95;
float triggerThresh = 0.91;
float left = sk.legLeftExtendedPct;
float right = sk.legRightExtendedPct;
bool abovePrime = (left > primeThresh) && (right > primeThresh);
bool belowTrigger = (left < triggerThresh) && (right < triggerThresh);
if(!_primed && abovePrime) {
_primed = true;
if(getSettings().notes.size() > 1) {
getMidiOut()->sendNoteOn(getSettings().channel, getSettings().notes[1]);
}
} else if(_primed && belowTrigger) {
getMidiOut()->sendNoteOn(getSettings().channel, getSettings().notes.front());
_primed = false;
}
}
| 27.630996 | 108 | 0.695379 | [
"vector"
] |
7464c33a3ece3611c8b04e04aead5362e4a1faab | 4,240 | hpp | C++ | include/mesh_generator.hpp | shakibbinhamid/OpenGL-Major-Project | 1f7d2138b3dd5b45679951a6170679dbb8638844 | [
"MIT"
] | null | null | null | include/mesh_generator.hpp | shakibbinhamid/OpenGL-Major-Project | 1f7d2138b3dd5b45679951a6170679dbb8638844 | [
"MIT"
] | null | null | null | include/mesh_generator.hpp | shakibbinhamid/OpenGL-Major-Project | 1f7d2138b3dd5b45679951a6170679dbb8638844 | [
"MIT"
] | null | null | null | //
// mesh_generator.h
// Coursework 3
//
// Created by Shakib-Bin Hamid on 30/03/2016.
// Copyright © 2016 Shakib-Bin Hamid. All rights reserved.
//
#ifndef mesh_generator_h
#define mesh_generator_h
#include "mesh.hpp"
#include <vector>
/*
Generates a sphere and populates the vertices, indices based on how many 'stacks' and 'slices' are needed.
It is a UV sphere.
vertices contain position, normal, texcord
q2 verts just contain position, normal
*/
Mesh generateUVSphere (const GLint Stacks, const GLint Slices, const GLfloat r, const string name = "sphere"){
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
std::vector<Texture> textures;
for (int i = 0; i <= Stacks; ++i){
float V = i / (float) Stacks;
float phi = V * glm::pi <float> ();
// Loop Through Slices
for (int j = 0; j <= Slices; ++j){
float U = j / (float) Slices;
float theta = U * (glm::pi <float> () * 2);
// Calc The Vertex Positions
float x = r * cosf (theta) * sinf (phi);
float y = r * cosf (phi);
float z = r * sinf (theta) * sinf (phi);
// vertices for sphere
Vertex v;
v.position = glm::vec3(x, y, z);
v.normal = glm::vec3(v.position + glm::normalize(v.position) * 0.05f);
v.texCoords = glm::vec2 (U, V);
vertices.push_back(v);
}
}
for (int i = 0; i < Slices * Stacks + Slices; ++i){
indices.push_back (i);
indices.push_back (i + Slices + 1);
indices.push_back (i + Slices);
indices.push_back (i + Slices + 1);
indices.push_back (i);
indices.push_back (i + 1);
}
return Mesh(vertices, indices, textures, name);
}
Mesh generateRectangularFloor (GLfloat width, GLfloat height, GLfloat elevation, const string name = "floor") {
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
std::vector<Texture> textures;
GLfloat vPositions[4][3] = {
{-width/2, elevation, -height/2},
{width/2, elevation, -height/2},
{width/2, elevation, height/2},
{-width/2, elevation, height/2},
};
GLfloat vTexCords[4][2] = {
{0.0, 0.0},
{1.0, 0.0},
{1.0, 1.0},
{0.0, 1.0}
};
int j = 0;
for (int i = 0; i < 4; i++) {
Vertex v;
v.position = glm::vec3(vPositions[i][j], vPositions[i][j+1], vPositions[i][j+2]);
v.normal = glm::vec3(glm::vec3(0.0f, 1.0f, 0.0f));
v.texCoords = glm::vec2(vTexCords[i][j], vTexCords[i][j+1]);
vertices.push_back(v);
}
indices.push_back(2); indices.push_back(1); indices.push_back(0);
indices.push_back(3); indices.push_back(2); indices.push_back(0);
return Mesh(vertices, indices, textures);
}
vector<GLfloat> getCubeVertices(){
GLfloat cubeVerts[] = {
// Positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
vector<GLfloat> verts;
for (int i = 0; i < 36*3; i++) verts.push_back(cubeVerts[i]);
return verts;
}
#endif /* mesh_generator_h */
| 28.648649 | 111 | 0.490802 | [
"mesh",
"vector"
] |
7464e3623f3df94930e399ead2d37010401812e2 | 1,512 | cpp | C++ | src/scene_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | 1 | 2021-04-30T11:14:32.000Z | 2021-04-30T11:14:32.000Z | src/scene_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | null | null | null | src/scene_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | null | null | null | #define MAX_ENTITY_CHILDREN 16
enum struct Entity_Type
{
DEFAULT = 0,
CAMERA = 1,
};
struct Transform
{
Vec3 position;
Vec3 scale;
Vec4 rotation;
Mat4 local_matrix;
Mat4 world_matrix;
};
struct Entity : Transform
{
u32 id;
b32 active;
Entity_Type entity_type;
Entity* parent;
Entity* children[MAX_ENTITY_CHILDREN];
};
struct Camera : Entity
{
Mat4 projection;
Mat4 view;
Mat4 view_projection;
Mat4 world_to_screen;
Mat4 screen_to_world;
Mat3 normal_matrix;
i32 mask;
f32 aspect;
f32 near;
f32 far;
f32 fov;
f32 size;
b32 orthographic;
};
struct Text_Mesh : Entity
{
Text_Style* style;
Mesh* mesh;
i32 index;
Vec3 pen;
Vec4 bounds;
f32 width;
f32 height;
u32 index_start;
u32 last_line_index;
u32 last_white_space_index;
f32 last_white_space_px;
f32 last_white_space_advance;
f32 last_line_px;
};
struct Scene
{
Vec3 position;
Vec3 scale;
Vec4 rotation;
Mat4 matrix;
Entity** entities;
u32 num_entities;
};
struct GL_Draw
{
Vec4 color;
Mat4 matrix;
Shader* line_shader;
Shader* triangle_shader;
Mesh* lines;
Mesh* triangles;
Text_Style* text_style;
Text_Mesh* text;
};
struct Engine
{
void* memory;
memsize memory_size;
Allocator persistant_storage;
Allocator scratch_storage;
b32 has_focus;
b32 can_update;
Vec4 view;
f32 pixel_ratio;
GL_State* gl_state;
Time time;
Input input;
Assets assets;
};
static Engine* engine; | 14.970297 | 39 | 0.683201 | [
"mesh",
"transform"
] |
7465dde6e530f461f3beaaf892eeed6134c21ab7 | 3,448 | cc | C++ | cc/paint/clear_for_opaque_raster.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 | cc/paint/clear_for_opaque_raster.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 | cc/paint/clear_for_opaque_raster.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 2020 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 "cc/paint/clear_for_opaque_raster.h"
#include <cmath>
#include "base/check_op.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace cc {
bool CalculateClearForOpaqueRasterRects(const gfx::Vector2dF& translation,
const gfx::Vector2dF& scale,
const gfx::Size& content_size,
const gfx::Rect& canvas_bitmap_rect,
const gfx::Rect& canvas_playback_rect,
gfx::Rect& outer_rect,
gfx::Rect& inner_rect) {
// If there is translation, the top and/or left texels are not guaranteed to
// be fully opaque.
DCHECK_GE(translation.x(), 0.0f);
DCHECK_GE(translation.y(), 0.0f);
DCHECK_LT(translation.x(), 1.0f);
DCHECK_LT(translation.y(), 1.0f);
bool left_opaque = translation.x() == 0.0f;
bool top_opaque = translation.y() == 0.0f;
// If there is scale, the right and/or bottom texels are not guaranteed to be
// fully opaque.
bool right_opaque = scale.x() == 1.0f;
bool bottom_opaque = scale.y() == 1.0f;
if (left_opaque && top_opaque && right_opaque && bottom_opaque)
return false;
// |outer_rect| is the bounds of all texels affected by content.
outer_rect = gfx::Rect(content_size);
// |inner_rect| is the opaque coverage of the content.
inner_rect = outer_rect;
// If not fully covered, one texel inside the content rect may not be opaque
// (because of blending during raster) and, for scale, one texel outside
// (because of bilinear filtering during draw) may not be opaque.
outer_rect.Inset(0, 0, right_opaque ? 0 : -1, bottom_opaque ? 0 : -1);
inner_rect.Inset(left_opaque ? 0 : 1, top_opaque ? 0 : 1,
right_opaque ? 0 : 1, bottom_opaque ? 0 : 1);
// If the playback rect is touching either edge of the content rect, extend it
// by one to include the extra texel outside that was added to outer_rect
// above.
bool touches_left_edge = !left_opaque && !canvas_playback_rect.x();
bool touches_top_edge = !top_opaque && !canvas_playback_rect.y();
bool touches_right_edge =
!right_opaque && content_size.width() == canvas_playback_rect.right();
bool touches_bottom_edge =
!bottom_opaque && content_size.height() == canvas_playback_rect.bottom();
gfx::Rect adjusted_playback_rect = canvas_playback_rect;
adjusted_playback_rect.Inset(
touches_left_edge ? -1 : 0, touches_top_edge ? -1 : 0,
touches_right_edge ? -1 : 0, touches_bottom_edge ? -1 : 0);
// No need to clear if the playback area is fully covered by the opaque
// content.
if (inner_rect.Contains(adjusted_playback_rect))
return false;
if (!outer_rect.Intersects(adjusted_playback_rect))
return false;
outer_rect.Intersect(adjusted_playback_rect);
inner_rect.Intersect(adjusted_playback_rect);
// inner_rect can be empty if the content is very small.
// Move the rects into the device space.
outer_rect.Offset(-canvas_bitmap_rect.OffsetFromOrigin());
inner_rect.Offset(-canvas_bitmap_rect.OffsetFromOrigin());
return inner_rect != outer_rect;
}
} // namespace cc
| 42.04878 | 80 | 0.673434 | [
"geometry"
] |
746658aba499f5e1cf7943916ed40e31205628b1 | 909 | cc | C++ | smart_pointers/01-pointer.cc | aakbar5/handy-cplusplus | fd8ae187811f1ff9a6d19909202ed31564c4e384 | [
"MIT"
] | null | null | null | smart_pointers/01-pointer.cc | aakbar5/handy-cplusplus | fd8ae187811f1ff9a6d19909202ed31564c4e384 | [
"MIT"
] | null | null | null | smart_pointers/01-pointer.cc | aakbar5/handy-cplusplus | fd8ae187811f1ff9a6d19909202ed31564c4e384 | [
"MIT"
] | null | null | null | //
// Program
// This program simply creates auto pointer.
//
// Compile
// g++ -std=c++17 -o 01-pointer 01-pointer.cc
//
// Execution
// ./01-pointer
//
#include <iostream>
#include <memory>
//
// Entry function
//
int main() {
std::cout << "--- std::auto_ptr ---" << "\n";
// Handling of Test object via shared pointer
std::cout << "--- simple auto_pointer ---" << "\n";
{
std::auto_ptr<unsigned int> aptr(new unsigned int(786));
std::cout << "aptr @ value: " << *aptr << "\n";
{
std::auto_ptr<unsigned int> wptr(aptr);
*wptr.get() = 100;
std::cout << "wptr > aptr @ value: " << *wptr << "\n";
}
// seg fault as ownership was wptr and
// it has ended its life due to scoped rule
std::cout << "aptr @ value: " << *aptr << "\n";
}
std::cout << "Good bye!" << "\n";
return 0;
}
| 20.659091 | 66 | 0.50275 | [
"object"
] |
74672eb4319a5101882806e4f7548fc7d62def89 | 4,805 | hpp | C++ | controller/ConnectionPool.hpp | icecubi/ZeroTierOne | 7ea2354540cd891f61d0944ff8a25c53a42bd038 | [
"RSA-MD"
] | null | null | null | controller/ConnectionPool.hpp | icecubi/ZeroTierOne | 7ea2354540cd891f61d0944ff8a25c53a42bd038 | [
"RSA-MD"
] | null | null | null | controller/ConnectionPool.hpp | icecubi/ZeroTierOne | 7ea2354540cd891f61d0944ff8a25c53a42bd038 | [
"RSA-MD"
] | 1 | 2019-03-04T07:31:55.000Z | 2019-03-04T07:31:55.000Z | /*
* Copyright (c)2021 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#ifndef ZT_CONNECTION_POOL_H_
#define ZT_CONNECTION_POOL_H_
#ifndef _DEBUG
#define _DEBUG(x)
#endif
#include <deque>
#include <set>
#include <memory>
#include <mutex>
#include <exception>
#include <string>
namespace ZeroTier {
struct ConnectionUnavailable : std::exception {
char const* what() const throw() {
return "Unable to allocate connection";
};
};
class Connection {
public:
virtual ~Connection() {};
};
class ConnectionFactory {
public:
virtual ~ConnectionFactory() {};
virtual std::shared_ptr<Connection> create()=0;
};
struct ConnectionPoolStats {
size_t pool_size;
size_t borrowed_size;
};
template<class T>
class ConnectionPool {
public:
ConnectionPool(size_t max_pool_size, size_t min_pool_size, std::shared_ptr<ConnectionFactory> factory)
: m_maxPoolSize(max_pool_size)
, m_minPoolSize(min_pool_size)
, m_factory(factory)
{
while(m_pool.size() < m_minPoolSize){
m_pool.push_back(m_factory->create());
}
};
ConnectionPoolStats get_stats() {
std::unique_lock<std::mutex> lock(m_poolMutex);
ConnectionPoolStats stats;
stats.pool_size = m_pool.size();
stats.borrowed_size = m_borrowed.size();
return stats;
};
~ConnectionPool() {
};
/**
* Borrow
*
* Borrow a connection for temporary use
*
* When done, either (a) call unborrow() to return it, or (b) (if it's bad) just let it go out of scope. This will cause it to automatically be replaced.
* @retval a shared_ptr to the connection object
*/
std::shared_ptr<T> borrow() {
std::unique_lock<std::mutex> l(m_poolMutex);
while((m_pool.size() + m_borrowed.size()) < m_minPoolSize) {
std::shared_ptr<Connection> conn = m_factory->create();
m_pool.push_back(conn);
}
if(m_pool.size()==0){
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
try {
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.insert(conn);
return std::static_pointer_cast<T>(conn);
} catch (std::exception &e) {
throw ConnectionUnavailable();
}
} else {
for(auto it = m_borrowed.begin(); it != m_borrowed.end(); ++it){
if((*it).unique()) {
// This connection has been abandoned! Destroy it and create a new connection
try {
// If we are able to create a new connection, return it
_DEBUG("Creating new connection to replace discarded connection");
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.erase(it);
m_borrowed.insert(conn);
return std::static_pointer_cast<T>(conn);
} catch(std::exception& e) {
// Error creating a replacement connection
throw ConnectionUnavailable();
}
}
}
// Nothing available
throw ConnectionUnavailable();
}
}
// Take one off the front
std::shared_ptr<Connection> conn = m_pool.front();
m_pool.pop_front();
// Add it to the borrowed list
m_borrowed.insert(conn);
return std::static_pointer_cast<T>(conn);
};
/**
* Unborrow a connection
*
* Only call this if you are returning a working connection. If the connection was bad, just let it go out of scope (so the connection manager can replace it).
* @param the connection
*/
void unborrow(std::shared_ptr<T> conn) {
// Lock
std::unique_lock<std::mutex> lock(m_poolMutex);
m_borrowed.erase(conn);
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
m_pool.push_back(conn);
}
};
protected:
size_t m_maxPoolSize;
size_t m_minPoolSize;
std::shared_ptr<ConnectionFactory> m_factory;
std::deque<std::shared_ptr<Connection> > m_pool;
std::set<std::shared_ptr<Connection> > m_borrowed;
std::mutex m_poolMutex;
};
}
#endif | 29.84472 | 164 | 0.576275 | [
"object"
] |
746d645c94c34c1ec0eb9a76eea59acbac454c27 | 3,412 | hpp | C++ | src/libraries/waves/waves/relaxationZone/relaxationScheme/spatialInterpolation/relaxationSchemeSpatialInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/waves/waves/relaxationZone/relaxationScheme/spatialInterpolation/relaxationSchemeSpatialInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/waves/waves/relaxationZone/relaxationScheme/spatialInterpolation/relaxationSchemeSpatialInterpolation.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright Niels Gjøl Jacobsen, Deltares.
-------------------------------------------------------------------------------
License
This file is part of Caelus.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::relaxationSchemes::relaxationSchemeSpatialInterpolation
Description
This relaxation scheme utilises interpolation over a pre-defined interval
for the intersection. This speed of the execution of the intersections
with a huge factor. Especially when using irregular waves with a lot of
wave components.
Should be combined with a relaxation shape that implements the interpolation
method.
SourceFiles
relaxationSchemeSpatialInterpolation.cpp
Author
Niels Gjøl Jacobsen, Deltares.
\*---------------------------------------------------------------------------*/
#ifndef relaxationSchemeSpatialInterpolation_HPP
#define relaxationSchemeSpatialInterpolation_HPP
#include "relaxationScheme.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
namespace relaxationSchemes
{
/*---------------------------------------------------------------------------*\
Class relaxationSchemeSpatialInterpolation Declaration
\*---------------------------------------------------------------------------*/
class relaxationSchemeSpatialInterpolation
:
public relaxationScheme
{
protected:
// Protected data
scalar exponent_;
scalarField weight_;
scalarField surfaceElevation_;
// Protected member functions
//- Returns a scalarField of the signed distance to an arbitrary
// surface
virtual void signedPointToSurfaceDistance
(
const pointField&,
scalarField&
);
//- Returns a scalar of the signed distance to an arbitrary surface
virtual scalar signedPointToSurfaceDistance
(
const point&
) const;
public:
//- Runtime type information
TypeName("relaxationSchemeSpatialInterpolation");
// Constructors
//- from components
relaxationSchemeSpatialInterpolation
(
const word& ,
const fvMesh& mesh_,
vectorField& U,
scalarField& alpha
);
// Destructor
virtual ~relaxationSchemeSpatialInterpolation()
{}
// Member Functions
virtual void correct();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace relaxationSchemes
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 28.198347 | 80 | 0.552755 | [
"shape"
] |
7478f89f57071774a36cf4ed577439cc8ac10dfd | 2,801 | cpp | C++ | TL_SIM_TimeProfile/TL_SIM_time_node.cpp | TinySim/TinySim | 2e3bed223b1b75faa25e4ab7d80551b9896bf446 | [
"MIT"
] | 1 | 2019-07-30T02:26:18.000Z | 2019-07-30T02:26:18.000Z | TL_SIM_TimeProfile/TL_SIM_time_node.cpp | TinySim/TinySim | 2e3bed223b1b75faa25e4ab7d80551b9896bf446 | [
"MIT"
] | null | null | null | TL_SIM_TimeProfile/TL_SIM_time_node.cpp | TinySim/TinySim | 2e3bed223b1b75faa25e4ab7d80551b9896bf446 | [
"MIT"
] | null | null | null | #include "TL_SIM_time_node.h"
#include <map>
#include <vector>
using namespace std;
void TL_SIM_time_node::set_moteid(int i_moteid)
{
this->moteid = i_moteid;
}
int TL_SIM_time_node::get_moteid()
{
return this->moteid;
}
void TL_SIM_time_node::set_random_access_delay(int random_access_delay)
{
this->random_access_delay = random_access_delay;
}
int TL_SIM_time_node::get_random_access_delay()
{
return this->random_access_delay;
}
void TL_SIM_time_node::set_pkt_delay(int key, int i_pkt_delay)
{
this->total_pkt_delay[key] = i_pkt_delay;
// this->total_pkt_delay = i_pkt_delay;
}
int TL_SIM_time_node::get_pkt_delay(int key)
{
return this->total_pkt_delay[key];
}
void TL_SIM_time_node::set_intend_pkt_num(int key,int intend_pkt_num)
{
this->intend_pkt_num[key] = intend_pkt_num;
}
int TL_SIM_time_node::get_intend_pkt_num(int key)
{
return this->intend_pkt_num[key];
}
void TL_SIM_time_node::set_tx_pkt_num(int key,int tx_pkt_num)
{
this->tx_pkt_num[key] = tx_pkt_num;
}
int TL_SIM_time_node::get_tx_pkt_num(int key)
{
return this->tx_pkt_num[key];
}
// void TL_SIM_time_node::set_pre_state(int key,int state)
// {
// this->pre_state[key] = state;
// }
// int TL_SIM_time_node::get_pre_state(int key)
// {
// return this->pre_state[key];
// }
// void TL_SIM_time_node::set_pre_time(int key,int time)
// {
// this->pre_time[key] = time;
// }
// int TL_SIM_time_node::get_pre_time(int key)
// {
// return this->pre_time[key];
// }
void TL_SIM_time_node::set_pre_state(int state)
{
this->pre_state = state;
}
int TL_SIM_time_node::get_pre_state()
{
return this->pre_state;
}
void TL_SIM_time_node::set_pre_time(int time)
{
this->pre_time = time;
}
int TL_SIM_time_node::get_pre_time()
{
return this->pre_time;
}
void TL_SIM_time_node::set_open_lock_pre_state(int state)
{
this->open_lock_pre_state = state;
}
int TL_SIM_time_node::get_open_lock_pre_state()
{
return this->open_lock_pre_state;
}
void TL_SIM_time_node::set_open_lock_pre_time(int time)
{
this->open_lock_pre_time = time;
}
int TL_SIM_time_node::get_open_lock_pre_time()
{
return this->open_lock_pre_time;
}
// void TL_SIM_time_node::add_pkt_delay_item(int key)
// {
// this->
// }
// void TL_SIM_time_node::add_intend_pkt_num_item(int key)
// {
// }
// void TL_SIM_time_node::add_tx_pkt_num_item(int key)
// {
// }
// randomly choose a variable to check whether there is the key
bool TL_SIM_time_node::isKeyInMap(int key)
{
map<int, int>::iterator it = total_pkt_delay.find(key);
if(it != total_pkt_delay.end())
{
return true;
}
else
{
return false;
}
}
void TL_SIM_time_node::get_all_dst_moteid(vector<int>& nodeList)
{
for(map<int, int>::iterator it = total_pkt_delay.begin(); it != total_pkt_delay.end(); it++)
{
nodeList.push_back(it->first);
}
}
| 18.427632 | 95 | 0.732953 | [
"vector"
] |
747d3d27722d89880286f002bdfdda3e83d15b7a | 11,163 | cpp | C++ | LightpackAPI/LedDevice.cpp | matthewn4444/Lightpack-Filter-and-API | b4cd7d448f12a111ebf8a8b55338a2d75e120517 | [
"MIT-0"
] | 9 | 2015-01-29T02:26:58.000Z | 2019-11-20T03:16:16.000Z | LightpackAPI/LedDevice.cpp | matthewn4444/Lightpack-Filter-and-API | b4cd7d448f12a111ebf8a8b55338a2d75e120517 | [
"MIT-0"
] | 7 | 2015-07-31T15:56:10.000Z | 2017-11-05T22:18:02.000Z | LightpackAPI/LedDevice.cpp | matthewn4444/Lightpack-Filter-and-API | b4cd7d448f12a111ebf8a8b55338a2d75e120517 | [
"MIT-0"
] | null | null | null | #include <algorithm>
#include "../include/Lightpack.h"
#include "thirdparty\hidapi\hidapi.h"
#include "device\commands.h"
#include "device\USB_ID.h"
#define WRITE_BUFFER_INDEX_REPORT_ID 0
#define WRITE_BUFFER_INDEX_COMMAND 1
#define WRITE_BUFFER_INDEX_DATA_START 2
namespace Lightpack {
LedDevice::LedDevice()
: mGamma(DefaultGamma)
, mBrightness(DefaultBrightness)
, mLedsOn(true)
{
}
LedDevice::~LedDevice() {
closeDevices();
mCurrentColors.clear();
}
bool LedDevice::open() {
if (!mDevices.empty()) {
return true;
}
openDevice(USB_VENDOR_ID, USB_PRODUCT_ID);
openDevice(USB_OLD_VENDOR_ID, USB_OLD_PRODUCT_ID);
allocateColors();
return !mDevices.empty();
}
bool LedDevice::tryToReopenDevice() {
closeDevices();
open();
return !mDevices.empty();
}
void LedDevice::closeDevices() {
for (size_t i = 0; i < mDevices.size(); i++) {
hid_close(mDevices[i]);
}
mDevices.clear();
}
RESULT LedDevice::setColor(int led, RGBCOLOR color) {
return setColor(led, GET_RED(color), GET_GREEN(color), GET_BLUE(color));
}
RESULT LedDevice::setColor(int led, int red, int green, int blue) {
if (led < 0 || led >= (int)mCurrentColors.size()) {
return FAIL;
}
mCurrentColors[led] = MAKE_RGB(red, green, blue);
if (!updateLeds()) {
return FAIL;
}
return OK;
}
RESULT LedDevice::setColors(std::vector<RGBCOLOR>& colors) {
if (colors.empty()) {
return OK;
}
for (size_t i = 0; i < std::min(colors.size(), mDevices.size() * LedsPerDevice); i++) {
if (colors[i] < 0) {
continue;
}
mCurrentColors[i] = colors[i];
}
if (!updateLeds()) {
return FAIL;
}
return OK;
}
RESULT LedDevice::setColors(const RGBCOLOR* colors, size_t length) {
if (!length) {
return OK;
}
for (size_t i = 0; i < std::min(length, getCountLeds()); i++) {
if (colors[i] < 0) {
continue;
}
mCurrentColors[i] = colors[i];
}
if (!updateLeds()) {
return FAIL;
}
return OK;
}
RESULT LedDevice::setColorToAll(RGBCOLOR color) {
mCurrentColors.assign(mCurrentColors.size(), color);
return updateLeds() ? OK : FAIL;
}
RESULT LedDevice::setColorToAll(int red, int green, int blue) {
return setColorToAll(MAKE_RGB(red, green, blue));
}
RESULT LedDevice::setSmooth(int value) {
if (mDevices.empty() && !tryToReopenDevice()) {
return FAIL;
}
mWriteBuffer[WRITE_BUFFER_INDEX_DATA_START] = (unsigned char)value;
bool flag = true;
for (size_t i = 0; i < mDevices.size(); i++) {
if (!writeBufferToDeviceWithCheck(CMD_SET_SMOOTH_SLOWDOWN, mDevices[i])) {
flag = false;
}
}
return flag ? OK : FAIL;
}
bool LedDevice::setColorDepth(int value) {
mWriteBuffer[WRITE_BUFFER_INDEX_DATA_START] = (unsigned char)value;
bool flag = true;
for (size_t i = 0; i < mDevices.size(); i++) {
if (!writeBufferToDeviceWithCheck(CMD_SET_PWM_LEVEL_MAX_VALUE, mDevices[i])) {
flag = false;
}
}
return flag;
}
bool LedDevice::setRefreshDelay(int value) {
mWriteBuffer[WRITE_BUFFER_INDEX_DATA_START] = value & 0xff;
mWriteBuffer[WRITE_BUFFER_INDEX_DATA_START + 1] = (value >> 8);
bool flag = true;
for (size_t i = 0; i < mDevices.size(); i++) {
if (!writeBufferToDeviceWithCheck(CMD_SET_TIMER_OPTIONS, mDevices[i])) {
flag = false;
}
}
return flag;
}
RESULT LedDevice::setGamma(double value) {
mGamma = value;
if (isBufferAllBlack()) {
return !mDevices.empty() ? OK : FAIL;
}
return updateLeds() ? OK : FAIL;
}
RESULT LedDevice::setBrightness(int value) {
mBrightness = value;
if (isBufferAllBlack()) {
return !mDevices.empty() ? OK : FAIL;
}
return updateLeds() ? OK : FAIL;
}
RESULT LedDevice::turnOff() {
mLedsOn = false;
return updateLeds() ? OK : FAIL;
}
RESULT LedDevice::turnOn() {
mLedsOn = true;
return updateLeds() ? OK : FAIL;
}
bool LedDevice::openDevice(unsigned short vid, unsigned short pid) {
struct hid_device_info *devs, *cur_dev;
const char *path_to_open = NULL;
hid_device * handle = NULL;
bool flag = true;
devs = hid_enumerate(vid, pid);
cur_dev = devs;
while (cur_dev) {
path_to_open = cur_dev->path;
if (path_to_open) {
/* Open the device */
handle = hid_open_path(path_to_open);
if (handle != NULL) {
// Immediately return from hid_read() if no data available
hid_set_nonblocking(handle, 1);
if (cur_dev->serial_number != NULL && wcslen(cur_dev->serial_number) > 0) {
char buffer[96];
wcstombs(buffer, cur_dev->serial_number, strlen(buffer));
mDevices.push_back(handle);
}
else {
mDevices.push_back(handle);
}
}
else {
flag = false;
}
}
cur_dev = cur_dev->next;
}
hid_free_enumeration(devs);
return flag;
}
bool LedDevice::writeBufferToDeviceWithCheck(int command, hid_device *phid_device) {
if (phid_device != NULL) {
if (!writeBufferToDevice(command, phid_device)) {
if (!writeBufferToDevice(command, phid_device)) {
if (tryToReopenDevice()) {
if (!writeBufferToDevice(command, phid_device)) {
if (tryToReopenDevice()) {
return writeBufferToDevice(command, phid_device);
}
else {
return false;
}
}
}
else {
return false;
}
}
}
return true;
}
else {
if (tryToReopenDevice()) {
return writeBufferToDevice(command, phid_device);
}
else {
return false;
}
}
return false;
}
bool LedDevice::writeBufferToDevice(int command, hid_device *phid_device) {
mWriteBuffer[WRITE_BUFFER_INDEX_REPORT_ID] = 0x00;
mWriteBuffer[WRITE_BUFFER_INDEX_COMMAND] = command;
int error = hid_write(phid_device, mWriteBuffer, sizeof(mWriteBuffer));
if (error < 0)
{
// Trying to repeat sending data:
error = hid_write(phid_device, mWriteBuffer, sizeof(mWriteBuffer));
if (error < 0){
return false;
}
}
return true;
}
bool LedDevice::readDataFromDeviceWithCheck() {
if (!mDevices.empty()) {
if (!readDataFromDevice()) {
if (tryToReopenDevice()) {
return readDataFromDevice();
}
else {
return false;
}
}
return true;
}
else if (tryToReopenDevice()) {
return readDataFromDevice();
}
return false;
}
bool LedDevice::readDataFromDevice() {
int bytes_read = hid_read(mDevices[0], mReadBuffer, sizeof(mReadBuffer));
return bytes_read >= 0;
}
bool LedDevice::updateLeds() {
if (mDevices.empty() && !tryToReopenDevice()) {
return false;
}
int buffIndex = WRITE_BUFFER_INDEX_DATA_START;
int ledCount = 10;
bool ok = true;
static const int kLedRemap[] = { 4, 3, 2, 0, 1, 5, 6, 7, 8, 9 };
static const size_t kSizeOfLedColor = 6;
bool flag = true;
memset(mWriteBuffer, 0, sizeof(mWriteBuffer));
for (size_t d = 0; d < mDevices.size(); d++) {
for (size_t i = 0; i < LedsPerDevice; i++) {
RGBCOLOR color = mLedsOn ? mCurrentColors[d * 10 + i] : 0;
buffIndex = WRITE_BUFFER_INDEX_DATA_START + kLedRemap[i] * kSizeOfLedColor;
int r = GET_RED(color);
int g = GET_GREEN(color);
int b = GET_BLUE(color);
colorAdjustments(r, g, b);
mWriteBuffer[buffIndex++] = (r & 0x0FF0) >> 4;
mWriteBuffer[buffIndex++] = (g & 0x0FF0) >> 4;
mWriteBuffer[buffIndex++] = (b & 0x0FF0) >> 4;
// Send over 4 bits for devices revision >= 6
// All existing devices ignore it
mWriteBuffer[buffIndex++] = (r & 0x000F);
mWriteBuffer[buffIndex++] = (g & 0x000F);
mWriteBuffer[buffIndex++] = (b & 0x000F);
}
// Write individual set of Lightpack modules
if (!writeBufferToDeviceWithCheck(CMD_UPDATE_LEDS, mDevices[d])) {
flag = false;
}
buffIndex = WRITE_BUFFER_INDEX_DATA_START;
memset(mWriteBuffer, 0, sizeof(mWriteBuffer));
}
return flag;
}
bool LedDevice::isBufferAllBlack() {
// Check the current color buffer, if all 0, then dont update; could be new allocated buffer
for (size_t i = 0; i < mCurrentColors.size(); i++) {
if (mCurrentColors[i]) {
return false;
}
}
return true;
}
void LedDevice::allocateColors() {
if (!mDevices.empty()) {
if (mDevices.size() * LedsPerDevice != mCurrentColors.size()) {
mCurrentColors.clear();
mCurrentColors.assign(mDevices.size() * LedsPerDevice, 0);
}
}
}
void LedDevice::colorAdjustments(int& red12bit, int& green12bit, int& blue12bit) {
// Normalize to 12 bit
static const double k = 4095 / 255.0;
double r = red12bit * k;
double g = green12bit * k;
double b = blue12bit * k;
r = 4095 * pow(r / 4095.0, mGamma);
g = 4095 * pow(g / 4095.0, mGamma);
b = 4095 * pow(b / 4095.0, mGamma);
// Brightness correction
r = (mBrightness / 100.0) * r;
g = (mBrightness / 100.0) * g;
b = (mBrightness / 100.0) * b;
red12bit = (int)r;
green12bit = (int)g;
blue12bit = (int)b;
}
};
| 30.752066 | 100 | 0.510705 | [
"vector"
] |
747e359cedacfde15eb92c964c6273b9dbea607f | 1,581 | cpp | C++ | DSA Crack Sheet/solutions/N-Queens II.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | DSA Crack Sheet/solutions/N-Queens II.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | DSA Crack Sheet/solutions/N-Queens II.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
N-Queens II
===========
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example 1:
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 9
*/
class Solution
{
public:
bool isSafe(vector<vector<int>> &board, int r, int c)
{
int n = board.size();
if (r < 0 || c < 0 || r >= n || c >= n)
return false;
// left side
for (int i = 0; i <= c; ++i)
{
if (board[r][i] == 1)
return false;
}
// up side
for (int i = 0; i <= r; ++i)
{
if (board[i][c] == 1)
return false;
}
// top left diagonal
for (int i = r, j = c; i >= 0 && j >= 0; j--, i--)
{
if (board[i][j] == 1)
return false;
}
// top right diagonal
for (int i = r, j = c; i >= 0 && j < n; j++, i--)
{
if (board[i][j] == 1)
return false;
}
return true;
}
void solve(int n, vector<vector<int>> &board, int r, int &ans)
{
if (r == n)
{
ans++;
return;
}
for (int c = 0; c < n; ++c)
{
if (isSafe(board, r, c))
{
board[r][c] = 1;
solve(n, board, r + 1, ans);
board[r][c] = 0;
}
}
}
int totalNQueens(int n)
{
int ans = 0;
vector<vector<int>> board(n, vector<int>(n, 0));
solve(n, board, 0, ans);
return ans;
}
};
| 17.764045 | 120 | 0.488931 | [
"vector"
] |
748ccb441eb18370807e4be31765363cb79286dc | 751 | cpp | C++ | Vishv_GE/Framework/Physics/Src/Firework.cpp | InFaNsO/Vishv_GameEngine | e721afa899fb8715e52cdd67c2656ba6cce7ffed | [
"MIT"
] | 1 | 2021-12-19T02:06:12.000Z | 2021-12-19T02:06:12.000Z | Vishv_GE/Framework/Physics/Src/Firework.cpp | InFaNsO/Vishv_GameEngine | e721afa899fb8715e52cdd67c2656ba6cce7ffed | [
"MIT"
] | null | null | null | Vishv_GE/Framework/Physics/Src/Firework.cpp | InFaNsO/Vishv_GameEngine | e721afa899fb8715e52cdd67c2656ba6cce7ffed | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "Particle.h"
#include "Firework.h"
#include "PhysicsVectors.h"
/*using namespace Vishv;
using namespace Vishv::Physics;
void Vishv::Physics::Firework::Initialize(std::vector<Firework> payload, Fireworks::Ruleset rule, Math::Vector3 spawnPos, float mass, Math::Vector3 acceleratrion)
{
mPayload = payload;
mRule = rule;
mType = rule.mRuleNumeber;
mParticle.SetMass(mass);
mParticle.SetPosition(spawnPos);
mParticle.SetVelocity(mRule.mMinVelocity);
mParticle.SetAcceleration(acceleratrion);
mParticle.SetDampening(mRule.mDampening);
}
bool Vishv::Physics::Firework::Update(float deltaTime)
{
mAge += deltaTime;
mParticle.Update(deltaTime);
if (mAge > mRule.mMaxAge)
return true;
return false;
}
*/ | 22.088235 | 162 | 0.76032 | [
"vector"
] |
748ee49a13e9422ee131463f1b215d1630941b47 | 1,649 | cxx | C++ | src/jpeg_transform.cxx | NoevilMe/libwebcam | 2c6d27fb7b92a1818a999f292e24adc03e20184b | [
"MIT"
] | null | null | null | src/jpeg_transform.cxx | NoevilMe/libwebcam | 2c6d27fb7b92a1818a999f292e24adc03e20184b | [
"MIT"
] | null | null | null | src/jpeg_transform.cxx | NoevilMe/libwebcam | 2c6d27fb7b92a1818a999f292e24adc03e20184b | [
"MIT"
] | null | null | null | #include "jpeg_transform.h"
#include <cstring>
#include <stdexcept>
namespace noevil {
namespace webcam {
JpegTransform::JpegTransform(JpegTransformOp op) : handle_(tjInitTransform()) {
if (!handle_) {
throw std::runtime_error(tjGetErrorStr());
}
memset(&xtrans_, 0, sizeof(xtrans_));
switch (op) {
case JpegTransformOp::kTransNone:
xtrans_.op = TJXOP_NONE;
break;
case JpegTransformOp::kTransRot90:
xtrans_.op = TJXOP_ROT90;
break;
case JpegTransformOp::kTransRot180:
xtrans_.op = TJXOP_ROT180;
break;
case JpegTransformOp::kTransRot270:
xtrans_.op = TJXOP_ROT270;
break;
default:
xtrans_.op = TJXOP_NONE;
}
xtrans_.options |= TJXOPT_TRIM;
}
JpegTransform::~JpegTransform() {
if (handle_) {
tjDestroy(handle_);
}
}
bool JpegTransform::Transform(unsigned char *jpeg_buf, unsigned long jpeg_size,
std::string &out) {
if (xtrans_.op == TJXOP_NONE) {
return false;
}
unsigned long dst_size = 0;
unsigned char *dst_buf = nullptr;
int rel = tjTransform(handle_, jpeg_buf, jpeg_size, 1, &dst_buf, &dst_size,
&xtrans_, TJFLAG_ACCURATEDCT);
if (rel) {
throw std::runtime_error(tjGetErrorStr());
}
out.assign((char *)dst_buf, dst_size);
if (dst_size) {
tjFree(dst_buf);
}
return true;
}
bool JpegTransform::Transform(const std::string &jpeg, std::string &out) {
return Transform((unsigned char *)jpeg.data(), jpeg.size(), out);
}
} // namespace webcam
} // namespace noevil
| 22.589041 | 79 | 0.619163 | [
"transform"
] |
749c85254a89b4aa21c3d47f46363548dbe4913e | 5,685 | cc | C++ | tensorrt-laboratory/core/src/affinity.cc | ryanleary/tensorrt-laboratory | 1bb2151bfdffbb2e72b1a096e41b67602789c445 | [
"BSD-3-Clause"
] | 4 | 2020-01-16T13:50:28.000Z | 2021-12-08T09:35:13.000Z | tensorrt-laboratory/core/src/affinity.cc | ryanleary/tensorrt-laboratory | 1bb2151bfdffbb2e72b1a096e41b67602789c445 | [
"BSD-3-Clause"
] | 5 | 2020-03-24T17:57:33.000Z | 2022-03-12T00:07:08.000Z | tensorrt-laboratory/core/src/affinity.cc | ryanleary/tensorrt-laboratory | 1bb2151bfdffbb2e72b1a096e41b67602789c445 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 "tensorrt/laboratory/core/affinity.h"
#include <algorithm>
#include <glog/logging.h>
#define test_bit(_n, _p) (_n & (1UL << _p))
namespace trtlab {
static cpuaff::affinity_manager s_Manager;
std::vector<int> ParseIDs(const std::string data);
void Affinity::SetAffinity(const CpuSet& cpus)
{
CHECK(s_Manager.set_affinity(cpus)) << "SetAffinity failed for cpu_set: " << cpus;
}
CpuSet Affinity::GetAffinity()
{
CpuSet cpus;
CHECK(s_Manager.get_affinity(cpus)) << "GetAffinity failed";
return cpus;
}
CpuSet Affinity::GetCpusByNuma(int numa_id)
{
CpuSet cpus;
CHECK(s_Manager.get_cpus_by_numa(cpus, numa_id))
<< "GetCpusByNuma failed for numa_id: " << numa_id;
return cpus;
}
CpuSet Affinity::GetCpusBySocket(int socket_id)
{
CpuSet cpus;
CHECK(s_Manager.get_cpus_by_socket(cpus, socket_id))
<< "GetCpusBySocket failed for socket_id: " << socket_id;
return cpus;
}
CpuSet Affinity::GetCpusByCore(int core_id)
{
CpuSet cpus;
CHECK(s_Manager.get_cpus_by_core(cpus, core_id))
<< "GetCpusByCore failed for core_id: " << core_id;
return cpus;
}
CpuSet Affinity::GetCpusByProcessingUnit(int thread_id)
{
CpuSet cpus;
CHECK(s_Manager.get_cpus_by_processing_unit(cpus, thread_id))
<< "GetCpusByProcessingUnit failed for thread_id: " << thread_id;
return cpus;
}
cpuaff::cpu Affinity::GetCpuFromId(int id)
{
cpuaff::cpu cpu;
CHECK(s_Manager.get_cpu_from_id(cpu, id)) << "GetCpuById failed for cpu_id: " << id;
return cpu;
}
CpuSet Affinity::GetCpusFromString(const std::string& ids)
{
CpuSet cpus;
auto int_ids = ParseIDs(ids);
for(const auto id : int_ids)
{
cpus.insert(Affinity::GetCpuFromId(id));
// cpus = cpus.Union(Affinity::GetCpuFromId(id));
}
return cpus;
}
CpuSet CpuSet::Intersection(const CpuSet& other) const
{
CpuSet value;
set_intersection(begin(), end(), other.begin(), other.end(),
std::inserter(value, value.begin()));
return value;
}
CpuSet CpuSet::Union(const CpuSet& other) const
{
CpuSet value;
set_union(begin(), end(), other.begin(), other.end(), std::inserter(value, value.begin()));
return value;
}
CpuSet CpuSet::Difference(const CpuSet& other) const
{
CpuSet value;
set_difference(begin(), end(), other.begin(), other.end(), std::inserter(value, value.begin()));
return value;
}
std::string CpuSet::GetCpuString() const
{
auto allocator = GetAllocator();
std::ostringstream convert;
for(size_t i = 0; i < allocator.size(); i++)
{
auto j = allocator.allocate();
convert << j.id().get() << " ";
}
return convert.str();
}
int ConvertString2Int(const std::string& str)
{
int x;
std::stringstream ss(str);
CHECK(ss >> x) << "Error converting " << str << " to integer";
return x;
}
std::vector<std::string> SplitStringToArray(const std::string& str, char splitter)
{
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string temp;
while(getline(ss, temp, splitter)) // split into new "lines" based on character
{
tokens.push_back(temp);
}
return tokens;
}
std::vector<int> ParseIDs(const std::string data)
{
std::vector<int> result;
std::vector<std::string> tokens = SplitStringToArray(data, ',');
for(std::vector<std::string>::const_iterator it = tokens.begin(), end_it = tokens.end();
it != end_it; ++it)
{
const std::string& token = *it;
std::vector<std::string> range = SplitStringToArray(token, '-');
if(range.size() == 1)
{
result.push_back(ConvertString2Int(range[0]));
}
else if(range.size() == 2)
{
int start = ConvertString2Int(range[0]);
int stop = ConvertString2Int(range[1]);
for(int i = start; i <= stop; i++)
{
result.push_back(i);
}
}
else
{
LOG(FATAL) << "Error parsing token " << token;
}
}
return result;
}
} // namespace trtlab
| 30.40107 | 100 | 0.666139 | [
"vector"
] |
74a340bfef8466d77ff8e0b74bf189c99a837d96 | 481 | cpp | C++ | Modules/TArc/Sources/TArc/Utils/Private/RhiEmptyFrame.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 5 | 2020-02-11T12:04:17.000Z | 2022-01-30T10:18:29.000Z | Modules/TArc/Sources/TArc/Utils/Private/RhiEmptyFrame.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | null | null | null | Modules/TArc/Sources/TArc/Utils/Private/RhiEmptyFrame.cpp | reven86/dava.engine | ca47540c8694668f79774669b67d874a30188c20 | [
"BSD-3-Clause"
] | 4 | 2019-11-28T19:24:34.000Z | 2021-08-24T19:12:50.000Z | #include "TArc/Utils/RhiEmptyFrame.h"
#include "Render/Renderer.h"
#include "Render/RenderHelper.h"
namespace DAVA
{
namespace TArc
{
RhiEmptyFrame::RhiEmptyFrame()
{
const rhi::HTexture nullTexture;
const rhi::Viewport nullViewport(0, 0, 1, 1);
Renderer::BeginFrame();
RenderHelper::CreateClearPass(nullTexture, nullTexture, 0, Color::Clear, nullViewport);
}
RhiEmptyFrame::~RhiEmptyFrame()
{
Renderer::EndFrame();
}
} // namespace TArc
} // namespace DAVA
| 20.041667 | 91 | 0.721414 | [
"render"
] |
74a5ecac2e8f64a4e05d08cf947f104983ead48c | 12,273 | cpp | C++ | src/mongo/db/repl/repl_set_heartbeat_response.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/repl/repl_set_heartbeat_response.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/repl/repl_set_heartbeat_response.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/repl/repl_set_heartbeat_response.h"
#include <string>
#include "mongo/base/status.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/repl/bson_extract_optime.h"
#include "mongo/db/server_options.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/str.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplication
namespace mongo {
namespace repl {
namespace {
const std::string kConfigFieldName = "config";
const std::string kConfigVersionFieldName = "v";
const std::string kConfigTermFieldName = "configTerm";
const std::string kElectionTimeFieldName = "electionTime";
const std::string kMemberStateFieldName = "state";
const std::string kOkFieldName = "ok";
const std::string kDurableOpTimeFieldName = "durableOpTime";
const std::string kDurableWallTimeFieldName = "durableWallTime";
const std::string kAppliedOpTimeFieldName = "opTime";
const std::string kAppliedWallTimeFieldName = "wallTime";
const std::string kPrimaryIdFieldName = "primaryId";
const std::string kReplSetFieldName = "set";
const std::string kSyncSourceFieldName = "syncingTo";
const std::string kTermFieldName = "term";
const std::string kTimestampFieldName = "ts";
const std::string kIsElectableFieldName = "electable";
} // namespace
void ReplSetHeartbeatResponse::addToBSON(BSONObjBuilder* builder) const {
builder->append(kOkFieldName, 1.0);
if (_electionTimeSet) {
builder->appendDate(kElectionTimeFieldName,
Date_t::fromMillisSinceEpoch(_electionTime.asLL()));
}
if (_configSet) {
*builder << kConfigFieldName << _config.toBSON();
}
if (_stateSet) {
builder->appendNumber(kMemberStateFieldName, _state.s);
}
if (_configVersion != -1) {
*builder << kConfigVersionFieldName << _configVersion;
*builder << kConfigTermFieldName << _configTerm;
}
if (!_setName.empty()) {
*builder << kReplSetFieldName << _setName;
}
if (!_syncingTo.empty()) {
*builder << kSyncSourceFieldName << _syncingTo.toString();
}
if (_term != -1) {
builder->append(kTermFieldName, _term);
}
if (_primaryIdSet) {
builder->append(kPrimaryIdFieldName, _primaryId);
}
if (_durableOpTimeSet) {
_durableOpTime.append(builder, kDurableOpTimeFieldName);
builder->appendDate(kDurableWallTimeFieldName, _durableWallTime);
}
if (_appliedOpTimeSet) {
_appliedOpTime.append(builder, kAppliedOpTimeFieldName);
builder->appendDate(kAppliedWallTimeFieldName, _appliedWallTime);
}
if (_electableSet) {
*builder << kIsElectableFieldName << _electable;
}
}
BSONObj ReplSetHeartbeatResponse::toBSON() const {
BSONObjBuilder builder;
addToBSON(&builder);
return builder.obj();
}
Status ReplSetHeartbeatResponse::initialize(const BSONObj& doc, long long term) {
auto status = getStatusFromCommandResult(doc);
if (!status.isOK()) {
return status;
}
const BSONElement replSetNameElement = doc[kReplSetFieldName];
if (replSetNameElement.eoo()) {
_setName.clear();
} else if (replSetNameElement.type() != String) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kReplSetFieldName
<< "\" field in response to replSetHeartbeat to have "
"type String, but found "
<< typeName(replSetNameElement.type()));
} else {
_setName = replSetNameElement.String();
}
const BSONElement electionTimeElement = doc[kElectionTimeFieldName];
if (electionTimeElement.eoo()) {
_electionTimeSet = false;
} else if (electionTimeElement.type() == Date) {
_electionTimeSet = true;
_electionTime = Timestamp(electionTimeElement.date());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kElectionTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date, but found type "
<< typeName(electionTimeElement.type()));
}
Status termStatus = bsonExtractIntegerField(doc, kTermFieldName, &_term);
if (!termStatus.isOK() && termStatus != ErrorCodes::NoSuchKey) {
return termStatus;
}
status = bsonExtractOpTimeField(doc, kDurableOpTimeFieldName, &_durableOpTime);
if (!status.isOK()) {
return status;
}
BSONElement durableWallTimeElement;
_durableWallTime = Date_t();
status = bsonExtractTypedField(
doc, kDurableWallTimeFieldName, BSONType::Date, &durableWallTimeElement);
if (!status.isOK()) {
return status;
}
_durableWallTime = durableWallTimeElement.Date();
_durableOpTimeSet = true;
// In V1, heartbeats OpTime is type Object and we construct an OpTime out of its nested fields.
status = bsonExtractOpTimeField(doc, kAppliedOpTimeFieldName, &_appliedOpTime);
if (!status.isOK()) {
return status;
}
BSONElement appliedWallTimeElement;
_appliedWallTime = Date_t();
status = bsonExtractTypedField(
doc, kAppliedWallTimeFieldName, BSONType::Date, &appliedWallTimeElement);
if (!status.isOK()) {
return status;
}
_appliedWallTime = appliedWallTimeElement.Date();
_appliedOpTimeSet = true;
status = bsonExtractBooleanField(doc, kIsElectableFieldName, &_electable);
if (!status.isOK()) {
_electableSet = false;
} else {
_electableSet = true;
}
const BSONElement memberStateElement = doc[kMemberStateFieldName];
if (memberStateElement.eoo()) {
_stateSet = false;
} else if (memberStateElement.type() != NumberInt && memberStateElement.type() != NumberLong) {
return Status(ErrorCodes::TypeMismatch,
str::stream()
<< "Expected \"" << kMemberStateFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type NumberInt or NumberLong, but found type "
<< typeName(memberStateElement.type()));
} else {
long long stateInt = memberStateElement.numberLong();
if (stateInt < 0 || stateInt > MemberState::RS_MAX) {
return Status(ErrorCodes::BadValue,
str::stream()
<< "Value for \"" << kMemberStateFieldName
<< "\" in response to replSetHeartbeat is "
"out of range; legal values are non-negative and no more than "
<< MemberState::RS_MAX);
}
_stateSet = true;
_state = MemberState(static_cast<int>(stateInt));
}
const BSONElement configVersionElement = doc[kConfigVersionFieldName];
if (configVersionElement.eoo()) {
return Status(ErrorCodes::NoSuchKey,
str::stream() << "Response to replSetHeartbeat missing required \""
<< kConfigVersionFieldName << "\" field");
}
if (configVersionElement.type() != NumberInt) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kConfigVersionFieldName
<< "\" field in response to replSetHeartbeat to have "
"type NumberInt, but found "
<< typeName(configVersionElement.type()));
}
_configVersion = configVersionElement.numberInt();
// Allow a missing term field for backward compatibility.
const BSONElement configTermElement = doc[kConfigTermFieldName];
if (!configTermElement.eoo() && configVersionElement.type() == NumberInt) {
_configTerm = configTermElement.numberInt();
}
const BSONElement syncingToElement = doc[kSyncSourceFieldName];
if (syncingToElement.eoo()) {
_syncingTo = HostAndPort();
} else if (syncingToElement.type() != String) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kSyncSourceFieldName
<< "\" field in response to replSetHeartbeat to "
"have type String, but found "
<< typeName(syncingToElement.type()));
} else {
_syncingTo = HostAndPort(syncingToElement.String());
}
const BSONElement rsConfigElement = doc[kConfigFieldName];
if (rsConfigElement.eoo()) {
_configSet = false;
_config = ReplSetConfig();
return Status::OK();
} else if (rsConfigElement.type() != Object) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kConfigFieldName
<< "\" in response to replSetHeartbeat to have type "
"Object, but found "
<< typeName(rsConfigElement.type()));
}
_configSet = true;
try {
_config = ReplSetConfig::parse(rsConfigElement.Obj());
} catch (const DBException& e) {
return e.toStatus();
}
return Status::OK();
}
MemberState ReplSetHeartbeatResponse::getState() const {
invariant(_stateSet);
return _state;
}
Timestamp ReplSetHeartbeatResponse::getElectionTime() const {
invariant(_electionTimeSet);
return _electionTime;
}
const ReplSetConfig& ReplSetHeartbeatResponse::getConfig() const {
invariant(_configSet);
return _config;
}
long long ReplSetHeartbeatResponse::getPrimaryId() const {
invariant(_primaryIdSet);
return _primaryId;
}
OpTime ReplSetHeartbeatResponse::getAppliedOpTime() const {
invariant(_appliedOpTimeSet);
return _appliedOpTime;
}
OpTimeAndWallTime ReplSetHeartbeatResponse::getAppliedOpTimeAndWallTime() const {
invariant(_appliedOpTimeSet);
return {_appliedOpTime, _appliedWallTime};
}
OpTime ReplSetHeartbeatResponse::getDurableOpTime() const {
invariant(_durableOpTimeSet);
return _durableOpTime;
}
OpTimeAndWallTime ReplSetHeartbeatResponse::getDurableOpTimeAndWallTime() const {
invariant(_durableOpTimeSet);
return {_durableOpTime, _durableWallTime};
}
bool ReplSetHeartbeatResponse::isElectable() const {
invariant(_electableSet);
return _electable;
}
} // namespace repl
} // namespace mongo
| 37.996904 | 99 | 0.644341 | [
"object"
] |
74a92e2eb944116b14240b6c27ecf4f5a126c60b | 1,906 | cc | C++ | src/measurement_models/measurement_model_base.cc | jwidauer/refill | 64947e0a8e15855f4a5ad048f09f8d38715bbe91 | [
"MIT"
] | 2 | 2021-06-13T07:28:51.000Z | 2021-09-08T11:26:34.000Z | src/measurement_models/measurement_model_base.cc | jwidauer/refill | 64947e0a8e15855f4a5ad048f09f8d38715bbe91 | [
"MIT"
] | null | null | null | src/measurement_models/measurement_model_base.cc | jwidauer/refill | 64947e0a8e15855f4a5ad048f09f8d38715bbe91 | [
"MIT"
] | 3 | 2021-06-01T13:21:41.000Z | 2021-06-01T20:33:20.000Z | #include "refill/measurement_models/measurement_model_base.h"
using std::size_t;
namespace refill {
/**
* Use this constructor when inheriting from this class.
* The constructor clones the measurement noise, so it can be used again.
*
* @param state_dim The state dimension.
* @param measurement_dim The measurement dimension.
* @param measurement_noise The measurement noise.
*/
MeasurementModelBase::MeasurementModelBase(
const size_t& state_dim, const size_t& measurement_dim,
const DistributionInterface& measurement_noise)
: state_dim_(state_dim),
measurement_dim_(measurement_dim),
measurement_noise_(measurement_noise.clone()) {}
/**
* The function clones the measurement noise, so it can be used again.
*
* @param state_dim The state dimension.
* @param measurement_dim The measurement dimension.
* @param measurement_noise The measurement noise.
*/
void MeasurementModelBase::setMeasurementModelBaseParameters(
const size_t& state_dim, const size_t& measurement_dim,
const DistributionInterface& measurement_noise) {
state_dim_ = state_dim;
measurement_dim_ = measurement_dim;
measurement_noise_.reset(measurement_noise.clone());
}
/** @return the state dimension. */
size_t MeasurementModelBase::getStateDim() const {
return state_dim_;
}
/** @return the measurement dimension. */
size_t MeasurementModelBase::getMeasurementDim() const {
return measurement_dim_;
}
/** @return the noise dimension. */
size_t MeasurementModelBase::getNoiseDim() const {
CHECK(measurement_noise_) << "Measurement noise has not been set.";
return measurement_noise_->mean().size();
}
/** @return a pointer to the measurement model noise distribution. */
DistributionInterface* MeasurementModelBase::getNoise() const {
CHECK(measurement_noise_) << "Measurement noise has not been set.";
return measurement_noise_.get();
}
} // namespace refill
| 31.766667 | 73 | 0.764953 | [
"model"
] |
74b464d302fd62ff34d0e9e4dd06be14cd965261 | 2,204 | cpp | C++ | src/globals.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | 2 | 2020-05-08T20:27:14.000Z | 2021-01-21T10:28:19.000Z | src/globals.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | null | null | null | src/globals.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | 1 | 2020-05-08T20:27:16.000Z | 2020-05-08T20:27:16.000Z | #include <parrlib/globals.h>
#include <parrlib/sprite.h>
#include <parrlib/utils3d/mesh3d.h>
namespace globals {
std::unordered_map<std::string, TextRenderer> txrs;
bool findTxr(std::string const& name) { return txrs.find(name) != txrs.end(); }
void setTxr(std::string const& name, std::vector<std::string> const& fonts, int const& fontSize) { txrs[name] = { fonts, fontSize }; }
void setTxr(std::string const& name, std::string const& font, int const& fontSize) { setTxr(name, std::vector<std::string>{ font }, fontSize); }
void setTxr(std::string const& name, int const& fontSize) { setTxr(name, "assets/fonts/segoeui.ttf", fontSize); }
TextRenderer& getTxr(std::string const& name){
if (txrs.find(name) == txrs.end()) setTxr(name, 24);
return txrs[name];
}
std::unordered_map<std::string, Sprite> sprites;
bool findSprite(std::string const& name) { return sprites.find(name) != sprites.end(); }
void setSprite(std::string const& name, Sprite const& s) { sprites[name] = s; }
Sprite& getSprite(std::string const& name) {
if (sprites.find(name) == sprites.end()) sprites[name] = name.c_str();
return sprites[name];
}
std::unordered_map<std::string, Shader> shaders;
bool findShader(std::string const& name) { return shaders.find(name) != shaders.end(); }
void setShader(std::string const& name, Shader const& sh) { shaders[name] = sh; }
Shader& getShader(std::string const& name) {
if (shaders.find(name) == shaders.end()) shaders[name] = { (name + ".vert"), (name + ".frag") };
return shaders[name];
}
std::unordered_map<std::string, VAO> vaos;
bool findVAO(std::string const& name) { return vaos.find(name) != vaos.end(); }
void setVAO(std::string const& name, VAO const& vao) { vaos[name] = vao; }
VAO& getVAO(std::string const& name) {
if (vaos.find(name) == vaos.end()) vaos[name] = {};
return vaos[name];
}
std::unordered_map<std::string, Mesh3D> meshes;
bool findMesh(std::string const& name) { return meshes.find(name) != meshes.end(); }
void setMesh(std::string const& name, Mesh3D const& m) { meshes[name] = m; }
Mesh3D& getMesh(std::string const& name) {
if (!findMesh(name)) meshes[name] = { name.c_str() };
return meshes[name];
}
}
| 42.384615 | 145 | 0.676951 | [
"vector"
] |
74b53c60c5031ec35edb51ebd786751d7def10ac | 1,118 | hpp | C++ | src/algorithms/prune.hpp | vgteam/od | 9e9c4811169760f64690e86619dbd1b088ec5955 | [
"MIT"
] | 60 | 2019-03-04T13:32:46.000Z | 2021-02-23T02:32:54.000Z | src/algorithms/prune.hpp | vgteam/od | 9e9c4811169760f64690e86619dbd1b088ec5955 | [
"MIT"
] | 120 | 2019-03-08T18:06:37.000Z | 2021-03-18T09:12:16.000Z | src/algorithms/prune.hpp | vgteam/od | 9e9c4811169760f64690e86619dbd1b088ec5955 | [
"MIT"
] | 18 | 2019-04-03T09:50:57.000Z | 2021-02-23T14:55:55.000Z | #ifndef DSGVG_PRUNE_HPP_INCLUDED
#define DSGVG_PRUNE_HPP_INCLUDED
#include <iostream>
#include <vector>
#include <list>
#include <omp.h>
#include <handlegraph/util.hpp>
#include <handlegraph/handle_graph.hpp>
#include "position.hpp"
/** \file
* Functions for working with `kmers_t`'s in HandleGraphs.
*/
namespace odgi {
using namespace handlegraph;
namespace algorithms {
/// Record a <=k-length walk in the context of a graph.
struct walk_t {
walk_t(uint16_t l,
const pos_t& b,
const pos_t& e,
const handle_t& c,
uint16_t f)
: length(l), begin(b), end(e), curr(c), forks(f) { };
/// our start position
pos_t begin;
pos_t end; /// one past the (current) end of the kmer
handle_t curr; /// the next handle we extend into
uint16_t forks; /// how many branching edge crossings we took to get here
uint16_t length; /// how far we've been
};
/// Iterate over all the walks up to length k, adding edges which
std::vector<edge_t> find_edges_to_prune(const HandleGraph& graph, size_t k, size_t edge_max, int n_threads);
}
}
#endif
| 24.304348 | 108 | 0.677102 | [
"vector"
] |
74bb5ff266a999a8f140d91ae76da88592aa300f | 1,600 | cpp | C++ | src/BMPFile.cpp | wysiwyng/sidecrawler | 4f19604945cc7377d7f3f8a4da71c340a7d87383 | [
"BSD-3-Clause"
] | 2 | 2015-03-11T09:20:37.000Z | 2015-09-06T21:02:28.000Z | src/BMPFile.cpp | wysiwyng/sidecrawler | 4f19604945cc7377d7f3f8a4da71c340a7d87383 | [
"BSD-3-Clause"
] | null | null | null | src/BMPFile.cpp | wysiwyng/sidecrawler | 4f19604945cc7377d7f3f8a4da71c340a7d87383 | [
"BSD-3-Clause"
] | null | null | null | #include "BMPFile.h"
#include "Polycode.h"
BMPFile::BMPFile(){
}
BMPFile::BMPFile(const char * filename){
read(filename);
}
BMPFile::~BMPFile(){
}
void BMPFile::read(const char* filename){
std::ifstream file(filename);
if (file){
file.seekg(0, std::ios::end);
std::streampos length = file.tellg();
file.seekg(0, std::ios::beg);
buffer.resize(length);
file.read(&buffer[0], length);
file_header = (pbmp_file_header)(&buffer[0]);
info_header = (pbmp_info_header)(&buffer[0] + sizeof(bmp_file_header));
for (int i = 0; i < info_header->biClrUsed; i++){
color_table.push_back((pcolor)(&buffer[0] + sizeof(bmp_file_header) + sizeof(bmp_info_header) + sizeof(color) * i));
}
//color_table = (pbmp_color_table)(&buffer[0] + sizeof(bmp_file_header) + sizeof(bmp_info_header));
}
}
std::vector< std::vector<unsigned char> > BMPFile::read_data(){
std::vector< std::vector<unsigned char> > ret;
int idx = file_header->bfOffBits;
int width = info_header->biWidth;
int height = info_header->biHeight;
for (int i = 0; i < height; i++){
std::vector<unsigned char> temp;
for (int j = 0; j < width / 2; j++){
temp.push_back((unsigned char)buffer[idx] >> 4);
temp.push_back((unsigned char)buffer[idx++] & 0xf);
Polycode::Logger::log("idx:%d, i:%d, j:%d, lower:%x, upper:%x\n", idx, i, j, (unsigned char)buffer[idx - 1] >> 4, (unsigned char)buffer[idx - 1] & 0xf);
}
ret.insert(ret.begin(), temp);
}
return ret;
}
unsigned int BMPFile::get_size_x(){
return info_header->biWidth;
}
unsigned int BMPFile::get_size_y(){
return info_header->biHeight;
}
| 24.615385 | 155 | 0.664375 | [
"vector"
] |
74c0c54273fe8334758c4357be6134352b02d739 | 3,654 | cc | C++ | src/server/memory/malloc.cc | TREiop/v6d | 9ad80c65c226405b0c7b4ed6b6c9b1229bbf9175 | [
"Apache-2.0",
"CC0-1.0"
] | 417 | 2020-10-23T12:35:27.000Z | 2021-04-15T09:37:00.000Z | src/server/memory/malloc.cc | TREiop/v6d | 9ad80c65c226405b0c7b4ed6b6c9b1229bbf9175 | [
"Apache-2.0",
"CC0-1.0"
] | 294 | 2021-05-28T03:04:26.000Z | 2022-03-31T07:09:45.000Z | src/server/memory/malloc.cc | TREiop/v6d | 9ad80c65c226405b0c7b4ed6b6c9b1229bbf9175 | [
"Apache-2.0",
"CC0-1.0"
] | 30 | 2021-05-31T13:34:57.000Z | 2022-03-25T06:39:47.000Z | /**
* NOLINT(legal/copyright)
*
* The file src/server/memory/malloc.cc is referred and derived from project
* apache-arrow,
*
* https://github.com/apache/arrow/blob/master/cpp/src/plasma/malloc.cc
*
* which has the following license:
*
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
*/
#include "server/memory/malloc.h"
#include <stddef.h>
#include <string>
#include <vector>
#include "common/util/logging.h"
namespace vineyard {
namespace memory {
std::unordered_map<void*, MmapRecord> mmap_records;
static void* pointer_advance(void* p, ptrdiff_t n) {
return (unsigned char*) p + n;
}
static ptrdiff_t pointer_distance(void const* pfrom, void const* pto) {
return (unsigned char const*) pto - (unsigned char const*) pfrom;
}
// Create a buffer. This is creating a temporary file and then
// immediately unlinking it so we do not leave traces in the system.
int create_buffer(int64_t size) {
int fd = -1;
#ifdef _WIN32
if (!CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
(DWORD)((uint64_t) size >> (CHAR_BIT * sizeof(DWORD))),
(DWORD)(uint64_t) size, NULL)) {
fd = -1;
}
#else
// directory where to create the memory-backed file
#ifdef __linux__
std::string file_template = "/dev/shm/vineyard-bulk-XXXXXX";
#else
std::string file_template = "/tmp/vineyard-bulk-XXXXXX";
#endif
std::vector<char> file_name(file_template.begin(), file_template.end());
file_name.push_back('\0');
fd = mkstemp(&file_name[0]);
if (fd < 0) {
LOG(FATAL) << "create_buffer failed to open file " << &file_name[0];
return -1;
}
// Immediately unlink the file so we do not leave traces in the system.
if (unlink(&file_name[0]) != 0) {
LOG(FATAL) << "failed to unlink file " << &file_name[0];
return -1;
}
if (true) {
// Increase the size of the file to the desired size. This seems not to be
// needed for files that are backed by the huge page fs, see also
// http://www.mail-archive.com/kvm-devel@lists.sourceforge.net/msg14737.html
if (ftruncate(fd, (off_t) size) != 0) {
LOG(FATAL) << "failed to ftruncate file " << &file_name[0];
return -1;
}
}
#endif
return fd;
}
void GetMallocMapinfo(void* addr, int* fd, int64_t* map_size,
ptrdiff_t* offset) {
// About the efficiences: the records size usually small, thus linear search
// is enough.
for (const auto& entry : mmap_records) {
if (addr >= entry.first &&
addr < pointer_advance(entry.first, entry.second.size)) {
*fd = entry.second.fd;
*map_size = entry.second.size;
*offset = pointer_distance(entry.first, addr);
return;
}
}
LOG(INFO) << "fd not found... for " << addr
<< ", size = " << mmap_records.size();
*fd = -1;
*map_size = 0;
*offset = 0;
}
} // namespace memory
} // namespace vineyard
| 31.230769 | 80 | 0.670224 | [
"vector"
] |
74c4e4d94b74138339cc14d538a7f8d45a279ad6 | 265 | cpp | C++ | ConsoleApplication2/ConsoleApplication2/ConsoleApplication2.cpp | mattgambill/MiscCppProjects | e2c6d39e8f6825b28ba0fea19268bfc3a59b736f | [
"MIT"
] | null | null | null | ConsoleApplication2/ConsoleApplication2/ConsoleApplication2.cpp | mattgambill/MiscCppProjects | e2c6d39e8f6825b28ba0fea19268bfc3a59b736f | [
"MIT"
] | null | null | null | ConsoleApplication2/ConsoleApplication2/ConsoleApplication2.cpp | mattgambill/MiscCppProjects | e2c6d39e8f6825b28ba0fea19268bfc3a59b736f | [
"MIT"
] | null | null | null | // ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include<iostream>
#include<cmath>
#include<vector>
int main()
{
int count=0, j=0;
double a0,a, v1, v2, k, purity, epsilon;
return 0;
}
| 10.6 | 82 | 0.596226 | [
"vector"
] |
74c5a99bb6933dc58fef991ea024c0fd00bd114c | 16,094 | cc | C++ | elec/ProcBox.cc | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 33 | 2018-12-12T20:05:06.000Z | 2021-09-26T13:30:16.000Z | elec/ProcBox.cc | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 5 | 2019-04-25T11:34:43.000Z | 2021-11-14T04:35:37.000Z | elec/ProcBox.cc | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 15 | 2018-12-21T22:44:59.000Z | 2021-08-29T10:30:25.000Z | #include "ProcBox.hh"
#include <cassert>
#include <iostream>
//ewd DEBUG
#include "GridPoint.hh"
#include <mpi.h>
//ewd DEBUG
using namespace std;
ProcBox::ProcBox(int peid) : peid_(peid)
{
addCnt_ = 0;
planes_.resize(3);
axisPoints_.resize(3);
min_.resize(3);
max_.resize(3);
for (int ii=0; ii<3; ii++)
{
min_[ii] = 999999999;
max_[ii] = -999999999;
}
}
ProcBox::~ProcBox()
{
// delete all Plane objects
for (int ii=0; ii<3; ++ii)
for (map<int,Plane*>::iterator it = planes_[ii].begin(); it != planes_[ii].end(); it++)
if ((*it).second != 0)
delete (*it).second;
}
int ProcBox::volume()
{
/*
int vol = 1;
for (int ii=0; ii<3; ii++)
vol *= (maxAxisPoint(ii) - minAxisPoint(ii) + 1);
if (vol < 0) vol = 0;
return vol;
*/
int vol = 1;
for (int ii=0; ii<3; ii++)
vol *= (max_[ii] - min_[ii] + 1);
if (vol < 0) vol = 0;
return vol;
}
void ProcBox::add3DCoord(int x, int y, int z)
{
addCnt_++;
axisPoints_[0].insert(x);
axisPoints_[1].insert(y);
axisPoints_[2].insert(z);
if (x < min_[0]) min_[0] = x;
if (y < min_[1]) min_[1] = y;
if (z < min_[2]) min_[2] = z;
if (x > max_[0]) max_[0] = x;
if (y > max_[1]) max_[1] = y;
if (z > max_[2]) max_[2] = z;
if (planes_[0][x] == 0)
planes_[0][x] = new Plane(x,x,y,y,z,z);
if (planes_[1][y] == 0)
planes_[1][y] = new Plane(x,x,y,y,z,z);
if (planes_[2][z] == 0)
planes_[2][z] = new Plane(x,x,y,y,z,z);
Plane* xp = planes_[0][x];
if (y < xp->min[1]) xp->min[1] = y;
if (y > xp->max[1]) xp->max[1] = y;
if (z < xp->min[2]) xp->min[2] = z;
if (z > xp->max[2]) xp->max[2] = z;
Plane* yp = planes_[1][y];
if (x < xp->min[0]) xp->min[0] = x;
if (x > xp->max[0]) xp->max[0] = x;
if (z < xp->min[2]) xp->min[2] = z;
if (z > xp->max[2]) xp->max[2] = z;
Plane* zp = planes_[2][z];
if (x < xp->min[0]) xp->min[0] = x;
if (x > xp->max[0]) xp->max[0] = x;
if (y < xp->min[1]) xp->min[1] = y;
if (y > xp->max[1]) xp->max[1] = y;
}
void ProcBox::planesToCoords(vector<int>& coords)
{
int x,y,z;
for (map<int,Plane*>::iterator it = planes_[0].begin(); it != planes_[0].end(); it++)
{
x = (*it).first;
Plane* pp = (*it).second;
if (pp != 0)
{
y = pp->min[1]; z = pp->min[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->max[1]; z = pp->min[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->min[1]; z = pp->max[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->max[1]; z = pp->max[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
}
}
for (map<int,Plane*>::iterator it = planes_[1].begin(); it != planes_[1].end(); it++)
{
y = (*it).first;
Plane* pp = (*it).second;
if (pp != 0)
{
x = pp->min[0]; z = pp->min[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
x = pp->max[0]; z = pp->min[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
x = pp->min[0]; z = pp->max[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
x = pp->max[0]; z = pp->max[2];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
}
}
for (map<int,Plane*>::iterator it = planes_[2].begin(); it != planes_[2].end(); it++)
{
z = (*it).first;
Plane* pp = (*it).second;
if (pp != 0)
{
y = pp->min[1]; x = pp->min[0];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->max[1]; x = pp->min[0];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->min[1]; x = pp->max[0];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
y = pp->max[1]; x = pp->max[0];
coords.push_back(x); coords.push_back(y); coords.push_back(z);
}
}
}
void ProcBox::addPlane(int dim, Plane* plptr)
{
int val = plptr->min[dim];
axisPoints_[dim].insert(val);
if (planes_[dim][val] == 0) // add pointer to planes_
planes_[dim][val] = plptr;
else // update boundaries of current plane
{
for (int ii=0; ii<3; ii++)
if (ii != dim)
{
if (plptr->min[ii] < planes_[dim][val]->min[ii])
planes_[dim][val]->min[ii] = plptr->min[ii];
if (plptr->max[ii] > planes_[dim][val]->max[ii])
planes_[dim][val]->max[ii] = plptr->max[ii];
}
}
// update plane boundaries in other dimensions
for (int ii=0; ii<3; ii++)
{
if (ii != dim)
{
int pminii = plptr->min[ii];
int pmaxii = plptr->max[ii];
for (map<int,Plane*>::iterator it = planes_[ii].begin(); it != planes_[ii].end(); it++)
{
int qval = (*it).first;
Plane* qptr = (*it).second;
if (qptr != 0)
{
if (qval <= pmaxii && qval >= pminii)
{
if (qptr->max[ii] < val)
qptr->max[ii] = val;
if (qptr->min[ii] > val)
qptr->min[ii] = val;
/*
// only update plane if it intersects in dim jj
for (int jj=0; jj<3; jj++)
{
if (jj != dim && jj != ii)
{
if (!(plptr->min[jj] > qptr->max[jj]) && !(plptr->max[jj] < qptr->min[jj]))
if (qptr->max[ii] < val)
qptr->max[ii] = val;
if (qptr->min[ii] > val)
qptr->min[ii] = val;
}
}
*/
}
}
}
}
}
}
void ProcBox::deletePlane(int dim, int val)
{
//ewd: this function isn't used currently, remove it?
if (planes_[dim][val] != 0)
delete planes_[dim][val];
axisPoints_[dim].erase(val);
}
void ProcBox::removePlane(int dim, int val)
{
//ewd: need to change min/max of other planes from this value
//ewd: to next one down the axisPoint list
for (int ii=0; ii<3; ii++)
{
if (ii != dim)
{
for (map<int,Plane*>::iterator it = planes_[ii].begin(); it != planes_[ii].end(); it++)
{
int plval = (*it).first;
Plane* plptr = (*it).second;
if (plptr != 0)
{
if (plptr->min[dim] == val && plptr->max[dim] == val)
{
axisPoints_[ii].erase(plval);
(*it).second = 0;
}
else
{
if (plptr->min[dim] == val)
{
int nextMin = secondMinAxisPoint(dim);
if (nextMin > -1)
plptr->min[dim] = nextMin;
}
if (plptr->max[dim] == val)
{
int nextMax = secondMaxAxisPoint(dim);
if (nextMax > -1)
plptr->max[dim] = nextMax;
}
}
}
}
}
}
if (planes_[dim][val] != 0)
planes_[dim][val] = 0;
axisPoints_[dim].erase(val);
}
void ProcBox::updateBoundaries()
{
/*
for (int ii=0; ii<3; ii++)
{
int tmin = 999999999;
int tmax = -999999999;
if (axisPoints_[ii].size() == 0)
{
for (int jj=0; jj<3; jj++)
if (jj != ii)
for (map<int,Plane*>::iterator it = planes_[jj].begin(); it != planes_[jj].end(); it++)
{
Plane* pp = (*it).second;
if (pp != 0)
{
{
if (pp->min[ii] < tmin) tmin = pp->min[ii];
if (pp->max[ii] > tmax) tmax = pp->max[ii];
}
}
}
}
else
{
tmin = minAxisPoint(ii);
tmax = maxAxisPoint(ii);
}
min_[ii] = ( tmin > -1 ? tmin : 999999999);
max_[ii] = ( tmax > -1 ? tmax : -999999999);
}
*/
// loop through all planes, compute min, max in all directions
for (int ii=0; ii<3; ii++)
{
min_[ii] = 999999999;
max_[ii] = -999999999;
}
for (int ii=0; ii<3; ii++)
for (map<int,Plane*>::iterator it = planes_[ii].begin(); it != planes_[ii].end(); it++)
{
int val = (*it).first;
Plane* pp = (*it).second;
if (pp != 0)
{
if (val < min_[ii]) min_[ii] = val;
if (val > max_[ii]) max_[ii] = val;
for (int jj=0; jj<3; jj++)
if (jj != ii)
{
if (pp->min[jj] < min_[jj]) min_[jj] = pp->min[jj];
if (pp->max[jj] > max_[jj]) max_[jj] = pp->max[jj];
}
}
}
}
int ProcBox::trialMove(int dim, int val, ProcBox& nbrbox)
{
if (val < 0)
return 1;
assert(dim < 3 && dim >= 0);
int myvol = volume();
int nbrvol = nbrbox.volume();
int maxvol = ( myvol > nbrvol ? myvol : nbrvol);
Plane* planeptr = planes_[dim][val]; // save plane pointer
Plane nbrcopy; // save copy of current plane, if necessary (shouldn't be)
int nbrcopied = 0;
// move plane from this ProcBox to nbrbox, see if maxvol is reduced
if (planeptr != 0 && myvol > 0)
{
//ewd DEBUG
{
int nbr = nbrbox.myRank();
int npex_ = 32;
int npey_ = 32;
int npez_ = 32;
GridPoint gpt(peid_,npex_,npey_,npez_);
GridPoint nbrpt(nbr,npex_,npey_,npez_);
int myRank_;
MPI_Comm_rank(MPI_COMM_WORLD, &myRank_);
if (myRank_ == 39)
cout << "TRIAL_START: dim = " << dim << ", val = " << val
<< ", pe " << peid_ << " (" << gpt.x << "," << gpt.y << "," << gpt.z << "), box = " <<
minPoint(0) << " " << maxPoint(0) << " " <<
minPoint(1) << " " << maxPoint(1) << " " <<
minPoint(2) << " " << maxPoint(2)
<< ", nbr " << nbr << " (" << nbrpt.x << "," << nbrpt.y << "," << nbrpt.z << "), box = " <<
nbrbox.minPoint(0) << " " << nbrbox.maxPoint(0) << " " <<
nbrbox.minPoint(1) << " " << nbrbox.maxPoint(1) << " " <<
nbrbox.minPoint(2) << " " << nbrbox.maxPoint(2)
<< ", myvol = " << myvol << ", nbrvol = " << nbrvol << endl;
}
//ewd DEBUG
int tvol = trialVolume(true,dim,planeptr);
int tnbr = nbrbox.trialVolume(false,dim,planeptr);
if (tvol > 0 && tnbr > 0 && tvol < maxvol && tnbr < maxvol) // accept move
{
removePlane(dim,val);
nbrbox.addPlane(dim,planeptr);
updateBoundaries();
nbrbox.updateBoundaries();
//ewd DEBUG
{
int nbr = nbrbox.myRank();
int npex_ = 32;
int npey_ = 32;
int npez_ = 32;
GridPoint gpt(peid_,npex_,npey_,npez_);
GridPoint nbrpt(nbr,npex_,npey_,npez_);
int myRank_;
MPI_Comm_rank(MPI_COMM_WORLD, &myRank_);
if (myRank_ == 39)
cout << "TRIAL_ACCEPTED: dim = " << dim << ", val = " << val
<< ", pe " << peid_ << " (" << gpt.x << "," << gpt.y << "," << gpt.z << "), box = " <<
minPoint(0) << " " << maxPoint(0) << " " <<
minPoint(1) << " " << maxPoint(1) << " " <<
minPoint(2) << " " << maxPoint(2)
<< ", nbr " << nbr << " (" << nbrpt.x << "," << nbrpt.y << "," << nbrpt.z << "), box = " <<
nbrbox.minPoint(0) << " " << nbrbox.maxPoint(0) << " " <<
nbrbox.minPoint(1) << " " << nbrbox.maxPoint(1) << " " <<
nbrbox.minPoint(2) << " " << nbrbox.maxPoint(2)
<< ", myvol = " << tvol << ", nbrvol = " << tnbr << endl;
}
//ewd DEBUG
return 0;
}
else // reject move
{
//ewd DEBUG
{
int nbr = nbrbox.myRank();
int npex_ = 32;
int npey_ = 32;
int npez_ = 32;
GridPoint gpt(peid_,npex_,npey_,npez_);
GridPoint nbrpt(nbr,npex_,npey_,npez_);
int myRank_;
myvol = volume();
nbrvol = nbrbox.volume();
MPI_Comm_rank(MPI_COMM_WORLD, &myRank_);
if (myRank_ == 39)
cout << "TRIAL_REJECTED1: dim = " << dim << ", val = " << val
<< ", pe " << peid_ << " (" << gpt.x << "," << gpt.y << "," << gpt.z << "), box = " <<
minPoint(0) << " " << maxPoint(0) << " " <<
minPoint(1) << " " << maxPoint(1) << " " <<
minPoint(2) << " " << maxPoint(2)
<< ", nbr " << nbr << " (" << nbrpt.x << "," << nbrpt.y << "," << nbrpt.z << "), box = " <<
nbrbox.minPoint(0) << " " << nbrbox.maxPoint(0) << " " <<
nbrbox.minPoint(1) << " " << nbrbox.maxPoint(1) << " " <<
nbrbox.minPoint(2) << " " << nbrbox.maxPoint(2)
<< ", myvol = " << myvol << ", nbrvol = " << nbrvol << endl;
}
//ewd DEBUG
return 1;
}
}
else // planeptr == 0 || vol == 0
return 1;
}
int ProcBox::trialVolume(bool removePlane, int dim, Plane* pptr)
{
vector<int> tmin(3), tmax(3), pmin(3), pmax(3);
for (int ii=0; ii<3; ii++)
{
tmin[ii] = min_[ii];
tmax[ii] = max_[ii];
pmin[ii] = pptr->min[ii];
pmax[ii] = pptr->max[ii];
}
int pval = pmin[dim];
if (removePlane)
{
if (pval == tmin[dim])
tmin[dim] = secondMinAxisPoint(dim);
if (pval == tmax[dim])
tmax[dim] = secondMaxAxisPoint(dim);
if (tmax[dim] == -1 || tmin[dim] == -1)
return -1;
for (int ii=0; ii<3; ii++)
{
if (ii != dim)
{
if (pmin[ii] == tmin[ii])
tmin[ii] = secondMinAxisPoint(ii);
if (pmax[ii] == tmax[ii])
tmax[ii] = secondMaxAxisPoint(ii);
if (tmax[ii] == -1 || tmin[ii] == -1)
return -1;
}
}
int tvol = (tmax[2]-tmin[2])*(tmax[1]-tmin[1])*(tmax[0]-tmin[0]);
return tvol;
}
else
{
for (int ii=0; ii<3; ii++)
{
if (pmin[ii] < tmin[ii])
tmin[ii] = pmin[ii];
if (pmax[ii] > tmax[ii])
tmax[ii] = pmax[ii];
}
int tvol = (tmax[2]-tmin[2])*(tmax[1]-tmin[1])*(tmax[0]-tmin[0]);
return tvol;
}
}
int ProcBox::maxAxisPoint(int dim)
{
int val = -1;
if (axisPoints_[dim].size() > 0)
{
set<int>::iterator it;
it = axisPoints_[dim].end();
it--;
val = *it;
}
return val;
}
int ProcBox::secondMaxAxisPoint(int dim)
{
int val = -1;
if (axisPoints_[dim].size() > 1)
{
set<int>::iterator it;
it = axisPoints_[dim].end();
it--;
it--;
val = *it;
}
return val;
}
int ProcBox::minAxisPoint(int dim)
{
int val = -1;
if (axisPoints_[dim].size() > 0)
{
set<int>::iterator it;
it = axisPoints_[dim].begin();
val = *it;
}
return val;
}
int ProcBox::secondMinAxisPoint(int dim)
{
int val = -1;
if (axisPoints_[dim].size() > 1)
{
set<int>::iterator it;
it = axisPoints_[dim].begin();
it++;
val = *it;
}
return val;
}
bool ProcBox::containsPoint(int x, int y, int z)
{
if (x > max_[0]) return false;
if (x < min_[0]) return false;
if (y > max_[1]) return false;
if (y < min_[1]) return false;
if (z > max_[2]) return false;
if (z < min_[2]) return false;
return true;
}
| 29.970205 | 111 | 0.441345 | [
"vector"
] |
74c6fe8405740ec3b0d135a93cf09b0cc2aff7ba | 3,466 | cpp | C++ | test/test_similarity.cpp | danila19991/graph-analysis | edac8a56ea0b74235c31340bf2b691dbbcdb7be6 | [
"Apache-2.0"
] | null | null | null | test/test_similarity.cpp | danila19991/graph-analysis | edac8a56ea0b74235c31340bf2b691dbbcdb7be6 | [
"Apache-2.0"
] | 2 | 2019-05-09T19:49:16.000Z | 2019-05-20T09:13:42.000Z | test/test_similarity.cpp | danila19991/graph-analysis | edac8a56ea0b74235c31340bf2b691dbbcdb7be6 | [
"Apache-2.0"
] | null | null | null | //
// Created by danila on 27.04.19.
//
#include <gtest/gtest.h>
#include "../algo/algorithms.hpp"
#include "test_utils.h"
#include <math.h>
TEST(test_common_neighbors, empty_graph)
{
std::vector<std::vector<int>> e;
std::vector<int> t;
graph g(e,t);
auto res = common_neighbors(g);
ASSERT_EQ(res, mat{}) << "empty graph is indirect";
}
TEST(test_common_neighbors, tree)
{
std::vector<std::vector<int>> e{
{1},
{0, 2},
{1}
};
std::vector<int> t{0,1,2};
graph g(e,t);
auto res = common_neighbors(g);
ASSERT_EQ(res, mat({{1, 0, 1},{0, 2, 0},{1, 0, 1}})) << "similarity is incorrect";
}
TEST(test_jaccard_metric, tree)
{
std::vector<std::vector<int>> e{
{1},
{0, 2},
{1}
};
std::vector<int> t{0,1,2};
graph g(e,t);
auto res = jaccard_metric(g);
ASSERT_EQ(res, mat({{1, 0, 1},{0, 1, 0},{1, 0, 1}})) << "empty graph is indirect";
}
TEST(test_adamic_adar_metric, tree)
{
std::vector<std::vector<int>> e{
{1},
{0, 2},
{1}
};
std::vector<int> t{0,1,2};
graph g(e,t);
auto res = adamic_adar_metric(g);
ASSERT_EQ(res, mat({{0, 0, 1./log(2.)},{0, 0, 0},{1./log(2.), 0, 0}})) << "empty graph is indirect";
}
TEST(test_preferential_attachment, tree)
{
std::vector<std::vector<int>> e{
{1},
{0, 2},
{1}
};
std::vector<int> t{0,1,2};
graph g(e,t);
auto res = preferential_attachment(g);
ASSERT_EQ(res, mat({{1, 2, 1},{2, 4, 2},{1, 2, 1}})) << "empty graph is indirect";
}
TEST(test_intersection, empty)
{
std::vector<int> e;
std::vector<int> t;
std::vector<int> expected;
auto res = intersection(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_intersection, empty_intersection)
{
std::vector<int> e{0,2,4};
std::vector<int> t{1,3,5};
std::vector<int> expected;
auto res = intersection(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_intersection, not_empty_intesection)
{
std::vector<int> e{0,1,3,5};
std::vector<int> t{1,2,3,4,6};
std::vector<int> expected{1,3};
auto res = intersection(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_intersection, equal_vectors)
{
std::vector<int> e{1,2,3};
std::vector<int> t{1,2,3};
std::vector<int> expected{1,2,3};
auto res = intersection(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_merge, empty)
{
std::vector<int> e;
std::vector<int> t;
std::vector<int> expected;
auto res = merge(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_merge, empty_intersection)
{
std::vector<int> e{0,2,4};
std::vector<int> t{1,3,5};
std::vector<int> expected{0,1,2,3,4,5};
auto res = merge(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_merge, not_empty_intesection)
{
std::vector<int> e{0,1,3,5};
std::vector<int> t{1,2,3,4,6};
std::vector<int> expected{0,1,2,3,4,5,6};
auto res = merge(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
TEST(test_merge, equal_vectors)
{
std::vector<int> e{1,2,3};
std::vector<int> t{1,2,3};
std::vector<int> expected{1,2,3};
auto res = merge(e, t);
ASSERT_EQ(res, expected) << "not correct intersection";
}
| 24.069444 | 104 | 0.578477 | [
"vector"
] |
74cba8a4d5fb30789e3ba152bcbb4bcfccac3147 | 5,008 | cc | C++ | rtc_base/sequenced_task_checker_unittest.cc | 18165/webrtc | b118d428499844749df6dd28aa3dbc8d5e1484fe | [
"BSD-3-Clause"
] | null | null | null | rtc_base/sequenced_task_checker_unittest.cc | 18165/webrtc | b118d428499844749df6dd28aa3dbc8d5e1484fe | [
"BSD-3-Clause"
] | null | null | null | rtc_base/sequenced_task_checker_unittest.cc | 18165/webrtc | b118d428499844749df6dd28aa3dbc8d5e1484fe | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/sequenced_task_checker.h"
#include <memory>
#include <utility>
#include "absl/memory/memory.h"
#include "api/function_view.h"
#include "rtc_base/event.h"
#include "rtc_base/platform_thread.h"
#include "rtc_base/task_queue_for_test.h"
#include "rtc_base/thread_checker.h"
#include "test/gtest.h"
namespace rtc {
namespace {
using ::webrtc::TaskQueueForTest;
// This class is dead code, but its purpose is to make sure that
// SequencedTaskChecker is compatible with the RTC_GUARDED_BY and RTC_RUN_ON
// attributes that are checked at compile-time.
class CompileTimeTestForGuardedBy {
public:
int CalledOnSequence() RTC_RUN_ON(sequence_checker_) { return guarded_; }
void CallMeFromSequence() {
RTC_DCHECK_RUN_ON(&sequence_checker_) << "Should be called on sequence";
guarded_ = 41;
}
private:
int guarded_ RTC_GUARDED_BY(sequence_checker_);
SequencedTaskChecker sequence_checker_;
};
void RunOnDifferentThread(FunctionView<void()> run) {
struct Object {
static void Run(void* obj) {
auto* me = static_cast<Object*>(obj);
me->run();
me->thread_has_run_event.Set();
}
FunctionView<void()> run;
Event thread_has_run_event;
} object{run};
PlatformThread thread(&Object::Run, &object, "thread");
thread.Start();
EXPECT_TRUE(object.thread_has_run_event.Wait(1000));
thread.Stop();
}
} // namespace
TEST(SequencedTaskCheckerTest, CallsAllowedOnSameThread) {
SequencedTaskChecker sequenced_task_checker;
EXPECT_TRUE(sequenced_task_checker.CalledSequentially());
}
TEST(SequencedTaskCheckerTest, DestructorAllowedOnDifferentThread) {
auto sequenced_task_checker = absl::make_unique<SequencedTaskChecker>();
RunOnDifferentThread([&] {
// Verify that the destructor doesn't assert when called on a different
// thread.
sequenced_task_checker.reset();
});
}
TEST(SequencedTaskCheckerTest, DetachFromThread) {
SequencedTaskChecker sequenced_task_checker;
sequenced_task_checker.Detach();
RunOnDifferentThread(
[&] { EXPECT_TRUE(sequenced_task_checker.CalledSequentially()); });
}
TEST(SequencedTaskCheckerTest, DetachFromThreadAndUseOnTaskQueue) {
SequencedTaskChecker sequenced_task_checker;
sequenced_task_checker.Detach();
TaskQueueForTest queue;
queue.SendTask(
[&] { EXPECT_TRUE(sequenced_task_checker.CalledSequentially()); });
}
TEST(SequencedTaskCheckerTest, DetachFromTaskQueueAndUseOnThread) {
TaskQueueForTest queue;
queue.SendTask([] {
SequencedTaskChecker sequenced_task_checker;
sequenced_task_checker.Detach();
RunOnDifferentThread(
[&] { EXPECT_TRUE(sequenced_task_checker.CalledSequentially()); });
});
}
TEST(SequencedTaskCheckerTest, MethodNotAllowedOnDifferentThreadInDebug) {
SequencedTaskChecker sequenced_task_checker;
RunOnDifferentThread([&] {
EXPECT_EQ(sequenced_task_checker.CalledSequentially(), !RTC_DCHECK_IS_ON);
});
}
TEST(SequencedTaskCheckerTest, MethodNotAllowedOnDifferentTaskQueueInDebug) {
SequencedTaskChecker sequenced_task_checker;
TaskQueueForTest queue;
queue.SendTask([&] {
EXPECT_EQ(sequenced_task_checker.CalledSequentially(), !RTC_DCHECK_IS_ON);
});
}
TEST(SequencedTaskCheckerTest, DetachFromTaskQueueInDebug) {
SequencedTaskChecker sequenced_task_checker;
sequenced_task_checker.Detach();
TaskQueueForTest queue1;
queue1.SendTask(
[&] { EXPECT_TRUE(sequenced_task_checker.CalledSequentially()); });
// CalledSequentially should return false in debug builds after moving to
// another task queue.
TaskQueueForTest queue2;
queue2.SendTask([&] {
EXPECT_EQ(sequenced_task_checker.CalledSequentially(), !RTC_DCHECK_IS_ON);
});
}
class TestAnnotations {
public:
TestAnnotations() : test_var_(false) {}
void ModifyTestVar() {
RTC_DCHECK_CALLED_SEQUENTIALLY(&checker_);
test_var_ = true;
}
private:
bool test_var_ RTC_GUARDED_BY(&checker_);
SequencedTaskChecker checker_;
};
TEST(SequencedTaskCheckerTest, TestAnnotations) {
TestAnnotations annotations;
annotations.ModifyTestVar();
}
#if GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
void TestAnnotationsOnWrongQueue() {
TestAnnotations annotations;
TaskQueueForTest queue;
queue.SendTask([&] { annotations.ModifyTestVar(); });
}
#if RTC_DCHECK_IS_ON
TEST(SequencedTaskCheckerTest, TestAnnotationsOnWrongQueueDebug) {
ASSERT_DEATH({ TestAnnotationsOnWrongQueue(); }, "");
}
#else
TEST(SequencedTaskCheckerTest, TestAnnotationsOnWrongQueueRelease) {
TestAnnotationsOnWrongQueue();
}
#endif
#endif // GTEST_HAS_DEATH_TEST
} // namespace rtc
| 28.781609 | 78 | 0.764776 | [
"object"
] |
74da78fff66cb40d379454c79f49a9a785fce164 | 1,923 | cpp | C++ | misc/set-of-intervals.cpp | hsnavarro/icpc-notebook | 5e501ecdd56a2a719d2a3a5e99e09d926d7231a3 | [
"MIT"
] | null | null | null | misc/set-of-intervals.cpp | hsnavarro/icpc-notebook | 5e501ecdd56a2a719d2a3a5e99e09d926d7231a3 | [
"MIT"
] | null | null | null | misc/set-of-intervals.cpp | hsnavarro/icpc-notebook | 5e501ecdd56a2a719d2a3a5e99e09d926d7231a3 | [
"MIT"
] | null | null | null | // Set of Intervals
// Use when you have disjoint intervals
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
#define pb push_back
#define st first
#define nd second
typedef pair<int, int> pii;
typedef pair<pii, int> piii;
int n, m, x, t;
set<piii> s;
set<pii> mosq;
vector<piii> frogs;
int c[N], len[N], p, b[N];
void in(int l, int r, int i) {
vector<piii> add, rem;
auto it = s.lower_bound({{l, 0}, 0});
if(it != s.begin()) it--;
for(; it != s.end(); it++) {
int ll = it->st.st;
int rr = it->st.nd;
int idx = it->nd;
if(ll > r) break;
if(rr < l) continue;
if(ll < l) add.pb({{ll, l-1}, idx});
if(rr > r) add.pb({{r+1, rr}, idx});
rem.pb(*it);
}
add.pb({{l, r}, i});
for(auto x : rem) s.erase(x);
for(auto x : add) s.insert(x);
}
void process(int l, int idx) {
auto it2 = s.lower_bound({{l, 0}, 0});
if(it2 != s.begin()) it2--;
if(it2 != s.end() and it2->st.nd < l) it2++;
mosq.insert({l, idx});
if(it2 == s.end() or !(it2->nd)) return;
vector<pii> rem;
int ll = it2->st.st, rr = it2->st.nd, id = it2->nd;
auto it = mosq.lower_bound({ll, 0});
for(; it != mosq.end(); it++) {
if(it->st > rr) break;
c[id]++;
len[id] += b[it->nd];
rr += b[it->nd];
rem.pb(*it);
}
for(auto x : rem) mosq.erase(x);
in(ll, rr, id);
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++) {
cin >> x >> t;
len[i] = t;
frogs.push_back({{x, x+t}, i});
}
s.insert({{0, int(1e9)}, 0});
sort(frogs.begin(), frogs.end());
for(int i = frogs.size() - 1; i >= 0; i--)
in(frogs[i].st.st, frogs[i].st.nd, frogs[i].nd);
for(int i = 1; i <= m; i++) {
cin >> p >> b[i];
process(p, i);
}
for(int i = 1; i <= n; i++) cout << c[i] << " " << len[i] << "\n";
}
| 22.623529 | 69 | 0.482059 | [
"vector"
] |
74dbefa3821dba0ab6ca549b30ede01379577798 | 2,248 | hpp | C++ | include/filesystem/serialisation/vector_serialization.hpp | FrancoisSestier/filesystem | ffea5fdeeb788718e6822c3374cfd450208fd193 | [
"Unlicense"
] | null | null | null | include/filesystem/serialisation/vector_serialization.hpp | FrancoisSestier/filesystem | ffea5fdeeb788718e6822c3374cfd450208fd193 | [
"Unlicense"
] | null | null | null | include/filesystem/serialisation/vector_serialization.hpp | FrancoisSestier/filesystem | ffea5fdeeb788718e6822c3374cfd450208fd193 | [
"Unlicense"
] | null | null | null | #pragma once
#include <filesystem/serialisation/trivially_copyable.hpp>
#include <filesystem/serializable.hpp>
#include <fstream>
#include <vector>
#include <type_traits>
namespace fs {
namespace details {
template <typename T, typename A>
inline void write_size(std::ostream& os, std::vector<T, A>& obj) {
size_t size = obj.size();
os.write(reinterpret_cast<char*>(&size), sizeof(size_t));
}
template <typename T, typename A>
inline void read_size(std::istream& is, std::vector<T, A>& obj) {
size_t size = 0;
is.read(reinterpret_cast<char*>(&size), sizeof(size_t));
obj.resize(size);
}
template <typename T, typename A>
inline size_t size_of_vector(const std::vector<T, A>& obj) {
return obj.size() * sizeof(T);
}
} // namespace details
template <trivially_copyable T, typename A>
inline std::ostream& operator<<(std::ostream& os, std::vector<T, A>& obj) {
details::write_size(os, obj);
os.write(reinterpret_cast<char*>(obj.data()), details::size_of_vector(obj));
return os;
};
template <serializable T, typename A, typename = std::enable_if_t<!std::is_trivially_copyable_v<T>>>
inline std::ostream& operator<<(std::ostream& os, std::vector<T, A>& obj) {
details::write_size(os, obj);
for (size_t i = 0; i < obj.size(); i++) {
os << obj[i];
}
return os;
};
template <trivially_copyable T, typename A>
inline std::istream& operator>>(std::istream& is, std::vector<T, A>& obj) {
details::read_size(is, obj);
if (obj.size() != 0) {
is.read(reinterpret_cast<char*>(obj.data()), details::size_of_vector(obj));
}
return is;
};
template <serializable T, typename A, typename = std::enable_if_t<!std::is_trivially_copyable_v<T>>>
inline std::istream& operator>>(std::istream& is, std::vector<T, A>& obj) {
details::read_size(is, obj);
if (obj.size() != 0) {
for (size_t i = 0; i < obj.size(); i++) {
is >> obj[i];
}
}
return is;
};
} // namespace fs
| 31.661972 | 104 | 0.572509 | [
"vector"
] |
74e06d47760364dc35274de54a6d7fc45cb651d8 | 1,146 | cpp | C++ | SistemaDeGerenciamentoDeFolha/Gerenciamento.cpp | cans10/Roteiro8 | 826663d50985adad2b0064725c8d14178e27255d | [
"MIT"
] | null | null | null | SistemaDeGerenciamentoDeFolha/Gerenciamento.cpp | cans10/Roteiro8 | 826663d50985adad2b0064725c8d14178e27255d | [
"MIT"
] | null | null | null | SistemaDeGerenciamentoDeFolha/Gerenciamento.cpp | cans10/Roteiro8 | 826663d50985adad2b0064725c8d14178e27255d | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include "Gerenciamento.h"
Gerenciamento::Gerenciamento(double o): orcamento(o){}
void Gerenciamento::setFuncionarios(vector<Funcionario*> &func){
funcionario = func;
}
double Gerenciamento::calcularTotalDaFolha(){
double totalFolha = 0;
for(int i = 0; i < funcionario.size(); i++){
totalFolha += funcionario[i]->calcularSalario();
}
if(totalFolha > orcamento){
cout << "A folha de pagamento ultrapassou o limite do orcamento semanal." << endl;
}
return totalFolha;
}
double Gerenciamento::consultaSalarioDeFuncionario(int matricula){
for(int i = 0; i < funcionario.size(); i++){
if(matricula == funcionario[i]->getMatricula()){
return funcionario[i]->calcularSalario();
}
}
}
int Gerenciamento::consultaNomeDeFuncionario(string nome){
int retorno = 0;
for(int i = 0; i < funcionario.size(); i++){
retorno = funcionario[i]->getNome() == nome;
if(retorno == 1){
break;
}
}
return retorno;
}
double Gerenciamento::getOrcamento(){
return orcamento;
}
| 23.875 | 90 | 0.638743 | [
"vector"
] |
d55d6ad46c7205e56ae7d589907c71337aeb6fab | 5,002 | cc | C++ | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_ios/cons/char/3.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_ios/cons/char/3.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_ios/cons/char/3.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // 2001-06-05 Benjamin Kosnik <bkoz@redhat.com>
// Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction. Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License. This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
// 27.4.2.1.6 class ios_base::init
#include <sstream>
#include <testsuite_hooks.h>
// char_traits specialization
namespace std
{
template<>
struct char_traits<unsigned short>
{
typedef unsigned short char_type;
// Unsigned as wint_t in unsigned.
typedef unsigned long int_type;
typedef streampos pos_type;
typedef streamoff off_type;
typedef mbstate_t state_type;
static void
assign(char_type& __c1, const char_type& __c2)
{ __c1 = __c2; }
static bool
eq(const char_type& __c1, const char_type& __c2)
{ return __c1 == __c2; }
static bool
lt(const char_type& __c1, const char_type& __c2)
{ return __c1 < __c2; }
static int
compare(const char_type* __s1, const char_type* __s2, size_t __n)
{
for (size_t __i = 0; __i < __n; ++__i)
if (!eq(__s1[__i], __s2[__i]))
return lt(__s1[__i], __s2[__i]) ? -1 : 1;
return 0;
}
static size_t
length(const char_type* __s)
{
const char_type* __p = __s;
while (__p)
++__p;
return (__p - __s);
}
static const char_type*
find(const char_type* __s, size_t __n, const char_type& __a)
{
for (const char_type* __p = __s; size_t(__p - __s) < __n; ++__p)
if (*__p == __a) return __p;
return 0;
}
static char_type*
move(char_type* __s1, const char_type* __s2, size_t __n)
{ return (char_type*) memmove(__s1, __s2, __n * sizeof(char_type)); }
static char_type*
copy(char_type* __s1, const char_type* __s2, size_t __n)
{ return (char_type*) memcpy(__s1, __s2, __n * sizeof(char_type)); }
static char_type*
assign(char_type* __s, size_t __n, char_type __a)
{
for (char_type* __p = __s; __p < __s + __n; ++__p)
assign(*__p, __a);
return __s;
}
static char_type
to_char_type(const int_type&)
{ return char_type(); }
static int_type
to_int_type(const char_type&) { return int_type(); }
static bool
eq_int_type(const int_type& __c1, const int_type& __c2)
{ return __c1 == __c2; }
static int_type
eof() { return static_cast<int_type>(-1); }
static int_type
not_eof(const int_type& __c)
{ return eq_int_type(__c, eof()) ? int_type(0) : __c; }
};
} // namespace std
// Non-required instantiations don't have the required facets inbued,
// by default, into the locale object.
// See 27.4.4.1
void test02()
{
bool test __attribute__((unused)) = true;
// 02: Calls basic_ios::init, which may call ctype<char_type>...
try
{
std::basic_string<unsigned short> str;
std::basic_ostringstream<unsigned short> oss(str);
// Try each member functions for unformatted io.
// put
oss.put(324);
// write
const unsigned short us[4] = {1246, 433, 520, 0};
oss.write(us, 4);
// flush
oss.flush();
}
catch(const std::bad_cast& obj)
{
// Should be able to do the above without calling fill() and
// forcing a call to widen...
test = false;
}
catch(...)
{
test = false;
}
VERIFY( test );
}
#if !__GXX_WEAK__
// Explicitly instantiate for systems with no COMDAT or weak support.
template
std::basic_string<unsigned short>::size_type
std::basic_string<unsigned short>::_Rep::_S_max_size;
template
unsigned short
std::basic_string<unsigned short>::_Rep::_S_terminal;
#endif
int main()
{
test02();
return 0;
}
| 28.420455 | 79 | 0.651739 | [
"object"
] |
d55da67d348a3b3ee28356017e1a58346cc891d4 | 6,618 | cpp | C++ | tests/capi/cell.cpp | jmintser/chemfiles | fb1ed5ee47790cc004468e5484954e2b3d1adff2 | [
"BSD-3-Clause"
] | null | null | null | tests/capi/cell.cpp | jmintser/chemfiles | fb1ed5ee47790cc004468e5484954e2b3d1adff2 | [
"BSD-3-Clause"
] | null | null | null | tests/capi/cell.cpp | jmintser/chemfiles | fb1ed5ee47790cc004468e5484954e2b3d1adff2 | [
"BSD-3-Clause"
] | 1 | 2021-07-19T11:12:52.000Z | 2021-07-19T11:12:52.000Z | // Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include "catch.hpp"
#include "helpers.hpp"
#include "chemfiles.h"
#include <cmath>
static bool approx_eq(double A[3][3], double B[3][3]) {
double eps = 1e-10;
return
(fabs(A[0][0] - B[0][0]) < eps) && (fabs(A[0][1] - B[0][1]) < eps) && (fabs(A[0][2] - B[0][2]) < eps) &&
(fabs(A[1][0] - B[1][0]) < eps) && (fabs(A[1][1] - B[1][1]) < eps) && (fabs(A[1][2] - B[1][2]) < eps) &&
(fabs(A[2][0] - B[2][0]) < eps) && (fabs(A[2][1] - B[2][1]) < eps) && (fabs(A[2][2] - B[2][2]) < eps);
}
TEST_CASE("chfl_cell") {
SECTION("Constructors") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_vector3d data = {0};
CHECK_STATUS(chfl_cell_lengths(cell, data));
CHECK(data[0] == 2);
CHECK(data[1] == 3);
CHECK(data[2] == 4);
CHECK_STATUS(chfl_cell_angles(cell, data));
CHECK(data[0] == 90);
CHECK(data[1] == 90);
CHECK(data[2] == 90);
chfl_free(cell);
lengths[0] = 20; lengths[1] = 21; lengths[2] = 22;
chfl_vector3d angles = {90, 100, 120};
cell = chfl_cell_triclinic(lengths, angles);
REQUIRE(cell);
CHECK_STATUS(chfl_cell_lengths(cell, data));
CHECK(data[0] == 20);
CHECK(data[1] == 21);
CHECK(data[2] == 22);
CHECK_STATUS(chfl_cell_angles(cell, data));
CHECK(data[0] == 90);
CHECK(data[1] == 100);
CHECK(data[2] == 120);
chfl_free(cell);
// Check that a call to chfl_cell_triclinic always gives a triclinic
// cell, even with all angles equal to 90°
angles[0] = 90; angles[1] = 90; angles[2] = 90;
cell = chfl_cell_triclinic(lengths, angles);
REQUIRE(cell);
chfl_cellshape shape;
CHECK_STATUS(chfl_cell_shape(cell, &shape));
CHECK(shape == CHFL_CELL_TRICLINIC);
chfl_free(cell);
}
SECTION("Constructors errors") {
chfl_vector3d dummy = {0, 0, 0};
fail_next_allocation();
CHECK(chfl_cell(dummy) == nullptr);
fail_next_allocation();
CHECK(chfl_cell_triclinic(dummy, dummy) == nullptr);
CHFL_CELL* cell = chfl_cell(dummy);
REQUIRE(cell);
fail_next_allocation();
CHECK(chfl_cell_copy(cell) == nullptr);
CHFL_FRAME* frame = chfl_frame();
REQUIRE(frame);
fail_next_allocation();
CHECK(chfl_cell_from_frame(frame) == nullptr);
chfl_free(cell);
chfl_free(frame);
}
SECTION("copy") {
chfl_vector3d lengths = {2, 2, 2};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
CHFL_CELL* copy = chfl_cell_copy(cell);
REQUIRE(copy);
double volume = 0;
CHECK_STATUS(chfl_cell_volume(cell, &volume));
CHECK(volume == 8);
CHECK_STATUS(chfl_cell_volume(copy, &volume));
CHECK(volume == 8);
chfl_vector3d new_lengths = {3, 3, 3};
CHECK_STATUS(chfl_cell_set_lengths(cell, new_lengths));
CHECK_STATUS(chfl_cell_volume(cell, &volume));
CHECK(volume == 27);
CHECK_STATUS(chfl_cell_volume(copy, &volume));
CHECK(volume == 8);
chfl_free(copy);
chfl_free(cell);
}
SECTION("Length") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_vector3d data = {0};
CHECK_STATUS(chfl_cell_lengths(cell, data));
CHECK(data[0] == 2);
CHECK(data[1] == 3);
CHECK(data[2] == 4);
lengths[0] = 10; lengths[1] = 20; lengths[2] = 30;
CHECK_STATUS(chfl_cell_set_lengths(cell, lengths));
CHECK_STATUS(chfl_cell_lengths(cell, data));
CHECK(data[0] == 10);
CHECK(data[1] == 20);
CHECK(data[2] == 30);
chfl_free(cell);
}
SECTION("Angles") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_vector3d data = {0};
CHECK_STATUS(chfl_cell_angles(cell, data));
CHECK(data[0] == 90);
CHECK(data[1] == 90);
CHECK(data[2] == 90);
chfl_vector3d angles = {80, 89, 100};
// Setting an orthorhombic cell angles is an error
CHECK(chfl_cell_set_angles(cell, angles) != CHFL_SUCCESS);
CHECK_STATUS(chfl_cell_set_shape(cell, CHFL_CELL_TRICLINIC));
CHECK_STATUS(chfl_cell_set_angles(cell, angles));
CHECK_STATUS(chfl_cell_angles(cell, data));
CHECK(data[0] == 80);
CHECK(data[1] == 89);
CHECK(data[2] == 100);
chfl_free(cell);
}
SECTION("Volume") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
double volume = 0;
CHECK_STATUS(chfl_cell_volume(cell, &volume));
CHECK(volume == 2 * 3 * 4);
chfl_free(cell);
}
SECTION("Matrix") {
chfl_vector3d lengths = {10, 20, 30};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_vector3d expected[3] = {{10, 0, 0}, {0, 20, 0}, {0, 0, 30}};
chfl_vector3d matrix[3];
CHECK_STATUS(chfl_cell_matrix(cell, matrix));
CHECK(approx_eq(expected, matrix));
chfl_free(cell);
}
SECTION("Shape") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_cellshape shape;
CHECK_STATUS(chfl_cell_shape(cell, &shape));
CHECK(shape == CHFL_CELL_ORTHORHOMBIC);
CHECK_STATUS(chfl_cell_set_shape(cell, CHFL_CELL_TRICLINIC));
CHECK_STATUS(chfl_cell_shape(cell, &shape));
CHECK(shape == CHFL_CELL_TRICLINIC);
lengths[0] = 0; lengths[1] = 0; lengths[2] = 0;
CHECK_STATUS(chfl_cell_set_lengths(cell, lengths));
CHECK_STATUS(chfl_cell_set_shape(cell, CHFL_CELL_INFINITE));
CHECK_STATUS(chfl_cell_shape(cell, &shape));
CHECK(shape == CHFL_CELL_INFINITE);
chfl_free(cell);
}
SECTION("Wrap") {
chfl_vector3d lengths = {2, 3, 4};
CHFL_CELL* cell = chfl_cell(lengths);
REQUIRE(cell);
chfl_vector3d vector = {0.8, 1.7, -6};
CHECK_STATUS(chfl_cell_wrap(cell, vector));
CHECK(vector[0] == 0.8);
CHECK(vector[1] == -1.3);
CHECK(vector[2] == 2);
chfl_free(cell);
}
}
| 29.283186 | 112 | 0.566183 | [
"shape",
"vector"
] |
d566b07a485b4daae2a3d7b65534be3ead57c86d | 307 | hpp | C++ | wrappers/ois/code/custom_to_from_ruby.hpp | cajun-code/ogrerb | 7b0ad79b5fa019fd033406149e3153e09c7c9222 | [
"MIT"
] | 1 | 2015-11-05T05:09:21.000Z | 2015-11-05T05:09:21.000Z | wrappers/ois/code/custom_to_from_ruby.hpp | cajun-code/ogrerb | 7b0ad79b5fa019fd033406149e3153e09c7c9222 | [
"MIT"
] | null | null | null | wrappers/ois/code/custom_to_from_ruby.hpp | cajun-code/ogrerb | 7b0ad79b5fa019fd033406149e3153e09c7c9222 | [
"MIT"
] | null | null | null | #ifndef __CUSTOM_TO_RUBY_H__
#define __CUSTOM_TO_RUBY_H__
#include <rice/Object.hpp>
#include <rice/Hash.hpp>
#include <rice/to_from_ruby.hpp>
#include "OIS.h"
template<>
Rice::Object to_ruby<short int>(short int const & a);
template<>
OIS::ParamList& from_ruby<OIS::ParamList&>(Rice::Object x);
#endif
| 19.1875 | 59 | 0.752443 | [
"object"
] |
d5697cfd68fd83563189dfcd465a4bd2b9a54805 | 23,640 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/CLauncherAppsImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/CLauncherAppsImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/CLauncherAppsImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/server/pm/CLauncherAppsImpl.h"
#include "Elastos.Droid.Net.h"
#include "Elastos.Droid.Provider.h"
#include "elastos/droid/os/Binder.h"
#include "elastos/droid/os/UserHandle.h"
#include "elastos/droid/app/AppGlobals.h"
#include <elastos/utility/logging/Logger.h>
#include <elastos/core/AutoLock.h>
using Elastos::Core::AutoLock;
using Elastos::Droid::App::AppGlobals;
using Elastos::Droid::Content::CIntent;
using Elastos::Droid::Content::Pm::IPackageInfo;
using Elastos::Droid::Content::Pm::IIPackageManager;
using Elastos::Droid::Content::Pm::IApplicationInfo;
using Elastos::Droid::Content::Pm::IActivityInfo;
using Elastos::Droid::Content::Pm::IUserInfo;
using Elastos::Droid::Content::Pm::EIID_IILauncherApps;
using Elastos::Droid::Content::Pm::IPackageItemInfo;
using Elastos::Droid::Content::Pm::IComponentInfo;
using Elastos::Droid::Net::IUriHelper;
using Elastos::Droid::Net::CUriHelper;
using Elastos::Droid::Net::IUri;
using Elastos::Droid::Os::Binder;
using Elastos::Droid::Os::UserHandle;
using Elastos::Droid::Os::CUserHandle;
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Droid::Provider::ISettings;
using Elastos::Utility::Logging::Logger;
using Elastos::Utility::IArrayList;
using Elastos::Utility::CArrayList;
using Elastos::Utility::IIterator;
namespace Elastos {
namespace Droid {
namespace Server {
namespace Pm {
//==============================================================================
// CLauncherAppsImpl::MyPackageMonitor
//==============================================================================
Boolean CLauncherAppsImpl::MyPackageMonitor::IsEnabledProfileOf(
/* [in] */ IUserHandle* user,
/* [in] */ IUserHandle* listeningUser,
/* [in] */ const String& debugMsg)
{
Int32 id, lisId;
user->GetIdentifier(&id);
listeningUser->GetIdentifier(&lisId);
if (id == lisId) {
if (DEBUG) Logger::D(TAG, "Delivering msg to same user %s", debugMsg.string());
return TRUE;
}
Int64 ident = Binder::ClearCallingIdentity();
// try {
AutoPtr<IUserInfo> userInfo, listeningUserInfo;
if (FAILED(mHost->mUm->GetUserInfo(id, (IUserInfo**)&userInfo))) {
Binder::RestoreCallingIdentity(ident);
return FALSE;
}
if (FAILED(mHost->mUm->GetUserInfo(lisId, (IUserInfo**)&listeningUserInfo))) {
Binder::RestoreCallingIdentity(ident);
return FALSE;
}
Int32 groupId, lisGroupId;
Boolean isEnabled;
if (userInfo == NULL || listeningUserInfo == NULL
|| (userInfo->GetProfileGroupId(&groupId), groupId == IUserInfo::NO_PROFILE_GROUP_ID)
|| (listeningUserInfo->GetProfileGroupId(&lisGroupId), groupId != lisGroupId)
|| (userInfo->IsEnabled(&isEnabled), !isEnabled)) {
if (DEBUG) {
Logger::D(TAG, "Not delivering msg from %p to %p:%s", user, listeningUser, debugMsg.string());
}
Binder::RestoreCallingIdentity(ident);
return FALSE;
}
else {
if (DEBUG) {
Logger::D(TAG, "Delivering msg from %p to %p:%s", user, listeningUser, debugMsg.string());
}
Binder::RestoreCallingIdentity(ident);
return TRUE;
}
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::MyPackageMonitor::OnPackageAdded(
/* [in] */ const String& packageName,
/* [in] */ Int32 uid)
{
Int32 id;
GetChangingUserId(&id);
AutoPtr<IUserHandle> user;
CUserHandle::New(id, (IUserHandle**)&user);
Int32 n;
mHost->mListeners->BeginBroadcast(&n);
for (Int32 i = 0; i < n; i++) {
AutoPtr<IInterface> item;
mHost->mListeners->GetBroadcastItem(i, (IInterface**)&item);
AutoPtr<IOnAppsChangedListener> listener = IOnAppsChangedListener::Probe(item);
AutoPtr<IInterface> cookie;
mHost->mListeners->GetBroadcastCookie(i, (IInterface**)&cookie);
AutoPtr<IUserHandle> listeningUser = IUserHandle::Probe(cookie);
if (!IsEnabledProfileOf(user, listeningUser, String("onPackageAdded"))) continue;
// try {
if (FAILED(listener->OnPackageAdded(user, packageName))) {
Logger::D(TAG, "Callback failed ");
}
// } catch (RemoteException re) {
// Slog.d(TAG, "Callback failed ", re);
// }
}
mHost->mListeners->FinishBroadcast();
return PackageMonitor::OnPackageAdded(packageName, uid);
}
ECode CLauncherAppsImpl::MyPackageMonitor::OnPackageRemoved(
/* [in] */ const String& packageName,
/* [in] */ Int32 uid)
{
Int32 id;
GetChangingUserId(&id);
AutoPtr<IUserHandle> user;
CUserHandle::New(id, (IUserHandle**)&user);
Int32 n;
mHost->mListeners->BeginBroadcast(&n);
for (Int32 i = 0; i < n; i++) {
AutoPtr<IInterface> item;
mHost->mListeners->GetBroadcastItem(i, (IInterface**)&item);
AutoPtr<IOnAppsChangedListener> listener = IOnAppsChangedListener::Probe(item);
AutoPtr<IInterface> cookie;
mHost->mListeners->GetBroadcastCookie(i, (IInterface**)&cookie);
AutoPtr<IUserHandle> listeningUser = IUserHandle::Probe(cookie);
if (!IsEnabledProfileOf(user, listeningUser, String("onPackageRemoved"))) continue;
// try {
if (FAILED(listener->OnPackageRemoved(user, packageName))) {
Logger::D(TAG, "Callback failed ");
}
// } catch (RemoteException re) {
// Slog.d(TAG, "Callback failed ", re);
// }
}
mHost->mListeners->FinishBroadcast();
return PackageMonitor::OnPackageRemoved(packageName, uid);
}
ECode CLauncherAppsImpl::MyPackageMonitor::OnPackageModified(
/* [in] */ const String& packageName)
{
Int32 id;
GetChangingUserId(&id);
AutoPtr<IUserHandle> user;
CUserHandle::New(id, (IUserHandle**)&user);
Int32 n;
mHost->mListeners->BeginBroadcast(&n);
for (Int32 i = 0; i < n; i++) {
AutoPtr<IInterface> item;
mHost->mListeners->GetBroadcastItem(i, (IInterface**)&item);
AutoPtr<IOnAppsChangedListener> listener = IOnAppsChangedListener::Probe(item);
AutoPtr<IInterface> cookie;
mHost->mListeners->GetBroadcastCookie(i, (IInterface**)&cookie);
AutoPtr<IUserHandle> listeningUser = IUserHandle::Probe(cookie);
if (!IsEnabledProfileOf(user, listeningUser, String("onPackageModified"))) continue;
// try {
if (FAILED(listener->OnPackageChanged(user, packageName))) {
Logger::D(TAG, "Callback failed ");
}
// } catch (RemoteException re) {
// Slog.d(TAG, "Callback failed ", re);
// }
}
mHost->mListeners->FinishBroadcast();
return PackageMonitor::OnPackageModified(packageName);
}
ECode CLauncherAppsImpl::MyPackageMonitor::OnPackagesAvailable(
/* [in] */ ArrayOf<String>* packages)
{
Int32 id;
GetChangingUserId(&id);
AutoPtr<IUserHandle> user;
CUserHandle::New(id, (IUserHandle**)&user);
Int32 n;
mHost->mListeners->BeginBroadcast(&n);
for (Int32 i = 0; i < n; i++) {
AutoPtr<IInterface> item;
mHost->mListeners->GetBroadcastItem(i, (IInterface**)&item);
AutoPtr<IOnAppsChangedListener> listener = IOnAppsChangedListener::Probe(item);
AutoPtr<IInterface> cookie;
mHost->mListeners->GetBroadcastCookie(i, (IInterface**)&cookie);
AutoPtr<IUserHandle> listeningUser = IUserHandle::Probe(cookie);
if (!IsEnabledProfileOf(user, listeningUser, String("onPackagesAvailable"))) continue;
// try {
Boolean isReplacing;
IsReplacing(&isReplacing);
if (FAILED(listener->OnPackagesAvailable(user, packages, isReplacing))) {
Logger::D(TAG, "Callback failed ");
}
// } catch (RemoteException re) {
// Slog.d(TAG, "Callback failed ", re);
// }
}
mHost->mListeners->FinishBroadcast();
return PackageMonitor::OnPackagesAvailable(packages);
}
ECode CLauncherAppsImpl::MyPackageMonitor::OnPackagesUnavailable(
/* [in] */ ArrayOf<String>* packages)
{
Int32 id;
GetChangingUserId(&id);
AutoPtr<IUserHandle> user;
CUserHandle::New(id, (IUserHandle**)&user);
Int32 n;
mHost->mListeners->BeginBroadcast(&n);
for (Int32 i = 0; i < n; i++) {
AutoPtr<IInterface> item;
mHost->mListeners->GetBroadcastItem(i, (IInterface**)&item);
AutoPtr<IOnAppsChangedListener> listener = IOnAppsChangedListener::Probe(item);
AutoPtr<IInterface> cookie;
mHost->mListeners->GetBroadcastCookie(i, (IInterface**)&cookie);
AutoPtr<IUserHandle> listeningUser = IUserHandle::Probe(cookie);
if (!IsEnabledProfileOf(user, listeningUser, String("onPackagesUnavailable"))) continue;
// try {
Boolean isReplacing;
IsReplacing(&isReplacing);
if (FAILED(listener->OnPackagesUnavailable(user, packages, isReplacing))) {
Logger::D(TAG, "Callback failed ");
}
// } catch (RemoteException re) {
// Slog.d(TAG, "Callback failed ", re);
// }
}
mHost->mListeners->FinishBroadcast();
return PackageMonitor::OnPackagesUnavailable(packages);
}
//==============================================================================
// CLauncherAppsImpl::PackageCallbackList
//==============================================================================
ECode CLauncherAppsImpl::PackageCallbackList::OnCallbackDied(
/* [in] */ IInterface* callback,
/* [in] */ IInterface* cookie)
{
mHost->CheckCallbackCount();
return NOERROR;
}
//==============================================================================
// CLauncherAppsImpl
//==============================================================================
const Boolean CLauncherAppsImpl::DEBUG;
const String CLauncherAppsImpl::TAG("CLauncherAppsImpl");
CLauncherAppsImpl::CLauncherAppsImpl()
{
mListeners = new PackageCallbackList(this);
mPackageMonitor = new MyPackageMonitor(this);
}
CAR_INTERFACE_IMPL_2(CLauncherAppsImpl, Object, IILauncherApps, IBinder)
CAR_OBJECT_IMPL(CLauncherAppsImpl)
ECode CLauncherAppsImpl::constructor(
/* [in] */ IContext* ctx)
{
mContext = ctx;
mContext->GetPackageManager((IPackageManager**)&mPm);
AutoPtr<IInterface> service;
mContext->GetSystemService(IContext::USER_SERVICE, (IInterface**)&service);
mUm = IUserManager::Probe(service);
return NOERROR;
}
ECode CLauncherAppsImpl::AddOnAppsChangedListener(
/* [in] */ IOnAppsChangedListener* listener)
{
{ AutoLock syncLock(mListenersLock);
if (DEBUG) {
Logger::D(TAG, "Adding listener from %p", Binder::GetCallingUserHandle().Get());
}
Int32 count;
if (mListeners->GetRegisteredCallbackCount(&count), count == 0) {
if (DEBUG) {
Logger::D(TAG, "Starting package monitoring");
}
StartWatchingPackageBroadcasts();
}
Boolean result;
FAIL_RETURN(mListeners->Unregister(listener, &result))
AutoPtr<IUserHandle> handle = Binder::GetCallingUserHandle();
FAIL_RETURN(mListeners->Register(listener, handle, &result))
}
return NOERROR;
}
ECode CLauncherAppsImpl::RemoveOnAppsChangedListener(
/* [in] */ IOnAppsChangedListener* listener)
{
{ AutoLock syncLock(mListenersLock);
if (DEBUG) {
Logger::D(TAG, "Removing listener from %p", Binder::GetCallingUserHandle().Get());
}
Boolean result;
FAIL_RETURN(mListeners->Unregister(listener, &result))
Int32 count;
if (mListeners->GetRegisteredCallbackCount(&count), count == 0) {
StopWatchingPackageBroadcasts();
}
}
return NOERROR;
}
void CLauncherAppsImpl::StartWatchingPackageBroadcasts()
{
mPackageMonitor->Register(mContext, NULL, UserHandle::ALL, TRUE);
}
void CLauncherAppsImpl::StopWatchingPackageBroadcasts()
{
if (DEBUG) {
Logger::D(TAG, "Stopped watching for packages");
}
mPackageMonitor->Unregister();
}
void CLauncherAppsImpl::CheckCallbackCount()
{
{ AutoLock syncLock(mListenersLock);
Int32 count;
mListeners->GetRegisteredCallbackCount(&count);
if (DEBUG) {
Logger::D(TAG, "Callback count = %d", count);
}
if (count == 0) {
StopWatchingPackageBroadcasts();
}
}
}
ECode CLauncherAppsImpl::EnsureInUserProfiles(
/* [in] */ IUserHandle* userToCheck,
/* [in] */ const String& message)
{
Int32 callingUserId = UserHandle::GetCallingUserId();
Int32 targetUserId;
userToCheck->GetIdentifier(&targetUserId);
if (targetUserId == callingUserId) return NOERROR;
Int64 ident = Binder::ClearCallingIdentity();
// try {
AutoPtr<IUserInfo> callingUserInfo;
mUm->GetUserInfo(callingUserId, (IUserInfo**)&callingUserInfo);
AutoPtr<IUserInfo> targetUserInfo;
mUm->GetUserInfo(targetUserId, (IUserInfo**)&targetUserInfo);
Int32 targetId, callingId;
if (targetUserInfo == NULL
|| (targetUserInfo->GetProfileGroupId(&targetId), targetId == IUserInfo::NO_PROFILE_GROUP_ID)
|| (callingUserInfo->GetProfileGroupId(&callingId), targetId != callingId)) {
Binder::RestoreCallingIdentity(ident);
return E_SECURITY_EXCEPTION;
}
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
Binder::RestoreCallingIdentity(ident);
return NOERROR;
}
Boolean CLauncherAppsImpl::IsUserEnabled(
/* [in] */ IUserHandle* user)
{
Int64 ident = Binder::ClearCallingIdentity();
// try {
Int32 id;
user->GetIdentifier(&id);
AutoPtr<IUserInfo> targetUserInfo;
mUm->GetUserInfo(id, (IUserInfo**)&targetUserInfo);
Binder::RestoreCallingIdentity(ident);
Boolean isEnabled;
return targetUserInfo != NULL && (targetUserInfo->IsEnabled(&isEnabled), isEnabled);
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::GetLauncherActivities(
/* [in] */ const String& packageName,
/* [in] */ IUserHandle* user,
/* [out] */ IList** list)
{
VALIDATE_NOT_NULL(list)
*list = NULL;
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot retrieve activities for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
return CArrayList::New(list);
}
AutoPtr<IIntent> mainIntent;
CIntent::New(IIntent::ACTION_MAIN, NULL, (IIntent**)&mainIntent);
mainIntent->AddCategory(IIntent::CATEGORY_LAUNCHER);
mainIntent->SetPackage(packageName);
Int64 ident = Binder::ClearCallingIdentity();
// try {
Int32 id;
user->GetIdentifier(&id);
ECode ec = mPm->QueryIntentActivitiesAsUser(mainIntent, 0 /* flags */, id, list);
Binder::RestoreCallingIdentity(ident);
return ec;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::ResolveActivity(
/* [in] */ IIntent* intent,
/* [in] */ IUserHandle* user,
/* [out] */ IResolveInfo** info)
{
VALIDATE_NOT_NULL(info)
*info = NULL;
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot resolve activity for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
return NOERROR;
}
Int64 ident = Binder::ClearCallingIdentity();
// try {
Int32 id;
user->GetIdentifier(&id);
ECode ec = mPm->ResolveActivityAsUser(intent, 0, id, info);
Binder::RestoreCallingIdentity(ident);
return ec;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::IsPackageEnabled(
/* [in] */ const String& packageName,
/* [in] */ IUserHandle* user,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
*result = FALSE;
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot check package for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
return NOERROR;
}
Int64 ident = Binder::ClearCallingIdentity();
// try {
AutoPtr<IIPackageManager> pm = AppGlobals::GetPackageManager();
Int32 id;
user->GetIdentifier(&id);
AutoPtr<IPackageInfo> info;
ECode ec = pm->GetPackageInfo(packageName, 0, id, (IPackageInfo**)&info);
if (FAILED(ec)) {
Binder::RestoreCallingIdentity(ident);
return ec;
}
if (info != NULL) {
AutoPtr<IApplicationInfo> ai;
info->GetApplicationInfo((IApplicationInfo**)&ai);
ai->GetEnabled(result);
}
Binder::RestoreCallingIdentity(ident);
return NOERROR;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::IsActivityEnabled(
/* [in] */ IComponentName* component,
/* [in] */ IUserHandle* user,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
*result = FALSE;
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot check component for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
return NOERROR;
}
Int64 ident = Binder::ClearCallingIdentity();
// try {
AutoPtr<IIPackageManager> pm = AppGlobals::GetPackageManager();
Int32 id;
user->GetIdentifier(&id);
AutoPtr<IActivityInfo> info;
ECode ec = pm->GetActivityInfo(component, 0, id, (IActivityInfo**)&info);
if (FAILED(ec)) {
Binder::RestoreCallingIdentity(ident);
return ec;
}
*result = info != NULL;
Binder::RestoreCallingIdentity(ident);
return NOERROR;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::StartActivityAsUser(
/* [in] */ IComponentName* component,
/* [in] */ IRect* sourceBounds,
/* [in] */ IBundle* opts,
/* [in] */ IUserHandle* user)
{
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot start activity for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
Logger::E(TAG, "Cannot start activity for disabled profile %s", str.string());
return E_ILLEGAL_STATE_EXCEPTION;
}
AutoPtr<IIntent> launchIntent;
CIntent::New(IIntent::ACTION_MAIN, (IIntent**)&launchIntent);
launchIntent->AddCategory(IIntent::CATEGORY_LAUNCHER);
launchIntent->SetSourceBounds(sourceBounds);
launchIntent->AddFlags(IIntent::FLAG_ACTIVITY_NEW_TASK);
String pkgName;
component->GetPackageName(&pkgName);
launchIntent->SetPackage(pkgName);
Int64 ident = Binder::ClearCallingIdentity();
// try {
AutoPtr<IIPackageManager> pm = AppGlobals::GetPackageManager();
Int32 id;
user->GetIdentifier(&id);
AutoPtr<IActivityInfo> info;
ECode ec = pm->GetActivityInfo(component, 0, id, (IActivityInfo**)&info);
if (FAILED(ec)) {
Binder::RestoreCallingIdentity(ident);
return ec;
}
Boolean exported;
if (IComponentInfo::Probe(info)->GetExported(&exported), !exported) {
Logger::E(TAG, "Cannot launch non-exported components %p", component);
Binder::RestoreCallingIdentity(ident);
return E_SECURITY_EXCEPTION;
}
// Check that the component actually has Intent.CATEGORY_LAUCNCHER
// as calling startActivityAsUser ignores the category and just
// resolves based on the component if present.
AutoPtr<IList> apps;
ec = mPm->QueryIntentActivitiesAsUser(launchIntent, 0 /* flags */, id, (IList**)&apps);
if (FAILED(ec)) {
Binder::RestoreCallingIdentity(ident);
return ec;
}
AutoPtr<IIterator> it;
apps->GetIterator((IIterator**)&it);
Boolean hasNext;
String aiPkgName, aiClsName, className;
component->GetClassName(&className);
while (it->HasNext(&hasNext), hasNext) {
AutoPtr<IInterface> value;
it->GetNext((IInterface**)&value);
AutoPtr<IResolveInfo> ri = IResolveInfo::Probe(value);
AutoPtr<IActivityInfo> activityInfo;
ri->GetActivityInfo((IActivityInfo**)&activityInfo);
IPackageItemInfo::Probe(activityInfo)->GetPackageName(&aiPkgName);
if (aiPkgName.Equals(pkgName)) {
IPackageItemInfo::Probe(activityInfo)->GetName(&aiClsName);
if (aiClsName.Equals(className)) {
// Found an activity with category launcher that matches
// this component so ok to launch.
launchIntent->SetComponent(component);
ec = mContext->StartActivityAsUser(launchIntent, opts, user);
Binder::RestoreCallingIdentity(ident);
if (FAILED(ec)) {
Logger::E(TAG, "Failed to launch activity [%s], ec=%08x.", TO_CSTR(component), ec);
}
return ec;
}
}
}
Logger::E(TAG, "Attempt to launch activity [%s] without category Intent.CATEGORY_LAUNCHER", TO_CSTR(component));
Binder::RestoreCallingIdentity(ident);
return E_SECURITY_EXCEPTION;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::ShowAppDetailsAsUser(
/* [in] */ IComponentName* component,
/* [in] */ IRect* sourceBounds,
/* [in] */ IBundle* opts,
/* [in] */ IUserHandle* user)
{
String str = Object::ToString(user);
FAIL_RETURN(EnsureInUserProfiles(user,
String("Cannot show app details for unrelated profile ") + str))
if (!IsUserEnabled(user)) {
Logger::E(TAG, "Cannot show app details for disabled profile %s", str.string());
}
Int64 ident = Binder::ClearCallingIdentity();
// try {
String packageName;
component->GetPackageName(&packageName);
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> uri;
helper->FromParts(String("package"), packageName, String(NULL), (IUri**)&uri);
AutoPtr<IIntent> intent;
CIntent::New(ISettings::ACTION_APPLICATION_DETAILS_SETTINGS, uri, (IIntent**)&intent);
intent->SetFlags(IIntent::FLAG_ACTIVITY_NEW_TASK | IIntent::FLAG_ACTIVITY_CLEAR_TASK |
IIntent::FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent->SetSourceBounds(sourceBounds);
Binder::RestoreCallingIdentity(ident);
ECode ec = mContext->StartActivityAsUser(intent, opts, user);
return ec;
// } finally {
// Binder.restoreCallingIdentity(ident);
// }
}
ECode CLauncherAppsImpl::ToString(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
return Object::ToString(str);
}
} // namespace Pm
} // namespace Server
} // namespace Droid
} // namespace Elastos
| 34.713656 | 116 | 0.636548 | [
"object"
] |
d56eee86d3390bf70776427f921943bb55c48783 | 5,958 | inl | C++ | 2007/utils/Atil/Inc/Image.inl | kevinzhwl/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 12 | 2015-10-05T07:11:57.000Z | 2021-11-20T10:22:38.000Z | 2007/utils/Atil/Inc/Image.inl | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | null | null | null | 2007/utils/Atil/Inc/Image.inl | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 14 | 2015-12-04T08:42:08.000Z | 2022-01-08T02:09:23.000Z | ///////////////////////////////////////////////////////////////////////////////
//
//
// (C) Copyright 2005-2006 by Autodesk, Inc. All rights reserved.
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef IMAGEREP_H
#include "ImageRep.h"
#endif
#ifndef SIZE_H
#include "Size.h"
#endif
#ifndef IMAGE_INL
#define IMAGE_INL
// As the Atil::Image class uses the "Letter/Envelope" or "Bridge" design pattern
// the "envelope" class is a very thin pass through to the implementation class.
// To facilitate performance by lowering the impact of the call indirection the
// forwarding calls are inlined by this header which is included by the parent header
// image.h.
//
namespace Atil
{
/// <summary
/// This method will return the Image's size.
/// </summary>
///
inline const Size& Image::size () const
{
return mImplementation->size();
}
/// <summary
/// This method will return the Image's tile size.
/// </summary>
///
inline Size Image::tileSize () const
{
return mImplementation->tileSize();
}
/// <summary
/// This method will return the Image's data model.
/// </summary>
///
inline const DataModel& Image::dataModel () const
{
return mImplementation->dataModel();
}
/// <summary
/// This method will return the Image's FileReadDescriptor.
/// </summary>
///
inline const FileReadDescriptor* Image::fileReadDescriptor () const
{
return mImplementation->fileReadDescriptor();
}
/// <summary
/// This method will return the number of tiles in the Image.
/// </summary>
///
inline int Image::numTiles (int& nRows, int& nColumns) const
{
return mImplementation->numTiles(nRows, nColumns);
}
/// <summary
/// This method will return the Image's clear color.
/// </summary>
///
inline const ImagePixel& Image::clearColor () const
{
return mImplementation->clearColor();
}
/// <summary
/// This method will set the Image's clear color.
/// </summary>
///
/// <remarks>
/// The clear color is the color that will be return for any pixel which is not
/// set with a value by the constructed image.
/// </remarks>
///
inline void Image::setClearColor (ImagePixel value)
{
mImplementation->setClearColor(value);
}
/// <summary
/// This method will set the Image's data model. Setting a data model onto an
/// existing image has restrictions.
/// </summary>
///
/// <exception cref="ATILException">An exception will be thrown if the data type of the
/// image is incompatible with the data model instance being set.
/// <see cref="ImageConstructionException"/>.
/// </exception>
///
inline void Image::setDataModel ( const DataModel& dataModel )
{
mImplementation->setDataModel( dataModel );
}
/// <summary>
/// This method is similar to <c>Image::paste</c> but differs in that
/// an alpha blend value for the source is specified.
/// </summary>
///
inline void Image::blend (RowProviderInterface* pPipe, const Offset& at,
int nAlphaValue, bool bRespectTransparency )
{
mImplementation->blend(pPipe, at, nAlphaValue, bRespectTransparency);
}
/// <summary>
/// The read method is the favor method for accessing pixels in an image.
/// Returning a <c>RowProviderInterface</c> instance it will supply rows of image
/// data. <see cref="RowProviderInterface"/>
/// </summary>
///
inline RowProviderInterface* Image::read (const Size& size, const Offset& offset) const
{
return mImplementation->read(size, offset);
}
//
inline RowProviderInterface* Image::read (const Size& size, const Offset& offset, Orientation orient) const
{
return mImplementation->read(size, offset, (int)orient);
}
/// <summary
/// This method will disable the Image's per tile locking. This can be a benefit to performance
/// but care must be taken if multiple threads will access the image.
/// </summary>
///
inline bool Image::disablePerTileLocking (bool bDisable)
{
return mImplementation->disablePerTileLocking(bDisable);
}
/// <summary
/// This method will cause all the pixels of an image to be set to the clear value.
/// <seealso cref"setClearColor"/>
/// </summary>
///
inline void Image::clear ()
{
mImplementation->clear();
}
//
/// <summary
/// This method will return true the contents of the Image are valid (non-NULL).
/// </summary>
///
inline bool Image::isValid () const
{
return (mImplementation != NULL && mImplementation->isValid());
}
//
/// <summary
/// This method will return true if <c>Image::paste</c>, <c>Image::blend</c>,
/// or an <c>ImageContext</c> has been opened for write.
/// </summary>
///
inline bool Image::isModified () const
{
return mImplementation->isModified();
}
/// <summary
/// This method will return true if the user buffer constructor was used to construct
/// this image instance.
/// </summary>
///
inline bool Image::usesUserBuffer () const
{
return mImplementation->usesUserBuffer();
}
} //end of namespace
#endif
| 30.553846 | 108 | 0.669856 | [
"object",
"model"
] |
d57f93ae5aec654fafad1d1fb2a10408e54aa7bc | 48,007 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/sw/swlib/swrast.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 2 | 2020-05-18T17:00:43.000Z | 2021-12-01T10:00:29.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/sw/swlib/swrast.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 5 | 2020-05-05T08:05:01.000Z | 2021-12-11T21:35:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/sw/swlib/swrast.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 4 | 2020-05-04T06:43:25.000Z | 2022-02-20T12:02:50.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_software
// $Keywords:
//
// $Description:
// Software Rasterizer
//
// The software rasterizer (SR) scan converts a primitive, feeding the
// scanlines to a CScanPipeline.
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
//+-----------------------------------------------------------------------------
//
// Function:
// IsMatrixIntegerTranslate
//
// Synopsis:
// Check that the given matrix only contains translation factors and that
// the translation factors always include a half translation
//
//------------------------------------------------------------------------------
BOOL IsMatrixIntegerTranslate(const CBaseMatrix *pmat)
{
REAL rM11 = REALABS(pmat->GetM11() - 1.0f);
REAL rM12 = REALABS(pmat->GetM12());
REAL rM21 = REALABS(pmat->GetM21());
REAL rM22 = REALABS(pmat->GetM22() - 1.0f);
if ((rM11 < MATRIX_EPSILON) && (rM21 < MATRIX_EPSILON) &&
(rM12 < MATRIX_EPSILON) && (rM22 < MATRIX_EPSILON))
{
REAL dx = pmat->GetDx();
REAL dy = pmat->GetDy();
dx = REALABS(static_cast<REAL>(CFloatFPU::Round(dx)) - dx);
dy = REALABS(static_cast<REAL>(CFloatFPU::Round(dy)) - dy);
if (dx <= PIXEL_EPSILON && dy <= PIXEL_EPSILON)
return TRUE;
}
return FALSE;
}
CSoftwareRasterizer::CSoftwareRasterizer()
{
m_pCSCreator = &m_Creator_sRGB;
}
CSoftwareRasterizer::~CSoftwareRasterizer()
{
}
void CSoftwareRasterizer::SetColorDataPixelFormat(MilPixelFormat::Enum fmtPixels)
{
if (fmtPixels == MilPixelFormat::PBGRA32bpp)
{
m_pCSCreator = &m_Creator_sRGB;
}
else
{
// we cannot rasterize in other formats for now.
Assert (FALSE);
}
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::Clear
//
// Synopsis:
// The Software Rasterizer must clear the entire device to the given solid
// color.
//
// The device extents are computed by requesting the device clipper and
// retrieving its bounding rectangle. This is then cleared by calling
// RasterizePath which will handle all the device clipping, format
// conversion etc.
//
HRESULT CSoftwareRasterizer::Clear(
__inout_ecount(1) CSpanSink *pSpanSink,
__in_ecount(1) CSpanClipper *pSpanClipper,
__in_ecount(1) const MilColorF *pColor
)
{
Assert(pSpanSink);
Assert(pSpanClipper);
HRESULT hr = S_OK;
if (m_pCSCreator == NULL)
{
MIL_THR(WGXERR_WRONGSTATE);
}
// Make a solid color output span class for this color.
CColorSource *pColorSource = NULL;
if (SUCCEEDED(hr))
{
MIL_THR(m_pCSCreator->GetCS_Constant(pColor, &pColorSource));
}
if (SUCCEEDED(hr))
{
// Get the bounds of the clipper which is the maximal rectangle we
// need to clear.
CMILSurfaceRect rc;
pSpanClipper->GetClipBounds(&rc);
// Make a path for this rectangle.
MilPoint2F points[] = {
{ float(rc.left), float(rc.top) },
{ float(rc.right), float(rc.top) },
{ float(rc.right), float(rc.bottom) },
{ float(rc.left), float(rc.bottom) }
};
static const BYTE types[] = { 0, 1, 1, 0x81 };
if (SUCCEEDED(hr))
{
MIL_THR(pSpanSink->SetupPipeline(
m_pCSCreator->GetPixelFormat(),
pColorSource,
FALSE, // No AA
false, // No complement
MilCompositingMode::SourceCopy,
pSpanClipper,
NULL,
NULL,
NULL));
}
if (SUCCEEDED(hr))
{
// Fill the path.
C_ASSERT(ARRAY_SIZE(points) == ARRAY_SIZE(types));
MilPointAndSizeL rcMilPointAndSizeL = {rc.left, rc.top, rc.Width(), rc.Height()};
MIL_THR(RasterizePath(
points,
types,
ARRAY_SIZE(points),
&IdentityMatrix,
MilFillMode::Alternate,
MilAntiAliasMode::None,
pSpanSink,
pSpanClipper,
&rcMilPointAndSizeL
));
pSpanSink->ReleaseExpensiveResources();
}
m_pCSCreator->ReleaseCS(pColorSource);
}
return hr;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::DrawBitmap
//
// Synopsis:
// The Software Rasterizer is being instructed to scan convert this
// primitive into the provided Render Target.
//
HRESULT CSoftwareRasterizer::DrawBitmap(
__inout_ecount(1) CSpanSink *pSpanSink,
__in_ecount(1) CSpanClipper *pSpanClipper,
__in_ecount(1) const CContextState *pContextState,
__in_ecount(1) IWGXBitmapSource *pIBitmap,
__in_ecount_opt(1) IMILEffectList *pIEffect
)
{
HRESULT hr = S_OK;
// Compute the proper source rectangle. If prcSource is NULL, make a
// rectangle equal to the bitmap dimensions.
CRectF<CoordinateSpace::RealizationSampling> rcSource;
CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::Device> const &
matLocalToDevice = pContextState->WorldToDevice;
// Effect is the same as local rendering for DrawBitmap
CMatrix<CoordinateSpace::Effect,CoordinateSpace::Device> const &
matEffectToDevice =
ReinterpretLocalRenderingAsBaseSampling(matLocalToDevice);
// Realization source sampling is the same as local rendering for DrawBitmap
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> const &
matSourceToDevice =
ReinterpretLocalRenderingAsRealizationSampling(matLocalToDevice);
// Source rectangle is also the local rendering rectangle.
CRectF<CoordinateSpace::LocalRendering> const &rcLocal =
ReinterpretRealizationSamplingAsLocalRendering(rcSource);
if (m_pCSCreator == NULL)
{
MIL_THR(WGXERR_WRONGSTATE);
}
MilPointAndSizeL rcBounds;
CMILSurfaceRect rcClipBounds;
if (SUCCEEDED(hr))
{
pSpanClipper->GetClipBounds(&rcClipBounds);
// figure out the source rect
if(pContextState->RenderState->Options.SourceRectValid)
{
MilRectFFromMilPointAndSizeL(OUT rcSource, pContextState->RenderState->SourceRect);
}
else
{
// Default source rect covers the bounds of the source, which
// is 1/2 beyond the extreme sample points in each direction.
MIL_THR(GetBitmapSourceBounds(
pIBitmap,
&rcSource
));
}
}
if (SUCCEEDED(hr))
{
// Compute the bounding rectangle.
CRectF<CoordinateSpace::Device> rc;
matSourceToDevice.Transform2DBounds(rcSource, OUT rc);
MIL_THR(InflateRectFToPointAndSizeL(rc, OUT rcBounds));
}
CColorSource *pColorSource = NULL;
if (SUCCEEDED(hr))
{
// Make an appropriate output span class based on the transform and
// the filter mode.
CMilColorF defColor;
MIL_THR(m_pCSCreator->GetCS_PrefilterAndResample(
pIBitmap,
MilBitmapWrapMode::Extend,
&defColor,
&matSourceToDevice,
pContextState->RenderState->InterpolationMode,
pContextState->RenderState->PrefilterEnable,
pContextState->RenderState->PrefilterThreshold,
NULL,
&pColorSource
));
}
if (SUCCEEDED(hr))
{
MIL_THR(pSpanSink->SetupPipeline(
m_pCSCreator->GetPixelFormat(),
pColorSource,
IsPPAAMode(pContextState->RenderState->AntiAliasMode),
false, // Complement support not required
pContextState->RenderState->CompositingMode,
pSpanClipper,
pIEffect,
&matEffectToDevice,
pContextState
));
if (SUCCEEDED(hr))
{
// This is ensured by our caller.
// If rcSource is empty, we will fail in AddRect and draw
// nothing, so all source rectangle flips are handled at
// in the engine by applying the flip to the matrix instead.
Assert(rcLocal.IsWellOrdered());
// make a path for this call.
MilPoint2F points[] = {
{ rcLocal.left , rcLocal.top },
{ rcLocal.right, rcLocal.top },
{ rcLocal.right, rcLocal.bottom },
{ rcLocal.left , rcLocal.bottom }
};
//
// Apply pixel snapping.
// This should be done in device space, so we convert points
// and let rasterizer to know that they are already converted
// by passing identity matrix to RasterizePath().
//
CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::Device> const *
pmatLocalToDevice = &matLocalToDevice;
CSnappingFrame *pSnappingFrame = pContextState->m_pSnappingStack;
if (pSnappingFrame && !pSnappingFrame->IsEmpty())
{
for (UINT i = 0; i < ARRAY_SIZE(points); i++)
{
TransformPoint(matLocalToDevice, points[i]);
pSnappingFrame->SnapPoint(points[i]);
}
pmatLocalToDevice = pmatLocalToDevice->pIdentity();
}
static const BYTE types[] = { 0, 1, 1, 0x81 };
// fill the path.
C_ASSERT(ARRAY_SIZE(points) == ARRAY_SIZE(types));
MIL_THR(RasterizePath(
points,
types,
ARRAY_SIZE(points),
pmatLocalToDevice,
MilFillMode::Alternate,
pContextState->RenderState->AntiAliasMode,
pSpanSink,
pSpanClipper,
&rcBounds
));
pSpanSink->ReleaseExpensiveResources();
}
m_pCSCreator->ReleaseCS(pColorSource);
}
// Some failure HRESULTs should only cause the primitive
// in question to not draw.
IgnoreNoRenderHRESULTs(&hr);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::DrawGlyphRun
//
// Synopsis:
// scan convert text primitive into the provided Render Target.
//
//------------------------------------------------------------------------------
HRESULT CSoftwareRasterizer::DrawGlyphRun(
__inout_ecount(1) CSpanSink *pSpanSink,
__in_ecount(1) CSpanClipper *pSpanClipper,
__inout_ecount(1) DrawGlyphsParameters &pars,
__inout_ecount(1) CMILBrush *pBrush,
FLOAT flEffectAlpha,
__in_ecount(1) CGlyphPainterMemory *pGlyphPainterMemory,
bool fTargetSupportsClearType,
__out_opt bool* pfClearTypeUsedToRender
)
{
HRESULT hr = S_OK;
CSWGlyphRunPainter painter;
BOOL fVisible = FALSE;
CColorSource *pColorSource = NULL;
CMILSurfaceRect rcClipBounds;
MilPointAndSizeL rcBounds;
if (pfClearTypeUsedToRender)
{
*pfClearTypeUsedToRender = false;
}
pSpanClipper->GetClipBounds(&rcClipBounds);
{
// Do a rough check for glyph run visibility.
// We need it, at least, to protect against
// overflows in rendering routines.
CRectF<CoordinateSpace::Device> rcClipBoundsF(
static_cast<float>(rcClipBounds.left),
static_cast<float>(rcClipBounds.top),
static_cast<float>(rcClipBounds.right),
static_cast<float>(rcClipBounds.bottom),
LTRB_Parameters
);
if (!pars.rcBounds.Device().DoesIntersect(rcClipBoundsF))
goto Cleanup;
}
IFC( painter.Init(
pars,
flEffectAlpha,
pGlyphPainterMemory,
fTargetSupportsClearType,
&fVisible
) );
if (pfClearTypeUsedToRender)
{
*pfClearTypeUsedToRender = !!painter.IsClearType();
}
if (!fVisible) goto Cleanup;
{
//
// For text rendering, local rendering and world sampling spaces are identical
//
const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &
matBaseSamplingToDevice =
ReinterpretLocalRenderingAsBaseSampling(pars.pContextState->WorldToDevice);
IFC( GetCS_Brush(
pBrush,
matBaseSamplingToDevice,
pars.pContextState,
&pColorSource
) );
{
CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> matGlyphRunToDevice;
const CRectF<CoordinateSpace::Shape> &rcfGlyphRun =
painter.GetOutlineRect(OUT matGlyphRunToDevice);
CShape shapeGlyphRun;
IFC(shapeGlyphRun.AddRect(rcfGlyphRun));
{
MilAntiAliasMode::Enum antiAliasMode = pars.pContextState->RenderState->AntiAliasMode;
CRectF<CoordinateSpace::Device> rcShapeBoundsDeviceSpace;
CShape scratchClipperShape;
CShapeClipperForFEB clipper(&shapeGlyphRun, &rcfGlyphRun, &matGlyphRunToDevice);
IFC(clipper.ApplyBrush(pBrush, matBaseSamplingToDevice, &scratchClipperShape));
// We should not call ApplyGuidelines to glyph run here,
// because guidelines should not stretch it.
// We only need to shift it as a whole, using guidelines closest to
// glyph run anchor point. CBaseGlyphRunPainter takes care of it.
IFC( pSpanSink->SetupPipelineForText(
pColorSource,
pars.pContextState->RenderState->CompositingMode,
painter,
antiAliasMode != MilAntiAliasMode::None && clipper.ShapeHasBeenCorrected()
) );
IFC(clipper.GetBoundsInDeviceSpace(&rcShapeBoundsDeviceSpace));
IFC(clipper.GetShape()->ConvertToGpPath(m_rgPoints, m_rgTypes));
IFC(InflateRectFToPointAndSizeL(rcShapeBoundsDeviceSpace, OUT rcBounds));
Assert(m_rgPoints.GetCount() == m_rgTypes.GetCount());
hr = RasterizePath(
m_rgPoints.GetDataBuffer(),
m_rgTypes.GetDataBuffer(),
m_rgPoints.GetCount(),
clipper.GetShapeToDeviceTransform(),
MilFillMode::Alternate,
antiAliasMode,
pSpanSink,
pSpanClipper,
&rcBounds
);
}
}
pSpanSink->ReleaseExpensiveResources();
}
Cleanup:
// Always reset the geometry scratch buffers to prevent stale
// types/points from being present on the next DrawGlyphRun call.
m_rgPoints.Reset(FALSE);
m_rgTypes.Reset(FALSE);
if (pColorSource != NULL)
{
m_pCSCreator->ReleaseCS(pColorSource);
}
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::FillPathUsingBrushRealizer
//
// Synopsis:
// version of FillPath that takes a CBrushRealizer
//
HRESULT
CSoftwareRasterizer::FillPathUsingBrushRealizer(
__inout_ecount(1) CSpanSink *pSpanSink,
MilPixelFormat::Enum fmtTarget,
DisplayId associatedDisplay,
__inout_ecount(1) CSpanClipper *pSpanClipper,
__in_ecount(1) const CContextState *pContextState,
__inout_ecount_opt(1) BrushContext *pBrushContext,
__in_ecount_opt(1) const IShapeData *pShape,
__in_ecount_opt(1) const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> *pmatShapeToDevice, // (NULL OK)
__in_ecount(1) CBrushRealizer *pBrushRealizer,
__in_ecount(1) const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &matWorldToDevice
DBG_STEP_RENDERING_COMMA_PARAM(__inout_ecount(1) ISteppedRenderingDisplayRT *pDisplayRTParent)
)
{
HRESULT hr = S_OK;
CMILBrush *pFillBrushNoRef = NULL;
IMILEffectList *pIEffectsNoRef = NULL;
{
CSwIntermediateRTCreator swRTCreator(
fmtTarget,
associatedDisplay
DBG_STEP_RENDERING_COMMA_PARAM(pDisplayRTParent)
);
IFC(pBrushRealizer->EnsureRealization(
CMILResourceCache::SwRealizationCacheIndex,
associatedDisplay,
pBrushContext,
pContextState,
&swRTCreator
));
pFillBrushNoRef = pBrushRealizer->GetRealizedBrushNoRef(false /* fConvertNULLToTransparent */);
IFC(pBrushRealizer->GetRealizedEffectsNoRef(&pIEffectsNoRef));
}
if (pFillBrushNoRef == NULL)
{
// Nothing to draw
goto Cleanup;
}
IFC(FillPath(
pSpanSink,
pSpanClipper,
pContextState,
pShape,
pmatShapeToDevice,
pFillBrushNoRef,
matWorldToDevice,
pIEffectsNoRef
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::FillPath
//
// Synopsis:
// Scan convert this shape into the provided Render Target. This is a low
// level utility, called both for filling, and during stroking.
//
//------------------------------------------------------------------------------
HRESULT
CSoftwareRasterizer::FillPath(
__inout_ecount(1) CSpanSink *pSpanSink,
__inout_ecount(1) CSpanClipper *pSpanClipper,
__in_ecount(1) const CContextState *pContextState,
__in_ecount_opt(1) const IShapeData *pShape, // NULL treated as infinite shape
__in_ecount_opt(1) const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> *pmatShapeToDevice, // NULL OK
__in_ecount(1) CMILBrush *pBrush,
__in_ecount(1) const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &matWorldToDevice,
__in_ecount_opt(1) IMILEffectList *pIEffect,
float rComplementFactor,
__in_ecount_opt(1) const CMILSurfaceRect *prcComplementBounds
)
{
HRESULT hr = S_OK;
// Clip shape to safe device bounds if needed.
CShape clippedShape;
bool fWasShapeClipped = false;
CRectF<CoordinateSpace::Shape> rcShapeBounds; // in shape space
if (pShape)
{
IFC(pShape->GetTightBounds(OUT rcShapeBounds));
}
IFC(ClipToSafeDeviceBounds(pShape, pmatShapeToDevice, &rcShapeBounds, &clippedShape, &fWasShapeClipped));
if (fWasShapeClipped)
{
pShape = &clippedShape;
pmatShapeToDevice = NULL;
IFC(pShape->GetTightBounds(OUT rcShapeBounds));
}
Assert(pShape != NULL); // NULL (infinite) shapes should be clipped to the device bounds.
{
CShape scratchClipperShape;
CShape scratchSnappedShape;
MilPointAndSizeL rcBounds;
CRectF<CoordinateSpace::Device> rcShapeBoundsDeviceSpace;
CMILSurfaceRect rcClipBounds;
CShapeClipperForFEB clipper(pShape, &rcShapeBounds, pmatShapeToDevice);
IFC(clipper.ApplyGuidelines(
pContextState->m_pSnappingStack,
&scratchSnappedShape
));
IFC(clipper.ApplyBrush(pBrush, matWorldToDevice, &scratchClipperShape));
IFC(clipper.GetBoundsInDeviceSpace(&rcShapeBoundsDeviceSpace));
// save the clip bounds in the context state
pSpanClipper->GetClipBounds(&rcClipBounds);
// Compute the bounding rectangle of the shape in device space.
IFC(InflateRectFToPointAndSizeL(rcShapeBoundsDeviceSpace, rcBounds));
IFC(clipper.GetShape()->ConvertToGpPath(m_rgPoints, m_rgTypes));
if (m_rgPoints.GetCount() > 0)
{
Assert(m_rgPoints.GetCount() == m_rgTypes.GetCount());
CColorSource *pColorSource = NULL;
// Make an appropriate output span class based on the transform and
// the filter mode.
IFC(GetCS_Brush(
pBrush,
matWorldToDevice,
pContextState,
&pColorSource
));
MIL_THR(pSpanSink->SetupPipeline(
m_pCSCreator->GetPixelFormat(),
pColorSource,
IsPPAAMode(pContextState->RenderState->AntiAliasMode),
rComplementFactor >= 0, // Requires support for complement?
pContextState->RenderState->CompositingMode,
pSpanClipper,
pIEffect,
&matWorldToDevice, // Effect coord space == World Sampling coord space
pContextState
));
if (SUCCEEDED(hr))
{
MIL_THR(RasterizePath(
m_rgPoints.GetDataBuffer(),
m_rgTypes.GetDataBuffer(),
m_rgPoints.GetCount(),
clipper.GetShapeToDeviceTransform(),
clipper.GetShape()->GetFillMode(),
pContextState->RenderState->AntiAliasMode,
pSpanSink,
pSpanClipper,
&rcBounds,
rComplementFactor,
prcComplementBounds
));
pSpanSink->ReleaseExpensiveResources();
}
m_pCSCreator->ReleaseCS(pColorSource);
}
}
Cleanup:
// Some failure HRESULTs should only cause the primitive
// in question to not draw.
IgnoreNoRenderHRESULTs(&hr);
// Always reset the geometry scratch buffers to prevent stale
// types/points from being present on the next DrawPath call.
m_rgPoints.Reset(FALSE);
m_rgTypes.Reset(FALSE);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CSoftwareRasterizer::GetCS_Brush
//
// Synopsis:
// Get a CColorSource which is appropriate for the given brush.
//
//------------------------------------------------------------------------------
HRESULT
CSoftwareRasterizer::GetCS_Brush(
CMILBrush *pBrush,
__in_ecount(1) const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> &matWorldHPCToDeviceHPC,
const CContextState *pContextState,
OUT CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
Assert( pBrush != NULL );
Assert( pContextState != NULL );
Assert( ppColorSource != NULL );
switch( pBrush->GetType() )
{
case BrushSolid:
{
const CMILBrushSolid *pSolidBrush = static_cast<CMILBrushSolid *>(pBrush);
MIL_THR(m_pCSCreator->GetCS_Constant(
&pSolidBrush->m_SolidColor,
ppColorSource));
}
break;
case BrushGradientLinear:
{
CMILBrushLinearGradient *pGradBrush = static_cast<CMILBrushLinearGradient *>(pBrush);
UINT nColorCount = pGradBrush->GetColorData()->GetCount();
if (nColorCount < 2)
{
// Specifiying at least 2 gradient stops is required
MIL_THR(WGXERR_INVALIDPARAMETER);
break;
}
MilPoint2F ptsGradient[3];
pGradBrush->GetEndPoints(&ptsGradient[0], &ptsGradient[1], &ptsGradient[2]);
if (SUCCEEDED(hr))
{
hr = m_pCSCreator->GetCS_LinearGradient(
ptsGradient,
pGradBrush->GetColorData()->GetCount(),
pGradBrush->GetColorData()->GetColorsPtr(),
pGradBrush->GetColorData()->GetPositionsPtr(),
pGradBrush->GetWrapMode(),
pGradBrush->GetColorInterpolationMode(),
&matWorldHPCToDeviceHPC,
ppColorSource);
}
}
break;
case BrushGradientRadial:
{
CMILBrushRadialGradient *pGradBrush = static_cast<CMILBrushRadialGradient *>(pBrush);
UINT nColorCount = pGradBrush->GetColorData()->GetCount();
if (nColorCount < 2)
{
// Specifiying at least 2 gradient stops is required
MIL_THR(WGXERR_INVALIDPARAMETER);
break;
}
MilPoint2F ptsGradient[3];
// Center is first gradient point
pGradBrush->GetEndPoints(
&ptsGradient[0],
&ptsGradient[1],
&ptsGradient[2]
);
if (!(pGradBrush->HasSeparateOriginFromCenter()))
{
// Create a standard radial gradient if no focal point was set, or
// the focal point & center are very close to each other
hr = m_pCSCreator->GetCS_RadialGradient(
ptsGradient,
pGradBrush->GetColorData()->GetCount(),
pGradBrush->GetColorData()->GetColorsPtr(),
pGradBrush->GetColorData()->GetPositionsPtr(),
pGradBrush->GetWrapMode(),
pGradBrush->GetColorInterpolationMode(),
&matWorldHPCToDeviceHPC,
ppColorSource);
}
else
{
// Create a focal gradient
hr = m_pCSCreator->GetCS_FocalGradient(
ptsGradient,
pGradBrush->GetColorData()->GetCount(),
pGradBrush->GetColorData()->GetColorsPtr(),
pGradBrush->GetColorData()->GetPositionsPtr(),
pGradBrush->GetWrapMode(),
pGradBrush->GetColorInterpolationMode(),
&pGradBrush->GetGradientOrigin(),
&matWorldHPCToDeviceHPC,
ppColorSource);
}
}
break;
case BrushBitmap:
{
CMILBrushBitmap *pBitmapBrush = static_cast<CMILBrushBitmap *>(pBrush);
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC> matBitmapToDeviceHPC;
pBitmapBrush->GetBitmapToSampleSpaceTransform(
matWorldHPCToDeviceHPC,
OUT matBitmapToDeviceHPC
);
hr = m_pCSCreator->GetCS_PrefilterAndResample(
pBitmapBrush->GetTextureNoAddRef(),
pBitmapBrush->GetWrapMode(),
&pBitmapBrush->GetBorderColorRef(),
&matBitmapToDeviceHPC,
pContextState->RenderState->InterpolationMode,
pContextState->RenderState->PrefilterEnable,
pContextState->RenderState->PrefilterThreshold,
pBitmapBrush,
ppColorSource
);
}
break;
case BrushShaderEffect:
{
CMILBrushShaderEffect *pShaderEffectBrush = static_cast<CMILBrushShaderEffect *>(pBrush);
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC> bitmapToSampleSpaceTransform;
pShaderEffectBrush->GetBitmapToSampleSpaceTransform(matWorldHPCToDeviceHPC, OUT &bitmapToSampleSpaceTransform);
hr = m_pCSCreator->GetCS_EffectShader(
reinterpret_cast<const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC>*>(&bitmapToSampleSpaceTransform),
pShaderEffectBrush,
OUT ppColorSource);
}
break;
}
if (hr == WGXERR_INVALIDPARAMETER)
{
// Invalid parameter triggered this, so just simply create
// a fully transparent brush.
CMilColorF trans(1.0, 1.0, 1.0, 0.0);
hr = m_pCSCreator->GetCS_Constant(&trans, ppColorSource);
}
return hr;
}
CResampleSpanCreator_sRGB::CResampleSpanCreator_sRGB()
{
m_pIdentitySpan = NULL;
m_pNearestNeighborSpan = NULL;
m_pBilinearSpanMMX = NULL;
// Future Consideration:
// Remove the non-optimized codepath once Intel integration is complete
#ifndef ENABLE_INTEL_OPTIMIZED_BILINEAR
m_pUnoptimizedBilinearSpan = NULL;
#else
m_pBilinearSpan = NULL;
#endif
}
CResampleSpanCreator_sRGB::~CResampleSpanCreator_sRGB()
{
delete m_pIdentitySpan;
delete m_pNearestNeighborSpan;
delete m_pBilinearSpanMMX;
// Future Consideration:
// Remove the non-optimized codepath once Intel integration is complete
#ifndef ENABLE_INTEL_OPTIMIZED_BILINEAR
delete m_pUnoptimizedBilinearSpan;
#else
delete m_pBilinearSpan;
#endif
}
HRESULT CResampleSpanCreator_sRGB::GetCS_Resample(
__in_ecount(1) IWGXBitmapSource *pIBitmapSource,
MilBitmapWrapMode::Enum wrapMode,
__in_ecount_opt(1) const MilColorF *pBorderColor,
__in_ecount(1) const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> *pmatTextureHPCToDeviceHPC,
MilBitmapInterpolationMode::Enum interpolationMode,
__deref_out_ecount(1) CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
// Ensure that the given bitmap source is in an acceptable format.
IWGXBitmapSource *pWICWrapper = NULL;
IWICFormatConverter *pConverter = NULL;
IWICImagingFactory *pIWICFactory = NULL;
IWICBitmapSource *pWGXWrapper = NULL;
IWICBitmapSource *pIWICBitmapSourceNoRef = NULL;
MilPixelFormat::Enum pixelFormat;
IFC(pIBitmapSource->GetPixelFormat(&pixelFormat));
IFC(WrapInClosestBitmapInterface(pIBitmapSource, &pWGXWrapper));
pIWICBitmapSourceNoRef = pWGXWrapper; // No ref change
if (!CSoftwareRasterizer::IsValidPixelFormat32(pixelFormat))
{
IFC(WICCreateImagingFactory_Proxy(WINCODEC_SDK_VERSION_WPF, &pIWICFactory));
IFC(pIWICFactory->CreateFormatConverter(&pConverter));
IFC(pConverter->Initialize(
pIWICBitmapSourceNoRef,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.0f,
WICBitmapPaletteTypeCustom
));
pIWICBitmapSourceNoRef = pConverter; // No ref change
}
UINT width, height;
width = 0;
height = 0;
IFC(pIWICBitmapSourceNoRef->GetSize(&width, &height));
CResampleSpan<GpCC> *pResampleSpan;
pResampleSpan = NULL;
// Go through our hierarchy of scan drawers:
if (IsMatrixIntegerTranslate(pmatTextureHPCToDeviceHPC) &&
((wrapMode == MilBitmapWrapMode::Tile) ||
(wrapMode == MilBitmapWrapMode::Border)))
{
if (m_pIdentitySpan == NULL)
{
m_pIdentitySpan = new CIdentitySpan();
}
pResampleSpan = m_pIdentitySpan;
}
else
{
if (interpolationMode == MilBitmapInterpolationMode::NearestNeighbor)
{
if (m_pNearestNeighborSpan == NULL)
{
m_pNearestNeighborSpan = new CNearestNeighborSpan();
}
pResampleSpan = m_pNearestNeighborSpan;
}
else
{
// Future Consideration:
// Remove this non-optimized codepath once Intel integration is complete
#ifndef ENABLE_INTEL_OPTIMIZED_BILINEAR
if (g_fUseMMX &&
CBilinearSpan_MMX::CanHandleInputRange(width, height, wrapMode)
)
{
if (m_pBilinearSpanMMX == NULL)
{
m_pBilinearSpanMMX = new CBilinearSpan_MMX();
}
pResampleSpan = m_pBilinearSpanMMX;
}
else
{
if (m_pUnoptimizedBilinearSpan == NULL)
{
m_pUnoptimizedBilinearSpan = new CUnoptimizedBilinearSpan();
}
pResampleSpan = m_pUnoptimizedBilinearSpan;
}
#else // _defined(ENABLE_INTEL_OPTIMIZED_BILINEAR)
BOOL fSupportsSSE2 = FALSE;
#if defined(_X86_)
// Check for SSE2 on x86 machines. SSE2 acceleration
// is disabled for 64-bit targets because intrinsics
// are causing compile errors.
fSupportsSSE2 = g_fUseSSE2;
#endif
// Check for MMX acceleration on machines that don't
// support SSE2.
if (!fSupportsSSE2 &&
g_fUseMMX &&
CBilinearSpan_MMX::CanHandleInputRange(width, height, wrapMode)
)
{
if (m_pBilinearSpanMMX == NULL)
{
m_pBilinearSpanMMX = new CBilinearSpan_MMX();
}
pResampleSpan = m_pBilinearSpanMMX;
}
else
{
// Use CBilinearSpan for SSE2-enabled machines,
// machines that don't support either SSE2 or MMX,
// or width/height's outside of the Fixed16 range.
//
// CBilinearSpan only optimizes for SSE2-enabled
// machines (not MMX machines), but it has non-optimized
// support for all machines types, and can support
// the full UINT range for all wrap modes.
if (m_pBilinearSpan == NULL)
{
m_pBilinearSpan = new CBilinearSpan();
}
pResampleSpan = m_pBilinearSpan;
}
#endif // !_defined(ENABLE_INTEL_OPTIMIZED_BILINEAR)
}
}
IFCOOM(pResampleSpan);
IFC(WrapInClosestBitmapInterface(pIWICBitmapSourceNoRef, &pWICWrapper));
IFC(pResampleSpan->Initialize(
pWICWrapper,
wrapMode,
pBorderColor,
pmatTextureHPCToDeviceHPC
));
*ppColorSource = pResampleSpan;
Cleanup:
ReleaseInterfaceNoNULL(pWGXWrapper);
ReleaseInterfaceNoNULL(pIWICFactory);
ReleaseInterfaceNoNULL(pConverter);
ReleaseInterfaceNoNULL(pWICWrapper);
RRETURN(hr);
}
HRESULT CColorSourceCreator::GetCS_PrefilterAndResample(
__in_ecount(1) IWGXBitmapSource *pIBitmapSource,
MilBitmapWrapMode::Enum wrapMode,
__in_ecount_opt(1) const MilColorF *pBorderColor,
__in_ecount(1) const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> *pmatTextureHPCToDeviceHPC,
MilBitmapInterpolationMode::Enum interpolationMode,
bool prefilterEnable,
FLOAT prefilterThreshold,
__inout_ecount_opt(1) IMILResourceCache *pICacheAlternate,
__deref_out_ecount(1) CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
IWGXBitmap *pBitmap = NULL;
if (prefilterEnable)
{
if (g_pMediaControl && g_pMediaControl->GetDataPtr()->FantScalerDisabled)
{
prefilterEnable = false;
}
}
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> matAdjustedTextureToDevice(*pmatTextureHPCToDeviceHPC);
IFC(CSwBitmapColorSource::DeriveFromBitmapAndContext(
pIBitmapSource,
IN OUT &matAdjustedTextureToDevice,
this,
prefilterEnable,
prefilterThreshold,
pICacheAlternate,
&pBitmap
));
pIBitmapSource = pBitmap;
pmatTextureHPCToDeviceHPC = &matAdjustedTextureToDevice;
IFC(GetCS_Resample(
pIBitmapSource,
wrapMode,
pBorderColor,
pmatTextureHPCToDeviceHPC,
interpolationMode,
ppColorSource
));
Cleanup:
ReleaseInterfaceNoNULL(pBitmap);
RRETURN(hr);
}
CColorSourceCreator_sRGB::CColorSourceCreator_sRGB()
: m_ResampleSpans()
{
m_pConstantColorSpan = NULL;
m_pLinearGradientSpan = NULL;
m_pRadialGradientSpan = NULL;
m_pFocalGradientSpan = NULL;
m_pShaderEffectSpan = NULL;
}
CColorSourceCreator_sRGB::~CColorSourceCreator_sRGB()
{
delete m_pConstantColorSpan;
delete m_pLinearGradientSpan;
delete m_pRadialGradientSpan;
delete m_pFocalGradientSpan;
delete m_pShaderEffectSpan;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CColorSourceCreator_sRGB::ReleaseCS, CColorSourceCreator
//
// Synopsis:
// Returns the color source to the color source creator.
//
//------------------------------------------------------------------------------
VOID CColorSourceCreator_sRGB::ReleaseCS(CColorSource *pColorSource)
{
// For now, we use a simplistic caching system:
//
// 1) Always hold on to the CColorSource objects we create (as a 1-deep
// cache per CColorSource type.)
// 2) Always release any expensive resources held by the color source
// object.
//
// When changing this to a more sophisticated caching system, note:
// CResampleSpanCreator_* owns caching decisions about resampling color
// sources, but ReleaseCS would have to do another virtual call to know
// whether to pass control on to CResampleSpanCreator_*.
//
// Another option is to collapse CResampleSpanCreator_* into
// CColorSourceCreator_*. But CMaskAlphaSpan_* currently uses
// CResampleSpanCreator_* without the overhead of CColorSourceCreator_*.
pColorSource->ReleaseExpensiveResources();
}
//+-----------------------------------------------------------------------------
//
// Member:
// CColorSourceCreator_sRGB::GetSupportedSourcePixelFormat
//
// Synopsis:
// Return pixel format needed by rasterizer when source is of given format
//
MilPixelFormat::Enum CColorSourceCreator_sRGB::GetSupportedSourcePixelFormat(
MilPixelFormat::Enum fmtSourceGiven,
bool fForceAlpha
) const
{
//
// sRGB supports only two source formats - 32bppBGR and PBGRA.
// If source is not BGR, then require PBGRA.
//
if ( fmtSourceGiven != MilPixelFormat::BGR32bpp
|| fForceAlpha
)
{
fmtSourceGiven = MilPixelFormat::PBGRA32bpp;
}
return fmtSourceGiven;
}
HRESULT
CColorSourceCreator_sRGB::GetCS_Constant(
const MilColorF *pColor,
OUT CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
if (m_pConstantColorSpan == NULL)
{
m_pConstantColorSpan = new CConstantColorBrushSpan;
if (m_pConstantColorSpan == NULL)
{
MIL_THR(E_OUTOFMEMORY);
}
}
if (SUCCEEDED(hr))
{
MIL_THR(m_pConstantColorSpan->Initialize(pColor));
}
if (SUCCEEDED(hr))
{
*ppColorSource = m_pConstantColorSpan;
}
return hr;
}
HRESULT
CColorSourceCreator_sRGB::GetCS_EffectShader(
__in const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC> *pRealizationSamplingToDevice,
__inout CMILBrushShaderEffect* pShaderEffectBrush,
__deref_out CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
if (m_pShaderEffectSpan == NULL)
{
m_pShaderEffectSpan = new CShaderEffectBrushSpan();
IFCOOM(m_pShaderEffectSpan);
}
IFC(m_pShaderEffectSpan->Initialize(
pRealizationSamplingToDevice,
pShaderEffectBrush));
*ppColorSource = m_pShaderEffectSpan;
Cleanup:
RRETURN(hr);
}
HRESULT
CColorSourceCreator_sRGB::GetCS_LinearGradient(
const MilPoint2F *pGradientPoints,
UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
Assert(nColorCount >= 2);
if (m_pLinearGradientSpan == NULL)
{
if (g_fUseMMX)
{
m_pLinearGradientSpan = new CLinearGradientBrushSpan_MMX;
}
else
{
m_pLinearGradientSpan = new CLinearGradientBrushSpan;
}
if (m_pLinearGradientSpan == NULL)
{
MIL_THR(E_OUTOFMEMORY);
}
}
if (SUCCEEDED(hr))
{
if (g_fUseMMX)
{
MIL_THR(((CLinearGradientBrushSpan_MMX *)m_pLinearGradientSpan)->Initialize(
pmatWorldHPCToDeviceHPC,
pGradientPoints,
pColors,
pPositions,
nColorCount,
wrapMode,
colorInterpolationMode));
}
else
{
MIL_THR(m_pLinearGradientSpan->Initialize(
pmatWorldHPCToDeviceHPC,
pGradientPoints,
pColors,
pPositions,
nColorCount,
wrapMode,
colorInterpolationMode));
}
}
if (SUCCEEDED(hr))
{
*ppColorSource = m_pLinearGradientSpan;
}
return hr;
}
HRESULT
CColorSourceCreator_sRGB::GetCS_RadialGradient(
const MilPoint2F *pGradientPoints,
const UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
Assert(nColorCount >= 2);
if (SUCCEEDED(hr))
{
if (m_pRadialGradientSpan == NULL)
{
m_pRadialGradientSpan = new CRadialGradientBrushSpan;
if (m_pRadialGradientSpan == NULL)
{
MIL_THR(E_OUTOFMEMORY);
}
}
}
if (SUCCEEDED(hr))
{
MIL_THR(m_pRadialGradientSpan->Initialize(
pmatWorldHPCToDeviceHPC,
pGradientPoints,
pColors,
pPositions,
nColorCount,
wrapMode,
colorInterpolationMode));
}
if (SUCCEEDED(hr))
{
*ppColorSource = m_pRadialGradientSpan;
}
return hr;
}
HRESULT
CColorSourceCreator_sRGB::GetCS_FocalGradient(
const MilPoint2F *pGradientPoints,
UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const MilPoint2F *pptOrigin,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
HRESULT hr = S_OK;
Assert(nColorCount >= 2);
if (SUCCEEDED(hr))
{
if (m_pFocalGradientSpan == NULL)
{
m_pFocalGradientSpan = new CFocalGradientBrushSpan;
if (m_pFocalGradientSpan == NULL)
{
MIL_THR(E_OUTOFMEMORY);
}
}
}
if (SUCCEEDED(hr))
{
MIL_THR(m_pFocalGradientSpan->Initialize(
pmatWorldHPCToDeviceHPC,
pGradientPoints,
pColors,
pPositions,
nColorCount,
wrapMode,
colorInterpolationMode,
pptOrigin));
}
if (SUCCEEDED(hr))
{
*ppColorSource = m_pFocalGradientSpan;
}
return hr;
}
HRESULT
CColorSourceCreator_sRGB::GetCS_Resample(
__in_ecount(1) IWGXBitmapSource *pIBitmapSource,
MilBitmapWrapMode::Enum wrapMode,
__in_ecount_opt(1) const MilColorF *pBorderColor,
__in_ecount(1) const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> *pmatTextureHPCToDeviceHPC,
MilBitmapInterpolationMode::Enum interpolationMode,
__deref_out_ecount(1) CColorSource **ppColorSource
)
{
return m_ResampleSpans.GetCS_Resample(
pIBitmapSource,
wrapMode,
pBorderColor,
pmatTextureHPCToDeviceHPC,
interpolationMode,
ppColorSource);
}
CResampleSpanCreator_scRGB::CResampleSpanCreator_scRGB()
{
Assert(FALSE);
}
CResampleSpanCreator_scRGB::~CResampleSpanCreator_scRGB()
{
Assert(FALSE);
}
HRESULT CResampleSpanCreator_scRGB::GetCS_Resample(
__in_ecount(1) IWGXBitmapSource *pIBitmapSource,
MilBitmapWrapMode::Enum wrapMode,
__in_ecount_opt(1) const MilColorF *pBorderColor,
__in_ecount(1) const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> *pmatTextureHPCToDeviceHPC,
MilBitmapInterpolationMode::Enum interpolationMode,
__deref_out_ecount(1) CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
CColorSourceCreator_scRGB::CColorSourceCreator_scRGB()
{
Assert(FALSE);
}
CColorSourceCreator_scRGB::~CColorSourceCreator_scRGB()
{
Assert(FALSE);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CColorSourceCreator_scRGB::ReleaseCS, CColorSourceCreator
//
// Synopsis:
// Returns the color source to the color source creator.
//
//------------------------------------------------------------------------------
VOID CColorSourceCreator_scRGB::ReleaseCS(CColorSource *pColorSource)
{
// See CColorSourceCreator_sRGB::ReleaseCS.
Assert(FALSE);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_Constant(
const MilColorF *pColor,
OUT CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_EffectShader(
__in const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC> *pRealizationSamplingToDevice,
__inout CMILBrushShaderEffect* pShaderEffectBrush,
__deref_out CColorSource **ppColorSource
)
{
Assert(false);
RRETURN(E_NOTIMPL);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_LinearGradient(
const MilPoint2F *pGradientPoints,
UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_RadialGradient(
const MilPoint2F *pGradientPoints,
UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_FocalGradient(
const MilPoint2F *pGradientPoints,
UINT nColorCount,
const MilColorF *pColors,
const FLOAT *pPositions,
MilGradientWrapMode::Enum wrapMode,
MilColorInterpolationMode::Enum colorInterpolationMode,
const MilPoint2F *pptOrigin,
const CMatrix<CoordinateSpace::BaseSamplingHPC,CoordinateSpace::DeviceHPC> *pmatWorldHPCToDeviceHPC,
OUT CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
HRESULT
CColorSourceCreator_scRGB::GetCS_Resample(
__in_ecount(1) IWGXBitmapSource *pIBitmapSource,
MilBitmapWrapMode::Enum wrapMode,
__in_ecount_opt(1) const MilColorF *pBorderColor,
__in_ecount(1) const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> *pmatTextureHPCToDeviceHPC,
MilBitmapInterpolationMode::Enum interpolationMode,
__deref_out_ecount(1) CColorSource **ppColorSource
)
{
Assert(FALSE);
RRETURN(E_NOTIMPL);
}
| 29.326206 | 145 | 0.609224 | [
"geometry",
"render",
"object",
"shape",
"transform",
"solid"
] |
d57fc3358be854872bbcf5261cf8a99e7fd4c7ac | 4,314 | cpp | C++ | src/Utils/Python/SoluteSolventComplexPython.cpp | qcscine/utilities | 493b8db45772b231bc0296535a09905b8e292f77 | [
"BSD-3-Clause"
] | null | null | null | src/Utils/Python/SoluteSolventComplexPython.cpp | qcscine/utilities | 493b8db45772b231bc0296535a09905b8e292f77 | [
"BSD-3-Clause"
] | 2 | 2019-06-19T14:34:38.000Z | 2022-03-25T15:07:18.000Z | src/Utils/Python/SoluteSolventComplexPython.cpp | qcscine/utilities | 493b8db45772b231bc0296535a09905b8e292f77 | [
"BSD-3-Clause"
] | 3 | 2019-06-14T16:44:19.000Z | 2020-04-19T20:48:19.000Z | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include <Utils/Solvation/SoluteSolventComplex.h>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
using namespace Scine::Utils;
using namespace Scine::Utils::SoluteSolventComplex;
void init_solute_solvent_complex(pybind11::module& m) {
auto solvation_submodule = m.def_submodule("solvation");
solvation_submodule.def(
"solvate",
pybind11::overload_cast<const AtomCollection&, int, const AtomCollection&, int, int, int, double, double, double, int, bool, double>(
&solvate),
pybind11::arg("solute_complex"), pybind11::arg("solute_size"), pybind11::arg("solvent"),
pybind11::arg("number_solvents"), pybind11::arg("seed"), pybind11::arg("resolution") = 32,
pybind11::arg("solvent_offset") = 0.0, pybind11::arg("max_distance") = 10.0, pybind11::arg("step_size") = 0.25,
pybind11::arg("number_rotamers") = 3, pybind11::arg("strategic_solvation") = false,
pybind11::arg("coverage_threshold") = 1.0, "Add systematically a number of solvents to solute.");
solvation_submodule.def("solvate_shells", &solvateShells, pybind11::arg("solute_complex"),
pybind11::arg("solute_size"), pybind11::arg("solvent"), pybind11::arg("number_shells"),
pybind11::arg("seed"), pybind11::arg("resolution") = 32, pybind11::arg("solvent_offset") = 0.0,
pybind11::arg("max_distance") = 10.0, pybind11::arg("step_size") = 0.25,
pybind11::arg("number_rotamers") = 3, pybind11::arg("strategic_solvation") = false,
pybind11::arg("coverage_threshold") = 1.0, "Add number of solvent shells to solute.");
solvation_submodule.def("give_solvent_shell_vector", &giveSolventShellVector, pybind11::arg("complex"),
pybind11::arg("solute_size"), pybind11::arg("solvent_size_vector"), pybind11::arg("resolution"),
pybind11::arg("logger"), pybind11::arg("strategic_solvation") = true,
pybind11::arg("threshold") = 1.0, "Analyze a complex and return its solvent shell vector.");
solvation_submodule.def(
"transfer_solvent_shell_vector", &transferSolventShellVector, pybind11::arg("shell_vector"),
"Translate solvent shell vector into one vector containing the size of the solvents in order.");
solvation_submodule.def("merge_atom_collection_vector", &mergeAtomCollectionVector,
pybind11::arg("atom_collection_vector"), "Merges list of atom collections to one atom collection.");
solvation_submodule.def(
"merge_solvent_shell_vector", &mergeSolventShellVector, pybind11::arg("shell_vector"),
"Merge a vector of a vector of atom collections (solvent shell vector) to one atom collection.");
solvation_submodule.def("check_distances", &checkDistances, pybind11::arg("molecule_1"), pybind11::arg("molecule_2"),
"Check if two atom collections overlap with their VdW spheres.");
solvation_submodule.def("solvation_strategy", &solvationStrategy,
"Solvation strategy for faster building of solute - solvent complexes.");
solvation_submodule.def("arrange", &arrange, pybind11::arg("surface_point_1"), pybind11::arg("surface_normal_1"),
pybind11::arg("surface_point_2"), pybind11::arg("surface_normal_2"),
pybind11::arg("molecule_2"), pybind11::arg("distance"),
"Arrange one atom collection such that the two positions given face each other.");
solvation_submodule.def("add", &add, pybind11::arg("complex"), pybind11::arg("additive"),
pybind11::arg("complex_surface_site"), pybind11::arg("additive_surface_site"),
pybind11::arg("min_distance"), pybind11::arg("max_distance"),
pybind11::arg("increment_distance") = 0.25, pybind11::arg("number_rotation_attempts") = 3,
"Add additive to given complex at given surface site of the complex.");
}
| 63.441176 | 139 | 0.658554 | [
"vector"
] |
d580e361bffe4e89e1c4f96be450490aae963fe4 | 6,669 | cpp | C++ | searchlib/src/tests/fef/featureoverride/featureoverride.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | searchlib/src/tests/fef/featureoverride/featureoverride.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | searchlib/src/tests/fef/featureoverride/featureoverride.cpp | Anlon-Burke/vespa | 5ecd989b36cc61716bf68f032a3482bf01fab726 | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/log/log.h>
LOG_SETUP("featureoverride_test");
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/fef/fef.h>
#include <vespa/searchlib/fef/test/indexenvironment.h>
#include <vespa/searchlib/fef/test/queryenvironment.h>
#include <vespa/searchlib/fef/test/plugin/double.h>
#include <vespa/searchlib/fef/test/plugin/sum.h>
#include <vespa/searchlib/features/valuefeature.h>
using namespace search::fef;
using namespace search::fef::test;
using namespace search::features;
using search::feature_t;
typedef Blueprint::SP BPSP;
struct Fixture
{
MatchDataLayout mdl;
vespalib::Stash stash;
std::vector<FeatureExecutor *> executors;
MatchData::UP md;
Fixture() : mdl(), stash(), executors(), md() {}
Fixture &add(FeatureExecutor *executor, size_t outCnt) {
executor->bind_outputs(stash.create_array<NumberOrObject>(outCnt));
executors.push_back(executor);
return *this;
}
Fixture &run() {
md = mdl.createMatchData();
for (const auto &executor : executors) {
executor->bind_match_data(*md);
executor->lazy_execute(1);
}
return *this;
}
FeatureExecutor &createValueExecutor() {
std::vector<feature_t> values;
values.push_back(1.0);
values.push_back(2.0);
values.push_back(3.0);
return stash.create<ValueExecutor>(values);
}
};
TEST_F("test decorator - single override", Fixture)
{
FeatureExecutor *fe = &f.createValueExecutor();
vespalib::Stash &stash = f.stash;
fe = &stash.create<FeatureOverrider>(*fe, 1, 50.0);
f.add(fe, 3).run();
EXPECT_EQUAL(fe->outputs().size(), 3u);
EXPECT_EQUAL(fe->outputs().get_number(0), 1.0);
EXPECT_EQUAL(fe->outputs().get_number(1), 50.0);
EXPECT_EQUAL(fe->outputs().get_number(2), 3.0);
}
TEST_F("test decorator - multiple overrides", Fixture)
{
FeatureExecutor *fe = &f.createValueExecutor();
vespalib::Stash &stash = f.stash;
fe = &stash.create<FeatureOverrider>(*fe, 0, 50.0);
fe = &stash.create<FeatureOverrider>(*fe, 2, 100.0);
f.add(fe, 3).run();
EXPECT_EQUAL(fe->outputs().size(), 3u);
EXPECT_EQUAL(fe->outputs().get_number(0), 50.0);
EXPECT_EQUAL(fe->outputs().get_number(1), 2.0);
EXPECT_EQUAL(fe->outputs().get_number(2), 100.0);
}
TEST_F("test decorator - non-existing override", Fixture)
{
FeatureExecutor *fe = &f.createValueExecutor();
vespalib::Stash &stash = f.stash;
fe = &stash.create<FeatureOverrider>(*fe, 1000, 50.0);
f.add(fe, 3).run();
EXPECT_EQUAL(fe->outputs().size(), 3u);
EXPECT_EQUAL(fe->outputs().get_number(0), 1.0);
EXPECT_EQUAL(fe->outputs().get_number(1), 2.0);
EXPECT_EQUAL(fe->outputs().get_number(2), 3.0);
}
TEST_F("test decorator - transitive override", Fixture)
{
FeatureExecutor *fe = &f.createValueExecutor();
vespalib::Stash &stash = f.stash;
fe = &stash.create<FeatureOverrider>(*fe, 1, 50.0);
f.add(fe, 3);
EXPECT_EQUAL(fe->outputs().size(), 3u);
FeatureExecutor *fe2 = &stash.create<DoubleExecutor>(3);
fe2 = &stash.create<FeatureOverrider>(*fe2, 2, 10.0);
auto inputs = stash.create_array<LazyValue>(3, nullptr);
inputs[0] = LazyValue(fe->outputs().get_raw(0), fe);
inputs[1] = LazyValue(fe->outputs().get_raw(1), fe);
inputs[2] = LazyValue(fe->outputs().get_raw(2), fe);
fe2->bind_inputs(inputs);
f.add(fe2, 3).run();
EXPECT_EQUAL(fe2->outputs().size(), 3u);
EXPECT_EQUAL(fe->outputs().get_number(0), 1.0);
EXPECT_EQUAL(fe->outputs().get_number(1), 50.0);
EXPECT_EQUAL(fe->outputs().get_number(2), 3.0);
EXPECT_EQUAL(fe2->outputs().get_number(0), 2.0);
EXPECT_EQUAL(fe2->outputs().get_number(1), 100.0);
EXPECT_EQUAL(fe2->outputs().get_number(2), 10.0);
}
TEST("test overrides")
{
BlueprintFactory bf;
bf.addPrototype(BPSP(new ValueBlueprint()));
bf.addPrototype(BPSP(new DoubleBlueprint()));
bf.addPrototype(BPSP(new SumBlueprint()));
IndexEnvironment idxEnv;
RankSetup rs(bf, idxEnv);
rs.addDumpFeature("value(1,2,3)");
rs.addDumpFeature("double(value(1))");
rs.addDumpFeature("double(value(2))");
rs.addDumpFeature("double(value(3))");
rs.addDumpFeature("mysum(value(2),value(2))");
rs.addDumpFeature("mysum(value(1),value(2),value(3))");
EXPECT_TRUE(rs.compile());
RankProgram::UP rankProgram = rs.create_dump_program();
MatchDataLayout mdl;
QueryEnvironment queryEnv;
Properties overrides;
overrides.add("value(2)", "20.0");
overrides.add("value(1,2,3).1", "4.0");
overrides.add("value(1,2,3).2", "6.0");
overrides.add("bogus(feature)", "10.0");
MatchData::UP match_data = mdl.createMatchData();
rankProgram->setup(*match_data, queryEnv, overrides);
std::map<vespalib::string, feature_t> res = Utils::getAllFeatures(*rankProgram, 2);
EXPECT_EQUAL(res.size(), 20u);
EXPECT_APPROX(res["value(1)"], 1.0, 1e-6);
EXPECT_APPROX(res["value(1).0"], 1.0, 1e-6);
EXPECT_APPROX(res["value(2)"], 20.0, 1e-6);
EXPECT_APPROX(res["value(2).0"], 20.0, 1e-6);
EXPECT_APPROX(res["value(3)"], 3.0, 1e-6);
EXPECT_APPROX(res["value(3).0"], 3.0, 1e-6);
EXPECT_APPROX(res["value(1,2,3)"], 1.0, 1e-6);
EXPECT_APPROX(res["value(1,2,3).0"], 1.0, 1e-6);
EXPECT_APPROX(res["value(1,2,3).1"], 4.0, 1e-6);
EXPECT_APPROX(res["value(1,2,3).2"], 6.0, 1e-6);
EXPECT_APPROX(res["mysum(value(2),value(2))"], 40.0, 1e-6);
EXPECT_APPROX(res["mysum(value(2),value(2)).out"], 40.0, 1e-6);
EXPECT_APPROX(res["mysum(value(1),value(2),value(3))"], 24.0, 1e-6);
EXPECT_APPROX(res["mysum(value(1),value(2),value(3)).out"], 24.0, 1e-6);
EXPECT_APPROX(res["double(value(1))"], 2.0, 1e-6);
EXPECT_APPROX(res["double(value(1)).0"], 2.0, 1e-6);
EXPECT_APPROX(res["double(value(2))"], 40.0, 1e-6);
EXPECT_APPROX(res["double(value(2)).0"], 40.0, 1e-6);
EXPECT_APPROX(res["double(value(3))"], 6.0, 1e-6);
EXPECT_APPROX(res["double(value(3)).0"], 6.0, 1e-6);
}
TEST_MAIN() { TEST_RUN_ALL(); }
| 38.549133 | 104 | 0.603239 | [
"vector"
] |
d586f0ee115625cce6a11e6949e73118678ed807 | 22,242 | cpp | C++ | Common/VirtualDisplay/Document/VirtualDisplay.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/VirtualDisplay/Document/VirtualDisplay.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/VirtualDisplay/Document/VirtualDisplay.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | //================================================================================
// Copyright (c) 2013 ~ 2019. HyungKi Jeong(clonextop@gmail.com)
// All rights reserved.
//
// The 3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause)
//
// 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 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.
//
// Title : Virtual display
// Rev. : 10/31/2019 Thu (clonextop@gmail.com)
//================================================================================
#include "VirtualDisplay.h"
#include "testdrive_document.inl"
#include <assert.h>
REGISTER_LOCALED_DOCUMENT(VirtualDisplay)
const LPCTSTR g_DisplayName = _T("Display");
#define MAX_DISPLAY_LENGTH 4096 // Maximum display screen width/height
typedef enum {
COORDINATE_TYPE_SCREEN,
COORDINATE_TYPE_OPENGL,
COORDINATE_TYPE_SIZE
} COORDINATE_TYPE;
typedef enum {
COMMAND_ID_CHECK_DISPLAY = 100, // check display update
} COMMAND_ID;
LPCTSTR g_sCoordinateType[COORDINATE_TYPE_SIZE] = {
_T("Screen"), // COORDINATE_TYPE_SCREEN
_T("OpenGL"), // COORDINATE_TYPE_OPENGL
};
LPCTSTR g_sColorFormat[] = {
_T("A8"), // DISPLAY_FORMAT_ALPHA
_T("L8"), // DISPLAY_FORMAT_LUMINANCE
_T("L8A8"), // DISPLAY_FORMAT_LUMINANCE_ALPHA
_T("R5G6B5"), // DISPLAY_FORMAT_RGB_565
_T("R4G4B4A4"), // DISPLAY_FORMAT_RGBA_4444
_T("R5G5B5A1"), // DISPLAY_FORMAT_RGBA_5551
_T("R8G8B8"), // DISPLAY_FORMAT_RGB_888
_T("A8B8G8R8"), // DISPLAY_FORMAT_ABGR_8888
_T("R8G8B8A8"), // DISPLAY_FORMAT_RGBA_8888
_T("A8R8G8B8"), // DISPLAY_FORMAT_ARGB_8888
};
LPCTSTR g_sWiseSay = _T("WISE");
static LPCTSTR __sListPreferredScreenMode[] = {
_T("TestDrive"),
_T("Window"),
_T("FullScreen"),
NULL
};
static LPCTSTR __sListPreferredScreenSize[] = {
_T("Orignal"),
_T("160x120 (QCIF)"),
_T("320x240 (QVGA)"),
_T("640x480 (VGA)"),
_T("1024x768 (XGA)"),
_T("1920x1080 (FullHD)"),
_T("3840x2160 (4K UHD)"),
_T("7680x4320 (8K UHD)"),
NULL
};
VirtualDisplay::VirtualDisplay(ITDDocument* pDoc)
{
m_pDoc = pDoc;
m_bShow = TRUE;
m_bUseAlphaChannel = FALSE;
m_pMemory = NULL;
m_bWaitPlayBtn = FALSE;
m_dwUpdateTimeout = 0;
ZeroMemory(&m_Wise, sizeof(m_Wise));
{
// wise saying initialization
m_sWiseSayFile = g_pSystem->RetrieveFullPath(_T("wise.ini"));
m_sWiseSayConfigFile = g_pSystem->RetrieveFullPath(_T("wise_config.ini"));
m_Wise.dwRestCount =
m_Wise.dwTotalCount = GetPrivateProfileInt(g_sWiseSay, _T("COUNT"), 0, m_sWiseSayFile);
if(m_Wise.dwTotalCount) {
m_Wise.pUsed = new BYTE[m_Wise.dwTotalCount];
CString sID;
for(int i = 0; i < m_Wise.dwTotalCount; i++) {
sID.Format(_T("SAY%d"), i);
m_Wise.pUsed[i] = GetPrivateProfileInt(g_sWiseSay, sID, 0, m_sWiseSayFile);
if(m_Wise.pUsed[i]) {
m_Wise.dwRestCount--;
}
}
}
}
{
// Get display memory
CString sName(g_DisplayName); // display memory name
ITDMemory* pMemory = g_pSystem->GetMemory(NULL); // get system memory
if(pMemory) { // new name that added post-fix '_Display' with name of system memory
sName = pMemory->GetName();
sName.AppendFormat(_T("_%s"), g_DisplayName);
m_pMemory = pMemory;
}
// Initialize system configuration
pMemory = g_pSystem->GetMemory(sName); // get display memory
if(!pMemory) pMemory = g_pSystem->GetMemory(g_DisplayName); // if not exist search with "Display"
if(!pMemory) pMemory = m_pMemory; // if not exist this too, set to system memory
if(!pMemory) { // if system memory is not existed too, create display memory
pMemory = g_pSystem->GetMemory(g_DisplayName, TRUE);
assert(pMemory != NULL);
pMemory->Create(2048 * 2048 * 4);
}
// Set Display window handle
m_pConfig = (DisplayConfig*)(pMemory->GetConfig());
m_pConfig->hWndHandle = pDoc->GetWindowHandle();
if(!m_pMemory) m_pMemory = pMemory;
}
m_pScreen = pDoc->CreateBuffer(NULL, 0, 0, 10, 10);
m_pScreen->SetEnable(BUFFER_INTERFACE_OUTLINE);
m_pScreen->SetEnable(BUFFER_INTERFACE_AUTOFIT);
m_pScreen->SetEnable(BUFFER_INTERFACE_LOAD_FROM_FILE);
m_pScreen->SetManager(this);
m_pBtnPlay = pDoc->CreateButton(NULL, 0, 0, 25, 19);
m_pBtnPlay->SetManager(this);
m_pBtnPlay->SetText(_L(PLAY));
m_pBtnPlay->GetObject()->SetEnable(FALSE);
m_pReport = pDoc->CreateReport(NULL, 0, 0, 10, 10);
m_pReport->EnableEdit(FALSE);
m_pReport->SetFont(_L(FONT));
m_pReport->SetText(_T("."));
m_pReport->SetHeight(10);
UpdateWiseSay();
m_pScreen->Create(10, 10);
{
ITDPropertyData* pProperty;
// coordinates
m_sCoordinateType.GetBuffer(MAX_PATH);
m_iCoordinateType = COORDINATE_TYPE_SCREEN;
m_sCoordinateType = g_sCoordinateType[m_iCoordinateType];
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_AXIS, _L(SCREEN_COORDINATE), (DWORD_PTR)m_sCoordinateType.GetBuffer(), _L(DESC_SCREEN_COORDINATE));
pProperty->AllowEdit(FALSE);
for(int i = 0; i < COORDINATE_TYPE_SIZE; i++) pProperty->AddOption(g_sCoordinateType[i]);
pProperty->UpdateConfigFile();
for(int i = 0; i < COORDINATE_TYPE_SIZE; i++)
if(!m_sCoordinateType.Compare(g_sCoordinateType[i])) {
m_iCoordinateType = i;
break;
}
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_BOOL, PROPERTY_ID_SHOW_FRONT, _L(FRONT_BUFFER), (DWORD_PTR)&m_pConfig->bShowFrontBuffer, _L(DESC_FRONT_BUFFER));
pProperty->UpdateConfigFile();
// use alpha channel
// pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_BOOL, PROPERTY_ID_USE_ALPHA, _T("Alpha channel"), (DWORD_PTR)&m_bUseAlphaChannel, _T("Appears on the screen using the alpha channel.\nNormal display buffer will be assumed alpha as zero."));
// pProperty->UpdateConfigFile();
// m_pScreen->UseAlphaChannel(m_bUseAlphaChannel);
m_pMovie = NULL;
m_pConfig->bMovieSave = FALSE;
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_BOOL, PROPERTY_ID_MOVIE_SAVE, _L(MOVIE_RECORD), (DWORD_PTR)&m_pConfig->bMovieSave, _L(DESC_MOVIE_RECORD));
m_iMovieFPS = 30;
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_INT, PROPERTY_ID_MOVIE_FPS, _L(MOVIE_FPS), (DWORD_PTR)&m_iMovieFPS, _L(DESC_MOVIE_FPS));
pProperty->UpdateConfigFile();
m_sMovieFilePath.GetBuffer(1024);
m_sMovieFilePath = _T("result.avi");
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_MOVIE_FILE_PATH, _L(MOVIE_FILE), (DWORD_PTR)m_sMovieFilePath.GetBuffer(), _L(DESC_MOVIE_FILE));
pProperty->UpdateConfigFile();
m_pConfig->bFramePause = FALSE;
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_BOOL, PROPERTY_ID_STOP_EACH_FRAME, _L(MOVIE_STOP), (DWORD_PTR)&m_pConfig->bFramePause, _L(DESC_MOVIE_STOP));
m_sPreferredScreenMode.GetBuffer(MAX_PATH);
m_sPreferredScreenMode = __sListPreferredScreenMode[0];
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_PREFERRED_SCREEN_MODE, _L(PREFERRED_SCREEN_MODE), (DWORD_PTR)m_sPreferredScreenMode.GetBuffer(), _L(DESC_PREFERRED_SCREEN_MODE));
pProperty->UpdateConfigFile();
for(int i = 0; __sListPreferredScreenMode[i]; i++) pProperty->AddOption(__sListPreferredScreenMode[i]);
m_sPreferredScreenSize.GetBuffer(MAX_PATH);
m_sPreferredScreenSize = __sListPreferredScreenSize[0];
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_PREFERRED_SCREEN_SIZE, _L(PREFERRED_SCREEN_SIZE), (DWORD_PTR)m_sPreferredScreenSize.GetBuffer(), _L(DESC_PREFERRED_SCREEN_SIZE));
pProperty->UpdateConfigFile();
for(int i = 0; __sListPreferredScreenSize[i]; i++) pProperty->AddOption(__sListPreferredScreenSize[i]);
}
m_pScreen->SetSmoothModeHighQuality();
m_pScreen->CreateFromFile(_T("default.png"));
OnCommand(COMMAND_ID_CHECK_DISPLAY);
}
VirtualDisplay::~VirtualDisplay(void)
{
m_pConfig->Front.bUpdate = FALSE;
if(m_pMovie) {
m_pMovie->Release();
m_pMovie = NULL;
}
m_pConfig->hWndHandle = NULL;
if(m_Wise.pUsed) {
delete [] m_Wise.pUsed;
m_Wise.pUsed = NULL;
}
}
void VirtualDisplay::UpdateWiseSay(void)
{
if(!m_Wise.dwTotalCount) return;
{
//refresh index(random)
SYSTEMTIME sys_time;
GetLocalTime(&sys_time);
m_Wise.dwIndex += (sys_time.wHour * 60 * 60 + sys_time.wMinute * 60 + sys_time.wSecond);
}
{
// Avoid duplication
if(!m_Wise.dwRestCount) {
ZeroMemory(m_Wise.pUsed, m_Wise.dwTotalCount * sizeof(BYTE));
m_Wise.dwRestCount = m_Wise.dwTotalCount;
_tremove(m_sWiseSayConfigFile);
}
for(DWORD i = 0; i < m_Wise.dwTotalCount; i++) {
m_Wise.dwIndex++;
m_Wise.dwIndex %= m_Wise.dwTotalCount;
if(!m_Wise.pUsed[m_Wise.dwIndex]) {
m_Wise.pUsed[m_Wise.dwIndex] = 1;
break;
}
}
m_Wise.dwRestCount--;
}
{
// Output
CString keyname;
TCHAR wise_say[1024];
keyname.Format(_T("SAY%d"), m_Wise.dwIndex);
GetPrivateProfileString(g_sWiseSay, keyname, _T(""), wise_say, 1024, m_sWiseSayFile);
WritePrivateProfileString(g_sWiseSay, keyname, _T("1"), m_sWiseSayConfigFile);
m_pReport->SetText(_T("%s"), wise_say);
}
}
BOOL VirtualDisplay::CheckDisplayUpdate(void)
{
BOOL bRet = FALSE;
BOOL bFrontBuffer = m_pConfig->bShowFrontBuffer;
DisplayBuffer* pBuffer = bFrontBuffer ? &m_pConfig->Front : &m_pConfig->Back;
if(!bFrontBuffer) { // bypass front buffer update, if you set the back buffer.
if(m_pConfig->Front.bUpdate)
m_pConfig->Front.bUpdate = FALSE;
} else if(m_bWaitPlayBtn) return FALSE;
// Initialize movie control, if it's needed.
if(!m_pMovie && m_pConfig->bMovieSave && m_pConfig->iWidth && m_pConfig->iHeight) {
m_pMovie = g_pSystem->CreateMovieInterface();
CString sProjectPath(g_pSystem->GetProjectPath());
m_pMovie->Create(sProjectPath + m_sMovieFilePath, m_pConfig->iWidth, m_pConfig->iHeight, m_iMovieFPS);
}
// Update framebuffer
if(pBuffer->bUpdate) {
if(!m_pMovie || !bFrontBuffer)
pBuffer->bUpdate = FALSE;
DWORD dwWidth = (DWORD)m_pConfig->iWidth;
DWORD dwHeight = (DWORD)m_pConfig->iHeight;
DWORD dwByteStride = m_pConfig->dwByteStride;
COLORFORMAT format = (COLORFORMAT)m_pConfig->ColorFormat;
BOOL bDraw = FALSE;
if(dwWidth && dwHeight) {
bDraw = TRUE;
// update resolution
if(m_pScreen->Width() != dwWidth || m_pScreen->Height() != dwHeight || m_pScreen->ColorFormat() != format) {
m_pScreen->Create(dwWidth, dwHeight, format);
m_pDoc->InvalidateLayout();
}
// copy buffer
{
BYTE* pMem = m_pMemory->GetPointer(pBuffer->dwAddress, dwByteStride * dwHeight);
if(pMem) {
if(m_pConfig->decoder) {
if(!m_pConfig->decoder((void*)m_pScreen->GetPointer(), pMem))
return FALSE;
} else {
if(!m_pScreen->CopyFromMemory(pMem, dwByteStride, m_pConfig->bReverse))
return FALSE;
}
m_pScreen->Present();
}
}
}
if(bFrontBuffer) {
if(m_pMovie && bDraw) { // If the movie is activated.
m_pMovie->Buffer()->CopyFromBuffer(m_pScreen);
m_pMovie->SetFrame();
}
if(m_pConfig->bFramePause) {
m_pReport->SetText(_L(PRESS_BUTTON_TO_CONTINUE));
m_bWaitPlayBtn = TRUE;
m_pBtnPlay->GetObject()->SetEnable();
} else if(m_pMovie)
pBuffer->bUpdate = FALSE;
}
bRet = TRUE;
}
return bRet;
}
BOOL VirtualDisplay::OnPropertyUpdate(ITDPropertyData* pProperty)
{
pProperty->UpdateData();
switch(pProperty->GetID()) {
case PROPERTY_ID_AXIS: // coordinates
for(int i = 0; i < COORDINATE_TYPE_SIZE; i++)
if(!m_sCoordinateType.Compare(g_sCoordinateType[i])) {
m_iCoordinateType = i;
break;
}
break;
case PROPERTY_ID_SHOW_FRONT: // Front / Back buffer
if(m_pConfig->bShowFrontBuffer) m_pConfig->Front.bUpdate = TRUE;
else m_pConfig->Back.bUpdate = TRUE;
UpdateWiseSay();
break;
case PROPERTY_ID_USE_ALPHA: // Use alpha channel
//g_pSystem->LogInfo(_T("m_bUseAlphaChannel = %d"), m_bUseAlphaChannel);
m_pScreen->UseAlphaChannel(m_bUseAlphaChannel);
m_pScreen->Present();
break;
case PROPERTY_ID_MOVIE_SAVE:
if(m_pConfig->bMovieSave) {
// start record
if(!m_pConfig->bShowFrontBuffer) {
m_pConfig->bMovieSave = FALSE;
pProperty->UpdateData(FALSE);
g_pSystem->LogWarning(_L(CHOOSE_FRONTBUFFER_FIRST));
} else {
g_pSystem->LogInfo(_L(ACTIVATE_MOVIE_RECOORD));
}
} else {
// end record
if(m_pMovie) {
m_pMovie->Release();
m_pMovie = NULL;
g_pSystem->LogInfo(_L(COMPLETE_MOVIE_RECOORD));
} else {
g_pSystem->LogInfo(_L(CANCEL_MOVIE_RECOORD));
}
}
break;
case PROPERTY_ID_STOP_EACH_FRAME:
if(!m_pConfig->bFramePause) OnButtonClick(0);
else m_pDoc->SetForegroundDocument();
m_pDoc->InvalidateLayout();
return TRUE;
case PROPERTY_ID_PREFERRED_SCREEN_MODE:
SetEnvironmentVariable(_T("PREFERRED_SCREEN_MODE"), m_sPreferredScreenMode);
break;
case PROPERTY_ID_PREFERRED_SCREEN_SIZE:
SetEnvironmentVariable(_T("PREFERRED_SCREEN_SIZE"), m_sPreferredScreenSize);
break;
}
pProperty->UpdateConfigFile(FALSE);
return TRUE;
}
CString GetStringFromSystemMemory(DWORD offset)
{
char* str_ansi = (char*)g_pSystem->GetMemory()->GetPointer(offset);
int str_size = MultiByteToWideChar(CP_ACP, 0, str_ansi, -1, NULL, NULL);
TCHAR* str_unicode = new TCHAR[str_size];
MultiByteToWideChar(CP_ACP, 0, str_ansi, strlen(str_ansi) + 1, str_unicode, str_size);
CString str(str_unicode);
delete [] str_unicode;
return str;
}
void VirtualDisplay::ExternalCommand(DWORD dwCommand, DWORD dwParam)
{
WORD op = HIWORD(dwCommand);
CheckDisplayUpdate();
switch(LOWORD(dwCommand)) {
case DISPLAY_CMD_SAVE_TO_FILE:
m_pScreen->SaveToFile(GetStringFromSystemMemory(dwParam));
break;
case DISPLAY_CMD_LOAD_FROM_FILE: {
DWORD* pMem = (DWORD*)m_pMemory->GetPointer(dwParam);
CString sPath = g_pSystem->RetrieveFullPath(GetStringFromSystemMemory(dwParam + 12));
if(m_pScreen->CreateFromFile(sPath, (COLORFORMAT)pMem[0])) {
m_pScreen->CopyToMemory(m_pMemory->GetPointer(pMem[1]), pMem[2]);
m_pConfig->ColorFormat = (DISPLAY_FORMAT)m_pScreen->ColorFormat();
m_pConfig->iWidth = m_pScreen->Width();
m_pConfig->iHeight = m_pScreen->Height();
m_pConfig->dwByteStride = m_pScreen->GetBytesStride();
*pMem = TRUE;
} else {
*pMem = FALSE;
}
}
break;
case DISPLAY_CMD_SET_FOREGROUND:
m_pDoc->SetForegroundDocument();
break;
default:
g_pSystem->LogError(_T("Invalid external command."));
}
}
BOOL VirtualDisplay::OnCommand(DWORD command, WPARAM wParam, LPARAM lParam)
{
switch(command) {
case 0:
UpdateWiseSay();
break;
case COMMAND_ID_CHECK_DISPLAY:
m_pDoc->KillTimer(COMMAND_ID_CHECK_DISPLAY);
if(!m_bShow) break;
{
DWORD dwDelay;
if(CheckDisplayUpdate()) {
m_dwUpdateTimeout = 500;
dwDelay = 5;
m_Wise.dwTime = 0;
} else {
if(m_dwUpdateTimeout) {
m_dwUpdateTimeout--;
dwDelay = 5;
} else {
dwDelay = 250;
}
if(m_Wise.dwTime >= 600000) { // Updated the quote one minute after
UpdateWiseSay();
m_Wise.dwTime = 0;
}
}
m_pDoc->SetTimer(COMMAND_ID_CHECK_DISPLAY, dwDelay);
m_Wise.dwTime += dwDelay;
}
break;
case TD_EXTERNAL_COMMAND:
ExternalCommand((DWORD)wParam, (DWORD)lParam);
break;
default:
break;
}
return TRUE;
}
void VirtualDisplay::OnBufferClick(DWORD dwID)
{
}
void VirtualDisplay::OnButtonClick(DWORD dwID)
{
m_pBtnPlay->GetObject()->SetEnable(FALSE);
m_pConfig->Front.bUpdate = FALSE;
m_bWaitPlayBtn = FALSE;
}
void VirtualDisplay::OnShow(BOOL bShow)
{
m_bShow = bShow;
OnCommand(COMMAND_ID_CHECK_DISPLAY);
}
void VirtualDisplay::OnSize(int width, int height)
{
ITDLayout* pLayout;
int report_height;
int x = 0;
// Leave space for pixel output information
report_height = width < 800 ? 34 : 23;
height -= report_height;
if(m_pScreen) {
// Apply
pLayout = m_pScreen->GetObject()->GetLayout();
pLayout->SetSize(width, height);
{
// Update button
ITDObject* pObject = m_pBtnPlay->GetObject();
if(m_pConfig->bFramePause != pObject->IsVisible())
pObject->Show(m_pConfig->bFramePause);
if(m_pConfig->bFramePause) {
pLayout = pObject->GetLayout();
pLayout->SetPosition(0, height + ((report_height - 19) >> 1));
x += 27;
width -= 27;
}
}
{
// Update report
pLayout = m_pReport->GetObject()->GetLayout();
pLayout->SetPosition(x, height);
pLayout->SetSize(width, report_height);
}
}
}
void VirtualDisplay::OnBufferMouseEvent(DWORD dwID, DWORD x, DWORD y, DWORD dwFlag)
{
if(!m_pScreen->IsInitialize() || !m_pConfig->iWidth || !m_pConfig->iHeight) {
return;
}
int coord_x, coord_y;
{
// Print coordinate
coord_x = x;
coord_y = m_pScreen->Height() - y - 1;
if(m_iCoordinateType == COORDINATE_TYPE_OPENGL) y = coord_y;
m_pReport->SetText(_T("%s_%s_%dx%d [X:%4d,Y:%4d] = "), m_pConfig->bShowFrontBuffer ? _T("Front") : _T("Back"), g_sColorFormat[m_pConfig->ColorFormat], m_pScreen->Width(), m_pScreen->Height(), x, y);
}
{
// Print Color
UINT r, g, b, a;
float fr, fg, fb, fa;
DWORD offset = m_pScreen->Width() * coord_y + coord_x;
{
// pick color
switch(m_pConfig->ColorFormat) {
case DISPLAY_FORMAT_ALPHA: {
r = g = b = 0;
fr = fg = fb = 0;
a = ((BYTE*)m_pScreen->GetPointer())[offset];
fa = a / 255.f;
}
break;
case DISPLAY_FORMAT_LUMINANCE: {
r = g = b = ((BYTE*)m_pScreen->GetPointer())[offset];
fr = fg = fb = r / 255.f;
a = 0;
fa = 0;
}
break;
case DISPLAY_FORMAT_LUMINANCE_ALPHA: {
WORD color = ((WORD*)m_pScreen->GetPointer())[offset];
r = g = b = color >> 8;
fr = fg = fb = r / 255.f;
a = color & 0xFF;
fa = a / 255.f;
}
break;
case DISPLAY_FORMAT_RGB_565: {
WORD color = ((WORD*)m_pScreen->GetPointer())[offset];
r = ((color >> 11) & 0x1F);
g = ((color >> 5) & 0x3F);
b = (color & 0x1F);
a = 0;
fr = r / 31.f;
fg = g / 63.f;
fb = b / 31.f;
fa = 0;
}
break;
case DISPLAY_FORMAT_RGBA_4444: {
WORD color = ((WORD*)m_pScreen->GetPointer())[offset];
r = ((color >> 12) & 0xF);
g = ((color >> 8) & 0xF);
b = ((color >> 4) & 0xF);
a = (color & 0xF);
fr = r / 15.f;
fg = g / 15.f;
fb = b / 15.f;
fa = a / 15.f;
}
break;
case DISPLAY_FORMAT_RGBA_5551: {
WORD color = ((WORD*)m_pScreen->GetPointer())[offset];
r = ((color >> 11) & 0x1F);
g = ((color >> 6) & 0x1F);
b = ((color >> 1) & 0x1F);
a = (color & 0x1);
fr = r / 15.f;
fg = g / 15.f;
fb = b / 15.f;
fa = a / 1.f;
}
break;
case DISPLAY_FORMAT_RGB_888: {
BYTE* pColor = &(((BYTE*)m_pScreen->GetPointer())[offset * 3]);
r = pColor[0];
g = pColor[1];
b = pColor[2];
a = 0;
goto GET_32BIT_COLOR;
}
break;
case DISPLAY_FORMAT_ABGR_8888: {
BYTE* pColor = (BYTE*) & (((DWORD*)m_pScreen->GetPointer())[offset]);
r = pColor[0];
g = pColor[1];
b = pColor[2];
a = pColor[3];
goto GET_32BIT_COLOR;
}
case DISPLAY_FORMAT_RGBA_8888: {
BYTE* pColor = (BYTE*) & (((DWORD*)m_pScreen->GetPointer())[offset]);
r = pColor[3];
g = pColor[2];
b = pColor[1];
a = pColor[0];
goto GET_32BIT_COLOR;
}
case DISPLAY_FORMAT_ARGB_8888: {
BYTE* pColor = (BYTE*) & (((DWORD*)m_pScreen->GetPointer())[offset]);
r = pColor[2];
g = pColor[1];
b = pColor[0];
a = pColor[3];
}
GET_32BIT_COLOR:
fr = r / 255.f;
fg = g / 255.f;
fb = b / 255.f;
fa = a / 255.f;
break;
}
}
// Show RED
m_pReport->SetColor(RGB(fr * 255, 0, 0));
m_pReport->AppendText(_L(BOX));
m_pReport->SetColor(RGB(255, 0, 0));
m_pReport->AppendText(_T("R(%3d/%.3f/0x%02X)"), r, fr, r);
m_pReport->SetColor(RGB(0, 0, 0));
m_pReport->AppendText(_T(" "));
// Show GREEN
m_pReport->SetColor(RGB(0, fg * 255, 0));
m_pReport->AppendText(_L(BOX));
m_pReport->SetColor(RGB(0, 128, 0));
m_pReport->AppendText(_T("G(%3d/%.3f/0x%02X)"), g, fg, g);
m_pReport->SetColor(RGB(0, 0, 0));
m_pReport->AppendText(_T(" "));
// Show Blue
m_pReport->SetColor(RGB(0, 0, fb * 255));
m_pReport->AppendText(_L(BOX));
m_pReport->SetColor(RGB(0, 0, 255));
m_pReport->AppendText(_T("B(%3d/%.3f/0x%02X)"), b, fb, b);
m_pReport->SetColor(RGB(0, 0, 0));
m_pReport->AppendText(_T(" "));
// Show Alpha
{
BYTE alpha = (BYTE)(fa * 255);
m_pReport->SetColor(RGB(alpha, alpha, alpha));
}
m_pReport->AppendText(_L(BOX));
m_pReport->SetColor(RGB(120, 120, 120));
m_pReport->AppendText(_T("A(%3d/%.3f/0x%02X)"), a, fa, a);
m_pReport->SetColor(RGB(0, 0, 0));
}
m_Wise.dwTime = 0;
}
BOOL VirtualDisplay::OnBufferBeforeFileOpen(DWORD dwID, LPCTSTR sFilename, DWORD dwWidth, DWORD dwHeight)
{
if(!dwWidth || !dwHeight) {
// custom load image...
return FALSE;
} else {
if(dwWidth > 4096) dwWidth = 4096;
if(dwHeight > 4096) dwHeight = 4096;
m_pScreen->Create(dwWidth, dwHeight);
m_pDoc->InvalidateLayout();
m_pReport->SetText(_L(CURRENT_DISPLAY_RESOLUTION), dwWidth, dwHeight);
}
return TRUE;
}
| 29.150721 | 245 | 0.684201 | [
"3d"
] |
d5918ac1b6e0566cfd05975ec816612cc7aaf99b | 1,898 | hpp | C++ | algebra/fft.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 10 | 2020-02-02T23:53:04.000Z | 2022-02-14T02:55:14.000Z | algebra/fft.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 2 | 2020-09-02T12:27:48.000Z | 2021-05-04T00:10:44.000Z | algebra/fft.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 1 | 2020-04-30T23:16:08.000Z | 2020-04-30T23:16:08.000Z | #pragma once
#include <vector>
namespace fft {
namespace detail {
int reverse(int number, int logs) {
int res = 0;
for (int log = 0, rev_log = logs - 1; log < logs; ++log, --rev_log) {
if (number & (1 << log)) {
res |= 1 << rev_log;
}
}
return res;
}
template <class T>
T root(size_t pow);
template <>
std::complex<long double> root(size_t pow) {
long double pi = std::acos(-1);
return {std::cos(2 * pi / pow), std::sin(2 * pi / pow)};
}
} // namespace detail
template<class T, class It>
void FFT(It begin, It end, T base) {
const int size = static_cast<int>(std::distance(begin, end));
int logs = __builtin_ctz(size);
for (int index = 0; index < size; ++index) {
auto rev = detail::reverse(index, logs);
if (rev < index) {
std::swap(*(begin + index), *(begin + rev));
}
}
std::vector<T> pows{base};
for (int i = 0; i + 1 < logs; ++i) {
pows.push_back(pows.back() * pows.back());
}
for (int log = 0; log < logs; ++log) {
auto bit = 1 << log;
T mult = pows[logs - log - 1];
for (int start = 0; start < size; start += 2 * bit) {
T pow = 1;
for (int index = start; index < start + bit; ++index, pow *= mult) {
T lhs = *(begin + index), rhs = *(begin + index + bit) * pow;
*(begin + index) = lhs + rhs, *(begin + index + bit) = lhs - rhs;
}
}
}
}
template <class T>
std::vector<T> multiply(std::vector<T> lhs, std::vector<T> rhs) {
auto size = lhs.size() + rhs.size() - 1;
size = 1 << (32 - __builtin_clz(size));
lhs.resize(size), rhs.resize(size);
auto base = detail::root<T>(size);
FFT(lhs.begin(), lhs.end(), base), FFT(rhs.begin(), rhs.end(), base);
for (size_t index = 0; index < size; ++index) { lhs[index] *= rhs[index]; }
FFT(lhs.begin(), lhs.end(), T(1) / base);
for (auto &value : lhs) { value /= size; }
return lhs;
}
} // namespace fft
| 24.025316 | 77 | 0.555848 | [
"vector"
] |
d5920e111d5c146ab01d8affebbd4404cfa77417 | 446 | cpp | C++ | C++/test/algorithm/searching/quick_search.cpp | aidan-lane/Algos | 59ce4db6d59b4ef05537ea50f921eb3ed369f382 | [
"MIT"
] | null | null | null | C++/test/algorithm/searching/quick_search.cpp | aidan-lane/Algos | 59ce4db6d59b4ef05537ea50f921eb3ed369f382 | [
"MIT"
] | null | null | null | C++/test/algorithm/searching/quick_search.cpp | aidan-lane/Algos | 59ce4db6d59b4ef05537ea50f921eb3ed369f382 | [
"MIT"
] | null | null | null | #include "third_party/catch.hpp"
#include "algorithm/searching/quick_search.hpp"
TEST_CASE("Base cases", "[searching][quick_search]") {
REQUIRE(quick_search(std::vector<int>(), 0, 0, 0) == -1);
REQUIRE(quick_search(std::vector<int>({0, 6, 3, 1, 2}), 3, 0, 5) == 4);
REQUIRE(quick_search(std::vector<int>({0, 1, 2, 3, 4, 5, 6, 7}), 8, 0, 8) == 8);
REQUIRE(quick_search(std::vector<int>({0, 1, 2, 3, 4, 5, 6, 7}), 1, 0, 8) == 0);
} | 49.555556 | 84 | 0.596413 | [
"vector"
] |
d59434cbf81cba62ccc26943c9bd9cc64bf106d4 | 1,559 | cpp | C++ | Source/Sample/MeshUtil.cpp | nhamil/oasis-engine | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | 1 | 2021-01-25T02:27:13.000Z | 2021-01-25T02:27:13.000Z | Source/Sample/MeshUtil.cpp | nhamil/oasis | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | null | null | null | Source/Sample/MeshUtil.cpp | nhamil/oasis | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | null | null | null | #include "Sample/MeshUtil.h"
Mesh* MeshUtil::CreateCube()
{
float s = 1;
float verts[] =
{
-s, s, -s,
-s, s, s,
s, s, s,
s, s, -s,
-s, -s, -s,
-s, -s, s,
s, -s, s,
s, -s, -s,
s, -s, -s,
s, s, -s,
s, s, s,
s, -s, s,
-s, -s, -s,
-s, s, -s,
-s, s, s,
-s, -s, s,
-s, -s, s,
s, -s, s,
s, s, s,
-s, s, s,
-s, -s, -s,
s, -s, -s,
s, s, -s,
-s, s, -s,
};
float texCoords[] =
{
0, 0,
1, 0,
1, 1,
0, 1,
0, 0,
1, 0,
1, 1,
0, 1,
0, 0,
1, 0,
1, 1,
0, 1,
0, 0,
1, 0,
1, 1,
0, 1,
0, 0,
1, 0,
1, 1,
0, 1,
0, 0,
1, 0,
1, 1,
0, 1,
};
short inds[] =
{
0, 1, 2,
0, 2, 3,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19,
20, 21, 22,
20, 22, 23,
};
Mesh* mesh = new Mesh();
mesh->SetVertexCount(4 * 6);
mesh->SetSubmeshCount(1);
mesh->SetPositions((Vector3*) verts);
mesh->SetTexCoords((Vector2*) texCoords);
mesh->SetIndices(0, 6 * 6, inds);
mesh->UploadToGPU();
return mesh;
} | 15.135922 | 46 | 0.270686 | [
"mesh"
] |
d594e32a50d8bb2d98dea1ef54478157e4b3c94e | 144,384 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_l2_eth_infra_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_l2_eth_infra_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_l2_eth_infra_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_l2_eth_infra_cfg.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_l2_eth_infra_cfg {
EthernetFeatures::EthernetFeatures()
:
egress_filtering(std::make_shared<EthernetFeatures::EgressFiltering>())
, cfm(std::make_shared<EthernetFeatures::Cfm>())
, ether_link_oam(std::make_shared<EthernetFeatures::EtherLinkOam>())
{
egress_filtering->parent = this;
cfm->parent = this;
ether_link_oam->parent = this;
yang_name = "ethernet-features"; yang_parent_name = "Cisco-IOS-XR-l2-eth-infra-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
EthernetFeatures::~EthernetFeatures()
{
}
bool EthernetFeatures::has_data() const
{
if (is_presence_container) return true;
return (egress_filtering != nullptr && egress_filtering->has_data())
|| (cfm != nullptr && cfm->has_data())
|| (ether_link_oam != nullptr && ether_link_oam->has_data());
}
bool EthernetFeatures::has_operation() const
{
return is_set(yfilter)
|| (egress_filtering != nullptr && egress_filtering->has_operation())
|| (cfm != nullptr && cfm->has_operation())
|| (ether_link_oam != nullptr && ether_link_oam->has_operation());
}
std::string EthernetFeatures::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "egress-filtering")
{
if(egress_filtering == nullptr)
{
egress_filtering = std::make_shared<EthernetFeatures::EgressFiltering>();
}
return egress_filtering;
}
if(child_yang_name == "Cisco-IOS-XR-ethernet-cfm-cfg:cfm")
{
if(cfm == nullptr)
{
cfm = std::make_shared<EthernetFeatures::Cfm>();
}
return cfm;
}
if(child_yang_name == "Cisco-IOS-XR-ethernet-link-oam-cfg:ether-link-oam")
{
if(ether_link_oam == nullptr)
{
ether_link_oam = std::make_shared<EthernetFeatures::EtherLinkOam>();
}
return ether_link_oam;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(egress_filtering != nullptr)
{
_children["egress-filtering"] = egress_filtering;
}
if(cfm != nullptr)
{
_children["Cisco-IOS-XR-ethernet-cfm-cfg:cfm"] = cfm;
}
if(ether_link_oam != nullptr)
{
_children["Cisco-IOS-XR-ethernet-link-oam-cfg:ether-link-oam"] = ether_link_oam;
}
return _children;
}
void EthernetFeatures::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> EthernetFeatures::clone_ptr() const
{
return std::make_shared<EthernetFeatures>();
}
std::string EthernetFeatures::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string EthernetFeatures::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function EthernetFeatures::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> EthernetFeatures::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool EthernetFeatures::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "egress-filtering" || name == "cfm" || name == "ether-link-oam")
return true;
return false;
}
EthernetFeatures::EgressFiltering::EgressFiltering()
:
egress_filtering_default_on{YType::empty, "egress-filtering-default-on"}
{
yang_name = "egress-filtering"; yang_parent_name = "ethernet-features"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::EgressFiltering::~EgressFiltering()
{
}
bool EthernetFeatures::EgressFiltering::has_data() const
{
if (is_presence_container) return true;
return egress_filtering_default_on.is_set;
}
bool EthernetFeatures::EgressFiltering::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(egress_filtering_default_on.yfilter);
}
std::string EthernetFeatures::EgressFiltering::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::EgressFiltering::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "egress-filtering";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EgressFiltering::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (egress_filtering_default_on.is_set || is_set(egress_filtering_default_on.yfilter)) leaf_name_data.push_back(egress_filtering_default_on.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EgressFiltering::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EgressFiltering::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EgressFiltering::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "egress-filtering-default-on")
{
egress_filtering_default_on = value;
egress_filtering_default_on.value_namespace = name_space;
egress_filtering_default_on.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EgressFiltering::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "egress-filtering-default-on")
{
egress_filtering_default_on.yfilter = yfilter;
}
}
bool EthernetFeatures::EgressFiltering::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "egress-filtering-default-on")
return true;
return false;
}
EthernetFeatures::Cfm::Cfm()
:
nv_satellite_sla_processing_disable{YType::empty, "nv-satellite-sla-processing-disable"}
,
traceroute_cache(std::make_shared<EthernetFeatures::Cfm::TracerouteCache>())
, domains(std::make_shared<EthernetFeatures::Cfm::Domains>())
{
traceroute_cache->parent = this;
domains->parent = this;
yang_name = "cfm"; yang_parent_name = "ethernet-features"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::Cfm::~Cfm()
{
}
bool EthernetFeatures::Cfm::has_data() const
{
if (is_presence_container) return true;
return nv_satellite_sla_processing_disable.is_set
|| (traceroute_cache != nullptr && traceroute_cache->has_data())
|| (domains != nullptr && domains->has_data());
}
bool EthernetFeatures::Cfm::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(nv_satellite_sla_processing_disable.yfilter)
|| (traceroute_cache != nullptr && traceroute_cache->has_operation())
|| (domains != nullptr && domains->has_operation());
}
std::string EthernetFeatures::Cfm::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::Cfm::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ethernet-cfm-cfg:cfm";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (nv_satellite_sla_processing_disable.is_set || is_set(nv_satellite_sla_processing_disable.yfilter)) leaf_name_data.push_back(nv_satellite_sla_processing_disable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "traceroute-cache")
{
if(traceroute_cache == nullptr)
{
traceroute_cache = std::make_shared<EthernetFeatures::Cfm::TracerouteCache>();
}
return traceroute_cache;
}
if(child_yang_name == "domains")
{
if(domains == nullptr)
{
domains = std::make_shared<EthernetFeatures::Cfm::Domains>();
}
return domains;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(traceroute_cache != nullptr)
{
_children["traceroute-cache"] = traceroute_cache;
}
if(domains != nullptr)
{
_children["domains"] = domains;
}
return _children;
}
void EthernetFeatures::Cfm::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "nv-satellite-sla-processing-disable")
{
nv_satellite_sla_processing_disable = value;
nv_satellite_sla_processing_disable.value_namespace = name_space;
nv_satellite_sla_processing_disable.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "nv-satellite-sla-processing-disable")
{
nv_satellite_sla_processing_disable.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "traceroute-cache" || name == "domains" || name == "nv-satellite-sla-processing-disable")
return true;
return false;
}
EthernetFeatures::Cfm::TracerouteCache::TracerouteCache()
:
hold_time{YType::uint32, "hold-time"},
cache_size{YType::uint32, "cache-size"}
{
yang_name = "traceroute-cache"; yang_parent_name = "cfm"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::Cfm::TracerouteCache::~TracerouteCache()
{
}
bool EthernetFeatures::Cfm::TracerouteCache::has_data() const
{
if (is_presence_container) return true;
return hold_time.is_set
|| cache_size.is_set;
}
bool EthernetFeatures::Cfm::TracerouteCache::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(hold_time.yfilter)
|| ydk::is_set(cache_size.yfilter);
}
std::string EthernetFeatures::Cfm::TracerouteCache::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/Cisco-IOS-XR-ethernet-cfm-cfg:cfm/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::Cfm::TracerouteCache::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "traceroute-cache";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::TracerouteCache::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (hold_time.is_set || is_set(hold_time.yfilter)) leaf_name_data.push_back(hold_time.get_name_leafdata());
if (cache_size.is_set || is_set(cache_size.yfilter)) leaf_name_data.push_back(cache_size.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::TracerouteCache::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::TracerouteCache::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::TracerouteCache::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "hold-time")
{
hold_time = value;
hold_time.value_namespace = name_space;
hold_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cache-size")
{
cache_size = value;
cache_size.value_namespace = name_space;
cache_size.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::TracerouteCache::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "hold-time")
{
hold_time.yfilter = yfilter;
}
if(value_path == "cache-size")
{
cache_size.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::TracerouteCache::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "hold-time" || name == "cache-size")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domains()
:
domain(this, {"domain"})
{
yang_name = "domains"; yang_parent_name = "cfm"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::Cfm::Domains::~Domains()
{
}
bool EthernetFeatures::Cfm::Domains::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<domain.len(); index++)
{
if(domain[index]->has_data())
return true;
}
return false;
}
bool EthernetFeatures::Cfm::Domains::has_operation() const
{
for (std::size_t index=0; index<domain.len(); index++)
{
if(domain[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string EthernetFeatures::Cfm::Domains::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/Cisco-IOS-XR-ethernet-cfm-cfg:cfm/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::Cfm::Domains::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "domains";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "domain")
{
auto ent_ = std::make_shared<EthernetFeatures::Cfm::Domains::Domain>();
ent_->parent = this;
domain.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : domain.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::Cfm::Domains::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::Cfm::Domains::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "domain")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Domain()
:
domain{YType::str, "domain"}
,
services(std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services>())
, domain_properties(std::make_shared<EthernetFeatures::Cfm::Domains::Domain::DomainProperties>())
{
services->parent = this;
domain_properties->parent = this;
yang_name = "domain"; yang_parent_name = "domains"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::Cfm::Domains::Domain::~Domain()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::has_data() const
{
if (is_presence_container) return true;
return domain.is_set
|| (services != nullptr && services->has_data())
|| (domain_properties != nullptr && domain_properties->has_data());
}
bool EthernetFeatures::Cfm::Domains::Domain::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(domain.yfilter)
|| (services != nullptr && services->has_operation())
|| (domain_properties != nullptr && domain_properties->has_operation());
}
std::string EthernetFeatures::Cfm::Domains::Domain::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/Cisco-IOS-XR-ethernet-cfm-cfg:cfm/domains/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::Cfm::Domains::Domain::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "domain";
ADD_KEY_TOKEN(domain, "domain");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (domain.is_set || is_set(domain.yfilter)) leaf_name_data.push_back(domain.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "services")
{
if(services == nullptr)
{
services = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services>();
}
return services;
}
if(child_yang_name == "domain-properties")
{
if(domain_properties == nullptr)
{
domain_properties = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::DomainProperties>();
}
return domain_properties;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(services != nullptr)
{
_children["services"] = services;
}
if(domain_properties != nullptr)
{
_children["domain-properties"] = domain_properties;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "domain")
{
domain = value;
domain.value_namespace = name_space;
domain.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "domain")
{
domain.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "services" || name == "domain-properties" || name == "domain")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Services()
:
service(this, {"service"})
{
yang_name = "services"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::~Services()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<service.len(); index++)
{
if(service[index]->has_data())
return true;
}
return false;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::has_operation() const
{
for (std::size_t index=0; index<service.len(); index++)
{
if(service[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "services";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "service")
{
auto ent_ = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service>();
ent_->parent = this;
service.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : service.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::Cfm::Domains::Domain::Services::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Service()
:
service{YType::str, "service"},
maximum_meps{YType::uint32, "maximum-meps"},
log_cross_check_errors{YType::empty, "log-cross-check-errors"},
continuity_check_archive_hold_time{YType::uint32, "continuity-check-archive-hold-time"},
tags{YType::uint32, "tags"},
log_continuity_check_state_changes{YType::empty, "log-continuity-check-state-changes"},
log_efd{YType::empty, "log-efd"},
continuity_check_auto_traceroute{YType::empty, "continuity-check-auto-traceroute"},
log_continuity_check_errors{YType::empty, "log-continuity-check-errors"},
log_ais{YType::empty, "log-ais"}
,
efd2(nullptr) // presence node
, continuity_check_interval(nullptr) // presence node
, mip_auto_creation(nullptr) // presence node
, ais(std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais>())
, cross_check(std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck>())
, service_properties(nullptr) // presence node
{
ais->parent = this;
cross_check->parent = this;
yang_name = "service"; yang_parent_name = "services"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::~Service()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::has_data() const
{
if (is_presence_container) return true;
return service.is_set
|| maximum_meps.is_set
|| log_cross_check_errors.is_set
|| continuity_check_archive_hold_time.is_set
|| tags.is_set
|| log_continuity_check_state_changes.is_set
|| log_efd.is_set
|| continuity_check_auto_traceroute.is_set
|| log_continuity_check_errors.is_set
|| log_ais.is_set
|| (efd2 != nullptr && efd2->has_data())
|| (continuity_check_interval != nullptr && continuity_check_interval->has_data())
|| (mip_auto_creation != nullptr && mip_auto_creation->has_data())
|| (ais != nullptr && ais->has_data())
|| (cross_check != nullptr && cross_check->has_data())
|| (service_properties != nullptr && service_properties->has_data());
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(service.yfilter)
|| ydk::is_set(maximum_meps.yfilter)
|| ydk::is_set(log_cross_check_errors.yfilter)
|| ydk::is_set(continuity_check_archive_hold_time.yfilter)
|| ydk::is_set(tags.yfilter)
|| ydk::is_set(log_continuity_check_state_changes.yfilter)
|| ydk::is_set(log_efd.yfilter)
|| ydk::is_set(continuity_check_auto_traceroute.yfilter)
|| ydk::is_set(log_continuity_check_errors.yfilter)
|| ydk::is_set(log_ais.yfilter)
|| (efd2 != nullptr && efd2->has_operation())
|| (continuity_check_interval != nullptr && continuity_check_interval->has_operation())
|| (mip_auto_creation != nullptr && mip_auto_creation->has_operation())
|| (ais != nullptr && ais->has_operation())
|| (cross_check != nullptr && cross_check->has_operation())
|| (service_properties != nullptr && service_properties->has_operation());
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "service";
ADD_KEY_TOKEN(service, "service");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (service.is_set || is_set(service.yfilter)) leaf_name_data.push_back(service.get_name_leafdata());
if (maximum_meps.is_set || is_set(maximum_meps.yfilter)) leaf_name_data.push_back(maximum_meps.get_name_leafdata());
if (log_cross_check_errors.is_set || is_set(log_cross_check_errors.yfilter)) leaf_name_data.push_back(log_cross_check_errors.get_name_leafdata());
if (continuity_check_archive_hold_time.is_set || is_set(continuity_check_archive_hold_time.yfilter)) leaf_name_data.push_back(continuity_check_archive_hold_time.get_name_leafdata());
if (tags.is_set || is_set(tags.yfilter)) leaf_name_data.push_back(tags.get_name_leafdata());
if (log_continuity_check_state_changes.is_set || is_set(log_continuity_check_state_changes.yfilter)) leaf_name_data.push_back(log_continuity_check_state_changes.get_name_leafdata());
if (log_efd.is_set || is_set(log_efd.yfilter)) leaf_name_data.push_back(log_efd.get_name_leafdata());
if (continuity_check_auto_traceroute.is_set || is_set(continuity_check_auto_traceroute.yfilter)) leaf_name_data.push_back(continuity_check_auto_traceroute.get_name_leafdata());
if (log_continuity_check_errors.is_set || is_set(log_continuity_check_errors.yfilter)) leaf_name_data.push_back(log_continuity_check_errors.get_name_leafdata());
if (log_ais.is_set || is_set(log_ais.yfilter)) leaf_name_data.push_back(log_ais.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "efd2")
{
if(efd2 == nullptr)
{
efd2 = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2>();
}
return efd2;
}
if(child_yang_name == "continuity-check-interval")
{
if(continuity_check_interval == nullptr)
{
continuity_check_interval = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval>();
}
return continuity_check_interval;
}
if(child_yang_name == "mip-auto-creation")
{
if(mip_auto_creation == nullptr)
{
mip_auto_creation = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation>();
}
return mip_auto_creation;
}
if(child_yang_name == "ais")
{
if(ais == nullptr)
{
ais = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais>();
}
return ais;
}
if(child_yang_name == "cross-check")
{
if(cross_check == nullptr)
{
cross_check = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck>();
}
return cross_check;
}
if(child_yang_name == "service-properties")
{
if(service_properties == nullptr)
{
service_properties = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties>();
}
return service_properties;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(efd2 != nullptr)
{
_children["efd2"] = efd2;
}
if(continuity_check_interval != nullptr)
{
_children["continuity-check-interval"] = continuity_check_interval;
}
if(mip_auto_creation != nullptr)
{
_children["mip-auto-creation"] = mip_auto_creation;
}
if(ais != nullptr)
{
_children["ais"] = ais;
}
if(cross_check != nullptr)
{
_children["cross-check"] = cross_check;
}
if(service_properties != nullptr)
{
_children["service-properties"] = service_properties;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "service")
{
service = value;
service.value_namespace = name_space;
service.value_namespace_prefix = name_space_prefix;
}
if(value_path == "maximum-meps")
{
maximum_meps = value;
maximum_meps.value_namespace = name_space;
maximum_meps.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-cross-check-errors")
{
log_cross_check_errors = value;
log_cross_check_errors.value_namespace = name_space;
log_cross_check_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "continuity-check-archive-hold-time")
{
continuity_check_archive_hold_time = value;
continuity_check_archive_hold_time.value_namespace = name_space;
continuity_check_archive_hold_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "tags")
{
tags = value;
tags.value_namespace = name_space;
tags.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-continuity-check-state-changes")
{
log_continuity_check_state_changes = value;
log_continuity_check_state_changes.value_namespace = name_space;
log_continuity_check_state_changes.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-efd")
{
log_efd = value;
log_efd.value_namespace = name_space;
log_efd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "continuity-check-auto-traceroute")
{
continuity_check_auto_traceroute = value;
continuity_check_auto_traceroute.value_namespace = name_space;
continuity_check_auto_traceroute.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-continuity-check-errors")
{
log_continuity_check_errors = value;
log_continuity_check_errors.value_namespace = name_space;
log_continuity_check_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "log-ais")
{
log_ais = value;
log_ais.value_namespace = name_space;
log_ais.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "service")
{
service.yfilter = yfilter;
}
if(value_path == "maximum-meps")
{
maximum_meps.yfilter = yfilter;
}
if(value_path == "log-cross-check-errors")
{
log_cross_check_errors.yfilter = yfilter;
}
if(value_path == "continuity-check-archive-hold-time")
{
continuity_check_archive_hold_time.yfilter = yfilter;
}
if(value_path == "tags")
{
tags.yfilter = yfilter;
}
if(value_path == "log-continuity-check-state-changes")
{
log_continuity_check_state_changes.yfilter = yfilter;
}
if(value_path == "log-efd")
{
log_efd.yfilter = yfilter;
}
if(value_path == "continuity-check-auto-traceroute")
{
continuity_check_auto_traceroute.yfilter = yfilter;
}
if(value_path == "log-continuity-check-errors")
{
log_continuity_check_errors.yfilter = yfilter;
}
if(value_path == "log-ais")
{
log_ais.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "efd2" || name == "continuity-check-interval" || name == "mip-auto-creation" || name == "ais" || name == "cross-check" || name == "service-properties" || name == "service" || name == "maximum-meps" || name == "log-cross-check-errors" || name == "continuity-check-archive-hold-time" || name == "tags" || name == "log-continuity-check-state-changes" || name == "log-efd" || name == "continuity-check-auto-traceroute" || name == "log-continuity-check-errors" || name == "log-ais")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::Efd2()
:
enable{YType::empty, "enable"},
protection_switching_enable{YType::empty, "protection-switching-enable"}
{
yang_name = "efd2"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::~Efd2()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::has_data() const
{
if (is_presence_container) return true;
return enable.is_set
|| protection_switching_enable.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(enable.yfilter)
|| ydk::is_set(protection_switching_enable.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "efd2";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
if (protection_switching_enable.is_set || is_set(protection_switching_enable.yfilter)) leaf_name_data.push_back(protection_switching_enable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "protection-switching-enable")
{
protection_switching_enable = value;
protection_switching_enable.value_namespace = name_space;
protection_switching_enable.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
if(value_path == "protection-switching-enable")
{
protection_switching_enable.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Efd2::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "enable" || name == "protection-switching-enable")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::ContinuityCheckInterval()
:
ccm_interval{YType::enumeration, "ccm-interval"},
loss_threshold{YType::uint32, "loss-threshold"}
{
yang_name = "continuity-check-interval"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::~ContinuityCheckInterval()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::has_data() const
{
if (is_presence_container) return true;
return ccm_interval.is_set
|| loss_threshold.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ccm_interval.yfilter)
|| ydk::is_set(loss_threshold.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "continuity-check-interval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ccm_interval.is_set || is_set(ccm_interval.yfilter)) leaf_name_data.push_back(ccm_interval.get_name_leafdata());
if (loss_threshold.is_set || is_set(loss_threshold.yfilter)) leaf_name_data.push_back(loss_threshold.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ccm-interval")
{
ccm_interval = value;
ccm_interval.value_namespace = name_space;
ccm_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "loss-threshold")
{
loss_threshold = value;
loss_threshold.value_namespace = name_space;
loss_threshold.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ccm-interval")
{
ccm_interval.yfilter = yfilter;
}
if(value_path == "loss-threshold")
{
loss_threshold.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ContinuityCheckInterval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ccm-interval" || name == "loss-threshold")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::MipAutoCreation()
:
mip_policy{YType::enumeration, "mip-policy"},
ccm_learning_enable{YType::empty, "ccm-learning-enable"}
{
yang_name = "mip-auto-creation"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::~MipAutoCreation()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::has_data() const
{
if (is_presence_container) return true;
return mip_policy.is_set
|| ccm_learning_enable.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(mip_policy.yfilter)
|| ydk::is_set(ccm_learning_enable.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "mip-auto-creation";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (mip_policy.is_set || is_set(mip_policy.yfilter)) leaf_name_data.push_back(mip_policy.get_name_leafdata());
if (ccm_learning_enable.is_set || is_set(ccm_learning_enable.yfilter)) leaf_name_data.push_back(ccm_learning_enable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "mip-policy")
{
mip_policy = value;
mip_policy.value_namespace = name_space;
mip_policy.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ccm-learning-enable")
{
ccm_learning_enable = value;
ccm_learning_enable.value_namespace = name_space;
ccm_learning_enable.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "mip-policy")
{
mip_policy.yfilter = yfilter;
}
if(value_path == "ccm-learning-enable")
{
ccm_learning_enable.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::MipAutoCreation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "mip-policy" || name == "ccm-learning-enable")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Ais()
:
transmission(nullptr) // presence node
{
yang_name = "ais"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::~Ais()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::has_data() const
{
if (is_presence_container) return true;
return (transmission != nullptr && transmission->has_data());
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::has_operation() const
{
return is_set(yfilter)
|| (transmission != nullptr && transmission->has_operation());
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ais";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "transmission")
{
if(transmission == nullptr)
{
transmission = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission>();
}
return transmission;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(transmission != nullptr)
{
_children["transmission"] = transmission;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "transmission")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::Transmission()
:
ais_interval{YType::enumeration, "ais-interval"},
cos{YType::uint32, "cos"}
{
yang_name = "transmission"; yang_parent_name = "ais"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::~Transmission()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::has_data() const
{
if (is_presence_container) return true;
return ais_interval.is_set
|| cos.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ais_interval.yfilter)
|| ydk::is_set(cos.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "transmission";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ais_interval.is_set || is_set(ais_interval.yfilter)) leaf_name_data.push_back(ais_interval.get_name_leafdata());
if (cos.is_set || is_set(cos.yfilter)) leaf_name_data.push_back(cos.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ais-interval")
{
ais_interval = value;
ais_interval.value_namespace = name_space;
ais_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cos")
{
cos = value;
cos.value_namespace = name_space;
cos.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ais-interval")
{
ais_interval.yfilter = yfilter;
}
if(value_path == "cos")
{
cos.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::Ais::Transmission::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ais-interval" || name == "cos")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheck()
:
auto_{YType::empty, "auto"}
,
cross_check_meps(std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps>())
{
cross_check_meps->parent = this;
yang_name = "cross-check"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::~CrossCheck()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::has_data() const
{
if (is_presence_container) return true;
return auto_.is_set
|| (cross_check_meps != nullptr && cross_check_meps->has_data());
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(auto_.yfilter)
|| (cross_check_meps != nullptr && cross_check_meps->has_operation());
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cross-check";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (auto_.is_set || is_set(auto_.yfilter)) leaf_name_data.push_back(auto_.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cross-check-meps")
{
if(cross_check_meps == nullptr)
{
cross_check_meps = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps>();
}
return cross_check_meps;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(cross_check_meps != nullptr)
{
_children["cross-check-meps"] = cross_check_meps;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "auto")
{
auto_ = value;
auto_.value_namespace = name_space;
auto_.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "auto")
{
auto_.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cross-check-meps" || name == "auto")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMeps()
:
cross_check_mep(this, {"mep_id"})
{
yang_name = "cross-check-meps"; yang_parent_name = "cross-check"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::~CrossCheckMeps()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<cross_check_mep.len(); index++)
{
if(cross_check_mep[index]->has_data())
return true;
}
return false;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::has_operation() const
{
for (std::size_t index=0; index<cross_check_mep.len(); index++)
{
if(cross_check_mep[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cross-check-meps";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cross-check-mep")
{
auto ent_ = std::make_shared<EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep>();
ent_->parent = this;
cross_check_mep.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : cross_check_mep.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cross-check-mep")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::CrossCheckMep()
:
mep_id{YType::uint32, "mep-id"},
enable_mac_address{YType::empty, "enable-mac-address"},
mac_address{YType::str, "mac-address"}
{
yang_name = "cross-check-mep"; yang_parent_name = "cross-check-meps"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::~CrossCheckMep()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::has_data() const
{
if (is_presence_container) return true;
return mep_id.is_set
|| enable_mac_address.is_set
|| mac_address.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(mep_id.yfilter)
|| ydk::is_set(enable_mac_address.yfilter)
|| ydk::is_set(mac_address.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cross-check-mep";
ADD_KEY_TOKEN(mep_id, "mep-id");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (mep_id.is_set || is_set(mep_id.yfilter)) leaf_name_data.push_back(mep_id.get_name_leafdata());
if (enable_mac_address.is_set || is_set(enable_mac_address.yfilter)) leaf_name_data.push_back(enable_mac_address.get_name_leafdata());
if (mac_address.is_set || is_set(mac_address.yfilter)) leaf_name_data.push_back(mac_address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "mep-id")
{
mep_id = value;
mep_id.value_namespace = name_space;
mep_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "enable-mac-address")
{
enable_mac_address = value;
enable_mac_address.value_namespace = name_space;
enable_mac_address.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mac-address")
{
mac_address = value;
mac_address.value_namespace = name_space;
mac_address.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "mep-id")
{
mep_id.yfilter = yfilter;
}
if(value_path == "enable-mac-address")
{
enable_mac_address.yfilter = yfilter;
}
if(value_path == "mac-address")
{
mac_address.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::CrossCheck::CrossCheckMeps::CrossCheckMep::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "mep-id" || name == "enable-mac-address" || name == "mac-address")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::ServiceProperties()
:
service_type{YType::enumeration, "service-type"},
group_name{YType::str, "group-name"},
switching_name{YType::str, "switching-name"},
ce_id{YType::uint32, "ce-id"},
remote_ce_id{YType::uint32, "remote-ce-id"},
evi{YType::uint32, "evi"},
short_ma_name_format{YType::enumeration, "short-ma-name-format"},
short_ma_name_string{YType::str, "short-ma-name-string"},
short_ma_name_number{YType::uint32, "short-ma-name-number"},
short_ma_name_oui{YType::uint32, "short-ma-name-oui"},
short_ma_name_vpn_index{YType::uint32, "short-ma-name-vpn-index"},
short_ma_name_icc{YType::str, "short-ma-name-icc"},
short_ma_name_umc{YType::str, "short-ma-name-umc"}
{
yang_name = "service-properties"; yang_parent_name = "service"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::~ServiceProperties()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::has_data() const
{
if (is_presence_container) return true;
return service_type.is_set
|| group_name.is_set
|| switching_name.is_set
|| ce_id.is_set
|| remote_ce_id.is_set
|| evi.is_set
|| short_ma_name_format.is_set
|| short_ma_name_string.is_set
|| short_ma_name_number.is_set
|| short_ma_name_oui.is_set
|| short_ma_name_vpn_index.is_set
|| short_ma_name_icc.is_set
|| short_ma_name_umc.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(service_type.yfilter)
|| ydk::is_set(group_name.yfilter)
|| ydk::is_set(switching_name.yfilter)
|| ydk::is_set(ce_id.yfilter)
|| ydk::is_set(remote_ce_id.yfilter)
|| ydk::is_set(evi.yfilter)
|| ydk::is_set(short_ma_name_format.yfilter)
|| ydk::is_set(short_ma_name_string.yfilter)
|| ydk::is_set(short_ma_name_number.yfilter)
|| ydk::is_set(short_ma_name_oui.yfilter)
|| ydk::is_set(short_ma_name_vpn_index.yfilter)
|| ydk::is_set(short_ma_name_icc.yfilter)
|| ydk::is_set(short_ma_name_umc.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "service-properties";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (service_type.is_set || is_set(service_type.yfilter)) leaf_name_data.push_back(service_type.get_name_leafdata());
if (group_name.is_set || is_set(group_name.yfilter)) leaf_name_data.push_back(group_name.get_name_leafdata());
if (switching_name.is_set || is_set(switching_name.yfilter)) leaf_name_data.push_back(switching_name.get_name_leafdata());
if (ce_id.is_set || is_set(ce_id.yfilter)) leaf_name_data.push_back(ce_id.get_name_leafdata());
if (remote_ce_id.is_set || is_set(remote_ce_id.yfilter)) leaf_name_data.push_back(remote_ce_id.get_name_leafdata());
if (evi.is_set || is_set(evi.yfilter)) leaf_name_data.push_back(evi.get_name_leafdata());
if (short_ma_name_format.is_set || is_set(short_ma_name_format.yfilter)) leaf_name_data.push_back(short_ma_name_format.get_name_leafdata());
if (short_ma_name_string.is_set || is_set(short_ma_name_string.yfilter)) leaf_name_data.push_back(short_ma_name_string.get_name_leafdata());
if (short_ma_name_number.is_set || is_set(short_ma_name_number.yfilter)) leaf_name_data.push_back(short_ma_name_number.get_name_leafdata());
if (short_ma_name_oui.is_set || is_set(short_ma_name_oui.yfilter)) leaf_name_data.push_back(short_ma_name_oui.get_name_leafdata());
if (short_ma_name_vpn_index.is_set || is_set(short_ma_name_vpn_index.yfilter)) leaf_name_data.push_back(short_ma_name_vpn_index.get_name_leafdata());
if (short_ma_name_icc.is_set || is_set(short_ma_name_icc.yfilter)) leaf_name_data.push_back(short_ma_name_icc.get_name_leafdata());
if (short_ma_name_umc.is_set || is_set(short_ma_name_umc.yfilter)) leaf_name_data.push_back(short_ma_name_umc.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "service-type")
{
service_type = value;
service_type.value_namespace = name_space;
service_type.value_namespace_prefix = name_space_prefix;
}
if(value_path == "group-name")
{
group_name = value;
group_name.value_namespace = name_space;
group_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "switching-name")
{
switching_name = value;
switching_name.value_namespace = name_space;
switching_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ce-id")
{
ce_id = value;
ce_id.value_namespace = name_space;
ce_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "remote-ce-id")
{
remote_ce_id = value;
remote_ce_id.value_namespace = name_space;
remote_ce_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "evi")
{
evi = value;
evi.value_namespace = name_space;
evi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-format")
{
short_ma_name_format = value;
short_ma_name_format.value_namespace = name_space;
short_ma_name_format.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-string")
{
short_ma_name_string = value;
short_ma_name_string.value_namespace = name_space;
short_ma_name_string.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-number")
{
short_ma_name_number = value;
short_ma_name_number.value_namespace = name_space;
short_ma_name_number.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-oui")
{
short_ma_name_oui = value;
short_ma_name_oui.value_namespace = name_space;
short_ma_name_oui.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-vpn-index")
{
short_ma_name_vpn_index = value;
short_ma_name_vpn_index.value_namespace = name_space;
short_ma_name_vpn_index.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-icc")
{
short_ma_name_icc = value;
short_ma_name_icc.value_namespace = name_space;
short_ma_name_icc.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-ma-name-umc")
{
short_ma_name_umc = value;
short_ma_name_umc.value_namespace = name_space;
short_ma_name_umc.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "service-type")
{
service_type.yfilter = yfilter;
}
if(value_path == "group-name")
{
group_name.yfilter = yfilter;
}
if(value_path == "switching-name")
{
switching_name.yfilter = yfilter;
}
if(value_path == "ce-id")
{
ce_id.yfilter = yfilter;
}
if(value_path == "remote-ce-id")
{
remote_ce_id.yfilter = yfilter;
}
if(value_path == "evi")
{
evi.yfilter = yfilter;
}
if(value_path == "short-ma-name-format")
{
short_ma_name_format.yfilter = yfilter;
}
if(value_path == "short-ma-name-string")
{
short_ma_name_string.yfilter = yfilter;
}
if(value_path == "short-ma-name-number")
{
short_ma_name_number.yfilter = yfilter;
}
if(value_path == "short-ma-name-oui")
{
short_ma_name_oui.yfilter = yfilter;
}
if(value_path == "short-ma-name-vpn-index")
{
short_ma_name_vpn_index.yfilter = yfilter;
}
if(value_path == "short-ma-name-icc")
{
short_ma_name_icc.yfilter = yfilter;
}
if(value_path == "short-ma-name-umc")
{
short_ma_name_umc.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::Services::Service::ServiceProperties::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "service-type" || name == "group-name" || name == "switching-name" || name == "ce-id" || name == "remote-ce-id" || name == "evi" || name == "short-ma-name-format" || name == "short-ma-name-string" || name == "short-ma-name-number" || name == "short-ma-name-oui" || name == "short-ma-name-vpn-index" || name == "short-ma-name-icc" || name == "short-ma-name-umc")
return true;
return false;
}
EthernetFeatures::Cfm::Domains::Domain::DomainProperties::DomainProperties()
:
level{YType::uint32, "level"},
mdid_format{YType::enumeration, "mdid-format"},
mdid_mac_address{YType::str, "mdid-mac-address"},
mdid_number{YType::uint32, "mdid-number"},
mdid_string{YType::str, "mdid-string"}
{
yang_name = "domain-properties"; yang_parent_name = "domain"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::Cfm::Domains::Domain::DomainProperties::~DomainProperties()
{
}
bool EthernetFeatures::Cfm::Domains::Domain::DomainProperties::has_data() const
{
if (is_presence_container) return true;
return level.is_set
|| mdid_format.is_set
|| mdid_mac_address.is_set
|| mdid_number.is_set
|| mdid_string.is_set;
}
bool EthernetFeatures::Cfm::Domains::Domain::DomainProperties::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(level.yfilter)
|| ydk::is_set(mdid_format.yfilter)
|| ydk::is_set(mdid_mac_address.yfilter)
|| ydk::is_set(mdid_number.yfilter)
|| ydk::is_set(mdid_string.yfilter);
}
std::string EthernetFeatures::Cfm::Domains::Domain::DomainProperties::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "domain-properties";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::Cfm::Domains::Domain::DomainProperties::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (level.is_set || is_set(level.yfilter)) leaf_name_data.push_back(level.get_name_leafdata());
if (mdid_format.is_set || is_set(mdid_format.yfilter)) leaf_name_data.push_back(mdid_format.get_name_leafdata());
if (mdid_mac_address.is_set || is_set(mdid_mac_address.yfilter)) leaf_name_data.push_back(mdid_mac_address.get_name_leafdata());
if (mdid_number.is_set || is_set(mdid_number.yfilter)) leaf_name_data.push_back(mdid_number.get_name_leafdata());
if (mdid_string.is_set || is_set(mdid_string.yfilter)) leaf_name_data.push_back(mdid_string.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::Cfm::Domains::Domain::DomainProperties::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::Cfm::Domains::Domain::DomainProperties::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::Cfm::Domains::Domain::DomainProperties::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "level")
{
level = value;
level.value_namespace = name_space;
level.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mdid-format")
{
mdid_format = value;
mdid_format.value_namespace = name_space;
mdid_format.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mdid-mac-address")
{
mdid_mac_address = value;
mdid_mac_address.value_namespace = name_space;
mdid_mac_address.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mdid-number")
{
mdid_number = value;
mdid_number.value_namespace = name_space;
mdid_number.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mdid-string")
{
mdid_string = value;
mdid_string.value_namespace = name_space;
mdid_string.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::Cfm::Domains::Domain::DomainProperties::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "level")
{
level.yfilter = yfilter;
}
if(value_path == "mdid-format")
{
mdid_format.yfilter = yfilter;
}
if(value_path == "mdid-mac-address")
{
mdid_mac_address.yfilter = yfilter;
}
if(value_path == "mdid-number")
{
mdid_number.yfilter = yfilter;
}
if(value_path == "mdid-string")
{
mdid_string.yfilter = yfilter;
}
}
bool EthernetFeatures::Cfm::Domains::Domain::DomainProperties::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "level" || name == "mdid-format" || name == "mdid-mac-address" || name == "mdid-number" || name == "mdid-string")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::EtherLinkOam()
:
profiles(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles>())
{
profiles->parent = this;
yang_name = "ether-link-oam"; yang_parent_name = "ethernet-features"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::EtherLinkOam::~EtherLinkOam()
{
}
bool EthernetFeatures::EtherLinkOam::has_data() const
{
if (is_presence_container) return true;
return (profiles != nullptr && profiles->has_data());
}
bool EthernetFeatures::EtherLinkOam::has_operation() const
{
return is_set(yfilter)
|| (profiles != nullptr && profiles->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::EtherLinkOam::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ethernet-link-oam-cfg:ether-link-oam";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "profiles")
{
if(profiles == nullptr)
{
profiles = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles>();
}
return profiles;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(profiles != nullptr)
{
_children["profiles"] = profiles;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::EtherLinkOam::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::EtherLinkOam::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "profiles")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profiles()
:
profile(this, {"profile"})
{
yang_name = "profiles"; yang_parent_name = "ether-link-oam"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::EtherLinkOam::Profiles::~Profiles()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<profile.len(); index++)
{
if(profile[index]->has_data())
return true;
}
return false;
}
bool EthernetFeatures::EtherLinkOam::Profiles::has_operation() const
{
for (std::size_t index=0; index<profile.len(); index++)
{
if(profile[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/Cisco-IOS-XR-ethernet-link-oam-cfg:ether-link-oam/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::EtherLinkOam::Profiles::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "profiles";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "profile")
{
auto ent_ = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile>();
ent_->parent = this;
profile.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : profile.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::EtherLinkOam::Profiles::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "profile")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::Profile()
:
profile{YType::str, "profile"},
mib_retrieval{YType::boolean, "mib-retrieval"},
udlf{YType::boolean, "udlf"},
hello_interval{YType::enumeration, "hello-interval"},
mode{YType::enumeration, "mode"},
remote_loopback{YType::boolean, "remote-loopback"},
timeout{YType::uint32, "timeout"}
,
action(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::Action>())
, require_remote(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote>())
, link_monitoring(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring>())
{
action->parent = this;
require_remote->parent = this;
link_monitoring->parent = this;
yang_name = "profile"; yang_parent_name = "profiles"; is_top_level_class = false; has_list_ancestor = false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::~Profile()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::has_data() const
{
if (is_presence_container) return true;
return profile.is_set
|| mib_retrieval.is_set
|| udlf.is_set
|| hello_interval.is_set
|| mode.is_set
|| remote_loopback.is_set
|| timeout.is_set
|| (action != nullptr && action->has_data())
|| (require_remote != nullptr && require_remote->has_data())
|| (link_monitoring != nullptr && link_monitoring->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(profile.yfilter)
|| ydk::is_set(mib_retrieval.yfilter)
|| ydk::is_set(udlf.yfilter)
|| ydk::is_set(hello_interval.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(remote_loopback.yfilter)
|| ydk::is_set(timeout.yfilter)
|| (action != nullptr && action->has_operation())
|| (require_remote != nullptr && require_remote->has_operation())
|| (link_monitoring != nullptr && link_monitoring->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-l2-eth-infra-cfg:ethernet-features/Cisco-IOS-XR-ethernet-link-oam-cfg:ether-link-oam/profiles/" << get_segment_path();
return path_buffer.str();
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "profile";
ADD_KEY_TOKEN(profile, "profile");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata());
if (mib_retrieval.is_set || is_set(mib_retrieval.yfilter)) leaf_name_data.push_back(mib_retrieval.get_name_leafdata());
if (udlf.is_set || is_set(udlf.yfilter)) leaf_name_data.push_back(udlf.get_name_leafdata());
if (hello_interval.is_set || is_set(hello_interval.yfilter)) leaf_name_data.push_back(hello_interval.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (remote_loopback.is_set || is_set(remote_loopback.yfilter)) leaf_name_data.push_back(remote_loopback.get_name_leafdata());
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "action")
{
if(action == nullptr)
{
action = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::Action>();
}
return action;
}
if(child_yang_name == "require-remote")
{
if(require_remote == nullptr)
{
require_remote = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote>();
}
return require_remote;
}
if(child_yang_name == "link-monitoring")
{
if(link_monitoring == nullptr)
{
link_monitoring = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring>();
}
return link_monitoring;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(action != nullptr)
{
_children["action"] = action;
}
if(require_remote != nullptr)
{
_children["require-remote"] = require_remote;
}
if(link_monitoring != nullptr)
{
_children["link-monitoring"] = link_monitoring;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "profile")
{
profile = value;
profile.value_namespace = name_space;
profile.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mib-retrieval")
{
mib_retrieval = value;
mib_retrieval.value_namespace = name_space;
mib_retrieval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "udlf")
{
udlf = value;
udlf.value_namespace = name_space;
udlf.value_namespace_prefix = name_space_prefix;
}
if(value_path == "hello-interval")
{
hello_interval = value;
hello_interval.value_namespace = name_space;
hello_interval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "remote-loopback")
{
remote_loopback = value;
remote_loopback.value_namespace = name_space;
remote_loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "profile")
{
profile.yfilter = yfilter;
}
if(value_path == "mib-retrieval")
{
mib_retrieval.yfilter = yfilter;
}
if(value_path == "udlf")
{
udlf.yfilter = yfilter;
}
if(value_path == "hello-interval")
{
hello_interval.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "remote-loopback")
{
remote_loopback.yfilter = yfilter;
}
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "action" || name == "require-remote" || name == "link-monitoring" || name == "profile" || name == "mib-retrieval" || name == "udlf" || name == "hello-interval" || name == "mode" || name == "remote-loopback" || name == "timeout")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::Action()
:
dying_gasp{YType::enumeration, "dying-gasp"},
session_up{YType::enumeration, "session-up"},
critical_event{YType::enumeration, "critical-event"},
session_down{YType::enumeration, "session-down"},
discovery_timeout{YType::enumeration, "discovery-timeout"},
high_threshold{YType::enumeration, "high-threshold"},
capabilities_conflict{YType::enumeration, "capabilities-conflict"},
remote_loopback{YType::enumeration, "remote-loopback"},
link_fault{YType::enumeration, "link-fault"},
wiring_conflict{YType::enumeration, "wiring-conflict"}
{
yang_name = "action"; yang_parent_name = "profile"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::~Action()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::has_data() const
{
if (is_presence_container) return true;
return dying_gasp.is_set
|| session_up.is_set
|| critical_event.is_set
|| session_down.is_set
|| discovery_timeout.is_set
|| high_threshold.is_set
|| capabilities_conflict.is_set
|| remote_loopback.is_set
|| link_fault.is_set
|| wiring_conflict.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(dying_gasp.yfilter)
|| ydk::is_set(session_up.yfilter)
|| ydk::is_set(critical_event.yfilter)
|| ydk::is_set(session_down.yfilter)
|| ydk::is_set(discovery_timeout.yfilter)
|| ydk::is_set(high_threshold.yfilter)
|| ydk::is_set(capabilities_conflict.yfilter)
|| ydk::is_set(remote_loopback.yfilter)
|| ydk::is_set(link_fault.yfilter)
|| ydk::is_set(wiring_conflict.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "action";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (dying_gasp.is_set || is_set(dying_gasp.yfilter)) leaf_name_data.push_back(dying_gasp.get_name_leafdata());
if (session_up.is_set || is_set(session_up.yfilter)) leaf_name_data.push_back(session_up.get_name_leafdata());
if (critical_event.is_set || is_set(critical_event.yfilter)) leaf_name_data.push_back(critical_event.get_name_leafdata());
if (session_down.is_set || is_set(session_down.yfilter)) leaf_name_data.push_back(session_down.get_name_leafdata());
if (discovery_timeout.is_set || is_set(discovery_timeout.yfilter)) leaf_name_data.push_back(discovery_timeout.get_name_leafdata());
if (high_threshold.is_set || is_set(high_threshold.yfilter)) leaf_name_data.push_back(high_threshold.get_name_leafdata());
if (capabilities_conflict.is_set || is_set(capabilities_conflict.yfilter)) leaf_name_data.push_back(capabilities_conflict.get_name_leafdata());
if (remote_loopback.is_set || is_set(remote_loopback.yfilter)) leaf_name_data.push_back(remote_loopback.get_name_leafdata());
if (link_fault.is_set || is_set(link_fault.yfilter)) leaf_name_data.push_back(link_fault.get_name_leafdata());
if (wiring_conflict.is_set || is_set(wiring_conflict.yfilter)) leaf_name_data.push_back(wiring_conflict.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "dying-gasp")
{
dying_gasp = value;
dying_gasp.value_namespace = name_space;
dying_gasp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "session-up")
{
session_up = value;
session_up.value_namespace = name_space;
session_up.value_namespace_prefix = name_space_prefix;
}
if(value_path == "critical-event")
{
critical_event = value;
critical_event.value_namespace = name_space;
critical_event.value_namespace_prefix = name_space_prefix;
}
if(value_path == "session-down")
{
session_down = value;
session_down.value_namespace = name_space;
session_down.value_namespace_prefix = name_space_prefix;
}
if(value_path == "discovery-timeout")
{
discovery_timeout = value;
discovery_timeout.value_namespace = name_space;
discovery_timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "high-threshold")
{
high_threshold = value;
high_threshold.value_namespace = name_space;
high_threshold.value_namespace_prefix = name_space_prefix;
}
if(value_path == "capabilities-conflict")
{
capabilities_conflict = value;
capabilities_conflict.value_namespace = name_space;
capabilities_conflict.value_namespace_prefix = name_space_prefix;
}
if(value_path == "remote-loopback")
{
remote_loopback = value;
remote_loopback.value_namespace = name_space;
remote_loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link-fault")
{
link_fault = value;
link_fault.value_namespace = name_space;
link_fault.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wiring-conflict")
{
wiring_conflict = value;
wiring_conflict.value_namespace = name_space;
wiring_conflict.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "dying-gasp")
{
dying_gasp.yfilter = yfilter;
}
if(value_path == "session-up")
{
session_up.yfilter = yfilter;
}
if(value_path == "critical-event")
{
critical_event.yfilter = yfilter;
}
if(value_path == "session-down")
{
session_down.yfilter = yfilter;
}
if(value_path == "discovery-timeout")
{
discovery_timeout.yfilter = yfilter;
}
if(value_path == "high-threshold")
{
high_threshold.yfilter = yfilter;
}
if(value_path == "capabilities-conflict")
{
capabilities_conflict.yfilter = yfilter;
}
if(value_path == "remote-loopback")
{
remote_loopback.yfilter = yfilter;
}
if(value_path == "link-fault")
{
link_fault.yfilter = yfilter;
}
if(value_path == "wiring-conflict")
{
wiring_conflict.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::Action::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dying-gasp" || name == "session-up" || name == "critical-event" || name == "session-down" || name == "discovery-timeout" || name == "high-threshold" || name == "capabilities-conflict" || name == "remote-loopback" || name == "link-fault" || name == "wiring-conflict")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::RequireRemote()
:
mib_retrieval{YType::boolean, "mib-retrieval"},
mode{YType::enumeration, "mode"},
remote_loopback{YType::boolean, "remote-loopback"},
link_monitoring{YType::boolean, "link-monitoring"}
{
yang_name = "require-remote"; yang_parent_name = "profile"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::~RequireRemote()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::has_data() const
{
if (is_presence_container) return true;
return mib_retrieval.is_set
|| mode.is_set
|| remote_loopback.is_set
|| link_monitoring.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(mib_retrieval.yfilter)
|| ydk::is_set(mode.yfilter)
|| ydk::is_set(remote_loopback.yfilter)
|| ydk::is_set(link_monitoring.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "require-remote";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (mib_retrieval.is_set || is_set(mib_retrieval.yfilter)) leaf_name_data.push_back(mib_retrieval.get_name_leafdata());
if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata());
if (remote_loopback.is_set || is_set(remote_loopback.yfilter)) leaf_name_data.push_back(remote_loopback.get_name_leafdata());
if (link_monitoring.is_set || is_set(link_monitoring.yfilter)) leaf_name_data.push_back(link_monitoring.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "mib-retrieval")
{
mib_retrieval = value;
mib_retrieval.value_namespace = name_space;
mib_retrieval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mode")
{
mode = value;
mode.value_namespace = name_space;
mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "remote-loopback")
{
remote_loopback = value;
remote_loopback.value_namespace = name_space;
remote_loopback.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link-monitoring")
{
link_monitoring = value;
link_monitoring.value_namespace = name_space;
link_monitoring.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "mib-retrieval")
{
mib_retrieval.yfilter = yfilter;
}
if(value_path == "mode")
{
mode.yfilter = yfilter;
}
if(value_path == "remote-loopback")
{
remote_loopback.yfilter = yfilter;
}
if(value_path == "link-monitoring")
{
link_monitoring.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::RequireRemote::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "mib-retrieval" || name == "mode" || name == "remote-loopback" || name == "link-monitoring")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::LinkMonitoring()
:
monitoring{YType::boolean, "monitoring"}
,
symbol_period(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod>())
, frame_period(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod>())
, frame_seconds(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds>())
, frame(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame>())
{
symbol_period->parent = this;
frame_period->parent = this;
frame_seconds->parent = this;
frame->parent = this;
yang_name = "link-monitoring"; yang_parent_name = "profile"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::~LinkMonitoring()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::has_data() const
{
if (is_presence_container) return true;
return monitoring.is_set
|| (symbol_period != nullptr && symbol_period->has_data())
|| (frame_period != nullptr && frame_period->has_data())
|| (frame_seconds != nullptr && frame_seconds->has_data())
|| (frame != nullptr && frame->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(monitoring.yfilter)
|| (symbol_period != nullptr && symbol_period->has_operation())
|| (frame_period != nullptr && frame_period->has_operation())
|| (frame_seconds != nullptr && frame_seconds->has_operation())
|| (frame != nullptr && frame->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "link-monitoring";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (monitoring.is_set || is_set(monitoring.yfilter)) leaf_name_data.push_back(monitoring.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "symbol-period")
{
if(symbol_period == nullptr)
{
symbol_period = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod>();
}
return symbol_period;
}
if(child_yang_name == "frame-period")
{
if(frame_period == nullptr)
{
frame_period = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod>();
}
return frame_period;
}
if(child_yang_name == "frame-seconds")
{
if(frame_seconds == nullptr)
{
frame_seconds = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds>();
}
return frame_seconds;
}
if(child_yang_name == "frame")
{
if(frame == nullptr)
{
frame = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame>();
}
return frame;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(symbol_period != nullptr)
{
_children["symbol-period"] = symbol_period;
}
if(frame_period != nullptr)
{
_children["frame-period"] = frame_period;
}
if(frame_seconds != nullptr)
{
_children["frame-seconds"] = frame_seconds;
}
if(frame != nullptr)
{
_children["frame"] = frame;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "monitoring")
{
monitoring = value;
monitoring.value_namespace = name_space;
monitoring.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "monitoring")
{
monitoring.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "symbol-period" || name == "frame-period" || name == "frame-seconds" || name == "frame" || name == "monitoring")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::SymbolPeriod()
:
window(nullptr) // presence node
, threshold(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold>())
{
threshold->parent = this;
yang_name = "symbol-period"; yang_parent_name = "link-monitoring"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::~SymbolPeriod()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::has_data() const
{
if (is_presence_container) return true;
return (window != nullptr && window->has_data())
|| (threshold != nullptr && threshold->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::has_operation() const
{
return is_set(yfilter)
|| (window != nullptr && window->has_operation())
|| (threshold != nullptr && threshold->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "symbol-period";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "window")
{
if(window == nullptr)
{
window = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window>();
}
return window;
}
if(child_yang_name == "threshold")
{
if(threshold == nullptr)
{
threshold = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold>();
}
return threshold;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(window != nullptr)
{
_children["window"] = window;
}
if(threshold != nullptr)
{
_children["threshold"] = threshold;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "window" || name == "threshold")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::Window()
:
window{YType::uint32, "window"},
units{YType::enumeration, "units"},
multiplier{YType::enumeration, "multiplier"}
{
yang_name = "window"; yang_parent_name = "symbol-period"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::~Window()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::has_data() const
{
if (is_presence_container) return true;
return window.is_set
|| units.is_set
|| multiplier.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(window.yfilter)
|| ydk::is_set(units.yfilter)
|| ydk::is_set(multiplier.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "window";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (window.is_set || is_set(window.yfilter)) leaf_name_data.push_back(window.get_name_leafdata());
if (units.is_set || is_set(units.yfilter)) leaf_name_data.push_back(units.get_name_leafdata());
if (multiplier.is_set || is_set(multiplier.yfilter)) leaf_name_data.push_back(multiplier.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "window")
{
window = value;
window.value_namespace = name_space;
window.value_namespace_prefix = name_space_prefix;
}
if(value_path == "units")
{
units = value;
units.value_namespace = name_space;
units.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier")
{
multiplier = value;
multiplier.value_namespace = name_space;
multiplier.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "window")
{
window.yfilter = yfilter;
}
if(value_path == "units")
{
units.yfilter = yfilter;
}
if(value_path == "multiplier")
{
multiplier.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Window::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "window" || name == "units" || name == "multiplier")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::Threshold()
:
threshold_low{YType::uint32, "threshold-low"},
threshold_high{YType::uint32, "threshold-high"},
units{YType::enumeration, "units"},
multiplier_low{YType::enumeration, "multiplier-low"},
multiplier_high{YType::enumeration, "multiplier-high"}
{
yang_name = "threshold"; yang_parent_name = "symbol-period"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::~Threshold()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::has_data() const
{
if (is_presence_container) return true;
return threshold_low.is_set
|| threshold_high.is_set
|| units.is_set
|| multiplier_low.is_set
|| multiplier_high.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(threshold_low.yfilter)
|| ydk::is_set(threshold_high.yfilter)
|| ydk::is_set(units.yfilter)
|| ydk::is_set(multiplier_low.yfilter)
|| ydk::is_set(multiplier_high.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "threshold";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (threshold_low.is_set || is_set(threshold_low.yfilter)) leaf_name_data.push_back(threshold_low.get_name_leafdata());
if (threshold_high.is_set || is_set(threshold_high.yfilter)) leaf_name_data.push_back(threshold_high.get_name_leafdata());
if (units.is_set || is_set(units.yfilter)) leaf_name_data.push_back(units.get_name_leafdata());
if (multiplier_low.is_set || is_set(multiplier_low.yfilter)) leaf_name_data.push_back(multiplier_low.get_name_leafdata());
if (multiplier_high.is_set || is_set(multiplier_high.yfilter)) leaf_name_data.push_back(multiplier_high.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "threshold-low")
{
threshold_low = value;
threshold_low.value_namespace = name_space;
threshold_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "threshold-high")
{
threshold_high = value;
threshold_high.value_namespace = name_space;
threshold_high.value_namespace_prefix = name_space_prefix;
}
if(value_path == "units")
{
units = value;
units.value_namespace = name_space;
units.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-low")
{
multiplier_low = value;
multiplier_low.value_namespace = name_space;
multiplier_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-high")
{
multiplier_high = value;
multiplier_high.value_namespace = name_space;
multiplier_high.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "threshold-low")
{
threshold_low.yfilter = yfilter;
}
if(value_path == "threshold-high")
{
threshold_high.yfilter = yfilter;
}
if(value_path == "units")
{
units.yfilter = yfilter;
}
if(value_path == "multiplier-low")
{
multiplier_low.yfilter = yfilter;
}
if(value_path == "multiplier-high")
{
multiplier_high.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::SymbolPeriod::Threshold::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold-low" || name == "threshold-high" || name == "units" || name == "multiplier-low" || name == "multiplier-high")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::FramePeriod()
:
window(nullptr) // presence node
, threshold(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold>())
{
threshold->parent = this;
yang_name = "frame-period"; yang_parent_name = "link-monitoring"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::~FramePeriod()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::has_data() const
{
if (is_presence_container) return true;
return (window != nullptr && window->has_data())
|| (threshold != nullptr && threshold->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::has_operation() const
{
return is_set(yfilter)
|| (window != nullptr && window->has_operation())
|| (threshold != nullptr && threshold->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "frame-period";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "window")
{
if(window == nullptr)
{
window = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window>();
}
return window;
}
if(child_yang_name == "threshold")
{
if(threshold == nullptr)
{
threshold = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold>();
}
return threshold;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(window != nullptr)
{
_children["window"] = window;
}
if(threshold != nullptr)
{
_children["threshold"] = threshold;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "window" || name == "threshold")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::Window()
:
window{YType::uint32, "window"},
units{YType::enumeration, "units"},
multiplier{YType::enumeration, "multiplier"}
{
yang_name = "window"; yang_parent_name = "frame-period"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::~Window()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::has_data() const
{
if (is_presence_container) return true;
return window.is_set
|| units.is_set
|| multiplier.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(window.yfilter)
|| ydk::is_set(units.yfilter)
|| ydk::is_set(multiplier.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "window";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (window.is_set || is_set(window.yfilter)) leaf_name_data.push_back(window.get_name_leafdata());
if (units.is_set || is_set(units.yfilter)) leaf_name_data.push_back(units.get_name_leafdata());
if (multiplier.is_set || is_set(multiplier.yfilter)) leaf_name_data.push_back(multiplier.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "window")
{
window = value;
window.value_namespace = name_space;
window.value_namespace_prefix = name_space_prefix;
}
if(value_path == "units")
{
units = value;
units.value_namespace = name_space;
units.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier")
{
multiplier = value;
multiplier.value_namespace = name_space;
multiplier.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "window")
{
window.yfilter = yfilter;
}
if(value_path == "units")
{
units.yfilter = yfilter;
}
if(value_path == "multiplier")
{
multiplier.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Window::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "window" || name == "units" || name == "multiplier")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::Threshold()
:
threshold_low{YType::uint32, "threshold-low"},
threshold_high{YType::uint32, "threshold-high"},
units{YType::enumeration, "units"},
multiplier_low{YType::enumeration, "multiplier-low"},
multiplier_high{YType::enumeration, "multiplier-high"}
{
yang_name = "threshold"; yang_parent_name = "frame-period"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::~Threshold()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::has_data() const
{
if (is_presence_container) return true;
return threshold_low.is_set
|| threshold_high.is_set
|| units.is_set
|| multiplier_low.is_set
|| multiplier_high.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(threshold_low.yfilter)
|| ydk::is_set(threshold_high.yfilter)
|| ydk::is_set(units.yfilter)
|| ydk::is_set(multiplier_low.yfilter)
|| ydk::is_set(multiplier_high.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "threshold";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (threshold_low.is_set || is_set(threshold_low.yfilter)) leaf_name_data.push_back(threshold_low.get_name_leafdata());
if (threshold_high.is_set || is_set(threshold_high.yfilter)) leaf_name_data.push_back(threshold_high.get_name_leafdata());
if (units.is_set || is_set(units.yfilter)) leaf_name_data.push_back(units.get_name_leafdata());
if (multiplier_low.is_set || is_set(multiplier_low.yfilter)) leaf_name_data.push_back(multiplier_low.get_name_leafdata());
if (multiplier_high.is_set || is_set(multiplier_high.yfilter)) leaf_name_data.push_back(multiplier_high.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "threshold-low")
{
threshold_low = value;
threshold_low.value_namespace = name_space;
threshold_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "threshold-high")
{
threshold_high = value;
threshold_high.value_namespace = name_space;
threshold_high.value_namespace_prefix = name_space_prefix;
}
if(value_path == "units")
{
units = value;
units.value_namespace = name_space;
units.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-low")
{
multiplier_low = value;
multiplier_low.value_namespace = name_space;
multiplier_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-high")
{
multiplier_high = value;
multiplier_high.value_namespace = name_space;
multiplier_high.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "threshold-low")
{
threshold_low.yfilter = yfilter;
}
if(value_path == "threshold-high")
{
threshold_high.yfilter = yfilter;
}
if(value_path == "units")
{
units.yfilter = yfilter;
}
if(value_path == "multiplier-low")
{
multiplier_low.yfilter = yfilter;
}
if(value_path == "multiplier-high")
{
multiplier_high.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FramePeriod::Threshold::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold-low" || name == "threshold-high" || name == "units" || name == "multiplier-low" || name == "multiplier-high")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::FrameSeconds()
:
window{YType::uint32, "window"}
,
threshold(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold>())
{
threshold->parent = this;
yang_name = "frame-seconds"; yang_parent_name = "link-monitoring"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::~FrameSeconds()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::has_data() const
{
if (is_presence_container) return true;
return window.is_set
|| (threshold != nullptr && threshold->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(window.yfilter)
|| (threshold != nullptr && threshold->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "frame-seconds";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (window.is_set || is_set(window.yfilter)) leaf_name_data.push_back(window.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "threshold")
{
if(threshold == nullptr)
{
threshold = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold>();
}
return threshold;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(threshold != nullptr)
{
_children["threshold"] = threshold;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "window")
{
window = value;
window.value_namespace = name_space;
window.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "window")
{
window.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold" || name == "window")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::Threshold()
:
threshold_low{YType::uint32, "threshold-low"},
threshold_high{YType::uint32, "threshold-high"}
{
yang_name = "threshold"; yang_parent_name = "frame-seconds"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::~Threshold()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::has_data() const
{
if (is_presence_container) return true;
return threshold_low.is_set
|| threshold_high.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(threshold_low.yfilter)
|| ydk::is_set(threshold_high.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "threshold";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (threshold_low.is_set || is_set(threshold_low.yfilter)) leaf_name_data.push_back(threshold_low.get_name_leafdata());
if (threshold_high.is_set || is_set(threshold_high.yfilter)) leaf_name_data.push_back(threshold_high.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "threshold-low")
{
threshold_low = value;
threshold_low.value_namespace = name_space;
threshold_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "threshold-high")
{
threshold_high = value;
threshold_high.value_namespace = name_space;
threshold_high.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "threshold-low")
{
threshold_low.yfilter = yfilter;
}
if(value_path == "threshold-high")
{
threshold_high.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::FrameSeconds::Threshold::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold-low" || name == "threshold-high")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Frame()
:
window{YType::uint32, "window"}
,
threshold(std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold>())
{
threshold->parent = this;
yang_name = "frame"; yang_parent_name = "link-monitoring"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::~Frame()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::has_data() const
{
if (is_presence_container) return true;
return window.is_set
|| (threshold != nullptr && threshold->has_data());
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(window.yfilter)
|| (threshold != nullptr && threshold->has_operation());
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "frame";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (window.is_set || is_set(window.yfilter)) leaf_name_data.push_back(window.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "threshold")
{
if(threshold == nullptr)
{
threshold = std::make_shared<EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold>();
}
return threshold;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(threshold != nullptr)
{
_children["threshold"] = threshold;
}
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "window")
{
window = value;
window.value_namespace = name_space;
window.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "window")
{
window.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold" || name == "window")
return true;
return false;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::Threshold()
:
threshold_low{YType::uint32, "threshold-low"},
threshold_high{YType::uint32, "threshold-high"},
multiplier_low{YType::enumeration, "multiplier-low"},
multiplier_high{YType::enumeration, "multiplier-high"}
{
yang_name = "threshold"; yang_parent_name = "frame"; is_top_level_class = false; has_list_ancestor = true;
}
EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::~Threshold()
{
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::has_data() const
{
if (is_presence_container) return true;
return threshold_low.is_set
|| threshold_high.is_set
|| multiplier_low.is_set
|| multiplier_high.is_set;
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(threshold_low.yfilter)
|| ydk::is_set(threshold_high.yfilter)
|| ydk::is_set(multiplier_low.yfilter)
|| ydk::is_set(multiplier_high.yfilter);
}
std::string EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "threshold";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (threshold_low.is_set || is_set(threshold_low.yfilter)) leaf_name_data.push_back(threshold_low.get_name_leafdata());
if (threshold_high.is_set || is_set(threshold_high.yfilter)) leaf_name_data.push_back(threshold_high.get_name_leafdata());
if (multiplier_low.is_set || is_set(multiplier_low.yfilter)) leaf_name_data.push_back(multiplier_low.get_name_leafdata());
if (multiplier_high.is_set || is_set(multiplier_high.yfilter)) leaf_name_data.push_back(multiplier_high.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "threshold-low")
{
threshold_low = value;
threshold_low.value_namespace = name_space;
threshold_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "threshold-high")
{
threshold_high = value;
threshold_high.value_namespace = name_space;
threshold_high.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-low")
{
multiplier_low = value;
multiplier_low.value_namespace = name_space;
multiplier_low.value_namespace_prefix = name_space_prefix;
}
if(value_path == "multiplier-high")
{
multiplier_high = value;
multiplier_high.value_namespace = name_space;
multiplier_high.value_namespace_prefix = name_space_prefix;
}
}
void EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "threshold-low")
{
threshold_low.yfilter = yfilter;
}
if(value_path == "threshold-high")
{
threshold_high.yfilter = yfilter;
}
if(value_path == "multiplier-low")
{
multiplier_low.yfilter = yfilter;
}
if(value_path == "multiplier-high")
{
multiplier_high.yfilter = yfilter;
}
}
bool EthernetFeatures::EtherLinkOam::Profiles::Profile::LinkMonitoring::Frame::Threshold::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "threshold-low" || name == "threshold-high" || name == "multiplier-low" || name == "multiplier-high")
return true;
return false;
}
const Enum::YLeaf EgressFiltering::egress_filtering_type_strict {1, "egress-filtering-type-strict"};
const Enum::YLeaf EgressFiltering::egress_filtering_type_disable {2, "egress-filtering-type-disable"};
const Enum::YLeaf EgressFiltering::egress_filtering_type_default {3, "egress-filtering-type-default"};
const Enum::YLeaf L2ProtocolName::cdp {0, "cdp"};
const Enum::YLeaf L2ProtocolName::stp {1, "stp"};
const Enum::YLeaf L2ProtocolName::vtp {2, "vtp"};
const Enum::YLeaf L2ProtocolName::pvst {3, "pvst"};
const Enum::YLeaf L2ProtocolName::cpsv {4, "cpsv"};
const Enum::YLeaf Filtering::filtering_type_dot1q {0, "filtering-type-dot1q"};
const Enum::YLeaf Filtering::filtering_type_dot1ad {1, "filtering-type-dot1ad"};
const Enum::YLeaf L2ProtocolMode::forward {0, "forward"};
const Enum::YLeaf L2ProtocolMode::drop {1, "drop"};
const Enum::YLeaf L2ProtocolMode::tunnel {2, "tunnel"};
const Enum::YLeaf L2ProtocolMode::reverse_tunnel {3, "reverse-tunnel"};
}
}
| 34.295487 | 492 | 0.706927 | [
"vector"
] |
d59a9efb1b1958556970f63572ecff6b40bf07d0 | 595 | hpp | C++ | 001/myvector.hpp | suomesta/myvector | 60a1844976b4d469d8115755f0e404ba6b0e173e | [
"MIT"
] | null | null | null | 001/myvector.hpp | suomesta/myvector | 60a1844976b4d469d8115755f0e404ba6b0e173e | [
"MIT"
] | null | null | null | 001/myvector.hpp | suomesta/myvector | 60a1844976b4d469d8115755f0e404ba6b0e173e | [
"MIT"
] | null | null | null | /**
* @file myvector.hpp
* @brief Implementation of myvector class.
* myvector class imitates std::vector.
* @author toda
* @date 2019-05-06
* @version 0.1.0
* @remark the target is C++11 or more.
*/
#ifndef INCLUDE_GUARD_MYVECTOR_HPP
#define INCLUDE_GUARD_MYVECTOR_HPP
/**
* @class myvector
* @brief myvector is a class which imitates std::vector.
* @tparam T: The type of the elements.
*/
template <typename T>
class myvector
{
};
/////////////////////////////////////////////////////////////////////////////
#endif // #ifndef INCLUDE_GUARD_MYVECTOR_HPP
| 22.884615 | 77 | 0.589916 | [
"vector"
] |
d59ada2077e784fe3543573f00560d3aa7227b08 | 1,772 | cpp | C++ | jogo_nave_cpp/uteis.cpp | eduardo-amaro-maciel/C- | fe5bbc126004f77422989ee6174686fdd47f9bf3 | [
"MIT"
] | null | null | null | jogo_nave_cpp/uteis.cpp | eduardo-amaro-maciel/C- | fe5bbc126004f77422989ee6174686fdd47f9bf3 | [
"MIT"
] | null | null | null | jogo_nave_cpp/uteis.cpp | eduardo-amaro-maciel/C- | fe5bbc126004f77422989ee6174686fdd47f9bf3 | [
"MIT"
] | null | null | null | #include <iostream>
#include "uteis.h"
#include <SDL2/SDL.h>
#include <ctime>
using namespace std;
SDL_Texture* LoadBMP(const char* img, SDL_Renderer* render)
{
SDL_Surface* backGround = SDL_LoadBMP(img);
if (!backGround)
{
cout << SDL_GetError() << endl;;
return nullptr;
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(render, backGround);
SDL_FreeSurface(backGround);
return texture;
}
bool colisao(SDL_Rect* a, SDL_Rect* b)
{
if(a->x+14 > b->x + b->w || a->x + a->w < b->x+14 || a->y+10 > b->y + b->h || a->y + a->h < b->y+10)
{
return false;
}
return true;
}
int geraPosicaoAleatoriaMeteoro(SDL_Rect* destinoInimigo1, SDL_Rect* destinoInimigo2, bool twoMeteor)
{
int maior = 400;
bool colisa = true;
int separador = 0;
if (twoMeteor)
{
while (colisa)
{
colisa = colisao(destinoInimigo1, destinoInimigo2);
separador += 4;
}
return separador;
}
else
{
return rand()%(maior-100) + 100;
}
}
int geraTamanhoAleatoriaMeteoro()
{
int maior = 60;
int menor = 100;
return rand()%(maior-menor+1) + menor;
}
int verificaBordasDoMapa_X(SDL_Rect* destinoAliado, int positionX)
{
if (destinoAliado->x < 0)
{
return positionX = 0;
}
else if (destinoAliado->x > 445)
{
return positionX = 445;
}
return positionX;
}
int verificaBordasDoMapa_Y(SDL_Rect* destinoAliado, int positionY)
{
if (destinoAliado->y < 0)
{
positionY = 0;
}
else if (destinoAliado->y > 425)
{
positionY = 425;
}
return positionY;
}
| 19.472527 | 105 | 0.555869 | [
"render"
] |
d59b60f05c24ee37b6b1d844de496a30bd4d9d21 | 1,663 | hpp | C++ | src/graphics/GraphicsManager.hpp | cstegel/opengl-fireworks | 5acc2e2e937cae632bf2cf8074d209ea22d719c8 | [
"MIT"
] | 1 | 2017-10-09T06:56:17.000Z | 2017-10-09T06:56:17.000Z | src/graphics/GraphicsManager.hpp | cstegel/opengl-fireworks | 5acc2e2e937cae632bf2cf8074d209ea22d719c8 | [
"MIT"
] | null | null | null | src/graphics/GraphicsManager.hpp | cstegel/opengl-fireworks | 5acc2e2e937cae632bf2cf8074d209ea22d719c8 | [
"MIT"
] | null | null | null | #pragma once
// NO INCLUDES BEFORE THIS SO WE GUARANTEE glew is included before glfw
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <Ecs.hh>
#include "Common.hpp"
#include "graphics/Renderer.hpp"
#include "graphics/Model.hpp"
#include "graphics/DisplayMode.hpp"
#include "graphics/RenderFeature.hpp"
#include "graphics/RenderStage.hpp"
#include "core/InputManager.hpp"
#include "core/AssetManager.hpp"
namespace fw
{
class Game;
class RenderContext;
class GraphicsManager
{
public:
GraphicsManager(Game &game);
~GraphicsManager();
bool Frame();
bool ShouldClose() const;
uint GetWindowWidth() const;
uint GetWindowHeight() const;
/**
* Sets the entity to be used when rendering the player's view.
* This entity must have a "View" component.
*/
void SetPlayerView(ecs::Entity playerView);
void BindInputCallbacks(InputManager & inputManager);
static string GetShaderPath(const string & filename);
Model & GetModel(string name);
Model & GetLightModel();
DisplayMode GetDisplayMode() const;
void SetDisplayMode(DisplayMode mode);
// returns if the feature was toggled to "enabled"
void ToggleRenderFeature(RenderFeature feature, bool enabled);
bool IsRenderFeatureEnabled(RenderFeature feature) const;
double GetRenderStageAvgTime(RenderStage stage) const;
Game & game;
private:
static const string LIGHT_MODEL;
void throwIfNotValidContext() const;
void loadModels();
shared_ptr<RenderContext> renderContext;
shared_ptr<Renderer> renderer;
unordered_map<string, Model> models;
double lastFrameEnd;
double fpsTimer;
uint32_t frameCounter = 0;
};
} | 22.780822 | 71 | 0.748046 | [
"model"
] |
d5aa6a0cc329a936fab6b19e02a1755136ccf7ff | 9,025 | cpp | C++ | apps/foundation_test/rftype_typetraverser.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | 3 | 2019-10-27T22:32:44.000Z | 2020-05-21T04:00:46.000Z | apps/foundation_test/rftype_typetraverser.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | apps/foundation_test/rftype_typetraverser.cpp | max-delta/retrofit-public | 5447fd6399fd74ffbb75494c103940751000db12 | [
"X11"
] | null | null | null | #include "stdafx.h"
// TODO: Remove dependency on Example.h, and move these tests to core tests
#include "RFType/Example.h"
#include "core_rftype/TypeTraverser.h"
#include "rftl/unordered_set"
namespace RF::rftype {
///////////////////////////////////////////////////////////////////////////////
void EnsureAllFunctionsFound( rftl::unordered_set<void const*> expectedLocations, rftl::vector<TypeTraverser::MemberVariableInstance> const& members )
{
ASSERT_EQ( expectedLocations.size(), members.size() );
for( TypeTraverser::MemberVariableInstance const& varInst : members )
{
void const* const varLoc = varInst.mMemberVariableLocation;
ASSERT_TRUE( expectedLocations.count( varLoc ) == 1 );
expectedLocations.erase( varLoc );
}
ASSERT_EQ( expectedLocations.size(), 0 );
}
void EnsureAllFunctionsFound( rftl::vector<void const*> expectedLocations, rftl::vector<TypeTraverser::MemberVariableInstance> const& members )
{
ASSERT_EQ( expectedLocations.size(), members.size() );
for( TypeTraverser::MemberVariableInstance const& varInst : members )
{
void const* const varLoc = varInst.mMemberVariableLocation;
bool found = false;
for( rftl::vector<void const*>::const_iterator iter = expectedLocations.begin(); iter != expectedLocations.end(); iter++ )
{
if( *iter == varLoc )
{
found = true;
expectedLocations.erase( iter );
break;
}
}
ASSERT_TRUE( found );
}
ASSERT_EQ( expectedLocations.size(), 0 );
}
TEST( RFType, TraverseSingleInheritance )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
rftype_example::ExampleDerivedClass classInstance;
TypeTraverser::TraverseVariablesT(
*classInstance.GetVirtualClassInfo(),
&classInstance,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 0 );
ASSERT_EQ( depth, 0 );
rftl::unordered_set<void const*> expectedLocations = {
&classInstance.mExampleNonStaticVariable,
&classInstance.mExampleDerivedNonStaticVariable };
EnsureAllFunctionsFound( expectedLocations, members );
}
TEST( RFType, TraverseNullSingleInheritance )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
TypeTraverser::TraverseVariablesT(
GetClassInfo<rftype_example::ExampleDerivedClass>(),
nullptr,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 0 );
ASSERT_EQ( depth, 0 );
}
TEST( RFType, TraverseMultipleInheritance )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
rftype_example::ExamplePoorLifeDecision classInstance;
TypeTraverser::TraverseVariablesT(
*classInstance.GetVirtualClassInfo(),
&classInstance,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 0 );
ASSERT_EQ( depth, 0 );
rftl::unordered_set<void const*> expectedLocations = {
&classInstance.mExampleNonStaticVariable,
&classInstance.mExampleSecondaryNonStaticVariable };
EnsureAllFunctionsFound( expectedLocations, members );
}
TEST( RFType, TraverseNullMultipleInheritance )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
TypeTraverser::TraverseVariablesT(
GetClassInfo<rftype_example::ExamplePoorLifeDecision>(),
nullptr,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 0 );
ASSERT_EQ( depth, 0 );
}
TEST( RFType, TraverseNesting )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
rftype_example::ExampleWithClassAsMember classInstance;
TypeTraverser::TraverseVariablesT(
GetClassInfo<rftype_example::ExampleWithClassAsMember>(),
&classInstance,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 1 );
ASSERT_EQ( depth, 0 );
rftl::vector<void const*> expectedLocations = {
&classInstance.mExampleClassAsMember,
&classInstance.mExampleClassAsMember.mExampleNonStaticVariable };
EnsureAllFunctionsFound( expectedLocations, members );
}
TEST( RFType, TraverseNullNesting )
{
rftl::vector<TypeTraverser::MemberVariableInstance> members;
auto onMemberVariableFunc = [&members](
TypeTraverser::MemberVariableInstance const& varInst ) ->
void
{
members.emplace_back( varInst );
};
rftl::vector<TypeTraverser::TraversalVariableInstance> nested;
size_t depth = 0;
auto onNestedTypeFoundFunc = [&nested, &depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst,
bool& shouldRecurse ) ->
void
{
nested.emplace_back( varInst );
shouldRecurse = true;
depth++;
};
auto onReturnFromNestedTypeFunc = [&depth](
TypeTraverser::TraversalType traversalType,
TypeTraverser::TraversalVariableInstance const& varInst ) ->
void
{
depth--;
};
TypeTraverser::TraverseVariablesT(
GetClassInfo<rftype_example::ExampleWithClassAsMember>(),
nullptr,
onMemberVariableFunc,
onNestedTypeFoundFunc,
onReturnFromNestedTypeFunc );
ASSERT_EQ( members.size(), 2 );
ASSERT_EQ( nested.size(), 1 );
ASSERT_EQ( depth, 0 );
}
TEST( RFType, TraverseVecInts )
{
// TODO
}
TEST( RFType, TraverseNullVecInts )
{
// TODO
}
TEST( RFType, TraverseVecNested )
{
// TODO
}
TEST( RFType, TraverseNullVecNested )
{
// TODO
}
TEST( RFType, TraverseVecVecInts )
{
// TODO
}
TEST( RFType, TraverseNullVecVecInts )
{
// TODO
}
///////////////////////////////////////////////////////////////////////////////
}
| 24.066667 | 150 | 0.735512 | [
"vector"
] |
d5b78c21229554fab88f31f13ae2556fd8299408 | 4,238 | cpp | C++ | Linux/Samples/TestPattern/VideoFrame3D.cpp | EncovGroup/DecklinkSDK | 61a2fff5e54720a2acdae4afbf78818cf7cbd269 | [
"BSL-1.0"
] | 1 | 2019-06-19T02:02:07.000Z | 2019-06-19T02:02:07.000Z | Linux/Samples/TestPattern/VideoFrame3D.cpp | EncovGroup/DecklinkSDK | 61a2fff5e54720a2acdae4afbf78818cf7cbd269 | [
"BSL-1.0"
] | null | null | null | Linux/Samples/TestPattern/VideoFrame3D.cpp | EncovGroup/DecklinkSDK | 61a2fff5e54720a2acdae4afbf78818cf7cbd269 | [
"BSL-1.0"
] | null | null | null | /* -LICENSE-START-
** Copyright (c) 2013 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "VideoFrame3D.h"
static inline bool CompareREFIID(const REFIID& ref1, const REFIID& ref2)
{
return memcmp(&ref1, &ref2, sizeof(REFIID)) == 0;
}
static inline int OSAtomicIncrement32(volatile int *valPtr)
{
// gcc atomic operation builtin
return __sync_add_and_fetch(valPtr, 1);
}
static inline int OSAtomicDecrement32(volatile int *valPtr)
{
// gcc atomic operation builtin
return __sync_sub_and_fetch(valPtr, 1);
}
// IUnknown methods
HRESULT VideoFrame3D::QueryInterface(REFIID iid, LPVOID *ppv)
{
if (CompareREFIID(iid, IID_IUnknown))
*ppv = static_cast<IDeckLinkVideoFrame*>(this);
else if (CompareREFIID(iid, IID_IDeckLinkVideoFrame))
*ppv = static_cast<IDeckLinkVideoFrame*>(this);
else if (CompareREFIID(iid, IID_IDeckLinkVideoFrame3DExtensions))
*ppv = static_cast<IDeckLinkVideoFrame3DExtensions*>(this);
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
ULONG VideoFrame3D::AddRef(void)
{
return OSAtomicIncrement32(&m_refCount);
}
ULONG VideoFrame3D::Release(void)
{
ULONG newRefValue = OSAtomicDecrement32(&m_refCount);
if (!newRefValue)
delete this;
return newRefValue;
}
// IDeckLinkVideoFrame methods
long VideoFrame3D::GetWidth(void)
{
return m_frameLeft->GetWidth();
}
long VideoFrame3D::GetHeight(void)
{
return m_frameLeft->GetHeight();
}
long VideoFrame3D::GetRowBytes(void)
{
return m_frameLeft->GetRowBytes();
}
BMDPixelFormat VideoFrame3D::GetPixelFormat(void)
{
return m_frameLeft->GetPixelFormat();
}
BMDFrameFlags VideoFrame3D::GetFlags(void)
{
return m_frameLeft->GetFlags();
}
HRESULT VideoFrame3D::GetBytes(void** buffer)
{
return m_frameLeft->GetBytes(buffer);
}
HRESULT VideoFrame3D::GetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode** timecode)
{
return m_frameLeft->GetTimecode(format, timecode);
}
HRESULT VideoFrame3D::GetAncillaryData(IDeckLinkVideoFrameAncillary** ancillary)
{
return m_frameLeft->GetAncillaryData(ancillary);
}
BMDVideo3DPackingFormat VideoFrame3D::Get3DPackingFormat(void)
{
return bmdVideo3DPackingLeftOnly;
}
HRESULT VideoFrame3D::GetFrameForRightEye(IDeckLinkVideoFrame** rightEyeFrame)
{
*rightEyeFrame = NULL;
if (m_frameRight)
return m_frameRight->QueryInterface(IID_IDeckLinkVideoFrame, (void**)rightEyeFrame);
else
return E_FAIL;
}
VideoFrame3D::VideoFrame3D(IDeckLinkVideoFrame* left, IDeckLinkVideoFrame* right) :
m_frameLeft(left),
m_frameRight(right),
m_refCount(1)
{
if (!m_frameLeft)
throw std::invalid_argument("at minimum a left frame must be defined");
m_frameLeft->AddRef();
if (m_frameRight)
m_frameRight->AddRef();
}
VideoFrame3D::~VideoFrame3D()
{
m_frameLeft->Release();
m_frameLeft = NULL;
if (m_frameRight)
m_frameRight->Release();
m_frameRight = NULL;
}
| 26 | 89 | 0.767579 | [
"object"
] |
d5bb737f733f18573f0dd46f3c4307dbabddfbaa | 47,927 | cpp | C++ | signin.cpp | RivuletSonata/BankSystem | ac2227d9a22a0c44c6b93fab8d178443bd31ba84 | [
"MIT"
] | null | null | null | signin.cpp | RivuletSonata/BankSystem | ac2227d9a22a0c44c6b93fab8d178443bd31ba84 | [
"MIT"
] | null | null | null | signin.cpp | RivuletSonata/BankSystem | ac2227d9a22a0c44c6b93fab8d178443bd31ba84 | [
"MIT"
] | 2 | 2019-06-28T05:22:43.000Z | 2019-06-28T08:30:51.000Z | #include <bits/stdc++.h>
#include <windows.h>
#include <cstdio>
#include "signin.h"
#include <conio.h>
#include <time.h>
#include "bank.h"
#include "BankPersonnel.hpp"
#include "uitool.h"
using namespace std;
void SignIn::Init_Signin_UI(){
//界面
system("cls");
for (int i = 1; i <= 35; ++i){
setCursorLocation(i, 1);
cout << "=";
setCursorLocation(71 - i, 1);
cout << "=";
Sleep(10);
}
for (int i = 2; i <= 30; ++i){
setCursorLocation(1, i);
cout << "||";
setCursorLocation(69, i);
cout << "||";
Sleep(10);
}
for (int i = 2; i <= 35; ++i){
setCursorLocation(i, 30);
cout << "=";
setCursorLocation(70 - i, 30);
cout << "=";
Sleep(10);
}
setCursorLocation(13, 8);
setBackgroundColor();
cout << "Sign In UI";
}
void SignIn::User_Opertation_UI(){
//User 操作界面
}
void SignIn::Manager_Operation_UI(){
//Manager操作界面
}
bool SignIn::JudgeType(){
bool usertype = false;
int count = 0;//计算错误次数
while(islocked){
setCursorLocation(13, 10);//输入ID 密码 并记录在ID KEY中
setTextColor(3);
cout << "Type In ID";
setCursorLocation(16, 11);
cin >> ID;
setCursorLocation(13, 14);
char* password;
int length=6;
password =new char[7];
int count=0;
char* p =NULL;
cout << "Type In Key, then Type In Enter to Confirm";
p=password;
count=0;
setCursorLocation(16, 15);
while (((*p = getch()) != 13) && count < length) {
putch('*');
fflush(stdin);
p++;
count++;
}
password[count]='\0';
Key = password;
//cout << Key;
islocked = false;
/*
========调用API===========
正确则islocked=false
===========================
*/
int kk=bank.login(ID, Key);
if(kk==-1)
islocked = true;
else if(kk==0){//用户
usertype = true;
islocked = false;
}
else if(kk==1){//管理员
usertype = false;
islocked = false;
}
if(islocked){
setCursorLocation(13, 20);
cout << "ID or Key error! Please Type In Again!";
++count;
system("Pause");
system("cls");
}
else{
setCursorLocation(13, 20);
//数据库查找返回usertype user则为true;
//usertype = false;
if(usertype){//user
cout << "User Load In Successfully!";
}
else cout<<"Manager Load In Successfully!";
system("Pause");
system("cls");
}
}
//islocked = false;
//usertype =true;
return usertype;
}
User* SignIn::ReturnUser(){
User *usr = NULL;
usr = bank.seeInfo();
//User *usr = new User(ID, Key);
/*
========================
通过数据库API返回用户指针
========================
*/
return usr;
}
Manager* SignIn::ReturnManager(){
Manager *usr=NULL;
/*
===========================
通过数据库API返回管理员指针
===========================
*/
return usr;
};
int SignIn::UserChoice(){
system("cls");
for (int i = 1; i <= 35; ++i){
setCursorLocation(i, 1);
cout << "=";
setCursorLocation(71 - i, 1);
cout << "=";
Sleep(10);
}
for (int i = 2; i <= 30; ++i){
setCursorLocation(1, i);
cout << "||";
setCursorLocation(69, i);
cout << "||";
Sleep(10);
}
for (int i = 2; i <= 35; ++i){
setCursorLocation(i, 30);
cout << "=";
setCursorLocation(70 - i, 30);
cout << "=";
Sleep(10);
}
setTextColor(3);
setCursorLocation(13,7);
std::cout <<"Use Direction Key to Choose Mode ";
setCursorLocation(13, 8);
std::cout <<"And Tap Enter to Confirm:";
setCursorLocation(13,10);
setBackgroundColor();
cout << ">1.Deposite Money";
setTextColor(3);
setCursorLocation(13,11);
cout << "2.Withdraw_Money";
setTextColor(3);
setCursorLocation(13,12);
cout << "3.Add_Info";
setTextColor(3);
setCursorLocation(13,13);
cout << "4.Delete_Info";
setTextColor(3);
setCursorLocation(13,14);
cout << "5.Modify_Info";
setTextColor(3);
setCursorLocation(13,15);
cout << "6.Report_Loss";
setTextColor(3);
setCursorLocation(13,16);
cout << "7.Relate_Card";
setTextColor(3);
setCursorLocation(13,17);
cout << "8.Retrieve_Password";
setTextColor(3);
setCursorLocation(13,18);
cout << "9.Transfer_Money";
setTextColor(3);
setCursorLocation(13,19);
cout << "10.Logout";
setTextColor(3);
setCursorLocation(13,20);
cout << "11.SeeInfor";
setTextColor(3);
setCursorLocation(13,21);
cout << "12.Appeal";
setTextColor(3);
setCursorLocation(13,22);
cout << "13.Exit";
int choice=1;
bool isenter=false;
/*这插入一个选择函数 ,选择要进行操作的类型并返回相应序号*/
int ch=1;
while(ch=getch()){
switch(ch){
case 72:
if(choice>1){
switch(choice){
case 2:
setCursorLocation(13,10);
setBackgroundColor();
cout << ">1.Deposite Money";
setTextColor(3);
setCursorLocation(13,11);
cout << "2.Withdraw_Money ";
--choice;
break;
case 3:
setCursorLocation(13,11);
setBackgroundColor();
cout << ">2.Withdraw_Money";
setTextColor(3);
setCursorLocation(13,12);
cout << "3.Add_Info ";
--choice;
break;
case 4:
setCursorLocation(13,12);
setBackgroundColor();
cout << ">3.Add_Info";
setTextColor(3);
setCursorLocation(13,13);
cout << "4.Delete_Info ";
--choice;
break;
case 5:
setCursorLocation(13,13);
setBackgroundColor();
cout << ">4.Delete_Info";
setTextColor(3);
setCursorLocation(13,14);
cout << "5.Modify_Info ";
--choice;
break;
case 6:
setCursorLocation(13,14);
setBackgroundColor();
cout << ">5.Modify_Info";
setTextColor(3);
setCursorLocation(13,15);
cout << "6.Report_Loss ";
--choice;
break;
case 7:
setCursorLocation(13,15);
setBackgroundColor();
cout << ">6.Report_Loss";
setTextColor(3);
setCursorLocation(13,16);
cout << "7.Relate_Card ";
--choice;
break;
case 8:
setCursorLocation(13,16);
setBackgroundColor();
cout << ">7.Relate_Card";
setTextColor(3);
setCursorLocation(13,17);
cout << "8.Retrieve_Password ";
--choice;
break;
case 9:
setCursorLocation(13,17);
setBackgroundColor();
cout << ">8.Retrieve_Password";
setTextColor(3);
setCursorLocation(13,18);
cout << "9.Transfer_Money ";
--choice;
break;
case 10:
setCursorLocation(13,18);
setBackgroundColor();
cout << ">9.Transfer_Money";
setTextColor(3);
setCursorLocation(13,19);
cout << "10.Logout ";
--choice;
break;
case 11:
setCursorLocation(13,19);
setBackgroundColor();
cout << ">10.Logout";
setTextColor(3);
setCursorLocation(13,20);
cout << "11.SeeInfor ";
--choice;
break;
case 12:
setCursorLocation(13,20);
setBackgroundColor();
cout << ">11.SeeInfor";
setTextColor(3);
setCursorLocation(13,21);
cout << "12.Appeal ";
--choice;
break;
case 13:
setCursorLocation(13,21);
setBackgroundColor();
cout << ">12.Appeal";
setTextColor(3);
setCursorLocation(13,22);
cout << "13.Exit ";
--choice;
break;
}
}
break;
case 80://downward
if(choice <13){
switch(choice){
case 1:
setCursorLocation(13,10);
setTextColor(3);
cout << "1.Deposite Money ";
setCursorLocation(13,11);
setBackgroundColor();
cout << ">2.Withdraw_Money";
++choice;
break;
case 2:
setCursorLocation(13,11);
setTextColor(3);
cout << "2.Withdraw_Money ";
setCursorLocation(13,12);
setBackgroundColor();
cout << ">3.Add_Info";
++choice;
break;
case 3:
setCursorLocation(13,12);
setTextColor(3);
cout << "3.Add_Info ";
setBackgroundColor();
setCursorLocation(13,13);
cout << ">4.Delete_Info";
++choice;
break;
case 4:
setCursorLocation(13,13);
setTextColor(3);
cout << "4.Delete_Info ";
setBackgroundColor();
setCursorLocation(13,14);
cout << ">5.Modify_Info";
++choice;
break;
case 5:
setCursorLocation(13,14);
setTextColor(3);
cout << "5.Modify_Info ";
setBackgroundColor();
setCursorLocation(13,15);
cout << ">6.Report_Loss";
++choice;
break;
case 6:
setCursorLocation(13,15);
setTextColor(3);
cout << "6.Report_Loss ";
setBackgroundColor();
setCursorLocation(13,16);
cout << ">7.Relate_Card";
++choice;
break;
case 7:
setCursorLocation(13,16);
setTextColor(3);
cout << "7.Relate_Card ";
setBackgroundColor();
setCursorLocation(13,17);
cout << ">8.Retrieve_Password";
++choice;
break;
case 8:
setCursorLocation(13,17);
setTextColor(3);
cout << "8.Retrieve_Password ";
setBackgroundColor();
setCursorLocation(13,18);
cout << ">9.Transfer_Money";
++choice;
break;
case 9:
setCursorLocation(13,18);
setTextColor(3);
cout << "9.Transfer_Money ";
setBackgroundColor();
setCursorLocation(13,19);
cout << ">10.Logout";
++choice;
break;
case 10:
setCursorLocation(13,19);
setTextColor(3);
cout << "10.Logout ";
setBackgroundColor();
setCursorLocation(13,20);
cout << ">11.SeeInfor";
++choice;
break;
case 11:
setCursorLocation(13,20);
setTextColor(3);
cout << "11.SeeInfor ";
setBackgroundColor();
setCursorLocation(13,21);
cout << ">12.Appeal";
++choice;
break;
case 12:
setCursorLocation(13,21);
setTextColor(3);
cout << "12.Appeal ";
setBackgroundColor();
setCursorLocation(13,22);
cout << ">13.Exit";
++choice;
break;
}
}
break;
case 13:
isenter = true;
break;
default:
break;
}
if(isenter)
break;
}
setCursorLocation(39, 31);
return choice;
}
int SignIn::ManagerChoice(){
system("cls");
for (int i = 1; i <= 35; ++i){
setCursorLocation(i, 1);
cout << "=";
setCursorLocation(71 - i, 1);
cout << "=";
Sleep(10);
}
for (int i = 2; i <= 30; ++i){
setCursorLocation(1, i);
cout << "||";
setCursorLocation(69, i);
cout << "||";
Sleep(10);
}
for (int i = 2; i <= 35; ++i){
setCursorLocation(i, 30);
cout << "=";
setCursorLocation(70 - i, 30);
cout << "=";
Sleep(10);
}
setTextColor(3);
setCursorLocation(13,7);
std::cout <<"Use Direction Key to Choose Mode ";
setCursorLocation(13, 8);
std::cout <<"And Tap Enter to Confirm:";
setCursorLocation(13,10);
setBackgroundColor();
cout << ">1.Verify_New_Account";
setTextColor(3);
setCursorLocation(13,11);
cout << "2.Process_Report_Loss";
setTextColor(3);
setCursorLocation(13,12);
cout << "3.SignUp_Manager";
setTextColor(3);
setCursorLocation(13,13);
cout << "4.Process_Appeal";
setTextColor(3);
setCursorLocation(13,14);
cout << "5.Process_Logout";
setTextColor(3);
setCursorLocation(13,15);
cout << "6.Exit";
int choice=1;
bool isenter=false;
/*这插入一个选择函数 ,选择要进行操作的类型并返回相应序号*/
int ch=1;
while(ch=getch()){
switch(ch){
case 72://up
if(choice>1){
switch(choice){
case 2:
setCursorLocation(13,10);
setBackgroundColor();
cout << ">1.Verify_New_Account";
setTextColor(3);
setCursorLocation(13,11);
cout << "2.Process_Report_Loss ";
--choice;
break;
case 3:
setCursorLocation(13,11);
setBackgroundColor();
cout << ">2.Process_Report_Loss";
setTextColor(3);
setCursorLocation(13,12);
cout << "3.SignUp_Manager ";
--choice;
break;
case 4:
setCursorLocation(13,12);
setBackgroundColor();
cout << ">3.SignUp_Manager";
setTextColor(3);
setCursorLocation(13,13);
cout << "4.Process_Appeal ";
--choice;
break;
case 5:
setCursorLocation(13,13);
setBackgroundColor();
cout << ">4.Process_Appeal";
setTextColor(3);
setCursorLocation(13,14);
cout << "5.Process_Logout ";
--choice;
break;
case 6:
setCursorLocation(13,14);
setBackgroundColor();
cout << ">5.Process_Logout";
setTextColor(3);
setCursorLocation(13,15);
cout << "6.Exit ";
--choice;
break;
}
}
break;
case 80://downward
if(choice <6){
switch(choice){
case 1:
setCursorLocation(13,10);
setTextColor(3);
cout << "1.Verify_New_Account ";
setCursorLocation(13,11);
setBackgroundColor();
cout << ">2.Process_Report_Loss";
++choice;
break;
case 2:
setCursorLocation(13,11);
setTextColor(3);
cout << "2.Process_Report_Loss ";
setCursorLocation(13,12);
setBackgroundColor();
cout << ">3.SignUp_Manager";
++choice;
break;
case 3:
setCursorLocation(13,12);
setTextColor(3);
cout << "3.SignUp_Manager ";
setCursorLocation(13,13);
setBackgroundColor();
cout << ">4.Process_Appeal";
++choice;
break;
case 4:
setCursorLocation(13,13);
setTextColor(3);
cout << "4.Process_Appeal ";
setCursorLocation(13,14);
setBackgroundColor();
cout << ">5.Process_Logout";
++choice;
break;
case 5:
setCursorLocation(13,14);
setTextColor(3);
cout << "5.Process_Logout ";
setCursorLocation(13,15);
setBackgroundColor();
cout << ">6.Exit";
++choice;
break;
}
}
break;
case 13:
setTextColor(3);
isenter = true;
break;
default:
break;
}
if(isenter)
break;
}
setCursorLocation(39, 31);
return choice;
}
void SignIn::UserSignin(){
setTextColor(3);
User_Opertation_UI();
int choice = UserChoice();
setTextColor(3);
bool Continue = true;
while(choice){
switch (choice)
{
case 1:
Deposite_Money();
break;
case 2:
Withdraw_Money();
break;
case 3:
Add_Info();
break;
case 4:
Delete_Info();
break;
case 5:
Modify_Info();
break;
case 6:
Report_Loss();
break;
case 7:
Relate_Card();
break;
case 8:
Retrieve_Password();
break;
case 9:
Tranfer_Money();
break;
case 10:
Logout();
break;
case 11:
SeeInfor();
break;
case 12:
Appeal();
break;
case 13:
bank.signout();
Continue = false;
break;
default:
Continue = false;
break;
};
/*是否继续 */
if (Continue){
setTextColor(3);
choice = UserChoice();
}
else{
setTextColor(3);
choice = 0;
break;
}
}
}
void SignIn::ManagerSignin(){
setTextColor(3);
Manager_Operation_UI();
int choice = ManagerChoice();
setTextColor(3);
bool Continue = true;
while(choice){
switch (choice)
{
case 1:
Verify_New_Account();
break;
case 2:
Process_Report_Loss();
break;
case 3:
SignUp_Manager();
break;
case 4:
Process_Appeal();
break;
case 5:
Process_Logout();
break;
case 6:
Continue = false;
break;
default:
Continue = false;
break;
};
/*是否继续 */
if (Continue){
setTextColor(3);
choice = ManagerChoice();
}
else{
choice = 0;
break;
}
}
}
void SignIn::SigninAction(){
Init_Signin_UI();
if(JudgeType()){//判定用户类型
if(!islocked){
UserSignin();
}
}
else{
if(!islocked){
ManagerSignin();//管理员登陆
}
}
}
void SignIn::SeeInfor(){
setTextColor(3);
system("cls");
User *Current_User = bank.seeInfo();
setCursorLocation(13, 10);
cout << "ID-Account : " << Current_User->id_account;
setCursorLocation(13, 11);
cout << "Name : " << Current_User->name;
setCursorLocation(13, 12);
cout << "Gender : " << Current_User->gender;
setCursorLocation(13, 13);
cout << "ID-Card : " << Current_User->cid;
setCursorLocation(13, 14);
cout << "Phone Number : " << Current_User->phone_number;
setCursorLocation(13, 15);
cout << "Email Address : " << Current_User->email_address;
setCursorLocation(13, 16);
cout << "Zip Code : " << Current_User->zip_code;
setCursorLocation(13, 17);
system("Pause");
}
void SignIn::Deposite_Money(){
setTextColor(3);
system("cls");
User *Current_User = bank.seeInfo();
setCursorLocation(13,10);
cout << "Current Remaining Sum is " << Current_User->depositeAmount;
setCursorLocation(13, 11);
cout << "Please Type In the Ammount ";
setCursorLocation(13, 12);
cout << "You Want To Deposite.";
setCursorLocation(13, 13);
string Amount="";
cin >> Amount;
bool is_success = false;
is_success = bank.depositeMoney(Amount);
if(is_success){
setCursorLocation(13, 14);
cout << "Successfully Deposite Money";
}
else{
setCursorLocation(13, 14);
cout << "Failed to Deposite Money";
}
setCursorLocation(13, 15);
system("Pause");
}
void SignIn::Withdraw_Money(){
setTextColor(3);
system("cls");
User *Current_User = bank.seeInfo();
setCursorLocation(13,10);
cout << "Current Remaining Sum is " << Current_User->depositeAmount;
setCursorLocation(13, 11);
cout << "Please Type In the Ammount ";
setCursorLocation(13, 12);
cout << "You Want To Withdraw.";
setCursorLocation(13, 13);
string Amount="";
cin >> Amount;
bool is_success = false;
is_success = bank.withdrawMoney(Amount);
if(is_success){
setCursorLocation(13, 14);
cout << "Successfully Withdraw Money";
}
else{
setCursorLocation(13, 14);
cout << "Failed to Withdraw Money";
}
setCursorLocation(13, 15);
system("Pause");
}
void SignIn::Add_Info(){
system("cls");
setCursorLocation(13,9);
cout << "Type In the type of information you want to Add";
setCursorLocation(13, 10);
cout << "1.phone, 2.email, 3.address, 4.zip";
setCursorLocation(13, 11);
int Type;
cin >> Type;
setCursorLocation(13, 12);
if(Type==1){
cout << "Phone Num:";
}
else if(Type==2){
cout << "Email Address:";
}else if(Type==3){
cout << "Home Address:";
}
else if(Type==4){
cout << "Zip Code:";
}
setCursorLocation(13, 13);
cout << "Type In the Added information";
setCursorLocation(13, 14);
string info;
cin >> info;
bool is_added=bank.alterInfo(Type, info);
if(is_added){
setCursorLocation(13, 15);
cout << "Successfully Add Information";
}
else {
setCursorLocation(13, 15);
cout << "Failed to Add Information";
}
setCursorLocation(13, 16);
system("Pause");
}
void SignIn::Delete_Info(){
system("cls");
setCursorLocation(13,9);
cout << "Type In the type of information you want to Delete";
setCursorLocation(13, 10);
cout << "1.phone, 2.email, 3.address, 4.zip";
setCursorLocation(13, 11);
int Type;
cin >> Type;
setCursorLocation(13, 12);
if(Type==1){
cout << "Phone Num:";
}
else if(Type==2){
cout << "Email Address:";
}else if(Type==3){
cout << "Home Address:";
}
else if(Type==4){
cout << "Zip Code:";
}
setCursorLocation(13, 13);
string info = "";
bool is_deleted=bank.alterInfo(Type, info);
if(is_deleted){
setCursorLocation(13, 14);
cout << "Successfully Delete Information";
}
else {
setCursorLocation(13, 14);
cout << "Failed to Delete Information";
}
setCursorLocation(13, 16);
system("Pause");
}
void SignIn::Modify_Info(){
system("cls");
setCursorLocation(13,9);
cout << "Type In the type of information you want to modify";
setCursorLocation(13, 10);
cout << "1.phone, 2.email, 3.address, 4.zip";
setCursorLocation(13, 11);
int Type;
cin >> Type;
setCursorLocation(13, 12);
if(Type==1){
cout << "Phone Num:";
}
else if(Type==2){
cout << "Email Address:";
}else if(Type==3){
cout << "Home Address:";
}
else if(Type==4){
cout << "Zip Code:";
}
setCursorLocation(13, 13);
cout << "Type In the motified information";
string info;
setCursorLocation(13, 14);
cin >> info;
bool is_motified=bank.alterInfo(Type, info);
if(is_motified){
setCursorLocation(13, 15);
cout << "Successfully Motify Information";
}
else {
setCursorLocation(13, 15);
cout << "Failed to Motify Information";
}
setCursorLocation(13, 16);
system("Pause");
}
void SignIn::Report_Loss(){
system("cls");
setCursorLocation(13,10);
cout << "Type In *1* to Report_Loss ";
setCursorLocation(13, 11);
cout << "Type In *2* to REVERT Report Loss";
setCursorLocation(13, 12);
int choice;
cin >> choice;
bool is_success;
setCursorLocation(13, 13);
if(choice==1){
cout << "Type in Your Lost ID Card Number";
string card;
setCursorLocation(13, 14);
cin >> card;
is_success=bank.reportCardLoss(card);
}
else if(choice==2){
cout << "Type in The ID Card Number to be revert RCL";
string card;
setCursorLocation(13, 14);
cin >> card;
is_success =bank.revertReportCardLoss(card);
}
setCursorLocation(13, 15);
if(is_success){
cout << "Successfully Operated";
}
else
cout << "Operation Failed";
setCursorLocation(13, 16);
system("Pause");
}
void SignIn::Relate_Card(){
system("cls");
setCursorLocation(13, 8);
cout << "Type In *1* if you want to bind Cards.";
setCursorLocation(13, 9);
cout<<" or *2* if you want to Remove Bingding Relationship ";
setCursorLocation(13, 10);
int choice;
cin >> choice;
setCursorLocation(13, 11);
cout << "Type In Your Card-Number.";
setCursorLocation(13, 12);
string Card_ID;
cin >> Card_ID;
if(choice==1){
bool is_bound = bank.bindCard(Card_ID);
setCursorLocation(13, 13);
if(is_bound){
cout << "Successfully Relate your Cards";
}
else
cout << "Relate Accounts Failed";
}
else if(choice==2){
bool is_remove = bank.removeCard(Card_ID);
setCursorLocation(13, 13);
if(is_remove){
cout << "Successfully Remove your Accounts";
}
else
cout << "Remove Relationship Failed";
}
setCursorLocation(13, 14);
system("Pause");
}
void SignIn::Retrieve_Password(){
system("cls");
string Key;
string Key1 = "123123", Key2 = "321321";
bool is_Same_Key = false;
while(!is_Same_Key){
setCursorLocation(13, 9);
char* password;
int length=6;
password =new char[7];
int count=0;
char* p =NULL;
cout << "Type In Key, then Type In Enter to Confirm";
p=password;
count=0;
setCursorLocation(16, 10);
while (((*p = getch()) != 13) && count < length) {
putch('*');
fflush(stdin);
p++;
count++;
}
password[count]='\0';
Key1 = password;
setCursorLocation(13, 11);
cout << "Type In Key Again to Confirm";
p=password;
count=0;
setCursorLocation(16, 12);
while (((*p = getch()) != 13) && count < length) {
putch('*');
fflush(stdin);
p++;
count++;
}
password[count]='\0';
Key2 = password;
if(Key1!=Key2){
setCursorLocation(13, 8);
cout << "Diffrent Key";
setCursorLocation(13, 9);
cout << " ";
setCursorLocation(13, 10);
cout << " ";
setCursorLocation(13, 11);
cout << " ";
setCursorLocation(13, 12);
cout << " ";
is_Same_Key=false;
}
else{
is_Same_Key = true;
Key = Key1;
break;
}
}
bool is_changed = bank.changePassword(Key);
setCursorLocation(13, 14);
if(is_changed){
cout << "Changed Password Successfully";
}
else
cout << "Failed to Change The Password";
setCursorLocation(13, 15);
system("Pause");
}
void SignIn::Tranfer_Money(){
system("cls");
setCursorLocation(13, 10);
cout << "Type in The Card-ID that you want to transfer towards";
setCursorLocation(13, 12);
string card;
cin >> card;
setCursorLocation(13, 14);
cout << "Type in The Amount You Want to Transfer";
setCursorLocation(13, 16);
string amount;
cin >> amount;
bool is_successful_tranfer = bank.tranferMoney(card, amount);
setCursorLocation(13, 18);
if(is_successful_tranfer){
cout << "Tranfer Money Successully";
}
else{
cout<< "Tranfer Money ";
}
setCursorLocation(13, 20);
system("Pause");
}
void SignIn::Appeal(){
system("cls");
setCursorLocation(13, 10);
cout << "Type In Your Appeal Content";
string content;
setCursorLocation(13, 12);
cin >> content;
bank.appeal(content);
setCursorLocation(13, 13);
system("Pause");
}
void SignIn::Logout(){
system("cls");
setCursorLocation(13,10);
cout << "Type in *CONFIRM* to confirm logging out";
string confirm;
setCursorLocation(13, 11);
cin >> confirm;
if(confirm=="CONFIRM"){
setCursorLocation(13, 12);
bool is_deleted = bank.deleteUser();
setCursorLocation(13, 13);
if(is_deleted){
cout << "Log Out Successfully" << endl;
}
else
cout << "Failed to Log Out" << endl;
}
setCursorLocation(13, 14);
system("Pause");
}
/*Manager 类外实现 */
void SignIn::Verify_New_Account(){
vector<User *> usr;
bool iscontinue = true;
while(iscontinue){
system("cls");
setCursorLocation(13,10);
cout << "Loading the List of To-be-verified Users";
setCursorLocation(13, 11);
usr = bank.getUnReviewedUser();
if(usr.empty()){
cout << "No Available Operation.";
iscontinue = false;
}
else{
int i = 12;
for(auto &user : usr){
setCursorLocation(9, i);
cout << i - 11 << ".";
setCursorLocation(13, i++);
cout << user->id_account << " " << user->name;
}
setCursorLocation(13, i++);
cout << "Type in the user ID_Account To Verify";
string id;
setCursorLocation(13, i++);
cin >> id ;
bool isverified = bank.approveUnReviewedUser(id);
setCursorLocation(13, i++);
if(isverified){
cout << "Verified Successfully,";
setCursorLocation(13, i++);
cout<< "type * 1 * to continue, *2 * to exit ";
}
else{
cout << "Verified Failed ,";
setCursorLocation(13, i++);
cout<< "type * 1 * to continue, *2 * to exit ";
}
int choice;
setCursorLocation(13, i++);
cin >> choice ;
if(choice==1)
iscontinue = true;
else
iscontinue = false;
}
}
setCursorLocation(13, 25);
system("Pause");
}
void SignIn::Process_Report_Loss(){
vector<Loss *> Loss_List;
bool iscontinue = true;
while(iscontinue){
system("cls");
setCursorLocation(13,10);
cout << "Loading Loss List...";
setCursorLocation(13, 11);
Loss_List = bank.getAllLoss();
setCursorLocation(13, 12);
if(Loss_List.empty()){
cout << "No Available Operation.";
iscontinue = false;
}
else{
int i = 13;
int k = 1;
for(auto &loss:Loss_List){
setCursorLocation(9, i);
cout << k++ << ".";
setCursorLocation(13, i++);
cout << "User Id: " << loss->userid;
setCursorLocation(13, i++);
cout << "Card Num: " << loss->cardnum;
}
//setCursorLocation(13, i);
setCursorLocation(13, i++);
cout << "Type in the user-Id and Lost cardnum To Verify";
string usr_id;
setCursorLocation(13, i++);
cin >> usr_id ;
string l_num;
setCursorLocation(13, i++);
cin >> l_num ;
setCursorLocation(13, i++);
cout << "Type in the New cardnum To Verify";
string n_num;
setCursorLocation(13, i++);
cin >> n_num ;
bool isapproved = bank.approveLoss(usr_id, l_num, n_num);
setCursorLocation(13, i++);
if(isapproved){
cout << "LossReport Approved Successfully,";
setCursorLocation(13, i++);
cout<< "type *1* to continue,*2* to exit";
}
else{
cout << "LossReport Approved Failed,";
setCursorLocation(13, i++);
cout<<"type * 1 * to continue, *2 * to exit ";
}
int choice;
setCursorLocation(13, i++);
cin >> choice ;
if(choice==1)
iscontinue = true;
else
iscontinue = false;
}
}
setCursorLocation(13, 25);
system("Pause");
}
void SignIn::Pro_Relate_Account(){
system("cls");
setCursorLocation(13,10);
cout << "Activity Inavailable";
setCursorLocation(13, 12);
system("Pause");
}
void SignIn::Process_Appeal(){
bool iscontinue = true;
while(iscontinue){
system("cls");
setCursorLocation(13,10);
cout << "Loading Appeal List...";
setCursorLocation(13, 11);
Appeal_List = bank.getAllAppeal();
if(Appeal_List.empty()){
cout << "No Available Operation.";
iscontinue = false;
}
else{
setCursorLocation(13, 12);
int i = 13;
for(auto &app:Appeal_List){
setCursorLocation(13, i++);
cout << "Appeal Id: " << app->tid << "User Id: " << app->userid;
setCursorLocation(13, i++);
cout << "Appeal Content: " << app->content;
}
//setCursorLocation(13, i);
setCursorLocation(13, i++);
cout << "Type in the Appeal Id To Verify";
string id;
setCursorLocation(13, i++);
cin >> id ;
bool isapproved = bank.approveAppeal(id);
setCursorLocation(13, i++);
if(isapproved){
cout << "Appeal Approved Successfully,";
setCursorLocation(13, i++);
cout<< "type *1* to continue,*2* to exit";
}
else{
cout << "Approved Failed ,";
setCursorLocation(13, i++);
cout<<"type * 1 * to continue, *2 * to exit ";
}
int choice;
setCursorLocation(13, i++);
cin >> choice ;
if(choice==1)
iscontinue = true;
else
iscontinue = false;
}
}
setCursorLocation(13, 25);
system("Pause");
}
void SignIn::Process_Logout(){
system("cls");
setCursorLocation(13, 9);
cout << "Type *1* to Continue,*2* to exit";
setCursorLocation(13, 10);
int choice;
cin >> choice;
if(choice==1){
setCursorLocation(13, 11);
cout << "Type In the User ID you want to delete";
setCursorLocation(13, 12);
string id;
cin >> id;
bool isdelete = bank.deleteUser(id);
setCursorLocation(13, 13);
if(isdelete){
cout << "Delete Successfully";
}
else
cout << "Delete Failed.";
}
setCursorLocation(13, 14);
system("Pause");
}
void SignIn::SignUp_Manager(){
system("cls");
string Key, Name, Sex, ID_Card, Phone, Email;
string Key1 = "123123", Key2 = "321321";
bool is_Same_Key = false;
while(!is_Same_Key){
setCursorLocation(13, 9);
char* password;
int length=6;
password =new char[7];
int count=0;
char* p =NULL;
cout << "Type In Key, then Type In Enter to Confirm";
p=password;
count=0;
setCursorLocation(16, 10);
while (((*p = getch()) != 13) && count < length) {
putch('*');
fflush(stdin);
p++;
count++;
}
password[count]='\0';
Key1 = password;
setCursorLocation(13, 11);
cout << "Type In Key Again to Confirm";
p=password;
count=0;
setCursorLocation(16, 12);
while (((*p = getch()) != 13) && count < length) {
putch('*');
fflush(stdin);
p++;
count++;
}
password[count]='\0';
Key2 = password;
if(Key1!=Key2){
setCursorLocation(13, 8);
cout << "Diffrent Key";
setCursorLocation(13, 9);
cout << " ";
setCursorLocation(13, 10);
cout << " ";
setCursorLocation(13, 11);
cout << " ";
setCursorLocation(13, 12);
cout << " ";
is_Same_Key=false;
}
else{
is_Same_Key = true;
Key = Key1;
break;
}
}
setCursorLocation(13, 13);
cout << "Type In Sex ";
cin >> Sex;
setCursorLocation(13, 14);
cout << "Type In Your ID Card Number.";
setCursorLocation(13, 15);
cin >> ID_Card;
setCursorLocation(13, 16);
cout << "Type In Your Telephone Number.";
setCursorLocation(13, 17);
cin >> Phone;
setCursorLocation(13, 18);
cout << "Type In Your Email Address.";
setCursorLocation(13, 19);
cin >> Email;
string _permission;
setCursorLocation(13, 20);
cout << "Type In Your Authority(1-4).";
setCursorLocation(13, 21);
cin >> _permission;
int Permission = (char)_permission[0] - '0';
/*上传数据至数据库中*/
Manager usr1(Key, Name, Sex, ID_Card, Phone, Email, _permission);
string id=bank.signup(usr1,Permission);
setCursorLocation(13, 23);
if(id!="")
{
cout << "Submit Successfully!!";
setCursorLocation(8, 24);
cout << "Please Remember Your ID: " << id;
}
setCursorLocation(13, 26);
system("Pause");
}
| 29.5117 | 90 | 0.395977 | [
"vector"
] |
d5bdcc83cd6977f73c336d540d4a6de3d561f5db | 16,456 | cpp | C++ | src/gui/brush.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | 1 | 2020-12-28T01:41:35.000Z | 2020-12-28T01:41:35.000Z | src/gui/brush.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | src/gui/brush.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Vincent Chambrin
// This file is part of the Yasl project
// For conditions of distribution and use, see copyright notice in LICENSE
#include "yasl/gui/brush.h"
#include "yasl/common/binding/class.h"
#include "yasl/common/binding/default_arguments.h"
#include "yasl/common/binding/namespace.h"
#include "yasl/common/enums.h"
#include "yasl/common/genericvarianthandler.h"
#include "yasl/core/datastream.h"
#include "yasl/core/enums.h"
#include "yasl/core/point.h"
#include "yasl/gui/brush.h"
#include "yasl/gui/color.h"
#include "yasl/gui/image.h"
#include "yasl/gui/pixmap.h"
#include "yasl/gui/transform.h"
#include <script/classbuilder.h>
#include <script/enumbuilder.h>
static void register_brush_class(script::Namespace ns)
{
using namespace script;
Class brush = ns.newClass("Brush").setId(script::Type::QBrush).get();
// QBrush();
bind::default_constructor<QBrush>(brush).create();
// QBrush(Qt::BrushStyle);
bind::constructor<QBrush, Qt::BrushStyle>(brush).create();
// QBrush(const QColor &, Qt::BrushStyle = Qt::SolidPattern);
bind::constructor<QBrush, const QColor &, Qt::BrushStyle>(brush)
.apply(bind::default_arguments(Qt::SolidPattern)).create();
// QBrush(Qt::GlobalColor, Qt::BrushStyle = Qt::SolidPattern);
bind::constructor<QBrush, Qt::GlobalColor, Qt::BrushStyle>(brush)
.apply(bind::default_arguments(Qt::SolidPattern)).create();
// QBrush(const QColor &, const QPixmap &);
bind::constructor<QBrush, const QColor &, const QPixmap &>(brush).create();
// QBrush(Qt::GlobalColor, const QPixmap &);
bind::constructor<QBrush, Qt::GlobalColor, const QPixmap &>(brush).create();
// QBrush(const QPixmap &);
bind::constructor<QBrush, const QPixmap &>(brush).create();
// QBrush(const QImage &);
bind::constructor<QBrush, const QImage &>(brush).create();
// QBrush(const QBrush &);
bind::constructor<QBrush, const QBrush &>(brush).create();
// QBrush(const QGradient &);
bind::constructor<QBrush, const QGradient &>(brush).create();
// ~QBrush();
bind::destructor<QBrush>(brush).create();
// QBrush & operator=(const QBrush &);
bind::memop_assign<QBrush, const QBrush &>(brush);
// QBrush & operator=(QBrush &&);
bind::memop_assign<QBrush, QBrush &&>(brush);
// void swap(QBrush &);
bind::void_member_function<QBrush, QBrush &, &QBrush::swap>(brush, "swap").create();
// Qt::BrushStyle style() const;
bind::member_function<QBrush, Qt::BrushStyle, &QBrush::style>(brush, "style").create();
// void setStyle(Qt::BrushStyle);
bind::void_member_function<QBrush, Qt::BrushStyle, &QBrush::setStyle>(brush, "setStyle").create();
// const QMatrix & matrix() const;
/// TODO: const QMatrix & matrix() const;
// void setMatrix(const QMatrix &);
/// TODO: void setMatrix(const QMatrix &);
// QTransform transform() const;
bind::member_function<QBrush, QTransform, &QBrush::transform>(brush, "transform").create();
// void setTransform(const QTransform &);
bind::void_member_function<QBrush, const QTransform &, &QBrush::setTransform>(brush, "setTransform").create();
// QPixmap texture() const;
bind::member_function<QBrush, QPixmap, &QBrush::texture>(brush, "texture").create();
// void setTexture(const QPixmap &);
bind::void_member_function<QBrush, const QPixmap &, &QBrush::setTexture>(brush, "setTexture").create();
// QImage textureImage() const;
bind::member_function<QBrush, QImage, &QBrush::textureImage>(brush, "textureImage").create();
// void setTextureImage(const QImage &);
bind::void_member_function<QBrush, const QImage &, &QBrush::setTextureImage>(brush, "setTextureImage").create();
// const QColor & color() const;
bind::member_function<QBrush, const QColor &, &QBrush::color>(brush, "color").create();
// void setColor(const QColor &);
bind::void_member_function<QBrush, const QColor &, &QBrush::setColor>(brush, "setColor").create();
// void setColor(Qt::GlobalColor);
bind::void_member_function<QBrush, Qt::GlobalColor, &QBrush::setColor>(brush, "setColor").create();
// const QGradient * gradient() const;
/// TODO: const QGradient * gradient() const;
// bool isOpaque() const;
bind::member_function<QBrush, bool, &QBrush::isOpaque>(brush, "isOpaque").create();
// bool operator==(const QBrush &) const;
bind::memop_eq<QBrush, const QBrush &>(brush);
// bool operator!=(const QBrush &) const;
bind::memop_neq<QBrush, const QBrush &>(brush);
// bool isDetached() const;
bind::member_function<QBrush, bool, &QBrush::isDetached>(brush, "isDetached").create();
// QBrush::DataPtr & data_ptr();
/// TODO: QBrush::DataPtr & data_ptr();
yasl::registerVariantHandler<yasl::GenericVariantHandler<QBrush, QMetaType::QBrush>>();
}
static void register_gradient_type_enum(script::Class gradient)
{
using namespace script;
Enum type = gradient.newEnum("Type").setId(script::Type::QGradientType).get();
type.addValue("LinearGradient", QGradient::LinearGradient);
type.addValue("RadialGradient", QGradient::RadialGradient);
type.addValue("ConicalGradient", QGradient::ConicalGradient);
type.addValue("NoGradient", QGradient::NoGradient);
}
static void register_gradient_spread_enum(script::Class gradient)
{
using namespace script;
Enum spread = gradient.newEnum("Spread").setId(script::Type::QGradientSpread).get();
spread.addValue("PadSpread", QGradient::PadSpread);
spread.addValue("ReflectSpread", QGradient::ReflectSpread);
spread.addValue("RepeatSpread", QGradient::RepeatSpread);
}
static void register_gradient_coordinate_mode_enum(script::Class gradient)
{
using namespace script;
Enum coordinate_mode = gradient.newEnum("CoordinateMode").setId(script::Type::QGradientCoordinateMode).get();
coordinate_mode.addValue("LogicalMode", QGradient::LogicalMode);
coordinate_mode.addValue("StretchToDeviceMode", QGradient::StretchToDeviceMode);
coordinate_mode.addValue("ObjectBoundingMode", QGradient::ObjectBoundingMode);
}
static void register_gradient_interpolation_mode_enum(script::Class gradient)
{
using namespace script;
Enum interpolation_mode = gradient.newEnum("InterpolationMode").setId(script::Type::QGradientInterpolationMode).get();
interpolation_mode.addValue("ColorInterpolation", QGradient::ColorInterpolation);
interpolation_mode.addValue("ComponentInterpolation", QGradient::ComponentInterpolation);
}
static void register_gradient_class(script::Namespace ns)
{
using namespace script;
Class gradient = ns.newClass("Gradient").setId(script::Type::QGradient).get();
register_gradient_type_enum(gradient);
register_gradient_spread_enum(gradient);
register_gradient_coordinate_mode_enum(gradient);
register_gradient_interpolation_mode_enum(gradient);
// QGradient();
bind::default_constructor<QGradient>(gradient).create();
// QGradient::Type type() const;
bind::member_function<QGradient, QGradient::Type, &QGradient::type>(gradient, "type").create();
// void setSpread(QGradient::Spread);
bind::void_member_function<QGradient, QGradient::Spread, &QGradient::setSpread>(gradient, "setSpread").create();
// QGradient::Spread spread() const;
bind::member_function<QGradient, QGradient::Spread, &QGradient::spread>(gradient, "spread").create();
// void setColorAt(qreal, const QColor &);
bind::void_member_function<QGradient, qreal, const QColor &, &QGradient::setColorAt>(gradient, "setColorAt").create();
// void setStops(const QGradientStops &);
/// TODO: void setStops(const QGradientStops &);
// QGradientStops stops() const;
/// TODO: QGradientStops stops() const;
// QGradient::CoordinateMode coordinateMode() const;
bind::member_function<QGradient, QGradient::CoordinateMode, &QGradient::coordinateMode>(gradient, "coordinateMode").create();
// void setCoordinateMode(QGradient::CoordinateMode);
bind::void_member_function<QGradient, QGradient::CoordinateMode, &QGradient::setCoordinateMode>(gradient, "setCoordinateMode").create();
// QGradient::InterpolationMode interpolationMode() const;
bind::member_function<QGradient, QGradient::InterpolationMode, &QGradient::interpolationMode>(gradient, "interpolationMode").create();
// void setInterpolationMode(QGradient::InterpolationMode);
bind::void_member_function<QGradient, QGradient::InterpolationMode, &QGradient::setInterpolationMode>(gradient, "setInterpolationMode").create();
// bool operator==(const QGradient &) const;
bind::memop_eq<QGradient, const QGradient &>(gradient);
// bool operator!=(const QGradient &) const;
bind::memop_neq<QGradient, const QGradient &>(gradient);
}
static void register_linear_gradient_class(script::Namespace ns)
{
using namespace script;
Class linear_gradient = ns.newClass("LinearGradient").setId(script::Type::QLinearGradient)
.setBase(script::Type::QGradient).get();
// QLinearGradient();
bind::default_constructor<QLinearGradient>(linear_gradient).create();
// QLinearGradient(const QLinearGradient &);
bind::constructor<QLinearGradient, const QLinearGradient &>(linear_gradient).create();
// ~QLinearGradient();
bind::destructor<QLinearGradient>(linear_gradient).create();
// QLinearGradient & operator=(const QLinearGradient &);
bind::memop_assign<QLinearGradient, const QLinearGradient &>(linear_gradient);
// QLinearGradient(const QPointF &, const QPointF &);
bind::constructor<QLinearGradient, const QPointF &, const QPointF &>(linear_gradient).create();
// QLinearGradient(qreal, qreal, qreal, qreal);
bind::constructor<QLinearGradient, qreal, qreal, qreal, qreal>(linear_gradient).create();
// QPointF start() const;
bind::member_function<QLinearGradient, QPointF, &QLinearGradient::start>(linear_gradient, "start").create();
// void setStart(const QPointF &);
bind::void_member_function<QLinearGradient, const QPointF &, &QLinearGradient::setStart>(linear_gradient, "setStart").create();
// void setStart(qreal, qreal);
bind::void_member_function<QLinearGradient, qreal, qreal, &QLinearGradient::setStart>(linear_gradient, "setStart").create();
// QPointF finalStop() const;
bind::member_function<QLinearGradient, QPointF, &QLinearGradient::finalStop>(linear_gradient, "finalStop").create();
// void setFinalStop(const QPointF &);
bind::void_member_function<QLinearGradient, const QPointF &, &QLinearGradient::setFinalStop>(linear_gradient, "setFinalStop").create();
// void setFinalStop(qreal, qreal);
bind::void_member_function<QLinearGradient, qreal, qreal, &QLinearGradient::setFinalStop>(linear_gradient, "setFinalStop").create();
}
static void register_radial_gradient_class(script::Namespace ns)
{
using namespace script;
Class radial_gradient = ns.newClass("RadialGradient").setId(script::Type::QRadialGradient)
.setBase(script::Type::QGradient).get();
// QRadialGradient();
bind::default_constructor<QRadialGradient>(radial_gradient).create();
// QRadialGradient(const QRadialGradient &);
bind::constructor<QRadialGradient, const QRadialGradient &>(radial_gradient).create();
// QRadialGradient & operator=(const QRadialGradient &);
bind::memop_assign<QRadialGradient, const QRadialGradient &>(radial_gradient);
// ~QRadialGradient();
bind::destructor<QRadialGradient>(radial_gradient).create();
// QRadialGradient(const QPointF &, qreal, const QPointF &);
bind::constructor<QRadialGradient, const QPointF &, qreal, const QPointF &>(radial_gradient).create();
// QRadialGradient(qreal, qreal, qreal, qreal, qreal);
bind::constructor<QRadialGradient, qreal, qreal, qreal, qreal, qreal>(radial_gradient).create();
// QRadialGradient(const QPointF &, qreal);
bind::constructor<QRadialGradient, const QPointF &, qreal>(radial_gradient).create();
// QRadialGradient(qreal, qreal, qreal);
bind::constructor<QRadialGradient, qreal, qreal, qreal>(radial_gradient).create();
// QRadialGradient(const QPointF &, qreal, const QPointF &, qreal);
bind::constructor<QRadialGradient, const QPointF &, qreal, const QPointF &, qreal>(radial_gradient).create();
// QRadialGradient(qreal, qreal, qreal, qreal, qreal, qreal);
bind::constructor<QRadialGradient, qreal, qreal, qreal, qreal, qreal, qreal>(radial_gradient).create();
// QPointF center() const;
bind::member_function<QRadialGradient, QPointF, &QRadialGradient::center>(radial_gradient, "center").create();
// void setCenter(const QPointF &);
bind::void_member_function<QRadialGradient, const QPointF &, &QRadialGradient::setCenter>(radial_gradient, "setCenter").create();
// void setCenter(qreal, qreal);
bind::void_member_function<QRadialGradient, qreal, qreal, &QRadialGradient::setCenter>(radial_gradient, "setCenter").create();
// QPointF focalPoint() const;
bind::member_function<QRadialGradient, QPointF, &QRadialGradient::focalPoint>(radial_gradient, "focalPoint").create();
// void setFocalPoint(const QPointF &);
bind::void_member_function<QRadialGradient, const QPointF &, &QRadialGradient::setFocalPoint>(radial_gradient, "setFocalPoint").create();
// void setFocalPoint(qreal, qreal);
bind::void_member_function<QRadialGradient, qreal, qreal, &QRadialGradient::setFocalPoint>(radial_gradient, "setFocalPoint").create();
// qreal radius() const;
bind::member_function<QRadialGradient, qreal, &QRadialGradient::radius>(radial_gradient, "radius").create();
// void setRadius(qreal);
bind::void_member_function<QRadialGradient, qreal, &QRadialGradient::setRadius>(radial_gradient, "setRadius").create();
// qreal centerRadius() const;
bind::member_function<QRadialGradient, qreal, &QRadialGradient::centerRadius>(radial_gradient, "centerRadius").create();
// void setCenterRadius(qreal);
bind::void_member_function<QRadialGradient, qreal, &QRadialGradient::setCenterRadius>(radial_gradient, "setCenterRadius").create();
// qreal focalRadius() const;
bind::member_function<QRadialGradient, qreal, &QRadialGradient::focalRadius>(radial_gradient, "focalRadius").create();
// void setFocalRadius(qreal);
bind::void_member_function<QRadialGradient, qreal, &QRadialGradient::setFocalRadius>(radial_gradient, "setFocalRadius").create();
}
static void register_conical_gradient_class(script::Namespace ns)
{
using namespace script;
Class conical_gradient = ns.newClass("ConicalGradient").setId(script::Type::QConicalGradient)
.setBase(script::Type::QGradient).get();
// QConicalGradient();
bind::default_constructor<QConicalGradient>(conical_gradient).create();
// QConicalGradient(const QConicalGradient &);
bind::constructor<QConicalGradient, const QConicalGradient &>(conical_gradient).create();
// QConicalGradient & operator=(const QConicalGradient &);
bind::memop_assign<QConicalGradient, const QConicalGradient &>(conical_gradient);
// ~QConicalGradient();
bind::destructor<QConicalGradient>(conical_gradient).create();
// QConicalGradient(const QPointF &, qreal);
bind::constructor<QConicalGradient, const QPointF &, qreal>(conical_gradient).create();
// QConicalGradient(qreal, qreal, qreal);
bind::constructor<QConicalGradient, qreal, qreal, qreal>(conical_gradient).create();
// QPointF center() const;
bind::member_function<QConicalGradient, QPointF, &QConicalGradient::center>(conical_gradient, "center").create();
// void setCenter(const QPointF &);
bind::void_member_function<QConicalGradient, const QPointF &, &QConicalGradient::setCenter>(conical_gradient, "setCenter").create();
// void setCenter(qreal, qreal);
bind::void_member_function<QConicalGradient, qreal, qreal, &QConicalGradient::setCenter>(conical_gradient, "setCenter").create();
// qreal angle() const;
bind::member_function<QConicalGradient, qreal, &QConicalGradient::angle>(conical_gradient, "angle").create();
// void setAngle(qreal);
bind::void_member_function<QConicalGradient, qreal, &QConicalGradient::setAngle>(conical_gradient, "setAngle").create();
}
void register_brush_file(script::Namespace gui)
{
using namespace script;
Namespace ns = gui;
register_brush_class(ns);
register_gradient_class(ns);
register_linear_gradient_class(ns);
register_radial_gradient_class(ns);
register_conical_gradient_class(ns);
// QDataStream & operator<<(QDataStream &, const QBrush &);
bind::op_put_to<QDataStream &, const QBrush &>(ns);
// QDataStream & operator>>(QDataStream &, QBrush &);
bind::op_read_from<QDataStream &, QBrush &>(ns);
// QDebug operator<<(QDebug, const QBrush &);
/// TODO: QDebug operator<<(QDebug, const QBrush &);
}
| 49.122388 | 147 | 0.748602 | [
"transform"
] |
d5c3ddc656ceadff13091a87ff613b640703254f | 170,551 | cc | C++ | Source/Compiler/CompilationVisitor.cc | fuzziqersoftware/nemesys | ee6cc8e1fd804b5cfaa94a79e295770cadec8204 | [
"MIT"
] | 9 | 2018-02-05T06:52:02.000Z | 2022-03-27T18:26:14.000Z | Source/Compiler/CompilationVisitor.cc | fuzziqersoftware/nemesys | ee6cc8e1fd804b5cfaa94a79e295770cadec8204 | [
"MIT"
] | 1 | 2021-05-17T16:53:12.000Z | 2021-05-31T11:19:28.000Z | Source/Compiler/CompilationVisitor.cc | fuzziqersoftware/nemesys | ee6cc8e1fd804b5cfaa94a79e295770cadec8204 | [
"MIT"
] | 3 | 2018-02-06T17:24:34.000Z | 2021-11-16T17:20:28.000Z | #include "CompilationVisitor.hh"
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <phosg/Filesystem.hh>
#include <phosg/Strings.hh>
#include <libamd64/AMD64Assembler.hh>
#include "../Debug.hh"
#include "../AST/PythonLexer.hh"
#include "../AST/PythonParser.hh"
#include "../AST/PythonASTNodes.hh"
#include "../AST/PythonASTVisitor.hh"
#include "../Environment/Value.hh"
#include "../Types/Reference.hh"
#include "../Types/Strings.hh"
#include "../Types/Format.hh"
#include "../Types/List.hh"
#include "../Types/Tuple.hh"
#include "../Types/Dictionary.hh"
#include "CommonObjects.hh"
#include "Exception.hh"
#include "BuiltinFunctions.hh"
#include "Compile.hh"
using namespace std;
static const vector<Register> int_argument_register_order = {
Register::RDI, Register::RSI, Register::RDX, Register::RCX, Register::R8,
Register::R9};
static const vector<Register> float_argument_register_order = {
Register::XMM0, Register::XMM1, Register::XMM2, Register::XMM3,
Register::XMM4, Register::XMM5, Register::XMM6, Register::XMM7};
static const int64_t default_available_int_registers =
(1 << Register::RAX) | (1 << Register::RCX) | (1 << Register::RDX) |
(1 << Register::RSI) | (1 << Register::RDI) | (1 << Register::R8) |
(1 << Register::R9) | (1 << Register::R10) | (1 << Register::R11);
static const int64_t default_available_float_registers = 0xFFFF; // all of them
CompilationVisitor::terminated_by_split::terminated_by_split(
int64_t callsite_token) : runtime_error("terminated by split"),
callsite_token(callsite_token) { }
CompilationVisitor::CompilationVisitor(GlobalContext* global,
ModuleContext* module, Fragment* fragment) : file_offset(-1),
global(global), module(module), fragment(fragment),
available_int_registers(default_available_int_registers),
available_float_registers(default_available_float_registers),
target_register(rax), float_target_register(xmm0), stack_bytes_used(0),
holding_reference(false), evaluating_instance_pointer(false),
in_finally_block(false) {
if (this->fragment->function) {
if (this->fragment->function->args.size() != this->fragment->arg_types.size()) {
throw compile_error("fragment and function take different argument counts", this->file_offset);
}
// populate local_variable_types with the argument types
for (size_t x = 0; x < this->fragment->arg_types.size(); x++) {
this->local_variable_types.emplace(this->fragment->function->args[x].name,
this->fragment->arg_types[x]);
}
// populate the rest of the locals
for (const auto& it : this->fragment->function->locals) {
this->local_variable_types.emplace(it.first, it.second);
}
// clear the split labels and offsets
this->fragment->call_split_offsets.resize(this->fragment->function->num_splits);
this->fragment->call_split_labels.resize(this->fragment->function->num_splits);
} else {
this->fragment->call_split_offsets.resize(this->module->root_fragment_num_splits);
this->fragment->call_split_labels.resize(this->module->root_fragment_num_splits);
}
for (size_t x = 0; x < this->fragment->call_split_offsets.size(); x++) {
this->fragment->call_split_offsets[x] = -1;
this->fragment->call_split_labels[x].clear();
}
}
AMD64Assembler& CompilationVisitor::assembler() {
return this->as;
}
const unordered_set<Value>& CompilationVisitor::return_types() const {
return this->function_return_types;
}
size_t CompilationVisitor::get_file_offset() const {
return this->file_offset;
}
CompilationVisitor::VariableLocation::VariableLocation() :
type(ValueType::Indeterminate), global_module(NULL), global_index(-1),
variable_mem(), variable_mem_valid(false) { }
string CompilationVisitor::VariableLocation::str() const {
string type_str = this->type.str();
if (this->global_module) {
string ret = string_printf("%s.%s (global) = %s @ +%" PRIX64,
this->global_module->name.c_str(), this->name.c_str(), type_str.c_str(),
this->global_index);
if (this->variable_mem_valid) {
ret += " == ";
ret += this->variable_mem.str(OperandSize::QuadWord);
}
return ret;
} else {
string mem_str = this->variable_mem.str(OperandSize::QuadWord);
return string_printf("%s = %s @ %s", this->name.c_str(), type_str.c_str(),
mem_str.c_str());
}
}
Register CompilationVisitor::reserve_register(Register which,
bool float_register) {
if (which == Register::None) {
which = this->available_register(Register::None, float_register);
}
int32_t* available_mask = float_register ? &this->available_float_registers :
&this->available_int_registers;
if (!(*available_mask & (1 << which))) {
throw compile_error(string_printf("register %s is not available", name_for_register(which)), this->file_offset);
}
*available_mask &= ~(1 << which);
return which;
}
void CompilationVisitor::release_register(Register which, bool float_register) {
int32_t* available_mask = float_register ? &this->available_float_registers :
&this->available_int_registers;
*available_mask |= (1 << which);
}
void CompilationVisitor::release_all_registers(bool float_registers) {
if (float_registers) {
this->available_float_registers = default_available_float_registers;
} else {
this->available_int_registers = default_available_int_registers;
}
}
Register CompilationVisitor::available_register(Register preferred,
bool float_register) {
int32_t* available_mask = float_register ? &this->available_float_registers :
&this->available_int_registers;
if (*available_mask & (1 << preferred)) {
return preferred;
}
Register which;
for (which = Register::RAX; // = 0
!(*available_mask & (1 << which)) && (static_cast<int64_t>(which) < Register::Count);
which = static_cast<Register>(static_cast<int64_t>(which) + 1));
if (static_cast<int64_t>(which) >= Register::Count) {
throw compile_error("no registers are available", this->file_offset);
}
return which;
}
bool CompilationVisitor::register_is_available(Register which,
bool float_register) {
int32_t* available_mask = float_register ? &this->available_float_registers :
&this->available_int_registers;
return *available_mask & (1 << which);
}
Register CompilationVisitor::available_register_except(
const vector<Register>& prevented, bool float_register) {
int32_t* available_mask = float_register ? &this->available_float_registers :
&this->available_int_registers;
int32_t prevented_mask = 0;
for (Register r : prevented) {
prevented_mask |= (1 << r);
}
Register which;
for (which = Register::RAX; // = 0
((prevented_mask & (1 << which)) || !(*available_mask & (1 << which))) &&
(static_cast<int64_t>(which) < Register::Count);
which = static_cast<Register>(static_cast<int64_t>(which) + 1));
if (static_cast<int64_t>(which) >= Register::Count) {
throw compile_error("no registers are available", this->file_offset);
}
return which;
}
int64_t CompilationVisitor::write_push_reserved_registers() {
// push int registers
Register which;
for (which = Register::RAX; // = 0
static_cast<int64_t>(which) < Register::Count;
which = static_cast<Register>(static_cast<int64_t>(which) + 1)) {
if (!(default_available_int_registers & (1 << which))) {
continue; // this register isn't used by CompilationVisitor
}
if (this->available_int_registers & (1 << which)) {
continue; // this register is used but not reserved
}
this->write_push(which);
}
// push xmm registers
for (which = Register::XMM0; // = 0
static_cast<int64_t>(which) < Register::Count;
which = static_cast<Register>(static_cast<int64_t>(which) + 1)) {
if (!(default_available_float_registers & (1 << which))) {
continue; // this register isn't used by CompilationVisitor
}
if (this->available_float_registers & (1 << which)) {
continue; // this register is used but not reserved
}
this->adjust_stack(-8);
this->as.write_movsd(MemoryReference(rsp, 0),
MemoryReference(which));
}
// reset the available flags and return the old flags
int64_t ret = this->available_registers;
this->available_int_registers = default_available_int_registers;
this->available_float_registers = default_available_float_registers;
return ret;
}
void CompilationVisitor::write_pop_reserved_registers(int64_t mask) {
if ((this->available_int_registers != default_available_int_registers) ||
(this->available_float_registers != default_available_float_registers)) {
throw compile_error("some registers were not released when reserved were popped", this->file_offset);
}
this->available_registers = mask;
Register which;
for (which = Register::XMM15;
static_cast<int64_t>(which) > Register::None;
which = static_cast<Register>(static_cast<int64_t>(which) - 1)) {
if (!(default_available_float_registers & (1 << which))) {
continue; // this register isn't used by CompilationVisitor
}
if (this->available_float_registers & (1 << which)) {
continue; // this register is used but not reserved
}
this->as.write_movsd(MemoryReference(which), MemoryReference(rsp, 0));
this->adjust_stack(8);
}
for (which = Register::R15;
static_cast<int64_t>(which) > Register::None;
which = static_cast<Register>(static_cast<int64_t>(which) - 1)) {
if (!(default_available_int_registers & (1 << which))) {
continue; // this register isn't used by CompilationVisitor
}
if (this->available_int_registers & (1 << which)) {
continue; // this register is used but not reserved
}
this->write_pop(which);
}
}
void CompilationVisitor::visit(UnaryOperation* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->as.write_label(string_printf("__UnaryOperation_%p_evaluate", a));
// generate code for the value expression
a->expr->accept(this);
if (this->current_type.type == ValueType::Indeterminate) {
throw compile_error("operand has Indeterminate type", this->file_offset);
}
// apply the unary operation on top of the result
// we can use the same target register
MemoryReference target_mem(this->target_register);
this->as.write_label(string_printf("__UnaryOperation_%p_apply", a));
switch (a->oper) {
case UnaryOperator::LogicalNot:
if (this->current_type.type == ValueType::None) {
// `not None` is always true
this->as.write_mov(this->target_register, 1);
} else if (this->current_type.type == ValueType::Bool) {
// bools are either 0 or 1; just flip it
this->as.write_xor(target_mem, 1);
} else if (this->current_type.type == ValueType::Int) {
// check if the value is zero
this->as.write_test(target_mem, target_mem);
this->as.write_mov(this->target_register, 0);
this->as.write_setz(MemoryReference(byte_register_for_register(
this->target_register)));
} else if (this->current_type.type == ValueType::Float) {
// 0.0 and -0.0 are falsey, everything else is truthy
// the sign bit is the highest bit; to truth-test floats, we just shift
// out the sign bit and check if the rest is zero
this->as.write_movq_from_xmm(target_mem, this->float_target_register);
this->as.write_shl(target_mem, 1);
this->as.write_test(target_mem, target_mem);
this->as.write_mov(this->target_register, 0);
this->as.write_setz(MemoryReference(byte_register_for_register(
this->target_register)));
} else if ((this->current_type.type == ValueType::Bytes) ||
(this->current_type.type == ValueType::Unicode) ||
(this->current_type.type == ValueType::List) ||
(this->current_type.type == ValueType::Tuple) ||
(this->current_type.type == ValueType::Set) ||
(this->current_type.type == ValueType::Dict)) {
// load the size field, check if it's zero
Register reg = this->available_register_except({this->target_register});
MemoryReference mem(reg);
this->reserve_register(reg);
this->as.write_mov(mem, MemoryReference(this->target_register, 0x10));
// if we're holding a reference to the object, release it
this->write_delete_held_reference(target_mem);
this->as.write_test(mem, mem);
this->as.write_mov(this->target_register, 0);
this->as.write_setz(MemoryReference(byte_register_for_register(
this->target_register)));
this->release_register(reg);
} else {
// other types cannot be falsey
this->as.write_mov(this->target_register, 1);
this->write_delete_held_reference(target_mem);
}
this->current_type = Value(ValueType::Bool);
break;
case UnaryOperator::Not:
if ((this->current_type.type == ValueType::Int) ||
(this->current_type.type == ValueType::Bool)) {
this->as.write_not(target_mem);
} else {
throw compile_error("bitwise not operator can only be applied to ints and bools", this->file_offset);
}
this->current_type = Value(ValueType::Int);
break;
case UnaryOperator::Positive:
// the + operator converts bools into ints; leaves ints and floats alone
if (this->current_type.type == ValueType::Bool) {
this->current_type = Value(ValueType::Int);
} else if ((this->current_type.type != ValueType::Int) &&
(this->current_type.type != ValueType::Float)) {
throw compile_error("arithmetic positive operator can only be applied to numeric values", this->file_offset);
}
break;
case UnaryOperator::Negative:
if ((this->current_type.type == ValueType::Bool) ||
(this->current_type.type == ValueType::Int)) {
this->as.write_neg(target_mem);
this->current_type = Value(ValueType::Int);
} else if (this->current_type.type == ValueType::Float) {
// this is totally cheating. here we manually flip the sign bit
// TODO: there's probably a not-stupid way to do this
MemoryReference tmp(this->available_register());
this->as.write_movq_from_xmm(tmp, this->float_target_register);
this->as.write_rol(tmp, 1);
this->as.write_xor(tmp, 1);
this->as.write_ror(tmp, 1);
this->as.write_movq_to_xmm(this->float_target_register, tmp);
} else {
throw compile_error("arithmetic negative operator can only be applied to numeric values", this->file_offset);
}
break;
case UnaryOperator::Yield:
throw compile_error("yield operator not yet supported", this->file_offset);
}
}
bool CompilationVisitor::is_always_truthy(const Value& type) {
return (type.type == ValueType::Function) ||
(type.type == ValueType::Class) ||
(type.type == ValueType::Module);
}
bool CompilationVisitor::is_always_falsey(const Value& type) {
return (type.type == ValueType::None);
}
void CompilationVisitor::write_current_truth_value_test() {
MemoryReference target_mem((this->current_type.type == ValueType::Float) ?
this->float_target_register : this->target_register);
switch (this->current_type.type) {
case ValueType::Indeterminate:
throw compile_error("truth value test on Indeterminate type", this->file_offset);
case ValueType::ExtensionTypeReference:
throw compile_error("truth value test on ExtensionTypeReference type", this->file_offset);
case ValueType::Bool:
case ValueType::Int:
this->as.write_test(target_mem, target_mem);
break;
case ValueType::Float: {
// 0.0 and -0.0 are falsey, everything else is truthy
// the sign bit is the highest bit; to truth-test floats, we just shift
// out the sign bit and check if the rest is zero
MemoryReference tmp(this->available_register());
this->as.write_movq_from_xmm(tmp, this->float_target_register);
this->as.write_shl(tmp, 1);
this->as.write_test(tmp, tmp);
break;
}
case ValueType::Bytes:
case ValueType::Unicode:
case ValueType::List:
case ValueType::Tuple:
case ValueType::Set:
case ValueType::Dict: {
// we have to use a register for this
MemoryReference size_mem(this->available_register_except(
{this->target_register}));
this->as.write_mov(size_mem, MemoryReference(this->target_register, 0x10));
this->as.write_test(size_mem, size_mem);
break;
}
case ValueType::None:
case ValueType::Function:
case ValueType::Class:
case ValueType::Instance:
case ValueType::Module: {
string type_str = this->current_type.str();
throw compile_error(string_printf(
"cannot generate truth test for %s value", type_str.c_str()),
this->file_offset);
}
}
}
void CompilationVisitor::visit(BinaryOperation* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
MemoryReference target_mem(this->target_register);
MemoryReference float_target_mem(this->float_target_register);
// LogicalOr and LogicalAnd may not evaluate the right-side operand, so we
// have to implement those separately (the other operators evaluate both
// operands in all cases)
if ((a->oper == BinaryOperator::LogicalOr) ||
(a->oper == BinaryOperator::LogicalAnd)) {
// generate code for the left value
this->as.write_label(string_printf("__BinaryOperation_%p_evaluate_left", a));
a->left->accept(this);
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("non-held reference to left binary operator argument",
this->file_offset);
}
// if the operator is trivialized, omit the right-side code
if ((a->oper == BinaryOperator::LogicalOr) &&
is_always_truthy(this->current_type)) {
this->as.write_label(string_printf("__BinaryOperation_%p_trivialized_true", a));
return;
}
if ((a->oper == BinaryOperator::LogicalAnd) &&
is_always_falsey(this->current_type)) {
this->as.write_label(string_printf("__BinaryOperation_%p_trivialized_false", a));
return;
}
// for LogicalOr, use the left value if it's nonzero and use the right value
// otherwise; for LogicalAnd, do the opposite
string label_name = string_printf("BinaryOperation_%p_evaluate_right", a);
this->write_current_truth_value_test();
if (a->oper == BinaryOperator::LogicalOr) {
this->as.write_jnz(label_name); // skip right if left truthy
} else { // LogicalAnd
this->as.write_jz(label_name); // skip right if left falsey
}
// if we get here, then the right-side value is the one that will be
// returned; delete the reference we may be holding to the left-side value
bool left_holding_reference = this->holding_reference;
this->write_delete_held_reference(MemoryReference(this->target_register));
// generate code for the right value
Value left_type = move(this->current_type);
try {
a->right->accept(this);
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("non-held reference to right binary operator argument",
this->file_offset);
}
if (left_type != this->current_type) {
throw compile_error("logical combine operator has different return types", this->file_offset);
}
if (left_holding_reference != this->holding_reference) {
throw compile_error("logical combine operator has different reference semantics", this->file_offset);
}
} catch (const terminated_by_split&) {
// we don't know what type right will be, so just use left_type for now
this->current_type = left_type;
this->holding_reference = left_holding_reference;
}
this->as.write_label(label_name);
return;
}
// all of the remaining operators use both operands, so evaluate both of them
// into different registers
// TODO: it's kind of stupid that we push the result onto the stack; figure
// out a way to implement this without using memory access
// TODO: delete the held reference to left if right raises
this->as.write_label(string_printf("__BinaryOperation_%p_evaluate_left", a));
a->left->accept(this);
Value left_type = move(this->current_type);
if (left_type.type == ValueType::Float) {
this->as.write_movq_from_xmm(target_mem, this->float_target_register);
}
this->write_push(this->target_register); // so right doesn't clobber it
bool left_holding_reference = type_has_refcount(this->current_type.type);
if (left_holding_reference && !this->holding_reference) {
throw compile_error("non-held reference to left binary operator argument",
this->file_offset);
}
this->as.write_label(string_printf("__BinaryOperation_%p_evaluate_right", a));
try {
a->right->accept(this);
} catch (const terminated_by_split& e) {
// TODO: delete reference to right if needed
this->adjust_stack(8);
throw;
}
Value& right_type = this->current_type;
if (right_type.type == ValueType::Float) {
this->as.write_movq_from_xmm(target_mem, this->float_target_register);
}
this->write_push(this->target_register); // for the destructor call later
bool right_holding_reference = type_has_refcount(this->current_type.type);
if (right_holding_reference && !this->holding_reference) {
throw compile_error("non-held reference to right binary operator argument",
this->file_offset);
}
MemoryReference left_mem(rsp, 8);
MemoryReference right_mem(rsp, 0);
// pick a temporary register that isn't the target register
MemoryReference temp_mem(this->available_register_except({this->target_register}));
bool left_int_only = (left_type.type == ValueType::Int);
bool right_int_only = (right_type.type == ValueType::Int);
bool left_int = left_int_only || (left_type.type == ValueType::Bool);
bool right_int = right_int_only || (right_type.type == ValueType::Bool);
bool left_float = (left_type.type == ValueType::Float);
bool right_float = (right_type.type == ValueType::Float);
bool left_numeric = left_int || left_float;
bool right_numeric = right_int || right_float;
bool left_bytes = (left_type.type == ValueType::Bytes);
bool right_bytes = (right_type.type == ValueType::Bytes);
bool left_unicode = (left_type.type == ValueType::Unicode);
bool right_unicode = (right_type.type == ValueType::Unicode);
bool right_tuple = (right_type.type == ValueType::Tuple);
this->as.write_label(string_printf("__BinaryOperation_%p_combine", a));
switch (a->oper) {
case BinaryOperator::LessThan:
case BinaryOperator::GreaterThan:
case BinaryOperator::LessOrEqual:
case BinaryOperator::GreaterOrEqual:
// it's an error to ordered-compare disparate types to each other, except
// for numeric types
if ((!left_numeric || !right_numeric) && (left_type.type != right_type.type)) {
throw compile_error("cannot perform ordered comparison between " +
left_type.str() + " and " + right_type.str(), this->file_offset);
}
case BinaryOperator::Equality:
case BinaryOperator::NotEqual:
if (left_numeric && right_numeric) {
Register xmm = this->available_register(Register::None, true);
MemoryReference xmm_mem(xmm);
this->as.write_xor(target_mem, target_mem);
// Int vs Int
if (left_int && right_int) {
this->as.write_mov(temp_mem, left_mem);
this->as.write_cmp(temp_mem, right_mem);
target_mem.base_register = byte_register_for_register(target_mem.base_register);
if (a->oper == BinaryOperator::LessThan) {
this->as.write_setl(target_mem);
} else if (a->oper == BinaryOperator::GreaterThan) {
this->as.write_setg(target_mem);
} else if (a->oper == BinaryOperator::LessOrEqual) {
this->as.write_setle(target_mem);
} else if (a->oper == BinaryOperator::GreaterOrEqual) {
this->as.write_setge(target_mem);
} else if (a->oper == BinaryOperator::Equality) {
this->as.write_sete(target_mem);
} else if (a->oper == BinaryOperator::NotEqual) {
this->as.write_setne(target_mem);
}
// Float vs Int
} else if (left_float && right_int) {
this->as.write_cvtsi2sd(xmm, right_mem);
// we're comparing in the opposite direction, so we negate the results
// of ordered comparisons
if (a->oper == BinaryOperator::LessThan) {
this->as.write_cmpnltsd(xmm, left_mem);
} else if (a->oper == BinaryOperator::GreaterThan) {
this->as.write_cmplesd(xmm, left_mem);
} else if (a->oper == BinaryOperator::LessOrEqual) {
this->as.write_cmpnlesd(xmm, left_mem);
} else if (a->oper == BinaryOperator::GreaterOrEqual) {
this->as.write_cmpltsd(xmm, left_mem);
} else if (a->oper == BinaryOperator::Equality) {
this->as.write_cmpeqsd(xmm, left_mem);
} else if (a->oper == BinaryOperator::NotEqual) {
this->as.write_cmpneqsd(xmm, left_mem);
}
this->as.write_movq_from_xmm(target_mem, xmm);
// Int vs Float and Float vs Float
} else if (right_float) {
if (left_int) {
this->as.write_cvtsi2sd(xmm, left_mem);
} else {
this->as.write_movsd(xmm_mem, left_mem);
}
if (a->oper == BinaryOperator::LessThan) {
this->as.write_cmpltsd(xmm, right_mem);
} else if (a->oper == BinaryOperator::GreaterThan) {
this->as.write_cmpnlesd(xmm, right_mem);
} else if (a->oper == BinaryOperator::LessOrEqual) {
this->as.write_cmplesd(xmm, right_mem);
} else if (a->oper == BinaryOperator::GreaterOrEqual) {
this->as.write_cmpnltsd(xmm, right_mem);
} else if (a->oper == BinaryOperator::Equality) {
this->as.write_cmpeqsd(xmm, right_mem);
} else if (a->oper == BinaryOperator::NotEqual) {
this->as.write_cmpneqsd(xmm, right_mem);
}
this->as.write_movq_from_xmm(target_mem, xmm);
} else {
throw compile_error("unimplemented numeric ordered comparison: " +
left_type.str() + " vs " + right_type.str(), this->file_offset);
}
} else if ((left_bytes && right_bytes) || (left_unicode && right_unicode)) {
if ((a->oper == BinaryOperator::Equality) ||
(a->oper == BinaryOperator::NotEqual)) {
const MemoryReference target_function = common_object_reference(
left_bytes ? void_fn_ptr(&bytes_equal) : void_fn_ptr(&unicode_equal));
this->write_function_call(target_function, {target_mem, left_mem},
{}, -1, this->target_register);
if (a->oper == BinaryOperator::NotEqual) {
this->as.write_xor(target_mem, 1);
}
} else {
const MemoryReference target_function = common_object_reference(
left_bytes ? void_fn_ptr(&bytes_compare) : void_fn_ptr(&unicode_compare));
this->write_function_call(target_function, {left_mem, right_mem},
{}, -1, this->target_register);
this->as.write_cmp(target_mem, 0);
this->as.write_mov(target_mem, 0);
target_mem.base_register = byte_register_for_register(target_mem.base_register);
if (a->oper == BinaryOperator::LessThan) {
this->as.write_setl(target_mem);
} else if (a->oper == BinaryOperator::GreaterThan) {
this->as.write_setg(target_mem);
} else if (a->oper == BinaryOperator::LessOrEqual) {
this->as.write_setle(target_mem);
} else if (a->oper == BinaryOperator::GreaterOrEqual) {
this->as.write_setge(target_mem);
}
}
} else {
throw compile_error("unimplemented non-numeric ordered comparison: " +
left_type.str() + " vs " + right_type.str(), this->file_offset);
}
this->current_type = Value(ValueType::Bool);
this->holding_reference = false;
break;
case BinaryOperator::In:
case BinaryOperator::NotIn:
if ((left_bytes && right_bytes) || (left_unicode && right_unicode)) {
const MemoryReference target_function = common_object_reference(
left_bytes ? void_fn_ptr(&bytes_contains) : void_fn_ptr(&unicode_contains));
this->write_function_call(target_function, {target_mem, left_mem}, {},
-1, this->target_register);
} else {
// TODO
throw compile_error("operator `in` not yet implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
}
if (a->oper == BinaryOperator::NotIn) {
this->as.write_xor(target_mem, 1);
}
this->current_type = Value(ValueType::Bool);
this->holding_reference = false;
break;
case BinaryOperator::Is:
case BinaryOperator::IsNot: {
bool negate = (a->oper == BinaryOperator::IsNot);
// if the left and right types don't match, the result is always false
if (left_type.type != right_type.type) {
if (negate) {
this->as.write_mov(this->target_register, 1);
} else {
this->as.write_xor(target_mem, target_mem);
}
// None has only one value, so `None is None` is always true
} else if (left_type.type == ValueType::None) {
if (negate) {
this->as.write_xor(target_mem, target_mem);
} else {
this->as.write_mov(this->target_register, 1);
}
// ints and floats aren't objects, so the `is` operator isn't well-defined
} else if (left_type.type == ValueType::Int || left_type.type == ValueType::Float) {
throw compile_error("operator `is` not well-defined for int and float values", this->file_offset);
// for everything else, just compare the values directly. this exact same
// code works for bools and all other types, since their values are
// pointers and we just need to compare the pointers to know if they're
// the same object
} else {
this->as.write_xor(target_mem, target_mem);
this->as.write_mov(temp_mem, left_mem);
this->as.write_cmp(temp_mem, right_mem);
target_mem.base_register = byte_register_for_register(target_mem.base_register);
if (negate) {
this->as.write_setne(target_mem);
} else {
this->as.write_sete(target_mem);
}
}
this->current_type = Value(ValueType::Bool);
this->holding_reference = false;
break;
}
case BinaryOperator::Or:
if (left_int && right_int) {
this->as.write_or(target_mem, left_mem);
break;
}
throw compile_error("operator `or` not valid for " + left_type.str() + " and " + right_type.str(), this->file_offset);
case BinaryOperator::And:
if (left_int && right_int) {
this->as.write_and(target_mem, left_mem);
break;
}
throw compile_error("operator `and` not valid for " + left_type.str() + " and " + right_type.str(), this->file_offset);
case BinaryOperator::Xor:
if (left_int && right_int) {
this->as.write_xor(target_mem, left_mem);
break;
}
throw compile_error("operator `xor` not valid for " + left_type.str() + " and " + right_type.str(), this->file_offset);
case BinaryOperator::LeftShift:
case BinaryOperator::RightShift:
if (left_int && right_int) {
// we can only use cl apparently
if (this->available_register(rcx) != rcx) {
throw compile_error("rcx register not available for shift operation", this->file_offset);
}
this->as.write_mov(rcx, target_mem);
this->as.write_mov(target_mem, left_mem);
if (a->oper == BinaryOperator::LeftShift) {
this->as.write_shl_cl(target_mem);
} else {
this->as.write_sar_cl(target_mem);
}
break;
}
throw compile_error("bit shift operator not valid for " + left_type.str() + " and " + right_type.str(), this->file_offset);
case BinaryOperator::Addition:
if (left_bytes && right_bytes) {
this->write_function_call(common_object_reference(void_fn_ptr(&bytes_concat)),
{left_mem, target_mem, r14}, {}, -1, this->target_register);
} else if ((left_type.type == ValueType::Unicode) &&
(right_type.type == ValueType::Unicode)) {
this->write_function_call(common_object_reference(void_fn_ptr(&unicode_concat)),
{left_mem, target_mem, r14}, {}, -1, this->target_register);
} else if (left_int && right_int) {
this->as.write_add(target_mem, left_mem);
} else if (left_int && right_float) {
this->as.write_cvtsi2sd(this->float_target_register, left_mem);
this->as.write_addsd(this->float_target_register, right_mem);
} else if (left_float && right_int) {
// the int value is still in the target register; skip the memory access
this->as.write_cvtsi2sd(this->float_target_register, target_mem);
this->as.write_addsd(this->float_target_register, left_mem);
// watch it: in this case the type is different from right_type
this->current_type = Value(ValueType::Float);
} else if (left_float && right_float) {
this->as.write_addsd(this->float_target_register, left_mem);
} else {
throw compile_error("addition operator not implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
}
break;
case BinaryOperator::Subtraction:
if (left_int && right_int) {
this->as.write_neg(target_mem);
this->as.write_add(target_mem, left_mem);
} else if (left_int && right_float) {
this->as.write_cvtsi2sd(this->float_target_register, left_mem);
this->as.write_subsd(this->float_target_register, right_mem);
} else if (left_float && right_int) {
this->as.write_neg(target_mem);
this->as.write_cvtsi2sd(this->float_target_register, target_mem);
this->as.write_addsd(this->float_target_register, left_mem);
// watch it: in this case the type is different from right_type
this->current_type = Value(ValueType::Float);
} else if (left_float && right_float) {
this->as.write_movq_to_xmm(this->float_target_register, left_mem);
this->as.write_subsd(this->float_target_register, right_mem);
} else {
throw compile_error("subtraction operator not implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
}
break;
case BinaryOperator::Multiplication:
if (left_int && right_int) {
this->as.write_imul(target_mem.base_register, left_mem);
} else if (left_int && right_float) {
this->as.write_cvtsi2sd(this->float_target_register, left_mem);
this->as.write_mulsd(this->float_target_register, right_mem);
} else if (left_float && right_int) {
this->as.write_cvtsi2sd(this->float_target_register, right_mem);
this->as.write_mulsd(this->float_target_register, left_mem);
// watch it: in this case the type is different from right_type
this->current_type = Value(ValueType::Float);
} else if (left_float && right_float) {
this->as.write_mulsd(this->float_target_register, left_mem);
} else {
throw compile_error("multiplication operator not implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
}
break;
case BinaryOperator::Division: {
// we'll need a temp reg for these
Register tmp_xmm = this->available_register_except(
{this->float_target_register}, true);
MemoryReference tmp_xmm_mem(tmp_xmm);
// TODO: check if right is zero and raise ZeroDivisionError if so
if (left_int && right_int) {
this->as.write_cvtsi2sd(this->float_target_register, left_mem);
this->as.write_cvtsi2sd(tmp_xmm, right_mem);
this->as.write_divsd(this->float_target_register, tmp_xmm_mem);
} else if (left_int && right_float) {
this->as.write_cvtsi2sd(this->float_target_register, left_mem);
this->as.write_divsd(this->float_target_register, right_mem);
} else if (left_float && right_int) {
this->as.write_movsd(float_target_mem, left_mem);
this->as.write_cvtsi2sd(tmp_xmm, right_mem);
this->as.write_divsd(this->float_target_register, tmp_xmm_mem);
} else if (left_float && right_float) {
this->as.write_movsd(float_target_mem, left_mem);
this->as.write_divsd(this->float_target_register, right_mem);
} else {
throw compile_error("division operator not implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
}
this->current_type = Value(ValueType::Float);
break;
}
case BinaryOperator::Modulus:
if (left_bytes || left_unicode) {
// AnalysisVisitor should have already done the typechecking - all we
// have to do is call the right format function
if (right_tuple) {
const void* fn = left_bytes ?
void_fn_ptr(&bytes_format) : void_fn_ptr(&unicode_format);
this->write_function_call(common_object_reference(fn),
{left_mem, right_mem, r14}, {}, -1, this->target_register);
} else {
// in this case (unlike above) right might not be an object, so we
// have to tell the callee whether it is or not
Register r = available_register(rdx);
MemoryReference r_mem(r);
if (!right_holding_reference) {
this->as.write_xor(r_mem, r_mem);
} else {
this->as.write_mov(r_mem, 1);
}
const void* fn = left_bytes ?
void_fn_ptr(&bytes_format_one) : void_fn_ptr(&unicode_format_one);
this->write_function_call(common_object_reference(fn),
{left_mem, right_mem, r_mem, r14}, {}, -1, this->target_register);
}
// if returned a new reference to a string of some sort
this->current_type = Value(left_bytes ?
ValueType::Bytes : ValueType::Unicode);
this->holding_reference = true;
break;
}
// intentional fallthrough to handle numeric modulus
case BinaryOperator::IntegerDivision: {
bool is_mod = (a->oper == BinaryOperator::Modulus);
// we only support numeric arguments here
if (!left_numeric || !right_numeric) {
throw compile_error("integer division and modulus not implemented for "
+ left_type.str() + " and " + right_type.str(), this->file_offset);
}
// if both arguments are ints, do integer div/mod
if (left_int && right_int) {
// x86 has a reasonable imul opcode, but no reasonable idiv; we have to
// use rdx and rax
bool push_rax = (this->target_register != rax) &&
!this->register_is_available(rax);
bool push_rdx = (this->target_register != rdx) &&
!this->register_is_available(rdx);
if (push_rax) {
this->write_push(rax);
}
if (push_rdx) {
this->write_push(rdx);
}
// TODO: check if right is zero and raise ZeroDivisionError if so
this->as.write_mov(rax, left_mem);
this->as.write_xor(rdx, rdx);
this->as.write_idiv(right_mem);
if (is_mod) {
if (this->target_register != rdx) {
this->as.write_mov(target_mem, rdx);
}
} else {
if (this->target_register != rax) {
this->as.write_mov(target_mem, rax);
}
}
if (push_rdx) {
this->write_pop(rdx);
}
if (push_rax) {
this->write_pop(rax);
}
// Int // Int == Int
this->current_type = Value(ValueType::Int);
} else {
Register left_xmm = this->float_target_register;
Register right_xmm = this->available_register_except({left_xmm}, true);
MemoryReference left_xmm_mem(left_xmm);
MemoryReference right_xmm_mem(right_xmm);
if (left_float) {
this->as.write_movsd(left_xmm_mem, left_mem);
} else {
this->as.write_cvtsi2sd(left_xmm, left_mem);
}
if (right_float) {
this->as.write_movsd(right_xmm_mem, right_mem);
} else {
this->as.write_cvtsi2sd(right_xmm, right_mem);
}
// TODO: check if right is zero and raise ZeroDivisionError if so
if (is_mod) {
// TODO: can we do this without using a third xmm register?
Register tmp_xmm = this->available_register_except(
{left_xmm, right_xmm}, true);
MemoryReference tmp_xmm_mem(tmp_xmm);
this->as.write_movsd(tmp_xmm_mem, left_xmm_mem);
this->as.write_divsd(tmp_xmm, right_xmm_mem);
this->as.write_roundsd(tmp_xmm, tmp_xmm_mem, 3);
this->as.write_mulsd(tmp_xmm, right_xmm_mem);
this->as.write_subsd(left_xmm, tmp_xmm_mem);
} else {
this->as.write_divsd(left_xmm, right_xmm_mem);
this->as.write_roundsd(left_xmm, left_xmm_mem, 3);
}
// Float // Int == Int // Float == Float // Float == Float
this->current_type = Value(ValueType::Float);
}
break;
}
case BinaryOperator::Exponentiation:
if (left_int && right_int) {
// if the exponent is negative, throw ValueError. unfortunately we can't
// fix this in a consistent way since the return type of the expression
// depends on the value, not on any part of the code that we can
// analyze. as far as I can tell this is the only case in the entire
// language that has this property, and it's easy to work around (just
// change the source to do `1/(a**b)` instead), so we'll make the user
// do that instead
string positive_label = string_printf("__BinaryOperation_%p_pow_not_neg", a);
this->as.write_label(string_printf("__BinaryOperation_%p_pow_check_neg", a));
this->as.write_cmp(right_mem, 0);
this->as.write_jge(positive_label);
this->write_raise_exception(this->global->ValueError_class_id,
L"exponent must be nonnegative");
this->as.write_label(positive_label);
// implementation mirrors notes/pow.s except that we load the base value
// into a temp register
string again_label = string_printf("__BinaryOperation_%p_pow_again", a);
string skip_base_label = string_printf("__BinaryOperation_%p_pow_skip_base", a);
this->as.write_mov(target_mem, 1);
this->as.write_mov(temp_mem, left_mem);
this->as.write_label(again_label);
this->as.write_test(right_mem, 1);
this->as.write_jz(skip_base_label);
this->as.write_imul(target_mem.base_register, temp_mem);
this->as.write_label(skip_base_label);
this->as.write_imul(temp_mem.base_register, temp_mem);
this->as.write_shr(right_mem, 1);
this->as.write_jnz(again_label);
break;
} else if (left_float || right_float) {
Register left_xmm = this->available_register(Register::None, true);
Register right_xmm = this->available_register_except({left_xmm}, true);
MemoryReference left_xmm_mem(left_xmm);
MemoryReference right_xmm_mem(right_xmm);
if (!left_float) { // left is Int, right is Float
this->as.write_cvtsi2sd(left_xmm, left_mem);
} else {
this->as.write_movsd(left_xmm_mem, left_mem);
}
if (!right_float) { // left is Float, right is Int
this->as.write_cvtsi2sd(right_xmm, right_mem);
// watch it: in this case the type is different from right_type
this->current_type = Value(ValueType::Float);
} else {
this->as.write_movsd(right_xmm_mem, right_mem);
}
static const void* pow_fn = void_fn_ptr(static_cast<double(*)(double, double)>(&pow));
this->write_function_call(common_object_reference(pow_fn), {},
{left_xmm_mem, right_xmm_mem}, -1, this->float_target_register, true);
break;
}
// TODO
throw compile_error("exponentiation operator not implemented for " + left_type.str() + " and " + right_type.str(), this->file_offset);
default:
throw compile_error("unhandled binary operator", this->file_offset);
}
this->as.write_label(string_printf("__BinaryOperation_%p_cleanup", a));
// if either value requires destruction, do so now
if (left_holding_reference || right_holding_reference) {
// save the return value before destroying the temp values
this->write_push(this->target_register);
// destroy the temp values
if (type_has_refcount(left_type.type)) {
this->as.write_label(string_printf("__BinaryOperation_%p_destroy_left", a));
this->write_delete_reference(MemoryReference(rsp, 8), left_type.type);
}
if (type_has_refcount(right_type.type)) {
this->as.write_label(string_printf("__BinaryOperation_%p_destroy_right", a));
this->write_delete_reference(MemoryReference(rsp, 16), right_type.type);
}
// load the result again and clean up the stack
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(rsp, 0));
this->adjust_stack(0x18);
// no destructor calls necessary; just remove left and right from the stack
} else {
this->adjust_stack(0x10);
}
this->as.write_label(string_printf("__BinaryOperation_%p_complete", a));
}
void CompilationVisitor::visit(TernaryOperation* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
if (a->oper != TernaryOperator::IfElse) {
throw compile_error("unrecognized ternary operator", this->file_offset);
}
this->as.write_label(string_printf("__TernaryOperation_%p_evaluate", a));
// generate the condition evaluation
a->center->accept(this);
// if the value is always truthy or always falsey, don't bother generating the
// unused side
if (this->is_always_truthy(this->current_type)) {
this->write_delete_held_reference(MemoryReference(this->target_register));
a->left->accept(this);
return;
}
if (this->is_always_falsey(this->current_type)) {
this->write_delete_held_reference(MemoryReference(this->target_register));
a->right->accept(this);
return;
}
// left comes first in the code
string false_label = string_printf("TernaryOperation_%p_condition_false", a);
string end_label = string_printf("TernaryOperation_%p_end", a);
this->write_current_truth_value_test();
this->as.write_jz(false_label); // skip left
int64_t left_callsite_token = -1, right_callsite_token = -1;
// generate code for the left (True) value
this->write_delete_held_reference(MemoryReference(this->target_register));
try {
a->left->accept(this);
} catch (const terminated_by_split& e) {
left_callsite_token = e.callsite_token;
}
this->as.write_jmp(end_label);
Value left_type = this->current_type;
bool left_holding_reference = this->holding_reference;
// generate code for the right (False) value
this->as.write_label(false_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
try {
a->right->accept(this);
} catch (const terminated_by_split& e) {
right_callsite_token = e.callsite_token;
}
this->as.write_label(end_label);
// if both of the values were terminated by a split, terminate the entire
// thing and don't typecheck
if ((left_callsite_token >= 0) && (right_callsite_token >= 0)) {
throw terminated_by_split(left_callsite_token);
}
// if right was terminated, use the type for left
if (right_callsite_token >= 0) {
this->current_type = left_type;
this->holding_reference = left_holding_reference;
// if neither was terminated, check that right and left have the same types
} else if (left_callsite_token < 0) {
// TODO: support different value types (maybe by splitting the function)
if (!left_type.types_equal(this->current_type)) {
string left_s = left_type.str();
string right_s = this->current_type.str();
throw compile_error(string_printf("ternary operator sides have different types (left is %s, right is %s)",
left_s.c_str(), right_s.c_str()), this->file_offset);
}
if (left_holding_reference != this->holding_reference) {
throw compile_error("ternary operator sides have different reference semantics", this->file_offset);
}
}
}
void CompilationVisitor::visit(ListConstructor* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->as.write_label(string_printf("__ListConstructor_%p_setup", a));
// we'll use rbx to store the list ptr while constructing items and I'm lazy
if (this->target_register == rbx) {
throw compile_error("cannot use rbx as target register for list construction", this->file_offset);
}
this->write_push(rbx);
int64_t previously_reserved_registers = this->write_push_reserved_registers();
// allocate the list object
this->as.write_label(string_printf("__ListConstructor_%p_allocate", a));
vector<MemoryReference> int_args({rdi, rsi, r14});
this->as.write_mov(int_args[0], a->items.size());
if (type_has_refcount(a->value_type.type)) {
this->as.write_mov(int_args[1], 1);
} else {
this->as.write_xor(int_args[1], int_args[1]);
}
this->write_function_call(common_object_reference(void_fn_ptr(&list_new)),
int_args, {}, -1, this->target_register);
// save the list items pointer
this->as.write_mov(rbx, MemoryReference(this->target_register, 0x28));
this->write_push(rax);
// generate code for each item and track the extension type
size_t item_index = 0;
for (const auto& item : a->items) {
this->as.write_label(string_printf("__ListConstructor_%p_item_%zu", a, item_index));
try {
item->accept(this);
} catch (const terminated_by_split& e) {
// TODO: delete unfinished list object
this->adjust_stack(8);
this->as.write_pop(rbx);
throw;
}
if (this->current_type.type == ValueType::Float) {
this->as.write_movsd(MemoryReference(rbx, item_index * 8),
MemoryReference(this->float_target_register));
} else {
this->as.write_mov(MemoryReference(rbx, item_index * 8),
MemoryReference(this->target_register));
}
item_index++;
// typecheck the value
if (!a->value_type.types_equal(this->current_type)) {
throw compile_error("list analysis produced different type than compilation: " +
a->value_type.type_only().str() + " (analysis) vs " +
this->current_type.type_only().str() + " (compilation)", this->file_offset);
}
}
// get the list pointer back
this->as.write_label(string_printf("__ListConstructor_%p_finalize", a));
this->write_pop(this->target_register);
// restore the regs we saved
this->write_pop_reserved_registers(previously_reserved_registers);
this->write_pop(rbx);
// the result type is a new reference to a List[extension_type]
vector<Value> extension_types({a->value_type});
this->current_type = Value(ValueType::List, extension_types);
this->holding_reference = true;
}
void CompilationVisitor::visit(SetConstructor* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO: generate malloc call, item constructor and insert code
throw compile_error("SetConstructor not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(DictConstructor* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO: generate malloc call, item constructor and insert code
throw compile_error("DictConstructor not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(TupleConstructor* a) {
// TODO: deduplicate this with ListConstructor
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->as.write_label(string_printf("__TupleConstructor_%p_setup", a));
// we'll use rbx to store the tuple ptr while constructing items and I'm lazy
if (this->target_register == rbx) {
throw compile_error("cannot use rbx as target register for tuple construction", this->file_offset);
}
this->write_push(rbx);
int64_t previously_reserved_registers = this->write_push_reserved_registers();
// allocate the tuple object
this->as.write_label(string_printf("__TupleConstructor_%p_allocate", a));
vector<MemoryReference> int_args({rdi, r14});
this->as.write_mov(rdi, a->items.size());
this->write_function_call(common_object_reference(void_fn_ptr(&tuple_new)),
int_args, {}, -1, this->target_register);
// save the tuple items pointer
this->as.write_lea(rbx, MemoryReference(this->target_register, 0x18));
this->write_push(rax);
// generate code for each item and track the extension type
if (a->value_types.size() != a->items.size()) {
throw compile_error("tuple item count and type count do not match", this->file_offset);
}
for (size_t x = 0; x < a->items.size(); x++) {
const auto& item = a->items[x];
const auto& expected_type = a->value_types[x];
this->as.write_label(string_printf("__TupleConstructor_%p_item_%zu", a, x));
try {
item->accept(this);
} catch (const terminated_by_split& e) {
// TODO: delete unfinished tuple object
this->adjust_stack(8);
this->as.write_pop(rbx);
throw;
}
if (this->current_type.type == ValueType::Float) {
this->as.write_movsd(MemoryReference(rbx, x * 8),
MemoryReference(this->float_target_register));
} else {
this->as.write_mov(MemoryReference(rbx, x * 8),
MemoryReference(this->target_register));
}
if (!expected_type.types_equal(this->current_type)) {
string analysis_type_str = expected_type.type_only().str();
string compilation_type_str = this->current_type.type_only().str();
throw compile_error(string_printf(
"tuple analysis produced different type than compilation "
"for item %zu: %s (analysis) vs %s (compilation)", x,
analysis_type_str.c_str(), compilation_type_str.c_str()), this->file_offset);
}
}
// generate code to write the has_refcount map
// TODO: we can coalesce these writes for tuples larger than 8 items
this->as.write_label(string_printf("__TupleConstructor_%p_has_refcount_map", a));
size_t types_handled = 0;
while (types_handled < a->value_types.size()) {
uint8_t value = 0;
for (size_t x = 0; (x < 8) && ((types_handled + x) < a->value_types.size()); x++) {
if (type_has_refcount(a->value_types[types_handled + x].type)) {
value |= (0x80 >> x);
}
}
this->as.write_mov(MemoryReference(rbx,
a->value_types.size() * 8 + (types_handled / 8)), value, OperandSize::Byte);
types_handled += 8;
}
// get the tuple pointer back
this->as.write_label(string_printf("__TupleConstructor_%p_finalize", a));
this->write_pop(this->target_register);
// restore the regs we saved
this->write_pop_reserved_registers(previously_reserved_registers);
this->write_pop(rbx);
// the result type is a new reference to a Tuple[extension_types]
this->current_type = Value(ValueType::Tuple, a->value_types);
this->holding_reference = true;
}
void CompilationVisitor::visit(ListComprehension* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("ListComprehension not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(SetComprehension* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("SetComprehension not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(DictComprehension* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("DictComprehension not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(LambdaDefinition* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// if this definition is not the function being compiled, don't recur; instead
// treat it as an assignment (of the function context to the local/global var)
if (!this->fragment->function ||
(this->fragment->function->id != a->function_id)) {
// if the function being declared is a closure, fail
// TODO: actually implement this check
// write the function's context to the variable. note that Function-typed
// variables don't point directly to the code; this is necessary for us to
// figure out the right fragment at call time
auto* declared_function_context = this->global->context_for_function(a->function_id);
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(declared_function_context));
this->current_type = Value(ValueType::Function, a->function_id);
return;
}
string base_label = string_printf("LambdaDefinition_%p", a);
this->write_function_setup(base_label, false);
this->target_register = rax;
this->RecursiveASTVisitor::visit(a);
this->function_return_types.emplace(this->current_type);
this->write_function_cleanup(base_label, false);
}
struct FunctionCallArgumentValue {
string name;
shared_ptr<Expression> passed_value;
Value default_value; // Indeterminate for positional args
Value type;
Register target_register; // if the type is Float, this is an xmm register
ssize_t stack_offset; // if < 0, this argument isn't stored on the stack
bool is_exception_block;
bool evaluate_instance_pointer;
FunctionCallArgumentValue(const std::string& name) : name(name),
passed_value(NULL), default_value(), type(), stack_offset(0),
is_exception_block(false), evaluate_instance_pointer(false) { }
};
void CompilationVisitor::visit(FunctionCall* a) {
this->file_offset = a->file_offset;
// if the target register is reserved, its value will be preserved instead of
// being overwritten by the function's return value, which probably isn't what
// we want
if (!this->register_is_available(this->target_register)) {
throw compile_error("target register is reserved at function call time",
this->file_offset);
}
// TODO: if the callee function is unresolved, write a call through the
// compiler's resolver instead of directly calling it. it will be slow but
// it will work
if (a->callee_function_id == 0) {
throw compile_error("can\'t resolve function reference", this->file_offset);
}
// get the function context
auto* fn = this->global->context_for_function(a->callee_function_id);
if (!fn) {
throw compile_error(string_printf("function %" PRId64 " has no context object", a->callee_function_id),
this->file_offset);
}
// if the function is in a different module, we'll need to push r13 and change
// it to that module's global space pointer before the call. but builtins
// don't need this because they don't use r13 as the global space pointer
bool update_global_space_pointer = !fn->is_builtin() && (fn->module != this->module);
// order of arguments:
// 1. positional arguments, in the order defined in the function
// 2. keyword arguments, in the order defined in the function
// 3. variadic arguments
// we currently don't support variadic keyword arguments at all
// TODO: figure out how to support variadic arguments
if (a->varargs.get() || a->varkwargs.get()) {
throw compile_error("variadic function calls not supported", this->file_offset);
}
if (!fn->varargs_name.empty() || !fn->varkwargs_name.empty()) {
throw compile_error("variadic function definitions not supported", this->file_offset);
}
this->as.write_label(string_printf("__FunctionCall_%p_push_registers", a));
// separate out the positional and keyword args from the call args
const vector<shared_ptr<Expression>>& positional_call_args = a->args;
const unordered_map<string, shared_ptr<Expression>> keyword_call_args = a->kwargs;
vector<FunctionCallArgumentValue> arg_values;
// for class member functions, the first argument is automatically populated
// and is the instance object, but only if it was called on an instance
// object. if it was called on a class object, pass all args directly,
// including self
bool add_implicit_self_arg = (fn->class_id && !a->is_class_method_call);
if (add_implicit_self_arg) {
arg_values.emplace_back(fn->args[0].name);
auto& arg = arg_values.back();
if (fn->is_class_init() != a->is_class_construction) {
throw compile_error("__init__ may not be called manually", this->file_offset);
}
// if the function being called is __init__, allocate a class object first
// and push it as the first argument (passing an Instance with a NULL
// pointer instructs the later code to allocate an instance)
if (a->is_class_construction) {
arg.default_value = Value(ValueType::Instance, fn->id, nullptr);
// if it's not __init__, we'll have to know what the instance is; instruct
// the later code to evaluate the instance pointer instead of the function
// object
} else {
arg.passed_value = a->function;
arg.evaluate_instance_pointer = true;
}
arg.type = Value(ValueType::Instance, fn->class_id, nullptr);
}
// push positional args first. if the callee is a method, skip the first
// positional argument (which will implicitly be self), but only if the
// function was called as instance.method(...)
size_t call_arg_index = 0;
size_t callee_arg_index = add_implicit_self_arg;
for (; call_arg_index < positional_call_args.size();
call_arg_index++, callee_arg_index++) {
if (callee_arg_index >= fn->args.size()) {
throw compile_error("too many arguments in function call", this->file_offset);
}
const auto& callee_arg = fn->args[callee_arg_index];
const auto& call_arg = positional_call_args[call_arg_index];
// if the callee arg is a kwarg and the call also includes that kwarg, fail
if ((callee_arg.default_value.type != ValueType::Indeterminate) &&
keyword_call_args.count(callee_arg.name)) {
throw compile_error(string_printf("argument %s specified multiple times",
callee_arg.name.c_str()), this->file_offset);
}
arg_values.emplace_back(callee_arg.name);
arg_values.back().passed_value = call_arg;
arg_values.back().default_value = Value(ValueType::Indeterminate);
}
// push remaining args, in the order the function defines them
for (; callee_arg_index < fn->args.size(); callee_arg_index++) {
const auto& callee_arg = fn->args[callee_arg_index];
arg_values.emplace_back(callee_arg.name);
try {
const auto& call_arg = keyword_call_args.at(callee_arg.name);
arg_values.back().passed_value = call_arg;
arg_values.back().default_value = Value(ValueType::Indeterminate);
} catch (const out_of_range& e) {
arg_values.back().passed_value.reset();
arg_values.back().default_value = callee_arg.default_value;
}
}
// at this point we should have the same number of args overall as the
// function wants
if (arg_values.size() != fn->args.size()) {
throw compile_error(string_printf(
"incorrect argument count in function call (given: %zu, expected: %zu)",
arg_values.size(), fn->args.size()), this->file_offset);
}
// if the function takes the exception block as an argument, push it here
if (fn->pass_exception_block) {
arg_values.emplace_back("(exception block)");
arg_values.back().is_exception_block = true;
}
// push all reserved registers and r13 if necessary
int64_t previously_reserved_registers = this->write_push_reserved_registers();
if (update_global_space_pointer) {
this->write_push(r13);
}
// reserve enough stack space for the worst case - all args are ints (since
// there are fewer int registers available and floats are less common)
ssize_t arg_stack_bytes = this->write_function_call_stack_prep(arg_values.size());
try {
// generate code for the arguments
Register original_target_register = this->target_register;
Register original_float_target_register = this->float_target_register;
size_t int_registers_used = 0, float_registers_used = 0, stack_offset = 0;
for (size_t arg_index = 0; arg_index < arg_values.size(); arg_index++) {
auto& arg = arg_values[arg_index];
// if it's an int, it goes into the next int register; if it's a float, it
// goes into the next float register. if either of these are exhausted, it
// goes onto the stack
if (int_registers_used == int_argument_register_order.size()) {
this->target_register = this->available_register();
} else {
this->target_register = int_argument_register_order[int_registers_used];
}
if (float_registers_used == float_argument_register_order.size()) {
// TODO: none of the registers will be available when this happens; figure
// out a way to deal with this
this->float_target_register = this->available_register(Register::None, true);
} else {
this->float_target_register = float_argument_register_order[float_registers_used];
}
// generate code for the argument's value
// if the argument has a passed value, generate code to compute it
if (arg.passed_value.get()) {
// if this argument is `self`, then it actually comes from the function
// expression (and we evaluate the instance pointer there instead)
if (arg.evaluate_instance_pointer) {
this->as.write_label(string_printf("__FunctionCall_%p_get_instance_pointer", a));
if (this->evaluating_instance_pointer) {
throw compile_error("recursive instance pointer evaluation", this->file_offset);
}
this->evaluating_instance_pointer = true;
a->function->accept(this);
if (this->evaluating_instance_pointer) {
throw compile_error("instance pointer evaluation failed", this->file_offset);
}
if (!type_has_refcount(this->current_type.type)) {
throw compile_error("instance pointer evaluation resulted in " + this->current_type.str(),
this->file_offset);
}
arg.type = move(this->current_type);
} else {
this->as.write_label(string_printf("__FunctionCall_%p_evaluate_arg_%zu_passed_value",
a, arg_index));
arg.passed_value->accept(this);
arg.type = move(this->current_type);
}
// if the argument is the instance object, figure out what it is
} else if (fn->is_class_init() && (arg_index == 0)) {
if (arg.default_value.type != ValueType::Instance) {
throw compile_error("first argument to class constructor is not an instance", this->file_offset);
}
auto* cls = this->global->context_for_class(fn->id);
if (!cls) {
throw compile_error("__init__ call does not have an associated class", this->file_offset);
}
this->as.write_label(string_printf("__FunctionCall_%p_evaluate_arg_%zu_alloc_instance",
a, arg_index));
this->write_alloc_class_instance(cls->id);
arg.type = arg.default_value;
this->current_type = Value(ValueType::Instance, cls->id, NULL);
this->holding_reference = true;
// if the argument is the exception block, copy it from r14
} else if (arg.is_exception_block) {
this->as.write_label(string_printf("__FunctionCall_%p_evaluate_arg_%zu_exception_block",
a, arg_index));
this->as.write_mov(MemoryReference(this->target_register), r14);
} else {
this->as.write_label(string_printf("__FunctionCall_%p_evaluate_arg_%zu_default_value",
a, arg_index));
if (!arg.default_value.value_known) {
throw compile_error(string_printf(
"required function argument %zu (%s) does not have a value",
arg_index, arg.name.c_str()), this->file_offset);
}
this->write_code_for_value(arg.default_value);
arg.type = arg.default_value;
}
// bugcheck: if the value has a refcount, we had better be holding a
// reference to it
if (type_has_refcount(arg.type.type) && !this->holding_reference) {
string s = arg.type.str();
throw compile_error(string_printf(
"function call argument %zu (%s) is a non-held reference", arg_index, s.c_str()),
this->file_offset);
}
// store the value on the stack if needed; otherwise, mark the register as
// reserved
if (arg.type.type == ValueType::Float) {
if (float_registers_used != float_argument_register_order.size()) {
this->reserve_register(this->float_target_register, true);
float_registers_used++;
} else {
this->as.write_movsd(MemoryReference(rsp, stack_offset),
MemoryReference(this->float_target_register));
stack_offset += sizeof(double);
}
} else {
if (int_registers_used != int_argument_register_order.size()) {
this->reserve_register(this->target_register);
int_registers_used++;
} else {
this->as.write_mov(MemoryReference(rsp, stack_offset),
MemoryReference(this->target_register));
stack_offset += sizeof(int64_t);
}
}
}
this->target_register = original_target_register;
this->float_target_register = original_float_target_register;
// we can now unreserve the argument registers. there should be no reserved
// registers at this point because we already saved them above
this->release_all_registers(false);
this->release_all_registers(true);
// figure out which fragment to call
vector<Value> arg_types;
for (const auto& arg : arg_values) {
if (arg.is_exception_block) {
continue; // don't include exc_block in the type signature
}
arg_types.emplace_back(arg.type);
}
int64_t callee_fragment_index = fn->fragment_index_for_call_args(arg_types);
string returned_label = string_printf("__FunctionCall_%p_returned", a);
// if there's no existing fragment and the function isn't builtin, check
// that the passed argument types match the type annotations
if ((callee_fragment_index < 0) && !fn->is_builtin()) {
vector<Value> types_from_annotation;
for (const auto& arg : fn->args) {
if (arg.type_annotation.get()) {
types_from_annotation.emplace_back(this->global->type_for_annotation(
this->module, arg.type_annotation));
} else {
types_from_annotation.emplace_back(ValueType::Indeterminate);
}
}
if (this->global->match_values_to_types(types_from_annotation, arg_types) < 0) {
throw compile_error("call argument does not match type annotation", this->file_offset);
}
// if there's no existing fragment, the function isn't builtin, and eager
// compilation is enabled, try to compile a new fragment now
if (!(debug_flags & DebugFlag::NoEagerCompilation)) {
fn->fragments.emplace_back(fn, fn->fragments.size(), arg_types);
try {
compile_fragment(this->global, fn->module, &fn->fragments.back());
callee_fragment_index = fn->fragments.size() - 1;
} catch (const compile_error& e) {
if (debug_flags & DebugFlag::ShowCompileErrors) {
this->global->print_compile_error(stderr, this->module, e);
}
fn->fragments.pop_back();
}
}
}
// if there's no existing fragment with the right types and this isn't a
// built-in function, write a call to the compiler instead. if this is a
// built-in function, fail (there's nothing to recompile)
if (callee_fragment_index < 0) {
if (fn->is_builtin()) {
string args_str;
for (const auto& v : arg_types) {
if (!args_str.empty()) {
args_str += ", ";
}
args_str += v.str();
}
throw compile_error(string_printf("callee_fragment %s(%s) does not exist",
fn->name.c_str(), args_str.c_str()), this->file_offset);
}
// calling the compiler is a little complicated - we already set up the
// function call arguments, so we can't just change the call address, and
// we need a way to tell the compiler what to compile and replace this
// call with. to deal with this, we put some useful info in r10 and r11
// before calling it.
int64_t callsite_token = this->global->next_callsite_token++;
if (this->fragment->function) {
this->global->unresolved_callsites.emplace(piecewise_construct,
forward_as_tuple(callsite_token), forward_as_tuple(
a->callee_function_id, arg_types, this->module,
this->fragment->function->id, this->fragment->index, a->split_id));
} else {
this->global->unresolved_callsites.emplace(piecewise_construct,
forward_as_tuple(callsite_token), forward_as_tuple(
a->callee_function_id, arg_types, this->module, 0, -1, a->split_id));
}
if (debug_flags & DebugFlag::ShowJITEvents) {
string s = this->global->unresolved_callsites.at(callsite_token).str();
fprintf(stderr, "created unresolved callsite %" PRId64 ": %s\n",
callsite_token, s.c_str());
}
this->as.write_label(string_printf("__FunctionCall_%p_call_compiler_%" PRId64 "_callsite_%" PRId64,
a, a->callee_function_id, callsite_token));
this->as.write_mov(r10, reinterpret_cast<int64_t>(this->global));
this->as.write_mov(r11, callsite_token);
// if this call ever returns to this point in the code, it must raise an
// exception, so just go directly to the exception handler if it does.
this->as.write_push(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
this->as.write_jmp(common_object_reference(void_fn_ptr(&_resolve_function_call)));
// we're done here - can't compile any more since we don't know the return
// type of this function. but we have to compile the rest of the scope to
// get the exception handlers
this->current_type = Value(ValueType::Indeterminate);
this->holding_reference = false;
throw terminated_by_split(callsite_token);
}
// the fragment exists, so we can call it
const auto& callee_fragment = fn->fragments[callee_fragment_index];
string call_split_label = string_printf("__FunctionCall_%p_call_function_%" PRId64 "_fragment_%" PRId64 "_split_%" PRId64,
a, a->callee_function_id, callee_fragment_index, a->split_id);
this->as.write_label(call_split_label);
this->fragment->call_split_labels.at(a->split_id) = call_split_label;
// call the fragment. note that the stack is already properly aligned here
if (update_global_space_pointer) {
this->as.write_mov(r13, reinterpret_cast<int64_t>(fn->module->global_space));
}
this->as.write_mov(rax, reinterpret_cast<int64_t>(callee_fragment.compiled));
this->as.write_call(rax);
this->as.write_label(returned_label);
// if the function raised an exception, the return value is meaningless;
// instead we should continue unwinding the stack
string no_exc_label = string_printf("__FunctionCall_%p_no_exception", a);
this->as.write_test(r15, r15);
this->as.write_jz(no_exc_label);
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
this->as.write_label(no_exc_label);
// put the return value into the target register
if (callee_fragment.return_type.type == ValueType::Float) {
if (this->target_register != rax) {
this->as.write_label(string_printf("__FunctionCall_%p_save_return_value", a));
this->as.write_movsd(MemoryReference(this->float_target_register), xmm0);
}
} else {
if (this->target_register != rax) {
this->as.write_label(string_printf("__FunctionCall_%p_save_return_value", a));
this->as.write_mov(MemoryReference(this->target_register), rax);
}
}
// functions always return new references, unless they return trivial types
this->current_type = callee_fragment.return_type;
this->holding_reference = type_has_refcount(this->current_type.type);
// note: we don't have to destroy the function arguments; we passed the
// references that we generated directly into the function and it's
// responsible for deleting those references
} catch (const terminated_by_split&) {
this->as.write_label(string_printf("__FunctionCall_%p_restore_stack", a));
this->adjust_stack(arg_stack_bytes);
if (update_global_space_pointer) {
this->write_pop(r13);
}
this->write_pop_reserved_registers(previously_reserved_registers);
throw;
}
// unreserve the argument stack space
this->as.write_label(string_printf("__FunctionCall_%p_restore_stack", a));
this->adjust_stack(arg_stack_bytes);
if (update_global_space_pointer) {
this->write_pop(r13);
}
this->write_pop_reserved_registers(previously_reserved_registers);
}
void CompilationVisitor::visit(ArrayIndex* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO: this leakes a reference! need to delete the reference to the
// collection (and key if it's a dict). maybe can fix this by using reference-
// absorbing functions instead?
// get the collection
a->array->accept(this);
Value collection_type = move(this->current_type);
if (!this->holding_reference) {
throw compile_error("not holding reference to collection", this->file_offset);
}
// save regs (all cases below need to evaluate more expressions)
Register original_target_register = this->target_register;
int64_t previously_reserved_registers = this->write_push_reserved_registers();
try {
// I'm lazy and don't want to duplicate work - just call the appropriate
// get_item function
if (collection_type.type == ValueType::Dict) {
// arg 1 is the dict object
if (this->target_register != rdi) {
this->as.write_mov(rdi, MemoryReference(this->target_register));
}
// compute the key
this->target_register = rsi;
this->reserve_register(rdi);
a->index->accept(this);
if (!this->current_type.types_equal(collection_type.extension_types[0])) {
string expr_key_type = this->current_type.str();
string dict_key_type = collection_type.extension_types[0].str();
string dict_value_type = collection_type.extension_types[1].str();
throw compile_error(string_printf("lookup for key of type %s on Dict[%s, %s]",
expr_key_type.c_str(), dict_key_type.c_str(), dict_value_type.c_str()),
this->file_offset);
}
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("not holding reference to key", this->file_offset);
}
this->release_register(rdi);
// get the dict item
this->write_function_call(common_object_reference(void_fn_ptr(&dictionary_at)),
{rdi, rsi, r14}, {}, -1, original_target_register);
// the return type is the value extension type
this->current_type = collection_type.extension_types[1];
} else if ((collection_type.type == ValueType::List) ||
(collection_type.type == ValueType::Tuple)) {
// arg 1 is the list/tuple object
if (this->target_register != rdi) {
this->as.write_mov(rdi, MemoryReference(this->target_register));
}
// for lists, the index can be dynamic; compute it now
int64_t tuple_index = a->index_value;
if (collection_type.type == ValueType::List) {
this->target_register = rsi;
this->reserve_register(rdi);
a->index->accept(this);
if (this->current_type.type != ValueType::Int) {
throw compile_error("list index must be Int; here it\'s " + this->current_type.str(),
this->file_offset);
}
this->release_register(rdi);
// for tuples, the index must be static since the result type depends on it.
// for this reason, it also needs to be in range of the extension types
} else {
if (!a->index_constant) {
throw compile_error("tuple indexes must be constants", this->file_offset);
}
if (tuple_index < 0) {
tuple_index += collection_type.extension_types.size();
}
if ((tuple_index < 0) || (tuple_index >= static_cast<ssize_t>(
collection_type.extension_types.size()))) {
throw compile_error("tuple index out of range", this->file_offset);
}
this->as.write_mov(rsi, tuple_index);
}
// now call the function
const void* fn = (collection_type.type == ValueType::List) ?
void_fn_ptr(&list_get_item) : void_fn_ptr(&tuple_get_item);
this->write_function_call(common_object_reference(fn), {rdi, rsi, r14}, {},
-1, original_target_register);
// for lists, the return type is the extension type
if (collection_type.type == ValueType::List) {
this->current_type = collection_type.extension_types[0];
// for tuples, the return type is one of the extension types, determined by
// the static index value
} else {
this->current_type = collection_type.extension_types[tuple_index];
}
} else {
// TODO
throw compile_error("ArrayIndex not yet implemented for collections of type " + collection_type.str(),
this->file_offset);
}
// if the return value has a refcount, then the function returned a new
// reference to it
this->holding_reference = type_has_refcount(this->current_type.type);
// if the return value is a float, it's currently in an int register; move
// it to an xmm reg if needed
if (this->current_type.type == ValueType::Float) {
this->as.write_movq_to_xmm(this->float_target_register,
MemoryReference(this->target_register));
}
} catch (const terminated_by_split&) {
this->write_pop_reserved_registers(previously_reserved_registers);
this->target_register = original_target_register;
throw;
}
this->write_pop_reserved_registers(previously_reserved_registers);
this->target_register = original_target_register;
}
void CompilationVisitor::visit(ArraySlice* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("ArraySlice not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(IntegerConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->as.write_mov(this->target_register, a->value);
this->current_type = Value(ValueType::Int);
this->holding_reference = false;
}
void CompilationVisitor::visit(FloatConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->write_load_double(this->float_target_register, a->value);
this->current_type = Value(ValueType::Float);
this->holding_reference = false;
}
void CompilationVisitor::visit(BytesConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
const BytesObject* o = this->global->get_or_create_constant(a->value);
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(o));
this->write_add_reference(this->target_register);
this->current_type = Value(ValueType::Bytes);
this->holding_reference = true;
}
void CompilationVisitor::visit(UnicodeConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
const UnicodeObject* o = this->global->get_or_create_constant(a->value);
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(o));
this->write_add_reference(this->target_register);
this->current_type = Value(ValueType::Unicode);
this->holding_reference = true;
}
void CompilationVisitor::visit(TrueConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
this->as.write_mov(this->target_register, 1);
this->current_type = Value(ValueType::Bool);
this->holding_reference = false;
}
void CompilationVisitor::visit(FalseConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
MemoryReference target_mem(this->target_register);
this->as.write_xor(target_mem, target_mem);
this->current_type = Value(ValueType::Bool);
this->holding_reference = false;
}
void CompilationVisitor::visit(NoneConstant* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
MemoryReference target_mem(this->target_register);
this->as.write_xor(target_mem, target_mem);
this->current_type = Value(ValueType::None);
this->holding_reference = false;
}
void CompilationVisitor::visit(VariableLookup* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
VariableLocation loc = this->location_for_variable(a->name);
this->write_read_variable(this->target_register, this->float_target_register, loc);
this->current_type = loc.type;
this->holding_reference = type_has_refcount(loc.type.type);
if (this->current_type.type == ValueType::Indeterminate) {
throw compile_error("variable has Indeterminate type: " + loc.str(), this->file_offset);
}
}
void CompilationVisitor::visit(AttributeLookup* a) {
this->file_offset = a->file_offset;
// since modules are static, lookups are short-circuited (AnalysisVisitor
// stores the module name in the AST)
if (!a->base_module_name.empty()) {
// technically this only needs to be at Annotated phase, since we only need
// the global space to be updated with the module's variables. but we don't
// have a way of specifying import dependencies and we need to make sure the
// module's globals are written before the code we're generating executes,
// so we require Imported phase here to enforce this ordering later.
auto base_module = this->global->get_or_create_module(a->base_module_name);
advance_module_phase(this->global, base_module.get(), ModuleContext::Phase::Imported);
VariableLocation loc = this->location_for_global(base_module.get(), a->name);
this->write_read_variable(this->target_register, this->float_target_register, loc);
this->current_type = loc.type;
this->holding_reference = type_has_refcount(loc.type.type);
if (this->current_type.type == ValueType::Indeterminate) {
throw compile_error("attribute has Indeterminate type", this->file_offset);
}
return;
}
// there had better be a base
if (!a->base.get()) {
throw compile_error("attribute lookup has no base", this->file_offset);
}
if (this->evaluating_instance_pointer) {
this->evaluating_instance_pointer = false;
this->as.write_label(string_printf("__AttributeLookup_%p_evaluate_instance", a));
a->base->accept(this);
if (!this->holding_reference) {
throw compile_error("instance pointer evaluation resulted in non-held reference",
this->file_offset);
}
return;
}
// evaluate the base object into another register
Register attr_register = this->target_register;
Register base_register = this->available_register_except({attr_register});
this->target_register = base_register;
this->as.write_label(string_printf("__AttributeLookup_%p_evaluate_base", a));
a->base->accept(this);
bool base_holding_reference = this->holding_reference;
// if the base object is a class, write code that gets the attribute
if (this->current_type.type == ValueType::Instance) {
auto* cls = this->global->context_for_class(this->current_type.class_id);
VariableLocation loc = this->location_for_attribute(cls, a->name, this->target_register);
// get the attribute value. note that we reserve the base reg in case adding
// a reference to the attr causes a function call (we need the base later)
this->as.write_label(string_printf("__AttributeLookup_%p_get_value", a));
this->reserve_register(base_register);
this->write_read_variable(attr_register, this->float_target_register, loc);
this->release_register(base_register);
// if we're holding a reference to the base, delete that reference now
if (base_holding_reference) {
this->reserve_register(attr_register);
this->write_delete_held_reference(MemoryReference(base_register));
this->release_register(attr_register);
}
this->target_register = attr_register;
this->current_type = loc.type;
this->holding_reference = type_has_refcount(this->current_type.type);
return;
}
// TODO
throw compile_error("AttributeLookup not yet implemented on " + this->current_type.str(),
this->file_offset);
}
void CompilationVisitor::visit(TupleLValueReference* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("TupleLValueReference not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(ArrayIndexLValueReference* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("ArrayIndexLValueReference not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(ArraySliceLValueReference* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// TODO
throw compile_error("ArraySliceLValueReference not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(AttributeLValueReference* a) {
this->file_offset = a->file_offset;
this->assert_not_evaluating_instance_pointer();
// if it's an object attribute, store the value and evaluate the object
if (a->base.get()) {
// we had better be holding a reference to the value
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("assignment of non-held reference to attribute",
this->file_offset);
}
// don't touch my value plz
Register value_register = this->target_register;
this->reserve_register(this->target_register);
this->target_register = this->available_register();
Value value_type = move(this->current_type);
// evaluate the base object
a->base->accept(this);
if (this->current_type.type == ValueType::Instance) {
// the class should have the attribute that we're setting
// (location_for_attribute will check this) and the attr should be the
// same type as the value being written
auto* cls = this->global->context_for_class(this->current_type.class_id);
if (!cls) {
throw compile_error("object class does not exist", this->file_offset);
}
VariableLocation loc = this->location_for_attribute(cls, a->name,
this->target_register);
size_t attr_index = cls->attribute_indexes.at(a->name);
const auto& attr = cls->attributes.at(attr_index);
if (!attr.value.types_equal(loc.type)) {
string attr_type = attr.value.str();
string new_type = value_type.str();
throw compile_error(string_printf("attribute %s changes type from %s to %s",
a->name.c_str(), attr_type.c_str(), new_type.c_str()),
this->file_offset);
}
// reserve the base in case delete_reference needs to be called
this->reserve_register(this->target_register);
this->write_write_variable(value_register, this->float_target_register, loc);
this->release_register(this->target_register);
// if we're holding a reference to the base, delete it
this->write_delete_held_reference(MemoryReference(this->target_register));
// clean up
this->target_register = value_register;
this->release_register(this->target_register);
} else if (this->current_type.type == ValueType::Module) {
// the class should have the attribute that we're setting
// (location_for_attribute will check this) and the attr should be the
// same type as the value being written
if (!this->current_type.value_known) {
throw compile_error("base is module, but value is unknown", this->file_offset);
}
auto base_module = this->global->get_or_create_module(*this->current_type.bytes_value);
// note: we use Imported here to make sure the target module's root scope
// runs before any external code that could modify it
advance_module_phase(this->global, base_module.get(), ModuleContext::Phase::Imported);
VariableLocation loc = this->location_for_global(base_module.get(), a->name);
if (loc.variable_mem_valid) {
throw compile_error("variable reference should not be valid", this->file_offset);
}
this->reserve_register(this->target_register);
this->write_write_variable(value_register, this->float_target_register, loc);
this->release_register(this->target_register);
} else {
string s = this->current_type.str();
throw compile_error(string_printf("cannot dynamically set attribute on %s", s.c_str()),
this->file_offset);
}
// if a->base is missing, then it's a simple variable write
} else {
VariableLocation loc = this->location_for_variable(a->name);
// typecheck the result. the type of a variable can only be changed if it's
// Indeterminate; otherwise it's an error
// TODO: deduplicate some of this with location_for_variable
Value* target_variable = NULL;
if (loc.global_module) {
target_variable = &loc.global_module->global_variables.at(loc.name).value;
} else {
target_variable = &this->local_variable_types.at(loc.name);
}
if (!target_variable) {
throw compile_error("target variable not found", this->file_offset);
}
if (target_variable->type == ValueType::Indeterminate) {
*target_variable = this->current_type;
} else if (!target_variable->types_equal(loc.type)) {
string target_type_str = target_variable->str();
string value_type_str = current_type.str();
throw compile_error(string_printf("variable %s changes type from %s to %s\n",
loc.name.c_str(), target_type_str.c_str(),
value_type_str.c_str()), this->file_offset);
}
// loc may be Indeterminate; for example, if the only assignment to a
// variable is the result of a function call. it always makes sense to use
// the target variable type here, and we checked that they match above if
// we have enough information to do so
loc.type = *target_variable;
this->reserve_register(this->target_register);
this->write_write_variable(this->target_register, this->float_target_register, loc);
this->release_register(this->target_register);
}
}
// statement visitation
void CompilationVisitor::visit(ModuleStatement* a) {
this->file_offset = a->file_offset;
this->as.write_label(string_printf("__ModuleStatement_%p", a));
this->stack_bytes_used = 8;
this->holding_reference = false;
// this is essentially a function, but it will only be called once. we still
// have to treat it like a function, but it has no local variables (everything
// it writes is global, so based on R13, not RSP). the global pointer is
// passed as an argument (RDI) instead of already being in R13, so we move it
// into place. it returns the active exception object (NULL means success).
this->write_push(rbp);
this->as.write_mov(rbp, rsp);
this->write_push(r12);
this->as.write_mov(r12, reinterpret_cast<int64_t>(common_object_base()));
this->write_push(r13);
this->as.write_mov(r13, reinterpret_cast<int64_t>(this->module->global_space));
this->write_push(r14);
this->as.write_xor(r14, r14);
this->write_push(r15);
this->as.write_xor(r15, r15);
// create an exception block for the root scope
// this exception block just returns from the module scope - but the calling
// code checks for a nonzero return value (which means an exception is active)
// and will handle it appropriately
string exc_label = string_printf("__ModuleStatement_%p_exc", a);
this->as.write_label(string_printf("__ModuleStatement_%p_create_exc_block", a));
this->write_create_exception_block({}, exc_label);
// generate the function's code
this->target_register = rax;
this->as.write_label(string_printf("__ModuleStatement_%p_body", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
// we're done; write the cleanup
this->as.write_label(string_printf("__ModuleStatement_%p_return", a));
this->adjust_stack(return_exception_block_size);
this->as.write_label(exc_label);
this->as.write_mov(rax, r15);
this->write_pop(r15);
this->write_pop(r14);
this->write_pop(r13);
this->write_pop(r12);
this->write_pop(rbp);
if (this->stack_bytes_used != 8) {
throw compile_error(string_printf(
"stack misaligned at end of module root scope (%" PRId64 " bytes used; should be 8)",
this->stack_bytes_used), this->file_offset);
}
this->as.write_ret();
}
void CompilationVisitor::visit(ExpressionStatement* a) {
this->file_offset = a->file_offset;
// just evaluate it into some random register and ignore the result
this->target_register = this->available_register();
a->expr->accept(this);
this->write_delete_held_reference(MemoryReference(this->target_register));
}
void CompilationVisitor::visit(AssignmentStatement* a) {
this->file_offset = a->file_offset;
this->as.write_label(string_printf("__AssignmentStatement_%p", a));
// unlike in AnalysisVisitor, we look at the lvalue references first, so we
// can know where to put the resulting values when generating their code
// TODO: currently we don't support unpacking at all; we only support simple
// assignments
// generate code to load the value into any available register
this->target_register = available_register();
a->value->accept(this);
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("can\'t assign borrowed reference to " + this->current_type.str(),
this->file_offset);
}
// write the value into the appropriate slot
this->as.write_label(string_printf("__AssignmentStatement_%p_write_value", a));
a->target->accept(this);
// if we were holding a reference, clear the flag - we wrote that reference to
// memory, but it still exists
this->holding_reference = false;
}
void CompilationVisitor::visit(AugmentStatement* a) {
this->file_offset = a->file_offset;
// TODO
throw compile_error("AugmentStatement not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(DeleteStatement* a) {
this->file_offset = a->file_offset;
// TODO
throw compile_error("DeleteStatement not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(ImportStatement* a) {
this->file_offset = a->file_offset;
// case 3
if (a->import_star) {
throw compile_error("import * is not supported", this->file_offset);
}
// case 1: import entire modules, not specific names
if (a->names.empty()) {
// we actually don't need to do anything here; module lookups are always
// done statically
return;
}
// case 2: import some names from a module (from x import y)
const string& base_module_name = a->modules.begin()->first;
auto base_module = this->global->get_or_create_module(base_module_name);
advance_module_phase(this->global, base_module.get(), ModuleContext::Phase::Imported);
MemoryReference target_mem(this->target_register);
for (const auto& it : a->names) {
VariableLocation src_loc = this->location_for_global(base_module.get(), it.first);
VariableLocation dest_loc = this->location_for_variable(it.second);
this->as.write_label(string_printf("__ImportStatement_%p_copy_%s_%s",
a, it.first.c_str(), it.second.c_str()));
// get the value from the other module
this->as.write_mov(target_mem, reinterpret_cast<int64_t>(src_loc.global_module->global_space));
this->as.write_mov(target_mem, MemoryReference(this->target_register, sizeof(int64_t) * src_loc.global_index));
// if it's an object, add a reference to it
if (type_has_refcount(src_loc.type.type)) {
this->write_add_reference(this->target_register);
}
// store the value in this module. variable_mem is valid if global_module is
// this module or NULL
if (!dest_loc.variable_mem_valid) {
throw compile_error("variable reference not valid", a->file_offset);
}
this->as.write_mov(dest_loc.variable_mem, target_mem);
}
}
void CompilationVisitor::visit(GlobalStatement* a) {
this->file_offset = a->file_offset;
// nothing to do here; AnnotationVisitor already extracted all useful info
}
void CompilationVisitor::visit(ExecStatement* a) {
this->file_offset = a->file_offset;
throw compile_error("exec is not supported", this->file_offset);
}
void CompilationVisitor::visit(AssertStatement* a) {
this->file_offset = a->file_offset;
string pass_label = string_printf("__AssertStatement_%p_pass", a);
// evaluate the check expression
this->as.write_label(string_printf("__AssertStatement_%p_check", a));
this->target_register = this->available_register();
a->check->accept(this);
// check if the result is truthy
this->as.write_label(string_printf("__AssertStatement_%p_test", a));
this->write_current_truth_value_test();
this->as.write_jnz(pass_label);
// save the result value type so we can destroy it later
Value truth_value_type = this->current_type;
bool was_holding_reference = this->holding_reference;
// if we get here, then the result was falsey. evaluate the message and save
// it on the stack so we can move it to the AssertionError object later. (we
// do this before allocating the AssertionError in case the message evaluation
// raises an exception)
this->write_delete_held_reference(MemoryReference(this->target_register));
if (a->failure_message.get()) {
this->as.write_label(string_printf("__AssertStatement_%p_evaluate_message", a));
a->failure_message->accept(this);
} else {
this->as.write_label(string_printf("__AssertStatement_%p_generate_message", a));
// if no message is given, use a blank message
const UnicodeObject* message = this->global->get_or_create_constant(L"");
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(message));
this->write_add_reference(this->target_register);
}
this->write_push(this->target_register);
// create an AssertionError object. note that we bypass __init__ here
// TODO: deduplicate most of the rest of this function (below here) with
// write_raise_exception
auto* cls = this->global->context_for_class(this->global->AssertionError_class_id);
if (!cls) {
throw compile_error("AssertionError class does not exist",
this->file_offset);
}
// allocate the AssertionError instance and put the message in it
this->as.write_label(string_printf("__AssertStatement_%p_allocate_instance", a));
this->write_alloc_class_instance(this->global->AssertionError_class_id, false);
Register tmp = this->available_register_except({this->target_register});
this->write_pop(tmp);
// fill in the attributes as needed
const auto* cls_init = this->global->context_for_function(this->global->AssertionError_class_id);
size_t message_index = cls->attribute_indexes.at("message");
size_t init_index = cls->attribute_indexes.at("__init__");
size_t message_offset = cls->offset_for_attribute(message_index);
size_t init_offset = cls->offset_for_attribute(init_index);
this->as.write_mov(MemoryReference(this->target_register, message_offset),
MemoryReference(tmp));
this->as.write_mov(tmp, reinterpret_cast<int64_t>(cls_init));
this->as.write_mov(MemoryReference(this->target_register, init_offset),
MemoryReference(tmp));
// we should have filled everything in
if (cls->instance_size() != 40) {
throw compile_error("did not fill in entire AssertionError structure",
this->file_offset);
}
// now jump to unwind_exception
this->as.write_label(string_printf("__AssertStatement_%p_unwind", a));
this->as.write_mov(r15, MemoryReference(this->target_register));
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
// if we get here, then the expression was truthy, but we may still need to
// destroy it if it has a refcount
this->as.write_label(pass_label);
this->current_type = truth_value_type;
this->holding_reference = was_holding_reference;
this->write_delete_held_reference(MemoryReference(this->target_register));
}
void CompilationVisitor::visit(BreakStatement* a) {
this->file_offset = a->file_offset;
if (this->break_label_stack.empty()) {
throw compile_error("break statement outside loop", this->file_offset);
}
this->as.write_label(string_printf("__BreakStatement_%p", a));
this->as.write_jmp(this->break_label_stack.back());
}
void CompilationVisitor::visit(ContinueStatement* a) {
this->file_offset = a->file_offset;
if (this->continue_label_stack.empty()) {
throw compile_error("continue statement outside loop", this->file_offset);
}
this->as.write_label(string_printf("__ContinueStatement_%p", a));
this->as.write_jmp(this->continue_label_stack.back());
}
void CompilationVisitor::visit(ReturnStatement* a) {
this->file_offset = a->file_offset;
if (!this->fragment->function) {
throw compile_error("return statement outside function definition", this->file_offset);
}
// the value should be returned in rax
this->as.write_label(string_printf("__ReturnStatement_%p_evaluate_expression", a));
this->target_register = rax;
try {
a->value->accept(this);
} catch (const terminated_by_split&) {
this->function_return_types.emplace(ValueType::Indeterminate);
throw;
}
// it had better be a new reference if the type is nontrivial
if (type_has_refcount(this->current_type.type) && !this->holding_reference) {
throw compile_error("can\'t return reference to " + this->current_type.str(),
this->file_offset);
}
// if the function has a type annotation, enforce that the return type matches
const Value& annotated_return_type = this->fragment->function->annotated_return_type;
if ((annotated_return_type.type != ValueType::Indeterminate) &&
(this->global->match_value_to_type(annotated_return_type, this->current_type) < 0)) {
throw compile_error("returned value does not match type annotation", this->file_offset);
}
// record this return type
this->function_return_types.emplace(this->current_type);
// if we're inside a finally block, there may be an active exception. but a
// return statement inside a finally block should cause the exception to be
// suppressed - for now we don't support this
// TODO: implement this case
if (this->in_finally_block) {
throw compile_error("return statement inside finally block", this->file_offset);
}
// generate a jump to the end of the function (this is right before the
// relevant destructor calls)
// TODO: this is wrong; it doesn't cause enclosing finally blocks to execute.
// we should unwind the exception blocks until the end of the function
this->as.write_label(string_printf("__ReturnStatement_%p_return", a));
this->as.write_jmp(this->return_label);
}
void CompilationVisitor::visit(RaiseStatement* a) {
this->file_offset = a->file_offset;
// we only support the one-argument form of the raise statement
if (a->value.get() || a->traceback.get()) {
throw compile_error("raise statement may only take one argument",
this->file_offset);
}
// we'll construct the exception object into r15
this->as.write_label(string_printf("__RaiseStatement_%p_evaluate_object", a));
a->type->accept(this);
// now jump to unwind_exception
this->as.write_label(string_printf("__RaiseStatement_%p_unwind", a));
this->as.write_mov(r15, MemoryReference(this->target_register));
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
}
void CompilationVisitor::visit(YieldStatement* a) {
this->file_offset = a->file_offset;
// TODO
throw compile_error("YieldStatement not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(SingleIfStatement* a) {
this->file_offset = a->file_offset;
throw compile_error("SingleIfStatement used instead of subclass",
this->file_offset);
}
void CompilationVisitor::visit(IfStatement* a) {
this->file_offset = a->file_offset;
// if the condition is always true, skip the condition check, elifs and else,
// and just generate the body
if (a->always_true) {
this->as.write_label(string_printf("__IfStatement_%p_always_true", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
return;
}
string false_label = string_printf("__IfStatement_%p_condition_false", a);
string end_label = string_printf("__IfStatement_%p_end", a);
// if the condition is always false, go directly to the elifs/else
if (a->always_false) {
this->as.write_label(string_printf("__IfStatement_%p_always_false", a));
} else {
// if the condition is always true, skip generating the condition check
if (!a->always_true) {
this->as.write_label(string_printf("__IfStatement_%p_condition", a));
this->target_register = this->available_register();
a->check->accept(this);
this->as.write_label(string_printf("__IfStatement_%p_test", a));
this->write_current_truth_value_test();
this->as.write_jz(false_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
} else {
this->as.write_label(string_printf("__IfStatement_%p_always_true", a));
}
// generate the body statements, then jump to the end (skip the elifs/else
// if the condition was true)
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
this->as.write_jmp(end_label);
}
// write the elif clauses
for (auto& elif : a->elifs) {
// if the condition is always false, just skip it entirely
if (elif->always_false) {
continue;
}
// this is where execution should resume if the previous block didn't run
this->as.write_label(false_label);
false_label = string_printf("__IfStatement_%p_elif_%p_condition_false",
a, elif.get());
// if the condition is always true, skip the condition check and just
// generate the body. no other elifs, nor the else block
if (elif->always_true) {
elif->accept(this);
this->as.write_label(end_label);
return;
}
// generate the condition check
this->as.write_label(string_printf("__IfStatement_%p_elif_%p_condition",
a, elif.get()));
this->target_register = this->available_register();
elif->check->accept(this);
this->as.write_label(string_printf("__IfStatement_%p_elif_%p_test", a,
elif.get()));
this->write_current_truth_value_test();
this->as.write_jz(false_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
// generate the body
elif->accept(this);
this->as.write_jmp(end_label);
}
// generate the else block, if any. note that we don't get here if any of the
// if blocks were always true
if (a->else_suite.get()) {
this->as.write_label(false_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
a->else_suite->accept(this);
} else {
this->as.write_label(false_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
}
this->as.write_label(end_label);
}
void CompilationVisitor::visit(ElseStatement* a) {
this->file_offset = a->file_offset;
// just do the sub-statements; the encapsulating logic is all in TryStatement
// or IfStatement
this->as.write_label(string_printf("__ElseStatement_%p", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
}
void CompilationVisitor::visit(ElifStatement* a) {
this->file_offset = a->file_offset;
// just do the sub-statements; the encapsulating logic is all in IfStatement
this->as.write_label(string_printf("__ElifStatement_%p", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
}
void CompilationVisitor::visit(ForStatement* a) {
this->file_offset = a->file_offset;
// get the collection object and save it on the stack
this->as.write_label(string_printf("__ForStatement_%p_get_collection", a));
a->collection->accept(this);
Value collection_type = this->current_type;
this->write_push(this->target_register);
// we'll use rbx for some loop state (e.g. the item index in lists)
if (this->target_register == rbx) {
throw compile_error("cannot use rbx as target register for list iteration", this->file_offset);
}
this->write_push(rbx);
this->as.write_xor(rbx, rbx);
try {
string next_label = string_printf("__ForStatement_%p_next", a);
string end_label = string_printf("__ForStatement_%p_complete", a);
string break_label = string_printf("__ForStatement_%p_broken", a);
if ((collection_type.type == ValueType::List) ||
(collection_type.type == ValueType::Tuple)) {
// tuples containing disparate types can't be iterated
if ((collection_type.type == ValueType::Tuple) &&
(!collection_type.extension_types.empty())) {
Value uniform_extension_type = collection_type.extension_types[0];
for (const Value& extension_type : collection_type.extension_types) {
if (uniform_extension_type != extension_type) {
string uniform_str = uniform_extension_type.str();
string other_str = extension_type.str();
throw compile_error(string_printf(
"can\'t iterate over Tuple with disparate types (contains %s and %s)",
uniform_str.c_str(), other_str.c_str()), this->file_offset);
}
}
}
ValueType item_type = collection_type.extension_types[0].type;
this->as.write_label(next_label);
// get the list/tuple object
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(rsp, 8));
// check if we're at the end and skip the body if so
this->as.write_cmp(rbx, MemoryReference(this->target_register, 0x10));
this->as.write_jge(end_label);
// get the next item
if (collection_type.type == ValueType::List) {
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(this->target_register, 0x28));
if (item_type == ValueType::Float) {
this->as.write_movq_to_xmm(this->float_target_register,
MemoryReference(this->target_register, 0, rbx, 8));
} else {
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(this->target_register, 0, rbx, 8));
}
} else {
if (item_type == ValueType::Float) {
this->as.write_movq_to_xmm(this->float_target_register,
MemoryReference(this->target_register, 0x18, rbx, 8));
} else {
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(this->target_register, 0x18, rbx, 8));
}
}
// increment the item index
this->as.write_inc(rbx);
// if the extension type has a refcount, add a reference
if (type_has_refcount(item_type)) {
this->write_add_reference(this->target_register);
}
// load the value into the correct local variable slot
this->as.write_label(string_printf("__ForStatement_%p_write_value", a));
this->current_type = collection_type.extension_types[0];
a->variable->accept(this);
// do the loop body
this->as.write_label(string_printf("__ForStatement_%p_body", a));
this->break_label_stack.emplace_back(break_label);
this->continue_label_stack.emplace_back(next_label);
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) {
this->continue_label_stack.pop_back();
this->break_label_stack.pop_back();
throw;
}
this->continue_label_stack.pop_back();
this->break_label_stack.pop_back();
this->as.write_jmp(next_label);
this->as.write_label(end_label);
} else if (collection_type.type == ValueType::Dict) {
int64_t previously_reserved_registers = this->write_push_reserved_registers();
// create a SlotContents structure
// TODO: figure out how this structure interacts with refcounting and
// exceptions (or if it does at all)
this->adjust_stack(-sizeof(DictionaryObject::SlotContents));
try {
this->as.write_mov(MemoryReference(rsp, 0), 0);
this->as.write_mov(MemoryReference(rsp, 8), 0);
this->as.write_mov(MemoryReference(rsp, 16), 0);
// get the dict object and SlotContents pointer. we +8 to the offset
// because we saved rbx between the SlotContents struct and the
// collection pointer
this->as.write_label(next_label);
this->as.write_mov(rdi, MemoryReference(rsp,
sizeof(DictionaryObject::SlotContents) + 8));
this->write_add_reference(rdi);
this->as.write_mov(rdi, MemoryReference(rsp,
sizeof(DictionaryObject::SlotContents) + 8));
this->as.write_mov(rsi, rsp);
// call dictionary_next_item
this->write_function_call(
common_object_reference(void_fn_ptr(&dictionary_next_item)), {rdi, rsi}, {});
// if dictionary_next_item returned 0, then we're done
this->as.write_test(rax, rax);
this->as.write_je(end_label);
// get the key pointer
this->as.write_mov(MemoryReference(this->target_register),
MemoryReference(rsp, 0));
// if the extension type has a refcount, add a reference
if (type_has_refcount(collection_type.extension_types[0].type)) {
this->write_add_reference(this->target_register);
}
// load the value into the correct local variable slot
this->as.write_label(string_printf("__ForStatement_%p_write_key_value", a));
this->current_type = collection_type.extension_types[0];
a->variable->accept(this);
// do the loop body
this->as.write_label(string_printf("__ForStatement_%p_body", a));
this->break_label_stack.emplace_back(break_label);
this->continue_label_stack.emplace_back(next_label);
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) {
this->continue_label_stack.pop_back();
this->break_label_stack.pop_back();
throw;
}
this->continue_label_stack.pop_back();
this->break_label_stack.pop_back();
this->as.write_jmp(next_label);
this->as.write_label(end_label);
} catch (const terminated_by_split&) {
this->adjust_stack(sizeof(DictionaryObject::SlotContents));
this->write_pop_reserved_registers(previously_reserved_registers);
throw;
}
this->adjust_stack(sizeof(DictionaryObject::SlotContents));
this->write_pop_reserved_registers(previously_reserved_registers);
} else {
throw compile_error("iteration not implemented for " + collection_type.str(),
this->file_offset);
}
// if there's an else statement, generate the body here
if (a->else_suite.get()) {
a->else_suite->accept(this);
}
// any break statement will jump over the loop body and the else statement
this->as.write_label(break_label);
} catch (const terminated_by_split&) {
// note: all collection types have refcounts, so we don't check the type of
// target_register here
this->write_pop(rbx);
this->write_pop(this->target_register);
this->write_delete_reference(MemoryReference(this->target_register),
collection_type.type);
throw;
}
this->write_pop(rbx);
this->write_pop(this->target_register);
this->write_delete_reference(MemoryReference(this->target_register),
collection_type.type);
}
void CompilationVisitor::visit(WhileStatement* a) {
this->file_offset = a->file_offset;
string start_label = string_printf("__WhileStatement_%p_condition", a);
string end_label = string_printf("__WhileStatement_%p_condition_false", a);
string break_label = string_printf("__WhileStatement_%p_broken", a);
// generate the condition check
this->as.write_label(start_label);
this->target_register = this->available_register();
a->condition->accept(this);
this->write_current_truth_value_test();
this->as.write_jz(end_label);
// generate the loop body
this->write_delete_held_reference(MemoryReference(this->target_register));
this->as.write_label(string_printf("__WhileStatement_%p_body", a));
this->break_label_stack.emplace_back(break_label);
this->continue_label_stack.emplace_back(start_label);
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
this->continue_label_stack.pop_back();
this->break_label_stack.pop_back();
this->as.write_jmp(start_label);
// when the loop ends normally, we may still be holding a reference to the
// condition result
this->as.write_label(end_label);
this->write_delete_held_reference(MemoryReference(this->target_register));
// if there's an else statement, generate the body here
if (a->else_suite.get()) {
a->else_suite->accept(this);
}
// any break statement will jump over the loop body and the else statement
this->as.write_label(break_label);
}
void CompilationVisitor::visit(ExceptStatement* a) {
this->file_offset = a->file_offset;
// just do the sub-statements; the encapsulating logic is all in TryStatement
this->as.write_label(string_printf("__FinallyStatement_%p", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
}
void CompilationVisitor::visit(FinallyStatement* a) {
this->file_offset = a->file_offset;
bool prev_in_finally_block = this->in_finally_block;
this->in_finally_block = true;
// we save the active exception and clear it, so the finally block can contain
// further try/except blocks without clobbering the active exception
this->as.write_label(string_printf("__FinallyStatement_%p_save_exc", a));
this->write_push(r15);
this->as.write_xor(r15, r15);
this->as.write_label(string_printf("__FinallyStatement_%p_body", a));
try {
this->visit_list(a->items);
} catch (const terminated_by_split&) { }
// if there's now an active exception, then the finally block raised an
// exception of its own. if there was a saved exception object, destroy it;
// then start unwinding the new exception
string no_exc_label = string_printf("__FinallyStatement_%p_no_exc", a);
string end_label = string_printf("__FinallyStatement_%p_end", a);
this->as.write_label(string_printf("__FinallyStatement_%p_restore_exc", a));
this->as.write_test(r15, r15);
this->as.write_jz(no_exc_label);
this->write_delete_reference(MemoryReference(r15, 0), ValueType::Instance);
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
// the finally block did not raise an exception, but there may be a saved
// exception. if so, unwind it now
this->as.write_label(no_exc_label);
this->write_pop(r15);
this->as.write_test(r15, r15);
this->as.write_jz(end_label);
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
this->as.write_label(end_label);
this->in_finally_block = prev_in_finally_block;
}
void CompilationVisitor::visit(TryStatement* a) {
this->file_offset = a->file_offset;
// here's how we implement exception handling:
// # all try blocks have a finally block, even if it's not defined in the code
// # let N be the number of except clauses on the try block
// try:
// # stack-allocate one exception block on the stack with exc_class_id = 0,
// # pointing to the finally block, and containing N except clause
// # blocks pointing to each except block's code
// if should_raise:
// raise KeyError() # allocate object, set r15, call unwind_exception
// # remove the exception block from the stack
// # if there's an else block, jump there
// # if there's a finally block, jump there
// # jump to end of suite chain
// except KeyError as e:
// # let this exception block's index be I
// # if the exception has a name (is assigned to a local variable), then
// # write r15 to that variable; else, delete the object pointed to by
// # r15 and clear r15
// # note: don't remove the exception block from the stack; this was already
// # done by unwind_exception
// print('caught KeyError')
// # if there's a finally block, jump there
// # jump to end of suite chain
// else:
// print('did not catch KeyError')
// # if there's a finally block, jump there
// # jump to end of suite chain
// finally:
// # note: we can get here with an active exception (r15 != 0)
// print('executed finally block')
// # if r15 is nonzero, call unwind_exception again
this->as.write_label(string_printf("__TryStatement_%p_create_exc_block", a));
// we jump here from other functions, so don't let any registers be reserved
int64_t previously_reserved_registers = this->write_push_reserved_registers();
// generate the exception block
string finally_label = string_printf("__TryStatement_%p_finally", a);
vector<pair<string, unordered_set<int64_t>>> label_to_class_ids;
for (size_t x = 0; x < a->excepts.size(); x++) {
string label = string_printf("__TryStatement_%p_except_%zd", a, x);
label_to_class_ids.emplace_back(make_pair(label, a->excepts[x]->class_ids));
}
size_t stack_bytes_used_on_restore = this->stack_bytes_used;
this->write_create_exception_block(label_to_class_ids, finally_label);
// generate the try block body. we catch terminated_by_split here because
// calling a split can cause an exception to be raised, and the code might
// need to catch it
try {
this->as.write_label(string_printf("__TryStatement_%p_body", a));
this->visit_list(a->items);
} catch (const terminated_by_split& e) { }
// remove the exception block from the stack
// the previous exception block pointer is the first field in the exception
// block, so load r14 from there
this->as.write_label(string_printf("__TryStatement_%p_remove_exc_blocks", a));
this->as.write_mov(r14, MemoryReference(rsp, 0));
this->adjust_stack_to(stack_bytes_used_on_restore);
// generate the else block if there is one. the exc block is already gone, so
// this code isn't covered by the except clauses, but we need to generate a
// new exc block to make this be covered by the finally clause
if (a->else_suite.get()) {
this->as.write_label(string_printf("__TryStatement_%p_create_else_exc_block", a));
this->write_create_exception_block({}, finally_label);
try {
a->else_suite->accept(this);
} catch (const terminated_by_split&) {
this->as.write_label(string_printf("__TryStatement_%p_delete_else_exc_block", a));
this->as.write_mov(r14, MemoryReference(rsp, 0));
this->adjust_stack_to(stack_bytes_used_on_restore);
throw;
}
this->as.write_label(string_printf("__TryStatement_%p_delete_else_exc_block", a));
this->as.write_mov(r14, MemoryReference(rsp, 0));
this->adjust_stack_to(stack_bytes_used_on_restore);
}
// go to the finally block
this->as.write_jmp(finally_label);
// generate the except blocks
for (size_t except_index = 0; except_index < a->excepts.size(); except_index++) {
const auto& except = a->excepts[except_index];
this->as.write_label(string_printf("__TryStatement_%p_except_%zd", a,
except_index));
// adjust our stack offset tracking appropriately. we don't write the opcode
// because the stack has already been set to this offset by
// _unwind_exception_internal; we just need to keep track of it so we can
// avoid unaligned function calls
this->adjust_stack_to(stack_bytes_used_on_restore, false);
// if the exception object isn't assigned to a name, destroy it now
if (except->name.empty()) {
this->write_delete_reference(r15, ValueType::Instance);
// else, assign the exception object to the appropriate name
} else {
this->as.write_label(string_printf("__TryStatement_%p_except_%zd_write_value",
a, except_index));
VariableLocation loc = this->location_for_variable(except->name);
// typecheck the result
// TODO: deduplicate some of this with AttributeLValueReference
Value* target_variable = NULL;
if (loc.global_module) {
if (!loc.variable_mem_valid) {
throw compile_error("exception reference not valid", a->file_offset);
}
target_variable = &loc.global_module->global_variables.at(loc.name).value;
} else {
target_variable = &this->local_variable_types.at(loc.name);
}
if (!target_variable) {
throw compile_error("target variable not found in exception block", a->file_offset);
}
if ((target_variable->type != ValueType::Instance) ||
!except->class_ids.count(target_variable->class_id)) {
throw compile_error(string_printf("variable %s is not an exception instance type",
loc.name.c_str()), a->file_offset);
}
// delete the old value if present, save the new value, and clear the active
// exception pointer
this->write_delete_reference(loc.variable_mem, loc.type.type);
this->as.write_mov(loc.variable_mem, r15);
}
// clear the active exception
this->as.write_xor(r15, r15);
// generate the except block code
this->as.write_label(string_printf("__TryStatement_%p_except_%zd_body",
a, except_index));
try {
except->accept(this);
} catch (const terminated_by_split&) { }
// we're done here; go to the finally block
// for the last except block, don't bother jumping; just fall through
if (except_index != a->excepts.size() - 1) {
this->as.write_label(string_printf("__TryStatement_%p_except_%zd_end", a,
except_index));
this->as.write_jmp(string_printf("__TryStatement_%p_finally", a));
}
}
// now we're back to the initial stack offset
this->adjust_stack_to(stack_bytes_used_on_restore, false);
// generate the finally block, if any
this->as.write_label(string_printf("__TryStatement_%p_finally", a));
if (a->finally_suite.get()) {
try {
a->finally_suite->accept(this);
} catch (const terminated_by_split&) { }
}
this->write_pop_reserved_registers(previously_reserved_registers);
}
void CompilationVisitor::visit(WithStatement* a) {
this->file_offset = a->file_offset;
// TODO
throw compile_error("WithStatement not yet implemented", this->file_offset);
}
void CompilationVisitor::visit(FunctionDefinition* a) {
this->file_offset = a->file_offset;
string base_label = string_printf("FunctionDefinition_%p_%s", a, a->name.c_str());
// if this definition is not the function being compiled, don't recur; instead
// treat it as an assignment (of the function context to the local/global var)
if (!this->fragment->function ||
(this->fragment->function->id != a->function_id)) {
// if the function being declared is a closure, fail
// TODO: actually implement this check
// write the function's context to the variable. note that Function-typed
// variables don't point directly to the code; this is necessary for us to
// figure out the right fragment at call time
auto* declared_function_context = this->global->context_for_function(a->function_id);
auto loc = this->location_for_variable(a->name);
if (!loc.variable_mem_valid) {
throw compile_error("function definition reference not valid", this->file_offset);
}
this->as.write_label("__" + base_label);
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(declared_function_context));
this->as.write_mov(loc.variable_mem, MemoryReference(this->target_register));
return;
}
// if the function being compiled is __del__ on a class, we need to set up the
// special registers within the function, since it can be called from anywhere
// (even non-nemesys code)
bool setup_special_regs = (this->fragment->function->class_id) &&
(this->fragment->function->name == "__del__");
this->write_function_setup(base_label, setup_special_regs);
this->target_register = rax;
try {
this->visit_list(a->decorators);
for (auto& arg : a->args.args) {
if (arg.default_value.get()) {
arg.default_value->accept(this);
}
}
this->visit_list(a->items);
} catch (const terminated_by_split&) {
this->write_function_cleanup(base_label, setup_special_regs);
throw;
}
// if the function is __init__, implicitly return self (the function cannot
// explicitly return a value)
if (this->fragment->function->is_class_init()) {
// the value should be returned in rax
this->as.write_label(string_printf("__FunctionDefinition_%p_return_self_from_init", a));
VariableLocation loc = this->location_for_variable("self");
if (!loc.variable_mem_valid) {
throw compile_error("self reference not valid", this->file_offset);
}
if (!type_has_refcount(loc.type.type)) {
throw compile_error("self is not an object", this->file_offset);
}
// add a reference to self and load it into rax for returning
// TODO: should we set holding_reference to true here?
this->target_register = rax;
this->as.write_mov(MemoryReference(this->target_register), loc.variable_mem);
this->write_add_reference(this->target_register);
}
this->write_function_cleanup(base_label, setup_special_regs);
}
void CompilationVisitor::visit(ClassDefinition* a) {
this->file_offset = a->file_offset;
// write the class' context to the variable
auto loc = this->location_for_variable(a->name);
if (!loc.variable_mem_valid) {
throw compile_error("self reference not valid", this->file_offset);
}
this->as.write_label(string_printf("__ClassDefinition_%p_assign", a));
auto* cls = this->global->context_for_class(a->class_id);
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(cls));
this->as.write_mov(loc.variable_mem, MemoryReference(this->target_register));
// create the class destructor function
if (!cls->destructor) {
// if none of the class attributes have destructors and it doesn't have a
// __del__ method, then the overall class destructor trivializes to free()
ssize_t del_index = -1;
try {
del_index = cls->attribute_indexes.at("__del__");
} catch (const out_of_range&) { }
bool has_subdestructors = (del_index >= 0);
if (!has_subdestructors) {
for (const auto& it : cls->attributes) {
if (type_has_refcount(it.value.type)) {
has_subdestructors = true;
break;
}
}
}
// no subdestructors; just use free()
if (!has_subdestructors) {
cls->destructor = reinterpret_cast<void*>(&free);
if (debug_flags & DebugFlag::ShowAssembly) {
fprintf(stderr, "[%s.%s:%" PRId64 "] class has trivial destructor\n",
this->module->name.c_str(), a->name.c_str(), a->class_id);
}
// there are subdestructors; have to write a destructor function
} else {
string base_label = string_printf("__ClassDefinition_%p_destructor", a);
AMD64Assembler dtor_as;
dtor_as.write_label(base_label);
// lead-in (stack frame setup)
dtor_as.write_push(rbp);
dtor_as.write_mov(rbp, rsp);
// we'll keep the object pointer in rbx since it's callee-save
dtor_as.write_push(rbx);
dtor_as.write_mov(rbx, rdi);
// align the stack
dtor_as.write_sub(rsp, 8);
// we have to add a fake reference to the object while destroying it;
// otherwise __del__ will call this destructor recursively
dtor_as.write_lock();
dtor_as.write_inc(MemoryReference(rbx, 0));
// call __del__ before deleting attribute references
if (del_index >= 0) {
// figure out what __del__ actually is
auto& del_attr = cls->attributes.at(del_index);
if (del_attr.value.type != ValueType::Function) {
throw compile_error("__del__ exists but is not a function; instead it\'s " + del_attr.value.str(), this->file_offset);
}
if (!del_attr.value.value_known) {
throw compile_error("__del__ exists but is an unknown value", this->file_offset);
}
auto* fn = this->global->context_for_function(del_attr.value.function_id);
// get or generate the Fragment object. this function should have at
// most one fragment because __del__ cannot take arguments
if (fn->fragments.size() > 1) {
throw compile_error("__del__ has multiple fragments", this->file_offset);
}
vector<Value> expected_arg_types({Value(ValueType::Instance, a->class_id, NULL)});
if (fn->fragments.empty()) {
vector<Value> arg_types({Value(ValueType::Instance, a->class_id, NULL)});
fn->fragments.emplace_back(fn, fn->fragments.size(), arg_types);
compile_fragment(this->global, fn->module, &fn->fragments.back());
}
auto fragment = fn->fragments.back();
if (fragment.arg_types != expected_arg_types) {
throw compile_error("__del__ fragment takes incorrect argument types", this->file_offset);
}
// generate the call to the fragment. note that the instance pointer is
// still in rdi, so we don't have to do anything to prepare
dtor_as.write_lock();
dtor_as.write_inc(MemoryReference(rbx, 0)); // reference for the function arg
dtor_as.write_mov(rax, reinterpret_cast<int64_t>(fragment.compiled));
dtor_as.write_call(rax);
// __del__ can add new references to the object; if this happens, don't
// proceed with the destruction
// TODO: if the refcount is zero, something has gone seriously wrong.
// what should we do in that case?
// TODO: do we need the lock prefix to do this compare?
dtor_as.write_cmp(MemoryReference(rbx, 0), 1);
dtor_as.write_je(base_label + "_proceed");
dtor_as.write_lock();
dtor_as.write_dec(MemoryReference(rbx, 0)); // fake reference
dtor_as.write_add(rsp, 8);
dtor_as.write_pop(rbx);
dtor_as.write_ret();
dtor_as.write_label(base_label + "_proceed");
}
// the first 2 fields are the refcount and destructor pointer; the rest
// are the attributes
for (size_t index = 0; index < cls->attributes.size(); index++) {
const auto& attr = cls->attributes[index];
size_t offset = cls->offset_for_attribute(index);
if (type_has_refcount(attr.value.type)) {
// write a destructor call
dtor_as.write_label(string_printf("%s_delete_reference_%s", base_label.c_str(),
attr.name.c_str()));
// if inline refcounting is disabled, call delete_reference manually
if (debug_flags & DebugFlag::NoInlineRefcounting) {
dtor_as.write_mov(rdi, MemoryReference(rbx, offset));
dtor_as.write_mov(rsi, r14);
dtor_as.write_call(common_object_reference(void_fn_ptr(&delete_reference)));
} else {
string skip_label = string_printf(
"__destructor_delete_reference_skip_%" PRIu64, offset);
// get the object pointer
dtor_as.write_mov(rdi, MemoryReference(rbx, offset));
// if the pointer is NULL, do nothing
dtor_as.write_test(rdi, rdi);
dtor_as.write_je(skip_label);
// decrement the refcount; if it's not zero, skip the destructor call
dtor_as.write_lock();
dtor_as.write_dec(MemoryReference(rdi, 0));
dtor_as.write_jnz(skip_label);
// call the destructor
dtor_as.write_mov(rax, MemoryReference(rdi, 8));
dtor_as.write_call(rax);
dtor_as.write_label(skip_label);
}
}
}
dtor_as.write_label(base_label + "_jmp_free");
// remove the fake reference to the object being destroyed. if anyone else
// added a reference in the meantime (e.g. while attributes were being
// destroyed), then they're holding a reference to an incomplete object
// and they deserve the segfault they will probably get
dtor_as.write_lock();
dtor_as.write_dec(MemoryReference(rbx, 0));
// cheating time: "return" by jumping directly to free() so it will return
// to the caller
dtor_as.write_mov(rdi, rbx);
dtor_as.write_add(rsp, 8);
dtor_as.write_pop(rbx);
dtor_as.write_pop(rbp);
dtor_as.write_jmp(common_object_reference(void_fn_ptr(&free)));
// assemble it
multimap<size_t, string> compiled_labels;
unordered_set<size_t> patch_offsets;
string compiled = dtor_as.assemble(&patch_offsets, &compiled_labels);
cls->destructor = this->global->code.append(compiled, &patch_offsets);
this->module->compiled_size += compiled.size();
if (debug_flags & DebugFlag::ShowAssembly) {
fprintf(stderr, "[%s:%" PRId64 "] class destructor assembled\n",
a->name.c_str(), a->class_id);
uint64_t addr = reinterpret_cast<uint64_t>(cls->destructor);
string disassembly = AMD64Assembler::disassemble(cls->destructor,
compiled.size(), addr, &compiled_labels);
fprintf(stderr, "\n%s\n", disassembly.c_str());
}
}
}
}
void CompilationVisitor::write_code_for_value(const Value& value) {
if (!value.value_known) {
throw compile_error("can\'t generate code for unknown value", this->file_offset);
}
this->current_type = value.type_only();
switch (value.type) {
case ValueType::Indeterminate:
throw compile_error("can\'t generate code for Indeterminate value", this->file_offset);
case ValueType::None:
this->as.write_xor(MemoryReference(this->target_register),
MemoryReference(this->target_register));
break;
case ValueType::Bool:
case ValueType::Int:
this->as.write_mov(this->target_register, value.int_value);
break;
case ValueType::Float:
this->write_load_double(this->float_target_register, value.float_value);
break;
case ValueType::Bytes:
case ValueType::Unicode: {
const void* o = (value.type == ValueType::Bytes) ?
void_fn_ptr(this->global->get_or_create_constant(*value.bytes_value)) :
void_fn_ptr(this->global->get_or_create_constant(*value.unicode_value));
this->as.write_mov(this->target_register, reinterpret_cast<int64_t>(o));
this->write_add_reference(this->target_register);
this->holding_reference = true;
break;
}
case ValueType::List:
throw compile_error("List default values not yet implemented", this->file_offset);
case ValueType::Tuple:
throw compile_error("Tuple default values not yet implemented", this->file_offset);
case ValueType::Set:
throw compile_error("Set default values not yet implemented", this->file_offset);
case ValueType::Dict:
throw compile_error("Dict default values not yet implemented", this->file_offset);
case ValueType::Function:
throw compile_error("Function default values not yet implemented", this->file_offset);
case ValueType::Class:
throw compile_error("Class default values not yet implemented", this->file_offset);
case ValueType::Module:
throw compile_error("Module default values not yet implemented", this->file_offset);
default:
throw compile_error("default value has unknown type", this->file_offset);
}
}
void CompilationVisitor::assert_not_evaluating_instance_pointer() {
if (this->evaluating_instance_pointer) {
throw compile_error("incorrect node visited when evaluating instance pointer",
this->file_offset);
}
}
ssize_t CompilationVisitor::write_function_call_stack_prep(size_t arg_count) {
ssize_t arg_stack_bytes = (arg_count > int_argument_register_order.size()) ?
((arg_count - int_argument_register_order.size()) * sizeof(int64_t)) : 0;
// make sure the stack will be aligned at call time
arg_stack_bytes += ((this->stack_bytes_used + arg_stack_bytes) & 0x0F);
if (arg_stack_bytes) {
this->adjust_stack(-arg_stack_bytes);
}
return arg_stack_bytes;
}
void CompilationVisitor::write_function_call(
const MemoryReference& function_loc,
const std::vector<MemoryReference>& int_args,
const std::vector<MemoryReference>& float_args,
ssize_t arg_stack_bytes, Register return_register, bool return_float) {
if (float_args.size() > 8) {
// TODO: we should support this in the future. probably we just stuff them
// into the stack somewhere, but need to figure out exactly where/how
throw compile_error("cannot call functions with more than 8 floating-point arguments",
this->file_offset);
}
int64_t previously_reserved_registers = this->write_push_reserved_registers();
size_t rsp_adjustment = 0;
if (arg_stack_bytes < 0) {
arg_stack_bytes = this->write_function_call_stack_prep(int_args.size());
// if any of the references are memory references based on RSP, we'll have
// to adjust them
rsp_adjustment = arg_stack_bytes;
}
// generate the list of move destinations
vector<MemoryReference> dests;
for (size_t x = 0; x < int_args.size(); x++) {
if (x < int_argument_register_order.size()) {
dests.emplace_back(int_argument_register_order[x]);
} else {
dests.emplace_back(rsp, (x - int_argument_register_order.size()) * 8);
}
}
// deal with conflicting moves by making a graph of the moves. in this graph,
// there's an edge from m1 to m2 if m1.src == m2.dest. this means m1 has to be
// done before m2 to maintain correct values. then we can just do a
// topological sort on this graph and do the moves in that order. but watch
// out: the graph can have cycles, and we'll have to break them somehow,
// probably by using stack space
unordered_map<size_t, unordered_set<size_t>> move_to_dependents;
for (size_t x = 0; x < int_args.size(); x++) {
for (size_t y = 0; y < int_args.size(); y++) {
if (x == y) {
continue;
}
if (int_args[x] == dests[y]) {
move_to_dependents[x].insert(y);
}
}
}
// DFS-based topological sort. for now just fail if a cycle is detected.
// TODO: deal with cycles somehow
deque<size_t> move_order;
vector<bool> moves_considered(int_args.size(), false);
vector<bool> moves_in_progress(int_args.size(), false);
std::function<void(size_t)> visit_move = [&](size_t x) {
if (moves_in_progress[x]) {
throw compile_error("cyclic argument move dependency", this->file_offset);
}
if (moves_considered[x]) {
return;
}
moves_in_progress[x] = true;
for (size_t y : move_to_dependents[x]) {
visit_move(y);
}
moves_in_progress[x] = false;
moves_considered[x] = true;
move_order.emplace_front(x);
};
for (size_t x = 0; x < int_args.size(); x++) {
if (moves_considered[x]) {
continue;
}
visit_move(x);
}
// generate the mov opcodes in the determined order
for (size_t arg_index : move_order) {
auto& ref = int_args[arg_index];
auto& dest = dests[arg_index];
if (ref == dest) {
continue;
}
if ((ref.base_register == rsp) && ref.field_size) {
MemoryReference new_ref(ref.base_register, ref.offset + rsp_adjustment,
ref.index_register, ref.field_size);
this->as.write_mov(dest, new_ref);
} else {
this->as.write_mov(dest, ref);
}
}
// generate the appropriate floating mov opcodes
// TODO: we need to topological sort these too, sigh
for (size_t arg_index = 0; arg_index < float_args.size(); arg_index++) {
auto& ref = float_args[arg_index];
MemoryReference dest(float_argument_register_order[arg_index]);
if (ref == dest) {
continue;
}
if (!ref.field_size) {
this->as.write_movq_to_xmm(dest.base_register, ref);
} else if (ref.base_register == rsp) {
MemoryReference new_ref(ref.base_register, ref.offset + rsp_adjustment,
ref.index_register, ref.field_size);
this->as.write_movsd(dest, new_ref);
} else {
this->as.write_movsd(dest, ref);
}
}
// finally, call the function. the stack must be 16-byte aligned at this point
if (this->stack_bytes_used & 0x0F) {
throw compile_error("stack not aligned at function call", this->file_offset);
}
this->as.write_call(function_loc);
// put the return value into the target register
if (return_float) {
if ((return_register != Register::None) && (return_register != xmm0)) {
this->as.write_movsd(MemoryReference(return_register), xmm0);
}
} else {
if ((return_register != Register::None) && (return_register != rax)) {
this->as.write_mov(MemoryReference(return_register), rax);
}
}
// reclaim any reserved stack space
if (arg_stack_bytes) {
this->adjust_stack(arg_stack_bytes);
}
this->write_pop_reserved_registers(previously_reserved_registers);
}
void CompilationVisitor::write_function_setup(const string& base_label,
bool setup_special_regs) {
// get ready to rumble
this->as.write_label("__" + base_label);
this->stack_bytes_used = 8;
// lead-in (stack frame setup)
this->write_push(rbp);
this->as.write_mov(rbp, rsp);
// figure out how much stack space is needed
unordered_map<string, Register> int_arg_to_register;
unordered_map<string, int64_t> int_arg_to_stack_offset;
unordered_map<string, Register> float_arg_to_register;
size_t arg_stack_offset = sizeof(int64_t) * (setup_special_regs ? 6 : 2); // account for ret addr, rbp, and maybe special regs
for (size_t arg_index = 0; arg_index < this->fragment->function->args.size(); arg_index++) {
const auto& arg = this->fragment->function->args[arg_index];
bool is_float;
try {
is_float = this->local_variable_types.at(arg.name).type == ValueType::Float;
} catch (const out_of_range&) {
throw compile_error(string_printf("argument %s not present in local_variable_types",
arg.name.c_str()), this->file_offset);
}
if (is_float) {
if (float_arg_to_register.size() >= float_argument_register_order.size()) {
throw compile_error("function accepts too many float args", this->file_offset);
}
float_arg_to_register.emplace(arg.name,
float_argument_register_order[float_arg_to_register.size()]);
} else if (int_arg_to_register.size() < int_argument_register_order.size()) {
int_arg_to_register.emplace(arg.name,
int_argument_register_order[int_arg_to_register.size()]);
} else {
int_arg_to_stack_offset.emplace(arg.name, arg_stack_offset);
arg_stack_offset += sizeof(int64_t);
}
}
// reserve space for locals and special regs
size_t num_stack_slots = this->fragment->function->locals.size() + (setup_special_regs ? 4 : 0);
this->adjust_stack(num_stack_slots * -sizeof(int64_t));
// save special regs if needed
if (setup_special_regs) {
this->as.write_mov(MemoryReference(rsp, 0), r12);
this->as.write_mov(MemoryReference(rsp, 8), r13);
this->as.write_mov(MemoryReference(rsp, 16), r14);
this->as.write_mov(MemoryReference(rsp, 24), r15);
this->as.write_mov(r12, reinterpret_cast<int64_t>(common_object_base()));
this->as.write_mov(r13, reinterpret_cast<int64_t>(this->module->global_space));
this->as.write_xor(r14, r14);
this->as.write_xor(r15, r15);
}
// set up the local space. note that local_index starts at 0 (hence 1 during
// the first loop) on purpose - this is the negative offset from rbp for the
// current local
ssize_t local_index = 0;
for (const auto& local : this->fragment->function->locals) {
local_index++;
MemoryReference dest(rbp, local_index * -8);
// if it's a float arg, write it from the xmm reg
try {
Register xmm_reg = float_arg_to_register.at(local.first);
MemoryReference xmm_mem(xmm_reg);
this->as.write_movsd(dest, xmm_mem);
continue;
} catch (const out_of_range&) { }
// if it's an int arg, write it from the reg
try {
this->as.write_mov(dest, MemoryReference(int_arg_to_register.at(local.first)));
continue;
} catch (const out_of_range&) { }
// if it's a stack arg, load it into a temp register, then save it again
try {
this->as.write_mov(rax, MemoryReference(rbp,
int_arg_to_stack_offset.at(local.first)));
this->as.write_mov(dest, rax);
continue;
} catch (const out_of_range&) { }
// else, initialize it to zero
this->as.write_mov(dest, 0);
}
// set up the exception block
this->return_label = string_printf("__%s_return", base_label.c_str());
this->exception_return_label = string_printf(
"__%s_exception_return", base_label.c_str());
this->as.write_label(string_printf(
"__%s_create_except_block", base_label.c_str()));
this->write_create_exception_block({}, this->exception_return_label);
}
void CompilationVisitor::write_function_cleanup(const string& base_label,
bool setup_special_regs) {
this->as.write_label(this->return_label);
// clean up the exception block. note that this is after the return label but
// before the destroy locals label - the latter is used when an exception
// occurs, since _unwind_exception_internal already removes the exc block from
// the stack
this->write_pop(r14);
this->adjust_stack(return_exception_block_size - sizeof(int64_t));
// restore special regs if needed. note that it's ok to do this before
// destroying locals because destruction cannot depend on the global space. if
// a local has a __del__ function, it will set up its own global space pointer
if (setup_special_regs) {
this->write_pop(r12);
this->write_pop(r13);
this->write_pop(r14);
this->write_pop(r15);
}
// call destructors for all the local variables that have refcounts
this->as.write_label(this->exception_return_label);
this->return_label.clear();
this->exception_return_label.clear();
for (auto it = this->fragment->function->locals.crbegin();
it != this->fragment->function->locals.crend(); it++) {
if (type_has_refcount(it->second.type)) {
// we have to preserve the value in rax since it's the function's return
// value, so store it on the stack (in the location we're destroying)
// while we destroy the object
this->as.write_xchg(rax, MemoryReference(rsp, 0));
this->write_delete_reference(rax, it->second.type);
this->write_pop(rax);
} else {
// no destructor; just skip it
// TODO: we can coalesce these adds for great justice
this->adjust_stack(8);
}
}
// hooray we're done
this->as.write_label(string_printf("__%s_leave_frame", base_label.c_str()));
this->write_pop(rbp);
if (this->stack_bytes_used != 8) {
throw compile_error(string_printf(
"stack misaligned at end of function (%" PRId64 " bytes used; should be 8)",
this->stack_bytes_used), this->file_offset);
}
this->as.write_ret();
}
void CompilationVisitor::write_add_reference(Register addr_reg) {
if (debug_flags & DebugFlag::NoInlineRefcounting) {
this->reserve_register(addr_reg);
this->write_function_call(common_object_reference(void_fn_ptr(&add_reference)),
{MemoryReference(addr_reg)}, {});
this->release_register(addr_reg);
} else {
this->as.write_lock();
this->as.write_inc(MemoryReference(addr_reg, 0));
}
// TODO: we should check if the value is 1. if it is, then we've encountered a
// data race, and another thread is currently deleting this object!
}
void CompilationVisitor::write_delete_held_reference(const MemoryReference& mem) {
if (this->holding_reference) {
if (!type_has_refcount(this->current_type.type)) {
throw compile_error("holding a reference to a trivial type: " + this->current_type.str(), this->file_offset);
}
this->write_delete_reference(mem, this->current_type.type);
this->holding_reference = false;
}
}
void CompilationVisitor::write_delete_reference(const MemoryReference& mem,
ValueType type) {
if (type == ValueType::Indeterminate) {
throw compile_error("can\'t call destructor for Indeterminate value", this->file_offset);
}
if (!type_has_refcount(type)) {
return;
}
if (debug_flags & DebugFlag::NoInlineRefcounting) {
this->write_function_call(common_object_reference(void_fn_ptr(&delete_reference)),
{mem, r14}, {});
} else {
static uint64_t skip_label_id = 0;
string skip_label = string_printf("__delete_reference_skip_%" PRIu64,
skip_label_id++);
Register r = this->available_register();
MemoryReference r_mem(r);
// get the object pointer
if (mem.field_size || (r != mem.base_register)) {
this->as.write_mov(r_mem, mem);
}
// if the pointer is NULL, do nothing
this->as.write_test(r_mem, r_mem);
this->as.write_je(skip_label);
// decrement the refcount; if it's not zero, skip the destructor call
this->as.write_lock();
this->as.write_dec(MemoryReference(r, 0));
this->as.write_jnz(skip_label);
// call the destructor
MemoryReference function_loc(r, 8);
this->write_function_call(function_loc, {r_mem}, {});
this->as.write_label(skip_label);
}
}
void CompilationVisitor::write_alloc_class_instance(int64_t class_id,
bool initialize_attributes) {
auto* cls = this->global->context_for_class(class_id);
static uint64_t skip_label_id = 0;
string skip_label = string_printf("__alloc_class_instance_skip_%" PRIu64,
skip_label_id++);
// call malloc to create the class object. note that the stack is already
// adjusted to the right alignment here
// note: this is a semi-ugly hack, but we ignore reserved registers here
// because this can only be the first argument - no registers can be
// reserved at this point
int64_t stack_bytes_used = this->write_function_call_stack_prep();
this->as.write_mov(rdi, cls->instance_size());
this->as.write_call(common_object_reference(void_fn_ptr(&malloc)));
this->adjust_stack(stack_bytes_used);
// check if the result is NULL and raise MemoryError in that case
this->as.write_test(rax, rax);
this->as.write_jnz(skip_label);
this->as.write_mov(rax, common_object_reference(&MemoryError_instance));
this->write_add_reference(rax);
this->as.write_mov(r15, rax);
this->as.write_jmp(
common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
this->as.write_label(skip_label);
// fill in the refcount, destructor function and class id
Register tmp = this->available_register_except({rax});
MemoryReference tmp_mem(tmp);
if (this->target_register != rax) {
this->as.write_mov(MemoryReference(this->target_register), rax);
}
this->as.write_mov(MemoryReference(this->target_register, 0), 1);
this->as.write_mov(tmp, reinterpret_cast<int64_t>(cls->destructor));
this->as.write_mov(MemoryReference(this->target_register, 8), tmp_mem);
this->as.write_mov(MemoryReference(this->target_register, 16), class_id);
// zero everything else in the class, if it has any attributes
if (initialize_attributes && (cls->instance_size() != sizeof(InstanceObject))) {
this->as.write_xor(tmp_mem, tmp_mem);
for (ssize_t x = sizeof(InstanceObject); x < cls->instance_size(); x += 8) {
this->as.write_mov(MemoryReference(this->target_register, x), tmp_mem);
}
}
}
void CompilationVisitor::write_raise_exception(int64_t class_id,
const wchar_t* message) {
const auto* cls = this->global->context_for_class(class_id);
this->write_alloc_class_instance(class_id, false);
if (message) {
// this form can only be used for exceptions that take exactly one argument
if (cls->instance_size() != sizeof(InstanceObject) + 2 * sizeof(void*)) {
throw compile_error("incorrect exception raise form generated", this->file_offset);
}
// set message
size_t message_index = cls->attribute_indexes.at("message");
size_t message_offset = cls->offset_for_attribute(message_index);
const UnicodeObject* constant = this->global->get_or_create_constant(message);
this->as.write_mov(r15, reinterpret_cast<int64_t>(constant));
this->as.write_mov(MemoryReference(this->target_register, message_offset), r15);
} else {
// this form can only be used for exceptions that don't take an argument
if (cls->instance_size() != sizeof(InstanceObject) + sizeof(void*)) {
throw compile_error("incorrect exception raise form generated", this->file_offset);
}
}
// set __init__
size_t init_index = cls->attribute_indexes.at("__init__");
size_t init_offset = cls->offset_for_attribute(init_index);
const auto* cls_init = this->global->context_for_function(class_id);
this->as.write_mov(r15, reinterpret_cast<int64_t>(cls_init));
this->as.write_mov(MemoryReference(this->target_register, init_offset), r15);
this->as.write_mov(r15, MemoryReference(this->target_register));
// raise the exception
this->as.write_jmp(common_object_reference(void_fn_ptr(&_unwind_exception_internal)));
}
void CompilationVisitor::write_create_exception_block(
const vector<pair<string, unordered_set<int64_t>>>& label_to_class_ids,
const string& exception_return_label) {
Register tmp_rsp = this->available_register();
Register tmp = this->available_register_except({tmp_rsp});
MemoryReference tmp_mem(tmp);
this->as.write_mov(MemoryReference(tmp_rsp), rsp);
this->write_push(0);
this->as.write_mov(tmp, exception_return_label);
this->write_push(tmp);
// label_to_class_ids is in the order that the except blocks are declared in
// the file, so we need to push them in the opposite order (so the first one
// appears earliest in memory and will match first)
for (auto it = label_to_class_ids.rbegin(); it != label_to_class_ids.rend(); it++) {
const string& target_label = it->first;
const auto& class_ids = it->second;
if (class_ids.size() == 0) {
throw compile_error("non-finally block contained zero class ids",
this->file_offset);
}
for (int64_t class_id : class_ids) {
this->write_push(class_id);
}
this->write_push(class_ids.size());
this->as.write_mov(tmp, target_label);
this->write_push(tmp);
}
this->write_push(r13);
this->write_push(r12);
this->write_push(rbp);
this->write_push(tmp_rsp);
this->write_push(r14);
this->as.write_mov(r14, rsp);
}
void CompilationVisitor::write_push(Register reg) {
this->as.write_push(reg);
this->stack_bytes_used += 8;
}
void CompilationVisitor::write_push(const MemoryReference& mem) {
this->as.write_push(mem);
this->stack_bytes_used += 8;
}
void CompilationVisitor::write_push(int64_t value) {
this->as.write_push(value);
this->stack_bytes_used += 8;
}
void CompilationVisitor::write_pop(Register reg) {
this->stack_bytes_used -= 8;
this->as.write_pop(reg);
}
void CompilationVisitor::adjust_stack(ssize_t bytes, bool write_opcode) {
if (!bytes) {
return;
}
if (write_opcode) {
if (bytes < 0) {
this->as.write_sub(rsp, -bytes);
} else {
this->as.write_add(rsp, bytes);
}
}
this->stack_bytes_used -= bytes;
}
void CompilationVisitor::adjust_stack_to(ssize_t bytes, bool write_opcode) {
this->adjust_stack(this->stack_bytes_used - bytes, write_opcode);
}
void CompilationVisitor::write_load_double(Register reg, double value) {
Register tmp = this->available_register();
const int64_t* int_value = reinterpret_cast<const int64_t*>(&value);
this->as.write_mov(tmp, *int_value);
this->as.write_movq_to_xmm(this->float_target_register, MemoryReference(tmp));
}
void CompilationVisitor::write_read_variable(Register target_register,
Register float_target_register, const VariableLocation& loc) {
MemoryReference variable_mem = loc.variable_mem;
// if variable_mem isn't valid, we're reading an attribute from a different
// module; we need to get the module's global space pointer and then look up
// the attribute
if (!loc.variable_mem_valid) {
this->as.write_mov(target_register, reinterpret_cast<int64_t>(loc.global_module->global_space));
variable_mem = MemoryReference(target_register, loc.global_index * sizeof(int64_t));
}
if (loc.type.type == ValueType::Float) {
this->as.write_movq_to_xmm(float_target_register, variable_mem);
} else {
this->as.write_mov(MemoryReference(target_register), variable_mem);
if (type_has_refcount(loc.type.type)) {
this->write_add_reference(target_register);
}
}
}
void CompilationVisitor::write_write_variable(Register value_register,
Register float_value_register, const VariableLocation& loc) {
MemoryReference variable_mem = loc.variable_mem;
// if variable_mem isn't valid, we're writing an attribute on a different
// module; we need to get the module's global space pointer and then look up
// the attribute
Register target_module_global_space_reg;
if (!loc.variable_mem_valid) {
target_module_global_space_reg = this->available_register_except({value_register});
this->as.write_mov(target_module_global_space_reg, reinterpret_cast<int64_t>(loc.global_module->global_space));
variable_mem = MemoryReference(target_module_global_space_reg, loc.global_index * sizeof(int64_t));
}
// if the type has a refcount, delete the old value
if (type_has_refcount(loc.type.type)) {
this->write_delete_reference(variable_mem, loc.type.type);
}
// write the value into the right attribute
if (loc.type.type == ValueType::Float) {
this->as.write_movsd(variable_mem, MemoryReference(float_value_register));
} else {
this->as.write_mov(variable_mem, MemoryReference(value_register));
}
}
CompilationVisitor::VariableLocation CompilationVisitor::location_for_global(
ModuleContext* module, const string& name) {
try {
const auto& var = module->global_variables.at(name);
VariableLocation loc;
loc.name = name;
loc.type = var.value;
loc.global_module = module;
loc.global_index = var.index;
if (loc.global_module == this->module) {
loc.variable_mem = MemoryReference(r13, loc.global_index * sizeof(int64_t));
loc.variable_mem_valid = true;
}
return loc;
} catch (const out_of_range&) {
throw compile_error("nonexistent global: " + name, this->file_offset);
}
}
CompilationVisitor::VariableLocation CompilationVisitor::location_for_variable(
const string& name) {
// if we're writing a global, use its global slot offset (from R13)
if (this->fragment->function &&
this->fragment->function->explicit_globals.count(name) &&
this->fragment->function->locals.count(name)) {
throw compile_error("explicit global is also a local", this->file_offset);
}
if (!this->fragment->function || !this->fragment->function->locals.count(name)) {
return this->location_for_global(this->module, name);
}
// if we're writing a local, use its local slot offset (from RBP)
auto it = this->fragment->function->locals.find(name);
if (it == this->fragment->function->locals.end()) {
throw compile_error("nonexistent local: " + name, this->file_offset);
}
VariableLocation loc;
loc.name = name;
loc.variable_mem = MemoryReference(rbp, sizeof(int64_t) * (-static_cast<ssize_t>(1 + distance(this->fragment->function->locals.begin(), it))));
loc.variable_mem_valid = true;
// use the argument type if given
try {
loc.type = this->local_variable_types.at(name);
} catch (const out_of_range&) {
loc.type = it->second;
}
return loc;
}
CompilationVisitor::VariableLocation CompilationVisitor::location_for_attribute(
ClassContext* cls, const string& name, Register instance_reg) {
VariableLocation loc;
loc.name = name;
try {
size_t index = cls->attribute_indexes.at(name);
loc.variable_mem = MemoryReference(instance_reg, cls->offset_for_attribute(index));
loc.variable_mem_valid = true;
loc.type = cls->attributes.at(index).value;
} catch (const out_of_range& e) {
throw compile_error("cannot generate lookup for missing attribute " + name,
this->file_offset);
}
return loc;
}
| 39.515987 | 145 | 0.689272 | [
"object",
"vector"
] |
d5dd13ace27ecf5abbbfdf587c40b7925c8709a2 | 3,934 | cpp | C++ | Samples/Server/Directx-Multithreaded/MultiDeviceContextDXUTMesh.cpp | HoeniS/PoC-3DStreaming | 143e56bfb1ad1f4cc4c83d09ec277905ecebc98e | [
"MIT"
] | 224 | 2018-07-13T19:14:12.000Z | 2022-03-23T23:54:44.000Z | Samples/Server/Directx-Multithreaded/MultiDeviceContextDXUTMesh.cpp | HoeniS/PoC-3DStreaming | 143e56bfb1ad1f4cc4c83d09ec277905ecebc98e | [
"MIT"
] | 193 | 2017-07-17T16:48:04.000Z | 2018-06-12T12:53:03.000Z | Samples/Server/Directx-Multithreaded/MultiDeviceContextDXUTMesh.cpp | HoeniS/PoC-3DStreaming | 143e56bfb1ad1f4cc4c83d09ec277905ecebc98e | [
"MIT"
] | 70 | 2018-07-10T08:04:49.000Z | 2022-03-21T07:02:44.000Z | //--------------------------------------------------------------------------------------
// File: MultiDeviceContextDXUTMesh.cpp
//
// Extended implementation of DXUT Mesh for M/T rendering
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "MultiDeviceContextDXUTMesh.h"
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT CMultiDeviceContextDXUTMesh::Create( ID3D11Device* pDev11, LPCWSTR szFileName,
MDC_SDKMESH_CALLBACKS11* pCallbacks )
{
if ( pCallbacks )
{
m_pRenderMeshCallback = pCallbacks->pRenderMesh;
}
else
{
m_pRenderMeshCallback = nullptr;
}
return CDXUTSDKMesh::Create( pDev11, szFileName, pCallbacks );
}
//--------------------------------------------------------------------------------------
// Name: RenderMesh()
// Calls the RenderMesh of the base class. We wrap this API because the base class
// version is protected and we need it to be public.
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
void CMultiDeviceContextDXUTMesh::RenderMesh( UINT iMesh,
bool bAdjacent,
ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
CDXUTSDKMesh::RenderMesh( iMesh,
bAdjacent,
pd3dDeviceContext,
iDiffuseSlot,
iNormalSlot,
iSpecularSlot );
}
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
void CMultiDeviceContextDXUTMesh::RenderFrame( UINT iFrame,
bool bAdjacent,
ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
if( !m_pStaticMeshData || !m_pFrameArray )
return;
if( m_pFrameArray[iFrame].Mesh != INVALID_MESH )
{
if ( !m_pRenderMeshCallback )
{
RenderMesh( m_pFrameArray[iFrame].Mesh,
bAdjacent,
pd3dDeviceContext,
iDiffuseSlot,
iNormalSlot,
iSpecularSlot );
}
else
{
m_pRenderMeshCallback( this,
m_pFrameArray[iFrame].Mesh,
bAdjacent,
pd3dDeviceContext,
iDiffuseSlot,
iNormalSlot,
iSpecularSlot );
}
}
// Render our children
if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].ChildFrame, bAdjacent, pd3dDeviceContext, iDiffuseSlot,
iNormalSlot, iSpecularSlot );
// Render our siblings
if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].SiblingFrame, bAdjacent, pd3dDeviceContext, iDiffuseSlot,
iNormalSlot, iSpecularSlot );
}
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
void CMultiDeviceContextDXUTMesh::Render( ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
RenderFrame( 0, false, pd3dDeviceContext, iDiffuseSlot, iNormalSlot, iSpecularSlot );
}
| 36.766355 | 101 | 0.466192 | [
"mesh",
"render"
] |
d5de04fe69480cbd39241fa7d9809692354c0bce | 17,852 | cpp | C++ | src/r3d_scene.cpp | ProjectAsura/sample_pt3 | 5696c22e0f476fb6ea8a3d8a8052e97f838740e3 | [
"MIT"
] | null | null | null | src/r3d_scene.cpp | ProjectAsura/sample_pt3 | 5696c22e0f476fb6ea8a3d8a8052e97f838740e3 | [
"MIT"
] | null | null | null | src/r3d_scene.cpp | ProjectAsura/sample_pt3 | 5696c22e0f476fb6ea8a3d8a8052e97f838740e3 | [
"MIT"
] | null | null | null | //-------------------------------------------------------------------------------------------------
// File : r3d_scene.cpp
// Desc : Scene.
// Copyright(c) Project Asura. All right reserved.
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Includes
//-------------------------------------------------------------------------------------------------
#include <r3d_scene.h>
#include <string>
#include <cassert>
#include <fstream>
#include <map>
#include <cereal/cereal.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/string.hpp>
template<typename Archive>
void serialize(Archive& archive, Vector2& value)
{
archive(
cereal::make_nvp("x", value.x),
cereal::make_nvp("y", value.y)
);
}
template<typename Archive>
void serialize(Archive& archive, Vector3& value)
{
archive(
cereal::make_nvp("x", value.x),
cereal::make_nvp("y", value.y),
cereal::make_nvp("z", value.z)
);
}
template<typename Archive>
void serialize(Archive& archive, Matrix& value)
{
archive(
cereal::make_nvp("_11", value._11),
cereal::make_nvp("_12", value._12),
cereal::make_nvp("_13", value._13),
cereal::make_nvp("_14", value._14),
cereal::make_nvp("_21", value._21),
cereal::make_nvp("_22", value._22),
cereal::make_nvp("_23", value._23),
cereal::make_nvp("_24", value._24),
cereal::make_nvp("_31", value._31),
cereal::make_nvp("_32", value._32),
cereal::make_nvp("_33", value._33),
cereal::make_nvp("_34", value._34),
cereal::make_nvp("_41", value._41),
cereal::make_nvp("_42", value._42),
cereal::make_nvp("_43", value._43),
cereal::make_nvp("_44", value._44)
);
}
struct ResTexture
{
int id;
std::string path;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(path)
);
}
};
struct ResLambert
{
int id;
Vector3 color;
Vector3 emissive;
int texture_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(color),
CEREAL_NVP(emissive),
CEREAL_NVP(texture_id)
);
}
};
struct ResMirror
{
int id;
Vector3 color;
Vector3 emissive;
int texture_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(color),
CEREAL_NVP(emissive),
CEREAL_NVP(texture_id)
);
}
};
struct ResRefract
{
int id;
Vector3 color;
Vector3 emissive;
float ior;
int texture_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(color),
CEREAL_NVP(emissive),
CEREAL_NVP(ior),
CEREAL_NVP(texture_id)
);
}
};
struct ResPhong
{
int id;
Vector3 color;
Vector3 emissive;
float shininess;
int texture_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(color),
CEREAL_NVP(emissive),
CEREAL_NVP(shininess),
CEREAL_NVP(texture_id)
);
}
};
struct ResSphere
{
int id;
Vector3 pos;
float radius;
int material_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(pos),
CEREAL_NVP(radius),
CEREAL_NVP(material_id)
);
}
};
struct ResShapeInstance
{
int id;
Matrix world;
int shape_id;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(world),
CEREAL_NVP(shape_id)
);
}
};
struct ResMesh
{
int id;
std::string path;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(id),
CEREAL_NVP(path)
);
}
};
struct ResCamera
{
Vector3 pos;
Vector3 dir;
Vector3 upward;
float fov;
float znear;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(pos),
CEREAL_NVP(dir),
CEREAL_NVP(upward),
CEREAL_NVP(fov),
CEREAL_NVP(znear)
);
}
};
struct ResThinLensCamera
{
Vector3 pos;
Vector3 dir;
Vector3 upward;
float fov_deg;
float aspect;
float znear;
float radius;
float focal_dist;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(pos),
CEREAL_NVP(dir),
CEREAL_NVP(upward),
CEREAL_NVP(fov_deg),
CEREAL_NVP(aspect),
CEREAL_NVP(znear),
CEREAL_NVP(radius),
CEREAL_NVP(focal_dist)
);
}
};
struct ResScene
{
int width;
int height;
int samples;
std::vector<ResTexture> textures;
std::vector<ResLambert> lamberts;
std::vector<ResMirror> mirrors;
std::vector<ResRefract> refracts;
std::vector<ResPhong> phongs;
std::vector<ResSphere> sphere_shapes;
std::vector<ResShapeInstance> instance_shapes;
std::vector<ResMesh> mesh_shapes;
std::vector<ResCamera> cameras;
std::string ibl_path;
template<class Archive>
void serialize(Archive& archive)
{
archive(
CEREAL_NVP(width),
CEREAL_NVP(height),
CEREAL_NVP(samples),
CEREAL_NVP(textures),
CEREAL_NVP(lamberts),
CEREAL_NVP(mirrors),
CEREAL_NVP(refracts),
CEREAL_NVP(phongs),
CEREAL_NVP(sphere_shapes),
CEREAL_NVP(mesh_shapes),
CEREAL_NVP(instance_shapes),
CEREAL_NVP(cameras),
CEREAL_NVP(ibl_path)
);
}
void default_scene()
{
int id = 1;
//width = 1280;
//height = 960;
width = 480;
height = 270;
samples = 512;
ResLambert lambert0 = {};
lambert0.id = id++;
lambert0.color = Vector3(0.25f, 0.75f, 0.25f);
lambert0.emissive = Vector3(0.0f, 0.0f, 0.0f);
ResLambert lambert1 = {};
lambert1.id = id++;
lambert1.color = Vector3(0.25f, 0.25f, 0.75f);
lambert1.emissive = Vector3(0.0f, 0.0f, 0.0f);
ResLambert lambert2 = {};
lambert2.id = id++;
lambert2.color = Vector3(0.75f, 0.75f, 0.75f);
lambert2.emissive = Vector3(0.0f, 0.0f, 0.0f);
ResLambert lambert3 = {};
lambert3.id = id++;
lambert3.color = Vector3(0.01f, 0.01f, 0.01f);
lambert3.emissive = Vector3(0.0f, 0.0f, 0.0f);
ResLambert lambert4 = {};
lambert4.id = id++;
lambert4.color = Vector3(0.0f, 0.0f, 0.0f);
lambert4.emissive = Vector3(12.0f, 12.0f, 12.0f);
lamberts.push_back(lambert0);
lamberts.push_back(lambert1);
lamberts.push_back(lambert2);
lamberts.push_back(lambert3);
lamberts.push_back(lambert4);
//ResMirror mirror0 = {};
//mirror0.id = id++;
//mirror0.color = Vector3(0.75f, 0.25f, 0.25f);
//mirror0.emissive = Vector3(0.0f, 0.0f, 0.0f);
//mirrors.push_back(mirror0);
ResRefract refract0 = {};
refract0.id = id++;
refract0.color = Vector3(0.99f, 0.99f, 0.99f);
refract0.ior = 1.5f;
refract0.emissive = Vector3(0.0f, 0.0f, 0.0f);
refracts.push_back(refract0);
id = 1;
ResSphere sphere0 = {};
sphere0.id = id++;
sphere0.radius = 1e5f;
sphere0.pos = Vector3(1e5f + 1.0f, 40.8f, 81.6f);
sphere0.material_id = lambert0.id;
ResSphere sphere1 = {};
sphere1.id = id++;
sphere1.radius = 1e5f;
sphere1.pos = Vector3(-1e5f + 99.0f, 40.8f, 81.6f);
sphere1.material_id = lambert1.id;
ResSphere sphere2 = {};
sphere2.id = id++;
sphere2.radius = 1e5f;
sphere2.pos = Vector3(50.0f, 40.8f, 1e5f);
sphere2.material_id = lambert2.id;
ResSphere sphere3 = {};
sphere3.id = id++;
sphere3.radius = 1e5f;
sphere3.pos = Vector3(50.0f, 40.8f, -1e5f + 170.0f);
sphere3.material_id = lambert3.id;
ResSphere sphere4 = {};
sphere4.id = id++;
sphere4.radius = 1e5f;
sphere4.pos = Vector3(50.0f, 1e5f, 81.6f);
sphere4.material_id = lambert2.id;
ResSphere sphere5= {};
sphere5.id = id++;
sphere5.radius = 1e5f;
sphere5.pos = Vector3(50.0f, -1e5f + 81.6f, 81.6f);
sphere5.material_id = lambert2.id;
//ResSphere sphere6 = {};
//sphere6.id = id++;
//sphere6.radius = 16.5f;
//sphere6.pos = Vector3(27.0f, 16.5f, 47.0f);
//sphere6.material_id = mirror0.id;
ResSphere sphere7 = {};
sphere7.id = id++;
sphere7.radius = 16.5f;
sphere7.pos = Vector3(73.0f, 16.5f, 78.0f);
sphere7.material_id = refract0.id;
ResSphere sphere8 = {};
sphere8.id = id++;
sphere8.radius = 5.0f;
sphere8.pos = Vector3(50.0f, 81.6f, 81.6f);
sphere8.material_id = lambert4.id;
sphere_shapes.push_back(sphere0);
sphere_shapes.push_back(sphere1);
sphere_shapes.push_back(sphere2);
sphere_shapes.push_back(sphere3);
sphere_shapes.push_back(sphere4);
sphere_shapes.push_back(sphere5);
//sphere_shapes.push_back(sphere6);
sphere_shapes.push_back(sphere7);
sphere_shapes.push_back(sphere8);
ResMesh mesh0;
mesh0.id = id++;
mesh0.path = "domo.smd";
mesh_shapes.push_back(mesh0);
ResCamera camera = {};
camera.pos = Vector3(50.0f, 52.0f, 295.6f);
camera.dir = normalize(Vector3(0.0f, -0.042612f, -1.0f));
camera.upward = Vector3(0.0f, 1.0f, 0.0f);
camera.fov = 45.0f;
camera.znear = 130.0f;
cameras.push_back(camera);
ibl_path = "HDR_041_Path.hdr";
}
};
Scene::Scene()
: m_cam(nullptr)
{ /* DO_NOTHING */ }
Scene::~Scene()
{ dispose(); }
bool Scene::load(const char* filename)
{
dispose();
std::ifstream stream(filename);
if (!stream.is_open())
{ return false; }
{
ResScene res;
cereal::XMLInputArchive arc(stream);
arc(cereal::make_nvp("scene", res));
m_w = res.width;
m_h = res.height;
m_s = res.samples;
if (!res.textures.empty())
{
m_texs.resize(res.textures.size());
for(size_t i=0; i<m_texs.size(); ++i)
{
m_texs[i] = new(std::nothrow) Texture();
if (!m_texs[i]->load(res.textures[i].path.c_str()))
{
fprintf_s(stderr, "Error : Texture Load Failed. %s\n", res.textures[i].path.c_str());
}
}
}
std::map<int, size_t> matid_dic;
if (!res.lamberts.empty())
{
for(size_t i=0; i<res.lamberts.size(); ++i)
{
auto lambert = Lambert::create(res.lamberts[i].color, res.lamberts[i].emissive);
auto idx = m_mats.size();
m_mats.push_back(lambert);
matid_dic[res.lamberts[i].id] = idx;
}
}
if (!res.mirrors.empty())
{
for(size_t i=0; i<res.mirrors.size(); ++i)
{
auto mirror = Mirror::create(res.mirrors[i].color, res.mirrors[i].emissive);
auto idx = m_mats.size();
m_mats.push_back(mirror);
matid_dic[res.mirrors[i].id] = idx;
}
}
if (!res.refracts.empty())
{
for(size_t i=0; i<res.refracts.size(); ++i)
{
auto refract = Refract::create(res.refracts[i].color, res.refracts[i].ior, res.refracts[i].emissive);
auto idx = m_mats.size();
m_mats.push_back(refract);
matid_dic[res.refracts[i].id] = idx;
}
}
if (!res.phongs.empty())
{
for(size_t i=0; i<res.phongs.size(); ++i)
{
auto phong = Phong::create(res.phongs[i].color, res.phongs[i].shininess, res.phongs[i].emissive);
auto idx = m_mats.size();
matid_dic[res.phongs[i].id] = idx;
}
}
m_mats.shrink_to_fit();
std::map<int, size_t> shapeid_dic;
if (!res.sphere_shapes.empty())
{
for(size_t i=0; i<res.sphere_shapes.size(); ++i)
{
auto idx = matid_dic[res.sphere_shapes[i].material_id];
auto mat = m_mats[idx];
auto shape = Sphere::create(res.sphere_shapes[i].radius, res.sphere_shapes[i].pos, mat);
auto id = m_objs.size();
m_objs.push_back(shape);
shapeid_dic[res.sphere_shapes[i].id] = id;
}
}
if (!res.mesh_shapes.empty())
{
for(size_t i=0; i<res.mesh_shapes.size(); ++i)
{
auto shape = Mesh::create(res.mesh_shapes[i].path.c_str());
auto id = m_objs.size();
m_objs.push_back(shape);
shapeid_dic[res.mesh_shapes[i].id] = id;
}
}
if (!res.instance_shapes.empty())
{
for(size_t i=0; i<res.instance_shapes.size(); ++i)
{
auto idx = shapeid_dic[res.instance_shapes[i].shape_id];
auto obj = m_objs[idx];
auto shape = ShapeInstance::create(obj, res.instance_shapes[i].world);
auto id = m_objs.size();
m_objs.push_back(shape);
shapeid_dic[res.instance_shapes[i].id] = id;
}
}
m_objs.shrink_to_fit();
if (!res.cameras.empty())
{
m_cam = new (std::nothrow) Camera(
res.cameras[0].pos,
res.cameras[0].dir,
res.cameras[0].upward,
radian(res.cameras[0].fov),
res.cameras[0].znear,
float(m_w),
float(m_h));
}
if (!res.ibl_path.empty())
{
m_ibl = new (std::nothrow) Texture();
if (!m_ibl->load(res.ibl_path.c_str()))
{
fprintf_s(stderr, "Error : IBL texture load failed. path = %s\n", res.ibl_path.c_str());
}
}
}
return true;
}
bool Scene::save(const char* filename)
{
std::ofstream stream(filename);
if (!stream.is_open())
{ return false; }
{
ResScene res;
res.default_scene();
cereal::XMLOutputArchive arc(stream);
arc(cereal::make_nvp("scene", res));
}
return true;
}
void Scene::dispose()
{
for(size_t i=0; i<m_texs.size(); ++i)
{
if (m_texs[i] != nullptr)
{
delete m_texs[i];
m_texs[i] = nullptr;
}
}
for(size_t i=0; i<m_objs.size(); ++i)
{
if (m_objs[i] != nullptr)
{
delete m_objs[i];
m_objs[i] = nullptr;
}
}
for(size_t i=0; i<m_mats.size(); ++i)
{
if (m_mats[i] != nullptr)
{
delete m_mats[i];
m_mats[i] = nullptr;
}
}
if (m_cam != nullptr)
{
delete m_cam;
m_cam = nullptr;
}
m_texs.clear();
m_objs.clear();
m_mats.clear();
m_w = 0;
m_h = 0;
m_s = 0;
}
Ray Scene::emit(float x, float y) const
{ return m_cam->emit(x, y); }
bool Scene::hit(const Ray& ray, HitRecord& record) const
{
record.dist = F_MAX;
record.shape = nullptr;
record.mat = nullptr;
bool hit = false;
for(size_t i=0; i<m_objs.size(); ++i)
{ hit |= m_objs[i]->hit(ray, record); }
return hit;
}
Vector3 Scene::sample_ibl(const Vector3& dir) const
{ return m_ibl->sample3d(dir); }
| 26.684604 | 118 | 0.479274 | [
"mesh",
"shape",
"vector"
] |
d5df62199762b42d0882df623ed9305a3235605b | 8,553 | cpp | C++ | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGMaskElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGMaskElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGMaskElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | /*
* Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
* Copyright (C) 2005 Alexander Kellett <lypanov@kde.org>
* Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
* Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGMaskElement.h"
#include "Attribute.h"
#include "CSSStyleSelector.h"
#include "RenderSVGResourceMasker.h"
#include "SVGNames.h"
#include "SVGRenderSupport.h"
#include "SVGUnitTypes.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_ENUMERATION(SVGMaskElement, SVGNames::maskUnitsAttr, MaskUnits, maskUnits)
DEFINE_ANIMATED_ENUMERATION(SVGMaskElement, SVGNames::maskContentUnitsAttr, MaskContentUnits, maskContentUnits)
DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::xAttr, X, x)
DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::yAttr, Y, y)
DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::widthAttr, Width, width)
DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::heightAttr, Height, height)
DEFINE_ANIMATED_BOOLEAN(SVGMaskElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document* document)
: SVGStyledLocatableElement(tagName, document)
, m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
, m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
, m_x(LengthModeWidth, "-10%")
, m_y(LengthModeHeight, "-10%")
, m_width(LengthModeWidth, "120%")
, m_height(LengthModeHeight, "120%")
{
// Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
// Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
}
PassRefPtr<SVGMaskElement> SVGMaskElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new SVGMaskElement(tagName, document));
}
void SVGMaskElement::parseMappedAttribute(Attribute* attr)
{
if (attr->name() == SVGNames::maskUnitsAttr) {
if (attr->value() == "userSpaceOnUse")
setMaskUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE);
else if (attr->value() == "objectBoundingBox")
setMaskUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX);
} else if (attr->name() == SVGNames::maskContentUnitsAttr) {
if (attr->value() == "userSpaceOnUse")
setMaskContentUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE);
else if (attr->value() == "objectBoundingBox")
setMaskContentUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX);
} else if (attr->name() == SVGNames::xAttr)
setXBaseValue(SVGLength(LengthModeWidth, attr->value()));
else if (attr->name() == SVGNames::yAttr)
setYBaseValue(SVGLength(LengthModeHeight, attr->value()));
else if (attr->name() == SVGNames::widthAttr)
setWidthBaseValue(SVGLength(LengthModeWidth, attr->value()));
else if (attr->name() == SVGNames::heightAttr)
setHeightBaseValue(SVGLength(LengthModeHeight, attr->value()));
else {
if (SVGTests::parseMappedAttribute(attr))
return;
if (SVGLangSpace::parseMappedAttribute(attr))
return;
if (SVGExternalResourcesRequired::parseMappedAttribute(attr))
return;
SVGStyledElement::parseMappedAttribute(attr);
}
}
void SVGMaskElement::svgAttributeChanged(const QualifiedName& attrName)
{
SVGStyledElement::svgAttributeChanged(attrName);
bool invalidateClients = false;
if (attrName == SVGNames::xAttr
|| attrName == SVGNames::yAttr
|| attrName == SVGNames::widthAttr
|| attrName == SVGNames::heightAttr) {
invalidateClients = true;
updateRelativeLengthsInformation();
}
RenderObject* object = renderer();
if (!object)
return;
if (invalidateClients
|| attrName == SVGNames::maskUnitsAttr
|| attrName == SVGNames::maskContentUnitsAttr
|| SVGTests::isKnownAttribute(attrName)
|| SVGLangSpace::isKnownAttribute(attrName)
|| SVGExternalResourcesRequired::isKnownAttribute(attrName)
|| SVGStyledElement::isKnownAttribute(attrName))
object->setNeedsLayout(true);
}
void SVGMaskElement::synchronizeProperty(const QualifiedName& attrName)
{
SVGStyledElement::synchronizeProperty(attrName);
if (attrName == anyQName()) {
synchronizeMaskUnits();
synchronizeMaskContentUnits();
synchronizeX();
synchronizeY();
synchronizeExternalResourcesRequired();
SVGTests::synchronizeProperties(this, attrName);
return;
}
if (attrName == SVGNames::maskUnitsAttr)
synchronizeMaskUnits();
else if (attrName == SVGNames::maskContentUnitsAttr)
synchronizeMaskContentUnits();
else if (attrName == SVGNames::xAttr)
synchronizeX();
else if (attrName == SVGNames::yAttr)
synchronizeY();
else if (SVGExternalResourcesRequired::isKnownAttribute(attrName))
synchronizeExternalResourcesRequired();
else if (SVGTests::isKnownAttribute(attrName))
SVGTests::synchronizeProperties(this, attrName);
}
AttributeToPropertyTypeMap& SVGMaskElement::attributeToPropertyTypeMap()
{
DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ());
return s_attributeToPropertyTypeMap;
}
void SVGMaskElement::fillAttributeToPropertyTypeMap()
{
AttributeToPropertyTypeMap& attributeToPropertyTypeMap = this->attributeToPropertyTypeMap();
SVGStyledLocatableElement::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap);
attributeToPropertyTypeMap.set(SVGNames::xAttr, AnimatedLength);
attributeToPropertyTypeMap.set(SVGNames::yAttr, AnimatedLength);
attributeToPropertyTypeMap.set(SVGNames::widthAttr, AnimatedLength);
attributeToPropertyTypeMap.set(SVGNames::heightAttr, AnimatedLength);
attributeToPropertyTypeMap.set(SVGNames::maskUnitsAttr, AnimatedEnumeration);
attributeToPropertyTypeMap.set(SVGNames::maskContentUnitsAttr, AnimatedEnumeration);
}
void SVGMaskElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
SVGStyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
if (changedByParser)
return;
if (RenderObject* object = renderer())
object->setNeedsLayout(true);
}
FloatRect SVGMaskElement::maskBoundingBox(const FloatRect& objectBoundingBox) const
{
FloatRect maskBBox;
if (maskUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
maskBBox = FloatRect(x().valueAsPercentage() * objectBoundingBox.width() + objectBoundingBox.x(),
y().valueAsPercentage() * objectBoundingBox.height() + objectBoundingBox.y(),
width().valueAsPercentage() * objectBoundingBox.width(),
height().valueAsPercentage() * objectBoundingBox.height());
else
maskBBox = FloatRect(x().value(this),
y().value(this),
width().value(this),
height().value(this));
return maskBBox;
}
RenderObject* SVGMaskElement::createRenderer(RenderArena* arena, RenderStyle*)
{
return new (arena) RenderSVGResourceMasker(this);
}
bool SVGMaskElement::selfHasRelativeLengths() const
{
return x().isRelative()
|| y().isRelative()
|| width().isRelative()
|| height().isRelative();
}
}
#endif // ENABLE(SVG)
| 39.96729 | 134 | 0.717175 | [
"object"
] |
d5e2869a482eb6a7e80824b61fd250aa91386d92 | 21,525 | cc | C++ | packager/media/event/hls_notify_muxer_listener_unittest.cc | s3bubble/shaka-packager | 77721fce857742744df7d118b651c6937dc90608 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,288 | 2016-05-25T01:20:31.000Z | 2022-03-02T23:56:56.000Z | packager/media/event/hls_notify_muxer_listener_unittest.cc | s3bubble/shaka-packager | 77721fce857742744df7d118b651c6937dc90608 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 894 | 2016-05-17T00:39:30.000Z | 2022-03-02T18:46:21.000Z | packager/media/event/hls_notify_muxer_listener_unittest.cc | s3bubble/shaka-packager | 77721fce857742744df7d118b651c6937dc90608 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 400 | 2016-05-25T01:20:35.000Z | 2022-03-03T02:12:00.000Z | // Copyright 2016 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "packager/hls/base/hls_notifier.h"
#include "packager/media/base/muxer_options.h"
#include "packager/media/base/protection_system_specific_info.h"
#include "packager/media/event/hls_notify_muxer_listener.h"
#include "packager/media/event/muxer_listener_test_helper.h"
namespace shaka {
namespace media {
using ::testing::_;
using ::testing::Bool;
using ::testing::ElementsAre;
using ::testing::InSequence;
using ::testing::Property;
using ::testing::Return;
using ::testing::StrEq;
using ::testing::TestWithParam;
namespace {
class MockHlsNotifier : public hls::HlsNotifier {
public:
MockHlsNotifier() : HlsNotifier(HlsParams()) {}
MOCK_METHOD0(Init, bool());
MOCK_METHOD5(NotifyNewStream,
bool(const MediaInfo& media_info,
const std::string& playlist_name,
const std::string& name,
const std::string& group_id,
uint32_t* stream_id));
MOCK_METHOD2(NotifySampleDuration,
bool(uint32_t stream_id, int32_t sample_duration));
MOCK_METHOD6(NotifyNewSegment,
bool(uint32_t stream_id,
const std::string& segment_name,
int64_t start_time,
int64_t duration,
uint64_t start_byte_offset,
uint64_t size));
MOCK_METHOD4(NotifyKeyFrame,
bool(uint32_t stream_id,
int64_t timestamp,
uint64_t start_byte_offset,
uint64_t size));
MOCK_METHOD2(NotifyCueEvent, bool(uint32_t stream_id, int64_t timestamp));
MOCK_METHOD5(
NotifyEncryptionUpdate,
bool(uint32_t stream_id,
const std::vector<uint8_t>& key_id,
const std::vector<uint8_t>& system_id,
const std::vector<uint8_t>& iv,
const std::vector<uint8_t>& protection_system_specific_data));
MOCK_METHOD0(Flush, bool());
};
// Doesn't really matter what the values are as long as it is a system ID (16
// bytes).
const uint8_t kAnySystemId[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
};
const uint8_t kAnyData[] = {
0xFF, 0x78, 0xAA, 0x6B,
};
const uint64_t kSegmentStartOffset = 10000;
const int64_t kSegmentStartTime = 19283;
const int64_t kSegmentDuration = 98028;
const uint64_t kSegmentSize = 756739;
const int64_t kCueStartTime = kSegmentStartTime;
const int64_t kKeyFrameTimestamp = 20123;
const uint64_t kKeyFrameStartByteOffset = 3456;
const uint64_t kKeyFrameSize = 543234;
static_assert(kKeyFrameStartByteOffset < kSegmentSize, "");
static_assert(kKeyFrameStartByteOffset + kKeyFrameSize <= kSegmentSize, "");
// This value doesn't really affect the test, it's not used by the
// implementation.
const bool kInitialEncryptionInfo = true;
const bool kIFramesOnlyPlaylist = true;
const char kDefaultPlaylistName[] = "default_playlist.m3u8";
const char kDefaultName[] = "DEFAULTNAME";
const char kDefaultGroupId[] = "DEFAULTGROUPID";
const char kCharactersticA[] = "public.accessibility.transcribes-spoken-dialog";
const char kCharactersticB[] = "public.easy-to-read";
MATCHER_P(HasEncryptionScheme, expected_scheme, "") {
*result_listener << "it has_protected_content: "
<< arg.has_protected_content() << " has_protection_scheme: "
<< arg.protected_content().has_protection_scheme()
<< " protection_scheme: "
<< arg.protected_content().protection_scheme();
return arg.has_protected_content() &&
arg.protected_content().has_protection_scheme() &&
arg.protected_content().protection_scheme() == expected_scheme;
}
} // namespace
class HlsNotifyMuxerListenerTest : public ::testing::Test {
protected:
HlsNotifyMuxerListenerTest()
: listener_(kDefaultPlaylistName,
!kIFramesOnlyPlaylist,
kDefaultName,
kDefaultGroupId,
std::vector<std::string>{kCharactersticA, kCharactersticB},
&mock_notifier_) {}
MuxerListener::MediaRanges GetMediaRanges(
const std::vector<Range>& segment_ranges) {
MuxerListener::MediaRanges ranges;
// We don't care about init range and index range values.
Range init_range;
init_range.start = 0;
init_range.end = 100;
Range index_range;
index_range.start = 101;
index_range.end = 200;
ranges.init_range = init_range;
ranges.index_range = index_range;
ranges.subsegment_ranges = segment_ranges;
return ranges;
}
MockHlsNotifier mock_notifier_;
HlsNotifyMuxerListener listener_;
};
// Verify that NotifyEncryptionUpdate() is not called before OnMediaStart() is
// called.
TEST_F(HlsNotifyMuxerListenerTest, OnEncryptionInfoReadyBeforeMediaStart) {
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cbcs, key_id,
iv, GetDefaultKeySystemInfo());
}
TEST_F(HlsNotifyMuxerListenerTest, OnMediaStart) {
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
EXPECT_CALL(
mock_notifier_,
NotifyNewStream(Property(&MediaInfo::hls_characteristics,
ElementsAre(kCharactersticA, kCharactersticB)),
StrEq(kDefaultPlaylistName), StrEq("DEFAULTNAME"),
StrEq("DEFAULTGROUPID"), _))
.WillOnce(Return(true));
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
}
// OnEncryptionStart() should call MuxerListener::NotifyEncryptionUpdate() after
// OnEncryptionInfoReady() and OnMediaStart().
TEST_F(HlsNotifyMuxerListenerTest, OnEncryptionStart) {
std::vector<uint8_t> system_id(kAnySystemId,
kAnySystemId + arraysize(kAnySystemId));
std::vector<uint8_t> pssh(kAnyData, kAnyData + arraysize(kAnyData));
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cbcs, key_id,
iv, {{system_id, pssh}});
::testing::Mock::VerifyAndClearExpectations(&mock_notifier_);
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
::testing::Mock::VerifyAndClearExpectations(&mock_notifier_);
EXPECT_CALL(mock_notifier_,
NotifyEncryptionUpdate(_, key_id, system_id, iv, pssh))
.WillOnce(Return(true));
listener_.OnEncryptionStart();
}
// If OnEncryptionStart() is called before media start,
// HlsNotiifer::NotifyEncryptionUpdate() should be called by the end of
// OnMediaStart().
TEST_F(HlsNotifyMuxerListenerTest, OnEncryptionStartBeforeMediaStart) {
std::vector<uint8_t> system_id(kAnySystemId,
kAnySystemId + arraysize(kAnySystemId));
std::vector<uint8_t> pssh(kAnyData, kAnyData + arraysize(kAnyData));
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cbcs, key_id,
iv, {{system_id, pssh}});
::testing::Mock::VerifyAndClearExpectations(&mock_notifier_);
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
// It doesn't really matter when this is called, could be called right away in
// OnEncryptionStart() if that is possible. Just matters that it is called by
// the time OnMediaStart() returns.
EXPECT_CALL(mock_notifier_,
NotifyEncryptionUpdate(_, key_id, system_id, iv, pssh))
.WillOnce(Return(true));
listener_.OnEncryptionStart();
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
}
// NotifyEncryptionUpdate() should not be called if NotifyNewStream() fails in
// OnMediaStart().
TEST_F(HlsNotifyMuxerListenerTest, NoEncryptionUpdateIfNotifyNewStreamFails) {
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cbcs, key_id,
iv, GetDefaultKeySystemInfo());
::testing::Mock::VerifyAndClearExpectations(&mock_notifier_);
EXPECT_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillOnce(Return(false));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
EXPECT_CALL(mock_notifier_, NotifyEncryptionUpdate(_, _, _, _, _)).Times(0);
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
}
// Verify that after OnMediaStart(), OnEncryptionInfoReady() calls
// NotifyEncryptionUpdate().
TEST_F(HlsNotifyMuxerListenerTest, OnEncryptionInfoReady) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
std::vector<uint8_t> system_id(kAnySystemId,
kAnySystemId + arraysize(kAnySystemId));
std::vector<uint8_t> pssh(kAnyData, kAnyData + arraysize(kAnyData));
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
EXPECT_CALL(mock_notifier_,
NotifyEncryptionUpdate(_, key_id, system_id, iv, pssh))
.WillOnce(Return(true));
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cbcs, key_id,
iv, {{system_id, pssh}});
}
// Verify that if protection scheme is specified in OnEncryptionInfoReady(),
// the information is copied to MediaInfo in OnMediaStart().
TEST_F(HlsNotifyMuxerListenerTest, OnEncryptionInfoReadyWithProtectionScheme) {
std::vector<uint8_t> key_id(16, 0x05);
std::vector<uint8_t> iv(16, 0x54);
listener_.OnEncryptionInfoReady(kInitialEncryptionInfo, FOURCC_cenc, key_id,
iv, GetDefaultKeySystemInfo());
::testing::Mock::VerifyAndClearExpectations(&mock_notifier_);
ON_CALL(mock_notifier_,
NotifyNewStream(HasEncryptionScheme("cenc"), _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
}
TEST_F(HlsNotifyMuxerListenerTest, OnSampleDurationReady) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
EXPECT_CALL(mock_notifier_, NotifySampleDuration(_, 2340));
listener_.OnSampleDurationReady(2340);
}
TEST_F(HlsNotifyMuxerListenerTest, OnNewSegmentAndCueEvent) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
EXPECT_CALL(mock_notifier_, NotifyCueEvent(_, kCueStartTime));
EXPECT_CALL(
mock_notifier_,
NotifyNewSegment(_, StrEq("new_segment_name10.ts"), kSegmentStartTime,
kSegmentDuration, _, kSegmentSize));
listener_.OnCueEvent(kCueStartTime, "dummy cue data");
listener_.OnNewSegment("new_segment_name10.ts", kSegmentStartTime,
kSegmentDuration, kSegmentSize);
}
// Verify that the notifier is called for every segment in OnMediaEnd if
// segment_template is not set.
TEST_F(HlsNotifyMuxerListenerTest, NoSegmentTemplateOnMediaEnd) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.output_file_name = "filename.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
listener_.OnCueEvent(kCueStartTime, "dummy cue data");
listener_.OnNewSegment("filename.mp4", kSegmentStartTime, kSegmentDuration,
kSegmentSize);
EXPECT_CALL(mock_notifier_, NotifyCueEvent(_, kCueStartTime));
EXPECT_CALL(
mock_notifier_,
NotifyNewSegment(_, StrEq("filename.mp4"), kSegmentStartTime,
kSegmentDuration, kSegmentStartOffset, kSegmentSize));
listener_.OnMediaEnd(
GetMediaRanges(
{{kSegmentStartOffset, kSegmentStartOffset + kSegmentSize - 1}}),
200000);
}
// Verify the event handling with multiple files, i.e. multiple OnMediaStart and
// OnMediaEnd calls.
TEST_F(HlsNotifyMuxerListenerTest, NoSegmentTemplateOnMediaEndTwice) {
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options1;
muxer_options1.output_file_name = "filename1.mp4";
MuxerOptions muxer_options2 = muxer_options1;
muxer_options2.output_file_name = "filename2.mp4";
InSequence in_sequence;
// Event flow for first file.
listener_.OnMediaStart(muxer_options1, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
listener_.OnNewSegment("filename1.mp4", kSegmentStartTime, kSegmentDuration,
kSegmentSize);
listener_.OnCueEvent(kCueStartTime, "dummy cue data");
EXPECT_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_notifier_, NotifyNewSegment(_, StrEq("filename1.mp4"),
kSegmentStartTime, _, _, _));
EXPECT_CALL(mock_notifier_, NotifyCueEvent(_, kCueStartTime));
listener_.OnMediaEnd(
GetMediaRanges(
{{kSegmentStartOffset, kSegmentStartOffset + kSegmentSize - 1}}),
200000);
// Event flow for second file.
listener_.OnMediaStart(muxer_options2, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
listener_.OnNewSegment("filename2.mp4", kSegmentStartTime + kSegmentDuration,
kSegmentDuration, kSegmentSize);
EXPECT_CALL(mock_notifier_,
NotifyNewSegment(_, StrEq("filename2.mp4"),
kSegmentStartTime + kSegmentDuration, _, _, _));
listener_.OnMediaEnd(
GetMediaRanges(
{{kSegmentStartOffset, kSegmentStartOffset + kSegmentSize - 1}}),
200000);
}
// Verify that when there is a mismatch in the number of calls to
// NotifyNewSegment and the number of segment ranges, it uses the min of the
// two.
TEST_F(HlsNotifyMuxerListenerTest,
NoSegmentTemplateOnMediaEndSubsegmentSizeMismatch) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.output_file_name = "filename.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
listener_.OnNewSegment("filename.mp4", kSegmentStartTime, kSegmentDuration,
kSegmentSize);
EXPECT_CALL(
mock_notifier_,
NotifyNewSegment(_, StrEq("filename.mp4"), kSegmentStartTime,
kSegmentDuration, kSegmentStartOffset, kSegmentSize));
listener_.OnMediaEnd(
GetMediaRanges(
{{kSegmentStartOffset, kSegmentStartOffset + kSegmentSize - 1},
{kSegmentStartOffset + kSegmentSize,
kSegmentStartOffset + kSegmentSize * 2 - 1}}),
200000);
}
class HlsNotifyMuxerListenerKeyFrameTest : public TestWithParam<bool> {
public:
HlsNotifyMuxerListenerKeyFrameTest()
: listener_(kDefaultPlaylistName,
GetParam(),
kDefaultName,
kDefaultGroupId,
std::vector<std::string>(), // no characteristics.
&mock_notifier_) {}
MockHlsNotifier mock_notifier_;
HlsNotifyMuxerListener listener_;
};
TEST_P(HlsNotifyMuxerListenerKeyFrameTest, WithSegmentTemplate) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.segment_template = "$Number$.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
EXPECT_CALL(mock_notifier_,
NotifyKeyFrame(_, kKeyFrameTimestamp, kKeyFrameStartByteOffset,
kKeyFrameSize))
.Times(GetParam() ? 1 : 0);
listener_.OnKeyFrame(kKeyFrameTimestamp, kKeyFrameStartByteOffset,
kKeyFrameSize);
}
// Verify that the notifier is called for every key frame in OnMediaEnd if
// segment_template is not set.
TEST_P(HlsNotifyMuxerListenerKeyFrameTest, NoSegmentTemplate) {
ON_CALL(mock_notifier_, NotifyNewStream(_, _, _, _, _))
.WillByDefault(Return(true));
VideoStreamInfoParameters video_params = GetDefaultVideoStreamInfoParams();
std::shared_ptr<StreamInfo> video_stream_info =
CreateVideoStreamInfo(video_params);
MuxerOptions muxer_options;
muxer_options.output_file_name = "filename.mp4";
listener_.OnMediaStart(muxer_options, *video_stream_info, 90000,
MuxerListener::kContainerMpeg2ts);
listener_.OnKeyFrame(kKeyFrameTimestamp, kKeyFrameStartByteOffset,
kKeyFrameSize);
listener_.OnNewSegment("filename.mp4", kSegmentStartTime, kSegmentDuration,
kSegmentSize);
EXPECT_CALL(mock_notifier_,
NotifyKeyFrame(_, kKeyFrameTimestamp,
kSegmentStartOffset + kKeyFrameStartByteOffset,
kKeyFrameSize))
.Times(GetParam() ? 1 : 0);
EXPECT_CALL(
mock_notifier_,
NotifyNewSegment(_, StrEq("filename.mp4"), kSegmentStartTime,
kSegmentDuration, kSegmentStartOffset, kSegmentSize));
MuxerListener::MediaRanges ranges;
ranges.subsegment_ranges.push_back(
{kSegmentStartOffset, kSegmentStartOffset + kSegmentSize - 1});
listener_.OnMediaEnd(ranges, 200000);
}
INSTANTIATE_TEST_CASE_P(InstantiationName,
HlsNotifyMuxerListenerKeyFrameTest,
Bool());
} // namespace media
} // namespace shaka
| 41 | 80 | 0.706945 | [
"vector"
] |
d5e4e1588f884d42c9d4bc7946e56cb01b4c51bf | 13,570 | hpp | C++ | 10 - Shunting Yard/ShuntingYard/shunting_yard.hpp | CrimsonCrow/yt-challenges | 5e4282fde046875221f82791511263b83cc3e257 | [
"W3C"
] | 11 | 2020-10-17T07:50:26.000Z | 2022-03-20T10:29:53.000Z | 10 - Shunting Yard/ShuntingYard/shunting_yard.hpp | CrimsonCrow/yt-challenges | 5e4282fde046875221f82791511263b83cc3e257 | [
"W3C"
] | 9 | 2020-10-06T18:41:40.000Z | 2021-11-17T11:10:54.000Z | 10 - Shunting Yard/ShuntingYard/shunting_yard.hpp | CrimsonCrow/yt-challenges | 5e4282fde046875221f82791511263b83cc3e257 | [
"W3C"
] | 22 | 2020-05-10T03:51:10.000Z | 2022-03-09T17:30:16.000Z | #ifndef SHUNTING_YARD
#define SHUNTING_YARD
#include <vector>
#include <string>
#include <map>
#include <stack>
#include <cmath>
namespace ShuntingYard {
/*
Typedefs
*/
// RPN list
typedef std::vector<std::string> RPN;
// callback to unary function (1 argument)
typedef double(*UnaryFuncEval)(double x);
// callback to binary function (2 arguments)
typedef double(*BinaryFuncEval)(double x, double y);
// types
enum class TokenTypes {
OPERATOR,
CONSTANT,
FUNCTION,
LPAREN,
RPAREN,
ELSE
};
/*
Utility function callbacks
*/
// determine if vector contains values
template<typename T>
bool contains(std::vector<T> v, T x);
// obtain key list
template<typename T>
std::vector<std::string> keys(std::map<std::string, T> m);
// obtain combined key list
template<typename T>
std::vector<std::string> keys(std::map<std::string, T> m1, std::map<std::string, T> m2);
// determine if character is number
bool isNumber(char c, bool acceptDecimal = true, bool acceptNegative = true);
// determine if entire string is number
bool isNumber(const char* str);
// determine if string only contains numerical characters
bool containsNumbers(const char* str);
// get numerical value of string
double getNumericalVal(const char* str);
// determine if string matches a function
bool isFunction(std::string str);
// determine if function is left associative
bool isLeftAssociative(std::string str);
// get function precedence
short getPrecedence(std::string str);
// find element from list in the equation starting at index i
std::string findElement(int i, const char* eqn, std::vector<std::string> list);
/*
Function class definition
*/
class Func {
public:
// default constructor
Func()
: type(TokenTypes::OPERATOR), prec(0), left(true), unary(true), u_eval(nullptr), b_eval(nullptr) {}
// constructor for unary functions
Func(UnaryFuncEval eval, TokenTypes type = TokenTypes::FUNCTION, short prec = 0, bool left = true)
: Func(type, prec, left, true) {
u_eval = eval;
}
// constructor for binary functions
Func(BinaryFuncEval eval, TokenTypes type = TokenTypes::FUNCTION, short prec = 0, bool left = true)
: Func(type, prec, left, false) {
b_eval = eval;
}
double eval(double x, double y = 0) {
return this->unary ? u_eval(x) : b_eval(x, y);
}
UnaryFuncEval u_eval; // unary function evaluation callback
BinaryFuncEval b_eval; // binary function evaluation callback
TokenTypes type; // type of function (ie function or operator)
short prec; // precedence
bool left; // is left associative
bool unary; // is a unary function
private:
Func(TokenTypes type, short prec, bool left, bool unary)
: type(type), prec(prec), left(left), unary(unary), u_eval(nullptr), b_eval(b_eval) {}
};
/*
Reference
*/
// unary functions
std::map<std::string, Func> unary_functions = {
{ "sin", Func(std::sin) }
};
// binary functions
std::map<std::string, Func> binary_functions = {
{ "+", Func([](double x, double y) -> double { return x + y; }, TokenTypes::OPERATOR, 2) },
{ "-", Func([](double x, double y) -> double { return x - y; }, TokenTypes::OPERATOR, 2) },
{ "*", Func([](double x, double y) -> double { return x * y; }, TokenTypes::OPERATOR, 3) },
{ "/", Func([](double x, double y) -> double { return x / y; }, TokenTypes::OPERATOR, 3) },
{ "^", Func(std::pow, TokenTypes::OPERATOR, 4, false) }
};
// function names
std::vector<std::string> functionNames = keys<Func>(unary_functions, binary_functions);
// constants
std::map<std::string, double> constants = {
{ "pi", std::atan(1) * 4 },
{ "e", std::exp(1) }
};
// constant names
std::vector<std::string> constantNames = keys<double>(constants);
// variables
std::map<std::string, double> variables;
// operators
std::vector<char> operators = { '+', '-', '/', '*', '^' };
// left brackets
std::vector<char> leftBrackets = { '(', '{', '[' };
// right brackets
std::vector<char> rightBrackets = { ')', '}', ']' };
/*
Node class definitions
*/
// base node class
class Node {
public:
Node(std::string name, bool isFunc)
: name(name), isFunc(isFunc) {}
double eval(double x = 0, double y = 0);
std::string name;
bool isFunc;
Node* right;
Node* left;
};
// function node class
class FuncNode : public Node {
public:
FuncNode(std::string name)
: Node(name, true) {}
// set type of function and then assign callback
void setUnary(bool isUnary) {
this->isUnary = isUnary;
this->func = isUnary ? unary_functions[name] : binary_functions[name];
}
// evaluate
double eval(double x, double y = 0) {
return this->func.eval(x, y);
}
bool isUnary;
Func func;
};
// number node class
class NumNode : public Node {
public:
NumNode(std::string name)
: Node(name, false) {}
// return numerical value
double eval(double x = 0, double y = 0) {
return getNumericalVal(name.c_str());
}
};
/*
Main functions
*/
// parse infix notation into reverse polish notation (Shunting Yard)
RPN reversePolishNotation(const char* eqn) {
std::vector<std::string> queue;
std::stack<std::string> stack;
std::string obj = "";
TokenTypes type = TokenTypes::ELSE;
TokenTypes prevType = TokenTypes::ELSE; // negative sign detection
bool acceptDecimal = true;
bool acceptNegative = true;
// token reading and detection
for (int i = 0, eqLen = (int)strlen(eqn); i < eqLen; i++) {
char t = eqn[i];
// skip spaces and commas
if (t == ' ' || t == ',') {
//prevType = TokenTypes::ELSE;
continue;
}
// classify token
if (isNumber(t)) {
type = TokenTypes::CONSTANT;
if (t == '.') {
acceptDecimal = false;
}
else if (t == '-') {
acceptNegative = false;
}
int startI = i;
if (i < eqLen - 1) {
while (isNumber(eqn[i + 1], acceptDecimal, acceptNegative)) {
i++;
if (i >= eqLen - 1) {
break;
}
}
}
obj = std::string(eqn).substr(startI, i - startI + 1);
// subtraction sign detection
if (obj == "-") {
type = TokenTypes::OPERATOR;
}
}
else {
obj = findElement(i, eqn, functionNames);
if (obj != "") {
// found valid object
type = contains<char>(operators, obj[0]) ? TokenTypes::OPERATOR : TokenTypes::FUNCTION;
}
else {
obj = findElement(i, eqn, constantNames);
if (obj != "") {
// found valid object
type = TokenTypes::CONSTANT;
}
else {
obj = findElement(i, eqn, keys<double>(variables));
if (obj != "") {
type = TokenTypes::CONSTANT;
}
else if (contains<char>(leftBrackets, t)) {
type = TokenTypes::LPAREN;
obj = "(";
}
else if (contains<char>(rightBrackets, t)) {
type = TokenTypes::RPAREN;
obj = ")";
}
else {
type = TokenTypes::ELSE;
}
}
}
i += obj.size() - 1;
}
// do something with the token
const char* last_stack = (stack.size() > 0) ? stack.top().c_str() : "";
switch (type) {
case TokenTypes::CONSTANT:
queue.push_back(obj);
break;
case TokenTypes::FUNCTION:
stack.push(obj);
break;
case TokenTypes::OPERATOR:
if (stack.size() != 0) {
while (
/*
stk = stack top = last_stack
obj = obj
stk is a function
AND
stk is not an operator
OR
stk has a higher precedence than obj
OR
they have equal precedence
AND
stk is left associative
AND
stk is not a left bracket
*/
(
(contains<std::string>(functionNames, last_stack) &&
!contains<char>(operators, last_stack[0])) ||
getPrecedence(last_stack) > getPrecedence(obj) ||
((getPrecedence(last_stack) == getPrecedence(obj)) &&
isLeftAssociative(last_stack))
) &&
!contains<char>(leftBrackets, last_stack[0])
) {
// pop from the stack to the queue
queue.push_back(stack.top());
stack.pop();
if (stack.size() == 0) {
break;
}
last_stack = stack.top().c_str();
}
}
stack.push(obj);
break;
case TokenTypes::LPAREN:
stack.push(obj);
break;
case TokenTypes::RPAREN:
while (last_stack[0] != '(') {
// pop from the stack to the queue
queue.push_back(stack.top());
stack.pop();
last_stack = stack.top().c_str();
}
stack.pop();
break;
default:
return queue;
}
// reset type
prevType = type;
}
while (stack.size() > 0) {
// pop from the stack to the queue
queue.push_back(stack.top());
stack.pop();
}
return queue;
}
// parse RPN to tree
Node* parse(RPN rpn) {
std::stack<Node*> stack;
for (std::string item : rpn) {
if (isNumber(item.c_str())) {
// push number node
stack.push(new NumNode(item));
}
else {
// function
FuncNode* f = new FuncNode(item);
if (contains<std::string>(keys(binary_functions), item)) {
f->setUnary(false);
// set children of node
// right child is second argument
f->right = stack.top();
stack.pop();
// left child is first argument
f->left = stack.top();
stack.pop();
}
else if (contains<std::string>(keys(unary_functions), item)) {
f->setUnary(true);
// set child of node
f->left = stack.top();
stack.pop();
}
stack.push(f);
}
}
if (stack.size() == 0) {
return nullptr;
}
return stack.top();
}
// evaluate tree
double eval(Node* tree) {
if (tree->isFunc) {
FuncNode* ftree = (FuncNode*)tree;
if (ftree->isUnary) {
// evaluate child recursively and then evaluate with return value
return ftree->eval(eval(tree->left));
}
else {
// evaluate each child recursively and then evaluate with return value
return ftree->eval(eval(tree->left), eval(tree->right));
}
}
else {
// number node
return ((NumNode*)tree)->eval();
}
}
/*
Utility function definitions
*/
// determine if vector contains values
template<typename T>
bool contains(std::vector<T> v, T x) {
return std::find(v.begin(), v.end(), x) != v.end();
}
// obtain key list
template<typename T>
std::vector<std::string> keys(std::map<std::string, T> m) {
std::vector<std::string> ret;
// push each key from each pair
for (auto const& element : m) {
ret.push_back(element.first);
}
return ret;
}
// obtain combined key list
template<typename T>
std::vector<std::string> keys(std::map<std::string, T> m1, std::map<std::string, T> m2) {
// get keys from each map
std::vector<std::string> keySet1 = keys<T>(m1);
std::vector<std::string> keySet2 = keys<T>(m2);
// insert the second list into first
keySet1.insert(keySet1.end(), keySet2.begin(), keySet2.end());
// return result
return keySet1;
}
// determine if character is number
bool isNumber(char c, bool acceptDecimal, bool acceptNegative) {
// digits
if (c >= '0' && c <= '9') {
return true;
}
// decimal point
else if (acceptDecimal && c == '.') {
return true;
}
// negative sign
else if (acceptNegative && c == '-') {
return true;
}
return false;
}
// determine if entire string is number
bool isNumber(const char* str) {
// it's a constant, variable, or a numerical string
return contains<std::string>(constantNames, str) ||
contains<std::string>(keys<double>(variables), str) ||
containsNumbers(str);
}
// determine if string only contains numerical characters
bool containsNumbers(const char* str) {
// cannot be a single decimal point or negative sign
if (std::strcmp(str, ".") == 0 || std::strcmp(str, "-") == 0) {
return false;
}
std::string obj = std::string(str);
// try to prove wrong
bool acceptDecimal = true;
if (isNumber(obj[0], true, true)) {
// check first character for negative sign
if (obj[0] == '.') {
// cannot be any more decimal points
acceptDecimal = false;
}
}
else {
return false;
}
for (unsigned int i = 1, len = obj.size(); i < len; i++) {
// do not accept anymore negative signs
if (!isNumber(obj[i], acceptDecimal, false)) {
return false;
}
if (obj[i] == '.') {
// cannot be any more decimal points
acceptDecimal = false;
}
}
return true;
}
// get numerical value of string
double getNumericalVal(const char* str) {
if (contains<std::string>(constantNames, str)) {
// is a constant
return constants[str];
}
else if (contains<std::string>(keys<double>(variables), str)) {
// is a variable
return variables[str];
}
else {
// is a number
return std::atof(str);
}
}
// determine if string matches a function
bool isFunction(std::string str) {
return contains<std::string>(functionNames, str);
}
// determine if function is left associative
bool isLeftAssociative(std::string str) {
return binary_functions[str].left;
}
// get function precedence
short getPrecedence(std::string str) {
if (contains<std::string>(keys(binary_functions), str)) {
return binary_functions[str].prec;
}
// only care about operators, which are binary functions, so otherwise we can return 0
return 0;
}
// find element from list in the equation starting at index i
std::string findElement(int i, const char* eqn, std::vector<std::string> list) {
for (std::string item : list) {
int n = (int)item.size();
if (std::string(eqn).substr(i, n) == item) {
return item;
}
}
return "";
}
}
#endif | 23.6 | 102 | 0.61577 | [
"object",
"vector"
] |
d5e6cfc4b5ca270c84d83fec95babbb401aebf6b | 2,347 | cpp | C++ | zadania/zad1/main.cpp | Kavaldrin/adv | 8fd4f3b8829b68030b1481c5460231528a7b9a2c | [
"MIT"
] | null | null | null | zadania/zad1/main.cpp | Kavaldrin/adv | 8fd4f3b8829b68030b1481c5460231528a7b9a2c | [
"MIT"
] | null | null | null | zadania/zad1/main.cpp | Kavaldrin/adv | 8fd4f3b8829b68030b1481c5460231528a7b9a2c | [
"MIT"
] | null | null | null | /*
Zadanie zeby przyswoic sobie skladnie z przenoszeniem
Prosze zaimplementowac klase MyObject
-glosny konstruktor kopiujacy
-glosny konstruktor przenoszacy
-glosny operator przypisania
-glosny przenoszacy operator przypisania
Adresy z mojego outputu powinny byc analogiczne...
Pliku main nie mozna edytowac.
*/
#include "zad1.h"
int main()
{
int x = 5, y = 9;
std::cout << "-------------- TWORZE OBIEKTY --------------\n\n";
MyObject<decltype(x)> o(&x);
MyObject<> oFromTemp = MyObject<>(&y);
MyObject<decltype(y)>&& rvalRef = MyObject<decltype(y)>();
auto movedObj = std::move(MyObject<decltype(x)>(&x));
std::cout << "\n-------------- STWORZYLEM OBIEKTY --------------\n\n";
std::cout << "Wypisuje obiekt bez std::move\n" << oFromTemp << std::endl;
std::cout << "Wypisuje obiekt uzywajac std::move\n" << std::move(oFromTemp) << std::endl;
std::cout << "----- TWORZE OBIEKTY Z UZYCIEM ISTNIEJACYCH OBIEKTOW -----\n\n";
auto oFromCopy(o);
auto oMoved(std::move(o));
std::cout << "\n-------------- STWORZYLEM OBIEKTY --------------\n\n";
std::cout << "Wypisuje o po jego przeniesieniu\n" << o << std::endl;
std::cout << "\nDokonuje wielu przypisan\n";
o = std::move(oFromCopy = rvalRef = movedObj);
std::cout << "\nWypisuje o po jego przenoszeniach\n" << o << std::endl;
return 0;
}
/*
-------------- TWORZE OBIEKTY --------------
Tworze obiekt z przechowywanym adresem: 0x7fffb4449868
Tworze obiekt z przechowywanym adresem: 0x7fffb444986c
Tworze obiekt z przechowywanym adresem: 0
Tworze obiekt z przechowywanym adresem: 0x7fffb4449868
My object -> konstruktor przenoszacy
-------------- STWORZYLEM OBIEKTY --------------
Wypisuje obiekt bez std::move
Wypisuje MyObject otrzymany jako l-wartosc: 0x7fffb444986c
Wypisuje obiekt uzywajac std::move
Wypisuje MyObject otrzymany jako r-wartosc: 0x7fffb444986c
----- TWORZE OBIEKTY Z UZYCIEM ISTNIEJACYCH OBIEKTOW -----
My object -> konstuktor kopiujacy
My object -> konstruktor przenoszacy
-------------- STWORZYLEM OBIEKTY --------------
Wypisuje o po jego przeniesieniu
Wypisuje MyObject otrzymany jako l-wartosc: 0
Dokonuje wielu przypisan
My object -> operator przypisania
My object -> operator przypisania
My object -> przenoszacy operator przypisania
Wypisuje o po jego przenoszeniach
Wypisuje MyObject otrzymany jako l-wartosc: 0x7fffb4449868
*/ | 26.977011 | 90 | 0.684278 | [
"object"
] |
d5ec9f5c384260e3bf5785a4220123f24510fb70 | 2,275 | hpp | C++ | libs/common/cloneable.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | 1 | 2021-12-03T02:01:43.000Z | 2021-12-03T02:01:43.000Z | libs/common/cloneable.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | 2 | 2020-07-07T19:31:15.000Z | 2021-06-01T22:29:48.000Z | libs/common/cloneable.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | 1 | 2021-12-03T02:00:05.000Z | 2021-12-03T02:00:05.000Z | /**
* Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved.
* http://soramitsu.co.jp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IROHA_CLONEABLE_HPP
#define IROHA_CLONEABLE_HPP
#include <memory>
/**
* Functions and interface for creation cloneable classes with
* smart pointers.
*
* Usage:
* struct Base : object::cloneable<Base> {
* // ... other methods
* };
*
* struct Derived : Base {
* // ... other methods
* protected:
* Derived* clone() const override {
* return new Derived(*this);
* }
* };
*
* Derived derived;
* auto c1 = clone(derived);
*/
/**
* Function to clone from Cloneable.
* @tparam T - derived from Cloneable
* @param object - object to clone
* @return clone of object
*/
template <typename T>
std::unique_ptr<T> clone(const T &object) {
using base_type = typename T::base_type;
static_assert(std::is_base_of<base_type, T>::value,
"T object has to derived from T::base_type");
auto ptr = static_cast<const base_type &>(object).clone();
return std::unique_ptr<T>(static_cast<T *>(ptr));
}
/**
* Helper function to copy from pointer to Cloneable.
* @tparam T - derived from Cloneable
* @param object - object to clone
* @return clone of object
*/
template <typename T>
auto clone(T *object) {
return clone(*object);
}
/**
* Interface for cloneable classes.
* @tparam T
*/
template <typename T>
class Cloneable {
public:
using base_type = T;
virtual ~Cloneable() = default;
protected:
/**
* Polymorphic clone constructor.
* Method guarantees deep-copy.
* @return pointer to cloned object
*/
virtual T *clone() const = 0;
template <typename X>
friend std::unique_ptr<X> clone(const X &);
};
#endif // IROHA_CLONEABLE_HPP
| 24.202128 | 75 | 0.67956 | [
"object"
] |
d5ed2d04b355a5293ae1e52db06e64c4f04850d8 | 1,634 | cpp | C++ | LeetCode/Algorithms/Medium/DesignCircularQueue.cpp | roshan11160/Competitive-Programming-Solutions | 2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e | [
"MIT"
] | 40 | 2020-07-25T19:35:37.000Z | 2022-01-28T02:57:02.000Z | LeetCode/Algorithms/Medium/DesignCircularQueue.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 160 | 2021-04-26T19:04:15.000Z | 2022-03-26T20:18:37.000Z | LeetCode/Algorithms/Medium/DesignCircularQueue.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 24 | 2020-05-03T08:11:53.000Z | 2021-10-04T03:23:20.000Z | class MyCircularQueue
{
public:
int front, rear, size, capacity;
vector<int> queue;
MyCircularQueue(int k)
{
queue = vector<int>(k, 0);
front = 0;
rear = -1;
size = 0;
capacity = k;
}
bool enQueue(int value)
{
if (!isFull())
{
if (rear == (capacity - 1))
rear = 0;
else
rear++;
queue[rear] = value;
size++;
return true;
}
return false;
}
bool deQueue()
{
if (!isEmpty())
{
if (front == (capacity - 1))
front = 0;
else
{
front++;
}
size--;
return true;
}
return false;
}
int Front()
{
if (isEmpty())
return -1;
return queue[front];
}
int Rear()
{
if (isEmpty())
return -1;
return queue[rear];
}
bool isEmpty()
{
if (size == 0)
return true;
return false;
}
bool isFull()
{
if (size == capacity)
return true;
return false;
}
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue* obj = new MyCircularQueue(k);
* bool param_1 = obj->enQueue(value);
* bool param_2 = obj->deQueue();
* int param_3 = obj->Front();
* int param_4 = obj->Rear();
* bool param_5 = obj->isEmpty();
* bool param_6 = obj->isFull();
*/
// Time Complexity - O(1)
// Space Complexity - O(N), using vector | 18.781609 | 71 | 0.439412 | [
"object",
"vector"
] |
d5ef77d7b0231f3dd57797235eea09168441993a | 24,880 | cpp | C++ | src/core/operation/TermVirtualList.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 14 | 2016-01-15T20:26:54.000Z | 2018-11-26T20:47:43.000Z | src/core/operation/TermVirtualList.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 2 | 2016-04-26T05:29:01.000Z | 2016-05-07T00:13:38.000Z | src/core/operation/TermVirtualList.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 7 | 2016-02-27T11:35:59.000Z | 2018-11-26T20:47:59.000Z | /*
* Copyright (c) 2016, SRCH2
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the SRCH2 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 SRCH2 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 <instantsearch/Ranker.h>
#include "TermVirtualList.h"
#include "util/Assert.h"
#include "util/Logger.h"
#include "index/Trie.h"
#include "index/InvertedIndex.h"
using srch2::util::Logger;
namespace srch2
{
namespace instantsearch
{
void TermVirtualList::initialiseTermVirtualListElement(TrieNodePointer prefixNode,
TrieNodePointer leafNode, unsigned distance)
{
unsigned invertedListId = leafNode->getInvertedListOffset();
unsigned invertedListCounter = 0;
shared_ptr<vectorview<unsigned> > invertedListReadView;
this->invertedIndex->getInvertedListReadView(this->invertedListDirectoryReadView,
invertedListId, invertedListReadView);
unsigned recordId = invertedListReadView->getElement(invertedListCounter);
// calculate record offset online
unsigned keywordOffset = this->invertedIndex->getKeywordOffset(this->forwardIndexDirectoryReadView,
this->invertedIndexKeywordIdsReadView,
recordId, invertedListId);
++ invertedListCounter;
bool foundValidHit = 0;
float termRecordStaticScore = 0;
vector<unsigned> matchedAttributeIdsList;
while (1) {
// We ignore the record if it's no longer valid
if (keywordOffset != FORWARDLIST_NOTVALID &&
this->invertedIndex->isValidTermPositionHit(this->forwardIndexDirectoryReadView,
recordId,
keywordOffset,
term->getAttributesToFilter(), term->getFilterAttrOperation(), matchedAttributeIdsList,
termRecordStaticScore) ) {
foundValidHit = 1;
break;
}
if (invertedListCounter < invertedListReadView->size()) {
recordId = invertedListReadView->getElement(invertedListCounter);
// calculate record offset online
keywordOffset = this->invertedIndex->getKeywordOffset(this->forwardIndexDirectoryReadView,
this->invertedIndexKeywordIdsReadView,
recordId, invertedListId);
++invertedListCounter;
} else {
break;
}
}
if (keywordOffset != FORWARDLIST_NOTVALID && foundValidHit == 1) {
this->numberOfItemsInPartialHeap ++; // increment partialHeap counter
if (this->numberOfItemsInPartialHeap == 0)
this->currentMaxEditDistanceOnHeap = distance;
if (this->getTermType() == srch2::instantsearch::TERM_TYPE_PREFIX) { // prefix term
bool isPrefixMatch = (prefixNode != leafNode);
float termRecordRuntimeScore =
DefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore,
distance,
term->getKeyword()->size(),
isPrefixMatch,
this->prefixMatchPenalty , term->getSimilarityBoost());
this->itemsHeap.push_back(new HeapItem(invertedListId, this->cursorVector.size(),
recordId, matchedAttributeIdsList, termRecordRuntimeScore,
keywordOffset, prefixNode,
distance, isPrefixMatch));
} else { // complete term
float termRecordRuntimeScore =
DefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore,
distance,
term->getKeyword()->size(),
false,
this->prefixMatchPenalty , term->getSimilarityBoost());// prefix match == false
this->itemsHeap.push_back(new HeapItem(invertedListId, this->cursorVector.size(),
recordId, matchedAttributeIdsList, termRecordRuntimeScore,
keywordOffset, leafNode, distance, false));
}
// Cursor points to the next element on InvertedList
this->cursorVector.push_back(invertedListCounter);
// keep the inverted list readviews in invertedListVector such that we can safely access them
this->invertedListReadViewVector.push_back(invertedListReadView);
}
}
void TermVirtualList::depthInitializeTermVirtualListElement(const TrieNode* trieNode, unsigned editDistance,
unsigned panDistance, unsigned bound)
{
if (trieNode->isTerminalNode()) {
initialiseTermVirtualListElement(NULL, trieNode, editDistance > panDistance ? editDistance : panDistance);
}
if (panDistance < bound) {
for (unsigned int childIterator = 0; childIterator < trieNode->getChildrenCount(); childIterator++) {
const TrieNode *child = trieNode->getChild(childIterator);
depthInitializeTermVirtualListElement(child, editDistance, panDistance + 1, bound);
}
}
}
// this function will depth initialize bitset, which will be used for complete term
void TermVirtualList::depthInitializeBitSet(const TrieNode* trieNode, unsigned editDistance, unsigned panDistance, unsigned bound)
{
if (trieNode->isTerminalNode()) {
unsigned invertedListId = trieNode->getInvertedListOffset();
this->invertedIndex->getInvertedListReadView(this->invertedListDirectoryReadView,
invertedListId, invertedListReadView);
for (unsigned invertedListCounter = 0; invertedListCounter < invertedListReadView->size(); invertedListCounter++) {
// set the bit of the record id to be true
if (!bitSet.getAndSet(invertedListReadView->at(invertedListCounter)))
bitSetSize++;
}
}
if (panDistance < bound) {
for (unsigned int childIterator = 0; childIterator < trieNode->getChildrenCount(); childIterator++) {
const TrieNode *child = trieNode->getChild(childIterator);
// As we visit the children of the current trie node, we use "panDistance + 1" as the new
// edit distance and ignore the "edit distance" value passed from the caller by using "0" and "false".
depthInitializeBitSet(child, editDistance, panDistance + 1, bound);
}
}
}
// Iterate over active nodes, fill the vector, and call make_heap on it.
TermVirtualList::TermVirtualList(const InvertedIndex* invertedIndex, const ForwardIndex * forwardIndex, PrefixActiveNodeSet *prefixActiveNodeSet,
Term *term, float prefixMatchPenalty, float shouldIterateToLeafNodesAndScoreOfTopRecord )
{
this->invertedIndex = invertedIndex;
this->invertedIndex->getInvertedIndexDirectory_ReadView(this->invertedListDirectoryReadView);
this->invertedIndex->getInvertedIndexKeywordIds_ReadView(this->invertedIndexKeywordIdsReadView);
forwardIndex->getForwardListDirectory_ReadView(this->forwardIndexDirectoryReadView);
this->prefixActiveNodeSet = prefixActiveNodeSet;
this->term = term;
this->prefixMatchPenalty = prefixMatchPenalty;
this->numberOfItemsInPartialHeap = 0;
this->currentMaxEditDistanceOnHeap = 0;
this->currentRecordID = -1;
this->usingBitset = false;
this->bitSetSize = 0;
this->maxScoreForBitSetCase = 0;
// this flag indicates whether this TVL is for a tooPopular term or not.
// If it is a TVL of a too popular term, this TVL is disabled, meaning it should not be used for iteration over
// heapItems. In this case shouldIterateToLeafNodesAndScoreOfTopRecord is not equal to -1
this->topRecordScoreWhenListIsDisabled = shouldIterateToLeafNodesAndScoreOfTopRecord;
if(this->topRecordScoreWhenListIsDisabled != -1){
return;
}
// check the TermType
if (this->getTermType() == TERM_TYPE_PREFIX) { //case 1: Term is prefix
LeafNodeSetIteratorForPrefix iter(prefixActiveNodeSet, term->getThreshold());
// This is our query-optimization logic. If the total number of leaf nodes for the term is
// greater than a threshold, we use bitset to do the union/intersection operations.
if (iter.size() >= TERM_COUNT_THRESHOLD){
// NOTE: BitSet is disabled for now since the fact that it must always return max score of leaf nodes
// disables early termination and even makes the engine slower.
// this->usingBitset = true;
this->usingBitset = false;
}
if (this->usingBitset) {// This term needs bitset
bitSet.resize(this->invertedIndex->getRecordNumber());
TrieNodePointer leafNode;
TrieNodePointer prefixNode;
unsigned distance;
//numberOfLeafNodes = 0;
//totalInveretListLength = 0;
this->maxScoreForBitSetCase = 0;
for (; !iter.isDone(); iter.next()) {
iter.getItem(prefixNode, leafNode, distance);
float runTimeScoreOfThisLeafNode = DefaultTopKRanker::computeTermRecordRuntimeScore(leafNode->getMaximumScoreOfLeafNodes(),
distance,
term->getKeyword()->size(),
true,
this->prefixMatchPenalty , term->getSimilarityBoost());
if( runTimeScoreOfThisLeafNode > this->maxScoreForBitSetCase){
this->maxScoreForBitSetCase = runTimeScoreOfThisLeafNode;
}
unsigned invertedListId = leafNode->getInvertedListOffset();
this->invertedIndex->getInvertedListReadView(this->invertedListDirectoryReadView,
invertedListId, invertedListReadView);
// loop the inverted list to add it to the Bitset
for (unsigned invertedListCounter = 0; invertedListCounter < invertedListReadView->size(); invertedListCounter++) {
// We compute the union of these bitsets. We increment the number of bits only if the previous bit was 0.
if (!bitSet.getAndSet(invertedListReadView->at(invertedListCounter)))
bitSetSize ++;
}
//termCount++;
//totalInveretListLength += invertedListReadView->size();
}
bitSetIter = bitSet.iterator();
} else { // If we don't use a bitset, we use the TA algorithm
cursorVector.reserve(iter.size());
invertedListReadViewVector.reserve(iter.size());
for (; !iter.isDone(); iter.next()) {
TrieNodePointer leafNode;
TrieNodePointer prefixNode;
unsigned distance;
iter.getItem(prefixNode, leafNode, distance);
initialiseTermVirtualListElement(prefixNode, leafNode, distance);
}
}
} else { // case 2: Term is complete
ActiveNodeSetIterator iter(prefixActiveNodeSet, term->getThreshold());
if (iter.size() >= TERM_COUNT_THRESHOLD){
// NOTE: BitSet is disabled for now since the fact that it must always return max score of leaf nodes
// disables early termination and even makes the engine slower.
// this->usingBitset = true;
this->usingBitset = false;
}
if (this->usingBitset) { // if this term virtual list is merged to a Bitset
bitSet.resize(this->invertedIndex->getRecordNumber());
TrieNodePointer trieNode;
unsigned editDistance;
//numberOfLeafNodes = 0;
//totalInveretListLength = 0;
this->maxScoreForBitSetCase = 0;
for (; !iter.isDone(); iter.next()) {
iter.getItem(trieNode, editDistance);
float runTimeScoreOfThisLeafNode = DefaultTopKRanker::computeTermRecordRuntimeScore(trieNode->getMaximumScoreOfLeafNodes(),
editDistance,
term->getKeyword()->size(),
false,
this->prefixMatchPenalty , term->getSimilarityBoost());
if( runTimeScoreOfThisLeafNode > this->maxScoreForBitSetCase){
this->maxScoreForBitSetCase = runTimeScoreOfThisLeafNode;
}
unsigned panDistance = prefixActiveNodeSet->getEditdistanceofPrefix(trieNode);
// we always use the panDistance between this pivotal active node (PAN) and the query term
depthInitializeBitSet(trieNode, editDistance, panDistance, term->getThreshold());
}
bitSetIter = bitSet.iterator();
} else {
cursorVector.reserve(iter.size());
invertedListReadViewVector.reserve(iter.size());
for (; !iter.isDone(); iter.next()) {
TrieNodePointer trieNode;
unsigned editDistance;
iter.getItem(trieNode, editDistance);
unsigned panDistance = prefixActiveNodeSet->getEditdistanceofPrefix(trieNode);
depthInitializeTermVirtualListElement(trieNode, editDistance, panDistance, term->getThreshold());
}
}
}
// Make partial heap by calling make_heap from begin() to begin()+"number of items within edit distance threshold"
make_heap(itemsHeap.begin(), itemsHeap.begin()+numberOfItemsInPartialHeap, TermVirtualList::HeapItemCmp());
}
bool TermVirtualList::isTermVirtualListDisabled(){
return (this->topRecordScoreWhenListIsDisabled != -1);
}
float TermVirtualList::getScoreOfTopRecordWhenListIsDisabled(){
ASSERT(this->topRecordScoreWhenListIsDisabled != -1);
return this->topRecordScoreWhenListIsDisabled;
}
TermVirtualList::~TermVirtualList()
{
for (vector<HeapItem* >::iterator iter = this->itemsHeap.begin(); iter != this->itemsHeap.end(); iter++) {
HeapItem *currentItem = *iter;
if (currentItem != NULL)
delete currentItem;
}
this->itemsHeap.clear();
this->cursorVector.clear();
this->invertedListReadViewVector.clear();
this->term = NULL;
this->invertedIndex = NULL;
}
//Called when this->numberOfItemsInPartialHeap = 0
bool TermVirtualList::_addItemsToPartialHeap()
{
bool returnValue = false;
// If partial heap is empty, increase editDistanceThreshold and add more elements
for ( vector<HeapItem* >::iterator iter = this->itemsHeap.begin(); iter != this->itemsHeap.end(); iter++) {
HeapItem *currentItem = *iter;
if (this->numberOfItemsInPartialHeap == 0) {
// partialHeap is empty, assign new maxEditDistance and add items to partialHeap
if (currentItem->ed > this->currentMaxEditDistanceOnHeap) {
this->currentMaxEditDistanceOnHeap = currentItem->ed;
this->numberOfItemsInPartialHeap++;
returnValue =true;
}
} else {
// Edit distance on itemHeap is less than maxEditDistance so far seen
if (currentItem->ed <= this->currentMaxEditDistanceOnHeap) {
this->numberOfItemsInPartialHeap++;
returnValue = true;
} //stopping condition: partialheap is not empty and edit distance is greater than maxEditDistance
else
break;
}
}
// PartialHeap changed;
if (returnValue) {
make_heap(this->itemsHeap.begin(),this->itemsHeap.begin()+numberOfItemsInPartialHeap,
TermVirtualList::HeapItemCmp());
}
return returnValue;
}
bool TermVirtualList::getMaxScore(float & score)
{
if (this->usingBitset) {
score = this->maxScoreForBitSetCase;
return true;
} else {
//If heapVector is empty
if (this->itemsHeap.size() == 0) {
return false;
}
//If partialHeap is empty
if (this->numberOfItemsInPartialHeap == 0) {
if ( this->_addItemsToPartialHeap() == false) {
return false;
}
}
if (this->numberOfItemsInPartialHeap != 0) {
HeapItem *currentHeapMax = *(itemsHeap.begin());
score = currentHeapMax->termRecordRuntimeScore;
return true;
} else {
return false;
}
}
}
bool TermVirtualList::getNext(HeapItemForIndexSearcher *returnHeapItem)
{
if (this->usingBitset) {
returnHeapItem->recordId = this->bitSetIter->getNextRecordId();
// When we use the bitset to get the next record for this virtual list, we don't have all the information for this record.
returnHeapItem->termRecordRuntimeScore = 1.0;
returnHeapItem->trieNode = 0;
returnHeapItem->attributeIdsList.clear();
returnHeapItem->ed = 0;
returnHeapItem->positionIndexOffset = 0;
if (returnHeapItem->recordId != RecordIdSetIterator::NO_MORE_RECORDS)
return true;
else
return false;
} else {
// If partialHeap is empty
if (this->numberOfItemsInPartialHeap == 0) {
if (this->_addItemsToPartialHeap() == false)
return false;
}
if (this->numberOfItemsInPartialHeap != 0) {
// Elements are there in PartialHeap and pop them out to calling function
HeapItem *currentHeapMax = *(itemsHeap.begin());
pop_heap(itemsHeap.begin(), itemsHeap.begin() + this->numberOfItemsInPartialHeap,
TermVirtualList::HeapItemCmp());
returnHeapItem->recordId = currentHeapMax->recordId;
returnHeapItem->termRecordRuntimeScore = currentHeapMax->termRecordRuntimeScore;
returnHeapItem->trieNode = currentHeapMax->trieNode;
returnHeapItem->attributeIdsList = currentHeapMax->attributeIdsList;
returnHeapItem->ed = currentHeapMax->ed;
returnHeapItem->positionIndexOffset = currentHeapMax->positionIndexOffset;
unsigned currentHeapMaxCursor = this->cursorVector[currentHeapMax->cursorVectorPosition];
unsigned currentHeapMaxInvertetedListId = currentHeapMax->invertedListId;
const shared_ptr<vectorview<unsigned> > ¤tHeapMaxInvertedList = this->invertedListReadViewVector[currentHeapMax->cursorVectorPosition];
unsigned currentHeapMaxInvertedListSize = currentHeapMaxInvertedList->size();
bool foundValidHit = 0;
// Check cursor is less than invertedList Size.
while (currentHeapMaxCursor < currentHeapMaxInvertedListSize) {
// InvertedList has more elements. Push invertedListElement at cursor into virtualList.
unsigned recordId = currentHeapMaxInvertedList->getElement(currentHeapMaxCursor);
// calculate record offset online
unsigned keywordOffset = this->invertedIndex->getKeywordOffset(this->forwardIndexDirectoryReadView,
this->invertedIndexKeywordIdsReadView,
recordId, currentHeapMaxInvertetedListId);
vector<unsigned> matchedAttributesList;
currentHeapMaxCursor++;
// check isValidTermPositionHit
float termRecordStaticScore = 0;
// ignore the record if it's no longer valid (e.g., marked deleted)
if (keywordOffset != FORWARDLIST_NOTVALID &&
this->invertedIndex->isValidTermPositionHit(forwardIndexDirectoryReadView,
recordId,
keywordOffset,
term->getAttributesToFilter(), term->getFilterAttrOperation(), matchedAttributesList,
termRecordStaticScore)) {
foundValidHit = 1;
this->cursorVector[currentHeapMax->cursorVectorPosition] = currentHeapMaxCursor;
// Update cursor of popped virtualList in invertedListCursorVector.
// Cursor always points to next element in invertedList
currentHeapMax->recordId = recordId;
currentHeapMax->termRecordRuntimeScore =
DefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore,
currentHeapMax->ed,
term->getKeyword()->size(),
currentHeapMax->isPrefixMatch,
this->prefixMatchPenalty , term->getSimilarityBoost());
currentHeapMax->attributeIdsList = matchedAttributesList;
currentHeapMax->positionIndexOffset = keywordOffset;
push_heap(itemsHeap.begin(), itemsHeap.begin()+this->numberOfItemsInPartialHeap,
TermVirtualList::HeapItemCmp());
break;
}
}
if (!foundValidHit) {
//InvertedList cursor end reached and so decrement number of elements in partialHeap
this->numberOfItemsInPartialHeap--;
//Delete the head of heap that represents empty converted list
delete currentHeapMax;
//TODO OPT Don't erase, accumulate and delete at the end.
this->itemsHeap.erase(itemsHeap.begin()+this->numberOfItemsInPartialHeap);
}
return true;
} else {
return false;
}
}
}
void TermVirtualList::getPrefixActiveNodeSet(PrefixActiveNodeSet* &prefixActiveNodeSet)
{
prefixActiveNodeSet = this->prefixActiveNodeSet;
}
void TermVirtualList::setCursors(std::vector<unsigned> *invertedListCursors)
{
// TODO mar 1
if (invertedListCursors != NULL) {
unsigned a = invertedListCursors->size();
unsigned b = this->cursorVector.size();
(void)( a == b);
//ASSERT(invertedListCursors->size() == this->cursorVector.size());
copy(invertedListCursors->begin(), invertedListCursors->end(), this->cursorVector.begin());
}
}
void TermVirtualList::getCursors(std::vector<unsigned>* &invertedListCursors)
{
// TODO mar 1
//invertedListCursors = new vector<unsigned>();
if (invertedListCursors != NULL) {
invertedListCursors->clear();
invertedListCursors->resize(this->cursorVector.size());
copy(this->cursorVector.begin(), this->cursorVector.end(), invertedListCursors->begin());
}
}
void TermVirtualList::print_test() const
{
Logger::debug("ItemsHeap Size %d", this->itemsHeap.size());
for (vector<HeapItem* >::const_iterator heapIterator = this->itemsHeap.begin();
heapIterator != this->itemsHeap.end(); heapIterator++) {
Logger::debug("InvListPosition:\tRecord: %d\t Score:%.5f", (*heapIterator)->recordId, (*heapIterator)->termRecordRuntimeScore);
}
}
unsigned TermVirtualList::getVirtualListTotalLength()
{
if (this->usingBitset) {
return bitSetSize;
} else {
unsigned totalLen = 0;
for (unsigned i=0; i<itemsHeap.size(); i++) {
totalLen += this->invertedListReadViewVector[itemsHeap[i]->cursorVectorPosition]->size();
}
return totalLen;
}
}
}
}
| 48.030888 | 154 | 0.634325 | [
"vector"
] |
d5f358de462cda09b30fe04eac05826b8bf73c05 | 3,272 | cpp | C++ | examples/glfw/src/example_4_particle_emiters.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 27 | 2015-09-26T23:29:48.000Z | 2021-03-06T08:54:46.000Z | examples/glfw/src/example_4_particle_emiters.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 83 | 2015-09-28T22:20:16.000Z | 2018-05-16T13:25:28.000Z | examples/glfw/src/example_4_particle_emiters.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 8 | 2015-11-03T22:29:29.000Z | 2018-11-17T08:49:07.000Z | #include "example_4_particle_emiters.h"
using namespace flw;
using namespace flw::flf;
using namespace flw::flc;
using namespace flw::flc;
WaterEmiter::WaterEmiter()
: EmiterPointCPU(ContextGLFW::mGraphics,
0.3,
60000.0,
glm::vec4(0.1, 0.1, 1.0, 1.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.9, 0.9, 0.9),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.0, 0.0, 0.0),
10.0,
10.0,
ContextGLFW::mGraphics->storeTexture("textures/particle.png"),
GL_SRC_ALPHA,
GL_ONE,
GL_FALSE) {
moveBy(glm::vec3(0.0, -1.0, -1.0));
}
WaterEmiter::~WaterEmiter() = default;
SandEmiter::SandEmiter()
: EmiterPointCPU(ContextGLFW::mGraphics,
0.3,
60000.0,
glm::vec4(1.0, 1.0, 0.0, 1.0),
glm::vec3(0.0, 2.0, 0.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.9, 0.9, 0.9),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.0, 0.0, 0.0),
10.0,
10.0,
ContextGLFW::mGraphics->storeTexture("textures/particle.png"),
GL_SRC_ALPHA,
GL_ONE,
GL_FALSE) {
// nothing
}
SandEmiter::~SandEmiter() = default;
SnowEmiter::SnowEmiter()
: EmiterPointGPU(ContextGLFW::mGraphics,
0.3,
600.0,
glm::vec4(1.0, 1.0, 1.0, 1.0),
glm::vec3(0.0, 1.0, 0.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.9, 0.9, 0.9),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.6, 0.6, 0.6),
1.0,
1.0,
ContextGLFW::mGraphics->storeTexture("textures/particle.png"),
GL_SRC_ALPHA,
GL_ONE,
GL_FALSE) {
// nothing
}
SnowEmiter::~SnowEmiter() = default;
int main(int argc, char* argv[]) {
ContextGLFW mContext(argc, argv);
ContextGLFW::mGraphics->attachHandler([](const Event& event) {
KeyboardEventData e = event.getData();
if (GLFW_KEY_T == e.key) {
ContextGLFW::mGraphics->configTime(0.0f);
} else {
ContextGLFW::mGraphics->configTime(1.0f);
}
}, flw::flf::EEventType::key);
auto camera = std::make_unique<CameraPerspective>(glm::vec3(0.0, 0.0, 6.0),
glm::quat(),
glm::radians(90.0),
1.0,
0.1,
1000.0);
camera->moveTo(glm::vec3(0.0, 0.0, 7.0));
auto scene = std::make_unique<Scene>();
scene->attachNew<WaterEmiter>();
scene->attachNew<SandEmiter>();
scene->attachNew<SnowEmiter>();
scene->setCamera(std::move(camera));
ContextGLFW::mGraphics->setCurrentScene(std::move(scene));
mContext.render();
exit(EXIT_SUCCESS);
}
| 31.161905 | 81 | 0.441626 | [
"render"
] |
d5f4ad8d050570bf3e3aaca4ebea5c418ef72554 | 16,227 | cpp | C++ | src/misc.cpp | MoochMcGee/SuperPC | e23e5d5d6ea50addcb9c46006f3e161f9c1abf96 | [
"BSD-3-Clause"
] | 9 | 2015-04-20T21:10:05.000Z | 2020-01-11T22:43:49.000Z | src/misc.cpp | qeeg/SuperPC | e23e5d5d6ea50addcb9c46006f3e161f9c1abf96 | [
"BSD-3-Clause"
] | 1 | 2016-10-02T17:27:36.000Z | 2016-10-04T18:26:34.000Z | src/misc.cpp | qeeg/SuperPC | e23e5d5d6ea50addcb9c46006f3e161f9c1abf96 | [
"BSD-3-Clause"
] | 2 | 2016-10-02T09:40:46.000Z | 2017-03-27T02:14:41.000Z | #include <cstdio>
#include "misc.h"
#include "cpu.h"
namespace IO_XT
{
std::vector<iohandler> handlers;
u8 rb(u16 addr)
{
int i;
for(i = 0; i<handlers.size(); i++)
{
if(addr>=handlers[i].start && addr<=handlers[i].end && handlers[i].rb != NULL) return handlers[i].rb(addr-handlers[i].start);
}
return 0;
}
void wb(u16 addr, u8 value)
{
int i;
printf("I/O port write to %04X with a value of %02X!\n",addr,value);
if(handlers.size() != 0)
{
for(i = 0; i<handlers.size(); i++)
{
if(addr>=handlers[i].start && addr<=handlers[i].end && handlers[i].wb != NULL){ handlers[i].wb(addr-handlers[i].start,value); return;}
}
printf("Calling callback!\n");
}
}
} //namespace IO_XT
namespace PIT
{
void tick()
{
for(int i = 0; i<3; i++)
{
switch(chan[i].mode)
{
case 0:
{
if(i == 2)
{
}
else
{
if(chan[i].enabled)
{
if(chan[i].counter==0)
{
//chan[i].counter = chan[i].reload;
chan[i].gate_out = true;
CPU::hint = true;
CPU::hintnum = 0;
}
chan[i].counter--;
}
}
break;
}
case 2:
{
if(i == 2)
{
}
else
{
if(chan[i].enabled)
{
chan[i].gate_out = true;
chan[i].counter--;
if(chan[i].counter==1) chan[i].gate_out = false;
if(chan[i].counter==0)
{
chan[i].gate_out = true;
chan[i].counter = chan[i].reload;
}
}
}
break;
}
case 3:
{
if(i == 2)
{
}
else
{
if(chan[i].enabled)
{
if(chan[i].counter != 0 && chan[i].counter != 1)
{
if(chan[i].flip_flop == false)
{
chan[i].gate_out ^= 1;
if(chan[i].gate_out == true)
{
CPU::hint = true;
CPU::hintnum = 0;
}
}
chan[i].flip_flop = true;
}
chan[i].counter--;
chan[i].counter--;
if(chan[i].counter==1)
{
chan[i].flip_flop = false;
chan[i].gate_out ^= 1;
if(chan[i].gate_out == true)
{
CPU::hint = true;
CPU::hintnum = 0;
}
}
if(chan[i].counter==0)
{
chan[i].flip_flop = true;
chan[i].gate_out ^= 1;
if(chan[i].gate_out == true)
{
CPU::hint = true;
CPU::hintnum = 0;
}
chan[i].counter = chan[i].reload;
}
}
}
break;
}
}
}
}
u8 rb(u16 addr)
{
switch(addr)
{
case 1:
{
if(chan[1].accessmode == 0)
{
chan[1].enabled = true;
return chan[1].counter;
}
break;
}
}
return 0;
}
void wb(u16 addr, u8 data)
{
switch(addr)
{
case 0:
{
switch(chan[0].accessmode)
{
case 1:
{
chan[0].reload = (chan[0].reload & 0xFF00) | data;
chan[0].enabled = true;
break;
}
case 3:
{
if(!chan[0].flip_flop)
{
chan[0].reload = (chan[0].reload & 0xFF00) | data;
}
else
{
chan[0].reload = (data << 8) | (chan[0].reload & 0x00FF);
}
break;
}
}
break;
}
case 1:
{
switch(chan[1].accessmode)
{
case 1:
{
chan[1].reload = (chan[1].reload & 0xFF00) | data;
chan[1].enabled = true;
break;
}
}
break;
}
case 3:
{
switch(data & 0xC0)
{
case 0x00:
{
chan[0].accessmode = (data >> 4) & 3;
chan[0].mode = (data >> 1) & 7;
chan[0].enabled = false;
chan[0].flip_flop = false;
break;
}
case 0x40:
{
chan[1].accessmode = (data >> 4) & 3;
chan[1].mode = (data >> 1) & 7;
chan[1].enabled = false;
break;
}
case 0x80:
{
chan[2].accessmode = (data >> 4) & 3;
chan[2].mode = (data >> 1) & 7;
chan[2].enabled = false;
break;
}
}
break;
}
}
}
iohandler pit = {0x0040,0x0043,rb,wb};
} //namespace PIT
//Programmable Interrupt Controller
namespace PIC
{
pic_t pic[2];
void pic1_w(u16 addr, u8 value)
{
switch(addr)
{
case 0:
{
if(value & 0x10)
{
pic[0].icw1 = value & 0x1F;
pic[0].enabled = false;
pic[0].init1 = true;
}
break;
}
case 1:
{
if(pic[0].init1 == true)
{
pic[0].offset = value;
pic[0].init2 = true;
pic[0].init1 = false;
}
else if(pic[0].init2 == true)
{
pic[0].icw3 = 0;
pic[0].init2 = false;
pic[0].init3 = true;
}
else if(pic[0].init3)
{
pic[0].init3 = false;
}
else
{
pic[0].intrmask = value;
}
break;
}
}
}
u8 pic1_r(u16 addr)
{
switch(addr)
{
case 0:
{
return 0;
break;
}
case 1:
{
return pic[0].intrmask;
break;
}
}
}
void pic2_w(u16 addr, u8 value)
{
switch(addr)
{
case 0:
{
if(value & 0x10)
{
pic[1].icw1 = value & 0x1F;
pic[1].enabled = false;
pic[1].init1 = true;
}
break;
}
case 1:
{
if(pic[1].init1 == true)
{
pic[1].offset = value;
pic[1].init2 = true;
pic[1].init1 = false;
}
else if(pic[0].init2 == true)
{
pic[1].icw3 = 0;
pic[1].init2 = false;
pic[1].init3 = true;
}
else if(pic[1].init3)
{
pic[1].init3 = false;
}
else
{
pic[1].intrmask = value;
}
break;
}
}
}
u8 pic2_r(u16 addr)
{
switch(addr)
{
case 0:
{
return 0;
break;
}
case 1:
{
return pic[1].intrmask;
break;
}
}
}
iohandler pic1 = {0x0020,0x0021,pic1_r,pic1_w};
iohandler pic2 = {0x00A0,0x00A1,pic2_r,pic2_w};
} //namespace PIC
namespace DMA_XT
{
DMA_chan chan[4];
void page_w(u16 addr, u8 value)
{
switch(addr)
{
case 3:
{
chan[3].page = value & 0x0F;
break;
}
}
}
u8 page_r(u16 addr)
{
switch(addr)
{
case 3:
{
return chan[3].page & 0x0F;
break;
}
}
}
void dma1_w(u16 addr, u8 value)
{
switch(addr)
{
case 0:
{
if(!chan[0].access_flip_flop)
{
chan[0].start_addr = (chan[0].start_addr & 0xFF00) | value;
chan[0].access_flip_flop = true;
}
else
{
chan[0].start_addr = (chan[0].start_addr & 0xFF) | (value << 8);
chan[0].access_flip_flop = false;
}
break;
}
case 1:
{
if(!chan[0].access_flip_flop)
{
chan[0].count = (chan[0].count & 0xFF00) | value;
chan[0].access_flip_flop = true;
}
else
{
chan[0].count = (chan[0].count & 0xFF) | (value << 8);
chan[0].access_flip_flop = false;
}
break;
}
case 2:
{
if(!chan[1].access_flip_flop)
{
chan[1].start_addr = (chan[1].start_addr & 0xFF00) | value;
chan[1].access_flip_flop = true;
}
else
{
chan[1].start_addr = (chan[1].start_addr & 0xFF) | (value << 8);
chan[1].access_flip_flop = false;
}
break;
}
case 3:
{
if(!chan[1].access_flip_flop)
{
chan[1].count = (chan[1].count & 0xFF00) | value;
chan[1].access_flip_flop = true;
}
else
{
chan[1].count = (chan[1].count & 0xFF) | (value << 8);
chan[1].access_flip_flop = false;
}
break;
}
case 4:
{
if(!chan[2].access_flip_flop)
{
chan[2].start_addr = (chan[2].start_addr & 0xFF00) | value;
chan[2].access_flip_flop = true;
}
else
{
chan[2].start_addr = (chan[2].start_addr & 0xFF) | (value << 8);
chan[2].access_flip_flop = false;
}
break;
}
case 5:
{
if(!chan[2].access_flip_flop)
{
chan[2].count = (chan[2].count & 0xFF00) | value;
chan[2].access_flip_flop = true;
}
else
{
chan[2].count = (chan[2].count & 0xFF) | (value << 8);
chan[2].access_flip_flop = false;
}
break;
}
case 6:
{
if(!chan[3].access_flip_flop)
{
chan[3].start_addr = (chan[3].start_addr & 0xFF00) | value;
chan[3].access_flip_flop = true;
}
else
{
chan[3].start_addr = (chan[3].start_addr & 0xFF) | (value << 8);
chan[3].access_flip_flop = false;
}
break;
}
case 7:
{
if(!chan[3].access_flip_flop)
{
chan[3].count = (chan[3].count & 0xFF00) | value;
chan[3].access_flip_flop = true;
}
else
{
chan[3].count = (chan[3].count & 0xFF) | (value << 8);
chan[3].access_flip_flop = false;
}
break;
}
}
}
u8 dma1_r(u16 addr)
{
switch(addr)
{
case 0:
{
if(!chan[0].access_flip_flop)
{
chan[0].access_flip_flop = true;
return (chan[0].start_addr & 0xFF);
}
else
{
chan[0].access_flip_flop = false;
return (chan[0].start_addr & 0xFF00) >> 8;
}
break;
}
case 1:
{
if(!chan[0].access_flip_flop)
{
chan[0].access_flip_flop = true;
return (chan[0].count & 0xFF);
}
else
{
chan[0].access_flip_flop = false;
return (chan[0].count & 0xFF00) >> 8;
}
break;
}
case 2:
{
if(!chan[1].access_flip_flop)
{
chan[1].access_flip_flop = true;
return (chan[1].start_addr & 0xFF);
}
else
{
chan[1].access_flip_flop = false;
return (chan[1].start_addr & 0xFF00) >> 8;
}
break;
}
case 3:
{
if(!chan[1].access_flip_flop)
{
chan[1].access_flip_flop = true;
return (chan[1].count & 0xFF);
}
else
{
chan[1].access_flip_flop = false;
return (chan[1].count & 0xFF00) >> 8;
}
break;
}
case 4:
{
if(!chan[2].access_flip_flop)
{
chan[2].access_flip_flop = true;
return (chan[2].start_addr & 0xFF);
}
else
{
chan[2].access_flip_flop = false;
return (chan[2].start_addr & 0xFF00) >> 8;
}
break;
}
case 5:
{
if(!chan[2].access_flip_flop)
{
chan[2].access_flip_flop = true;
return (chan[2].count & 0xFF);
}
else
{
chan[2].access_flip_flop = false;
return (chan[2].count & 0xFF00) >> 8;
}
break;
}
case 6:
{
if(!chan[3].access_flip_flop)
{
chan[3].access_flip_flop = true;
return (chan[3].start_addr & 0xFF);
}
else
{
chan[3].access_flip_flop = false;
return (chan[3].start_addr & 0xFF00) >> 8;
}
break;
}
case 7:
{
if(!chan[3].access_flip_flop)
{
chan[3].access_flip_flop = true;
return (chan[3].count & 0xFF);
}
else
{
chan[3].access_flip_flop = false;
return (chan[3].count & 0xFF00) >> 8;
}
break;
}
}
}
iohandler handler = {0x0080, 0x0083, page_r, page_w};
iohandler handler2 = {0x0000,0x0007, dma1_r, dma1_w};
} //namespace DMA_XT
namespace FDC
{
u8 fifo_res[16];
u8 fifo_exec[8];
u8 fifo_exec_pointer = 0;
u8 fifo_res_end = 0;
u8 fifo_res_pointer = 0;
u8 fifo_r(u16 addr)
{
u8 res = fifo_res[0];
return res;
}
void fifo_w(u16 addr,u8 data)
{
if(fifo_exec_pointer == 7) return;
fifo_exec[fifo_exec_pointer] = data;
fifo_exec_pointer++;
switch(fifo_exec[0])
{
case 0x10:
{
fifo_res[0] = 0x90;
fifo_res_pointer = 0;
fifo_res_end = 0;
break;
}
}
}
iohandler handler = {0x03F5,0x03F5, fifo_r, fifo_w};
}
namespace PPI
{
u8 control;
u8 porta;
u8 portb;
u8 portc;
bool dipsw1set;
bool keyboardclk;
bool keyboardena;
bool keyboardena2;
std::vector<u8> keyboardshift; //This is a vector so that input doesn't get lost.
u8 rb(u16 addr)
{
switch(addr)
{
case 0:
{
if((keyboardshift.size() != 0))
{
u8 ret = keyboardshift.at(keyboardshift.size()-1);
return ret;
}
return 0x01; //HACK
break;
}
case 2:
{
//TODO: currently hardcoded.
if(!dipsw1set) return 0x0C;
else return 0x00;
break;
}
case 4:
{
return 0x00;
break;
}
}
}
void wb(u16 addr, u8 data)
{
switch(addr)
{
case 1:
{
if(control & 2) return;
if(!(control & 4))
{
keyboardena = (data & 4) ? true : false;
dipsw1set = (data & 8) ? true : false;
keyboardclk = (data & 0x40) ? true : false;
keyboardena2 = (data & 0x80) ? true : false;
}
break;
}
case 3:
{
control = data;
break;
}
}
}
iohandler handler = {0x0060,0x0064,rb,wb};
} //namespace PPI | 22.228767 | 147 | 0.383127 | [
"vector"
] |
d5fa5c008fe10f5573a6181ca90866858f3b09ec | 9,842 | cpp | C++ | Universal-Physics-mod/src/gui/search/SearchController.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T20:01:13.000Z | 2022-03-26T20:01:13.000Z | Universal-Physics-mod/src/gui/search/SearchController.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | null | null | null | Universal-Physics-mod/src/gui/search/SearchController.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T19:59:13.000Z | 2022-03-26T19:59:13.000Z | #include "SearchController.h"
#include "SearchModel.h"
#include "SearchView.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "gui/preview/PreviewController.h"
#include "gui/preview/PreviewView.h"
#include "tasks/Task.h"
#include "tasks/TaskWindow.h"
#include "Platform.h"
#include "Controller.h"
#include "graphics/Graphics.h"
#include "client/Client.h"
#include "common/tpt-minmax.h"
SearchController::SearchController(std::function<void ()> onDone_):
activePreview(NULL),
nextQueryTime(0.0f),
nextQueryDone(true),
instantOpen(false),
doRefresh(false),
HasExited(false)
{
searchModel = new SearchModel();
searchView = new SearchView();
searchModel->AddObserver(searchView);
searchView->AttachController(this);
searchModel->UpdateSaveList(1, "");
onDone = onDone_;
}
SaveInfo * SearchController::GetLoadedSave()
{
return searchModel->GetLoadedSave();
}
void SearchController::ReleaseLoadedSave()
{
searchModel->SetLoadedSave(NULL);
}
void SearchController::Update()
{
if (doRefresh)
{
if (searchModel->UpdateSaveList(searchModel->GetPageNum(), searchModel->GetLastQuery()))
{
nextQueryDone = true;
doRefresh = false;
}
}
else if (!nextQueryDone && nextQueryTime < Platform::GetTime())
{
if (searchModel->UpdateSaveList(1, nextQuery))
nextQueryDone = true;
}
searchModel->Update();
if(activePreview && activePreview->HasExited)
{
delete activePreview;
activePreview = NULL;
if(searchModel->GetLoadedSave())
{
Exit();
}
}
}
void SearchController::Exit()
{
InstantOpen(false);
searchView->CloseActiveWindow();
if (onDone)
onDone();
//HasExited = true;
}
SearchController::~SearchController()
{
delete activePreview;
searchView->CloseActiveWindow();
delete searchModel;
delete searchView;
}
void SearchController::DoSearch(String query, bool now)
{
nextQuery = query;
if (!now)
{
nextQueryTime = Platform::GetTime()+600;
nextQueryDone = false;
}
else
{
nextQueryDone = searchModel->UpdateSaveList(1, nextQuery);
}
}
void SearchController::DoSearch2(String query)
{
// calls SearchView function to set textbox text, then calls DoSearch
searchView->Search(query);
}
void SearchController::Refresh()
{
doRefresh = true;
}
void SearchController::SetPage(int page)
{
if (page != searchModel->GetPageNum() && page > 0 && page <= searchModel->GetPageCount())
searchModel->UpdateSaveList(page, searchModel->GetLastQuery());
}
void SearchController::SetPageRelative(int offset)
{
int page = std::min(std::max(searchModel->GetPageNum() + offset, 1), searchModel->GetPageCount());
if (page != searchModel->GetPageNum())
searchModel->UpdateSaveList(page, searchModel->GetLastQuery());
}
void SearchController::ChangeSort()
{
if(searchModel->GetSort() == "new")
{
searchModel->SetSort("best");
}
else
{
searchModel->SetSort("new");
}
searchModel->UpdateSaveList(1, searchModel->GetLastQuery());
}
void SearchController::ShowOwn(bool show)
{
if(Client::Ref().GetAuthUser().UserID)
{
searchModel->SetShowFavourite(false);
searchModel->SetShowOwn(show);
}
else
searchModel->SetShowOwn(false);
searchModel->UpdateSaveList(1, searchModel->GetLastQuery());
}
void SearchController::ShowFavourite(bool show)
{
if(Client::Ref().GetAuthUser().UserID)
{
searchModel->SetShowOwn(false);
searchModel->SetShowFavourite(show);
}
else
searchModel->SetShowFavourite(false);
searchModel->UpdateSaveList(1, searchModel->GetLastQuery());
}
void SearchController::Selected(int saveID, bool selected)
{
if(!Client::Ref().GetAuthUser().UserID)
return;
if(selected)
searchModel->SelectSave(saveID);
else
searchModel->DeselectSave(saveID);
}
void SearchController::SelectAllSaves()
{
if (!Client::Ref().GetAuthUser().UserID)
return;
if (searchModel->GetShowOwn() ||
Client::Ref().GetAuthUser().UserElevation == User::ElevationModerator ||
Client::Ref().GetAuthUser().UserElevation == User::ElevationAdmin)
searchModel->SelectAllSaves();
}
void SearchController::InstantOpen(bool instant)
{
instantOpen = instant;
}
void SearchController::OpenSaveDone()
{
if (activePreview->GetDoOpen() && activePreview->GetSaveInfo())
{
searchModel->SetLoadedSave(activePreview->GetSaveInfo());
}
else
{
searchModel->SetLoadedSave(NULL);
}
}
void SearchController::OpenSave(int saveID)
{
delete activePreview;
Graphics * g = searchView->GetGraphics();
g->fillrect(XRES/3, WINDOWH-20, XRES/3, 20, 0, 0, 0, 150); //dim the "Page X of Y" a little to make the CopyTextButton more noticeable
activePreview = new PreviewController(saveID, 0, instantOpen, [this] { OpenSaveDone(); });
activePreview->GetView()->MakeActiveWindow();
}
void SearchController::OpenSave(int saveID, int saveDate)
{
delete activePreview;
Graphics * g = searchView->GetGraphics();
g->fillrect(XRES/3, WINDOWH-20, XRES/3, 20, 0, 0, 0, 150); //dim the "Page X of Y" a little to make the CopyTextButton more noticeable
activePreview = new PreviewController(saveID, saveDate, instantOpen, [this] { OpenSaveDone(); });
activePreview->GetView()->MakeActiveWindow();
}
void SearchController::ClearSelection()
{
searchModel->ClearSelected();
}
void SearchController::RemoveSelected()
{
StringBuilder desc;
desc << "Are you sure you want to delete " << searchModel->GetSelected().size() << " save";
if(searchModel->GetSelected().size()>1)
desc << "s";
desc << "?";
new ConfirmPrompt("Delete saves", desc.Build(), { [this] {
removeSelectedC();
} });
}
void SearchController::removeSelectedC()
{
class RemoveSavesTask : public Task
{
SearchController *c;
std::vector<int> saves;
public:
RemoveSavesTask(std::vector<int> saves_, SearchController *c_) { saves = saves_; c = c_; }
bool doWork() override
{
for (size_t i = 0; i < saves.size(); i++)
{
notifyStatus(String::Build("Deleting save [", saves[i], "] ..."));
if (Client::Ref().DeleteSave(saves[i])!=RequestOkay)
{
notifyError(String::Build("Failed to delete [", saves[i], "]: ", Client::Ref().GetLastError()));
c->Refresh();
return false;
}
notifyProgress((i + 1) * 100 / saves.size());
}
c->Refresh();
return true;
}
};
std::vector<int> selected = searchModel->GetSelected();
new TaskWindow("Removing saves", new RemoveSavesTask(selected, this));
ClearSelection();
searchModel->UpdateSaveList(searchModel->GetPageNum(), searchModel->GetLastQuery());
}
void SearchController::UnpublishSelected(bool publish)
{
StringBuilder desc;
desc << "Are you sure you want to " << (publish ? String("publish ") : String("unpublish ")) << searchModel->GetSelected().size() << " save";
if (searchModel->GetSelected().size() > 1)
desc << "s";
desc << "?";
new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.Build(), { [this, publish] {
unpublishSelectedC(publish);
} });
}
void SearchController::unpublishSelectedC(bool publish)
{
class UnpublishSavesTask : public Task
{
std::vector<int> saves;
SearchController *c;
bool publish;
public:
UnpublishSavesTask(std::vector<int> saves_, SearchController *c_, bool publish_) { saves = saves_; c = c_; publish = publish_; }
bool PublishSave(int saveID)
{
notifyStatus(String::Build("Publishing save [", saveID, "]"));
if (Client::Ref().PublishSave(saveID) != RequestOkay)
return false;
return true;
}
bool UnpublishSave(int saveID)
{
notifyStatus(String::Build("Unpublishing save [", saveID, "]"));
if (Client::Ref().UnpublishSave(saveID) != RequestOkay)
return false;
return true;
}
bool doWork() override
{
bool ret;
for (size_t i = 0; i < saves.size(); i++)
{
if (publish)
ret = PublishSave(saves[i]);
else
ret = UnpublishSave(saves[i]);
if (!ret)
{
if (publish) // uses html page so error message will be spam
notifyError(String::Build("Failed to publish [", saves[i], "], is this save yours?"));
else
notifyError(String::Build("Failed to unpublish [", saves[i], "]: " + Client::Ref().GetLastError()));
c->Refresh();
return false;
}
notifyProgress((i + 1) * 100 / saves.size());
}
c->Refresh();
return true;
}
};
std::vector<int> selected = searchModel->GetSelected();
new TaskWindow(publish ? String("Publishing Saves") : String("Unpublishing Saves"), new UnpublishSavesTask(selected, this, publish));
}
void SearchController::FavouriteSelected()
{
class FavouriteSavesTask : public Task
{
std::vector<int> saves;
public:
FavouriteSavesTask(std::vector<int> saves_) { saves = saves_; }
bool doWork() override
{
for (size_t i = 0; i < saves.size(); i++)
{
notifyStatus(String::Build("Favouring save [", saves[i], "]"));
if (Client::Ref().FavouriteSave(saves[i], true)!=RequestOkay)
{
notifyError(String::Build("Failed to favourite [", saves[i], "]: " + Client::Ref().GetLastError()));
return false;
}
notifyProgress((i + 1) * 100 / saves.size());
}
return true;
}
};
class UnfavouriteSavesTask : public Task
{
std::vector<int> saves;
public:
UnfavouriteSavesTask(std::vector<int> saves_) { saves = saves_; }
bool doWork() override
{
for (size_t i = 0; i < saves.size(); i++)
{
notifyStatus(String::Build("Unfavouring save [", saves[i], "]"));
if (Client::Ref().FavouriteSave(saves[i], false)!=RequestOkay)
{
notifyError(String::Build("Failed to unfavourite [", saves[i], "]: " + Client::Ref().GetLastError()));
return false;
}
notifyProgress((i + 1) * 100 / saves.size());
}
return true;
}
};
std::vector<int> selected = searchModel->GetSelected();
if (!searchModel->GetShowFavourite())
new TaskWindow("Favouring saves", new FavouriteSavesTask(selected));
else
new TaskWindow("Unfavouring saves", new UnfavouriteSavesTask(selected));
ClearSelection();
}
| 25.043257 | 142 | 0.687665 | [
"vector"
] |
d5fd722ac090fed0f9d5a693bc505f6a9a40332c | 92,815 | cpp | C++ | qcom-caf/display/sdm/libs/core/drm/hw_device_drm.cpp | nubia-rom-team/android_device_nubia_NX651J | a55ec3e131a4ebeb2c973f4abc982584464d79f8 | [
"Apache-2.0"
] | 1 | 2022-02-11T10:31:53.000Z | 2022-02-11T10:31:53.000Z | qcom-caf/display/sdm/libs/core/drm/hw_device_drm.cpp | nubia-rom-team/android_device_nubia_NX651J | a55ec3e131a4ebeb2c973f4abc982584464d79f8 | [
"Apache-2.0"
] | null | null | null | qcom-caf/display/sdm/libs/core/drm/hw_device_drm.cpp | nubia-rom-team/android_device_nubia_NX651J | a55ec3e131a4ebeb2c973f4abc982584464d79f8 | [
"Apache-2.0"
] | 3 | 2021-08-17T19:04:22.000Z | 2021-11-11T11:06:10.000Z | /*
* Copyright (c) 2017-2020, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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.
*/
#define __STDC_FORMAT_MACROS
#include <ctype.h>
#include <time.h>
#include <drm/drm_fourcc.h>
#include <drm_lib_loader.h>
#include <drm_master.h>
#include <drm_res_mgr.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/fb.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utils/constants.h>
#include <utils/debug.h>
#include <utils/formats.h>
#include <utils/sys.h>
#include <drm/sde_drm.h>
#include <private/color_params.h>
#include <utils/rect.h>
#include <utils/utils.h>
#include <sstream>
#include <ctime>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <limits>
#include "hw_device_drm.h"
#include "hw_info_interface.h"
#define __CLASS__ "HWDeviceDRM"
#ifndef DRM_FORMAT_MOD_QCOM_COMPRESSED
#define DRM_FORMAT_MOD_QCOM_COMPRESSED fourcc_mod_code(QCOM, 1)
#endif
#ifndef DRM_FORMAT_MOD_QCOM_DX
#define DRM_FORMAT_MOD_QCOM_DX fourcc_mod_code(QCOM, 0x2)
#endif
#ifndef DRM_FORMAT_MOD_QCOM_TIGHT
#define DRM_FORMAT_MOD_QCOM_TIGHT fourcc_mod_code(QCOM, 0x4)
#endif
using std::string;
using std::to_string;
using std::fstream;
using std::unordered_map;
using std::stringstream;
using std::ifstream;
using std::ofstream;
using drm_utils::DRMMaster;
using drm_utils::DRMResMgr;
using drm_utils::DRMLibLoader;
using drm_utils::DRMBuffer;
using sde_drm::GetDRMManager;
using sde_drm::DestroyDRMManager;
using sde_drm::DRMDisplayType;
using sde_drm::DRMDisplayToken;
using sde_drm::DRMConnectorInfo;
using sde_drm::DRMPPFeatureInfo;
using sde_drm::DRMRect;
using sde_drm::DRMRotation;
using sde_drm::DRMBlendType;
using sde_drm::DRMSrcConfig;
using sde_drm::DRMOps;
using sde_drm::DRMTopology;
using sde_drm::DRMPowerMode;
using sde_drm::DRMSecureMode;
using sde_drm::DRMSecurityLevel;
using sde_drm::DRMCscType;
using sde_drm::DRMMultiRectMode;
using sde_drm::DRMSSPPLayoutIndex;
namespace sdm {
std::atomic<uint32_t> HWDeviceDRM::hw_dest_scaler_blocks_used_(0);
static PPBlock GetPPBlock(const HWToneMapLut &lut_type) {
PPBlock pp_block = kPPBlockMax;
switch (lut_type) {
case kDma1dIgc:
case kDma1dGc:
pp_block = kDGM;
break;
case kVig1dIgc:
case kVig3dGamut:
pp_block = kVIG;
break;
default:
DLOGE("Unknown PP Block");
break;
}
return pp_block;
}
static void GetDRMFormat(LayerBufferFormat format, uint32_t *drm_format,
uint64_t *drm_format_modifier) {
switch (format) {
case kFormatRGBA8888:
*drm_format = DRM_FORMAT_ABGR8888;
break;
case kFormatRGBA8888Ubwc:
*drm_format = DRM_FORMAT_ABGR8888;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatRGBA5551:
*drm_format = DRM_FORMAT_ABGR1555;
break;
case kFormatRGBA4444:
*drm_format = DRM_FORMAT_ABGR4444;
break;
case kFormatBGRA8888:
*drm_format = DRM_FORMAT_ARGB8888;
break;
case kFormatRGBX8888:
*drm_format = DRM_FORMAT_XBGR8888;
break;
case kFormatRGBX8888Ubwc:
*drm_format = DRM_FORMAT_XBGR8888;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatBGRX8888:
*drm_format = DRM_FORMAT_XRGB8888;
break;
case kFormatRGB888:
*drm_format = DRM_FORMAT_BGR888;
break;
case kFormatRGB565:
*drm_format = DRM_FORMAT_BGR565;
break;
case kFormatBGR565:
*drm_format = DRM_FORMAT_RGB565;
break;
case kFormatBGR565Ubwc:
*drm_format = DRM_FORMAT_BGR565;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatRGBA1010102:
*drm_format = DRM_FORMAT_ABGR2101010;
break;
case kFormatRGBA1010102Ubwc:
*drm_format = DRM_FORMAT_ABGR2101010;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatARGB2101010:
*drm_format = DRM_FORMAT_BGRA1010102;
break;
case kFormatRGBX1010102:
*drm_format = DRM_FORMAT_XBGR2101010;
break;
case kFormatRGBX1010102Ubwc:
*drm_format = DRM_FORMAT_XBGR2101010;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatXRGB2101010:
*drm_format = DRM_FORMAT_BGRX1010102;
break;
case kFormatBGRA1010102:
*drm_format = DRM_FORMAT_ARGB2101010;
break;
case kFormatABGR2101010:
*drm_format = DRM_FORMAT_RGBA1010102;
break;
case kFormatBGRX1010102:
*drm_format = DRM_FORMAT_XRGB2101010;
break;
case kFormatXBGR2101010:
*drm_format = DRM_FORMAT_RGBX1010102;
break;
case kFormatYCbCr420SemiPlanar:
*drm_format = DRM_FORMAT_NV12;
break;
case kFormatYCbCr420SemiPlanarVenus:
*drm_format = DRM_FORMAT_NV12;
break;
case kFormatYCbCr420SPVenusUbwc:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED;
break;
case kFormatYCbCr420SPVenusTile:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_TILE;
break;
case kFormatYCrCb420SemiPlanar:
*drm_format = DRM_FORMAT_NV21;
break;
case kFormatYCrCb420SemiPlanarVenus:
*drm_format = DRM_FORMAT_NV21;
break;
case kFormatYCbCr420P010:
case kFormatYCbCr420P010Venus:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_DX;
break;
case kFormatYCbCr420P010Ubwc:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED |
DRM_FORMAT_MOD_QCOM_DX;
break;
case kFormatYCbCr420P010Tile:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_TILE |
DRM_FORMAT_MOD_QCOM_DX;
break;
case kFormatYCbCr420TP10Ubwc:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_COMPRESSED |
DRM_FORMAT_MOD_QCOM_DX | DRM_FORMAT_MOD_QCOM_TIGHT;
break;
case kFormatYCbCr420TP10Tile:
*drm_format = DRM_FORMAT_NV12;
*drm_format_modifier = DRM_FORMAT_MOD_QCOM_TILE |
DRM_FORMAT_MOD_QCOM_DX | DRM_FORMAT_MOD_QCOM_TIGHT;
break;
case kFormatYCbCr422H2V1SemiPlanar:
*drm_format = DRM_FORMAT_NV16;
break;
case kFormatYCrCb422H2V1SemiPlanar:
*drm_format = DRM_FORMAT_NV61;
break;
case kFormatYCrCb420PlanarStride16:
*drm_format = DRM_FORMAT_YVU420;
break;
default:
DLOGW("Unsupported format %s", GetFormatString(format));
}
}
class FrameBufferObject : public LayerBufferObject {
public:
explicit FrameBufferObject(uint32_t fb_id, LayerBufferFormat format,
uint32_t width, uint32_t height)
:fb_id_(fb_id), format_(format), width_(width), height_(height) {
}
~FrameBufferObject() {
DRMMaster *master;
DRMMaster::GetInstance(&master);
int ret = master->RemoveFbId(fb_id_);
if (ret < 0) {
DLOGE("Removing fb_id %d failed with error %d", fb_id_, errno);
}
}
uint32_t GetFbId() { return fb_id_; }
bool IsEqual(LayerBufferFormat format, uint32_t width, uint32_t height) {
return (format == format_ && width == width_ && height == height_);
}
private:
uint32_t fb_id_;
LayerBufferFormat format_;
uint32_t width_;
uint32_t height_;
};
HWDeviceDRM::Registry::Registry(BufferAllocator *buffer_allocator) :
buffer_allocator_(buffer_allocator) {
int value = 0;
if (Debug::GetProperty(DISABLE_FBID_CACHE, &value) == kErrorNone) {
disable_fbid_cache_ = (value == 1);
}
}
void HWDeviceDRM::Registry::Register(HWLayers *hw_layers) {
HWLayersInfo &hw_layer_info = hw_layers->info;
uint32_t hw_layer_count = UINT32(hw_layer_info.hw_layers.size());
for (uint32_t i = 0; i < hw_layer_count; i++) {
Layer &layer = hw_layer_info.hw_layers.at(i);
LayerBuffer input_buffer = layer.input_buffer;
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[0];
fbid_cache_limit_ = input_buffer.flags.video ? VIDEO_FBID_LIMIT : UI_FBID_LIMIT;
if (hw_rotator_session->mode == kRotatorOffline && hw_rotate_info->valid) {
input_buffer = hw_rotator_session->output_buffer;
fbid_cache_limit_ = OFFLINE_ROTATOR_FBID_LIMIT;
}
if (input_buffer.flags.interlace) {
input_buffer.width *= 2;
input_buffer.height /= 2;
}
MapBufferToFbId(&layer, input_buffer);
}
}
int HWDeviceDRM::Registry::CreateFbId(const LayerBuffer &buffer, uint32_t *fb_id) {
DRMMaster *master = nullptr;
DRMMaster::GetInstance(&master);
int ret = -1;
if (!master) {
DLOGE("Failed to acquire DRM Master instance");
return ret;
}
DRMBuffer layout{};
AllocatedBufferInfo buf_info{};
buf_info.fd = layout.fd = buffer.planes[0].fd;
buf_info.aligned_width = layout.width = buffer.width;
buf_info.aligned_height = layout.height = buffer.height;
buf_info.format = buffer.format;
GetDRMFormat(buf_info.format, &layout.drm_format, &layout.drm_format_modifier);
buffer_allocator_->GetBufferLayout(buf_info, layout.stride, layout.offset, &layout.num_planes);
ret = master->CreateFbId(layout, fb_id);
if (ret < 0) {
DLOGE("CreateFbId failed. width %d, height %d, format: %s, stride %u, error %d",
layout.width, layout.height, GetFormatString(buf_info.format), layout.stride[0], errno);
}
return ret;
}
void HWDeviceDRM::Registry::MapBufferToFbId(Layer* layer, const LayerBuffer &buffer) {
if (buffer.planes[0].fd < 0) {
return;
}
uint64_t handle_id = buffer.handle_id;
if (!handle_id || disable_fbid_cache_) {
// In legacy path, clear fb_id map in each frame.
layer->buffer_map->buffer_map.clear();
} else {
auto it = layer->buffer_map->buffer_map.find(handle_id);
if (it != layer->buffer_map->buffer_map.end()) {
FrameBufferObject *fb_obj = static_cast<FrameBufferObject*>(it->second.get());
if (fb_obj->IsEqual(buffer.format, buffer.width, buffer.height)) {
// Found fb_id for given handle_id key
return;
} else {
// Erase from fb_id map if format or size have been modified
layer->buffer_map->buffer_map.erase(it);
}
}
if (layer->buffer_map->buffer_map.size() >= fbid_cache_limit_) {
// Clear fb_id map, if the size reaches cache limit.
layer->buffer_map->buffer_map.clear();
}
}
uint32_t fb_id = 0;
if (CreateFbId(buffer, &fb_id) >= 0) {
// Create and cache the fb_id in map
layer->buffer_map->buffer_map[handle_id] = std::make_shared<FrameBufferObject>(fb_id,
buffer.format, buffer.width, buffer.height);
}
}
void HWDeviceDRM::Registry::MapOutputBufferToFbId(LayerBuffer *output_buffer) {
if (output_buffer->planes[0].fd < 0) {
return;
}
uint64_t handle_id = output_buffer->handle_id;
if (!handle_id || disable_fbid_cache_) {
// In legacy path, clear output buffer map in each frame.
output_buffer_map_.clear();
} else {
auto it = output_buffer_map_.find(handle_id);
if (it != output_buffer_map_.end()) {
FrameBufferObject *fb_obj = static_cast<FrameBufferObject*>(it->second.get());
if (fb_obj->IsEqual(output_buffer->format, output_buffer->width, output_buffer->height)) {
return;
} else {
output_buffer_map_.erase(it);
}
}
if (output_buffer_map_.size() >= UI_FBID_LIMIT) {
// Clear output buffer map, if the size reaches cache limit.
output_buffer_map_.clear();
}
}
uint32_t fb_id = 0;
if (CreateFbId(*output_buffer, &fb_id) >= 0) {
output_buffer_map_[handle_id] = std::make_shared<FrameBufferObject>(fb_id,
output_buffer->format, output_buffer->width, output_buffer->height);
}
}
void HWDeviceDRM::Registry::Clear() {
output_buffer_map_.clear();
}
uint32_t HWDeviceDRM::Registry::GetFbId(Layer *layer, uint64_t handle_id) {
auto it = layer->buffer_map->buffer_map.find(handle_id);
if (it != layer->buffer_map->buffer_map.end()) {
FrameBufferObject *fb_obj = static_cast<FrameBufferObject*>(it->second.get());
return fb_obj->GetFbId();
}
return 0;
}
uint32_t HWDeviceDRM::Registry::GetOutputFbId(uint64_t handle_id) {
auto it = output_buffer_map_.find(handle_id);
if (it != output_buffer_map_.end()) {
FrameBufferObject *fb_obj = static_cast<FrameBufferObject*>(it->second.get());
return fb_obj->GetFbId();
}
return 0;
}
HWDeviceDRM::HWDeviceDRM(BufferSyncHandler *buffer_sync_handler, BufferAllocator *buffer_allocator,
HWInfoInterface *hw_info_intf)
: hw_info_intf_(hw_info_intf), buffer_sync_handler_(buffer_sync_handler),
registry_(buffer_allocator) {
hw_info_intf_ = hw_info_intf;
}
DisplayError HWDeviceDRM::Init() {
int ret = 0;
DRMMaster *drm_master = {};
DRMMaster::GetInstance(&drm_master);
drm_master->GetHandle(&dev_fd_);
DRMLibLoader::GetInstance()->FuncGetDRMManager()(dev_fd_, &drm_mgr_intf_);
if (-1 == display_id_) {
if (drm_mgr_intf_->RegisterDisplay(disp_type_, &token_)) {
DLOGE("RegisterDisplay (by type) failed for %s", device_name_);
return kErrorResources;
}
} else if (drm_mgr_intf_->RegisterDisplay(display_id_, &token_)) {
DLOGE("RegisterDisplay (by id) failed for %s - %d", device_name_, display_id_);
return kErrorResources;
}
if (token_.conn_id > INT32_MAX) {
DLOGE("Connector id %u beyond supported range", token_.conn_id);
drm_mgr_intf_->UnregisterDisplay(&token_);
return kErrorNotSupported;
}
display_id_ = static_cast<int32_t>(token_.conn_id);
ret = drm_mgr_intf_->CreateAtomicReq(token_, &drm_atomic_intf_);
if (ret) {
DLOGE("Failed creating atomic request for connector id %u. Error: %d.", token_.conn_id, ret);
drm_mgr_intf_->UnregisterDisplay(&token_);
return kErrorResources;
}
ret = drm_mgr_intf_->GetConnectorInfo(token_.conn_id, &connector_info_);
if (ret) {
DLOGE("Failed getting info for connector id %u. Error: %d.", token_.conn_id, ret);
drm_mgr_intf_->DestroyAtomicReq(drm_atomic_intf_);
drm_atomic_intf_ = {};
drm_mgr_intf_->UnregisterDisplay(&token_);
return kErrorHardware;
}
if (!connector_info_.is_connected || connector_info_.modes.empty()) {
DLOGW("Device removal detected on connector id %u. Connector status %s and %zu modes.",
token_.conn_id, connector_info_.is_connected ? "connected":"disconnected",
connector_info_.modes.size());
drm_mgr_intf_->DestroyAtomicReq(drm_atomic_intf_);
drm_atomic_intf_ = {};
drm_mgr_intf_->UnregisterDisplay(&token_);
return kErrorDeviceRemoved;
}
hw_info_intf_->GetHWResourceInfo(&hw_resource_);
InitializeConfigs();
PopulateHWPanelInfo();
UpdateMixerAttributes();
// TODO(user): In future, remove has_qseed3 member, add version and pass version to constructor
if (hw_resource_.has_qseed3) {
hw_scale_ = new HWScaleDRM(HWScaleDRM::Version::V2);
}
std::unique_ptr<HWColorManagerDrm> hw_color_mgr(new HWColorManagerDrm());
hw_color_mgr_ = std::move(hw_color_mgr);
return kErrorNone;
}
DisplayError HWDeviceDRM::Deinit() {
DisplayError err = kErrorNone;
if (!first_cycle_) {
// A null-commit is needed only if the first commit had gone through. e.g., If a pluggable
// display is plugged in and plugged out immediately, HWDeviceDRM::Deinit() may be called
// before any commit happened on the device. The driver may have removed any not-in-use
// connector (i.e., any connector which did not have a display commit on it and a crtc path
// setup), so token_.conn_id may have been removed if there was no commit, resulting in
// drmModeAtomicCommit() failure with ENOENT, 'No such file or directory'.
ClearSolidfillStages();
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_CRTC, token_.conn_id, 0);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::OFF);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_MODE, token_.crtc_id, nullptr);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 0);
int ret = NullCommit(true /* synchronous */, false /* retain_planes */);
if (ret) {
DLOGE("Commit failed with error: %d", ret);
err = kErrorHardware;
}
}
delete hw_scale_;
registry_.Clear();
display_attributes_ = {};
drm_mgr_intf_->DestroyAtomicReq(drm_atomic_intf_);
drm_atomic_intf_ = {};
drm_mgr_intf_->UnregisterDisplay(&token_);
hw_dest_scaler_blocks_used_ -= dest_scaler_blocks_used_;
return err;
}
DisplayError HWDeviceDRM::GetDisplayId(int32_t *display_id) {
*display_id = display_id_;
return kErrorNone;
}
void HWDeviceDRM::InitializeConfigs() {
current_mode_index_ = 0;
// Update current mode with preferred mode
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if (connector_info_.modes[mode_index].mode.type & DRM_MODE_TYPE_PREFERRED) {
DLOGI("Updating current display mode %d to preferred mode %d.", current_mode_index_,
mode_index);
current_mode_index_ = mode_index;
break;
}
}
display_attributes_.resize(connector_info_.modes.size());
uint32_t width = connector_info_.modes[current_mode_index_].mode.hdisplay;
uint32_t height = connector_info_.modes[current_mode_index_].mode.vdisplay;
for (uint32_t i = 0; i < connector_info_.modes.size(); i++) {
auto &mode = connector_info_.modes[i].mode;
if (mode.hdisplay != width || mode.vdisplay != height) {
resolution_switch_enabled_ = true;
}
PopulateDisplayAttributes(i);
}
SetDisplaySwitchMode(current_mode_index_);
}
DisplayError HWDeviceDRM::PopulateDisplayAttributes(uint32_t index) {
drmModeModeInfo mode = {};
uint32_t mm_width = 0;
uint32_t mm_height = 0;
DRMTopology topology = DRMTopology::SINGLE_LM;
if (default_mode_) {
DRMResMgr *res_mgr = nullptr;
int ret = DRMResMgr::GetInstance(&res_mgr);
if (ret < 0) {
DLOGE("Failed to acquire DRMResMgr instance");
return kErrorResources;
}
res_mgr->GetMode(&mode);
res_mgr->GetDisplayDimInMM(&mm_width, &mm_height);
} else {
mode = connector_info_.modes[index].mode;
mm_width = connector_info_.mmWidth;
mm_height = connector_info_.mmHeight;
topology = connector_info_.modes[index].topology;
if (mode.flags & DRM_MODE_FLAG_CMD_MODE_PANEL) {
display_attributes_[index].smart_panel = true;
}
}
display_attributes_[index].x_pixels = mode.hdisplay;
display_attributes_[index].y_pixels = mode.vdisplay;
display_attributes_[index].fps = mode.vrefresh;
display_attributes_[index].vsync_period_ns =
UINT32(1000000000L / display_attributes_[index].fps);
/*
Active Front Sync Back
Region Porch Porch
<-----------------------><----------------><-------------><-------------->
<----- [hv]display ----->
<------------- [hv]sync_start ------------>
<--------------------- [hv]sync_end --------------------->
<-------------------------------- [hv]total ----------------------------->
*/
display_attributes_[index].v_front_porch = mode.vsync_start - mode.vdisplay;
display_attributes_[index].v_pulse_width = mode.vsync_end - mode.vsync_start;
display_attributes_[index].v_back_porch = mode.vtotal - mode.vsync_end;
display_attributes_[index].v_total = mode.vtotal;
display_attributes_[index].h_total = mode.htotal;
display_attributes_[index].is_device_split =
(topology == DRMTopology::DUAL_LM || topology == DRMTopology::DUAL_LM_MERGE ||
topology == DRMTopology::DUAL_LM_MERGE_DSC || topology == DRMTopology::DUAL_LM_DSC ||
topology == DRMTopology::DUAL_LM_DSCMERGE || topology == DRMTopology::QUAD_LM_MERGE ||
topology == DRMTopology::QUAD_LM_DSCMERGE || topology == DRMTopology::QUAD_LM_MERGE_DSC);
display_attributes_[index].clock_khz = mode.clock;
// If driver doesn't return panel width/height information, default to 320 dpi
if (INT(mm_width) <= 0 || INT(mm_height) <= 0) {
mm_width = UINT32(((FLOAT(mode.hdisplay) * 25.4f) / 320.0f) + 0.5f);
mm_height = UINT32(((FLOAT(mode.vdisplay) * 25.4f) / 320.0f) + 0.5f);
DLOGW("Driver doesn't report panel physical width and height - defaulting to 320dpi");
}
display_attributes_[index].x_dpi = (FLOAT(mode.hdisplay) * 25.4f) / FLOAT(mm_width);
display_attributes_[index].y_dpi = (FLOAT(mode.vdisplay) * 25.4f) / FLOAT(mm_height);
SetTopology(topology, &display_attributes_[index].topology);
DLOGI("Display attributes[%d]: WxH: %dx%d, DPI: %fx%f, FPS: %d, LM_SPLIT: %d, V_BACK_PORCH: %d," \
" V_FRONT_PORCH: %d, V_PULSE_WIDTH: %d, V_TOTAL: %d, H_TOTAL: %d, CLK: %dKHZ," \
" TOPOLOGY: %d, HW_SPLIT: %d", index, display_attributes_[index].x_pixels,
display_attributes_[index].y_pixels, display_attributes_[index].x_dpi,
display_attributes_[index].y_dpi, display_attributes_[index].fps,
display_attributes_[index].is_device_split, display_attributes_[index].v_back_porch,
display_attributes_[index].v_front_porch, display_attributes_[index].v_pulse_width,
display_attributes_[index].v_total, display_attributes_[index].h_total,
display_attributes_[index].clock_khz, display_attributes_[index].topology,
mixer_attributes_.split_type);
return kErrorNone;
}
void HWDeviceDRM::PopulateHWPanelInfo() {
hw_panel_info_ = {};
snprintf(hw_panel_info_.panel_name, sizeof(hw_panel_info_.panel_name), "%s",
connector_info_.panel_name.c_str());
uint32_t index = current_mode_index_;
hw_panel_info_.split_info.left_split = display_attributes_[index].x_pixels;
if (display_attributes_[index].is_device_split) {
hw_panel_info_.split_info.left_split = hw_panel_info_.split_info.right_split =
display_attributes_[index].x_pixels / 2;
}
hw_panel_info_.partial_update = connector_info_.modes[index].num_roi;
hw_panel_info_.left_roi_count = UINT32(connector_info_.modes[index].num_roi);
hw_panel_info_.right_roi_count = UINT32(connector_info_.modes[index].num_roi);
hw_panel_info_.left_align = connector_info_.modes[index].xstart;
hw_panel_info_.top_align = connector_info_.modes[index].ystart;
hw_panel_info_.width_align = connector_info_.modes[index].walign;
hw_panel_info_.height_align = connector_info_.modes[index].halign;
hw_panel_info_.min_roi_width = connector_info_.modes[index].wmin;
hw_panel_info_.min_roi_height = connector_info_.modes[index].hmin;
hw_panel_info_.needs_roi_merge = connector_info_.modes[index].roi_merge;
hw_panel_info_.transfer_time_us = connector_info_.modes[index].transfer_time_us;
hw_panel_info_.dynamic_fps = connector_info_.dynamic_fps;
hw_panel_info_.qsync_support = connector_info_.qsync_support;
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
if (hw_panel_info_.dynamic_fps) {
uint32_t min_fps = current_mode.vrefresh;
uint32_t max_fps = current_mode.vrefresh;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay)) {
if (min_fps > connector_info_.modes[mode_index].mode.vrefresh) {
min_fps = connector_info_.modes[mode_index].mode.vrefresh;
}
if (max_fps < connector_info_.modes[mode_index].mode.vrefresh) {
max_fps = connector_info_.modes[mode_index].mode.vrefresh;
}
}
}
hw_panel_info_.min_fps = min_fps;
hw_panel_info_.max_fps = max_fps;
} else {
hw_panel_info_.min_fps = current_mode.vrefresh;
hw_panel_info_.max_fps = current_mode.vrefresh;
}
hw_panel_info_.is_primary_panel = connector_info_.is_primary;
hw_panel_info_.is_pluggable = 0;
hw_panel_info_.hdr_enabled = connector_info_.panel_hdr_prop.hdr_enabled;
// Convert the luminance values to cd/m^2 units.
hw_panel_info_.peak_luminance = FLOAT(connector_info_.panel_hdr_prop.peak_brightness) / 10000.0f;
hw_panel_info_.blackness_level = FLOAT(connector_info_.panel_hdr_prop.blackness_level) / 10000.0f;
hw_panel_info_.primaries.white_point[0] = connector_info_.panel_hdr_prop.display_primaries[0];
hw_panel_info_.primaries.white_point[1] = connector_info_.panel_hdr_prop.display_primaries[1];
hw_panel_info_.primaries.red[0] = connector_info_.panel_hdr_prop.display_primaries[2];
hw_panel_info_.primaries.red[1] = connector_info_.panel_hdr_prop.display_primaries[3];
hw_panel_info_.primaries.green[0] = connector_info_.panel_hdr_prop.display_primaries[4];
hw_panel_info_.primaries.green[1] = connector_info_.panel_hdr_prop.display_primaries[5];
hw_panel_info_.primaries.blue[0] = connector_info_.panel_hdr_prop.display_primaries[6];
hw_panel_info_.primaries.blue[1] = connector_info_.panel_hdr_prop.display_primaries[7];
hw_panel_info_.dyn_bitclk_support = connector_info_.dyn_bitclk_support;
// no supprt for 90 rotation only flips or 180 supported
hw_panel_info_.panel_orientation.rotation = 0;
hw_panel_info_.panel_orientation.flip_horizontal =
(connector_info_.panel_orientation == DRMRotation::FLIP_H) ||
(connector_info_.panel_orientation == DRMRotation::ROT_180);
hw_panel_info_.panel_orientation.flip_vertical =
(connector_info_.panel_orientation == DRMRotation::FLIP_V) ||
(connector_info_.panel_orientation == DRMRotation::ROT_180);
GetHWDisplayPortAndMode();
GetHWPanelMaxBrightness();
if (current_mode.flags & DRM_MODE_FLAG_CMD_MODE_PANEL) {
hw_panel_info_.mode = kModeCommand;
}
if (current_mode.flags & DRM_MODE_FLAG_VID_MODE_PANEL) {
hw_panel_info_.mode = kModeVideo;
}
DLOGI_IF(kTagDriverConfig, "%s, Panel Interface = %s, Panel Mode = %s, Is Primary = %d",
device_name_, interface_str_.c_str(),
hw_panel_info_.mode == kModeVideo ? "Video" : "Command",
hw_panel_info_.is_primary_panel);
DLOGI_IF(kTagDriverConfig, "Partial Update = %d, Dynamic FPS = %d, HDR Panel = %d QSync = %d",
hw_panel_info_.partial_update, hw_panel_info_.dynamic_fps, hw_panel_info_.hdr_enabled,
hw_panel_info_.qsync_support);
DLOGI_IF(kTagDriverConfig, "Align: left = %d, width = %d, top = %d, height = %d",
hw_panel_info_.left_align, hw_panel_info_.width_align, hw_panel_info_.top_align,
hw_panel_info_.height_align);
DLOGI_IF(kTagDriverConfig, "ROI: min_width = %d, min_height = %d, need_merge = %d",
hw_panel_info_.min_roi_width, hw_panel_info_.min_roi_height,
hw_panel_info_.needs_roi_merge);
DLOGI_IF(kTagDriverConfig, "FPS: min = %d, max = %d", hw_panel_info_.min_fps,
hw_panel_info_.max_fps);
DLOGI_IF(kTagDriverConfig, "Left Split = %d, Right Split = %d",
hw_panel_info_.split_info.left_split, hw_panel_info_.split_info.right_split);
DLOGI_IF(kTagDriverConfig, "Panel Transfer time = %d us", hw_panel_info_.transfer_time_us);
DLOGI_IF(kTagDriverConfig, "Dynamic Bit Clk Support = %d", hw_panel_info_.dyn_bitclk_support);
}
DisplayError HWDeviceDRM::GetDisplayIdentificationData(uint8_t *out_port, uint32_t *out_data_size,
uint8_t *out_data) {
*out_port = token_.hw_port;
std::vector<uint8_t> &edid = connector_info_.edid;
if (out_data == nullptr) {
*out_data_size = (uint32_t)(edid.size());
if (*out_data_size == 0) {
DLOGE("EDID blob is empty, no data to return");
return kErrorDriverData;
}
} else {
*out_data_size = std::min(*out_data_size, (uint32_t)(edid.size()));
memcpy(out_data, edid.data(), *out_data_size);
}
return kErrorNone;
}
void HWDeviceDRM::GetHWDisplayPortAndMode() {
hw_panel_info_.port = kPortDefault;
hw_panel_info_.mode =
(connector_info_.panel_mode == sde_drm::DRMPanelMode::VIDEO) ? kModeVideo : kModeCommand;
if (default_mode_) {
return;
}
switch (connector_info_.type) {
case DRM_MODE_CONNECTOR_DSI:
hw_panel_info_.port = kPortDSI;
interface_str_ = "DSI";
break;
case DRM_MODE_CONNECTOR_LVDS:
hw_panel_info_.port = kPortLVDS;
interface_str_ = "LVDS";
break;
case DRM_MODE_CONNECTOR_eDP:
hw_panel_info_.port = kPortEDP;
interface_str_ = "EDP";
break;
case DRM_MODE_CONNECTOR_TV:
case DRM_MODE_CONNECTOR_HDMIA:
case DRM_MODE_CONNECTOR_HDMIB:
hw_panel_info_.port = kPortDTV;
interface_str_ = "HDMI";
break;
case DRM_MODE_CONNECTOR_VIRTUAL:
hw_panel_info_.port = kPortWriteBack;
interface_str_ = "Virtual";
break;
case DRM_MODE_CONNECTOR_DisplayPort:
hw_panel_info_.port = kPortDP;
interface_str_ = "DisplayPort";
break;
}
return;
}
DisplayError HWDeviceDRM::GetActiveConfig(uint32_t *active_config) {
*active_config = current_mode_index_;
return kErrorNone;
}
DisplayError HWDeviceDRM::GetNumDisplayAttributes(uint32_t *count) {
*count = UINT32(display_attributes_.size());
return kErrorNone;
}
DisplayError HWDeviceDRM::GetDisplayAttributes(uint32_t index,
HWDisplayAttributes *display_attributes) {
if (index >= display_attributes_.size()) {
return kErrorParameters;
}
*display_attributes = display_attributes_[index];
return kErrorNone;
}
DisplayError HWDeviceDRM::GetHWPanelInfo(HWPanelInfo *panel_info) {
*panel_info = hw_panel_info_;
return kErrorNone;
}
void HWDeviceDRM::SetDisplaySwitchMode(uint32_t index) {
uint32_t mode_flag = 0;
uint32_t curr_mode_flag = 0, switch_mode_flag = 0;
drmModeModeInfo to_set = connector_info_.modes[index].mode;
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
uint64_t current_bit_clk = connector_info_.modes[current_mode_index_].bit_clk_rate;
uint32_t switch_index = 0;
if (to_set.flags & DRM_MODE_FLAG_CMD_MODE_PANEL) {
mode_flag = DRM_MODE_FLAG_CMD_MODE_PANEL;
switch_mode_flag = DRM_MODE_FLAG_VID_MODE_PANEL;
} else if (to_set.flags & DRM_MODE_FLAG_VID_MODE_PANEL) {
mode_flag = DRM_MODE_FLAG_VID_MODE_PANEL;
switch_mode_flag = DRM_MODE_FLAG_CMD_MODE_PANEL;
}
if (current_mode.flags & DRM_MODE_FLAG_CMD_MODE_PANEL) {
curr_mode_flag = DRM_MODE_FLAG_CMD_MODE_PANEL;
} else if (current_mode.flags & DRM_MODE_FLAG_VID_MODE_PANEL) {
curr_mode_flag = DRM_MODE_FLAG_VID_MODE_PANEL;
}
if (curr_mode_flag != mode_flag) {
panel_mode_changed_ = mode_flag;
}
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((to_set.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(to_set.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(to_set.vrefresh == connector_info_.modes[mode_index].mode.vrefresh) &&
(current_bit_clk == connector_info_.modes[mode_index].bit_clk_rate) &&
(mode_flag & connector_info_.modes[mode_index].mode.flags)) {
index = mode_index;
break;
}
}
current_mode_index_ = index;
switch_mode_valid_ = false;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((to_set.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(to_set.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(to_set.vrefresh == connector_info_.modes[mode_index].mode.vrefresh) &&
(switch_mode_flag & connector_info_.modes[mode_index].mode.flags)) {
switch_index = mode_index;
switch_mode_valid_ = true;
break;
}
}
if (!switch_mode_valid_) {
// in case there is no corresponding switch mode with same fps, try for a switch
// mode with lowest fps. This is to handle cases where there are multiple video mode fps
// but only one command mode for doze like 30 fps.
uint32_t refresh_rate = 0;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((to_set.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(to_set.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(switch_mode_flag & connector_info_.modes[mode_index].mode.flags)) {
if (!refresh_rate || (refresh_rate > connector_info_.modes[mode_index].mode.vrefresh)) {
switch_index = mode_index;
switch_mode_valid_ = true;
refresh_rate = connector_info_.modes[mode_index].mode.vrefresh;
}
}
}
}
if (switch_mode_valid_) {
if (mode_flag & DRM_MODE_FLAG_VID_MODE_PANEL) {
video_mode_index_ = current_mode_index_;
cmd_mode_index_ = switch_index;
} else {
video_mode_index_ = switch_index;
cmd_mode_index_ = current_mode_index_;
}
}
}
DisplayError HWDeviceDRM::SetDisplayAttributes(uint32_t index) {
if (index >= display_attributes_.size()) {
DLOGE("Invalid mode index %d mode size %d", index, UINT32(display_attributes_.size()));
return kErrorParameters;
}
SetDisplaySwitchMode(index);
PopulateHWPanelInfo();
UpdateMixerAttributes();
DLOGI_IF(kTagDriverConfig,
"Display attributes[%d]: WxH: %dx%d, DPI: %fx%f, FPS: %d, LM_SPLIT: %d, V_BACK_PORCH: %d," \
" V_FRONT_PORCH: %d, V_PULSE_WIDTH: %d, V_TOTAL: %d, H_TOTAL: %d, CLK: %dKHZ, " \
"TOPOLOGY: %d, PanelMode %s", index, display_attributes_[index].x_pixels,
display_attributes_[index].y_pixels, display_attributes_[index].x_dpi,
display_attributes_[index].y_dpi, display_attributes_[index].fps,
display_attributes_[index].is_device_split, display_attributes_[index].v_back_porch,
display_attributes_[index].v_front_porch, display_attributes_[index].v_pulse_width,
display_attributes_[index].v_total, display_attributes_[index].h_total,
display_attributes_[index].clock_khz, display_attributes_[index].topology,
(connector_info_.modes[index].mode.flags & DRM_MODE_FLAG_VID_MODE_PANEL) ?
"Video" : "Command");
return kErrorNone;
}
DisplayError HWDeviceDRM::SetDisplayAttributes(const HWDisplayAttributes &display_attributes) {
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::GetConfigIndex(char *mode, uint32_t *index) {
return kErrorNone;
}
DisplayError HWDeviceDRM::PowerOn(const HWQosData &qos_data, int *release_fence) {
SetQOSData(qos_data);
int64_t release_fence_t = -1;
int64_t retire_fence_t = -1;
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 1);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::ON);
if (release_fence) {
drm_atomic_intf_->Perform(DRMOps::CRTC_GET_RELEASE_FENCE, token_.crtc_id, &release_fence_t);
}
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_GET_RETIRE_FENCE, token_.conn_id, &retire_fence_t);
int ret = NullCommit(false /* asynchronous */, true /* retain_planes */);
if (ret) {
DLOGE("Failed with error: %d", ret);
return kErrorHardware;
}
if (release_fence) {
*release_fence = static_cast<int>(release_fence_t);
DLOGD_IF(kTagDriverConfig, "RELEASE fence created: fd:%d", *release_fence);
}
pending_doze_ = false;
buffer_sync_handler_->SyncWait(INT(retire_fence_t), kTimeoutMsPowerOn);
Sys::close_(INT(retire_fence_t));
return kErrorNone;
}
DisplayError HWDeviceDRM::PowerOff(bool teardown) {
DTRACE_SCOPED();
if (!drm_atomic_intf_) {
DLOGE("DRM Atomic Interface is null!");
return kErrorUndefined;
}
if (first_cycle_) {
return kErrorNone;
}
ResetROI();
int64_t retire_fence_t = -1;
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_MODE, token_.crtc_id, ¤t_mode);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::OFF);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 0);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_GET_RETIRE_FENCE, token_.conn_id, &retire_fence_t);
int ret = NullCommit(false /* asynchronous */, false /* retain_planes */);
if (ret) {
DLOGE("Failed with error: %d", ret);
return kErrorHardware;
}
pending_doze_ = false;
int retire_fence = static_cast<int>(retire_fence_t);
buffer_sync_handler_->SyncWait(retire_fence, kTimeoutMsPowerOff);
Sys::close_(retire_fence);
return kErrorNone;
}
DisplayError HWDeviceDRM::Doze(const HWQosData &qos_data, int *release_fence) {
DTRACE_SCOPED();
if (!first_cycle_) {
pending_doze_ = true;
return kErrorDeferred;
}
SetQOSData(qos_data);
int64_t release_fence_t = -1;
int64_t retire_fence_t = -1;
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_CRTC, token_.conn_id, token_.crtc_id);
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_MODE, token_.crtc_id, ¤t_mode);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 1);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::DOZE);
if (release_fence) {
drm_atomic_intf_->Perform(DRMOps::CRTC_GET_RELEASE_FENCE, token_.crtc_id, &release_fence_t);
}
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_GET_RETIRE_FENCE, token_.conn_id, &retire_fence_t);
int ret = NullCommit(false /* asynchronous */, true /* retain_planes */);
if (ret) {
DLOGE("Failed with error: %d", ret);
return kErrorHardware;
}
if (release_fence) {
*release_fence = static_cast<int>(release_fence_t);
DLOGD_IF(kTagDriverConfig, "RELEASE fence created: fd:%d", *release_fence);
}
int retire_fence = static_cast<int>(retire_fence_t);
buffer_sync_handler_->SyncWait(retire_fence, kTimeoutMsDoze);
Sys::close_(retire_fence);
return kErrorNone;
}
DisplayError HWDeviceDRM::DozeSuspend(const HWQosData &qos_data, int *release_fence) {
DTRACE_SCOPED();
SetQOSData(qos_data);
int64_t release_fence_t = -1;
int64_t retire_fence_t = -1;
if (first_cycle_) {
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_CRTC, token_.conn_id, token_.crtc_id);
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_MODE, token_.crtc_id, ¤t_mode);
}
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 1);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id,
DRMPowerMode::DOZE_SUSPEND);
if (release_fence) {
drm_atomic_intf_->Perform(DRMOps::CRTC_GET_RELEASE_FENCE, token_.crtc_id, &release_fence_t);
}
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_GET_RETIRE_FENCE, token_.conn_id, &retire_fence_t);
int ret = NullCommit(false /* asynchronous */, true /* retain_planes */);
if (ret) {
DLOGE("Failed with error: %d", ret);
return kErrorHardware;
}
if (release_fence) {
*release_fence = static_cast<int>(release_fence_t);
DLOGD_IF(kTagDriverConfig, "RELEASE fence created: fd:%d", *release_fence);
}
pending_doze_ = false;
int retire_fence = static_cast<int>(retire_fence_t);
buffer_sync_handler_->SyncWait(retire_fence, kTimeoutMsDozeSuspend);
Sys::close_(retire_fence);
return kErrorNone;
}
void HWDeviceDRM::SetQOSData(const HWQosData &qos_data) {
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_CORE_CLK, token_.crtc_id, qos_data.clock_hz);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_CORE_AB, token_.crtc_id, qos_data.core_ab_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_CORE_IB, token_.crtc_id, qos_data.core_ib_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_LLCC_AB, token_.crtc_id, qos_data.llcc_ab_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_LLCC_IB, token_.crtc_id, qos_data.llcc_ib_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_DRAM_AB, token_.crtc_id, qos_data.dram_ab_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_DRAM_IB, token_.crtc_id, qos_data.dram_ib_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ROT_PREFILL_BW, token_.crtc_id,
qos_data.rot_prefill_bw_bps);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ROT_CLK, token_.crtc_id, qos_data.rot_clock_hz);
}
DisplayError HWDeviceDRM::Standby() {
return kErrorNone;
}
void HWDeviceDRM::SetupAtomic(HWLayers *hw_layers, bool validate) {
if (default_mode_) {
return;
}
DTRACE_SCOPED();
HWLayersInfo &hw_layer_info = hw_layers->info;
uint32_t hw_layer_count = UINT32(hw_layer_info.hw_layers.size());
HWQosData &qos_data = hw_layers->qos_data;
DRMSecurityLevel crtc_security_level = DRMSecurityLevel::SECURE_NON_SECURE;
uint32_t index = current_mode_index_;
drmModeModeInfo current_mode = connector_info_.modes[index].mode;
uint64_t current_bit_clk = connector_info_.modes[index].bit_clk_rate;
solid_fills_.clear();
bool resource_update = hw_layers->updates_mask.test(kUpdateResources);
bool buffer_update = hw_layers->updates_mask.test(kSwapBuffers);
bool update_config = resource_update || buffer_update ||
hw_layer_info.stack->flags.geometry_changed;
if (hw_panel_info_.partial_update && update_config) {
if (IsFullFrameUpdate(hw_layer_info)) {
ResetROI();
} else {
const int kNumMaxROIs = 4;
DRMRect crtc_rects[kNumMaxROIs] = {{0, 0, mixer_attributes_.width, mixer_attributes_.height}};
DRMRect conn_rects[kNumMaxROIs] = {{0, 0, display_attributes_[index].x_pixels,
display_attributes_[index].y_pixels}};
for (uint32_t i = 0; i < hw_layer_info.left_frame_roi.size(); i++) {
auto &roi = hw_layer_info.left_frame_roi.at(i);
// TODO(user): In multi PU, stitch ROIs vertically adjacent and upate plane destination
crtc_rects[i].left = UINT32(roi.left);
crtc_rects[i].right = UINT32(roi.right);
crtc_rects[i].top = UINT32(roi.top);
crtc_rects[i].bottom = UINT32(roi.bottom);
conn_rects[i].left = UINT32(roi.left);
conn_rects[i].right = UINT32(roi.right);
conn_rects[i].top = UINT32(roi.top);
conn_rects[i].bottom = UINT32(roi.bottom);
}
uint32_t num_rects = std::max(1u, static_cast<uint32_t>(hw_layer_info.left_frame_roi.size()));
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ROI, token_.crtc_id, num_rects, crtc_rects);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_ROI, token_.conn_id, num_rects, conn_rects);
}
}
for (uint32_t i = 0; i < hw_layer_count; i++) {
Layer &layer = hw_layer_info.hw_layers.at(i);
LayerBuffer *input_buffer = &layer.input_buffer;
HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe;
HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe;
HWLayerConfig &layer_config = hw_layers->config[i];
HWRotatorSession *hw_rotator_session = &layer_config.hw_rotator_session;
if (hw_layers->config[i].use_solidfill_stage) {
hw_layers->config[i].hw_solidfill_stage.solid_fill_info = layer.solid_fill_info;
AddSolidfillStage(hw_layers->config[i].hw_solidfill_stage, layer.plane_alpha);
continue;
}
for (uint32_t count = 0; count < 2; count++) {
HWPipeInfo *pipe_info = (count == 0) ? left_pipe : right_pipe;
HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[count];
if (hw_rotator_session->mode == kRotatorOffline && hw_rotate_info->valid) {
input_buffer = &hw_rotator_session->output_buffer;
}
uint32_t fb_id = registry_.GetFbId(&layer, input_buffer->handle_id);
if (pipe_info->valid && fb_id) {
uint32_t pipe_id = pipe_info->pipe_id;
if (update_config) {
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_ALPHA, pipe_id, layer.plane_alpha);
#ifdef FOD_ZPOS
uint32_t z_order = pipe_info->z_order;
if (layer.flags.fod_pressed
|| (hw_layer_info.stack->flags.fod_pressed_present
&& i == hw_layer_count - 1)) {
z_order |= FOD_PRESSED_LAYER_ZORDER;
}
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_ZORDER, pipe_id, z_order);
#else
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_ZORDER, pipe_id, pipe_info->z_order);
#endif
DRMBlendType blending = {};
SetBlending(layer.blending, &blending);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_BLEND_TYPE, pipe_id, blending);
DRMRect src = {};
SetRect(pipe_info->src_roi, &src);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_SRC_RECT, pipe_id, src);
DRMRect dst = {};
SetRect(pipe_info->dst_roi, &dst);
LayerRect right_mixer = {FLOAT(mixer_attributes_.split_left), 0,
FLOAT(mixer_attributes_.width), FLOAT(mixer_attributes_.height)};
LayerRect dst_roi = pipe_info->dst_roi;
// For larget displays ie; 2 * 2k * 2k * 90 fps 4 LM's get programmed.
// Each pair of LM's drive independent displays.
// Layout Index indicates the panel onto which pipe gets staged.
DRMSSPPLayoutIndex layout_index = DRMSSPPLayoutIndex::NONE;
if (mixer_attributes_.split_type == kQuadSplit) {
layout_index = DRMSSPPLayoutIndex::LEFT;
if (IsValid(Intersection(dst_roi, right_mixer))) {
dst_roi = Reposition(dst_roi, -INT(mixer_attributes_.split_left), 0);
layout_index = DRMSSPPLayoutIndex::RIGHT;
DLOGV_IF(kTagDriverConfig, "Layer index = %d sspp layout = RIGHT", i);
DLOGV_IF(kTagDriverConfig, "Right dst_roi l = %f t = %f r = %f b = %f",
dst_roi.left, dst_roi.top, dst_roi.right, dst_roi.bottom);
} else {
DLOGV_IF(kTagDriverConfig, "Layer index = %d sspp layout = LEFT", i);
DLOGV_IF(kTagDriverConfig, "Left dst_roi l = %f t = %f r = %f b = %f",
dst_roi.left, dst_roi.top, dst_roi.right, dst_roi.bottom);
}
}
SetRect(dst_roi, &dst);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_DST_RECT, pipe_id, dst);
// Update Layout index.
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_SSPP_LAYOUT, pipe_id, layout_index);
DRMRect excl = {};
SetRect(pipe_info->excl_rect, &excl);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_EXCL_RECT, pipe_id, excl);
uint32_t rot_bit_mask = 0;
SetRotation(layer.transform, layer_config, &rot_bit_mask);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_ROTATION, pipe_id, rot_bit_mask);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_H_DECIMATION, pipe_id,
pipe_info->horizontal_decimation);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_V_DECIMATION, pipe_id,
pipe_info->vertical_decimation);
DRMSecureMode fb_secure_mode;
DRMSecurityLevel security_level;
SetSecureConfig(layer.input_buffer, &fb_secure_mode, &security_level);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_FB_SECURE_MODE, pipe_id, fb_secure_mode);
if (security_level > crtc_security_level) {
crtc_security_level = security_level;
}
uint32_t config = 0;
SetSrcConfig(layer.input_buffer, hw_rotator_session->mode, &config);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_SRC_CONFIG, pipe_id, config);;
if (hw_scale_) {
SDEScaler scaler_output = {};
hw_scale_->SetScaler(pipe_info->scale_data, &scaler_output);
// TODO(user): Remove qseed3 and add version check, then send appropriate scaler object
if (hw_resource_.has_qseed3) {
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_SCALER_CONFIG, pipe_id,
reinterpret_cast<uint64_t>(&scaler_output.scaler_v2));
}
}
DRMCscType csc_type = DRMCscType::kCscTypeMax;
SelectCscType(layer.input_buffer, &csc_type);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_CSC_CONFIG, pipe_id, &csc_type);
DRMMultiRectMode multirect_mode;
SetMultiRectMode(pipe_info->flags, &multirect_mode);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_MULTIRECT_MODE, pipe_id, multirect_mode);
SetSsppTonemapFeatures(pipe_info);
}
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_FB_ID, pipe_id, fb_id);
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_CRTC, pipe_id, token_.crtc_id);
if (!validate && input_buffer->acquire_fence_fd >= 0) {
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_INPUT_FENCE, pipe_id,
input_buffer->acquire_fence_fd);
}
}
}
}
if (update_config) {
SetSolidfillStages();
SetQOSData(qos_data);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_SECURITY_LEVEL, token_.crtc_id, crtc_security_level);
}
if (hw_layers->hw_avr_info.update) {
sde_drm::DRMQsyncMode mode = sde_drm::DRMQsyncMode::NONE;
if (hw_layers->hw_avr_info.mode == kContinuousMode) {
mode = sde_drm::DRMQsyncMode::CONTINUOUS;
} else if (hw_layers->hw_avr_info.mode == kOneShotMode) {
mode = sde_drm::DRMQsyncMode::ONESHOT;
}
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_QSYNC_MODE, token_.conn_id, mode);
}
drm_atomic_intf_->Perform(DRMOps::DPPS_COMMIT_FEATURE, 0 /* argument is not used */);
if (reset_output_fence_offset_ && !validate) {
// Change back the fence_offset
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_OUTPUT_FENCE_OFFSET, token_.crtc_id, 0);
reset_output_fence_offset_ = false;
}
// Set panel mode
if (panel_mode_changed_ & DRM_MODE_FLAG_VID_MODE_PANEL) {
if (!validate) {
// Switch to video mode, corresponding change the fence_offset
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_OUTPUT_FENCE_OFFSET, token_.crtc_id, 1);
}
ResetROI();
}
if (!validate) {
drm_atomic_intf_->Perform(DRMOps::CRTC_GET_RELEASE_FENCE, token_.crtc_id, &release_fence_);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_GET_RETIRE_FENCE, token_.conn_id, &retire_fence_);
}
DLOGI_IF(kTagDriverConfig, "%s::%s System Clock=%d Hz, Core: AB=%f KBps, IB=%f Bps, " \
"LLCC: AB=%f Bps, IB=%f Bps, DRAM AB=%f Bps, IB=%f Bps, "\
"Rot: Bw=%f Bps, Clock=%d Hz", validate ? "Validate" : "Commit", device_name_,
qos_data.clock_hz, qos_data.core_ab_bps / 1000.f, qos_data.core_ib_bps / 1000.f,
qos_data.llcc_ab_bps / 1000.f, qos_data.llcc_ib_bps / 1000.f,
qos_data.dram_ab_bps / 1000.f, qos_data.dram_ib_bps / 1000.f,
qos_data.rot_prefill_bw_bps / 1000.f, qos_data.rot_clock_hz);
// Set refresh rate
if (vrefresh_) {
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(current_bit_clk == connector_info_.modes[mode_index].bit_clk_rate) &&
(current_mode.flags == connector_info_.modes[mode_index].mode.flags) &&
(vrefresh_ == connector_info_.modes[mode_index].mode.vrefresh)) {
current_mode = connector_info_.modes[mode_index].mode;
break;
}
}
}
if (bit_clk_rate_) {
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(current_mode.vrefresh == connector_info_.modes[mode_index].mode.vrefresh) &&
(current_mode.flags == connector_info_.modes[mode_index].mode.flags) &&
(bit_clk_rate_ == connector_info_.modes[mode_index].bit_clk_rate)) {
current_mode = connector_info_.modes[mode_index].mode;
break;
}
}
}
if (first_cycle_) {
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_TOPOLOGY_CONTROL, token_.conn_id,
topology_control_);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 1);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_CRTC, token_.conn_id, token_.crtc_id);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::ON);
last_power_mode_ = DRMPowerMode::ON;
} else if (pending_doze_ && !validate) {
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ACTIVE, token_.crtc_id, 1);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POWER_MODE, token_.conn_id, DRMPowerMode::DOZE);
last_power_mode_ = DRMPowerMode::DOZE;
}
// Set CRTC mode, only if display config changes
if (first_cycle_ || vrefresh_ || update_mode_ || panel_mode_changed_) {
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_MODE, token_.crtc_id, ¤t_mode);
}
if (!validate && (hw_layer_info.set_idle_time_ms >= 0)) {
DLOGI_IF(kTagDriverConfig, "Setting idle timeout to = %d ms",
hw_layer_info.set_idle_time_ms);
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_IDLE_TIMEOUT, token_.crtc_id,
hw_layer_info.set_idle_time_ms);
}
if (hw_panel_info_.mode == kModeCommand) {
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_AUTOREFRESH, token_.conn_id, autorefresh_);
}
}
void HWDeviceDRM::AddSolidfillStage(const HWSolidfillStage &sf, uint32_t plane_alpha) {
sde_drm::DRMSolidfillStage solidfill;
solidfill.bounding_rect.left = UINT32(sf.roi.left);
solidfill.bounding_rect.top = UINT32(sf.roi.top);
solidfill.bounding_rect.right = UINT32(sf.roi.right);
solidfill.bounding_rect.bottom = UINT32(sf.roi.bottom);
solidfill.is_exclusion_rect = sf.is_exclusion_rect;
solidfill.plane_alpha = plane_alpha;
solidfill.z_order = sf.z_order;
if (!sf.solid_fill_info.bit_depth) {
solidfill.color_bit_depth = 8;
solidfill.alpha = (0xff000000 & sf.color) >> 24;
solidfill.red = (0xff0000 & sf.color) >> 16;
solidfill.green = (0xff00 & sf.color) >> 8;
solidfill.blue = 0xff & sf.color;
} else {
solidfill.color_bit_depth = sf.solid_fill_info.bit_depth;
solidfill.alpha = sf.solid_fill_info.alpha;
solidfill.red = sf.solid_fill_info.red;
solidfill.green = sf.solid_fill_info.green;
solidfill.blue = sf.solid_fill_info.blue;
}
solid_fills_.push_back(solidfill);
DLOGI_IF(kTagDriverConfig, "Add a solidfill stage at z_order:%d argb_color:%x plane_alpha:%x",
solidfill.z_order, solidfill.color, solidfill.plane_alpha);
}
void HWDeviceDRM::SetSolidfillStages() {
if (hw_resource_.num_solidfill_stages) {
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_SOLIDFILL_STAGES, token_.crtc_id,
reinterpret_cast<uint64_t> (&solid_fills_));
}
}
void HWDeviceDRM::ClearSolidfillStages() {
solid_fills_.clear();
SetSolidfillStages();
}
DisplayError HWDeviceDRM::Validate(HWLayers *hw_layers) {
DTRACE_SCOPED();
DisplayError err = kErrorNone;
registry_.Register(hw_layers);
SetupAtomic(hw_layers, true /* validate */);
int ret = drm_atomic_intf_->Validate();
if (ret) {
DLOGE("failed with error %d for %s", ret, device_name_);
DumpHWLayers(hw_layers);
vrefresh_ = 0;
panel_mode_changed_ = 0;
err = kErrorHardware;
}
return err;
}
DisplayError HWDeviceDRM::Commit(HWLayers *hw_layers) {
DTRACE_SCOPED();
DisplayError err = kErrorNone;
registry_.Register(hw_layers);
if (default_mode_) {
err = DefaultCommit(hw_layers);
} else {
err = AtomicCommit(hw_layers);
}
return err;
}
DisplayError HWDeviceDRM::DefaultCommit(HWLayers *hw_layers) {
DTRACE_SCOPED();
HWLayersInfo &hw_layer_info = hw_layers->info;
LayerStack *stack = hw_layer_info.stack;
stack->retire_fence_fd = -1;
for (Layer &layer : hw_layer_info.hw_layers) {
layer.input_buffer.release_fence_fd = -1;
}
DRMMaster *master = nullptr;
int ret = DRMMaster::GetInstance(&master);
if (ret < 0) {
DLOGE("Failed to acquire DRMMaster instance");
return kErrorResources;
}
DRMResMgr *res_mgr = nullptr;
ret = DRMResMgr::GetInstance(&res_mgr);
if (ret < 0) {
DLOGE("Failed to acquire DRMResMgr instance");
return kErrorResources;
}
int dev_fd = -1;
master->GetHandle(&dev_fd);
uint32_t connector_id = 0;
res_mgr->GetConnectorId(&connector_id);
uint32_t crtc_id = 0;
res_mgr->GetCrtcId(&crtc_id);
drmModeModeInfo mode;
res_mgr->GetMode(&mode);
uint64_t handle_id = hw_layer_info.hw_layers.at(0).input_buffer.handle_id;
uint32_t fb_id = registry_.GetFbId(&hw_layer_info.hw_layers.at(0), handle_id);
ret = drmModeSetCrtc(dev_fd, crtc_id, fb_id, 0 /* x */, 0 /* y */, &connector_id,
1 /* num_connectors */, &mode);
if (ret < 0) {
DLOGE("drmModeSetCrtc failed dev fd %d, fb_id %d, crtc id %d, connector id %d, %s", dev_fd,
fb_id, crtc_id, connector_id, strerror(errno));
return kErrorHardware;
}
return kErrorNone;
}
DisplayError HWDeviceDRM::AtomicCommit(HWLayers *hw_layers) {
DTRACE_SCOPED();
SetupAtomic(hw_layers, false /* validate */);
if (hw_layers->elapse_timestamp > 0) {
struct timespec t = {0, 0};
clock_gettime(CLOCK_MONOTONIC, &t);
uint64_t current_time = (UINT64(t.tv_sec) * 1000000000LL + t.tv_nsec);
if (current_time < hw_layers->elapse_timestamp) {
usleep(UINT32((hw_layers->elapse_timestamp - current_time) / 1000));
}
}
int ret = drm_atomic_intf_->Commit(synchronous_commit_, false /* retain_planes*/);
int release_fence = INT(release_fence_);
int retire_fence = INT(retire_fence_);
if (ret) {
DLOGE("%s failed with error %d crtc %d", __FUNCTION__, ret, token_.crtc_id);
DumpHWLayers(hw_layers);
vrefresh_ = 0;
panel_mode_changed_ = 0;
CloseFd(&release_fence);
CloseFd(&retire_fence);
release_fence_ = -1;
retire_fence_ = -1;
return kErrorHardware;
}
DLOGD_IF(kTagDriverConfig, "RELEASE fence created: fd:%d", release_fence);
DLOGD_IF(kTagDriverConfig, "RETIRE fence created: fd:%d", retire_fence);
HWLayersInfo &hw_layer_info = hw_layers->info;
LayerStack *stack = hw_layer_info.stack;
stack->retire_fence_fd = retire_fence;
for (uint32_t i = 0; i < hw_layer_info.hw_layers.size(); i++) {
Layer &layer = hw_layer_info.hw_layers.at(i);
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
if (hw_rotator_session->mode == kRotatorOffline) {
hw_rotator_session->output_buffer.release_fence_fd = Sys::dup_(release_fence);
} else {
layer.input_buffer.release_fence_fd = Sys::dup_(release_fence);
}
}
hw_layer_info.sync_handle = release_fence;
if (vrefresh_) {
// Update current mode index if refresh rate is changed
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
uint64_t current_bit_clk = connector_info_.modes[current_mode_index_].bit_clk_rate;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(current_bit_clk == connector_info_.modes[mode_index].bit_clk_rate) &&
(vrefresh_ == connector_info_.modes[mode_index].mode.vrefresh)) {
current_mode_index_ = mode_index;
SetDisplaySwitchMode(mode_index);
break;
}
}
vrefresh_ = 0;
}
if (bit_clk_rate_) {
// Update current mode index if bit clk rate is changed.
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(current_mode.vrefresh == connector_info_.modes[mode_index].mode.vrefresh) &&
(bit_clk_rate_ == connector_info_.modes[mode_index].bit_clk_rate)) {
current_mode_index_ = mode_index;
SetDisplaySwitchMode(mode_index);
break;
}
}
bit_clk_rate_ = 0;
}
if (panel_mode_changed_ & DRM_MODE_FLAG_CMD_MODE_PANEL) {
panel_mode_changed_ = 0;
synchronous_commit_ = false;
} else if (panel_mode_changed_ & DRM_MODE_FLAG_VID_MODE_PANEL) {
panel_mode_changed_ = 0;
synchronous_commit_ = false;
reset_output_fence_offset_ = true;
}
first_cycle_ = false;
update_mode_ = false;
hw_layers->updates_mask = 0;
pending_doze_ = false;
return kErrorNone;
}
DisplayError HWDeviceDRM::Flush(HWLayers *hw_layers) {
ClearSolidfillStages();
ResetROI();
int ret = NullCommit(secure_display_active_ /* synchronous */, false /* retain_planes*/);
if (ret) {
DLOGE("failed with error %d", ret);
return kErrorHardware;
}
return kErrorNone;
}
void HWDeviceDRM::SetBlending(const LayerBlending &source, DRMBlendType *target) {
switch (source) {
case kBlendingPremultiplied:
*target = DRMBlendType::PREMULTIPLIED;
break;
case kBlendingOpaque:
*target = DRMBlendType::OPAQUE;
break;
case kBlendingCoverage:
*target = DRMBlendType::COVERAGE;
break;
default:
*target = DRMBlendType::UNDEFINED;
}
}
void HWDeviceDRM::SetSrcConfig(const LayerBuffer &input_buffer, const HWRotatorMode &mode,
uint32_t *config) {
// In offline rotation case, rotator will handle deinterlacing.
if (mode == kRotatorInline) {
if (input_buffer.flags.interlace) {
*config |= (0x01 << UINT32(DRMSrcConfig::DEINTERLACE));
}
}
}
void HWDeviceDRM::SelectCscType(const LayerBuffer &input_buffer, DRMCscType *type) {
if (type == NULL) {
return;
}
*type = DRMCscType::kCscTypeMax;
if (input_buffer.format < kFormatYCbCr420Planar) {
return;
}
switch (input_buffer.color_metadata.colorPrimaries) {
case ColorPrimaries_BT601_6_525:
case ColorPrimaries_BT601_6_625:
*type = ((input_buffer.color_metadata.range == Range_Full) ?
DRMCscType::kCscYuv2Rgb601FR : DRMCscType::kCscYuv2Rgb601L);
break;
case ColorPrimaries_BT709_5:
*type = DRMCscType::kCscYuv2Rgb709L;
break;
case ColorPrimaries_BT2020:
*type = ((input_buffer.color_metadata.range == Range_Full) ?
DRMCscType::kCscYuv2Rgb2020FR : DRMCscType::kCscYuv2Rgb2020L);
break;
default:
break;
}
}
void HWDeviceDRM::SetRect(const LayerRect &source, DRMRect *target) {
target->left = UINT32(source.left);
target->top = UINT32(source.top);
target->right = UINT32(source.right);
target->bottom = UINT32(source.bottom);
}
void HWDeviceDRM::SetRotation(LayerTransform transform, const HWLayerConfig &layer_config,
uint32_t* rot_bit_mask) {
HWRotatorMode mode = layer_config.hw_rotator_session.mode;
// In offline rotation case, rotator will handle flips set via offline rotator interface.
if (mode == kRotatorOffline) {
*rot_bit_mask = 0;
return;
}
// In no rotation case or inline rotation case, plane will handle flips
// In DRM framework rotation is applied in counter-clockwise direction.
if (layer_config.use_inline_rot && transform.rotation == 90) {
// a) rotate 90 clockwise = rotate 270 counter-clockwise in DRM
// rotate 270 is translated as hflip + vflip + rotate90
// b) rotate 270 clockwise = rotate 90 counter-clockwise in DRM
// c) hflip + rotate 90 clockwise = vflip + rotate 90 counter-clockwise in DRM
// d) vflip + rotate 90 clockwise = hflip + rotate 90 counter-clockwise in DRM
*rot_bit_mask = UINT32(DRMRotation::ROT_90);
transform.flip_horizontal = !transform.flip_horizontal;
transform.flip_vertical = !transform.flip_vertical;
}
if (transform.flip_horizontal) {
*rot_bit_mask |= UINT32(DRMRotation::FLIP_H);
}
if (transform.flip_vertical) {
*rot_bit_mask |= UINT32(DRMRotation::FLIP_V);
}
}
bool HWDeviceDRM::EnableHotPlugDetection(int enable) {
return true;
}
DisplayError HWDeviceDRM::SetCursorPosition(HWLayers *hw_layers, int x, int y) {
DTRACE_SCOPED();
return kErrorNone;
}
DisplayError HWDeviceDRM::GetPPFeaturesVersion(PPFeatureVersion *vers) {
struct DRMPPFeatureInfo info = {};
if (!hw_color_mgr_)
return kErrorNotSupported;
for (uint32_t i = 0; i < kMaxNumPPFeatures; i++) {
std::vector<DRMPPFeatureID> drm_id = {};
memset(&info, 0, sizeof(struct DRMPPFeatureInfo));
hw_color_mgr_->ToDrmFeatureId(kDSPP, i, &drm_id);
if (drm_id.empty())
continue;
info.id = drm_id.at(0);
drm_mgr_intf_->GetCrtcPPInfo(token_.crtc_id, &info);
vers->version[i] = hw_color_mgr_->GetFeatureVersion(info);
}
return kErrorNone;
}
DisplayError HWDeviceDRM::SetPPFeatures(PPFeaturesConfig *feature_list) {
if (pending_doze_) {
DLOGI("Doze state pending!! Skip for now");
return kErrorNone;
}
int ret = 0;
PPFeatureInfo *feature = NULL;
if (!hw_color_mgr_)
return kErrorNotSupported;
while (true) {
std::vector<DRMPPFeatureID> drm_id = {};
DRMPPFeatureInfo kernel_params = {};
bool crtc_feature = true;
ret = feature_list->RetrieveNextFeature(&feature);
if (ret || !feature)
break;
hw_color_mgr_->ToDrmFeatureId(kDSPP, feature->feature_id_, &drm_id);
if (drm_id.empty())
continue;
kernel_params.id = drm_id.at(0);
drm_mgr_intf_->GetCrtcPPInfo(token_.crtc_id, &kernel_params);
if (kernel_params.version == std::numeric_limits<uint32_t>::max()) {
crtc_feature = false;
}
DLOGV_IF(kTagDriverConfig, "feature_id = %d", feature->feature_id_);
for (DRMPPFeatureID id : drm_id) {
if (id >= kPPFeaturesMax) {
DLOGE("Invalid feature id %d", id);
continue;
}
kernel_params.id = id;
ret = hw_color_mgr_->GetDrmFeature(feature, &kernel_params);
if (!ret && crtc_feature)
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_POST_PROC,
token_.crtc_id, &kernel_params);
else if (!ret && !crtc_feature)
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_POST_PROC,
token_.conn_id, &kernel_params);
hw_color_mgr_->FreeDrmFeatureData(&kernel_params);
}
}
// Once all features were consumed, then destroy all feature instance from feature_list,
feature_list->Reset();
return kErrorNone;
}
DisplayError HWDeviceDRM::SetVSyncState(bool enable) {
return kErrorNotSupported;
}
void HWDeviceDRM::SetIdleTimeoutMs(uint32_t timeout_ms) {
// TODO(user): This function can be removed after fb is deprecated
}
DisplayError HWDeviceDRM::SetDisplayMode(const HWDisplayMode hw_display_mode) {
if (!switch_mode_valid_) {
return kErrorNotSupported;
}
uint32_t mode_flag = 0;
if (hw_display_mode == kModeCommand) {
mode_flag = DRM_MODE_FLAG_CMD_MODE_PANEL;
current_mode_index_ = cmd_mode_index_;
DLOGI_IF(kTagDriverConfig, "switch panel mode to command");
} else if (hw_display_mode == kModeVideo) {
mode_flag = DRM_MODE_FLAG_VID_MODE_PANEL;
current_mode_index_ = video_mode_index_;
DLOGI_IF(kTagDriverConfig, "switch panel mode to video");
}
PopulateHWPanelInfo();
panel_mode_changed_ = mode_flag;
synchronous_commit_ = true;
return kErrorNone;
}
DisplayError HWDeviceDRM::SetRefreshRate(uint32_t refresh_rate) {
if (bit_clk_rate_) {
// bit rate update pending.
// Defer any refresh rate setting.
return kErrorNotSupported;
}
// Check if requested refresh rate is valid
drmModeModeInfo current_mode = connector_info_.modes[current_mode_index_].mode;
uint64_t current_bit_clk = connector_info_.modes[current_mode_index_].bit_clk_rate;
for (uint32_t mode_index = 0; mode_index < connector_info_.modes.size(); mode_index++) {
if ((current_mode.vdisplay == connector_info_.modes[mode_index].mode.vdisplay) &&
(current_mode.hdisplay == connector_info_.modes[mode_index].mode.hdisplay) &&
(current_bit_clk == connector_info_.modes[mode_index].bit_clk_rate) &&
(current_mode.flags == connector_info_.modes[mode_index].mode.flags) &&
(refresh_rate == connector_info_.modes[mode_index].mode.vrefresh)) {
vrefresh_ = refresh_rate;
DLOGV_IF(kTagDriverConfig, "Set refresh rate to %d", refresh_rate);
return kErrorNone;
}
}
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::GetHWScanInfo(HWScanInfo *scan_info) {
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::GetVideoFormat(uint32_t config_index, uint32_t *video_format) {
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::GetMaxCEAFormat(uint32_t *max_cea_format) {
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level) {
DisplayError error = kErrorNone;
int fd = -1;
char data[kMaxStringLength] = {'\0'};
snprintf(data, sizeof(data), "/sys/devices/virtual/hdcp/msm_hdcp/min_level_change");
fd = Sys::open_(data, O_WRONLY);
if (fd < 0) {
DLOGE("File '%s' could not be opened. errno = %d, desc = %s", data, errno, strerror(errno));
return kErrorHardware;
}
snprintf(data, sizeof(data), "%d", min_enc_level);
ssize_t err = Sys::pwrite_(fd, data, strlen(data), 0);
if (err <= 0) {
DLOGE("Write failed, Error = %s", strerror(errno));
error = kErrorHardware;
}
Sys::close_(fd);
return error;
}
DisplayError HWDeviceDRM::SetScaleLutConfig(HWScaleLutInfo *lut_info) {
sde_drm::DRMScalerLUTInfo drm_lut_info = {};
drm_lut_info.cir_lut = lut_info->cir_lut;
drm_lut_info.dir_lut = lut_info->dir_lut;
drm_lut_info.sep_lut = lut_info->sep_lut;
drm_lut_info.cir_lut_size = lut_info->cir_lut_size;
drm_lut_info.dir_lut_size = lut_info->dir_lut_size;
drm_lut_info.sep_lut_size = lut_info->sep_lut_size;
drm_mgr_intf_->SetScalerLUT(drm_lut_info);
return kErrorNone;
}
DisplayError HWDeviceDRM::UnsetScaleLutConfig() {
drm_mgr_intf_->UnsetScalerLUT();
return kErrorNone;
}
DisplayError HWDeviceDRM::SetMixerAttributes(const HWMixerAttributes &mixer_attributes) {
if (IsResolutionSwitchEnabled()) {
return kErrorNotSupported;
}
if (!dest_scaler_blocks_used_) {
return kErrorNotSupported;
}
uint32_t index = current_mode_index_;
if (mixer_attributes.width > display_attributes_[index].x_pixels ||
mixer_attributes.height > display_attributes_[index].y_pixels) {
DLOGW("Input resolution exceeds display resolution! input: res %dx%d display: res %dx%d",
mixer_attributes.width, mixer_attributes.height, display_attributes_[index].x_pixels,
display_attributes_[index].y_pixels);
return kErrorNotSupported;
}
uint32_t max_input_width = hw_resource_.hw_dest_scalar_info.max_input_width;
if (display_attributes_[index].is_device_split) {
max_input_width *= 2;
}
if (mixer_attributes.width > max_input_width) {
DLOGW("Input width exceeds width limit! input_width %d width_limit %d", mixer_attributes.width,
max_input_width);
return kErrorNotSupported;
}
float mixer_aspect_ratio = FLOAT(mixer_attributes.width) / FLOAT(mixer_attributes.height);
float display_aspect_ratio =
FLOAT(display_attributes_[index].x_pixels) / FLOAT(display_attributes_[index].y_pixels);
if (display_aspect_ratio != mixer_aspect_ratio) {
DLOGW("Aspect ratio mismatch! input: res %dx%d display: res %dx%d", mixer_attributes.width,
mixer_attributes.height, display_attributes_[index].x_pixels,
display_attributes_[index].y_pixels);
return kErrorNotSupported;
}
float scale_x = FLOAT(display_attributes_[index].x_pixels) / FLOAT(mixer_attributes.width);
float scale_y = FLOAT(display_attributes_[index].y_pixels) / FLOAT(mixer_attributes.height);
float max_scale_up = hw_resource_.hw_dest_scalar_info.max_scale_up;
if (scale_x > max_scale_up || scale_y > max_scale_up) {
DLOGW(
"Up scaling ratio exceeds for destination scalar upscale limit scale_x %f scale_y %f "
"max_scale_up %f",
scale_x, scale_y, max_scale_up);
return kErrorNotSupported;
}
float mixer_split_ratio = FLOAT(mixer_attributes_.split_left) / FLOAT(mixer_attributes_.width);
mixer_attributes_ = mixer_attributes;
mixer_attributes_.split_left = mixer_attributes_.width;
mixer_attributes_.split_type = kNoSplit;
mixer_attributes_.dest_scaler_blocks_used = dest_scaler_blocks_used_; // No change.
if (display_attributes_[index].is_device_split) {
mixer_attributes_.split_left = UINT32(FLOAT(mixer_attributes.width) * mixer_split_ratio);
mixer_attributes_.split_type = kDualSplit;
if (display_attributes_[index].topology == kQuadLMMerge ||
display_attributes_[index].topology == kQuadLMDSCMerge ||
display_attributes_[index].topology == kQuadLMMergeDSC) {
mixer_attributes_.split_type = kQuadSplit;
}
}
return kErrorNone;
}
DisplayError HWDeviceDRM::GetMixerAttributes(HWMixerAttributes *mixer_attributes) {
if (!mixer_attributes) {
return kErrorParameters;
}
*mixer_attributes = mixer_attributes_;
return kErrorNone;
}
DisplayError HWDeviceDRM::DumpDebugData() {
string dir_path = "/data/vendor/display/hw_recovery/";
string device_str = device_name_;
// Attempt to make hw_recovery dir, it may exist
if (mkdir(dir_path.c_str(), 0777) != 0 && errno != EEXIST) {
DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path.c_str(), errno,
strerror(errno));
return kErrorPermission;
}
// If it does exist, ensure permissions are fine
if (errno == EEXIST && chmod(dir_path.c_str(), 0777) != 0) {
DLOGW("Failed to change permissions on %s directory", dir_path.c_str());
return kErrorPermission;
}
string filename = dir_path+device_str+"_HWR_"+to_string(debug_dump_count_);
ofstream dst(filename);
debug_dump_count_++;
{
ifstream src;
src.open("/sys/kernel/debug/dri/0/debug/dump");
dst << "---- Event Logs ----" << std::endl;
dst << src.rdbuf() << std::endl;
src.close();
}
{
ifstream src;
src.open("/sys/kernel/debug/dri/0/debug/recovery_reg");
dst << "---- All Registers ----" << std::endl;
dst << src.rdbuf() << std::endl;
src.close();
}
{
ifstream src;
src.open("/sys/kernel/debug/dri/0/debug/recovery_dbgbus");
dst << "---- Debug Bus ----" << std::endl;
dst << src.rdbuf() << std::endl;
src.close();
}
{
ifstream src;
src.open("/sys/kernel/debug/dri/0/debug/recovery_vbif_dbgbus");
dst << "---- VBIF Debug Bus ----" << std::endl;
dst << src.rdbuf() << std::endl;
src.close();
}
dst.close();
DLOGI("Wrote hw_recovery file %s", filename.c_str());
return kErrorNone;
}
void HWDeviceDRM::GetDRMDisplayToken(sde_drm::DRMDisplayToken *token) const {
*token = token_;
}
void HWDeviceDRM::UpdateMixerAttributes() {
uint32_t index = current_mode_index_;
mixer_attributes_.width = display_attributes_[index].x_pixels;
mixer_attributes_.height = display_attributes_[index].y_pixels;
mixer_attributes_.split_left = display_attributes_[index].is_device_split
? hw_panel_info_.split_info.left_split
: mixer_attributes_.width;
mixer_attributes_.split_type = kNoSplit;
if (display_attributes_[index].is_device_split) {
mixer_attributes_.split_type = kDualSplit;
if (display_attributes_[index].topology == kQuadLMMerge ||
display_attributes_[index].topology == kQuadLMDSCMerge ||
display_attributes_[index].topology == kQuadLMMergeDSC) {
mixer_attributes_.split_type = kQuadSplit;
}
}
DLOGI("Mixer WxH %dx%d-%d for %s", mixer_attributes_.width, mixer_attributes_.height,
mixer_attributes_.split_type, device_name_);
update_mode_ = true;
}
void HWDeviceDRM::SetSecureConfig(const LayerBuffer &input_buffer, DRMSecureMode *fb_secure_mode,
DRMSecurityLevel *security_level) {
*fb_secure_mode = DRMSecureMode::NON_SECURE;
*security_level = DRMSecurityLevel::SECURE_NON_SECURE;
if (input_buffer.flags.secure) {
if (input_buffer.flags.secure_camera) {
// IOMMU configuration for this framebuffer mode is secure domain & requires
// only stage II translation, when this buffer is accessed by Display H/W.
// Secure and non-secure planes can be attached to this CRTC.
*fb_secure_mode = DRMSecureMode::SECURE_DIR_TRANSLATION;
} else if (input_buffer.flags.secure_display) {
// IOMMU configuration for this framebuffer mode is secure domain & requires
// only stage II translation, when this buffer is accessed by Display H/W.
// Only secure planes can be attached to this CRTC.
*fb_secure_mode = DRMSecureMode::SECURE_DIR_TRANSLATION;
*security_level = DRMSecurityLevel::SECURE_ONLY;
} else {
// IOMMU configuration for this framebuffer mode is secure domain & requires both
// stage I and stage II translations, when this buffer is accessed by Display H/W.
// Secure and non-secure planes can be attached to this CRTC.
*fb_secure_mode = DRMSecureMode::SECURE;
}
}
}
void HWDeviceDRM::SetTopology(sde_drm::DRMTopology drm_topology, HWTopology *hw_topology) {
switch (drm_topology) {
case DRMTopology::SINGLE_LM: *hw_topology = kSingleLM; break;
case DRMTopology::SINGLE_LM_DSC: *hw_topology = kSingleLMDSC; break;
case DRMTopology::DUAL_LM: *hw_topology = kDualLM; break;
case DRMTopology::DUAL_LM_DSC: *hw_topology = kDualLMDSC; break;
case DRMTopology::DUAL_LM_MERGE: *hw_topology = kDualLMMerge; break;
case DRMTopology::DUAL_LM_MERGE_DSC: *hw_topology = kDualLMMergeDSC; break;
case DRMTopology::DUAL_LM_DSCMERGE: *hw_topology = kDualLMDSCMerge; break;
case DRMTopology::QUAD_LM_MERGE: *hw_topology = kQuadLMMerge; break;
case DRMTopology::QUAD_LM_DSCMERGE: *hw_topology = kQuadLMDSCMerge; break;
case DRMTopology::QUAD_LM_MERGE_DSC: *hw_topology = kQuadLMMergeDSC; break;
case DRMTopology::PPSPLIT: *hw_topology = kPPSplit; break;
default: *hw_topology = kUnknown; break;
}
}
void HWDeviceDRM::SetMultiRectMode(const uint32_t flags, DRMMultiRectMode *target) {
*target = DRMMultiRectMode::NONE;
if (flags & kMultiRect) {
*target = DRMMultiRectMode::SERIAL;
if (flags & kMultiRectParallelMode) {
*target = DRMMultiRectMode::PARALLEL;
}
}
}
void HWDeviceDRM::SetSsppTonemapFeatures(HWPipeInfo *pipe_info) {
if (pipe_info->dgm_csc_info.op != kNoOp) {
SDECsc csc = {};
SetDGMCsc(pipe_info->dgm_csc_info, &csc);
DLOGV_IF(kTagDriverConfig, "Call Perform DGM CSC Op = %s",
(pipe_info->dgm_csc_info.op == kSet) ? "Set" : "Reset");
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_DGM_CSC_CONFIG, pipe_info->pipe_id,
reinterpret_cast<uint64_t>(&csc.csc_v1));
}
if (pipe_info->inverse_pma_info.op != kNoOp) {
DLOGV_IF(kTagDriverConfig, "Call Perform Inverse PMA Op = %s",
(pipe_info->inverse_pma_info.op == kSet) ? "Set" : "Reset");
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_INVERSE_PMA, pipe_info->pipe_id,
(pipe_info->inverse_pma_info.inverse_pma) ? 1: 0);
}
SetSsppLutFeatures(pipe_info);
}
void HWDeviceDRM::SetDGMCsc(const HWPipeCscInfo &dgm_csc_info, SDECsc *csc) {
SetDGMCscV1(dgm_csc_info.csc, &csc->csc_v1);
}
void HWDeviceDRM::SetDGMCscV1(const HWCsc &dgm_csc, sde_drm_csc_v1 *csc_v1) {
uint32_t i = 0;
for (i = 0; i < MAX_CSC_MATRIX_COEFF_SIZE; i++) {
csc_v1->ctm_coeff[i] = dgm_csc.ctm_coeff[i];
DLOGV_IF(kTagDriverConfig, " DGM csc_v1[%d] = %" PRId64, i, csc_v1->ctm_coeff[i]);
}
for (i = 0; i < MAX_CSC_BIAS_SIZE; i++) {
csc_v1->pre_bias[i] = dgm_csc.pre_bias[i];
csc_v1->post_bias[i] = dgm_csc.post_bias[i];
}
for (i = 0; i < MAX_CSC_CLAMP_SIZE; i++) {
csc_v1->pre_clamp[i] = dgm_csc.pre_clamp[i];
csc_v1->post_clamp[i] = dgm_csc.post_clamp[i];
}
}
void HWDeviceDRM::SetSsppLutFeatures(HWPipeInfo *pipe_info) {
for (HWPipeTonemapLutInfo &lut_info : pipe_info->lut_info) {
if (lut_info.op != kNoOp) {
std::shared_ptr<PPFeatureInfo> feature = lut_info.pay_load;
if (feature == nullptr) {
DLOGE("Null Pointer for Op = %d lut type = %d", lut_info.op, lut_info.type);
continue;
}
DRMPPFeatureInfo kernel_params = {};
std::vector<DRMPPFeatureID> drm_id = {};
PPBlock pp_block = GetPPBlock(lut_info.type);
hw_color_mgr_->ToDrmFeatureId(pp_block, feature->feature_id_, &drm_id);
for (DRMPPFeatureID id : drm_id) {
if (id >= kPPFeaturesMax) {
DLOGE("Invalid feature id %d", id);
continue;
}
kernel_params.id = id;
bool disable = (lut_info.op == kReset);
DLOGV_IF(kTagDriverConfig, "Lut Type = %d PPBlock = %d Op = %s Disable = %d Feature = %p",
lut_info.type, pp_block, (lut_info.op ==kSet) ? "Set" : "Reset", disable,
feature.get());
int ret = hw_color_mgr_->GetDrmFeature(feature.get(), &kernel_params, disable);
if (!ret) {
drm_atomic_intf_->Perform(DRMOps::PLANE_SET_POST_PROC, pipe_info->pipe_id,
&kernel_params);
hw_color_mgr_->FreeDrmFeatureData(&kernel_params);
} else {
DLOGE("GetDrmFeature failed for Lut type = %d", lut_info.type);
}
}
drm_id.clear();
}
}
}
void HWDeviceDRM::AddDimLayerIfNeeded() {
if (secure_display_active_ && hw_resource_.secure_disp_blend_stage >= 0) {
HWSolidfillStage sf = {};
sf.z_order = UINT32(hw_resource_.secure_disp_blend_stage);
sf.roi = { 0.0, 0.0, FLOAT(mixer_attributes_.width), FLOAT(mixer_attributes_.height) };
solid_fills_.clear();
AddSolidfillStage(sf, 0xFF);
SetSolidfillStages();
}
if (!secure_display_active_) {
DRMSecurityLevel crtc_security_level = DRMSecurityLevel::SECURE_NON_SECURE;
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_SECURITY_LEVEL, token_.crtc_id, crtc_security_level);
}
}
DisplayError HWDeviceDRM::NullCommit(bool synchronous, bool retain_planes) {
DTRACE_SCOPED();
AddDimLayerIfNeeded();
int ret = drm_atomic_intf_->Commit(synchronous , retain_planes);
if (ret) {
DLOGE("failed with error %d", ret);
return kErrorHardware;
}
return kErrorNone;
}
void HWDeviceDRM::DumpConnectorModeInfo() {
for (uint32_t i = 0; i < (uint32_t)connector_info_.modes.size(); i++) {
DLOGI("Mode[%d] Name:%s vref:%d hdisp:%d hsync_s:%d hsync_e:%d htotal:%d " \
"vdisp:%d vsync_s:%d vsync_e:%d vtotal:%d\n", i, connector_info_.modes[i].mode.name,
connector_info_.modes[i].mode.vrefresh, connector_info_.modes[i].mode.hdisplay,
connector_info_.modes[i].mode.hsync_start, connector_info_.modes[i].mode.hsync_end,
connector_info_.modes[i].mode.htotal, connector_info_.modes[i].mode.vdisplay,
connector_info_.modes[i].mode.vsync_start, connector_info_.modes[i].mode.vsync_end,
connector_info_.modes[i].mode.vtotal);
}
}
void HWDeviceDRM::ResetROI() {
drm_atomic_intf_->Perform(DRMOps::CRTC_SET_ROI, token_.crtc_id, 0, nullptr);
drm_atomic_intf_->Perform(DRMOps::CONNECTOR_SET_ROI, token_.conn_id, 0, nullptr);
}
bool HWDeviceDRM::IsFullFrameUpdate(const HWLayersInfo &hw_layer_info) {
LayerRect full_frame = {0, 0, FLOAT(mixer_attributes_.width), FLOAT(mixer_attributes_.height)};
const LayerRect &frame_roi = hw_layer_info.left_frame_roi.at(0);
// If multiple ROIs are present, then it's not fullscreen update.
if (hw_layer_info.left_frame_roi.size() > 1 ||
(IsValid(frame_roi) && !IsCongruent(full_frame, frame_roi))) {
return false;
}
return true;
}
DisplayError HWDeviceDRM::SetDynamicDSIClock(uint64_t bit_clk_rate) {
return kErrorNotSupported;
}
DisplayError HWDeviceDRM::GetDynamicDSIClock(uint64_t *bit_clk_rate) {
return kErrorNotSupported;
}
void HWDeviceDRM::DumpHWLayers(HWLayers *hw_layers) {
HWLayersInfo &hw_layer_info = hw_layers->info;
DestScaleInfoMap &dest_scale_info_map = hw_layer_info.dest_scale_info_map;
LayerStack *stack = hw_layer_info.stack;
uint32_t hw_layer_count = UINT32(hw_layer_info.hw_layers.size());
std::vector<LayerRect> &left_frame_roi = hw_layer_info.left_frame_roi;
std::vector<LayerRect> &right_frame_roi = hw_layer_info.right_frame_roi;
DLOGI("HWLayers Stack: layer_count: %d, app_layer_count: %d, gpu_target_index: %d",
hw_layer_count, hw_layer_info.app_layer_count, hw_layer_info.gpu_target_index);
DLOGI("LayerStackFlags = 0x%" PRIu32 ", blend_cs = {primaries = %d, transfer = %d}",
UINT32(stack->flags.flags), UINT32(stack->blend_cs.primaries),
UINT32(stack->blend_cs.transfer));
for (uint32_t i = 0; i < left_frame_roi.size(); i++) {
DLOGI("left_frame_roi: x = %d, y = %d, w = %d, h = %d", INT(left_frame_roi[i].left),
INT(left_frame_roi[i].top), INT(left_frame_roi[i].right), INT(left_frame_roi[i].bottom));
}
for (uint32_t i = 0; i < right_frame_roi.size(); i++) {
DLOGI("right_frame_roi: x = %d, y = %d, w = %d h = %d", INT(right_frame_roi[i].left),
INT(right_frame_roi[i].top), INT(right_frame_roi[i].right),
INT(right_frame_roi[i].bottom));
}
for (uint32_t i = 0; i < dest_scale_info_map.size(); i++) {
HWDestScaleInfo *dest_scalar_data = dest_scale_info_map[i];
if (dest_scalar_data->scale_data.enable.scale) {
HWScaleData &scale_data = dest_scalar_data->scale_data;
DLOGI("Dest scalar index %d Mixer WxH %dx%d", i,
dest_scalar_data->mixer_width, dest_scalar_data->mixer_height);
DLOGI("Panel ROI [%d, %d, %d, %d]", INT(dest_scalar_data->panel_roi.left),
INT(dest_scalar_data->panel_roi.top), INT(dest_scalar_data->panel_roi.right),
INT(dest_scalar_data->panel_roi.bottom));
DLOGI("Dest scalar Dst WxH %dx%d", scale_data.dst_width, scale_data.dst_height);
}
}
for (uint32_t i = 0; i < hw_layer_count; i++) {
HWLayerConfig &hw_config = hw_layers->config[i];
HWRotatorSession &hw_rotator_session = hw_config.hw_rotator_session;
HWSessionConfig &hw_session_config = hw_rotator_session.hw_session_config;
DLOGI("========================= HW_layer: %d =========================", i);
DLOGI("src_width = %d, src_height = %d, src_format = %d, src_LayerBufferFlags = 0x%" PRIx32 ,
hw_layer_info.hw_layers[i].input_buffer.width,
hw_layer_info.hw_layers[i].input_buffer.height,
hw_layer_info.hw_layers[i].input_buffer.format,
hw_layer_info.hw_layers[i].input_buffer.flags.flags);
if (hw_config.use_inline_rot) {
DLOGI("rotator = %s, rotation = %d, flip_horizontal = %s, flip_vertical = %s",
"inline rotator", INT(hw_session_config.transform.rotation),
hw_session_config.transform.flip_horizontal ? "true" : "false",
hw_session_config.transform.flip_vertical ? "true" : "false");
} else if (hw_rotator_session.mode == kRotatorOffline) {
DLOGI("rotator = %s, rotation = %d, flip_horizontal = %s, flip_vertical = %s",
"offline rotator", INT(hw_session_config.transform.rotation),
hw_session_config.transform.flip_horizontal ? "true" : "false",
hw_session_config.transform.flip_vertical ? "true" : "false");
}
if (hw_config.use_solidfill_stage) {
HWSolidfillStage &hw_solidfill_stage = hw_config.hw_solidfill_stage;
LayerSolidFill &solid_fill_info = hw_solidfill_stage.solid_fill_info;
DLOGI("HW Solid fill info: z_order = %d, color = %d", hw_solidfill_stage.z_order,
hw_solidfill_stage.color);
DLOGI("bit_depth = %d, red = %d, green = %d, blue = %d, alpha = %d",
solid_fill_info.bit_depth, solid_fill_info.red, solid_fill_info.green,
solid_fill_info.blue, solid_fill_info.alpha);
}
for (uint32_t count = 0; count < 2; count++) {
HWPipeInfo &left_pipe = hw_config.left_pipe;
HWPipeInfo &right_pipe = hw_config.right_pipe;
HWPipeInfo &pipe_info = (count == 0) ? left_pipe : right_pipe;
HWScaleData &scale_data = pipe_info.scale_data;
if (!pipe_info.valid) {
continue;
}
std::string pipe = (count == 0) ? "left_pipe" : "right_pipe";
DLOGI("pipe = %s, pipe_id = %d, z_order = %d, flags = 0x%X",
pipe.c_str(), pipe_info.pipe_id, pipe_info.z_order, pipe_info.flags);
DLOGI("src_rect: x = %d, y = %d, w = %d, h = %d", INT(pipe_info.src_roi.left),
INT(pipe_info.src_roi.top), INT(pipe_info.src_roi.right - pipe_info.src_roi.left),
INT(pipe_info.src_roi.bottom - pipe_info.src_roi.top));
DLOGI("dst_rect: x = %d, y = %d, w = %d, h = %d", INT(pipe_info.dst_roi.left),
INT(pipe_info.dst_roi.top), INT(pipe_info.dst_roi.right - pipe_info.dst_roi.left),
INT(pipe_info.dst_roi.bottom - pipe_info.dst_roi.top));
DLOGI("excl_rect: left = %d, top = %d, right = %d, bottom = %d",
INT(pipe_info.excl_rect.left), INT(pipe_info.excl_rect.top),
INT(pipe_info.excl_rect.right), INT(pipe_info.excl_rect.bottom));
if (scale_data.enable.scale) {
DLOGI("HWScaleData enable flags: scale = %s, direction_detection = %s, detail_enhance = %s,"
" dyn_exp_disable = %s", scale_data.enable.scale ? "true" : "false",
scale_data.enable.direction_detection ? "true" : "false",
scale_data.enable.detail_enhance ? "true" : "false",
scale_data.enable.dyn_exp_disable ? "true" : "false");
DLOGI("lut_flags: lut_swap = 0x%X, lut_dir_wr = 0x%X, lut_y_cir_wr = 0x%X, "
"lut_uv_cir_wr = 0x%X, lut_y_sep_wr = 0x%X, lut_uv_sep_wr = 0x%X",
scale_data.lut_flag.lut_swap, scale_data.lut_flag.lut_dir_wr,
scale_data.lut_flag.lut_y_cir_wr, scale_data.lut_flag.lut_uv_cir_wr,
scale_data.lut_flag.lut_y_sep_wr, scale_data.lut_flag.lut_uv_sep_wr);
DLOGI("dir_lut_idx = %d, y_rgb_cir_lut_idx = %d, uv_cir_lut_idx = %d, "
"y_rgb_sep_lut_idx = %d, uv_sep_lut_idx = %d", scale_data.dir_lut_idx,
scale_data.y_rgb_cir_lut_idx, scale_data.uv_cir_lut_idx,
scale_data.y_rgb_sep_lut_idx, scale_data.uv_sep_lut_idx);
}
}
}
}
DisplayError HWDeviceDRM::SetBlendSpace(const PrimariesTransfer &blend_space) {
blend_space_ = blend_space;
return kErrorNone;
}
} // namespace sdm
| 38.576475 | 100 | 0.702602 | [
"object",
"vector",
"transform",
"solid"
] |
9100e4d16aa0f40107cd7d716a659b2bdeae86d9 | 4,544 | cpp | C++ | csp.cpp | ZerglingOne/CSP | 7bfe2b04bb5471c7c44f0d0d848a4f1b6af952ec | [
"MIT"
] | null | null | null | csp.cpp | ZerglingOne/CSP | 7bfe2b04bb5471c7c44f0d0d848a4f1b6af952ec | [
"MIT"
] | null | null | null | csp.cpp | ZerglingOne/CSP | 7bfe2b04bb5471c7c44f0d0d848a4f1b6af952ec | [
"MIT"
] | null | null | null | #include "csp.h"
bool constraint1(string sum, string num1, string num2)//the length of the sum cannot exceed more than +1 of the operands
{
int longer;
if(num1.size() > num2.size())
longer = num1.size();
else
longer = num2.size();
if((sum.size() - longer) == 0 || (sum.size() - longer) == 1)
return true;
else
return false;
}
bool constraint2(string sum, string num1, string num2, string &holder)//the number of unique letters must be <=10
{
holder = "";
bool contains = false;
for(int i = 0; i < sum.size(); i++)
{
for(int j = 0; j <= holder.size(); j++)
{
if(sum[i] == holder[j])
contains = true;
}
if(!contains)
holder+= sum[i];
contains = false;
}
for(int i = 0; i < num1.size(); i++)
{
for(int j = 0; j <= holder.size(); j++)
{
if(num1[i] == holder[j])
contains = true;
}
if(!contains)
holder+= num1[i];
contains = false;
}
for(int i = 0; i < num2.size(); i++)
{
for(int j = 0; j <= holder.size(); j++)
{
if(num2[i] == holder[j])
contains = true;
}
if(!contains)
holder+= num2[i];
contains = false;
}
if(holder.size() <= 10)
return true;
else
return false;
}
void makePuzzle(puzzle &thePuzzle, int num1, int num2, string numw1, string numw2, string sumw, string letters)
{//builds puzzle struct
if(numw1.size() >= numw2.size())
{
thePuzzle.num1 = num1;
thePuzzle.num2 = num2;
thePuzzle.num_word1 = numw1;
thePuzzle.num_word2 = numw2;
}
else
{
thePuzzle.num1 = num2;
thePuzzle.num2 = num1;
thePuzzle.num_word1 = numw2;
thePuzzle.num_word2 = numw1;
}
thePuzzle.sum = num1 + num2;
thePuzzle.sum_word = sumw;
thePuzzle.letters = letters;
}
bool checkSolution(puzzle &thePuzzle, vector<int> answers, int mode)//takes a set of answers and checks if they're valid
{
int test1 = 0, test2 = 0, test3 = 0;//3 variables used to test the correctness of the string.
bool f = false;//used for initializing the array below.
bool check[10] = {f,f,f,f,f,f,f,f,f,f};//array to check if a digit was used.
string num_w1 = thePuzzle.num_word1;//hold the puzzle words here
string num_w2 = thePuzzle.num_word2;
string sum_w = thePuzzle.sum_word;
string letters = thePuzzle.letters;//the individual letters here indicate all of the letters in the puzzle
for(int i = 0; i < answers.size(); i++)//answers must be unique
{
if(!check[answers[i]])
check[answers[i]] = true;
else if(check[answers[i]])
return false;
}
if(answers[atIndex(num_w1[num_w1.size()-1], letters)] == 0 || answers[atIndex(num_w2[num_w2.size()-1], letters)] == 0)
return false;//leading number cannot be zero
for(int a = 0; a < num_w1.size(); a++)
test1 += pow(10, a) * answers[atIndex(num_w1[a], letters)];
for(int a = 0; a < num_w2.size(); a++)
test2 += pow(10, a) * answers[atIndex(num_w2[a], letters)];
for(int a = 0; a < sum_w.size(); a++)
test3 += pow(10, a) * answers[atIndex(sum_w[a], letters)];
if(test3 != (test1 + test2))//constraint: the answer must be factual
return false;
else
{
if(mode == 2)
{
cout << " ";
for(int i = num_w1.size(); i < sum_w.size(); i++)
cout << " ";
cout << test1 << endl;
cout << "+ ";
for(int i = num_w2.size(); i < sum_w.size(); i++)
cout << " ";
cout << test2;
cout << endl;
cout << "---------\n";
cout << " ";
cout << test3 << endl;
}
return true;
}
}
vector<int> generateSolution(puzzle &thePuzzle, int mode)//goes through permutations until it finds a valid solution.
{
int count = 0;
vector<int> attempt;
for(int i = 0; i < thePuzzle.letters.size(); i++)
attempt.push_back(-1);
bool f = false;
vector<int> digits = {0,1,2,3,4,5,6,7,8,9};
while(!checkSolution(thePuzzle, attempt, mode) && next_permutation(digits.begin(), digits.end()))
{
for(int i = 0; i < attempt.size(); i++)
attempt[i] = digits[i];
}
if(mode == 1)
return attempt;
if(mode == 2)
{
cout << "One solution is\n";
for(int i = 0; i < thePuzzle.letters.size(); i++)
cout << thePuzzle.letters[i];
cout << endl;
for(int i = 0; i < attempt.size(); i++)
cout << attempt[i];
cout << endl;
}
}
int atIndex(char findme, string inme)//little useful function for finding indices.
{
for(int i = 0; i < inme.size(); i++)
{
if(inme[i] == findme)
return i;
}
}
| 24.967033 | 120 | 0.577465 | [
"vector"
] |
91042ef1ac69246b885b7f9c7f1c1db5e9f798b3 | 15,705 | cc | C++ | aria2/src/DownloadCommand.cc | dingdayu/aria2 | 7e5edc5c1de8b880b20c2d22dabce08558d9e2f6 | [
"Apache-2.0"
] | null | null | null | aria2/src/DownloadCommand.cc | dingdayu/aria2 | 7e5edc5c1de8b880b20c2d22dabce08558d9e2f6 | [
"Apache-2.0"
] | null | null | null | aria2/src/DownloadCommand.cc | dingdayu/aria2 | 7e5edc5c1de8b880b20c2d22dabce08558d9e2f6 | [
"Apache-2.0"
] | null | null | null | /* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#include "DownloadCommand.h"
#include <cassert>
#include "Request.h"
#include "RequestGroup.h"
#include "DownloadEngine.h"
#include "PeerStat.h"
#include "DlAbortEx.h"
#include "DlRetryEx.h"
#include "SegmentMan.h"
#include "Segment.h"
#include "Logger.h"
#include "LogFactory.h"
#include "ChecksumCheckIntegrityEntry.h"
#include "PieceStorage.h"
#include "CheckIntegrityCommand.h"
#include "DiskAdaptor.h"
#include "DownloadContext.h"
#include "Option.h"
#include "util.h"
#include "SocketCore.h"
#include "message.h"
#include "prefs.h"
#include "fmt.h"
#include "RequestGroupMan.h"
#include "wallclock.h"
#include "SinkStreamFilter.h"
#include "FileEntry.h"
#include "SocketRecvBuffer.h"
#include "Piece.h"
#include "WrDiskCacheEntry.h"
#include "DownloadFailureException.h"
#include "MessageDigest.h"
#include "message_digest_helper.h"
#ifdef ENABLE_BITTORRENT
#include "bittorrent_helper.h"
#endif // ENABLE_BITTORRENT
namespace aria2 {
DownloadCommand::DownloadCommand(
cuid_t cuid, const std::shared_ptr<Request>& req,
const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup,
DownloadEngine* e, const std::shared_ptr<SocketCore>& s,
const std::shared_ptr<SocketRecvBuffer>& socketRecvBuffer)
: AbstractCommand(cuid, req, fileEntry, requestGroup, e, s,
socketRecvBuffer),
startupIdleTime_(10),
lowestDownloadSpeedLimit_(0),
pieceHashValidationEnabled_(false)
{
{
if (getOption()->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
const std::string& algo = getDownloadContext()->getPieceHashType();
if (MessageDigest::supports(algo)) {
messageDigest_ = MessageDigest::create(algo);
pieceHashValidationEnabled_ = true;
}
}
}
peerStat_ = req->initPeerStat();
peerStat_->downloadStart();
getSegmentMan()->registerPeerStat(peerStat_);
streamFilter_ = make_unique<SinkStreamFilter>(
getPieceStorage()->getWrDiskCache(), pieceHashValidationEnabled_);
streamFilter_->init();
sinkFilterOnly_ = true;
checkSocketRecvBuffer();
}
DownloadCommand::~DownloadCommand()
{
peerStat_->downloadStop();
getSegmentMan()->updateFastestPeerStat(peerStat_);
}
namespace {
void flushWrDiskCacheEntry(WrDiskCache* wrDiskCache,
const std::shared_ptr<Segment>& segment)
{
const std::shared_ptr<Piece>& piece = segment->getPiece();
if (piece->getWrDiskCacheEntry()) {
piece->flushWrCache(wrDiskCache);
if (piece->getWrDiskCacheEntry()->getError() !=
WrDiskCacheEntry::CACHE_ERR_SUCCESS) {
segment->clear(wrDiskCache);
throw DOWNLOAD_FAILURE_EXCEPTION2(
fmt("Write disk cache flush failure index=%lu",
static_cast<unsigned long>(piece->getIndex())),
piece->getWrDiskCacheEntry()->getErrorCode());
}
}
}
} // namespace
bool DownloadCommand::executeInternal()
{
if (getDownloadEngine()
->getRequestGroupMan()
->doesOverallDownloadSpeedExceed() ||
getRequestGroup()->doesDownloadSpeedExceed()) {
addCommandSelf();
disableReadCheckSocket();
disableWriteCheckSocket();
return false;
}
setReadCheckSocket(getSocket());
const std::shared_ptr<DiskAdaptor>& diskAdaptor =
getPieceStorage()->getDiskAdaptor();
std::shared_ptr<Segment> segment = getSegments().front();
bool eof = false;
if (getSocketRecvBuffer()->bufferEmpty()) {
// Only read from socket when buffer is empty. Imagine that When
// segment length is *short* and we are using HTTP pilelining. We
// issued 2 requests in pipeline. When reading first response
// header, we may read its response body and 2nd response header
// and 2nd response body in buffer if they are small enough to fit
// in buffer. And then server may sends EOF. In this case, we
// read data from socket here, we will get EOF and leaves 2nd
// response unprocessed. To prevent this, we don't read from
// socket when buffer is not empty.
eof = getSocketRecvBuffer()->recv() == 0 && !getSocket()->wantRead() &&
!getSocket()->wantWrite();
}
if (!eof) {
size_t bufSize;
if (sinkFilterOnly_) {
if (segment->getLength() > 0) {
if (segment->getPosition() + segment->getLength() <=
getFileEntry()->getLastOffset()) {
bufSize = std::min(static_cast<size_t>(segment->getLength() -
segment->getWrittenLength()),
getSocketRecvBuffer()->getBufferLength());
}
else {
bufSize =
std::min(static_cast<size_t>(getFileEntry()->getLastOffset() -
segment->getPositionToWrite()),
getSocketRecvBuffer()->getBufferLength());
}
}
else {
bufSize = getSocketRecvBuffer()->getBufferLength();
}
streamFilter_->transform(diskAdaptor, segment,
getSocketRecvBuffer()->getBuffer(), bufSize);
}
else {
// It is possible that segment is completed but we have some bytes
// of stream to read. For example, chunked encoding has "0"+CRLF
// after data. After we read data(at this moment segment is
// completed), we need another 3bytes(or more if it has trailers).
streamFilter_->transform(diskAdaptor, segment,
getSocketRecvBuffer()->getBuffer(),
getSocketRecvBuffer()->getBufferLength());
bufSize = streamFilter_->getBytesProcessed();
}
getSocketRecvBuffer()->drain(bufSize);
peerStat_->updateDownload(bufSize);
getDownloadContext()->updateDownload(bufSize);
}
bool segmentPartComplete = false;
// Note that GrowSegment::complete() always returns false.
if (sinkFilterOnly_) {
if (segment->complete() ||
(getFileEntry()->getLength() != 0 &&
segment->getPositionToWrite() == getFileEntry()->getLastOffset())) {
segmentPartComplete = true;
}
else if (segment->getLength() == 0 && eof) {
segmentPartComplete = true;
}
}
else {
int64_t loff = getFileEntry()->gtoloff(segment->getPositionToWrite());
if (getFileEntry()->getLength() > 0 && !sinkFilterOnly_ &&
((loff == getRequestEndOffset() && streamFilter_->finished()) ||
loff < getRequestEndOffset()) &&
(segment->complete() ||
segment->getPositionToWrite() == getFileEntry()->getLastOffset())) {
// In this case, StreamFilter other than *SinkStreamFilter is
// used and Content-Length is known. We check
// streamFilter_->finished() only if the requested end offset
// equals to written position in file local offset; in other
// words, data in the requested range is all received. If
// requested end offset is greater than this segment, then
// streamFilter_ is not finished in this segment.
segmentPartComplete = true;
}
else if (streamFilter_->finished()) {
segmentPartComplete = true;
}
}
if (!segmentPartComplete && eof) {
throw DL_RETRY_EX(EX_GOT_EOF);
}
if (segmentPartComplete) {
if (segment->complete() || segment->getLength() == 0) {
// If segment->getLength() == 0, the server doesn't provide
// content length, but the client detected that download
// completed.
A2_LOG_INFO(fmt(MSG_SEGMENT_DOWNLOAD_COMPLETED, getCuid()));
{
const std::string& expectedPieceHash =
getDownloadContext()->getPieceHash(segment->getIndex());
if (pieceHashValidationEnabled_ && !expectedPieceHash.empty()) {
if (
#ifdef ENABLE_BITTORRENT
// TODO Is this necessary?
(!getPieceStorage()->isEndGame() ||
!getDownloadContext()->hasAttribute(CTX_ATTR_BT)) &&
#endif // ENABLE_BITTORRENT
segment->isHashCalculated()) {
A2_LOG_DEBUG(fmt("Hash is available! index=%lu",
static_cast<unsigned long>(segment->getIndex())));
validatePieceHash(segment, expectedPieceHash, segment->getDigest());
}
else {
try {
std::string actualHash =
segment->getPiece()->getDigestWithWrCache(
segment->getSegmentLength(), diskAdaptor);
validatePieceHash(segment, expectedPieceHash, actualHash);
}
catch (RecoverableException& e) {
segment->clear(getPieceStorage()->getWrDiskCache());
getSegmentMan()->cancelSegment(getCuid());
throw;
}
}
}
else {
completeSegment(getCuid(), segment);
}
}
}
else {
// If segment is not canceled here, in the next pipelining
// request, aria2 requests bad range
// [FileEntry->getLastOffset(), FileEntry->getLastOffset())
getSegmentMan()->cancelSegment(getCuid(), segment);
}
checkLowestDownloadSpeed();
// this unit is going to download another segment.
return prepareForNextSegment();
}
else {
checkLowestDownloadSpeed();
setWriteCheckSocketIf(getSocket(), shouldEnableWriteCheck());
checkSocketRecvBuffer();
addCommandSelf();
return false;
}
}
bool DownloadCommand::shouldEnableWriteCheck()
{
return getSocket()->wantWrite();
}
void DownloadCommand::checkLowestDownloadSpeed() const
{
if (lowestDownloadSpeedLimit_ > 0 &&
peerStat_->getDownloadStartTime().difference(global::wallclock()) >=
startupIdleTime_) {
int nowSpeed = peerStat_->calculateDownloadSpeed();
if (nowSpeed <= lowestDownloadSpeedLimit_) {
throw DL_ABORT_EX2(fmt(EX_TOO_SLOW_DOWNLOAD_SPEED, nowSpeed,
lowestDownloadSpeedLimit_,
getRequest()->getHost().c_str()),
error_code::TOO_SLOW_DOWNLOAD_SPEED);
}
}
}
bool DownloadCommand::prepareForNextSegment()
{
if (getRequestGroup()->downloadFinished()) {
// Remove in-flight request here.
getFileEntry()->poolRequest(getRequest());
// If this is a single file download, and file size becomes known
// just after downloading, set total length to FileEntry object
// here.
if (getDownloadContext()->getFileEntries().size() == 1) {
if (getFileEntry()->getLength() == 0) {
getFileEntry()->setLength(getPieceStorage()->getCompletedLength());
}
}
if (getDownloadContext()->getPieceHashType().empty()) {
auto entry = make_unique<ChecksumCheckIntegrityEntry>(getRequestGroup());
if (entry->isValidationReady()) {
entry->initValidator();
entry->cutTrailingGarbage();
getDownloadEngine()->getCheckIntegrityMan()->pushEntry(
std::move(entry));
}
}
// Following 2lines are needed for DownloadEngine to detect
// completed RequestGroups without 1sec delay.
getDownloadEngine()->setNoWait(true);
getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
return true;
}
else {
// The number of segments should be 1 in order to pass through the next
// segment.
if (getSegments().size() == 1) {
std::shared_ptr<Segment> tempSegment = getSegments().front();
if (!tempSegment->complete()) {
return prepareForRetry(0);
}
if (getRequestEndOffset() ==
getFileEntry()->gtoloff(tempSegment->getPosition() +
tempSegment->getLength())) {
return prepareForRetry(0);
}
std::shared_ptr<Segment> nextSegment =
getSegmentMan()->getSegmentWithIndex(getCuid(),
tempSegment->getIndex() + 1);
if (!nextSegment) {
nextSegment = getSegmentMan()->getCleanSegmentIfOwnerIsIdle(
getCuid(), tempSegment->getIndex() + 1);
}
if (!nextSegment || nextSegment->getWrittenLength() > 0) {
// If nextSegment->getWrittenLength() > 0, current socket must
// be closed because writing incoming data at
// nextSegment->getWrittenLength() corrupts file.
return prepareForRetry(0);
}
else {
checkSocketRecvBuffer();
addCommandSelf();
return false;
}
}
else {
return prepareForRetry(0);
}
}
}
void DownloadCommand::validatePieceHash(const std::shared_ptr<Segment>& segment,
const std::string& expectedHash,
const std::string& actualHash)
{
if (actualHash == expectedHash) {
A2_LOG_INFO(fmt(MSG_GOOD_CHUNK_CHECKSUM, util::toHex(actualHash).c_str()));
completeSegment(getCuid(), segment);
}
else {
A2_LOG_INFO(fmt(EX_INVALID_CHUNK_CHECKSUM,
static_cast<unsigned long>(segment->getIndex()),
segment->getPosition(), util::toHex(expectedHash).c_str(),
util::toHex(actualHash).c_str()));
segment->clear(getPieceStorage()->getWrDiskCache());
getSegmentMan()->cancelSegment(getCuid());
throw DL_RETRY_EX(fmt("Invalid checksum index=%lu",
static_cast<unsigned long>(segment->getIndex())));
}
}
void DownloadCommand::completeSegment(cuid_t cuid,
const std::shared_ptr<Segment>& segment)
{
flushWrDiskCacheEntry(getPieceStorage()->getWrDiskCache(), segment);
getSegmentMan()->completeSegment(cuid, segment);
}
void DownloadCommand::installStreamFilter(
std::unique_ptr<StreamFilter> streamFilter)
{
if (!streamFilter) {
return;
}
streamFilter->installDelegate(std::move(streamFilter_));
streamFilter_ = std::move(streamFilter);
const std::string& name = streamFilter_->getName();
sinkFilterOnly_ = util::endsWith(name, SinkStreamFilter::NAME);
}
// We need to override noCheck() to return true in order to measure
// download speed to check lowest speed.
bool DownloadCommand::noCheck() const { return lowestDownloadSpeedLimit_ > 0; }
} // namespace aria2
| 36.779859 | 80 | 0.649284 | [
"object",
"transform"
] |
9107ec20e4cd6da49b9aeb135bd7c27017e16d05 | 7,612 | cc | C++ | chrome/browser/toolbar_model.cc | zachlatta/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2021-09-24T22:49:10.000Z | 2021-09-24T22:49:10.000Z | chrome/browser/toolbar_model.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/toolbar_model.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/toolbar_model.h"
#include "app/l10n_util.h"
#include "chrome/browser/cert_store.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ssl/ssl_error_info.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
ToolbarModel::ToolbarModel() : input_in_progress_(false) {
}
ToolbarModel::~ToolbarModel() {
}
// ToolbarModel Implementation.
std::wstring ToolbarModel::GetText() {
static const GURL kAboutBlankURL("about:blank");
GURL url(kAboutBlankURL);
std::wstring languages; // Empty if we don't have a |navigation_controller|.
NavigationController* navigation_controller = GetNavigationController();
if (navigation_controller) {
languages = navigation_controller->profile()->GetPrefs()->GetString(
prefs::kAcceptLanguages);
NavigationEntry* entry = navigation_controller->GetActiveEntry();
// We may not have a navigation entry yet
if (!navigation_controller->tab_contents()->ShouldDisplayURL()) {
// Explicitly hide the URL for this tab.
url = GURL();
} else if (entry) {
url = entry->display_url();
}
}
return net::FormatUrl(url, languages, true, UnescapeRule::NORMAL, NULL, NULL);
}
ToolbarModel::SecurityLevel ToolbarModel::GetSecurityLevel() {
if (input_in_progress_) // When editing, assume no security style.
return ToolbarModel::NORMAL;
NavigationController* navigation_controller = GetNavigationController();
if (!navigation_controller) // We might not have a controller on init.
return ToolbarModel::NORMAL;
NavigationEntry* entry = navigation_controller->GetActiveEntry();
if (!entry)
return ToolbarModel::NORMAL;
switch (entry->ssl().security_style()) {
case SECURITY_STYLE_AUTHENTICATED:
if (entry->ssl().has_mixed_content())
return ToolbarModel::NORMAL;
return ToolbarModel::SECURE;
case SECURITY_STYLE_AUTHENTICATION_BROKEN:
return ToolbarModel::INSECURE;
case SECURITY_STYLE_UNKNOWN:
case SECURITY_STYLE_UNAUTHENTICATED:
return ToolbarModel::NORMAL;
default:
NOTREACHED();
return ToolbarModel::NORMAL;
}
}
ToolbarModel::SecurityLevel ToolbarModel::GetSchemeSecurityLevel() {
// For now, in sync with the security level.
return GetSecurityLevel();
}
ToolbarModel::Icon ToolbarModel::GetIcon() {
if (input_in_progress_)
return ToolbarModel::NO_ICON;
NavigationController* navigation_controller = GetNavigationController();
if (!navigation_controller) // We might not have a controller on init.
return ToolbarModel::NO_ICON;
NavigationEntry* entry = navigation_controller->GetActiveEntry();
if (!entry)
return ToolbarModel::NO_ICON;
const NavigationEntry::SSLStatus& ssl = entry->ssl();
switch (ssl.security_style()) {
case SECURITY_STYLE_AUTHENTICATED:
if (ssl.has_mixed_content())
return ToolbarModel::WARNING_ICON;
return ToolbarModel::LOCK_ICON;
case SECURITY_STYLE_AUTHENTICATION_BROKEN:
return ToolbarModel::WARNING_ICON;
case SECURITY_STYLE_UNKNOWN:
case SECURITY_STYLE_UNAUTHENTICATED:
return ToolbarModel::NO_ICON;
default:
NOTREACHED();
return ToolbarModel::NO_ICON;
}
}
void ToolbarModel::GetIconHoverText(std::wstring* text, SkColor* text_color) {
static const SkColor kOKHttpsInfoBubbleTextColor =
SkColorSetRGB(0, 153, 51); // Green.
static const SkColor kBrokenHttpsInfoBubbleTextColor =
SkColorSetRGB(255, 0, 0); // Red.
DCHECK(text && text_color);
NavigationController* navigation_controller = GetNavigationController();
// We don't expect to be called during initialization, so the controller
// should never be NULL.
DCHECK(navigation_controller);
NavigationEntry* entry = navigation_controller->GetActiveEntry();
DCHECK(entry);
const NavigationEntry::SSLStatus& ssl = entry->ssl();
switch (ssl.security_style()) {
case SECURITY_STYLE_AUTHENTICATED: {
if (ssl.has_mixed_content()) {
SSLErrorInfo error_info =
SSLErrorInfo::CreateError(SSLErrorInfo::MIXED_CONTENTS,
NULL, GURL::EmptyGURL());
text->assign(error_info.short_description());
*text_color = kBrokenHttpsInfoBubbleTextColor;
} else {
DCHECK(entry->url().has_host());
text->assign(l10n_util::GetStringF(IDS_SECURE_CONNECTION,
UTF8ToWide(entry->url().host())));
*text_color = kOKHttpsInfoBubbleTextColor;
}
break;
}
case SECURITY_STYLE_AUTHENTICATION_BROKEN: {
CreateErrorText(entry, text);
if (text->empty()) {
// If the authentication is broken, we should always have at least one
// error.
NOTREACHED();
return;
}
*text_color = kBrokenHttpsInfoBubbleTextColor;
break;
}
default:
// Don't show the info bubble in any other cases.
text->clear();
break;
}
}
ToolbarModel::InfoTextType ToolbarModel::GetInfoText(std::wstring* text,
std::wstring* tooltip) {
DCHECK(text && tooltip);
text->clear();
tooltip->clear();
NavigationController* navigation_controller = GetNavigationController();
if (!navigation_controller) // We might not have a controller on init.
return INFO_NO_INFO;
NavigationEntry* entry = navigation_controller->GetActiveEntry();
const NavigationEntry::SSLStatus& ssl = entry->ssl();
if (!entry || ssl.has_mixed_content() ||
net::IsCertStatusError(ssl.cert_status()) ||
((ssl.cert_status() & net::CERT_STATUS_IS_EV) == 0))
return INFO_NO_INFO;
scoped_refptr<net::X509Certificate> cert;
CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert);
if (!cert.get()) {
NOTREACHED();
return INFO_NO_INFO;
}
SSLManager::GetEVCertNames(*cert, text, tooltip);
return INFO_EV_TEXT;
}
void ToolbarModel::CreateErrorText(NavigationEntry* entry, std::wstring* text) {
const NavigationEntry::SSLStatus& ssl = entry->ssl();
std::vector<SSLErrorInfo> errors;
SSLErrorInfo::GetErrorsForCertStatus(ssl.cert_id(),
ssl.cert_status(),
entry->url(),
&errors);
if (ssl.has_mixed_content()) {
errors.push_back(SSLErrorInfo::CreateError(SSLErrorInfo::MIXED_CONTENTS,
NULL, GURL::EmptyGURL()));
}
if (ssl.has_unsafe_content()) {
errors.push_back(SSLErrorInfo::CreateError(SSLErrorInfo::UNSAFE_CONTENTS,
NULL, GURL::EmptyGURL()));
}
int error_count = static_cast<int>(errors.size());
if (error_count == 0) {
text->assign(L"");
} else if (error_count == 1) {
text->assign(errors[0].short_description());
} else {
// Multiple errors.
text->assign(l10n_util::GetString(IDS_SEVERAL_SSL_ERRORS));
text->append(L"\n");
for (int i = 0; i < error_count; ++i) {
text->append(errors[i].short_description());
if (i != error_count - 1)
text->append(L"\n");
}
}
}
| 34.6 | 80 | 0.676957 | [
"vector"
] |
510d29d44fb3036c42b5aabb06b7890997369600 | 3,678 | cpp | C++ | Templates/BasicChebyshev/src/main.cpp | Huaguiyuan/TBTK | fc4382395ed0eaae32c236b914dd4e888e21bfc3 | [
"Apache-2.0"
] | null | null | null | Templates/BasicChebyshev/src/main.cpp | Huaguiyuan/TBTK | fc4382395ed0eaae32c236b914dd4e888e21bfc3 | [
"Apache-2.0"
] | null | null | null | Templates/BasicChebyshev/src/main.cpp | Huaguiyuan/TBTK | fc4382395ed0eaae32c236b914dd4e888e21bfc3 | [
"Apache-2.0"
] | 1 | 2019-12-08T01:21:49.000Z | 2019-12-08T01:21:49.000Z | /* Copyright 2016 Kristofer Björnson
*
* 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.
*/
/** @package TBTKtemp
* @file main.cpp
* @brief Basic Chebyshev example
*
* Basic example of using the Chebyshev method to solve a 2D tight-binding
* model with t = 1 and mu = -1. Lattice with edges and a size of 40x40 sites.
* Using 5000 Chebyshev coefficients and evaluating the Green's function with
* an energy resolution of 10000. Calculates LDOS at SIZE_X = 40 sites along
* the line y = SIZE_Y/2 = 20.
*
* @author Kristofer Björnson
*/
#include "TBTK/FileWriter.h"
#include "TBTK/Model.h"
#include "TBTK/Property/LDOS.h"
#include "TBTK/PropertyExtractor/ChebyshevExpander.h"
#include "TBTK/Solver/ChebyshevExpander.h"
#include <complex>
using namespace std;
using namespace TBTK;
const complex<double> i(0, 1);
int main(int argc, char **argv){
//Lattice size
const int SIZE_X = 40;
const int SIZE_Y = 40;
//Model parameters.
complex<double> mu = -1.0;
complex<double> t = 1.0;
//Create model and set up hopping parameters
Model model;
for(int x = 0; x < SIZE_X; x++){
for(int y = 0; y < SIZE_Y; y++){
for(int s = 0; s < 2; s++){
//Add hopping amplitudes corresponding to chemical potential
model << HoppingAmplitude(
-mu,
{x, y, s},
{x, y, s}
);
//Add hopping parameters corresponding to t
if(x+1 < SIZE_X){
model << HoppingAmplitude(
-t,
{(x+1)%SIZE_X, y, s},
{x, y, s}
) + HC;
}
if(y+1 < SIZE_Y){
model << HoppingAmplitude(
-t,
{x, (y+1)%SIZE_Y, s},
{x, y, s}
) + HC;
}
}
}
}
//Construct model
model.construct();
//Chebyshev expansion parameters.
const int NUM_COEFFICIENTS = 5000;
const int ENERGY_RESOLUTION = 10000;
const double SCALE_FACTOR = 5.;
//Setup Solver::ChebyshevExpander
Solver::ChebyshevExpander solver;
solver.setModel(model);
solver.setScaleFactor(SCALE_FACTOR);
solver.setCalculateCoefficientsOnGPU(false);
solver.setGenerateGreensFunctionsOnGPU(false);
solver.setUseLookupTable(true);
solver.setNumCoefficients(NUM_COEFFICIENTS);
//Set filename and remove any file already in the folder
FileWriter::setFileName("TBTKResults.h5");
FileWriter::clear();
//Create PropertyExtractor. The parameter are in order: The
//ChebyshevSolver, number of expansion coefficients used in the
//Cebyshev expansion, energy resolution with which the Green's function
// is evaluated, whether calculate expansion functions using a GPU or
//not, whether to evaluate the Green's function using a GPU or not,
//whether to use a lookup table for the Green's function or not
//(required if the Green's function is evaluated on a GPU), and the
//lower and upper bound between which the Green's function is evaluated
//(has to be inside the interval [-SCALE_FACTOR, SCALE_FACTOR]).
PropertyExtractor::ChebyshevExpander pe(solver);
pe.setEnergyWindow(-SCALE_FACTOR, SCALE_FACTOR, ENERGY_RESOLUTION);
//Extract local density of states and write to file
Property::LDOS ldos = pe.calculateLDOS(
{IDX_X, SIZE_Y/2, IDX_SUM_ALL},
{SIZE_X, 1, 2}
);
FileWriter::writeLDOS(ldos);
return 0;
}
| 29.66129 | 79 | 0.705275 | [
"model"
] |
510dbf625dfa58c49e12d27e670eaa9ac0e00b25 | 4,581 | cpp | C++ | sources/System/Lobby/ResumeLobbySystem.cpp | EternalRat/Bomberman | d4d0c6dea61f7de1e71c6f182a6bf27407092356 | [
"MIT"
] | 6 | 2021-05-27T13:31:37.000Z | 2021-11-21T17:35:08.000Z | sources/System/Lobby/ResumeLobbySystem.cpp | EternalRat/Bomberman | d4d0c6dea61f7de1e71c6f182a6bf27407092356 | [
"MIT"
] | 174 | 2021-05-12T14:10:04.000Z | 2021-06-26T11:29:39.000Z | sources/System/Lobby/ResumeLobbySystem.cpp | EternalRat/Bomberman | d4d0c6dea61f7de1e71c6f182a6bf27407092356 | [
"MIT"
] | 2 | 2021-05-27T13:28:46.000Z | 2021-06-21T12:25:27.000Z | //
// Created by Zoe Roux on 6/11/21.
//
#include "System/Event/EventSystem.hpp"
#include "Component/Renderer/Drawable2DComponent.hpp"
#include "System/Lobby/ResumeLobbySystem.hpp"
#include "Component/Controllable/ControllableComponent.hpp"
#include "Component/Speed/SpeedComponent.hpp"
#include "System/MenuControllable/MenuControllableSystem.hpp"
#include "Component/Tag/TagComponent.hpp"
#include <Runner/Runner.hpp>
#include <Component/Position/PositionComponent.hpp>
#include <Component/Renderer/Drawable3DComponent.hpp>
#include <Component/BombHolder/BombHolderComponent.hpp>
#include <Parser/ParserYaml.hpp>
#include "Component/Color/ColorComponent.hpp"
#include "System/Lobby/LobbySystem.hpp"
namespace RAY3D = RAY::Drawables::Drawables3D;
namespace RAY2D = RAY::Drawables::Drawables2D;
namespace BBM
{
ResumeLobbySystem::ResumeLobbySystem(WAL::Wal &wal)
: System(wal)
{}
void ResumeLobbySystem::onUpdate(WAL::ViewEntity<ResumeLobbyComponent, Drawable2DComponent> &entity, std::chrono::nanoseconds dtime)
{
auto &lobby = entity.get<ResumeLobbyComponent>();
auto lastTick = std::chrono::steady_clock::now();
if (lastTick - lobby.lastInput < std::chrono::milliseconds(150))
return;
if (lobby.layout == ControllableComponent::NONE) {
for (auto &[_, ctrl] : this->_wal.getScene()->view<ControllableComponent>()) {
auto &controller = ctrl;
if (controller.bomb) {
if (std::any_of(this->getView().begin(), this->getView().end(), [&controller](WAL::ViewEntity<ResumeLobbyComponent, Drawable2DComponent> &view) {
return view.get<ResumeLobbyComponent>().layout == controller.layout;
}))
return;
lobby.ready = true;
lobby.lastInput = lastTick;
lobby.layout = controller.layout;
controller.bomb = false;
this->_wal.getSystem<MenuControllableSystem>().now = lastTick;
auto *texture = dynamic_cast<RAY::Texture *>(lobby.readyButton.getComponent<Drawable2DComponent>().drawable.get());
if (texture)
texture->use("assets/player/icons/ready.png");
return;
}
}
}
}
void ResumeLobbySystem::onSelfUpdate(std::chrono::nanoseconds dtime)
{
auto &view = this->_wal.getScene()->view<TagComponent<ResumeButton>, Drawable2DComponent>();
if (view.size() == 0)
return;
auto *texture = dynamic_cast<RAY::Texture *>(view.front().get<Drawable2DComponent>().drawable.get());
if (!texture)
return;
if (playersAreReady(*this->_wal.getScene()))
texture->setColor(WHITE);
else
texture->setColor(GRAY);
}
bool ResumeLobbySystem::playersAreReady(WAL::Scene &scene)
{
auto &lobby = scene.view<ResumeLobbyComponent>();
return std::all_of(lobby.begin(), lobby.end(), [](WAL::ViewEntity<ResumeLobbyComponent> &entity) {
auto &lobbyPlayer = entity.get<ResumeLobbyComponent>();
return lobbyPlayer.ready && lobbyPlayer.layout != ControllableComponent::NONE;
}); }
void ResumeLobbySystem::resumeToGame(WAL::Wal &wal)
{
auto scene = Runner::gameState.loadedScenes[GameState::SceneID::GameScene];
int countPlayer = 0;
for (auto &[_, lobby] : wal.getScene()->view<ResumeLobbyComponent>()) {
if (lobby.layout == ControllableComponent::NONE)
continue;
auto &player = Runner::createPlayer(*scene);
player.setName(ParserYAML::playersInfos[countPlayer].name);
auto *position = player.tryGetComponent<PositionComponent>();
auto *bombHolder = player.tryGetComponent<BombHolderComponent>();
auto *model = player.tryGetComponent<Drawable3DComponent>();
auto *speed = player.tryGetComponent<SpeedComponent>();
if (position && bombHolder && model && speed) {
dynamic_cast<RAY3D::Model *>(model->drawable.get())->setTextureToMaterial(MAP_DIFFUSE,
ParserYAML::playersInfos[countPlayer].asset);
position->position = ParserYAML::playersInfos[countPlayer].position;
bombHolder->explosionRadius = ParserYAML::playersInfos[countPlayer].explosionRange;
bombHolder->maxBombCount = ParserYAML::playersInfos[countPlayer].maxBombCount;
speed->speed = ParserYAML::playersInfos[countPlayer].speed;
}
LobbySystem::addController(player, lobby.layout);
LobbySystem::createTile(scene, player, lobby.playerColor, countPlayer);
countPlayer++;
}
Runner::gameState.nextScene = BBM::GameState::SceneID::GameScene;
wal.getSystem<ResumeLobbySystem>().unloadLobbyFromResume();
ParserYAML::playersInfos.clear();
}
void ResumeLobbySystem::unloadLobbyFromResume()
{
for (auto &entity : this->getView()) {
entity->scheduleDeletion();
}
}
} | 38.822034 | 150 | 0.719712 | [
"model"
] |
5113524011919ca0954b09f5c02709465130122a | 4,106 | cpp | C++ | src/MapleFE/autogen/src/operator_gen.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | 2 | 2019-09-06T07:02:41.000Z | 2019-09-09T12:24:46.000Z | src/MapleFE/autogen/src/operator_gen.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | src/MapleFE/autogen/src/operator_gen.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (C) [2020] Futurewei Technologies, Inc. All rights reverved.
*
* OpenArkFE is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <cstring>
#include <string>
#include "operator_gen.h"
#include "massert.h"
namespace maplefe {
////////////// Operators supported /////////////////
#undef OPERATOR
#define OPERATOR(S, D) {#S, OPR_##S},
OperatorId OprsSupported[OPR_NA] = {
#include "supported_operators.def"
};
// s : the literal name
// return the OprId
OprId FindOperatorId(const std::string &s) {
for (unsigned u = 0; u < OPR_NA; u++) {
if (!OprsSupported[u].mName.compare(0, s.length(), s) &&
s.length() == OprsSupported[u].mName.size())
return OprsSupported[u].mOprId;
}
return OPR_NA;
}
std::string FindOperatorName(OprId id) {
std::string s("");
for (unsigned u = 0; u < OPR_NA; u++) {
if (OprsSupported[u].mOprId == id){
s = OprsSupported[u].mName;
break;
}
}
return s;
}
/////////////////////////////////////////////////////////////////////
// Generate the Operator table //
// The table in the cpp file:
// OprTableEntry OprTable[OPR_Null] = {
// {"xxx", OPR_Xxx},
// ...
// };
/////////////////////////////////////////////////////////////////////
const void OperatorGen::EnumBegin(){
mEnumIter = mOperators.begin();
return;
}
const bool OperatorGen::EnumEnd(){
return mEnumIter == mOperators.end();
}
// The format is OPR_ appended with the operator name which is from
// the Operator.mText
const std::string OperatorGen::EnumNextElem(){
Operator opr = *mEnumIter;
std::string enum_item = "{";
enum_item = enum_item + "\"" + opr.mText + "\", OPR_" + FindOperatorName(opr.mID);
enum_item = enum_item + "}";
mEnumIter++;
return enum_item;
}
/////////////////////////////////////////////////////////////////////
// Parse the Operator .spec file //
// //
/////////////////////////////////////////////////////////////////////
// Fill Map
void OperatorGen::ProcessStructData() {
std::vector<StructBase *>::iterator it = mStructs.begin();
for (; it != mStructs.end(); it++) {
// Sort
StructBase *sb = *it;
sb->Sort(0);
for (auto eit: sb->mStructElems) {
const std::string s(eit->mDataVec[1]->GetString());
OprId id = FindOperatorId(s);
AddEntry(eit->mDataVec[0]->GetString(), id);
}
}
}
/////////////////////////////////////////////////////////////////////
// Generate the output files //
/////////////////////////////////////////////////////////////////////
void OperatorGen::Generate() {
GenHeaderFile();
GenCppFile();
}
void OperatorGen::GenHeaderFile() {
mHeaderFile.WriteOneLine("#ifndef __OPERATOR_GEN_H__", 26);
mHeaderFile.WriteOneLine("#define __OPERATOR_GEN_H__", 26);
mHeaderFile.WriteOneLine("namespace maplefe {", 19);
mHeaderFile.WriteOneLine("extern OprTableEntry OprTable[];", 32);
mHeaderFile.WriteOneLine("}", 1);
mHeaderFile.WriteOneLine("#endif", 6);
}
void OperatorGen::GenCppFile() {
mCppFile.WriteOneLine("#include \"ruletable.h\"", 22);
mCppFile.WriteOneLine("namespace maplefe {", 19);
TableBuffer tb;
std::string s = "OprTableEntry OprTable[";
std::string num = std::to_string(mOperators.size());
s += num;
s += "] = {";
tb.Generate(this, s);
mCppFile.WriteFormattedBuffer(&tb);
mCppFile.WriteOneLine("};", 2);
// generate the table size
s = "unsigned OprTableSize = ";
s += num;
s += ";";
mCppFile.WriteOneLine(s.c_str(), s.size());
mCppFile.WriteOneLine("}", 1);
}
}
| 28.713287 | 87 | 0.560156 | [
"vector"
] |
51154914fc617eded8b218a6f3851d43baddc233 | 1,034 | hh | C++ | extern/typed-geometry/src/typed-geometry/functions/matrix/compose.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/matrix/compose.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/matrix/compose.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <typed-geometry/detail/operators.hh>
#include <typed-geometry/functions/basic/scalar_math.hh>
#include <typed-geometry/types/mat.hh>
#include <typed-geometry/types/quat.hh>
#include <typed-geometry/types/size.hh>
#include <typed-geometry/types/vec.hh>
namespace tg
{
template <class T>
constexpr mat<4, 4, T> compose_transformation(vec<3, T> const& translation, mat<3, 3, T> const& rotation, float scale)
{
mat<4, 4, T> M;
M[0] = tg::vec4(rotation[0] * scale, T(0));
M[1] = tg::vec4(rotation[1] * scale, T(0));
M[2] = tg::vec4(rotation[2] * scale, T(0));
M[3] = tg::vec4(translation, T(1));
return M;
}
template <class T>
constexpr mat<4, 4, T> compose_transformation(vec<3, T> const& translation, mat<3, 3, T> const& rotation, size<3, T> const& scale)
{
mat<4, 4, T> M;
M[0] = tg::vec4(rotation[0] * scale[0], T(0));
M[1] = tg::vec4(rotation[1] * scale[1], T(0));
M[2] = tg::vec4(rotation[2] * scale[2], T(0));
M[3] = tg::vec4(translation, T(1));
return M;
}
}
| 31.333333 | 130 | 0.630561 | [
"geometry"
] |
513bf3ca78cdbc5a15ca97bcad99bb9237ab06b7 | 3,939 | cpp | C++ | src/Application.cpp | darsto/spooky | f1d43e63137bb9179ec76683df5ee51669d35815 | [
"MIT"
] | 7 | 2016-05-03T15:58:49.000Z | 2018-12-16T15:50:44.000Z | src/Application.cpp | darsto/spookytom | f1d43e63137bb9179ec76683df5ee51669d35815 | [
"MIT"
] | 11 | 2016-08-14T10:56:52.000Z | 2020-09-29T13:32:35.000Z | src/Application.cpp | darsto/spookytom | f1d43e63137bb9179ec76683df5ee51669d35815 | [
"MIT"
] | 3 | 2016-06-28T23:37:21.000Z | 2019-10-01T14:15:32.000Z | /*
* Copyright (c) 2017 Dariusz Stojaczyk. All Rights Reserved.
* The following source code is released under an MIT-style license,
* that can be found in the LICENSE file.
*/
#include <cmath>
#include "Application.h"
#include "util/os.h"
#include "util/log.h"
#include "window/Window.h"
#ifndef SIMULATION
#define RENDER_CALL(X) X
#else
#define RENDER_CALL(X)
#endif
#ifdef USES_SDL
static int convertSDLButtonId(int id) {
return (int) std::round(std::log((double) id) / std::log(2.0)) + 1;
}
static Input::TouchPoint::State convertSDLEventId(uint32_t id) {
switch (id) {
case SDL_MOUSEBUTTONDOWN:
return Input::TouchPoint::State::PRESS;
case SDL_MOUSEBUTTONUP:
return Input::TouchPoint::State::RELEASE;
default:
return Input::TouchPoint::State::REPEAT;
}
}
#endif // USES_SDL
Application::Application(ApplicationContext &context,
WindowManager &windowManager)
: m_windowManager(windowManager),
#ifndef SIMULATION
m_renderer(context, m_windowManager),
#endif
m_window(m_windowManager.getWindow(WindowManager::INITIAL_WINDOW_ID)) {
context.init(this);
#ifndef SIMULATION
if (!m_renderer.initialized()) {
Log::error("Couldn't initialize RenderManager.");
return;
}
#endif
m_running = true;
}
void Application::reinit() {
m_inputManager.reload();
m_window->reload();
RENDER_CALL(
if (m_renderer.switchWindow(*m_window) != 0) {
Log::error("Couldn't reinit window.");
m_running = false;
});
/* if not called right now, first call in
game loop would return a very huge value */
m_timer.delta();
}
void Application::update() {
if (m_newWindow) {
switchWindow();
m_newWindow = nullptr;
}
m_window->tick(m_timer.delta());
RENDER_CALL(m_renderer.render());
handleEvents();
m_inputManager.tick(*m_window);
}
void Application::resize(uint32_t width, uint32_t height) {
RENDER_CALL(m_renderer.resize(width, height));
m_window->reload();
}
void Application::handleClick(int button, Input::TouchPoint::State state,
float x, float y) {
m_inputManager.handleClick(button, state, x, y);
}
void Application::handleEvents() {
#ifdef USES_SDL
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
switch (event.type) {
case SDL_QUIT:
m_running = false;
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED ||
event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
resize((uint32_t) event.window.data1,
(uint32_t) event.window.data2);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
m_inputManager.handleKeypress(&event);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEMOTION: {
int button = convertSDLButtonId(event.button.button);
if (button >= 0 && button < 5) {
int x, y;
SDL_GetMouseState(&x, &y);
handleClick(button, convertSDLEventId(event.type), x, y);
}
break;
}
default:
break;
}
}
#endif // USES_SDL
}
bool Application::running() const {
return m_running;
}
void Application::switchWindow() {
if (m_newWindow == nullptr) {
m_running = false;
} else {
m_window = m_newWindow;
m_newWindow = nullptr;
m_window->reload();
RENDER_CALL(
if (m_renderer.switchWindow(*m_window) != 0) {
m_running = false;
});
}
}
#undef RENDER_CALL | 26.614865 | 77 | 0.582889 | [
"render"
] |
51488e0cb2a484ba8c016a2cf0cb2d6ba30b1a82 | 4,617 | cpp | C++ | mps_voxels/src/mps_voxels/logging/log_cv_mat.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 3 | 2020-10-31T21:42:36.000Z | 2021-12-16T12:56:02.000Z | mps_voxels/src/mps_voxels/logging/log_cv_mat.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 1 | 2020-11-11T03:46:08.000Z | 2020-11-11T03:46:08.000Z | mps_voxels/src/mps_voxels/logging/log_cv_mat.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 1 | 2022-03-02T12:32:21.000Z | 2022-03-02T12:32:21.000Z | /*
* Copyright (c) 2020 Andrew Price
* 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.
* 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 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 "mps_voxels/logging/log_cv_mat.h"
#include <opencv2/imgcodecs.hpp>
namespace mps
{
std::string cvType2Str(int type)
{
std::string r;
switch (type)
{
case CV_8UC1: return sensor_msgs::image_encodings::MONO8;
case CV_8UC3: return sensor_msgs::image_encodings::BGR8;
case CV_16UC1: return sensor_msgs::image_encodings::MONO16;
default: ; // Do nothing
}
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
sensor_msgs::Image
ros_message_conversion<cv::Mat>::toMessage(const cv::Mat& t, const std::nullptr_t)
{
return *cv_bridge::CvImage(std_msgs::Header(), cvType2Str(t.type()), t).toImageMsg();
}
sensor_msgs::Image
ros_message_conversion<cv::Mat>::toMessage(const cv::Mat& t, const std_msgs::Header& h)
{
return *cv_bridge::CvImage(h, cvType2Str(t.type()), t).toImageMsg();
}
cv::Mat
ros_message_conversion<cv::Mat>::fromMessage(const sensor_msgs::Image& t)
{
return cv_bridge::toCvCopy(t, t.encoding)->image;
}
sensor_msgs::CameraInfo
ros_message_conversion<image_geometry::PinholeCameraModel>::toMessage(const image_geometry::PinholeCameraModel& t, const std::nullptr_t)
{
return t.cameraInfo();
}
image_geometry::PinholeCameraModel
ros_message_conversion<image_geometry::PinholeCameraModel>::fromMessage(const sensor_msgs::CameraInfo& t)
{
image_geometry::PinholeCameraModel msg;
msg.fromCameraInfo(t);
return msg;
}
sensor_msgs::CompressedImage toMaskMessage(const cv::Mat& mask, const std_msgs::Header& header)
{
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
compression_params.push_back(cv::IMWRITE_PNG_BILEVEL);
compression_params.push_back(1);
sensor_msgs::CompressedImage imgMsg;
imgMsg.header = header;
imgMsg.format = "png";
cv::imencode(".png", mask, imgMsg.data, compression_params);
return imgMsg;
}
cv::Mat fromCompressedMessage(const sensor_msgs::CompressedImage& msg)
{
// NB: This seems to correctly handle 1-bit pngcv::IMREAD_GRAYSCALE
return cv::imdecode(msg.data, cv::IMREAD_UNCHANGED); //
}
template <>
void DataLog::log<image_geometry::PinholeCameraModel>(const std::string& channel, const image_geometry::PinholeCameraModel& msg)
{
log(channel, msg.cameraInfo());
}
template <>
image_geometry::PinholeCameraModel DataLog::load<image_geometry::PinholeCameraModel>(const std::string& channel)
{
return fromMessage(load<sensor_msgs::CameraInfo>(channel));
}
template <>
cv::Mat DataLog::load<cv::Mat>(const std::string& channel)
{
try
{
return fromCompressedMessage(load<sensor_msgs::CompressedImage>(channel));
}
catch (const rosbag::BagException&)
{
return fromMessage(load<sensor_msgs::Image>(channel));
}
}
}
| 30.78 | 136 | 0.749404 | [
"vector"
] |
514b37d29403fe67b597e09874134ac80ff14cdd | 14,875 | cpp | C++ | src/sphere.cpp | tengtonggan/PBRT-Learning | 6a4e01b768b4d215023c51befe2f6e753d080f30 | [
"Apache-2.0"
] | null | null | null | src/sphere.cpp | tengtonggan/PBRT-Learning | 6a4e01b768b4d215023c51befe2f6e753d080f30 | [
"Apache-2.0"
] | null | null | null | src/sphere.cpp | tengtonggan/PBRT-Learning | 6a4e01b768b4d215023c51befe2f6e753d080f30 | [
"Apache-2.0"
] | null | null | null | #include "sphere.h"
#include "onb.h"
bool sphere::hit(const ray& r, double t_min, double t_max, hit_record& rec) const {
Vector3f oc = r.origin() - center;
auto a = r.direction().LengthSquared();
auto half_b = Dot(oc, r.direction());
auto c = oc.LengthSquared() - radius * radius;
auto discriminant = half_b * half_b - a * c;
if (discriminant < 0) return false;
auto sqrtd = sqrt(discriminant);
// Find the nearest root that lies in the acceptable range.
auto root = (-half_b - sqrtd) / a;
if (root < t_min || t_max < root) {
root = (-half_b + sqrtd) / a;
if (root < t_min || t_max < root)
return false;
}
rec.t = root;
rec.p = r.at(rec.t);
Normal3f outward_normal = Normal3f((rec.p - center) / radius);
rec.set_face_normal(r, outward_normal);
get_sphere_uv(Vector3f(outward_normal), rec.u, rec.v);
rec.mat_ptr = mat_ptr;
return true;
}
bool sphere::bounding_box(double time0, double time1, aabb& output_box) const {
output_box = aabb(
center - Vector3f(radius, radius, radius),
center + Vector3f(radius, radius, radius));
return true;
}
void sphere::get_sphere_uv(const Vector3f& p, double& u, double& v) {
// p: a given point on the sphere of radius one, centered at the origin.
// u: returned value [0,1] of angle around the Y axis from X=-1.
// v: returned value [0,1] of angle from Y=-1 to Y=+1.
// <1 0 0> yields <0.50 0.50> <-1 0 0> yields <0.00 0.50>
// <0 1 0> yields <0.50 1.00> < 0 -1 0> yields <0.50 0.00>
// <0 0 1> yields <0.25 0.50> < 0 0 -1> yields <0.75 0.50>
auto theta = acos(-p.y);
auto phi = atan2(-p.z, p.x) + pi;
u = phi / (2 * pi);
v = theta / pi;
}
double sphere::pdf_value(const Point3f& o, const Vector3f& v) const {
hit_record rec;
if (!this->hit(ray(o, v), 0.001, infinity, rec))
return 0;
auto cos_theta_max = sqrt(1 - radius * radius / (center - o).LengthSquared());
auto solid_angle = 2 * pi * (1 - cos_theta_max);
return 1 / solid_angle;
}
Vector3f sphere::random(const Point3f& o) const {
Vector3f direction = center - o;
auto distance_squared = direction.LengthSquared();
onb uvw;
uvw.build_from_w(direction);
return uvw.local(random_to_sphere(radius, distance_squared));
}
//#include "shapes/sphere.h"
//#include "sampling.h"
//#include "paramset.h"
#include "efloat.h"
//#include "stats.h"
namespace pbrt {
// Sphere Method Definitions
Bounds3f Sphere::ObjectBound() const {
return Bounds3f(Point3f(-radius, -radius, zMin),
Point3f(radius, radius, zMax));
}
bool Sphere::Intersect(const Ray& r, Float* tHit, SurfaceInteraction* isect,
bool testAlphaTexture) const {
//ProfilePhase p(Prof::ShapeIntersect);
Float phi;
Point3f pHit;
// Transform _Ray_ to object space
Vector3f oErr, dErr;
Ray ray = (*WorldToObject)(r, &oErr, &dErr);
// Compute quadratic sphere coefficients
// Initialize _EFloat_ ray coordinate values
EFloat ox(ray.o.x, oErr.x), oy(ray.o.y, oErr.y), oz(ray.o.z, oErr.z);
EFloat dx(ray.d.x, dErr.x), dy(ray.d.y, dErr.y), dz(ray.d.z, dErr.z);
EFloat a = dx * dx + dy * dy + dz * dz;
EFloat b = 2 * (dx * ox + dy * oy + dz * oz);
EFloat c = ox * ox + oy * oy + oz * oz - EFloat(radius) * EFloat(radius);
// Solve quadratic equation for _t_ values
EFloat t0, t1;
if (!Quadratic(a, b, c, &t0, &t1)) return false;
// Check quadric shape _t0_ and _t1_ for nearest intersection
//if (t0.UpperBound() > ray.tMax || t1.LowerBound() <= 0) return false;
if (t0.UpperBound() > ray.tMax || t1.LowerBound() <= ray.tMin) return false;
EFloat tShapeHit = t0;
if (tShapeHit.LowerBound() <= 0) {
tShapeHit = t1;
if (tShapeHit.UpperBound() > ray.tMax) return false;
}
// Compute sphere hit position and $\phi$
pHit = ray((Float)tShapeHit);
// Refine sphere intersection point
pHit *= radius / Distance(pHit, Point3f(0, 0, 0));
if (pHit.x == 0 && pHit.y == 0) pHit.x = 1e-5f * radius;
phi = std::atan2(pHit.y, pHit.x);
if (phi < 0) phi += 2 * Pi;
// Test sphere intersection against clipping parameters
if ((zMin > -radius && pHit.z < zMin) || (zMax < radius && pHit.z > zMax) ||
phi > phiMax) {
if (tShapeHit == t1) return false;
if (t1.UpperBound() > ray.tMax) return false;
tShapeHit = t1;
// Compute sphere hit position and $\phi$
pHit = ray((Float)tShapeHit);
// Refine sphere intersection point
pHit *= radius / Distance(pHit, Point3f(0, 0, 0));
if (pHit.x == 0 && pHit.y == 0) pHit.x = 1e-5f * radius;
phi = std::atan2(pHit.y, pHit.x);
if (phi < 0) phi += 2 * Pi;
if ((zMin > -radius && pHit.z < zMin) ||
(zMax < radius && pHit.z > zMax) || phi > phiMax)
return false;
}
// Find parametric representation of sphere hit
Float u = phi / phiMax;
Float theta = std::acos(Clamp(pHit.z / radius, -1, 1));
Float v = (theta - thetaMin) / (thetaMax - thetaMin);
// Compute sphere $\dpdu$ and $\dpdv$
Float zRadius = std::sqrt(pHit.x * pHit.x + pHit.y * pHit.y);
Float invZRadius = 1 / zRadius;
Float cosPhi = pHit.x * invZRadius;
Float sinPhi = pHit.y * invZRadius;
Vector3f dpdu(-phiMax * pHit.y, phiMax * pHit.x, 0);
Vector3f dpdv =
(thetaMax - thetaMin) *
Vector3f(pHit.z * cosPhi, pHit.z * sinPhi, -radius * std::sin(theta));
// Compute sphere $\dndu$ and $\dndv$
Vector3f d2Pduu = -phiMax * phiMax * Vector3f(pHit.x, pHit.y, 0);
Vector3f d2Pduv =
(thetaMax - thetaMin) * pHit.z * phiMax * Vector3f(-sinPhi, cosPhi, 0.);
Vector3f d2Pdvv = -(thetaMax - thetaMin) * (thetaMax - thetaMin) *
Vector3f(pHit.x, pHit.y, pHit.z);
// Compute coefficients for fundamental forms
Float E = Dot(dpdu, dpdu);
Float F = Dot(dpdu, dpdv);
Float G = Dot(dpdv, dpdv);
Vector3f N = Normalize(Cross(dpdu, dpdv));
Float e = Dot(N, d2Pduu);
Float f = Dot(N, d2Pduv);
Float g = Dot(N, d2Pdvv);
// Compute $\dndu$ and $\dndv$ from fundamental form coefficients
Float invEGF2 = 1 / (E * G - F * F);
Normal3f dndu = Normal3f((f * F - e * G) * invEGF2 * dpdu +
(e * F - f * E) * invEGF2 * dpdv);
Normal3f dndv = Normal3f((g * F - f * G) * invEGF2 * dpdu +
(f * F - g * E) * invEGF2 * dpdv);
// Compute error bounds for sphere intersection
Vector3f pError = gamma(5) * Abs((Vector3f)pHit);
// Initialize _SurfaceInteraction_ from parametric information
*isect = (*ObjectToWorld)(SurfaceInteraction(pHit, pError, Point2f(u, v),
-ray.d, dpdu, dpdv, dndu, dndv,
ray.time, this));
// Update _tHit_ for quadric intersection
*tHit = (Float)tShapeHit;
return true;
}
bool Sphere::IntersectP(const Ray& r, bool testAlphaTexture) const {
//ProfilePhase p(Prof::ShapeIntersectP);
Float phi;
Point3f pHit;
// Transform _Ray_ to object space
Vector3f oErr, dErr;
Ray ray = (*WorldToObject)(r, &oErr, &dErr);
// Compute quadratic sphere coefficients
// Initialize _EFloat_ ray coordinate values
EFloat ox(ray.o.x, oErr.x), oy(ray.o.y, oErr.y), oz(ray.o.z, oErr.z);
EFloat dx(ray.d.x, dErr.x), dy(ray.d.y, dErr.y), dz(ray.d.z, dErr.z);
EFloat a = dx * dx + dy * dy + dz * dz;
EFloat b = 2 * (dx * ox + dy * oy + dz * oz);
EFloat c = ox * ox + oy * oy + oz * oz - EFloat(radius) * EFloat(radius);
// Solve quadratic equation for _t_ values
EFloat t0, t1;
if (!Quadratic(a, b, c, &t0, &t1)) return false;
// Check quadric shape _t0_ and _t1_ for nearest intersection
if (t0.UpperBound() > ray.tMax || t1.LowerBound() <= 0) return false;
EFloat tShapeHit = t0;
if (tShapeHit.LowerBound() <= 0) {
tShapeHit = t1;
if (tShapeHit.UpperBound() > ray.tMax) return false;
}
// Compute sphere hit position and $\phi$
pHit = ray((Float)tShapeHit);
// Refine sphere intersection point
pHit *= radius / Distance(pHit, Point3f(0, 0, 0));
if (pHit.x == 0 && pHit.y == 0) pHit.x = 1e-5f * radius;
phi = std::atan2(pHit.y, pHit.x);
if (phi < 0) phi += 2 * Pi;
// Test sphere intersection against clipping parameters
if ((zMin > -radius && pHit.z < zMin) || (zMax < radius && pHit.z > zMax) ||
phi > phiMax) {
if (tShapeHit == t1) return false;
if (t1.UpperBound() > ray.tMax) return false;
tShapeHit = t1;
// Compute sphere hit position and $\phi$
pHit = ray((Float)tShapeHit);
// Refine sphere intersection point
pHit *= radius / Distance(pHit, Point3f(0, 0, 0));
if (pHit.x == 0 && pHit.y == 0) pHit.x = 1e-5f * radius;
phi = std::atan2(pHit.y, pHit.x);
if (phi < 0) phi += 2 * Pi;
if ((zMin > -radius && pHit.z < zMin) ||
(zMax < radius && pHit.z > zMax) || phi > phiMax)
return false;
}
return true;
}
Float Sphere::Area() const { return phiMax * radius * (zMax - zMin); }
/*
Interaction Sphere::Sample(const Point2f& u, Float* pdf) const {
Point3f pObj = Point3f(0, 0, 0) + radius * UniformSampleSphere(u);
Interaction it;
it.n = Normalize((*ObjectToWorld)(Normal3f(pObj.x, pObj.y, pObj.z)));
if (reverseOrientation) it.n *= -1;
// Reproject _pObj_ to sphere surface and compute _pObjError_
pObj *= radius / Distance(pObj, Point3f(0, 0, 0));
Vector3f pObjError = gamma(5) * Abs((Vector3f)pObj);
it.p = (*ObjectToWorld)(pObj, pObjError, &it.pError);
*pdf = 1 / Area();
return it;
}
Interaction Sphere::Sample(const Interaction& ref, const Point2f& u,
Float* pdf) const {
Point3f pCenter = (*ObjectToWorld)(Point3f(0, 0, 0));
// Sample uniformly on sphere if $\pt{}$ is inside it
Point3f pOrigin =
OffsetRayOrigin(ref.p, ref.pError, ref.n, pCenter - ref.p);
if (DistanceSquared(pOrigin, pCenter) <= radius * radius) {
Interaction intr = Sample(u, pdf);
Vector3f wi = intr.p - ref.p;
if (wi.LengthSquared() == 0)
*pdf = 0;
else {
// Convert from area measure returned by Sample() call above to
// solid angle measure.
wi = Normalize(wi);
*pdf *= DistanceSquared(ref.p, intr.p) / AbsDot(intr.n, -wi);
}
if (std::isinf(*pdf)) *pdf = 0.f;
return intr;
}
// Sample sphere uniformly inside subtended cone
// Compute coordinate system for sphere sampling
Float dc = Distance(ref.p, pCenter);
Float invDc = 1 / dc;
Vector3f wc = (pCenter - ref.p) * invDc;
Vector3f wcX, wcY;
CoordinateSystem(wc, &wcX, &wcY);
// Compute $\theta$ and $\phi$ values for sample in cone
Float sinThetaMax = radius * invDc;
Float sinThetaMax2 = sinThetaMax * sinThetaMax;
Float invSinThetaMax = 1 / sinThetaMax;
Float cosThetaMax = std::sqrt(std::max((Float)0.f, 1 - sinThetaMax2));
Float cosTheta = (cosThetaMax - 1) * u[0] + 1;
Float sinTheta2 = 1 - cosTheta * cosTheta;
if (sinThetaMax2 < 0.00068523f // sin^2(1.5 deg) //) {
// Fall back to a Taylor series expansion for small angles, where
// the standard approach suffers from severe cancellation errors
sinTheta2 = sinThetaMax2 * u[0];
cosTheta = std::sqrt(1 - sinTheta2);
}
// Compute angle $\alpha$ from center of sphere to sampled point on surface
Float cosAlpha = sinTheta2 * invSinThetaMax +
cosTheta * std::sqrt(std::max((Float)0.f, 1.f - sinTheta2 * invSinThetaMax * invSinThetaMax));
Float sinAlpha = std::sqrt(std::max((Float)0.f, 1.f - cosAlpha * cosAlpha));
Float phi = u[1] * 2 * Pi;
// Compute surface normal and sampled point on sphere
Vector3f nWorld =
SphericalDirection(sinAlpha, cosAlpha, phi, -wcX, -wcY, -wc);
Point3f pWorld = pCenter + radius * Point3f(nWorld.x, nWorld.y, nWorld.z);
// Return _Interaction_ for sampled point on sphere
Interaction it;
it.p = pWorld;
it.pError = gamma(5) * Abs((Vector3f)pWorld);
it.n = Normal3f(nWorld);
if (reverseOrientation) it.n *= -1;
// Uniform cone PDF.
*pdf = 1 / (2 * Pi * (1 - cosThetaMax));
return it;
}
Float Sphere::Pdf(const Interaction& ref, const Vector3f& wi) const {
Point3f pCenter = (*ObjectToWorld)(Point3f(0, 0, 0));
// Return uniform PDF if point is inside sphere
Point3f pOrigin =
OffsetRayOrigin(ref.p, ref.pError, ref.n, pCenter - ref.p);
if (DistanceSquared(pOrigin, pCenter) <= radius * radius)
return Shape::Pdf(ref, wi);
// Compute general sphere PDF
Float sinThetaMax2 = radius * radius / DistanceSquared(ref.p, pCenter);
Float cosThetaMax = std::sqrt(std::max((Float)0, 1 - sinThetaMax2));
return UniformConePdf(cosThetaMax);
}
Float Sphere::SolidAngle(const Point3f& p, int nSamples) const {
Point3f pCenter = (*ObjectToWorld)(Point3f(0, 0, 0));
if (DistanceSquared(p, pCenter) <= radius * radius)
return 4 * Pi;
Float sinTheta2 = radius * radius / DistanceSquared(p, pCenter);
Float cosTheta = std::sqrt(std::max((Float)0, 1 - sinTheta2));
return (2 * Pi * (1 - cosTheta));
}
std::shared_ptr<Shape> CreateSphereShape(const Transform* o2w,
const Transform* w2o,
bool reverseOrientation,
const ParamSet& params) {
Float radius = params.FindOneFloat("radius", 1.f);
Float zmin = params.FindOneFloat("zmin", -radius);
Float zmax = params.FindOneFloat("zmax", radius);
Float phimax = params.FindOneFloat("phimax", 360.f);
return std::make_shared<Sphere>(o2w, w2o, reverseOrientation, radius, zmin,
zmax, phimax);
}
*/
} // namespace pbrt
| 38.939791 | 106 | 0.565916 | [
"object",
"shape",
"transform",
"solid"
] |
514c17014b6c078df37c439ecfc14a5b1f6bc38a | 573 | hpp | C++ | include/components/Component.hpp | dknb0709/MandelbrotExploler | 5df64d0ac4d63712c2321e41aafdb07c72156c67 | [
"MIT"
] | null | null | null | include/components/Component.hpp | dknb0709/MandelbrotExploler | 5df64d0ac4d63712c2321e41aafdb07c72156c67 | [
"MIT"
] | null | null | null | include/components/Component.hpp | dknb0709/MandelbrotExploler | 5df64d0ac4d63712c2321e41aafdb07c72156c67 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <initializer_list>
#include <unordered_map>
#include <vector>
#include "../events/Event.hpp"
#include "../shared/AppConstants.hpp"
#include "../events/EventHandler.hpp"
#include "../events/MouseEvent.hpp"
#include "../events/KeyBoardEvent.hpp"
struct Component {
EventHandler m_handler;
void addEventListener(EventType type, EventHandlerType &&handler) {
m_handler.addEventHandler(type, handler);
}
void dispatch(Event *ev) { m_handler.dispatch(ev); }
virtual void render(std::array<uint32_t, W * H> &pixels) = 0;
};
| 26.045455 | 69 | 0.727749 | [
"render",
"vector"
] |
514faa0b7fb22fe85e89fd3437a63b78ef304e2d | 3,269 | cc | C++ | stapl_release/test/containers/heap/cm_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/heap/cm_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/heap/cm_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#include <stapl/views/array_view.hpp>
#include <stapl/containers/array/array.hpp>
#include <stapl/containers/heap/base_container.hpp>
#include <stapl/containers/distribution/container_manager/cm_heap.hpp>
#include <vector>
#include <stapl/domains/indexed.hpp>
#include <stapl/containers/partitions/balanced.hpp>
#include <stapl/containers/mapping/mapper.hpp>
#include "../../test_report.hpp"
using namespace stapl;
typedef heap_base_container<int,std::less<int>,
heap_base_container_traits<int,std::less<int> > > bc_type;
typedef container_manager_heap<bc_type> cm_type;
typedef cm_type::iterator cm_iter;
stapl::exit_code stapl_main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "usage: exe n" << std::endl;
exit(1);
}
size_t n = atol(argv[1]);
srand(time(NULL));
//Create and fill a base container
bc_type* ptr_bc = new bc_type();
for (size_t i = 0 ; i < n ; i++) {
ptr_bc->push(i);
}
//Create random number of partition
int my_f = 0;
int nb_part = 0;
if (n > 10) {
my_f = rand() % ((int) (n/10));
}
if (my_f == 0) {
nb_part = 1;
} else {
nb_part = my_f;
}
//Create domain, partitionner, mapper
indexed_domain <size_t> dom(0,n-1); //Domain from 0 to n-1
//Creating trunc(n/2) partition
balanced_partition< indexed_domain<size_t> > part(dom,nb_part);
//Map the partitions to the previous domain
mapper<size_t> Mapper(indexed_domain<size_t> (0,nb_part - 1));
//Create container managers
cm_type cm1(part,Mapper);
cm_type cm2(cm1);
cm_iter ite1 = cm1.begin();
bool passed = true;
//If cm1 hold data, return false
if (cm1.begin() != cm1.end()) {
passed = false;
}
STAPL_TEST_REPORT(passed,"Testing constructors");
passed = true;
//If size !=0 after clear, return false
cm2.clear();
if (cm2.size() != 0) {
passed = false;
}
STAPL_TEST_REPORT(passed,"testing clear() and size()");
passed = true;
//Push_bc test aborted, pushing several same base containers
//works but crash at the end of program.
//The program try to free the same container several time ...
cm2.push_bc(ptr_bc);
if (cm2.size() != n)
passed = false;
STAPL_TEST_REPORT(passed,"testing push_bc()");
passed = true;
//Create a fake gid and check if it is in cm2
for (ite1 = cm2.begin() ; ite1 != cm2.end() ; ite1++) {
bc_type::gid_type my_gid((*(cm2.begin()))->end(),
NULL, get_location_id() + 1);
if (cm2.contains(my_gid)) {
passed = false;
}
}
//Create a real gid and check if it is in cm2
(*(*(cm2.begin()))).push(n);
bc_type::gid_type my_gid((*(cm2.begin()))->end(),
*(cm2.begin()),get_location_id());
if (!cm2.contains(my_gid)) {
passed = false;
std::cout<<"Element n not contained"<<std::endl;
}
STAPL_TEST_REPORT(passed,"Testing contains(gid)");
return EXIT_SUCCESS;
}
| 26.795082 | 74 | 0.657693 | [
"vector"
] |
514fd39ad71380497e1bed6e5b4bd0e672456150 | 88,387 | cpp | C++ | tests/generated/world/SceneValidInputRangeTests.cpp | tier4/ad-rss-lib | 7634fd6f040e33e176d5be83638a74b29f5a012b | [
"BSD-3-Clause"
] | 1 | 2019-07-20T02:10:53.000Z | 2019-07-20T02:10:53.000Z | tests/generated/world/SceneValidInputRangeTests.cpp | ANTi7kZ/ad-rss-lib | 7634fd6f040e33e176d5be83638a74b29f5a012b | [
"BSD-3-Clause"
] | null | null | null | tests/generated/world/SceneValidInputRangeTests.cpp | ANTi7kZ/ad-rss-lib | 7634fd6f040e33e176d5be83638a74b29f5a012b | [
"BSD-3-Clause"
] | 1 | 2021-02-25T01:02:15.000Z | 2021-02-25T01:02:15.000Z | /*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (c) 2018-2019 Intel Corporation
*
* 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 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.
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/*
* Generated file
*/
#include <gtest/gtest.h>
#include <limits>
#include "ad_rss/world/SceneValidInputRange.hpp"
TEST(SceneValidInputRangeTests, testValidInputRange)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
ASSERT_TRUE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeSituationTypeTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::situation::SituationType invalidInitializedMember(static_cast<::ad_rss::situation::SituationType>(-1));
value.situationType = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeSituationTypeTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::situation::SituationType invalidInitializedMember(static_cast<::ad_rss::situation::SituationType>(-1));
value.situationType = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeEgoVehicleTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::Object invalidInitializedMember;
::ad_rss::world::ObjectType invalidInitializedMemberObjectType(static_cast<::ad_rss::world::ObjectType>(-1));
invalidInitializedMember.objectType = invalidInitializedMemberObjectType;
value.egoVehicle = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeEgoVehicleTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::Object invalidInitializedMember;
::ad_rss::world::ObjectType invalidInitializedMemberObjectType(static_cast<::ad_rss::world::ObjectType>(-1));
invalidInitializedMember.objectType = invalidInitializedMemberObjectType;
value.egoVehicle = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeObjectTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::Object invalidInitializedMember;
::ad_rss::world::ObjectType invalidInitializedMemberObjectType(static_cast<::ad_rss::world::ObjectType>(-1));
invalidInitializedMember.objectType = invalidInitializedMemberObjectType;
value.object = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeObjectTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::Object invalidInitializedMember;
::ad_rss::world::ObjectType invalidInitializedMemberObjectType(static_cast<::ad_rss::world::ObjectType>(-1));
invalidInitializedMember.objectType = invalidInitializedMemberObjectType;
value.object = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeObjectRssDynamicsTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RssDynamics invalidInitializedMember;
::ad_rss::world::LongitudinalRssAccelerationValues invalidInitializedMemberAlphaLon;
::ad_rss::physics::Acceleration invalidInitializedMemberAlphaLonAccelMax(-1e2 * 1.1);
invalidInitializedMemberAlphaLon.accelMax = invalidInitializedMemberAlphaLonAccelMax;
invalidInitializedMember.alphaLon = invalidInitializedMemberAlphaLon;
value.objectRssDynamics = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeObjectRssDynamicsTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RssDynamics invalidInitializedMember;
::ad_rss::world::LongitudinalRssAccelerationValues invalidInitializedMemberAlphaLon;
::ad_rss::physics::Acceleration invalidInitializedMemberAlphaLonAccelMax(1e2 * 1.1);
invalidInitializedMemberAlphaLon.accelMax = invalidInitializedMemberAlphaLonAccelMax;
invalidInitializedMember.alphaLon = invalidInitializedMemberAlphaLon;
value.objectRssDynamics = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeIntersectingRoadTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RoadArea invalidInitializedMember;
::ad_rss::world::RoadSegment invalidInitializedMemberRoadAreaElement;
::ad_rss::world::LaneSegment invalidInitializedMemberRoadAreaElementElement;
::ad_rss::world::LaneSegmentId invalidInitializedMemberRoadAreaElementElementId(
std::numeric_limits<::ad_rss::world::LaneSegmentId>::lowest());
invalidInitializedMemberRoadAreaElementElement.id = invalidInitializedMemberRoadAreaElementElementId;
::ad_rss::world::LaneSegmentType invalidInitializedMemberRoadAreaElementElementType(
::ad_rss::world::LaneSegmentType::Normal);
invalidInitializedMemberRoadAreaElementElement.type = invalidInitializedMemberRoadAreaElementElementType;
::ad_rss::world::LaneDrivingDirection invalidInitializedMemberRoadAreaElementElementDrivingDirection(
::ad_rss::world::LaneDrivingDirection::Bidirectional);
invalidInitializedMemberRoadAreaElementElement.drivingDirection
= invalidInitializedMemberRoadAreaElementElementDrivingDirection;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMinimum(0.);
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLengthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMaximum(0.);
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLengthMaximum;
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLength.minimum;
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLength.maximum;
invalidInitializedMemberRoadAreaElementElement.length = invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementWidth;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMinimum(0.);
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMaximum(0.);
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidthMaximum;
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidth.minimum;
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidth.maximum;
invalidInitializedMemberRoadAreaElementElement.width = invalidInitializedMemberRoadAreaElementElementWidth;
invalidInitializedMemberRoadAreaElement.resize(1, invalidInitializedMemberRoadAreaElementElement);
invalidInitializedMember.resize(51, invalidInitializedMemberRoadAreaElement);
value.intersectingRoad = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeIntersectingRoadTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RoadArea invalidInitializedMember;
::ad_rss::world::RoadSegment invalidInitializedMemberRoadAreaElement;
::ad_rss::world::LaneSegment invalidInitializedMemberRoadAreaElementElement;
::ad_rss::world::LaneSegmentId invalidInitializedMemberRoadAreaElementElementId(
std::numeric_limits<::ad_rss::world::LaneSegmentId>::max());
invalidInitializedMemberRoadAreaElementElement.id = invalidInitializedMemberRoadAreaElementElementId;
::ad_rss::world::LaneSegmentType invalidInitializedMemberRoadAreaElementElementType(
::ad_rss::world::LaneSegmentType::Intersection);
invalidInitializedMemberRoadAreaElementElement.type = invalidInitializedMemberRoadAreaElementElementType;
::ad_rss::world::LaneDrivingDirection invalidInitializedMemberRoadAreaElementElementDrivingDirection(
::ad_rss::world::LaneDrivingDirection::Negative);
invalidInitializedMemberRoadAreaElementElement.drivingDirection
= invalidInitializedMemberRoadAreaElementElementDrivingDirection;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMinimum(1e6);
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLengthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMaximum(1e6);
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLengthMaximum;
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLength.minimum;
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLength.maximum;
invalidInitializedMemberRoadAreaElementElement.length = invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementWidth;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMinimum(1e6);
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMaximum(1e6);
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidthMaximum;
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidth.minimum;
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidth.maximum;
invalidInitializedMemberRoadAreaElementElement.width = invalidInitializedMemberRoadAreaElementElementWidth;
invalidInitializedMemberRoadAreaElement.resize(1 + 1, invalidInitializedMemberRoadAreaElementElement);
invalidInitializedMember.resize(51, invalidInitializedMemberRoadAreaElement);
value.intersectingRoad = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeEgoVehicleRoadTooSmall)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RoadArea invalidInitializedMember;
::ad_rss::world::RoadSegment invalidInitializedMemberRoadAreaElement;
::ad_rss::world::LaneSegment invalidInitializedMemberRoadAreaElementElement;
::ad_rss::world::LaneSegmentId invalidInitializedMemberRoadAreaElementElementId(
std::numeric_limits<::ad_rss::world::LaneSegmentId>::lowest());
invalidInitializedMemberRoadAreaElementElement.id = invalidInitializedMemberRoadAreaElementElementId;
::ad_rss::world::LaneSegmentType invalidInitializedMemberRoadAreaElementElementType(
::ad_rss::world::LaneSegmentType::Normal);
invalidInitializedMemberRoadAreaElementElement.type = invalidInitializedMemberRoadAreaElementElementType;
::ad_rss::world::LaneDrivingDirection invalidInitializedMemberRoadAreaElementElementDrivingDirection(
::ad_rss::world::LaneDrivingDirection::Bidirectional);
invalidInitializedMemberRoadAreaElementElement.drivingDirection
= invalidInitializedMemberRoadAreaElementElementDrivingDirection;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMinimum(0.);
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLengthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMaximum(0.);
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLengthMaximum;
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLength.minimum;
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLength.maximum;
invalidInitializedMemberRoadAreaElementElement.length = invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementWidth;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMinimum(0.);
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMaximum(0.);
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidthMaximum;
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidth.minimum;
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidth.maximum;
invalidInitializedMemberRoadAreaElementElement.width = invalidInitializedMemberRoadAreaElementElementWidth;
invalidInitializedMemberRoadAreaElement.resize(1, invalidInitializedMemberRoadAreaElementElement);
invalidInitializedMember.resize(51, invalidInitializedMemberRoadAreaElement);
value.egoVehicleRoad = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
TEST(SceneValidInputRangeTests, testValidInputRangeEgoVehicleRoadTooBig)
{
::ad_rss::world::Scene value;
::ad_rss::situation::SituationType valueSituationType(::ad_rss::situation::SituationType::NotRelevant);
value.situationType = valueSituationType;
::ad_rss::world::Object valueEgoVehicle;
::ad_rss::world::ObjectId valueEgoVehicleObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueEgoVehicle.objectId = valueEgoVehicleObjectId;
::ad_rss::world::ObjectType valueEgoVehicleObjectType(::ad_rss::world::ObjectType::Invalid);
valueEgoVehicle.objectType = valueEgoVehicleObjectType;
::ad_rss::world::OccupiedRegionVector valueEgoVehicleOccupiedRegions;
valueEgoVehicle.occupiedRegions = valueEgoVehicleOccupiedRegions;
::ad_rss::world::Velocity valueEgoVehicleVelocity;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLon(-100.);
valueEgoVehicleVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueEgoVehicleVelocity.speedLon = valueEgoVehicleVelocitySpeedLon;
::ad_rss::physics::Speed valueEgoVehicleVelocitySpeedLat(-100.);
valueEgoVehicleVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueEgoVehicleVelocity.speedLat = valueEgoVehicleVelocitySpeedLat;
valueEgoVehicle.velocity = valueEgoVehicleVelocity;
value.egoVehicle = valueEgoVehicle;
::ad_rss::world::Object valueObject;
::ad_rss::world::ObjectId valueObjectObjectId(std::numeric_limits<::ad_rss::world::ObjectId>::lowest());
valueObject.objectId = valueObjectObjectId;
::ad_rss::world::ObjectType valueObjectObjectType(::ad_rss::world::ObjectType::Invalid);
valueObject.objectType = valueObjectObjectType;
::ad_rss::world::OccupiedRegionVector valueObjectOccupiedRegions;
valueObject.occupiedRegions = valueObjectOccupiedRegions;
::ad_rss::world::Velocity valueObjectVelocity;
::ad_rss::physics::Speed valueObjectVelocitySpeedLon(-100.);
valueObjectVelocitySpeedLon = ::ad_rss::physics::Speed(0.); // set to valid value within struct
valueObjectVelocity.speedLon = valueObjectVelocitySpeedLon;
::ad_rss::physics::Speed valueObjectVelocitySpeedLat(-100.);
valueObjectVelocitySpeedLat = ::ad_rss::physics::Speed(-10.); // set to valid value within struct
valueObjectVelocity.speedLat = valueObjectVelocitySpeedLat;
valueObject.velocity = valueObjectVelocity;
value.object = valueObject;
::ad_rss::world::RssDynamics valueObjectRssDynamics;
::ad_rss::world::LongitudinalRssAccelerationValues valueObjectRssDynamicsAlphaLon;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonAccelMax(-1e2);
valueObjectRssDynamicsAlphaLonAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.accelMax = valueObjectRssDynamicsAlphaLonAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMax(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLonBrakeMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLonBrakeMin;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLonBrakeMinCorrect(-1e2);
valueObjectRssDynamicsAlphaLonBrakeMinCorrect = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLonBrakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMinCorrect;
valueObjectRssDynamicsAlphaLon.brakeMax = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamicsAlphaLon.brakeMin = valueObjectRssDynamicsAlphaLon.brakeMax;
valueObjectRssDynamicsAlphaLon.brakeMinCorrect = valueObjectRssDynamicsAlphaLon.brakeMin;
valueObjectRssDynamics.alphaLon = valueObjectRssDynamicsAlphaLon;
::ad_rss::world::LateralRssAccelerationValues valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatAccelMax(-1e2);
valueObjectRssDynamicsAlphaLatAccelMax = ::ad_rss::physics::Acceleration(0.); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.accelMax = valueObjectRssDynamicsAlphaLatAccelMax;
::ad_rss::physics::Acceleration valueObjectRssDynamicsAlphaLatBrakeMin(-1e2);
valueObjectRssDynamicsAlphaLatBrakeMin = ::ad_rss::physics::Acceleration(
0. + ::ad_rss::physics::Acceleration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamicsAlphaLat.brakeMin = valueObjectRssDynamicsAlphaLatBrakeMin;
valueObjectRssDynamics.alphaLat = valueObjectRssDynamicsAlphaLat;
::ad_rss::physics::Distance valueObjectRssDynamicsLateralFluctuationMargin(0.);
valueObjectRssDynamics.lateralFluctuationMargin = valueObjectRssDynamicsLateralFluctuationMargin;
::ad_rss::physics::Duration valueObjectRssDynamicsResponseTime(0.);
valueObjectRssDynamicsResponseTime = ::ad_rss::physics::Duration(
0. + ::ad_rss::physics::Duration::cPrecisionValue); // set to valid value within struct
valueObjectRssDynamics.responseTime = valueObjectRssDynamicsResponseTime;
value.objectRssDynamics = valueObjectRssDynamics;
::ad_rss::world::RoadArea valueIntersectingRoad;
value.intersectingRoad = valueIntersectingRoad;
::ad_rss::world::RoadArea valueEgoVehicleRoad;
value.egoVehicleRoad = valueEgoVehicleRoad;
// override member with invalid value
::ad_rss::world::RoadArea invalidInitializedMember;
::ad_rss::world::RoadSegment invalidInitializedMemberRoadAreaElement;
::ad_rss::world::LaneSegment invalidInitializedMemberRoadAreaElementElement;
::ad_rss::world::LaneSegmentId invalidInitializedMemberRoadAreaElementElementId(
std::numeric_limits<::ad_rss::world::LaneSegmentId>::max());
invalidInitializedMemberRoadAreaElementElement.id = invalidInitializedMemberRoadAreaElementElementId;
::ad_rss::world::LaneSegmentType invalidInitializedMemberRoadAreaElementElementType(
::ad_rss::world::LaneSegmentType::Intersection);
invalidInitializedMemberRoadAreaElementElement.type = invalidInitializedMemberRoadAreaElementElementType;
::ad_rss::world::LaneDrivingDirection invalidInitializedMemberRoadAreaElementElementDrivingDirection(
::ad_rss::world::LaneDrivingDirection::Negative);
invalidInitializedMemberRoadAreaElementElement.drivingDirection
= invalidInitializedMemberRoadAreaElementElementDrivingDirection;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMinimum(1e6);
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLengthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementLengthMaximum(1e6);
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLengthMaximum;
invalidInitializedMemberRoadAreaElementElementLength.maximum
= invalidInitializedMemberRoadAreaElementElementLength.minimum;
invalidInitializedMemberRoadAreaElementElementLength.minimum
= invalidInitializedMemberRoadAreaElementElementLength.maximum;
invalidInitializedMemberRoadAreaElementElement.length = invalidInitializedMemberRoadAreaElementElementLength;
::ad_rss::physics::MetricRange invalidInitializedMemberRoadAreaElementElementWidth;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMinimum(1e6);
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidthMinimum;
::ad_rss::physics::Distance invalidInitializedMemberRoadAreaElementElementWidthMaximum(1e6);
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidthMaximum;
invalidInitializedMemberRoadAreaElementElementWidth.maximum
= invalidInitializedMemberRoadAreaElementElementWidth.minimum;
invalidInitializedMemberRoadAreaElementElementWidth.minimum
= invalidInitializedMemberRoadAreaElementElementWidth.maximum;
invalidInitializedMemberRoadAreaElementElement.width = invalidInitializedMemberRoadAreaElementElementWidth;
invalidInitializedMemberRoadAreaElement.resize(1 + 1, invalidInitializedMemberRoadAreaElementElement);
invalidInitializedMember.resize(51, invalidInitializedMemberRoadAreaElement);
value.egoVehicleRoad = invalidInitializedMember;
ASSERT_FALSE(withinValidInputRange(value));
}
| 69.43205 | 115 | 0.82804 | [
"object"
] |
51532056b09a1be7dcf4e4416bb560deaaaac35c | 7,004 | cpp | C++ | engines/interpolantmc.cpp | yoni206/pono | 0b8223bfff70932555aa3eda12e2ee3ca04a0462 | [
"BSD-3-Clause"
] | null | null | null | engines/interpolantmc.cpp | yoni206/pono | 0b8223bfff70932555aa3eda12e2ee3ca04a0462 | [
"BSD-3-Clause"
] | null | null | null | engines/interpolantmc.cpp | yoni206/pono | 0b8223bfff70932555aa3eda12e2ee3ca04a0462 | [
"BSD-3-Clause"
] | null | null | null | /********************* */
/*! \file
** \verbatim
** Top contributors (to current version):
** Makai Mann, Ahmed Irfan
** This file is part of the pono project.
** Copyright (c) 2019 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file LICENSE in the top-level source
** directory for licensing information.\endverbatim
**
** \brief
**
**
**/
#include "engines/interpolantmc.h"
#include "smt-switch/exceptions.h"
#include "smt-switch/utils.h"
#include "smt/available_solvers.h"
#include "utils/logger.h"
#include "utils/term_analysis.h"
using namespace smt;
namespace pono {
InterpolantMC::InterpolantMC(Property & p, SolverEnum se)
: super(p, se),
interpolator_(create_interpolating_solver(se)),
to_interpolator_(interpolator_),
to_solver_(solver_)
{
}
InterpolantMC::InterpolantMC(Property & p,
const SmtSolver & slv,
const SmtSolver & itp)
: super(p, slv),
interpolator_(itp),
to_interpolator_(interpolator_),
to_solver_(solver_)
{
}
InterpolantMC::InterpolantMC(const PonoOptions & opt,
Property & p,
SolverEnum se)
: super(opt, p, se),
interpolator_(create_interpolating_solver(se)),
to_interpolator_(interpolator_),
to_solver_(solver_)
{
}
InterpolantMC::InterpolantMC(const PonoOptions & opt,
Property & p,
const SmtSolver & slv,
const SmtSolver & itp)
: super(opt, p, slv),
interpolator_(itp),
to_interpolator_(itp),
to_solver_(slv)
{
}
InterpolantMC::~InterpolantMC() {}
void InterpolantMC::initialize()
{
if (initialized_) {
return;
}
super::initialize();
reset_assertions(interpolator_);
// symbols are already created in solver
// need to add symbols at time 1 to cache
// (only time 1 because Craig Interpolant has to share symbols between A and
// B)
UnorderedTermMap & cache = to_solver_.get_cache();
Term tmp1;
for (auto s : ts_->statevars()) {
tmp1 = unroller_.at_time(s, 1);
cache[to_interpolator_.transfer_term(tmp1)] = tmp1;
}
for (auto i : ts_->inputvars()) {
tmp1 = unroller_.at_time(i, 1);
cache[to_interpolator_.transfer_term(tmp1)] = tmp1;
}
// need to copy over UF as well
UnorderedTermSet free_symbols;
get_free_symbols(bad_, free_symbols);
get_free_symbols(ts_->init(), free_symbols);
get_free_symbols(ts_->trans(), free_symbols);
for (auto s : free_symbols) {
if (s->get_sort()->get_sort_kind() == FUNCTION) {
cache[to_interpolator_.transfer_term(s)] = s;
}
}
concrete_cex_ = false;
init0_ = unroller_.at_time(ts_->init(), 0);
transA_ = unroller_.at_time(ts_->trans(), 0);
transB_ = solver_->make_term(true);
bad_disjuncts_ = solver_->make_term(false);
}
ProverResult InterpolantMC::check_until(int k)
{
initialize();
try {
for (int i = 0; i <= k; ++i) {
if (step(i)) {
return ProverResult::TRUE;
} else if (concrete_cex_) {
compute_witness();
return ProverResult::FALSE;
}
}
}
catch (InternalSolverException & e) {
logger.log(1, "Failed when computing interpolant.");
}
return ProverResult::UNKNOWN;
}
bool InterpolantMC::step(int i)
{
if (i <= reached_k_) {
return false;
}
logger.log(1, "Checking interpolation at bound: {}", i);
if (i == 0) {
// Can't get an interpolant at bound 0
// only checking for trivial bug
return step_0();
}
Term bad_i = unroller_.at_time(bad_, i);
bad_disjuncts_ = solver_->make_term(Or, bad_disjuncts_, bad_i);
Term int_bad_disjuncts = to_interpolator_.transfer_term(bad_disjuncts_);
Term int_transA = to_interpolator_.transfer_term(transA_);
Term int_transB = to_interpolator_.transfer_term(transB_);
Term R = init0_;
Term Ri;
bool got_interpolant = true;
while (got_interpolant) {
Term int_R = to_interpolator_.transfer_term(R);
Term int_Ri;
Result r = interpolator_->get_interpolant(
interpolator_->make_term(And, int_R, int_transA),
interpolator_->make_term(And, int_transB, int_bad_disjuncts),
int_Ri);
got_interpolant = r.is_unsat();
if (got_interpolant) {
Ri = to_solver_.transfer_term(int_Ri);
// map Ri to time 0
Ri = unroller_.at_time(unroller_.untime(Ri), 0);
if (check_entail(Ri, R)) {
// check if the over-approximation has reached a fix-point
logger.log(1, "Found a proof at bound: {}", i);
invar_ = unroller_.untime(R);
return true;
} else {
logger.log(1, "Extending initial states.");
logger.log(3, "Using interpolant: {}", Ri);
R = solver_->make_term(Or, R, Ri);
}
} else if (R == init0_) {
// found a concrete counter example
// replay it in the solver with model generation
concrete_cex_ = true;
reset_assertions(solver_);
Term solver_trans = solver_->make_term(And, transA_, transB_);
solver_->assert_formula(solver_->make_term(
And, init0_, solver_->make_term(And, solver_trans, bad_i)));
Result r = solver_->check_sat();
if (!r.is_sat()) {
throw PonoException("Internal error: Expecting satisfiable result");
}
// increment reached_k_ so that witness goes up to the bad state
++reached_k_;
return false;
}
else if (r.is_unknown())
{
// TODO: figure out if makes sense to increase bound and try again
throw PonoException("Interpolant generation failed.");
}
}
// Note: important that it's for i > 0
// transB can't have any symbols from time 0 in it
assert(i > 0);
// extend the unrolling
transB_ =
solver_->make_term(And, transB_, unroller_.at_time(ts_->trans(), i));
++reached_k_;
return false;
}
bool InterpolantMC::step_0()
{
reset_assertions(solver_);
solver_->assert_formula(init0_);
solver_->assert_formula(unroller_.at_time(bad_, 0));
Result r = solver_->check_sat();
if (r.is_unsat()) {
++reached_k_;
} else {
concrete_cex_ = true;
}
return false;
}
void InterpolantMC::reset_assertions(SmtSolver & s)
{
// reset assertions is not supported by all solvers
// but MathSAT is the only supported solver that can do interpolation
// so this should be safe
try {
s->reset_assertions();
}
catch (NotImplementedException & e) {
throw PonoException("Got unexpected solver in InterpolantMC.");
}
}
bool InterpolantMC::check_entail(const Term & p, const Term & q)
{
reset_assertions(solver_);
solver_->assert_formula(
solver_->make_term(And, p, solver_->make_term(Not, q)));
Result r = solver_->check_sat();
assert(r.is_unsat() || r.is_sat());
return r.is_unsat();
}
} // namespace pono
| 27.359375 | 80 | 0.63992 | [
"model"
] |
516a348e7ee78be92afc35850cf0c5a2c2f967ec | 44,310 | cpp | C++ | libsplit/src/Driver.cpp | phuchant/libsplitcl | 4688bd9ab8c3b60c7848eab73519e44cb083cbbc | [
"MIT"
] | null | null | null | libsplit/src/Driver.cpp | phuchant/libsplitcl | 4688bd9ab8c3b60c7848eab73519e44cb083cbbc | [
"MIT"
] | null | null | null | libsplit/src/Driver.cpp | phuchant/libsplitcl | 4688bd9ab8c3b60c7848eab73519e44cb083cbbc | [
"MIT"
] | null | null | null | #include <Queue/DeviceQueue.h>
#include <Queue/Event.h>
#include <Scheduler/Scheduler.h>
#include <Scheduler/SchedulerBadBroyden.h>
#include <Scheduler/SchedulerBroyden.h>
#include <Scheduler/SchedulerEnv.h>
#include <Scheduler/SchedulerFixedPoint.h>
#include <Scheduler/SchedulerMKGR.h>
#include <Scheduler/SchedulerMKGR2.h>
#include <Scheduler/SchedulerMKStatic.h>
#include <Scheduler/SchedulerSample.h>
#include <Utils/Debug.h>
#include <Utils/Utils.h>
#include <Driver.h>
#include <EventFactory.h>
#include <Options.h>
#include <Globals.h>
#include <set>
#include <cstring>
namespace libsplit {
static void waitForEvents(cl_uint num_events_in_wait_list,
const cl_event *event_wait_list)
{
cl_int err;
if (event_wait_list) {
err = real_clWaitForEvents(num_events_in_wait_list, event_wait_list);
clCheck(err, __FILE__, __LINE__);
}
}
static void createFakeEvent(cl_event *event, cl_command_queue queue) {
if (event) {
cl_int err;
cl_context context;
err = real_clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT,
sizeof(context), &context, NULL);
clCheck(err, __FILE__, __LINE__);
*event = real_clCreateUserEvent(context, &err);
clCheck(err, __FILE__, __LINE__);
err = real_clSetUserEventStatus(*event, CL_COMPLETE);
clCheck(err, __FILE__, __LINE__);
}
}
static void debugRegions(KernelHandle *k,
std::vector<DeviceBufferRegion> &dataRequired,
std::vector<DeviceBufferRegion> &dataWritten,
std::vector<DeviceBufferRegion> &dataWrittenAtomicSum) {
for (unsigned i=0; i<dataRequired.size(); i++) {
std::cerr << "data required on dev " << dataRequired[i].devId << " :";
std::cerr << "m=" << dataRequired[i].m << " ";
std::cerr << "pos= " << k->getArgPosFromBuffer(dataRequired[i].m) << " ";
if (dataRequired[i].region.isUndefined())
std::cerr << "(undefined) ";
dataRequired[i].region.debug();
std::cerr << "\n";
}
for (unsigned i=0; i<dataWritten.size(); i++) {
std::cerr << "data written on dev " << dataWritten[i].devId << " :";
std::cerr << "m=" << dataWritten[i].m << " ";
std::cerr << "pos= " << k->getArgPosFromBuffer(dataWritten[i].m) << " ";
if (dataWritten[i].region.isUndefined())
std::cerr << "(undefined) ";
dataWritten[i].region.debug();
std::cerr << "\n";
}
for (unsigned i=0; i<dataWrittenAtomicSum.size(); i++) {
std::cerr << "m=" << dataWrittenAtomicSum[i].m << " ";
std::cerr << "pos= " << k->getArgPosFromBuffer(dataWrittenAtomicSum[i].m) << " ";
if (dataWrittenAtomicSum[i].region.isUndefined())
std::cerr << "(undefined) ";
std::cerr << "data written atomic sum on dev " << dataWrittenAtomicSum[i].devId << " :";
dataWrittenAtomicSum[i].region.debug();
std::cerr << "\n";
}
}
Driver::Driver() {
bufferMgr = new BufferManager(optDelayedWrite);
unsigned nbDevices = optDeviceSelection.size() / 2;
if (optSkipKernels > 0) {
scheduler = new SchedulerEnv(bufferMgr, nbDevices);
} else {
switch(optScheduler) {
case Scheduler::BADBROYDEN:
scheduler = new SchedulerBadBroyden(bufferMgr, nbDevices);
break;
case Scheduler::BROYDEN:
scheduler = new SchedulerBroyden(bufferMgr, nbDevices);
break;
case Scheduler::FIXEDPOINT:
scheduler = new SchedulerFixedPoint(bufferMgr, nbDevices);
break;
case Scheduler::MKGR:
scheduler = new SchedulerMKGR(bufferMgr, nbDevices);
break;
case Scheduler::MKGR2:
scheduler = new SchedulerMKGR2(bufferMgr, nbDevices);
break;
case Scheduler::MKSTATIC:
scheduler = new SchedulerMKStatic(bufferMgr, nbDevices);
break;
case Scheduler::SAMPLE:
scheduler = new SchedulerSample(bufferMgr, nbDevices);
break;
default:
scheduler = new SchedulerEnv(bufferMgr, nbDevices);
};
}
}
Driver::~Driver() {
delete scheduler;
delete bufferMgr;
}
void
Driver::enqueueDummyEvents() {
static bool done = false;
if (done)
return;
done = true;
for (unsigned d=0; d<contextHandle->getNbDevices(); d++)
contextHandle->getQueueNo(d)->enqueueDummyEvents();
}
void
Driver::enqueueReadBuffer(cl_command_queue queue,
MemoryHandle *m,
cl_bool blocking,
size_t offset,
size_t size,
void *ptr,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
bufferMgr->read(m, blocking, offset, size, ptr);
createFakeEvent(event, queue);
}
void
Driver::enqueueWriteBuffer(cl_command_queue queue,
MemoryHandle *m,
cl_bool blocking,
size_t offset,
size_t size,
const void *ptr,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
bufferMgr->write(m, blocking, offset, size, ptr);
createFakeEvent(event, queue);
}
void
Driver::enqueueCopyBuffer(cl_command_queue queue,
MemoryHandle *src,
MemoryHandle *dst,
size_t src_offset,
size_t dst_offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
bufferMgr->copy(src, dst, src_offset, dst_offset, size);
createFakeEvent(event, queue);
}
void *
Driver::enqueueMapBuffer(cl_command_queue queue,
MemoryHandle *m,
cl_bool blocking_map,
cl_map_flags map_flags,
size_t offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
createFakeEvent(event, queue);
return bufferMgr->map(m, blocking_map, map_flags, offset, size);
}
void
Driver::enqueueUnmapMemObject(cl_command_queue queue,
MemoryHandle *m,
void *mapped_ptr,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
bufferMgr->unmap(m, mapped_ptr);
createFakeEvent(event, queue);
}
void
Driver:: enqueueFillBuffer(cl_command_queue queue,
MemoryHandle *m,
const void *pattern,
size_t pattern_size,
size_t offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
waitForEvents(num_events_in_wait_list, event_wait_list);
bufferMgr->fill(m, pattern, pattern_size, offset, size);
createFakeEvent(event, queue);
}
static void printDriverTimers(double t1, double t2, double t3, double t4,
double t5, double t6)
{
std::cerr << "driver getPartition " << (t2-t1)*1.0e3 << "\n";
std::cerr << "driver compute transfers " << (t3-t2)*1.0e3 << "\n";
std::cerr << "driver D2H transfers " << (t4-t3)*1.0e3 << "\n";
std::cerr << "driver enqueue H2D + subkernels " << (t5-t4)*1.0e3 << "\n";
std::cerr << "driver finish H2D + subkernels " << (t6-t5)*1.0e3 << "\n";
}
static void debugIndirectionRegion(BufferIndirectionRegion ®) {
std::cerr << "kerId= " << reg.subkernelId
<< " lbAddr= " << reg.lb
<< " hbAddr= " << reg.hb
<< " indirId=" << reg.indirectionId;
switch (reg.type) {
case INT:
std::cerr << " lb=" << reg.lbValue->getLongValue()
<< " hb=" << reg.hbValue->getLongValue() << "\n";
break;
case FLOAT:
std::cerr << " lb=" << reg.lbValue->getFloatValue()
<< " hb=" << reg.hbValue->getFloatValue() << "\n";
break;
case DOUBLE:
std::cerr << " lb=" << reg.lbValue->getDoubleValue()
<< " hb=" << reg.hbValue->getDoubleValue() << "\n";
break;
default:
std::cerr << "lb=UNKNOWN hb=UNKNOWN\n";
};
}
void
Driver::enqueueNDRangeKernel(cl_command_queue queue,
KernelHandle *k,
cl_uint work_dim,
const size_t *global_work_offset,
const size_t *global_work_size,
const size_t *local_work_size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
enqueueDummyEvents();
// Option skipKernels
{
static unsigned kernelNo = 0;
if (optSkipKernels > 0 && optSkipKernels == kernelNo) {
delete scheduler;
unsigned nbDevices = optDeviceSelection.size() / 2;
switch(optScheduler) {
case Scheduler::BADBROYDEN:
scheduler = new SchedulerBadBroyden(bufferMgr, nbDevices);
break;
case Scheduler::BROYDEN:
scheduler = new SchedulerBroyden(bufferMgr, nbDevices);
break;
case Scheduler::FIXEDPOINT:
scheduler = new SchedulerFixedPoint(bufferMgr, nbDevices);
break;
case Scheduler::MKGR:
scheduler = new SchedulerMKGR(bufferMgr, nbDevices);
break;
case Scheduler::MKGR2:
scheduler = new SchedulerMKGR2(bufferMgr, nbDevices);
break;
case Scheduler::MKSTATIC:
scheduler = new SchedulerMKStatic(bufferMgr, nbDevices);
break;
case Scheduler::SAMPLE:
scheduler = new SchedulerSample(bufferMgr, nbDevices);
break;
default:
scheduler = new SchedulerEnv(bufferMgr, nbDevices);
};
}
kernelNo++;
}
double t1 = get_time();
if (local_work_size == NULL) {
std::cerr << "Error, local_work_size NULL not handled !\n";
exit(EXIT_FAILURE);
}
std::cerr << "kernel " << k->getName() << "\n";
DEBUG("ndrange",
for (unsigned i=0; i<work_dim; i++)
std::cerr << "#wg" << i << ": " << global_work_size[i] / local_work_size[i] << " ";
std::cerr << "\n";);
waitForEvents(num_events_in_wait_list, event_wait_list);
std::vector<SubKernelExecInfo *> subkernels;
std::vector<DeviceBufferRegion> dataRequired;
std::vector<DeviceBufferRegion> dataWritten;
std::vector<DeviceBufferRegion> dataWrittenMerge;
std::vector<DeviceBufferRegion> dataWrittenOr;
std::vector<DeviceBufferRegion> dataWrittenAtomicSum;
std::vector<DeviceBufferRegion> dataWrittenAtomicMin;
std::vector<DeviceBufferRegion> dataWrittenAtomicMax;
std::vector<DeviceBufferRegion> D2HTransfers;
std::vector<DeviceBufferRegion> H2DTransfers;
std::vector<DeviceBufferRegion> OrD2HTransfers;
std::vector<DeviceBufferRegion> AtomicSumD2HTransfers;
std::vector<DeviceBufferRegion> AtomicMinD2HTransfers;
std::vector<DeviceBufferRegion> AtomicMaxD2HTransfers;
std::vector<DeviceBufferRegion> MergeD2HTransfers;
bool needOtherExecutionToComplete = false;
unsigned kerId = 0;
// Read required data for indirections while scheduler is not done.
bool done = false;
do {
std::vector<BufferIndirectionRegion> indirectionRegions;
std::vector<DeviceBufferRegion> D2HTransfers;
scheduler->getIndirectionRegions(k,
work_dim,
global_work_offset,
global_work_size,
local_work_size,
indirectionRegions);
bufferMgr->computeIndirectionTransfers(indirectionRegions, D2HTransfers);
if (indirectionRegions.size() > 0) {
std::set<unsigned> devToWait;
startD2HTransfers(D2HTransfers, devToWait);
// Barrier
ContextHandle *context = k->getContext();
for (unsigned i : devToWait) {
context->getQueueNo(i)->finish();
}
// Fill indirection values.
for (unsigned i=0; i<indirectionRegions.size(); i++) {
size_t cb = indirectionRegions[i].cb;
size_t lb = indirectionRegions[i].lb;
size_t hb = indirectionRegions[i].hb;
MemoryHandle *m = indirectionRegions[i].m;
void *lbAddress = ((char *)m->mLocalBuffer) + lb;
void *hbAddress = ((char *)m->mLocalBuffer) + hb;
switch (indirectionRegions[i].type) {
case INT:
switch(cb) {
case 8:
indirectionRegions[i].lbValue =
IndexExprValue::createLong(*((long *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createLong(*((long *) hbAddress));
break;
case 4:
indirectionRegions[i].lbValue =
IndexExprValue::createLong((long) *((int *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createLong((long) *((int *) hbAddress));
break;
case 2:
indirectionRegions[i].lbValue =
IndexExprValue::createLong((long) *((short *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createLong((long) *((short *) hbAddress));
break;
case 1:
indirectionRegions[i].lbValue =
IndexExprValue::createLong((long) *((char *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createLong((long) *((char *) hbAddress));
break;
default:
std::cerr << "Error: Unhandled integer size : " << cb << "\n";
exit(EXIT_FAILURE);
};
break;
case FLOAT:
assert(cb == 4);
indirectionRegions[i].lbValue =
IndexExprValue::createFloat(*((float *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createFloat(*((float *) hbAddress));
break;
case DOUBLE:
assert(cb == 8);
indirectionRegions[i].lbValue =
IndexExprValue::createDouble(*((double *) lbAddress));
indirectionRegions[i].hbValue =
IndexExprValue::createDouble(*((double *) hbAddress));
break;
case UNDEF:
std::cerr << "Error: unknown indirection type.\n";
exit(EXIT_FAILURE);
};
DEBUG("indirection",
debugIndirectionRegion(indirectionRegions[i]);
);
}
}
done = scheduler->setIndirectionValues(k, indirectionRegions);
if (indirectionRegions.size() > 0) {
for (unsigned i=0; i<indirectionRegions.size(); i++) {
delete indirectionRegions[i].lbValue;
delete indirectionRegions[i].hbValue;
}
}
} while(!done);
// Get partition from scheduler along with data required and data written.
scheduler->getPartition(k,
&needOtherExecutionToComplete,
subkernels,
dataRequired, dataWritten, dataWrittenMerge,
dataWrittenOr,
dataWrittenAtomicSum, dataWrittenAtomicMin,
dataWrittenAtomicMax,
&kerId);
double t2 = get_time();
DEBUG("regions", debugRegions(k, dataRequired, dataWritten, dataWrittenAtomicSum));
DEBUG("granu",
std::cerr << k->getName() << ": ";
for (SubKernelExecInfo *ki : subkernels)
std::cerr << "<" << ki->device << ","
<< (float) ki->global_work_size[ki->splitdim] /
global_work_size[ki->splitdim] *100 << " %> ";
std::cerr << "\n";);
bufferMgr->computeTransfers(dataRequired,
dataWritten,
dataWrittenMerge,
dataWrittenOr,
dataWrittenAtomicSum, dataWrittenAtomicMin,
dataWrittenAtomicMax,
D2HTransfers, H2DTransfers,
OrD2HTransfers,
AtomicSumD2HTransfers, AtomicMinD2HTransfers,
AtomicMaxD2HTransfers, MergeD2HTransfers);
DEBUG("transfers",
std::cerr << "OrD2HTransfers.size()="<< OrD2HTransfers.size() << "\n";
std::cerr << "AtomicSumD2HTransfers.size()="<< AtomicSumD2HTransfers.size() << "\n";
std::cerr << "AtomicMinD2HTransfers.size()="<< AtomicMinD2HTransfers.size() << "\n";
std::cerr << "AtomicMaxD2HTransfers.size()="<< AtomicMaxD2HTransfers.size() << "\n";);
double t3 = get_time();
ContextHandle *context = k->getContext();
if (D2HTransfers.size() > 0) {
std::set<unsigned> devToWait;
startD2HTransfers(kerId, D2HTransfers, devToWait);
// Barrier
for (unsigned i : devToWait) {
context->getQueueNo(i)->finish();
}
}
if (H2DTransfers.size() > 0) {
std::set<unsigned> devToWait;
startH2DTransfers(kerId, H2DTransfers, devToWait);
}
double t4 = get_time();
// No nead for a barrier given the fact that we use in order queues.
// Barrier
enqueueSubKernels(k, kerId, subkernels, dataWritten);
if (OrD2HTransfers.size() > 0)
startOrD2HTransfers(kerId, OrD2HTransfers);
if (AtomicSumD2HTransfers.size() > 0)
startAtomicSumD2HTransfers(kerId, AtomicSumD2HTransfers);
if (AtomicMinD2HTransfers.size() > 0)
startAtomicMinD2HTransfers(kerId, AtomicMinD2HTransfers);
if (AtomicMaxD2HTransfers.size() > 0)
startAtomicMaxD2HTransfers(kerId, AtomicMaxD2HTransfers);
if (MergeD2HTransfers.size() > 0)
startMergeD2HTransfers(kerId, MergeD2HTransfers);
double t5 = get_time();
// Barrier with MKSTATIC scheduler for each cycle iteration.
if ((optScheduler == Scheduler::MKSTATIC ||
optScheduler == Scheduler::MKGR ||
optScheduler == Scheduler::MKGR2)
&& kerId == optCycleLength-1) {
for (unsigned i=0; i<context->getNbDevices(); i++)
context->getQueueNo(i)->finish();
}
double t6 = get_time();
if (OrD2HTransfers.size() > 0)
performHostOrVariableReduction(OrD2HTransfers);
if (AtomicSumD2HTransfers.size() > 0)
performHostAtomicSumReduction(k, AtomicSumD2HTransfers);
if (AtomicMinD2HTransfers.size() > 0)
performHostAtomicMinReduction(k, AtomicMinD2HTransfers);
if (AtomicMaxD2HTransfers.size() > 0)
performHostAtomicMaxReduction(k, AtomicMaxD2HTransfers);
if (MergeD2HTransfers.size() > 0)
performHostMerge(k, MergeD2HTransfers);
// Case where we need another execution to complete the whole original
// NDRange.
if (needOtherExecutionToComplete) {
assert(false);
return enqueueNDRangeKernel(queue, k, work_dim,
global_work_offset,
global_work_size,
local_work_size,
0, NULL, event);
}
createFakeEvent(event, queue);
DEBUG("drivertimers", printDriverTimers(t1, t2, t3, t4, t5, t6));
// Save R/W regions for each buffers.
{
std::set<MemoryHandle *>buffersWritten;
for (unsigned i=0; i<dataWritten.size(); i++)
buffersWritten.insert(dataWritten[i].m);
for (MemoryHandle *m : buffersWritten) {
for (unsigned d=0; d<m->mNbBuffers; d++) {
m->ker2Dev2WrittenRegion[kerId][d].clear();
}
}
for (unsigned i=0; i<dataWritten.size(); i++) {
dataWritten[i].m->
ker2Dev2WrittenRegion[kerId][dataWritten[i].devId].
myUnion(dataWritten[i].region);
}
std::set<MemoryHandle *>buffersRead;
for (unsigned i=0; i<dataRequired.size(); i++) {
buffersRead.insert(dataRequired[i].m);
scheduler->setBufferRequired(kerId, dataRequired[i].m);
}
for (MemoryHandle *m : buffersRead) {
for (unsigned d=0; d<m->mNbBuffers; d++) {
m->ker2Dev2ReadRegion[kerId][d].clear();
}
}
for (unsigned i=0; i<dataRequired.size(); i++) {
dataRequired[i].m->
ker2Dev2ReadRegion[kerId][dataRequired[i].devId].
myUnion(dataRequired[i].region);
}
}
}
void
Driver::startD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList,
std::set<unsigned> &devToWait) {
DEBUG("transfers",
std::cerr << "start D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
devToWait.insert(d);
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) m->mLocalBuffer + offset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
scheduler->setD2HEvent(m->lastWriter, kerId, d, cb, event);
}
// 2) update valid data
m->hostValidData.myUnion(transferList[i].region);
}
DEBUG("transfers", std::cerr << "end D2H\n");
}
void
Driver::startD2HTransfers(const std::vector<DeviceBufferRegion>
&transferList, std::set<unsigned> & devToWait) {
DEBUG("transfers",
std::cerr << "start D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
devToWait.insert(d);
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) m->mLocalBuffer + offset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
}
// 2) update valid data
m->hostValidData.myUnion(transferList[i].region);
}
DEBUG("transfers", std::cerr << "end D2H\n");
}
void
Driver::startH2DTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList, std::set<unsigned> &devToWait) {
DEBUG("transfers", std::cerr << "start H2D\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
devToWait.insert(d);
// 1) enqueue transfers
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "writing [" << offset << "," << offset+cb-1
<< "] to dev " << d << " on buffer " << m->id << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueWrite(m->mBuffers[d],
offset, cb,
(char *) m->mLocalBuffer + offset,
event);
scheduler->setH2DEvent(m->lastWriter, kerId, d, cb, event);
timeline->pushH2DEvent(event, queue->dev_id);
}
// 2) update valid data
m->devicesValidData[d].myUnion(transferList[i].region);
}
DEBUG("transfers", std::cerr << "end H2D\n");
}
void
Driver::startOrD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList) {
DEBUG("transfers", std::cerr << "start OR D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
size_t tmpOffset = 0;
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "OrD2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) transferList[i].tmp + tmpOffset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
tmpOffset += cb;
}
}
DEBUG("transfers", std::cerr << "end OR D2H\n");
}
void
Driver::startAtomicSumD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList) {
DEBUG("transfers", std::cerr << "start ATOMIC SUM D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
size_t tmpOffset = 0;
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "AtomicSum D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) transferList[i].tmp + tmpOffset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
tmpOffset += cb;
}
}
DEBUG("transfers", std::cerr << "end AtomicSum D2H\n");
}
void
Driver::startAtomicMinD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList) {
DEBUG("transfers", std::cerr << "start ATOMIC MIN D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
size_t tmpOffset = 0;
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "AtomicMin D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) transferList[i].tmp + tmpOffset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
tmpOffset += cb;
}
}
DEBUG("transfers", std::cerr << "end AtomicMin D2H\n");
}
void
Driver::startAtomicMaxD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList) {
DEBUG("transfers", std::cerr << "start ATOMIC MAX D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
size_t tmpOffset = 0;
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "AtomicMax D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) transferList[i].tmp + tmpOffset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
tmpOffset += cb;
}
}
DEBUG("transfers", std::cerr << "end AtomicMax D2H\n");
}
void
Driver::startMergeD2HTransfers(unsigned kerId,
const std::vector<DeviceBufferRegion>
&transferList) {
std::cerr << "Error: merge disabled !\n";
assert(false);
DEBUG("transfers", std::cerr << "start MERGE D2H\n");
// For each device
for (unsigned i=0; i<transferList.size(); ++i) {
MemoryHandle *m = transferList[i].m;
unsigned d = transferList[i].devId;
DeviceQueue *queue = m->mContext->getQueueNo(d);
// 1) enqueue transfers
size_t tmpOffset = 0;
for (unsigned j=0; j<transferList[i].region.mList.size(); j++) {
size_t offset = transferList[i].region.mList[j].lb;
size_t cb = transferList[i].region.mList[j].hb -
transferList[i].region.mList[j].lb + 1;
DEBUG("transfers",
std::cerr << "Merge D2H: reading [" << offset << "," << offset+cb-1
<< "] from dev " << d << "\n");
Event *event = eventFactory->getNewEvent();
queue->enqueueRead(m->mBuffers[d],
offset, cb,
(char *) transferList[i].tmp + tmpOffset,
event);
timeline->pushD2HEvent(event, queue->dev_id);
tmpOffset += cb;
}
}
DEBUG("transfers", std::cerr << "end Merge D2H\n");
}
void
Driver::enqueueSubKernels(KernelHandle *k,
unsigned kerId,
std::vector<SubKernelExecInfo *> &subkernels,
const std::vector<DeviceBufferRegion> &dataWritten)
{
// 1) enqueue subkernels with events
for (unsigned i=0; i<subkernels.size(); ++i) {
unsigned d = subkernels[i]->device;
DeviceQueue *queue = k->getContext()->getQueueNo(d);
k->setNumgroupsArg(d, subkernels[i]->numgroups);
k->setSplitdimArg(d, subkernels[i]->splitdim);
subkernels[i]->event = eventFactory->getNewEvent();
queue->enqueueExec(k->getDeviceKernel(d),
subkernels[i]->work_dim,
subkernels[i]->global_work_offset,
subkernels[i]->global_work_size,
subkernels[i]->local_work_size,
k->getKernelArgsForDevice(d),
subkernels[i]->event);
std::string kernelName(k->getName());
timeline->pushEvent(subkernels[i]->event, kernelName,
queue->dev_id);
}
// 2) update valid data
for (unsigned i=0; i<dataWritten.size(); i++) {
MemoryHandle *m = dataWritten[i].m;
m->lastWriter = kerId;
unsigned dev = dataWritten[i].devId;
unsigned nbDevices = m->mNbBuffers;
m->hostValidData.difference(dataWritten[i].region);
for (unsigned j=0; j<nbDevices; j++) {
if (j == dev)
continue;
m->devicesValidData[j].difference(dataWritten[i].region);
}
}
for (unsigned i=0; i<dataWritten.size(); i++) {
MemoryHandle *m = dataWritten[i].m;
unsigned dev = dataWritten[i].devId;
m->devicesValidData[dev].myUnion(dataWritten[i].region);
}
}
void
Driver::performHostOrVariableReduction(const std::vector<DeviceBufferRegion> &
transferList) {
if (transferList.empty())
return;
std::set<MemoryHandle *> memHandles;
std::map<MemoryHandle *, std::vector<DeviceBufferRegion> > mem2RegMap;
for (unsigned i=0; i<transferList.size(); ++i) {
memHandles.insert(transferList[i].m);
mem2RegMap[transferList[i].m].push_back(transferList[i]);
}
for (MemoryHandle *m : memHandles) {
std::vector<DeviceBufferRegion> regVec = mem2RegMap[m];
assert(regVec.size() > 0);
// Perform OR reduction
for (unsigned o=0; o<regVec[0].region.total(); o++) {
for (unsigned i=1; i<regVec.size(); ++i)
((char *) regVec[0].tmp)[o] |= ((char *) regVec[i].tmp)[o];
}
// Update value in local buffer
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
memcpy((char *) m->mLocalBuffer + myoffset,
(char *) regVec[0].tmp + tmpOffset,
mycb);
tmpOffset += mycb;
}
// Update valid data
for (unsigned d=0; d<m->mNbBuffers; d++)
m->devicesValidData[d].difference(regVec[0].region);
m->hostValidData.myUnion(regVec[0].region);
// Free tmp buffers
for (unsigned i=0; i<regVec.size(); ++i)
free(regVec[i].tmp);
}
}
template<typename T>
void doReduction(MemoryHandle *m, std::vector<DeviceBufferRegion> ®Vec) {
unsigned nbDevices = regVec.size();
size_t total_size = regVec[0].region.total();
size_t elemSize = sizeof(T);
size_t numElem = total_size / elemSize;
assert(total_size % elemSize == 0);
// Sum of elements from all devices in regVec[0]
#pragma omp parallel for
for (size_t i = 0; i < numElem; ++i) {
for (unsigned d=1; d<nbDevices; d++) {
T elem = ((T *) regVec[d].tmp)[i];
((T *) regVec[0].tmp)[i] += elem;
}
}
// Final res: localBuffer[e] += regVec[e] - nbDevices * localBuffer[e]
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
size_t numElem = mycb / elemSize;
assert(mycb % elemSize == 0);
#pragma omp parallel for
for (size_t i=0; i < numElem; ++i) {
T *ptr = &((T *) ((char *) m->mLocalBuffer + myoffset))[i];
*ptr += ((T *) ((char *) regVec[0].tmp + tmpOffset))[i] -
nbDevices * (*ptr);
}
tmpOffset += mycb;
}
}
void
Driver::performHostAtomicSumReduction(KernelHandle *k,
const std::vector<DeviceBufferRegion> &
transferList) {
if (transferList.empty())
return;
std::set<MemoryHandle *> memHandles;
std::map<MemoryHandle *, std::vector<DeviceBufferRegion> > mem2RegMap;
for (unsigned i=0; i<transferList.size(); ++i) {
memHandles.insert(transferList[i].m);
mem2RegMap[transferList[i].m].push_back(transferList[i]);
}
for (MemoryHandle *m : memHandles) {
std::vector<DeviceBufferRegion> regVec = mem2RegMap[m];
assert(regVec.size() > 0);
// Get argument type
ArgumentAnalysis::TYPE type = k->getBufferType(m);
// Perform atomic sum reduction
switch(type) {
case ArgumentAnalysis::BOOL:
case ArgumentAnalysis::UNKNOWN:
assert(false);
case ArgumentAnalysis::CHAR:
break;
case ArgumentAnalysis::UCHAR:
break;
case ArgumentAnalysis::SHORT:
doReduction<short>(m, regVec);
break;
case ArgumentAnalysis::USHORT:
doReduction<unsigned short>(m, regVec);
break;
case ArgumentAnalysis::INT:
doReduction<int>(m, regVec);
break;
case ArgumentAnalysis::UINT:
doReduction<unsigned int>(m, regVec);
break;
case ArgumentAnalysis::LONG:
doReduction<long>(m, regVec);
break;
case ArgumentAnalysis::ULONG:
doReduction<unsigned long>(m, regVec);
break;
case ArgumentAnalysis::FLOAT:
doReduction<float>(m, regVec);
break;
case ArgumentAnalysis::DOUBLE:
doReduction<double>(m, regVec);
break;
};
// Update valid data
for (unsigned d=0; d<m->mNbBuffers; d++)
m->devicesValidData[d].difference(regVec[0].region);
m->hostValidData.myUnion(regVec[0].region);
// Free tmp buffers
for (unsigned i=0; i<regVec.size(); ++i)
free(regVec[i].tmp);
}
}
template<typename T>
void doMaxReduction(MemoryHandle *m, std::vector<DeviceBufferRegion> ®Vec) {
size_t total_size = regVec[0].region.total();
size_t elemSize = sizeof(T);
assert(total_size % elemSize == 0);
for (size_t o = 0; elemSize * o < total_size; o++) {
for (unsigned i=1; i<regVec.size(); i++) {
T a = ((T *) regVec[0].tmp)[o];
T b = ((T *) regVec[i].tmp)[o];
DEBUG("reduction",
std::cerr << "reduce max " << a << "," << b << "\n";);
((T *) regVec[0].tmp)[o] = b > a ? b : a;
}
}
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
assert(mycb % elemSize == 0);
for (size_t o=0; elemSize * o < mycb; o++) {
T *ptr = &((T *) ((char *) m->mLocalBuffer + myoffset))[o];
*ptr = ((T *) ((char *) regVec[0].tmp + tmpOffset))[o];
}
tmpOffset += mycb;
}
return;
}
void
Driver::performHostAtomicMaxReduction(KernelHandle *k,
const std::vector<DeviceBufferRegion> &
transferList) {
if (transferList.empty())
return;
std::set<MemoryHandle *> memHandles;
std::map<MemoryHandle *, std::vector<DeviceBufferRegion> > mem2RegMap;
for (unsigned i=0; i<transferList.size(); ++i) {
memHandles.insert(transferList[i].m);
mem2RegMap[transferList[i].m].push_back(transferList[i]);
}
for (MemoryHandle *m : memHandles) {
std::vector<DeviceBufferRegion> regVec = mem2RegMap[m];
assert(regVec.size() > 0);
// Get argument type
ArgumentAnalysis::TYPE type = k->getBufferType(m);
// Perform atomic sum reduction
switch(type) {
case ArgumentAnalysis::BOOL:
case ArgumentAnalysis::UNKNOWN:
assert(false);
case ArgumentAnalysis::CHAR:
break;
case ArgumentAnalysis::UCHAR:
break;
case ArgumentAnalysis::SHORT:
doMaxReduction<short>(m, regVec);
break;
case ArgumentAnalysis::USHORT:
doMaxReduction<unsigned short>(m, regVec);
break;
case ArgumentAnalysis::INT:
doMaxReduction<int>(m, regVec);
break;
case ArgumentAnalysis::UINT:
doMaxReduction<unsigned int>(m, regVec);
break;
case ArgumentAnalysis::LONG:
doMaxReduction<long>(m, regVec);
break;
case ArgumentAnalysis::ULONG:
doMaxReduction<unsigned long>(m, regVec);
break;
case ArgumentAnalysis::FLOAT:
doMaxReduction<float>(m, regVec);
break;
case ArgumentAnalysis::DOUBLE:
doMaxReduction<double>(m, regVec);
break;
};
// Update valid data
for (unsigned d=0; d<m->mNbBuffers; d++)
m->devicesValidData[d].difference(regVec[0].region);
m->hostValidData.myUnion(regVec[0].region);
// Free tmp buffers
for (unsigned i=0; i<regVec.size(); ++i)
free(regVec[i].tmp);
}
}
template<typename T>
void doMinReduction(MemoryHandle *m, std::vector<DeviceBufferRegion> ®Vec) {
size_t total_size = regVec[0].region.total();
size_t elemSize = sizeof(T);
assert(total_size % elemSize == 0);
for (size_t o = 0; elemSize * o < total_size; o++) {
for (unsigned i=1; i<regVec.size(); i++) {
T a = ((T *) regVec[0].tmp)[o];
T b = ((T *) regVec[i].tmp)[o];
DEBUG("reduction",
std::cerr << "reduce min " << a << "," << b << "\n";);
((T *) regVec[0].tmp)[o] = b < a ? b : a;
}
}
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
assert(mycb % elemSize == 0);
for (size_t o=0; elemSize * o < mycb; o++) {
T *ptr = &((T *) ((char *) m->mLocalBuffer + myoffset))[o];
*ptr = ((T *) ((char *) regVec[0].tmp + tmpOffset))[o];
}
tmpOffset += mycb;
}
return;
}
void
Driver::performHostAtomicMinReduction(KernelHandle *k,
const std::vector<DeviceBufferRegion> &
transferList) {
if (transferList.empty())
return;
std::set<MemoryHandle *> memHandles;
std::map<MemoryHandle *, std::vector<DeviceBufferRegion> > mem2RegMap;
for (unsigned i=0; i<transferList.size(); ++i) {
memHandles.insert(transferList[i].m);
mem2RegMap[transferList[i].m].push_back(transferList[i]);
}
for (MemoryHandle *m : memHandles) {
std::vector<DeviceBufferRegion> regVec = mem2RegMap[m];
assert(regVec.size() > 0);
// Get argument type
ArgumentAnalysis::TYPE type = k->getBufferType(m);
// Perform atomic sum reduction
switch(type) {
case ArgumentAnalysis::BOOL:
case ArgumentAnalysis::UNKNOWN:
assert(false);
case ArgumentAnalysis::CHAR:
break;
case ArgumentAnalysis::UCHAR:
break;
case ArgumentAnalysis::SHORT:
doMinReduction<short>(m, regVec);
break;
case ArgumentAnalysis::USHORT:
doMinReduction<unsigned short>(m, regVec);
break;
case ArgumentAnalysis::INT:
doMinReduction<int>(m, regVec);
break;
case ArgumentAnalysis::UINT:
doMinReduction<unsigned int>(m, regVec);
break;
case ArgumentAnalysis::LONG:
doMinReduction<long>(m, regVec);
break;
case ArgumentAnalysis::ULONG:
doMinReduction<unsigned long>(m, regVec);
break;
case ArgumentAnalysis::FLOAT:
doMinReduction<float>(m, regVec);
break;
case ArgumentAnalysis::DOUBLE:
doMinReduction<double>(m, regVec);
break;
};
// Update valid data
for (unsigned d=0; d<m->mNbBuffers; d++)
m->devicesValidData[d].difference(regVec[0].region);
m->hostValidData.myUnion(regVec[0].region);
// Free tmp buffers
for (unsigned i=0; i<regVec.size(); ++i)
free(regVec[i].tmp);
}
}
template<typename T>
void doMergeReduction(MemoryHandle *m, std::vector<DeviceBufferRegion> ®Vec) {
std::cerr << "Error: merge disabled !\n";
assert(false);
unsigned nbDevices = regVec.size();
size_t total_size = regVec[0].region.total();
size_t elemSize = sizeof(T);
assert(total_size % elemSize == 0);
{
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
assert(mycb % elemSize == 0);
for (size_t o=0; elemSize * o < mycb; o++) {
T *ptr = &((T *) ((char *) m->mLocalBuffer + myoffset))[o];
std::cerr << myoffset + o * elemSize << " ";
std::cerr << *ptr << " ";
bool found = false;
for (unsigned i=0; i<nbDevices; i++) {
std::cerr << ((T *) ((char *) regVec[i].tmp + tmpOffset))[o] << " ";
if (*ptr == ((T *) ((char *) regVec[i].tmp + tmpOffset))[o])
found = true;
}
assert(found);
}
tmpOffset += mycb;
}
}
// Sum of elements from all devices in regVec[0]
for (size_t o = 0; elemSize * o < total_size; o++) {
for (unsigned i=1; i<nbDevices; i++) {
T b = ((T *) regVec[i].tmp)[o];
((T *) regVec[0].tmp)[o] += b;
}
}
// Final res: localBuffer[e] + regVec[e] - nbDevices * localBuffer[e]
unsigned tmpOffset = 0;
for (unsigned id=0; id<regVec[0].region.mList.size(); ++id) {
size_t myoffset = regVec[0].region.mList[id].lb;
size_t mycb = regVec[0].region.mList[id].hb - myoffset + 1;
assert(mycb % elemSize == 0);
for (size_t o=0; elemSize * o < mycb; o++) {
T *ptr = &((T *) ((char *) m->mLocalBuffer + myoffset))[o];
*ptr += ((T *) ((char *) regVec[0].tmp + tmpOffset))[o] -
nbDevices * (*ptr);
}
tmpOffset += mycb;
}
return;
}
void
Driver::performHostMerge(KernelHandle *k,
const std::vector<DeviceBufferRegion> &
transferList) {
std::cerr << "Error: merge disabled !\n";
assert(false);
if (transferList.empty())
return;
std::set<MemoryHandle *> memHandles;
std::map<MemoryHandle *, std::vector<DeviceBufferRegion> > mem2RegMap;
for (unsigned i=0; i<transferList.size(); ++i) {
memHandles.insert(transferList[i].m);
mem2RegMap[transferList[i].m].push_back(transferList[i]);
}
for (MemoryHandle *m : memHandles) {
std::vector<DeviceBufferRegion> regVec = mem2RegMap[m];
assert(regVec.size() > 0);
// Get argument type
ArgumentAnalysis::TYPE type = k->getBufferType(m);
// Perform atomic sum reduction
switch(type) {
case ArgumentAnalysis::BOOL:
case ArgumentAnalysis::UNKNOWN:
assert(false);
case ArgumentAnalysis::CHAR:
break;
case ArgumentAnalysis::UCHAR:
break;
case ArgumentAnalysis::SHORT:
doMergeReduction<short>(m, regVec);
break;
case ArgumentAnalysis::USHORT:
doMergeReduction<unsigned short>(m, regVec);
break;
case ArgumentAnalysis::INT:
doMergeReduction<int>(m, regVec);
break;
case ArgumentAnalysis::UINT:
doMergeReduction<unsigned int>(m, regVec);
break;
case ArgumentAnalysis::LONG:
doMergeReduction<long>(m, regVec);
break;
case ArgumentAnalysis::ULONG:
doMergeReduction<unsigned long>(m, regVec);
break;
case ArgumentAnalysis::FLOAT:
doMergeReduction<float>(m, regVec);
break;
case ArgumentAnalysis::DOUBLE:
doMergeReduction<double>(m, regVec);
break;
};
// Update valid data
for (unsigned d=0; d<m->mNbBuffers; d++)
m->devicesValidData[d].difference(regVec[0].region);
m->hostValidData.myUnion(regVec[0].region);
// Free tmp buffers
for (unsigned i=0; i<regVec.size(); ++i)
free(regVec[i].tmp);
}
}
void
Driver::shutdown() {
if (optScheduler == Scheduler::MKGR2) {
SchedulerMKGR2 *schedMKGR2 = static_cast<SchedulerMKGR2 *>(scheduler);
schedMKGR2->plotD2HPoints();
schedMKGR2->plotH2DPoints();
}
}
};
| 30.349315 | 94 | 0.633085 | [
"vector"
] |
516bf4a10fbe066683204bb819e69a20d667388d | 9,548 | hpp | C++ | mcu/cortex-m0/CortexM0Cpu.hpp | fgr1986/fused | 2443cf92390914060b074d12e9226f5358e3899b | [
"Apache-2.0"
] | 9 | 2020-04-25T13:37:31.000Z | 2021-02-27T08:36:12.000Z | mcu/cortex-m0/CortexM0Cpu.hpp | fgr1986/fused | 2443cf92390914060b074d12e9226f5358e3899b | [
"Apache-2.0"
] | null | null | null | mcu/cortex-m0/CortexM0Cpu.hpp | fgr1986/fused | 2443cf92390914060b074d12e9226f5358e3899b | [
"Apache-2.0"
] | 5 | 2021-01-20T23:08:23.000Z | 2021-11-18T04:39:32.000Z | /*
* Copyright (c) 2019-2020, University of Southampton and Contributors.
* All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "mcu/ClockSourceIf.hpp"
#include "ps/PowerModelChannelIf.hpp"
#include <deque>
#include <systemc>
#include <tlm>
#include <unordered_set>
extern "C" {
#include "mcu/cortex-m0/decode.h"
#include "mcu/cortex-m0/exmemwb.h"
}
extern struct CPU cpu;
class CortexM0Cpu : public sc_core::sc_module, tlm::tlm_bw_transport_if<> {
SC_HAS_PROCESS(CortexM0Cpu);
public:
/* ------ Ports ------ */
sc_core::sc_port<ClockSourceConsumerIf> clk{"clk"}; //! CPU clock
tlm::tlm_initiator_socket<> iSocket; //! TLM initiator socket
sc_core::sc_in<bool> pwrOn{"pwrOn"}; //! "power-good" signal
sc_core::sc_in<bool> busStall{"busStall"}; //! indicate busy bus
//! Output port for power model events
PowerModelEventOutPort powerModelPort{"powerModelPort"};
// -- Interrupts
// SysTick
sc_core::sc_in<bool> sysTickIrq{"sysTickIrq"};
// NVIC
sc_core::sc_in<int> nvicIrq{"nvicIrq"};
// Output/feedback
sc_core::sc_out<int> returningException{"returningException"};
sc_core::sc_out<int> activeException{"activeException"};
/* ------ Types ------ */
/* ------ Methods ------ */
/**
* @brief CortexM0Cpu constructor
*/
CortexM0Cpu(const sc_core::sc_module_name nm);
/**
* @brief end_of_elaboration SystemC callback. Used here for registering power
* modelling events as well as setting up SC_THREADs and SC_METHODs.
*/
virtual void end_of_elaboration() override;
/**
* @brief exceptionCheck Check for pending exceptions, and handle them.
*/
void exceptionCheck();
/**
* @brief exceptionEnter Enter the handler corresponding to exceptionId.
* @param exceptionId ID of pending exception to be handled.
*/
void exceptionEnter(const unsigned exceptionId);
/**
* @brief exceptionReturn Return from an exception.
* @param EXC_RETURN value loaded into PC to signal an exception return.
*/
void exceptionReturn(const uint32_t EXC_RETURN);
/**
* @brief read_cb adds CPP context to C callback
* @param addr read address (MCU memory space)
* @param data buffer for return value
* @param bytelen number of bytes to be read
*/
static void read_cb(const uint32_t addr, uint8_t *const data,
const size_t bytelen);
/**
* @brief write_cb adds CPP context to C callback
* @param addr write address (MCU memory space)
* @param data buffer for return value
* @param bytelen number of bytes to be written
*/
static void write_cb(const uint32_t addr, uint8_t *const data,
const size_t bytelen);
/**
* @brief consume_cycles_cb Call SC wait() to wait for n clock cycles
* @param n number of cycles to consume
*/
static void consume_cycles_cb(const size_t n);
/**
* @brief exception_return_cb Call adds C++ context to C callback of
* exceptionReturn
*/
static void exception_return_cb(const uint32_t EXC_RETURN);
/**
* @brief exception_return_cb Call adds C++ context to C callback of
* getNextPipelineInst
*/
static uint16_t next_pipeline_instr_cb();
/**
* @brief getNextPipelineInst Used for getting second half of 32-bit
* instructions. Pops an instruction from the pipeline and inserts a NOP in
* its place.
* @retval next instruction from the pipeline
*/
uint16_t getNextPipelineInstr();
/**
* @brief writeMem: Callback function for write operations to memory by
* emulator
* @param addr write address (MCU memory space)
* @param data buffer for return value
* @param bytelen number of bytes to be read
*/
void writeMem(const uint32_t addr, uint8_t *const data, const size_t bytelen);
/**
* @brief write32 Utility function to write a word to memory.
* @param addr address to write to
* @param val value to write
*/
void write32(const uint32_t addr, const uint32_t val);
/**
* @brief read32 Utility function to read a word from memory.
* @param addr address to read from
* @retval Value read from memory (bus)
*/
uint32_t read32(const uint32_t addr);
/**
* @brief readMem: Callback function for read operations from memory by
* emulator
* @param addr read address (MCU memory space)
* @param data buffer for return value
* @param bytelen number of bytes to be read
*/
void readMem(const uint32_t addr, uint8_t *const data, const size_t bytelen);
/* ------ Controls for GDB server ------ */
/**
* @brief dbg_readReg Read register value without consuming simulation
* time.
* @param addr Specify which register to read (0-15).
* @return Value held in register.
*/
uint32_t dbg_readReg(size_t addr);
/**
* @brief dbg_writeReg Write to register without consuming simulation
* time.
* @param data Value to write to register.
* @param addr Specify which register to write to (0-15)
*/
void dbg_writeReg(size_t addr, uint32_t data);
/**
* @brief stall Stall processor
*/
void stall(void);
/**
* @brief unstall Unstall processor
*/
void unstall(void);
/**
* @brief isStalled
* @return True if processors is stalled, false otherwise.
*/
bool isStalled(void);
/**
* @brief insertBreakPoint Insert a breakpoint at the specified address.
* @param addr Address of breakpoint to be inserted.
*/
void insertBreakpoint(unsigned addr);
/**
* @brief removeBreakpoint Remove a breakpoint at specified address.
* @param addr Address of breakpoint to be removed.
*/
void removeBreakpoint(unsigned addr);
/**
* @brief step Activate execution of a single instruction.
*/
void step(void);
/**
* @brief Get PC register number
* @retval PC register number
*/
uint32_t pc_regnum() const { return PC_REGNUM; }
/**
* @brief Get number of general purpose registers
* @retval number of gprs
*/
uint32_t n_regs() const { return N_GPR; }
/**
* @brief operator<< debug printout
*/
friend std::ostream &operator<<(std::ostream &os, const CortexM0Cpu &rhs);
/*------ Dummy methods --------------------------------------------------*/
// Dummy method:
[[noreturn]] void invalidate_direct_mem_ptr(sc_dt::uint64 start_range
[[maybe_unused]],
sc_dt::uint64 end_range
[[maybe_unused]]) {
SC_REPORT_FATAL(this->name(), "invalidate_direct_mem_ptr not implemented");
exit(1);
}
// Dummy method:
[[noreturn]] tlm::tlm_sync_enum
nb_transport_bw(tlm::tlm_generic_payload &trans [[maybe_unused]],
tlm::tlm_phase &phase [[maybe_unused]],
sc_core::sc_time &delay [[maybe_unused]]) {
SC_REPORT_FATAL(this->name(), "nb_transport_bw is not implemented");
exit(1);
}
/* ------ Public variables ------*/
private:
/* ------ Constants ------ */
static const unsigned N_GPR = 16; // How many general purpose registers
static const unsigned SP_REGNUM = 13; // Stack pointer
static const unsigned LR_REGNUM = 14; // Link register
static const unsigned PC_REGNUM = 15; // Program counter
static const unsigned CPSR_REGNUM = 0x19; // (virtual register)
static const unsigned OPCODE_WFE = 0xbf20; //! Wait for Event opcode
static const unsigned OPCODE_WFI = 0xbf30; //! Wait for Interrupt opcode
static const unsigned OPCODE_NOP = 0x46c0; // 0xbf00; //! NOP (mov r8, r8)
/* ------ Private variables ------ */
struct InstructionBuffer {
unsigned data{0};
unsigned address{0};
bool valid{false};
};
std::deque<uint16_t> m_instructionQueue{}; //! Pipeline
int m_bubbles{0}; //! Current number of pipeline bubbles
int m_pipelineStages;
bool m_sleeping{false};
bool m_run{false};
bool m_doStep{false};
InstructionBuffer m_instructionBuffer;
std::unordered_set<unsigned> m_breakpoints; // Set of breakpoint addresses
std::unordered_set<unsigned> m_watchpoints; // Set of watchpoint addresses
std::array<unsigned, 17> m_regsAtExceptEnter{{0}}; //! Used for checking
/* Power model event & state ids */
int m_idleCyclesEventId{-1}; //! Event used to track idle cycles
int m_nInstructionsEventId{-1}; //! Event used to track number of
//! executed instructions
int m_offStateId{-1};
int m_onStateId{-1};
int m_sleepStateId{-1};
/* ------ Private methods ------ */
/**
* @brief process SystemC thread -- main processing loop
*/
[[noreturn]] void process();
/**
* @brief reset Reset state to power-up default
*/
void reset();
/**
* @brief powerOffChecks Perform checks when power is lost, issue warning if
* CPU is active.
*/
void powerOffChecks();
/**
* @brief wait for a command from controller.
*/
void waitForCommand();
/**
* @brief flushPipeline flush the instruction queue and insert nops
*/
void flushPipeline();
/**
*@brief fetch fetch an instruction via the instructino buffer.
*@param address memory address of instruction
*@retval instruction at address.
*/
unsigned fetch(const unsigned address);
/**
* @brief getNextExecutionPc get the address of the next instruction to be
* executed. This value is PC adjusted for pipeline and bubbles.
* @retval address of next instruction to be executed.
*/
unsigned getNextExecutionPc() const;
};
| 29.469136 | 80 | 0.661709 | [
"model"
] |
516c241d444000bbe53b979b7af78afcd53488e0 | 2,354 | cpp | C++ | src/tsppd/solver/ap/ap_atsppd_solver.cpp | ryanjoneil/tsppd | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 4 | 2018-03-30T20:58:57.000Z | 2018-04-25T01:48:09.000Z | src/tsppd/solver/ap/ap_atsppd_solver.cpp | ryanjoneil/tsppd | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 7 | 2019-04-21T13:42:09.000Z | 2019-05-09T15:49:56.000Z | src/tsppd/solver/ap/ap_atsppd_solver.cpp | ryanjoneil/tsppd-hybrid | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 1 | 2020-03-01T16:19:18.000Z | 2020-03-01T16:19:18.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the tsppd program and library for solving */
/* Traveling Salesman Problems with Pickup and Delivery. tsppd requires */
/* other commercial and open source software to build. tsppd is decribed */
/* in the paper "Exact Methods for Solving Traveling Salesman Problems */
/* with Pickup and Delivery in Real Time". */
/* */
/* Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu> */
/* */
/* tsppd is distributed under the terms of the ZIB Academic License. */
/* You should have received a copy of the ZIB Academic License along with */
/* tsppd. See the file LICENSE. If not, email roneil1@gmu.edu. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <tsppd/solver/ap/ap_atsppd_callback.h>
#include <tsppd/solver/ap/ap_atsppd_solver.h>
#include <tsppd/util/exception.h>
using namespace TSPPD::Data;
using namespace TSPPD::IO;
using namespace TSPPD::Solver;
using namespace TSPPD::Util;
using namespace std;
APATSPPDSolver::APATSPPDSolver(
const TSPPDProblem& problem,
const map<string, string> options,
TSPSolutionWriter& writer) :
APATSPSolver(problem, options, writer) {
initialize_atsppd_variables();
}
TSPPDSolution APATSPPDSolver::solve() {
configure_solver();
if (sec == ATSP_SEC_OTHER)
throw TSPPDException("sec can be either subtour or cutset");
APATSPPDCallback callback(problem, x, sec, writer);
model.setCallback(&callback);
model.optimize();
return solution();
}
void APATSPPDSolver::initialize_atsppd_variables() {
for (auto p : problem.pickup_indices()) {
// ~(+0 -i)
auto d = problem.successor_index(p);
x[start_index][d].set(GRB_DoubleAttr_UB, 0);
// ~(+i -0)
x[p][end_index].set(GRB_DoubleAttr_UB, 0);
// ~(-i +i)
x[d][p].set(GRB_DoubleAttr_UB, 0);
}
} | 38.590164 | 79 | 0.52124 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.