hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 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 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
339f12faeca90e0dda5926fb9e53fdad5c1fabea | 177 | cpp | C++ | src/Example/project_WhiteBoxStudio/code/WhiteboxTestingPlatform/WhiteboxTestingPlatform/WhiteboxTestingPlatform/ThirdStandardDataModel.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | 5 | 2017-09-07T06:58:34.000Z | 2021-07-21T08:41:26.000Z | src/Example/project_WhiteBoxStudio/code/WhiteboxTestingPlatform/WhiteboxTestingPlatform/WhiteboxTestingPlatform/ThirdStandardDataModel.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | null | null | null | src/Example/project_WhiteBoxStudio/code/WhiteboxTestingPlatform/WhiteboxTestingPlatform/WhiteboxTestingPlatform/ThirdStandardDataModel.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | 2 | 2017-09-27T06:31:11.000Z | 2020-05-13T12:29:58.000Z | #include "StdAfx.h"
#include "ThirdStandardDataModel.h"
CThirdStandardDataModel::CThirdStandardDataModel(void)
{
}
CThirdStandardDataModel::~CThirdStandardDataModel(void)
{
}
| 16.090909 | 55 | 0.813559 | yds086 |
339fd28879d12676327871f30ea0de3c01012193 | 4,667 | cpp | C++ | Nacro/SDK/FN_GA_DefaultPlayer_InteractSearch_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_GA_DefaultPlayer_InteractSearch_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_GA_DefaultPlayer_InteractSearch_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | // Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Completed_B697D9B445CA2BFDB1328D93C33FBCF3
// (HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm)
// struct FGameplayTag ApplicationTag (Parm)
void UGA_DefaultPlayer_InteractSearch_C::Completed_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag)
{
static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Completed_B697D9B445CA2BFDB1328D93C33FBCF3");
UGA_DefaultPlayer_InteractSearch_C_Completed_B697D9B445CA2BFDB1328D93C33FBCF3_Params params;
params.TargetData = TargetData;
params.ApplicationTag = ApplicationTag;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3
// (HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm)
// struct FGameplayTag ApplicationTag (Parm)
void UGA_DefaultPlayer_InteractSearch_C::Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag)
{
static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3");
UGA_DefaultPlayer_InteractSearch_C_Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3_Params params;
params.TargetData = TargetData;
params.ApplicationTag = ApplicationTag;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Triggered_B697D9B445CA2BFDB1328D93C33FBCF3
// (HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm)
// struct FGameplayTag ApplicationTag (Parm)
void UGA_DefaultPlayer_InteractSearch_C::Triggered_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag)
{
static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Triggered_B697D9B445CA2BFDB1328D93C33FBCF3");
UGA_DefaultPlayer_InteractSearch_C_Triggered_B697D9B445CA2BFDB1328D93C33FBCF3_Params params;
params.TargetData = TargetData;
params.ApplicationTag = ApplicationTag;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.K2_ActivateAbility
// (Event, Protected, BlueprintEvent)
void UGA_DefaultPlayer_InteractSearch_C::K2_ActivateAbility()
{
static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.K2_ActivateAbility");
UGA_DefaultPlayer_InteractSearch_C_K2_ActivateAbility_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.ExecuteUbergraph_GA_DefaultPlayer_InteractSearch
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UGA_DefaultPlayer_InteractSearch_C::ExecuteUbergraph_GA_DefaultPlayer_InteractSearch(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.ExecuteUbergraph_GA_DefaultPlayer_InteractSearch");
UGA_DefaultPlayer_InteractSearch_C_ExecuteUbergraph_GA_DefaultPlayer_InteractSearch_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 37.943089 | 185 | 0.78573 | Milxnor |
33a03b45d3a7f9aad320034c272f015d93063494 | 208 | cpp | C++ | ue/Drone_Simulator/Drone_Simulator.cpp | gabriserra/CatchingDrone | 65bab95d3dbd8085f79082db672954f752c77b12 | [
"MIT"
] | null | null | null | ue/Drone_Simulator/Drone_Simulator.cpp | gabriserra/CatchingDrone | 65bab95d3dbd8085f79082db672954f752c77b12 | [
"MIT"
] | null | null | null | ue/Drone_Simulator/Drone_Simulator.cpp | gabriserra/CatchingDrone | 65bab95d3dbd8085f79082db672954f752c77b12 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Drone_Simulator.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Drone_Simulator, "Drone_Simulator" );
| 34.666667 | 93 | 0.802885 | gabriserra |
33a08d1dba7069d2c5790e63ee7974f3c9c0fb3f | 83,350 | cpp | C++ | src/PE/EnumToString.cpp | junghee/LIEF | de7492ee49ef813cd8db3a858892e4ed5a5638c5 | [
"Apache-2.0"
] | 2,999 | 2017-04-03T13:43:23.000Z | 2022-03-31T15:24:27.000Z | src/PE/EnumToString.cpp | junghee/LIEF | de7492ee49ef813cd8db3a858892e4ed5a5638c5 | [
"Apache-2.0"
] | 626 | 2017-04-04T15:57:04.000Z | 2022-03-31T19:25:18.000Z | src/PE/EnumToString.cpp | junghee/LIEF | de7492ee49ef813cd8db3a858892e4ed5a5638c5 | [
"Apache-2.0"
] | 498 | 2017-04-04T14:18:25.000Z | 2022-03-29T19:31:38.000Z | /* Copyright 2017 - 2021 R. Thomas
* Copyright 2017 - 2021 Quarkslab
*
* 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 "LIEF/PE/Structures.hpp"
#include "LIEF/PE/EnumToString.hpp"
#include "frozen.hpp"
namespace LIEF {
namespace PE {
const char* to_string(PE_TYPE e) {
CONST_MAP(PE_TYPE, const char*, 2) enumStrings {
{ PE_TYPE::PE32, "PE32" },
{ PE_TYPE::PE32_PLUS,"PE32_PLUS" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(DATA_DIRECTORY e) {
CONST_MAP(DATA_DIRECTORY, const char*, 15) enumStrings {
{ DATA_DIRECTORY::EXPORT_TABLE, "EXPORT_TABLE" },
{ DATA_DIRECTORY::IMPORT_TABLE, "IMPORT_TABLE" },
{ DATA_DIRECTORY::RESOURCE_TABLE, "RESOURCE_TABLE" },
{ DATA_DIRECTORY::EXCEPTION_TABLE, "EXCEPTION_TABLE" },
{ DATA_DIRECTORY::CERTIFICATE_TABLE, "CERTIFICATE_TABLE" },
{ DATA_DIRECTORY::BASE_RELOCATION_TABLE, "BASE_RELOCATION_TABLE" },
{ DATA_DIRECTORY::DEBUG, "DEBUG" },
{ DATA_DIRECTORY::ARCHITECTURE, "ARCHITECTURE" },
{ DATA_DIRECTORY::GLOBAL_PTR, "GLOBAL_PTR" },
{ DATA_DIRECTORY::TLS_TABLE, "TLS_TABLE" },
{ DATA_DIRECTORY::LOAD_CONFIG_TABLE, "LOAD_CONFIG_TABLE" },
{ DATA_DIRECTORY::BOUND_IMPORT, "BOUND_IMPORT" },
{ DATA_DIRECTORY::IAT, "IAT" },
{ DATA_DIRECTORY::DELAY_IMPORT_DESCRIPTOR, "DELAY_IMPORT_DESCRIPTOR" },
{ DATA_DIRECTORY::CLR_RUNTIME_HEADER, "CLR_RUNTIME_HEADER" }
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(MACHINE_TYPES e) {
CONST_MAP(MACHINE_TYPES, const char*, 26) enumStrings {
{ MACHINE_TYPES::MT_Invalid, "INVALID" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_UNKNOWN, "UNKNOWN" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_AM33, "AM33" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_AMD64, "AMD64" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM, "ARM" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_ARMNT, "ARMNT" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM64, "ARM64" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_EBC, "EBC" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_I386, "I386" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_IA64, "IA64" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_M32R, "M32R" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPS16, "MIPS16" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU, "MIPSFPU" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU16, "MIPSFPU16" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPC, "POWERPC" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPCFP, "POWERPCFP" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_R4000, "R4000" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV32, "RISCV32" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV64, "RISCV64" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV128, "RISCV128" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3, "SH3" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3DSP, "SH3DSP" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_SH4, "SH4" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_SH5, "SH5" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_THUMB, "THUMB" },
{ MACHINE_TYPES::IMAGE_FILE_MACHINE_WCEMIPSV2, "WCEMIPSV2" }
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(HEADER_CHARACTERISTICS e) {
CONST_MAP(HEADER_CHARACTERISTICS, const char*, 15) enumStrings {
{ HEADER_CHARACTERISTICS::IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_AGGRESSIVE_WS_TRIM, "AGGRESSIVE_WS_TRIM" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_32BIT_MACHINE, "CHARA_32BIT_MACHINE" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_SYSTEM, "SYSTEM" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_DLL, "DLL" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY" },
{ HEADER_CHARACTERISTICS::IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI" }
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SUBSYSTEM e) {
CONST_MAP(SUBSYSTEM, const char*, 14) enumStrings {
{ SUBSYSTEM::IMAGE_SUBSYSTEM_UNKNOWN, "UNKNOWN" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_NATIVE, "NATIVE" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_GUI, "WINDOWS_GUI" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_CUI, "WINDOWS_CUI" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_OS2_CUI, "OS2_CUI" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_POSIX_CUI, "POSIX_CUI" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_NATIVE_WINDOWS, "NATIVE_WINDOWS" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI, "WINDOWS_CE_GUI" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_APPLICATION, "EFI_APPLICATION" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, "EFI_BOOT_SERVICE_DRIVER" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, "EFI_RUNTIME_DRIVER" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_ROM, "EFI_ROM" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_XBOX, "XBOX" },
{ SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION, "WINDOWS_BOOT_APPLICATION" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(DLL_CHARACTERISTICS e) {
CONST_MAP(DLL_CHARACTERISTICS, const char*, 11) enumStrings {
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA, "HIGH_ENTROPY_VA" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NX_COMPAT, "NX_COMPAT" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_SEH, "NO_SEH" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_BIND, "NO_BIND" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_APPCONTAINER, "APPCONTAINER" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_GUARD_CF, "GUARD_CF" },
{ DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SECTION_CHARACTERISTICS e) {
CONST_MAP(SECTION_CHARACTERISTICS, const char*, 35) enumStrings {
{ SECTION_CHARACTERISTICS::IMAGE_SCN_TYPE_NO_PAD, "TYPE_NO_PAD" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_CODE, "CNT_CODE" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_INITIALIZED_DATA, "CNT_INITIALIZED_DATA" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_UNINITIALIZED_DATA, "CNT_UNINITIALIZED_DATA" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_OTHER, "LNK_OTHER" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_INFO, "LNK_INFO" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_GPREL, "GPREL" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_16BIT, "MEM_16BIT" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_SHARED, "MEM_SHARED" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_READ, "MEM_READ" },
{ SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_WRITE, "MEM_WRITE" }
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(PE_SECTION_TYPES e) {
CONST_MAP(PE_SECTION_TYPES, const char*, 10) enumStrings {
{ PE_SECTION_TYPES::TEXT, "TEXT" },
{ PE_SECTION_TYPES::TLS, "TLS_" },
{ PE_SECTION_TYPES::IMPORT, "IDATA" },
{ PE_SECTION_TYPES::DATA, "DATA" },
{ PE_SECTION_TYPES::BSS, "BSS" },
{ PE_SECTION_TYPES::RESOURCE, "RESOURCE" },
{ PE_SECTION_TYPES::RELOCATION, "RELOCATION" },
{ PE_SECTION_TYPES::EXPORT, "EXPORT" },
{ PE_SECTION_TYPES::DEBUG, "DEBUG" },
{ PE_SECTION_TYPES::UNKNOWN, "UNKNOWN" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SYMBOL_BASE_TYPES e) {
CONST_MAP(SYMBOL_BASE_TYPES, const char*, 16) enumStrings {
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_NULL, "NULL" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_VOID, "VOID" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_CHAR, "CHAR" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_SHORT, "SHORT" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_INT, "INT" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_LONG, "LONG" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_FLOAT, "FLOAT" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_DOUBLE, "DOUBLE" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_STRUCT, "STRUCT" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_UNION, "UNION" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_ENUM, "ENUM" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_MOE, "MOE" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_BYTE, "BYTE" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_WORD, "WORD" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_UINT, "UINT" },
{ SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_DWORD, "DWORD" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SYMBOL_COMPLEX_TYPES e) {
CONST_MAP(SYMBOL_COMPLEX_TYPES, const char*, 5) enumStrings {
{ SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_NULL, "NULL" },
{ SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_POINTER, "POINTER" },
{ SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_FUNCTION, "FUNCTION" },
{ SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_ARRAY, "ARRAY" },
{ SYMBOL_COMPLEX_TYPES::SCT_COMPLEX_TYPE_SHIFT, "COMPLEX_TYPE_SHIFT" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SYMBOL_SECTION_NUMBER e) {
CONST_MAP(SYMBOL_SECTION_NUMBER, const char*, 3) enumStrings {
{ SYMBOL_SECTION_NUMBER::IMAGE_SYM_DEBUG, "DEBUG" },
{ SYMBOL_SECTION_NUMBER::IMAGE_SYM_ABSOLUTE, "ABSOLUTE" },
{ SYMBOL_SECTION_NUMBER::IMAGE_SYM_UNDEFINED, "UNDEFINED" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(SYMBOL_STORAGE_CLASS e) {
CONST_MAP(SYMBOL_STORAGE_CLASS, const char*, 24) enumStrings {
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_END_OF_FUNCTION, "END_OF_FUNCTION" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_NULL, "NULL" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_AUTOMATIC, "AUTOMATIC" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_EXTERNAL, "EXTERNAL" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_STATIC, "STATIC" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_REGISTER, "REGISTER" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_EXTERNAL_DEF, "EXTERNAL_DEF" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_LABEL, "LABEL" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNDEFINED_LABEL, "UNDEFINED_LABEL" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT, "MEMBER_OF_STRUCT" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNION_TAG, "UNION_TAG" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_TYPE_DEFINITION, "TYPE_DEFINITION" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNDEFINED_STATIC, "UDEFINED_STATIC" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_ENUM_TAG, "ENUM_TAG" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_MEMBER_OF_ENUM, "MEMBER_OF_ENUM" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_REGISTER_PARAM, "REGISTER_PARAM" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_BIT_FIELD, "BIT_FIELD" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_BLOCK, "BLOCK" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_FUNCTION, "FUNCTION" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_END_OF_STRUCT, "END_OF_STRUCT" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_FILE, "FILE" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_SECTION, "SECTION" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_WEAK_EXTERNAL, "WEAK_EXTERNAL" },
{ SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_CLR_TOKEN, "CLR_TOKEN" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RELOCATIONS_I386 e) {
CONST_MAP(RELOCATIONS_I386, const char*, 11) enumStrings {
{ RELOCATIONS_I386::IMAGE_REL_I386_ABSOLUTE, "ABSOLUTE" },
{ RELOCATIONS_I386::IMAGE_REL_I386_DIR16, "DIR16" },
{ RELOCATIONS_I386::IMAGE_REL_I386_REL16, "REL16" },
{ RELOCATIONS_I386::IMAGE_REL_I386_DIR32, "DIR32" },
{ RELOCATIONS_I386::IMAGE_REL_I386_DIR32NB, "DIR32NB" },
{ RELOCATIONS_I386::IMAGE_REL_I386_SEG12, "SEG12" },
{ RELOCATIONS_I386::IMAGE_REL_I386_SECTION, "SECTION" },
{ RELOCATIONS_I386::IMAGE_REL_I386_SECREL, "SECREL" },
{ RELOCATIONS_I386::IMAGE_REL_I386_TOKEN, "TOKEN" },
{ RELOCATIONS_I386::IMAGE_REL_I386_SECREL7, "SECREL7" },
{ RELOCATIONS_I386::IMAGE_REL_I386_REL32, "REL32" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RELOCATIONS_AMD64 e) {
CONST_MAP(RELOCATIONS_AMD64, const char*, 17) enumStrings {
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_ABSOLUTE, "ABSOLUTE" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR64, "ADDR64" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR32, "ADDR32" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR32NB, "ADDR32NB" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32, "REL32" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_1, "REL32_1" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_2, "REL32_2" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_3, "REL32_3" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_4, "REL32_4" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_5, "REL32_5" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECTION, "SECTION" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECREL, "SECREL" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECREL7, "SECREL7" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_TOKEN, "TOKEN" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_SREL32, "SREL32" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_PAIR, "PAIR" },
{ RELOCATIONS_AMD64::IMAGE_REL_AMD64_SSPAN32, "SSPAN32" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RELOCATIONS_ARM e) {
CONST_MAP(RELOCATIONS_ARM, const char*, 15) enumStrings {
{ RELOCATIONS_ARM::IMAGE_REL_ARM_ABSOLUTE, "ABSOLUTE" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_ADDR32, "ADDR32" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_ADDR32NB, "ADDR32NB" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH24, "BRANCH24" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH11, "BRANCH11" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_TOKEN, "TOKEN" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BLX24, "BLX24" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BLX11, "BLX11" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_SECTION, "SECTION" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_SECREL, "SECREL" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_MOV32A, "MOV32A" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_MOV32T, "MOV32T" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH20T, "BRANCH20T" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH24T, "BRANCH24T" },
{ RELOCATIONS_ARM::IMAGE_REL_ARM_BLX23T, "BLX23T" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RELOCATIONS_BASE_TYPES e) {
CONST_MAP(RELOCATIONS_BASE_TYPES, const char*, 19) enumStrings {
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ABSOLUTE, "ABSOLUTE" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGH, "HIGH" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_LOW, "LOW" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGHLOW, "HIGHLOW" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGHADJ, "HIGHADJ" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_MIPS_JMPADDR, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32A, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_HI20, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_SECTION, "SECTION" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_REL, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32T, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_THUMB_MOV32, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_LOW12I, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_LOW12S, "RISCV_LOW12S" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_MIPS_JMPADDR16, "MIPS_JMPADDR16 | IA64_IMM64" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_IA64_IMM64, "MIPS_JMPADDR16 | IA64_IMM64" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_DIR64, "DIR64" },
{ RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGH3ADJ, "HIGH3ADJ" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(DEBUG_TYPES e) {
CONST_MAP(DEBUG_TYPES, const char*, 18) enumStrings {
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_UNKNOWN, "UNKNOWN" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_COFF, "COFF" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_CODEVIEW, "CODEVIEW" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_FPO, "FPO" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_MISC, "MISC" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_EXCEPTION, "EXCEPTION" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_FIXUP, "FIXUP" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_OMAP_TO_SRC, "OMAP_TO_SRC" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC, "OMAP_FROM_SRC" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_BORLAND, "BORLAND" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_RESERVED10, "RESERVED" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_CLSID, "CLSID" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_VC_FEATURE, "VC_FEATURE" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_POGO, "POGO" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_ILTCG, "ILTCG" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_MPX, "MPX" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_REPRO, "REPRO" },
{ DEBUG_TYPES::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS, "EX_DLLCHARACTERISTICS" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RESOURCE_TYPES e) {
CONST_MAP(RESOURCE_TYPES, const char*, 21) enumStrings {
{ RESOURCE_TYPES::CURSOR, "CURSOR" },
{ RESOURCE_TYPES::BITMAP, "BITMAP" },
{ RESOURCE_TYPES::ICON, "ICON" },
{ RESOURCE_TYPES::MENU, "MENU" },
{ RESOURCE_TYPES::DIALOG, "DIALOG" },
{ RESOURCE_TYPES::STRING, "STRING" },
{ RESOURCE_TYPES::FONTDIR, "FONTDIR" },
{ RESOURCE_TYPES::FONT, "FONT" },
{ RESOURCE_TYPES::ACCELERATOR, "ACCELERATOR" },
{ RESOURCE_TYPES::RCDATA, "RCDATA" },
{ RESOURCE_TYPES::MESSAGETABLE, "MESSAGETABLE" },
{ RESOURCE_TYPES::GROUP_CURSOR, "GROUP_CURSOR" },
{ RESOURCE_TYPES::GROUP_ICON, "GROUP_ICON" },
{ RESOURCE_TYPES::VERSION, "VERSION" },
{ RESOURCE_TYPES::DLGINCLUDE, "DLGINCLUDE" },
{ RESOURCE_TYPES::PLUGPLAY, "PLUGPLAY" },
{ RESOURCE_TYPES::VXD, "VXD" },
{ RESOURCE_TYPES::ANICURSOR, "ANICURSOR" },
{ RESOURCE_TYPES::ANIICON, "ANIICON" },
{ RESOURCE_TYPES::HTML, "HTML" },
{ RESOURCE_TYPES::MANIFEST, "MANIFEST" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RESOURCE_LANGS e) {
CONST_MAP(RESOURCE_LANGS, const char*, 98) enumStrings {
{ RESOURCE_LANGS::LANG_NEUTRAL, "NEUTRAL" },
{ RESOURCE_LANGS::LANG_INVARIANT, "INVARIANT" },
{ RESOURCE_LANGS::LANG_AFRIKAANS, "AFRIKAANS" },
{ RESOURCE_LANGS::LANG_ALBANIAN, "ALBANIAN" },
{ RESOURCE_LANGS::LANG_ARABIC, "ARABIC" },
{ RESOURCE_LANGS::LANG_ARMENIAN, "ARMENIAN" },
{ RESOURCE_LANGS::LANG_ASSAMESE, "ASSAMESE" },
{ RESOURCE_LANGS::LANG_AZERI, "AZERI" },
{ RESOURCE_LANGS::LANG_BASQUE, "BASQUE" },
{ RESOURCE_LANGS::LANG_BELARUSIAN, "BELARUSIAN" },
{ RESOURCE_LANGS::LANG_BANGLA, "BANGLA" },
{ RESOURCE_LANGS::LANG_BULGARIAN, "BULGARIAN" },
{ RESOURCE_LANGS::LANG_CATALAN, "CATALAN" },
{ RESOURCE_LANGS::LANG_CHINESE, "CHINESE" },
{ RESOURCE_LANGS::LANG_CROATIAN, "CROATIAN" },
{ RESOURCE_LANGS::LANG_CZECH, "CZECH" },
{ RESOURCE_LANGS::LANG_DANISH, "DANISH" },
{ RESOURCE_LANGS::LANG_DIVEHI, "DIVEHI" },
{ RESOURCE_LANGS::LANG_DUTCH, "DUTCH" },
{ RESOURCE_LANGS::LANG_ENGLISH, "ENGLISH" },
{ RESOURCE_LANGS::LANG_ESTONIAN, "ESTONIAN" },
{ RESOURCE_LANGS::LANG_FAEROESE, "FAEROESE" },
{ RESOURCE_LANGS::LANG_FARSI, "FARSI" },
{ RESOURCE_LANGS::LANG_FINNISH, "FINNISH" },
{ RESOURCE_LANGS::LANG_FRENCH, "FRENCH" },
{ RESOURCE_LANGS::LANG_GALICIAN, "GALICIAN" },
{ RESOURCE_LANGS::LANG_GEORGIAN, "GEORGIAN" },
{ RESOURCE_LANGS::LANG_GERMAN, "GERMAN" },
{ RESOURCE_LANGS::LANG_GREEK, "GREEK" },
{ RESOURCE_LANGS::LANG_GUJARATI, "GUJARATI" },
{ RESOURCE_LANGS::LANG_HEBREW, "HEBREW" },
{ RESOURCE_LANGS::LANG_HINDI, "HINDI" },
{ RESOURCE_LANGS::LANG_HUNGARIAN, "HUNGARIAN" },
{ RESOURCE_LANGS::LANG_ICELANDIC, "ICELANDIC" },
{ RESOURCE_LANGS::LANG_INDONESIAN, "INDONESIAN" },
{ RESOURCE_LANGS::LANG_ITALIAN, "ITALIAN" },
{ RESOURCE_LANGS::LANG_JAPANESE, "JAPANESE" },
{ RESOURCE_LANGS::LANG_KANNADA, "KANNADA" },
{ RESOURCE_LANGS::LANG_KASHMIRI, "KASHMIRI" },
{ RESOURCE_LANGS::LANG_KAZAK, "KAZAK" },
{ RESOURCE_LANGS::LANG_KONKANI, "KONKANI" },
{ RESOURCE_LANGS::LANG_KOREAN, "KOREAN" },
{ RESOURCE_LANGS::LANG_KYRGYZ, "KYRGYZ" },
{ RESOURCE_LANGS::LANG_LATVIAN, "LATVIAN" },
{ RESOURCE_LANGS::LANG_LITHUANIAN, "LITHUANIAN" },
{ RESOURCE_LANGS::LANG_MACEDONIAN, "MACEDONIAN" },
{ RESOURCE_LANGS::LANG_MALAY, "MALAY" },
{ RESOURCE_LANGS::LANG_MALAYALAM, "MALAYALAM" },
{ RESOURCE_LANGS::LANG_MANIPURI, "MANIPURI" },
{ RESOURCE_LANGS::LANG_MARATHI, "MARATHI" },
{ RESOURCE_LANGS::LANG_MONGOLIAN, "MONGOLIAN" },
{ RESOURCE_LANGS::LANG_NEPALI, "NEPALI" },
{ RESOURCE_LANGS::LANG_NORWEGIAN, "NORWEGIAN" },
{ RESOURCE_LANGS::LANG_ORIYA, "ORIYA" },
{ RESOURCE_LANGS::LANG_POLISH, "POLISH" },
{ RESOURCE_LANGS::LANG_PORTUGUESE, "PORTUGUESE" },
{ RESOURCE_LANGS::LANG_PUNJABI, "PUNJABI" },
{ RESOURCE_LANGS::LANG_ROMANIAN, "ROMANIAN" },
{ RESOURCE_LANGS::LANG_RUSSIAN, "RUSSIAN" },
{ RESOURCE_LANGS::LANG_SANSKRIT, "SANSKRIT" },
{ RESOURCE_LANGS::LANG_SINDHI, "SINDHI" },
{ RESOURCE_LANGS::LANG_SLOVAK, "SLOVAK" },
{ RESOURCE_LANGS::LANG_SLOVENIAN, "SLOVENIAN" },
{ RESOURCE_LANGS::LANG_SPANISH, "SPANISH" },
{ RESOURCE_LANGS::LANG_SWAHILI, "SWAHILI" },
{ RESOURCE_LANGS::LANG_SWEDISH, "SWEDISH" },
{ RESOURCE_LANGS::LANG_SYRIAC, "SYRIAC" },
{ RESOURCE_LANGS::LANG_TAMIL, "TAMIL" },
{ RESOURCE_LANGS::LANG_TATAR, "TATAR" },
{ RESOURCE_LANGS::LANG_TELUGU, "TELUGU" },
{ RESOURCE_LANGS::LANG_THAI, "THAI" },
{ RESOURCE_LANGS::LANG_TURKISH, "TURKISH" },
{ RESOURCE_LANGS::LANG_UKRAINIAN, "UKRAINIAN" },
{ RESOURCE_LANGS::LANG_URDU, "URDU" },
{ RESOURCE_LANGS::LANG_UZBEK, "UZBEK" },
{ RESOURCE_LANGS::LANG_VIETNAMESE, "VIETNAMESE" },
{ RESOURCE_LANGS::LANG_MALTESE, "MALTESE" },
{ RESOURCE_LANGS::LANG_MAORI, "MAORI" },
{ RESOURCE_LANGS::LANG_RHAETO_ROMANCE, "RHAETO_ROMANCE" },
{ RESOURCE_LANGS::LANG_SAMI, "SAMI" },
{ RESOURCE_LANGS::LANG_SORBIAN, "SORBIAN" },
{ RESOURCE_LANGS::LANG_SUTU, "SUTU" },
{ RESOURCE_LANGS::LANG_TSONGA, "TSONGA" },
{ RESOURCE_LANGS::LANG_TSWANA, "TSWANA" },
{ RESOURCE_LANGS::LANG_VENDA, "VENDA" },
{ RESOURCE_LANGS::LANG_XHOSA, "XHOSA" },
{ RESOURCE_LANGS::LANG_ZULU, "ZULU" },
{ RESOURCE_LANGS::LANG_ESPERANTO, "ESPERANTO" },
{ RESOURCE_LANGS::LANG_WALON, "WALON" },
{ RESOURCE_LANGS::LANG_CORNISH, "CORNISH" },
{ RESOURCE_LANGS::LANG_WELSH, "WELSH" },
{ RESOURCE_LANGS::LANG_BRETON, "BRETON" },
{ RESOURCE_LANGS::LANG_INUKTITUT, "INUKTITUT" },
{ RESOURCE_LANGS::LANG_IRISH, "IRISH" },
{ RESOURCE_LANGS::LANG_PULAR, "PULAR" },
{ RESOURCE_LANGS::LANG_QUECHUA, "QUECHUA" },
{ RESOURCE_LANGS::LANG_TAMAZIGHT, "TAMAZIGHT" },
{ RESOURCE_LANGS::LANG_TIGRINYA, "TIGRINYA" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(RESOURCE_SUBLANGS e) {
CONST_MAP(RESOURCE_SUBLANGS, const char*, 229) enumStrings {
{ RESOURCE_SUBLANGS::SUBLANG_AFRIKAANS_SOUTH_AFRICA, "AFRIKAANS_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_ALBANIAN_ALBANIA, "ALBANIAN_ALBANIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ALSATIAN_FRANCE, "ALSATIAN_FRANCE" },
{ RESOURCE_SUBLANGS::SUBLANG_AMHARIC_ETHIOPIA, "AMHARIC_ETHIOPIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_ALGERIA, "ARABIC_ALGERIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_BAHRAIN, "ARABIC_BAHRAIN" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_EGYPT, "ARABIC_EGYPT" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_IRAQ, "ARABIC_IRAQ" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_JORDAN, "ARABIC_JORDAN" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_KUWAIT, "ARABIC_KUWAIT" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_LEBANON, "ARABIC_LEBANON" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_LIBYA, "ARABIC_LIBYA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_MOROCCO, "ARABIC_MOROCCO" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_OMAN, "ARABIC_OMAN" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_QATAR, "ARABIC_QATAR" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_SAUDI_ARABIA, "ARABIC_SAUDI_ARABIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_SYRIA, "ARABIC_SYRIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_TUNISIA, "ARABIC_TUNISIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_UAE, "ARABIC_UAE" },
{ RESOURCE_SUBLANGS::SUBLANG_ARABIC_YEMEN, "ARABIC_YEMEN" },
{ RESOURCE_SUBLANGS::SUBLANG_ARMENIAN_ARMENIA, "ARMENIAN_ARMENIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ASSAMESE_INDIA, "ASSAMESE_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_AZERI_CYRILLIC, "AZERI_CYRILLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_AZERI_LATIN, "AZERI_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_BASHKIR_RUSSIA, "BASHKIR_RUSSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_BASQUE_BASQUE, "BASQUE_BASQUE" },
{ RESOURCE_SUBLANGS::SUBLANG_BELARUSIAN_BELARUS, "BELARUSIAN_BELARUS" },
{ RESOURCE_SUBLANGS::SUBLANG_BANGLA_BANGLADESH, "BANGLA_BANGLADESH" },
{ RESOURCE_SUBLANGS::SUBLANG_BANGLA_INDIA, "BANGLA_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC, "BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN, "BOSNIAN_BOSNIA_HERZEGOVINA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_BRETON_FRANCE, "BRETON_FRANCE" },
{ RESOURCE_SUBLANGS::SUBLANG_BULGARIAN_BULGARIA, "BULGARIAN_BULGARIA" },
{ RESOURCE_SUBLANGS::SUBLANG_CATALAN_CATALAN, "CATALAN_CATALAN" },
{ RESOURCE_SUBLANGS::SUBLANG_CHINESE_HONGKONG, "CHINESE_HONGKONG" },
{ RESOURCE_SUBLANGS::SUBLANG_CHINESE_MACAU, "CHINESE_MACAU" },
{ RESOURCE_SUBLANGS::SUBLANG_CHINESE_SIMPLIFIED, "CHINESE_SIMPLIFIED" },
{ RESOURCE_SUBLANGS::SUBLANG_CHINESE_SINGAPORE, "CHINESE_SINGAPORE" },
{ RESOURCE_SUBLANGS::SUBLANG_CHINESE_TRADITIONAL, "CHINESE_TRADITIONAL" },
{ RESOURCE_SUBLANGS::SUBLANG_CORSICAN_FRANCE, "CORSICAN_FRANCE" },
{ RESOURCE_SUBLANGS::SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN, "CROATIAN_BOSNIA_HERZEGOVINA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_CROATIAN_CROATIA, "CROATIAN_CROATIA" },
{ RESOURCE_SUBLANGS::SUBLANG_CUSTOM_DEFAULT, "CUSTOM_DEFAULT" },
{ RESOURCE_SUBLANGS::SUBLANG_CUSTOM_UNSPECIFIED, "CUSTOM_UNSPECIFIED" },
{ RESOURCE_SUBLANGS::SUBLANG_CZECH_CZECH_REPUBLIC, "CZECH_CZECH_REPUBLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_DANISH_DENMARK, "DANISH_DENMARK" },
{ RESOURCE_SUBLANGS::SUBLANG_DARI_AFGHANISTAN, "DARI_AFGHANISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_DEFAULT, "DEFAULT" },
{ RESOURCE_SUBLANGS::SUBLANG_DIVEHI_MALDIVES, "DIVEHI_MALDIVES" },
{ RESOURCE_SUBLANGS::SUBLANG_DUTCH_BELGIAN, "DUTCH_BELGIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_DUTCH, "DUTCH" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_AUS, "ENGLISH_AUS" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_BELIZE, "ENGLISH_BELIZE" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_CAN, "ENGLISH_CAN" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_CARIBBEAN, "ENGLISH_CARIBBEAN" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_EIRE, "ENGLISH_EIRE" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_INDIA, "ENGLISH_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_JAMAICA, "ENGLISH_JAMAICA" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_MALAYSIA, "ENGLISH_MALAYSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_NZ, "ENGLISH_NZ" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_PHILIPPINES, "ENGLISH_PHILIPPINES" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_SINGAPORE, "ENGLISH_SINGAPORE" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_SOUTH_AFRICA, "ENGLISH_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_TRINIDAD, "ENGLISH_TRINIDAD" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_UK, "ENGLISH_UK" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_US, "ENGLISH_US" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_ZIMBABWE, "ENGLISH_ZIMBABWE" },
{ RESOURCE_SUBLANGS::SUBLANG_ENGLISH_IRELAND, "ENGLISH_IRELAND" },
{ RESOURCE_SUBLANGS::SUBLANG_ESTONIAN_ESTONIA, "ESTONIAN_ESTONIA" },
{ RESOURCE_SUBLANGS::SUBLANG_FAEROESE_FAROE_ISLANDS, "FAEROESE_FAROE_ISLANDS" },
{ RESOURCE_SUBLANGS::SUBLANG_FILIPINO_PHILIPPINES, "FILIPINO_PHILIPPINES" },
{ RESOURCE_SUBLANGS::SUBLANG_FINNISH_FINLAND, "FINNISH_FINLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH_BELGIAN, "FRENCH_BELGIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH_CANADIAN, "FRENCH_CANADIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH_LUXEMBOURG, "FRENCH_LUXEMBOURG" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH_MONACO, "FRENCH_MONACO" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH_SWISS, "FRENCH_SWISS" },
{ RESOURCE_SUBLANGS::SUBLANG_FRENCH, "FRENCH" },
{ RESOURCE_SUBLANGS::SUBLANG_FRISIAN_NETHERLANDS, "FRISIAN_NETHERLANDS" },
{ RESOURCE_SUBLANGS::SUBLANG_GALICIAN_GALICIAN, "GALICIAN_GALICIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_GEORGIAN_GEORGIA, "GEORGIAN_GEORGIA" },
{ RESOURCE_SUBLANGS::SUBLANG_GERMAN_AUSTRIAN, "GERMAN_AUSTRIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_GERMAN_LIECHTENSTEIN, "GERMAN_LIECHTENSTEIN" },
{ RESOURCE_SUBLANGS::SUBLANG_GERMAN_LUXEMBOURG, "GERMAN_LUXEMBOURG" },
{ RESOURCE_SUBLANGS::SUBLANG_GERMAN_SWISS, "GERMAN_SWISS" },
{ RESOURCE_SUBLANGS::SUBLANG_GERMAN, "GERMAN" },
{ RESOURCE_SUBLANGS::SUBLANG_GREEK_GREECE, "GREEK_GREECE" },
{ RESOURCE_SUBLANGS::SUBLANG_GREENLANDIC_GREENLAND, "GREENLANDIC_GREENLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_GUJARATI_INDIA, "GUJARATI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_HAUSA_NIGERIA_LATIN, "HAUSA_NIGERIA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_HEBREW_ISRAEL, "HEBREW_ISRAEL" },
{ RESOURCE_SUBLANGS::SUBLANG_HINDI_INDIA, "HINDI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_HUNGARIAN_HUNGARY, "HUNGARIAN_HUNGARY" },
{ RESOURCE_SUBLANGS::SUBLANG_ICELANDIC_ICELAND, "ICELANDIC_ICELAND" },
{ RESOURCE_SUBLANGS::SUBLANG_IGBO_NIGERIA, "IGBO_NIGERIA" },
{ RESOURCE_SUBLANGS::SUBLANG_INDONESIAN_INDONESIA, "INDONESIAN_INDONESIA" },
{ RESOURCE_SUBLANGS::SUBLANG_INUKTITUT_CANADA_LATIN, "INUKTITUT_CANADA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_INUKTITUT_CANADA, "INUKTITUT_CANADA" },
{ RESOURCE_SUBLANGS::SUBLANG_IRISH_IRELAND, "IRISH_IRELAND" },
{ RESOURCE_SUBLANGS::SUBLANG_ITALIAN_SWISS, "ITALIAN_SWISS" },
{ RESOURCE_SUBLANGS::SUBLANG_ITALIAN, "ITALIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_JAPANESE_JAPAN, "JAPANESE_JAPAN" },
{ RESOURCE_SUBLANGS::SUBLANG_KANNADA_INDIA, "KANNADA_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_KASHMIRI_INDIA, "KASHMIRI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_KASHMIRI_SASIA, "KASHMIRI_SASIA" },
{ RESOURCE_SUBLANGS::SUBLANG_KAZAK_KAZAKHSTAN, "KAZAK_KAZAKHSTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_KHMER_CAMBODIA, "KHMER_CAMBODIA" },
{ RESOURCE_SUBLANGS::SUBLANG_KICHE_GUATEMALA, "KICHE_GUATEMALA" },
{ RESOURCE_SUBLANGS::SUBLANG_KINYARWANDA_RWANDA, "KINYARWANDA_RWANDA" },
{ RESOURCE_SUBLANGS::SUBLANG_KONKANI_INDIA, "KONKANI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_KOREAN, "KOREAN" },
{ RESOURCE_SUBLANGS::SUBLANG_KYRGYZ_KYRGYZSTAN, "KYRGYZ_KYRGYZSTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_LAO_LAO, "LAO_LAO" },
{ RESOURCE_SUBLANGS::SUBLANG_LATVIAN_LATVIA, "LATVIAN_LATVIA" },
{ RESOURCE_SUBLANGS::SUBLANG_LITHUANIAN_CLASSIC, "LITHUANIAN_CLASSIC" },
{ RESOURCE_SUBLANGS::SUBLANG_LITHUANIAN, "LITHUANIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_LOWER_SORBIAN_GERMANY, "LOWER_SORBIAN_GERMANY" },
{ RESOURCE_SUBLANGS::SUBLANG_LUXEMBOURGISH_LUXEMBOURG, "LUXEMBOURGISH_LUXEMBOURG" },
{ RESOURCE_SUBLANGS::SUBLANG_MACEDONIAN_MACEDONIA, "MACEDONIAN_MACEDONIA" },
{ RESOURCE_SUBLANGS::SUBLANG_MALAY_BRUNEI_DARUSSALAM, "MALAY_BRUNEI_DARUSSALAM" },
{ RESOURCE_SUBLANGS::SUBLANG_MALAY_MALAYSIA, "MALAY_MALAYSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_MALAYALAM_INDIA, "MALAYALAM_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_MALTESE_MALTA, "MALTESE_MALTA" },
{ RESOURCE_SUBLANGS::SUBLANG_MAORI_NEW_ZEALAND, "MAORI_NEW_ZEALAND" },
{ RESOURCE_SUBLANGS::SUBLANG_MAPUDUNGUN_CHILE, "MAPUDUNGUN_CHILE" },
{ RESOURCE_SUBLANGS::SUBLANG_MARATHI_INDIA, "MARATHI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_MOHAWK_MOHAWK, "MOHAWK_MOHAWK" },
{ RESOURCE_SUBLANGS::SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA, "MONGOLIAN_CYRILLIC_MONGOLIA" },
{ RESOURCE_SUBLANGS::SUBLANG_MONGOLIAN_PRC, "MONGOLIAN_PRC" },
{ RESOURCE_SUBLANGS::SUBLANG_NEPALI_INDIA, "NEPALI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_NEPALI_NEPAL, "NEPALI_NEPAL" },
{ RESOURCE_SUBLANGS::SUBLANG_NEUTRAL, "NEUTRAL" },
{ RESOURCE_SUBLANGS::SUBLANG_NORWEGIAN_BOKMAL, "NORWEGIAN_BOKMAL" },
{ RESOURCE_SUBLANGS::SUBLANG_NORWEGIAN_NYNORSK, "NORWEGIAN_NYNORSK" },
{ RESOURCE_SUBLANGS::SUBLANG_OCCITAN_FRANCE, "OCCITAN_FRANCE" },
{ RESOURCE_SUBLANGS::SUBLANG_ORIYA_INDIA, "ORIYA_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_PASHTO_AFGHANISTAN, "PASHTO_AFGHANISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_PERSIAN_IRAN, "PERSIAN_IRAN" },
{ RESOURCE_SUBLANGS::SUBLANG_POLISH_POLAND, "POLISH_POLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_PORTUGUESE_BRAZILIAN, "PORTUGUESE_BRAZILIAN" },
{ RESOURCE_SUBLANGS::SUBLANG_PORTUGUESE, "PORTUGUESE" },
{ RESOURCE_SUBLANGS::SUBLANG_PUNJABI_INDIA, "PUNJABI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_QUECHUA_BOLIVIA, "QUECHUA_BOLIVIA" },
{ RESOURCE_SUBLANGS::SUBLANG_QUECHUA_ECUADOR, "QUECHUA_ECUADOR" },
{ RESOURCE_SUBLANGS::SUBLANG_QUECHUA_PERU, "QUECHUA_PERU" },
{ RESOURCE_SUBLANGS::SUBLANG_ROMANIAN_ROMANIA, "ROMANIAN_ROMANIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ROMANSH_SWITZERLAND, "ROMANSH_SWITZERLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_RUSSIAN_RUSSIA, "RUSSIAN_RUSSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_INARI_FINLAND, "SAMI_INARI_FINLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_LULE_NORWAY, "SAMI_LULE_NORWAY" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_LULE_SWEDEN, "SAMI_LULE_SWEDEN" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_FINLAND, "SAMI_NORTHERN_FINLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_NORWAY, "SAMI_NORTHERN_NORWAY" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_SWEDEN, "SAMI_NORTHERN_SWEDEN" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_SKOLT_FINLAND, "SAMI_SKOLT_FINLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_SOUTHERN_NORWAY, "SAMI_SOUTHERN_NORWAY" },
{ RESOURCE_SUBLANGS::SUBLANG_SAMI_SOUTHERN_SWEDEN, "SAMI_SOUTHERN_SWEDEN" },
{ RESOURCE_SUBLANGS::SUBLANG_SANSKRIT_INDIA, "SANSKRIT_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC, "SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN, "SERBIAN_BOSNIA_HERZEGOVINA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_SERBIAN_CROATIA, "SERBIAN_CROATIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SERBIAN_CYRILLIC, "SERBIAN_CYRILLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_SERBIAN_LATIN, "SERBIAN_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_SINDHI_AFGHANISTAN, "SINDHI_AFGHANISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_SINDHI_INDIA, "SINDHI_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SINDHI_PAKISTAN, "SINDHI_PAKISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_SINHALESE_SRI_LANKA, "SINHALESE_SRI_LANKA" },
{ RESOURCE_SUBLANGS::SUBLANG_SLOVAK_SLOVAKIA, "SLOVAK_SLOVAKIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SLOVENIAN_SLOVENIA, "SLOVENIAN_SLOVENIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA, "SOTHO_NORTHERN_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_ARGENTINA, "SPANISH_ARGENTINA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_BOLIVIA, "SPANISH_BOLIVIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_CHILE, "SPANISH_CHILE" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_COLOMBIA, "SPANISH_COLOMBIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_COSTA_RICA, "SPANISH_COSTA_RICA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_DOMINICAN_REPUBLIC, "SPANISH_DOMINICAN_REPUBLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_ECUADOR, "SPANISH_ECUADOR" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_EL_SALVADOR, "SPANISH_EL_SALVADOR" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_GUATEMALA, "SPANISH_GUATEMALA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_HONDURAS, "SPANISH_HONDURAS" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_MEXICAN, "SPANISH_MEXICAN" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_MODERN, "SPANISH_MODERN" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_NICARAGUA, "SPANISH_NICARAGUA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_PANAMA, "SPANISH_PANAMA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_PARAGUAY, "SPANISH_PARAGUAY" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_PERU, "SPANISH_PERU" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_PUERTO_RICO, "SPANISH_PUERTO_RICO" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_URUGUAY, "SPANISH_URUGUAY" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_US, "SPANISH_US" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH_VENEZUELA, "SPANISH_VENEZUELA" },
{ RESOURCE_SUBLANGS::SUBLANG_SPANISH, "SPANISH" },
{ RESOURCE_SUBLANGS::SUBLANG_SWAHILI_KENYA, "SWAHILI_KENYA" },
{ RESOURCE_SUBLANGS::SUBLANG_SWEDISH_FINLAND, "SWEDISH_FINLAND" },
{ RESOURCE_SUBLANGS::SUBLANG_SWEDISH, "SWEDISH" },
{ RESOURCE_SUBLANGS::SUBLANG_SYRIAC_SYRIA, "SYRIAC_SYRIA" },
{ RESOURCE_SUBLANGS::SUBLANG_SYS_DEFAULT, "SYS_DEFAULT" },
{ RESOURCE_SUBLANGS::SUBLANG_TAJIK_TAJIKISTAN, "TAJIK_TAJIKISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_TAMAZIGHT_ALGERIA_LATIN, "TAMAZIGHT_ALGERIA_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_TAMIL_INDIA, "TAMIL_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_TATAR_RUSSIA, "TATAR_RUSSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_TELUGU_INDIA, "TELUGU_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_THAI_THAILAND, "THAI_THAILAND" },
{ RESOURCE_SUBLANGS::SUBLANG_TIBETAN_PRC, "TIBETAN_PRC" },
{ RESOURCE_SUBLANGS::SUBLANG_TIGRIGNA_ERITREA, "TIGRIGNA_ERITREA" },
{ RESOURCE_SUBLANGS::SUBLANG_TSWANA_SOUTH_AFRICA, "TSWANA_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_TURKISH_TURKEY, "TURKISH_TURKEY" },
{ RESOURCE_SUBLANGS::SUBLANG_TURKMEN_TURKMENISTAN, "TURKMEN_TURKMENISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_UI_CUSTOM_DEFAULT, "UI_CUSTOM_DEFAULT" },
{ RESOURCE_SUBLANGS::SUBLANG_UIGHUR_PRC, "UIGHUR_PRC" },
{ RESOURCE_SUBLANGS::SUBLANG_UKRAINIAN_UKRAINE, "UKRAINIAN_UKRAINE" },
{ RESOURCE_SUBLANGS::SUBLANG_UPPER_SORBIAN_GERMANY, "UPPER_SORBIAN_GERMANY" },
{ RESOURCE_SUBLANGS::SUBLANG_URDU_INDIA, "URDU_INDIA" },
{ RESOURCE_SUBLANGS::SUBLANG_URDU_PAKISTAN, "URDU_PAKISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_UZBEK_CYRILLIC, "UZBEK_CYRILLIC" },
{ RESOURCE_SUBLANGS::SUBLANG_UZBEK_LATIN, "UZBEK_LATIN" },
{ RESOURCE_SUBLANGS::SUBLANG_VIETNAMESE_VIETNAM, "VIETNAMESE_VIETNAM" },
{ RESOURCE_SUBLANGS::SUBLANG_WELSH_UNITED_KINGDOM, "WELSH_UNITED_KINGDOM" },
{ RESOURCE_SUBLANGS::SUBLANG_WOLOF_SENEGAL, "WOLOF_SENEGAL" },
{ RESOURCE_SUBLANGS::SUBLANG_XHOSA_SOUTH_AFRICA, "XHOSA_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_YAKUT_RUSSIA, "YAKUT_RUSSIA" },
{ RESOURCE_SUBLANGS::SUBLANG_YI_PRC, "YI_PRC" },
{ RESOURCE_SUBLANGS::SUBLANG_YORUBA_NIGERIA, "YORUBA_NIGERIA" },
{ RESOURCE_SUBLANGS::SUBLANG_ZULU_SOUTH_AFRICA, "ZULU_SOUTH_AFRICA" },
{ RESOURCE_SUBLANGS::SUBLANG_PUNJABI_PAKISTAN, "PUNJABI_PAKISTAN" },
{ RESOURCE_SUBLANGS::SUBLANG_TSWANA_BOTSWANA, "TSWANA_BOTSWANA" },
{ RESOURCE_SUBLANGS::SUBLANG_TAMIL_SRI_LANKA, "TAMIL_SRI_LANKA" },
{ RESOURCE_SUBLANGS::SUBLANG_TIGRINYA_ETHIOPIA, "TIGRINYA_ETHIOPIA" },
{ RESOURCE_SUBLANGS::SUBLANG_TIGRINYA_ERITREA, "TIGRINYA_ERITREA" },
{ RESOURCE_SUBLANGS::SUBLANG_VALENCIAN_VALENCIA, "VALENCIAN_VALENCIA" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(EXTENDED_WINDOW_STYLES e) {
CONST_MAP(EXTENDED_WINDOW_STYLES, const char*, 17) enumStrings {
{ EXTENDED_WINDOW_STYLES::WS_EX_DLGMODALFRAME, "DLGMODALFRAME" },
{ EXTENDED_WINDOW_STYLES::WS_EX_NOPARENTNOTIFY, "NOPARENTNOTIFY" },
{ EXTENDED_WINDOW_STYLES::WS_EX_TOPMOST, "TOPMOST" },
{ EXTENDED_WINDOW_STYLES::WS_EX_ACCEPTFILES, "ACCEPTFILES" },
{ EXTENDED_WINDOW_STYLES::WS_EX_TRANSPARENT, "TRANSPARENT" },
{ EXTENDED_WINDOW_STYLES::WS_EX_MDICHILD, "MDICHILD" },
{ EXTENDED_WINDOW_STYLES::WS_EX_TOOLWINDOW, "TOOLWINDOW" },
{ EXTENDED_WINDOW_STYLES::WS_EX_WINDOWEDGE, "WINDOWEDGE" },
{ EXTENDED_WINDOW_STYLES::WS_EX_CLIENTEDGE, "CLIENTEDGE" },
{ EXTENDED_WINDOW_STYLES::WS_EX_CONTEXTHELP, "CONTEXTHELP" },
{ EXTENDED_WINDOW_STYLES::WS_EX_RIGHT, "RIGHT" },
{ EXTENDED_WINDOW_STYLES::WS_EX_LEFT, "LEFT" },
{ EXTENDED_WINDOW_STYLES::WS_EX_RTLREADING, "RTLREADING" },
{ EXTENDED_WINDOW_STYLES::WS_EX_LEFTSCROLLBAR, "LEFTSCROLLBAR" },
{ EXTENDED_WINDOW_STYLES::WS_EX_CONTROLPARENT, "CONTROLPARENT" },
{ EXTENDED_WINDOW_STYLES::WS_EX_STATICEDGE, "STATICEDGE" },
{ EXTENDED_WINDOW_STYLES::WS_EX_APPWINDOW, "APPWINDOW" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(WINDOW_STYLES e) {
CONST_MAP(WINDOW_STYLES, const char*, 18) enumStrings {
{ WINDOW_STYLES::WS_OVERLAPPED, "OVERLAPPED" },
{ WINDOW_STYLES::WS_POPUP, "POPUP" },
{ WINDOW_STYLES::WS_CHILD, "CHILD" },
{ WINDOW_STYLES::WS_MINIMIZE, "MINIMIZE" },
{ WINDOW_STYLES::WS_VISIBLE, "VISIBLE" },
{ WINDOW_STYLES::WS_DISABLED, "DISABLED" },
{ WINDOW_STYLES::WS_CLIPSIBLINGS, "CLIPSIBLINGS" },
{ WINDOW_STYLES::WS_CLIPCHILDREN, "CLIPCHILDREN" },
{ WINDOW_STYLES::WS_MAXIMIZE, "MAXIMIZE" },
{ WINDOW_STYLES::WS_CAPTION, "CAPTION" },
{ WINDOW_STYLES::WS_BORDER, "BORDER" },
{ WINDOW_STYLES::WS_DLGFRAME, "DLGFRAME" },
{ WINDOW_STYLES::WS_VSCROLL, "VSCROLL" },
{ WINDOW_STYLES::WS_HSCROLL, "HSCROLL" },
{ WINDOW_STYLES::WS_SYSMENU, "SYSMENU" },
{ WINDOW_STYLES::WS_THICKFRAME, "THICKFRAME" },
{ WINDOW_STYLES::WS_MINIMIZEBOX, "MINIMIZEBOX" },
{ WINDOW_STYLES::WS_MAXIMIZEBOX, "MAXIMIZEBOX" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(DIALOG_BOX_STYLES e) {
CONST_MAP(DIALOG_BOX_STYLES, const char*, 15) enumStrings {
{ DIALOG_BOX_STYLES::DS_ABSALIGN, "ABSALIGN" },
{ DIALOG_BOX_STYLES::DS_SYSMODAL, "SYSMODAL" },
{ DIALOG_BOX_STYLES::DS_LOCALEDIT, "LOCALEDIT" },
{ DIALOG_BOX_STYLES::DS_SETFONT, "SETFONT" },
{ DIALOG_BOX_STYLES::DS_MODALFRAME, "MODALFRAME" },
{ DIALOG_BOX_STYLES::DS_NOIDLEMSG, "NOIDLEMSG" },
{ DIALOG_BOX_STYLES::DS_SETFOREGROUND, "SETFOREGROUND" },
{ DIALOG_BOX_STYLES::DS_3DLOOK, "D3DLOOK" },
{ DIALOG_BOX_STYLES::DS_FIXEDSYS, "FIXEDSYS" },
{ DIALOG_BOX_STYLES::DS_NOFAILCREATE, "NOFAILCREATE" },
{ DIALOG_BOX_STYLES::DS_CONTROL, "CONTROL" },
{ DIALOG_BOX_STYLES::DS_CENTER, "CENTER" },
{ DIALOG_BOX_STYLES::DS_CENTERMOUSE, "CENTERMOUSE" },
{ DIALOG_BOX_STYLES::DS_CONTEXTHELP, "CONTEXTHELP" },
{ DIALOG_BOX_STYLES::DS_SHELLFONT, "SHELLFONT" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(FIXED_VERSION_OS e) {
CONST_MAP(FIXED_VERSION_OS, const char*, 14) enumStrings {
{ FIXED_VERSION_OS::VOS_UNKNOWN, "UNKNOWN" },
{ FIXED_VERSION_OS::VOS_DOS, "DOS" },
{ FIXED_VERSION_OS::VOS_NT, "NT" },
{ FIXED_VERSION_OS::VOS__WINDOWS16, "WINDOWS16" },
{ FIXED_VERSION_OS::VOS__WINDOWS32, "WINDOWS32" },
{ FIXED_VERSION_OS::VOS_OS216, "OS216" },
{ FIXED_VERSION_OS::VOS_OS232, "OS232" },
{ FIXED_VERSION_OS::VOS__PM16, "PM16" },
{ FIXED_VERSION_OS::VOS__PM32, "PM32" },
{ FIXED_VERSION_OS::VOS_DOS_WINDOWS16, "DOS_WINDOWS16" },
{ FIXED_VERSION_OS::VOS_DOS_WINDOWS32, "DOS_WINDOWS32" },
{ FIXED_VERSION_OS::VOS_NT_WINDOWS32, "NT_WINDOWS32" },
{ FIXED_VERSION_OS::VOS_OS216_PM16, "OS216_PM16" },
{ FIXED_VERSION_OS::VOS_OS232_PM32, "OS232_PM32" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(FIXED_VERSION_FILE_FLAGS e) {
CONST_MAP(FIXED_VERSION_FILE_FLAGS, const char*, 6) enumStrings {
{ FIXED_VERSION_FILE_FLAGS::VS_FF_DEBUG, "DEBUG" },
{ FIXED_VERSION_FILE_FLAGS::VS_FF_INFOINFERRED, "INFOINFERRED" },
{ FIXED_VERSION_FILE_FLAGS::VS_FF_PATCHED, "PATCHED" },
{ FIXED_VERSION_FILE_FLAGS::VS_FF_PRERELEASE, "PRERELEASE" },
{ FIXED_VERSION_FILE_FLAGS::VS_FF_PRIVATEBUILD, "PRIVATEBUILD" },
{ FIXED_VERSION_FILE_FLAGS::VS_FF_SPECIALBUILD, "SPECIALBUILD" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(FIXED_VERSION_FILE_TYPES e) {
CONST_MAP(FIXED_VERSION_FILE_TYPES, const char*, 7) enumStrings {
{ FIXED_VERSION_FILE_TYPES::VFT_APP, "APP" },
{ FIXED_VERSION_FILE_TYPES::VFT_DLL, "DLL" },
{ FIXED_VERSION_FILE_TYPES::VFT_DRV, "DRV" },
{ FIXED_VERSION_FILE_TYPES::VFT_FONT, "FONT" },
{ FIXED_VERSION_FILE_TYPES::VFT_STATIC_LIB, "STATIC_LIB" },
{ FIXED_VERSION_FILE_TYPES::VFT_UNKNOWN, "UNKNOWN" },
{ FIXED_VERSION_FILE_TYPES::VFT_VXD, "VXD" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(FIXED_VERSION_FILE_SUB_TYPES e) {
CONST_MAP(FIXED_VERSION_FILE_SUB_TYPES, const char*, 12) enumStrings {
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_COMM, "DRV_COMM" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_DISPLAY, "DRV_DISPLAY" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_INSTALLABLE, "DRV_INSTALLABLE" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_KEYBOARD, "DRV_KEYBOARD" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_LANGUAGE, "DRV_LANGUAGE" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_MOUSE, "DRV_MOUSE" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_NETWORK, "DRV_NETWORK" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_PRINTER, "DRV_PRINTER" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_SOUND, "DRV_SOUND" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_SYSTEM, "DRV_SYSTEM" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_VERSIONED_PRINTER, "DRV_VERSIONED_PRINTER" },
{ FIXED_VERSION_FILE_SUB_TYPES::VFT2_UNKNOWN, "UNKNOWN" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(CODE_PAGES e) {
CONST_MAP(CODE_PAGES, const char*, 140) enumStrings {
{ CODE_PAGES::CP_IBM037, "IBM037"},
{ CODE_PAGES::CP_IBM437, "IBM437"},
{ CODE_PAGES::CP_IBM500, "IBM500"},
{ CODE_PAGES::CP_ASMO_708, "ASMO_708"},
{ CODE_PAGES::CP_DOS_720, "DOS_720"},
{ CODE_PAGES::CP_IBM737, "IBM737"},
{ CODE_PAGES::CP_IBM775, "IBM775"},
{ CODE_PAGES::CP_IBM850, "IBM850"},
{ CODE_PAGES::CP_IBM852, "IBM852"},
{ CODE_PAGES::CP_IBM855, "IBM855"},
{ CODE_PAGES::CP_IBM857, "IBM857"},
{ CODE_PAGES::CP_IBM00858, "IBM00858"},
{ CODE_PAGES::CP_IBM860, "IBM860"},
{ CODE_PAGES::CP_IBM861, "IBM861"},
{ CODE_PAGES::CP_DOS_862, "DOS_862"},
{ CODE_PAGES::CP_IBM863, "IBM863"},
{ CODE_PAGES::CP_IBM864, "IBM864"},
{ CODE_PAGES::CP_IBM865, "IBM865"},
{ CODE_PAGES::CP_CP866, "CP866"},
{ CODE_PAGES::CP_IBM869, "IBM869"},
{ CODE_PAGES::CP_IBM870, "IBM870"},
{ CODE_PAGES::CP_WINDOWS_874, "WINDOWS_874"},
{ CODE_PAGES::CP_CP875, "CP875"},
{ CODE_PAGES::CP_SHIFT_JIS, "SHIFT_JIS"},
{ CODE_PAGES::CP_GB2312, "GB2312"},
{ CODE_PAGES::CP_KS_C_5601_1987, "KS_C_5601_1987"},
{ CODE_PAGES::CP_BIG5, "BIG5"},
{ CODE_PAGES::CP_IBM1026, "IBM1026"},
{ CODE_PAGES::CP_IBM01047, "IBM01047"},
{ CODE_PAGES::CP_IBM01140, "IBM01140"},
{ CODE_PAGES::CP_IBM01141, "IBM01141"},
{ CODE_PAGES::CP_IBM01142, "IBM01142"},
{ CODE_PAGES::CP_IBM01143, "IBM01143"},
{ CODE_PAGES::CP_IBM01144, "IBM01144"},
{ CODE_PAGES::CP_IBM01145, "IBM01145"},
{ CODE_PAGES::CP_IBM01146, "IBM01146"},
{ CODE_PAGES::CP_IBM01147, "IBM01147"},
{ CODE_PAGES::CP_IBM01148, "IBM01148"},
{ CODE_PAGES::CP_IBM01149, "IBM01149"},
{ CODE_PAGES::CP_UTF_16, "UTF_16"},
{ CODE_PAGES::CP_UNICODEFFFE, "UNICODEFFFE"},
{ CODE_PAGES::CP_WINDOWS_1250, "WINDOWS_1250"},
{ CODE_PAGES::CP_WINDOWS_1251, "WINDOWS_1251"},
{ CODE_PAGES::CP_WINDOWS_1252, "WINDOWS_1252"},
{ CODE_PAGES::CP_WINDOWS_1253, "WINDOWS_1253"},
{ CODE_PAGES::CP_WINDOWS_1254, "WINDOWS_1254"},
{ CODE_PAGES::CP_WINDOWS_1255, "WINDOWS_1255"},
{ CODE_PAGES::CP_WINDOWS_1256, "WINDOWS_1256"},
{ CODE_PAGES::CP_WINDOWS_1257, "WINDOWS_1257"},
{ CODE_PAGES::CP_WINDOWS_1258, "WINDOWS_1258"},
{ CODE_PAGES::CP_JOHAB, "JOHAB"},
{ CODE_PAGES::CP_MACINTOSH, "MACINTOSH"},
{ CODE_PAGES::CP_X_MAC_JAPANESE, "X_MAC_JAPANESE"},
{ CODE_PAGES::CP_X_MAC_CHINESETRAD, "X_MAC_CHINESETRAD"},
{ CODE_PAGES::CP_X_MAC_KOREAN, "X_MAC_KOREAN"},
{ CODE_PAGES::CP_X_MAC_ARABIC, "X_MAC_ARABIC"},
{ CODE_PAGES::CP_X_MAC_HEBREW, "X_MAC_HEBREW"},
{ CODE_PAGES::CP_X_MAC_GREEK, "X_MAC_GREEK"},
{ CODE_PAGES::CP_X_MAC_CYRILLIC, "X_MAC_CYRILLIC"},
{ CODE_PAGES::CP_X_MAC_CHINESESIMP, "X_MAC_CHINESESIMP"},
{ CODE_PAGES::CP_X_MAC_ROMANIAN, "X_MAC_ROMANIAN"},
{ CODE_PAGES::CP_X_MAC_UKRAINIAN, "X_MAC_UKRAINIAN"},
{ CODE_PAGES::CP_X_MAC_THAI, "X_MAC_THAI"},
{ CODE_PAGES::CP_X_MAC_CE, "X_MAC_CE"},
{ CODE_PAGES::CP_X_MAC_ICELANDIC, "X_MAC_ICELANDIC"},
{ CODE_PAGES::CP_X_MAC_TURKISH, "X_MAC_TURKISH"},
{ CODE_PAGES::CP_X_MAC_CROATIAN, "X_MAC_CROATIAN"},
{ CODE_PAGES::CP_UTF_32, "UTF_32"},
{ CODE_PAGES::CP_UTF_32BE, "UTF_32BE"},
{ CODE_PAGES::CP_X_CHINESE_CNS, "X_CHINESE_CNS"},
{ CODE_PAGES::CP_X_CP20001, "X_CP20001"},
{ CODE_PAGES::CP_X_CHINESE_ETEN, "X_CHINESE_ETEN"},
{ CODE_PAGES::CP_X_CP20003, "X_CP20003"},
{ CODE_PAGES::CP_X_CP20004, "X_CP20004"},
{ CODE_PAGES::CP_X_CP20005, "X_CP20005"},
{ CODE_PAGES::CP_X_IA5, "X_IA5"},
{ CODE_PAGES::CP_X_IA5_GERMAN, "X_IA5_GERMAN"},
{ CODE_PAGES::CP_X_IA5_SWEDISH, "X_IA5_SWEDISH"},
{ CODE_PAGES::CP_X_IA5_NORWEGIAN, "X_IA5_NORWEGIAN"},
{ CODE_PAGES::CP_US_ASCII, "US_ASCII"},
{ CODE_PAGES::CP_X_CP20261, "X_CP20261"},
{ CODE_PAGES::CP_X_CP20269, "X_CP20269"},
{ CODE_PAGES::CP_IBM273, "IBM273"},
{ CODE_PAGES::CP_IBM277, "IBM277"},
{ CODE_PAGES::CP_IBM278, "IBM278"},
{ CODE_PAGES::CP_IBM280, "IBM280"},
{ CODE_PAGES::CP_IBM284, "IBM284"},
{ CODE_PAGES::CP_IBM285, "IBM285"},
{ CODE_PAGES::CP_IBM290, "IBM290"},
{ CODE_PAGES::CP_IBM297, "IBM297"},
{ CODE_PAGES::CP_IBM420, "IBM420"},
{ CODE_PAGES::CP_IBM423, "IBM423"},
{ CODE_PAGES::CP_IBM424, "IBM424"},
{ CODE_PAGES::CP_X_EBCDIC_KOREANEXTENDED, "X_EBCDIC_KOREANEXTENDED"},
{ CODE_PAGES::CP_IBM_THAI, "IBM_THAI"},
{ CODE_PAGES::CP_KOI8_R, "KOI8_R"},
{ CODE_PAGES::CP_IBM871, "IBM871"},
{ CODE_PAGES::CP_IBM880, "IBM880"},
{ CODE_PAGES::CP_IBM905, "IBM905"},
{ CODE_PAGES::CP_IBM00924, "IBM00924"},
{ CODE_PAGES::CP_EUC_JP_JIS, "EUC_JP_JIS"},
{ CODE_PAGES::CP_X_CP20936, "X_CP20936"},
{ CODE_PAGES::CP_X_CP20949, "X_CP20949"},
{ CODE_PAGES::CP_CP1025, "CP1025"},
{ CODE_PAGES::CP_KOI8_U, "KOI8_U"},
{ CODE_PAGES::CP_ISO_8859_1, "ISO_8859_1"},
{ CODE_PAGES::CP_ISO_8859_2, "ISO_8859_2"},
{ CODE_PAGES::CP_ISO_8859_3, "ISO_8859_3"},
{ CODE_PAGES::CP_ISO_8859_4, "ISO_8859_4"},
{ CODE_PAGES::CP_ISO_8859_5, "ISO_8859_5"},
{ CODE_PAGES::CP_ISO_8859_6, "ISO_8859_6"},
{ CODE_PAGES::CP_ISO_8859_7, "ISO_8859_7"},
{ CODE_PAGES::CP_ISO_8859_8, "ISO_8859_8"},
{ CODE_PAGES::CP_ISO_8859_9, "ISO_8859_9"},
{ CODE_PAGES::CP_ISO_8859_13, "ISO_8859_13"},
{ CODE_PAGES::CP_ISO_8859_15, "ISO_8859_15"},
{ CODE_PAGES::CP_X_EUROPA, "X_EUROPA"},
{ CODE_PAGES::CP_ISO_8859_8_I, "ISO_8859_8_I"},
{ CODE_PAGES::CP_ISO_2022_JP, "ISO_2022_JP"},
{ CODE_PAGES::CP_CSISO2022JP, "CSISO2022JP"},
{ CODE_PAGES::CP_ISO_2022_JP_JIS, "ISO_2022_JP_JIS"},
{ CODE_PAGES::CP_ISO_2022_KR, "ISO_2022_KR"},
{ CODE_PAGES::CP_X_CP50227, "X_CP50227"},
{ CODE_PAGES::CP_EUC_JP, "EUC_JP"},
{ CODE_PAGES::CP_EUC_CN, "EUC_CN"},
{ CODE_PAGES::CP_EUC_KR, "EUC_KR"},
{ CODE_PAGES::CP_HZ_GB_2312, "HZ_GB_2312"},
{ CODE_PAGES::CP_GB18030, "GB18030"},
{ CODE_PAGES::CP_X_ISCII_DE, "X_ISCII_DE"},
{ CODE_PAGES::CP_X_ISCII_BE, "X_ISCII_BE"},
{ CODE_PAGES::CP_X_ISCII_TA, "X_ISCII_TA"},
{ CODE_PAGES::CP_X_ISCII_TE, "X_ISCII_TE"},
{ CODE_PAGES::CP_X_ISCII_AS, "X_ISCII_AS"},
{ CODE_PAGES::CP_X_ISCII_OR, "X_ISCII_OR"},
{ CODE_PAGES::CP_X_ISCII_KA, "X_ISCII_KA"},
{ CODE_PAGES::CP_X_ISCII_MA, "X_ISCII_MA"},
{ CODE_PAGES::CP_X_ISCII_GU, "X_ISCII_GU"},
{ CODE_PAGES::CP_X_ISCII_PA, "X_ISCII_PA"},
{ CODE_PAGES::CP_UTF_7, "UTF_7"},
{ CODE_PAGES::CP_UTF_8, "UTF_8"},
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(WIN_VERSION e) {
CONST_MAP(WIN_VERSION, const char*, 9) enumStrings {
{ WIN_VERSION::WIN_UNKNOWN, "UNKNOWN" },
{ WIN_VERSION::WIN_SEH, "SEH" },
{ WIN_VERSION::WIN8_1, "WIN_8_1" },
{ WIN_VERSION::WIN10_0_9879, "WIN10_0_9879" },
{ WIN_VERSION::WIN10_0_14286, "WIN10_0_14286" },
{ WIN_VERSION::WIN10_0_14383, "WIN10_0_14383" },
{ WIN_VERSION::WIN10_0_14901, "WIN10_0_14901" },
{ WIN_VERSION::WIN10_0_15002, "WIN10_0_15002" },
{ WIN_VERSION::WIN10_0_16237, "WIN10_0_16237" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(GUARD_CF_FLAGS e) {
CONST_MAP(GUARD_CF_FLAGS, const char*, 10) enumStrings {
{ GUARD_CF_FLAGS::GCF_NONE, "GCF_NONE" },
{ GUARD_CF_FLAGS::GCF_INSTRUMENTED, "GCF_INSTRUMENTED" },
{ GUARD_CF_FLAGS::GCF_W_INSTRUMENTED, "GCF_W_INSTRUMENTED" },
{ GUARD_CF_FLAGS::GCF_FUNCTION_TABLE_PRESENT, "GCF_FUNCTION_TABLE_PRESENT" },
{ GUARD_CF_FLAGS::GCF_EXPORT_SUPPRESSION_INFO_PRESENT, "GCF_EXPORT_SUPPRESSION_INFO_PRESENT" },
{ GUARD_CF_FLAGS::GCF_ENABLE_EXPORT_SUPPRESSION, "GCF_ENABLE_EXPORT_SUPPRESSION" },
{ GUARD_CF_FLAGS::GCF_LONGJUMP_TABLE_PRESENT, "GCF_LONGJUMP_TABLE_PRESENT" },
{ GUARD_CF_FLAGS::GRF_INSTRUMENTED, "GRF_INSTRUMENTED" },
{ GUARD_CF_FLAGS::GRF_ENABLE, "GRF_ENABLE" },
{ GUARD_CF_FLAGS::GRF_STRICT, "GRF_STRICT" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(CODE_VIEW_SIGNATURES e) {
CONST_MAP(CODE_VIEW_SIGNATURES, const char*, 5) enumStrings {
{ CODE_VIEW_SIGNATURES::CVS_UNKNOWN, "UNKNOWN" },
{ CODE_VIEW_SIGNATURES::CVS_PDB_70, "PDB_70" },
{ CODE_VIEW_SIGNATURES::CVS_PDB_20, "PDB_20" },
{ CODE_VIEW_SIGNATURES::CVS_CV_50, "CV_50" },
{ CODE_VIEW_SIGNATURES::CVS_CV_41, "CV_41" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? to_string(CODE_VIEW_SIGNATURES::CVS_UNKNOWN) : it->second;
}
const char* to_string(POGO_SIGNATURES e) {
CONST_MAP(POGO_SIGNATURES, const char*, 3) enumStrings {
{ POGO_SIGNATURES::POGO_UNKNOWN, "UNKNOWN" },
{ POGO_SIGNATURES::POGO_LCTG, "LCTG" },
{ POGO_SIGNATURES::POGO_PGI, "PGI" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? to_string(POGO_SIGNATURES::POGO_UNKNOWN) : it->second;
}
const char* to_string(ACCELERATOR_FLAGS e) {
CONST_MAP(ACCELERATOR_FLAGS, const char*, 6) enumStrings {
{ ACCELERATOR_FLAGS::FVIRTKEY, "FVIRTKEY" },
{ ACCELERATOR_FLAGS::FNOINVERT, "FNOINVERT" },
{ ACCELERATOR_FLAGS::FSHIFT, "FSHIFT" },
{ ACCELERATOR_FLAGS::FCONTROL, "FCONTROL" },
{ ACCELERATOR_FLAGS::FALT, "FALT" },
{ ACCELERATOR_FLAGS::END, "END" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "Out of range" : it->second;
}
const char* to_string(ACCELERATOR_VK_CODES e) {
CONST_MAP(ACCELERATOR_VK_CODES, const char*, 174) enumStrings {
{ ACCELERATOR_VK_CODES::VK_LBUTTON, "VK_LBUTTON" },
{ ACCELERATOR_VK_CODES::VK_RBUTTON, "VK_RBUTTON" },
{ ACCELERATOR_VK_CODES::VK_CANCEL, "VK_CANCEL" },
{ ACCELERATOR_VK_CODES::VK_MBUTTON, "VK_MBUTTON" },
{ ACCELERATOR_VK_CODES::VK_XBUTTON1, "VK_XBUTTON1" },
{ ACCELERATOR_VK_CODES::VK_XBUTTON2, "VK_XBUTTON2" },
{ ACCELERATOR_VK_CODES::VK_BACK, "VK_BACK" },
{ ACCELERATOR_VK_CODES::VK_TAB, "VK_TAB" },
{ ACCELERATOR_VK_CODES::VK_CLEAR, "VK_CLEAR" },
{ ACCELERATOR_VK_CODES::VK_RETURN, "VK_RETURN" },
{ ACCELERATOR_VK_CODES::VK_SHIFT, "VK_SHIFT" },
{ ACCELERATOR_VK_CODES::VK_CONTROL, "VK_CONTROL" },
{ ACCELERATOR_VK_CODES::VK_MENU, "VK_MENU" },
{ ACCELERATOR_VK_CODES::VK_PAUSE, "VK_PAUSE" },
{ ACCELERATOR_VK_CODES::VK_CAPITAL, "VK_CAPITAL" },
{ ACCELERATOR_VK_CODES::VK_KANA, "VK_KANA" },
{ ACCELERATOR_VK_CODES::VK_HANGUEL, "VK_HANGUEL" },
{ ACCELERATOR_VK_CODES::VK_HANGUL, "VK_HANGUL" },
{ ACCELERATOR_VK_CODES::VK_IME_ON, "VK_IME_ON" },
{ ACCELERATOR_VK_CODES::VK_JUNJA, "VK_JUNJA" },
{ ACCELERATOR_VK_CODES::VK_FINAL, "VK_FINAL" },
{ ACCELERATOR_VK_CODES::VK_HANJA, "VK_HANJA" },
{ ACCELERATOR_VK_CODES::VK_KANJI, "VK_KANJI" },
{ ACCELERATOR_VK_CODES::VK_IME_OFF, "VK_IME_OFF" },
{ ACCELERATOR_VK_CODES::VK_ESCAPE, "VK_ESCAPE" },
{ ACCELERATOR_VK_CODES::VK_CONVERT, "VK_CONVERT" },
{ ACCELERATOR_VK_CODES::VK_NONCONVERT, "VK_NONCONVERT" },
{ ACCELERATOR_VK_CODES::VK_ACCEPT, "VK_ACCEPT" },
{ ACCELERATOR_VK_CODES::VK_MODECHANGE, "VK_MODECHANGE" },
{ ACCELERATOR_VK_CODES::VK_SPACE, "VK_SPACE" },
{ ACCELERATOR_VK_CODES::VK_PRIOR, "VK_PRIOR" },
{ ACCELERATOR_VK_CODES::VK_NEXT, "VK_NEXT" },
{ ACCELERATOR_VK_CODES::VK_END, "VK_END" },
{ ACCELERATOR_VK_CODES::VK_HOME, "VK_HOME" },
{ ACCELERATOR_VK_CODES::VK_LEFT, "VK_LEFT" },
{ ACCELERATOR_VK_CODES::VK_UP, "VK_UP" },
{ ACCELERATOR_VK_CODES::VK_RIGHT, "VK_RIGHT" },
{ ACCELERATOR_VK_CODES::VK_DOWN, "VK_DOWN" },
{ ACCELERATOR_VK_CODES::VK_SELECT, "VK_SELECT" },
{ ACCELERATOR_VK_CODES::VK_PRINT, "VK_PRINT" },
{ ACCELERATOR_VK_CODES::VK_EXECUTE, "VK_EXECUTE" },
{ ACCELERATOR_VK_CODES::VK_SNAPSHOT, "VK_SNAPSHOT" },
{ ACCELERATOR_VK_CODES::VK_INSERT, "VK_INSERT" },
{ ACCELERATOR_VK_CODES::VK_DELETE, "VK_DELETE" },
{ ACCELERATOR_VK_CODES::VK_HELP, "VK_HELP" },
{ ACCELERATOR_VK_CODES::VK_0, "VK_0" },
{ ACCELERATOR_VK_CODES::VK_1, "VK_1" },
{ ACCELERATOR_VK_CODES::VK_2, "VK_2" },
{ ACCELERATOR_VK_CODES::VK_3, "VK_3" },
{ ACCELERATOR_VK_CODES::VK_4, "VK_4" },
{ ACCELERATOR_VK_CODES::VK_5, "VK_5" },
{ ACCELERATOR_VK_CODES::VK_6, "VK_6" },
{ ACCELERATOR_VK_CODES::VK_7, "VK_7" },
{ ACCELERATOR_VK_CODES::VK_8, "VK_8" },
{ ACCELERATOR_VK_CODES::VK_9, "VK_9" },
{ ACCELERATOR_VK_CODES::VK_A, "VK_A" },
{ ACCELERATOR_VK_CODES::VK_B, "VK_B" },
{ ACCELERATOR_VK_CODES::VK_C, "VK_C" },
{ ACCELERATOR_VK_CODES::VK_D, "VK_D" },
{ ACCELERATOR_VK_CODES::VK_E, "VK_E" },
{ ACCELERATOR_VK_CODES::VK_F, "VK_F" },
{ ACCELERATOR_VK_CODES::VK_G, "VK_G" },
{ ACCELERATOR_VK_CODES::VK_H, "VK_H" },
{ ACCELERATOR_VK_CODES::VK_I, "VK_I" },
{ ACCELERATOR_VK_CODES::VK_J, "VK_J" },
{ ACCELERATOR_VK_CODES::VK_K, "VK_K" },
{ ACCELERATOR_VK_CODES::VK_L, "VK_L" },
{ ACCELERATOR_VK_CODES::VK_M, "VK_M" },
{ ACCELERATOR_VK_CODES::VK_N, "VK_N" },
{ ACCELERATOR_VK_CODES::VK_O, "VK_O" },
{ ACCELERATOR_VK_CODES::VK_P, "VK_P" },
{ ACCELERATOR_VK_CODES::VK_Q, "VK_Q" },
{ ACCELERATOR_VK_CODES::VK_R, "VK_R" },
{ ACCELERATOR_VK_CODES::VK_S, "VK_S" },
{ ACCELERATOR_VK_CODES::VK_T, "VK_T" },
{ ACCELERATOR_VK_CODES::VK_U, "VK_U" },
{ ACCELERATOR_VK_CODES::VK_V, "VK_V" },
{ ACCELERATOR_VK_CODES::VK_W, "VK_W" },
{ ACCELERATOR_VK_CODES::VK_X, "VK_X" },
{ ACCELERATOR_VK_CODES::VK_Y, "VK_Y" },
{ ACCELERATOR_VK_CODES::VK_Z, "VK_Z" },
{ ACCELERATOR_VK_CODES::VK_LWIN, "VK_LWIN" },
{ ACCELERATOR_VK_CODES::VK_RWIN, "VK_RWIN" },
{ ACCELERATOR_VK_CODES::VK_APPS, "VK_APPS" },
{ ACCELERATOR_VK_CODES::VK_SLEEP, "VK_SLEEP" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD0, "VK_NUMPAD0" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD1, "VK_NUMPAD1" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD2, "VK_NUMPAD2" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD3, "VK_NUMPAD3" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD4, "VK_NUMPAD4" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD5, "VK_NUMPAD5" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD6, "VK_NUMPAD6" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD7, "VK_NUMPAD7" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD8, "VK_NUMPAD8" },
{ ACCELERATOR_VK_CODES::VK_NUMPAD9, "VK_NUMPAD9" },
{ ACCELERATOR_VK_CODES::VK_MULTIPLY, "VK_MULTIPLY" },
{ ACCELERATOR_VK_CODES::VK_ADD, "VK_ADD" },
{ ACCELERATOR_VK_CODES::VK_SEPARATOR, "VK_SEPARATOR" },
{ ACCELERATOR_VK_CODES::VK_SUBTRACT, "VK_SUBTRACT" },
{ ACCELERATOR_VK_CODES::VK_DECIMAL, "VK_DECIMAL" },
{ ACCELERATOR_VK_CODES::VK_DIVIDE, "VK_DIVIDE" },
{ ACCELERATOR_VK_CODES::VK_F1, "VK_F1" },
{ ACCELERATOR_VK_CODES::VK_F2, "VK_F2" },
{ ACCELERATOR_VK_CODES::VK_F3, "VK_F3" },
{ ACCELERATOR_VK_CODES::VK_F4, "VK_F4" },
{ ACCELERATOR_VK_CODES::VK_F5, "VK_F5" },
{ ACCELERATOR_VK_CODES::VK_F6, "VK_F6" },
{ ACCELERATOR_VK_CODES::VK_F7, "VK_F7" },
{ ACCELERATOR_VK_CODES::VK_F8, "VK_F8" },
{ ACCELERATOR_VK_CODES::VK_F9, "VK_F9" },
{ ACCELERATOR_VK_CODES::VK_F10, "VK_F10" },
{ ACCELERATOR_VK_CODES::VK_F11, "VK_F11" },
{ ACCELERATOR_VK_CODES::VK_F12, "VK_F12" },
{ ACCELERATOR_VK_CODES::VK_F13, "VK_F13" },
{ ACCELERATOR_VK_CODES::VK_F14, "VK_F14" },
{ ACCELERATOR_VK_CODES::VK_F15, "VK_F15" },
{ ACCELERATOR_VK_CODES::VK_F16, "VK_F16" },
{ ACCELERATOR_VK_CODES::VK_F17, "VK_F17" },
{ ACCELERATOR_VK_CODES::VK_F18, "VK_F18" },
{ ACCELERATOR_VK_CODES::VK_F19, "VK_F19" },
{ ACCELERATOR_VK_CODES::VK_F20, "VK_F20" },
{ ACCELERATOR_VK_CODES::VK_F21, "VK_F21" },
{ ACCELERATOR_VK_CODES::VK_F22, "VK_F22" },
{ ACCELERATOR_VK_CODES::VK_F23, "VK_F23" },
{ ACCELERATOR_VK_CODES::VK_F24, "VK_F24" },
{ ACCELERATOR_VK_CODES::VK_NUMLOCK, "VK_NUMLOCK" },
{ ACCELERATOR_VK_CODES::VK_SCROLL, "VK_SCROLL" },
{ ACCELERATOR_VK_CODES::VK_LSHIFT, "VK_LSHIFT" },
{ ACCELERATOR_VK_CODES::VK_RSHIFT, "VK_RSHIFT" },
{ ACCELERATOR_VK_CODES::VK_LCONTROL, "VK_LCONTROL" },
{ ACCELERATOR_VK_CODES::VK_RCONTROL, "VK_RCONTROL" },
{ ACCELERATOR_VK_CODES::VK_LMENU, "VK_LMENU" },
{ ACCELERATOR_VK_CODES::VK_RMENU, "VK_RMENU" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_BACK, "VK_BROWSER_BACK" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_FORWARD, "VK_BROWSER_FORWARD" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_REFRESH, "VK_BROWSER_REFRESH" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_STOP, "VK_BROWSER_STOP" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_SEARCH, "VK_BROWSER_SEARCH" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_FAVORITES, "VK_BROWSER_FAVORITES" },
{ ACCELERATOR_VK_CODES::VK_BROWSER_HOME, "VK_BROWSER_HOME" },
{ ACCELERATOR_VK_CODES::VK_VOLUME_MUTE, "VK_VOLUME_MUTE" },
{ ACCELERATOR_VK_CODES::VK_VOLUME_DOWN, "VK_VOLUME_DOWN" },
{ ACCELERATOR_VK_CODES::VK_VOLUME_UP, "VK_VOLUME_UP" },
{ ACCELERATOR_VK_CODES::VK_MEDIA_NEXT_TRACK, "VK_MEDIA_NEXT_TRACK" },
{ ACCELERATOR_VK_CODES::VK_MEDIA_PREV_TRACK, "VK_MEDIA_PREV_TRACK" },
{ ACCELERATOR_VK_CODES::VK_MEDIA_STOP, "VK_MEDIA_STOP" },
{ ACCELERATOR_VK_CODES::VK_MEDIA_PLAY_PAUSE, "VK_MEDIA_PLAY_PAUSE" },
{ ACCELERATOR_VK_CODES::VK_LAUNCH_MAIL, "VK_LAUNCH_MAIL" },
{ ACCELERATOR_VK_CODES::VK_LAUNCH_MEDIA_SELECT, "VK_LAUNCH_MEDIA_SELECT" },
{ ACCELERATOR_VK_CODES::VK_LAUNCH_APP1, "VK_LAUNCH_APP1" },
{ ACCELERATOR_VK_CODES::VK_LAUNCH_APP2, "VK_LAUNCH_APP2" },
{ ACCELERATOR_VK_CODES::VK_OEM_1, "VK_OEM_1" },
{ ACCELERATOR_VK_CODES::VK_OEM_PLUS, "VK_OEM_PLUS" },
{ ACCELERATOR_VK_CODES::VK_OEM_COMMA, "VK_OEM_COMMA" },
{ ACCELERATOR_VK_CODES::VK_OEM_MINUS, "VK_OEM_MINUS" },
{ ACCELERATOR_VK_CODES::VK_OEM_PERIOD, "VK_OEM_PERIOD" },
{ ACCELERATOR_VK_CODES::VK_OEM_2, "VK_OEM_2" },
{ ACCELERATOR_VK_CODES::VK_OEM_4, "VK_OEM_4" },
{ ACCELERATOR_VK_CODES::VK_OEM_5, "VK_OEM_5" },
{ ACCELERATOR_VK_CODES::VK_OEM_6, "VK_OEM_6" },
{ ACCELERATOR_VK_CODES::VK_OEM_7, "VK_OEM_7" },
{ ACCELERATOR_VK_CODES::VK_OEM_8, "VK_OEM_8" },
{ ACCELERATOR_VK_CODES::VK_OEM_102, "VK_OEM_102" },
{ ACCELERATOR_VK_CODES::VK_PROCESSKEY, "VK_PROCESSKEY" },
{ ACCELERATOR_VK_CODES::VK_PACKET, "VK_PACKET" },
{ ACCELERATOR_VK_CODES::VK_ATTN, "VK_ATTN" },
{ ACCELERATOR_VK_CODES::VK_CRSEL, "VK_CRSEL" },
{ ACCELERATOR_VK_CODES::VK_EXSEL, "VK_EXSEL" },
{ ACCELERATOR_VK_CODES::VK_EREOF, "VK_EREOF" },
{ ACCELERATOR_VK_CODES::VK_PLAY, "VK_PLAY" },
{ ACCELERATOR_VK_CODES::VK_ZOOM, "VK_ZOOM" },
{ ACCELERATOR_VK_CODES::VK_NONAME, "VK_NONAME" },
{ ACCELERATOR_VK_CODES::VK_PA1, "VK_PA1" },
{ ACCELERATOR_VK_CODES::VK_OEM_CLEAR, "VK_OEM_CLEAR" },
};
auto it = enumStrings.find(e);
return it != enumStrings.end() ? it->second : "Undefined or reserved";
}
const char* to_string(ALGORITHMS e) {
CONST_MAP(ALGORITHMS, const char*, 20) enumStrings {
{ ALGORITHMS::UNKNOWN, "UNKNOWN" },
{ ALGORITHMS::SHA_512, "SHA_512" },
{ ALGORITHMS::SHA_384, "SHA_384" },
{ ALGORITHMS::SHA_256, "SHA_256" },
{ ALGORITHMS::SHA_1, "SHA_1" },
{ ALGORITHMS::MD5, "MD5" },
{ ALGORITHMS::MD4, "MD4" },
{ ALGORITHMS::MD2, "MD2" },
{ ALGORITHMS::RSA, "RSA" },
{ ALGORITHMS::EC, "EC" },
{ ALGORITHMS::MD5_RSA, "MD5_RSA" },
{ ALGORITHMS::SHA1_DSA, "SHA1_DSA" },
{ ALGORITHMS::SHA1_RSA, "SHA1_RSA" },
{ ALGORITHMS::SHA_256_RSA, "SHA_256_RSA" },
{ ALGORITHMS::SHA_384_RSA, "SHA_384_RSA" },
{ ALGORITHMS::SHA_512_RSA, "SHA_512_RSA" },
{ ALGORITHMS::SHA1_ECDSA, "SHA1_ECDSA" },
{ ALGORITHMS::SHA_256_ECDSA, "SHA_256_ECDSA" },
{ ALGORITHMS::SHA_384_ECDSA, "SHA_384_ECDSA" },
{ ALGORITHMS::SHA_512_ECDSA, "SHA_512_ECDSA" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "UNKNOWN" : it->second;
}
const char* to_string(SIG_ATTRIBUTE_TYPES e) {
CONST_MAP(SIG_ATTRIBUTE_TYPES, const char*, 11) enumStrings {
{ SIG_ATTRIBUTE_TYPES::UNKNOWN, "UNKNOWN" },
{ SIG_ATTRIBUTE_TYPES::CONTENT_TYPE, "CONTENT_TYPE" },
{ SIG_ATTRIBUTE_TYPES::GENERIC_TYPE, "GENERIC_TYPE" },
{ SIG_ATTRIBUTE_TYPES::SPC_SP_OPUS_INFO, "SPC_SP_OPUS_INFO" },
{ SIG_ATTRIBUTE_TYPES::MS_COUNTER_SIGN, "MS_COUNTER_SIGN" },
{ SIG_ATTRIBUTE_TYPES::MS_SPC_NESTED_SIGN, "MS_SPC_NESTED_SIGN" },
{ SIG_ATTRIBUTE_TYPES::MS_SPC_STATEMENT_TYPE, "MS_SPC_STATEMENT_TYPE" },
{ SIG_ATTRIBUTE_TYPES::PKCS9_AT_SEQUENCE_NUMBER, "PKCS9_AT_SEQUENCE_NUMBER" },
{ SIG_ATTRIBUTE_TYPES::PKCS9_COUNTER_SIGNATURE, "PKCS9_COUNTER_SIGNATURE" },
{ SIG_ATTRIBUTE_TYPES::PKCS9_MESSAGE_DIGEST, "PKCS9_MESSAGE_DIGEST" },
{ SIG_ATTRIBUTE_TYPES::PKCS9_SIGNING_TIME, "PKCS9_SIGNING_TIME" },
};
auto it = enumStrings.find(e);
return it == enumStrings.end() ? "UNKNOWN" : it->second;
}
} // namespace PE
} // namespace LIEF
| 59.92092 | 117 | 0.623863 | junghee |
33a1533625818e7d82b92ebf0eadfb77d6937f29 | 3,749 | cpp | C++ | TabGraph/src/Driver/OpenGL/Renderer/Light/PointLightRenderer.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-08-28T09:35:18.000Z | 2020-08-28T09:35:18.000Z | TabGraph/src/Driver/OpenGL/Renderer/Light/PointLightRenderer.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | null | null | null | TabGraph/src/Driver/OpenGL/Renderer/Light/PointLightRenderer.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-10-08T11:21:13.000Z | 2020-10-08T11:21:13.000Z | /*
* @Author: gpinchon
* @Date: 2021-04-11 20:53:00
* @Last Modified by: gpinchon
* @Last Modified time: 2021-04-11 20:53:22
*/
#include <Driver/OpenGL/Renderer/Light/PointLightRenderer.hpp>
#include <Light/PointLight.hpp>
#include <Surface/SphereMesh.hpp>
#include <Renderer/Surface/GeometryRenderer.hpp>
#include <Renderer/Renderer.hpp>
#include <Shader/Program.hpp>
#include <Shader/Stage.hpp>
#include <Texture/Framebuffer.hpp>
#include <Texture/Texture2D.hpp>
#include <GL/glew.h>
namespace Renderer {
static inline auto PointLightGeometry()
{
static std::weak_ptr<Geometry> s_geometry;
auto geometryPtr = s_geometry.lock();
if (geometryPtr == nullptr) {
geometryPtr = SphereMesh::CreateGeometry("PointLightGeometry", 1, 1);
s_geometry = geometryPtr;
}
return geometryPtr;
}
static inline auto PointLightVertexCode()
{
auto deferred_vert_code =
#include "deferred.vert"
;
auto lightVertexCode =
#include "Lights/TransformGeometry.vert"
;
Shader::Stage::Code shaderCode = Shader::Stage::Code{ lightVertexCode, "TransformGeometry();" };
return shaderCode;
}
static inline auto PointLightFragmentCode()
{
auto deferred_frag_code =
#include "deferred.frag"
;
auto lightFragmentShader =
#include "Lights/DeferredPointLight.frag"
;
Shader::Stage::Code shaderCode =
Shader::Stage::Code{ deferred_frag_code, "FillFragmentData();" } +
Shader::Stage::Code{ lightFragmentShader, "Lighting();" };
return shaderCode;
}
static inline auto PointLightShader()
{
auto shader = Component::Create<Shader::Program>("PointLightShader");
shader->SetDefine("Pass", "DeferredLighting");
shader->Attach(Shader::Stage(Shader::Stage::Type::Fragment, PointLightFragmentCode()));
shader->Attach(Shader::Stage(Shader::Stage::Type::Vertex, PointLightVertexCode()));
return shader;
}
PointLightRenderer::PointLightRenderer(PointLight &light)
: LightRenderer(light)
{
_deferredShader = PointLightShader();
_deferredGeometry = PointLightGeometry();
}
void PointLightRenderer::Render(const Renderer::Options& options)
{
if (options.pass == Renderer::Options::Pass::DeferredLighting)
_RenderDeferredLighting(static_cast<PointLight&>(_light), options);
else if (options.pass == Renderer::Options::Pass::ShadowDepth)
_RenderShadow(static_cast<PointLight&>(_light), options);
}
void PointLightRenderer::UpdateLightProbe(const Renderer::Options&, LightProbe&)
{
}
void PointLightRenderer::_RenderDeferredLighting(PointLight& light, const Renderer::Options& options)
{
auto geometryBuffer = options.renderer->DeferredGeometryBuffer();
_deferredShader->Use()
.SetUniform("Light.DiffuseFactor", light.GetDiffuseFactor())
.SetUniform("Light.SpecularFactor", light.GetSpecularFactor())
.SetUniform("Light.Power", light.GetPower())
.SetUniform("Light.Radius", light.GetRadius())
.SetUniform("Light.Color", light.GetColor())
.SetUniform("Light.Position", light.WorldPosition())
.SetUniform("GeometryMatrix", light.WorldTranslationMatrix() * glm::scale(glm::vec3(light.GetRadius())))
.SetTexture("Texture.Geometry.F0", geometryBuffer->GetColorBuffer(1))
.SetTexture("Texture.Geometry.Normal", geometryBuffer->GetColorBuffer(2))
.SetTexture("Texture.Geometry.Depth", geometryBuffer->GetDepthBuffer());
glCullFace(GL_FRONT);
Renderer::Render(_deferredGeometry);
glCullFace(GL_BACK);
_deferredShader->Done();
}
void PointLightRenderer::_RenderShadow(PointLight&, const Renderer::Options&)
{
}
} | 34.081818 | 113 | 0.696452 | Gpinchon |
33a81c2af4a95b2a563fb7c3d993bbd10e9e2c52 | 6,236 | cpp | C++ | libs/StateSync-pinvoke-cpp/src/ReplicatedState-pinvoke.cpp | ivte-ms/MixedReality-Sharing | edb38467be6dcd09447962a3c1f998fe700b8832 | [
"MIT"
] | 24 | 2019-12-11T18:56:39.000Z | 2021-12-28T02:48:59.000Z | libs/StateSync-pinvoke-cpp/src/ReplicatedState-pinvoke.cpp | ivte-ms/MixedReality-Sharing | edb38467be6dcd09447962a3c1f998fe700b8832 | [
"MIT"
] | 23 | 2019-12-11T20:21:30.000Z | 2020-02-12T12:12:05.000Z | libs/StateSync-pinvoke-cpp/src/ReplicatedState-pinvoke.cpp | ivte-ms/MixedReality-Sharing | edb38467be6dcd09447962a3c1f998fe700b8832 | [
"MIT"
] | 14 | 2019-12-11T18:56:44.000Z | 2021-06-09T18:13:10.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "src/pch.h"
#include <Microsoft/MixedReality/Sharing/StateSync/NetworkConnection.h>
#include <Microsoft/MixedReality/Sharing/StateSync/NetworkListener.h>
#include <Microsoft/MixedReality/Sharing/StateSync/NetworkManager.h>
#include <Microsoft/MixedReality/Sharing/StateSync/ReplicatedState.h>
#include <Microsoft/MixedReality/Sharing/StateSync/export.h>
#include <Microsoft/MixedReality/Sharing/Common/bit_cast.h>
using namespace Microsoft::MixedReality::Sharing;
using namespace Microsoft::MixedReality::Sharing::StateSync;
namespace {
class PInvokeNetworkManager;
using ReleaseGCHandleDelegate = void(__stdcall*)(intptr_t gc_handle);
using GetConnectionDelegate =
void(__stdcall*)(intptr_t connection_string_blob,
intptr_t manager_gc_handle,
PInvokeNetworkManager* pinvoke_network_manager,
std::shared_ptr<NetworkConnection>* result_location);
using PollMessageDelegate = bool(__stdcall*)(intptr_t manager_gc_handle,
void* listener);
using SendMessageDelegate = intptr_t(__stdcall*)(intptr_t connection_gc_handle,
const char* message_begin,
int message_size);
class PInvokeNetworkManager : public NetworkManager {
public:
PInvokeNetworkManager(intptr_t manager_gc_handle,
ReleaseGCHandleDelegate release_gc_handle_delegate,
GetConnectionDelegate get_connection_delegate,
PollMessageDelegate poll_message_delegate,
SendMessageDelegate send_message_delegate)
: manager_gc_handle_{manager_gc_handle},
release_gc_handle_delegate_{release_gc_handle_delegate},
get_connection_delegate_{get_connection_delegate},
poll_message_delegate_{poll_message_delegate},
send_message_delegate_{send_message_delegate} {}
~PInvokeNetworkManager() noexcept override {
release_gc_handle_delegate_(manager_gc_handle_);
}
std::shared_ptr<NetworkConnection> GetConnection(
const InternedBlob& connection_string) override;
bool PollMessage(NetworkListener& listener) override {
return poll_message_delegate_(manager_gc_handle_, &listener);
}
std::shared_ptr<NetworkConnection> CreateConnectionWrapper(
const InternedBlob& connection_string,
intptr_t connection_handle) {
return std::make_shared<Connection>(&connection_string, this,
connection_handle);
}
private:
class Connection : public NetworkConnection {
public:
Connection(RefPtr<const InternedBlob> connection_string,
RefPtr<PInvokeNetworkManager> manager,
intptr_t connection_handle);
~Connection() noexcept override;
void SendMessage(std::string_view message) override;
private:
RefPtr<PInvokeNetworkManager> manager_;
intptr_t connection_handle_;
};
intptr_t manager_gc_handle_;
ReleaseGCHandleDelegate release_gc_handle_delegate_;
GetConnectionDelegate get_connection_delegate_;
PollMessageDelegate poll_message_delegate_;
SendMessageDelegate send_message_delegate_;
};
std::shared_ptr<NetworkConnection> PInvokeNetworkManager::GetConnection(
const InternedBlob& connection_string) {
std::shared_ptr<NetworkConnection> result;
get_connection_delegate_(bit_cast<intptr_t>(&connection_string),
manager_gc_handle_, this, &result);
return result;
}
PInvokeNetworkManager::Connection::Connection(
RefPtr<const InternedBlob> connection_string,
RefPtr<PInvokeNetworkManager> manager,
intptr_t connection_handle)
: NetworkConnection{std::move(connection_string)},
manager_{std::move(manager)},
connection_handle_{connection_handle} {}
PInvokeNetworkManager::Connection::~Connection() noexcept {
manager_->release_gc_handle_delegate_(connection_handle_);
}
void PInvokeNetworkManager::Connection::SendMessage(std::string_view message) {
if (message.size() > std::numeric_limits<int>::max()) {
throw std::invalid_argument{
"The message is too large to be marshaled to C#"};
}
manager_->send_message_delegate_(connection_handle_, message.data(),
static_cast<int>(message.size()));
}
} // namespace
extern "C" {
MS_MR_SHARING_STATESYNC_API intptr_t MS_MR_CALL
Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Create() noexcept {
return bit_cast<intptr_t>(new std::weak_ptr<NetworkConnection>);
}
MS_MR_SHARING_STATESYNC_API void MS_MR_CALL
Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Destroy(
intptr_t weak_ptr_handle) noexcept {
auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle);
delete wptr;
}
MS_MR_SHARING_STATESYNC_API bool MS_MR_CALL
Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Lock(
intptr_t weak_ptr_handle,
std::shared_ptr<NetworkConnection>* result) noexcept {
auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle);
*result = wptr->lock();
return result;
}
MS_MR_SHARING_STATESYNC_API void MS_MR_CALL
Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Update(
intptr_t weak_ptr_handle,
PInvokeNetworkManager* manager,
intptr_t connection_string_blob,
intptr_t connecton_gc_handle,
std::shared_ptr<NetworkConnection>* result) noexcept {
*result = manager->CreateConnectionWrapper(
*bit_cast<const InternedBlob*>(connection_string_blob),
connecton_gc_handle);
auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle);
*wptr = *result; // Updating the cache.
}
MS_MR_SHARING_STATESYNC_API void MS_MR_CALL
Microsoft_MixedReality_Sharing_StateSync_NetworkListener_OnMessage(
NetworkListener* listener,
intptr_t sender,
const char* messageBegin,
int messageSize) noexcept {
std::string_view message{messageBegin, static_cast<size_t>(messageSize)};
listener->OnMessage(*bit_cast<const InternedBlob*>(sender), message);
}
} // extern "C"
| 37.119048 | 88 | 0.747915 | ivte-ms |
33aa7913d2ba041c244e75a53cf72d2ae073a76e | 3,385 | cpp | C++ | src/plugins/nacheku/directorywatcher.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/nacheku/directorywatcher.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/nacheku/directorywatcher.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* 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.
**********************************************************************/
#include "directorywatcher.h"
#include <QDir>
#include <QTimer>
#include <QUrl>
#include <util/xpc/util.h>
#include "xmlsettingsmanager.h"
namespace LeechCraft
{
namespace Nacheku
{
DirectoryWatcher::DirectoryWatcher (QObject *parent)
: QObject (parent)
, Watcher_ (new QFileSystemWatcher)
{
XmlSettingsManager::Instance ().RegisterObject ("WatchDirectory",
this,
"settingsChanged");
QTimer::singleShot (5000,
this,
SLOT (settingsChanged ()));
connect (Watcher_.get (),
SIGNAL (directoryChanged (const QString&)),
this,
SLOT (handleDirectoryChanged (const QString&)),
Qt::QueuedConnection);
}
void DirectoryWatcher::settingsChanged ()
{
const QString& path = XmlSettingsManager::Instance ()
.property ("WatchDirectory").toString ();
const QStringList& dirs = Watcher_->directories ();
if (dirs.size () == 1 &&
dirs.at (0) == path)
return;
if (!dirs.isEmpty ())
Watcher_->removePaths (dirs);
if (!path.isEmpty ())
{
QDir dir (path);
Olds_ = dir.entryInfoList (QDir::Files);
Watcher_->addPath (path);
handleDirectoryChanged (path);
}
}
void DirectoryWatcher::handleDirectoryChanged (const QString& path)
{
QDir dir (path);
const auto& cur = dir.entryInfoList (QDir::Files);
auto nl = cur;
Q_FOREACH (const QFileInfo& oldFi, Olds_)
{
const QString& fname = oldFi.absoluteFilePath ();
Q_FOREACH (const QFileInfo& newFi, nl)
if (newFi.absoluteFilePath () == fname)
{
nl.removeOne (newFi);
break;
}
}
Olds_ = cur;
Q_FOREACH (const QFileInfo& newFi, nl)
emit gotEntity (Util::MakeEntity (QUrl::fromLocalFile (newFi.absoluteFilePath ()),
path,
FromUserInitiated));
}
}
}
| 31.055046 | 85 | 0.684195 | MellonQ |
33abe561f89c1c591a40feb8a2272c0547fb96f2 | 2,528 | cpp | C++ | src/client/particles/FireworkParticle.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | src/client/particles/FireworkParticle.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | src/client/particles/FireworkParticle.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright 2017-2019 azarias.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* File: Fireworkparticle.cpp
* Author: azarias
*
* Created on 08/05/2019
*/
#include "FireworkParticle.hpp"
#include "src/client/Renderer.hpp"
#include "src/common/Config.hpp"
namespace mp {
FireworkParticle::FireworkParticle():
Particle (this),
m_line(sf::PrimitiveType::Lines, 2)
{
}
const sf::Vector2f &FireworkParticle::getExplosionPosition() const
{
return m_target;
}
void FireworkParticle::init(const sf::Vector2f &target, const sf::Time &climbTime)
{
m_target = target;
const sf::Time added = sf::milliseconds(static_cast<sf::Int32>(ARENA_HEIGHT - target.y)) * ARENA_HEIGHT;
m_length = twin::makeTwin(10.f, 0.f, added + climbTime, twin::easing::quadIn);
m_yPos = twin::makeTwin(ARENA_HEIGHT, target.y, added + climbTime, twin::easing::quadOut);
m_line[0] = sf::Vertex(sf::Vector2f(m_target.x, ARENA_HEIGHT), sf::Color::White);
m_line[1] = sf::Vertex(sf::Vector2f(m_target.x, ARENA_HEIGHT) , sf::Color::Transparent);
}
bool FireworkParticle::isFinished() const
{
return m_yPos.progress() == 1.f;
}
void FireworkParticle::render(Renderer &renderer) const
{
renderer.draw(m_line);
}
void FireworkParticle::update(const sf::Time &elapsed)
{
m_length.step(elapsed);
m_yPos.step(elapsed);
const float yPos = m_yPos.get();
m_line[0].position.y = yPos;
m_line[1].position.y = yPos + m_length.get();
}
}
| 30.095238 | 108 | 0.721915 | AzariasB |
33acac7974d9e7125b1d23005899f74f4db4c16f | 2,616 | cpp | C++ | ls_base/malloc_hook.cpp | bbxionglei/LoveSnow | f6f4b73e9cc18817480cb53a08d936c0e0cc8029 | [
"MIT"
] | 3 | 2019-04-19T02:59:36.000Z | 2019-10-16T05:55:28.000Z | ls_base/malloc_hook.cpp | bbxionglei/LoveSnow | f6f4b73e9cc18817480cb53a08d936c0e0cc8029 | [
"MIT"
] | 2 | 2019-11-11T04:28:42.000Z | 2019-11-11T04:30:54.000Z | ls_base/malloc_hook.cpp | bbxionglei/LoveSnow | f6f4b73e9cc18817480cb53a08d936c0e0cc8029 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <lua.hpp>
#include <stdio.h>
#include "malloc_hook.h"
#include "ls.h"
// turn on MEMORY_CHECK can do more memory check, such as double free
// #define MEMORY_CHECK
#define MEMORY_ALLOCTAG 0x20140605
#define MEMORY_FREETAG 0x0badf00d
static size_t _used_memory = 0;
static size_t _memory_block = 0;
struct mem_data {
uint32_t handle;
size_t allocated;
};
struct mem_cookie {
uint32_t handle;
};
#define SLOT_SIZE 0x10000
#define PREFIX_SIZE sizeof(struct mem_cookie)
static struct mem_data mem_stats[SLOT_SIZE];
// for ls_lalloc use
#define raw_realloc realloc
#define raw_free free
void
memory_info_dump(void) {
ls_error(NULL, "No jemalloc");
}
size_t
mallctl_int64(const char* name, size_t* newval) {
ls_error(NULL, "No jemalloc : mallctl_int64 %s.", name);
return 0;
}
int
mallctl_opt(const char* name, int* newval) {
ls_error(NULL, "No jemalloc : mallctl_opt %s.", name);
return 0;
}
size_t
malloc_used_memory(void) {
return _used_memory;
}
size_t
malloc_memory_block(void) {
return _memory_block;
}
void
dump_c_mem() {
int i;
size_t total = 0;
ls_error(NULL, "dump all service mem:");
for (i = 0; i < SLOT_SIZE; i++) {
struct mem_data* data = &mem_stats[i];
if (data->handle != 0 && data->allocated != 0) {
total += data->allocated;
ls_error(NULL, ":%08x -> %zdkb %db", data->handle, data->allocated >> 10, (int)(data->allocated % 1024));
}
}
ls_error(NULL, "+total: %zdkb", total >> 10);
}
char*
ls_strdup(const char* str) {
size_t sz = strlen(str);
char* ret = (char*)ls_malloc(sz + 1);
memcpy(ret, str, sz + 1);
return ret;
}
void*
ls_lalloc(void* ptr, size_t osize, size_t nsize) {
if (nsize == 0) {
raw_free(ptr);
return NULL;
}
else {
return raw_realloc(ptr, nsize);
}
}
int
dump_mem_lua(lua_State * L) {
int i;
lua_newtable(L);
for (i = 0; i < SLOT_SIZE; i++) {
struct mem_data* data = &mem_stats[i];
if (data->handle != 0 && data->allocated != 0) {
lua_pushinteger(L, data->allocated);
lua_rawseti(L, -2, (lua_Integer)data->handle);
}
}
return 1;
}
size_t
malloc_current_memory(void) {
uint32_t handle = ls_current_handle();
int i;
for (i = 0; i < SLOT_SIZE; i++) {
struct mem_data* data = &mem_stats[i];
if (data->handle == (uint32_t)handle && data->allocated != 0) {
return (size_t)data->allocated;
}
}
return 0;
}
void
ls_debug_memory(const char* info) {
// for debug use
uint32_t handle = ls_current_handle();
size_t mem = malloc_current_memory();
fprintf(stderr, "[:%08x] %s %p\n", handle, info, (void*)mem);
}
| 19.235294 | 108 | 0.676988 | bbxionglei |
33b0d447893668d87306e25e7210c48469f6d67e | 23,895 | hxx | C++ | Modules/IO/ImageBase/include/itkConvertPixelBuffer.hxx | jond01/ITK | 88d152f65ff8982d4b926e8ab01f81dddf06291b | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/IO/ImageBase/include/itkConvertPixelBuffer.hxx | jond01/ITK | 88d152f65ff8982d4b926e8ab01f81dddf06291b | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/IO/ImageBase/include/itkConvertPixelBuffer.hxx | jond01/ITK | 88d152f65ff8982d4b926e8ab01f81dddf06291b | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkConvertPixelBuffer_hxx
#define itkConvertPixelBuffer_hxx
#include "itkConvertPixelBuffer.h"
#include "itkRGBPixel.h"
#include "itkDefaultConvertPixelTraits.h"
#include <cstddef>
namespace itk
{
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
template <typename UComponentType>
std::enable_if_t<!NumericTraits<UComponentType>::IsInteger, UComponentType>
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::DefaultAlphaValue()
{
return NumericTraits<UComponentType>::One;
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
template <typename UComponentType>
std::enable_if_t<NumericTraits<UComponentType>::IsInteger, UComponentType>
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::DefaultAlphaValue()
{
return NumericTraits<UComponentType>::max();
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::Convert(InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
switch (OutputConvertTraits::GetNumberOfComponents())
{
// output number of components is 1
case 1:
{
switch (inputNumberOfComponents)
{
case 1:
ConvertGrayToGray(inputData, outputData, size);
break;
case 3:
ConvertRGBToGray(inputData, outputData, size);
break;
case 4:
ConvertRGBAToGray(inputData, outputData, size);
break;
default:
ConvertMultiComponentToGray(inputData, inputNumberOfComponents, outputData, size);
break;
}
break;
}
// handle the complex case
case 2:
{
switch (inputNumberOfComponents)
{
case 1:
ConvertGrayToComplex(inputData, outputData, size);
break;
case 2:
ConvertComplexToComplex(inputData, outputData, size);
break;
default:
ConvertMultiComponentToComplex(inputData, inputNumberOfComponents, outputData, size);
break;
}
break;
}
// output number of components is 3 RGB
case 3:
{
switch (inputNumberOfComponents)
{
case 1:
ConvertGrayToRGB(inputData, outputData, size);
break;
case 3:
ConvertRGBToRGB(inputData, outputData, size);
break;
case 4:
ConvertRGBAToRGB(inputData, outputData, size);
break;
default:
ConvertMultiComponentToRGB(inputData, inputNumberOfComponents, outputData, size);
}
break;
}
// output number of components is 4 RGBA
case 4:
{
switch (inputNumberOfComponents)
{
case 1:
ConvertGrayToRGBA(inputData, outputData, size);
break;
case 3:
ConvertRGBToRGBA(inputData, outputData, size);
break;
case 4:
ConvertRGBAToRGBA(inputData, outputData, size);
break;
default:
ConvertMultiComponentToRGBA(inputData, inputNumberOfComponents, outputData, size);
}
break;
}
// output number of components is 6 (SymmetricSecondRankTensor)
case 6:
{
switch (inputNumberOfComponents)
{
case 6:
ConvertTensor6ToTensor6(inputData, outputData, size);
break;
case 9:
ConvertTensor9ToTensor6(inputData, outputData, size);
break;
default:
itkGenericExceptionMacro("No conversion available from " << inputNumberOfComponents
<< " components to: 6 components");
break;
}
break;
}
default:
itkGenericExceptionMacro("No conversion available from "
<< inputNumberOfComponents
<< " components to: " << OutputConvertTraits::GetNumberOfComponents() << " components");
break;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToGray(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData++, static_cast<OutputComponentType>(*inputData));
inputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToGray(InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
// Weights convert from linear RGB to CIE luminance assuming a
// modern monitor. See Charles Pontyon's Colour FAQ
// http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html
// NOTE: The scale factors are converted to whole numbers for precision
InputPixelType * endInput = inputData + size * 3;
while (inputData != endInput)
{
auto val = static_cast<OutputComponentType>((2125.0 * static_cast<OutputComponentType>(*inputData) +
7154.0 * static_cast<OutputComponentType>(*(inputData + 1)) +
0721.0 * static_cast<OutputComponentType>(*(inputData + 2))) /
10000.0);
inputData += 3;
OutputConvertTraits::SetNthComponent(0, *outputData++, val);
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToGray(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
// Weights convert from linear RGB to CIE luminance assuming a
// modern monitor. See Charles Pontyon's Colour FAQ
// http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html
// NOTE: The scale factors are converted to whole numbers for
// precision
InputPixelType * endInput = inputData + size * 4;
double maxAlpha(DefaultAlphaValue<InputPixelType>());
//
// To be backwards campatible, if the output pixel type
// isn't a short or char type, don't fix the problem.
if (sizeof(*outputData) > 2)
{
maxAlpha = 1.0;
}
while (inputData != endInput)
{
// this is an ugly implementation of the simple equation
// greval = (.2125 * red + .7154 * green + .0721 * blue) / alpha
//
double tempval = ((2125.0 * static_cast<double>(*inputData) + 7154.0 * static_cast<double>(*(inputData + 1)) +
0721.0 * static_cast<double>(*(inputData + 2))) /
10000.0) *
static_cast<double>(*(inputData + 3)) / maxAlpha;
inputData += 4;
auto val = static_cast<OutputComponentType>(tempval);
OutputConvertTraits::SetNthComponent(0, *outputData++, val);
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToGray(
InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
//
// To be backwards campatible, if the output pixel type
// isn't a short or char type, don't fix the problem.
double maxAlpha(DefaultAlphaValue<InputPixelType>());
if (sizeof(*outputData) > 2)
{
maxAlpha = 1.0;
}
// 2 components assumed intensity and alpha
if (inputNumberOfComponents == 2)
{
InputPixelType * endInput = inputData + size * 2;
while (inputData != endInput)
{
OutputComponentType val =
static_cast<OutputComponentType>(*inputData) * static_cast<OutputComponentType>(*(inputData + 1) / maxAlpha);
inputData += 2;
OutputConvertTraits::SetNthComponent(0, *outputData++, val);
}
}
// just skip the rest of the data
else
{
// Weights convert from linear RGB to CIE luminance assuming a
// modern monitor. See Charles Pontyon's Colour FAQ
// http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html
// NOTE: The scale factors are converted to whole numbers for
// precision
ptrdiff_t diff = inputNumberOfComponents - 4;
InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents;
while (inputData != endInput)
{
double tempval = ((2125.0 * static_cast<double>(*inputData) + 7154.0 * static_cast<double>(*(inputData + 1)) +
0721.0 * static_cast<double>(*(inputData + 2))) /
10000.0) *
static_cast<double>(*(inputData + 3)) / maxAlpha;
inputData += 4;
auto val = static_cast<OutputComponentType>(tempval);
OutputConvertTraits::SetNthComponent(0, *outputData++, val);
inputData += diff;
}
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToRGB(InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*inputData));
inputData++;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToRGB(InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size * 3;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
inputData += 3;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToRGB(InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size * 4;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
inputData += 3;
inputData++; // skip alpha
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToRGB(
InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
// assume intensity alpha
if (inputNumberOfComponents == 2)
{
InputPixelType * endInput = inputData + size * 2;
while (inputData != endInput)
{
OutputComponentType val =
static_cast<OutputComponentType>(*inputData) * static_cast<OutputComponentType>(*(inputData + 1));
inputData += 2;
OutputConvertTraits::SetNthComponent(0, *outputData, val);
OutputConvertTraits::SetNthComponent(1, *outputData, val);
OutputConvertTraits::SetNthComponent(2, *outputData, val);
outputData++;
}
}
// just skip the rest of the data
else
{
ptrdiff_t diff = inputNumberOfComponents - 3;
InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
inputData += 3;
inputData += diff;
outputData++;
}
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToRGBA(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(
3, *outputData, static_cast<OutputComponentType>(DefaultAlphaValue<InputPixelType>()));
inputData++;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToRGBA(InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
using InputConvertTraits = itk::DefaultConvertPixelTraits<InputPixelType>;
using InputComponentType = typename InputConvertTraits::ComponentType;
InputPixelType * endInput = inputData + size * 3;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
OutputConvertTraits::SetNthComponent(
3, *outputData, static_cast<OutputComponentType>(DefaultAlphaValue<InputComponentType>()));
inputData += 3;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToRGBA(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size * 4;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3)));
inputData += 4;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToRGBA(
InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
// equal weights for 2 components??
if (inputNumberOfComponents == 2)
{
InputPixelType * endInput = inputData + size * 2;
while (inputData != endInput)
{
auto val = static_cast<OutputComponentType>(*inputData);
auto alpha = static_cast<OutputComponentType>(*(inputData + 1));
inputData += 2;
OutputConvertTraits::SetNthComponent(0, *outputData, val);
OutputConvertTraits::SetNthComponent(1, *outputData, val);
OutputConvertTraits::SetNthComponent(2, *outputData, val);
OutputConvertTraits::SetNthComponent(3, *outputData, alpha);
}
}
else
{
ptrdiff_t diff = inputNumberOfComponents - 4;
InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3)));
inputData += 4;
inputData += diff;
outputData++;
}
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertTensor6ToTensor6(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
for (size_t i = 0; i < size; ++i)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3)));
OutputConvertTraits::SetNthComponent(4, *outputData, static_cast<OutputComponentType>(*(inputData + 4)));
OutputConvertTraits::SetNthComponent(5, *outputData, static_cast<OutputComponentType>(*(inputData + 5)));
++outputData;
inputData += 6;
}
}
// Convert Grayscale to Complex
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToComplex(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData));
inputData++;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertComplexToComplex(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
InputPixelType * endInput = inputData + size * 2;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
inputData += 2;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertTensor9ToTensor6(
InputPixelType * inputData,
OutputPixelType * outputData,
size_t size)
{
for (size_t i = 0; i < size; ++i)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2)));
OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 4)));
OutputConvertTraits::SetNthComponent(4, *outputData, static_cast<OutputComponentType>(*(inputData + 5)));
OutputConvertTraits::SetNthComponent(5, *outputData, static_cast<OutputComponentType>(*(inputData + 8)));
++outputData;
inputData += 9;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToComplex(
InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
ptrdiff_t diff = inputNumberOfComponents - 2;
InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents;
while (inputData != endInput)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1)));
inputData += 2;
inputData += diff;
outputData++;
}
}
template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits>
void
ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertVectorImage(
InputPixelType * inputData,
int inputNumberOfComponents,
OutputPixelType * outputData,
size_t size)
{
size_t length = size * (size_t)inputNumberOfComponents;
for (size_t i = 0; i < length; ++i)
{
OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData));
++outputData;
++inputData;
}
}
} // end namespace itk
#endif
| 39.561258 | 120 | 0.670475 | jond01 |
33b14adf56d17d2402ebe668b7e63522721a6d99 | 35,998 | cpp | C++ | TEDStore/src/client/chunker.cpp | jingwei87/ted | 112ec68b33fd00b4adb89c99af2fe94a9376da47 | [
"MIT"
] | 4 | 2020-03-04T18:36:23.000Z | 2021-06-11T10:25:25.000Z | TEDStore/src/client/chunker.cpp | jingwei87/ted | 112ec68b33fd00b4adb89c99af2fe94a9376da47 | [
"MIT"
] | null | null | null | TEDStore/src/client/chunker.cpp | jingwei87/ted | 112ec68b33fd00b4adb89c99af2fe94a9376da47 | [
"MIT"
] | 3 | 2020-11-22T23:29:52.000Z | 2021-11-05T14:00:29.000Z | #include "chunker.hpp"
#include "sys/time.h"
extern Configure config;
struct timeval timestartChunker;
struct timeval timeendChunker;
struct timeval timestartChunker_VarSizeInsert;
struct timeval timeendChunker_VarSizeInsert;
struct timeval timestartChunker_VarSizeHash;
struct timeval timeendChunker_VarSizeHash;
uint32_t DivCeil(uint32_t a, uint32_t b) {
uint32_t tmp = a / b;
if (a % b == 0) {
return tmp;
} else {
return (tmp + 1);
}
}
uint32_t CompareLimit(uint32_t input, uint32_t lower, uint32_t upper) {
if (input <= lower) {
return lower;
} else if (input >= upper) {
return upper;
} else {
return input;
}
}
Chunker::Chunker(std::string path, keyClient* keyClientObjTemp)
{
loadChunkFile(path);
ChunkerInit(path);
cryptoObj = new CryptoPrimitive();
keyClientObj = keyClientObjTemp;
}
Chunker::~Chunker()
{
if (powerLUT != NULL) {
delete powerLUT;
}
if (removeLUT != NULL) {
delete removeLUT;
}
if (waitingForChunkingBuffer != NULL) {
delete waitingForChunkingBuffer;
}
if (chunkBuffer != NULL) {
delete chunkBuffer;
}
if (cryptoObj != NULL) {
delete cryptoObj;
}
if (chunkingFile.is_open()) {
chunkingFile.close();
}
}
std::ifstream& Chunker::getChunkingFile()
{
if (!chunkingFile.is_open()) {
cerr << "Chunker : chunking file open failed" << endl;
exit(1);
}
return chunkingFile;
}
void Chunker::loadChunkFile(std::string path)
{
if (chunkingFile.is_open()) {
chunkingFile.close();
}
chunkingFile.open(path, std::ios::binary);
if (!chunkingFile.is_open()) {
cerr << "Chunker : open file: " << path << "error, client exit now" << endl;
exit(1);
}
}
void Chunker::ChunkerInit(string path)
{
u_char filePathHash[FILE_NAME_HASH_SIZE];
cryptoObj->generateHash((u_char*)&path[0], path.length(), filePathHash);
memcpy(fileRecipe.recipe.fileRecipeHead.fileNameHash, filePathHash, FILE_NAME_HASH_SIZE);
memcpy(fileRecipe.recipe.keyRecipeHead.fileNameHash, filePathHash, FILE_NAME_HASH_SIZE);
ChunkerType = (int)config.getChunkingType();
if (ChunkerType == CHUNKER_VAR_SIZE_TYPE) {
int numOfMaskBits;
avgChunkSize = (int)config.getAverageChunkSize();
minChunkSize = (int)config.getMinChunkSize();
maxChunkSize = (int)config.getMaxChunkSize();
slidingWinSize = (int)config.getSlidingWinSize();
ReadSize = config.getReadSize();
ReadSize = ReadSize * 1024 * 1024;
waitingForChunkingBuffer = new u_char[ReadSize];
chunkBuffer = new u_char[maxChunkSize];
if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) {
cerr << "Chunker : Memory malloc error" << endl;
exit(1);
}
if (minChunkSize >= avgChunkSize) {
cerr << "Chunker : minChunkSize should be smaller than avgChunkSize!" << endl;
exit(1);
}
if (maxChunkSize <= avgChunkSize) {
cerr << "Chunker : maxChunkSize should be larger than avgChunkSize!" << endl;
exit(1);
}
/*initialize the base and modulus for calculating the fingerprint of a window*/
/*these two values were employed in open-vcdiff: "http://code.google.com/p/open-vcdiff/"*/
polyBase = 257; /*a prime larger than 255, the max value of "unsigned char"*/
polyMOD = (1 << 23) - 1; /*polyMOD - 1 = 0x7fffff: use the last 23 bits of a polynomial as its hash*/
/*initialize the lookup table for accelerating the power calculation in rolling hash*/
powerLUT = (uint32_t*)malloc(sizeof(uint32_t) * slidingWinSize);
/*powerLUT[i] = power(polyBase, i) mod polyMOD*/
powerLUT[0] = 1;
for (int i = 1; i < slidingWinSize; i++) {
/*powerLUT[i] = (powerLUT[i-1] * polyBase) mod polyMOD*/
powerLUT[i] = (powerLUT[i - 1] * polyBase) & polyMOD;
}
/*initialize the lookup table for accelerating the byte remove in rolling hash*/
removeLUT = (uint32_t*)malloc(sizeof(uint32_t) * 256); /*256 for unsigned char*/
for (int i = 0; i < 256; i++) {
/*removeLUT[i] = (- i * powerLUT[_slidingWinSize-1]) mod polyMOD*/
removeLUT[i] = (i * powerLUT[slidingWinSize - 1]) & polyMOD;
if (removeLUT[i] != 0) {
removeLUT[i] = (polyMOD - removeLUT[i] + 1) & polyMOD;
}
/*note: % is a remainder (rather than modulus) operator*/
/* if a < 0, -polyMOD < a % polyMOD <= 0 */
}
/*initialize the anchorMask for depolytermining an anchor*/
/*note: power(2, numOfanchorMaskBits) = avgChunkSize*/
numOfMaskBits = 1;
while ((avgChunkSize >> numOfMaskBits) != 1) {
numOfMaskBits++;
}
anchorMask = (1 << numOfMaskBits) - 1;
/*initialize the value for depolytermining an anchor*/
anchorValue = 0;
} else if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) {
avgChunkSize = (int)config.getAverageChunkSize();
minChunkSize = (int)config.getMinChunkSize();
maxChunkSize = (int)config.getMaxChunkSize();
ReadSize = config.getReadSize();
ReadSize = ReadSize * 1024 * 1024;
waitingForChunkingBuffer = new u_char[ReadSize];
chunkBuffer = new u_char[avgChunkSize];
if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) {
cerr << "Chunker : Memory Error" << endl;
exit(1);
}
if (minChunkSize != avgChunkSize || maxChunkSize != avgChunkSize) {
cerr << "Chunker : Error: minChunkSize and maxChunkSize should be same in fixed size mode!" << endl;
exit(1);
}
if (ReadSize % avgChunkSize != 0) {
cerr << "Chunker : Setting fixed size chunking error : ReadSize not compat with average chunk size" << endl;
}
} else if (ChunkerType == CHUNKER_FAST_CDC) {
avgChunkSize = (int)config.getAverageChunkSize();
minChunkSize = (int)config.getMinChunkSize();
maxChunkSize = (int)config.getMaxChunkSize();
ReadSize = config.getReadSize();
ReadSize = ReadSize * 1024 * 1024;
waitingForChunkingBuffer = new u_char[ReadSize];
chunkBuffer = new u_char[maxChunkSize];
if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) {
cerr << "Chunker : Memory malloc error" << endl;
exit(1);
}
if (minChunkSize >= avgChunkSize) {
cerr << "Chunker : minChunkSize should be smaller than avgChunkSize!" << endl;
exit(1);
}
if (maxChunkSize <= avgChunkSize) {
cerr << "Chunker : maxChunkSize should be larger than avgChunkSize!" << endl;
exit(1);
}
normalSize_ = calNormalSize(minChunkSize, avgChunkSize, maxChunkSize);
uint32_t bits = (uint32_t) round(log2(static_cast<double>(avgChunkSize)));
maskS_ = generateFastCDCMask(bits + 1);
maskL_ = generateFastCDCMask(bits - 1);
} else if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) {
avgChunkSize = (int)config.getAverageChunkSize();
minChunkSize = (int)config.getMinChunkSize();
maxChunkSize = (int)config.getMaxChunkSize();
ReadSize = config.getReadSize();
ReadSize = ReadSize * 1024 * 1024;
waitingForChunkingBuffer = new u_char[ReadSize];
chunkBuffer = new u_char[avgChunkSize];
if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) {
cerr << "Chunker : Memory Error" << endl;
exit(1);
}
if (minChunkSize != avgChunkSize || maxChunkSize != avgChunkSize) {
cerr << "Chunker : Error: minChunkSize and maxChunkSize should be same in fixed size mode!" << endl;
exit(1);
}
if (ReadSize % avgChunkSize != 0) {
cerr << "Chunker : Setting fixed size chunking error : ReadSize not compat with average chunk size" << endl;
}
} else if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_FSL) {
maxChunkSize = (int)config.getMaxChunkSize();
chunkBuffer = new u_char[maxChunkSize + 6];
} else if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_UBC) {
maxChunkSize = (int)config.getMaxChunkSize();
chunkBuffer = new u_char[maxChunkSize + 5];
} else {
cerr << "Chunker : Error chunker type.\n";
exit(1);
}
}
bool Chunker::chunking()
{
/*fixed-size Chunker*/
if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) {
fixSizeChunking();
}
/*variable-size Chunker*/
if (ChunkerType == CHUNKER_VAR_SIZE_TYPE) {
varSizeChunking();
}
if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_FSL) {
traceDrivenChunkingFSL();
}
if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_UBC) {
traceDrivenChunkingUBC();
}
if (ChunkerType == CHUNKER_FAST_CDC) {
fastCDC();
}
return true;
}
void Chunker::fixSizeChunking()
{
double chunkTime = 0;
double hashTime = 0;
long diff;
double second;
std::ifstream& fin = getChunkingFile();
uint64_t chunkIDCounter = 0;
memset(chunkBuffer, 0, sizeof(char) * avgChunkSize);
uint64_t fileSize = 0;
u_char hash[CHUNK_HASH_SIZE];
/*start chunking*/
while (true) {
memset((char*)waitingForChunkingBuffer, 0, sizeof(unsigned char) * ReadSize);
fin.read((char*)waitingForChunkingBuffer, sizeof(char) * ReadSize);
uint64_t totalReadSize = fin.gcount();
fileSize += totalReadSize;
uint64_t chunkedSize = 0;
if (totalReadSize == ReadSize) {
while (chunkedSize < totalReadSize) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
memset(chunkBuffer, 0, sizeof(char) * avgChunkSize);
memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, avgChunkSize);
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
chunkTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, avgChunkSize, hash)) {
cerr << "Chunker : fixed size chunking: compute hash error" << endl;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCounter;
tempChunk.chunk.logicDataSize = avgChunkSize;
memcpy(tempChunk.chunk.logicData, chunkBuffer, avgChunkSize);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
insertMQToKeyClient(tempChunk);
chunkIDCounter++;
chunkedSize += avgChunkSize;
}
} else {
uint64_t retSize = 0;
while (chunkedSize < totalReadSize) {
memset(chunkBuffer, 0, sizeof(char) * avgChunkSize);
Data_t tempChunk;
if (retSize > avgChunkSize) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, avgChunkSize);
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
chunkTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, avgChunkSize, hash)) {
cerr << "Chunker : fixed size chunking: compute hash error" << endl;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
tempChunk.chunk.ID = chunkIDCounter;
tempChunk.chunk.logicDataSize = avgChunkSize;
memcpy(tempChunk.chunk.logicData, chunkBuffer, avgChunkSize);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
} else {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, retSize);
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
chunkTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, retSize, hash)) {
cerr << "Chunker : fixed size chunking: compute hash error" << endl;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
tempChunk.chunk.ID = chunkIDCounter;
tempChunk.chunk.logicDataSize = retSize;
memcpy(tempChunk.chunk.logicData, chunkBuffer, retSize);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
}
retSize = totalReadSize - chunkedSize;
tempChunk.dataType = DATA_TYPE_CHUNK;
insertMQToKeyClient(tempChunk);
chunkIDCounter++;
chunkedSize += avgChunkSize;
}
}
if (fin.eof()) {
break;
}
}
fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter;
fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter;
fileRecipe.recipe.fileRecipeHead.fileSize = fileSize;
fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize;
fileRecipe.dataType = DATA_TYPE_RECIPE;
insertMQToKeyClient(fileRecipe);
if (setJobDoneFlag() == false) {
cerr << "Chunker : set chunking done flag error" << endl;
}
cout << "Chunker : Fixed chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl;
#if SYSTEM_BREAK_DOWN == 1
cout << "Chunker : total chunking time = " << chunkTime << " s" << endl;
cout << "Chunker : total hashing time = " << hashTime << " s" << endl;
#endif
}
void Chunker::traceDrivenChunkingFSL()
{
double chunkTime = 0;
double hashTime = 0;
long diff;
double second;
std::ifstream& fin = getChunkingFile();
uint64_t chunkIDCounter = 0;
uint64_t fileSize = 0;
u_char hash[CHUNK_HASH_SIZE];
char readLineBuffer[256];
string readLineStr;
/*start chunking*/
getline(fin, readLineStr);
while (true) {
getline(fin, readLineStr);
if (fin.eof()) {
break;
}
memset(readLineBuffer, 0, 256);
memcpy(readLineBuffer, (char*)readLineStr.c_str(), readLineStr.length());
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
u_char chunkFp[7];
memset(chunkFp, 0, 7);
char* item;
item = strtok(readLineBuffer, ":\t\n ");
for (int index = 0; item != NULL && index < 6; index++) {
chunkFp[index] = strtol(item, NULL, 16);
item = strtok(NULL, ":\t\n");
}
chunkFp[6] = '\0';
auto size = atoi(item);
int copySize = 0;
memset(chunkBuffer, 0, sizeof(char) * maxChunkSize + 6);
if (size > maxChunkSize) {
continue;
}
while (copySize < size) {
memcpy(chunkBuffer + copySize, chunkFp, 6);
copySize += 6;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
chunkTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, size, hash)) {
cerr << "Chunker : trace driven chunking: compute hash error" << endl;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCounter;
tempChunk.chunk.logicDataSize = size;
memcpy(tempChunk.chunk.logicData, chunkBuffer, size);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
insertMQToKeyClient(tempChunk);
chunkIDCounter++;
fileSize += size;
}
fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter;
fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter;
fileRecipe.recipe.fileRecipeHead.fileSize = fileSize;
fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize;
fileRecipe.dataType = DATA_TYPE_RECIPE;
insertMQToKeyClient(fileRecipe);
if (setJobDoneFlag() == false) {
cerr << "Chunker : set chunking done flag error" << endl;
}
cout << "Chunker : trace gen over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl;
#if SYSTEM_BREAK_DOWN == 1
cout << "Chunker : total chunking time = " << chunkTime << " s" << endl;
cout << "Chunker : total hashing time = " << hashTime << " s" << endl;
#endif
}
void Chunker::traceDrivenChunkingUBC()
{
double chunkTime = 0;
double hashTime = 0;
long diff;
double second;
std::ifstream& fin = getChunkingFile();
uint64_t chunkIDCounter = 0;
uint64_t fileSize = 0;
u_char hash[CHUNK_HASH_SIZE];
char readLineBuffer[256];
string readLineStr;
/*start chunking*/
getline(fin, readLineStr);
while (true) {
getline(fin, readLineStr);
if (fin.eof()) {
break;
}
memset(readLineBuffer, 0, 256);
memcpy(readLineBuffer, (char*)readLineStr.c_str(), readLineStr.length());
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
u_char chunkFp[6];
memset(chunkFp, 0, 6);
char* item;
item = strtok(readLineBuffer, ":\t\n ");
for (int index = 0; item != NULL && index < 5; index++) {
chunkFp[index] = strtol(item, NULL, 16);
item = strtok(NULL, ":\t\n");
}
chunkFp[5] = '\0';
auto size = atoi(item);
int copySize = 0;
memset(chunkBuffer, 0, sizeof(char) * maxChunkSize + 5);
if (size > maxChunkSize) {
continue;
}
while (copySize < size) {
memcpy(chunkBuffer + copySize, chunkFp, 5);
copySize += 5;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
chunkTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, size, hash)) {
cerr << "Chunker : trace driven chunking: compute hash error" << endl;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCounter;
tempChunk.chunk.logicDataSize = size;
memcpy(tempChunk.chunk.logicData, chunkBuffer, size);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
insertMQToKeyClient(tempChunk);
chunkIDCounter++;
fileSize += size;
}
fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter;
fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter;
fileRecipe.recipe.fileRecipeHead.fileSize = fileSize;
fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize;
fileRecipe.dataType = DATA_TYPE_RECIPE;
insertMQToKeyClient(fileRecipe);
if (setJobDoneFlag() == false) {
cerr << "Chunker : set chunking done flag error" << endl;
}
cout << "Chunker : trace gen over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl;
#if SYSTEM_BREAK_DOWN == 1
cout << "Chunker : total chunking time = " << chunkTime << " s" << endl;
cout << "Chunker : total hashing time = " << hashTime << " s" << endl;
#endif
}
void Chunker::varSizeChunking()
{
double insertTime = 0;
double hashTime = 0;
long diff;
double second;
uint16_t winFp;
uint64_t chunkBufferCnt = 0, chunkIDCnt = 0;
ifstream& fin = getChunkingFile();
uint64_t fileSize = 0;
u_char hash[CHUNK_HASH_SIZE];
/*start chunking*/
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
while (true) {
memset((char*)waitingForChunkingBuffer, 0, sizeof(unsigned char) * ReadSize);
fin.read((char*)waitingForChunkingBuffer, sizeof(unsigned char) * ReadSize);
int len = fin.gcount();
fileSize += len;
for (int i = 0; i < len; i++) {
chunkBuffer[chunkBufferCnt] = waitingForChunkingBuffer[i];
/*full fill sliding window*/
if (chunkBufferCnt < slidingWinSize) {
winFp = winFp + (chunkBuffer[chunkBufferCnt] * powerLUT[slidingWinSize - chunkBufferCnt - 1]) & polyMOD; //Refer to doc/Chunking.md hash function:RabinChunker
chunkBufferCnt++;
continue;
}
winFp &= (polyMOD);
/*slide window*/
unsigned short int v = chunkBuffer[chunkBufferCnt - slidingWinSize]; //queue
winFp = ((winFp + removeLUT[v]) * polyBase + chunkBuffer[chunkBufferCnt]) & polyMOD; //remove queue front and add queue tail
chunkBufferCnt++;
/*chunk's size less than minChunkSize*/
if (chunkBufferCnt < minChunkSize)
continue;
/*find chunk pattern*/
if ((winFp & anchorMask) == anchorValue) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeHash, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) {
cerr << "Chunker : average size chunking compute hash error" << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeHash, NULL);
diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCnt;
tempChunk.chunk.logicDataSize = chunkBufferCnt;
memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeInsert, NULL);
#endif
if (!insertMQToKeyClient(tempChunk)) {
cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeInsert, NULL);
diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec;
second = diff / 1000000.0;
insertTime += second;
#endif
chunkIDCnt++;
chunkBufferCnt = winFp = 0;
}
/*chunk's size exceed maxChunkSize*/
if (chunkBufferCnt >= maxChunkSize) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeHash, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) {
cerr << "Chunker : average size chunking compute hash error" << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeHash, NULL);
diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCnt;
tempChunk.chunk.logicDataSize = chunkBufferCnt;
memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeInsert, NULL);
#endif
if (!insertMQToKeyClient(tempChunk)) {
cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeInsert, NULL);
diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec;
second = diff / 1000000.0;
insertTime += second;
#endif
chunkIDCnt++;
chunkBufferCnt = winFp = 0;
}
}
if (fin.eof()) {
break;
}
}
/*add final chunk*/
if (chunkBufferCnt != 0) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeHash, NULL);
#endif
if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) {
cerr << "Chunker : average size chunking compute hash error" << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeHash, NULL);
diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCnt;
tempChunk.chunk.logicDataSize = chunkBufferCnt;
memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt);
memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE);
tempChunk.dataType = DATA_TYPE_CHUNK;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeInsert, NULL);
#endif
if (!insertMQToKeyClient(tempChunk)) {
cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeInsert, NULL);
diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec;
second = diff / 1000000.0;
insertTime += second;
#endif
chunkIDCnt++;
chunkBufferCnt = winFp = 0;
}
fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCnt;
fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCnt;
fileRecipe.recipe.fileRecipeHead.fileSize = fileSize;
fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize;
fileRecipe.dataType = DATA_TYPE_RECIPE;
if (!insertMQToKeyClient(fileRecipe)) {
cerr << "Chunker : error insert recipe head to keyClient message queue" << endl;
return;
}
if (setJobDoneFlag() == false) {
cerr << "Chunker: set chunking done flag error" << endl;
return;
}
cout << "Chunker : variable size chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
cout << "Chunker : total chunking time = " << setbase(10) << second - (insertTime + hashTime) << " s" << endl;
cout << "Chunker : total hashing time = " << hashTime << " s" << endl;
#endif
return;
}
bool Chunker::insertMQToKeyClient(Data_t& newData)
{
return keyClientObj->insertMQFromChunker(newData);
}
bool Chunker::setJobDoneFlag()
{
return keyClientObj->editJobDoneFlag();
}
uint32_t Chunker::cutPoint(const uint8_t* src, const uint32_t len) {
uint32_t n;
uint32_t fp = 0;
uint32_t i;
i = std::min(len, static_cast<uint32_t>(minChunkSize));
n = std::min(normalSize_, len);
for (; i < n; i++) {
fp = (fp >> 1) + GEAR[src[i]];
if (!(fp & maskS_)) {
return (i + 1);
}
}
n = std::min(static_cast<uint32_t>(maxChunkSize), len);
for (; i < n; i++) {
fp = (fp >> 1) + GEAR[src[i]];
if (!(fp & maskL_)) {
return (i + 1);
}
}
return i;
}
void Chunker::fastCDC() {
double insertTime = 0;
double hashTime = 0;
long diff;
double second;
size_t pos = 0;
ifstream& fin = getChunkingFile();
uint64_t fileSize = 0;
uint64_t chunkIDCnt = 0;
size_t totalOffset = 0;
bool end = false;
/*start chunking*/
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker, NULL);
#endif
while (!end) {
memset((char*)waitingForChunkingBuffer, 0, sizeof(uint8_t) * ReadSize);
fin.read((char*)waitingForChunkingBuffer, sizeof(uint8_t) * ReadSize);
end = fin.eof();
size_t len = fin.gcount();
fprintf(stderr, "Chunker: len: %lu\n", len);
size_t localOffset = 0;
while (((len - localOffset) >= maxChunkSize) || (end && (localOffset < len))) {
uint32_t cp = cutPoint(waitingForChunkingBuffer + localOffset, len - localOffset);
Data_t tempChunk;
tempChunk.chunk.ID = chunkIDCnt;
tempChunk.chunk.logicDataSize = cp;
memcpy(tempChunk.chunk.logicData, waitingForChunkingBuffer + localOffset, cp);
tempChunk.dataType = DATA_TYPE_CHUNK;
#if SYSTEM_BREAK_DOWN==1
gettimeofday(×tartChunker_VarSizeHash, NULL);
#endif
if (!cryptoObj->generateHash(tempChunk.chunk.logicData, tempChunk.chunk.logicDataSize, tempChunk.chunk.chunkHash)) {
cerr << "Chunker : average size chunking compute hash error" << endl;
return;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeHash, NULL);
diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec;
second = diff / 1000000.0;
hashTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartChunker_VarSizeInsert, NULL);
#endif
if (!insertMQToKeyClient(tempChunk)) {
fprintf(stderr, "Chunker, error insert chunk to FPWorker MQ for chunkID: %u.\n",
tempChunk.chunk.ID);
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker_VarSizeInsert, NULL);
diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec;
second = diff / 1000000.0;
insertTime += second;
#endif
localOffset += cp;
fileSize += cp;
chunkIDCnt++;
}
pos += localOffset;
totalOffset += localOffset;
fin.seekg(totalOffset, std::ios_base::beg);
}
fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCnt;
fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCnt;
fileRecipe.recipe.fileRecipeHead.fileSize = fileSize;
fileRecipe.recipe.keyRecipeHead.fileSize = fileSize;
fileRecipe.dataType = DATA_TYPE_RECIPE;
if (!insertMQToKeyClient(fileRecipe)) {
cerr << "Chunker : error insert recipe head to keyClient message queue" << endl;
return;
}
if (setJobDoneFlag() == false) {
cerr << "Chunker: set chunking done flag error" << endl;
return;
}
cout << "Chunker : variable size chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendChunker, NULL);
diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec;
second = diff / 1000000.0;
cout << "Chunker : total chunking time = " << setbase(10) << second - (insertTime + hashTime) << " s" << endl;
cout << "Chunker : total hashing time = " << hashTime << " s" << endl;
#endif
return ;
}
uint32_t Chunker::calNormalSize(const uint32_t min, const uint32_t av, const uint32_t max) {
uint32_t off = min + DivCeil(min, 2);
if (off > av) {
off = av;
}
uint32_t diff = av - off;
if (diff > max) {
return max;
}
return diff;
}
uint32_t Chunker::generateFastCDCMask(uint32_t bits) {
uint32_t tmp;
tmp = (1 << CompareLimit(bits, 1, 31)) - 1;
return tmp;
} | 39.689085 | 208 | 0.617201 | jingwei87 |
33b44f8e28ed0adc0ab594d2485f0e2d63b25e6e | 8,664 | cpp | C++ | libs/base/src/utils/CMHPropertiesValuesList.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 4 | 2017-08-04T15:44:04.000Z | 2021-02-02T02:00:18.000Z | libs/base/src/utils/CMHPropertiesValuesList.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | null | null | null | libs/base/src/utils/CMHPropertiesValuesList.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T23:10:09.000Z | 2018-07-29T09:41:33.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "base-precomp.h" // Precompiled headers
#include <mrpt/utils/CMHPropertiesValuesList.h>
#include <mrpt/system/os.h>
#include <stdio.h>
using namespace mrpt::utils;
using namespace mrpt::system;
// This must be added to any CSerializable class implementation file.
IMPLEMENTS_SERIALIZABLE(CMHPropertiesValuesList, CSerializable, mrpt::utils)
/*---------------------------------------------------------------
writeToStream
---------------------------------------------------------------*/
void CMHPropertiesValuesList::writeToStream(
mrpt::utils::CStream& out, int* out_Version) const
{
if (out_Version)
*out_Version = 0;
else
{
uint32_t i, n = (uint32_t)m_properties.size();
uint8_t isNull;
out << n;
for (i = 0; i < n; i++)
{
// Name:
out << m_properties[i].name.c_str();
// Object:
isNull = !m_properties[i].value;
out << isNull;
if (!isNull) out << *m_properties[i].value;
// Hypot. ID:
out << m_properties[i].ID;
}
}
}
/*---------------------------------------------------------------
readFromStream
---------------------------------------------------------------*/
void CMHPropertiesValuesList::readFromStream(
mrpt::utils::CStream& in, int version)
{
switch (version)
{
case 0:
{
uint32_t i, n;
uint8_t isNull;
// Erase previous contents:
clear();
in >> n;
m_properties.resize(n);
for (i = 0; i < n; i++)
{
char nameBuf[1024];
// Name:
in >> nameBuf;
m_properties[i].name = nameBuf;
// Object:
in >> isNull;
if (isNull)
m_properties[i].value.reset();
else
in >> m_properties[i].value;
// Hypot. ID:
in >> m_properties[i].ID;
}
}
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version)
};
}
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CMHPropertiesValuesList::CMHPropertiesValuesList() {}
/*---------------------------------------------------------------
Destructor
---------------------------------------------------------------*/
CMHPropertiesValuesList::~CMHPropertiesValuesList() { clear(); }
/*---------------------------------------------------------------
clear
---------------------------------------------------------------*/
void CMHPropertiesValuesList::clear()
{
MRPT_START
m_properties.clear();
MRPT_END
}
/*---------------------------------------------------------------
get
---------------------------------------------------------------*/
CSerializable::Ptr CMHPropertiesValuesList::get(
const char* propertyName, const int64_t& hypothesis_ID) const
{
std::vector<TPropertyValueIDTriplet>::const_iterator it;
for (it = m_properties.begin(); it != m_properties.end(); ++it)
if (!os::_strcmpi(propertyName, it->name.c_str()) &&
it->ID == hypothesis_ID)
return it->value;
for (it = m_properties.begin(); it != m_properties.end(); ++it)
if (!os::_strcmpi(propertyName, it->name.c_str()) && it->ID == 0)
return it->value;
// Not found:
return CSerializable::Ptr();
}
/*---------------------------------------------------------------
getAnyHypothesis
---------------------------------------------------------------*/
CSerializable::Ptr CMHPropertiesValuesList::getAnyHypothesis(
const char* propertyName) const
{
for (std::vector<TPropertyValueIDTriplet>::const_iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
{
if (!os::_strcmpi(propertyName, it->name.c_str())) return it->value;
}
// Not found:
return CSerializable::Ptr();
}
/*---------------------------------------------------------------
set
---------------------------------------------------------------*/
void CMHPropertiesValuesList::set(
const char* propertyName, const CSerializable::Ptr& obj,
const int64_t& hypothesis_ID)
{
MRPT_START
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
{
if (it->ID == hypothesis_ID &&
!os::_strcmpi(propertyName, it->name.c_str()))
{
// Delete current contents:
// Copy new value:
it->value.reset(dynamic_cast<CSerializable*>(obj->clone()));
// if (!obj) it->value.clear();
// else it->value = obj; //->clone();
return;
}
}
// Insert:
TPropertyValueIDTriplet newPair;
newPair.name = std::string(propertyName);
newPair.value = obj;
newPair.ID = hypothesis_ID;
m_properties.push_back(newPair);
MRPT_END_WITH_CLEAN_UP(
printf("Exception while setting annotation '%s'", propertyName););
}
/*---------------------------------------------------------------
setMemoryReference
---------------------------------------------------------------*/
void CMHPropertiesValuesList::setMemoryReference(
const char* propertyName, const CSerializable::Ptr& obj,
const int64_t& hypothesis_ID)
{
MRPT_START
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
{
if (it->ID == hypothesis_ID &&
!os::_strcmpi(propertyName, it->name.c_str()))
{
// Delete current contents & set a copy of the same smart pointer:
it->value = obj;
return;
}
}
// Insert:
TPropertyValueIDTriplet newPair;
newPair.name = std::string(propertyName);
newPair.value = obj;
newPair.ID = hypothesis_ID;
m_properties.push_back(newPair);
MRPT_END_WITH_CLEAN_UP(
printf("Exception while setting annotation '%s'", propertyName););
}
/*---------------------------------------------------------------
getPropertyNames
---------------------------------------------------------------*/
std::vector<std::string> CMHPropertiesValuesList::getPropertyNames() const
{
std::vector<std::string> ret;
for (std::vector<TPropertyValueIDTriplet>::const_iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
{
bool isNew = true;
for (std::vector<std::string>::iterator itS = ret.begin();
itS != ret.end(); ++itS)
{
if ((*itS) == it->name)
{
isNew = false;
break;
}
}
if (isNew) ret.push_back(it->name); // Yes, it is new:
}
return ret;
}
/*---------------------------------------------------------------
remove
---------------------------------------------------------------*/
void CMHPropertiesValuesList::remove(
const char* propertyName, const int64_t& hypothesis_ID)
{
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end();)
if (!os::_strcmpi(propertyName, it->name.c_str()) &&
it->ID == hypothesis_ID)
it = m_properties.erase(it);
else
++it;
}
/*---------------------------------------------------------------
removeAll
---------------------------------------------------------------*/
void CMHPropertiesValuesList::removeAll(const int64_t& hypothesis_ID)
{
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end();)
if (it->ID == hypothesis_ID)
it = m_properties.erase(it);
else
++it;
}
/*---------------------------------------------------------------
Copy
---------------------------------------------------------------*/
CMHPropertiesValuesList::CMHPropertiesValuesList(
const CMHPropertiesValuesList& o)
: m_properties(o.m_properties)
{
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
it->value.reset(dynamic_cast<CSerializable*>(it->value->clone()));
}
/*---------------------------------------------------------------
Copy
---------------------------------------------------------------*/
CMHPropertiesValuesList& CMHPropertiesValuesList::operator=(
const CMHPropertiesValuesList& o)
{
if (this == &o) return *this;
m_properties = o.m_properties;
for (std::vector<TPropertyValueIDTriplet>::iterator it =
m_properties.begin();
it != m_properties.end(); ++it)
it->value.reset(dynamic_cast<CSerializable*>(it->value->clone()));
return *this;
}
| 28.221498 | 80 | 0.504386 | tg1716 |
33bce9c40270adb9d2ef0ac5de01957f887e7b72 | 521 | hpp | C++ | SimipleNetworkProtocol/src/PeriodicExecutor.hpp | DrLk/MultiThreaded-Socket | 54d0b4b7c99cf0eeed7c6182501778f1e4a35333 | [
"Apache-2.0"
] | null | null | null | SimipleNetworkProtocol/src/PeriodicExecutor.hpp | DrLk/MultiThreaded-Socket | 54d0b4b7c99cf0eeed7c6182501778f1e4a35333 | [
"Apache-2.0"
] | null | null | null | SimipleNetworkProtocol/src/PeriodicExecutor.hpp | DrLk/MultiThreaded-Socket | 54d0b4b7c99cf0eeed7c6182501778f1e4a35333 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <chrono>
#include <functional>
namespace FastTransport::Protocol {
class PeriodicExecutor {
public:
PeriodicExecutor(std::function<void()>, const std::chrono::microseconds& interval);
void Run();
private:
using clock = std::chrono::steady_clock;
std::function<void()> _function;
std::chrono::microseconds _interval;
std::chrono::microseconds _start;
clock::time_point _end;
void RunFunction();
};
} // namespace FastTransport::Protocol | 20.84 | 88 | 0.675624 | DrLk |
33be1b92715b0dce2bcc58a0178894f7b6dbf2e1 | 34,188 | hpp | C++ | lib/gpc/buffer.hpp | bamert/openGPC | ac61f9b0420ddf42bae02a7b9366f3744906cc72 | [
"BSD-3-Clause"
] | 8 | 2019-02-13T10:47:28.000Z | 2020-09-26T02:36:26.000Z | lib/gpc/buffer.hpp | bamert/openGPC | ac61f9b0420ddf42bae02a7b9366f3744906cc72 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T13:39:07.000Z | 2020-08-25T09:03:05.000Z | lib/gpc/buffer.hpp | bamert/openGPC | ac61f9b0420ddf42bae02a7b9366f3744906cc72 | [
"BSD-3-Clause"
] | 3 | 2020-04-16T06:05:20.000Z | 2020-10-28T14:18:06.000Z | // Copyright (c) 2018, ETH Zurich
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 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.
//
// Code Author: Niklaus Bamert (bamertn@ethz.ch)
#ifndef __NDB_BUFFER
#define __NDB_BUFFER
#include <vector>
#include <png.h>
#include <Eigen/Dense>
#include <type_traits>
using namespace std;
namespace ndb {
struct RGBColor {
uint8_t b, g, r;
RGBColor(uint8_t r, uint8_t g, uint8_t b) : r(r), g(g), b(b) {}
RGBColor(png_byte* ptr) {
this->r = ptr[0];
this->g = ptr[1];
this->b = ptr[2];
}
RGBColor() {};
};
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point() {};
};
struct Descriptor {
Point point;
uint64_t state;
bool srcDescr = false; //indicates if this is a descriptor from the source or from the target set
Descriptor(ndb::Point point, uint64_t state) : point(point), state(state) {}
Descriptor() {};
//ops for sorting and comparing descriptors for matching
bool operator==( const Descriptor &d ) const {
if (state == d.state ) return true;
return false;
}
//Checks if two descriptors are from different images
bool diffImgs(const Descriptor &d) {
if (srcDescr != d.srcDescr) return true;
return false;
}
bool operator!=( const Descriptor &d ) const {
if (state != d.state) return true;
return false;
}
bool operator<( const Descriptor &d ) const {
return state < d.state;
}
bool operator<=( const Descriptor &d ) const {
return state <= d.state;
}
int operator%( const int &d ) const {
return state % d;
}
};
//Keeps support points with associated disparity
//Support points are only used in the left image
struct Support {
int x, y;
float d;
Support(int x, int y, float d) : x(x), y(y), d(d) {}
Support(int x, int y) : x(x), y(y), d(0.) {}
Support() {};
};
// Keeps correspondences in case of non-epipolar matching scenario
struct Correspondence{
Point srcPt, tarPt;
Correspondence(Point srcPt, Point tarPt) : srcPt(srcPt), tarPt(tarPt) {}
};
//The Cg matrix elements used in Disparity Refinement
struct ConfidentSupport {
int x, y, cost;
float d;
ConfidentSupport() {};
ConfidentSupport(int x, int y, float d, int cost ) : x(x), y(y), d(d), cost(cost) {}
};
struct InvalidMatch {
int x, y, cost;
InvalidMatch() { cost = 0;};
InvalidMatch(int x, int y, int cost) : x(x), y(y), cost(cost) {}
};
struct Triangle {
int v1, v2, v3;
Triangle(int v1, int v2, int v3) : v1(v1), v2(v2), v3(v3) {}
};
struct Edge {
Support a, b;
Edge(Support& a, Support& b) {
if (a.y < b.y) {
this->a = a;
this->b = b;
} else {
this->a = b;
this->b = a;
}
}
};
struct Span {
int x1, x2;
Span(int x1, int x2) : x1(x1), x2(x2) {}
};
struct Dimension {
int w, h;
Dimension(int w, int h): w(w), h(h) {}
};
#define ALIGN16(X) (X%16) == 0 ? X :((X/16)+1)*16
template<class T>
class __attribute__((aligned(32),
packed)) Buffer : public Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> {
//The actual height and width of the image.
public:
int width;
int height;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Base;
Buffer(const int r, const int c) :
Base(r, ALIGN16(c)) {
this->width = c;
this->height = r;
}
Buffer(const int r, const int c, T color) :
Base(r, ALIGN16(c)) {
this->width = c;
this->height = r;
T *ptr = reinterpret_cast<T *>(Base::data());
for (int i = 0; i < Base::cols()*Base::rows(); i++) {
*ptr = color;
ptr++;
}
}
//Create new buffer from two side by side
Buffer(Buffer& i1, Buffer& i2) : Base(i1.rows(), i1.cols() + i2.cols()) {
for (int x = 0; x < i1.cols(); x++) {
for (int y = 0; y < i1.rows(); y++) {
setPixel(x, y, i1.getPixel(x, y));
setPixel(x + i1.cols(), y, i2.getPixel(x, y));
}
}
this->height = Base::rows();
this->width = Base::cols();
}
Buffer(const Eigen::Vector2i &size = Eigen::Vector2i(0, 0)) :
Base(size.y(), ALIGN16(size.x())) {
this->width = size.x();
this->height = size.y();
}
Buffer(const Eigen::Vector2i &size , T color) :
Base(size.y(), ALIGN16(size.x())) {
this->width = size.x();
this->height = size.y();
T *ptr = reinterpret_cast<T *>(Base::data());
for (int i = 0; i < Base::cols()*Base::rows(); i++) {
*ptr = color;
ptr++;
}
}
// original sources provided by Guillaume Cottenceau under the X11 license
// from http://zarb.org/~gc/html/libpng.html
int readPNG(std::string filename) {
unsigned char header[8]; // 8 is the maximum size that can be checked
png_byte colorType;
png_byte bitDepth;
png_structp pngPtr;
png_infop infoPtr;
png_bytep * rowPointers;
// open file and test for it being a png
FILE *fp = fopen(filename.c_str(), "rb");
if (!fp) {
cout << "ERR: File" << filename << " could not be opened for reading" << endl;
return 1;
}
size_t res = fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8)) {
cout << "ERR: File" << filename << " is not recognized as a PNG file" << endl;
return 1;
}
// initialize stuff
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr) {
cout << "ERR: png_create_read_struct failed" << endl;
return 1;
}
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr) {
cout << "ERR: png_create_info_struct failed" << endl;
return 1;
}
if (setjmp(png_jmpbuf(pngPtr))) {
cout << "ERR: Error during init_io" << endl;
return 1;
}
png_init_io(pngPtr, fp);
png_set_sig_bytes(pngPtr, 8);
png_read_info(pngPtr, infoPtr);
this->width = png_get_image_width(pngPtr, infoPtr);
this->height = png_get_image_height(pngPtr, infoPtr);
colorType = png_get_color_type(pngPtr, infoPtr);
bitDepth = png_get_bit_depth(pngPtr, infoPtr);
//We will do a conservative resize after reading in the data,
//such that we don't have to translate addresses ourselves
Base::resize(this->height, this->width);
int numberOfPasses = png_set_interlace_handling(pngPtr);
png_read_update_info(pngPtr, infoPtr);
// read file
if (setjmp(png_jmpbuf(pngPtr))) {
cout << "ERR: Error during read_image" << endl;
return 1;
}
rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (int y = 0; y < height; y++)
rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr));
png_read_image(pngPtr, rowPointers);
fclose(fp);
//Read image into buffer (row-major)
int nChannels;
switch (png_get_color_type(pngPtr, infoPtr)) {
case PNG_COLOR_TYPE_GRAY: nChannels = 1; break;
case PNG_COLOR_TYPE_RGB: nChannels = 3; break;
case PNG_COLOR_TYPE_RGBA: nChannels = 4; break;
default: nChannels = 0; break;
}
T *ptr = reinterpret_cast<T *>(Base::data());
if (bitDepth == 16) {
for (int y = 0; y < this->height; y++) {
png_byte* row = rowPointers[y];
for (int x = 0; x < this->width; x++) {
int val = ((int)row[x * 2] << 8) + row[x * 2 + 1];
*ptr = val;
ptr++;
}
}
} else {
for (int y = 0; y < this->height; y++) {
png_byte* row = rowPointers[y];
for (int x = 0; x < this->width; x++) {
int offset = y * this->width + x;
if ( nChannels == 1 ) {
*ptr = row[x];
ptr++;
} else if (nChannels == 3) { //convert to grayscale if color
*ptr = (row[3 * x] + row[3 * x + 1] + row[3 * x + 2]) / 3;
ptr++;
}
}
}
}
//Conservative resize of underlying matrix to align with 16 byte boundary
Base::conservativeResize(this->height, ALIGN16(this->width));
if (nChannels == 0 || nChannels == 4) {
cout << "ERR: found something other than gray or 3 channel color image(" << int(png_get_color_type(pngPtr,
infoPtr)) << ") aborting!" << endl;
return 1;
}
for (int y = 0; y < this->height; y++)
free(rowPointers[y]);
free(rowPointers);
return 0;
}
void writePNG(std::string filename) {
png_byte colorType = PNG_COLOR_TYPE_GRAY;
int nChannels = 1;
png_byte bitDepth = 8;
png_structp pngPtr;
png_infop infoPtr;
png_bytep * rowPointers;
//Copy Image matrix such that we can do a conservative resize to its correct size
Base img = *this;
img.conservativeResize(this->height, this->width);
FILE *fp = fopen(filename.c_str(), "wb");
if (!fp)
cout << "ERR: File" << filename << " could not be opened for writing" << endl;
// init
pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr)
cout << "ERR: png_create_write_struct failed" << endl;
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr)
cout << "ERR: png_create_info_struct failed" << endl;
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during init_io" << endl;
png_init_io(pngPtr, fp);
// write header
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during writing header" << endl;
png_set_IHDR(pngPtr, infoPtr, img.cols(), img.rows(),
bitDepth, colorType, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(pngPtr, infoPtr);
// write bytes
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during writing bytes" << endl;
//Allocate row pointers
rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * img.rows());
for (int y = 0; y < img.rows(); y++)
rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr));
T *ptr = reinterpret_cast<T *>(img.data());
//Copy our data from std::vector into allocated memory region
for (int y = 0; y < img.rows(); y++) {
png_byte* row = rowPointers[y];
for (int x = 0; x < img.cols(); x++) {
int offset;
offset = y * img.cols() + x;
row[x * nChannels] = ptr[offset];
}
}
png_write_image(pngPtr, rowPointers);
// end write
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during end of write" << endl;
png_write_end(pngPtr, NULL);
for (int y = 0; y < img.rows(); y++)
free(rowPointers[y]);
free(rowPointers);
fclose(fp);
}
void writePNGRGB(std::string filename) {
png_byte colorType = PNG_COLOR_TYPE_RGB;
int nChannels = 3;
png_byte bitDepth = 8;
png_structp pngPtr;
png_infop infoPtr;
png_bytep * rowPointers;
//Make copy of self that we can resize to actual size
Base img = *this;
img.conservativeResize(this->height, this->width);
// create file
FILE *fp = fopen(filename.c_str(), "wb");
if (!fp)
cout << "ERR: File" << filename << " could not be opened for writing" << endl;
// initialize stuff
pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr)
cout << "ERR: png_create_write_struct failed" << endl;
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr)
cout << "ERR: png_create_info_struct failed" << endl;
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during init_io" << endl;
png_init_io(pngPtr, fp);
// write header
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during writing header" << endl;
png_set_IHDR(pngPtr, infoPtr, img.cols(), img.rows(),
bitDepth, colorType, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(pngPtr, infoPtr);
// write bytes
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during writing bytes" << endl;
// Allocate row pointers
rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * img.rows());
for (int y = 0; y < img.rows(); y++)
rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr));
T *ptr = reinterpret_cast<T *>(img.data());
//Copy our data from std::vector into allocated memory region
for (int y = 0; y < img.rows(); y++) {
png_byte* row = rowPointers[y];
for (int x = 0; x < img.cols(); x++) {
int offset;
offset = y * img.cols() + x;
row[x * nChannels] = ptr[offset].r;
row[x * nChannels + 1] = ptr[offset].g;
row[x * nChannels + 2] = ptr[offset].b;
}
}
png_write_image(pngPtr, rowPointers);
// end write
if (setjmp(png_jmpbuf(pngPtr)))
cout << "ERR: Error during end of write" << endl;
png_write_end(pngPtr, NULL);
// cleanup heap allocation
for (int y = 0; y < img.rows(); y++)
free(rowPointers[y]);
free(rowPointers);
fclose(fp);
}
/**
* @brief "Unsafe" but fast pixel set method (no dimension check. If you write
* outside the bounds, it'll segfault!)
*
* @param[in] x { parameter_description }
* @param[in] y { parameter_description }
*/
void setPixel(int x, int y, T color) {
T *ptr = reinterpret_cast<T *>(Base::data());
*(ptr + Base::cols()*y + x) = color;
}
/**
* @brief Set all values in matrix to same value
*
* @param[in] color The color
*/
void set(T color) {
T *ptr = reinterpret_cast<T *>(Base::data());
int size = Base::cols() * Base::rows();
for (int i = 0; i < size; i++) {
*ptr = color;
ptr++;
}
}
/**
* @brief Gets the pixel.
*
* @param[in] x { parameter_description }
* @param[in] y { parameter_description }
*
* @return The pixel.
*/
T getPixel(int x, int y) {
T *ptr = reinterpret_cast<T *>(Base::data());
return *(ptr + Base::cols() * y + x);
}
/**
* @brief Gets the pixel. Const method overload for calls from GPC.
*
* @param[in] x { parameter_description }
* @param[in] y { parameter_description }
*
* @return The pixel.
*/
T getPixel(int x, int y) const {
T *ptr = const_cast<T *>(Base::data());
return *(ptr + Base::cols() * y + x);
}
/**
* @brief Gets a patch from the buffer
*
* @param[in] x { parameter_description }
* @param[in] y { parameter_description }
* @param[in] size The size
*
* @return The patch.
*/
void getPatch(ndb::Buffer<uint8_t>& patch, int x, int y, int size) {
patch.resize(size, size);
//extract patch
for (int ix = 0; ix < size; ix++) {
for (int iy = 0; iy < size; iy++) {
patch(ix, iy) = getPixel(x + ix - (size / 2), y + iy - (size / 2));
}
}
}
Dimension getDimension() {
return Dimension(Base::cols(), Base::rows());
}
/**
* @brief Draws a line.
*
* @param a { parameter_description }
* @param b { parameter_description }
* @param[in] color The color
*/
void drawLine(Support& a, Support& b, T color) {
float xdiff = (b.x - a.x);
float ydiff = (b.y - a.y);
if (xdiff == 0.0f && ydiff == 0.0f) {
setPixel(a.x, a.y, color);
return;
}
if (fabs(xdiff) > fabs(ydiff)) {
float xmin, xmax;
// set xmin to the lower x value given
// and xmax to the higher value
if (a.x < b.x) {
xmin = a.x;
xmax = b.x;
} else {
xmin = b.x;
xmax = a.x;
}
// draw line in terms of y slope
float slope = ydiff / xdiff;
for (float x = xmin; x <= xmax; x += 1.0f) {
float y = a.y + ((x - a.x) * slope);
setPixel(x, y, color);
}
} else {
float ymin, ymax;
// set ymin to the lower y value given
// and ymax to the higher value
if (a.y < b.y) {
ymin = a.y;
ymax = b.y;
} else {
ymin = b.y;
ymax = a.y;
}
// draw line in terms of x slope
float slope = xdiff / ydiff;
for (float y = ymin; y <= ymax; y += 1.0f) {
float x = a.x + ((y - a.y) * slope);
setPixel(x, y, color);
}
}
}
void drawLine(Point& a, Point& b, T color) {
Support aa(a.x, a.y, 0), bb(b.x, b.y, 0);
drawLine(aa, bb, color);
}
void drawLine(Point a, Point b, T color) {
Support aa(a.x, a.y, 0), bb(b.x, b.y, 0);
drawLine(aa, bb, color);
}
/**
* @brief Draws a span.
*
* @param[in] span The span
* @param[in] y
* @param color The color
*/
void drawSpan(const Span& span, int y, T& color) {
int xdiff = span.x2 - span.x1;
if (xdiff == 0) {
return;
}
for (int x = span.x1; x < span.x2; x++)
setPixel(x, y, color);
}
void clearBoundary() {
T *ptr = reinterpret_cast<T *>(Base::data());
//Dimension of the (visible) image
int h = this->height;
int w = this->width;
//Width of 16-aligned container
int waligned = this->cols();
//first 2 columns contains invalid data -> set them zero.
for (int x = 0; x < 2; x++) {
for (int y = 0; y < h; y++) {
ptr[y * waligned + x] = 0x00;
}
}
//first row
for (int x = 0; x < w; x++)
ptr[x] = 0x00;
//last two rowsrow
for (int x = 0; x < w; x++)
for (int y = h - 2; y < h; y++)
ptr[y * waligned + x] = 0x00;
//last column
for (int y = 0; y < h; y++)
ptr[y * waligned + (waligned - 1)] = 0x00;
}
/**
* @brief Draws spans between edges.
* modified from
* https://github.com/joshb/triangleraster
* @param[in] e1 The e 1 (long edge)
* @param[in] e2 The e 2 (short edge)
*/
void drawSpansBetweenEdges(const Edge &e1, const Edge &e2, T& color) {
// calculate difference between the y coordinates
// of the first edge and return if 0
float e1ydiff = (float)(e1.b.y - e1.a.y);
if (e1ydiff == 0.0f) {
return;
}
// calculate difference between the y coordinates
// of the second edge and return if 0
float e2ydiff = (float)(e2.b.y - e2.a.y);
if (e2ydiff == 0.0f) {
return;
}
// calculate differences between the x coordinates
float e1xdiff = (float)(e1.b.x - e1.a.x);
float e2xdiff = (float)(e2.b.x - e2.a.x);
// calculate factors to use for interpolation
// with the edges and the step values to increase
// them by after drawing each span
float factor1 = (float)(e2.a.y - e1.a.y) / e1ydiff;
float factorStep1 = 1.0f / e1ydiff;
float factor2 = 0.0f;
float factorStep2 = 1.0f / e2ydiff;
// loop through the lines between the edges and draw spans
for (int y = e2.a.y; y < e2.b.y; y++) {
// create and draw span
Span span(e1.a.x + (int)(e1xdiff * factor1),
e2.a.x + (int)(e2xdiff * factor2));
if (span.x1 > span.x2) std::swap(span.x1, span.x2);
drawSpan(span, y, color);
// increase factors
factor1 += factorStep1;
factor2 += factorStep2;
}
}
/**
* @brief Draw a triangle from three vertices and fill it. modified from
* https://github.com/joshb/triangleraster
* released under BSD licence
*
* @param a { parameter_description }
* @param b { parameter_description }
* @param c { parameter_description }
* @param[in] color The color
*/
void fillTriangle(Support a, Support b, Support c, T color) {
// create edges for the triangle
Edge edges[3] = {
Edge(a, b),
Edge(b, c),
Edge(c, a)
};
int maxLength = 0;
int longEdge = 0;
// find edge with the greatest length in the y axis
for (int i = 0; i < 3; i++) {
int length = edges[i].b.y - edges[i].a.y;
if (length > maxLength) {
maxLength = length;
longEdge = i;
}
}
int shortEdge1 = (longEdge + 1) % 3;
int shortEdge2 = (longEdge + 2) % 3;
// draw spans between edges; the long edge can be drawn
// with the shorter edges to draw the full triangle
drawSpansBetweenEdges(edges[longEdge], edges[shortEdge1], color);
drawSpansBetweenEdges(edges[longEdge], edges[shortEdge2], color);
}
/**
* @brief Draws a triangle.
*
* @param a { parameter_description }
* @param b { parameter_description }
* @param c { parameter_description }
* @param[in] color The color
*/
void drawTriangle(Support& a, Support& b, Support& c, T color) {
drawLine(a, b, color);
drawLine(b, c, color);
drawLine(c, a, color);
}
Buffer<RGBColor> convertToRGB() {
Buffer<RGBColor> out(Eigen::Vector2i(Base::cols(), Base::rows()));
T *ptr = reinterpret_cast<T *>(Base::data());
int width = Base::cols();
int height = Base::rows();
out.width = this->width;
//should fail graciously if heights incompatible
for (int y = 0; y < height; y++) {
for (int x = 0; x < width ; x++) {
out(y, x) = ndb::RGBColor(*ptr, *ptr, *ptr);
ptr++;
}
}
return out;
}
};
class RGBBuffer : public Buffer<RGBColor>{
public:
RGBBuffer(){
}
int readPNGRGB(std::string filename) {
unsigned char header[8]; // 8 is the maximum size that can be checked
png_byte colorType;
png_byte bitDepth;
png_structp pngPtr;
png_infop infoPtr;
png_bytep * rowPointers;
// open file and test for it being a png
FILE *fp = fopen(filename.c_str(), "rb");
if (!fp) {
cout << "ERR: File" << filename << " could not be opened for reading" << endl;
return 1;
}
size_t res = fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8)) {
cout << "ERR: File" << filename << " is not recognized as a PNG file" << endl;
return 1;
}
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr) {
cout << "ERR: png_create_read_struct failed" << endl;
return 1;
}
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr) {
cout << "ERR: png_create_info_struct failed" << endl;
return 1;
}
if (setjmp(png_jmpbuf(pngPtr))) {
cout << "ERR: Error during init_io" << endl;
return 1;
}
png_init_io(pngPtr, fp);
png_set_sig_bytes(pngPtr, 8);
png_read_info(pngPtr, infoPtr);
this->width = png_get_image_width(pngPtr, infoPtr);
this->height = png_get_image_height(pngPtr, infoPtr);
colorType = png_get_color_type(pngPtr, infoPtr);
bitDepth = png_get_bit_depth(pngPtr, infoPtr);
//We will do a conservative resize after reading in the data,
//such that we don't have to translate addresses ourselves
Base::resize(this->height, this->width);
png_read_update_info(pngPtr, infoPtr);
if (setjmp(png_jmpbuf(pngPtr))) {
cout << "ERR: Error during read_image" << endl;
return 1;
}
rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (int y = 0; y < height; y++)
rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr));
png_read_image(pngPtr, rowPointers);
fclose(fp);
//Read image into buffer (row-major)
int nChannels;
switch (png_get_color_type(pngPtr, infoPtr)) {
case PNG_COLOR_TYPE_GRAY: nChannels = 1; break;
case PNG_COLOR_TYPE_RGB: nChannels = 3; break;
case PNG_COLOR_TYPE_RGBA: nChannels = 4; break;
default: nChannels = 0; break;
}
RGBColor *ptr = reinterpret_cast<RGBColor *>(Base::data());
if (bitDepth == 8) {
if (nChannels == 3)
for (int y = 0; y < this->height; y++) {
png_byte* row = rowPointers[y];
for (int x = 0; x < this->width; x++) {
int offset = y * this->cols() + x;
ptr[offset] = RGBColor(row[3 * x], row[3 * x + 1], row[3 * x + 2]);
}
}
}
//Conservative resize of underlying matrix to align with 16 byte boundary
Base::conservativeResize(this->height, ALIGN16(this->width));
if (nChannels == 0 || nChannels == 4) {
cout << "ERR: found something other than gray or 3 channel color image(" << int(png_get_color_type(pngPtr,
infoPtr)) << ") aborting!" << endl;
return 1;
}
for (int y = 0; y < this->height; y++)
free(rowPointers[y]);
free(rowPointers);
return 0;
}
};
Buffer<RGBColor> getDisparityVisualization(ndb::Buffer<uint8_t>& srcImg,
std::vector<int>& validEstimateIndices,
ndb::Buffer<float>& disparity) {
float min_disparity = 0;
float max_disparity = 128;
Buffer<RGBColor> dispVis(Eigen::Vector2i(srcImg.width, srcImg.rows()));
for(int x=0;x<srcImg.width;x++){
for(int y=0;y<srcImg.height;y++) {
uint8_t c= srcImg.getPixel(x,y);
dispVis.setPixel(x,y,RGBColor(c,c,c));
}
}
// Create color-coded reconstruction disparity visualization.
// This uses Andreas Geiger's color map from the Kitti benchmark:
float map[8][4] = {{0, 0, 0, 114}, {0, 0, 1, 185}, {1, 0, 0, 114},
{1, 0, 1, 174}, {0, 1, 0, 114}, {0, 1, 1, 185},
{1, 1, 0, 114}, {1, 1, 1, 0}
};
float sum = 0;
for (int32_t i = 0; i < 8; ++ i) {
sum += map[i][3];
}
float weights[8]; // relative weights
float cumsum[8]; // cumulative weights
cumsum[0] = 0;
for (int32_t i = 0; i < 7; ++ i) {
weights[i] = sum / map[i][3];
cumsum[i + 1] = cumsum[i] + map[i][3] / sum;
}
//Copy image into a three channel color image first:
for (auto& idx : validEstimateIndices) {
//Pixel coords of disparity value
int x = idx % srcImg.cols();
int y = idx / srcImg.cols();
uint8_t p = srcImg.getPixel(x, y);
dispVis.setPixel(x, y, RGBColor(p, p, p));
//Overwrite pixel in red if we have significant error.
float reconstruction_disp = disparity.getPixel(x,y);
float value =
std::max(0.f,
std::min(0.8f, (reconstruction_disp - min_disparity) /
(max_disparity - min_disparity)));
int32_t bin;
for (bin = 0; bin < 7; ++ bin) {
if (value < cumsum[bin + 1]) {
break;
}
}
uint8_t colR, colG, colB;
// Compute red/green/blue values.
float w = 1.0f - (value - cumsum[bin]) * weights[bin];
colR =
static_cast<uint8_t>(
(w * map[bin][0] + (1.0f - w) * map[bin + 1][0]) * 255.0f);
colG =
static_cast<uint8_t>(
(w * map[bin][1] + (1.0f - w) * map[bin + 1][1]) * 255.0f);
colB =
static_cast<uint8_t>(
(w * map[bin][2] + (1.0f - w) * map[bin + 1][2]) * 255.0f);
dispVis.setPixel(x, y, RGBColor(colR,colG,colB));
}
return dispVis;
}
Buffer<RGBColor> getDisparityVisualization(ndb::Buffer<uint8_t>& srcImg,
std::vector<Support>& support) {
float min_disparity = 0;
float max_disparity = 128;
Buffer<RGBColor> dispVis(Eigen::Vector2i(srcImg.width, srcImg.rows()));
dispVis = srcImg.convertToRGB();;
for(auto& s:support)
dispVis.setPixel(s.x,s.y,RGBColor(s.d,s.d,s.d));
// Create color-coded reconstruction disparity visualization.
// This uses Andreas Geiger's color map from the Kitti benchmark:
float map[8][4] = { {0, 0, 1, 185}, {1, 0, 0, 114},
{1, 0, 1, 174}, {0, 1, 0, 114}, {0, 1, 1, 185},
{1, 1, 0, 114}, {1, 1, 1, 0} ,{0, 0, 0, 114},
};
float sum = 0;
for (int32_t i = 0; i < 8; ++ i) {
sum += map[i][3];
}
float weights[8]; // relative weights
float cumsum[8]; // cumulative weights
cumsum[0] = 0;
for (int32_t i = 0; i < 7; ++ i) {
weights[i] = sum / map[i][3];
cumsum[i + 1] = cumsum[i] + map[i][3] / sum;
}
//Copy image into a three channel color image first:
for (auto& s : support) {
//Pixel coords of disparity value
int x = s.x;
int y = s.y;
//Overwrite pixel in red if we have significant error.
float reconstruction_disp = s.d;
float value =
std::max(0.f,
std::min(0.8f, (reconstruction_disp - min_disparity) /
(max_disparity - min_disparity)));
int32_t bin;
for (bin = 0; bin < 7; ++ bin) {
if (value < cumsum[bin + 1]) {
break;
}
}
uint8_t colR, colG, colB;
// Compute red/green/blue values.
float w = 1.0f - (value - cumsum[bin]) * weights[bin];
colR =
static_cast<uint8_t>(
(w * map[bin][0] + (1.0f - w) * map[bin + 1][0]) * 255.0f);
colG =
static_cast<uint8_t>(
(w * map[bin][1] + (1.0f - w) * map[bin + 1][1]) * 255.0f);
colB =
static_cast<uint8_t>(
(w * map[bin][2] + (1.0f - w) * map[bin + 1][2]) * 255.0f);
dispVis.setPixel(x, y, RGBColor(colR,colG,colB));
}
return dispVis;
}
}
#endif
| 33.616519 | 118 | 0.515386 | bamert |
33c0d6843bb1f0fd477ec8b7140daa053a9db842 | 1,609 | hpp | C++ | src/utility.hpp | BigDataAnalyticsGroup/ACM-SIGMOD-19-Programming-Contest | 6193d5db300dad97737fa2438d0c7cede8e3550e | [
"Apache-2.0"
] | 2 | 2020-03-27T21:28:41.000Z | 2020-10-29T11:58:21.000Z | src/utility.hpp | BigDataAnalyticsGroup/ACM-SIGMOD-19-Programming-Contest | 6193d5db300dad97737fa2438d0c7cede8e3550e | [
"Apache-2.0"
] | null | null | null | src/utility.hpp | BigDataAnalyticsGroup/ACM-SIGMOD-19-Programming-Contest | 6193d5db300dad97737fa2438d0c7cede8e3550e | [
"Apache-2.0"
] | null | null | null | //===== utility.hpp ====================================================================================================
//
// Author: Immanuel Haffner <haffner.immanuel@gmail.com>
//
// Licence:
// Copyright 2019 Immanuel Haffner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Description:
// This file provides utility definitions.
//
//======================================================================================================================
#pragma once
#include <cstdlib>
#include <initializer_list>
template<typename T>
T * allocate(std::size_t count) { return static_cast<T*>(malloc(count * sizeof(T))); }
template<typename T>
T * reallocate(T *ptr, std::size_t count) { return static_cast<T*>(realloc(ptr, count * sizeof(T))); }
template<typename T>
void deallocate(T *ptr) { free(static_cast<void*>(ptr)); }
template<typename T>
T * stack_allocate(std::size_t count) { return static_cast<T*>(alloca(count * sizeof(T))); }
void clear_page_cache();
void bind_to_cpus(std::initializer_list<unsigned> cpus);
| 34.234043 | 120 | 0.599751 | BigDataAnalyticsGroup |
33c2358a81265eb5e06c41c74703d79ad98a9e97 | 465 | hpp | C++ | extensions/arduino/kit/QHRobot/lib/ArduinoJson6_8/src/ArduinoJson/Operators/VariantCasts.hpp | Suku1989/external-resources | 5d2b8fba60556d325cd31d29caa02508885910be | [
"MIT"
] | 2 | 2020-01-14T08:38:42.000Z | 2020-10-06T15:22:23.000Z | extensions/arduino/kit/QHRobot/lib/ArduinoJson6_8/src/ArduinoJson/Operators/VariantCasts.hpp | Suku1989/external-resources | 5d2b8fba60556d325cd31d29caa02508885910be | [
"MIT"
] | 6 | 2022-03-08T04:11:48.000Z | 2022-03-11T05:46:05.000Z | extensions/arduino/kit/QHRobot/lib/ArduinoJson6_8/src/ArduinoJson/Operators/VariantCasts.hpp | Suku1989/external-resources | 5d2b8fba60556d325cd31d29caa02508885910be | [
"MIT"
] | 8 | 2022-01-19T18:15:39.000Z | 2022-03-26T06:07:17.000Z | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License
#pragma once
#include "../Polyfills/attributes.hpp"
namespace ARDUINOJSON_NAMESPACE {
template <typename TImpl>
class VariantCasts {
public:
template <typename T>
FORCE_INLINE operator T() const {
return impl()->template as<T>();
}
private:
const TImpl *impl() const {
return static_cast<const TImpl *>(this);
}
};
} // namespace ARDUINOJSON_NAMESPACE
| 18.6 | 44 | 0.709677 | Suku1989 |
33c37075e4cc5313304a21b87476bf25bbcff28d | 4,845 | cpp | C++ | game/song1.cpp | kaplaars/gba-sprite-engine | 2653846d2c50a4eb57010e389288d23854d34eba | [
"MIT"
] | null | null | null | game/song1.cpp | kaplaars/gba-sprite-engine | 2653846d2c50a4eb57010e389288d23854d34eba | [
"MIT"
] | null | null | null | game/song1.cpp | kaplaars/gba-sprite-engine | 2653846d2c50a4eb57010e389288d23854d34eba | [
"MIT"
] | 1 | 2019-12-05T10:30:36.000Z | 2019-12-05T10:30:36.000Z | #include <libgba-sprite-engine/scene.h>
#include <libgba-sprite-engine/sprites/sprite_builder.h>
#include <libgba-sprite-engine/background/text_stream.h>
#include <libgba-sprite-engine/gba/tonc_memdef.h>
#include <libgba-sprite-engine/gba_engine.h>
#include "karakter.h"
#include "SongSelect.h"
#include "song1.h"
#include "danceroom1.h"
#include "Menu.h"
#include "music1.h"
#include "data.h"
#include "Highscore.h"
extern data data1;
song1::song1(const std::shared_ptr<GBAEngine> &engine) : Scene(engine) {}
std::vector<Sprite *> song1::sprites() {
return {animation.get(),
animation2.get(),
animation3.get(),
animation4.get(),
buttons.get()};
}
std::vector<Background *> song1::backgrounds() {
return {
bg.get()
};
}
void song1::tick(u16 keys) {
//ga terug naar startscene
if (keys & KEY_R) {
engine->setScene(new SongSelect(engine));
}
//topscore timer
if(engine->getTimer()->getMinutes()>=1){
data1.setEndgameScore(score1);
engine->setScene(new Highscore(engine));
}
TextStream::instance().setText("score:", 1, 1);
TextStream::instance().setText(std::to_string(score1), 2, 1);
TextStream::instance().setText(std::to_string(60-(engine->getTimer()->getSecs())),3,1);
//moving and generating the buttons
if(buttons->isOffScreen()) {
int frame=(rand()%6+6);
buttons->animateToFrame(frame);
TextStream::instance().setText(std::to_string(frame), 4, 1);
buttons->moveTo((GBA_SCREEN_WIDTH/2)-16,0);
pressed = 0;
}else{
buttons->setVelocity(0, data1.getFallSpeed());
}
//y pos checker
/*TextStream::instance().setText("Y-position:", 3, 1);
TextStream::instance().setText(std::to_string(buttons->getY()), 4, 1);*/
//points detection
if(buttons->getY()>=60 && buttons->getY() <= 75 && pressed == 0){
if(keys & KEY_B && buttons->getCurrentFrame() == 6){
score1+=buttons->getY();
pressed = 1;
}else if(keys & KEY_A && buttons->getCurrentFrame() == 7){
score1+=buttons->getY();
pressed = 1;
}else if(keys & KEY_LEFT && buttons->getCurrentFrame() == 8){
score1+=buttons->getY();
pressed = 1;
}else if(keys & KEY_DOWN && buttons->getCurrentFrame() == 9){
score1+=buttons->getY();
pressed = 1;
}else if(keys & KEY_RIGHT && buttons->getCurrentFrame() == 10){
score1+=buttons->getY();
pressed = 1;
}else if(keys & KEY_UP && buttons->getCurrentFrame() == 11){
score1+=buttons->getY();
pressed = 1;
}
}
}
void song1::load() {
foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(new ForegroundPaletteManager(SharedPal, sizeof(SharedPal)));
backgroundPalette = std::unique_ptr<BackgroundPaletteManager>(new BackgroundPaletteManager(danceroomPal, sizeof(danceroomPal)));
engine.get()->enableText();
engine->getTimer()->reset();
engine->getTimer()->start();
engine->enqueueMusic(music1, music1_bytes, data1.getSpeed());
bg = std::unique_ptr<Background>(new Background(1, danceroomTiles, sizeof(danceroomTiles), danceroomMap, sizeof(danceroomMap)));
bg.get()->useMapScreenBlock(16);
SpriteBuilder<Sprite> builder;
buttons = builder
.withData(buttonsTiles, sizeof(buttonsTiles))
.withSize(SIZE_32_32)
.withLocation((GBA_SCREEN_WIDTH/2)-16, 0)
.buildPtr();
animation = builder
.withData(bokmanTiles, sizeof(bokmanTiles))
.withSize(SIZE_32_32)
.withAnimated(3, (16-(data1.getFallSpeed()*5)))
.withLocation((GBA_SCREEN_WIDTH/4)-16, (GBA_SCREEN_HEIGHT/4))
.withinBounds()
.buildPtr();
animation2 = builder
.withData(dancingmichmanTiles, sizeof(dancingmichmanTiles))
.withSize(SIZE_32_32)
.withAnimated(3, (16-(data1.getFallSpeed()*5)))
.withLocation((GBA_SCREEN_WIDTH/4)-16, ((GBA_SCREEN_HEIGHT*3)/4)-32)
.withinBounds()
.buildPtr();
animation3= builder
.withData(nederlandmanTiles, sizeof(nederlandmanTiles))
.withSize(SIZE_32_32)
.withAnimated(3, (16-(data1.getFallSpeed()*5)))
.withLocation(((GBA_SCREEN_WIDTH*3)/4)-16, (GBA_SCREEN_HEIGHT/4))
.withinBounds()
.buildPtr();
animation4 = builder
.withData(j_germanTiles, sizeof(j_germanTiles))
.withSize(SIZE_32_32)
.withAnimated(3, (16-(data1.getFallSpeed()*5)))
.withLocation(((GBA_SCREEN_WIDTH*3)/4)-16, ((GBA_SCREEN_HEIGHT*3)/4)-32)
.withinBounds()
.buildPtr();
score1 = 0;
} | 34.361702 | 132 | 0.606192 | kaplaars |
33c440860bb47ff41cba083cc8f0baa836e92681 | 465 | cpp | C++ | Flick/src/Flick/Renderer/VertexArray.cpp | firo1738/FLICK | a6ccb0f23c212d0f1b97f71520beb3a89be57f2d | [
"Apache-2.0"
] | null | null | null | Flick/src/Flick/Renderer/VertexArray.cpp | firo1738/FLICK | a6ccb0f23c212d0f1b97f71520beb3a89be57f2d | [
"Apache-2.0"
] | null | null | null | Flick/src/Flick/Renderer/VertexArray.cpp | firo1738/FLICK | a6ccb0f23c212d0f1b97f71520beb3a89be57f2d | [
"Apache-2.0"
] | null | null | null | #include "fipch.h"
#include "VertexArray.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLVertexArray.h"
namespace Flick
{
VertexArray* VertexArray::Create()
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: FI_CORE_ASSERT(false, "RendererAPI::None is not yet supported by Flick!"); return nullptr;
case RendererAPI::API::OpenGL: return new OpenGLVertexArray();
}
FI_CORE_ASSERT(false, "Unknown RendererAPI!");
return 0;
}
} | 22.142857 | 121 | 0.722581 | firo1738 |
33c46982cc7dc4a9725b31f0be427aef3b71a382 | 616 | cpp | C++ | src/osm.ReferenceObject.cpp | rydotyosh/OpenSoundMixer | d81472a79655ba02b2456300f5ba345df8350b14 | [
"BSD-3-Clause"
] | 3 | 2018-05-31T11:06:57.000Z | 2019-10-13T16:08:44.000Z | src/osm.ReferenceObject.cpp | rydotyosh/OpenSoundMixer | d81472a79655ba02b2456300f5ba345df8350b14 | [
"BSD-3-Clause"
] | 1 | 2015-09-13T12:35:23.000Z | 2015-09-13T12:35:23.000Z | src/osm.ReferenceObject.cpp | rydotyosh/OpenSoundMixer | d81472a79655ba02b2456300f5ba345df8350b14 | [
"BSD-3-Clause"
] | 3 | 2015-12-15T05:10:43.000Z | 2019-11-17T10:13:13.000Z |
#include "osm.ReferenceObject.h"
namespace osm {
ReferenceObject::ReferenceObject() : m_reference(1) {}
ReferenceObject::~ReferenceObject() {}
int ReferenceObject::AddRef() {
std::atomic_fetch_add_explicit(&m_reference, 1, std::memory_order_consume);
return m_reference;
}
int ReferenceObject::GetRef() { return m_reference; }
int ReferenceObject::Release() {
assert(m_reference > 0);
bool destroy = std::atomic_fetch_sub_explicit(&m_reference, 1, std::memory_order_consume) == 1;
if (destroy) {
delete this;
return 0;
}
return m_reference;
}
} // namespace osm
| 22 | 99 | 0.694805 | rydotyosh |
33c8a08e2877efa578534cb6f768c6ffe6a21d4a | 4,589 | cpp | C++ | src/opengl/debugcontext.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 8 | 2016-09-13T12:39:49.000Z | 2022-03-21T12:30:50.000Z | src/opengl/debugcontext.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 33 | 2016-07-07T20:35:05.000Z | 2021-10-15T03:12:13.000Z | src/opengl/debugcontext.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 16 | 2015-06-24T20:41:28.000Z | 2022-01-08T04:14:03.000Z | /*****************************************************************************************
* *
* GHOUL *
* General Helpful Open Utility Library *
* *
* Copyright (c) 2012-2021 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <ghoul/opengl/debugcontext.h>
#include <ghoul/misc/assert.h>
#include <ghoul/misc/exception.h>
#include <map>
#include <type_traits>
namespace ghoul::opengl::debug {
namespace {
void internalCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei,
const GLchar* message, const GLvoid* userParam)
{
const CallbackFunction& cb = *reinterpret_cast<const CallbackFunction*>(userParam);
cb(Source(source), Type(type), Severity(severity), id, std::string(message));
}
} // namespace
void setDebugOutput(DebugOutput debug, SynchronousOutput synchronous) {
if (debug) {
glEnable(GL_DEBUG_OUTPUT);
}
else {
glDisable(GL_DEBUG_OUTPUT);
}
if (synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
}
void setDebugMessageControl(Source source, Type type, Severity severity, Enabled enabled)
{
glDebugMessageControl(
static_cast<GLenum>(source),
static_cast<GLenum>(type),
static_cast<GLenum>(severity),
0,
nullptr,
enabled ? GL_TRUE : GL_FALSE
);
}
void setDebugMessageControl(Source source, Type type,
const std::vector<unsigned int>& identifiers, Enabled enabled)
{
ghoul_assert(source != Source::DontCare, "source must not be Source::Dontcare");
ghoul_assert(type != Type::DontCare, "type must not be Type::Dontcare");
static_assert(
std::is_same<unsigned int, GLuint>::value,
"We exploit that 'int' and 'GLsizei' are the same for glDebugMessageControl"
);
glDebugMessageControl(
static_cast<GLenum>(source),
static_cast<GLenum>(type),
GL_DONT_CARE,
static_cast<GLsizei>(identifiers.size()),
identifiers.data(),
enabled ? GL_TRUE : GL_FALSE
);
}
void setDebugCallback(CallbackFunction callback) {
// We have to store the function pointer that is passed into this function locally as
// it might otherwise be destroyed (and still be referenced by \c internalCallback.
// In a perfect world, we'd want to capture the function pointer, but the OpenGL
// callback only allows pure C functions
static CallbackFunction storage;
storage = callback;
glDebugMessageCallback(internalCallback, &storage);
}
} // namespace ghoul::opengl::debug
| 44.125 | 90 | 0.548486 | OpenSpace |
33c8d159e7f8588c819bf84b5024a9364e2083ed | 249 | cpp | C++ | partitioner/problem/default_partitioner_inputs.cpp | elenabac/dgswemv2 | ecc776811de304cbae7bfa696b3d22c513e7d4de | [
"MIT"
] | 5 | 2018-05-30T08:43:10.000Z | 2021-12-14T18:33:10.000Z | partitioner/problem/default_partitioner_inputs.cpp | elenabac/dgswemv2 | ecc776811de304cbae7bfa696b3d22c513e7d4de | [
"MIT"
] | 57 | 2018-05-08T21:44:14.000Z | 2019-11-07T17:13:30.000Z | partitioner/problem/default_partitioner_inputs.cpp | elenabac/dgswemv2 | ecc776811de304cbae7bfa696b3d22c513e7d4de | [
"MIT"
] | 7 | 2018-05-07T21:50:49.000Z | 2021-04-30T14:02:02.000Z | #include "default_partitioner_inputs.hpp"
DefaultPartitionerInputs::DefaultPartitionerInputs(const MeshMetaData& mesh) {
for (const auto& elt : mesh.elements) {
weights.insert(std::make_pair(elt.first, std::vector<double>{1.}));
}
} | 35.571429 | 78 | 0.726908 | elenabac |
33caa8cba2e71a171072eb009157adf123bba03e | 18,658 | cpp | C++ | src/geometry/geometry_ply.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 662 | 2019-09-01T02:16:59.000Z | 2022-03-29T19:24:07.000Z | src/geometry/geometry_ply.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 38 | 2019-09-05T05:02:20.000Z | 2022-03-30T02:59:49.000Z | src/geometry/geometry_ply.cpp | Yoyochen0106/Pangolin | e55463bd2bdd758e46ded7d95332e31f9cdc4f71 | [
"MIT"
] | 104 | 2019-09-01T07:41:58.000Z | 2022-03-27T16:24:54.000Z | /* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 Steven Lovegrove
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <pangolin/geometry/geometry_ply.h>
#include <pangolin/utils/file_utils.h>
#include <pangolin/utils/variadic_all.h>
#include <pangolin/utils/parse.h>
#include <pangolin/utils/type_convert.h>
#include <pangolin/utils/simple_math.h>
// TODO: Should really remove need for GL here.
#include <pangolin/gl/gl.h>
namespace pangolin {
#define FORMAT_STRING_LIST(x) #x,
const char* PlyHeaderString[] = {
PLY_HEADER_LIST(FORMAT_STRING_LIST)
};
const char* PlyFormatString[] = {
PLY_FORMAT_LIST(FORMAT_STRING_LIST)
};
const char* PlyTypeString[] = {
PLY_TYPE_LIST(FORMAT_STRING_LIST)
};
#undef FORMAT_STRING_LIST
PLY_GROUP_LIST(PANGOLIN_DEFINE_PARSE_TOKEN)
void ParsePlyHeader(PlyHeaderDetails& ply, std::istream& is)
{
// 'Active' element for property definitions.
int current_element = -1;
// Check header is correct
PlyHeader token = ParseTokenPlyHeader(is);
if( token != PlyHeader_ply) {
throw std::runtime_error("Bad PLY header magic.");
}
ConsumeToNewline(is);
while(is.good() && token != PlyHeader_end_header) {
token = ParseTokenPlyHeader(is);
switch (token) {
case PlyHeader_format:
// parse PLY format and version
ConsumeWhitespace(is);
ply.format = ParseTokenPlyFormat(is);
ConsumeWhitespace(is);
ply.version = ReadToken(is);
break;
case PlyHeader_element:
{
current_element = ply.elements.size();
PlyElementDetails el;
el.stride_bytes = 0;
ConsumeWhitespace(is);
el.name = ReadToken(is);
ConsumeWhitespace(is);
el.num_items = FromString<int>(ReadToken(is));
ply.elements.push_back(el);
break;
}
case PlyHeader_property:
if(current_element >= 0) {
PlyElementDetails& el = ply.elements[current_element];
PlyPropertyDetails prop;
ConsumeWhitespace(is);
const PlyType t = ParseTokenPlyType(is);
if( t == PlyType_list) {
ConsumeWhitespace(is);
const PlyType idtype = ParseTokenPlyType(is);
ConsumeWhitespace(is);
const PlyType itemtype = ParseTokenPlyType(is);
prop.list_index_type = PlyTypeGl[idtype];
prop.type = PlyTypeGl[itemtype];
prop.offset_bytes = el.stride_bytes;
prop.num_items = -1;
el.stride_bytes = -1;
}else{
prop.type = PlyTypeGl[t];
prop.list_index_type = GL_NONE;
prop.offset_bytes = el.stride_bytes;
prop.num_items = 1;
const size_t size_bytes = GlDataTypeBytes(prop.type);
if( el.stride_bytes >= 0) {
el.stride_bytes += size_bytes;
}
}
ConsumeWhitespace(is);
prop.name = ReadToken(is);
el.properties.push_back(prop);
}else{
pango_print_warn("PLY Parser: property declaration before element. Ignoring line.");
}
break;
case PlyHeader_comment:
case PlyHeader_end_header:
break;
default:
pango_print_warn("PLY Parser: Unknown token - ignoring line.");
}
ConsumeToNewline(is);
}
}
void ParsePlyAscii(pangolin::Geometry& /*geom*/, const PlyHeaderDetails& /*ply*/, std::istream& /*is*/)
{
throw std::runtime_error("Not implemented.");
}
void AddVertexNormals(pangolin::Geometry& geom)
{
auto it_geom = geom.buffers.find("geometry");
auto it_face = geom.objects.find("default");
if(it_geom != geom.buffers.end() && it_face != geom.objects.end())
{
const auto it_vbo = it_geom->second.attributes.find("vertex");
const auto it_ibo = it_face->second.attributes.find("vertex_indices");
if(it_vbo != it_geom->second.attributes.end() && it_ibo != it_face->second.attributes.end()) {
const auto& ibo = get<Image<uint32_t>>(it_ibo->second);
const auto& vbo = get<Image<float>>(it_vbo->second);
// Assume we have triangles.
PANGO_ASSERT(ibo.w == 3 && vbo.w == 3);
ManagedImage<float> vert_normals(3, vbo.h);
ManagedImage<size_t> vert_face_count(1, vbo.h);
vert_normals.Fill(0.0f);
vert_face_count.Fill(0);
float ab[3];
float ac[3];
float fn[3];
for(size_t i=0; i < ibo.h; ++i) {
uint32_t i0 = ibo(0,i);
uint32_t i1 = ibo(1,i);
uint32_t i2 = ibo(2,i);
MatSub<3,1>(ab, vbo.RowPtr(i1), vbo.RowPtr(i0));
MatSub<3,1>(ac, vbo.RowPtr(i2), vbo.RowPtr(i0));
VecCross3(fn, ab, ac);
Normalise<3>(fn);
for(size_t v=0; v < 3; ++v) {
MatAdd<3,1>(vert_normals.RowPtr(ibo(v,i)), vert_normals.RowPtr(ibo(v,i)), fn);
++vert_face_count(0,ibo(v,i));
}
}
for(size_t v=0; v < vert_normals.h; ++v) {
// Compute average
MatMul<3,1>(vert_normals.RowPtr(v), 1.0f / vert_face_count(0,v));
}
auto& el = geom.buffers["normal"];
(ManagedImage<float>&)el = std::move(vert_normals);
auto& attr_norm = el.attributes["normal"];
attr_norm = MakeAttribute(GL_FLOAT, el.h, 3, el.ptr, el.pitch);
}
}
}
void StandardizeXyzToVertex(pangolin::Geometry& geom)
{
auto it_verts = geom.buffers.find("geometry");
if(it_verts != geom.buffers.end()) {
auto& verts = it_verts->second;
auto it_x = verts.attributes.find("x");
auto it_y = verts.attributes.find("y");
auto it_z = verts.attributes.find("z");
if(all_found(verts.attributes, it_x, it_y, it_z)) {
if(verts.attributes.find("vertex") == verts.attributes.end()) {
auto& vertex = verts.attributes["vertex"];
auto& imx = get<Image<float>>(it_x->second);
auto& imy = get<Image<float>>(it_y->second);
auto& imz = get<Image<float>>(it_z->second);
if(imx.ptr + 1 == imy.ptr && imy.ptr + 1 == imz.ptr) {
vertex = MakeAttribute(GL_FLOAT, verts.h, 3, imx.ptr, imx.pitch);
}else{
throw std::runtime_error("Ooops");
}
}
verts.attributes.erase(it_x);
verts.attributes.erase(it_y);
verts.attributes.erase(it_z);
}
}
}
void StandardizeRgbToColor(pangolin::Geometry& geom)
{
auto it_verts = geom.buffers.find("geometry");
if(it_verts != geom.buffers.end()) {
auto& verts = it_verts->second;
auto it_r = verts.attributes.find("r");
auto it_g = verts.attributes.find("g");
auto it_b = verts.attributes.find("b");
auto it_a = verts.attributes.find("a");
if(!all_found(verts.attributes, it_r, it_b, it_g)) {
it_r = verts.attributes.find("red");
it_g = verts.attributes.find("green");
it_b = verts.attributes.find("blue");
it_a = verts.attributes.find("alpha");
}
if(all_found(verts.attributes, it_r, it_g, it_b)) {
const bool have_alpha = it_a != verts.attributes.end();
if(verts.attributes.find("color") == verts.attributes.end()) {
Geometry::Element::Attribute& red = it_r->second;
Geometry::Element::Attribute& color = verts.attributes["color"];
// TODO: Check that these really are contiguous in memory...
if(auto attrib = get_if<Image<float>>(&red)) {
color = Image<float>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch);
}else if(auto attrib = get_if<Image<uint8_t>>(&red)) {
color = Image<uint8_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch);
}else if(auto attrib = get_if<Image<uint16_t>>(&red)) {
color = Image<uint16_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch);
}else if(auto attrib = get_if<Image<uint32_t>>(&red)) {
color = Image<uint32_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch);
}
}
verts.attributes.erase(it_r);
verts.attributes.erase(it_g);
verts.attributes.erase(it_b);
if(have_alpha) verts.attributes.erase(it_a);
}
}
}
void StandardizeMultiTextureFaceToXyzuv(pangolin::Geometry& geom)
{
const auto it_multi_texture_face = geom.buffers.find("multi_texture_face");
const auto it_multi_texture_vertex = geom.buffers.find("multi_texture_vertex");
const auto it_geom = geom.buffers.find("geometry");
const auto it_face = geom.objects.find("default");
if(it_geom != geom.buffers.end() && it_face != geom.objects.end())
{
const auto it_vbo = it_geom->second.attributes.find("vertex");
const auto it_ibo = it_face->second.attributes.find("vertex_indices");
if(all_found(geom.buffers, it_multi_texture_face, it_multi_texture_vertex) &&
it_vbo != it_geom->second.attributes.end() &&
it_ibo != it_face->second.attributes.end()
) {
const auto it_uv_ibo = it_multi_texture_face->second.attributes.find("texture_vertex_indices");
const auto it_tx = it_multi_texture_face->second.attributes.find("tx");
const auto it_tn = it_multi_texture_face->second.attributes.find("tn");
const auto it_u = it_multi_texture_vertex->second.attributes.find("u");
const auto it_v = it_multi_texture_vertex->second.attributes.find("v");
if(all_found(it_multi_texture_vertex->second.attributes, it_u, it_v) &&
it_uv_ibo != it_multi_texture_face->second.attributes.end()
) {
// We're going to create a new vertex buffer to hold uv's too
auto& orig_ibo = get<Image<uint32_t>>(it_ibo->second);
const auto& orig_xyz = get<Image<float>>(it_vbo->second);
const auto& uv_ibo = get<Image<uint32_t>>(it_uv_ibo->second);
const auto& u = get<Image<float>>(it_u->second);
const auto& v = get<Image<float>>(it_v->second);
const auto& tx = get<Image<uint8_t>>(it_tx->second);
const auto& tn = get<Image<uint32_t>>(it_tn->second);
PANGO_ASSERT(u.h == v.h);
PANGO_ASSERT(orig_ibo.w == 3 && uv_ibo.w == 3);
pangolin::Geometry::Element new_xyzuv(5*sizeof(float), u.h);
Image<float> new_xyz = new_xyzuv.UnsafeReinterpret<float>().SubImage(0,0,3,new_xyzuv.h);
Image<float> new_uv = new_xyzuv.UnsafeReinterpret<float>().SubImage(3,0,2,new_xyzuv.h);
new_xyzuv.attributes["vertex"] = new_xyz;
new_xyzuv.attributes["uv"] = new_uv;
for(size_t face=0; face < orig_ibo.h; ++face) {
uint32_t vtn = tn(0,face);
uint8_t vtx = tx(0,face);
PANGO_ASSERT(vtx==0, "Haven't implemented multi-texture yet.");
for(size_t vert=0; vert < 3; ++vert)
{
uint32_t& orig_xyz_index = orig_ibo(vert,vtn);
const uint32_t uv_index = uv_ibo(vert,face);
PANGO_ASSERT(uv_index < new_xyzuv.h && orig_xyz_index < orig_xyz.h);
for(int el=0; el < 3; ++el) {
new_xyz(el,uv_index) = orig_xyz(el,orig_xyz_index);
}
new_uv(0,uv_index) = u(0,uv_index);
new_uv(1,uv_index) = v(0,uv_index);
orig_xyz_index = uv_index;
}
}
geom.buffers["geometry"] = std::move(new_xyzuv);
geom.buffers.erase(it_multi_texture_face);
geom.buffers.erase(it_multi_texture_vertex);
}
}
}
}
void Standardize(pangolin::Geometry& geom)
{
StandardizeXyzToVertex(geom);
StandardizeRgbToColor(geom);
StandardizeMultiTextureFaceToXyzuv(geom);
AddVertexNormals(geom);
}
inline int ReadGlIntType(GLenum type, std::istream& is)
{
// TODO: This seems really dodgey...
// int may not be big enough and if the datatype is smaller will it be padded?
int v = 0;
is.read( (char*)&v, GlDataTypeBytes(type));
return v;
}
inline void ReadInto(std::vector<unsigned char>& vec, std::istream& is, size_t num_bytes)
{
const size_t current_size = vec.size();
vec.resize(current_size + num_bytes);
is.read((char*)vec.data() + current_size, num_bytes);
}
void ParsePlyLE(pangolin::Geometry& geom, PlyHeaderDetails& ply, std::istream& is)
{
std::vector<uint8_t> buffer;
for(auto& el : ply.elements) {
pangolin::Geometry::Element geom_el;
if(el.stride_bytes > 0) {
// This will usually be the case for vertex buffers with a known number of attributes
PANGO_ASSERT(el.num_items > 0);
geom_el.Reinitialise(el.stride_bytes, el.num_items);
is.read((char*)geom_el.ptr, geom_el.Area());
}else {
// This will generally be the case for face data (containing a list of vertex indices)
// Reserve enough space for a list of quads
buffer.clear();
buffer.reserve(el.num_items * el.properties.size() * 4);
for(int i=0; i< el.num_items; ++i) {
size_t offset_bytes = 0;
for(auto& prop : el.properties) {
if(prop.isList()) {
const int list_items = ReadGlIntType(prop.list_index_type, is);
if(prop.num_items == -1) {
prop.num_items = list_items;
prop.offset_bytes = offset_bytes;
}else{
PANGO_ASSERT(prop.num_items == list_items);
}
}
const size_t num_bytes = prop.num_items * GlDataTypeBytes(prop.type);
ReadInto(buffer, is, num_bytes);
offset_bytes += num_bytes;
}
}
// Update element stride now we know
el.stride_bytes = 0;
for(auto& prop : el.properties) {
el.stride_bytes += prop.num_items * GlDataTypeBytes(prop.type);
}
geom_el.Reinitialise(el.stride_bytes, el.num_items);
PANGO_ASSERT(geom_el.SizeBytes() == buffer.size());
std::memcpy(geom_el.ptr, buffer.data(), buffer.size());
}
for(auto& prop : el.properties) {
geom_el.attributes[prop.name] = MakeAttribute(
prop.type, el.num_items, prop.num_items, geom_el.ptr + prop.offset_bytes, geom_el.pitch
);
}
if(el.name == "vertex") {
geom.buffers["geometry"] = std::move(geom_el);
}else if(el.name == "face") {
geom.objects.emplace("default", std::move(geom_el));
}else{
geom.buffers[el.name] = std::move(geom_el);
}
}
Standardize(geom);
}
void ParsePlyBE(pangolin::Geometry& /*geom*/, const PlyHeaderDetails& /*ply*/, std::istream& /*is*/)
{
throw std::runtime_error("Not implemented.");
}
void AttachAssociatedTexturesPly(pangolin::Geometry& geom, const std::string& filename)
{
// For PLY, texture names are generally implicit
auto dot = filename.find_last_of('.');
if(dot != filename.npos) {
const std::string base = filename.substr(0, dot);
for(int i=0; i < 10; ++i) {
const std::string glob = FormatString("%_%.*", base, i);
std::vector<std::string> file_vec;
if(FilesMatchingWildcard(glob, file_vec)) {
for(const auto& file : file_vec) {
try {
geom.textures[FormatString("texture_%",i)] = LoadImage(file);
break;
}catch(std::runtime_error&)
{
}
}
}
}
}
}
pangolin::Geometry LoadGeometryPly(const std::string& filename)
{
std::ifstream bFile( filename.c_str(), std::ios::in | std::ios::binary );
if( !bFile.is_open() ) throw std::runtime_error("Unable to open PLY file: " + filename);
PlyHeaderDetails ply;
ParsePlyHeader(ply, bFile);
// Initialise geom object
pangolin::Geometry geom;
// Fill in geometry from file.
if(ply.format == PlyFormat_ascii) {
ParsePlyAscii(geom, ply, bFile);
}else if(ply.format == PlyFormat_binary_little_endian) {
ParsePlyLE(geom, ply, bFile);
}else if(ply.format == PlyFormat_binary_big_endian) {
ParsePlyBE(geom, ply, bFile);
}
AttachAssociatedTexturesPly(geom, filename);
return geom;
}
}
| 38.549587 | 107 | 0.571873 | Yoyochen0106 |
33ced71548adf7d6e95c4db8b69f9cf6d7011bd6 | 525 | hpp | C++ | util/slave_commun.hpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 64 | 2018-05-15T01:57:55.000Z | 2021-12-14T01:49:18.000Z | util/slave_commun.hpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 3 | 2019-11-28T12:10:09.000Z | 2021-11-03T15:16:06.000Z | util/slave_commun.hpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 24 | 2018-05-15T01:57:22.000Z | 2021-11-24T14:09:14.000Z | //Copyright 2018 Husky Data Lab, CUHK
//Authors: Hongzhi Chen, Miao Liu
#ifndef SLAVE_COMMUN_HPP_
#define SLAVE_COMMUN_HPP_
#include <mpi.h>
#include "util/communication.hpp"
#include "util/global.hpp"
int slave_all_sum(int my_copy)
{
int tmp = my_copy;
if( _my_rank != SLAVE_LEADER)
{
send_data(my_copy, SLAVE_LEADER, MSCOMMUN_CHANNEL);
}
else
{
for (int i = 0; i < _num_workers - 2; i++)
{
tmp += recv_data<int>(MPI_ANY_SOURCE, MSCOMMUN_CHANNEL);
}
}
return tmp;
}
#endif /* SLAVE_COMMUN_HPP_ */
| 15.909091 | 59 | 0.697143 | Mogami95 |
33cfd798a247b5ef564239c78e25a50ba2174e58 | 3,467 | hpp | C++ | lib/cpalgo/tree/lca/lca_binary_lifting.hpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | lib/cpalgo/tree/lca/lca_binary_lifting.hpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | lib/cpalgo/tree/lca/lca_binary_lifting.hpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #pragma once
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <vector>
// LCA: Lowest Common Ancestor
// using Binary Lifting
//
// Space: O(V log V + E)
//
// NOTE:
// - undirected
// - non-loop
// - non-multi-edge
// - it can NOT handle a forest
//
// Verified:
// - https://onlinejudge.u-aizu.ac.jp/problems/GRL_5_C
//
class LCABinaryLifting {
private:
size_t N, L;
std::vector<size_t> tin, tout;
std::vector<std::vector<size_t>> up;
public:
// root = [0,N)
// Time: O(N logN)
LCABinaryLifting(
std::vector<std::vector<size_t>> const& adj = {},
size_t const root = 0
)
{
build(adj, root);
}
// root = [0,N)
// O(N logN)
void build(
std::vector<std::vector<size_t>> const& adj,
size_t const root = 0
)
{
N = adj.size();
L = std::ceil(std::log2(std::max(size_t(1),N))) + 1;
tin.assign(N, 2 * N);
tout.assign(N, 2 * N);
up.assign(N, std::vector<size_t>(L, 0));
if (N > 0) {
size_t timer = 0;
if (root >= N) throw std::out_of_range("root");
dfs_euler(adj, root, root, timer);
}
}
// A LCA node of both the node 'u' and the node 'v'
// Time: O(logN)
size_t query(size_t u, size_t v) const {
if (u >= N) throw std::out_of_range("u");
if (v >= N) throw std::out_of_range("v");
if (is_ancestor(u, v)) return u;
if (is_ancestor(v, u)) return v;
for (size_t i = 0; i < L; ++i) {
if (is_ancestor(up[u][L-1-i], v)) continue;
u = up[u][L-1-i];
}
return up[u][0];
}
// A highest ancestor node of the node 'u'
// where the ancestor is not an ancestor of the node 'v'.
// If 'u' is an ancestor of 'v', return 'N'.
// Time: O(logN)
size_t upper_bound(size_t u, size_t const v) const {
if (u >= N) throw std::out_of_range("u");
if (v >= N) throw std::out_of_range("v");
if (is_ancestor(u, v)) return N;
for (size_t i = 0; i < L; ++i) {
if (is_ancestor(up[u][L-1-i], v)) continue;
u = up[u][L-1-i];
}
return u;
}
// True if the node 'u' is an ancestor of the node 'v'
// u = [0,N), v = [0,N)
// Time: O(1)
bool is_ancestor(size_t const u, size_t const v) const {
if (u >= N) throw std::out_of_range("u");
if (v >= N) throw std::out_of_range("v");
return tin[u] <= tin[v] && tout[u] >= tout[v];
}
// The In Index of the Euler Tour
// u = [0,N)
// The In Index = [0,2*N)
size_t euler_in(size_t const u) const {
if (u >= N) throw std::out_of_range("u");
return tin[u];
}
// The Out Index of the Euler Tour
// u = [0,N)
// The Out Index = [0, 2*N)
size_t euler_out(size_t const u) const {
if (u >= N) throw std::out_of_range("u");
return tout[u];
}
// Time: O(1)
size_t size() const {
return N;
}
private:
// Time: O(N logN)
void dfs_euler(std::vector<std::vector<size_t>> const& adj, size_t v, size_t p, size_t& timer) {
tin[v] = timer++;
up[v][0] = p;
for (size_t i = 1; i < L; ++i) {
up[v][i] = up[up[v][i-1]][i-1];
}
for (auto const& u : adj[v]) {
if (u == p) continue;
dfs_euler(adj, u, v, timer);
}
tout[v] = timer++;
}
}; | 26.875969 | 100 | 0.498702 | xirc |
33d2536a885aef96ca0793a12d3dd44ab30976ff | 743 | hpp | C++ | include/freedom/decision_node.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | 9 | 2019-08-22T06:25:12.000Z | 2021-02-17T16:27:27.000Z | include/freedom/decision_node.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | null | null | null | include/freedom/decision_node.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | 4 | 2019-09-04T14:20:05.000Z | 2022-02-09T06:32:14.000Z | #ifndef DECISION_NODE_H
#define DECISION_NODE_H
#include "fconfig.hpp"
#include "fcontext.hpp"
#include <mcts/inner_node.hpp>
namespace freedom {
using mcts::INode;
using mcts::InnerNode;
// ----------------------------------------------------------------------
/// @brief Uses a selectionStrategy for nodes in which we (the bot)
/// has to make a move.
// ----------------------------------------------------------------------
class DecisionNode : public InnerNode<FContext, FConfig> {
typedef typename INode<FContext, FConfig>::node_t node_t;
public:
DecisionNode(const FContext &fcontext_, FConfig *fconfig_, node_t *parent_);
void expand();
virtual node_t *select_child();
virtual ~DecisionNode();
};
}
#endif
| 24.766667 | 78 | 0.584118 | strikles |
33d72117ec4bcba4be1c8057e873f602103626df | 3,394 | cc | C++ | src/ppl/nn/models/onnx/model_parser.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | 1 | 2022-03-27T07:55:37.000Z | 2022-03-27T07:55:37.000Z | src/ppl/nn/models/onnx/model_parser.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/models/onnx/model_parser.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "ppl/nn/models/onnx/model_parser.h"
#include "ppl/nn/models/onnx/graph_parser.h"
#include "ppl/nn/common/logger.h"
#include "ppl/common/file_mapping.h"
// large proto file support
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace onnx {
static bool ParseFromBinaryBuffer(const char* buf, uint64_t buf_len, google::protobuf::MessageLite* pb_model) {
if (!buf) {
LOG(ERROR) << "buf ptr is nullptr.";
return false;
}
if (buf_len == 0) {
LOG(ERROR) << "buf len is 0.";
return false;
}
google::protobuf::io::CodedInputStream cis((uint8_t*)buf, buf_len);
cis.SetTotalBytesLimit(INT_MAX);
return pb_model->ParseFromCodedStream(&cis);
}
static map<string, uint64_t> ParseOpSets(const ::onnx::ModelProto pb_model) {
map<string, uint64_t> res;
for (int i = 0; i < pb_model.opset_import_size(); ++i) {
const string& domain = pb_model.opset_import(i).domain();
uint64_t version = pb_model.opset_import(i).version();
auto ref = res.insert(make_pair(domain, 0));
if (version > ref.first->second) {
ref.first->second = version;
}
}
return res;
}
RetCode ModelParser::Parse(const char* buf, uint64_t buf_len, const char* model_file_dir, ir::Graph* graph) {
::onnx::ModelProto pb_model;
if (!ParseFromBinaryBuffer(buf, buf_len, &pb_model)) {
LOG(ERROR) << "load onnx model from model buffer failed.";
return RC_OTHER_ERROR;
}
if (pb_model.graph().quantization_annotation_size() > 0) {
LOG(ERROR) << "quantization in ONNX model is not supported now.";
return RC_UNSUPPORTED;
}
map<string, uint64_t> op_sets = ParseOpSets(pb_model);
GraphParser graph_parser;
auto status = graph_parser.Parse(pb_model.graph(), op_sets, model_file_dir, graph);
if (status != RC_SUCCESS) {
LOG(ERROR) << "parse graph failed: " << GetRetCodeStr(status);
return status;
}
if (graph->topo->GetExtraInputCount() > 0) {
auto topo = graph->topo.get();
LOG(ERROR) << "unresolved extra input of graph[" << topo->GetName() << "]:";
for (uint32_t i = 0; i < topo->GetExtraInputCount(); ++i) {
LOG(ERROR) << " -> " << topo->GetEdge(topo->GetExtraInput(i))->GetName();
}
return RC_NOT_FOUND;
}
return RC_SUCCESS;
}
}}} // namespace ppl::nn::onnx
| 34.989691 | 111 | 0.671184 | kuroro-tian |
33d7db421d47e5b9a09cd1e3ee4fd25153ca24e5 | 2,092 | cpp | C++ | src/main.cpp | codingwithjulio/sdl2-create-window | 418e3258eda05f63a07c5dc42732adddf6bb3793 | [
"MIT"
] | null | null | null | src/main.cpp | codingwithjulio/sdl2-create-window | 418e3258eda05f63a07c5dc42732adddf6bb3793 | [
"MIT"
] | null | null | null | src/main.cpp | codingwithjulio/sdl2-create-window | 418e3258eda05f63a07c5dc42732adddf6bb3793 | [
"MIT"
] | null | null | null | #include <iostream>
#include <SDL2/SDL.h>
// Graphics
const int WINDOW_WIDTH = 512;
const int WINDOW_HEIGHT = 284;
SDL_Window* g_main_window;
SDL_Renderer* g_main_renderer;
// Colors
namespace Colors {
const SDL_Color GREEN = { 0, 255, 0, SDL_ALPHA_OPAQUE };
const SDL_Color BLACK = { 0, 0, 0, SDL_ALPHA_OPAQUE };
}
static void ClearScreen(SDL_Renderer* renderer)
{
SDL_SetRenderDrawColor(renderer, Colors::BLACK.r, Colors::BLACK.g, Colors::BLACK.b, Colors::BLACK.a);
SDL_RenderClear(renderer);
}
static bool Init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cout << "SDL_Init failed with error: " << SDL_GetError() << std::endl;
return EXIT_FAILURE;
}
g_main_window = SDL_CreateWindow(
"Creating a Window (512x284)",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
SDL_WINDOW_OPENGL
);
if (g_main_window == nullptr) {
std::cout << "Unable to crete the main window. Erro: " << SDL_GetError() << std::endl;
SDL_Quit();
return EXIT_FAILURE;
}
g_main_renderer = SDL_CreateRenderer(g_main_window, -1, SDL_RENDERER_PRESENTVSYNC);
return true;
}
void Shutdown()
{
if (g_main_window != nullptr) {
SDL_DestroyWindow(g_main_window);
g_main_window = nullptr;
}
if (g_main_renderer != nullptr) {
SDL_DestroyRenderer(g_main_renderer);
g_main_renderer = nullptr;
}
SDL_Quit();
}
int main()
{
if (Init() == false) { Shutdown(); }
// Draw loop
SDL_Event event;
bool running = true;
while(running)
{
ClearScreen(g_main_renderer);
// Check and process I/O events
if (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
{
running = event.key.keysym.scancode != SDL_SCANCODE_ESCAPE;
break;
}
case SDL_QUIT:
{
running = false;
break;
}
default:
break;
}
}
// Update the screen with the content rendered in the background
SDL_RenderPresent(g_main_renderer);
}
Shutdown();
return EXIT_SUCCESS;
}
| 20.712871 | 103 | 0.650096 | codingwithjulio |
33d8dcd655bf8d4f972500b2a104006dcf45bea2 | 1,192 | cpp | C++ | code/src/problem4_type_conversion/main.cpp | dsba2020-z/workshops5-6 | 5466ef1241208ca93df18c81deb4fbc69957ee7f | [
"BSD-3-Clause"
] | null | null | null | code/src/problem4_type_conversion/main.cpp | dsba2020-z/workshops5-6 | 5466ef1241208ca93df18c81deb4fbc69957ee7f | [
"BSD-3-Clause"
] | null | null | null | code/src/problem4_type_conversion/main.cpp | dsba2020-z/workshops5-6 | 5466ef1241208ca93df18c81deb4fbc69957ee7f | [
"BSD-3-Clause"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Main module for Problem 4: Type conversion.
/// \author Georgii Zhulikov
/// \version 0.1.0
/// \date 25.01.2021
/// This code is for educational purposes of the course "Introduction
/// to programming" provided by the Faculty of Computer Science
/// at the Higher School of Economics.
///
/// Create a program that performs the following steps:
/// 1. Reads three integer numbers from input.
/// 2. Multiplies each number by 2.
/// 3. Concatenates the results into a single large number.
/// 4. Multiplies the result by 2.
/// 5. Outputs the resulting number.
///
/// Use stringstream for type converstion between numbers and strings.
/// (Additional) Use a debugger to check that at each step the strings and
/// numbers hold the correct values.
///
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <sstream>
int main()
{
using std::cout;
using std::cin;
// TODO: provide your implementation here
cout << "\n\n";
return 0;
}
| 30.564103 | 81 | 0.564597 | dsba2020-z |
33d9f85d13e0f54d4fe7cdcd1f481d7cb4783d0f | 6,721 | cpp | C++ | strategies/src/moving_averages_crossing/moving_average_crossing.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 21 | 2020-06-07T20:34:47.000Z | 2021-08-10T20:19:59.000Z | strategies/src/moving_averages_crossing/moving_average_crossing.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | null | null | null | strategies/src/moving_averages_crossing/moving_average_crossing.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 4 | 2020-07-13T10:19:44.000Z | 2022-03-11T12:15:43.000Z | /*
* Copyright (c) 2020, Rapprise.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <set>
#include "common/exceptions/strategy_exception/small_analyzed_period_exception.h"
#include "common/exceptions/undefined_type_exception.h"
#include "common/loggers/file_logger.h"
#include "include/exponential_moving_average/exponential_moving_average.h"
#include "include/moving_averages_crossing/moving_averages_crossing.h"
#include "include/simple_moving_average/simple_moving_average.h"
constexpr unsigned int MIN_MOVING_AVERAGES_COUNT = 2;
namespace auto_trader {
namespace strategies {
void MovingAveragesCrossing::createLines(const std::vector<common::MarketData> &marketData,
int smallerPeriodSize, int biggerPeriodSize,
double lastBuyCrossingPoint, double lastSellCrossingPoint,
common::MovingAverageType type) {
crossingForSellSignal_.second = false;
crossingForBuySignal_.second = false;
if (marketData.size() == 0 || marketData.size() < biggerPeriodSize) {
common::loggers::FileLogger::getLogger() << "MAC: bad data for creating lines.";
throw common::exceptions::StrategyException(
"Moving Averages Crossing: not valid data for creating lines");
}
lastBuyCrossingPoint_ = lastBuyCrossingPoint;
lastSellCrossingPoint_ = lastSellCrossingPoint;
auto movingAveragePtr = createMovingAverage(type);
movingAveragePtr->createLine(marketData, smallerPeriodSize);
smallerPeriodLine_ = movingAveragePtr->getLine();
movingAveragePtr->createLine(marketData, biggerPeriodSize);
biggerPeriodLine_ = movingAveragePtr->getLine();
crossingToBuySignal();
crossingToSellSignal();
}
std::shared_ptr<MovingAverageBase> MovingAveragesCrossing::createMovingAverage(
common::MovingAverageType type) {
switch (type) {
case common::MovingAverageType::EXPONENTIAL:
return std::make_shared<ExponentialMovingAverage>();
case common::MovingAverageType::SIMPLE:
return std::make_shared<SimpleMovingAverage>();
default:
break;
}
throw common::exceptions::UndefinedTypeException("Moving Average Type");
}
MovingAverageLine MovingAveragesCrossing::getSmallerPeriodLine() const {
return smallerPeriodLine_;
}
MovingAverageLine MovingAveragesCrossing::getBiggerPeriodLine() const { return biggerPeriodLine_; }
bool MovingAveragesCrossing::isNeedToBuy() const { return crossingForBuySignal_.second; }
bool MovingAveragesCrossing::isNeedToSell() const { return crossingForSellSignal_.second; }
double MovingAveragesCrossing::getLastBuyCrossingPoint() const { return lastBuyCrossingPoint_; }
double MovingAveragesCrossing::getLastSellCrossingPoint() const { return lastSellCrossingPoint_; }
void MovingAveragesCrossing::setCrossingInterval(unsigned int crossingInterval) {
crossingInterval_ = crossingInterval;
}
void MovingAveragesCrossing::crossingToBuySignal() {
auto lowerPeriodLineSize = smallerPeriodLine_.getSize();
auto highPeriodLineSize = biggerPeriodLine_.getSize();
auto beforeTheLastPointLowerPeriodLine = smallerPeriodLine_.getPoint(lowerPeriodLineSize - 2);
auto beforeTheLastPointHighPeriodLine = biggerPeriodLine_.getPoint(highPeriodLineSize - 2);
auto lastLowerLinePoint = smallerPeriodLine_.getLastPoint();
auto lastHighLinePoint = biggerPeriodLine_.getLastPoint();
if (beforeTheLastPointLowerPeriodLine < beforeTheLastPointHighPeriodLine &&
lastLowerLinePoint > lastHighLinePoint) {
auto isDuplicate = isBuyCrossingDuplicatedOnInterval();
if (!isDuplicate) {
lastBuyCrossingPoint_ = lastLowerLinePoint;
crossingForBuySignal_.second = true;
} else {
crossingForBuySignal_.second = false;
}
} else {
crossingForBuySignal_.second = false;
}
}
void MovingAveragesCrossing::crossingToSellSignal() {
auto lowerPeriodLineSize = smallerPeriodLine_.getSize();
auto highPeriodLineSize = biggerPeriodLine_.getSize();
auto beforeTheLastPointLowerPeriodLine = smallerPeriodLine_.getPoint(lowerPeriodLineSize - 2);
auto beforeTheLastPointHighPeriodLine = biggerPeriodLine_.getPoint(highPeriodLineSize - 2);
auto lastLowerLinePoint = smallerPeriodLine_.getLastPoint();
auto lastHighLinePoint = biggerPeriodLine_.getLastPoint();
if (beforeTheLastPointLowerPeriodLine > beforeTheLastPointHighPeriodLine &&
lastLowerLinePoint < lastHighLinePoint) {
auto isDuplicate = isSellCrossingDuplicatedOnInterval();
if (!isDuplicate) {
lastSellCrossingPoint_ = lastLowerLinePoint;
crossingForSellSignal_.second = true;
} else {
crossingForSellSignal_.second = false;
}
} else {
crossingForSellSignal_.second = false;
}
}
bool MovingAveragesCrossing::isBuyCrossingDuplicatedOnInterval() const {
auto lineSize = smallerPeriodLine_.getSize();
for (size_t index = lineSize - 1; index >= lineSize - crossingInterval_ - 1; --index) {
if (smallerPeriodLine_.getPoint(index) == lastBuyCrossingPoint_) return true;
}
return false;
}
bool MovingAveragesCrossing::isSellCrossingDuplicatedOnInterval() const {
auto lineSize = smallerPeriodLine_.getSize();
for (size_t index = lineSize - 1; index >= lineSize - crossingInterval_ - 1; --index) {
if (smallerPeriodLine_.getPoint(index) == lastSellCrossingPoint_) return true;
}
return false;
}
} // namespace strategies
} // namespace auto_trader | 39.769231 | 99 | 0.767743 | Rapprise |
33dabeba49d27b05f1ba25ee914e1af5babc18b6 | 11,616 | hpp | C++ | external/include/boost/proto/domain.hpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | external/include/boost/proto/domain.hpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | external/include/boost/proto/domain.hpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | ///////////////////////////////////////////////////////////////////////////////
/// \file domain.hpp
/// Contains definition of domain\<\> class template and helpers for
/// defining domains with a generator and a grammar for controlling
/// operator overloading.
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROTO_DOMAIN_HPP_EAN_02_13_2007
#define BOOST_PROTO_DOMAIN_HPP_EAN_02_13_2007
#include <boost/ref.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/proto/proto_fwd.hpp>
#include <boost/proto/generate.hpp>
#include <boost/proto/detail/as_expr.hpp>
#include <boost/proto/detail/deduce_domain.hpp>
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4714) // function 'xxx' marked as __forceinline not inlined
#endif
namespace boost { namespace proto
{
namespace detail
{
struct not_a_generator
{};
struct not_a_grammar
{};
struct not_a_domain
{};
}
namespace domainns_
{
/// \brief For use in defining domain tags to be used
/// with \c proto::extends\<\>. A \e Domain associates
/// an expression type with a \e Generator, and optionally
/// a \e Grammar.
///
/// The Generator determines how new expressions in the
/// domain are constructed. Typically, a generator wraps
/// all new expressions in a wrapper that imparts
/// domain-specific behaviors to expressions within its
/// domain. (See \c proto::extends\<\>.)
///
/// The Grammar determines whether a given expression is
/// valid within the domain, and automatically disables
/// any operator overloads which would cause an invalid
/// expression to be created. By default, the Grammar
/// parameter defaults to the wildcard, \c proto::_, which
/// makes all expressions valid within the domain.
///
/// The Super declares the domain currently being defined
/// to be a sub-domain of Super. Expressions in sub-domains
/// can be freely combined with expressions in its super-
/// domain (and <I>its</I> super-domain, etc.).
///
/// Example:
/// \code
/// template<typename Expr>
/// struct MyExpr;
///
/// struct MyGrammar
/// : or_< terminal<_>, plus<MyGrammar, MyGrammar> >
/// {};
///
/// // Define MyDomain, in which all expressions are
/// // wrapped in MyExpr<> and only expressions that
/// // conform to MyGrammar are allowed.
/// struct MyDomain
/// : domain<generator<MyExpr>, MyGrammar>
/// {};
///
/// // Use MyDomain to define MyExpr
/// template<typename Expr>
/// struct MyExpr
/// : extends<Expr, MyExpr<Expr>, MyDomain>
/// {
/// // ...
/// };
/// \endcode
///
template<
typename Generator // = default_generator
, typename Grammar // = proto::_
, typename Super // = no_super_domain
>
struct domain
: Generator
{
typedef Generator proto_generator;
typedef Grammar proto_grammar;
typedef Super proto_super_domain;
typedef domain proto_base_domain;
/// INTERNAL ONLY
typedef void proto_is_domain_;
/// \brief A unary MonomorphicFunctionObject that turns objects into Proto
/// expression objects in this domain.
///
/// The <tt>as_expr\<\></tt> function object turns objects into Proto expressions, if
/// they are not already, by making them Proto terminals held by value if
/// possible. Objects that are already Proto expressions are left alone.
///
/// If <tt>wants_basic_expr\<Generator\>::value</tt> is true, then let \c E be \c basic_expr;
/// otherwise, let \t E be \c expr. Given an lvalue \c t of type \c T:
///
/// If \c T is not a Proto expression type the resulting terminal is
/// calculated as follows:
///
/// If \c T is a function type, an abstract type, or a type derived from
/// \c std::ios_base, let \c A be <tt>T &</tt>.
/// Otherwise, let \c A be the type \c T stripped of cv-qualifiers.
/// Then, the result of applying <tt>as_expr\<T\>()(t)</tt> is
/// <tt>Generator()(E\<tag::terminal, term\<A\> \>::make(t))</tt>.
///
/// If \c T is a Proto expression type and its generator type is different from
/// \c Generator, the result is <tt>Generator()(t)</tt>.
///
/// Otherwise, the result is \c t converted to an (un-const) rvalue.
///
template<typename T, typename IsExpr = void, typename Callable = proto::callable>
struct as_expr
: detail::as_expr<
T
, typename detail::base_generator<Generator>::type
, wants_basic_expr<Generator>::value
>
{
BOOST_PROTO_CALLABLE()
};
/// INTERNAL ONLY
///
template<typename T>
struct as_expr<T, typename T::proto_is_expr_, proto::callable>
{
BOOST_PROTO_CALLABLE()
typedef typename remove_const<T>::type result_type;
BOOST_FORCEINLINE
result_type operator()(T &e) const
{
return e;
}
};
/// \brief A unary MonomorphicFunctionObject that turns objects into Proto
/// expression objects in this domain.
///
/// The <tt>as_child\<\></tt> function object turns objects into Proto expressions, if
/// they are not already, by making them Proto terminals held by reference.
/// Objects that are already Proto expressions are simply returned by reference.
///
/// If <tt>wants_basic_expr\<Generator\>::value</tt> is true, then let \c E be \c basic_expr;
/// otherwise, let \t E be \c expr. Given an lvalue \c t of type \c T:
///
/// If \c T is not a Proto expression type the resulting terminal is
/// <tt>Generator()(E\<tag::terminal, term\<T &\> \>::make(t))</tt>.
///
/// If \c T is a Proto expression type and its generator type is different from
/// \c Generator, the result is <tt>Generator()(t)</tt>.
///
/// Otherwise, the result is the lvalue \c t.
///
template<typename T, typename IsExpr = void, typename Callable = proto::callable>
struct as_child
: detail::as_child<
T
, typename detail::base_generator<Generator>::type
, wants_basic_expr<Generator>::value
>
{
BOOST_PROTO_CALLABLE()
};
/// INTERNAL ONLY
///
template<typename T>
struct as_child<T, typename T::proto_is_expr_, proto::callable>
{
BOOST_PROTO_CALLABLE()
typedef T &result_type;
BOOST_FORCEINLINE
result_type operator()(T &e) const
{
return e;
}
};
};
/// \brief The domain expressions have by default, if
/// \c proto::extends\<\> has not been used to associate
/// a domain with an expression.
///
struct default_domain
: domain<>
{};
/// \brief A domain to use when you prefer the use of
/// \c proto::basic_expr\<\> over \c proto::expr\<\>.
///
struct basic_default_domain
: domain<basic_default_generator>
{};
/// \brief A pseudo-domain for use in functions and
/// metafunctions that require a domain parameter. It
/// indicates that the domain of the parent node should
/// be inferred from the domains of the child nodes.
///
/// \attention \c deduce_domain is not itself a valid domain.
///
struct deduce_domain
: domain<detail::not_a_generator, detail::not_a_grammar, detail::not_a_domain>
{};
/// \brief Given a domain, a tag type and an argument list,
/// compute the type of the expression to generate. This is
/// either an instance of \c proto::expr\<\> or
/// \c proto::basic_expr\<\>.
///
template<typename Domain, typename Tag, typename Args, bool WantsBasicExpr>
struct base_expr
{
typedef proto::expr<Tag, Args, Args::arity> type;
};
/// INTERNAL ONLY
///
template<typename Domain, typename Tag, typename Args>
struct base_expr<Domain, Tag, Args, true>
{
typedef proto::basic_expr<Tag, Args, Args::arity> type;
};
}
/// A metafunction that returns \c mpl::true_
/// if the type \c T is the type of a Proto domain;
/// \c mpl::false_ otherwise. If \c T inherits from
/// \c proto::domain\<\>, \c is_domain\<T\> is
/// \c mpl::true_.
template<typename T, typename Void /* = void*/>
struct is_domain
: mpl::false_
{};
/// INTERNAL ONLY
///
template<typename T>
struct is_domain<T, typename T::proto_is_domain_>
: mpl::true_
{};
/// A metafunction that returns the domain of
/// a given type. If \c T is a Proto expression
/// type, it returns that expression's associated
/// domain. If not, it returns
/// \c proto::default_domain.
template<typename T, typename Void /* = void*/>
struct domain_of
{
typedef default_domain type;
};
/// INTERNAL ONLY
///
template<typename T>
struct domain_of<T, typename T::proto_is_expr_>
{
typedef typename T::proto_domain type;
};
/// INTERNAL ONLY
///
template<typename T>
struct domain_of<T &, void>
{
typedef typename domain_of<T>::type type;
};
/// INTERNAL ONLY
///
template<typename T>
struct domain_of<boost::reference_wrapper<T>, void>
{
typedef typename domain_of<T>::type type;
};
/// INTERNAL ONLY
///
template<typename T>
struct domain_of<boost::reference_wrapper<T> const, void>
{
typedef typename domain_of<T>::type type;
};
/// A metafunction that returns \c mpl::true_
/// if the type \c SubDomain is a sub-domain of
/// \c SuperDomain; \c mpl::false_ otherwise.
template<typename SubDomain, typename SuperDomain>
struct is_sub_domain_of
: is_sub_domain_of<typename SubDomain::proto_super_domain, SuperDomain>
{};
/// INTERNAL ONLY
///
template<typename SuperDomain>
struct is_sub_domain_of<proto::no_super_domain, SuperDomain>
: mpl::false_
{};
/// INTERNAL ONLY
///
template<typename SuperDomain>
struct is_sub_domain_of<SuperDomain, SuperDomain>
: mpl::true_
{};
}}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif
| 34.366864 | 105 | 0.557335 | sbrown-uhd |
33dea591772d1b2c41ef7468c9f59744cbd25b4e | 1,318 | hpp | C++ | Engine/Engine.hpp | Patryk404/Tetris-sfml | 9bfc01726e7996184c4499addbb1eed02c735a12 | [
"MIT"
] | null | null | null | Engine/Engine.hpp | Patryk404/Tetris-sfml | 9bfc01726e7996184c4499addbb1eed02c735a12 | [
"MIT"
] | null | null | null | Engine/Engine.hpp | Patryk404/Tetris-sfml | 9bfc01726e7996184c4499addbb1eed02c735a12 | [
"MIT"
] | null | null | null | #include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <time.h>
#pragma once
#include "../Blocks/Block.hpp"
#include "../Map/Map.hpp"
class Engine {
public:
Engine();
void move();
void rotation();
void tick(Block block[]);
void check_lines();
void check_gameover();
void run_timer();
void set_default();
void check_events(sf::Event &event);
void render(sf::RenderWindow &window,sf::Text game_over[]);
private:
const int figures[7][4] =
{
{1,3,5,7}, // I
{2,4,5,7}, // Z
{3,5,4,6}, // S
{3,5,4,7}, // T
{2,3,5,7}, // L
{3,5,7,6}, // J
{2,3,4,5} // O
};
float time;
int delay;
bool game;
int direction;
int score;
bool rotate;
bool first;
bool play_once;
sf::Music music;
sf::SoundBuffer buffer;
sf::SoundBuffer game_over_buffer;
sf::Sound dissmiss;
sf::Sound gameover;
sf::RectangleShape s;
sf::Clock timer;
Block a[4],b[4];
Map Map;
bool check();
friend class UI;
};
| 24.867925 | 67 | 0.456753 | Patryk404 |
33e030a5735e8e0a59ea50d1306e22d76f02af62 | 9,170 | cpp | C++ | scene/gui/box_container.cpp | kingoftheconnors/godot | e93af13959e2840e6fed58fb79ec4f7b9fdfec6a | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2021-06-04T14:29:54.000Z | 2021-06-04T14:29:54.000Z | scene/gui/box_container.cpp | kingoftheconnors/godot | e93af13959e2840e6fed58fb79ec4f7b9fdfec6a | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 6 | 2020-10-05T20:00:21.000Z | 2021-07-10T19:07:27.000Z | scene/gui/box_container.cpp | kingoftheconnors/godot | e93af13959e2840e6fed58fb79ec4f7b9fdfec6a | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 2 | 2020-12-28T13:10:08.000Z | 2021-12-31T20:53:18.000Z | /*************************************************************************/
/* box_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "box_container.h"
#include "label.h"
#include "margin_container.h"
struct _MinSizeCache {
int min_size;
bool will_stretch;
int final_size;
};
void BoxContainer::_resort() {
/** First pass, determine minimum size AND amount of stretchable elements */
Size2i new_size = get_size();
int sep = get_theme_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
int children_count = 0;
int stretch_min = 0;
int stretch_avail = 0;
float stretch_ratio_total = 0;
Map<Control *, _MinSizeCache> min_size_cache;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
Size2i size = c->get_combined_minimum_size();
_MinSizeCache msc;
if (vertical) { /* VERTICAL */
stretch_min += size.height;
msc.min_size = size.height;
msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
} else { /* HORIZONTAL */
stretch_min += size.width;
msc.min_size = size.width;
msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND;
}
if (msc.will_stretch) {
stretch_avail += msc.min_size;
stretch_ratio_total += c->get_stretch_ratio();
}
msc.final_size = msc.min_size;
min_size_cache[c] = msc;
children_count++;
}
if (children_count == 0) {
return;
}
int stretch_max = (vertical ? new_size.height : new_size.width) - (children_count - 1) * sep;
int stretch_diff = stretch_max - stretch_min;
if (stretch_diff < 0) {
//avoid negative stretch space
stretch_diff = 0;
}
stretch_avail += stretch_diff; //available stretch space.
/** Second, pass successively to discard elements that can't be stretched, this will run while stretchable
elements exist */
bool has_stretched = false;
while (stretch_ratio_total > 0) { // first of all, don't even be here if no stretchable objects exist
has_stretched = true;
bool refit_successful = true; //assume refit-test will go well
float error = 0; // Keep track of accumulated error in pixels
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
ERR_FAIL_COND(!min_size_cache.has(c));
_MinSizeCache &msc = min_size_cache[c];
if (msc.will_stretch) { //wants to stretch
//let's see if it can really stretch
float final_pixel_size = stretch_avail * c->get_stretch_ratio() / stretch_ratio_total;
// Add leftover fractional pixels to error accumulator
error += final_pixel_size - (int)final_pixel_size;
if (final_pixel_size < msc.min_size) {
//if available stretching area is too small for widget,
//then remove it from stretching area
msc.will_stretch = false;
stretch_ratio_total -= c->get_stretch_ratio();
refit_successful = false;
stretch_avail -= msc.min_size;
msc.final_size = msc.min_size;
break;
} else {
msc.final_size = final_pixel_size;
// Dump accumulated error if one pixel or more
if (error >= 1) {
msc.final_size += 1;
error -= 1;
}
}
}
}
if (refit_successful) { //uf refit went well, break
break;
}
}
/** Final pass, draw and stretch elements **/
int ofs = 0;
if (!has_stretched) {
switch (align) {
case ALIGN_BEGIN:
break;
case ALIGN_CENTER:
ofs = stretch_diff / 2;
break;
case ALIGN_END:
ofs = stretch_diff;
break;
}
}
first = true;
int idx = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
_MinSizeCache &msc = min_size_cache[c];
if (first) {
first = false;
} else {
ofs += sep;
}
int from = ofs;
int to = ofs + msc.final_size;
if (msc.will_stretch && idx == children_count - 1) {
//adjust so the last one always fits perfect
//compensating for numerical imprecision
to = vertical ? new_size.height : new_size.width;
}
int size = to - from;
Rect2 rect;
if (vertical) {
rect = Rect2(0, from, new_size.width, size);
} else {
rect = Rect2(from, 0, size, new_size.height);
}
fit_child_in_rect(c, rect);
ofs = to;
idx++;
}
}
Size2 BoxContainer::get_minimum_size() const {
/* Calculate MINIMUM SIZE */
Size2i minimum;
int sep = get_theme_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
if (!c->is_visible()) {
continue;
}
Size2i size = c->get_combined_minimum_size();
if (vertical) { /* VERTICAL */
if (size.width > minimum.width) {
minimum.width = size.width;
}
minimum.height += size.height + (first ? 0 : sep);
} else { /* HORIZONTAL */
if (size.height > minimum.height) {
minimum.height = size.height;
}
minimum.width += size.width + (first ? 0 : sep);
}
first = false;
}
return minimum;
}
void BoxContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
case NOTIFICATION_THEME_CHANGED: {
minimum_size_changed();
} break;
}
}
void BoxContainer::set_alignment(AlignMode p_align) {
align = p_align;
_resort();
}
BoxContainer::AlignMode BoxContainer::get_alignment() const {
return align;
}
void BoxContainer::add_spacer(bool p_begin) {
Control *c = memnew(Control);
c->set_mouse_filter(MOUSE_FILTER_PASS); //allow spacer to pass mouse events
if (vertical) {
c->set_v_size_flags(SIZE_EXPAND_FILL);
} else {
c->set_h_size_flags(SIZE_EXPAND_FILL);
}
add_child(c);
if (p_begin) {
move_child(c, 0);
}
}
BoxContainer::BoxContainer(bool p_vertical) {
vertical = p_vertical;
align = ALIGN_BEGIN;
}
void BoxContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_spacer", "begin"), &BoxContainer::add_spacer);
ClassDB::bind_method(D_METHOD("get_alignment"), &BoxContainer::get_alignment);
ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &BoxContainer::set_alignment);
BIND_ENUM_CONSTANT(ALIGN_BEGIN);
BIND_ENUM_CONSTANT(ALIGN_CENTER);
BIND_ENUM_CONSTANT(ALIGN_END);
ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment", "get_alignment");
}
MarginContainer *VBoxContainer::add_margin_child(const String &p_label, Control *p_control, bool p_expand) {
Label *l = memnew(Label);
l->set_text(p_label);
add_child(l);
MarginContainer *mc = memnew(MarginContainer);
mc->add_theme_constant_override("margin_left", 0);
mc->add_child(p_control);
add_child(mc);
if (p_expand) {
mc->set_v_size_flags(SIZE_EXPAND_FILL);
}
return mc;
}
| 28.042813 | 129 | 0.618757 | kingoftheconnors |
33e3f4bfa8178f6ca4828664f24947e7ae3471f8 | 5,460 | cpp | C++ | sp/src/game/client/view_scene.cpp | tingtom/Fodder | 3250572dbc56547709f564ba68e451b21660cdb4 | [
"Unlicense"
] | 12 | 2016-09-24T02:47:18.000Z | 2020-12-29T16:16:52.000Z | sp/src/game/client/view_scene.cpp | tingtom/Fodder | 3250572dbc56547709f564ba68e451b21660cdb4 | [
"Unlicense"
] | 31 | 2016-11-27T14:38:02.000Z | 2020-06-03T11:11:29.000Z | sp/src/game/client/view_scene.cpp | tingtom/Fodder | 3250572dbc56547709f564ba68e451b21660cdb4 | [
"Unlicense"
] | 6 | 2015-02-20T06:11:13.000Z | 2018-11-15T08:22:01.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Responsible for drawing the scene
//
//===========================================================================//
#include "cbase.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/imaterialsystemhardwareconfig.h"
#include "rendertexture.h"
#include "view_scene.h"
#include "viewrender.h"
#include "headtrack/isourcevirtualreality.h"
#include "client_virtualreality.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Convars related to controlling rendering
//-----------------------------------------------------------------------------
ConVar r_updaterefracttexture( "r_updaterefracttexture", "1", FCVAR_CHEAT );
ConVar r_depthoverlay( "r_depthoverlay", "0", FCVAR_CHEAT, "Replaces opaque objects with their grayscaled depth values. r_showz_power scales the output." );
int g_viewscene_refractUpdateFrame = 0;
bool g_bAllowMultipleRefractUpdatesPerScenePerFrame = false;
#if defined( _X360 )
class CAllowMultipleRefractsLogic : public CAutoGameSystem
{
public:
void LevelInitPreEntity()
{
// EP1 core room needs many refract updates per frame to avoid looking broken (ep1_citadel_03)
// Same with Kleiner's lab (d1_trainstation_05)
g_bAllowMultipleRefractUpdatesPerScenePerFrame = FStrEq( MapName(), "ep1_citadel_03" ) || FStrEq( MapName(), "d1_trainstation_05" );
}
};
static CAllowMultipleRefractsLogic s_AllowMultipleRefractsLogic;
#endif
void ViewTransform( const Vector &worldSpace, Vector &viewSpace )
{
const VMatrix &viewMatrix = engine->WorldToViewMatrix();
Vector3DMultiplyPosition( viewMatrix, worldSpace, viewSpace );
}
//-----------------------------------------------------------------------------
// Purpose: Transforms a world-space position into a 2D position inside a supplied frustum.
//-----------------------------------------------------------------------------
int FrustumTransform( const VMatrix &worldToSurface, const Vector& point, Vector& screen )
{
// UNDONE: Clean this up some, handle off-screen vertices
float w;
screen.x = worldToSurface[0][0] * point[0] + worldToSurface[0][1] * point[1] + worldToSurface[0][2] * point[2] + worldToSurface[0][3];
screen.y = worldToSurface[1][0] * point[0] + worldToSurface[1][1] * point[1] + worldToSurface[1][2] * point[2] + worldToSurface[1][3];
// z = worldToSurface[2][0] * point[0] + worldToSurface[2][1] * point[1] + worldToSurface[2][2] * point[2] + worldToSurface[2][3];
w = worldToSurface[3][0] * point[0] + worldToSurface[3][1] * point[1] + worldToSurface[3][2] * point[2] + worldToSurface[3][3];
// Just so we have something valid here
screen.z = 0.0f;
bool behind;
if( w < 0.001f )
{
behind = true;
screen.x *= 100000;
screen.y *= 100000;
}
else
{
behind = false;
float invw = 1.0f / w;
screen.x *= invw;
screen.y *= invw;
}
return behind;
}
//-----------------------------------------------------------------------------
// Purpose: UNDONE: Clean this up some, handle off-screen vertices
// Input : *point -
// *screen -
// Output : int
//-----------------------------------------------------------------------------
int ScreenTransform( const Vector& point, Vector& screen )
{
// UNDONE: Clean this up some, handle off-screen vertices
return FrustumTransform ( engine->WorldToScreenMatrix(), point, screen );
}
//-----------------------------------------------------------------------------
// Purpose: Same as ScreenTransform, but transforms to HUD space.
// These are totally different things in VR mode!
//-----------------------------------------------------------------------------
int HudTransform( const Vector& point, Vector& screen )
{
if ( UseVR() )
{
return FrustumTransform ( g_ClientVirtualReality.GetHudProjectionFromWorld(), point, screen );
}
else
{
return FrustumTransform ( engine->WorldToScreenMatrix(), point, screen );
}
}
void UpdateFullScreenDepthTexture( void )
{
if( !g_pMaterialSystemHardwareConfig->SupportsPixelShaders_2_b() )
return;
ITexture *pDepthTex = GetFullFrameDepthTexture();
CMatRenderContextPtr pRenderContext( materials );
if( IsX360() )
{
pRenderContext->CopyRenderTargetToTextureEx( pDepthTex, -1, NULL, NULL );
}
else
{
pRenderContext->CopyRenderTargetToTextureEx( pDepthTex, 0, NULL, NULL );
}
pRenderContext->SetFullScreenDepthTextureValidityFlag( true );
if( r_depthoverlay.GetBool() )
{
IMaterial *pMaterial = materials->FindMaterial( "debug/showz", TEXTURE_GROUP_OTHER, true );
pMaterial->IncrementReferenceCount();
IMaterialVar *BaseTextureVar = pMaterial->FindVar( "$basetexture", NULL, false );
IMaterialVar *pDepthInAlpha = NULL;
if( IsPC() )
{
pDepthInAlpha = pMaterial->FindVar( "$ALPHADEPTH", NULL, false );
pDepthInAlpha->SetIntValue( 1 );
}
BaseTextureVar->SetTextureValue( pDepthTex );
pRenderContext->OverrideDepthEnable( true, false ); //don't write to depth, or else we'll never see translucents
pRenderContext->DrawScreenSpaceQuad( pMaterial );
pRenderContext->OverrideDepthEnable( false, true );
pMaterial->DecrementReferenceCount();
}
}
| 35 | 157 | 0.61337 | tingtom |
33e545f539c638f2cb465f4dc3b0e170baba2fb6 | 1,745 | cpp | C++ | samples/CoreAPI_PointSpriteTest/PointSpriteTestApp.cpp | odayibasi/swengine | ef07b7c9125d01596837a423a9f3dcbced1f5aa7 | [
"Zlib",
"MIT"
] | 3 | 2021-03-01T20:41:13.000Z | 2021-07-10T13:45:47.000Z | samples/CoreAPI_PointSpriteTest/PointSpriteTestApp.cpp | odayibasi/swengine | ef07b7c9125d01596837a423a9f3dcbced1f5aa7 | [
"Zlib",
"MIT"
] | null | null | null | samples/CoreAPI_PointSpriteTest/PointSpriteTestApp.cpp | odayibasi/swengine | ef07b7c9125d01596837a423a9f3dcbced1f5aa7 | [
"Zlib",
"MIT"
] | null | null | null | //SWEngine
#include "../../include/SWEngine.h"
#pragma comment (lib,"../../lib/SWUtil.lib")
#pragma comment (lib,"../../lib/SWTypes.lib")
#pragma comment (lib,"../../lib/SWCore.lib")
#pragma comment (lib,"../../lib/SWEngine.lib")
swApplication pointSpriteApp;
int pointSpriteID=-1;
swPoint pointS[3];
swColor colorS[3];
//-------------------------------------------------------------------------------------------
void GameLoop(){
swGraphicsBeginScene();
swGraphicsSetBlendingMode(SW_BLENDING_MODE_ADDITIVE_ACCORDING2_ALPHA);
swGraphicsRenderPointSprite0(pointSpriteID,60,3,colorS,pointS);
swGraphicsEndScene();
}
//-------------------------------------------------------------------------------------------
void GameInit(){
pointSpriteID=swGraphicsCreatePointSprite("particleX.tga");
pointS[0].x=100; pointS[0].y=100;
colorS[0].r=0.2; colorS[0].g=0.8; colorS[0].b=0.8; colorS[0].a=0.5;
pointS[1].x=300; pointS[1].y=300;
colorS[1].r=0.8; colorS[1].g=0.8; colorS[1].b=0.8; colorS[1].a=1;
pointS[2].x=500; pointS[2].y=500;
colorS[2].r=1.0; colorS[2].g=0.1; colorS[2].b=0.1; colorS[2].a=1;
}
//-------------------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
//Application Settings
pointSpriteApp.hInstance=hInstance;
pointSpriteApp.fullScreen=false;
pointSpriteApp.cursor=true;
pointSpriteApp.width=800;
pointSpriteApp.height=600;
pointSpriteApp.title="Point Sprite";
pointSpriteApp.path="\\rsc\\PointSprites\\";
pointSpriteApp.appRun=GameLoop;
//Application Execution
swEngineInit(&pointSpriteApp);
GameInit();
swEngineRun();
swEngineExit();
return 0;
} | 25.661765 | 93 | 0.598281 | odayibasi |
33e6c449f6b19c517cbc22da4bff066717cefd83 | 3,867 | cc | C++ | arcane/src/arcane/mesh/DoFFamilyPolicyMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/mesh/DoFFamilyPolicyMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/mesh/DoFFamilyPolicyMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* DoFFamilyPolicyMng.cc (C) 2000-2016 */
/* */
/* Gestionnaire des politiques d'une famille de DoF. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/utils/NotSupportedException.h"
#include "arcane/mesh/ItemFamilyPolicyMng.h"
#include "arcane/mesh/ItemFamilyCompactPolicy.h"
#include "arcane/mesh/ItemFamilySerializer.h"
#include "arcane/mesh/IndirectItemFamilySerializer.h"
#include "arcane/mesh/DoFFamily.h"
#include "arcane/mesh/DynamicMesh.h"
#include "arcane/mesh/DynamicMeshIncrementalBuilder.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
ARCANE_MESH_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
class DoFFamilyCompactPolicy
: public ItemFamilyCompactPolicy
{
public:
DoFFamilyCompactPolicy(ItemFamily* family) : ItemFamilyCompactPolicy(family){}
public:
void updateInternalReferences(IMeshCompacter* compacter) override
{
// Pour l'instant ne fait rien car c'est la famille source qui gère la
// mise à jour dans ItemFamily::beginCompactItems().
ARCANE_UNUSED(compacter);
}
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Gestionnaire des politiques d'une famille de DoF.
*/
class ARCANE_MESH_EXPORT DoFFamilyPolicyMng
: public ItemFamilyPolicyMng
{
public:
DoFFamilyPolicyMng(DoFFamily* family)
: ItemFamilyPolicyMng(family,new DoFFamilyCompactPolicy(family))
, m_family(family){}
public:
IItemFamilySerializer* createSerializer(bool use_flags) override
{
if (use_flags)
throw NotSupportedException(A_FUNCINFO,"serialisation with 'use_flags==true'");
IMesh* mesh = m_family->mesh();
DynamicMesh* dmesh = ARCANE_CHECK_POINTER(dynamic_cast<DynamicMesh*>(mesh));
return new ItemFamilySerializer(m_family, m_family, dmesh->incrementalBuilder());
//return new IndirectItemFamilySerializer(m_family);
}
private:
DoFFamily* m_family;
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
extern "C++" ARCANE_MESH_EXPORT IItemFamilyPolicyMng*
createDoFFamilyPolicyMng(ItemFamily* family)
{
DoFFamily* f = ARCANE_CHECK_POINTER(dynamic_cast<DoFFamily*>(family));
return new DoFFamilyPolicyMng(f);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_MESH_END_NAMESPACE
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 40.705263 | 85 | 0.44091 | JeromeDuboisPro |
33e7b3fef67d51960183dd80a06465bf4843e744 | 69,509 | cpp | C++ | libgpopt/src/engine/CEngine.cpp | ppmht/gporca | 7131e3e134e6e608f7e9fef9152a8b5d71e6a59e | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libgpopt/src/engine/CEngine.cpp | ppmht/gporca | 7131e3e134e6e608f7e9fef9152a8b5d71e6a59e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/src/engine/CEngine.cpp | ppmht/gporca | 7131e3e134e6e608f7e9fef9152a8b5d71e6a59e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2009 - 2011 EMC Corp.
//
// @filename:
// CEngine.cpp
//
// @doc:
// Implementation of optimization engine
//---------------------------------------------------------------------------
#include "gpos/base.h"
#include "gpos/common/CAutoTimer.h"
#include "gpos/io/COstreamString.h"
#include "gpos/string/CWStringDynamic.h"
#include "gpos/task/CAutoTaskProxy.h"
#include "gpos/task/CAutoTraceFlag.h"
#include "gpos/memory/CAutoMemoryPool.h"
#include "gpopt/exception.h"
#include "gpopt/base/CDrvdPropCtxtPlan.h"
#include "gpopt/base/CCostContext.h"
#include "gpopt/base/COptimizationContext.h"
#include "gpopt/base/CReqdPropPlan.h"
#include "gpopt/base/CReqdPropRelational.h"
#include "gpopt/base/CQueryContext.h"
#include "gpopt/base/COptCtxt.h"
#include "gpopt/engine/CEngine.h"
#include "gpopt/engine/CEnumeratorConfig.h"
#include "gpopt/engine/CStatisticsConfig.h"
#include "gpopt/minidump/CSerializableStackTrace.h"
#include "gpopt/operators/CExpression.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CLogical.h"
#include "gpopt/operators/CPattern.h"
#include "gpopt/operators/CPatternLeaf.h"
#include "gpopt/operators/CPhysicalMotionGather.h"
#include "gpopt/operators/CPhysicalAgg.h"
#include "gpopt/operators/CPhysicalSort.h"
#include "gpopt/optimizer/COptimizerConfig.h"
#include "gpopt/search/CGroup.h"
#include "gpopt/search/CGroupExpression.h"
#include "gpopt/search/CGroupProxy.h"
#include "gpopt/search/CJob.h"
#include "gpopt/search/CJobFactory.h"
#include "gpopt/search/CMemo.h"
#include "gpopt/search/CScheduler.h"
#include "gpopt/search/CSchedulerContext.h"
#include "gpopt/xforms/CXformFactory.h"
#include "naucrates/traceflags/traceflags.h"
#define GPOPT_SAMPLING_MAX_ITERS 30
#define GPOPT_JOBS_CAP 5000 // maximum number of initial optimization jobs
#define GPOPT_JOBS_PER_GROUP 20 // estimated number of needed optimization jobs per memo group
// memory consumption unit in bytes -- currently MB
#define GPOPT_MEM_UNIT (1024 * 1024)
#define GPOPT_MEM_UNIT_NAME "MB"
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CEngine::CEngine
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CEngine::CEngine
(
IMemoryPool *pmp
)
:
m_pmp(pmp),
m_pqc(NULL),
m_pdrgpss(NULL),
m_ulCurrSearchStage(0),
m_pmemo(NULL),
m_pexprEnforcerPattern(NULL),
m_pxfs(NULL),
m_pdrgpulpXformCalls(NULL),
m_pdrgpulpXformTimes(NULL)
{
m_pmemo = GPOS_NEW(pmp) CMemo(pmp);
m_pexprEnforcerPattern = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CPatternLeaf(pmp));
m_pxfs = GPOS_NEW(pmp) CXformSet(pmp);
m_pdrgpulpXformCalls = GPOS_NEW(pmp) DrgPulp(pmp);
m_pdrgpulpXformTimes = GPOS_NEW(pmp) DrgPulp(pmp);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::~CEngine
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CEngine::~CEngine()
{
#ifdef GPOS_DEBUG
// in optimized build, we flush-down memory pools without leak checking,
// we can save time in optimized build by skipping all de-allocations here,
// we still have all de-llocations enabled in debug-build to detect any possible leaks
GPOS_DELETE(m_pmemo);
CRefCount::SafeRelease(m_pxfs);
m_pdrgpulpXformCalls->Release();
m_pdrgpulpXformTimes->Release();
m_pexprEnforcerPattern->Release();
CRefCount::SafeRelease(m_pdrgpss);
#endif // GPOS_DEBUG
}
//---------------------------------------------------------------------------
// @function:
// CEngine::InitLogicalExpression
//
// @doc:
// Initialize engine with a given expression
//
//---------------------------------------------------------------------------
void
CEngine::InitLogicalExpression
(
CExpression *pexpr
)
{
GPOS_ASSERT(NULL == m_pmemo->PgroupRoot() && "Root is already set");
GPOS_ASSERT(pexpr->Pop()->FLogical());
CGroup *pgroupRoot = PgroupInsert(NULL /*pgroupTarget*/, pexpr, CXform::ExfInvalid, NULL /*pgexprOrigin*/, false /*fIntermediate*/);
m_pmemo->SetRoot(pgroupRoot);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::Init
//
// @doc:
// Initialize engine using a given query context
//
//---------------------------------------------------------------------------
void
CEngine::Init
(
CQueryContext *pqc,
DrgPss *pdrgpss
)
{
GPOS_ASSERT(NULL == m_pqc);
GPOS_ASSERT(NULL != pqc);
GPOS_ASSERT_IMP
(
0 == CDrvdPropRelational::Pdprel(pqc->Pexpr()->PdpDerive())->PcrsOutput()->CElements(),
0 == pqc->Prpp()->PcrsRequired()->CElements() &&
"requiring columns from a zero column expression"
);
m_pdrgpss = pdrgpss;
if (NULL == pdrgpss)
{
m_pdrgpss = CSearchStage::PdrgpssDefault(m_pmp);
}
GPOS_ASSERT(0 < m_pdrgpss->UlLength());
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
// initialize per-stage xform calls array
const ULONG ulStages = m_pdrgpss->UlLength();
for (ULONG ul = 0; ul < ulStages; ul++)
{
ULONG_PTR *pulpXformCalls = GPOS_NEW_ARRAY(m_pmp, ULONG_PTR, CXform::ExfSentinel);
ULONG_PTR *pulpXformTimes = GPOS_NEW_ARRAY(m_pmp, ULONG_PTR, CXform::ExfSentinel);
for (ULONG ulXform = 0; ulXform < CXform::ExfSentinel; ulXform++)
{
pulpXformCalls[ulXform] = 0;
pulpXformTimes[ulXform] = 0;
}
m_pdrgpulpXformCalls->Append(pulpXformCalls);
m_pdrgpulpXformTimes->Append(pulpXformTimes);
}
}
m_pqc = pqc;
InitLogicalExpression(m_pqc->Pexpr());
m_pqc->PdrgpcrSystemCols()->AddRef();
COptCtxt::PoctxtFromTLS()->SetReqdSystemCols(m_pqc->PdrgpcrSystemCols());
}
//---------------------------------------------------------------------------
// @function:
// CEngine::AddEnforcers
//
// @doc:
// Add enforcers to a memo group
//
//---------------------------------------------------------------------------
void
CEngine::AddEnforcers
(
CGroupExpression *pgexpr, // belongs to group where we need to add enforcers
DrgPexpr *pdrgpexprEnforcers
)
{
GPOS_ASSERT(NULL != pdrgpexprEnforcers);
GPOS_ASSERT(NULL != pgexpr);
for (ULONG ul = 0; ul < pdrgpexprEnforcers->UlLength(); ul++)
{
// assemble an expression rooted by the enforcer operator
CExpression *pexprEnforcer = (*pdrgpexprEnforcers)[ul];
#ifdef GPOS_DEBUG
CGroup * pgroup =
#endif // GPOS_DEBUG
PgroupInsert(pgexpr->Pgroup(), pexprEnforcer, CXform::ExfInvalid, NULL /*pgexprOrigin*/, false /*fIntermediate*/);
GPOS_ASSERT(pgroup == pgexpr->Pgroup());
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::InsertExpressionChildren
//
// @doc:
// Insert children of the given expression to memo, and copy the groups
// they end up at to the given group array
//
//---------------------------------------------------------------------------
void
CEngine::InsertExpressionChildren
(
CExpression *pexpr,
DrgPgroup *pdrgpgroupChildren,
CXform::EXformId exfidOrigin,
CGroupExpression *pgexprOrigin
)
{
GPOS_ASSERT(NULL != pexpr);
GPOS_ASSERT(NULL != pdrgpgroupChildren);
ULONG ulArity = pexpr->UlArity();
for (ULONG i = 0; i < ulArity; i++)
{
CGroup *pgroupChild = NULL;
COperator *popChild = (*pexpr)[i]->Pop();
if (popChild->FPattern() && CPattern::PopConvert(popChild)->FLeaf())
{
GPOS_ASSERT(NULL != (*pexpr)[i]->Pgexpr()->Pgroup());
// group is already assigned during binding extraction;
pgroupChild = (*pexpr)[i]->Pgexpr()->Pgroup();
}
else
{
// insert child expression recursively
pgroupChild = PgroupInsert(NULL /*pgroupTarget*/, (*pexpr)[i], exfidOrigin, pgexprOrigin, true /*fIntermediate*/);
}
pdrgpgroupChildren->Append(pgroupChild);
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PgroupInsert
//
// @doc:
// Insert an expression tree into the memo, with explicit target group;
// the function returns a pointer to the group that contains the given
// group expression
//
//---------------------------------------------------------------------------
CGroup *
CEngine::PgroupInsert
(
CGroup *pgroupTarget,
CExpression *pexpr,
CXform::EXformId exfidOrigin,
CGroupExpression *pgexprOrigin,
BOOL fIntermediate
)
{
// recursive function - check stack
GPOS_CHECK_STACK_SIZE;
GPOS_CHECK_ABORT;
GPOS_ASSERT_IMP(CXform::ExfInvalid != exfidOrigin, NULL != pgexprOrigin);
CGroup *pgroupOrigin = NULL;
// check if expression was produced by extracting
// a binding from the memo
if (NULL != pexpr->Pgexpr())
{
pgroupOrigin = pexpr->Pgexpr()->Pgroup();
GPOS_ASSERT(NULL != pgroupOrigin && NULL == pgroupTarget &&
"A valid group is expected");
// if parent has group pointer, all children must have group pointers;
// terminate recursive insertion here
return pgroupOrigin;
}
// if we have a valid origin group, target group must be NULL
GPOS_ASSERT_IMP(NULL != pgroupOrigin, NULL == pgroupTarget);
// insert expression's children to memo by recursive call
DrgPgroup *pdrgpgroupChildren = GPOS_NEW(m_pmp) DrgPgroup(m_pmp, pexpr->UlArity());
InsertExpressionChildren(pexpr, pdrgpgroupChildren, exfidOrigin, pgexprOrigin);
COperator *pop = pexpr->Pop();
pop->AddRef();
CGroupExpression *pgexpr =
GPOS_NEW(m_pmp) CGroupExpression
(
m_pmp,
pop,
pdrgpgroupChildren,
exfidOrigin,
pgexprOrigin,
fIntermediate
);
// find the group that contains created group expression
CGroup *pgroupContainer = m_pmemo->PgroupInsert(pgroupTarget, pexpr, pgexpr);
if (NULL == pgexpr->Pgroup())
{
// insertion failed, release created group expression
pgexpr->Release();
}
return pgroupContainer;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::InsertXformResult
//
// @doc:
// Insert a set of transformation results to memo
//
//---------------------------------------------------------------------------
void
CEngine::InsertXformResult
(
CGroup *pgroupOrigin,
CXformResult *pxfres,
CXform::EXformId exfidOrigin,
CGroupExpression *pgexprOrigin,
ULONG ulXformTime // time consumed by transformation in msec
)
{
GPOS_ASSERT(NULL != pxfres);
GPOS_ASSERT(NULL != pgroupOrigin);
GPOS_ASSERT(CXform::ExfInvalid != exfidOrigin);
GPOS_ASSERT(NULL != pgexprOrigin);
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics) && 0 < pxfres->Pdrgpexpr()->UlLength())
{
(void) m_pxfs->FExchangeSet(exfidOrigin);
(void) UlpExchangeAdd(&(*m_pdrgpulpXformCalls)[m_ulCurrSearchStage][exfidOrigin], 1);
{
CAutoMutex am(m_mutexOptStats);
am.Lock();
(*m_pdrgpulpXformTimes)[m_ulCurrSearchStage][exfidOrigin] += ulXformTime;
}
}
CExpression *pexpr = pxfres->PexprNext();
while (NULL != pexpr)
{
CGroup *pgroupContainer = PgroupInsert(pgroupOrigin, pexpr, exfidOrigin, pgexprOrigin, false /*fIntermediate*/);
if (pgroupContainer != pgroupOrigin && FPossibleDuplicateGroups(pgroupContainer, pgroupOrigin))
{
m_pmemo->MarkDuplicates(pgroupOrigin, pgroupContainer);
}
pexpr = pxfres->PexprNext();
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FPossibleDuplicateGroups
//
// @doc:
// Check whether the given memo groups can be marked as duplicates. This is
// true only if they have the same logical properties
//
//---------------------------------------------------------------------------
BOOL
CEngine::FPossibleDuplicateGroups
(
CGroup *pgroupFst,
CGroup *pgroupSnd
)
{
GPOS_ASSERT(NULL != pgroupFst);
GPOS_ASSERT(NULL != pgroupSnd);
CDrvdPropRelational *pdprelFst = CDrvdPropRelational::Pdprel(pgroupFst->Pdp());
CDrvdPropRelational *pdprelSnd = CDrvdPropRelational::Pdprel(pgroupSnd->Pdp());
// right now we only check the output columns, but we may possibly need to
// check other properties as well
return pdprelFst->PcrsOutput()->FEqual(pdprelSnd->PcrsOutput());
}
//---------------------------------------------------------------------------
// @function:
// CEngine::DeriveStats
//
// @doc:
// Derive statistics on the root group
//
//---------------------------------------------------------------------------
void
CEngine::DeriveStats
(
IMemoryPool *pmpLocal
)
{
CWStringDynamic str(m_pmp);
COstreamString oss (&str);
oss << "\n[OPT]: Statistics Derivation Time (stage " << m_ulCurrSearchStage <<") ";
CHAR *sz = CUtils::SzFromWsz(m_pmp, const_cast<WCHAR *>(str.Wsz()));
{
CAutoTimer at(sz, GPOS_FTRACE(EopttracePrintOptimizationStatistics));
// derive stats on root group
CEngine::DeriveStats(pmpLocal, m_pmp, PgroupRoot(), NULL /*prprel*/);
}
GPOS_DELETE_ARRAY(sz);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::DeriveStats
//
// @doc:
// Derive statistics on the group
//
//---------------------------------------------------------------------------
void
CEngine::DeriveStats
(
IMemoryPool *pmpLocal,
IMemoryPool *pmpGlobal,
CGroup *pgroup,
CReqdPropRelational *prprel
)
{
CGroupExpression *pgexprFirst = CEngine::PgexprFirst(pgroup);
CExpressionHandle exprhdl(pmpGlobal);
exprhdl.Attach(pgexprFirst);
exprhdl.DeriveStats(pmpLocal, pmpGlobal, prprel, NULL /*pdrgpstatCtxt*/);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PgexprFirst
//
// @doc:
// Return the first group expression in a given group
//
//---------------------------------------------------------------------------
CGroupExpression *
CEngine::PgexprFirst
(
CGroup *pgroup
)
{
CGroupExpression *pgexprFirst = NULL;
{
// group proxy scope
CGroupProxy gp(pgroup);
pgexprFirst = gp.PgexprFirst();
}
GPOS_ASSERT(NULL != pgexprFirst);
return pgexprFirst;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::EolDamp
//
// @doc:
// Damp optimization level
//
//---------------------------------------------------------------------------
EOptimizationLevel
CEngine::EolDamp
(
EOptimizationLevel eol
)
{
if (EolHigh == eol)
{
return EolLow;
}
return EolSentinel;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FOptimizeChild
//
// @doc:
// Check if parent group expression needs to optimize child group expression.
// This method is called right before a group optimization job is about to
// schedule a group expression optimization job.
//
// Relation properties as well the optimizing parent group expression is
// available to make the decision. So, operators can reject being optimized
// under specific parent operators. For example, a GatherMerge under a Sort
// can be prevented here since it destroys the order from a GatherMerge.
//---------------------------------------------------------------------------
BOOL
CEngine::FOptimizeChild
(
CGroupExpression *pgexprParent,
CGroupExpression *pgexprChild,
COptimizationContext *pocChild,
EOptimizationLevel eolCurrent // current optimization level in child group
)
{
GPOS_ASSERT(NULL != PgroupRoot());
GPOS_ASSERT(PgroupRoot()->FImplemented());
GPOS_ASSERT(NULL != pgexprChild);
GPOS_ASSERT_IMP(NULL == pgexprParent, pgexprChild->Pgroup() == PgroupRoot());
if (pgexprParent == pgexprChild)
{
// a group expression cannot optimize itself
return false;
}
if (pgexprChild->Eol() != eolCurrent)
{
// child group expression does not match current optimization level
return false;
}
COperator *popChild = pgexprChild->Pop();
if (NULL != pgexprParent &&
COperator::EopPhysicalSort == pgexprParent->Pop()->Eopid() &&
COperator::EopPhysicalMotionGather == popChild->Eopid())
{
// prevent (Sort --> GatherMerge), since Sort destroys order maintained by GatherMerge
return !CPhysicalMotionGather::PopConvert(popChild)->FOrderPreserving();
}
return COptimizationContext::FOptimize(m_pmp, pgexprParent, pgexprChild, pocChild, UlSearchStages());
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FSafeToPruneWithDPEStats
//
// @doc:
// Determine if a plan rooted by given group expression can be safely
// pruned during optimization when stats for Dynamic Partition Elimination
// are derived
//
//---------------------------------------------------------------------------
BOOL
CEngine::FSafeToPruneWithDPEStats
(
CGroupExpression *pgexpr,
CReqdPropPlan *, // prpp
CCostContext *pccChild,
ULONG ulChildIndex
)
{
GPOS_ASSERT(GPOS_FTRACE(EopttraceDeriveStatsForDPE));
GPOS_ASSERT(GPOS_FTRACE(EopttraceEnableSpacePruning));
if (NULL == pccChild)
{
// group expression has not been optimized yet
CDrvdPropRelational *pdprel = CDrvdPropRelational::Pdprel(pgexpr->Pgroup()->Pdp());
if (0 < pdprel->Ppartinfo()->UlConsumers())
{
// we cannot bound cost here because of possible DPE that can happen below the operator
return false;
}
return true;
}
// first child has been optimized
CExpressionHandle exprhdl(m_pmp);
exprhdl.Attach(pgexpr);
ULONG ulNextChild = exprhdl.UlNextOptimizedChildIndex(ulChildIndex);
CDrvdPropRelational *pdprelChild = CDrvdPropRelational::Pdprel((*pgexpr)[ulNextChild]->Pdp());
if (0 < pdprelChild->Ppartinfo()->UlConsumers())
{
// we cannot bound cost here because of possible DPE that can happen for the unoptimized child
return false;
}
return true;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FSafeToPrune
//
// @doc:
// Determine if a plan rooted by given group expression can be safely
// pruned during optimization
//
//---------------------------------------------------------------------------
BOOL
CEngine::FSafeToPrune
(
CGroupExpression *pgexpr,
CReqdPropPlan *prpp,
CCostContext *pccChild,
ULONG ulChildIndex,
CCost *pcostLowerBound // output: a lower bound on plan's cost
)
{
GPOS_ASSERT(NULL != pcostLowerBound);
*pcostLowerBound = GPOPT_INVALID_COST;
if (!GPOS_FTRACE(EopttraceEnableSpacePruning))
{
// space pruning is disabled
return false;
}
if (GPOS_FTRACE(EopttraceDeriveStatsForDPE) &&
!FSafeToPruneWithDPEStats(pgexpr, prpp, pccChild, ulChildIndex))
{
// stat derivation for Dynamic Partition Elimination may not allow non-trivial cost bounds
return false;
}
// check if container group has a plan for given properties
CGroup *pgroup = pgexpr->Pgroup();
COptimizationContext *pocGroup = pgroup->PocLookupBest(m_pmp, UlSearchStages(), prpp);
if (NULL != pocGroup && NULL != pocGroup->PccBest())
{
// compute a cost lower bound for the equivalent plan rooted by given group expression
CCost costLowerBound = pgexpr->CostLowerBound(m_pmp, prpp, pccChild, ulChildIndex);
*pcostLowerBound = costLowerBound;
if (costLowerBound > pocGroup->PccBest()->Cost())
{
// group expression cannot deliver a better plan for given properties and can be safely pruned
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::Pmemotmap
//
// @doc:
// Build tree map on memo
//
//---------------------------------------------------------------------------
MemoTreeMap *
CEngine::Pmemotmap()
{
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
if (NULL == m_pmemo->Pmemotmap())
{
m_pqc->Prpp()->AddRef();
COptimizationContext *poc = GPOS_NEW(m_pmp) COptimizationContext
(
m_pmp,
PgroupRoot(),
m_pqc->Prpp(),
GPOS_NEW(m_pmp) CReqdPropRelational(GPOS_NEW(m_pmp) CColRefSet(m_pmp)), // pass empty required relational properties initially
GPOS_NEW(m_pmp) DrgPstat(m_pmp), // pass empty stats context initially
0 // ulSearchStageIndex
);
m_pmemo->BuildTreeMap(poc);
poconf->Pec()->SetPlanSpaceSize(m_pmemo->Pmemotmap()->UllCount());
poc->Release();
}
return m_pmemo->Pmemotmap();
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CEngine::ApplyTransformations
//
// @doc:
// Applies given set of xforms to group expression and insert
// results to memo
//
//---------------------------------------------------------------------------
void
CEngine::ApplyTransformations
(
IMemoryPool *pmpLocal,
CXformSet *pxfs,
CGroupExpression *pgexpr
)
{
// iterate over xforms
CXformSetIter xsi(*pxfs);
while (xsi.FAdvance())
{
GPOS_CHECK_ABORT;
CXform *pxform = CXformFactory::Pxff()->Pxf(xsi.TBit());
// transform group expression, and insert results to memo
CXformResult *pxfres = GPOS_NEW(m_pmp) CXformResult(m_pmp);
ULONG ulElapsedTime = 0;
pgexpr->Transform(m_pmp, pmpLocal, pxform, pxfres, &ulElapsedTime);
InsertXformResult(pgexpr->Pgroup(), pxfres, pxform->Exfid(), pgexpr, ulElapsedTime);
pxfres->Release();
if (PssCurrent()->FTimedOut())
{
break;
}
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::TransitionGroupExpression
//
// @doc:
// Transition group expression to a given target state
//
//---------------------------------------------------------------------------
void
CEngine::TransitionGroupExpression
(
IMemoryPool *pmpLocal,
CGroupExpression *pgexpr,
CGroupExpression::EState estTarget
)
{
GPOS_ASSERT(CGroupExpression::estExplored == estTarget ||
CGroupExpression::estImplemented == estTarget);
if (PssCurrent()->FTimedOut())
{
return;
}
CGroupExpression::EState estInitial = CGroupExpression::estExploring;
CGroup::EState estGroupTargetState = CGroup::estExplored;
if (CGroupExpression::estImplemented == estTarget)
{
estInitial = CGroupExpression::estImplementing;
estGroupTargetState = CGroup::estImplemented;
}
pgexpr->SetState(estInitial);
// transition all child groups
ULONG ulArity = pgexpr->UlArity();
for (ULONG i = 0; i < ulArity; i++)
{
TransitionGroup(pmpLocal, (*pgexpr)[i], estGroupTargetState);
GPOS_CHECK_ABORT;
}
// find which set of xforms should be used
CXformSet *pxfs = CXformFactory::Pxff()->PxfsExploration();
if (CGroupExpression::estImplemented == estTarget)
{
pxfs = CXformFactory::Pxff()->PxfsImplementation();
}
// get all applicable xforms
COperator *pop = pgexpr->Pop();
CXformSet *pxfsCandidates = CLogical::PopConvert(pop)->PxfsCandidates(m_pmp);
// intersect them with the required set of xforms, then apply transformations
pxfsCandidates->Intersection(pxfs);
pxfsCandidates->Intersection(PxfsCurrentStage());
ApplyTransformations(pmpLocal, pxfsCandidates, pgexpr);
pxfsCandidates->Release();
pgexpr->SetState(estTarget);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::TransitionGroup
//
// @doc:
// Transition group to a target state
//
//---------------------------------------------------------------------------
void
CEngine::TransitionGroup
(
IMemoryPool *pmpLocal,
CGroup *pgroup,
CGroup::EState estTarget
)
{
// check stack size
GPOS_CHECK_STACK_SIZE;
if (PssCurrent()->FTimedOut())
{
return;
}
GPOS_ASSERT(CGroup::estExplored == estTarget ||
CGroup::estImplemented == estTarget);
BOOL fTransitioned = false;
{
CGroupProxy gp(pgroup);
fTransitioned = gp.FTransitioned(estTarget);
}
// check if we can end recursion early
if (!fTransitioned)
{
CGroup::EState estInitial = CGroup::estExploring;
CGroupExpression::EState estGExprTargetState = CGroupExpression::estExplored;
if (CGroup::estImplemented == estTarget)
{
estInitial = CGroup::estImplementing;
estGExprTargetState = CGroupExpression::estImplemented;
}
CGroupExpression *pgexprCurrent = NULL;
// transition group's state to initial state
{
CGroupProxy gp(pgroup);
gp.SetState(estInitial);
}
// get first group expression
{
CGroupProxy gp(pgroup);
pgexprCurrent = gp.PgexprFirst();
}
while (NULL != pgexprCurrent)
{
if (!pgexprCurrent->FTransitioned(estGExprTargetState))
{
TransitionGroupExpression
(
pmpLocal,
pgexprCurrent,
estGExprTargetState
);
}
if (PssCurrent()->FTimedOut())
{
break;
}
// get next group expression
{
CGroupProxy gp(pgroup);
pgexprCurrent = gp.PgexprNext(pgexprCurrent);
}
GPOS_CHECK_ABORT;
}
// transition group to target state
{
CGroupProxy gp(pgroup);
gp.SetState(estTarget);
}
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PocChild
//
// @doc:
// Create optimization context for child group
//
//---------------------------------------------------------------------------
COptimizationContext *
CEngine::PocChild
(
CGroupExpression *pgexpr, // parent expression
COptimizationContext *pocOrigin, // optimization context of parent operator
CExpressionHandle &exprhdlPlan, // handle to compute required plan properties
CExpressionHandle &exprhdlRel, // handle to compute required relational properties
DrgPdp *pdrgpdpChildren, // derived plan properties of optimized children
DrgPstat *pdrgpstatCurrentCtxt,
ULONG ulChildIndex,
ULONG ulOptReq
)
{
GPOS_ASSERT(exprhdlPlan.Pgexpr() == pgexpr);
GPOS_ASSERT(NULL != pocOrigin);
GPOS_ASSERT(NULL != pdrgpdpChildren);
GPOS_ASSERT(NULL != pdrgpstatCurrentCtxt);
CGroup *pgroupChild = (*pgexpr)[ulChildIndex];
// compute required properties of the n-th child
exprhdlPlan.ComputeChildReqdProps(ulChildIndex, pdrgpdpChildren, ulOptReq);
exprhdlPlan.Prpp(ulChildIndex)->AddRef();
// use current stats for optimizing current child
DrgPstat *pdrgpstatCtxt = GPOS_NEW(m_pmp) DrgPstat(m_pmp);
CUtils::AddRefAppend<IStatistics, CleanupStats>(pdrgpstatCtxt, pdrgpstatCurrentCtxt);
// compute required relational properties
CReqdPropRelational *prprel = NULL;
if (CPhysical::PopConvert(pgexpr->Pop())->FPassThruStats())
{
// copy requirements from origin context
prprel = pocOrigin->Prprel();
}
else
{
// retrieve requirements from handle
prprel = exprhdlRel.Prprel(ulChildIndex);
}
GPOS_ASSERT(NULL != prprel);
prprel->AddRef();
COptimizationContext *pocChild =
GPOS_NEW(m_pmp) COptimizationContext
(
m_pmp,
pgroupChild,
exprhdlPlan.Prpp(ulChildIndex),
prprel,
pdrgpstatCtxt,
m_ulCurrSearchStage
);
return pocChild;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PccOptimizeChild
//
// @doc:
// Optimize child group and return best cost context satisfying
// required properties
//
//---------------------------------------------------------------------------
CCostContext *
CEngine::PccOptimizeChild
(
CExpressionHandle &exprhdl, // initialized with required properties
CExpressionHandle &exprhdlRel,
COptimizationContext *pocOrigin, // optimization context of parent operator
DrgPdp *pdrgpdp,
DrgPstat *pdrgpstatCurrentCtxt,
ULONG ulChildIndex,
ULONG ulOptReq
)
{
CGroupExpression *pgexpr = exprhdl.Pgexpr();
CGroup *pgroupChild = (*exprhdl.Pgexpr())[ulChildIndex];
// create optimization context for child group
COptimizationContext *pocChild =
PocChild(pgexpr, pocOrigin, exprhdl, exprhdlRel, pdrgpdp, pdrgpstatCurrentCtxt, ulChildIndex, ulOptReq);
if (pgroupChild == pgexpr->Pgroup() && pocChild->FMatch(pocOrigin))
{
// child context is the same as origin context, this is a deadlock
pocChild->Release();
return NULL;
}
// optimize child group
CGroupExpression *pgexprChildBest = PgexprOptimize(pgroupChild, pocChild, pgexpr);
pocChild->Release();
if (NULL == pgexprChildBest || PssCurrent()->FTimedOut())
{
// failed to generate a plan for the child, or search stage is timed-out
return NULL;
}
// derive plan properties of child group optimal implementation
COptimizationContext *pocFound = pgroupChild->PocLookupBest(m_pmp, m_pdrgpss->UlLength(), exprhdl.Prpp(ulChildIndex));
GPOS_ASSERT(NULL != pocFound);
CCostContext *pccChildBest = pocFound->PccBest();
GPOS_ASSERT(NULL != pccChildBest);
// check if optimization can be early terminated after first child has been optimized
CCost costLowerBound(GPOPT_INVALID_COST);
if (exprhdl.UlFirstOptimizedChildIndex() == ulChildIndex &&
FSafeToPrune(pgexpr, pocOrigin->Prpp(), pccChildBest, ulChildIndex, &costLowerBound))
{
// failed to optimize child due to cost bounding
(void) pgexpr->PccComputeCost(m_pmp, pocOrigin, ulOptReq, NULL /*pdrgpoc*/, true /*fPruned*/, costLowerBound);
return NULL;
}
return pccChildBest;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PdrgpocOptimizeChildren
//
// @doc:
// Optimize child groups of a given group expression;
//
//---------------------------------------------------------------------------
DrgPoc *
CEngine::PdrgpocOptimizeChildren
(
CExpressionHandle &exprhdl, // initialized with required properties
COptimizationContext *pocOrigin, // optimization context of parent operator
ULONG ulOptReq
)
{
GPOS_ASSERT(NULL != exprhdl.Pgexpr());
CGroupExpression *pgexpr = exprhdl.Pgexpr();
const ULONG ulArity = exprhdl.UlArity();
if (0 == ulArity)
{
// return empty array if no children
return GPOS_NEW(m_pmp) DrgPoc(m_pmp);
}
// create array of child derived properties
DrgPdp *pdrgpdp = GPOS_NEW(m_pmp) DrgPdp(m_pmp);
// initialize current stats context with input stats context
DrgPstat *pdrgpstatCurrentCtxt = GPOS_NEW(m_pmp) DrgPstat(m_pmp);
CUtils::AddRefAppend<IStatistics, CleanupStats>(pdrgpstatCurrentCtxt, pocOrigin->Pdrgpstat());
// initialize required relational properties computation
CExpressionHandle exprhdlRel(m_pmp);
CGroupExpression *pgexprForStats = pgexpr->Pgroup()->PgexprBestPromise(m_pmp, pgexpr);
if (NULL != pgexprForStats)
{
exprhdlRel.Attach(pgexprForStats);
exprhdlRel.DeriveProps(NULL /*pdpctxt*/);
exprhdlRel.ComputeReqdProps(pocOrigin->Prprel(), 0 /*ulOptReq*/);
}
// iterate over child groups and optimize them
BOOL fSuccess = true;
ULONG ulChildIndex = exprhdl.UlFirstOptimizedChildIndex();
do
{
CGroup *pgroupChild = (*exprhdl.Pgexpr())[ulChildIndex];
if (pgroupChild->FScalar())
{
// skip scalar groups from optimization
continue;
}
CCostContext *pccChildBest = PccOptimizeChild(exprhdl, exprhdlRel, pocOrigin, pdrgpdp, pdrgpstatCurrentCtxt, ulChildIndex, ulOptReq);
if (NULL == pccChildBest)
{
fSuccess = false;
break;
}
CExpressionHandle exprhdlChild(m_pmp);
exprhdlChild.Attach(pccChildBest);
exprhdlChild.DerivePlanProps();
exprhdlChild.Pdp()->AddRef();
pdrgpdp->Append(exprhdlChild.Pdp());
// copy stats of child's best cost context to current stats context
IStatistics *pstat = pccChildBest->Pstats();
pstat->AddRef();
pdrgpstatCurrentCtxt->Append(pstat);
GPOS_CHECK_ABORT;
}
while (exprhdl.FNextChildIndex(&ulChildIndex));
pdrgpdp->Release();
pdrgpstatCurrentCtxt->Release();
if (!fSuccess)
{
return NULL;
}
// return child optimization contexts array
return PdrgpocChildren(m_pmp, exprhdl);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::OptimizeGroupExpression
//
// @doc:
// Optimize group expression under a given context
//
//---------------------------------------------------------------------------
void
CEngine::OptimizeGroupExpression
(
CGroupExpression *pgexpr,
COptimizationContext *poc
)
{
CGroup *pgroup = pgexpr->Pgroup();
const ULONG ulOptRequests = CPhysical::PopConvert(pgexpr->Pop())->UlOptRequests();
for (ULONG ul = 0; ul < ulOptRequests; ul++)
{
CExpressionHandle exprhdl(m_pmp);
exprhdl.Attach(pgexpr);
exprhdl.DeriveProps(NULL /*pdpctxt*/);
// check if group expression optimization can be early terminated without optimizing any child
CCost costLowerBound(GPOPT_INVALID_COST);
if (FSafeToPrune(pgexpr, poc->Prpp(), NULL /*pccChild*/, ULONG_MAX /*ulChildIndex*/, &costLowerBound))
{
(void) pgexpr->PccComputeCost(m_pmp, poc, ul, NULL /*pdrgpoc*/, true /*fPruned*/, costLowerBound);
continue;
}
if (FCheckReqdProps(exprhdl, poc->Prpp(), ul))
{
// load required properties on the handle
exprhdl.InitReqdProps(poc->Prpp());
// optimize child groups
DrgPoc *pdrgpoc = PdrgpocOptimizeChildren(exprhdl, poc, ul);
if (NULL != pdrgpoc && FCheckEnfdProps(m_pmp, pgexpr, poc, ul, pdrgpoc))
{
// compute group expression cost under the current optimization context
CCostContext *pccComputed = pgexpr->PccComputeCost(m_pmp, poc, ul, pdrgpoc, false /*fPruned*/, CCost(0.0));
if (NULL != pccComputed)
{
// update best group expression under the current optimization context
pgroup->UpdateBestCost(poc, pccComputed);
}
}
CRefCount::SafeRelease(pdrgpoc);
}
GPOS_CHECK_ABORT;
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PgexprOptimize
//
// @doc:
// Optimize group under a given context;
//
//---------------------------------------------------------------------------
CGroupExpression *
CEngine::PgexprOptimize
(
CGroup *pgroup,
COptimizationContext *poc,
CGroupExpression *pgexprOrigin
)
{
// recursive function - check stack
GPOS_CHECK_STACK_SIZE;
COptimizationContext *pocFound = pgroup->PocInsert(poc);
if (poc != pocFound)
{
GPOS_ASSERT(COptimizationContext::estOptimized == pocFound->Est());
return pocFound->PgexprBest();
}
// add-ref context to pin it in hash table
poc->AddRef();
poc->SetState(COptimizationContext::estOptimizing);
EOptimizationLevel eolCurrent = pgroup->EolMax();
while (EolSentinel != eolCurrent)
{
CGroupExpression *pgexprCurrent = NULL;
{
CGroupProxy gp(pgroup);
pgexprCurrent = gp.PgexprSkipLogical(NULL /*pgexpr*/);
}
while (NULL != pgexprCurrent)
{
if (FOptimizeChild(pgexprOrigin, pgexprCurrent, poc, eolCurrent))
{
OptimizeGroupExpression(pgexprCurrent, poc);
}
if (PssCurrent()->FTimedOut())
{
break;
}
// move to next group expression
{
CGroupProxy gp(pgroup);
pgexprCurrent = gp.PgexprSkipLogical(pgexprCurrent);
}
}
// damp optimization level
eolCurrent = EolDamp(eolCurrent);
GPOS_CHECK_ABORT;
}
poc->SetState(COptimizationContext::estOptimized);
return poc->PgexprBest();
}
//---------------------------------------------------------------------------
// @function:
// CEngine::Explore
//
// @doc:
// Apply all exploration xforms
//
//---------------------------------------------------------------------------
void
CEngine::Explore()
{
GPOS_ASSERT(NULL != m_pqc);
GPOS_ASSERT(NULL != PgroupRoot());
// explore root group
GPOS_ASSERT(!PgroupRoot()->FExplored());
TransitionGroup(m_pmp, PgroupRoot(), CGroup::estExplored /*estTarget*/);
GPOS_ASSERT_IMP
(
!PssCurrent()->FTimedOut(),
PgroupRoot()->FExplored()
);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::Implement
//
// @doc:
// Apply all implementation xforms
//
//---------------------------------------------------------------------------
void
CEngine::Implement()
{
GPOS_ASSERT(NULL != m_pqc);
GPOS_ASSERT(NULL != PgroupRoot());
// implement root group
GPOS_ASSERT(!PgroupRoot()->FImplemented());
TransitionGroup(m_pmp, PgroupRoot(), CGroup::estImplemented /*estTarget*/);
GPOS_ASSERT_IMP
(
!PssCurrent()->FTimedOut(),
PgroupRoot()->FImplemented()
);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::RecursiveOptimize
//
// @doc:
// Recursive optimization
//
//---------------------------------------------------------------------------
void
CEngine::RecursiveOptimize()
{
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
CAutoTimer at("\n[OPT]: Total Optimization Time", GPOS_FTRACE(EopttracePrintOptimizationStatistics));
const ULONG ulSearchStages = m_pdrgpss->UlLength();
for (ULONG ul = 0; !FSearchTerminated() && ul < ulSearchStages; ul++)
{
PssCurrent()->RestartTimer();
// apply exploration xforms
Explore();
// run exploration completion operations
FinalizeExploration();
// apply implementation xforms
Implement();
// run implementation completion operations
FinalizeImplementation();
// optimize root group
m_pqc->Prpp()->AddRef();
COptimizationContext *poc =
GPOS_NEW(m_pmp) COptimizationContext
(
m_pmp,
PgroupRoot(),
m_pqc->Prpp(),
GPOS_NEW(m_pmp) CReqdPropRelational(GPOS_NEW(m_pmp) CColRefSet(m_pmp)), // pass empty required relational properties initially
GPOS_NEW(m_pmp) DrgPstat(m_pmp), // pass an empty stats context initially
m_ulCurrSearchStage
);
(void) PgexprOptimize(PgroupRoot(), poc, NULL /*pgexprOrigin*/);
poc->Release();
// extract best plan found at the end of current search stage
CExpression *pexprPlan =
m_pmemo->PexprExtractPlan
(
m_pmp,
m_pmemo->PgroupRoot(),
m_pqc->Prpp(),
m_pdrgpss->UlLength()
);
PssCurrent()->SetBestExpr(pexprPlan);
FinalizeSearchStage();
}
{
CAutoTrace atSearch(m_pmp);
atSearch.Os() << "[OPT]: Search terminated at stage " << m_ulCurrSearchStage << "/" << m_pdrgpss->UlLength();
}
if (poconf->Pec()->FSample())
{
SamplePlans();
}
}
#endif // GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CEngine::PdrgpocChildren
//
// @doc:
// Return array of child optimization contexts corresponding
// to handle requirements
//
//---------------------------------------------------------------------------
DrgPoc *
CEngine::PdrgpocChildren
(
IMemoryPool *pmp,
CExpressionHandle &exprhdl
)
{
GPOS_ASSERT(NULL != exprhdl.Pgexpr());
DrgPoc *pdrgpoc = GPOS_NEW(pmp) DrgPoc(pmp);
const ULONG ulArity = exprhdl.UlArity();
for (ULONG ul = 0; ul < ulArity; ul++)
{
CGroup *pgroupChild = (*exprhdl.Pgexpr())[ul];
if (!pgroupChild->FScalar())
{
COptimizationContext *poc =
pgroupChild->PocLookupBest(pmp, m_pdrgpss->UlLength(), exprhdl.Prpp(ul));
GPOS_ASSERT(NULL != poc);
poc->AddRef();
pdrgpoc->Append(poc);
}
}
return pdrgpoc;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::ScheduleMainJob
//
// @doc:
// Create and schedule the main optimization job
//
//---------------------------------------------------------------------------
void
CEngine::ScheduleMainJob
(
CSchedulerContext *psc,
COptimizationContext *poc
)
{
GPOS_ASSERT(NULL != PgroupRoot());
CJobGroupOptimization::ScheduleJob(psc, PgroupRoot(), NULL /*pgexprOrigin*/, poc, NULL /*pjParent*/);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FinalizeExploration
//
// @doc:
// Execute operations after exploration completes
//
//---------------------------------------------------------------------------
void
CEngine::FinalizeExploration()
{
GroupMerge();
if (m_pqc->FDeriveStats())
{
// derive statistics
m_pmemo->ResetStats();
DeriveStats(m_pmp);
}
if (!GPOS_FTRACE(EopttraceDonotDeriveStatsForAllGroups))
{
// derive stats for every group without stats
m_pmemo->DeriveStatsIfAbsent(m_pmp);
}
if (GPOS_FTRACE(EopttracePrintMemoAfterExploration))
{
{
CAutoTrace at(m_pmp);
at.Os() << "MEMO after exploration (stage " << m_ulCurrSearchStage << ")" << std::endl;
}
{
CAutoTrace at(m_pmp);
at.Os() << *this;
}
}
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
CAutoTrace at(m_pmp);
(void) OsPrintMemoryConsumption(at.Os(), "Memory consumption after exploration ");
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FinalizeImplementation
//
// @doc:
// Execute operations after implementation completes
//
//---------------------------------------------------------------------------
void
CEngine::FinalizeImplementation()
{
if (GPOS_FTRACE(EopttracePrintMemoAfterImplementation))
{
{
CAutoTrace at(m_pmp);
at.Os() << "MEMO after implementation (stage " << m_ulCurrSearchStage << ")" << std::endl;
}
{
CAutoTrace at(m_pmp);
at.Os() << *this;
}
}
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
CAutoTrace at(m_pmp);
(void) OsPrintMemoryConsumption(at.Os(), "Memory consumption after implementation ");
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FinalizeSearchStage
//
// @doc:
// Execute operations after search stage completes
//
//---------------------------------------------------------------------------
void
CEngine::FinalizeSearchStage()
{
ProcessTraceFlags();
m_pxfs->Release();
m_pxfs = NULL;
m_pxfs = GPOS_NEW(m_pmp) CXformSet(m_pmp);
m_ulCurrSearchStage++;
m_pmemo->ResetGroupStates();
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PrintActivatedXforms
//
// @doc:
// Print activated xform
//
//---------------------------------------------------------------------------
void
CEngine::PrintActivatedXforms
(
IOstream &os
)
const
{
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
os << std::endl << "[OPT]: <Begin Xforms - stage " << m_ulCurrSearchStage << ">" << std::endl;
CXformSetIter xsi(*m_pxfs);
while (xsi.FAdvance())
{
CXform *pxform = CXformFactory::Pxff()->Pxf(xsi.TBit());
ULONG ulCalls = (ULONG) (*m_pdrgpulpXformCalls)[m_ulCurrSearchStage][pxform->Exfid()];
ULONG ulTime = (ULONG) (*m_pdrgpulpXformTimes)[m_ulCurrSearchStage][pxform->Exfid()];
os
<< pxform->SzId() << ": "
<< ulCalls << " calls, "
<< ulTime << "ms"<< std::endl;
}
os << "[OPT]: <End Xforms - stage " << m_ulCurrSearchStage << ">" << std::endl;
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PrintMemoryConsumption
//
// @doc:
// Print current memory consumption
//
//---------------------------------------------------------------------------
IOstream &
CEngine::OsPrintMemoryConsumption
(
IOstream &os,
const CHAR *szHeader
)
const
{
CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda();
CMDAccessor::MDCache *pcache = pmda->Pcache();
os << std::endl << szHeader
<< "Engine: [" << (DOUBLE) m_pmp->UllTotalAllocatedSize() / GPOPT_MEM_UNIT << "] " << GPOPT_MEM_UNIT_NAME
<< ", MD Cache: [" << (DOUBLE) (pcache->UllTotalAllocatedSize()) / GPOPT_MEM_UNIT << "] " << GPOPT_MEM_UNIT_NAME
<< ", Total: [" << (DOUBLE) (CMemoryPoolManager::Pmpm()->UllTotalAllocatedSize()) / GPOPT_MEM_UNIT << "] " << GPOPT_MEM_UNIT_NAME;
return os;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::ProcessTraceFlags
//
// @doc:
// Process trace flags after optimization is complete
//
//---------------------------------------------------------------------------
void
CEngine::ProcessTraceFlags()
{
if (GPOS_FTRACE(EopttracePrintMemoAfterOptimization))
{
{
CAutoTrace at(m_pmp);
at.Os() << "MEMO after optimization (stage "<< m_ulCurrSearchStage << "):" << std::endl;
}
{
CAutoTrace at(m_pmp);
at.Os() << *this;
}
}
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
CAutoTrace at(m_pmp);
// print optimization stats
at.Os()
<< std::endl << "[OPT]: Memo (stage "<< m_ulCurrSearchStage << "): ["
<< (ULONG) (m_pmemo->UlpGroups()) << " groups"
<< ", " << m_pmemo->UlDuplicateGroups() << " duplicate groups"
<< ", " << m_pmemo->UlGrpExprs() << " group expressions"
<< ", " << m_pxfs->CElements() << " activated xforms]";
at.Os()
<< std::endl << "[OPT]: stage "<< m_ulCurrSearchStage << " completed in "
<< PssCurrent()->UlElapsedTime() << " msec, ";
if (NULL == PssCurrent()->PexprBest())
{
at.Os() << " no plan was found";
}
else
{
at.Os() << " plan with cost "<< PssCurrent()->CostBest() <<" was found";
}
PrintActivatedXforms(at.Os());
(void) OsPrintMemoryConsumption(at.Os(), "Memory consumption after optimization ");
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::Optimize
//
// @doc:
// Main driver of optimization engine
//
//---------------------------------------------------------------------------
void
CEngine::Optimize()
{
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
CAutoTimer at("\n[OPT]: Total Optimization Time", GPOS_FTRACE(EopttracePrintOptimizationStatistics));
if (GPOS_FTRACE(EopttraceParallel))
{
MultiThreadedOptimize(2 /*ulWorkers*/);
}
else
{
MainThreadOptimize();
}
{
if (GPOS_FTRACE(EopttracePrintOptimizationStatistics))
{
CAutoTrace atSearch(m_pmp);
atSearch.Os() << "[OPT]: Search terminated at stage " << m_ulCurrSearchStage << "/" << m_pdrgpss->UlLength();
}
}
if (poconf->Pec()->FSample())
{
SamplePlans();
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::MainThreadOptimize
//
// @doc:
// Run optimizer on the main thread
//
//---------------------------------------------------------------------------
void
CEngine::MainThreadOptimize()
{
GPOS_ASSERT(NULL != PgroupRoot());
GPOS_ASSERT(NULL != COptCtxt::PoctxtFromTLS());
const ULONG ulJobs = std::min((ULONG) GPOPT_JOBS_CAP, (ULONG) (m_pmemo->UlpGroups() * GPOPT_JOBS_PER_GROUP));
CJobFactory jf(m_pmp, ulJobs);
CScheduler sched(m_pmp, ulJobs, 1 /*ulWorkers*/);
CSchedulerContext sc;
sc.Init(m_pmp, &jf, &sched, this);
const ULONG ulSearchStages = m_pdrgpss->UlLength();
for (ULONG ul = 0; !FSearchTerminated() && ul < ulSearchStages; ul++)
{
PssCurrent()->RestartTimer();
// optimize root group
m_pqc->Prpp()->AddRef();
COptimizationContext *poc = GPOS_NEW(m_pmp) COptimizationContext
(
m_pmp,
PgroupRoot(),
m_pqc->Prpp(),
GPOS_NEW(m_pmp) CReqdPropRelational(GPOS_NEW(m_pmp) CColRefSet(m_pmp)), // pass empty required relational properties initially
GPOS_NEW(m_pmp) DrgPstat(m_pmp), // pass empty stats context initially
m_ulCurrSearchStage
);
// schedule main optimization job
ScheduleMainJob(&sc, poc);
// run optimization job
CScheduler::Run(&sc);
poc->Release();
// extract best plan found at the end of current search stage
CExpression *pexprPlan =
m_pmemo->PexprExtractPlan
(
m_pmp,
m_pmemo->PgroupRoot(),
m_pqc->Prpp(),
m_pdrgpss->UlLength()
);
PssCurrent()->SetBestExpr(pexprPlan);
FinalizeSearchStage();
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::MultiThreadedOptimize
//
// @doc:
// Multi-threaded optimization
//
//---------------------------------------------------------------------------
void
CEngine::MultiThreadedOptimize
(
ULONG ulWorkers
)
{
GPOS_ASSERT(NULL != PgroupRoot());
GPOS_ASSERT(NULL != COptCtxt::PoctxtFromTLS());
const ULONG ulJobs = std::min((ULONG) GPOPT_JOBS_CAP, (ULONG) (m_pmemo->UlpGroups() * GPOPT_JOBS_PER_GROUP));
CJobFactory jf(m_pmp, ulJobs);
CScheduler sched(m_pmp, ulJobs, ulWorkers);
CSchedulerContext sc;
sc.Init(m_pmp, &jf, &sched, this);
const ULONG ulSearchStages = m_pdrgpss->UlLength();
for (ULONG ul = 0; !FSearchTerminated() && ul < ulSearchStages; ul++)
{
PssCurrent()->RestartTimer();
// optimize root group
m_pqc->Prpp()->AddRef();
COptimizationContext *poc = GPOS_NEW(m_pmp) COptimizationContext
(
m_pmp,
PgroupRoot(),
m_pqc->Prpp(),
GPOS_NEW(m_pmp) CReqdPropRelational(GPOS_NEW(m_pmp) CColRefSet(m_pmp)), // pass empty required relational properties initially
GPOS_NEW(m_pmp) DrgPstat(m_pmp), // pass empty stats context initially
m_ulCurrSearchStage
);
// schedule main optimization job
ScheduleMainJob(&sc, poc);
// create task array
CAutoRg<CTask*> a_rgptsk;
a_rgptsk = GPOS_NEW_ARRAY(m_pmp, CTask*, ulWorkers);
// create scheduling contexts
CAutoRg<CSchedulerContext> a_rgsc;
a_rgsc = GPOS_NEW_ARRAY(m_pmp, CSchedulerContext, ulWorkers);
// scope for ATP
{
CWorkerPoolManager *pwpm = CWorkerPoolManager::Pwpm();
CAutoTaskProxy atp(m_pmp, pwpm);
for (ULONG i = 0; i < ulWorkers; i++)
{
// initialize scheduling context
a_rgsc[i].Init(m_pmp, &jf, &sched, this);
// create scheduling task
a_rgptsk[i] = atp.PtskCreate(CScheduler::Run, &a_rgsc[i]);
// store a pointer to optimizer's context in current task local storage
a_rgptsk[i]->Tls().Reset(m_pmp);
a_rgptsk[i]->Tls().Store(COptCtxt::PoctxtFromTLS());
}
// start tasks
for (ULONG i = 0; i < ulWorkers; i++)
{
atp.Schedule(a_rgptsk[i]);
}
// wait for tasks to complete
for (ULONG i = 0; i < ulWorkers; i++)
{
CTask *ptsk;
atp.WaitAny(&ptsk);
}
}
poc->Release();
// extract best plan found at the end of current search stage
CExpression *pexprPlan =
m_pmemo->PexprExtractPlan
(
m_pmp,
m_pmemo->PgroupRoot(),
m_pqc->Prpp(),
m_pdrgpss->UlLength()
);
PssCurrent()->SetBestExpr(pexprPlan);
FinalizeSearchStage();
}
}
//---------------------------------------------------------------------------
// @function:
// CEngine::CEngine
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CExpression *
CEngine::PexprUnrank
(
ULLONG ullPlanId
)
{
// The CTE map will be updated by the Producer instead of the Sequence operator
// because we are doing a DFS traversal of the TreeMap.
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(m_pmp) CDrvdPropCtxtPlan(m_pmp, false /*fUpdateCTEMap*/);
CExpression *pexpr = Pmemotmap()->PrUnrank(m_pmp, pdpctxtplan, ullPlanId);
pdpctxtplan->Release();
#ifdef GPOS_DEBUG
// check plan using configured plan checker, if any
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
CEnumeratorConfig *pec = poconf->Pec();
BOOL fCheck = pec->FCheckPlan(pexpr);
if (!fCheck)
{
CAutoTrace at(m_pmp);
at.Os() << "\nextracted plan failed PlanChecker function: " << std::endl << *pexpr;
}
GPOS_ASSERT(fCheck);
#endif // GPOS_DEBUG
return pexpr;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PexprExtractPlan
//
// @doc:
// Extract a physical plan from the memo
//
//---------------------------------------------------------------------------
CExpression *
CEngine::PexprExtractPlan()
{
GPOS_ASSERT(NULL != m_pqc);
GPOS_ASSERT(NULL != m_pmemo);
GPOS_ASSERT(NULL != m_pmemo->PgroupRoot());
BOOL fGenerateAlt = false;
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
CEnumeratorConfig *pec = poconf->Pec();
if (pec->FEnumerate())
{
CAutoTrace at(m_pmp);
ULLONG ullCount = Pmemotmap()->UllCount();
at.Os() << "[OPT]: Number of plan alternatives: " << ullCount << std::endl;
if (0 < pec->UllPlanId())
{
if (pec->UllPlanId() > ullCount)
{
// an invalid plan number is chosen
GPOS_RAISE(gpopt::ExmaGPOPT, gpopt::ExmiInvalidPlanAlternative, pec->UllPlanId(), ullCount);
}
// a valid plan number was chosen
fGenerateAlt = true;
}
}
CExpression *pexpr = NULL;
if (fGenerateAlt)
{
pexpr = PexprUnrank(pec->UllPlanId() - 1 /*rank of plan alternative is zero-based*/);
CAutoTrace at(m_pmp);
at.Os() << "[OPT]: Successfully generated plan: " << pec->UllPlanId() << std::endl;
}
else
{
pexpr = m_pmemo->PexprExtractPlan
(
m_pmp,
m_pmemo->PgroupRoot(),
m_pqc->Prpp(),
m_pdrgpss->UlLength()
);
}
if (NULL == pexpr)
{
GPOS_RAISE(gpopt::ExmaGPOPT, gpopt::ExmiNoPlanFound);
}
return pexpr;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::UllRandomPlanId
//
// @doc:
// Generate random plan id
//
//---------------------------------------------------------------------------
ULLONG
CEngine::UllRandomPlanId
(
ULONG *pulSeed
)
{
ULLONG ullCount = Pmemotmap()->UllCount();
ULLONG ullPlanId = 0;
do
{
ullPlanId = clib::UlRandR(pulSeed);
}
while (ullPlanId >= ullCount);
return ullPlanId;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FValidPlanSample
//
// @doc:
// Extract a plan sample and handle exceptions according to enumerator
// configurations
//
//---------------------------------------------------------------------------
BOOL
CEngine::FValidPlanSample
(
CEnumeratorConfig *pec,
ULLONG ullPlanId,
CExpression **ppexpr // output: extracted plan
)
{
GPOS_ASSERT(NULL != pec);
GPOS_ASSERT(NULL != ppexpr);
BOOL fValidPlan = true;
if (pec->FSampleValidPlans())
{
// if enumerator is configured to extract valid plans only,
// we extract plan and catch invalid plan exception here
GPOS_TRY
{
*ppexpr = PexprUnrank(ullPlanId);
}
GPOS_CATCH_EX(ex)
{
if (GPOS_MATCH_EX(ex, gpopt::ExmaGPOPT, gpopt::ExmiUnsatisfiedRequiredProperties))
{
GPOS_RESET_EX;
fValidPlan = false;
}
else
{
// for all other exceptions, we bail out
GPOS_RETHROW(ex);
}
}
GPOS_CATCH_END;
}
else
{
// otherwise, we extract plan and leave exception handling to the caller
*ppexpr = PexprUnrank(ullPlanId);
}
return fValidPlan;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::SamplePlans
//
// @doc:
// Sample distribution of possible plans uniformly;
//
//---------------------------------------------------------------------------
void
CEngine::SamplePlans()
{
COptimizerConfig *poconf = COptCtxt::PoctxtFromTLS()->Poconf();
GPOS_ASSERT(NULL != poconf);
CEnumeratorConfig *pec = poconf->Pec();
ULLONG ullSamples = pec->UllInputSamples();
GPOS_ASSERT(0 < ullSamples);
pec->ClearSamples();
ULLONG ullCount = Pmemotmap()->UllCount();
if (0 == ullCount)
{
// optimizer generated no plans
return;
}
// generate full plan space when space size is less than or equal to
// the required number of samples
BOOL fGenerateAll = (ullSamples >= ullCount);
ULLONG ullTargetSamples = ullSamples;
if (fGenerateAll)
{
ullTargetSamples = ullCount;
}
// find cost of best plan
CExpression *pexpr =
m_pmemo->PexprExtractPlan
(
m_pmp,
m_pmemo->PgroupRoot(),
m_pqc->Prpp(),
m_pdrgpss->UlLength()
);
CCost costBest = pexpr->Cost();
pec->SetBestCost(costBest);
pexpr->Release();
// generate randomized seed using local time
TIMEVAL tv;
syslib::GetTimeOfDay(&tv, NULL/*timezone*/);
ULONG ulSeed = UlCombineHashes((ULONG) tv.tv_sec, (ULONG)tv.tv_usec);
// set maximum number of iterations based number of samples
// we use maximum iteration to prevent infinite looping below
const ULLONG ullMaxIters = ullTargetSamples * GPOPT_SAMPLING_MAX_ITERS;
ULLONG ullIters = 0;
ULLONG ull = 0;
while (ullIters < ullMaxIters && ull < ullTargetSamples)
{
// generate id of plan to be extracted
ULLONG ullPlanId = ull;
if (!fGenerateAll)
{
ullPlanId = UllRandomPlanId(&ulSeed);
}
pexpr = NULL;
BOOL fAccept = false;
if (FValidPlanSample(pec, ullPlanId, &pexpr))
{
// add plan to the sample if it is below cost threshold
CCost cost = pexpr->Cost();
fAccept = pec->FAddSample(ullPlanId, cost);
pexpr->Release();
}
if (fGenerateAll || fAccept)
{
ull++;
}
ullIters++;
}
pec->PrintPlanSample();
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FCheckEnfdProps
//
// @doc:
// Check enforceable properties and append enforcers to the current group if
// required.
//
// This check is done in two steps:
//
// First, it determines if any particular property needs to be enforced at
// all. For example, the EopttraceDisableSort traceflag can disable order
// enforcement. Also, if there are no partitioned tables referenced in the
// subtree, partition propagation enforcement can be skipped.
//
// Second, EPET methods are called for each property to determine if an
// enforcer needs to be added. These methods in turn call into virtual
// methods in the different operators. For example, CPhysical::EpetOrder()
// is used to determine a Sort node needs to be added to the group. These
// methods are passed an expression handle (to access derived properties of
// the subtree) and the required properties as a object of a subclass of
// CEnfdProp.
//
// Finally, based on return values of the EPET methods,
// CEnfdProp::AppendEnforcers() is called for each of the enforced
// properties.
//
// Returns true if no enforcers were created because they were deemed
// unnecessary or optional i.e all enforced properties were satisfied for
// the group expression under the current optimization context. Returns
// false otherwise.
//
// NB: This method is only concerned with a certain enforcer needs to be
// added into the group. Once added, there is no connection between the
// enforcer and the operator that created it. That is although some group
// expression X created the enforcer E, later, during costing, E can still
// decide to pick some other group expression Y for its child, since
// theoretically, all group expressions in a group are equivalent.
//
//---------------------------------------------------------------------------
BOOL
CEngine::FCheckEnfdProps
(
IMemoryPool *pmp,
CGroupExpression *pgexpr,
COptimizationContext *poc,
ULONG ulOptReq,
DrgPoc *pdrgpoc
)
{
GPOS_CHECK_ABORT;
if (GPOS_FTRACE(EopttracePrintMemoEnforcement))
{
CAutoTrace at(m_pmp);
at.Os() << "CEngine::FCheckEnfdProps (Group ID: " << pgexpr->Pgroup()->UlId() <<
" Expression ID: " << pgexpr->UlId() << ")"<< std::endl;
m_pmemo->OsPrint(at.Os());
}
// check if all children could be successfully optimized
if (!FChildrenOptimized(pdrgpoc))
{
return false;
}
// load a handle with derived plan properties
poc->AddRef();
pgexpr->AddRef();
pdrgpoc->AddRef();
CCostContext *pcc= GPOS_NEW(pmp) CCostContext(pmp, poc, ulOptReq, pgexpr);
pcc->SetChildContexts(pdrgpoc);
CExpressionHandle exprhdl(pmp);
exprhdl.Attach(pcc);
exprhdl.DerivePlanProps();
pcc->Release();
CPhysical *popPhysical = CPhysical::PopConvert(exprhdl.Pop());
CReqdPropPlan *prpp = poc->Prpp();
// check whether the current physical operator satisfies the CTE requirements
// and whether it is a motion over unresolved part consumers
if (!FValidCTEAndPartitionProperties(pmp, exprhdl, prpp))
{
return false;
}
// Determine if any property enforcement is disable or unnecessary
BOOL fOrderReqd =
!GPOS_FTRACE(EopttraceDisableSort) &&
!prpp->Peo()->PosRequired()->FEmpty();
BOOL fDistributionReqd =
!GPOS_FTRACE(EopttraceDisableMotions) &&
(CDistributionSpec::EdtAny != prpp->Ped()->PdsRequired()->Edt());
BOOL fRewindabilityReqd =
!GPOS_FTRACE(EopttraceDisableSpool) &&
(CRewindabilitySpec::ErtNone != prpp->Per()->PrsRequired()->Ert());
BOOL fPartPropagationReqd =
!GPOS_FTRACE(EopttraceDisablePartPropagation) &&
prpp->Pepp()->PppsRequired()->FPartPropagationReqd();
// Determine if adding an enforcer to the group is required, optional,
// unnecessary or prohibited over the group expression and given the current
// optimization context (required properties)
// get order enforcing type
CEnfdProp::EPropEnforcingType epetOrder =
prpp->Peo()->Epet(exprhdl, popPhysical, fOrderReqd);
// get distribution enforcing type
CEnfdProp::EPropEnforcingType epetDistribution = prpp->Ped()->Epet(exprhdl, popPhysical, prpp->Pepp()->PppsRequired(), fDistributionReqd);
// get rewindability enforcing type
CEnfdProp::EPropEnforcingType epetRewindability =
prpp->Per()->Epet(exprhdl, popPhysical, fRewindabilityReqd);
// get partition propagation enforcing type
CEnfdProp::EPropEnforcingType epetPartitionPropagation =
prpp->Pepp()->Epet(exprhdl, popPhysical, fPartPropagationReqd);
// Skip adding enforcers entirely if any property determines it to be
// 'prohibited'. In this way, a property may veto out the creation of an
// enforcer for the current group expression and optimization context.
//
// NB: Even though an enforcer E is not added because of some group
// expression G because it was prohibited, some other group expression H may
// decide to add it. And if E is added, it is possible for E to consider both
// G and H as its child.
if (FProhibited(epetOrder, epetDistribution, epetRewindability, epetPartitionPropagation))
{
return false;
}
DrgPexpr *pdrgpexprEnforcers = GPOS_NEW(pmp) DrgPexpr(pmp);
// extract a leaf pattern from target group
CBinding binding;
CExpression *pexpr =
binding.PexprExtract(m_pmp, exprhdl.Pgexpr(), m_pexprEnforcerPattern, NULL /* pexprLast */);
GPOS_ASSERT(NULL != pexpr);
GPOS_ASSERT(pexpr->Pgexpr()->Pgroup() == pgexpr->Pgroup());
prpp->Peo()->AppendEnforcers(pmp, prpp, pdrgpexprEnforcers, pexpr, epetOrder, exprhdl);
prpp->Ped()->AppendEnforcers(pmp, prpp, pdrgpexprEnforcers, pexpr, epetDistribution, exprhdl);
prpp->Per()->AppendEnforcers(pmp, prpp, pdrgpexprEnforcers, pexpr, epetRewindability, exprhdl);
prpp->Pepp()->AppendEnforcers(pmp, prpp, pdrgpexprEnforcers, pexpr, epetPartitionPropagation, exprhdl);
if (0 < pdrgpexprEnforcers->UlLength())
{
AddEnforcers(exprhdl.Pgexpr(), pdrgpexprEnforcers);
}
pdrgpexprEnforcers->Release();
pexpr->Release();
return FOptimize(epetOrder, epetDistribution, epetRewindability, epetPartitionPropagation);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FValidCTEAndPartitionProperties
//
// @doc:
// Check if the given expression has valid cte and partition properties
// with respect to the given requirements. This function returns true iff
// ALL the following conditions are met:
// 1. The expression satisfies the CTE requirements
// 2. The root of the expression is not a motion over an unresolved part consumer
// 3. The expression does not have an unneeded part propagator
//
//---------------------------------------------------------------------------
BOOL
CEngine::FValidCTEAndPartitionProperties
(
IMemoryPool *pmp,
CExpressionHandle &exprhdl,
CReqdPropPlan *prpp
)
{
CPhysical *popPhysical = CPhysical::PopConvert(exprhdl.Pop());
CPartIndexMap *ppimDrvd = CDrvdPropPlan::Pdpplan(exprhdl.Pdp())->Ppim();
return popPhysical->FProvidesReqdCTEs(exprhdl, prpp->Pcter()) &&
!CUtils::FMotionOverUnresolvedPartConsumers(pmp, exprhdl, prpp->Pepp()->PppsRequired()->Ppim()) &&
!ppimDrvd->FContainsRedundantPartitionSelectors(prpp->Pepp()->PppsRequired()->Ppim());
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FChildrenOptimized
//
// @doc:
// Check if all children were successfully optimized
//
//---------------------------------------------------------------------------
BOOL
CEngine::FChildrenOptimized
(
DrgPoc *pdrgpoc
)
{
GPOS_ASSERT(NULL != pdrgpoc);
const ULONG ulLen = pdrgpoc->UlLength();
for (ULONG ul = 0; ul < ulLen; ul++)
{
if (NULL == (*pdrgpoc)[ul]->PgexprBest())
{
return false;
}
}
return true;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FOptimize
//
// @doc:
// Check if optimization is possible under the given property enforcing
// types
//
//---------------------------------------------------------------------------
BOOL
CEngine::FOptimize
(
CEnfdProp::EPropEnforcingType epetOrder,
CEnfdProp::EPropEnforcingType epetDistribution,
CEnfdProp::EPropEnforcingType epetRewindability,
CEnfdProp::EPropEnforcingType epetPropagation
)
{
return CEnfdProp::FOptimize(epetOrder) &&
CEnfdProp::FOptimize(epetDistribution) &&
CEnfdProp::FOptimize(epetRewindability) &&
CEnfdProp::FOptimize(epetPropagation);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FProhibited
//
// @doc:
// Check if any of the given property enforcing types prohibits enforcement
//
//---------------------------------------------------------------------------
BOOL
CEngine::FProhibited
(
CEnfdProp::EPropEnforcingType epetOrder,
CEnfdProp::EPropEnforcingType epetDistribution,
CEnfdProp::EPropEnforcingType epetRewindability,
CEnfdProp::EPropEnforcingType epetPropagation
)
{
return (CEnfdProp::EpetProhibited == epetOrder ||
CEnfdProp::EpetProhibited == epetDistribution ||
CEnfdProp::EpetProhibited == epetRewindability ||
CEnfdProp::EpetProhibited == epetPropagation);
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FCheckReqdPartPropagation
//
// @doc:
// Check if partition propagation resolver is passed an empty part propagation
// spec
//
//---------------------------------------------------------------------------
BOOL
CEngine::FCheckReqdPartPropagation
(
CPhysical *pop,
CEnfdPartitionPropagation *pepp
)
{
BOOL fPartPropagationReqd = (NULL != pepp && pepp->PppsRequired()->Ppim()->FContainsUnresolvedZeroPropagators());
return fPartPropagationReqd || COperator::EopPhysicalPartitionSelector != pop->Eopid();
}
//---------------------------------------------------------------------------
// @function:
// CEngine::FCheckReqdProps
//
// @doc:
// Determine if checking required properties is needed.
// This method is called after a group expression optimization job has
// started executing and can be used to cancel the job early.
//
// This is useful to prevent deadlocks when an enforcer optimizes same
// group with the same optimization context. Also, in case the subtree
// doesn't provide the required columns we can save optimization time by
// skipping this optimization request.
//
// NB: Only relational properties are available at this stage to make this
// decision.
//---------------------------------------------------------------------------
BOOL
CEngine::FCheckReqdProps
(
CExpressionHandle &exprhdl,
CReqdPropPlan *prpp,
ULONG ulOptReq
)
{
GPOS_CHECK_ABORT;
if (GPOS_FTRACE(EopttracePrintMemoEnforcement))
{
CAutoTrace at(m_pmp);
at.Os() << "CEngine::FCheckReqdProps (Group ID: " << exprhdl.Pgexpr()->Pgroup()->UlId() <<
" Expression ID: " << exprhdl.Pgexpr()->UlId() << ")" << std::endl;
m_pmemo->OsPrint(at.Os());
}
// check if operator provides required columns
if (!prpp->FProvidesReqdCols(m_pmp, exprhdl, ulOptReq))
{
return false;
}
CPhysical *popPhysical = CPhysical::PopConvert(exprhdl.Pop());
COperator::EOperatorId eopid = popPhysical->Eopid();
// check if sort operator is passed an empty order spec;
// this check is required to avoid self-deadlocks, i.e.
// sort optimizing same group with the same optimization context;
BOOL fOrderReqd = !prpp->Peo()->PosRequired()->FEmpty();
if (!fOrderReqd && COperator::EopPhysicalSort == eopid)
{
return false;
}
// check if motion operator is passed an ANY distribution spec;
// this check is required to avoid self-deadlocks, i.e.
// motion optimizing same group with the same optimization context;
BOOL fDistributionReqd =
(CDistributionSpec::EdtAny != prpp->Ped()->PdsRequired()->Edt());
if (!fDistributionReqd && CUtils::FPhysicalMotion(popPhysical))
{
return false;
}
// check if spool operator is passed a non-rewindable spec;
// this check is required to avoid self-deadlocks, i.e.
// spool optimizing same group with the same optimization context;
BOOL fRewindabilityReqd =
(CRewindabilitySpec::ErtNone != prpp->Per()->PrsRequired()->Ert());
if (!fRewindabilityReqd && COperator::EopPhysicalSpool == eopid)
{
return false;
}
return FCheckReqdPartPropagation(popPhysical, prpp->Pepp());
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CEngine::PrintRoot
//
// @doc:
// Print root group
//
//---------------------------------------------------------------------------
void
CEngine::PrintRoot()
{
CAutoTrace at(m_pmp);
at.Os() << "Root Group:" << std::endl;
m_pmemo->Pgroup(m_pmemo->PgroupRoot()->UlId())->OsPrint(at.Os());
at.Os() << std::endl;
}
//---------------------------------------------------------------------------
// @function:
// CEngine::PrintOptCtxts
//
// @doc:
// Print main optimization context and optimal cost context
//
//---------------------------------------------------------------------------
void
CEngine::PrintOptCtxts()
{
CAutoTrace at(m_pmp);
COptimizationContext *poc =
m_pmemo->PgroupRoot()->PocLookupBest(m_pmp, m_pdrgpss->UlLength(), m_pqc->Prpp());
GPOS_ASSERT(NULL != poc);
at.Os() << std::endl << "Main Opt Ctxt:" << std::endl;
(void) poc->OsPrint(at.Os(), " ");
at.Os() << std::endl;
at.Os() << "Optimal Cost Ctxt:" << std::endl;
(void) poc->PccBest()->OsPrint(at.Os());
at.Os() << std::endl;
}
#endif // GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CEngine::OsPrint
//
// @doc:
// print function
//
//---------------------------------------------------------------------------
IOstream &
CEngine::OsPrint
(
IOstream &os
)
const
{
return m_pmemo->OsPrint(os);
}
// EOF
| 27.046304 | 139 | 0.622725 | ppmht |
33ed40bb55e7845acd4c00ac251507ba899ec019 | 13,974 | cpp | C++ | EchoCanceller.cpp | kebbbnnn/libtgvoip | 8d8522a5e89f8bb44119d4d35f94a3f18d61f115 | [
"Unlicense"
] | null | null | null | EchoCanceller.cpp | kebbbnnn/libtgvoip | 8d8522a5e89f8bb44119d4d35f94a3f18d61f115 | [
"Unlicense"
] | null | null | null | EchoCanceller.cpp | kebbbnnn/libtgvoip | 8d8522a5e89f8bb44119d4d35f94a3f18d61f115 | [
"Unlicense"
] | 1 | 2021-05-03T17:24:04.000Z | 2021-05-03T17:24:04.000Z | //
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#include "EchoCanceller.h"
#include "audio/AudioOutput.h"
#include "audio/AudioInput.h"
#include "logging.h"
#include <string.h>
#include <stdio.h>
#ifndef TGVOIP_NO_DSP
#ifndef TGVOIP_USE_DESKTOP_DSP
#include "webrtc/modules/audio_processing/aecm/echo_control_mobile.h"
#include "webrtc/modules/audio_processing/ns/noise_suppression_x.h"
#else
#include "webrtc/modules/audio_processing/aec/echo_cancellation.h"
//#include "webrtc/modules/audio_processing/ns/noise_suppression.h"
#include "webrtc/modules/audio_processing/ns/noise_suppression_x.h"
#endif
#include "webrtc/modules/audio_processing/splitting_filter.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/modules/audio_processing/agc/legacy/gain_control.h"
#endif
#define AEC_FRAME_SIZE 160
#define OFFSET_STEP AEC_FRAME_SIZE*2
//#define CLAMP(x, min, max) (x<max ? (x>min ? x : min) : max)
#define CLAMP(x, min, max) x
using namespace tgvoip;
#ifdef TGVOIP_USE_DESKTOP_DSP
namespace webrtc{
void WebRtcAec_enable_delay_agnostic(AecCore* self, int enable);
}
#endif
EchoCanceller::EchoCanceller(bool enableAEC, bool enableNS, bool enableAGC){
#ifndef TGVOIP_NO_DSP
this->enableAEC=enableAEC;
this->enableAGC=enableAGC;
this->enableNS=enableNS;
isOn=true;
splittingFilter=new webrtc::SplittingFilter(1, 3, 960);
splittingFilterFarend=new webrtc::SplittingFilter(1, 3, 960);
splittingFilterIn=new webrtc::IFChannelBuffer(960, 1, 1);
splittingFilterFarendIn=new webrtc::IFChannelBuffer(960, 1, 1);
splittingFilterOut=new webrtc::IFChannelBuffer(960, 1, 3);
splittingFilterFarendOut=new webrtc::IFChannelBuffer(960, 1, 3);
if(enableAEC){
#ifndef TGVOIP_USE_DESKTOP_DSP
aec=WebRtcAecm_Create();
WebRtcAecm_Init(aec, 16000);
AecmConfig cfg;
cfg.cngMode=AecmFalse;
cfg.echoMode=0;
WebRtcAecm_set_config(aec, cfg);
#else
aec=webrtc::WebRtcAec_Create();
webrtc::WebRtcAec_Init(aec, 48000, 48000);
webrtc::WebRtcAec_enable_delay_agnostic(webrtc::WebRtcAec_aec_core(aec), 1);
webrtc::AecConfig config;
config.metricsMode=webrtc::kAecFalse;
config.nlpMode=webrtc::kAecNlpAggressive;
config.skewMode=webrtc::kAecFalse;
config.delay_logging=webrtc::kAecFalse;
webrtc::WebRtcAec_set_config(aec, config);
#endif
farendQueue=new BlockingQueue<int16_t*>(11);
farendBufferPool=new BufferPool(960*2, 10);
running=true;
bufferFarendThread=new Thread(new MethodPointer<EchoCanceller>(&EchoCanceller::RunBufferFarendThread, this), NULL);
bufferFarendThread->Start();
}else{
aec=NULL;
}
if(enableNS){
//#ifndef TGVOIP_USE_DESKTOP_DSP
ns=WebRtcNsx_Create();
WebRtcNsx_Init((NsxHandle*)ns, 48000);
WebRtcNsx_set_policy((NsxHandle*)ns, 0);
/*#else
ns=WebRtcNs_Create();
WebRtcNs_Init((NsHandle*)ns, 48000);
WebRtcNs_set_policy((NsHandle*)ns, 1);
#endif*/
}else{
ns=NULL;
}
if(enableAGC){
agc=WebRtcAgc_Create();
WebRtcAgcConfig agcConfig;
agcConfig.compressionGaindB = 20;
agcConfig.limiterEnable = 1;
agcConfig.targetLevelDbfs = 9;
WebRtcAgc_Init(agc, 0, 255, kAgcModeAdaptiveDigital, 48000);
WebRtcAgc_set_config(agc, agcConfig);
agcMicLevel=0;
}else{
agc=NULL;
}
#else
this->enableAEC=this->enableAGC=enableAGC=this->enableNS=enableNS=false;
isOn=true;
#endif
}
EchoCanceller::~EchoCanceller(){
#ifndef TGVOIP_NO_DSP
if(enableAEC){
running=false;
farendQueue->Put(NULL);
bufferFarendThread->Join();
delete bufferFarendThread;
delete farendQueue;
delete farendBufferPool;
#ifndef TGVOIP_USE_DESKTOP_DSP
WebRtcAecm_Free(aec);
#else
webrtc::WebRtcAec_Free(aec);
#endif
}
if(enableNS){
//#ifndef TGVOIP_USE_DESKTOP_DSP
WebRtcNsx_Free((NsxHandle*)ns);
/*#else
WebRtcNs_Free((NsHandle*)ns);
#endif*/
}
if(enableAGC){
WebRtcAgc_Free(agc);
}
//webrtc::WebRtcAec_Free(state);
delete (webrtc::SplittingFilter*)splittingFilter;
delete (webrtc::SplittingFilter*)splittingFilterFarend;
delete (webrtc::IFChannelBuffer*)splittingFilterIn;
delete (webrtc::IFChannelBuffer*)splittingFilterOut;
delete (webrtc::IFChannelBuffer*)splittingFilterFarendIn;
delete (webrtc::IFChannelBuffer*)splittingFilterFarendOut;
#endif
}
void EchoCanceller::Start(){
}
void EchoCanceller::Stop(){
}
void EchoCanceller::SpeakerOutCallback(unsigned char* data, size_t len){
if(len!=960*2 || !enableAEC || !isOn)
return;
/*size_t offset=0;
while(offset<len){
WebRtcAecm_BufferFarend(state, (int16_t*)(data+offset), AEC_FRAME_SIZE);
offset+=OFFSET_STEP;
}*/
#ifndef TGVOIP_NO_DSP
int16_t* buf=(int16_t*)farendBufferPool->Get();
if(buf){
memcpy(buf, data, 960*2);
farendQueue->Put(buf);
}
#endif
}
#ifndef TGVOIP_NO_DSP
void EchoCanceller::RunBufferFarendThread(void* arg){
while(running){
int16_t* samplesIn=farendQueue->GetBlocking();
if(samplesIn){
webrtc::IFChannelBuffer* bufIn=(webrtc::IFChannelBuffer*) splittingFilterFarendIn;
webrtc::IFChannelBuffer* bufOut=(webrtc::IFChannelBuffer*) splittingFilterFarendOut;
memcpy(bufIn->ibuf()->bands(0)[0], samplesIn, 960*2);
farendBufferPool->Reuse((unsigned char *) samplesIn);
((webrtc::SplittingFilter*)splittingFilterFarend)->Analysis(bufIn, bufOut);
aecMutex.Lock();
//outstandingFarendFrames++;
//LOGV("BufferFarend: %d frames", outstandingFarendFrames);
#ifndef TGVOIP_USE_DESKTOP_DSP
WebRtcAecm_BufferFarend(aec, bufOut->ibuf_const()->bands(0)[0], 160);
WebRtcAecm_BufferFarend(aec, bufOut->ibuf_const()->bands(0)[0]+160, 160);
#else
webrtc::WebRtcAec_BufferFarend(aec, bufOut->fbuf_const()->bands(0)[0], 160);
webrtc::WebRtcAec_BufferFarend(aec, bufOut->fbuf_const()->bands(0)[0]+160, 160);
#endif
aecMutex.Unlock();
didBufferFarend=true;
}
}
}
#endif
void EchoCanceller::Enable(bool enabled){
isOn=enabled;
}
void EchoCanceller::ProcessInput(unsigned char* data, unsigned char* out, size_t len){
int i;
if(!isOn || (!enableAEC && !enableAGC && !enableNS)){
memcpy(out, data, len);
return;
}
#ifndef TGVOIP_NO_DSP
int16_t* samplesIn=(int16_t*)data;
int16_t* samplesOut=(int16_t*)out;
webrtc::IFChannelBuffer* bufIn=(webrtc::IFChannelBuffer*) splittingFilterIn;
webrtc::IFChannelBuffer* bufOut=(webrtc::IFChannelBuffer*) splittingFilterOut;
memcpy(bufIn->ibuf()->bands(0)[0], samplesIn, 960*2);
((webrtc::SplittingFilter*)splittingFilter)->Analysis(bufIn, bufOut);
#ifndef TGVOIP_USE_DESKTOP_DSP
if(enableAEC && enableNS){
int16_t _nsOut[3][320];
int16_t* nsIn[3];
int16_t* nsOut[3];
for(i=0;i<3;i++){
nsIn[i]=(int16_t*)bufOut->ibuf_const()->bands(0)[i];
nsOut[i]=_nsOut[i];
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *) nsIn, 3, nsOut);
for(i=0;i<3;i++){
nsOut[i]+=160;
nsIn[i]+=160;
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *) nsIn, 3, nsOut);
memcpy(bufOut->ibuf()->bands(0)[1], _nsOut[1], 320*2*2);
aecMutex.Lock();
WebRtcAecm_Process(aec, bufOut->ibuf()->bands(0)[0], _nsOut[0], samplesOut, AEC_FRAME_SIZE, (int16_t) tgvoip::audio::AudioOutput::GetEstimatedDelay());
WebRtcAecm_Process(aec, bufOut->ibuf()->bands(0)[0]+160, _nsOut[0]+160, samplesOut+160, AEC_FRAME_SIZE, (int16_t) (tgvoip::audio::AudioOutput::GetEstimatedDelay()+audio::AudioInput::GetEstimatedDelay()));
aecMutex.Unlock();
memcpy(bufOut->ibuf()->bands(0)[0], samplesOut, 320*2);
}else if(enableAEC){
aecMutex.Lock();
WebRtcAecm_Process(aec, bufOut->ibuf()->bands(0)[0], NULL, samplesOut, AEC_FRAME_SIZE, (int16_t) tgvoip::audio::AudioOutput::GetEstimatedDelay());
WebRtcAecm_Process(aec, bufOut->ibuf()->bands(0)[0]+160, NULL, samplesOut+160, AEC_FRAME_SIZE, (int16_t) (tgvoip::audio::AudioOutput::GetEstimatedDelay()+audio::AudioInput::GetEstimatedDelay()));
aecMutex.Unlock();
memcpy(bufOut->ibuf()->bands(0)[0], samplesOut, 320*2);
}else if(enableNS){
int16_t _nsOut[3][320];
int16_t* nsIn[3];
int16_t* nsOut[3];
for(i=0;i<3;i++){
nsIn[i]=(int16_t*)bufOut->ibuf_const()->bands(0)[i];
nsOut[i]=_nsOut[i];
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *) nsIn, 3, nsOut);
for(i=0;i<3;i++){
nsOut[i]+=160;
nsIn[i]+=160;
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *) nsIn, 3, nsOut);
memcpy(bufOut->ibuf()->bands(0)[0], _nsOut[0], 320*2);
memcpy(bufOut->ibuf()->bands(0)[1], _nsOut[1], 320*2);
memcpy(bufOut->ibuf()->bands(0)[2], _nsOut[2], 320*2);
}
#else
/*if(enableNS){
float _nsOut[3][320];
const float* nsIn[3];
float* nsOut[3];
for(i=0;i<3;i++){
nsIn[i]=bufOut->fbuf_const()->bands(0)[i];
nsOut[i]=_nsOut[i];
}
WebRtcNs_Process((NsHandle*)ns, nsIn, 3, nsOut);
for(i=0;i<3;i++){
nsOut[i]+=160;
nsIn[i]+=160;
}
WebRtcNs_Process((NsHandle*)ns, nsIn, 3, nsOut);
memcpy(bufOut->fbuf()->bands(0)[0], _nsOut[0], 320*4);
memcpy(bufOut->fbuf()->bands(0)[1], _nsOut[1], 320*4);
memcpy(bufOut->fbuf()->bands(0)[2], _nsOut[2], 320*4);
}*/
if(enableNS){
int16_t _nsOut[3][320];
int16_t* nsIn[3];
int16_t* nsOut[3];
for(i=0;i<3;i++){
nsIn[i]=(int16_t*)bufOut->ibuf_const()->bands(0)[i];
nsOut[i]=_nsOut[i];
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *)nsIn, 3, nsOut);
for(i=0;i<3;i++){
nsOut[i]+=160;
nsIn[i]+=160;
}
WebRtcNsx_Process((NsxHandle*)ns, (const short *const *)nsIn, 3, nsOut);
memcpy(bufOut->ibuf()->bands(0)[0], _nsOut[0], 320*2);
memcpy(bufOut->ibuf()->bands(0)[1], _nsOut[1], 320*2);
memcpy(bufOut->ibuf()->bands(0)[2], _nsOut[2], 320*2);
}
if(enableAEC){
const float* aecIn[3];
float* aecOut[3];
float _aecOut[3][320];
for(i=0;i<3;i++){
aecIn[i]=bufOut->fbuf_const()->bands(0)[i];
aecOut[i]=_aecOut[i];
}
webrtc::WebRtcAec_Process(aec, aecIn, 3, aecOut, AEC_FRAME_SIZE, audio::AudioOutput::GetEstimatedDelay()+audio::AudioInput::GetEstimatedDelay(), 0);
for(i=0;i<3;i++){
aecOut[i]+=160;
aecIn[i]+=160;
}
webrtc::WebRtcAec_Process(aec, aecIn, 3, aecOut, AEC_FRAME_SIZE, audio::AudioOutput::GetEstimatedDelay()+audio::AudioInput::GetEstimatedDelay(), 0);
//outstandingFarendFrames--;
//LOGV("Process: %d frames", outstandingFarendFrames);
memcpy(bufOut->fbuf()->bands(0)[0], _aecOut[0], 320*4);
memcpy(bufOut->fbuf()->bands(0)[1], _aecOut[1], 320*4);
memcpy(bufOut->fbuf()->bands(0)[2], _aecOut[2], 320*4);
}
#endif
if(enableAGC){
int16_t _agcOut[3][320];
int16_t* agcIn[3];
int16_t* agcOut[3];
for(i=0;i<3;i++){
agcIn[i]=(int16_t*)bufOut->ibuf_const()->bands(0)[i];
agcOut[i]=_agcOut[i];
}
uint8_t saturation;
WebRtcAgc_AddMic(agc, agcIn, 3, 160);
WebRtcAgc_Process(agc, (const int16_t *const *) agcIn, 3, 160, agcOut, agcMicLevel, &agcMicLevel, 0, &saturation);
for(i=0;i<3;i++){
agcOut[i]+=160;
agcIn[i]+=160;
}
WebRtcAgc_AddMic(agc, agcIn, 3, 160);
WebRtcAgc_Process(agc, (const int16_t *const *) agcIn, 3, 160, agcOut, agcMicLevel, &agcMicLevel, 0, &saturation);
//LOGV("AGC mic level %d", agcMicLevel);
memcpy(bufOut->ibuf()->bands(0)[0], _agcOut[0], 320*2);
memcpy(bufOut->ibuf()->bands(0)[1], _agcOut[1], 320*2);
memcpy(bufOut->ibuf()->bands(0)[2], _agcOut[2], 320*2);
}
((webrtc::SplittingFilter*)splittingFilter)->Synthesis(bufOut, bufIn);
memcpy(samplesOut, bufIn->ibuf_const()->bands(0)[0], 960*2);
#endif
}
void EchoCanceller::SetAECStrength(int strength){
#ifndef TGVOIP_NO_DSP
if(aec){
#ifndef TGVOIP_USE_DESKTOP_DSP
AecmConfig cfg;
cfg.cngMode=AecmFalse;
cfg.echoMode=(int16_t) strength;
WebRtcAecm_set_config(aec, cfg);
#endif
}
#endif
}
AudioEffect::~AudioEffect(){
}
void AudioEffect::SetPassThrough(bool passThrough){
this->passThrough=passThrough;
}
AutomaticGainControl::AutomaticGainControl(){
#ifndef TGVOIP_NO_DSP
splittingFilter=new webrtc::SplittingFilter(1, 3, 960);
splittingFilterIn=new webrtc::IFChannelBuffer(960, 1, 1);
splittingFilterOut=new webrtc::IFChannelBuffer(960, 1, 3);
agc=WebRtcAgc_Create();
WebRtcAgcConfig agcConfig;
agcConfig.compressionGaindB = 9;
agcConfig.limiterEnable = 1;
agcConfig.targetLevelDbfs = 3;
WebRtcAgc_Init(agc, 0, 255, kAgcModeAdaptiveDigital, 48000);
WebRtcAgc_set_config(agc, agcConfig);
agcMicLevel=0;
#endif
}
AutomaticGainControl::~AutomaticGainControl(){
#ifndef TGVOIP_NO_DSP
delete (webrtc::SplittingFilter*)splittingFilter;
delete (webrtc::IFChannelBuffer*)splittingFilterIn;
delete (webrtc::IFChannelBuffer*)splittingFilterOut;
WebRtcAgc_Free(agc);
#endif
}
void AutomaticGainControl::Process(int16_t *inOut, size_t numSamples){
#ifndef TGVOIP_NO_DSP
if(passThrough)
return;
if(numSamples!=960){
LOGW("AutomaticGainControl only works on 960-sample buffers (got %u samples)", (unsigned int)numSamples);
return;
}
//LOGV("processing frame through AGC");
webrtc::IFChannelBuffer* bufIn=(webrtc::IFChannelBuffer*) splittingFilterIn;
webrtc::IFChannelBuffer* bufOut=(webrtc::IFChannelBuffer*) splittingFilterOut;
memcpy(bufIn->ibuf()->bands(0)[0], inOut, 960*2);
((webrtc::SplittingFilter*)splittingFilter)->Analysis(bufIn, bufOut);
int i;
int16_t _agcOut[3][320];
int16_t* agcIn[3];
int16_t* agcOut[3];
for(i=0;i<3;i++){
agcIn[i]=(int16_t*)bufOut->ibuf_const()->bands(0)[i];
agcOut[i]=_agcOut[i];
}
uint8_t saturation;
WebRtcAgc_AddMic(agc, agcIn, 3, 160);
WebRtcAgc_Process(agc, (const int16_t *const *) agcIn, 3, 160, agcOut, agcMicLevel, &agcMicLevel, 0, &saturation);
for(i=0;i<3;i++){
agcOut[i]+=160;
agcIn[i]+=160;
}
WebRtcAgc_AddMic(agc, agcIn, 3, 160);
WebRtcAgc_Process(agc, (const int16_t *const *) agcIn, 3, 160, agcOut, agcMicLevel, &agcMicLevel, 0, &saturation);
memcpy(bufOut->ibuf()->bands(0)[0], _agcOut[0], 320*2);
memcpy(bufOut->ibuf()->bands(0)[1], _agcOut[1], 320*2);
memcpy(bufOut->ibuf()->bands(0)[2], _agcOut[2], 320*2);
((webrtc::SplittingFilter*)splittingFilter)->Synthesis(bufOut, bufIn);
memcpy(inOut, bufIn->ibuf_const()->bands(0)[0], 960*2);
#endif
}
| 30.312364 | 206 | 0.714684 | kebbbnnn |
33ee39f036d47eeca1f02a556144d2ea0632affc | 62,240 | cpp | C++ | cbits/coin/CglTwomir.cpp | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 8 | 2015-05-11T04:18:49.000Z | 2020-02-16T00:14:35.000Z | cbits/coin/CglTwomir.cpp | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 9 | 2015-06-06T22:02:28.000Z | 2020-02-01T22:03:59.000Z | cbits/coin/CglTwomir.cpp | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 4 | 2015-05-20T22:04:53.000Z | 2020-01-29T21:46:25.000Z | // $Id: CglTwomir.cpp 1132 2013-04-25 18:57:12Z stefan $
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cfloat>
#include <cassert>
#include <iostream>
#include "CoinPragma.hpp"
#include "CoinHelperFunctions.hpp"
#include "CoinPackedVector.hpp"
#include "CoinPackedMatrix.hpp"
#include "CoinIndexedVector.hpp"
#include "OsiRowCutDebugger.hpp"
#include "CoinFactorization.hpp"
#include "CoinWarmStartBasis.hpp"
#include "CoinFinite.hpp"
#include "CoinPackedMatrix.hpp"
#include "OsiRowCutDebugger.hpp"
#include "CoinWarmStartBasis.hpp"
#include "CglTwomir.hpp"
class CoinWarmStartBasis;
#define COIN_HAS_CLP_TWOMIR
#ifdef COIN_HAS_CLP_TWOMIR
#include "OsiClpSolverInterface.hpp"
#endif
#undef DGG_DEBUG_DGG
//#define DGG_DEBUG_DGG 1
//#define CGL_DEBUG
//#define CGL_DEBUG_ZERO
#define q_max data->cparams.q_max
#define q_min data->cparams.q_min
#define t_max data->cparams.t_max
#define t_min data->cparams.t_min
#define a_max data->cparams.a_max
#define max_elements data->cparams.max_elements
#ifdef CGL_DEBUG
// Declarations and defines for debug build.
#define talk true
namespace {
const OsiSolverInterface *six ;
}
void write_cut( DGG_constraint_t *cut){ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
printf("2mir_test: cut: !!!!!!!!!!!!!!!!!!!!!!!***********************************\n");
for (int i=0; i<cut->nz; i++)
{ printf(" %12.10f x[%d] ", cut->coeff[i],cut->index[i]);}
printf(" >= %12.10f \n", cut->rhs);
}
void testus( DGG_constraint_t *cut){ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// const OsiRowCutDebugger debugg(*six, "flugpl.mps");
const OsiRowCutDebugger debugg(*six, "egout.mps");
const OsiRowCutDebugger *debugger = &debugg;
if (debugger&&!debugger->onOptimalPath(*six))
return;
OsiRowCut rowcut;
rowcut.setRow(cut->nz, cut->index, cut->coeff);
rowcut.setUb(DBL_MAX);
rowcut.setLb(cut->rhs);
if(debugger->invalidCut(rowcut)){
write_cut(cut);
//assert(0);
}
}
#else // CGL_DEBUG
#define talk false
#endif // CGL_DEBUG
//-------------------------------------------------------------------
// Generate cuts
//-------------------------------------------------------------------
void CglTwomir::generateCuts(const OsiSolverInterface & si, OsiCuts & cs,
const CglTreeInfo info )
{
# ifdef CGL_DEBUG
//!!!!!!!!!!!!!!!!!!
six = &si;
# endif
const double * colUpper = si.getColUpper();
const double * colLower = si.getColLower();
const OsiSolverInterface * useSolver;
#ifdef COIN_HAS_CLP_TWOMIR
double * objective = NULL;
OsiClpSolverInterface * clpSolver = dynamic_cast<OsiClpSolverInterface *>(originalSolver_);
int numberOriginalRows;
int numberColumns=si.getNumCols();
int twomirType=0;
if (!clpSolver) {
#endif
useSolver=&si;
// Temp - check if free variables
int ncol = useSolver->getNumCols();
int numberFree=0;
for (int i=0;i<ncol;i++) {
if (colLower[i]<-1.0e20&&colUpper[i]>1.0e20)
numberFree++;
}
if (numberFree) {
#ifdef COIN_DEVELOP
if (!info.inTree&&!info.pass)
printf("CglTwoMir - %d free variables - returning\n",numberFree);
#endif
return;
}
#ifdef COIN_HAS_CLP_TWOMIR
} else {
useSolver = originalSolver_;
assert (twomirType_);
// check simplex is plausible
if (!clpSolver->getNumRows()||numberColumns!=clpSolver->getNumCols()) {
delete originalSolver_;
originalSolver_=si.clone();
clpSolver = dynamic_cast<OsiClpSolverInterface *>(originalSolver_);
assert (clpSolver);
useSolver = originalSolver_;
}
ClpSimplex * simplex = clpSolver->getModelPtr();
numberOriginalRows = simplex->numberRows();
int numberRows = si.getNumRows();
assert (numberOriginalRows<=numberRows);
// only do if different (unless type 2x)
twomirType = twomirType_%10;
int whenToDo = twomirType_/10;
if (whenToDo==2 ||(numberRows>numberOriginalRows && whenToDo==1
&& (info.options&512)==0) ||
((info.options&1024)!=0 && (info.options&512)==0)) {
// bounds
const double * solution = si.getColSolution();
memcpy(simplex->columnLower(),colLower,numberColumns*sizeof(double));
memcpy(simplex->columnUpper(),colUpper,numberColumns*sizeof(double));
for (int i=0;i<numberColumns;i++) {
if (colLower[i]<-1.0e20&&colUpper[i]>1.0e20) {
double lower=-COIN_DBL_MAX;
double upper=COIN_DBL_MAX;
if (solution[i]>0.0)
lower=-1.0e10;
else
upper=1.0e10;
originalSolver_->setColLower(i,lower);
originalSolver_->setColUpper(i,upper);
}
}
double * obj = simplex->objective();
objective = CoinCopyOfArray(obj,numberColumns);
const double * pi = si.getRowPrice();
const CoinPackedMatrix * rowCopy = si.getMatrixByRow();
const int * column = rowCopy->getIndices();
const CoinBigIndex * rowStart = rowCopy->getVectorStarts();
const int * rowLength = rowCopy->getVectorLengths();
const double * rowElements = rowCopy->getElements();
const double * rowLower = si.getRowLower();
const double * rowUpper = si.getRowUpper();
int numberCopy;
int numberAdd;
double * rowLower2 = NULL;
double * rowUpper2 = NULL;
int * column2 = NULL;
CoinBigIndex * rowStart2 = NULL;
double * rowElements2 = NULL;
char * copy = new char [numberRows-numberOriginalRows];
memset(copy,0,numberRows-numberOriginalRows);
if (twomirType==2) {
numberCopy=0;
numberAdd=0;
for (int iRow=numberOriginalRows;iRow<numberRows;iRow++) {
bool simple = true;
for (int k=rowStart[iRow];
k<rowStart[iRow]+rowLength[iRow];k++) {
double value = rowElements[k];
if (value!=floor(value+0.5)) {
simple=false;
break;
}
}
if (simple) {
numberCopy++;
numberAdd+=rowLength[iRow];
copy[iRow-numberOriginalRows]=1;
}
}
if (numberCopy) {
//printf("Using %d rows out of %d\n",numberCopy,numberRows-numberOriginalRows);
rowLower2 = new double [numberCopy];
rowUpper2 = new double [numberCopy];
rowStart2 = new CoinBigIndex [numberCopy+1];
rowStart2[0]=0;
column2 = new int [numberAdd];
rowElements2 = new double [numberAdd];
}
}
numberCopy=0;
numberAdd=0;
const double * rowSolution = si.getRowActivity();
double offset=0.0;
for (int iRow=numberOriginalRows;iRow<numberRows;iRow++) {
if (!copy[iRow-numberOriginalRows]) {
double value = pi[iRow];
offset += rowSolution[iRow]*value;
for (int k=rowStart[iRow];
k<rowStart[iRow]+rowLength[iRow];k++) {
int iColumn=column[k];
obj[iColumn] -= value*rowElements[k];
}
} else {
rowLower2[numberCopy]=rowLower[iRow];
rowUpper2[numberCopy]=rowUpper[iRow];
for (int k=rowStart[iRow];
k<rowStart[iRow]+rowLength[iRow];k++) {
column2[numberAdd]=column[k];
rowElements2[numberAdd++]=rowElements[k];
}
numberCopy++;
rowStart2[numberCopy]=numberAdd;
}
}
#if 0
CoinThreadRandom randomNumberGenerator;
const double * solution = si.getColSolution();
for (int i=0;i<numberColumns;i++) {
if (intVar[i]==1) {
double randomNumber = randomNumberGenerator.randomDouble();
//randomNumber = 0.001*floor(randomNumber*1000.0);
if (solution[i]>0.5)
obj[i] -= randomNumber*0.001*fabs(obj[i]);
else
obj[i] += randomNumber*0.001*fabs(obj[i]);
}
}
#endif
if (numberCopy) {
clpSolver->addRows(numberCopy,
rowStart2,column2,rowElements2,
rowLower2,rowUpper2);
delete [] rowLower2 ;
delete [] rowUpper2 ;
delete [] column2 ;
delete [] rowStart2 ;
delete [] rowElements2 ;
}
delete [] copy;
memcpy(simplex->primalColumnSolution(),si.getColSolution(),
numberColumns*sizeof(double));
CoinWarmStart * warmstart = si.getWarmStart();
CoinWarmStartBasis* warm =
dynamic_cast<CoinWarmStartBasis*>(warmstart);
warm->resize(simplex->numberRows(),numberColumns);
clpSolver->setBasis(*warm);
delete warm;
simplex->setDualObjectiveLimit(COIN_DBL_MAX);
simplex->setLogLevel(0);
clpSolver->resolve();
//printf("Trying - %d its status %d objs %g %g - with offset %g\n",
// simplex->numberIterations(),simplex->status(),
// simplex->objectiveValue(),si.getObjValue(),simplex->objectiveValue()+offset);
//simplex->setLogLevel(0);
if (simplex->status()) {
//printf("BAD status %d\n",simplex->status());
//clpSolver->writeMps("clp");
//si.writeMps("si");
delete [] objective;
objective=NULL;
useSolver=&si;
}
}
}
#endif
useSolver->getStrParam(OsiProbName,probname_) ;
int numberRowCutsBefore = cs.sizeRowCuts();
DGG_list_t cut_list;
DGG_list_init (&cut_list);
DGG_data_t* data = DGG_getData(reinterpret_cast<const void *> (useSolver));
// Note that the lhs variables are hash defines to data->cparams.*
q_max = q_max_;
q_min = q_min_;
t_max = t_max_;
t_min = t_min_;
a_max = a_max_;
max_elements = info.inTree ? max_elements_ : max_elements_root_;
data->gomory_threshold = info.inTree ? away_ : awayAtRoot_;
if (!info.inTree) {
//const CoinPackedMatrix * columnCopy = useSolver->getMatrixByCol();
//int numberColumns=columnCopy->getNumCols();
if (!info.pass||(info.options&32)!=0) {
max_elements=useSolver->getNumCols();
//} else {
//int numberRows=columnCopy.getNumRows();
//int numberElements=columnCopy->getNumElements();
//if (max_elements>500&&numberElements>10*numberColumns)
//max_elements=numberColumns;
}
}
if (!do_mir_) t_max = t_min - 1;
if (!do_2mir_) q_max = q_min - 1;
if (do_tab_ && info.level < 1 && info.pass < 6)
DGG_generateTabRowCuts( &cut_list, data, reinterpret_cast<const void *> (useSolver) );
if (do_form_)
DGG_generateFormulationCuts( &cut_list, data, reinterpret_cast<const void *> (useSolver),
info.formulation_rows,
randomNumberGenerator_);
#ifdef CGL_DEBUG
const OsiRowCutDebugger debugg(si,probname_.c_str()) ;
const OsiRowCutDebugger *debugger = &debugg;
if (debugger&&!debugger->onOptimalPath(si))
debugger = NULL;
else
{if(talk) printf ("2mir_test: debug success\n");}
#endif
int i;
for ( i=0; i<cut_list.n; i++){
DGG_constraint_t *cut = cut_list.c[i];
OsiRowCut rowcut;
if (cut->nz<max_elements) {
// See if any zero coefficients!!!!!!!
int nZero=0;
for( int i=0; i < cut->nz; i++) {
if (!cut->coeff[i])
nZero++;
}
#ifdef CGL_DEBUG_ZERO
if (nZero) {
printf("Cut ");
for( int i=0; i < cut->nz; i++) {
printf("%d %g ",cut->index[i],cut->coeff[i]);
}
printf("\n");
}
#endif
if (nZero) {
#ifdef CGL_DEBUG_ZERO
printf("TwoMir cut had %d zero coefficients!\n",nZero);
#endif
} else {
#ifdef CBC_CHECK_CUT
double rhs = cut->rhs;
int * cutIndex = cut->index;
double * packed = cut->coeff;
int i,number2=cut->nz;
int number=0;
double largest=0.0;
double smallest=1.0e30;
const double *colUpper = useSolver->getColUpper();
const double *colLower = useSolver->getColLower();
bool goodCut=true;
for (i=0;i<number2;i++) {
double value=fabs(packed[i]);
if (value<1.0e-9) {
int iColumn = cutIndex[i];
if (colUpper[iColumn]-colLower[iColumn]<100.0) {
// weaken cut
if (packed[i]>0.0)
rhs -= value*colUpper[iColumn];
else
rhs += value*colLower[iColumn];
} else {
// throw away
goodCut=false;
break;
}
} else {
int iColumn = cutIndex[i];
if (colUpper[iColumn]!=colLower[iColumn]) {
largest=CoinMax(largest,value);
smallest=CoinMin(smallest,value);
cutIndex[number]=cutIndex[i];
packed[number++]=packed[i];
} else {
// fixed so subtract out
rhs -= packed[i]*colLower[iColumn];
}
}
}
if (largest<5.0e9*smallest&&goodCut) {
rowcut.setRow(number, cutIndex, packed);
rowcut.setUb(COIN_DBL_MAX);
rowcut.setLb(rhs);
cs.insert(rowcut);
}
#else
rowcut.setRow(cut->nz, cut->index, cut->coeff);
rowcut.setUb(DBL_MAX);
rowcut.setLb(cut->rhs);
cs.insert(rowcut);
#endif
}
#ifdef CGL_DEBUG
if (debugger) {
if (debugger->invalidCut(rowcut)) {
write_cut(cut);
printf ("2mir_test: debug failed, mayday, mayday **********************************\n");}
//assert(0);
}
//assert(!debugger->invalidCut(rowcut));
#endif
}
}
for ( i=0; i<cut_list.n; i++)
DGG_freeConstraint (cut_list.c[i]);
DGG_list_free (&cut_list);
DGG_freeData (data);
if (!info.inTree&&((info.options&4)==4||((info.options&8)&&!info.pass))) {
int numberRowCutsAfter = cs.sizeRowCuts();
for (int i=numberRowCutsBefore;i<numberRowCutsAfter;i++) {
int length = cs.rowCutPtr(i)->row().getNumElements();
if (length<=max_elements_)
cs.rowCutPtr(i)->setGloballyValid();
}
}
#ifdef COIN_HAS_CLP_TWOMIR
if (objective) {
int numberRowCutsAfter = cs.sizeRowCuts();
ClpSimplex * simplex = clpSolver->getModelPtr();
memcpy(simplex->objective(),objective,numberColumns*sizeof(double));
delete [] objective;
// take out locally useless cuts
const double * solution = si.getColSolution();
double primalTolerance = 1.0e-7;
for (int k = numberRowCutsAfter - 1; k >= numberRowCutsBefore; k--) {
const OsiRowCut * thisCut = cs.rowCutPtr(k) ;
double sum = 0.0;
int n = thisCut->row().getNumElements();
const int * column = thisCut->row().getIndices();
const double * element = thisCut->row().getElements();
assert (n);
for (int i = 0; i < n; i++) {
double value = element[i];
sum += value * solution[column[i]];
}
if (sum > thisCut->ub() + primalTolerance) {
sum = sum - thisCut->ub();
} else if (sum < thisCut->lb() - primalTolerance) {
sum = thisCut->lb() - sum;
} else {
sum = 0.0;
}
if (!sum) {
// take out
cs.eraseRowCut(k);
}
}
#ifdef CLP_INVESTIGATE2
printf("OR %p pass %d inTree %c - %d cuts (but %d deleted)\n",
originalSolver_,info.pass,info.inTree?'Y':'N',
numberRowCutsAfter-numberRowCutsBefore,
numberRowCutsAfter-cs.sizeRowCuts());
#endif
}
int numberRowCutsAfter = cs.sizeRowCuts();
if (!info.inTree) {
for (int i=numberRowCutsBefore;i<numberRowCutsAfter;i++) {
cs.rowCutPtr(i)->setGloballyValid();
}
}
if (twomirType==2) {
// back to original
int numberRows = clpSolver->getNumRows();
if (numberRows>numberOriginalRows) {
int numberDelete = numberRows-numberOriginalRows;
int * delRow = new int [numberDelete];
for (int i=0;i<numberDelete;i++)
delRow[i]=i+numberOriginalRows;
clpSolver->deleteRows(numberDelete,delRow);
delete [] delRow;
}
}
#endif
}
//-------------------------------------------------------------------
// Default Constructor
//-------------------------------------------------------------------
CglTwomir::CglTwomir () :
CglCutGenerator(),
probname_(),
randomNumberGenerator_(987654321),originalSolver_(NULL),
away_(0.0005),awayAtRoot_(0.0005),twomirType_(0),
do_mir_(true), do_2mir_(true), do_tab_(true), do_form_(true),
t_min_(1), t_max_(1), q_min_(1), q_max_(1), a_max_(2),max_elements_(50000),
max_elements_root_(50000),form_nrows_(0) {}
//-------------------------------------------------------------------
// Copy constructor
//-------------------------------------------------------------------
CglTwomir::CglTwomir (const CglTwomir & source) :
CglCutGenerator(source),
randomNumberGenerator_(source.randomNumberGenerator_),
originalSolver_(NULL),
away_(source.away_),
awayAtRoot_(source.awayAtRoot_),
twomirType_(source.twomirType_),
do_mir_(source.do_mir_),
do_2mir_(source.do_2mir_),
do_tab_(source.do_tab_),
do_form_(source.do_form_),
t_min_(source.t_min_),
t_max_(source.t_max_),
q_min_(source.q_min_),
q_max_(source.q_max_),
a_max_(source.a_max_),
max_elements_(source.max_elements_),
max_elements_root_(source.max_elements_root_),
form_nrows_(source.form_nrows_)
{
probname_ = source.probname_ ;
if (source.originalSolver_)
originalSolver_ = source.originalSolver_->clone();
}
//-------------------------------------------------------------------
// Clone
//-------------------------------------------------------------------
CglCutGenerator *
CglTwomir::clone() const
{
return new CglTwomir(*this);
}
//-------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------
CglTwomir::~CglTwomir ()
{
delete originalSolver_;
}
//----------------------------------------------------------------
// Assignment operator
//-------------------------------------------------------------------
CglTwomir &
CglTwomir::operator=(const CglTwomir& rhs)
{
if (this != &rhs) {
CglCutGenerator::operator=(rhs);
randomNumberGenerator_ = rhs.randomNumberGenerator_;
away_=rhs.away_;
awayAtRoot_=rhs.awayAtRoot_;
twomirType_ = rhs.twomirType_;
delete originalSolver_;
if (rhs.originalSolver_)
originalSolver_ = rhs.originalSolver_->clone();
else
originalSolver_=NULL;
do_mir_=rhs.do_mir_;
do_2mir_=rhs.do_2mir_;
do_tab_=rhs.do_tab_;
do_form_=rhs.do_form_;
t_min_=rhs.t_min_;
t_max_=rhs.t_max_;
q_min_=rhs.q_min_;
q_max_=rhs.q_max_;
a_max_=rhs.a_max_;
max_elements_=rhs.max_elements_;
max_elements_root_ = rhs.max_elements_root_;
form_nrows_=rhs.form_nrows_;
}
return *this;
}
// Pass in a copy of original solver (clone it)
void
CglTwomir::passInOriginalSolver(OsiSolverInterface * solver)
{
delete originalSolver_;
if (solver) {
if (!twomirType_)
twomirType_=1;
originalSolver_ = solver->clone();
originalSolver_->setHintParam(OsiDoDualInResolve, false, OsiHintDo);
// Temp - check if free variables
const double *colUpper = originalSolver_->getColUpper();
const double *colLower = originalSolver_->getColLower();
int ncol = originalSolver_->getNumCols();
int numberFree=0;
for (int i=0;i<ncol;i++) {
if (colLower[i]<-1.0e20&&colUpper[i]>1.0e20)
numberFree++;
}
if (numberFree)
printf("CglTwoMir - %d free variables - take care\n",numberFree);
} else {
twomirType_=0;
originalSolver_=NULL;
}
}
int DGG_freeData( DGG_data_t *data )
{
free(data->info);
free(data->lb);
free(data->ub);
free(data->x);
free(data->rc);
free(data);
return 0;
}
DGG_data_t* DGG_getData(const void *osi_ptr )
{
DGG_data_t *data = NULL;
const OsiSolverInterface *si = reinterpret_cast<const OsiSolverInterface *> (osi_ptr);
data = reinterpret_cast<DGG_data_t*> (malloc( sizeof(DGG_data_t)) );
/* retrieve basis information */
CoinWarmStart *startbasis = si->getWarmStart();
const CoinWarmStartBasis *basis = dynamic_cast<const CoinWarmStartBasis*>(startbasis);
/* retrieve bounds information */
const double *colUpper = si->getColUpper();
const double *colLower = si->getColLower();
const double *rowUpper = si->getRowUpper();
const double *rowLower = si->getRowLower();
const double *redCost = si->getReducedCost();
const double *dualVal = si->getRowPrice();
/* retrieve current optimal solution */
const double *colSolut = si->getColSolution();
/* retrieve the matrix in row format */
const CoinPackedMatrix *rowMatrixPtr = si->getMatrixByRow();
const int *rowBeg = 0, *rowCnt = 0, *rowInd = 0;
const double *rowMat;
rowBeg = rowMatrixPtr->getVectorStarts();
rowCnt = rowMatrixPtr->getVectorLengths();
rowMat = rowMatrixPtr->getElements();
rowInd = rowMatrixPtr->getIndices();
/* set number of columns and number of rows */
data->ncol = si->getNumCols();
data->nrow = si->getNumRows();
/* set ninteger */
data->ninteger = 0;
/* allocate memory for the arrays in 'data' */
data->info = reinterpret_cast<int*> (malloc( sizeof(int)*(data->ncol+data->nrow)) );
data->lb = reinterpret_cast<double*> (malloc( sizeof(double)*(data->ncol+data->nrow)) );
data->ub = reinterpret_cast<double*> (malloc( sizeof(double)*(data->ncol+data->nrow)) );
data->x = reinterpret_cast<double*> (malloc( sizeof(double)*(data->ncol+data->nrow)) );
data->rc = reinterpret_cast<double*> (malloc( sizeof(double)*(data->ncol+data->nrow)) );
memset(data->info, 0, sizeof(int)*(data->ncol+data->nrow));
/* set parameters for column variables */
data->nbasic_col = 0;
for(int i=0; i < data->ncol; i++){
/* is variable basic */
if ( basis->getStructStatus(i) == CoinWarmStartBasis::basic ){
data->nbasic_col++;
DGG_setIsBasic(data,i);
}
#if DGG_DEBUG_DGG
{
int error = 0;
if ( basis->getStructStatus(i) != CoinWarmStartBasis::basic )
if ( fabs(colSolut[i] - colUpper[i]) > DGG_BOUND_THRESH )
if ( fabs(colSolut[i] - colLower[i]) > DGG_BOUND_THRESH ){
fprintf(stdout, "WARNING!!!! : ");
fprintf(stdout, "variable %d non-basic, lb = %f, ub = %f, x = %f\n",
i, colLower[i], colUpper[i], colSolut[i]);
error+=1;
}
if (error)
fprintf(stdout, "\nFOUND %d errors. BYE.\n", error);
}
#endif
/* set variable bounds*/
data->lb[i] = colLower[i];
data->ub[i] = colUpper[i];
/* is variable integer */
if ( si->isInteger(i) ){
data->ninteger++;
DGG_setIsInteger(data,i);
/* tighten variable bounds*/
data->lb[i] = ceil(colLower[i]);
data->ub[i] = floor(colUpper[i]);
}
/* set x value */
data->x[i] = colSolut[i];
/* WARNING: remember to set rc!! Its not set!! */
data->rc[i] = redCost[i];
}
/* set parameters for row variables */
/* slack variables (row variables) work as follows:
for a ranged constraint, b_dw < ax < b_up, define a variable s so that
1) if b_up is not infinity:
ax + s = b_up, 0 < s < b_up - b_dw
2) if b_up is infinity:
ax - s = b_dw, 0 < s < b_up - b_dw
*/
{
int i,j;
double activity;
data->nbasic_row = 0;
for(i=0, j=data->ncol; i < data->nrow; i++, j++){
/* check if the row is an equality constraint */
if ( fabs( rowUpper[i] - rowLower[i] ) <= DGG_BOUND_THRESH )
DGG_setEqualityConstraint(data,j);
/* check if the row is bounded above/below and define variable bounds */
if ( rowUpper[i] < COIN_DBL_MAX )
DGG_setIsConstraintBoundedAbove(data,j);
if ( rowLower[i] > -1*COIN_DBL_MAX )
DGG_setIsConstraintBoundedBelow(data,j);
data->lb[j] = 0.0;
if (DGG_isConstraintBoundedAbove(data,j) && DGG_isConstraintBoundedBelow(data,j))
data->ub[j] = rowUpper[i] - rowLower[i];
else
data->ub[j] = COIN_DBL_MAX;
/* compute row activity. for this we need to go to the row in question,
and multiply all the coefficients times their respective variables.
For the moment, we will store the inverse of this value in
the 'x' field (since it is in fact a partial computation of it) */
{
int k;
activity = 0.0;
for(k=rowBeg[i]; k < rowBeg[i]+rowCnt[i]; k++)
activity += rowMat[k]*colSolut[rowInd[k]];
}
/* compute x value */
if ( DGG_isConstraintBoundedAbove(data,j) )
data->x[j] = rowUpper[i] - activity;
else
data->x[j] = activity - rowLower[i];
if ( data->x[j] < -DGG_NULL_SLACK ){
#if DGG_DEBUG_DGG
int k;
double norm = 0.0, min = DBL_MAX, amin = DBL_MAX, max = DBL_MIN;
printf("** warning: row %d has negative slack!\n", i);
for(k=rowBeg[i]; k < rowBeg[i]+rowCnt[i]; k++){
norm += rowMat[k]*rowMat[k];
if ( fabs(rowMat[k]) < amin ) amin = fabs(rowMat[k]);
if ( rowMat[k] < min ) min = rowMat[k];
if ( rowMat[k] > max ) max = rowMat[k];
}
norm = sqrt(norm);
printf("min = %f amin = %f max = %f\n", min, amin, max);
printf("rlower = %f activity = %f\n", rowLower[i], activity);
printf("norm = %f (b-ax) = %f\n", norm, (rowLower[i] - activity));
printf("steepn = %f\n", (rowLower[i] - activity)/norm);
#endif
}
data->rc[j] = dualVal[i];
#if DGG_DEBUG_SOLVER
DGG_IF_EXIT( !DGG_isConstraintBoundedAbove(data,j) && !DGG_isConstraintBoundedBelow(data,j),
1, "some row is not bounded above or below");
#endif
/* is variable basic */
if ( basis->getArtifStatus(i) == CoinWarmStartBasis::basic ){
data->nbasic_row++;
DGG_setIsBasic(data,j);
}
/* is variable integer. For this we need to go to the row in question,
and check that the rhs is integer, and that all of the coefficients
and variables participating in the constraint are also integer. */
{
int k;
if( DGG_isConstraintBoundedAbove(data,j)) {
if ( frac_part(rowUpper[i]) > DGG_INTEGRALITY_THRESH )
goto DONE_ROW;
}
else
if ( frac_part(rowLower[i]) > DGG_INTEGRALITY_THRESH )
goto DONE_ROW;
for(k=rowBeg[i]; k < rowBeg[i]+rowCnt[i]; k++)
if ( frac_part(rowMat[k]) > DGG_INTEGRALITY_THRESH || !DGG_isInteger(data, rowInd[k]))
goto DONE_ROW;
DGG_setIsInteger(data, j);
data->ninteger++;
}
DONE_ROW:;
/* set variable bounds: careful!! Later, remember to adjust
the INFINITY to a DGG standard (to deal with neq solvers). */
/* WARNING: remember to set rc!! Its not set!! */
}
}
/* CLEANUP */
delete basis;
return data;
}
DGG_constraint_t*
DGG_getSlackExpression(const void *osi_ptr, DGG_data_t* data, int row_index)
{
DGG_constraint_t *row = 0;
int i,j;
/* retrieve the matrix in row format */
const OsiSolverInterface *si = reinterpret_cast<const OsiSolverInterface *> (osi_ptr);
const CoinPackedMatrix *rowMatrixPtr = si->getMatrixByRow();
const int *rowBeg = 0, *rowCnt = 0, *rowInd = 0;
const double *rowMat;
const double *rowUpper;
const double *rowLower;
row = DGG_newConstraint(data->ncol);
rowBeg = rowMatrixPtr->getVectorStarts();
rowCnt = rowMatrixPtr->getVectorLengths();
rowMat = rowMatrixPtr->getElements();
rowInd = rowMatrixPtr->getIndices();
rowUpper = si->getRowUpper();
rowLower = si->getRowLower();
#if DGG_DEBUG_DGG
if ( row_index < 0 || row_index > data->nrow )
DGG_THROW(0, "bad row index");
#endif
/* copy the information into the row ADT */
row->nz = rowCnt[row_index];
for(j=0, i=rowBeg[row_index]; i < rowBeg[row_index]+rowCnt[row_index]; i++, j++){
row->coeff[j] = rowMat[i];
row->index[j] = rowInd[i];
if (DGG_isConstraintBoundedAbove (data, data->ncol + row_index))
row->coeff[j] = -row->coeff[j];
}
row->sense = '?';
if ( DGG_isConstraintBoundedAbove(data, data->ncol + row_index) )
row->rhs = rowUpper[row_index];
else
row->rhs = -rowLower[row_index];
return row;
}
int
DGG_getTableauConstraint( int index, const void *osi_ptr, DGG_data_t *data,
DGG_constraint_t* tabrow,
const int * colIsBasic,
const int * /*rowIsBasic*/,
CoinFactorization & factorization,
int mode )
{
#if DGG_DEBUG_DGG
/* ensure that the index corresponds to a basic variable */
if ( !DGG_isBasic(data, index) )
DGG_THROW(1, "index is non-basic");
/* ensure that the index corresponds to a column variable */
if ( index < 0 || index > (data->ncol - 1) )
DGG_THROW(1, "index not a column variable");
#endif
/* obtain pointer to solver interface */
const OsiSolverInterface *si = reinterpret_cast<const OsiSolverInterface *> (osi_ptr);
DGG_TEST(!si, 1, "null OsiSolverInterfave");
/* obtain address of the LP matrix */
const CoinPackedMatrix *colMatrixPtr = si->getMatrixByCol();
const int* colBeg = colMatrixPtr->getVectorStarts();
const int* colCnt = colMatrixPtr->getVectorLengths();
const int* colInd = colMatrixPtr->getIndices();
const double* colMat = colMatrixPtr->getElements();
/* obtain row right-hand-sides */
const double *rowUpper = si->getRowUpper();
const double *rowLower = si->getRowLower();
/* allocate memory for constraint in non-sparse form */
int nz = 0;
double *value = NULL, rhs = 0.0;
value = reinterpret_cast<double*>(malloc(sizeof(double)*(data->nrow+data->ncol)));
memset(value, 0, sizeof(double)*(data->nrow+data->ncol));
/* obtain the tableau row coefficients for all variables */
/* note: we could speed this up by only computing non-basic variables */
{
int i, j, cnt = 0;
double one = 1.0;
CoinIndexedVector work;
CoinIndexedVector array;
work.reserve(data->nrow);
array.reserve(data->nrow);
array.setVector(1,&colIsBasic[index],&one);
factorization.updateColumnTranspose ( &work, &array );
int * arrayRows = array.getIndices();
double *arrayElements = array.denseVector();
cnt = array.getNumElements();
/* compute column (structural) variable coefficients */
for(j = 0; j < data->ncol; j++) {
value[j] = 0.0;
for(i=colBeg[j]; i < colBeg[j]+colCnt[j]; i++)
value[j] += colMat[i]*arrayElements[ colInd[i] ];
}
#if DGG_DEBUG_SOLVER
/* check pivot */
if ( fabs(value[index] - 1.0) > DGG_INTEGRALITY_THRESH )
DGG_THROW(1, "pivot is not one");
#endif
/* compute row variable (slack/logical) variable coefficients */
for(j = 0; j < cnt; j++){
if ( DGG_isEqualityConstraint(data,data->ncol + arrayRows[j]) && !mode )
value[ data->ncol + arrayRows[j] ] = 0.0;
else if ( DGG_isConstraintBoundedAbove(data, data->ncol + arrayRows[j]) )
value[ data->ncol + arrayRows[j] ] = arrayElements[ arrayRows[j] ];
else
value[ data->ncol + arrayRows[j] ] = -1*arrayElements[ arrayRows[j] ];
}
/* compute rhs */
rhs = 0.0;
for(i=0; i < cnt; i++){
if ( DGG_isConstraintBoundedAbove(data,data->ncol + arrayRows[i]) )
rhs += arrayElements[arrayRows[i]]*rowUpper[arrayRows[i]];
else
rhs += arrayElements[arrayRows[i]]*rowLower[arrayRows[i]];
}
/* free 'work' and 'array' ?? do the empty functions do it?? they are not
cleared in CglGomory. Is that due to a mistake? Is it done on purpose? */
/*
work.empty();
array.empty();
*/
}
/* count non-zeroes */
nz = 0;
int j;
for( j=0; j<data->ncol+data->nrow; j++){
if ( fabs(value[j]) > DGG_MIN_TABLEAU_COEFFICIENT )
nz += 1;
}
/* put in sparse constraint format */
/* technical issue: should we let max_nz == nz or should we instead
set max_nz == (nrow+ncol). The advantage of the latter approach
is that later, when we substitute the slacks, the denser column
will not require us to re-allocate memory */
tabrow->max_nz = nz;
if (tabrow->coeff)
free(tabrow->coeff);
if (tabrow->index)
free(tabrow->index);
tabrow->coeff = reinterpret_cast<double*> (malloc(sizeof(double)*nz));
tabrow->index = reinterpret_cast<int*> (malloc(sizeof(int)*nz));
tabrow->nz = 0;
for( j = 0; j < data->ncol + data->nrow; j++)
if ( fabs(value[j]) > DGG_MIN_TABLEAU_COEFFICIENT ){
tabrow->coeff[tabrow->nz] = value[j];
tabrow->index[tabrow->nz] = j;
tabrow->nz += 1;
}
tabrow->sense = 'E';
tabrow->rhs = rhs;
/* CLEANUP */
free(value);
return 0;
}
int
DGG_getFormulaConstraint( int da_row,
const void *osi_ptr,
DGG_data_t *data,
DGG_constraint_t* form_row )
{
/* ensure that the da_row corresponds to a row */
if ( data->nrow <= da_row || 0> da_row) DGG_THROW(1, "row out of range...");
/* obtain pointer to solver interface */
const OsiSolverInterface *si = reinterpret_cast<const OsiSolverInterface *> (osi_ptr);
//DGG_TEST(!si, 1, "null OsiSolverInterfave");
/* obtain address of the LP matrix */
const CoinPackedMatrix *rowMatrixPtr = si->getMatrixByRow();
const int* rowBeg = rowMatrixPtr->getVectorStarts();
const int* rowCnt = rowMatrixPtr->getVectorLengths();
const int* rowInd = rowMatrixPtr->getIndices();
const double* rowMat = rowMatrixPtr->getElements();
/* obtain row right-hand-sides */
const double *rowUpper = si->getRowUpper();
const double *rowLower = si->getRowLower();
int nz = rowCnt[da_row];
form_row->nz = nz;
form_row->max_nz = nz+1;
int i;
for( i=0; i < nz; i++) form_row->coeff[i] = rowMat[rowBeg[da_row]+i];
for( i=0; i < nz; i++) form_row->index[i] = rowInd[rowBeg[da_row]+i];
if ( DGG_isConstraintBoundedAbove(data,data->ncol + da_row) ){
form_row->rhs = rowUpper[da_row];
form_row->sense = 'L';
}
else{
form_row->rhs = rowLower[da_row];
form_row->sense = 'G';
}
if ( DGG_isEqualityConstraint(data,data->ncol + da_row) )
form_row->sense = 'E';
/* now add slack/surplus if there is one */
if ( DGG_isEqualityConstraint(data,data->ncol + da_row) == 0 ){
form_row->index[nz] = data->ncol + da_row;
if ( DGG_isConstraintBoundedAbove(data, data->ncol + da_row) )
form_row->coeff[nz] = 1;
else
form_row->coeff[nz] = -1;
form_row->nz +=1;
}
return 0;
}
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
/******************** CONSTRAINT ADTs *****************************************/
DGG_constraint_t* DGG_newConstraint(int max_arrays)
{
DGG_constraint_t *c = NULL;
if (max_arrays <= 0) return NULL;
c = reinterpret_cast<DGG_constraint_t*> (malloc(sizeof(DGG_constraint_t)));
c->nz = 0;
c->max_nz = max_arrays;
c->rhs = 0.0;
c->sense = '?';
c->coeff = NULL;
c->index = NULL;
c->coeff = reinterpret_cast<double*>(malloc(sizeof(double)*max_arrays));
c->index = reinterpret_cast<int*>(malloc(sizeof(int)*max_arrays));
return c;
}
void DGG_freeConstraint(DGG_constraint_t *c)
{
if (c == NULL) return;
if (c->coeff) free(c->coeff);
if (c->index) free(c->index);
free(c);
}
DGG_constraint_t *DGG_copyConstraint(DGG_constraint_t* c)
{
DGG_constraint_t *nc = NULL;
if (!c || c->max_nz <= 0) return nc;
nc = DGG_newConstraint(c->max_nz);
if (nc == NULL) return nc;
nc->nz = c->nz;
nc->rhs = c->rhs;
nc->sense = c->sense;
memcpy(nc->coeff, c->coeff, sizeof(double)*nc->nz);
memcpy(nc->index, c->index, sizeof(int)*nc->nz);
return nc;
}
void DGG_scaleConstraint(DGG_constraint_t *c, int t)
{
int i;
c->rhs *= t;
if (t < 0){
if (c->sense == 'G') c->sense = 'L';
else if (c->sense == 'L') c->sense = 'G';
}
for(i=0; i<c->nz; i++) c->coeff[i] *= t;
}
void DGG_list_init (DGG_list_t *l)
{
l->n = 0;
l->c = NULL;
l->ctype = NULL;
l->alpha = NULL;
}
void DGG_list_free(DGG_list_t *l)
{
if (l->c != NULL) free (l->c);
if (l->ctype != NULL) free (l->ctype);
if (l->alpha != NULL) free (l->alpha);
}
int DGG_list_addcut (DGG_list_t *l, DGG_constraint_t *cut, int ctype, double alpha)
{
l->n ++;
l->c = reinterpret_cast<DGG_constraint_t **>(realloc (l->c, l->n * sizeof(DGG_constraint_t *)));
l->ctype = reinterpret_cast<int *>(realloc (l->ctype, l->n * sizeof (int)));
l->alpha = reinterpret_cast<double *>(realloc (l->alpha, l->n * sizeof (double)));
if (l->c == NULL || l->ctype == NULL || l->alpha == NULL){
printf ("No memory, bailing out\n");
return -1;
}
l->c[l->n - 1] = cut;
l->ctype[l->n - 1] = ctype;
l->alpha[l->n - 1] = alpha;
return 0;
}
void DGG_list_delcut (DGG_list_t *l, int i)
{
if (i >= l->n && i < 0) return;
DGG_freeConstraint (l->c[i]);
l->c[i] = l->c[l->n - 1];
l->ctype[i] = l->ctype[l->n - 1];
l->alpha[i] = l->alpha[l->n - 1];
l->n --;
}
/******************* CONSTRAINT MANIPULATION **********************************/
/* VARIABLES CLOSE TO UPPER BOUNDS:
we will substitute: x' = (u - x); hence the constraint will change from ax ~ b
to -ax' ~ b - au note: the new bounds of x' will be, 0 <= x' <= u - l
VARIABLES CLOSE TO LOWER BOUNDS:
we will substitute: x' = (x - l); hence, the constraint will change from
ax ~ b to ax' ~ b - al. note: some variable lower bounds may have changed
when doing the complement in the previous stage - this must be taken into
account. note: the new bounds of x' will be, 0 <= x' <= u - l */
int DGG_transformConstraint( DGG_data_t *data,
double **x_out,
double **rc_out,
char **isint_out,
DGG_constraint_t *constraint )
{
double half;
double *px = reinterpret_cast<double*> (malloc( sizeof(double)*constraint->max_nz ));
double *rc = reinterpret_cast<double*> (malloc( sizeof(double)*constraint->max_nz ));
char *pi = reinterpret_cast<char*> (malloc( sizeof(char) *constraint->max_nz ));
{
int i, idx;
for(i=0; i < constraint->nz; i++){
idx = constraint->index[i];
px[i] = data->x[idx];
rc[i] = data->rc[idx];
pi[i] = static_cast<char>(DGG_isInteger(data, idx));
half = (data->ub[idx] - data->lb[idx]) / 2;
if ( data->ub[idx] - data->x[idx] < half ){
px[i] = data->ub[idx] - data->x[idx];
if (fabs(px[i]) <= DGG_BOUND_THRESH)
px[i] = 0.0;
constraint->rhs -= constraint->coeff[i]*data->ub[idx];
constraint->coeff[i] *= -1;
}
else {
px[i] = data->x[idx] - data->lb[idx];
if (fabs(px[i]) <= DGG_BOUND_THRESH)
px[i] = 0.0;
constraint->rhs -= constraint->coeff[i]*data->lb[idx];
}
}
}
*x_out = px;
*rc_out = rc;
*isint_out = pi;
#if DGG_DEBUG_DGG
DGG_TEST(DGG_isConstraintViolated(data, constraint), 1, "bad transformation");
#endif
return 0;
}
int DGG_unTransformConstraint( DGG_data_t *data,
DGG_constraint_t *constraint )
{
int i, idx;
double half;
for(i=0; i < constraint->nz; i++){
idx = constraint->index[i];
half = (data->ub[idx] - data->lb[idx]) / 2;
if ( data->ub[idx] - data->x[idx] < half ){
constraint->rhs -= constraint->coeff[i]*data->ub[idx];
constraint->coeff[i] *= -1;
}
else
constraint->rhs += constraint->coeff[i]*data->lb[idx];
}
return 0;
}
int
DGG_substituteSlacks( const void *solver_ptr,
DGG_data_t *data,
DGG_constraint_t *cut )
{
int i,j, lnz;
double *lcut, lrhs;
DGG_constraint_t *row=NULL;
/* lcut will store all the column coefficients. allocate space and init. */
lcut = reinterpret_cast<double*>(malloc(sizeof(double)*data->ncol));
memset(lcut, 0, sizeof(double)*data->ncol);
/* initialize lrhs */
lrhs = cut->rhs;
/* set coefficients in lcut */
/* technical: we could speed this up by re-using allocated memory
for row->coeff and row->index */
for(i=0; i < cut->nz; i++){
if ( cut->index[i] < data->ncol )
lcut[ cut->index[i] ] += cut->coeff[i];
else{
row = DGG_getSlackExpression(solver_ptr, data, (cut->index[i] - data->ncol));
for(j=0; j < row->nz; j++)
lcut[ row->index[j] ] += row->coeff[j]*cut->coeff[i];
lrhs -= row->rhs*cut->coeff[i];
DGG_freeConstraint(row);
}
}
/* count nz in new constraint */
lnz = 0;
for(i=0; i < data->ncol; i++)
if ( fabs(lcut[i]) > DGG_MIN_TABLEAU_COEFFICIENT )
lnz += 1;
/* free row->coeff and row->index, and re-allocate */
free(cut->coeff); cut->coeff = 0;
free(cut->index); cut->index = 0;
cut->nz = lnz;
cut->max_nz = lnz;
if (lnz)
{
cut->coeff = reinterpret_cast<double*> (malloc( sizeof(double)*lnz ));
cut->index = reinterpret_cast<int*> (malloc( sizeof(int)*lnz ));
}
/* set new constraint */
lnz = 0;
for(i=0; i < data->ncol; i++){
if ( fabs(lcut[i]) > DGG_MIN_TABLEAU_COEFFICIENT ){
cut->coeff[lnz] = lcut[i];
cut->index[lnz] = i;
lnz += 1;
}
}
cut->rhs = lrhs;
free(lcut);
return 0;
}
int DGG_nicefyConstraint( const void * /*solver_ptr*/,
DGG_data_t *data,
DGG_constraint_t *cut)
{
double min_coef = COIN_DBL_MAX, max_coef = COIN_DBL_MIN;
DGG_TEST(cut->sense == 'L', 1, "can't nicefy an L constraint");
int i;
for( i=0; i<cut->nz; i++) // first clean out noise
if( fabs(cut->coeff[i]) < DGG_NICEFY_MIN_ABSVALUE)
cut->coeff[i] = 0;
for( i=0; i<cut->nz; i++){
if( DGG_isInteger(data, cut->index[i])){// look at integral vars.
double aht = ABOV(cut->coeff[i]);
double ub = data->ub[ cut->index[i]];
if(aht < DGG_NICEFY_MIN_FIX){// coefficient = integer + epsylon
cut->coeff[i] = floor( cut->coeff[i]);
double ahtu = aht * ub;
if(ahtu<DGG_NICEFY_MAX_PADDING)
cut->rhs -= ahtu;// safely remove the fractional part
else
cut->coeff[i] += DGG_NICEFY_MIN_FIX; // inflate the fractional part
}
else
if (1-aht < DGG_NICEFY_MIN_FIX) // coefficient = integer - epsylon
cut->coeff[i] = ceil( cut->coeff[i]);
}// done with integers
else // now look at continuous variables
if ( cut->coeff[i] < DGG_NICEFY_MIN_ABSVALUE) // delete all negative and noise
cut->coeff[i] = 0.0;
else
if(cut->coeff[i] < DGG_NICEFY_MIN_FIX) {// coefficient = epsylon
double au = cut->coeff[i] * data->ub[ cut->index[i]];
if(au<DGG_NICEFY_MAX_PADDING){ // safely remove the variable
cut->coeff[i] = 0.0;
cut->rhs -= au;
}
else
cut->coeff[i] = DGG_NICEFY_MIN_FIX; // inflate the coefficient
}// done with continuous variables too
double abs_coef = fabs(cut->coeff[i]);
min_coef = DGG_MIN(min_coef, abs_coef);
max_coef = DGG_MAX(max_coef, abs_coef);
}
cut->sense = 'G';
/*
if ( max_coef > DGG_NICEFY_MAX_RATIO*min_coef ) // kill the cut if numbers are all over the place
cut->nz = 0;
*/
return 0;
}
/******************* CUT GENERATION *******************************************/
int
DGG_generateTabRowCuts( DGG_list_t *cut_list,
DGG_data_t *data,
const void *solver_ptr )
{
int k, rval = 0;
DGG_constraint_t *base = NULL;
int nc = cut_list->n;
base = DGG_newConstraint(data->ncol + data->nrow);
if(talk) printf ("2mir_test: generating tab row cuts\n");
/* allocate memory for basic column/row indicators */
int *rowIsBasic = 0, *colIsBasic = 0;
rowIsBasic = reinterpret_cast<int*>(malloc(sizeof(int)*data->nrow));
colIsBasic = reinterpret_cast<int*>(malloc(sizeof(int)*data->ncol));
/* initialize the IsBasic arrays with -1 / 1 values indicating
where the basic rows and columns are. NOTE: WE could do this
only once and keep it in osi_data at the expense of space!! */
int i;
for( i=0; i<data->ncol; i++){
if ( DGG_isBasic(data,i) ) colIsBasic[i] = 1;
else colIsBasic[i] = -1;
}
for( i=0; i<data->nrow; i++){
if ( DGG_isBasic(data,i+data->ncol) ) rowIsBasic[i] = 1;
else rowIsBasic[i] = -1;
}
/* obtain factorization */
CoinFactorization factorization;
/* obtain address of the LP matrix */
const OsiSolverInterface *si = reinterpret_cast<const OsiSolverInterface *> (solver_ptr);
const CoinPackedMatrix *colMatrixPtr = si->getMatrixByCol();
rval = factorization.factorize(*colMatrixPtr, rowIsBasic, colIsBasic);
/* 0 = okay. -1 = singular. -2 = too many in basis. -99 = memory. */
DGG_TEST2(rval, 1, "factorization error = %d", rval);
for(k=0; k<data->ncol; k++){
if (!(DGG_isBasic(data, k) && DGG_isInteger(data,k))) continue;
double frac = frac_part (data->x[k]);
if (frac < data->gomory_threshold || frac > 1-data->gomory_threshold) continue;
base->nz = 0;
rval = DGG_getTableauConstraint(k, solver_ptr, data, base,
colIsBasic,rowIsBasic,factorization,0);
DGG_CHECKRVAL(rval, rval);
if (base->nz == 0){
printf ("2mir_test: why does constraint not exist ?\n");
continue;
}
if (base->nz > 500) continue;
rval = DGG_generateCutsFromBase(base, cut_list, data, solver_ptr);
DGG_CHECKRVAL(rval, rval);
}
free(rowIsBasic);
free(colIsBasic);
if(talk) printf ("2mir_test: generated %d tab cuts\n", cut_list->n - nc); fflush (stdout);
DGG_freeConstraint(base);
return rval;
}
int DGG_generateFormulationCuts( DGG_list_t *cut_list,
DGG_data_t *data,
const void *solver_ptr,
int nrows,
CoinThreadRandom & generator)
{
int k, rval = 0;
DGG_constraint_t *base = NULL;
int num_rows = (data->nrow < nrows) ? data->nrow : nrows;
int nc = cut_list->n;
base = DGG_newConstraint(data->ncol + data->nrow);
if(talk) printf ("2mir_test: generating form row cuts %d\n", num_rows);
for(k=0; k<num_rows; k++) {
base->nz = 0;
rval = DGG_getFormulaConstraint(k, solver_ptr, data, base);
DGG_CHECKRVAL1(rval, rval);
//printf ("generating formulation for row %d\n", k);
rval = DGG_generateFormulationCutsFromBase(base, data->x[data->ncol+k],
cut_list, data, solver_ptr,
generator);
DGG_CHECKRVAL1(rval, rval);
if (base->nz == 0){
#ifdef COIN_DEVELOP
printf ("why does constraint not exist ?\n");
#endif
continue;
}
}
CLEANUP:
if(talk) printf ("2mir_test: generated %d form cuts\n", cut_list->n - nc); fflush (stdout);
DGG_freeConstraint(base);
return rval;
}
int DGG_generateFormulationCutsFromBase( DGG_constraint_t *base,
double slack,
DGG_list_t *cut_list,
DGG_data_t *data,
const void *solver_ptr,
CoinThreadRandom & generator)
{
int i, p, rval;
int int_skala;
double skala;
int num_inlist = 0;
int* skala_list = reinterpret_cast<int*> (malloc( sizeof(int)*base->nz ));
char *isint = NULL;
double *xout = NULL, *rcout = NULL;
DGG_constraint_t *scaled_base = NULL;
int tot_int = 0;
double prob_choose = 0.0;
rval = DGG_transformConstraint(data, &xout, &rcout, &isint, base);
DGG_CHECKRVAL1(rval, rval);
for(p = 0; p < base->nz; p++) if(isint[p]) tot_int ++;
if (tot_int == 0) goto CLEANUP;
prob_choose = 5.0/tot_int;
for(p = 0; p < base->nz; p++) {
if(isint[p]) if(generator.randomDouble() < prob_choose){
if(xout[p]<0.01) continue;
skala =fabs(base->coeff[p]);
if(skala<0.01) continue;
// check if slack is too large
if (fabs(slack/skala) > 0.5) continue;
scaled_base = DGG_copyConstraint(base);
DGG_CHECKRVAL1((scaled_base == NULL),-1);
if(base->sense == 'L') {
skala = -skala;
scaled_base->sense = 'G';
}
int_skala = int(100*skala);
for(i = 0; i< num_inlist; i++)
if(int_skala == skala_list[i])
goto END_LOOP;
skala_list[num_inlist++] = int_skala;
scaled_base->rhs = base->rhs/skala;
for(i = 0; i<base->nz; i++)
scaled_base->coeff[i] = base->coeff[i] / skala;
rval = DGG_unTransformConstraint(data, scaled_base);
DGG_CHECKRVAL1(rval, rval);
rval = DGG_generateCutsFromBase(scaled_base, cut_list,
data, solver_ptr);
DGG_CHECKRVAL1(rval, rval);
END_LOOP:
DGG_freeConstraint(scaled_base);
scaled_base = NULL;
}
}
CLEANUP:
if (isint) free(isint);
if (xout) free(xout);
if (rcout) free(rcout);
if (skala_list) free(skala_list);
if (scaled_base != NULL) DGG_freeConstraint (scaled_base);
return rval;
}
int
DGG_generateCutsFromBase( DGG_constraint_t *orig_base,
DGG_list_t *cut_list,
DGG_data_t *data,
const void *solver_ptr )
{
int rval = 0;
int t;
double *x = NULL, *rc = NULL;
char *isint = NULL;
DGG_constraint_t *base = NULL;
bool not_nicefied = true;
int new_pos = cut_list->n;
// DGG_constraint_t *keep_origbase = DGG_copyConstraint(orig_base); //for debug only ------
if (orig_base->sense == 'L') return 0;
if (orig_base->nz == 0) return 0;
rval = DGG_transformConstraint(data, &x, &rc, &isint, orig_base);
double frac = frac_part(orig_base->rhs);
//printf ("frac = %.7f, r %.7f, fr %.7f\n", frac, orig_base->rhs, floor(orig_base->rhs));
if (rval || frac < data->gomory_threshold || frac > 1-data->gomory_threshold){
free (x); free (rc); free (isint);
return 0;
}
int min_t = t_min;
int min_q = q_min;
if (orig_base->sense == 'G' && min_t < 1) min_t = 1;
if (orig_base->sense == 'G' && min_q < 1) min_q = 1;
if (min_q > 0 && min_t > 0 ) {
not_nicefied = false;
rval = DGG_nicefyConstraint(solver_ptr, data, orig_base);
DGG_CHECKRVAL(rval, rval);
if (orig_base->nz == 0){
if(talk) printf ("2mir_test: Nicefy returns empty constraint\n"); rval = 0; goto CLEANUP;
}
}
for(t = min_t; t <= t_max ; t++){
if (t == 0) continue;
base = DGG_copyConstraint(orig_base);
DGG_TEST(!base, 1, "error making copy of base");
DGG_scaleConstraint (base, t);
if(not_nicefied){
rval = DGG_nicefyConstraint(solver_ptr, data, base);
DGG_CHECKRVAL(rval, rval);
if (base->nz == 0){
if(talk) printf ("2mir_test: Nicefy returns empty constraint\n"); goto MIR_DONE;
}
}
if ( DGG_isBaseTrivial(data, base) ) goto MIR_DONE;
rval = DGG_addMirToList(base, isint, x, cut_list, data, orig_base);
DGG_CHECKRVAL(rval, rval);
MIR_DONE:
DGG_freeConstraint(base);
}
for( t = min_q; t <= q_max; t++ ){
if (t == 0) continue;
base = DGG_copyConstraint(orig_base);
DGG_TEST(!base, 1, "error making copy of base");
DGG_scaleConstraint (base, t);
if(not_nicefied){
rval = DGG_nicefyConstraint(solver_ptr, data, base);
DGG_CHECKRVAL(rval, rval);
if (base->nz == 0){
if(talk) printf ("2mir_test: Nicefy returns empty constraint\n"); goto TWOMIR_DONE;
}
}
if ( DGG_isBaseTrivial(data, base) ) goto TWOMIR_DONE;
rval = DGG_add2stepToList(base, isint, x, rc, cut_list, data, orig_base);
DGG_CHECKRVAL(rval, rval);
TWOMIR_DONE:
DGG_freeConstraint(base);
}
int i;
for ( i = cut_list->n-1; i>=new_pos; i--){
DGG_constraint_t *lcut = cut_list->c[i];
rval = DGG_unTransformConstraint(data, lcut);
DGG_CHECKRVAL(rval, rval);
rval = DGG_substituteSlacks(solver_ptr, data, lcut);
DGG_CHECKRVAL(rval, rval);
if ( !DGG_isCutDesirable(lcut, data) ){
DGG_list_delcut (cut_list, i);
continue;
}
//else testus(lcut);//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*
if ( data->opt_x && DGG_cutsOffPoint(data->opt_x, lcut) ){
//DGG_cutDisplay_sparse(data, data->opt_x, lcut, stdout);
DGG_TEST(1,1, "new cut is infeasible for optimal solution\n");
}
*/
}
CLEANUP:
if (x) free(x);
if (rc) free (rc);
if (isint) free(isint);
return 0;
}
int
DGG_addMirToList ( DGG_constraint_t *base, char *isint, double * /*x*/,
DGG_list_t *list, DGG_data_t * /*data*/,
DGG_constraint_t * /*orig_base*/ )
{
int rval = 0;
DGG_constraint_t *cut = NULL;
rval = DGG_buildMir(isint, base, &cut);
DGG_CHECKRVAL(rval, rval);
DGG_list_addcut(list, cut, DGG_TMIR_CUT, 0.0);
return 0;
}
int
DGG_add2stepToList ( DGG_constraint_t *base, char *isint, double * /*x*/,
double *rc, DGG_list_t *list, DGG_data_t *data,
DGG_constraint_t * /*orig_base*/ )
{
int rval;
DGG_constraint_t *cut = NULL;
int i;
double norm_val, best_norm_val, best_norm_alpha=-1.0;
double rc_val, best_rc_val, best_rc_alpha=-1.0;
double vht, bht, alpha;
best_rc_val = best_norm_val = COIN_DBL_MAX;
bht = ABOV(base->rhs);
double best_rc = 0;
for(i=0; i<base->nz; i++) if (isint[i]) best_rc = CoinMax(best_rc, fabs(rc[i]));
double rc_cutoff = best_rc / 10;
for(i=0; i<base->nz; i++){
if (!isint[i]) continue;
if (fabs(rc[i]) <= rc_cutoff) continue; //too unimportant
vht = ABOV(base->coeff[i]);
if(vht >= bht) continue; // too big
if(vht < bht/a_max) continue; // too small
alpha = vht;
int kk = 1;
while ( !DGG_is2stepValid(alpha, bht) && bht/alpha <= a_max) {
alpha = vht/kk;
kk++;
if (kk>1000)
break;
}
if ( !DGG_is2stepValid(alpha, bht) ) continue;
rval = DGG_build2step(alpha, isint, base, &cut);
DGG_CHECKRVAL(rval, rval);
rc_val = COIN_DBL_MAX; // this gives a lower bound on obj. fn. improvement
for(i=0; i<cut->nz; i++) if(cut->coeff[i]> 1E-6){
rc_val = CoinMin(rc_val, fabs(rc[i])/cut->coeff[i]);
}
rc_val *= cut->rhs;
norm_val = 0; // this is the square of the L2 norm
for(i=0; i<cut->nz; i++) if(cut->coeff[i]> 1E-6){
norm_val += (cut->coeff[i]*cut->coeff[i]);
}
norm_val /= cut->rhs * cut->rhs;
if (rc_val < best_rc_val ) {
best_rc_val = rc_val; best_rc_alpha = alpha; }
if (norm_val < best_norm_val ) {
best_norm_val = norm_val; best_norm_alpha = alpha; }
DGG_freeConstraint(cut);
}
if( best_rc_val> 1E-6 && best_rc_alpha != -1.0){
rval = DGG_build2step(best_rc_alpha, isint, base, &cut);
DGG_CHECKRVAL(rval, rval);
DGG_list_addcut(list, cut, DGG_2STEP_CUT, best_rc_alpha);
}
else if (best_norm_alpha != -1.0){
rval = DGG_build2step(best_norm_alpha, isint, base, &cut);
DGG_CHECKRVAL(rval, rval);
DGG_list_addcut(list, cut, DGG_2STEP_CUT, best_norm_alpha);
}
return 0;
}
int DGG_buildMir( char *isint,
DGG_constraint_t *base,
DGG_constraint_t **cut_out )
{
int i, lnz = 0;
double b = (base->rhs);
double bht = ABOV(b);
double bup = ceil(b);
DGG_constraint_t *tmir = NULL;
DGG_TEST( base->sense == 'L', 1, "this form not valid for L");
DGG_TEST( base->nz == 0, 1, "base must have some coefficients\n");
tmir = DGG_newConstraint( base->nz );
tmir->sense = 'G';
tmir->rhs = bht * bup;
for(i=0; i<base->nz; i++){
double v = base->coeff[i];
if (!isint[i]) {
if (v > 0.0) tmir->coeff[lnz] = v;
else tmir->coeff[lnz] = 0.0;
}
else {
double vht = ABOV(v);
DGG_IF_EXIT( vht<0, 1, "negative vht");
tmir->coeff[lnz] = bht * floor(v) + DGG_MIN(bht,vht);
}
tmir->index[lnz] = base->index[i];
lnz += 1;
}
tmir->nz = lnz;
*cut_out = tmir;
return 0;
}
int DGG_build2step( double alpha,
char *isint,
DGG_constraint_t *base,
DGG_constraint_t **cut_out )
{
DGG_constraint_t *tmir = 0;
int i, lnz = 0;
double vht, bht, bup, rho, tau, k;
double b = (base->rhs);
DGG_TEST( base->sense == 'L', 1, "this form not valid for L");
DGG_TEST( base->nz == 0, 1, "base must have some coefficients\n");
bht = ABOV(b);
bup = ceil(b);
tau = ceil(bht/alpha);
rho = bht - alpha*floor(bht/alpha);
/* ensure bht > alpha > 0 */
DGG_TEST3( (bht <= alpha) || (alpha <= 0.0), 1, "bad alpha (%f) / bht (%f) pair", alpha, bht);
/* ensure that we are not in a limiting case */
DGG_TEST( DGG_is_a_multiple_of_b(alpha, bht), 1, "can't generate simple 2mir in limiting case");
/* ensure that rho is not zero */
DGG_TEST2( rho < DGG_MIN_RHO, 1, "rho (%f) too small", rho);
/* initialize constraint */
tmir = DGG_newConstraint( base->nz );
tmir->rhs = bup*tau*rho;
tmir->sense = 'G';
/* compute cut coefficients */
for(i=0; i<base->nz; i++){
double v = base->coeff[i];
if (!isint[i]) {
if (v > 0.0) tmir->coeff[lnz] = v;
else tmir->coeff[lnz] = 0.0;
}
else {
vht = v - floor(v);
DGG_IF_EXIT( vht < 0.0, 1, "negative vht");
k = DGG_MIN(tau-1,floor(vht/alpha));
tmir->coeff[lnz] = floor(v)*tau*rho + k*rho + DGG_MIN(rho,vht-k*alpha);
}
tmir->index[lnz] = base->index[i];
lnz += 1;
}
tmir->nz = lnz;
*cut_out = tmir;
return 0;
}
/******************* TEST / DEBUGGING ROUTINES ********************************/
/* DGG_is2stepValid:
checks that:
bht > alpha > 0
(1/alpha) >= tau > (bht/alpha)
*/
int DGG_is2stepValid(double alpha, double bht)
{
/* d */
double tau;
/* ensure that alpha is not null or negative */
if ( alpha < DGG_MIN_ALPHA )
return 0;
/* compute tau and tau_lim */
tau = ceil( bht / alpha );
/* make sure alpha is not a divisor of bht */
if ( DGG_is_a_multiple_of_b(alpha, bht) )
return 0;
/* page 15, definition 12 */
/* check if alpha is admissible for simple-2-step-tmir */
if ( (bht > alpha) && (alpha > 0.0) )
if ( (1/alpha) >= tau )
return 1;
/* not admissible */
return 0;
}
/* checks that its worth doing a 1MIR on the constraint. More precisely,
- Is the RHS null?
- Are there any integer variables set at fractional values? */
int DGG_isBaseTrivial(DGG_data_t *d, DGG_constraint_t* c)
{
/* is rhs sufficiently fractional */
if ( frac_part(ABOV(c->rhs)) < d->gomory_threshold )
return 1;
if ( (1.0 - frac_part(ABOV(c->rhs))) < d->gomory_threshold )
return 1;
return 0;
}
/* tests lhs vs rhs of a constraint */
int DGG_isConstraintViolated(DGG_data_t *d, DGG_constraint_t *c)
{
double lhs = DGG_cutLHS(c, d->x);
double rhs = c->rhs;
/* compare LHS and RHS */
if (c->sense == 'G')
if ( lhs > (rhs - DGG_NULL_SLACK) )
return 0;
if (c->sense == 'L')
if ( lhs < (rhs + DGG_NULL_SLACK) )
return 0;
if (c->sense == 'E')
if ( fabs(lhs - rhs) < DGG_NULL_SLACK )
return 0;
return 0;
}
double DGG_cutLHS(DGG_constraint_t *c, double *x)
{
int i;
double lhs = 0.0;
for(i=0; i < c->nz; i++)
lhs += c->coeff[i]*x[c->index[i]];
return lhs;
}
int DGG_isCutDesirable(DGG_constraint_t *c, DGG_data_t *d)
{
double lhs, rhs;
lhs = DGG_cutLHS(c, d->x);
rhs = c->rhs;
if (c->nz > 500) return 0;
/* if the cut is not violated, return 0 */
if (c->sense == 'G')
if ( lhs > (rhs - DGG_NULL_SLACK) )
return 0;
if (c->sense == 'L')
if ( lhs < (rhs + DGG_NULL_SLACK) )
return 0;
if (c->sense == 'E')
if ( fabs(lhs - rhs) < DGG_NULL_SLACK )
return 0;
return 1;
}
/******************** SIMPLE MACROS AND FUNCTIONS *****************************/
int DGG_is_even(double vht, double bht, int tau, int q)
{
double v2 = V2I(bht, tau, q);
if ( vht > v2 )
return 1;
return 0;
}
double frac_part(double value)
{
return value-floor(value);
}
int DGG_is_a_multiple_of_b(double a, double b)
{
double c = b/a;
if ( (b - a*floor(c)) < DGG_MIN_RHO )
return 1;
return 0;
}
int DGG_cutsOffPoint(double *x, DGG_constraint_t *cut)
{
int i;
double LHS = 0.0;
for(i=0; i < cut->nz; i++)
LHS += cut->coeff[i]*(x[ cut->index[i] ]);
//fprintf(stdout, "LHS = %f, SENSE = %c, RHS = %f\n", LHS, cut->sense, cut->rhs);
if ( cut->sense == 'E' )
if ( fabs(LHS - cut->rhs) > DGG_NULL_SLACK )
goto BAD;
if (cut->sense == 'G' )
if ( (cut->rhs - LHS) > DGG_NULL_SLACK )
goto BAD;
if (cut->sense == 'L' )
if ( (LHS - cut->rhs) > DGG_NULL_SLACK )
goto BAD;
return 0;
BAD:
fprintf(stdout, "LHS = %f, SENSE = %c, RHS = %f\n", LHS, cut->sense, cut->rhs);
DGG_TEST(1, 1, "found a bad cut!");
return 0;
}
// Returns true if needs optimal basis to do cuts
bool
CglTwomir::needsOptimalBasis() const
{
return true;
}
// Away stuff
void CglTwomir::setAway(double value)
{
if (value>0.0&&value<=0.5)
away_=value;
}
double CglTwomir::getAway() const
{
return away_;
}
// Away stuff at root
void CglTwomir::setAwayAtRoot(double value)
{
if (value>0.0&&value<=0.5)
awayAtRoot_=value;
}
double CglTwomir::getAwayAtRoot() const
{
return awayAtRoot_;
}
// This can be used to refresh any information
void
CglTwomir::refreshSolver(OsiSolverInterface * solver)
{
if (originalSolver_) {
delete originalSolver_;
originalSolver_ = solver->clone();
}
}
// Create C++ lines to get to current state
std::string
CglTwomir::generateCpp( FILE * fp)
{
CglTwomir other;
fprintf(fp,"0#include \"CglTwomir.hpp\"\n");
fprintf(fp,"3 CglTwomir twomir;\n");
if (t_min_!=other.t_min_||t_max_!=other.t_max_)
fprintf(fp,"3 twomir.setMirScale(%d,%d);\n",t_min_,t_max_);
else
fprintf(fp,"4 twomir.setMirScale(%d,%d);\n",t_min_,t_max_);
if (q_min_!=other.q_min_||q_max_!=other.q_max_)
fprintf(fp,"3 twomir.setTwomirScale(%d,%d);\n",q_min_,q_max_);
else
fprintf(fp,"4 twomir.setTwomirScale(%d,%d);\n",q_min_,q_max_);
if (do_mir_!=other.do_mir_||do_2mir_!=other.do_2mir_||
do_tab_!=other.do_tab_||do_form_!=other.do_form_)
fprintf(fp,"3 twomir.setCutTypes(%s,%s,%s,%s);\n",
do_mir_ ? "true" : "false",
do_2mir_ ? "true" : "false",
do_tab_ ? "true" : "false",
do_form_ ? "true" : "false");
else
fprintf(fp,"4 twomir.setCutTypes(%s,%s,%s,%s);\n",
do_mir_ ? "true" : "false",
do_2mir_ ? "true" : "false",
do_tab_ ? "true" : "false",
do_form_ ? "true" : "false");
if (a_max_!=other.a_max_)
fprintf(fp,"3 twomir.setAMax(%d);\n",a_max_);
else
fprintf(fp,"4 twomir.setAMax(%d);\n",a_max_);
if (max_elements_!=other.max_elements_)
fprintf(fp,"3 twomir.setMaxElements(%d);\n",max_elements_);
else
fprintf(fp,"4 twomir.setMaxElements(%d);\n",max_elements_);
if (max_elements_root_!=other.max_elements_root_)
fprintf(fp,"3 twomir.setMaxElementsRoot(%d);\n",max_elements_root_);
else
fprintf(fp,"4 twomir.setMaxElementsRoot(%d);\n",max_elements_root_);
if (getAggressiveness()!=other.getAggressiveness())
fprintf(fp,"3 twomir.setAggressiveness(%d);\n",getAggressiveness());
else
fprintf(fp,"4 twomir.setAggressiveness(%d);\n",getAggressiveness());
return "twomir";
}
| 28.881671 | 105 | 0.607471 | amosr |
33ef5d49ba2446e65f25fead5f1cc3e93da72c15 | 5,989 | cc | C++ | plugins/experimental/rate_limit/txn_limiter.cc | rob05c/trafficserver | b2004604e00bc7216856ea5e79082b4e53118a76 | [
"Apache-2.0"
] | null | null | null | plugins/experimental/rate_limit/txn_limiter.cc | rob05c/trafficserver | b2004604e00bc7216856ea5e79082b4e53118a76 | [
"Apache-2.0"
] | null | null | null | plugins/experimental/rate_limit/txn_limiter.cc | rob05c/trafficserver | b2004604e00bc7216856ea5e79082b4e53118a76 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unistd.h>
#include <getopt.h>
#include <cstdlib>
#include "txn_limiter.h"
///////////////////////////////////////////////////////////////////////////////
// These continuations are "helpers" to the TXN limiter object. Putting them
// outside the class implementation is just cleaner.
//
static int
txn_limit_cont(TSCont cont, TSEvent event, void *edata)
{
TxnRateLimiter *limiter = static_cast<TxnRateLimiter *>(TSContDataGet(cont));
switch (event) {
case TS_EVENT_HTTP_TXN_CLOSE:
limiter->release();
TSContDestroy(cont); // We are done with this continuation now
TSHttpTxnReenable(static_cast<TSHttpTxn>(edata), TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_CONTINUE;
break;
case TS_EVENT_HTTP_POST_REMAP:
limiter->push(static_cast<TSHttpTxn>(edata), cont);
return TS_EVENT_NONE;
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR: // This is only applicable when we set an error in remap
retryAfter(static_cast<TSHttpTxn>(edata), limiter->retry);
TSContDestroy(cont); // We are done with this continuation now
TSHttpTxnReenable(static_cast<TSHttpTxn>(edata), TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_CONTINUE;
break;
default:
TSDebug(PLUGIN_NAME, "Unknown event %d", static_cast<int>(event));
TSError("Unknown event in %s", PLUGIN_NAME);
break;
}
return TS_EVENT_NONE;
}
static int
txn_queue_cont(TSCont cont, TSEvent event, void *edata)
{
TxnRateLimiter *limiter = static_cast<TxnRateLimiter *>(TSContDataGet(cont));
QueueTime now = std::chrono::system_clock::now(); // Only do this once per "loop"
// Try to enable some queued txns (if any) if there are slots available
while (limiter->size() > 0 && limiter->reserve()) {
auto [txnp, contp, start_time] = limiter->pop();
std::chrono::milliseconds delay = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
delayHeader(txnp, limiter->header, delay);
TSDebug(PLUGIN_NAME, "Enabling queued txn after %ldms", static_cast<long>(delay.count()));
// Since this was a delayed transaction, we need to add the TXN_CLOSE hook to free the slot when done
TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, contp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
}
// Kill any queued txns if they are too old
if (limiter->size() > 0 && limiter->max_age > std::chrono::milliseconds::zero()) {
now = std::chrono::system_clock::now(); // Update the "now", for some extra accuracy
while (limiter->size() > 0 && limiter->hasOldEntity(now)) {
// The oldest object on the queue is too old on the queue, so "kill" it.
auto [txnp, contp, start_time] = limiter->pop();
std::chrono::milliseconds age = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
delayHeader(txnp, limiter->header, age);
TSDebug(PLUGIN_NAME, "Queued TXN is too old (%ldms), erroring out", static_cast<long>(age.count()));
TSHttpTxnStatusSet(txnp, static_cast<TSHttpStatus>(limiter->error));
TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, contp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);
}
}
return TS_EVENT_NONE;
}
///////////////////////////////////////////////////////////////////////////////
// Parse the configurations for the TXN limiter.
//
bool
TxnRateLimiter::initialize(int argc, const char *argv[])
{
static const struct option longopt[] = {
{const_cast<char *>("limit"), required_argument, nullptr, 'l'},
{const_cast<char *>("queue"), required_argument, nullptr, 'q'},
{const_cast<char *>("error"), required_argument, nullptr, 'e'},
{const_cast<char *>("retry"), required_argument, nullptr, 'r'},
{const_cast<char *>("header"), required_argument, nullptr, 'h'},
{const_cast<char *>("maxage"), required_argument, nullptr, 'm'},
// EOF
{nullptr, no_argument, nullptr, '\0'},
};
while (true) {
int opt = getopt_long(argc, (char *const *)argv, "", longopt, nullptr);
switch (opt) {
case 'l':
this->limit = strtol(optarg, nullptr, 10);
break;
case 'q':
this->max_queue = strtol(optarg, nullptr, 10);
break;
case 'e':
this->error = strtol(optarg, nullptr, 10);
break;
case 'r':
this->retry = strtol(optarg, nullptr, 10);
break;
case 'm':
this->max_age = std::chrono::milliseconds(strtol(optarg, nullptr, 10));
break;
case 'h':
this->header = optarg;
break;
}
if (opt == -1) {
break;
}
}
if (this->max_queue > 0) {
_queue_cont = TSContCreate(txn_queue_cont, TSMutexCreate());
TSReleaseAssert(_queue_cont);
TSContDataSet(_queue_cont, this);
_action = TSContScheduleEveryOnPool(_queue_cont, QUEUE_DELAY_TIME.count(), TS_THREAD_POOL_TASK);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Sets up a transaction based continuation for this transaction.
//
void
TxnRateLimiter::setupTxnCont(TSHttpTxn txnp, TSHttpHookID hook)
{
TSCont cont = TSContCreate(txn_limit_cont, nullptr);
TSReleaseAssert(cont);
TSContDataSet(cont, this);
TSHttpTxnHookAdd(txnp, hook, cont);
}
| 36.078313 | 111 | 0.667223 | rob05c |
33f0d6a9434a5f4585b17d460d2d86cf3750fb83 | 70,564 | cpp | C++ | test/float/mm-lin.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | 1 | 2020-06-26T11:10:55.000Z | 2020-06-26T11:10:55.000Z | test/float/mm-lin.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | null | null | null | test/float/mm-lin.cpp | SaGagnon/gecode-5.5.0-cbs | e871b320a9b2031423bb0fa452b1a5c09641a041 | [
"MIT-feh"
] | 1 | 2020-06-26T11:10:57.000Z | 2020-06-26T11:10:57.000Z | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2008, 2012
*
* Last modified:
* $Date: 2016-04-19 17:19:45 +0200 (Tue, 19 Apr 2016) $ by $Author: schulte $
* $Revision: 14967 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "test/int.hh"
#include "test/float.hh"
#include <gecode/minimodel.hh>
namespace Test { namespace Float {
/// %Tests for minimal modeling constraints (linear)
namespace MiniModelLin {
/// Linear opcode
enum LinOpcode {
LO_ACE, ///< Add float and expression
LO_AEC, ///< Add expression and float
LO_AEE, ///< Add expressions
LO_SCE, ///< Subtract float and expression
LO_SEC, ///< Subtract expression and float
LO_SEE, ///< Subtract expressions
LO_SE, ///< Unary subtraction
LO_MCE, ///< Multiply constant and expression
LO_MEC, ///< Multiply constant and expression
LO_HLT ///< Stop execution
};
/// Type for representing a linear instruction
class LinInstr {
public:
LinOpcode o; ///< Which instruction to execute
unsigned char x, y, z; ///< Instruction arguments, \a y is destination (or \a z)
int c; ///< Numerical constant
};
/// Evaluate linear instructions
template<class Expr>
Expr
eval(const LinInstr* pc, Expr reg[]) {
while (true) {
switch (pc->o) {
case LO_ACE: reg[pc->y] = pc->c + reg[pc->x]; break;
case LO_AEC: reg[pc->y] = reg[pc->x] + pc->c; break;
case LO_AEE: reg[pc->z] = reg[pc->x] + reg[pc->y]; break;
case LO_SCE: reg[pc->y] = pc->c - reg[pc->x]; break;
case LO_SEC: reg[pc->y] = reg[pc->x] - pc->c; break;
case LO_SEE: reg[pc->z] = reg[pc->x] - reg[pc->y]; break;
case LO_SE: reg[pc->y] = -reg[pc->x]; break;
case LO_MCE: reg[pc->y] = pc->c * reg[pc->x]; break;
case LO_MEC: reg[pc->y] = reg[pc->x] * pc->c; break;
case LO_HLT: return reg[pc->x];
default: GECODE_NEVER;
}
pc++;
}
GECODE_NEVER;
}
/**
* \defgroup TaskTestFloatMiniModelLin Minimal modeling constraints (linear constraints)
* \ingroup TaskTestFloat
*/
//@{
/// %Test linear expressions over float variables
class LinExpr : public Int::Test {
protected:
/// Linear instruction sequence
const LinInstr* lis;
public:
/// Create and register test
LinExpr(const LinInstr* lis0, const std::string& s)
: Test("Float::","MiniModel::LinExpr::"+s,4,-3,3),
lis(lis0) {
testfix = false;
}
/// %Test whether \a x is solution
virtual bool solution(const Int::Assignment& x) const {
int reg[3] = {x[0],x[1],x[2]};
return eval(lis, reg) == x[3];
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
FloatVarArray y(home,4,dom.min(),dom.max());
channel(home, x[0], y[0]);
channel(home, x[1], y[1]);
channel(home, x[2], y[2]);
channel(home, x[3], y[3]);
LinFloatExpr reg[3] = {y[0],y[1],y[2]};
rel(home, y[3], FRT_EQ, expr(home, eval(lis,reg)));
}
};
/// %Test linear relations over float variables
class LinRel : public Int::Test {
protected:
/// Linear instruction sequence for left hand side
const LinInstr* l_lis;
/// Linear instruction sequence for right hand side
const LinInstr* r_lis;
/// Float relation type to propagate
Gecode::FloatRelType frt;
public:
/// Create and register test
LinRel(const LinInstr* l_lis0, const LinInstr* r_lis0,
Gecode::FloatRelType frt0, const std::string& s)
: Test("Float::","MiniModel::LinRel::"+s+"::"+
Float::Test::str(frt0),3,-3,3),
l_lis(l_lis0), r_lis(r_lis0), frt(frt0) {
testfix = false;
}
/// %Test whether \a x is solution
virtual bool solution(const Int::Assignment& x) const {
using namespace Gecode;
int l_reg[3] = {x[0],x[1],x[2]};
int l = eval(l_lis,l_reg);
int r_reg[3] = {x[0],x[1],x[2]};
int r = eval(r_lis,r_reg);
switch (frt) {
case FRT_EQ: return l == r;
case FRT_NQ: return l != r;
case FRT_LE: return l < r;
case FRT_GR: return l > r;
case FRT_LQ: return l <= r;
case FRT_GQ: return l >= r;
default: GECODE_NEVER;
}
return false;
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
FloatVarArray y(home,3,dom.min(),dom.max());
channel(home, x[0], y[0]);
channel(home, x[1], y[1]);
channel(home, x[2], y[2]);
LinFloatExpr l_reg[3] = {y[0],y[1],y[2]};
LinFloatExpr r_reg[3] = {y[0],y[1],y[2]};
switch (frt) {
case FRT_EQ:
Gecode::rel(home, eval(l_lis,l_reg) == eval(r_lis,r_reg));
break;
case FRT_NQ:
Gecode::rel(home, eval(l_lis,l_reg) != eval(r_lis,r_reg));
break;
case FRT_LQ:
Gecode::rel(home, eval(l_lis,l_reg) <= eval(r_lis,r_reg));
break;
case FRT_LE:
Gecode::rel(home, eval(l_lis,l_reg) < eval(r_lis,r_reg));
break;
case FRT_GQ:
Gecode::rel(home, eval(l_lis,l_reg) >= eval(r_lis,r_reg));
break;
case FRT_GR:
Gecode::rel(home, eval(l_lis,l_reg) > eval(r_lis,r_reg));
break;
default: GECODE_NEVER;
}
}
};
const LinInstr li000[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li001[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li002[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li003[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li004[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li005[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li006[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li007[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li008[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li009[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li010[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li011[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li012[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li013[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li014[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li015[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li016[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li017[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li018[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li019[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li020[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li021[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li022[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li023[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li024[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li025[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li026[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li027[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li028[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li029[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li030[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li031[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li032[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li033[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li034[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li035[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li036[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li037[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li038[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li039[] = {
{LO_AEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li040[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li041[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li042[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li043[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li044[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li045[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li046[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li047[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li048[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li049[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li050[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li051[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li052[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li053[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li054[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li055[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li056[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li057[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li058[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li059[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li060[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li061[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li062[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li063[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li064[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li065[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li066[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li067[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li068[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li069[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li070[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li071[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li072[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li073[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li074[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li075[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li076[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li077[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li078[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li079[] = {
{LO_AEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li080[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li081[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li082[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li083[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li084[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li085[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li086[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li087[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li088[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li089[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li090[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li091[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li092[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li093[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li094[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li095[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li096[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li097[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li098[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li099[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li100[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li101[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li102[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li103[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li104[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li105[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li106[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li107[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li108[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li109[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li110[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li111[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li112[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li113[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li114[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li115[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li116[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li117[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li118[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li119[] = {
{LO_AEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li120[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li121[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li122[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li123[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li124[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li125[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li126[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li127[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li128[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li129[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li130[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li131[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li132[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li133[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li134[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li135[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li136[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li137[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li138[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li139[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li140[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li141[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li142[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li143[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li144[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li145[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li146[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li147[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li148[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li149[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li150[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li151[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li152[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li153[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li154[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li155[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li156[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li157[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li158[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li159[] = {
{LO_AEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li160[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li161[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li162[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li163[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li164[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li165[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li166[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li167[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li168[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li169[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li170[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li171[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li172[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li173[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li174[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li175[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li176[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li177[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li178[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li179[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li180[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li181[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li182[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li183[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li184[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li185[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li186[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li187[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li188[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li189[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li190[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li191[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li192[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li193[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li194[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li195[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li196[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li197[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li198[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li199[] = {
{LO_AEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li200[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li201[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li202[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li203[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li204[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li205[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li206[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li207[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li208[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li209[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li210[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li211[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li212[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li213[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li214[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li215[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li216[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li217[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li218[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li219[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li220[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li221[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li222[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li223[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li224[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li225[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li226[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li227[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li228[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li229[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li230[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li231[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li232[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li233[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li234[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li235[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li236[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li237[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li238[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li239[] = {
{LO_SEE,0,1,0, 0},{LO_AEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li240[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li241[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li242[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li243[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li244[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li245[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li246[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li247[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li248[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li249[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li250[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li251[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li252[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li253[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li254[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li255[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li256[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li257[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li258[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li259[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li260[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li261[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li262[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li263[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li264[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li265[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li266[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li267[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li268[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li269[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li270[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li271[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li272[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li273[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li274[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li275[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li276[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li277[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li278[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li279[] = {
{LO_SEE,0,1,0, 0},{LO_SCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li280[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li281[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li282[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li283[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li284[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li285[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li286[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li287[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li288[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li289[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li290[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li291[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li292[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li293[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li294[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li295[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li296[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li297[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li298[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li299[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li300[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li301[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li302[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li303[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li304[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li305[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li306[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li307[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li308[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li309[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li310[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li311[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li312[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li313[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li314[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li315[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li316[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li317[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li318[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li319[] = {
{LO_SEE,0,1,0, 0},{LO_SEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li320[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li321[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li322[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li323[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li324[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li325[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li326[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li327[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li328[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li329[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li330[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li331[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li332[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li333[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li334[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li335[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li336[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li337[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li338[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li339[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li340[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li341[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li342[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li343[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li344[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li345[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li346[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li347[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li348[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li349[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li350[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li351[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li352[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li353[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li354[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li355[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li356[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li357[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li358[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li359[] = {
{LO_SEE,0,1,0, 0},{LO_MCE,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li360[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li361[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li362[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li363[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li364[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li365[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li366[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li367[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li368[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li369[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li370[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li371[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li372[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li373[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li374[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li375[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0,-1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li376[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li377[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li378[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li379[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li380[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li381[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li382[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li383[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 0},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li384[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li385[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li386[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li387[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li388[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li389[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li390[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li391[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 1},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li392[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li393[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li394[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li395[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_AEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li396[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0,-1},{LO_HLT,0,0,0, 0}
};
const LinInstr li397[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_ACE,0,0,0, 1},{LO_HLT,0,0,0, 0}
};
const LinInstr li398[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr li399[] = {
{LO_SEE,0,1,0, 0},{LO_MEC,0,0,0, 2},{LO_SEE,0,2,0, 0},
{LO_SE ,0,0,0, 0},{LO_HLT,0,0,0, 0}
};
const LinInstr* li[] = {
&li000[0],&li001[0],&li002[0],&li003[0],&li004[0],&li005[0],
&li006[0],&li007[0],&li008[0],&li009[0],&li010[0],&li011[0],
&li012[0],&li013[0],&li014[0],&li015[0],&li016[0],&li017[0],
&li018[0],&li019[0],&li020[0],&li021[0],&li022[0],&li023[0],
&li024[0],&li025[0],&li026[0],&li027[0],&li028[0],&li029[0],
&li030[0],&li031[0],&li032[0],&li033[0],&li034[0],&li035[0],
&li036[0],&li037[0],&li038[0],&li039[0],&li040[0],&li041[0],
&li042[0],&li043[0],&li044[0],&li045[0],&li046[0],&li047[0],
&li048[0],&li049[0],&li050[0],&li051[0],&li052[0],&li053[0],
&li054[0],&li055[0],&li056[0],&li057[0],&li058[0],&li059[0],
&li060[0],&li061[0],&li062[0],&li063[0],&li064[0],&li065[0],
&li066[0],&li067[0],&li068[0],&li069[0],&li070[0],&li071[0],
&li072[0],&li073[0],&li074[0],&li075[0],&li076[0],&li077[0],
&li078[0],&li079[0],&li080[0],&li081[0],&li082[0],&li083[0],
&li084[0],&li085[0],&li086[0],&li087[0],&li088[0],&li089[0],
&li090[0],&li091[0],&li092[0],&li093[0],&li094[0],&li095[0],
&li096[0],&li097[0],&li098[0],&li099[0],&li100[0],&li101[0],
&li102[0],&li103[0],&li104[0],&li105[0],&li106[0],&li107[0],
&li108[0],&li109[0],&li110[0],&li111[0],&li112[0],&li113[0],
&li114[0],&li115[0],&li116[0],&li117[0],&li118[0],&li119[0],
&li120[0],&li121[0],&li122[0],&li123[0],&li124[0],&li125[0],
&li126[0],&li127[0],&li128[0],&li129[0],&li130[0],&li131[0],
&li132[0],&li133[0],&li134[0],&li135[0],&li136[0],&li137[0],
&li138[0],&li139[0],&li140[0],&li141[0],&li142[0],&li143[0],
&li144[0],&li145[0],&li146[0],&li147[0],&li148[0],&li149[0],
&li150[0],&li151[0],&li152[0],&li153[0],&li154[0],&li155[0],
&li156[0],&li157[0],&li158[0],&li159[0],&li160[0],&li161[0],
&li162[0],&li163[0],&li164[0],&li165[0],&li166[0],&li167[0],
&li168[0],&li169[0],&li170[0],&li171[0],&li172[0],&li173[0],
&li174[0],&li175[0],&li176[0],&li177[0],&li178[0],&li179[0],
&li180[0],&li181[0],&li182[0],&li183[0],&li184[0],&li185[0],
&li186[0],&li187[0],&li188[0],&li189[0],&li190[0],&li191[0],
&li192[0],&li193[0],&li194[0],&li195[0],&li196[0],&li197[0],
&li198[0],&li199[0],&li200[0],&li201[0],&li202[0],&li203[0],
&li204[0],&li205[0],&li206[0],&li207[0],&li208[0],&li209[0],
&li210[0],&li211[0],&li212[0],&li213[0],&li214[0],&li215[0],
&li216[0],&li217[0],&li218[0],&li219[0],&li220[0],&li221[0],
&li222[0],&li223[0],&li224[0],&li225[0],&li226[0],&li227[0],
&li228[0],&li229[0],&li230[0],&li231[0],&li232[0],&li233[0],
&li234[0],&li235[0],&li236[0],&li237[0],&li238[0],&li239[0],
&li240[0],&li241[0],&li242[0],&li243[0],&li244[0],&li245[0],
&li246[0],&li247[0],&li248[0],&li249[0],&li250[0],&li251[0],
&li252[0],&li253[0],&li254[0],&li255[0],&li256[0],&li257[0],
&li258[0],&li259[0],&li260[0],&li261[0],&li262[0],&li263[0],
&li264[0],&li265[0],&li266[0],&li267[0],&li268[0],&li269[0],
&li270[0],&li271[0],&li272[0],&li273[0],&li274[0],&li275[0],
&li276[0],&li277[0],&li278[0],&li279[0],&li280[0],&li281[0],
&li282[0],&li283[0],&li284[0],&li285[0],&li286[0],&li287[0],
&li288[0],&li289[0],&li290[0],&li291[0],&li292[0],&li293[0],
&li294[0],&li295[0],&li296[0],&li297[0],&li298[0],&li299[0],
&li300[0],&li301[0],&li302[0],&li303[0],&li304[0],&li305[0],
&li306[0],&li307[0],&li308[0],&li309[0],&li310[0],&li311[0],
&li312[0],&li313[0],&li314[0],&li315[0],&li316[0],&li317[0],
&li318[0],&li319[0],&li320[0],&li321[0],&li322[0],&li323[0],
&li324[0],&li325[0],&li326[0],&li327[0],&li328[0],&li329[0],
&li330[0],&li331[0],&li332[0],&li333[0],&li334[0],&li335[0],
&li336[0],&li337[0],&li338[0],&li339[0],&li340[0],&li341[0],
&li342[0],&li343[0],&li344[0],&li345[0],&li346[0],&li347[0],
&li348[0],&li349[0],&li350[0],&li351[0],&li352[0],&li353[0],
&li354[0],&li355[0],&li356[0],&li357[0],&li358[0],&li359[0],
&li360[0],&li361[0],&li362[0],&li363[0],&li364[0],&li365[0],
&li366[0],&li367[0],&li368[0],&li369[0],&li370[0],&li371[0],
&li372[0],&li373[0],&li374[0],&li375[0],&li376[0],&li377[0],
&li378[0],&li379[0],&li380[0],&li381[0],&li382[0],&li383[0],
&li384[0],&li385[0],&li386[0],&li387[0],&li388[0],&li389[0],
&li390[0],&li391[0],&li392[0],&li393[0],&li394[0],&li395[0],
&li396[0],&li397[0],&li398[0],&li399[0],
};
/// Help class to create and register tests
class Create {
public:
/// Perform creation and registration
Create(void) {
int n = sizeof(li)/sizeof(LinInstr*);
for (int i=0; i<n; i++) {
std::string s = Test::str(i);
if (i < 10) {
s = "00" + s;
} else if (i < 100) {
s = "0" + s;
}
(void) new LinExpr(li[i],s);
}
FloatRelTypes frts;
for (int i=0; i<n/2; i++) {
std::string s = Test::str(i);
if (i < 10) {
s = "00" + s;
} else if (i < 100) {
s = "0" + s;
}
(void) new LinRel(li[2*i],li[2*i+1],frts.frt(),s);
++frts;
if (!frts())
frts.reset();
}
}
};
Create c;
//@}
}
}}
// STATISTICS: test-minimodel
| 37.022036 | 93 | 0.47931 | SaGagnon |
33f1d1866090d7b523881c4a92cd5f1820dbc088 | 6,635 | cpp | C++ | src/images/image.cpp | AKholetsky/blah | fb21ec869d476e525d728e61f2ba689ee02322e5 | [
"MIT"
] | null | null | null | src/images/image.cpp | AKholetsky/blah | fb21ec869d476e525d728e61f2ba689ee02322e5 | [
"MIT"
] | null | null | null | src/images/image.cpp | AKholetsky/blah | fb21ec869d476e525d728e61f2ba689ee02322e5 | [
"MIT"
] | null | null | null | #include <blah/images/image.h>
#include <blah/streams/stream.h>
#include <blah/streams/filestream.h>
#include <blah/core/log.h>
using namespace Blah;
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_JPEG
#define STBI_ONLY_PNG
#define STBI_ONLY_BMP
#include "../third_party/stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../third_party/stb_image_write.h"
namespace
{
int Blah_STBI_Read(void* user, char* data, int size)
{
int64_t read = ((Stream*)user)->read(data, size);
return (int)read;
}
void Blah_STBI_Skip(void* user, int n)
{
((Stream*)user)->seek(((Stream*)user)->position() + n);
}
int Blah_STBI_Eof(void* user)
{
int64_t position = ((Stream*)user)->position();
int64_t length = ((Stream*)user)->length();
if (position >= length)
return 1;
return 0;
}
void Blah_STBI_Write(void* context, void* data, int size)
{
((Stream*)context)->write((char*)data, size);
}
}
Image::Image()
{
width = height = 0;
pixels = nullptr;
m_stbi_ownership = false;
}
Image::Image(Stream& stream)
{
width = height = 0;
pixels = nullptr;
m_stbi_ownership = false;
from_stream(stream);
}
Image::Image(const char* file)
{
width = height = 0;
pixels = nullptr;
m_stbi_ownership = false;
FileStream fs(file, FileMode::Read);
if (fs.is_readable())
from_stream(fs);
}
Image::Image(int w, int h)
{
BLAH_ASSERT(w >= 0 && h >= 0, "Image width and height must be larger than 0");
width = w;
height = h;
pixels = new Color[width * height];
m_stbi_ownership = false;
memset(pixels, 0, (size_t)width * (size_t)height * sizeof(Color));
}
Image::Image(const Image& src)
{
width = src.width;
height = src.height;
m_stbi_ownership = src.m_stbi_ownership;
pixels = nullptr;
if (src.pixels != nullptr && width > 0 && height > 0)
{
pixels = new Color[width * height];
memcpy(pixels, src.pixels, sizeof(Color) * width * height);
}
}
Image& Image::operator=(const Image& src)
{
width = src.width;
height = src.height;
m_stbi_ownership = src.m_stbi_ownership;
pixels = nullptr;
if (src.pixels != nullptr && width > 0 && height > 0)
{
pixels = new Color[width * height];
memcpy(pixels, src.pixels, sizeof(Color) * width * height);
}
return *this;
}
Image::Image(Image&& src) noexcept
{
width = src.width;
height = src.height;
pixels = src.pixels;
m_stbi_ownership = src.m_stbi_ownership;
src.width = src.height = 0;
src.pixels = nullptr;
src.m_stbi_ownership = false;
}
Image& Image::operator=(Image&& src) noexcept
{
width = src.width;
height = src.height;
pixels = src.pixels;
m_stbi_ownership = src.m_stbi_ownership;
src.width = src.height = 0;
src.pixels = nullptr;
src.m_stbi_ownership = false;
return *this;
}
Image::~Image()
{
dispose();
}
void Image::from_stream(Stream& stream)
{
dispose();
if (!stream.is_readable())
{
BLAH_ERROR("Unable to load image as the Stream was not readable");
return;
}
stbi_io_callbacks callbacks;
callbacks.eof = Blah_STBI_Eof;
callbacks.read = Blah_STBI_Read;
callbacks.skip = Blah_STBI_Skip;
int x, y, comps;
uint8_t* data = stbi_load_from_callbacks(&callbacks, &stream, &x, &y, &comps, 4);
if (data == nullptr)
{
BLAH_ERROR("Unable to load image as the Stream's data was not a valid image");
return;
}
m_stbi_ownership = true;
pixels = (Color*)data;
width = x;
height = y;
}
void Image::dispose()
{
if (m_stbi_ownership)
stbi_image_free(pixels);
else
delete[] pixels;
pixels = nullptr;
width = height = 0;
m_stbi_ownership = false;
}
void Image::premultiply()
{
if (pixels != nullptr)
{
for (int n = 0; n < width * height; n ++)
{
pixels[n].r = (uint8_t)(pixels[n].r * pixels[n].a / 255);
pixels[n].g = (uint8_t)(pixels[n].g * pixels[n].a / 255);
pixels[n].b = (uint8_t)(pixels[n].b * pixels[n].a / 255);
}
}
}
void Image::set_pixels(const RectI& rect, Color* data)
{
for (int y = 0; y < rect.h; y++)
{
int to = rect.x + ((rect.y + y) * width);
int from = (y * rect.w);
memcpy(pixels + to, data + from, sizeof(Color) * rect.w);
}
}
bool Image::save_png(const char* file) const
{
FileStream fs(file, FileMode::Write);
return save_png(fs);
}
bool Image::save_png(Stream& stream) const
{
BLAH_ASSERT(pixels != nullptr, "Image Pixel data cannot be null");
BLAH_ASSERT(width > 0 && height > 0, "Image Width and Height must be larger than 0");
if (stream.is_writable())
{
stbi_write_force_png_filter = 0;
stbi_write_png_compression_level = 0;
if (stbi_write_png_to_func(Blah_STBI_Write, &stream, width, height, 4, pixels, width * 4) != 0)
return true;
else
Log::error("stbi_write_png_to_func failed");
}
else
{
Log::error("Cannot save Image, the Stream is not writable");
}
return false;
}
bool Image::save_jpg(const char* file, int quality) const
{
FileStream fs(file, FileMode::Write);
return save_jpg(fs, quality);
}
bool Image::save_jpg(Stream& stream, int quality) const
{
BLAH_ASSERT(pixels != nullptr, "Image Pixel data cannot be null");
BLAH_ASSERT(width > 0 && height > 0, "Image Width and Height must be larger than 0");
if (quality < 1)
{
Log::warn("jpg quality value should be between 1 and 100; input was %i", quality);
quality = 1;
}
else if (quality > 100)
{
Log::warn("jpg quality value should be between 1 and 100; input was %i", quality);
quality = 100;
}
if (stream.is_writable())
{
if (stbi_write_jpg_to_func(Blah_STBI_Write, &stream, width, height, 4, pixels, quality) != 0)
return true;
else
Log::error("stbi_write_jpg_to_func failed");
}
else
{
Log::error("Cannot save Image, the Stream is not writable");
}
return false;
}
void Image::get_pixels(Color* dest, const Point& destPos, const Point& destSize, RectI sourceRect)
{
// can't be outside of the source image
if (sourceRect.x < 0) sourceRect.x = 0;
if (sourceRect.y < 0) sourceRect.y = 0;
if (sourceRect.x + sourceRect.w > width) sourceRect.w = width - sourceRect.x;
if (sourceRect.y + sourceRect.h > height) sourceRect.h = height - sourceRect.y;
// can't be larger than our destination
if (sourceRect.w > destSize.x - destPos.x)
sourceRect.w = destSize.x - destPos.x;
if (sourceRect.h > destSize.y - destPos.y)
sourceRect.h = destSize.y - destPos.y;
for (int y = 0; y < sourceRect.h; y++)
{
int to = destPos.x + (destPos.y + y) * destSize.x;
int from = sourceRect.x + (sourceRect.y + y) * width;
memcpy(dest + to, pixels + from, sizeof(Color) * (int)sourceRect.w);
}
}
Image Image::get_sub_image(const RectI& sourceRect)
{
Image img(sourceRect.w, sourceRect.h);
get_pixels(img.pixels, Point::zero, Point(img.width, img.height), sourceRect);
return img;
}
| 21.970199 | 98 | 0.674755 | AKholetsky |
33f216c181bf52fddc6e7c38d14e1a66455a1665 | 8,705 | cpp | C++ | ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | /*
*
* TezosLikeTransactionDatabaseHelper
*
* Created by El Khalil Bellakrid on 27/04/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <tezos/database/TezosLikeTransactionDatabaseHelper.hpp>
#include <tezos/api/enum_from_string.hpp>
#include <tezos/api/TezosOperationTag.hpp>
#include <core/crypto/SHA256.hpp>
#include <core/database/SociOption.hpp>
#include <core/database/SociDate.hpp>
#include <core/database/SociNumber.hpp>
#include <core/utils/Option.hpp>
#include <core/wallet/BlockDatabaseHelper.hpp>
using namespace soci;
namespace ledger {
namespace core {
bool TezosLikeTransactionDatabaseHelper::getTransactionByHash(
soci::session &sql,
const std::string &hash,
const std::string &operationUid,
TezosLikeBlockchainExplorerTransaction &tx
) {
rowset<row> rows = (sql.prepare << "SELECT tx.hash, tx.value, tx.time, "
" tx.sender, tx.receiver, tx.fees, tx.gas_limit, tx.storage_limit, tx.confirmations, tx.type, tx.public_key, tx.originated_account, tx.status, "
"block.height, block.hash, block.time, block.currency_name "
"FROM tezos_transactions AS tx "
"LEFT JOIN blocks AS block ON tx.block_uid = block.uid "
"LEFT JOIN tezos_operations AS xtz_ops ON xtz_ops.transaction_uid = tx.transaction_uid "
"WHERE tx.hash = :hash AND xtz_ops.uid = :uid", use(hash), use(operationUid));
for (auto &row : rows) {
inflateTransaction(sql, row, tx);
return true;
}
return false;
}
bool TezosLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql,
const soci::row &row,
TezosLikeBlockchainExplorerTransaction &tx) {
tx.hash = row.get<std::string>(0);
tx.value = BigInt::fromHex(row.get<std::string>(1));
tx.receivedAt = row.get<std::chrono::system_clock::time_point>(2);
tx.sender = row.get<std::string>(3);
tx.receiver = row.get<std::string>(4);
tx.fees = BigInt::fromHex(row.get<std::string>(5));
tx.gas_limit = BigInt::fromHex(row.get<std::string>(6));
tx.storage_limit = BigInt::fromHex(row.get<std::string>(7));
tx.confirmations = get_number<uint64_t>(row, 8);
tx.type = api::from_string<api::TezosOperationTag>(row.get<std::string>(9));
auto pubKey = row.get<std::string>(10);
if (!pubKey.empty()) {
tx.publicKey = pubKey;
}
auto values = strings::split(row.get<std::string>(11), ":");
if (values.size() == 3) {
tx.originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(values[0], static_cast<bool>(std::stoi(values[1])), static_cast<bool>(std::stoi(values[2])));
}
tx.status = get_number<uint64_t>(row, 12);
if (row.get_indicator(13) != i_null) {
TezosLikeBlockchainExplorer::Block block;
block.height = get_number<uint64_t>(row, 13);
block.blockHash = row.get<std::string>(14);
block.time = row.get<std::chrono::system_clock::time_point>(15);
block.currencyName = row.get<std::string>(16);
tx.block = block;
}
return true;
}
bool TezosLikeTransactionDatabaseHelper::transactionExists(soci::session &sql,
const std::string &tezosTxUid) {
int32_t count = 0;
sql << "SELECT COUNT(*) FROM tezos_transactions WHERE transaction_uid = :tezosTxUid", use(tezosTxUid), into(
count);
return count == 1;
}
std::string TezosLikeTransactionDatabaseHelper::createTezosTransactionUid(const std::string &accountUid,
const std::string &txHash,
api::TezosOperationTag type) {
auto result = SHA256::stringToHexHash(fmt::format("uid:{}+{}+{}", accountUid, txHash, api::to_string(type)));
return result;
}
std::string TezosLikeTransactionDatabaseHelper::putTransaction(soci::session &sql,
const std::string &accountUid,
const TezosLikeBlockchainExplorerTransaction &tx) {
auto blockUid = tx.block.map<std::string>([](const TezosLikeBlockchainExplorer::Block &block) {
return BlockDatabaseHelper::createBlockUid(block.blockHash, block.currencyName);
});
auto tezosTxUid = createTezosTransactionUid(accountUid, tx.hash, tx.type);
if (transactionExists(sql, tezosTxUid)) {
// UPDATE (we only update block information)
if (tx.block.nonEmpty()) {
auto type = api::to_string(tx.type);
use(blockUid), use(tx.status), use(tx.hash);
sql << "UPDATE tezos_transactions SET block_uid = :uid, status = :code WHERE hash = :tx_hash AND type = :type",
use(blockUid), use(tx.status), use(tx.hash), use(type);
}
return tezosTxUid;
} else {
// Insert
if (tx.block.nonEmpty()) {
BlockDatabaseHelper::putBlock(sql, tx.block.getValue());
}
auto hexValue = tx.value.toHexString();
auto hexFees = tx.fees.toHexString();
auto hexGasLimit = tx.gas_limit.toHexString();
auto hexStorageLimit = tx.storage_limit.toHexString();
auto type = api::to_string(tx.type);
auto pubKey = tx.publicKey.getValueOr("");
std::string sOrigAccount;
if (tx.originatedAccount.hasValue()) {
std::stringstream origAccount;
std::vector<std::string> vOrigAccount{tx.originatedAccount.getValue().address, std::to_string(tx.originatedAccount.getValue().spendable), std::to_string(tx.originatedAccount.getValue().delegatable)};
strings::join(vOrigAccount, origAccount, ":");
sOrigAccount = origAccount.str();
}
sql << "INSERT INTO tezos_transactions VALUES(:tx_uid, :hash, :value, :block_uid, :time, :sender, :receiver, :fees, :gas_limit, :storage_limit, :confirmations, :type, :public_key, :originated_account, :status)",
use(tezosTxUid),
use(tx.hash),
use(hexValue),
use(blockUid),
use(tx.receivedAt),
use(tx.sender),
use(tx.receiver),
use(hexFees),
use(hexGasLimit),
use(hexStorageLimit),
use(tx.confirmations),
use(type),
use(pubKey),
use(sOrigAccount),
use(tx.status);
return tezosTxUid;
}
}
}
}
| 48.904494 | 227 | 0.559563 | phaazon |
33f318206761e0974f2143add8de7c12bcdc3a36 | 457 | hpp | C++ | core/Light.hpp | jmppmj/3dgameengine_jillplatts | 64f472322423aa4d2c8be5366f36d78dde9f568b | [
"MIT"
] | null | null | null | core/Light.hpp | jmppmj/3dgameengine_jillplatts | 64f472322423aa4d2c8be5366f36d78dde9f568b | [
"MIT"
] | null | null | null | core/Light.hpp | jmppmj/3dgameengine_jillplatts | 64f472322423aa4d2c8be5366f36d78dde9f568b | [
"MIT"
] | null | null | null | #pragma once
#include "ModelData.hpp"
class Light
{
private:
glm::vec3 pos = glm::vec3(0, 0, 0);
glm::vec3 color = glm::vec3(1, 1, 1);
bool isPointLight = true;
public:
Light(glm::vec3 pos, glm::vec3 color, bool isPointLight);
void Light::setPos(glm::vec3 pos2);
bool Light::getIsPointLight();
void Light::setIsPointLight(bool isPointLight);
void Light::setColor(glm::vec3 color);
glm::vec4 Light::getColor();
glm::vec4 Light::getPos();
}; | 18.28 | 58 | 0.68709 | jmppmj |
33f3319ba7dee8950a9dd95f73ffc956570be68b | 612 | cc | C++ | kattis/alicedigital.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | kattis/alicedigital.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | kattis/alicedigital.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://open.kattis.com/problems/alicedigital
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vi;
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vi a(n + 1, 0);
int p = 0;
int q = 0;
int M = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
if (a[i] < m) {
if (q) M = max(M, a[i - 1] - a[p]);
p = i;
q = 0;
} else if (a[i] == m) {
if (!q) q = i;
else {
M = max(M, a[i - 1] - a[p]);
p = q;
q = i;
}
}
a[i] += a[i - 1];
}
if (q) M = max(M, a[n] - a[p]);
cout << M << endl;
}
}
| 15.692308 | 48 | 0.406863 | Ashindustry007 |
33f56b32135cbdb9f7fec298a823d6a3209ba514 | 106,894 | cpp | C++ | thorlcr/graph/thgraph.cpp | roscoche/HPCC-Platform | 9975e6c5a0996d25ac3c24e3b57dd1389a87f06b | [
"Apache-2.0"
] | null | null | null | thorlcr/graph/thgraph.cpp | roscoche/HPCC-Platform | 9975e6c5a0996d25ac3c24e3b57dd1389a87f06b | [
"Apache-2.0"
] | null | null | null | thorlcr/graph/thgraph.cpp | roscoche/HPCC-Platform | 9975e6c5a0996d25ac3c24e3b57dd1389a87f06b | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
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 "thgraph.hpp"
#include "jptree.hpp"
#include "commonext.hpp"
#include "dasess.hpp"
#include "jhtree.hpp"
#include "thcodectx.hpp"
#include "thbuf.hpp"
#include "thormisc.hpp"
#include "thbufdef.hpp"
#include "thmem.hpp"
#include "rtlformat.hpp"
PointerArray createFuncs;
void registerCreateFunc(CreateFunc func)
{
createFuncs.append((void *)func);
}
///////////////////////////////////
//////
/////
class CThorGraphResult : implements IThorResult, implements IRowWriter, public CInterface
{
CActivityBase &activity;
rowcount_t rowStreamCount;
IOutputMetaData *meta;
Owned<IRowWriterMultiReader> rowBuffer;
IThorRowInterfaces *rowIf;
IEngineRowAllocator *allocator;
bool stopped, readers;
ThorGraphResultType resultType;
void init()
{
stopped = readers = false;
allocator = rowIf->queryRowAllocator();
meta = allocator->queryOutputMeta();
rowStreamCount = 0;
}
class CStreamWriter : implements IRowWriterMultiReader, public CSimpleInterface
{
CThorGraphResult &owner;
CThorExpandingRowArray rows;
public:
IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
CStreamWriter(CThorGraphResult &_owner, EmptyRowSemantics emptyRowSemantics) : owner(_owner), rows(owner.activity, owner.rowIf, emptyRowSemantics)
{
}
//IRowWriterMultiReader
virtual void putRow(const void *row)
{
rows.append(row);
}
virtual void flush() { }
virtual IRowStream *getReader()
{
return rows.createRowStream(0, (rowidx_t)-1, false);
}
};
public:
IMPLEMENT_IINTERFACE;
CThorGraphResult(CActivityBase &_activity, IThorRowInterfaces *_rowIf, ThorGraphResultType _resultType, unsigned spillPriority) : activity(_activity), rowIf(_rowIf), resultType(_resultType)
{
init();
EmptyRowSemantics emptyRowSemantics;
if (isGrouped())
emptyRowSemantics = ers_eogonly;
else if (isSparse())
emptyRowSemantics = ers_allow;
else
emptyRowSemantics = ers_forbidden;
if (SPILL_PRIORITY_DISABLE == spillPriority)
rowBuffer.setown(new CStreamWriter(*this, emptyRowSemantics));
else
rowBuffer.setown(createOverflowableBuffer(activity, rowIf, emptyRowSemantics, true));
}
// IRowWriter
virtual void putRow(const void *row)
{
assertex(!readers);
++rowStreamCount;
rowBuffer->putRow(row);
}
virtual void flush() { }
virtual offset_t getPosition() { UNIMPLEMENTED; return 0; }
// IThorResult
virtual IRowWriter *getWriter()
{
return LINK(this);
}
virtual void setResultStream(IRowWriterMultiReader *stream, rowcount_t count)
{
assertex(!readers);
rowBuffer.setown(stream);
rowStreamCount = count;
}
virtual IRowStream *getRowStream()
{
readers = true;
return rowBuffer->getReader();
}
virtual IThorRowInterfaces *queryRowInterfaces() { return rowIf; }
virtual CActivityBase *queryActivity() { return &activity; }
virtual bool isDistributed() const { return resultType & thorgraphresult_distributed; }
virtual bool isSparse() const { return resultType & thorgraphresult_sparse; }
virtual bool isGrouped() const { return resultType & thorgraphresult_grouped; }
virtual void serialize(MemoryBuffer &mb)
{
Owned<IRowStream> stream = getRowStream();
bool grouped = meta->isGrouped();
if (grouped)
{
OwnedConstThorRow prev = stream->nextRow();
if (prev)
{
bool eog;
for (;;)
{
eog = false;
OwnedConstThorRow next = stream->nextRow();
if (!next)
eog = true;
size32_t sz = meta->getRecordSize(prev);
mb.append(sz, prev.get());
mb.append(eog);
if (!next)
{
next.setown(stream->nextRow());
if (!next)
break;
}
prev.set(next);
}
}
}
else
{
for (;;)
{
OwnedConstThorRow row = stream->nextRow();
if (!row)
break;
size32_t sz = meta->getRecordSize(row);
mb.append(sz, row.get());
}
}
}
virtual void getResult(size32_t &len, void * & data)
{
MemoryBuffer mb;
serialize(mb);
len = mb.length();
data = mb.detach();
}
virtual void getLinkedResult(unsigned &countResult, const byte * * & result) override
{
assertex(rowStreamCount==((unsigned)rowStreamCount)); // catch, just in case
Owned<IRowStream> stream = getRowStream();
countResult = 0;
OwnedConstThorRow _rowset = allocator->createRowset((unsigned)rowStreamCount);
const void **rowset = (const void **)_rowset.get();
while (countResult < rowStreamCount)
{
OwnedConstThorRow row = stream->nextRow();
rowset[countResult++] = row.getClear();
}
result = (const byte **)_rowset.getClear();
}
virtual const void * getLinkedRowResult()
{
assertex(rowStreamCount==1); // catch, just in case
Owned<IRowStream> stream = getRowStream();
return stream->nextRow();
}
};
/////
IThorResult *CThorGraphResults::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
{
Owned<IThorResult> result = ::createResult(activity, rowIf, resultType, spillPriority);
setResult(id, result);
return result;
}
/////
IThorResult *createResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
{
return new CThorGraphResult(activity, rowIf, resultType, spillPriority);
}
/////
class CThorBoundLoopGraph : implements IThorBoundLoopGraph, public CInterface
{
CGraphBase *graph;
activity_id activityId;
Linked<IOutputMetaData> resultMeta;
Owned<IOutputMetaData> counterMeta, loopAgainMeta;
Owned<IThorRowInterfaces> resultRowIf, countRowIf, loopAgainRowIf;
public:
IMPLEMENT_IINTERFACE;
CThorBoundLoopGraph(CGraphBase *_graph, IOutputMetaData * _resultMeta, unsigned _activityId) : graph(_graph), resultMeta(_resultMeta), activityId(_activityId)
{
counterMeta.setown(createFixedSizeMetaData(sizeof(thor_loop_counter_t)));
loopAgainMeta.setown(createFixedSizeMetaData(sizeof(bool)));
}
virtual void prepareCounterResult(CActivityBase &activity, IThorGraphResults *results, unsigned loopCounter, unsigned pos)
{
if (!countRowIf)
countRowIf.setown(activity.createRowInterfaces(counterMeta));
RtlDynamicRowBuilder counterRow(countRowIf->queryRowAllocator());
thor_loop_counter_t * res = (thor_loop_counter_t *)counterRow.ensureCapacity(sizeof(thor_loop_counter_t),NULL);
*res = loopCounter;
OwnedConstThorRow counterRowFinal = counterRow.finalizeRowClear(sizeof(thor_loop_counter_t));
IThorResult *counterResult = results->createResult(activity, pos, countRowIf, thorgraphresult_nul, SPILL_PRIORITY_DISABLE);
Owned<IRowWriter> counterResultWriter = counterResult->getWriter();
counterResultWriter->putRow(counterRowFinal.getClear());
graph->setLoopCounter(loopCounter);
}
virtual void prepareLoopAgainResult(CActivityBase &activity, IThorGraphResults *results, unsigned pos)
{
if (!loopAgainRowIf)
loopAgainRowIf.setown(activity.createRowInterfaces(loopAgainMeta));
activity.queryGraph().createResult(activity, pos, results, loopAgainRowIf, activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed, SPILL_PRIORITY_DISABLE);
}
virtual void prepareLoopResults(CActivityBase &activity, IThorGraphResults *results)
{
if (!resultRowIf)
resultRowIf.setown(activity.createRowInterfaces(resultMeta));
ThorGraphResultType resultType = activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed;
IThorResult *loopResult = activity.queryGraph().createResult(activity, 0, results, resultRowIf, resultType); // loop output
IThorResult *inputResult = activity.queryGraph().createResult(activity, 1, results, resultRowIf, resultType); // loop input
}
virtual CGraphBase *queryGraph() { return graph; }
};
IThorBoundLoopGraph *createBoundLoopGraph(CGraphBase *graph, IOutputMetaData *resultMeta, unsigned activityId)
{
return new CThorBoundLoopGraph(graph, resultMeta, activityId);
}
///////////////////////////////////
bool isDiskInput(ThorActivityKind kind)
{
switch (kind)
{
case TAKcsvread:
case TAKxmlread:
case TAKjsonread:
case TAKdiskread:
case TAKdisknormalize:
case TAKdiskaggregate:
case TAKdiskcount:
case TAKdiskgroupaggregate:
case TAKindexread:
case TAKindexcount:
case TAKindexnormalize:
case TAKindexaggregate:
case TAKindexgroupaggregate:
case TAKindexgroupexists:
case TAKindexgroupcount:
case TAKspillread:
return true;
default:
return false;
}
}
void CIOConnection::connect(unsigned which, CActivityBase *destActivity)
{
destActivity->setInput(which, activity->queryActivity(), index);
}
///////////////////////////////////
CGraphElementBase *createGraphElement(IPropertyTree &node, CGraphBase &owner, CGraphBase *resultsGraph)
{
CGraphElementBase *container = NULL;
ForEachItemIn(m, createFuncs)
{
CreateFunc func = (CreateFunc)createFuncs.item(m);
container = func(node, owner, resultsGraph);
if (container) break;
}
if (NULL == container)
{
ThorActivityKind tak = (ThorActivityKind)node.getPropInt("att[@name=\"_kind\"]/@value", TAKnone);
throw MakeStringException(TE_UnsupportedActivityKind, "Unsupported activity kind: %s", activityKindStr(tak));
}
container->setResultsGraph(resultsGraph);
return container;
}
CGraphElementBase::CGraphElementBase(CGraphBase &_owner, IPropertyTree &_xgmml) : owner(&_owner)
{
xgmml.setown(createPTreeFromIPT(&_xgmml));
eclText.set(xgmml->queryProp("att[@name=\"ecl\"]/@value"));
id = xgmml->getPropInt("@id", 0);
kind = (ThorActivityKind)xgmml->getPropInt("att[@name=\"_kind\"]/@value", TAKnone);
sink = isActivitySink(kind);
bool coLocal = xgmml->getPropBool("att[@name=\"coLocal\"]/@value", false);
isLocalData = xgmml->getPropBool("att[@name=\"local\"]/@value", false); // local execute + local data access only
isLocal = isLocalData || coLocal; // local execute
isGrouped = xgmml->getPropBool("att[@name=\"grouped\"]/@value", false);
resultsGraph = NULL;
ownerId = xgmml->getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
onCreateCalled = prepared = haveCreateCtx = nullAct = false;
onlyUpdateIfChanged = xgmml->getPropBool("att[@name=\"_updateIfChanged\"]/@value", false);
StringBuffer helperName("fAc");
xgmml->getProp("@id", helperName);
helperFactory = (EclHelperFactory) queryJob().queryDllEntry().getEntry(helperName.str());
if (!helperFactory)
throw makeOsExceptionV(GetLastError(), "Failed to load helper factory method: %s (dll handle = %p)", helperName.str(), queryJob().queryDllEntry().getInstance());
alreadyUpdated = false;
whichBranch = (unsigned)-1;
log = true;
sentActInitData.setown(createThreadSafeBitSet());
maxCores = queryXGMML().getPropInt("hint[@name=\"max_cores\"]/@value", 0);
if (0 == maxCores)
maxCores = queryJob().queryMaxDefaultActivityCores();
baseHelper.setown(helperFactory());
}
CGraphElementBase::~CGraphElementBase()
{
activity.clear();
baseHelper.clear(); // clear before dll is unloaded
}
CJobBase &CGraphElementBase::queryJob() const
{
return owner->queryJob();
}
CJobChannel &CGraphElementBase::queryJobChannel() const
{
return owner->queryJobChannel();
}
IGraphTempHandler *CGraphElementBase::queryTempHandler() const
{
if (resultsGraph)
return resultsGraph->queryTempHandler();
else
return queryJob().queryTempHandler();
}
void CGraphElementBase::releaseIOs()
{
loopGraph.clear();
if (activity)
activity->releaseIOs();
connectedInputs.kill();
inputs.kill();
outputs.kill();
activity.clear();
}
void CGraphElementBase::addDependsOn(CGraphBase *graph, int controlId)
{
ForEachItemIn(i, dependsOn)
{
if (dependsOn.item(i).graph == graph)
return;
}
dependsOn.append(*new CGraphDependency(graph, controlId));
}
StringBuffer &CGraphElementBase::getOpt(const char *prop, StringBuffer &out) const
{
VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
if (!queryXGMML().getProp(path.toLowerCase().str(), out))
queryJob().getOpt(prop, out);
return out;
}
bool CGraphElementBase::getOptBool(const char *prop, bool defVal) const
{
bool def = queryJob().getOptBool(prop, defVal);
VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
return queryXGMML().getPropBool(path.toLowerCase().str(), def);
}
int CGraphElementBase::getOptInt(const char *prop, int defVal) const
{
int def = queryJob().getOptInt(prop, defVal);
VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
return queryXGMML().getPropInt(path.toLowerCase().str(), def);
}
__int64 CGraphElementBase::getOptInt64(const char *prop, __int64 defVal) const
{
__int64 def = queryJob().getOptInt64(prop, defVal);
VStringBuffer path("hint[@name=\"%s\"]/@value", prop);
return queryXGMML().getPropInt64(path.toLowerCase().str(), def);
}
IThorGraphDependencyIterator *CGraphElementBase::getDependsIterator() const
{
return new ArrayIIteratorOf<const CGraphDependencyArray, CGraphDependency, IThorGraphDependencyIterator>(dependsOn);
}
void CGraphElementBase::reset()
{
alreadyUpdated = false;
if (activity)
activity->reset();
}
void CGraphElementBase::ActPrintLog(const char *format, ...)
{
va_list args;
va_start(args, format);
::ActPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args);
va_end(args);
}
void CGraphElementBase::ActPrintLog(IException *e, const char *format, ...)
{
va_list args;
va_start(args, format);
::ActPrintLogArgs(this, e, thorlog_all, MCexception(e), format, args);
va_end(args);
}
void CGraphElementBase::ActPrintLog(IException *e)
{
ActPrintLog(e, "%s", "");
}
void CGraphElementBase::abort(IException *e)
{
CActivityBase *activity = queryActivity();
if (activity)
activity->abort();
}
void CGraphElementBase::doconnect()
{
ForEachItemIn(i, connectedInputs)
{
CIOConnection *io = connectedInputs.item(i);
if (io)
io->connect(i, queryActivity());
}
}
void CGraphElementBase::clearConnections()
{
connectedInputs.kill();
connectedOutputs.kill();
if (activity)
activity->clearConnections();
}
void CGraphElementBase::addInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx)
{
while (inputs.ordinality()<=input) inputs.append(NULL);
inputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input);
while (inputAct->outputs.ordinality()<=inputOutIdx) inputAct->outputs.append(NULL);
inputAct->outputs.replace(new CIOConnection(this, input), inputOutIdx);
}
void CGraphElementBase::connectInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx)
{
ActPrintLog("CONNECTING (id=%" ACTPF "d, idx=%d) to (id=%" ACTPF "d, idx=%d)", inputAct->queryId(), inputOutIdx, queryId(), input);
while (connectedInputs.ordinality()<=input) connectedInputs.append(NULL);
connectedInputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input);
while (inputAct->connectedOutputs.ordinality()<=inputOutIdx) inputAct->connectedOutputs.append(NULL);
inputAct->connectedOutputs.replace(new CIOConnection(this, input), inputOutIdx);
}
void CGraphElementBase::serializeCreateContext(MemoryBuffer &mb)
{
if (!onCreateCalled) return;
DelayedSizeMarker sizeMark(mb);
queryHelper()->serializeCreateContext(mb);
sizeMark.write();
if (isSink())
mb.append(alreadyUpdated);
}
void CGraphElementBase::deserializeCreateContext(MemoryBuffer &mb)
{
size32_t createCtxLen;
mb.read(createCtxLen);
createCtxMb.clear().append(createCtxLen, mb.readDirect(createCtxLen));
haveCreateCtx = true;
if (isSink())
mb.read(alreadyUpdated);
}
void CGraphElementBase::serializeStartContext(MemoryBuffer &mb)
{
DelayedSizeMarker sizeMark(mb);
queryHelper()->serializeStartContext(mb);
sizeMark.write();
}
void CGraphElementBase::onCreate()
{
CriticalBlock b(crit);
if (onCreateCalled)
return;
onCreateCalled = true;
if (!nullAct)
{
CGraphElementBase *ownerActivity = owner->queryOwner() ? owner->queryOwner()->queryElement(ownerId) : NULL;
if (ownerActivity)
{
ownerActivity->onCreate(); // ensure owner created, might not be if this is child query inside another child query.
baseHelper->onCreate(queryCodeContext(), ownerActivity->queryHelper(), haveCreateCtx?&createCtxMb:NULL);
}
else
baseHelper->onCreate(queryCodeContext(), NULL, haveCreateCtx?&createCtxMb:NULL);
if (isLoopActivity(*this))
{
unsigned loopId = queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value");
Owned<CGraphStub> stub = owner->getChildGraph(loopId);
Owned<IThorBoundLoopGraph> boundLoopGraph = createBoundLoopGraph(&stub->queryOriginalGraph(), baseHelper->queryOutputMeta(), queryId());
setBoundGraph(boundLoopGraph);
}
}
}
void CGraphElementBase::onStart(size32_t parentExtractSz, const byte *parentExtract, MemoryBuffer *startCtx)
{
if (nullAct)
return;
CriticalBlock b(crit);
baseHelper->onStart(parentExtract, startCtx);
}
bool CGraphElementBase::executeDependencies(size32_t parentExtractSz, const byte *parentExtract, int controlId, bool async)
{
Owned<IThorGraphDependencyIterator> deps = getDependsIterator();
ForEach(*deps)
{
CGraphDependency &dep = deps->query();
if (dep.controlId == controlId)
dep.graph->execute(parentExtractSz, parentExtract, true, async);
if (owner->queryJob().queryAborted() || owner->queryAborted()) return false;
}
return true;
}
bool CGraphElementBase::prepareContext(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async, bool connectOnly)
{
try
{
bool create = true;
if (connectOnly)
{
if (prepared)
return true;
ForEachItemIn(i, inputs)
{
if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true))
return false;
}
}
else
{
bool _shortCircuit = shortCircuit;
Owned<IThorGraphDependencyIterator> deps = getDependsIterator();
bool depsDone = true;
ForEach(*deps)
{
CGraphDependency &dep = deps->query();
if (0 == dep.controlId && NotFound == owner->dependentSubGraphs.find(*dep.graph))
{
owner->dependentSubGraphs.append(*dep.graph);
if (!dep.graph->isComplete())
depsDone = false;
}
}
if (depsDone) _shortCircuit = false;
if (!depsDone && checkDependencies)
{
if (!executeDependencies(parentExtractSz, parentExtract, 0, async))
return false;
}
whichBranch = (unsigned)-1;
switch (getKind())
{
case TAKindexwrite:
case TAKdiskwrite:
case TAKcsvwrite:
case TAKxmlwrite:
case TAKjsonwrite:
case TAKspillwrite:
if (_shortCircuit) return true;
onCreate();
alreadyUpdated = checkUpdate();
if (alreadyUpdated)
return false;
break;
case TAKchildif:
case TAKif:
case TAKifaction:
{
if (_shortCircuit) return true;
onCreate();
onStart(parentExtractSz, parentExtract);
IHThorIfArg *helper = (IHThorIfArg *)baseHelper.get();
whichBranch = helper->getCondition() ? 0 : 1; // True argument precedes false...
/* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default
* It should be removed, once we are positive there are no issues with in-line conditional actions
*/
if (TAKifaction == getKind())
{
if (!executeDependencies(parentExtractSz, parentExtract, whichBranch+1, async)) //NB whenId 1 based
return false;
create = false;
}
break;
}
case TAKchildcase:
case TAKcase:
{
if (_shortCircuit) return true;
onCreate();
onStart(parentExtractSz, parentExtract);
IHThorCaseArg *helper = (IHThorCaseArg *)baseHelper.get();
whichBranch = helper->getBranch();
if (whichBranch >= inputs.ordinality())
whichBranch = inputs.ordinality()-1;
break;
}
case TAKfilter:
case TAKfiltergroup:
case TAKfilterproject:
{
if (_shortCircuit) return true;
onCreate();
onStart(parentExtractSz, parentExtract);
switch (getKind())
{
case TAKfilter:
whichBranch = ((IHThorFilterArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
break;
case TAKfiltergroup:
whichBranch = ((IHThorFilterGroupArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
break;
case TAKfilterproject:
whichBranch = ((IHThorFilterProjectArg *)baseHelper.get())->canMatchAny() ? 0 : 1;
break;
}
break;
}
case TAKsequential:
case TAKparallel:
{
/* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default
* It should be removed, once we are positive there are no issues with in-line sequential/parallel activities
*/
for (unsigned s=1; s<=dependsOn.ordinality(); s++)
executeDependencies(parentExtractSz, parentExtract, s, async);
create = false;
break;
}
case TAKwhen_dataset:
case TAKwhen_action:
{
if (!executeDependencies(parentExtractSz, parentExtract, WhenBeforeId, async))
return false;
if (!executeDependencies(parentExtractSz, parentExtract, WhenParallelId, async))
return false;
break;
}
}
if (checkDependencies && ((unsigned)-1 != whichBranch))
{
if (inputs.queryItem(whichBranch))
{
if (!queryInput(whichBranch)->prepareContext(parentExtractSz, parentExtract, true, false, async, connectOnly))
return false;
}
ForEachItemIn(i, inputs)
{
if (i != whichBranch)
{
if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true))
return false;
}
}
}
else
{
ForEachItemIn(i, inputs)
{
if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, checkDependencies, false, async, connectOnly))
return false;
}
}
}
if (create)
{
if (prepared) // no need to recreate
return true;
prepared = true;
ForEachItemIn(i2, inputs)
{
CIOConnection *inputIO = inputs.item(i2);
connectInput(i2, inputIO->activity, inputIO->index);
}
createActivity();
}
return true;
}
catch (IException *_e)
{
IThorException *e = QUERYINTERFACE(_e, IThorException);
if (e)
{
if (!e->queryActivityId())
setExceptionActivityInfo(*this, e);
}
else
{
e = MakeActivityException(this, _e);
_e->Release();
}
throw e;
}
}
void CGraphElementBase::preStart(size32_t parentExtractSz, const byte *parentExtract)
{
activity->preStart(parentExtractSz, parentExtract);
}
void CGraphElementBase::createActivity()
{
CriticalBlock b(crit);
if (activity)
return;
activity.setown(factory());
if (isSink())
owner->addActiveSink(*this);
}
ICodeContext *CGraphElementBase::queryCodeContext()
{
return queryOwner().queryCodeContext();
}
/////
// JCSMORE loop - probably need better way to check if any act in graph is global(meaning needs some synchronization between slaves in activity execution)
bool isGlobalActivity(CGraphElementBase &container)
{
switch (container.getKind())
{
// always global, but only co-ordinate init/done
case TAKcsvwrite:
case TAKxmlwrite:
case TAKjsonwrite:
case TAKindexwrite:
case TAKkeydiff:
case TAKkeypatch:
case TAKdictionaryworkunitwrite:
return true;
case TAKdiskwrite:
{
Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *)container.helperFactory();
unsigned flags = helper->getFlags();
return (0 == (TDXtemporary & flags)); // global if not temporary
}
case TAKspillwrite:
case TAKspill:
return false;
case TAKcsvread:
{
Owned<IHThorCsvReadArg> helper = (IHThorCsvReadArg *)container.helperFactory();
// if header lines, then [may] need to co-ordinate across slaves
if (container.queryOwner().queryOwner() && (!container.queryOwner().isGlobal())) // I am in a child query
return false;
return helper->queryCsvParameters()->queryHeaderLen() > 0;
}
// dependent on child acts?
case TAKlooprow:
case TAKloopcount:
case TAKgraphloop:
case TAKparallelgraphloop:
case TAKloopdataset:
case TAKexternalsink:
case TAKexternalsource:
case TAKexternalprocess:
return false;
// dependent on local/grouped
case TAKkeyeddistribute:
case TAKhashdistribute:
case TAKhashdistributemerge:
case TAKnwaydistribute:
case TAKworkunitwrite:
case TAKdistribution:
case TAKpartition:
case TAKdiskaggregate:
case TAKdiskcount:
case TAKdiskgroupaggregate:
case TAKindexaggregate:
case TAKindexcount:
case TAKindexgroupaggregate:
case TAKindexgroupexists:
case TAKindexgroupcount:
case TAKremoteresult:
case TAKcountproject:
case TAKcreaterowlimit:
case TAKskiplimit:
case TAKlimit:
case TAKsort:
case TAKdedup:
case TAKjoin:
case TAKselfjoin:
case TAKhashjoin:
case TAKsmartjoin:
case TAKkeyeddenormalize:
case TAKhashdenormalize:
case TAKdenormalize:
case TAKlookupdenormalize: //GH->JCS why are these here, and join not?
case TAKalldenormalize:
case TAKsmartdenormalize:
case TAKdenormalizegroup:
case TAKhashdenormalizegroup:
case TAKlookupdenormalizegroup:
case TAKkeyeddenormalizegroup:
case TAKalldenormalizegroup:
case TAKsmartdenormalizegroup:
case TAKaggregate:
case TAKexistsaggregate:
case TAKcountaggregate:
case TAKhashaggregate:
case TAKhashdedup:
case TAKrollup:
case TAKiterate:
case TAKselectn:
case TAKfirstn:
case TAKenth:
case TAKsample:
case TAKgroup:
case TAKchoosesets:
case TAKchoosesetsenth:
case TAKchoosesetslast:
case TAKtopn:
case TAKprocess:
case TAKchildcount:
case TAKwhen_dataset:
case TAKwhen_action:
case TAKnonempty:
if (!container.queryLocalOrGrouped())
return true;
break;
case TAKkeyedjoin:
case TAKalljoin:
case TAKlookupjoin:
if (!container.queryLocal())
return true;
// always local
case TAKfilter:
case TAKfilterproject:
case TAKfiltergroup:
case TAKsplit:
case TAKpipewrite:
case TAKdegroup:
case TAKproject:
case TAKprefetchproject:
case TAKprefetchcountproject:
case TAKnormalize:
case TAKnormalizechild:
case TAKnormalizelinkedchild:
case TAKpipethrough:
case TAKif:
case TAKchildif:
case TAKchildcase:
case TAKcase:
case TAKparse:
case TAKpiperead:
case TAKxmlparse:
case TAKjoinlight:
case TAKselfjoinlight:
case TAKdiskread:
case TAKdisknormalize:
case TAKchildaggregate:
case TAKchildgroupaggregate:
case TAKchildthroughnormalize:
case TAKchildnormalize:
case TAKspillread:
case TAKindexread:
case TAKindexnormalize:
case TAKxmlread:
case TAKjsonread:
case TAKdiskexists:
case TAKindexexists:
case TAKchildexists:
case TAKthroughaggregate:
case TAKmerge:
case TAKfunnel:
case TAKregroup:
case TAKcombine:
case TAKrollupgroup:
case TAKcombinegroup:
case TAKsoap_rowdataset:
case TAKhttp_rowdataset:
case TAKsoap_rowaction:
case TAKsoap_datasetdataset:
case TAKsoap_datasetaction:
case TAKlinkedrawiterator:
case TAKchilditerator:
case TAKstreamediterator:
case TAKworkunitread:
case TAKchilddataset:
case TAKinlinetable:
case TAKnull:
case TAKemptyaction:
case TAKlocalresultread:
case TAKlocalresultwrite:
case TAKdictionaryresultwrite:
case TAKgraphloopresultread:
case TAKgraphloopresultwrite:
case TAKnwaygraphloopresultread:
case TAKapply:
case TAKsideeffect:
case TAKsimpleaction:
case TAKsorted:
case TAKdistributed:
case TAKtrace:
break;
case TAKnwayjoin:
case TAKnwaymerge:
case TAKnwaymergejoin:
case TAKnwayinput:
case TAKnwayselect:
return false; // JCSMORE - I think and/or have to be for now
// undefined
case TAKdatasetresult:
case TAKrowresult:
case TAKremotegraph:
case TAKlibrarycall:
default:
return true; // if in doubt
}
return false;
}
bool isLoopActivity(CGraphElementBase &container)
{
switch (container.getKind())
{
case TAKlooprow:
case TAKloopcount:
case TAKloopdataset:
case TAKgraphloop:
case TAKparallelgraphloop:
return true;
}
return false;
}
static void getGlobalDeps(CGraphBase &graph, CICopyArrayOf<CGraphDependency> &deps)
{
Owned<IThorActivityIterator> iter = graph.getIterator();
ForEach(*iter)
{
CGraphElementBase &elem = iter->query();
Owned<IThorGraphDependencyIterator> dependIterator = elem.getDependsIterator();
ForEach(*dependIterator)
{
CGraphDependency &dependency = dependIterator->query();
if (dependency.graph->isGlobal() && NULL==dependency.graph->queryOwner())
deps.append(dependency);
getGlobalDeps(*dependency.graph, deps);
}
}
}
static void noteDependency(CGraphElementBase *targetActivity, CGraphElementBase *sourceActivity, CGraphBase *targetGraph, CGraphBase *sourceGraph, unsigned controlId)
{
targetActivity->addDependsOn(sourceGraph, controlId);
// NB: record dependency in source graph, serialized to slaves, used to decided if should run dependency sinks or not
Owned<IPropertyTree> dependencyFor = createPTree();
dependencyFor->setPropInt("@id", sourceActivity->queryId());
dependencyFor->setPropInt("@graphId", targetGraph->queryGraphId());
if (controlId)
dependencyFor->setPropInt("@conditionalId", controlId);
sourceGraph->queryXGMML().addPropTree("Dependency", dependencyFor.getClear());
}
static void addDependencies(IPropertyTree *xgmml, bool failIfMissing, CGraphTableCopy &graphs)
{
CGraphArrayCopy dependentchildGraphs;
CGraphElementArrayCopy targetActivities, sourceActivities;
Owned<IPropertyTreeIterator> iter = xgmml->getElements("edge");
ForEach(*iter)
{
IPropertyTree &edge = iter->query();
graph_id sourceGid = edge.getPropInt("@source");
graph_id targetGid = edge.getPropInt("@target");
Owned<CGraphBase> source = LINK(graphs.find(sourceGid));
Owned<CGraphBase> target = LINK(graphs.find(targetGid));
if (!source || !target)
{
if (failIfMissing)
throwUnexpected();
else
continue; // expected if assigning dependencies in slaves
}
CGraphElementBase *targetActivity = (CGraphElementBase *)target->queryElement(edge.getPropInt("att[@name=\"_targetActivity\"]/@value"));
CGraphElementBase *sourceActivity = (CGraphElementBase *)source->queryElement(edge.getPropInt("att[@name=\"_sourceActivity\"]/@value"));
if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value"))
{
if (TAKlocalresultwrite == sourceActivity->getKind() && (TAKlocalresultread != targetActivity->getKind()))
{
if (source->isLoopSubGraph())
source->setGlobal(true);
}
}
int controlId = 0;
if (edge.getPropBool("att[@name=\"_dependsOn\"]/@value", false))
{
if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do.
controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0);
CGraphBase &sourceGraph = sourceActivity->queryOwner();
unsigned sourceGraphContext = sourceGraph.queryParentActivityId();
CGraphBase *targetGraph = NULL;
unsigned targetGraphContext = -1;
for (;;)
{
targetGraph = &targetActivity->queryOwner();
targetGraphContext = targetGraph->queryParentActivityId();
if (sourceGraphContext == targetGraphContext)
break;
targetActivity = targetGraph->queryElement(targetGraphContext);
}
assertex(targetActivity && sourceActivity);
noteDependency(targetActivity, sourceActivity, target, source, controlId);
}
else if (edge.getPropBool("att[@name=\"_conditionSource\"]/@value", false))
{ /* Ignore it */ }
else if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false))
{
// NB: any dependencies of the child acts. are dependencies of this act.
dependentchildGraphs.append(*source);
targetActivities.append(*targetActivity);
sourceActivities.append(*sourceActivity);
}
else
{
if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do.
controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0);
noteDependency(targetActivity, sourceActivity, target, source, controlId);
}
}
ForEachItemIn(c, dependentchildGraphs)
{
CGraphBase &childGraph = dependentchildGraphs.item(c);
CGraphElementBase &targetActivity = targetActivities.item(c);
CGraphElementBase &sourceActivity = sourceActivities.item(c);
if (!childGraph.isGlobal())
{
CICopyArrayOf<CGraphDependency> globalChildGraphDeps;
getGlobalDeps(childGraph, globalChildGraphDeps);
ForEachItemIn(gcd, globalChildGraphDeps)
{
CGraphDependency &globalDep = globalChildGraphDeps.item(gcd);
noteDependency(&targetActivity, &sourceActivity, globalDep.graph, &childGraph, globalDep.controlId);
}
}
}
SuperHashIteratorOf<CGraphBase> allIter(graphs);
ForEach(allIter)
{
CGraphBase &subGraph = allIter.query();
if (subGraph.queryOwner() && subGraph.queryParentActivityId())
{
CGraphElementBase *parentElement = subGraph.queryOwner()->queryElement(subGraph.queryParentActivityId());
if (isLoopActivity(*parentElement))
{
if (!parentElement->queryOwner().isLocalChild() && !subGraph.isLocalOnly())
subGraph.setGlobal(true);
}
}
}
}
void traceMemUsage()
{
StringBuffer memStatsStr;
roxiemem::memstats(memStatsStr);
PROGLOG("Roxiemem stats: %s", memStatsStr.str());
memsize_t heapUsage = getMapInfo("heap");
if (heapUsage) // if 0, assumed to be unavailable
{
memsize_t rmtotal = roxiemem::getTotalMemoryLimit();
PROGLOG("Heap usage (excluding Roxiemem) : %" I64F "d bytes", (unsigned __int64)(heapUsage-rmtotal));
}
}
/////
CGraphBase::CGraphBase(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob()), progressUpdated(false)
{
xgmml = NULL;
parent = owner = graphResultsContainer = NULL;
complete = false;
parentActivityId = 0;
connected = started = graphDone = aborted = false;
startBarrier = waitBarrier = doneBarrier = NULL;
mpTag = waitBarrierTag = startBarrierTag = doneBarrierTag = TAG_NULL;
executeReplyTag = TAG_NULL;
parentExtractSz = 0;
counter = 0; // loop/graph counter, will be set by loop/graph activity if needed
loopBodySubgraph = false;
}
CGraphBase::~CGraphBase()
{
clean();
}
CGraphBase *CGraphBase::cloneGraph()
{
Owned<CGraphBase> subGraph = queryJobChannel().createGraph();
CGraphTableCopy newGraphs;
subGraph->createFromXGMML(node, owner, parent, graphResultsContainer, newGraphs);
addDependencies(queryJob().queryXGMML(), false, newGraphs);
return subGraph.getClear();
}
void CGraphBase::init()
{
bool log = queryJob().queryForceLogging(queryGraphId(), (NULL == queryOwner()) || isGlobal());
setLogging(log);
}
void CGraphBase::clean()
{
::Release(startBarrier);
::Release(waitBarrier);
::Release(doneBarrier);
localResults.clear();
graphLoopResults.clear();
childGraphsTable.releaseAll();
disconnectActivities();
containers.releaseAll();
sinks.kill();
activeSinks.kill();
}
void CGraphBase::serializeCreateContexts(MemoryBuffer &mb)
{
DelayedSizeMarker sizeMark(mb);
Owned<IThorActivityIterator> iter = getIterator();
ForEach (*iter)
{
CGraphElementBase &element = iter->query();
if (element.isOnCreated())
{
mb.append(element.queryId());
element.serializeCreateContext(mb);
}
}
mb.append((activity_id)0);
sizeMark.write();
}
void CGraphBase::deserializeCreateContexts(MemoryBuffer &mb)
{
activity_id id;
for (;;)
{
mb.read(id);
if (0 == id) break;
CGraphElementBase *element = queryElement(id);
assertex(element);
element->deserializeCreateContext(mb);
}
}
void CGraphBase::reset()
{
setCompleteEx(false);
clearProgressUpdated();
graphCancelHandler.reset();
if (0 == containers.count())
{
Owned<IThorGraphIterator> iter = getChildGraphIterator();
ForEach(*iter)
iter->query().reset();
}
else
{
Owned<IThorActivityIterator> iter = getIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
element.reset();
}
dependentSubGraphs.kill();
}
if (!queryOwner())
clearNodeStats();
}
void CGraphBase::addChildGraph(CGraphStub *stub)
{
CriticalBlock b(crit);
childGraphsTable.replace(*LINK(stub));
if (sequential)
orderedChildGraphs.append(*stub);
}
IThorGraphStubIterator *CGraphBase::getChildStubIterator() const
{
CriticalBlock b(crit);
class CIter : private SuperHashIteratorOf<CGraphStub>, public CSimpleInterfaceOf<IThorGraphStubIterator>
{
typedef SuperHashIteratorOf<CGraphStub> PARENT;
public:
CIter(const CChildGraphTable &table) : PARENT(table) { }
// IIterator
virtual bool first() { return PARENT::first(); }
virtual bool next() { return PARENT::next(); }
virtual bool isValid() { return PARENT::isValid(); }
virtual CGraphStub &query() { return PARENT::query(); }
};
return new CIter(childGraphsTable);
}
IThorGraphIterator *CGraphBase::getChildGraphIterator() const
{
CriticalBlock b(crit);
class CIter : public CSimpleInterfaceOf<IThorGraphIterator>
{
Owned<IThorGraphStubIterator> iter;
public:
CIter(IThorGraphStubIterator *_iter) : iter(_iter)
{
}
// IIterator
virtual bool first() { return iter->first(); }
virtual bool next() { return iter->next(); }
virtual bool isValid() { return iter->isValid(); }
virtual CGraphBase &query()
{
CGraphStub &stub = iter->query();
return stub.queryOriginalGraph();
}
};
return new CIter(getChildStubIterator());
}
bool CGraphBase::fireException(IException *e)
{
return queryJobChannel().fireException(e);
}
bool CGraphBase::preStart(size32_t parentExtractSz, const byte *parentExtract)
{
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
element.preStart(parentExtractSz, parentExtract);
}
return true;
}
void CGraphBase::executeSubGraph(size32_t parentExtractSz, const byte *parentExtract)
{
CriticalBlock b(executeCrit);
if (job.queryPausing())
return;
Owned<IException> exception;
try
{
if (!queryOwner())
{
StringBuffer s;
toXML(&queryXGMML(), s, 2);
GraphPrintLog("Running graph [%s] : %s", isGlobal()?"global":"local", s.str());
}
if (localResults)
localResults->clear();
doExecute(parentExtractSz, parentExtract, false);
}
catch (IException *e)
{
GraphPrintLog(e);
exception.setown(e);
}
if (!queryOwner())
{
GraphPrintLog("Graph Done");
StringBuffer memStr;
getSystemTraceInfo(memStr, PerfMonStandard | PerfMonExtended);
GraphPrintLog("%s", memStr.str());
}
if (exception)
throw exception.getClear();
}
void CGraphBase::onCreate()
{
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
element.onCreate();
}
}
void CGraphBase::execute(size32_t _parentExtractSz, const byte *parentExtract, bool checkDependencies, bool async)
{
if (isComplete())
return;
if (async)
queryJobChannel().startGraph(*this, checkDependencies, _parentExtractSz, parentExtract); // may block if enough running
else
{
if (!prepare(_parentExtractSz, parentExtract, checkDependencies, false, false))
{
setComplete();
return;
}
executeSubGraph(_parentExtractSz, parentExtract);
}
}
void CGraphBase::doExecute(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies)
{
if (isComplete()) return;
if (queryAborted())
{
if (abortException)
throw abortException.getLink();
throw MakeGraphException(this, 0, "subgraph aborted");
}
GraphPrintLog("Processing graph");
Owned<IException> exception;
try
{
if (started)
reset();
else
started = true;
++numExecuted;
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
element.onStart(parentExtractSz, parentExtract);
element.initActivity();
}
initialized = true;
if (!preStart(parentExtractSz, parentExtract)) return;
start();
if (!wait(aborted?MEDIUMTIMEOUT:INFINITE)) // can't wait indefinitely, query may have aborted and stall, but prudent to wait a short time for underlying graphs to unwind.
GraphPrintLogEx(this, thorlog_null, MCuserWarning, "Graph wait cancelled, aborted=%s", aborted?"true":"false");
else
graphDone = true;
}
catch (IException *e)
{
GraphPrintLog(e);
exception.setown(e);
}
try
{
if (!exception && abortException)
exception.setown(abortException.getClear());
if (exception)
{
if (NULL == owner || isGlobal())
waitBarrier->cancel(exception);
if (!queryOwner())
{
StringBuffer str;
Owned<IThorException> e = MakeGraphException(this, exception->errorCode(), "%s", exception->errorMessage(str).str());
e->setAction(tea_abort);
fireException(e);
}
}
}
catch (IException *e)
{
GraphPrintLog(e, "during abort()");
e->Release();
}
try
{
done();
if (doneBarrier)
doneBarrier->wait(false);
}
catch (IException *e)
{
GraphPrintLog(e);
if (!exception.get())
exception.setown(e);
else
e->Release();
}
end();
if (exception)
throw exception.getClear();
if (!queryAborted())
setComplete();
}
bool CGraphBase::prepare(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async)
{
if (isComplete()) return false;
bool needToExecute = false;
ForEachItemIn(s, sinks)
{
CGraphElementBase &sink = sinks.item(s);
if (sink.prepareContext(parentExtractSz, parentExtract, checkDependencies, shortCircuit, async, false))
needToExecute = true;
}
onCreate();
return needToExecute;
}
void CGraphBase::done()
{
if (aborted) return; // activity done methods only called on success
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach (*iter)
{
CGraphElementBase &element = iter->query();
element.queryActivity()->done();
}
}
unsigned CGraphBase::queryJobChannelNumber() const
{
return queryJobChannel().queryChannel();
}
IMPServer &CGraphBase::queryMPServer() const
{
return jobChannel.queryMPServer();
}
bool CGraphBase::syncInitData()
{
if (loopBodySubgraph)
{
CGraphElementBase *parentElement = queryOwner() ? queryOwner()->queryElement(queryParentActivityId()) : nullptr;
assertex(parentElement);
return parentElement->queryLoopGraph()->queryGraph()->isGlobal();
}
else
return !isLocalChild();
}
void CGraphBase::end()
{
// always called, any final action clear up
Owned<IThorActivityIterator> iter = getIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
try
{
if (element.queryActivity())
element.queryActivity()->kill();
}
catch (IException *e)
{
Owned<IException> e2 = MakeActivityException(element.queryActivity(), e, "Error calling kill()");
GraphPrintLog(e2);
e->Release();
}
}
}
class CGraphTraverseIteratorBase : implements IThorActivityIterator, public CInterface
{
protected:
CGraphBase &graph;
Linked<CGraphElementBase> cur;
CIArrayOf<CGraphElementBase> others;
CGraphElementArrayCopy covered;
CGraphElementBase *popNext()
{
if (!others.ordinality())
{
cur.clear();
return NULL;
}
cur.setown(&others.popGet());
return cur;
}
void setNext(bool branchOnConditional)
{
if (branchOnConditional && ((unsigned)-1) != cur->whichBranch)
{
CIOConnection *io = cur->connectedInputs.queryItem(cur->whichBranch);
if (io)
cur.set(io->activity);
else
cur.clear();
}
else
{
CIOConnectionArray &inputs = cur->connectedInputs;
cur.clear();
unsigned n = inputs.ordinality();
bool first = true;
for (unsigned i=0; i<n; i++)
{
CIOConnection *io = inputs.queryItem(i);
if (io)
{
if (first)
{
first = false;
cur.set(io->activity);
}
else
others.append(*LINK(io->activity));
}
}
}
if (!cur)
{
if (!popNext())
return;
}
// check haven't been here before
for (;;)
{
if (cur->getOutputs() < 2)
break;
else if (NotFound == covered.find(*cur))
{
if (!cur->alreadyUpdated)
{
covered.append(*cur);
break;
}
}
if (!popNext())
return;
}
}
public:
IMPLEMENT_IINTERFACE;
CGraphTraverseIteratorBase(CGraphBase &_graph) : graph(_graph)
{
}
virtual bool first()
{
covered.kill();
others.kill();
cur.clear();
Owned<IThorActivityIterator> sinkIter = graph.getSinkIterator();
if (!sinkIter->first())
return false;
for (;;)
{
cur.set(& sinkIter->query());
if (!cur->alreadyUpdated)
break;
if (!sinkIter->next())
return false;
}
while (sinkIter->next())
others.append(sinkIter->get());
return true;
}
virtual bool isValid() { return NULL != cur.get(); }
virtual CGraphElementBase & query() { return *cur; }
CGraphElementBase & get() { return *LINK(cur); }
};
class CGraphTraverseConnectedIterator : public CGraphTraverseIteratorBase
{
bool branchOnConditional;
public:
CGraphTraverseConnectedIterator(CGraphBase &graph, bool _branchOnConditional) : CGraphTraverseIteratorBase(graph), branchOnConditional(_branchOnConditional) { }
virtual bool next()
{
setNext(branchOnConditional);
return NULL!=cur.get();
}
};
IThorActivityIterator *CGraphBase::getConnectedIterator(bool branchOnConditional)
{
return new CGraphTraverseConnectedIterator(*this, branchOnConditional);
}
bool CGraphBase::wait(unsigned timeout)
{
CTimeMon tm(timeout);
unsigned remaining = timeout;
class CWaitException
{
CGraphBase *graph;
Owned<IException> exception;
public:
CWaitException(CGraphBase *_graph) : graph(_graph) { }
IException *get() { return exception; }
void set(IException *e)
{
if (!exception)
exception.setown(e);
else
e->Release();
}
void throwException()
{
if (exception)
throw exception.getClear();
throw MakeGraphException(graph, 0, "Timed out waiting for graph to end");
}
} waitException(this);
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach (*iter)
{
CGraphElementBase &element = iter->query();
CActivityBase *activity = element.queryActivity();
if (INFINITE != timeout && tm.timedout(&remaining))
waitException.throwException();
try
{
if (!activity->wait(remaining))
waitException.throwException();
}
catch (IException *e)
{
waitException.set(e); // will discard if already set
if (timeout == INFINITE)
{
unsigned e = tm.elapsed();
if (e >= MEDIUMTIMEOUT)
waitException.throwException();
timeout = MEDIUMTIMEOUT-e;
tm.reset(timeout);
}
}
}
if (waitException.get())
waitException.throwException();
// synchronize all slaves to end of graphs
if (NULL == owner || isGlobal())
{
if (INFINITE != timeout && tm.timedout(&remaining))
waitException.throwException();
if (!waitBarrier->wait(true, remaining))
return false;
}
return true;
}
void CGraphBase::abort(IException *e)
{
if (aborted)
return;
{
CriticalBlock cb(crit);
abortException.set(e);
aborted = true;
graphCancelHandler.cancel(0);
if (0 == containers.count())
{
Owned<IThorGraphStubIterator> iter = getChildStubIterator();
ForEach(*iter)
{
CGraphStub &graph = iter->query();
graph.abort(e);
}
}
}
if (started && !graphDone)
{
Owned<IThorActivityIterator> iter = getConnectedIterator();
ForEach (*iter)
{
iter->query().abort(e); // JCSMORE - could do in parallel, they can take some time to timeout
}
if (startBarrier)
startBarrier->cancel(e);
if (waitBarrier)
waitBarrier->cancel(e);
if (doneBarrier)
doneBarrier->cancel(e);
}
}
void CGraphBase::GraphPrintLog(const char *format, ...)
{
va_list args;
va_start(args, format);
::GraphPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args);
va_end(args);
}
void CGraphBase::GraphPrintLog(IException *e, const char *format, ...)
{
va_list args;
va_start(args, format);
::GraphPrintLogArgs(this, e, thorlog_null, MCdebugProgress, format, args);
va_end(args);
}
void CGraphBase::GraphPrintLog(IException *e)
{
GraphPrintLog(e, "%s", "");
}
void CGraphBase::setLogging(bool tf)
{
Owned<IThorActivityIterator> iter = getIterator();
ForEach(*iter)
iter->query().setLogging(tf);
}
void CGraphBase::createFromXGMML(IPropertyTree *_node, CGraphBase *_owner, CGraphBase *_parent, CGraphBase *resultsGraph, CGraphTableCopy &newGraphs)
{
class CChildParallelFactory : public CGraphStub
{
Linked<CGraphBase> originalChildGraph;
CriticalSection crit;
CIArrayOf<CGraphBase> stack;
CIArrayOf<CGraphBase> active;
bool originalAvailable = true;
CGraphBase *getGraph()
{
Owned<CGraphBase> childGraph;
{
CriticalBlock b(crit);
if (originalAvailable)
{
originalAvailable = false;
active.append(*originalChildGraph.getLink());
return originalChildGraph.getLink();
}
if (stack.length())
childGraph.setown(&stack.popGet());
}
if (!childGraph)
childGraph.setown(originalChildGraph->cloneGraph());
if (originalChildGraph->queryAborted())
throw MakeGraphException(originalChildGraph, 0, "Job aborted");
{
CriticalBlock b(crit);
active.append(*childGraph.getLink());
}
return childGraph.getClear();
}
void pushGraph(CGraphBase *childGraph)
{
CriticalBlock b(crit);
verifyex(active.zap(*childGraph));
if (childGraph == originalChildGraph)
originalAvailable = true;
else
stack.append(*LINK(childGraph));
}
public:
CChildParallelFactory(CGraphBase *_originalChildGraph) : originalChildGraph(_originalChildGraph)
{
graphId = originalChildGraph->queryGraphId();
}
virtual CGraphBase &queryOriginalGraph() override { return *originalChildGraph; }
virtual void abort(IException *e) override
{
for (;;)
{
Owned<CGraphBase> activeChildGraph;
{
CriticalBlock b(crit);
activeChildGraph.setown(&active.popGet());
if (!activeChildGraph)
break;
}
activeChildGraph->abort(e);
}
}
virtual bool serializeStats(MemoryBuffer &mb) override
{
// JCSMORE - need to merge other instances
return originalChildGraph->serializeStats(mb);
}
virtual IEclGraphResults * evaluate(unsigned parentExtractSz, const byte * parentExtract) override
{
Owned<CGraphBase> childGraph = getGraph();
Owned<IEclGraphResults> results = childGraph->evaluate(parentExtractSz, parentExtract);
pushGraph(childGraph);
return results.getClear();
}
};
owner = _owner;
parent = _parent?_parent:owner;
node.setown(createPTreeFromIPT(_node));
xgmml = node->queryPropTree("att/graph");
sink = xgmml->getPropBool("att[@name=\"rootGraph\"]/@value", false);
sequential = xgmml->getPropBool("@sequential");
graphId = node->getPropInt("@id");
global = false;
localOnly = -1; // unset
parentActivityId = node->getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
graphResultsContainer = resultsGraph;
CGraphBase *graphContainer = this;
if (resultsGraph)
graphContainer = resultsGraph; // JCSMORE is this right?
graphCodeContext.setContext(this, graphContainer, (ICodeContextExt *)&jobChannel.queryCodeContext());
unsigned numResults = xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0);
if (numResults)
{
localResults.setown(createThorGraphResults(numResults));
resultsGraph = this;
// JCSMORE - it might more sense if this temp handler was owned by parent act., which may finish(get stopped) earlier than the owning graph
tmpHandler.setown(queryJob().createTempHandler(false));
}
localChild = false;
if (owner && parentActivityId)
{
CGraphElementBase *parentElement = owner->queryElement(parentActivityId);
if (isLoopActivity(*parentElement))
{
localChild = parentElement->queryOwner().isLocalChild();
unsigned loopId = parentElement->queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value");
if ((graphId == loopId) || (owner->queryGraphId() == loopId))
loopBodySubgraph = true;
else
localChild = true;
}
else
localChild = true;
}
Owned<IPropertyTreeIterator> nodes = xgmml->getElements("node");
ForEach(*nodes)
{
IPropertyTree &e = nodes->query();
ThorActivityKind kind = (ThorActivityKind) e.getPropInt("att[@name=\"_kind\"]/@value");
if (TAKsubgraph == kind)
{
Owned<CGraphBase> subGraph = queryJobChannel().createGraph();
subGraph->createFromXGMML(&e, this, parent, resultsGraph, newGraphs);
activity_id subGraphParentActivityId = e.getPropInt("att[@name=\"_parentActivity\"]/@value", 0);
if (subGraphParentActivityId) // JCS - not sure if ever false
{
Owned<CGraphStub> stub = new CChildParallelFactory(subGraph);
addChildGraph(stub);
}
else
addChildGraph(subGraph);
if (!global)
global = subGraph->isGlobal();
newGraphs.replace(*subGraph);
}
else
{
if (localChild && !e.getPropBool("att[@name=\"coLocal\"]/@value", false))
{
IPropertyTree *att = createPTree("att");
att->setProp("@name", "coLocal");
att->setPropBool("@value", true);
e.addPropTree("att", att);
}
CGraphElementBase *act = createGraphElement(e, *this, resultsGraph);
addActivity(act);
if (!global)
global = isGlobalActivity(*act);
}
}
Owned<IPropertyTreeIterator> edges = xgmml->getElements("edge");
ForEach(*edges)
{
IPropertyTree &edge = edges->query();
//Ignore edges that represent dependencies from parent activities to child activities.
if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false))
continue;
unsigned sourceOutput = edge.getPropInt("att[@name=\"_sourceIndex\"]/@value", 0);
unsigned targetInput = edge.getPropInt("att[@name=\"_targetIndex\"]/@value", 0);
CGraphElementBase *source = queryElement(edge.getPropInt("@source"));
CGraphElementBase *target = queryElement(edge.getPropInt("@target"));
target->addInput(targetInput, source, sourceOutput);
}
Owned<IThorActivityIterator> iter = getIterator();
ForEach(*iter)
{
CGraphElementBase &element = iter->query();
if (0 == element.getOutputs())
{
/* JCSMORE - Making some outputs conditional, will require:
* a) Pass through information as to which dependent graph causes this graph (and this sink) to execute)
* b) Allow the subgraph to re-executed by other dependent subgraphs and avoid re-executing completed sinks
* c) Keep common points (splitters) around (preferably in memory), re-execution of graph will need them
*/
sinks.append(*LINK(&element));
}
}
init();
}
void CGraphBase::executeChildGraphs(size32_t parentExtractSz, const byte *parentExtract)
{
if (sequential)
{
// JCSMORE - would need to re-think how this is done if these sibling child queries could be executed in parallel
ForEachItemIn(o, orderedChildGraphs)
{
CGraphBase &graph = orderedChildGraphs.item(o).queryOriginalGraph();
if (graph.isSink())
graph.execute(parentExtractSz, parentExtract, true, false);
}
}
else
{
Owned<IThorGraphIterator> iter = getChildGraphIterator();
ForEach(*iter)
{
CGraphBase &graph = iter->query();
if (graph.isSink())
graph.execute(parentExtractSz, parentExtract, true, false);
}
}
}
void CGraphBase::doExecuteChild(size32_t parentExtractSz, const byte *parentExtract)
{
reset();
if (0 == containers.count())
executeChildGraphs(parentExtractSz, parentExtract);
else
execute(parentExtractSz, parentExtract, false, false);
queryTempHandler()->clearTemps();
}
void CGraphBase::executeChild(size32_t & retSize, void * &ret, size32_t parentExtractSz, const byte *parentExtract)
{
reset();
doExecute(parentExtractSz, parentExtract, false);
UNIMPLEMENTED;
/*
ForEachItemIn(idx1, elements)
{
EclGraphElement & cur = elements.item(idx1);
if (cur.isResult)
{
cur.extractResult(retSize, ret);
return;
}
}
*/
throwUnexpected();
}
void CGraphBase::setResults(IThorGraphResults *results) // used by master only
{
localResults.set(results);
}
void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract, IThorGraphResults *results, IThorGraphResults *_graphLoopResults)
{
localResults.set(results);
graphLoopResults.set(_graphLoopResults);
doExecuteChild(parentExtractSz, parentExtract);
graphLoopResults.clear();
localResults.clear();
}
StringBuffer &getGlobals(CGraphBase &graph, StringBuffer &str)
{
bool first = true;
Owned<IThorActivityIterator> iter = graph.getIterator();
ForEach(*iter)
{
CGraphElementBase &e = iter->query();
if (isGlobalActivity(e))
{
if (first)
str.append("Graph(").append(graph.queryGraphId()).append("): [");
else
str.append(", ");
first = false;
ThorActivityKind kind = e.getKind();
str.append(activityKindStr(kind));
str.append("(").append(e.queryId()).append(")");
}
}
if (!first)
str.append("]");
Owned<IThorGraphIterator> childIter = graph.getChildGraphIterator();
ForEach(*childIter)
{
CGraphBase &childGraph = childIter->query();
getGlobals(childGraph, str);
}
return str;
}
void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract)
{
assertex(localResults);
localResults->clear();
if (isGlobal()) // any slave
{
StringBuffer str("Global acts = ");
getGlobals(*this, str);
throw MakeGraphException(this, 0, "Global child graph? : %s", str.str());
}
doExecuteChild(parentExtractSz, parentExtract);
}
IThorResult *CGraphBase::getResult(unsigned id, bool distributed)
{
return localResults->getResult(id, distributed);
}
IThorResult *CGraphBase::getGraphLoopResult(unsigned id, bool distributed)
{
return graphLoopResults->getResult(id, distributed);
}
IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorGraphResults *results, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
{
return results->createResult(activity, id, rowIf, resultType, spillPriority);
}
IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
{
return localResults->createResult(activity, id, rowIf, resultType, spillPriority);
}
IThorResult *CGraphBase::createGraphLoopResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority)
{
return graphLoopResults->createResult(activity, rowIf, resultType, spillPriority);
}
// IEclGraphResults
void CGraphBase::getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id)
{
Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
result->getLinkedResult(count, ret);
}
void CGraphBase::getLinkedResult(unsigned & count, const byte * * & ret, unsigned id)
{
Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
result->getLinkedResult(count, ret);
}
const void * CGraphBase::getLinkedRowResult(unsigned id)
{
Owned<IThorResult> result = getResult(id, true); // will get collated distributed result
return result->getLinkedRowResult();
}
// IThorChildGraph impl.
IEclGraphResults *CGraphBase::evaluate(unsigned _parentExtractSz, const byte *parentExtract)
{
CriticalBlock block(evaluateCrit);
localResults.setown(createThorGraphResults(xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0)));
parentExtractSz = _parentExtractSz;
executeChild(parentExtractSz, parentExtract);
return localResults.getClear();
}
static bool isLocalOnly(const CGraphElementBase &activity);
static bool isLocalOnly(const CGraphBase &graph) // checks all dependencies, if something needs to be global, whole body is forced to be execution sync.
{
if (0 == graph.activityCount())
{
Owned<IThorGraphIterator> iter = graph.getChildGraphIterator();
ForEach(*iter)
{
CGraphBase &childGraph = iter->query();
if (childGraph.isSink())
{
if (!isLocalOnly(childGraph))
return false;
}
}
}
else
{
if (graph.isGlobal())
return false;
Owned<IThorActivityIterator> sinkIter = graph.getAllSinkIterator();
ForEach(*sinkIter)
{
CGraphElementBase &sink = sinkIter->query();
if (!isLocalOnly(sink))
return false;
}
}
return true;
}
static bool isLocalOnly(const CGraphElementBase &activity)
{
Owned<IThorGraphDependencyIterator> deps = activity.getDependsIterator();
ForEach(*deps)
{
if (!isLocalOnly(*(deps->query().graph)))
return false;
}
StringBuffer match("edge[@target=\"");
match.append(activity.queryId()).append("\"]");
Owned<IPropertyTreeIterator> inputs = activity.queryOwner().queryXGMML().getElements(match.str());
ForEach(*inputs)
{
IPropertyTree &edge = inputs->query();
//Ignore edges that represent dependencies from parent activities to child activities.
if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false))
continue;
CGraphElementBase *sourceAct = activity.queryOwner().queryElement(edge.getPropInt("@source"));
if (!isLocalOnly(*sourceAct))
return false;
}
return true;
}
bool CGraphBase::isLocalOnly() const // checks all dependencies, if something needs to be global, whole body is forced to be execution sync.
{
if (-1 == localOnly)
localOnly = (int)::isLocalOnly(*this);
return 1==localOnly;
}
IThorGraphResults *CGraphBase::createThorGraphResults(unsigned num)
{
return new CThorGraphResults(num);
}
////
void CGraphTempHandler::registerFile(const char *name, graph_id graphId, unsigned usageCount, bool temp, WUFileKind fileKind, StringArray *clusters)
{
assertex(temp);
LOG(MCdebugProgress, thorJob, "registerTmpFile name=%s, usageCount=%d", name, usageCount);
CriticalBlock b(crit);
if (tmpFiles.find(name))
throw MakeThorException(TE_FileAlreadyUsedAsTempFile, "File already used as temp file (%s)", name);
tmpFiles.replace(* new CFileUsageEntry(name, graphId, fileKind, usageCount));
}
void CGraphTempHandler::deregisterFile(const char *name, bool kept)
{
LOG(MCdebugProgress, thorJob, "deregisterTmpFile name=%s", name);
CriticalBlock b(crit);
CFileUsageEntry *fileUsage = tmpFiles.find(name);
if (!fileUsage)
{
if (errorOnMissing)
throw MakeThorException(TE_FileNotFound, "File not found (%s) deregistering tmp file", name);
return;
}
if (0 == fileUsage->queryUsage()) // marked 'not to be deleted' until workunit complete.
return;
else if (1 == fileUsage->queryUsage())
{
tmpFiles.remove(name);
try
{
if (!removeTemp(name))
LOG(MCwarning, unknownJob, "Failed to delete tmp file : %s (not found)", name);
}
catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(name).str()); }
}
else
fileUsage->decUsage();
}
void CGraphTempHandler::clearTemps()
{
CriticalBlock b(crit);
Owned<IFileUsageIterator> iter = getIterator();
ForEach(*iter)
{
CFileUsageEntry &entry = iter->query();
const char *tmpname = entry.queryName();
try
{
if (!removeTemp(tmpname))
LOG(MCwarning, thorJob, "Failed to delete tmp file : %s (not found)", tmpname);
}
catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(tmpname).str()); }
}
iter.clear();
tmpFiles.kill();
}
/////
class CGraphExecutor;
class CGraphExecutorGraphInfo : public CInterface
{
public:
CGraphExecutorGraphInfo(CGraphExecutor &_executor, CGraphBase *_subGraph, IGraphCallback &_callback, const byte *parentExtract, size32_t parentExtractSz) : executor(_executor), subGraph(_subGraph), callback(_callback)
{
parentExtractMb.append(parentExtractSz, parentExtract);
}
CGraphExecutor &executor;
IGraphCallback &callback;
Linked<CGraphBase> subGraph;
MemoryBuffer parentExtractMb;
};
class CGraphExecutor : implements IGraphExecutor, public CInterface
{
CJobChannel &jobChannel;
CJobBase &job;
CIArrayOf<CGraphExecutorGraphInfo> stack, running, toRun;
UnsignedArray seen;
bool stopped;
unsigned limit;
unsigned waitOnRunning;
CriticalSection crit;
Semaphore runningSem;
Owned<IThreadPool> graphPool;
class CGraphExecutorFactory : implements IThreadFactory, public CInterface
{
CGraphExecutor &executor;
public:
IMPLEMENT_IINTERFACE;
CGraphExecutorFactory(CGraphExecutor &_executor) : executor(_executor) { }
// IThreadFactory
virtual IPooledThread *createNew()
{
class CGraphExecutorThread : implements IPooledThread, public CInterface
{
Owned<CGraphExecutorGraphInfo> graphInfo;
public:
IMPLEMENT_IINTERFACE;
CGraphExecutorThread()
{
}
virtual void init(void *startInfo) override
{
graphInfo.setown((CGraphExecutorGraphInfo *)startInfo);
}
virtual void threadmain() override
{
for (;;)
{
Linked<CGraphBase> graph = graphInfo->subGraph;
Owned<IException> e;
try
{
PROGLOG("CGraphExecutor: Running graph, graphId=%" GIDPF "d", graph->queryGraphId());
graphInfo->callback.runSubgraph(*graph, graphInfo->parentExtractMb.length(), (const byte *)graphInfo->parentExtractMb.toByteArray());
}
catch (IException *_e)
{
e.setown(_e);
}
Owned<CGraphExecutorGraphInfo> nextGraphInfo;
try
{
nextGraphInfo.setown(graphInfo->executor.graphDone(*graphInfo, e));
}
catch (IException *e)
{
GraphPrintLog(graph, e, "graphDone");
e->Release();
}
graphInfo.clear(); // NB: at this point the graph will be destroyed
if (e)
throw e.getClear();
if (!nextGraphInfo)
return;
graphInfo.setown(nextGraphInfo.getClear());
}
}
virtual bool canReuse() const override { return true; }
virtual bool stop() override { return true; }
};
return new CGraphExecutorThread();
}
} *factory;
CGraphExecutorGraphInfo *findRunning(graph_id gid)
{
ForEachItemIn(r, running)
{
CGraphExecutorGraphInfo *graphInfo = &running.item(r);
if (gid == graphInfo->subGraph->queryGraphId())
return graphInfo;
}
return NULL;
}
public:
IMPLEMENT_IINTERFACE;
CGraphExecutor(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob())
{
limit = (unsigned)job.getWorkUnitValueInt("concurrentSubGraphs", globals->getPropInt("@concurrentSubGraphs", 1));
PROGLOG("CGraphExecutor: limit = %d", limit);
waitOnRunning = 0;
stopped = false;
factory = new CGraphExecutorFactory(*this);
graphPool.setown(createThreadPool("CGraphExecutor pool", factory, &jobChannel, limit));
}
~CGraphExecutor()
{
stopped = true;
graphPool->joinAll();
factory->Release();
}
CGraphExecutorGraphInfo *graphDone(CGraphExecutorGraphInfo &doneGraphInfo, IException *e)
{
CriticalBlock b(crit);
running.zap(doneGraphInfo);
if (waitOnRunning)
{
runningSem.signal(waitOnRunning);
waitOnRunning = 0;
}
if (e || job.queryAborted())
{
stopped = true;
stack.kill();
return NULL;
}
if (job.queryPausing())
stack.kill();
else if (stack.ordinality())
{
CICopyArrayOf<CGraphExecutorGraphInfo> toMove;
ForEachItemIn(s, stack)
{
bool dependenciesDone = true;
CGraphExecutorGraphInfo &graphInfo = stack.item(s);
ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs)
{
CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d);
if (!subGraph.isComplete())
{
dependenciesDone = false;
break;
}
}
if (dependenciesDone)
{
graphInfo.subGraph->dependentSubGraphs.kill();
graphInfo.subGraph->prepare(graphInfo.parentExtractMb.length(), (const byte *)graphInfo.parentExtractMb.toByteArray(), true, true, true); // now existing deps done, maybe more to prepare
ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs)
{
CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d);
if (!subGraph.isComplete())
{
dependenciesDone = false;
break;
}
}
if (dependenciesDone)
{
graphInfo.subGraph->dependentSubGraphs.kill(); // none to track anymore
toMove.append(graphInfo);
}
}
}
ForEachItemIn(m, toMove)
{
Linked<CGraphExecutorGraphInfo> graphInfo = &toMove.item(m);
stack.zap(*graphInfo);
toRun.add(*graphInfo.getClear(), 0);
}
}
job.markWuDirty();
PROGLOG("CGraphExecutor running=%d, waitingToRun=%d, dependentsWaiting=%d", running.ordinality(), toRun.ordinality(), stack.ordinality());
while (toRun.ordinality())
{
if (job.queryPausing())
return NULL;
Linked<CGraphExecutorGraphInfo> nextGraphInfo = &toRun.item(0);
toRun.remove(0);
if (!nextGraphInfo->subGraph->isComplete() && (NULL == findRunning(nextGraphInfo->subGraph->queryGraphId())))
{
running.append(*nextGraphInfo.getLink());
return nextGraphInfo.getClear();
}
}
return NULL;
}
// IGraphExecutor
virtual void add(CGraphBase *subGraph, IGraphCallback &callback, bool checkDependencies, size32_t parentExtractSz, const byte *parentExtract)
{
bool alreadyRunning;
{
CriticalBlock b(crit);
if (job.queryPausing())
return;
if (subGraph->isComplete())
return;
alreadyRunning = NULL != findRunning(subGraph->queryGraphId());
if (alreadyRunning)
++waitOnRunning;
}
if (alreadyRunning)
{
for (;;)
{
PROGLOG("Waiting on subgraph %" GIDPF "d", subGraph->queryGraphId());
if (runningSem.wait(MEDIUMTIMEOUT) || job.queryAborted() || job.queryPausing())
break;
}
return;
}
else
{
CriticalBlock b(crit);
if (seen.contains(subGraph->queryGraphId()))
return; // already queued;
seen.append(subGraph->queryGraphId());
}
if (!subGraph->prepare(parentExtractSz, parentExtract, checkDependencies, true, true))
{
subGraph->setComplete();
return;
}
if (subGraph->dependentSubGraphs.ordinality())
{
bool dependenciesDone = true;
ForEachItemIn (d, subGraph->dependentSubGraphs)
{
CGraphBase &graph = subGraph->dependentSubGraphs.item(d);
if (!graph.isComplete())
{
dependenciesDone = false;
break;
}
}
if (dependenciesDone)
subGraph->dependentSubGraphs.kill(); // none to track anymore
}
Owned<CGraphExecutorGraphInfo> graphInfo = new CGraphExecutorGraphInfo(*this, subGraph, callback, parentExtract, parentExtractSz);
CriticalBlock b(crit);
if (0 == subGraph->dependentSubGraphs.ordinality())
{
if (running.ordinality()<limit)
{
running.append(*LINK(graphInfo));
PROGLOG("Add: Launching graph thread for graphId=%" GIDPF "d", subGraph->queryGraphId());
graphPool->start(graphInfo.getClear());
}
else
stack.add(*graphInfo.getClear(), 0); // push to front, no dependency, free to run next.
}
else
stack.append(*graphInfo.getClear()); // as dependencies finish, may move up the list
}
virtual IThreadPool &queryGraphPool() { return *graphPool; }
virtual void wait()
{
PROGLOG("CGraphExecutor exiting, waiting on graph pool");
graphPool->joinAll();
PROGLOG("CGraphExecutor graphPool finished");
}
};
////
// IContextLogger
class CThorContextLogger : implements IContextLogger, public CSimpleInterface
{
CJobBase &job;
unsigned traceLevel;
StringAttr globalIdHeader;
StringAttr callerIdHeader;
StringAttr globalId;
StringBuffer localId;
public:
IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
CThorContextLogger(CJobBase &_job) : job(_job)
{
traceLevel = 1;
if (globals->hasProp("@httpGlobalIdHeader"))
setHttpIdHeaders(globals->queryProp("@httpGlobalIdHeader"), globals->queryProp("@httpCallerIdHeader"));
}
virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
{
StringBuffer ss;
ss.valist_appendf(format, args);
LOG(MCdebugProgress, thorJob, "%s", ss.str());
}
virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
{
StringBuffer ss;
ss.append("ERROR");
if (E)
ss.append(": ").append(E->errorCode());
if (file)
ss.appendf(": %s(%d) ", file, line);
if (E)
E->errorMessage(ss.append(": "));
if (format)
ss.append(": ").valist_appendf(format, args);
LOG(MCoperatorProgress, thorJob, "%s", ss.str());
}
virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
{
}
virtual void mergeStats(const CRuntimeStatisticCollection &from) const
{
}
virtual unsigned queryTraceLevel() const
{
return traceLevel;
}
virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid)
{
globalId.set(id);
appendLocalId(localId.clear(), ep, pid);
}
virtual const char *queryGlobalId() const
{
return globalId.get();
}
virtual const char *queryLocalId() const
{
return localId.str();
}
virtual void setHttpIdHeaders(const char *global, const char *caller)
{
if (global && *global)
globalIdHeader.set(global);
if (caller && *caller)
callerIdHeader.set(caller);
}
virtual const char *queryGlobalIdHttpHeader() const
{
return globalIdHeader.str();
}
virtual const char *queryCallerIdHttpHeader() const
{
return callerIdHeader.str();
}
};
////
CJobBase::CJobBase(ILoadedDllEntry *_querySo, const char *_graphName) : querySo(_querySo), graphName(_graphName)
{
maxDiskUsage = diskUsage = 0;
dirty = true;
aborted = false;
globalMemoryMB = globals->getPropInt("@globalMemorySize"); // in MB
channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1);
numChannels = channelsPerSlave;
pluginMap = new SafePluginMap(&pluginCtx, true);
// JCSMORE - Will pass down at job creation time...
jobGroup.set(&::queryClusterGroup());
slaveGroup.setown(jobGroup->remove(0));
nodeGroup.set(&queryNodeGroup());
myNodeRank = nodeGroup->rank(::queryMyNode());
unsigned channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1);
jobChannelSlaveNumbers.allocateN(channelsPerSlave, true); // filled when channels are added.
jobSlaveChannelNum.allocateN(querySlaves()); // filled when channels are added.
for (unsigned s=0; s<querySlaves(); s++)
jobSlaveChannelNum[s] = NotFound;
StringBuffer wuXML;
if (!getEmbeddedWorkUnitXML(querySo, wuXML))
throw MakeStringException(0, "Failed to locate workunit info in query : %s", querySo->queryName());
Owned<ILocalWorkUnit> localWU = createLocalWorkUnit(wuXML);
Owned<IConstWUGraph> graph = localWU->getGraph(graphName);
graphXGMML.setown(graph->getXGMMLTree(false));
if (!graphXGMML)
throwUnexpected();
}
void CJobBase::init()
{
StringBuffer tmp;
tmp.append(wuid);
tmp.append(graphName);
key.set(tmp.str());
StringBuffer user;
extractFromWorkunitDAToken(token.str(), nullptr, &user, nullptr);
userDesc = createUserDescriptor();
userDesc->set(user.str(), token.str());//use workunit token as password
forceLogGraphIdMin = (graph_id)getWorkUnitValueInt("forceLogGraphIdMin", 0);
forceLogGraphIdMax = (graph_id)getWorkUnitValueInt("forceLogGraphIdMax", 0);
logctx.setown(new CThorContextLogger(*this));
// global setting default on, can be overridden by #option
timeActivities = 0 != getWorkUnitValueInt("timeActivities", globals->getPropBool("@timeActivities", true));
maxActivityCores = (unsigned)getWorkUnitValueInt("maxActivityCores", 0); // NB: 0 means system decides
if (0 == maxActivityCores)
maxActivityCores = getAffinityCpus();
pausing = false;
resumed = false;
crcChecking = 0 != getWorkUnitValueInt("THOR_ROWCRC", globals->getPropBool("@THOR_ROWCRC", false));
usePackedAllocator = 0 != getWorkUnitValueInt("THOR_PACKEDALLOCATOR", globals->getPropBool("@THOR_PACKEDALLOCATOR", true));
memorySpillAtPercentage = (unsigned)getWorkUnitValueInt("memorySpillAt", globals->getPropInt("@memorySpillAt", 80));
sharedMemoryLimitPercentage = (unsigned)getWorkUnitValueInt("globalMemoryLimitPC", globals->getPropInt("@sharedMemoryLimit", 90));
sharedMemoryMB = globalMemoryMB*sharedMemoryLimitPercentage/100;
failOnLeaks = getOptBool("failOnLeaks");
maxLfnBlockTimeMins = getOptInt(THOROPT_MAXLFN_BLOCKTIME_MINS, DEFAULT_MAXLFN_BLOCKTIME_MINS);
PROGLOG("Global memory size = %d MB, shared memory = %d%%, memory spill at = %d%%", globalMemoryMB, sharedMemoryLimitPercentage, memorySpillAtPercentage);
StringBuffer tracing("maxActivityCores = ");
if (maxActivityCores)
tracing.append(maxActivityCores);
else
tracing.append("[unbound]");
PROGLOG("%s", tracing.str());
}
void CJobBase::beforeDispose()
{
endJob();
}
CJobChannel &CJobBase::queryJobChannel(unsigned c) const
{
return jobChannels.item(c);
}
CActivityBase &CJobBase::queryChannelActivity(unsigned c, graph_id gid, activity_id id) const
{
CJobChannel &channel = queryJobChannel(c);
Owned<CGraphBase> graph = channel.getGraph(gid);
dbgassertex(graph);
CGraphElementBase *container = graph->queryElement(id);
dbgassertex(container);
return *container->queryActivity();
}
void CJobBase::startJob()
{
LOG(MCdebugProgress, thorJob, "New Graph started : %s", graphName.get());
ClearTempDirs();
perfmonhook.setown(createThorMemStatsPerfMonHook(*this, getOptInt(THOROPT_MAX_KERNLOG, 3)));
setPerformanceMonitorHook(perfmonhook);
PrintMemoryStatusLog();
logDiskSpace();
unsigned keyNodeCacheMB = (unsigned)getWorkUnitValueInt("keyNodeCacheMB", DEFAULT_KEYNODECACHEMB * queryJobChannels());
unsigned keyLeafCacheMB = (unsigned)getWorkUnitValueInt("keyLeafCacheMB", DEFAULT_KEYLEAFCACHEMB * queryJobChannels());
unsigned keyBlobCacheMB = (unsigned)getWorkUnitValueInt("keyBlobCacheMB", DEFAULT_KEYBLOBCACHEMB * queryJobChannels());
setNodeCacheMem(keyNodeCacheMB * 0x100000);
setLeafCacheMem(keyLeafCacheMB * 0x100000);
setBlobCacheMem(keyBlobCacheMB * 0x100000);
PROGLOG("Key node caching setting: node=%u MB, leaf=%u MB, blob=%u MB", keyNodeCacheMB, keyLeafCacheMB, keyBlobCacheMB);
unsigned keyFileCacheLimit = (unsigned)getWorkUnitValueInt("keyFileCacheLimit", 0);
if (!keyFileCacheLimit)
keyFileCacheLimit = (querySlaves()+1)*2;
setKeyIndexCacheSize(keyFileCacheLimit);
PROGLOG("Key file cache size set to: %d", keyFileCacheLimit);
if (getOptBool("dumpStacks")) // mainly as an example of printAllStacks() usage
{
StringBuffer output;
if (getAllStacks(output))
PrintLogDirect(output);
else
WARNLOG("Failed to capture process stacks: %s", output.str());
}
}
void CJobBase::endJob()
{
if (jobEnded)
return;
jobEnded = true;
setPerformanceMonitorHook(nullptr);
LOG(MCdebugProgress, thorJob, "Job ended : %s", graphName.get());
clearKeyStoreCache(true);
PrintMemoryStatusLog();
Owned<IMultiException> exceptions;
ForEachItemIn(c, jobChannels)
{
try
{
jobChannels.item(c).clean();
}
catch (IException *e)
{
if (!exceptions)
exceptions.setown(makeMultiException());
exceptions->append(*LINK(e));
}
}
try
{
jobChannels.kill(); // avoiding circular references. Kill before other CJobBase components are destroyed that channels reference.
::Release(userDesc);
::Release(pluginMap);
traceMemUsage();
if (numChannels > 1) // if only 1 - then channel allocator is same as sharedAllocator, leaks will be reported by the single channel
checkAndReportLeaks(sharedAllocator->queryRowManager());
}
catch (IException *e)
{
if (!exceptions)
exceptions.setown(makeMultiException());
exceptions->append(*LINK(e));
}
if (exceptions && exceptions->ordinality())
throw exceptions.getClear();
}
void CJobBase::checkAndReportLeaks(roxiemem::IRowManager *rowManager)
{
if (!failOnLeaks) // NB: leaks reported by row manager destructor anyway
return;
if (rowManager->allocated())
{
rowManager->reportLeaks();
throw MakeThorException(TE_RowLeaksDetected, "Row leaks detected");
}
}
bool CJobBase::queryForceLogging(graph_id graphId, bool def) const
{
// JCSMORE, could add comma separated range, e.g. 1-5,10-12
if ((graphId >= forceLogGraphIdMin) && (graphId <= forceLogGraphIdMax))
return true;
return def;
}
void CJobBase::addSubGraph(IPropertyTree &xgmml)
{
CriticalBlock b(crit);
for (unsigned c=0; c<queryJobChannels(); c++)
{
CJobChannel &jobChannel = queryJobChannel(c);
Owned<CGraphBase> subGraph = jobChannel.createGraph();
subGraph->createFromXGMML(&xgmml, NULL, NULL, NULL, jobChannel.queryAllGraphs());
jobChannel.addSubGraph(*subGraph.getClear());
}
}
void CJobBase::addDependencies(IPropertyTree *xgmml, bool failIfMissing)
{
for (unsigned c=0; c<queryJobChannels(); c++)
{
CJobChannel &jobChannel = queryJobChannel(c);
jobChannel.addDependencies(xgmml, failIfMissing);
}
}
bool CJobBase::queryUseCheckpoints() const
{
return globals->getPropBool("@checkPointRecovery") || 0 != getWorkUnitValueInt("checkPointRecovery", 0);
}
void CJobBase::abort(IException *e)
{
aborted = true;
for (unsigned c=0; c<queryJobChannels(); c++)
{
CJobChannel &jobChannel = queryJobChannel(c);
jobChannel.abort(e);
}
}
void CJobBase::increase(offset_t usage, const char *key)
{
diskUsage += usage;
if (diskUsage > maxDiskUsage) maxDiskUsage = diskUsage;
}
void CJobBase::decrease(offset_t usage, const char *key)
{
diskUsage -= usage;
}
// these getX methods for property in workunit settings, then global setting, defaulting to provided 'dft' if not present
StringBuffer &CJobBase::getOpt(const char *opt, StringBuffer &out)
{
if (!opt || !*opt)
return out; // probably error
VStringBuffer gOpt("Debug/@%s", opt);
getWorkUnitValue(opt, out);
if (0 == out.length())
globals->getProp(gOpt, out);
return out;
}
bool CJobBase::getOptBool(const char *opt, bool dft)
{
if (!opt || !*opt)
return dft; // probably error
VStringBuffer gOpt("Debug/@%s", opt);
return getWorkUnitValueBool(opt, globals->getPropBool(gOpt, dft));
}
int CJobBase::getOptInt(const char *opt, int dft)
{
if (!opt || !*opt)
return dft; // probably error
VStringBuffer gOpt("Debug/@%s", opt);
return (int)getWorkUnitValueInt(opt, globals->getPropInt(gOpt, dft));
}
__int64 CJobBase::getOptInt64(const char *opt, __int64 dft)
{
if (!opt || !*opt)
return dft; // probably error
VStringBuffer gOpt("Debug/@%s", opt);
return getWorkUnitValueInt(opt, globals->getPropInt64(gOpt, dft));
}
IThorAllocator *CJobBase::getThorAllocator(unsigned channel)
{
return sharedAllocator.getLink();
}
/// CJobChannel
CJobChannel::CJobChannel(CJobBase &_job, IMPServer *_mpServer, unsigned _channel)
: job(_job), mpServer(_mpServer), channel(_channel)
{
aborted = false;
thorAllocator.setown(job.getThorAllocator(channel));
jobComm.setown(mpServer->createCommunicator(&job.queryJobGroup()));
myrank = job.queryJobGroup().rank(queryMyNode());
graphExecutor.setown(new CGraphExecutor(*this));
}
CJobChannel::~CJobChannel()
{
if (!cleaned)
clean();
}
INode *CJobChannel::queryMyNode()
{
return mpServer->queryMyNode();
}
void CJobChannel::wait()
{
if (graphExecutor)
graphExecutor->wait();
}
ICodeContext &CJobChannel::queryCodeContext() const
{
return *codeCtx;
}
ICodeContext &CJobChannel::querySharedMemCodeContext() const
{
return *sharedMemCodeCtx;
}
mptag_t CJobChannel::deserializeMPTag(MemoryBuffer &mb)
{
mptag_t tag;
deserializeMPtag(mb, tag);
if (TAG_NULL != tag)
{
PROGLOG("deserializeMPTag: tag = %d", (int)tag);
jobComm->flush(tag);
}
return tag;
}
IEngineRowAllocator *CJobChannel::getRowAllocator(IOutputMetaData * meta, activity_id activityId, roxiemem::RoxieHeapFlags flags) const
{
return thorAllocator->getRowAllocator(meta, activityId, flags);
}
roxiemem::IRowManager *CJobChannel::queryRowManager() const
{
return thorAllocator->queryRowManager();
}
void CJobChannel::addDependencies(IPropertyTree *xgmml, bool failIfMissing)
{
::addDependencies(xgmml, failIfMissing, allGraphs);
}
IThorGraphIterator *CJobChannel::getSubGraphs()
{
CriticalBlock b(crit);
return new CGraphTableIterator(subGraphs);
}
void CJobChannel::clean()
{
if (cleaned)
return;
cleaned = true;
wait();
queryRowManager()->reportMemoryUsage(false);
PROGLOG("CJobBase resetting memory manager");
if (graphExecutor)
{
graphExecutor->queryGraphPool().stopAll();
graphExecutor.clear();
}
subGraphs.kill();
job.checkAndReportLeaks(thorAllocator->queryRowManager());
thorAllocator.clear();
codeCtx.clear();
}
void CJobChannel::startGraph(CGraphBase &graph, bool checkDependencies, size32_t parentExtractSize, const byte *parentExtract)
{
graphExecutor->add(&graph, *this, checkDependencies, parentExtractSize, parentExtract);
}
IThorResult *CJobChannel::getOwnedResult(graph_id gid, activity_id ownerId, unsigned resultId)
{
Owned<CGraphBase> graph = getGraph(gid);
if (!graph)
{
Owned<IThorException> e = MakeThorException(0, "getOwnedResult: graph not found");
e->setGraphInfo(queryJob().queryGraphName(), gid);
throw e.getClear();
}
Owned<IThorResult> result;
if (ownerId)
{
CGraphElementBase *container = graph->queryElement(ownerId);
assertex(container);
CActivityBase *activity = container->queryActivity();
IThorGraphResults *results = activity->queryResults();
if (!results)
throw MakeGraphException(graph, 0, "GraphGetResult: no results created (requesting: %d)", resultId);
result.setown(activity->queryResults()->getResult(resultId));
}
else
result.setown(graph->getResult(resultId));
if (!result)
throw MakeGraphException(graph, 0, "GraphGetResult: result not found: %d", resultId);
return result.getClear();
}
void CJobChannel::abort(IException *e)
{
aborted = true;
Owned<IThorGraphIterator> iter = getSubGraphs();
ForEach (*iter)
{
CGraphBase &graph = iter->query();
graph.abort(e);
}
}
// IGraphCallback
void CJobChannel::runSubgraph(CGraphBase &graph, size32_t parentExtractSz, const byte *parentExtract)
{
graph.executeSubGraph(parentExtractSz, parentExtract);
}
static IThorResource *iThorResource = NULL;
void setIThorResource(IThorResource &r)
{
iThorResource = &r;
}
IThorResource &queryThor()
{
return *iThorResource;
}
//
//
//
//
CActivityBase::CActivityBase(CGraphElementBase *_container) : container(*_container), timeActivities(_container->queryJob().queryTimeActivities())
{
mpTag = TAG_NULL;
abortSoon = receiving = cancelledReceive = initialized = reInit = false;
baseHelper.set(container.queryHelper());
parentExtractSz = 0;
parentExtract = NULL;
}
CActivityBase::~CActivityBase()
{
}
void CActivityBase::abort()
{
if (!abortSoon) ActPrintLog("Abort condition set");
abortSoon = true;
}
void CActivityBase::kill()
{
ownedResults.clear();
}
bool CActivityBase::appendRowXml(StringBuffer & target, IOutputMetaData & meta, const void * row) const
{
if (!meta.hasXML())
{
target.append("<xml-unavailable/>");
return false;
}
try
{
CommonXmlWriter xmlWrite(XWFnoindent);
meta.toXML((byte *) row, xmlWrite);
target.append(xmlWrite.str());
return true;
}
catch (IException * e)
{
e->Release();
target.append("<invalid-row/>");
return false;
}
}
void CActivityBase::logRow(const char * prefix, IOutputMetaData & meta, const void * row) const
{
bool blindLogging = false; // MORE: should check a workunit/global option
if (meta.hasXML() && !blindLogging)
{
StringBuffer xml;
appendRowXml(xml, meta, row);
ActPrintLog("%s: %s", prefix, xml.str());
}
}
void CActivityBase::ActPrintLog(const char *format, ...) const
{
va_list args;
va_start(args, format);
::ActPrintLogArgs(&queryContainer(), thorlog_null, MCdebugProgress, format, args);
va_end(args);
}
void CActivityBase::ActPrintLog(IException *e, const char *format, ...) const
{
va_list args;
va_start(args, format);
::ActPrintLogArgs(&queryContainer(), e, thorlog_all, MCexception(e), format, args);
va_end(args);
}
void CActivityBase::ActPrintLog(IException *e) const
{
ActPrintLog(e, "%s", "");
}
IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, byte seq)
{
activity_id id = createCompoundActSeqId(queryId(), seq);
return createThorRowInterfaces(queryRowManager(), meta, id, queryHeapFlags(), queryCodeContext());
}
IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, roxiemem::RoxieHeapFlags heapFlags, byte seq)
{
activity_id id = createCompoundActSeqId(queryId(), seq);
return createThorRowInterfaces(queryRowManager(), meta, id, heapFlags, queryCodeContext());
}
bool CActivityBase::fireException(IException *e)
{
Owned<IThorException> _te;
IThorException *te = QUERYINTERFACE(e, IThorException);
if (te)
{
if (!te->queryActivityId())
setExceptionActivityInfo(container, te);
}
else
{
te = MakeActivityException(this, e);
te->setAudience(e->errorAudience());
_te.setown(te);
}
return container.queryOwner().fireException(te);
}
void CActivityBase::processAndThrowOwnedException(IException * _e)
{
IThorException *e = QUERYINTERFACE(_e, IThorException);
if (e)
{
if (!e->queryActivityId())
setExceptionActivityInfo(container, e);
}
else
{
e = MakeActivityException(this, _e);
_e->Release();
}
throw e;
}
IEngineRowAllocator * CActivityBase::queryRowAllocator()
{
if (CABallocatorlock.lock()) {
if (!rowAllocator)
{
roxiemem::RoxieHeapFlags heapFlags = queryHeapFlags();
rowAllocator.setown(getRowAllocator(queryRowMetaData(), heapFlags));
}
CABallocatorlock.unlock();
}
return rowAllocator;
}
IOutputRowSerializer * CActivityBase::queryRowSerializer()
{
if (CABserializerlock.lock()) {
if (!rowSerializer)
rowSerializer.setown(queryRowMetaData()->createDiskSerializer(queryCodeContext(),queryId()));
CABserializerlock.unlock();
}
return rowSerializer;
}
IOutputRowDeserializer * CActivityBase::queryRowDeserializer()
{
if (CABdeserializerlock.lock()) {
if (!rowDeserializer)
rowDeserializer.setown(queryRowMetaData()->createDiskDeserializer(queryCodeContext(),queryId()));
CABdeserializerlock.unlock();
}
return rowDeserializer;
}
IThorRowInterfaces *CActivityBase::getRowInterfaces()
{
// create an independent instance, to avoid circular link dependency problems
return createThorRowInterfaces(queryRowManager(), queryRowMetaData(), container.queryId(), queryHeapFlags(), queryCodeContext());
}
IEngineRowAllocator *CActivityBase::getRowAllocator(IOutputMetaData * meta, roxiemem::RoxieHeapFlags flags, byte seq) const
{
activity_id actId = createCompoundActSeqId(queryId(), seq);
return queryJobChannel().getRowAllocator(meta, actId, flags);
}
bool CActivityBase::receiveMsg(ICommunicator &comm, CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout)
{
BooleanOnOff onOff(receiving);
CTimeMon t(timeout);
unsigned remaining = timeout;
// check 'cancelledReceive' every 10 secs
while (!cancelledReceive && ((MP_WAIT_FOREVER==timeout) || !t.timedout(&remaining)))
{
if (comm.recv(mb, rank, mpTag, sender, remaining>10000?10000:remaining))
return true;
}
return false;
}
bool CActivityBase::receiveMsg(CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout)
{
return receiveMsg(queryJobChannel().queryJobComm(), mb, rank, mpTag, sender, timeout);
}
void CActivityBase::cancelReceiveMsg(ICommunicator &comm, const rank_t rank, const mptag_t mpTag)
{
cancelledReceive = true;
if (receiving)
comm.cancel(rank, mpTag);
}
void CActivityBase::cancelReceiveMsg(const rank_t rank, const mptag_t mpTag)
{
cancelReceiveMsg(queryJobChannel().queryJobComm(), rank, mpTag);
}
| 32.951295 | 221 | 0.617172 | roscoche |
33f74ccc3b216a435803e2b9423c0caf6b88825e | 56,981 | cpp | C++ | src/ARIA/ariaUtil.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | 1 | 2018-10-13T02:50:25.000Z | 2018-10-13T02:50:25.000Z | src/ARIA/ariaUtil.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | null | null | null | src/ARIA/ariaUtil.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | 1 | 2018-10-13T02:50:26.000Z | 2018-10-13T02:50:26.000Z | /*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
Copyright (C) 2010, 2011 Adept Technology, Inc.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
#define _GNU_SOURCE 1 // for isnormal() and other newer (non-ansi) C functions
#include "ArExport.h"
#include "ariaOSDef.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#ifdef WIN32
#include <windows.h> // for timeGetTime() and mmsystem.h
#include <mmsystem.h> // for timeGetTime()
#else
#include <sys/time.h>
#include <stdarg.h>
#include <unistd.h>
#include <utime.h>
#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#endif
#include "ariaInternal.h"
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#ifndef ARINTERFACE
#include "ArSick.h"
#include "ArUrg.h"
#include "ArLMS1XX.h"
#include "ArUrg_2_0.h"
#endif // ARINTERFACE
#include "ArSerialConnection.h"
#include "ArTcpConnection.h"
#ifdef WIN32
#include <io.h>
AREXPORT const char *ArUtil::COM1 = "COM1";
AREXPORT const char *ArUtil::COM2 = "COM2";
AREXPORT const char *ArUtil::COM3 = "COM3";
AREXPORT const char *ArUtil::COM4 = "COM4";
AREXPORT const char *ArUtil::COM5 = "COM5";
AREXPORT const char *ArUtil::COM6 = "COM6";
AREXPORT const char *ArUtil::COM7 = "COM7";
AREXPORT const char *ArUtil::COM8 = "COM8";
AREXPORT const char *ArUtil::COM9 = "COM9";
AREXPORT const char *ArUtil::COM10 = "COM10";
AREXPORT const char *ArUtil::COM11 = "COM11";
AREXPORT const char *ArUtil::COM12 = "COM12";
AREXPORT const char *ArUtil::COM13 = "COM13";
AREXPORT const char *ArUtil::COM14 = "COM14";
AREXPORT const char *ArUtil::COM15 = "COM15";
AREXPORT const char *ArUtil::COM16 = "COM16";
#else // ifndef WIN32
AREXPORT const char *ArUtil::COM1 = "/dev/ttyS0";
AREXPORT const char *ArUtil::COM2 = "/dev/ttyS1";
AREXPORT const char *ArUtil::COM3 = "/dev/ttyS2";
AREXPORT const char *ArUtil::COM4 = "/dev/ttyS3";
AREXPORT const char *ArUtil::COM5 = "/dev/ttyS4";
AREXPORT const char *ArUtil::COM6 = "/dev/ttyS5";
AREXPORT const char *ArUtil::COM7 = "/dev/ttyS6";
AREXPORT const char *ArUtil::COM8 = "/dev/ttyS7";
AREXPORT const char *ArUtil::COM9 = "/dev/ttyS8";
AREXPORT const char *ArUtil::COM10 = "/dev/ttyS9";
AREXPORT const char *ArUtil::COM11 = "/dev/ttyS10";
AREXPORT const char *ArUtil::COM12 = "/dev/ttyS11";
AREXPORT const char *ArUtil::COM13 = "/dev/ttyS12";
AREXPORT const char *ArUtil::COM14 = "/dev/ttyS13";
AREXPORT const char *ArUtil::COM15 = "/dev/ttyS14";
AREXPORT const char *ArUtil::COM16 = "/dev/ttyS15";
#endif // WIN32
AREXPORT const char *ArUtil::TRUESTRING = "true";
AREXPORT const char *ArUtil::FALSESTRING = "false";
// const double eps = std::numeric_limits<double>::epsilon();
const double ArMath::ourEpsilon = 0.00000001;
#ifdef WIN32
// max returned by rand()
const long ArMath::ourRandMax = RAND_MAX;
#else
// max returned by lrand48()
const long ArMath::ourRandMax = 2147483648;// 2^31, per lrand48 man page
#endif
#ifdef WIN32
const char ArUtil::SEPARATOR_CHAR = '\\';
const char *ArUtil::SEPARATOR_STRING = "\\";
const char ArUtil::OTHER_SEPARATOR_CHAR = '/';
#else
const char ArUtil::SEPARATOR_CHAR = '/';
const char *ArUtil::SEPARATOR_STRING = "/";
const char ArUtil::OTHER_SEPARATOR_CHAR = '\\';
#endif
#ifdef WIN32
ArMutex ArUtil::ourLocaltimeMutex;
#endif
/**
This sleeps for the given number of milliseconds... Note in linux it
tries to sleep for 10 ms less than the amount given, which should wind up
close to correct...
Linux is broken in this regard and sleeps for too long...
it sleeps for the ceiling of the current 10 ms range,
then for an additional 10 ms... so:
11 to 20 ms sleeps for 30 ms...
21 to 30 ms sleeps for 40 ms...
31 to 40 ms sleeps for 50 ms...
this continues on up to the values we care about of..
81 to 90 ms sleeps for 100 ms...
91 to 100 ms sleeps for 110 ms...
so we'll sleep for 10 ms less than we want to, which should put us about
right... guh
@param ms the number of milliseconds to sleep for
*/
AREXPORT void ArUtil::sleep(unsigned int ms)
{
#ifdef WIN32
Sleep(ms);
#else // ifndef win32
if (ms > 10)
ms -= 10;
usleep(ms * 1000);
#endif // linux
}
/**
Get the time in milliseconds, counting from some arbitrary point.
This time is only valid within this run of the program.
@return millisecond time
*/
AREXPORT unsigned int ArUtil::getTime(void)
{
// the good unix way
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
struct timespec tp;
if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
return tp.tv_nsec / 1000000 + (tp.tv_sec % 1000000)*1000;
// the old unix way as a fallback
#endif // if it isn't the good way
#if !defined(WIN32)
struct timeval tv;
if (gettimeofday(&tv,NULL) == 0)
return tv.tv_usec/1000 + (tv.tv_sec % 1000000)*1000;//windows
else
return 0;
#elif defined(WIN32)
return timeGetTime();
#endif
}
/*
Takes a string and splits it into a list of words. It appends the words
to the outList. If there is nothing found, it will not touch the outList.
@param inString the input string to split
@param outList the list in which to store the words that are found
*/
/*
AREXPORT void ArUtil::splitString(std::string inString,
std::list<std::string> &outList)
{
const char *start, *end;
// Strip off leading white space
for (end=inString.c_str(); *end && isspace(*end); ++end)
;
while (*end)
{
// Mark start of the word then find end
for (start=end; *end && !isspace(*end); ++end)
;
// Store the word
if (*start && ((*end && isspace(*end)) || !*end))
outList.push_back(std::string(start, (int)(end-start)));
for (; *end && isspace(*end); ++end)
;
}
}
*/
#ifdef WIN32
/**
@return size in bytes. -1 on error.
@param fileName name of the file to size
*/
AREXPORT long ArUtil::sizeFile(std::string fileName)
{
struct _stat buf;
if (_stat(fileName.c_str(), &buf) < 0)
return(-1);
if (!(buf.st_mode | _S_IFREG))
return(-1);
return(buf.st_size);
}
/**
@return size in bytes. -1 on error.
@param fileName name of the file to size
*/
AREXPORT long ArUtil::sizeFile(const char * fileName)
{
struct _stat buf;
if (_stat(fileName, &buf) < 0)
return(-1);
if (!(buf.st_mode | _S_IFREG))
return(-1);
return(buf.st_size);
}
#else // !WIN32
AREXPORT long ArUtil::sizeFile(std::string fileName)
{
struct stat buf;
if (stat(fileName.c_str(), &buf) < 0)
{
ArLog::logErrorFromOS(ArLog::Normal, "ArUtil::sizeFile: stat failed");
return(-1);
}
if (!S_ISREG(buf.st_mode))
return(-1);
return(buf.st_size);
}
/**
@return size in bytes. -1 on error.
@param fileName name of the file to size
*/
AREXPORT long ArUtil::sizeFile(const char * fileName)
{
struct stat buf;
if (stat(fileName, &buf) < 0)
{
ArLog::logErrorFromOS(ArLog::Normal, "ArUtil::sizeFile: stat failed");
return(-1);
}
if (!S_ISREG(buf.st_mode))
return(-1);
return(buf.st_size);
}
#endif // else !WIN32
/**
@return true if file is found
@param fileName name of the file to size
*/
AREXPORT bool ArUtil::findFile(const char *fileName)
{
FILE *fp;
if ((fp=ArUtil::fopen(fileName, "r")))
{
fclose(fp);
return(true);
}
else
return(false);
}
/*
Works for \ and /. Returns true if something was actualy done. Sets
fileOut to be what ever the answer is.
@return true if the path contains a file
@param fileIn input path/fileName
@param fileOut output fileName
*/
/*AREXPORT bool ArUtil::stripDir(std::string fileIn, std::string &fileOut)
{
const char *ptr;
for (ptr=fileIn.c_str(); *ptr; ++ptr)
;
for (--ptr; (ptr > fileIn.c_str()) && (*ptr != '/') && (*ptr != '\\'); --ptr)
;
if ((*ptr == '/') || (*ptr == '\\'))
{
fileOut=ptr+1;
return(true);
}
else
{
fileOut=fileIn;
return(false);
}
}
*/
/*
Works for \ and /. Returns true if something was actualy done. Sets
fileOut to be what ever the answer is.
@return true if the file contains a path
@param fileIn input path/fileName
@param fileOut output path
*/
/*
AREXPORT bool ArUtil::stripFile(std::string fileIn, std::string &fileOut)
{
const char *start, *end;
for (start=end=fileIn.c_str(); *end; ++end)
{
if ((*end == '/') || (*end == '\\'))
{
start=end;
for (; *end && ((*end == '/') || (*end == '\\')); ++end)
;
}
}
if (start < end)
{
fileOut.assign(fileIn, 0, start-fileIn.c_str());
return(true);
}
fileOut=fileIn;
return(false);
}
*/
AREXPORT bool ArUtil::stripQuotes(char *dest, const char *src, size_t destLen)
{
size_t srcLen = strlen(src);
if (destLen < srcLen + 1)
{
ArLog::log(ArLog::Normal, "ArUtil::stripQuotes: destLen isn't long enough to fit copy its %d should be %d", destLen, srcLen + 1);
return false;
}
// if there are no quotes to strip just copy and return
if (srcLen < 2 ||
(src[0] != '"' || src[srcLen - 1] != '"'))
{
strcpy(dest, src);
return true;
}
// we have quotes so chop of the first and last char
strncpy(dest, &src[1], srcLen - 1);
dest[srcLen - 2] = '\0';
return true;
}
/** Append a directory separator character to the given path string, depending on the
* platform. On Windows, a backslash ('\\') is added. On other platforms, a
* forward slash ('/') is appended. If there is no more allocated space in the
* path string, no character will be appended.
@param path the path string to append a slash to
@param pathLength maximum length allocated for path string
*/
AREXPORT void ArUtil::appendSlash(char *path, size_t pathLength)
{
// first check boundary
size_t len;
len = strlen(path);
if (len > pathLength - 2)
return;
if (len == 0 || (path[len - 1] != '\\' && path[len - 1] != '/'))
{
#ifdef WIN32
path[len] = '\\';
#else
path[len] = '/';
#endif
path[len + 1] = '\0';
}
}
AREXPORT void ArUtil::appendSlash(std::string &path)
{
// first check boundary
size_t len = path.length();
if ((len == 0) ||
(path[len - 1] != SEPARATOR_CHAR && path[len - 1] != OTHER_SEPARATOR_CHAR)) {
path += SEPARATOR_STRING;
}
} // end method appendSlash
/**
@param path the path in which to fix the orientation of the slashes
@param pathLength the maximum length of path
*/
AREXPORT void ArUtil::fixSlashes(char *path, size_t pathLength)
{
#ifdef WIN32
fixSlashesBackward(path, pathLength);
#else
fixSlashesForward(path, pathLength);
#endif
}
/**
@param path the path in which to fix the orientation of the slashes
@param pathLength how long that path is at max
*/
AREXPORT void ArUtil::fixSlashesBackward(char *path, size_t pathLength)
{
for (size_t i=0; path[i] != '\0' && i < pathLength; i++)
{
if (path[i] == '/')
path[i]='\\';
}
}
/**
@param path the path in which to fix the orientation of the slashes
@param pathLength how long that path is at max
*/
AREXPORT void ArUtil::fixSlashesForward(char *path, size_t pathLength)
{
for (size_t i=0; path[i] != '\0' && i < pathLength; i++)
{
if (path[i] == '\\')
path[i]='/';
}
}
/**
@param path the path in which to fix the orientation of the slashes
*/
AREXPORT void ArUtil::fixSlashes(std::string &path)
{
for (size_t i = 0; i < path.length(); i++)
{
if (path[i] == OTHER_SEPARATOR_CHAR)
path[i]= SEPARATOR_CHAR;
}
}
AREXPORT char ArUtil::getSlash()
{
return SEPARATOR_CHAR;
}
/**
This function will take the 'baseDir' and put the 'insideDir' after
it so that it winds up with 'baseDir/insideDir/'. It will take
care of slashes, making sure there is one between them and one at
the end, and the slashes will match what the operating system
expects.
@param dest the place to put the result
@param destLength the length of the place to put the results
@param baseDir the directory to start with
@param insideDir the directory to place after the baseDir
**/
AREXPORT void ArUtil::addDirectories(char *dest, size_t destLength,
const char *baseDir,
const char *insideDir)
{
// start it off
strncpy(dest, baseDir, destLength - 1);
// make sure we have a null term
dest[destLength - 1] = '\0';
// toss on that slash
appendSlash(dest, destLength);
// put on the inside dir
strncat(dest, insideDir, destLength - strlen(dest) - 1);
// now toss on that slash
appendSlash(dest, destLength);
// and now fix up all the slashes
fixSlashes(dest, destLength);
}
/**
This compares two strings, it returns an integer less than, equal to,
or greater than zero if str is found, respectively, to be less than, to
match, or be greater than str2.
@param str the string to compare
@param str2 the second string to compare
@return an integer less than, equal to, or greater than zero if str is
found, respectively, to be less than, to match, or be greater than str2.
*/
AREXPORT int ArUtil::strcmp(std::string str, std::string str2)
{
return ::strcmp(str.c_str(), str2.c_str());
}
/**
This compares two strings, it returns an integer less than, equal to,
or greater than zero if str is found, respectively, to be less than, to
match, or be greater than str2.
@param str the string to compare
@param str2 the second string to compare
@return an integer less than, equal to, or greater than zero if str is
found, respectively, to be less than, to match, or be greater than str2.
*/
AREXPORT int ArUtil::strcmp(std::string str, const char *str2)
{
return ::strcmp(str.c_str(), str2);
}
/**
This compares two strings, it returns an integer less than, equal to,
or greater than zero if str is found, respectively, to be less than, to
match, or be greater than str2.
@param str the string to compare
@param str2 the second string to compare
@return an integer less than, equal to, or greater than zero if str is
found, respectively, to be less than, to match, or be greater than str2.
*/
AREXPORT int ArUtil::strcmp(const char *str, std::string str2)
{
return ::strcmp(str, str2.c_str());
}
/**
This compares two strings, it returns an integer less than, equal to,
or greater than zero if str is found, respectively, to be less than, to
match, or be greater than str2.
@param str the string to compare
@param str2 the second string to compare
@return an integer less than, equal to, or greater than zero if str is
found, respectively, to be less than, to match, or be greater than str2.
*/
AREXPORT int ArUtil::strcmp(const char *str, const char *str2)
{
return ::strcmp(str, str2);
}
/**
This compares two strings ignoring case, it returns an integer
less than, equal to, or greater than zero if str is found,
respectively, to be less than, to match, or be greater than str2.
@param str the string to compare @param str2 the second string to
compare @return an integer less than, equal to, or greater than
zero if str is found, respectively, to be less than, to match, or
be greater than str2. */
AREXPORT int ArUtil::strcasecmp(std::string str, std::string str2)
{
return ::strcasecmp(str.c_str(), str2.c_str());
}
/**
This compares two strings ignoring case, it returns an integer
less than, equal to, or greater than zero if str is found,
respectively, to be less than, to match, or be greater than str2.
@param str the string to compare @param str2 the second string to
compare @return an integer less than, equal to, or greater than
zero if str is found, respectively, to be less than, to match, or
be greater than str2. */
AREXPORT int ArUtil::strcasecmp(std::string str, const char *str2)
{
return ::strcasecmp(str.c_str(), str2);
}
/**
This compares two strings ignoring case, it returns an integer
less than, equal to, or greater than zero if str is found,
respectively, to be less than, to match, or be greater than str2.
@param str the string to compare @param str2 the second string to
compare @return an integer less than, equal to, or greater than
zero if str is found, respectively, to be less than, to match, or
be greater than str2. */
AREXPORT int ArUtil::strcasecmp(const char *str, std::string str2)
{
return ::strcasecmp(str, str2.c_str());
}
/**
This compares two strings ignoring case, it returns an integer
less than, equal to, or greater than zero if str is found,
respectively, to be less than, to match, or be greater than str2.
@param str the string to compare @param str2 the second string to
compare @return an integer less than, equal to, or greater than
zero if str is found, respectively, to be less than, to match, or
be greater than str2. */
AREXPORT int ArUtil::strcasecmp(const char *str, const char *str2)
{
return ::strcasecmp(str, str2);
}
AREXPORT int ArUtil::strcasequotecmp(const std::string &str1,
const std::string &str2)
{
int len1 = str1.length();
size_t pos1 = 0;
if ((len1 >= 2) && (str1[0] == '\"') && (str1[len1 - 1] == '\"')) {
pos1 = 1;
}
int len2 = str2.length();
size_t pos2 = 0;
if ((len2 >= 2) && (str2[0] == '\"') && (str2[len2 - 1] == '\"')) {
pos2 = 1;
}
/* Unfortunately gcc2 does't support the 5 argument version of std::string::compare()...
* (Furthermore, note that it's 3-argument compare has the arguments in the wrong order.)
*/
#if defined(__GNUC__) && (__GNUC__ <= 2) && (__GNUC_MINOR__ <= 96)
#warning Using GCC 2.96 or less so must use nonstandard std::string::compare method.
int cmp = str1.compare(str2.substr(pos2, len2 - 2 * pos2), pos1, len1 - 2 * pos1);
#else
int cmp = str1.compare(pos1,
len1 - 2 * pos1,
str2,
pos2,
len2 - 2 * pos2);
#endif
return cmp;
} // end method strcasequotecmp
/**
This copies src into dest but puts a \ before any spaces in src,
escaping them... its mostly for use with ArArgumentBuilder...
make sure you have at least maxLen spaces in the arrays that you're passing
as dest... this allocates no memory
**/
AREXPORT void ArUtil::escapeSpaces(char *dest, const char *src, size_t maxLen)
{
size_t i, adj, len;
len = strlen(src);
// walk it, when we find one toss in the slash and incr adj so the
// next characters go in the right space
for (i = 0, adj = 0; i < len && i + adj < maxLen; i++)
{
if (src[i] == ' ')
{
dest[i+adj] = '\\';
adj++;
}
dest[i+adj] = src[i];
}
// make sure its null terminated
dest[i+adj] = '\0';
}
/**
This copies src into dest but makes it lower case make sure you
have at least maxLen arrays that you're passing as dest... this
allocates no memory
**/
AREXPORT void ArUtil::lower(char *dest, const char *src, size_t maxLen)
{
size_t i;
size_t len;
len = strlen(src);
for (i = 0; i < len && i < maxLen; i++)
dest[i] = tolower(src[i]);
dest[i] = '\0';
}
AREXPORT bool ArUtil::isOnlyAlphaNumeric(const char *str)
{
unsigned int ui;
unsigned int len;
if (str == NULL)
return true;
for (ui = 0, len = strlen(str); ui < len; ui++)
{
if (!isalpha(str[ui]) && !isdigit(str[ui]) && str[ui] != '\0')
return false;
}
return true;
}
AREXPORT bool ArUtil::isOnlyNumeric(const char *str)
{
if (str == NULL)
return true;
for (unsigned i = 0, len = strlen(str); i < len; i++)
{
if (!isdigit(str[i]) && str[i] != '\0')
return false;
}
return true;
}
AREXPORT bool ArUtil::isStrEmpty(const char *str)
{
if (str == NULL) {
return true;
}
if (str[0] == '\0') {
return true;
}
return false;
} // end method isStrEmpty
AREXPORT bool ArUtil::isStrInList(const char *str,
const std::list<std::string> &list,
bool isIgnoreCase)
{
if (str == NULL) {
return false;
}
for (std::list<std::string>::const_iterator aIter = list.begin();
aIter != list.end();
aIter++) {
if (!isIgnoreCase) {
if (strcmp((*aIter).c_str(), str) == 0) {
return true;
}
}
else { // ignore case
if (strcasecmp((*aIter).c_str(), str) == 0) {
return true;
}
} // end else ignore case
} // end for each string
return false;
} // end method isStrInList
AREXPORT const char *ArUtil::convertBool(int val)
{
if (val)
return TRUESTRING;
else
return FALSESTRING;
}
AREXPORT double ArUtil::atof(const char *nptr)
{
if (strcasecmp(nptr, "inf") == 0)
return HUGE_VAL;
else if (strcasecmp(nptr, "-inf") == 0)
return -HUGE_VAL;
else
return ::atof(nptr);
}
AREXPORT void ArUtil::functorPrintf(ArFunctor1<const char *> *functor,
char *str, ...)
{
char buf[10000];
va_list ptr;
va_start(ptr, str);
//vsprintf(buf, str, ptr);
vsnprintf(buf, sizeof(buf) - 1, str, ptr);
buf[sizeof(buf) - 1] = '\0';
functor->invoke(buf);
va_end(ptr);
}
AREXPORT void ArUtil::writeToFile(const char *str, FILE *file)
{
fputs(str, file);
}
/**
This function reads a string from a file.
The file can contain spaces or tabs, but a '\\r'
or '\\n' will be treated as the end of the string, and the string
cannot have more characters than the value given by strLen. This is mostly for internal use
with Linux to determine the Aria directory from a file in /etc, but
will work with Linux or Windows.
@param fileName name of the file in which to look
@param str the string to copy the file contents into
@param strLen the maximum allocated length of str
**/
AREXPORT bool ArUtil::getStringFromFile(const char *fileName,
char *str, size_t strLen)
{
FILE *strFile;
unsigned int i;
str[0] = '\0';
if ((strFile = ArUtil::fopen(fileName, "r")) != NULL)
{
fgets(str, strLen, strFile);
for (i = 0; i < strLen; i++)
{
if (str[i] == '\r' || str[i] == '\n' || str[i] == '\0')
{
str[i] = '\0';
fclose(strFile);
break;
}
}
}
else
{
str[0] = '\0';
return false;
}
return true;
}
/**
* Look up the given value under the given key, within the given registry root
* key.
@param root the root key to use, one of the REGKEY enum values
@param key the name of the key to find
@param value the value name in which to find the string
@param str where to put the string found, or if it could not be
found, an empty (length() == 0) string
@param len the length of the allocated memory in str
@return true if the string was found, false if it was not found or if there was a problem such as the string not being long enough
**/
AREXPORT bool ArUtil::getStringFromRegistry(REGKEY root,
const char *key,
const char *value,
char *str,
int len)
{
#ifndef WIN32
return false;
#else // WIN32
HKEY hkey;
int err;
unsigned long numKeys;
unsigned long longestKey;
unsigned long numValues;
unsigned long longestValue;
unsigned long longestDataLength;
char *valueName;
unsigned long valueLength;
unsigned long type;
char *data;
unsigned long dataLength;
HKEY rootKey;
switch (root)
{
case REGKEY_CLASSES_ROOT:
rootKey = HKEY_CLASSES_ROOT;
break;
case REGKEY_CURRENT_CONFIG:
rootKey = HKEY_CURRENT_CONFIG;
break;
case REGKEY_CURRENT_USER:
rootKey = HKEY_CURRENT_USER;
break;
case REGKEY_LOCAL_MACHINE:
rootKey = HKEY_LOCAL_MACHINE;
break;
case REGKEY_USERS:
rootKey=HKEY_USERS;
break;
default:
ArLog::log(ArLog::Terse,
"ArUtil::getStringFromRegistry: Bad root key given.");
return false;
}
if ((err = RegOpenKeyEx(rootKey, key, 0, KEY_READ, &hkey)) == ERROR_SUCCESS)
{
//printf("Got a key\n");
if (RegQueryInfoKey(hkey, NULL, NULL, NULL, &numKeys, &longestKey, NULL,
&numValues, &longestValue, &longestDataLength, NULL, NULL) == ERROR_SUCCESS)
{
/*
printf("Have %d keys longest is %d, have %d values longest name is %d, longest data is %d\n",
numKeys, longestKey, numValues, longestValue, longestDataLength);
*/
data = new char[longestDataLength+2];
valueName = new char[longestValue+2];
for (unsigned long i = 0; i < numValues; ++i)
{
dataLength = longestDataLength+1;
valueLength = longestValue+1;
if ((err = RegEnumValue(hkey, i, valueName, &valueLength, NULL,
&type, (unsigned char *)data, &dataLength)) == ERROR_SUCCESS)
{
//printf("Enumed value %d, name is %s, value is %s\n", i, valueName, data);
if (strcmp(value, valueName) == 0)
{
if (len < dataLength)
{
ArLog::log(ArLog::Terse,"ArUtil::getStringFromRegistry: str passed in not long enough for data.");
delete data;
delete valueName;
return false;
}
strncpy(str, data, len);
delete data;
delete valueName;
return true;
}
}
/*
else
printf("Couldn't enum value %d cause %d\n",i, err);
*/
}
delete data;
delete valueName;
}
/*
else
printf("QueryInfoKey failed\n");
*/
}
/*
else
printf("No key %d\n", err);
*/
return false;
#endif
}
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
bool ArTime::ourMonotonicClock = true;
#endif
AREXPORT void ArTime::setToNow(void)
{
// if we have the best way of finding time use that
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
if (ourMonotonicClock)
{
struct timespec timeNow;
if (clock_gettime(CLOCK_MONOTONIC, &timeNow) == 0)
{
mySec = timeNow.tv_sec;
myMSec = timeNow.tv_nsec / 1000000;
return;
}
else
{
ourMonotonicClock = false;
ArLog::logNoLock(ArLog::Terse, "ArTime::setToNow: invalid return from clock_gettime.");
}
}
#endif
// if our good way didn't work use the old ways
#ifndef WIN32
struct timeval timeNow;
if (gettimeofday(&timeNow, NULL) == 0)
{
mySec = timeNow.tv_sec;
myMSec = timeNow.tv_usec / 1000;
}
else
ArLog::logNoLock(ArLog::Terse, "ArTime::setToNow: invalid return from gettimeofday.");
// thats probably not available in windows, so this is the one we've been using
#else
/* this should be the better way, but it doesn't really work...
this would be seconds from 1970, but it is based on the
hardware timer or something and so winds up not being updated
all the time and winds up being some number of ms < 20 ms off
struct _timeb startTime;
_ftime(&startTime);
mySec = startTime.time;
myMSec = startTime.millitm;*/
// so we're going with just their normal function, msec since boot
long timeNow;
timeNow = timeGetTime();
mySec = timeNow / 1000;
myMSec = timeNow % 1000;
// but if the good way isn't available use the old way...
#endif
}
AREXPORT ArRunningAverage::ArRunningAverage(size_t numToAverage)
{
myNumToAverage = numToAverage;
myTotal = 0;
myNum = 0;
myUseRootMeanSquare = false;
}
AREXPORT ArRunningAverage::~ArRunningAverage()
{
}
AREXPORT double ArRunningAverage::getAverage(void) const
{
if (myNum == 0)
return 0.0;
if (myUseRootMeanSquare)
return sqrt(myTotal / myNum);
else
return myTotal / myNum;
}
AREXPORT void ArRunningAverage::add(double val)
{
if (myUseRootMeanSquare)
myTotal += (val * val);
else
myTotal += val;
myNum++;
myVals.push_front(val);
if (myVals.size() > myNumToAverage || myNum > myNumToAverage)
{
if (myUseRootMeanSquare)
myTotal -= (myVals.back() * myVals.back());
else
myTotal -= myVals.back();
myNum--;
myVals.pop_back();
}
}
AREXPORT void ArRunningAverage::clear(void)
{
while (myVals.size() > 0)
myVals.pop_back();
myNum = 0;
myTotal = 0;
}
AREXPORT size_t ArRunningAverage::getNumToAverage(void) const
{
return myNumToAverage;
}
AREXPORT void ArRunningAverage::setNumToAverage(size_t numToAverage)
{
myNumToAverage = numToAverage;
while (myVals.size() > myNumToAverage)
{
if (myUseRootMeanSquare)
myTotal -= (myVals.back() * myVals.back());
else
myTotal -= myVals.back();
myNum--;
myVals.pop_back();
}
}
AREXPORT size_t ArRunningAverage::getCurrentNumAveraged(void)
{
return myNum;
}
AREXPORT void ArRunningAverage::setUseRootMeanSquare(bool useRootMeanSquare)
{
if (myUseRootMeanSquare != useRootMeanSquare)
{
myTotal = 0;
std::list<double>::iterator it;
for (it = myVals.begin(); it != myVals.end(); it++)
{
if (useRootMeanSquare)
myTotal += ((*it) * (*it));
else
myTotal += (*it);
}
}
myUseRootMeanSquare = useRootMeanSquare;
}
AREXPORT bool ArRunningAverage::getUseRootMeanSquare(void)
{
return myUseRootMeanSquare;
}
AREXPORT ArRootMeanSquareCalculator::ArRootMeanSquareCalculator()
{
clear();
myName = "ArRootMeanSquareCalculator";
}
AREXPORT ArRootMeanSquareCalculator::~ArRootMeanSquareCalculator()
{
}
AREXPORT double ArRootMeanSquareCalculator::getRootMeanSquare (void) const
{
if (myNum == 0)
return 0;
else
return sqrt((double) myTotal / (double)myNum);
}
AREXPORT void ArRootMeanSquareCalculator::add(int val)
{
myTotal += val * val;
myNum++;
if (myTotal < 0)
{
ArLog::log(ArLog::Normal, "%s: total wrapped, resetting", myName.c_str());
clear();
// this isn't a clean fix, but won't let it infinitely loop on a bad value
//add(val);
}
}
AREXPORT void ArRootMeanSquareCalculator::clear(void)
{
myTotal = 0;
myNum = 0;
}
AREXPORT size_t ArRootMeanSquareCalculator::getCurrentNumAveraged(void)
{
return myNum;
}
AREXPORT void ArRootMeanSquareCalculator::setName(const char *name)
{
if (name != NULL)
myName = name;
else
myName = "ArRootMeanSquareCalculator";
}
AREXPORT const char *ArRootMeanSquareCalculator::getName(void)
{
return myName.c_str();
}
#ifndef WIN32
AREXPORT ArDaemonizer::ArDaemonizer(int *argc, char **argv,
bool closeStdErrAndStdOut) :
myParser(argc, argv),
myLogOptionsCB(this, &ArDaemonizer::logOptions)
{
myIsDaemonized = false;
myCloseStdErrAndStdOut = closeStdErrAndStdOut;
Aria::addLogOptionsCB(&myLogOptionsCB);
}
AREXPORT ArDaemonizer::~ArDaemonizer()
{
}
AREXPORT bool ArDaemonizer::daemonize(void)
{
if (myParser.checkArgument("-daemonize") ||
myParser.checkArgument("-d"))
{
return forceDaemonize();
}
else
return true;
}
/**
This returns true if daemonizing worked, returns false if it
didn't... the parent process exits here if forking worked.
**/
AREXPORT bool ArDaemonizer::forceDaemonize(void)
{
switch (fork())
{
case 0: // child process just return
myIsDaemonized = true;
if (myCloseStdErrAndStdOut)
{
fclose(stdout);
fclose(stderr);
}
return true;
case -1: // error.... fail
printf("Can't fork");
ArLog::log(ArLog::Terse, "ArDaemonizer: Can't fork");
return false;
default: // parent process
printf("Daemon started\n");
exit(0);
}
}
AREXPORT void ArDaemonizer::logOptions(void) const
{
ArLog::log(ArLog::Terse, "Options for Daemonizing:");
ArLog::log(ArLog::Terse, "-daemonize");
ArLog::log(ArLog::Terse, "-d");
ArLog::log(ArLog::Terse, "");
}
#endif // WIN32
std::map<ArPriority::Priority, std::string> ArPriority::ourPriorityNames;
std::string ArPriority::ourUnknownPriorityName;
bool ArPriority::ourStringsInited = false;
AREXPORT const char *ArPriority::getPriorityName(Priority priority)
{
if (!ourStringsInited)
{
ourPriorityNames[IMPORTANT] = "Basic";
ourPriorityNames[NORMAL] = "Intermediate";
ourPriorityNames[TRIVIAL] = "Advanced";
ourPriorityNames[DETAILED] = "Advanced";
ourPriorityNames[EXPERT] = "Expert";
ourPriorityNames[FACTORY] = "Factory";
ourUnknownPriorityName = "Unknown";
ourStringsInited = true;
}
std::map<ArPriority::Priority, std::string>::iterator iter =
ourPriorityNames.find(priority);
if (iter != ourPriorityNames.end()) {
return iter->second.c_str();
}
else {
return ourUnknownPriorityName.c_str();
}
}
AREXPORT void ArUtil::putCurrentYearInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%4d", 1900 + t.tm_year);
s[len-1] = '\0';
}
AREXPORT void ArUtil::putCurrentMonthInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%02d", t.tm_mon + 1);
s[len-1] = '\0';
}
AREXPORT void ArUtil::putCurrentDayInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%02d", t.tm_mday);
s[len-1] = '\0';
}
AREXPORT void ArUtil::putCurrentHourInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%02d", t.tm_hour);
s[len-1] = '\0';
}
AREXPORT void ArUtil::putCurrentMinuteInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%02d", t.tm_min);
s[len-1] = '\0';
}
AREXPORT void ArUtil::putCurrentSecondInString(char* s, size_t len)
{
struct tm t;
ArUtil::localtime(&t);
snprintf(s, len, "%02d", t.tm_sec);
s[len-1] = '\0';
}
AREXPORT time_t ArUtil::parseTime(const char *str, bool *ok, bool toToday)
{
struct tm tmOut;
if (toToday)
{
struct tm now;
if (!localtime(&now))
{
*ok = false;
return 0;
}
memcpy(&tmOut, &now, sizeof(now));
}
else
{
memset(&tmOut, 0, sizeof(tmOut));
// The day-of-the-month starts at 1 (not 0)...
tmOut.tm_mday = 1;
// Setting the year to 70 because if it is left at 0 or 1, then
// the call to mktime() returns an apparently bogus value. Think
// that 70 makes sense since times are generally measured from
// 1/1/1970 (but still, it's all a little strange).
tmOut.tm_year = 70;
tmOut.tm_isdst = -1; // Negative value means unknown
}
bool isValid = true;
int hrs = -1;
int min = -1;
int sec = 0;
ArArgumentBuilder separator(512, ':');
separator.add(str);
// if there's the wrong number of args, or any of the args aren't
// integers then it's invalid and we won't parse it
if ((separator.getArgc() != 2 && separator.getArgc() != 3) ||
!separator.isArgInt(0) || !separator.isArgInt(1) ||
(separator.getArgc() == 3 && !separator.isArgInt(2)))
{
//printf("Invalid... %d\n", separator.getArgc());
//separator.log();
isValid = false;
}
else
{
hrs = separator.getArgInt(0);
min = separator.getArgInt(1);
if (separator.getArgc() == 3)
sec = separator.getArgInt(2);
//printf("Was %02d:%02d:%02d", hrs, min, sec);
}
/*
char *tempBuf = new char[strlen(str) + 1];
strncpy(tempBuf, str, sizeof(tempBuf));
// Attempted to use strptime, but it doesn't seem to be universally
// available.
char *pch = strtok(tempBuf, ":");
if (pch != NULL) {
hrs = atoi(pch);
}
pch = strtok(NULL, ":");
if (pch != NULL) {
min = atoi(pch);
}
*/
// make sure the actual numbers are valid
if (!((hrs >= 0) && (hrs < 24) && (min >= 0) && (min < 60) &&
(sec >= 0) && (sec < 60)))
isValid = false;
if (isValid)
{
tmOut.tm_hour = hrs;
tmOut.tm_min = min;
tmOut.tm_sec = sec;
}
time_t newTime = mktime(&tmOut);
if (ok != NULL)
{
*ok = (isValid && (newTime != -1));
}
//delete [] tempBuf;
return newTime;
} // end method parseTime
AREXPORT bool ArUtil::localtime(const time_t *timep, struct tm *result)
{
#ifdef WIN32
ourLocaltimeMutex.lock();
struct tm *r = ::localtime(timep);
if(r == NULL) {
ourLocaltimeMutex.unlock();
return false;
}
*result = *r; // copy the 'struct tm' object before unlocking.
ourLocaltimeMutex.unlock();
return true;
#else
return (::localtime_r(timep, result) != NULL);
#endif
}
/** Call ArUtil::localtime() with the current time obtained by calling
* time(NULL).
* @return false on error (e.g. invalid input), otherwise true.
*/
AREXPORT bool ArUtil::localtime(struct tm *result)
{
time_t now = time(NULL);
return ArUtil::localtime(&now, result);
}
AREXPORT ArCallbackList::ArCallbackList(
const char *name, ArLog::LogLevel logLevel, bool singleShot)
{
myName = name;
mySingleShot = singleShot;
setLogLevel(logLevel);
std::string mutexName;
mutexName = "ArCallbackList::";
mutexName += name;
mutexName += "::myDataMutex";
myDataMutex.setLogName(mutexName.c_str());
}
AREXPORT ArCallbackList::~ArCallbackList()
{
}
AREXPORT void ArCallbackList::addCallback(
ArFunctor *functor, int position)
{
myDataMutex.lock();
myList.insert(
std::pair<int, ArFunctor *>(-position,
functor));
myDataMutex.unlock();
}
AREXPORT void ArCallbackList::remCallback(ArFunctor *functor)
{
myDataMutex.lock();
std::multimap<int, ArFunctor *>::iterator it;
for (it = myList.begin(); it != myList.end(); it++)
{
if ((*it).second == functor)
{
myList.erase(it);
myDataMutex.unlock();
remCallback(functor);
return;
}
}
myDataMutex.unlock();
}
AREXPORT void ArCallbackList::setName(const char *name)
{
myDataMutex.lock();
myName = name;
myDataMutex.unlock();
}
AREXPORT void ArCallbackList::setNameVar(const char *name, ...)
{
char arg[2048];
va_list ptr;
va_start(ptr, name);
vsnprintf(arg, sizeof(arg), name, ptr);
arg[sizeof(arg) - 1] = '\0';
va_end(ptr);
return setName(arg);
}
AREXPORT void ArCallbackList::setSingleShot(bool singleShot)
{
myDataMutex.lock();
mySingleShot = singleShot;
myDataMutex.unlock();
}
AREXPORT void ArCallbackList::setLogLevel(ArLog::LogLevel logLevel)
{
myDataMutex.lock();
myLogLevel = logLevel;
myDataMutex.unlock();
}
AREXPORT void ArCallbackList::invoke(void)
{
myDataMutex.lock();
std::multimap<int, ArFunctor *>::iterator it;
ArFunctor *functor;
ArLog::log(myLogLevel, "%s: Starting calls", myName.c_str());
for (it = myList.begin();
it != myList.end();
it++)
{
functor = (*it).second;
if (functor == NULL)
continue;
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(myLogLevel, "%s: Calling functor '%s' at %d",
myName.c_str(), functor->getName(), -(*it).first);
else
ArLog::log(myLogLevel, "%s: Calling unnamed functor at %d",
myName.c_str(), -(*it).first);
functor->invoke();
}
ArLog::log(myLogLevel, "%s: Ended calls", myName.c_str());
if (mySingleShot)
{
ArLog::log(myLogLevel, "%s: Clearing callbacks", myName.c_str());
myList.clear();
}
myDataMutex.unlock();
}
#ifndef WIN32
/**
@param baseDir the base directory to work from
@param fileName the fileName to squash the case from
@param result where to put the result
@param resultLen length of the result
@return true if it could find the file, the result is in result,
false if it couldn't find the file
**/
AREXPORT bool ArUtil::matchCase(const char *baseDir,
const char *fileName,
char *result,
size_t resultLen)
{
/***
ArLog::log(ArLog::Normal,
"ArUtil::matchCase() baseDir = \"%s\" fileName = \"%s\"",
baseDir,
fileName);
***/
DIR *dir;
struct dirent *ent;
char separator;
#ifndef WIN32
separator = '/';
#else
separator = '\\';
#endif
result[0] = '\0';
std::list<std::string> split = splitFileName(fileName);
std::list<std::string>::iterator it = split.begin();
std::string finding = (*it);
/*
for (it = split.begin(); it != split.end(); it++)
{
printf("@@@@@@@@ %s\n", (*it).c_str());
}
*/
// how this works is we start at the base dir then read through
// until we find what the next name we need, if entry is a directory
// and we're not at the end of our string list then we change into
// that dir and the while loop keeps going, if the entry isn't a
// directory and matchs and its the last in our string list we've
// found what we want
if ((dir = opendir(baseDir)) == NULL)
{
ArLog::log(ArLog::Normal,
"ArUtil: No such directory '%s' for base",
baseDir);
return false;
}
if (finding == ".")
{
it++;
if (it != split.end())
{
finding = (*it);
}
else
{
ArLog::log(ArLog::Normal,
"ArUtil: No file or directory given (base = %s file = %s)",
baseDir,
fileName);
closedir(dir);
// KMC NEED TO DETERMINE WHICH IS CORRECT.
// The following change appears to be necessary for maps, but is still
// undergoing testing....
// Just return the given ".". (This is necessary to find maps in the local
// directory under some circumstances.)
// snprintf(result, resultLen, finding.c_str());
// return true;
return false;
}
}
while ((ent = readdir(dir)) != NULL)
{
// ignore some of these
if (ent->d_name[0] == '.')
{
//printf("Ignoring %s\n", ent->d_name[0]);
continue;
}
//printf("NAME %s finding %s\n", ent->d_name, finding.c_str());
// we've found what we were looking for
if (ArUtil::strcasecmp(ent->d_name, finding) == 0)
{
size_t lenOfResult;
lenOfResult = strlen(result);
// make sure we can put the filename in
if (strlen(ent->d_name) > resultLen - lenOfResult - 2)
{
ArLog::log(ArLog::Normal,
"ArUtil::matchCase: result not long enough");
closedir(dir);
return false;
}
//printf("Before %s", result);
if (lenOfResult != 0)
{
result[lenOfResult] = separator;
result[lenOfResult+1] = '\0';
}
// put the filename in
strcpy(&result[strlen(result)], ent->d_name);
//printf("after %s\n", result);
// see if we're at the end
it++;
if (it != split.end())
{
//printf("Um.........\n");
finding = (*it);
std::string wholeDir;
wholeDir = baseDir;
wholeDir += result;
closedir(dir);
//printf("'%s' '%s' '%s'\n", baseDir, result, wholeDir.c_str());
if ((dir = opendir(wholeDir.c_str())) == NULL)
{
ArLog::log(ArLog::Normal,
"ArUtil::matchCase: Error going into %s",
result);
return false;
}
}
else
{
//printf("\n########## Got it %s\n", result);
closedir(dir);
return true;
}
}
}
ArLog::log(ArLog::Normal,
"ArUtil::matchCase: %s doesn't exist in %s", fileName,
baseDir);
//printf("!!!!!!!! %s", finding.c_str());
closedir(dir);
return false;
}
#endif // !WIN32
AREXPORT bool ArUtil::getDirectory(const char *fileName,
char *result, size_t resultLen)
{
char separator;
#ifndef WIN32
separator = '/';
#else
separator = '\\';
#endif
if (fileName == NULL || fileName[0] == '\0' || resultLen == 0)
{
ArLog::log(ArLog::Normal, "ArUtil: getDirectory, bad setup");
return false;
}
// just play in the result buffer
strncpy(result, fileName, resultLen - 1);
// make sure its nulled
result[resultLen - 1] = '\0';
char *toPos;
ArUtil::fixSlashes(result, resultLen);
// see where the last directory is
toPos = strrchr(result, separator);
// if there's no divider it must just be a file name
if (toPos == NULL)
{
result[0] = '\0';
return true;
}
// otherwise just toss a null into the last separator and we're done
else
{
*toPos = '\0';
return true;
}
}
AREXPORT bool ArUtil::getFileName(const char *fileName,
char *result, size_t resultLen)
{
char separator;
#ifndef WIN32
separator = '/';
#else
separator = '\\';
#endif
if (fileName == NULL || fileName[0] == '\0' || resultLen == 0)
{
ArLog::log(ArLog::Normal, "ArUtil: getFileName, bad setup");
return false;
}
char *str;
size_t fileNameLen = strlen(fileName);
str = new char[fileNameLen + 1];
//printf("0 %s\n", fileName);
// just play in the result buffer
strncpy(str, fileName, fileNameLen);
// make sure its nulled
str[fileNameLen] = '\0';
//printf("1 %s\n", str);
char *toPos;
ArUtil::fixSlashes(str, fileNameLen + 1);
//printf("2 %s\n", str);
// see where the last directory is
toPos = strrchr(str, separator);
// if there's no divider it must just be a file name
if (toPos == NULL)
{
// copy the filename in and make sure it has a null
strncpy(result, str, resultLen - 1);
result[resultLen - 1] = '\0';
//printf("3 %s\n", result);
delete[] str;
return true;
}
// otherwise take the section from that separator to the end
else
{
strncpy(result, &str[toPos - str + 1], resultLen - 2);
result[resultLen - 1] = '\0';
//printf("4 %s\n", result);
delete[] str;
return true;
}
}
#ifndef WIN32
/**
This function assumes the slashes are all heading the right way already.
**/
std::list<std::string> ArUtil::splitFileName(const char *fileName)
{
std::list<std::string> split;
if (fileName == NULL)
return split;
char separator;
#ifndef WIN32
separator = '/';
#else
separator = '\\';
#endif
size_t len;
size_t i;
size_t last;
bool justSepped;
char entry[2048];
for (i = 0, justSepped = false, last = 0, len = strlen(fileName);
;
i++)
{
if ((fileName[i] == separator && !justSepped)
|| fileName[i] == '\0' || i >= len)
{
if (i - last > 2047)
{
ArLog::log(ArLog::Normal, "ArUtil::splitFileName: some directory or file too long");
}
if (!justSepped)
{
strncpy(entry, &fileName[last], i - last);
entry[i-last] = '\0';
split.push_back(entry);
justSepped = true;
}
if (fileName[i] == '\0' || i >= len)
return split;
}
else if (fileName[i] == separator && justSepped)
{
justSepped = true;
last = i;
}
else if (fileName[i] != separator && justSepped)
{
justSepped = false;
last = i;
}
}
ArLog::log(ArLog::Normal, "ArUtil::splitFileName: file str ('%s') happened weird", fileName);
return split;
}
#endif // !WIN32
AREXPORT bool ArUtil::changeFileTimestamp(const char *fileName,
time_t timestamp)
{
if (ArUtil::isStrEmpty(fileName)) {
ArLog::log(ArLog::Normal,
"Cannot change date on file with empty name");
return false;
}
#ifdef WIN32
FILETIME fileTime;
HANDLE hFile = CreateFile(fileName,
GENERIC_READ | GENERIC_WRITE,
0,NULL,
OPEN_EXISTING,
0,NULL);
if (hFile == NULL) {
return false;
}
// The following is extracted from the MSDN article "Converting a time_t Value
// to a File Time".
LONGLONG temp = Int32x32To64(timestamp, 10000000) + 116444736000000000;
fileTime.dwLowDateTime = (DWORD) temp;
fileTime.dwHighDateTime = temp >> 32;
SetFileTime(hFile,
&fileTime,
(LPFILETIME) NULL, // don't change last access time (?)
&fileTime);
CloseHandle(hFile);
#else // unix
char timeBuf[500];
strftime(timeBuf, sizeof(timeBuf), "%c", ::localtime(×tamp));
ArLog::log(ArLog::Normal,
"Changing file %s modified time to %s",
fileName,
timeBuf);
// time_t newTime = mktime(×tamp);
struct utimbuf fileTime;
fileTime.actime = timestamp;
fileTime.modtime = timestamp;
utime(fileName, &fileTime);
#endif // else unix
return true;
} // end method changeFileTimestamp
AREXPORT void ArUtil::setFileCloseOnExec(int fd, bool closeOnExec)
{
#ifndef WIN32
if (fd <= 0)
return;
int flags;
if ((flags = fcntl(fd, F_GETFD)) < 0)
{
ArLog::log(ArLog::Normal, "ArUtil::setFileCloseOnExec: Cannot use F_GETFD in fnctl on fd %d", fd);
return;
}
if (closeOnExec)
flags |= FD_CLOEXEC;
else
flags &= ~FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) < 0)
{
ArLog::log(ArLog::Normal, "ArUtil::setFileCloseOnExec: Cannot use F_GETFD in fnctl on fd %d", fd);
return;
}
#endif
}
AREXPORT void ArUtil::setFileCloseOnExec(FILE *file, bool closeOnExec)
{
if (file != NULL)
setFileCloseOnExec(fileno(file));
}
AREXPORT FILE *ArUtil::fopen(const char *path, const char *mode,
bool closeOnExec)
{
FILE *file;
file = ::fopen(path, mode);
setFileCloseOnExec(file, closeOnExec);
return file;
}
AREXPORT int ArUtil::open(const char *pathname, int flags,
bool closeOnExec)
{
int fd;
fd = ::open(pathname, flags);
setFileCloseOnExec(fd, closeOnExec);
return fd;
}
AREXPORT int ArUtil::open(const char *pathname, int flags, mode_t mode,
bool closeOnExec)
{
int fd;
fd = ::open(pathname, flags, mode);
setFileCloseOnExec(fd, closeOnExec);
return fd;
}
AREXPORT int ArUtil::creat(const char *pathname, mode_t mode,
bool closeOnExec)
{
int fd;
fd = ::creat(pathname, mode);
setFileCloseOnExec(fd, closeOnExec);
return fd;
}
AREXPORT FILE *ArUtil::popen(const char *command, const char *type,
bool closeOnExec)
{
FILE *file;
#ifndef WIN32
file = ::popen(command, type);
#else
file = _popen(command, type);
#endif
setFileCloseOnExec(file, closeOnExec);
return file;
}
AREXPORT bool ArUtil::floatIsNormal(double f)
{
#ifdef WIN32
return (!::_isnan(f) && ::_finite(f));
#else
return isnormal(f);
#endif
}
AREXPORT long ArMath::randomInRange(long m, long n)
{
// simple method
return m + random() / (ourRandMax / (n - m + 1) + 1);
// alternate method is to use drand48, multiply and round (does Windows have
// drand48?), or keep trying numbers until we get one in range.
}
AREXPORT double ArMath::epsilon() { return ourEpsilon; }
AREXPORT long ArMath::getRandMax() { return ourRandMax; }
#ifndef ARINTERFACE
ArGlobalRetFunctor2<ArLaser *, int, const char *>
ArLaserCreatorHelper::ourLMS2xxCB(&ArLaserCreatorHelper::createLMS2xx);
ArGlobalRetFunctor2<ArLaser *, int, const char *>
ArLaserCreatorHelper::ourUrgCB(&ArLaserCreatorHelper::createUrg);
ArGlobalRetFunctor2<ArLaser *, int, const char *>
ArLaserCreatorHelper::ourLMS1XXCB(&ArLaserCreatorHelper::createLMS1XX);
ArGlobalRetFunctor2<ArLaser *, int, const char *>
ArLaserCreatorHelper::ourUrg_2_0CB(&ArLaserCreatorHelper::createUrg_2_0);
ArLaser *ArLaserCreatorHelper::createLMS2xx(int laserNumber,
const char *logPrefix)
{
return new ArLMS2xx(laserNumber);
}
ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateLMS2xxCB(void)
{
return &ourLMS2xxCB;
}
ArLaser *ArLaserCreatorHelper::createUrg(int laserNumber, const char *logPrefix)
{
return new ArUrg(laserNumber);
}
ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateUrgCB(void)
{
return &ourUrgCB;
}
ArLaser *ArLaserCreatorHelper::createLMS1XX(int laserNumber,
const char *logPrefix)
{
return new ArLMS1XX(laserNumber);
}
ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateLMS1XXCB(void)
{
return &ourLMS1XXCB;
}
ArLaser *ArLaserCreatorHelper::createUrg_2_0(int laserNumber,
const char *logPrefix)
{
return new ArUrg_2_0(laserNumber);
}
ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateUrg_2_0CB(void)
{
return &ourUrg_2_0CB;
}
#endif // ARINTERFACE
ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *>
ArDeviceConnectionCreatorHelper::ourSerialCB(
&ArDeviceConnectionCreatorHelper::createSerialConnection);
ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *>
ArDeviceConnectionCreatorHelper::ourTcpCB(
&ArDeviceConnectionCreatorHelper::createTcpConnection);
ArLog::LogLevel ArDeviceConnectionCreatorHelper::ourSuccessLogLevel;
ArDeviceConnection *ArDeviceConnectionCreatorHelper::createSerialConnection(
const char *port, const char *defaultInfo, const char *logPrefix)
{
ArDeviceConnection *devConn;
devConn = internalCreateSerialConnection(port, defaultInfo, logPrefix);
return devConn;
}
ArDeviceConnection *ArDeviceConnectionCreatorHelper::internalCreateSerialConnection(
const char *port, const char *defaultInfo, const char *logPrefix)
{
ArSerialConnection *serConn = new ArSerialConnection();
std::string serPort;
if (strcasecmp(port, "COM1") == 0)
serPort = ArUtil::COM1;
else if (strcasecmp(port, "COM2") == 0)
serPort = ArUtil::COM2;
else if (strcasecmp(port, "COM3") == 0)
serPort = ArUtil::COM3;
else if (strcasecmp(port, "COM4") == 0)
serPort = ArUtil::COM4;
else if (strcasecmp(port, "COM5") == 0)
serPort = ArUtil::COM5;
else if (strcasecmp(port, "COM6") == 0)
serPort = ArUtil::COM6;
else if (strcasecmp(port, "COM7") == 0)
serPort = ArUtil::COM7;
else if (strcasecmp(port, "COM8") == 0)
serPort = ArUtil::COM8;
else if (strcasecmp(port, "COM9") == 0)
serPort = ArUtil::COM9;
else if (strcasecmp(port, "COM10") == 0)
serPort = ArUtil::COM10;
else if (strcasecmp(port, "COM11") == 0)
serPort = ArUtil::COM11;
else if (strcasecmp(port, "COM12") == 0)
serPort = ArUtil::COM12;
else if (strcasecmp(port, "COM13") == 0)
serPort = ArUtil::COM13;
else if (strcasecmp(port, "COM14") == 0)
serPort = ArUtil::COM14;
else if (strcasecmp(port, "COM15") == 0)
serPort = ArUtil::COM15;
else if (strcasecmp(port, "COM16") == 0)
serPort = ArUtil::COM16;
else if (port != NULL)
serPort = port;
ArLog::log(ourSuccessLogLevel, "%Set serial port to open %s",
logPrefix, serPort.c_str());
serConn->setPort(serPort.c_str());
return serConn;
/*
This code is commented out because it created problems with demo
(or any other program that used ArLaserConnector::connectLasers
with addAllLasersToRobot as true)
int ret;
if ((ret = serConn->open(serPort.c_str())) == 0)
{
ArLog::log(ourSuccessLogLevel, "%sOpened serial port %s",
logPrefix, serPort.c_str());
return serConn;
}
else
{
ArLog::log(ArLog::Normal, "%sCould not open serial port %s (from %s), because %s",
logPrefix, serPort.c_str(), port,
serConn->getOpenMessage(ret));
delete serConn;
return NULL;
}
*/
}
ArRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> *
ArDeviceConnectionCreatorHelper::getCreateSerialCB(void)
{
return &ourSerialCB;
}
ArDeviceConnection *ArDeviceConnectionCreatorHelper::createTcpConnection(
const char *port, const char *defaultInfo, const char *logPrefix)
{
ArTcpConnection *tcpConn = new ArTcpConnection;
int ret;
tcpConn->setPort(port, atoi(defaultInfo));
ArLog::log(ourSuccessLogLevel,
"%sSet tcp connection to open %s (and port %d)",
logPrefix, port, atoi(defaultInfo));
return tcpConn;
/*
This code is commented out because it created problems with demo
(or any other program that used ArLaserConnector::connectLasers
with addAllLasersToRobot as true)
if ((ret = tcpConn->open(port, atoi(defaultInfo))) == 0)
{
ArLog::log(ourSuccessLogLevel,
"%sOpened tcp connection from %s (and port %d)",
logPrefix, port, atoi(defaultInfo));
return tcpConn;
}
else
{
ArLog::log(ArLog::Normal, "%sCould not open a tcp connection to host '%s' with default port %d (from '%s'), because %s",
logPrefix, port, atoi(defaultInfo), defaultInfo,
tcpConn->getOpenMessage(ret));
delete tcpConn;
return NULL;
}
*/
}
ArRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> *
ArDeviceConnectionCreatorHelper::getCreateTcpCB(void)
{
return &ourTcpCB;
}
void ArDeviceConnectionCreatorHelper::setSuccessLogLevel(
ArLog::LogLevel successLogLevel)
{
ourSuccessLogLevel = successLogLevel;
}
ArLog::LogLevel ArDeviceConnectionCreatorHelper::setSuccessLogLevel(void)
{
return ourSuccessLogLevel;
}
| 25.3587 | 134 | 0.647777 | rzsavilla |
33f7c9daf4599356166825b3a4a5694d2668467c | 1,679 | cpp | C++ | test/deduce_scalar_mv_test.cpp | boostorg/boost-qvm | 5791440b346232c391ab8d16f559ca5b2d7ae9b3 | [
"BSL-1.0"
] | null | null | null | test/deduce_scalar_mv_test.cpp | boostorg/boost-qvm | 5791440b346232c391ab8d16f559ca5b2d7ae9b3 | [
"BSL-1.0"
] | null | null | null | test/deduce_scalar_mv_test.cpp | boostorg/boost-qvm | 5791440b346232c391ab8d16f559ca5b2d7ae9b3 | [
"BSL-1.0"
] | null | null | null | // Copyright 2008-2022 Emil Dotchevski and Reverge Studios, Inc.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifdef BOOST_QVM_TEST_SINGLE_HEADER
# include BOOST_QVM_TEST_SINGLE_HEADER
#else
# include <boost/qvm/deduce_scalar.hpp>
# include <boost/qvm/mat.hpp>
# include <boost/qvm/mat_operations.hpp>
# include <boost/qvm/vec.hpp>
# include <boost/qvm/vec_mat_operations3.hpp>
#endif
#include <boost/core/lightweight_test.hpp>
template <class T>
struct
wrap
{
T t;
wrap() { }
explicit wrap(T t):t(t) { }
};
template <class S, class T>
wrap<T>
operator*(S s, wrap<T> w)
{
return wrap<T>(s * w.t);
}
template <class T>
wrap<T> operator+(wrap<T> a, wrap<T> b)
{
return wrap<T>(a.t + b.t);
}
namespace
boost
{
namespace
qvm
{
template <class T>
struct
is_scalar<wrap<T> >
{
static bool const value=true;
};
template <class S, class T>
struct
deduce_scalar<S, wrap<T> >
{
typedef wrap<typename deduce_scalar<S, T>::type> type;
};
}
}
int
main()
{
using namespace boost::qvm;
mat<double, 3, 3> m = rotz_mat<3>(3.14159);
vec<wrap<double>, 3> v;
v.a[0] = wrap<double>(1.0);
v.a[1] = wrap<double>(0);
v.a[2] = wrap<double>(0);
vec<wrap<double>, 3> r = m * v;
BOOST_TEST_LT(fabs(r.a[0].t+1), 0.0001);
BOOST_TEST_LT(fabs(r.a[1].t), 0.0001);
BOOST_TEST_LT(fabs(r.a[2].t), 0.0001);
return boost::report_errors();
}
| 22.092105 | 79 | 0.585468 | boostorg |
33facceab40746a6a205d13aaa958b7e1675ca04 | 1,047 | cpp | C++ | topic_wise/arrays/CountandSay.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | 1 | 2021-01-27T16:37:36.000Z | 2021-01-27T16:37:36.000Z | topic_wise/arrays/CountandSay.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | topic_wise/arrays/CountandSay.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | /*The count-and-say sequence is the sequence of integers with the first five
terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say
sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"*/
class Solution {
public:
string countAndSay(int n) {
if (n == 1) {
return "1";
} else if (n == 2) {
return "11";
} else {
string s = countAndSay(n - 1);
string n{};
int c = 1;
for (int i = 0; i < s.size(); i++) {
if (i + 1 < s.size() and s[i] == s[i + 1]) {
c++;
} else {
char num = c + '0';
n += string{num} + string{s[i]};
c = 1;
}
}
return n;
}
}
};
| 19.754717 | 80 | 0.494747 | archit-1997 |
33faec5db7f5f4242cdf3e7e164458fa1e7105c6 | 2,006 | cpp | C++ | src/iq_neuron.cpp | twetto/iq-neuron | dad804c61001ffcaa5578ec9e7531eeec4952188 | [
"MIT"
] | 4 | 2019-10-18T10:01:01.000Z | 2020-07-17T03:43:48.000Z | src/iq_neuron.cpp | twetto/iq-neuron | dad804c61001ffcaa5578ec9e7531eeec4952188 | [
"MIT"
] | 1 | 2019-10-25T08:35:27.000Z | 2019-10-28T05:06:55.000Z | src/iq_neuron.cpp | twetto/iq-neuron | dad804c61001ffcaa5578ec9e7531eeec4952188 | [
"MIT"
] | 3 | 2019-07-29T09:21:11.000Z | 2021-08-28T14:25:13.000Z | /* IQIF neuron object
* Chen-Fu Yeh, 2019/11/09
*/
#include "iq_neuron.h"
using namespace std;
iq_neuron::iq_neuron(int rest, int threshold,
int reset, int a, int b, int noise)
{
x = rest; // initialize with rest potential
t_neuron = 0;
f_min = (a*rest + b*threshold) / (a+b); // dV/dt and others
_a = a;
_b = b;
_rest = rest;
_threshold = threshold;
_reset = reset;
if(noise == 0) noise++; // set noise strength
else if(noise < 0) noise = -noise;
_noise = noise;
_is_set = true;
return;
}
bool iq_neuron::is_set()
{
return _is_set;
}
void iq_neuron::set(int rest, int threshold,
int reset, int a, int b, int noise)
{
x = rest;
t_neuron = 0;
f_min = (a*rest + b*threshold) / (a+b);
_a = a;
_b = b;
_rest = rest;
_threshold = threshold;
_reset = reset;
if(noise == 0) noise++;
else if(noise < 0) noise = -noise;
_noise = noise;
_is_set = true;
return;
}
void iq_neuron::set_vmax(int vmax)
{
VMAX = vmax;
return;
}
void iq_neuron::set_vmin(int vmin)
{
VMIN = vmin;
return;
}
void iq_neuron::iq(int external_current)
{
int f;
/* solving dV/dt */
if(x < f_min)
f = _a * (_rest - x);
else
f = _b * (x - _threshold);
x += (f >> 3) + external_current + rand()%_noise - (_noise >> 1);
/* fire if exceeding action potential */
_is_firing = false;
if(x > VMAX) {
_spike_count++;
_is_firing = true;
x = _reset;
}
else if(x < VMIN) x = VMIN;
t_neuron++;
return;
}
int iq_neuron::potential()
{
return x;
}
bool iq_neuron::is_firing()
{
return _is_firing;
}
int iq_neuron::spike_count()
{
int count = _spike_count;
_spike_count = 0;
return count;
}
float iq_neuron::spike_rate()
{
float r = _spike_count / (float) t_neuron;
t_neuron = 0;
_spike_count = 0;
return r;
}
| 18.236364 | 77 | 0.547856 | twetto |
33fbb210810bab91e3e5e5281a19e74822a79a9e | 44,258 | cpp | C++ | src/Widgets/MultiVarTransferFunctionWindow.cpp | FelixBrendel/LineVis | 428cf82328ba3d3ac9435f3df765330149d4a921 | [
"Apache-2.0"
] | null | null | null | src/Widgets/MultiVarTransferFunctionWindow.cpp | FelixBrendel/LineVis | 428cf82328ba3d3ac9435f3df765330149d4a921 | [
"Apache-2.0"
] | null | null | null | src/Widgets/MultiVarTransferFunctionWindow.cpp | FelixBrendel/LineVis | 428cf82328ba3d3ac9435f3df765330149d4a921 | [
"Apache-2.0"
] | null | null | null | /*
* BSD 2-Clause License
*
* Copyright (c) 2020, Christoph Neuhauser
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <cmath>
#ifdef __linux__
#include <sys/inotify.h>
#include <poll.h>
#endif
#include <GL/glew.h>
#include <glm/glm.hpp>
#define IMGUI_DEFINE_MATH_OPERATORS
#include <ImGui/imgui.h>
#include <ImGui/imgui_internal.h>
#include <ImGui/imgui_custom.h>
#include <ImGui/imgui_stdlib.h>
#include <Utils/AppSettings.hpp>
#include <Utils/XML.hpp>
#include <Utils/File/Logfile.hpp>
#include <Utils/File/FileUtils.hpp>
#include <Math/Math.hpp>
#include <Graphics/Renderer.hpp>
#include <Graphics/Texture/TextureManager.hpp>
#ifdef SUPPORT_VULKAN
#include <Graphics/Vulkan/Buffers/Buffer.hpp>
#endif
#include "MultiVarTransferFunctionWindow.hpp"
using namespace tinyxml2;
const size_t TRANSFER_FUNCTION_TEXTURE_SIZE = 256;
GuiVarData::GuiVarData(
MultiVarTransferFunctionWindow* window, const std::string& tfPresetFile,
sgl::Color16* transferFunctionMap_sRGB,
sgl::Color16* transferFunctionMap_linearRGB) {
this->window = window;
this->transferFunctionMap_sRGB = transferFunctionMap_sRGB;
this->transferFunctionMap_linearRGB = transferFunctionMap_linearRGB;
std::string tfFileName = window->saveDirectory + tfPresetFile;
const std::string stdFileName = window->saveDirectory + "Standard.xml";
if (tfFileName.empty() || !sgl::FileUtils::get()->exists(tfFileName)) {
tfFileName = stdFileName;
}
if (sgl::FileUtils::get()->exists(tfFileName)) {
loadTfFromFile(tfFileName);
} else {
colorPoints = {
sgl::ColorPoint_sRGB(sgl::Color(59, 76, 192), 0.0f),
sgl::ColorPoint_sRGB(sgl::Color(144, 178, 254), 0.25f),
sgl::ColorPoint_sRGB(sgl::Color(220, 220, 220), 0.5f),
sgl::ColorPoint_sRGB(sgl::Color(245, 156, 125), 0.75f),
sgl::ColorPoint_sRGB(sgl::Color(180, 4, 38), 1.0f)
};
opacityPoints = { sgl::OpacityPoint(1.0f, 0.0f), sgl::OpacityPoint(1.0f, 1.0f) };
}
}
bool GuiVarData::saveTfToFile(const std::string& filename) {
FILE* file = fopen(filename.c_str(), "w");
if (file == NULL) {
sgl::Logfile::get()->writeError(
std::string() + "ERROR: MultiVarTransferFunctionWindow::saveFunctionToFile: Couldn't create file \""
+ filename + "\"!");
return false;
}
XMLPrinter printer(file);
printer.OpenElement("TransferFunction");
printer.PushAttribute("colorspace", "sRGB"); // Currently only sRGB supported for points
printer.PushAttribute("interpolation_colorspace", sgl::COLOR_SPACE_NAMES[interpolationColorSpace]);
printer.OpenElement("OpacityPoints");
// Traverse all opacity points
for (size_t i = 0; i < opacityPoints.size(); i++) {
printer.OpenElement("OpacityPoint");
printer.PushAttribute("position", opacityPoints.at(i).position);
printer.PushAttribute("opacity", opacityPoints.at(i).opacity);
printer.CloseElement();
}
printer.CloseElement();
printer.OpenElement("ColorPoints");
printer.PushAttribute("color_data", sgl::COLOR_DATA_MODE_NAMES[int(sgl::COLOR_DATA_MODE_UNSIGNED_SHORT)]);
// Traverse all color points
for (size_t i = 0; i < colorPoints.size(); i++) {
printer.OpenElement("ColorPoint");
printer.PushAttribute("position", colorPoints.at(i).position);
printer.PushAttribute("r", (int)colorPoints.at(i).color.getR());
printer.PushAttribute("g", (int)colorPoints.at(i).color.getG());
printer.PushAttribute("b", (int)colorPoints.at(i).color.getB());
printer.CloseElement();
}
printer.CloseElement();
printer.CloseElement();
fclose(file);
return true;
}
bool GuiVarData::loadTfFromFile(const std::string& filename) {
XMLDocument doc;
if (doc.LoadFile(filename.c_str()) != 0) {
sgl::Logfile::get()->writeError(
std::string() + "MultiVarTransferFunctionWindow::loadFunctionFromFile: Couldn't open file \""
+ filename + "\"!");
return false;
}
XMLElement* tfNode = doc.FirstChildElement("TransferFunction");
if (tfNode == nullptr) {
sgl::Logfile::get()->writeError(
"MultiVarTransferFunctionWindow::loadFunctionFromFile: No \"TransferFunction\" node found!");
return false;
}
interpolationColorSpace = sgl::COLOR_SPACE_SRGB; // Standard
const char* interpolationColorSpaceName = tfNode->Attribute("colorspace_interpolation");
if (interpolationColorSpaceName != nullptr) {
for (int i = 0; i < 2; i++) {
if (strcmp(interpolationColorSpaceName, sgl::COLOR_SPACE_NAMES[interpolationColorSpace]) == 0) {
interpolationColorSpace = (sgl::ColorSpace)i;
}
}
}
colorPoints.clear();
opacityPoints.clear();
// Traverse all opacity points
auto opacityPointsNode = tfNode->FirstChildElement("OpacityPoints");
if (opacityPointsNode != nullptr) {
for (sgl::XMLIterator it(opacityPointsNode, sgl::XMLNameFilter("OpacityPoint")); it.isValid(); ++it) {
XMLElement* childElement = *it;
float position = childElement->FloatAttribute("position");
float opacity = sgl::clamp(childElement->FloatAttribute("opacity"), 0.0f, 1.0f);
opacityPoints.emplace_back(opacity, position);
}
}
// Traverse all color points
auto colorPointsNode = tfNode->FirstChildElement("ColorPoints");
if (colorPointsNode != nullptr) {
sgl::ColorDataMode colorDataMode = sgl::COLOR_DATA_MODE_UNSIGNED_BYTE;
const char* colorDataModeName = colorPointsNode->Attribute("color_data");
if (colorDataModeName != nullptr) {
colorDataMode = sgl::parseColorDataModeName(colorDataModeName);
}
for (sgl::XMLIterator it(colorPointsNode, sgl::XMLNameFilter("ColorPoint")); it.isValid(); ++it) {
XMLElement* childElement = *it;
sgl::Color16 color;
float position = childElement->FloatAttribute("position");
if (colorDataMode == sgl::COLOR_DATA_MODE_UNSIGNED_BYTE) {
int red = sgl::clamp(childElement->IntAttribute("r"), 0, 255);
int green = sgl::clamp(childElement->IntAttribute("g"), 0, 255);
int blue = sgl::clamp(childElement->IntAttribute("b"), 0, 255);
color = sgl::Color(red, green, blue);
} else if (colorDataMode == sgl::COLOR_DATA_MODE_UNSIGNED_SHORT) {
int red = sgl::clamp(childElement->IntAttribute("r"), 0, 65535);
int green = sgl::clamp(childElement->IntAttribute("g"), 0, 65535);
int blue = sgl::clamp(childElement->IntAttribute("b"), 0, 65535);
color = sgl::Color16(red, green, blue);
} else if (colorDataMode == sgl::COLOR_DATA_MODE_FLOAT_NORMALIZED) {
float red = sgl::clamp(childElement->FloatAttribute("r"), 0.0f, 1.0f);
float green = sgl::clamp(childElement->FloatAttribute("g"), 0.0f, 1.0f);
float blue = sgl::clamp(childElement->FloatAttribute("b"), 0.0f, 1.0f);
color = sgl::Color16(glm::vec3(red, green, blue));
} else if (colorDataMode == sgl::COLOR_DATA_MODE_FLOAT_255) {
float red = sgl::clamp(childElement->FloatAttribute("r"), 0.0f, 255.0f) / 255.0f;
float green = sgl::clamp(childElement->FloatAttribute("g"), 0.0f, 255.0f) / 255.0f;
float blue = sgl::clamp(childElement->FloatAttribute("b"), 0.0f, 255.0f) / 255.0f;
color = sgl::Color16(glm::vec3(red, green, blue));
}
colorPoints.emplace_back(color, position);
}
}
selectedPointType = sgl::SELECTED_POINT_TYPE_NONE;
rebuildTransferFunctionMap();
return true;
}
void GuiVarData::setAttributeValues(const std::string& name, const std::vector<float>& attributes) {
attributeName = name;
this->attributes = attributes;
float minAttr = std::numeric_limits<float>::max();
float maxAttr = std::numeric_limits<float>::lowest();
#if _OPENMP >= 201107
#pragma omp parallel for reduction(min: minAttr) reduction(max: maxAttr) shared(attributes) default(none)
#endif
for (size_t i = 0; i < attributes.size(); i++) {
float value = attributes.at(i);
minAttr = std::min(minAttr, value);
maxAttr = std::max(maxAttr, value);
}
this->dataRange = glm::vec2(minAttr, maxAttr);
this->selectedRange = glm::vec2(minAttr, maxAttr);
computeHistogram();
}
void GuiVarData::computeHistogram() {
float histogramsMax = 0;
histogram = std::vector<float>(histogramResolution, 0.0f);
for (const float& value : attributes) {
int32_t index = glm::clamp(
static_cast<int>((value - selectedRange.x) / (selectedRange.y - selectedRange.x)
* static_cast<float>(histogramResolution)), 0, histogramResolution - 1);
histogram.at(index)++;
}
// Normalize values of histogram.
for (const float& binNumber : histogram) {
histogramsMax = std::max(histogramsMax, binNumber);
}
for (float& numBin : histogram) {
numBin /= histogramsMax;
}
}
// For OpenGL: Has TRANSFER_FUNCTION_TEXTURE_SIZE entries.
// Get mapped color for normalized attribute by accessing entry at "attr*255".
void GuiVarData::rebuildTransferFunctionMap() {
rebuildTransferFunctionMapLocal();
window->rebuildTransferFunctionMap();
}
void GuiVarData::rebuildTransferFunctionMapLocal() {
// Create linear RGB color points
colorPoints_LinearRGB.clear();
for (sgl::ColorPoint_sRGB& colorPoint : colorPoints) {
glm::vec3 linearRGBColor = sgl::TransferFunctionWindow::sRGBToLinearRGB(colorPoint.color.getFloatColorRGB());
colorPoints_LinearRGB.push_back(sgl::ColorPoint_LinearRGB(linearRGBColor, colorPoint.position));
}
if (interpolationColorSpace == sgl::COLOR_SPACE_LINEAR_RGB) {
rebuildTransferFunctionMap_LinearRGB();
} else {
rebuildTransferFunctionMap_sRGB();
}
}
// For OpenGL: Has 256 entries. Get mapped color for normalized attribute by accessing entry at "attr*255".
void GuiVarData::rebuildTransferFunctionMap_LinearRGB() {
int colorPointsIdx = 0;
int opacityPointsIdx = 0;
for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) {
glm::vec3 linearRGBColorAtIdx;
float opacityAtIdx;
float currentPosition = static_cast<float>(i) / float(TRANSFER_FUNCTION_TEXTURE_SIZE-1);
// colorPoints.at(colorPointsIdx) should be to the right of/equal to currentPosition
while (colorPoints_LinearRGB.at(colorPointsIdx).position < currentPosition) {
colorPointsIdx++;
}
while (opacityPoints.at(opacityPointsIdx).position < currentPosition) {
opacityPointsIdx++;
}
// Now compute the color...
if (colorPoints_LinearRGB.at(colorPointsIdx).position == currentPosition) {
linearRGBColorAtIdx = colorPoints_LinearRGB.at(colorPointsIdx).color;
} else {
glm::vec3 color0 = colorPoints_LinearRGB.at(colorPointsIdx-1).color;
glm::vec3 color1 = colorPoints_LinearRGB.at(colorPointsIdx).color;
float pos0 = colorPoints_LinearRGB.at(colorPointsIdx-1).position;
float pos1 = colorPoints_LinearRGB.at(colorPointsIdx).position;
float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0);
linearRGBColorAtIdx = glm::mix(color0, color1, factor);
}
// ... and the opacity.
if (opacityPoints.at(opacityPointsIdx).position == currentPosition) {
opacityAtIdx = opacityPoints.at(opacityPointsIdx).opacity;
} else {
float opacity0 = opacityPoints.at(opacityPointsIdx-1).opacity;
float opacity1 = opacityPoints.at(opacityPointsIdx).opacity;
float pos0 = opacityPoints.at(opacityPointsIdx-1).position;
float pos1 = opacityPoints.at(opacityPointsIdx).position;
float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0);
opacityAtIdx = sgl::interpolateLinear(opacity0, opacity1, factor);
}
transferFunctionMap_linearRGB[i] = sgl::Color16(glm::vec4(linearRGBColorAtIdx, opacityAtIdx));
transferFunctionMap_sRGB[i] = sgl::Color16(glm::vec4(
sgl::TransferFunctionWindow::linearRGBTosRGB(linearRGBColorAtIdx), opacityAtIdx));
}
}
// For OpenGL: Has 256 entries. Get mapped color for normalized attribute by accessing entry at "attr*255".
void GuiVarData::rebuildTransferFunctionMap_sRGB() {
int colorPointsIdx = 0;
int opacityPointsIdx = 0;
for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) {
glm::vec3 sRGBColorAtIdx;
float opacityAtIdx;
float currentPosition = static_cast<float>(i) / float(TRANSFER_FUNCTION_TEXTURE_SIZE-1);
// colorPoints.at(colorPointsIdx) should be to the right of/equal to currentPosition
while (colorPoints.at(colorPointsIdx).position < currentPosition) {
colorPointsIdx++;
}
while (opacityPoints.at(opacityPointsIdx).position < currentPosition) {
opacityPointsIdx++;
}
// Now compute the color...
if (colorPoints.at(colorPointsIdx).position == currentPosition) {
sRGBColorAtIdx = colorPoints.at(colorPointsIdx).color.getFloatColorRGB();
} else {
glm::vec3 color0 = colorPoints.at(colorPointsIdx-1).color.getFloatColorRGB();
glm::vec3 color1 = colorPoints.at(colorPointsIdx).color.getFloatColorRGB();
float pos0 = colorPoints.at(colorPointsIdx-1).position;
float pos1 = colorPoints.at(colorPointsIdx).position;
float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0);
sRGBColorAtIdx = glm::mix(color0, color1, factor);
}
// ... and the opacity.
if (opacityPoints.at(opacityPointsIdx).position == currentPosition) {
opacityAtIdx = opacityPoints.at(opacityPointsIdx).opacity;
} else {
float opacity0 = opacityPoints.at(opacityPointsIdx-1).opacity;
float opacity1 = opacityPoints.at(opacityPointsIdx).opacity;
float pos0 = opacityPoints.at(opacityPointsIdx-1).position;
float pos1 = opacityPoints.at(opacityPointsIdx).position;
float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0);
opacityAtIdx = sgl::interpolateLinear(opacity0, opacity1, factor);
}
transferFunctionMap_linearRGB[i] = sgl::Color16(glm::vec4(
sgl::TransferFunctionWindow::sRGBToLinearRGB(sRGBColorAtIdx), opacityAtIdx));
transferFunctionMap_sRGB[i] = sgl::Color16(glm::vec4(sRGBColorAtIdx, opacityAtIdx));
}
}
bool GuiVarData::renderGui() {
renderOpacityGraph();
renderColorBar();
if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY) {
if (ImGui::DragFloat("Opacity", &opacitySelection, 0.001f, 0.0f, 1.0f)) {
opacityPoints.at(currentSelectionIndex).opacity = opacitySelection;
rebuildTransferFunctionMap();
reRender = true;
}
} else if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR) {
if (ImGui::ColorEdit3("Color", (float*)&colorSelection)) {
colorPoints.at(currentSelectionIndex).color = sgl::color16FromFloat(
colorSelection.x, colorSelection.y, colorSelection.z, colorSelection.w);
rebuildTransferFunctionMap();
reRender = true;
}
}
if (ImGui::Combo(
"Color Space", (int*)&interpolationColorSpace,
sgl::COLOR_SPACE_NAMES, IM_ARRAYSIZE(sgl::COLOR_SPACE_NAMES))) {
rebuildTransferFunctionMap();
reRender = true;
}
if (ImGui::SliderFloat2("Range", &selectedRange.x, dataRange.x, dataRange.y)) {
computeHistogram();
window->rebuildRangeSsbo();
reRender = true;
}
ImGui::SameLine();
if (ImGui::Button("Reset")) {
selectedRange = dataRange;
computeHistogram();
window->rebuildRangeSsbo();
reRender = true;
}
if (ImGui::SliderInt("Histogram Res.", &histogramResolution, 1, 256)) {
computeHistogram();
}
renderFileDialog();
if (reRender) {
reRender = false;
return true;
}
return false;
}
void GuiVarData::renderFileDialog() {
// Load file data
if (ImGui::ListBox("##availablefiles", &selectedFileIndex, [this](void* data, int idx, const char** out_text) -> bool {
*out_text = window->availableFiles.at(idx).c_str();
return true;
}, nullptr, int(window->availableFiles.size()), 4)) {
saveFileString = window->availableFiles.at(selectedFileIndex);
} ImVec2 cursorPosEnd = ImGui::GetCursorPos(); ImGui::SameLine();
ImVec2 cursorPos = ImGui::GetCursorPos();
ImGui::Text("Available files"); ImGui::SameLine(); ImGui::SetCursorPos(cursorPos + ImVec2(0.0f, 42.0f));
if (ImGui::Button("Load file") && selectedFileIndex >= 0) {
loadTfFromFile(window->saveDirectory + window->availableFiles.at(selectedFileIndex));
reRender = true;
} ImGui::SetCursorPos(cursorPosEnd);
// Save file data
ImGui::InputText("##savefilelabel", &saveFileString); ImGui::SameLine();
if (ImGui::Button("Save file")) {
saveTfToFile(window->saveDirectory + saveFileString);
window->updateAvailableFiles();
}
}
void GuiVarData::renderOpacityGraph() {
ImDrawList* drawList = ImGui::GetWindowDrawList();
float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor();
float regionWidth = ImGui::GetContentRegionAvailWidth();
float graphHeight = 300 * scaleFactor / 1.875f;
float border = 2*scaleFactor;
float areaWidth = regionWidth - 2.0f*border;
float areaHeight = graphHeight - 2.0f*border;
opacityGraphBox.min = glm::vec2(ImGui::GetCursorScreenPos().x + border, ImGui::GetCursorScreenPos().y + border);
opacityGraphBox.max = opacityGraphBox.min + glm::vec2(areaWidth, areaHeight);
sgl::Color& clearColor = window->clearColor;
ImColor backgroundColor(clearColor.getFloatR(), clearColor.getFloatG(), clearColor.getFloatB());
ImColor borderColor(
1.0f - clearColor.getFloatR(), 1.0f - clearColor.getFloatG(), 1.0f - clearColor.getFloatB());
// First render the graph box
ImVec2 startPos = ImGui::GetCursorScreenPos();
ImVec2 cursorPosHistogram = ImGui::GetCursorPos();
drawList->AddRectFilled(
ImVec2(startPos.x, startPos.y),
ImVec2(startPos.x + regionWidth, startPos.y + graphHeight),
borderColor, ImGui::GetStyle().FrameRounding);
drawList->AddRectFilled(
ImVec2(startPos.x + border, startPos.y + border),
ImVec2(startPos.x + regionWidth - border, startPos.y + graphHeight - border),
backgroundColor, ImGui::GetStyle().FrameRounding);
if (ImGui::ClickArea("##grapharea", ImVec2(regionWidth, graphHeight + 2), mouseReleased)) {
onOpacityGraphClick();
}
//ImGui::SetItemAllowOverlap();
ImGui::SetCursorPos(cursorPosHistogram + ImVec2(border, border));
ImVec2 oldPadding = ImGui::GetStyle().FramePadding;
ImGui::GetStyle().FramePadding = ImVec2(1, 1);
ImGui::PlotHistogram(
"##histogram", histogram.data(), int(histogram.size()), 0,
nullptr, 0.0f, 1.0f,
ImVec2(regionWidth - border * 2, graphHeight - border * 2));
ImGui::GetStyle().FramePadding = oldPadding;
// Then render the graph itself
for (int i = 0; i < (int)opacityPoints.size()-1; i++) {
float positionX0 = opacityPoints.at(i).position * areaWidth + border;
float positionX1 = opacityPoints.at(i+1).position * areaWidth + border;
float positionY0 = (1.0f - opacityPoints.at(i).opacity) * areaHeight + border;
float positionY1 = (1.0f - opacityPoints.at(i+1).opacity) * areaHeight + border;
drawList->AddLine(
ImVec2(startPos.x + positionX0, startPos.y + positionY0),
ImVec2(startPos.x + positionX1, startPos.y + positionY1),
borderColor, 1.5f * scaleFactor);
}
// Finally, render the points
for (int i = 0; i < (int)opacityPoints.size(); i++) {
ImVec2 centerPt = ImVec2(
startPos.x + border + opacityPoints.at(i).position * areaWidth,
startPos.y + border + (1.0f - opacityPoints.at(i).opacity) * areaHeight);
float radius = 4*scaleFactor;
if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY && i == currentSelectionIndex) {
radius = 6*scaleFactor;
}
drawList->AddCircleFilled(centerPt, radius, backgroundColor, 24);
drawList->AddCircle(centerPt, radius, borderColor, 24, 1.5f);
}
}
void GuiVarData::renderColorBar() {
ImDrawList* drawList = ImGui::GetWindowDrawList();
float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor();
float regionWidth = ImGui::GetContentRegionAvailWidth() - 2.0f;
float barHeight = 30 * scaleFactor / 1.875f;
colorBarBox.min = glm::vec2(ImGui::GetCursorScreenPos().x + 1, ImGui::GetCursorScreenPos().y + 1);
colorBarBox.max = colorBarBox.min + glm::vec2(regionWidth - 2, barHeight - 2);
// Draw bar
ImVec2 startPos = ImGui::GetCursorScreenPos();
ImVec2 pos = ImVec2(startPos.x + 1, startPos.y + 1);
for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) {
sgl::Color16 color = transferFunctionMap_sRGB[i];
ImU32 colorImgui = ImColor(color.getFloatR(), color.getFloatG(), color.getFloatB());
drawList->AddLine(ImVec2(pos.x, pos.y), ImVec2(pos.x, pos.y + barHeight), colorImgui, 2.0f * regionWidth / 255.0f);
pos.x += regionWidth / 255.0f;
}
// Draw points
pos = ImVec2(startPos.x + 2, startPos.y + 2);
for (int i = 0; i < (int)colorPoints.size(); i++) {
sgl::Color16 color = colorPoints.at(i).color;
ImU32 colorImgui = ImColor(color.getFloatR(), color.getFloatG(), color.getFloatB());
ImU32 colorInvertedImgui = ImColor(1.0f - color.getFloatR(), 1.0f - color.getFloatG(), 1.0f - color.getFloatB());
ImVec2 centerPt = ImVec2(pos.x + colorPoints.at(i).position * regionWidth, pos.y + barHeight/2);
float radius = 4*scaleFactor;
if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR && i == currentSelectionIndex) {
radius = 6*scaleFactor;
}
drawList->AddCircleFilled(centerPt, radius, colorImgui, 24);
drawList->AddCircle(centerPt, radius, colorInvertedImgui, 24);
}
if (ImGui::ClickArea("##bararea", ImVec2(regionWidth + 2, barHeight), mouseReleased)) {
onColorBarClick();
}
}
void GuiVarData::onOpacityGraphClick() {
glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - opacityGraphBox.min;
glm::vec2 normalizedPosition = mousePosWidget / opacityGraphBox.getDimensions();
normalizedPosition.y = 1.0f - normalizedPosition.y;
normalizedPosition = glm::clamp(normalizedPosition, glm::vec2(0), glm::vec2(1));
dragging = false;
if (selectNearestOpacityPoint(currentSelectionIndex, mousePosWidget)) {
// A) Point near to normalized position
if (ImGui::GetIO().MouseClicked[0]) {
// A.1 Left clicked? Select/drag-and-drop
opacitySelection = opacityPoints.at(currentSelectionIndex).opacity;
selectedPointType = sgl::SELECTED_POINT_TYPE_OPACITY;
dragging = true;
} else if (ImGui::GetIO().MouseClicked[1] && currentSelectionIndex != 0
&& currentSelectionIndex != int(opacityPoints.size())-1) {
// A.2 Middle clicked? Delete point
opacityPoints.erase(opacityPoints.begin() + currentSelectionIndex);
selectedPointType = sgl::SELECTED_POINT_TYPE_NONE;
reRender = true;
}
} else {
// B) If no point near and left clicked: Create new point at position
if (ImGui::GetIO().MouseClicked[0]) {
// Compute insert position for new point
int insertPosition = 0;
for (insertPosition = 0; insertPosition < (int)opacityPoints.size(); insertPosition++) {
if (normalizedPosition.x < opacityPoints.at(insertPosition).position
|| insertPosition == int(opacityPoints.size())-1) {
break;
}
}
// Add new opacity point
glm::vec2 newPosition = normalizedPosition;
float newOpacity = newPosition.y;
opacityPoints.insert(opacityPoints.begin() + insertPosition, sgl::OpacityPoint(newOpacity, newPosition.x));
currentSelectionIndex = insertPosition;
opacitySelection = opacityPoints.at(currentSelectionIndex).opacity;
selectedPointType = sgl::SELECTED_POINT_TYPE_OPACITY;
dragging = true;
reRender = true;
}
}
rebuildTransferFunctionMap();
}
void GuiVarData::onColorBarClick() {
glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - colorBarBox.min;
float normalizedPosition = mousePosWidget.x / colorBarBox.getWidth();
dragging = false;
if (selectNearestColorPoint(currentSelectionIndex, mousePosWidget)) {
// A) Point near to normalized position
if (ImGui::GetIO().MouseClicked[0]) {
// A.1 Left clicked? Select/drag-and-drop
sgl::Color16& color16 = colorPoints.at(currentSelectionIndex).color;
colorSelection = ImColor(color16.getFloatR(), color16.getFloatG(), color16.getFloatB());
selectedPointType = sgl::SELECTED_POINT_TYPE_COLOR;
if (currentSelectionIndex != 0 && currentSelectionIndex != int(colorPoints.size())-1) {
dragging = true;
}
} else if (ImGui::GetIO().MouseClicked[1] && currentSelectionIndex != 0
&& currentSelectionIndex != int(colorPoints.size())-1) {
// A.2 Middle clicked? Delete point
colorPoints.erase(colorPoints.begin() + currentSelectionIndex);
colorPoints_LinearRGB.erase(colorPoints_LinearRGB.begin() + currentSelectionIndex);
selectedPointType = sgl::SELECTED_POINT_TYPE_NONE;
reRender = true;
}
} else {
// B) If no point near and left clicked: Create new point at position
if (ImGui::GetIO().MouseClicked[0]) {
// Compute insert position for new point
int insertPosition = 0;
for (insertPosition = 0; insertPosition < (int)colorPoints.size(); insertPosition++) {
if (normalizedPosition < colorPoints.at(insertPosition).position
|| insertPosition == int(colorPoints.size())-1) {
break;
}
}
// Add new color point
float newPosition = normalizedPosition;
if (interpolationColorSpace == sgl::COLOR_SPACE_LINEAR_RGB) {
// Linear RGB interplation
glm::vec3 newColor_linearRGB = glm::mix(
colorPoints_LinearRGB.at(insertPosition-1).color,
colorPoints_LinearRGB.at(insertPosition).color,
1.0 - (colorPoints_LinearRGB.at(insertPosition).position - newPosition)
/ (colorPoints_LinearRGB.at(insertPosition).position
- colorPoints_LinearRGB.at(insertPosition-1).position));
sgl::Color16 newColorsRGB(sgl::TransferFunctionWindow::linearRGBTosRGB(newColor_linearRGB));
colorPoints_LinearRGB.insert(
colorPoints_LinearRGB.begin() + insertPosition,
sgl::ColorPoint_LinearRGB(newColor_linearRGB, newPosition));
colorPoints.insert(
colorPoints.begin() + insertPosition,
sgl::ColorPoint_sRGB(newColorsRGB, newPosition));
} else {
// sRGB interpolation
sgl::Color16 newColor = sgl::color16Lerp(
colorPoints.at(insertPosition-1).color,
colorPoints.at(insertPosition).color,
1.0f - (colorPoints.at(insertPosition).position - newPosition)
/ (colorPoints.at(insertPosition).position - colorPoints.at(insertPosition-1).position));
colorPoints.insert(
colorPoints.begin() + insertPosition,
sgl::ColorPoint_sRGB(newColor, newPosition));
// colorPoints_LinearRGB computed in @ref rebuildTransferFunctionMap
}
currentSelectionIndex = insertPosition;
sgl::Color16& color16 = colorPoints.at(currentSelectionIndex).color;
colorSelection = ImColor(color16.getFloatR(), color16.getFloatG(), color16.getFloatB());
selectedPointType = sgl::SELECTED_POINT_TYPE_COLOR;
reRender = true;
}
}
rebuildTransferFunctionMap();
}
void GuiVarData::dragPoint() {
if (mouseReleased) {
dragging = false;
}
glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - opacityGraphBox.min;
if (!dragging || mousePosWidget == oldMousePosWidget) {
oldMousePosWidget = mousePosWidget;
return;
}
oldMousePosWidget = mousePosWidget;
if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY) {
glm::vec2 normalizedPosition = mousePosWidget / opacityGraphBox.getDimensions();
normalizedPosition.y = 1.0f - normalizedPosition.y;
normalizedPosition = glm::clamp(normalizedPosition, 0.0f, 1.0f);
if (currentSelectionIndex == 0) {
normalizedPosition.x = 0.0f;
}
if (currentSelectionIndex == int(opacityPoints.size())-1) {
normalizedPosition.x = 1.0f;
}
// Clip to neighbors!
if (currentSelectionIndex != 0
&& normalizedPosition.x < opacityPoints.at(currentSelectionIndex-1).position) {
normalizedPosition.x = opacityPoints.at(currentSelectionIndex-1).position;
}
if (currentSelectionIndex != int(opacityPoints.size())-1
&& normalizedPosition.x > opacityPoints.at(currentSelectionIndex+1).position) {
normalizedPosition.x = opacityPoints.at(currentSelectionIndex+1).position;
}
opacityPoints.at(currentSelectionIndex).position = normalizedPosition.x;
opacityPoints.at(currentSelectionIndex).opacity = normalizedPosition.y;
opacitySelection = opacityPoints.at(currentSelectionIndex).opacity;
}
if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR) {
float normalizedPosition = mousePosWidget.x / colorBarBox.getWidth();
normalizedPosition = glm::clamp(normalizedPosition, 0.0f, 1.0f);
// Clip to neighbors!
if (currentSelectionIndex != 0
&& normalizedPosition < colorPoints.at(currentSelectionIndex-1).position) {
normalizedPosition = colorPoints.at(currentSelectionIndex-1).position;
}
if (currentSelectionIndex != int(colorPoints.size())-1
&& normalizedPosition > colorPoints.at(currentSelectionIndex+1).position) {
normalizedPosition = colorPoints.at(currentSelectionIndex+1).position;
}
colorPoints.at(currentSelectionIndex).position = normalizedPosition;
}
rebuildTransferFunctionMap();
reRender = true;
}
bool GuiVarData::selectNearestOpacityPoint(int& currentSelectionIndex, const glm::vec2& mousePosWidget) {
float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor();
for (int i = 0; i < (int)opacityPoints.size(); i++) {
glm::vec2 centerPt = glm::vec2(
opacityPoints.at(i).position * opacityGraphBox.getWidth(),
(1.0f - opacityPoints.at(i).opacity) * opacityGraphBox.getHeight());
if (glm::length(centerPt - mousePosWidget) < scaleFactor * 10.0f) {
currentSelectionIndex = i;
return true;
}
}
return false;
}
bool GuiVarData::selectNearestColorPoint(int& currentSelectionIndex, const glm::vec2& mousePosWidget) {
float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor();
for (int i = 0; i < (int)colorPoints.size(); i++) {
ImVec2 centerPt = ImVec2(
colorPoints.at(i).position * colorBarBox.getWidth(),
colorBarBox.getHeight()/2);
if (glm::abs(centerPt.x - mousePosWidget.x) < scaleFactor * 10.0f) {
currentSelectionIndex = i;
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------------------------------------------------
MultiVarTransferFunctionWindow::MultiVarTransferFunctionWindow(
const std::string& saveDirectoryPrefix,
const std::vector<std::string>& tfPresetFiles) {
parentDirectory = sgl::AppSettings::get()->getDataDirectory();
saveDirectory = sgl::AppSettings::get()->getDataDirectory() + "TransferFunctions/";
if (!saveDirectoryPrefix.empty()) {
directoryName = saveDirectoryPrefix;
parentDirectory = saveDirectory;
saveDirectory = saveDirectory + saveDirectoryPrefix + "/";
}
this->tfPresetFiles = tfPresetFiles;
directoryContentWatch.setPath(saveDirectory, true);
directoryContentWatch.initialize();
#ifdef SUPPORT_OPENGL
if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) {
tfMapTextureSettings.type = sgl::TEXTURE_1D_ARRAY;
tfMapTextureSettings.internalFormat = GL_RGBA16;
}
#endif
#ifdef USE_VULKAN_INTEROP
if (sgl::AppSettings::get()->getPrimaryDevice()) {
tfMapImageSettingsVulkan.imageType = VK_IMAGE_TYPE_1D;
tfMapImageSettingsVulkan.format = VK_FORMAT_R16G16B16A16_UNORM;
}
#endif
updateAvailableFiles();
}
MultiVarTransferFunctionWindow::~MultiVarTransferFunctionWindow() {
}
void MultiVarTransferFunctionWindow::setAttributesValues(
const std::vector<std::string>& names,
const std::vector<std::vector<float>>& allAttributes) {
assert(names.size() == allAttributes.size());
varNames = names;
transferFunctionMap_sRGB.resize(TRANSFER_FUNCTION_TEXTURE_SIZE * names.size());
transferFunctionMap_linearRGB.resize(TRANSFER_FUNCTION_TEXTURE_SIZE * names.size());
selectedVarIndex = 0;
if (guiVarData.size() != names.size()){
guiVarData.clear();
guiVarData.reserve(names.size());
#ifdef SUPPORT_OPENGL
if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) {
tfMapTexture = sgl::TextureManager->createEmptyTexture(
TRANSFER_FUNCTION_TEXTURE_SIZE, int(names.size()), tfMapTextureSettings);
minMaxSsbo = sgl::Renderer->createGeometryBuffer(
names.size() * sizeof(glm::vec2), sgl::SHADER_STORAGE_BUFFER);
}
#endif
#ifdef USE_VULKAN_INTEROP
if (sgl::AppSettings::get()->getPrimaryDevice()) {
tfMapImageSettingsVulkan.width = TRANSFER_FUNCTION_TEXTURE_SIZE;
tfMapImageSettingsVulkan.arrayLayers = uint32_t(names.size());
tfMapTextureVulkan = std::make_shared<sgl::vk::Texture>(
sgl::AppSettings::get()->getPrimaryDevice(), tfMapImageSettingsVulkan,
VK_IMAGE_VIEW_TYPE_1D_ARRAY);
minMaxSsboVulkan = std::make_shared<sgl::vk::Buffer>(
sgl::AppSettings::get()->getPrimaryDevice(), names.size() * sizeof(glm::vec2),
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
VMA_MEMORY_USAGE_GPU_ONLY);
}
#endif
minMaxData.clear();
minMaxData.resize(names.size() * 2, 0);
for (size_t varIdx = 0; varIdx < names.size(); varIdx++) {
guiVarData.push_back(GuiVarData(
this, tfPresetFiles.size() > 0 ? tfPresetFiles.at(varIdx % tfPresetFiles.size()) : "",
&transferFunctionMap_sRGB.at(TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx),
&transferFunctionMap_linearRGB.at(TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx)
));
}
}
for (size_t varIdx = 0; varIdx < names.size(); varIdx++) {
GuiVarData& varData = guiVarData.at(varIdx);
varData.setAttributeValues(names.at(varIdx), allAttributes.at(varIdx));
}
currVarData = &guiVarData.at(selectedVarIndex);
updateAvailableFiles();
rebuildTransferFunctionMapComplete();
rebuildRangeSsbo();
}
bool MultiVarTransferFunctionWindow::loadFromTfNameList(const std::vector<std::string>& tfNames) {
if (tfNames.size() != guiVarData.size()) {
sgl::Logfile::get()->writeError(
"MultiVarTransferFunctionWindow::loadFromTfNameList: tfNames.size() != guiVarData.size()");
return false;
}
for (size_t varIdx = 0; varIdx < tfNames.size(); varIdx++) {
GuiVarData& varData = guiVarData.at(varIdx);
varData.loadTfFromFile(saveDirectory + tfNames.at(varIdx));
}
return true;
}
void MultiVarTransferFunctionWindow::updateAvailableFiles() {
sgl::FileUtils::get()->ensureDirectoryExists(saveDirectory);
std::vector<std::string> availableFilesAll = sgl::FileUtils::get()->getFilesInDirectoryVector(saveDirectory);
availableFiles.clear();
availableFiles.reserve(availableFilesAll.size());
for (const std::string& filename : availableFilesAll) {
if (sgl::FileUtils::get()->hasExtension(filename.c_str(), ".xml")) {
availableFiles.push_back(filename);
}
}
sgl::FileUtils::get()->sortPathStrings(availableFiles);
// Update currently selected filename
for (size_t i = 0; i < availableFiles.size(); i++) {
availableFiles.at(i) = sgl::FileUtils::get()->getPureFilename(availableFiles.at(i));
for (GuiVarData& varData : guiVarData) {
if (availableFiles.at(i) == varData.getSaveFileString()) {
varData.selectedFileIndex = (int)i;
}
}
}
}
void MultiVarTransferFunctionWindow::setClearColor(const sgl::Color& clearColor) {
this->clearColor = clearColor;
}
#ifdef SUPPORT_OPENGL
sgl::TexturePtr& MultiVarTransferFunctionWindow::getTransferFunctionMapTexture() {
return tfMapTexture;
}
#endif
#ifdef USE_VULKAN_INTEROP
sgl::vk::TexturePtr& MultiVarTransferFunctionWindow::getTransferFunctionMapTextureVulkan() {
return tfMapTextureVulkan;
}
#endif
bool MultiVarTransferFunctionWindow::getTransferFunctionMapRebuilt() {
if (transferFunctionMapRebuilt) {
// Reset the flag
transferFunctionMapRebuilt = false;
return true;
}
return false;
}
std::vector<sgl::Color16> MultiVarTransferFunctionWindow::getTransferFunctionMap_sRGB(int varIdx) {
return std::vector<sgl::Color16>(
transferFunctionMap_sRGB.cbegin() + TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx,
transferFunctionMap_sRGB.cbegin() + TRANSFER_FUNCTION_TEXTURE_SIZE * (varIdx + 1));
}
void MultiVarTransferFunctionWindow::update(float dt) {
directoryContentWatch.update([this] { this->updateAvailableFiles(); });
if (currVarData) {
currVarData->dragPoint();
}
}
void MultiVarTransferFunctionWindow::setUseLinearRGB(bool useLinearRGB) {
this->useLinearRGB = useLinearRGB;
rebuildTransferFunctionMapComplete();
}
void MultiVarTransferFunctionWindow::rebuildTransferFunctionMapComplete() {
for (GuiVarData& varData : guiVarData) {
varData.rebuildTransferFunctionMapLocal();
}
rebuildTransferFunctionMap();
}
void MultiVarTransferFunctionWindow::rebuildRangeSsbo() {
for (size_t varIdx = 0; varIdx < guiVarData.size(); varIdx++) {
GuiVarData& varData = guiVarData.at(varIdx);
const glm::vec2& range = varData.getSelectedRange();
minMaxData[varIdx * 2] = range.x;
minMaxData[varIdx * 2 + 1] = range.y;
}
#ifdef SUPPORT_OPENGL
if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) {
minMaxSsbo->subData(0, minMaxData.size() * sizeof(float), minMaxData.data());
}
#endif
#ifdef USE_VULKAN_INTEROP
if (sgl::AppSettings::get()->getPrimaryDevice()) {
minMaxSsboVulkan->uploadData(minMaxData.size() * sizeof(float), minMaxData.data());
}
#endif
}
void MultiVarTransferFunctionWindow::rebuildTransferFunctionMap() {
#ifdef SUPPORT_OPENGL
if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) {
sgl::PixelFormat pixelFormat;
pixelFormat.pixelType = GL_UNSIGNED_SHORT;
if (useLinearRGB) {
tfMapTexture->uploadPixelData(
TRANSFER_FUNCTION_TEXTURE_SIZE, int(varNames.size()),
transferFunctionMap_linearRGB.data(), pixelFormat);
} else {
tfMapTexture->uploadPixelData(
TRANSFER_FUNCTION_TEXTURE_SIZE, int(varNames.size()),
transferFunctionMap_sRGB.data(), pixelFormat);
}
}
#endif
#ifdef USE_VULKAN_INTEROP
if (sgl::AppSettings::get()->getPrimaryDevice()) {
if (useLinearRGB) {
tfMapTextureVulkan->getImage()->uploadData(
TRANSFER_FUNCTION_TEXTURE_SIZE * uint32_t(varNames.size()) * 8,
transferFunctionMap_linearRGB.data());
} else {
tfMapTextureVulkan->getImage()->uploadData(
TRANSFER_FUNCTION_TEXTURE_SIZE * uint32_t(varNames.size()) * 8,
transferFunctionMap_sRGB.data());
}
}
#endif
transferFunctionMapRebuilt = true;
}
bool MultiVarTransferFunctionWindow::renderGui() {
sgl::ImGuiWrapper::get()->setNextWindowStandardPosSize(2, 1278, 634, 818);
if (showWindow && ImGui::Begin("Multi-Var Transfer Function", &showWindow)) {
if (ImGui::BeginCombo("Variable", varNames.at(selectedVarIndex).c_str())) {
for (size_t i = 0; i < varNames.size(); ++i) {
if (ImGui::Selectable(varNames.at(i).c_str(), selectedVarIndex == i)) {
selectedVarIndex = i;
currVarData = &guiVarData.at(selectedVarIndex);
}
}
ImGui::EndCombo();
}
if (currVarData) {
reRender = currVarData->renderGui() || reRender;
}
ImGui::End();
}
if (reRender) {
reRender = false;
return true;
}
return false;
}
| 43.390196 | 123 | 0.64908 | FelixBrendel |
33fdf948cd6d64179e9d82b680ba30593b58de6f | 2,509 | cpp | C++ | src/cimple/tests/type/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | 4 | 2015-12-16T06:43:14.000Z | 2020-01-24T06:05:47.000Z | src/cimple/tests/type/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | src/cimple/tests/type/main.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | /*
**==============================================================================
**
** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**
**==============================================================================
*/
#include <cassert>
#include <cimple/cimple.h>
using namespace cimple;
void test(const char* name, Type expected_type)
{
Type type;
int status = type_name_to_type(name, type);
assert(status == 0);
assert(type == expected_type);
}
int main(int /* argc */, char** argv)
{
printf("Test+++ %s\n",argv[0]);
test("boolean", BOOLEAN);
test("uint8", UINT8);
test("sint8", SINT8);
test("uint16", UINT16);
test("sint16", SINT16);
test("uint32", UINT32);
test("sint32", SINT32);
test("uint64", UINT64);
test("sint64", SINT64);
test("real32", REAL32);
test("real64", REAL64);
test("char16", CHAR16);
test("string", STRING);
test("datetime", DATETIME);
test("BOOLEAN", BOOLEAN);
test("UINT8", UINT8);
test("SINT8", SINT8);
test("UINT16", UINT16);
test("SINT16", SINT16);
test("UINT32", UINT32);
test("SINT32", SINT32);
test("UINT64", UINT64);
test("SINT64", SINT64);
test("REAL32", REAL32);
test("REAL64", REAL64);
test("CHAR16", CHAR16);
test("STRING", STRING);
test("DATETIME", DATETIME);
printf("+++++ passed all tests (%s)\n", argv[0]);
return 0;
}
| 32.584416 | 80 | 0.62774 | LegalizeAdulthood |
33ff6e3d328c652ea717362e770c0dae140c6366 | 1,802 | hpp | C++ | networkit/cpp/embedding/BiasedRandomWalk.hpp | angriman/network | 3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894 | [
"MIT"
] | 366 | 2019-06-27T18:48:18.000Z | 2022-03-29T08:36:49.000Z | networkit/cpp/embedding/BiasedRandomWalk.hpp | angriman/network | 3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894 | [
"MIT"
] | 387 | 2019-06-24T11:30:39.000Z | 2022-03-31T10:37:28.000Z | networkit/cpp/embedding/BiasedRandomWalk.hpp | angriman/network | 3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894 | [
"MIT"
] | 131 | 2019-07-04T15:40:13.000Z | 2022-03-29T12:34:23.000Z | /*
* BiasedRandomWalk.hpp
*
* Created on: 03.07.2020
* Author: Klaus Ahrens <ahrens@informatik.hu-berlin.de>
*
* adapted and reimplemented from node2vec
* part of snap [https://github.com/snap-stanford/snap]
* Copyright (c) 2007-2019, Jure Leskovec (under BSD license)
*
* see [https://arxiv.org/pdf/1607.00653v1.pdf]
*
*/
#ifndef BIASEDRANDOMWALK_HPP
#define BIASEDRANDOMWALK_HPP
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <networkit/graph/Graph.hpp>
namespace NetworKit {
namespace Embedding {
class BiasedRandomWalk {
public:
using Walk = std::vector<node>; // one walk
using AllWalks = std::vector<Walk>; // n walks for all nodes: 2 dimensions in one big chunk
/// preprocesses transition probabilities for random walks. Has to be called once before doWalks
/// calls
void preprocessTransitionProbs(double paramP, double paramQ);
/// Simulates walks from every node and writes it into walks vector
AllWalks doWalks(count walkLen, count numberOfWalks);
BiasedRandomWalk(const Graph *graph);
private:
const Graph *graph;
using NeighborSet = std::unordered_set<node>;
using NeighborMap = std::unordered_map<node, AliasSampler>;
struct GraphData {
// assuming contiguous node numbers 0..n-1, they serve as indices
using Data = std::vector<NeighborMap>;
Data data;
GraphData(size_t nn) : data{nn, NeighborMap()} {}
};
std::unique_ptr<GraphData> graphData;
std::vector<std::vector<node>> index2node;
Walk oneWalk(node start, count walkLen);
void preprocessNode(node t, double paramP, double paramQ);
}; // class BiasedRandomWalk
} // namespace Embedding
} // namespace NetworKit
#endif // BIASEDRANDOMWALK_HPP
| 27.30303 | 100 | 0.704772 | angriman |
33ff8198ae66cc42da76d1efc0d75657d14fdb16 | 2,098 | cc | C++ | day06/part01/puzzle.cc | ovove/aoc19 | 7b74552cf376a699fe554afcae980d7de6dd18cd | [
"Unlicense"
] | null | null | null | day06/part01/puzzle.cc | ovove/aoc19 | 7b74552cf376a699fe554afcae980d7de6dd18cd | [
"Unlicense"
] | null | null | null | day06/part01/puzzle.cc | ovove/aoc19 | 7b74552cf376a699fe554afcae980d7de6dd18cd | [
"Unlicense"
] | null | null | null |
#include <string>
#include <string_view>
#include <iostream>
#include <regex>
#include <algorithm>
#include <map>
// #include <range/v3/all.hpp>
namespace {
using SatelliteGraph = std::map<std::string, std::vector<std::string>>;
SatelliteGraph map2graph(std::istream& map) {
SatelliteGraph result;
const std::regex regex(R"(([A-Z0-9]+)\)([A-Z0-9]+))");
for (std::string line; std::getline(map, line);) {
std::smatch match;
if (not std::regex_match(line, match, regex)) continue;
const auto& center = match[1];
const auto& satellite = match[2];
result[center].push_back(satellite);
static_cast<void>(result[satellite]);
}
return result;
}
using SatelliteDistances = std::map<std::string, unsigned>;
void checksum_(const SatelliteGraph& graph,
const std::string& satellite,
SatelliteDistances& satellite_distances,
unsigned distance) {
satellite_distances[satellite] = distance;
for (const auto next_satellite : graph.at(satellite)) {
checksum_(graph, next_satellite, satellite_distances, distance + 1);
}
}
unsigned checksum(const SatelliteGraph& graph) {
SatelliteDistances satellite_distances;
checksum_(graph, "COM", satellite_distances, 0);
unsigned tot_dist = 0;
for (auto [satellite, distance] : satellite_distances) tot_dist += distance;
return tot_dist;
}
} // namespace
#if not defined(DO_UNIT_TEST)
#include <filesystem>
#include <fstream>
int main() {
using std::filesystem::path;
std::ifstream input(path(BINARY_DIR) / path("..") / path("input"));
const auto graph = map2graph(input);
const auto chksum = checksum(graph);
std::cout << chksum << std::endl;
}
#else // DO_UNIT_TEST
#include <gtest/gtest.h>
#include <sstream>
TEST(DAY06_PART01, TEST01) {
const std::string map = R"(
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L)";
std::istringstream iss(map);
const auto graph = map2graph(iss);
const auto chksum = checksum(graph);
ASSERT_EQ(chksum, 42);
}
#endif // DO_UNIT_TEST
| 23.840909 | 80 | 0.659676 | ovove |
d5018e36c13540c04dfcdf308c8537bae3c2e67d | 413 | hpp | C++ | include/httplib/http/response.hpp | andrusha97/httplib | 3f1733ea03c009c22393a99eadc006befd5b4942 | [
"MIT"
] | null | null | null | include/httplib/http/response.hpp | andrusha97/httplib | 3f1733ea03c009c22393a99eadc006befd5b4942 | [
"MIT"
] | null | null | null | include/httplib/http/response.hpp | andrusha97/httplib | 3f1733ea03c009c22393a99eadc006befd5b4942 | [
"MIT"
] | null | null | null | #pragma once
#include <httplib/detail/common.hpp>
#include <httplib/http/headers.hpp>
#include <httplib/http/version.hpp>
#include <string>
HTTPLIB_OPEN_NAMESPACE
struct http_response_t {
unsigned int code = 0;
std::string reason;
http_version_t version;
http_headers_t headers;
};
std::ostream &operator<<(std::ostream &stream, const http_response_t &response);
HTTPLIB_CLOSE_NAMESPACE
| 16.52 | 80 | 0.748184 | andrusha97 |
d501a76112ee571565b25b56c1e25347067fbe08 | 19,005 | hpp | C++ | include/tudocomp/compressors/lfs/LFS2Compressor.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-09-22T11:29:02.000Z | 2020-09-22T11:29:02.000Z | include/tudocomp/compressors/lfs/LFS2Compressor.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/tudocomp/compressors/lfs/LFS2Compressor.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-09-29T08:57:13.000Z | 2020-09-29T08:57:13.000Z | #pragma once
#include <tudocomp/config.h>
#ifndef SDSL_FOUND
#pragma message "SDSL required, but not available!"
#else
//std includes:
#include <vector>
#include <tuple>
//general includes:
#include <tudocomp/util.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/Compressor.hpp>
#include <tudocomp/Error.hpp>
#include <tudocomp/Tags.hpp>
#include <tudocomp_stat/StatPhase.hpp>
//sdsl include stree:
#include <sdsl/suffix_trees.hpp>
//includes encoding:
#include <tudocomp/io/BitOStream.hpp>
#include <tudocomp/coders/EliasGammaCoder.hpp>
#include <tudocomp/coders/HuffmanCoder.hpp>
//decompressor:
#include <tudocomp/decompressors/LFS2Decompressor.hpp>
namespace tdc {
namespace lfs {
template<
typename literal_coder_t = HuffmanCoder,
typename len_coder_t = EliasGammaCoder
>
class LFS2Compressor : public Compressor {
private:
//Suffix Tree type + st
typedef sdsl::cst_sct3< sdsl::csa_bitcompressed<> > cst_t;
cst_t stree;
using node_type = typename cst_t::node_type;
//Stores nts_symbols of first layer
IntVector<uint> first_layer_nts;
// offset to begin of last nts +1. if ==0 no substitution
IntVector<uint> fl_offsets;
// stores subs in first layer symbols
IntVector<uint> second_layer_nts;
// dead pos in first layer
BitVector second_layer_dead;
//pair contains begin pos, length
std::vector<std::pair<uint, uint> > non_terminal_symbols;
//stores node_ids of corresponding factor length
std::vector<std::vector<uint> > bins;
//stores beginning positions corresponding to node_ids
std::vector<std::vector<uint> > node_begins;
bool exact;
uint size;
public:
inline static Meta meta() {
Meta m(Compressor::type_desc(), "lfs2", "lfs2 with simst");
m.param("min_lrf").primitive(5);
m.param("exact").primitive(0);
m.param("lfs2_lit_coder").strategy<literal_coder_t>(
Coder::type_desc(), Meta::Default<HuffmanCoder>());
m.param("lfs2_len_coder").strategy<len_coder_t>(
Coder::type_desc(), Meta::Default<EliasGammaCoder>());
m.add_tag(tags::require_sentinel);
return m;
}
using Compressor::Compressor;
inline virtual void compress(Input& input, Output& output) override {
uint min_lrf = config().param("min_lrf").as_uint();
exact = config().param("exact").as_bool();
auto in = input.as_view();
MissingSentinelError::check(in);
//create vectors:
first_layer_nts = IntVector<uint>(input.size(), 0);
fl_offsets = IntVector<uint>(input.size(), 0);
second_layer_nts = IntVector<uint>(input.size(), 0);
second_layer_dead = BitVector(input.size(), 0);
if(in.size() >= min_lrf){
StatPhase::wrap("Constructing ST", [&]{
size = in.size();
//remove sentinel because sdsl cant handle that
while(in[size-1] == 0){
size--;
}
std::string in_string ((const char*) in.data(), size);
sdsl::construct_im(stree, in_string , 1);
});
StatPhase::wrap("Computing LRF", [&]{
bins.resize(200);
uint node_counter = 0;
typedef sdsl::cst_bfs_iterator<cst_t> iterator;
iterator begin = iterator(&stree, stree.root());
iterator end = iterator(&stree, stree.root(), true, true);
StatPhase::wrap("Iterate over ST", [&]{
DLOG(INFO)<<"iterate st";
for (iterator it = begin; it != end; ++it) {
if(!stree.is_leaf(*it)){
if(bins.size() <= stree.depth(*it)) {
uint resize = bins.size()*2;
while (resize<= stree.depth(*it)) {
resize*=2;
}
bins.resize(resize);
}
bins[stree.depth(*it)].push_back(stree.id(*it));
node_counter++;
}
}
});
node_begins.resize(node_counter);
uint nts_number = 1 ;
StatPhase::wrap("Iterate over Node Bins", [&]{
//iterate node bins top down
DLOG(INFO)<<"iterate over Node Bins";
for(uint i = bins.size()-1; i>=min_lrf; i--){
//iterate over ids in bin:
while(!bins[i].empty()){
uint id = bins[i].back();
bins[i].pop_back();
node_type node = stree.inv_id(id);
uint no_leaf_id = id - stree.size();
//get bps of node
if(node_begins[no_leaf_id].empty()){
//get leaves or merge child vectors
std::vector<uint> offsets;
std::vector<uint> leaf_bps;
for (auto & child : stree.children(node)) {
if(stree.is_leaf(child)){
leaf_bps.push_back(stree.csa[stree.lb(child)]);
} else {
int child_id = stree.id(child) - stree.size();
if(!node_begins[child_id ].empty()){
//append child list, remember offset
offsets.push_back(node_begins[no_leaf_id].size());
node_begins[no_leaf_id].insert(node_begins[no_leaf_id].end(),node_begins[child_id ].begin(), node_begins[child_id].end());
node_begins[child_id] = std::vector<uint>();
}
}
}
std::sort(leaf_bps.begin(), leaf_bps.end());
offsets.push_back(node_begins[no_leaf_id].size());
node_begins[no_leaf_id].insert(node_begins[no_leaf_id].end(),leaf_bps.begin(), leaf_bps.end());
//inplace merge with offset
for(uint k = 0; k < offsets.size()-1; k++){
std::inplace_merge(node_begins[no_leaf_id].begin(), node_begins[no_leaf_id].begin()+ offsets[k], node_begins[no_leaf_id].begin()+ offsets[k+1]);
}
//now inplace merge to end
std::inplace_merge(node_begins[no_leaf_id].begin(), node_begins[no_leaf_id].begin()+ offsets.back(), node_begins[no_leaf_id].end());
}
//if still empty, because everything is substituted...
if(node_begins[no_leaf_id].empty()){
continue;
}
//check if viable lrf, else sort higher!
if((node_begins[no_leaf_id].size()>=2)){
if (( (uint)( node_begins[no_leaf_id].back() - node_begins[no_leaf_id].front() )) >= i ){
//greedily iterate over occurences
signed long last = 0 - (long) i;
std::vector<uint> first_layer_viable;
std::vector<uint> second_layer_viable;
for(uint occurence : node_begins[no_leaf_id]){
//check for viability
if( (last+i <= (long) occurence)){
if(fl_offsets[occurence] == 0){
if(fl_offsets[occurence + i -1] == 0){
//Position is firs layer viable
first_layer_viable.push_back(occurence);
last= occurence;
}
} else {
//find nts number of symbol that corresponds to substitued occ
uint parent_nts= first_layer_nts[ occurence - (fl_offsets[occurence] -1) ];
auto nts = non_terminal_symbols[parent_nts-1];
//if length of parent nts is greater than current len + offset
if(nts.second >=fl_offsets[occurence]-1 + i ){
second_layer_viable.push_back(occurence);
}
}
}
}
//and substitute
//if at least 2 first level layer occs viable:
if(first_layer_viable.size() >=1 &&(first_layer_viable.size() + second_layer_viable.size() >= 2) ) {
std::pair<uint,uint> nts = std::make_pair(first_layer_viable.front(), i);
non_terminal_symbols.push_back(nts);
//iterate over vector, make first layer unviable:
for(uint occ : first_layer_viable){
first_layer_nts[occ]= nts_number;
for(uint nts_length =0; nts_length < i; nts_length++){
fl_offsets[occ + nts_length] = nts_length+1;
}
}
for(uint sl_occ :second_layer_viable){
uint parent_nts= first_layer_nts[ sl_occ - (fl_offsets[sl_occ] -1) ];
auto parent_sym = non_terminal_symbols[parent_nts-1];
uint parent_start= parent_sym.first;
uint sl_start = (parent_start + fl_offsets[sl_occ] -1);
uint sl_end = sl_start+i-1;
if(second_layer_dead[sl_start] == (uint)0 && second_layer_dead[sl_end] == (uint)0){
second_layer_nts[sl_start]=nts_number;
for(uint dead = sl_start; dead<=sl_end;dead++){
second_layer_dead[dead]=1;
}
}
}
//raise nts number:
nts_number++;
}
} else {
if(exact){
//readd node if lrf shorter
uint min_shorter = node_begins[no_leaf_id].back() - node_begins[no_leaf_id].front();
//check if parent subs this lrf
node_type parent = stree.parent(node);
uint depth = stree.depth(parent);
if(depth < (min_shorter)){
//just re-add node, if the possible replaceable lrf is longer than dpeth of parent node
bins[min_shorter].push_back(stree.id(node));
}
}
continue;
}
}
}
}
});
});
DLOG(INFO)<<"Computing symbol depth";
IntVector<uint> nts_depth(non_terminal_symbols.size(), 0);
for(uint nts_num =0; nts_num<non_terminal_symbols.size(); nts_num++){
auto symbol = non_terminal_symbols[nts_num];
uint cur_depth = nts_depth[nts_num];
for(uint pos = symbol.first; pos < symbol.second + symbol.first ; pos++){
if(second_layer_nts[pos]>0){
uint symbol_num = second_layer_nts[pos] -1;
if(nts_depth[symbol_num]< cur_depth+1){
nts_depth[symbol_num]= cur_depth+1;
}
}
}
}
DLOG(INFO)<<"Computing done";
std::sort(nts_depth.begin(), nts_depth.end());
if(nts_depth.size()>0){
uint max_depth = nts_depth[nts_depth.size()-1];
DLOG(INFO)<<"Max CFG Depth: "<< max_depth;
DLOG(INFO)<<"Number of CFG rules: "<< non_terminal_symbols.size();
if(nts_depth.size()>=4){
uint quarter = nts_depth.size() /4;
StatPhase::log("25 \% quantil CFG Depth", nts_depth[quarter -1]);
StatPhase::log("50 \% quantil CFG Depth", nts_depth[(2*quarter) -1]);
StatPhase::log("75 \% quantil CFG Depth", nts_depth[(3*quarter) -1]);
}
StatPhase::log("Max CFG Depth", max_depth);
}
//input size end
}
StatPhase::log("Number of CFG rules", non_terminal_symbols.size());
std::stringstream literals;
for(uint position = 0; position< in.size(); position++){
if(fl_offsets[position]==0){
literals << in[position];
}
}
for(uint nts_num = 0; nts_num<non_terminal_symbols.size(); nts_num++){
auto symbol = non_terminal_symbols[nts_num];
for(uint pos = symbol.first; pos < symbol.second + symbol.first; pos++){
if(second_layer_nts[pos] == 0 && pos < in.size()){
literals<< in[pos];
}
}
}
StatPhase::wrap("Encoding Comp", [&]{
// encode dictionary:
DLOG(INFO) << "encoding dictionary symbol sizes ";
std::shared_ptr<BitOStream> bitout = std::make_shared<BitOStream>(output);
typename literal_coder_t::Encoder lit_coder(
config().sub_config("lfs2_lit_coder"),
bitout,
ViewLiterals(literals.str())
);
typename len_coder_t::Encoder len_coder(
config().sub_config("lfs2_len_coder"),
bitout,
NoLiterals()
);
//encode lengths:
DLOG(INFO)<<"number nts: " << non_terminal_symbols.size();
Range intrange (0, UINT_MAX);
//encode first length:
if(non_terminal_symbols.size()>=1){
auto symbol = non_terminal_symbols[0];
uint last_length=symbol.second;
//Range for encoding nts number
Range s_length_r (0,last_length);
len_coder.encode(last_length,intrange);
//encode delta length of following symbols
for(uint nts_num = 1; nts_num < non_terminal_symbols.size(); nts_num++){
symbol = non_terminal_symbols[nts_num];
len_coder.encode(last_length-symbol.second,s_length_r);
last_length=symbol.second;
}
//encode last length, to have zero length last
len_coder.encode(symbol.second,s_length_r);
}else {
len_coder.encode(0ULL,intrange);
}
Range dict_r(0, non_terminal_symbols.size());
long buf_size = bitout->stream().tellp();
StatPhase::log("Bytes Length Encoding", buf_size);
DLOG(INFO)<<"Bytes Length Encoding: "<< buf_size;
DLOG(INFO) << "encoding dictionary symbols";
uint dict_literals=0;
// encode dictionary strings, backwards, to directly decode strings:
if(non_terminal_symbols.size()>=1){
std::pair<uint,uint> symbol;
for(long nts_num =non_terminal_symbols.size()-1; nts_num >= 0; nts_num--){
symbol = non_terminal_symbols[nts_num];
for(uint pos = symbol.first; pos < symbol.second + symbol.first ; pos++){
if(second_layer_nts[pos] > 0){
lit_coder.encode(1, bit_r);
lit_coder.encode(second_layer_nts[pos], dict_r);
auto symbol = non_terminal_symbols[second_layer_nts[pos] -1];
pos += symbol.second - 1;
} else {
lit_coder.encode(0, bit_r);
lit_coder.encode(in[pos],literal_r);
dict_literals++;
}
}
}
}
uint literals=0;
buf_size = long(bitout->stream().tellp()) - buf_size;
StatPhase::log("Bytes Non-Terminal Symbol Encoding", buf_size);
DLOG(INFO)<<"Bytes Non-Terminal Symbol Encoding: "<< buf_size;
//encode start symbol
DLOG(INFO)<<"encode start symbol";
for(uint pos = 0; pos < in.size(); pos++){
if(first_layer_nts[pos]>0){
lit_coder.encode(1, bit_r);
lit_coder.encode(first_layer_nts[pos], dict_r);
auto symbol = non_terminal_symbols[first_layer_nts[pos] -1];
pos += symbol.second - 1;
} else {
lit_coder.encode(0, bit_r);
lit_coder.encode(in[pos],literal_r);
literals++;
}
}
buf_size = long(bitout->stream().tellp()) - buf_size;
StatPhase::log("Bytes Start Symbol Encoding", buf_size);
DLOG(INFO)<<"Bytes Start Symbol Encoding: "<< buf_size;
StatPhase::log("Literals in Dictionary", dict_literals);
StatPhase::log("Literals in Start Symbol", literals);
StatPhase::log("Literals in Input", in.size());
double literal_percent = ((double)dict_literals + (double)literals)/ (double)in.size();
StatPhase::log("Literals Encoding / Literals Input", literal_percent);
DLOG(INFO)<<"encoding done";
});
}
inline std::unique_ptr<Decompressor> decompressor() const override {
return Algorithm::instance<
LFS2Decompressor<literal_coder_t, len_coder_t>>();
}
};
//namespaces closing
}}
#endif
| 37.858566 | 176 | 0.473612 | 421408 |
d5046672da82a39afaaa79a713ad8494c3e43f72 | 11,486 | cpp | C++ | background-change.cpp | 2vin/background-changing | c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f | [
"MIT"
] | null | null | null | background-change.cpp | 2vin/background-changing | c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f | [
"MIT"
] | 1 | 2018-05-27T18:56:25.000Z | 2018-05-27T18:56:25.000Z | background-change.cpp | 2vin/background-changing | c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f | [
"MIT"
] | 1 | 2018-09-05T11:18:06.000Z | 2018-09-05T11:18:06.000Z | #include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
Mat myMask;
Mat myFrame;
Mat origFrame;
int frameCols = 0, frameRows = 0;
Mat refine(Mat frame, Mat mask);
static void help()
{
cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
"and then grabcut will attempt to segment it out.\n"
"Call:\n"
"./grabcut <image_name>\n"
"\nSelect a rectangular area around the object you want to segment\n" <<
"\nHot keys: \n"
"\tESC - quit the program\n"
"\tr - restore the original image\n"
"\tn - next iteration\n"
"\n"
"\tleft mouse button - set rectangle\n"
"\n"
"\tCTRL+left mouse button - set GC_BGD pixels\n"
"\tSHIFT+left mouse button - set GC_FGD pixels\n"
"\n"
"\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
"\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl;
}
const Scalar RED = Scalar(0,0,255);
const Scalar PINK = Scalar(230,130,255);
const Scalar BLUE = Scalar(255,0,0);
const Scalar LIGHTBLUE = Scalar(255,255,160);
const Scalar GREEN = Scalar(0,255,0);
const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;
static void getBinMask( const Mat& comMask, Mat& binMask )
{
if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
binMask.create( comMask.size(), CV_8UC1 );
binMask = comMask & 1;
}
class GCApplication
{
public:
enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
static const int radius = 2;
static const int thickness = -1;
void reset();
void setImageAndWinName( const Mat& _image, const string& _winName );
void showImage() const;
void mouseClick( int event, int x, int y, int flags, void* param );
int nextIter();
int getIterCount() const { return iterCount; }
private:
void setRectInMask();
void setLblsInMask( int flags, Point p, bool isPr );
const string* winName;
const Mat* image;
Mat mask;
Mat bgdModel, fgdModel;
uchar rectState, lblsState, prLblsState;
bool isInitialized;
Rect rect;
vector<Point> fgdPxls, bgdPxls, prFgdPxls, prBgdPxls;
int iterCount;
};
void GCApplication::reset()
{
if( !mask.empty() )
mask.setTo(Scalar::all(GC_BGD));
bgdPxls.clear(); fgdPxls.clear();
prBgdPxls.clear(); prFgdPxls.clear();
isInitialized = false;
rectState = NOT_SET;
lblsState = NOT_SET;
prLblsState = NOT_SET;
iterCount = 0;
}
void GCApplication::setImageAndWinName( const Mat& _image, const string& _winName )
{
if( _image.empty() || _winName.empty() )
return;
image = &_image;
winName = &_winName;
mask.create( image->size(), CV_8UC1);
reset();
}
void GCApplication::showImage() const
{
if( image->empty() || winName->empty() )
return;
Mat res;
Mat binMask;
if( !isInitialized )
image->copyTo( res );
else
{
getBinMask( mask, binMask );
image->copyTo( res, binMask );
}
vector<Point>::const_iterator it;
for( it = bgdPxls.begin(); it != bgdPxls.end(); ++it )
circle( res, *it, radius, BLUE, thickness );
for( it = fgdPxls.begin(); it != fgdPxls.end(); ++it )
circle( res, *it, radius, RED, thickness );
for( it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it )
circle( res, *it, radius, LIGHTBLUE, thickness );
for( it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it )
circle( res, *it, radius, PINK, thickness );
if( rectState == IN_PROCESS || rectState == SET )
rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);
imshow( *winName, res );
if(!binMask.empty())
{
myFrame = res.clone();
normalize(binMask, myMask, 0, 255, NORM_MINMAX, -1, Mat() );
}
}
void GCApplication::setRectInMask()
{
CV_Assert( !mask.empty() );
mask.setTo( GC_BGD );
rect.x = max(0, rect.x);
rect.y = max(0, rect.y);
rect.width = min(rect.width, image->cols-rect.x);
rect.height = min(rect.height, image->rows-rect.y);
(mask(rect)).setTo( Scalar(GC_PR_FGD) );
}
void GCApplication::setLblsInMask( int flags, Point p, bool isPr )
{
vector<Point> *bpxls, *fpxls;
uchar bvalue, fvalue;
if( !isPr )
{
bpxls = &bgdPxls;
fpxls = &fgdPxls;
bvalue = GC_BGD;
fvalue = GC_FGD;
}
else
{
bpxls = &prBgdPxls;
fpxls = &prFgdPxls;
bvalue = GC_PR_BGD;
fvalue = GC_PR_FGD;
}
if( flags & BGD_KEY )
{
bpxls->push_back(p);
circle( mask, p, radius, bvalue, thickness );
}
if( flags & FGD_KEY )
{
fpxls->push_back(p);
circle( mask, p, radius, fvalue, thickness );
}
}
void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
{
if( rectState == NOT_SET )
{
rect = Rect( Point(0, 0), Point(frameCols,frameRows) );
rectState = SET;
setRectInMask();
CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
//showImage();
}
// TODO add bad args check
switch( event )
{
case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
{
bool isb = (flags & BGD_KEY) != 0,
isf = (flags & FGD_KEY) != 0;
if( rectState == NOT_SET && !isb && !isf )
{
rectState = IN_PROCESS;
rect = Rect( x, y, 1, 1 );
}
if ( (isb || isf) && rectState == SET )
lblsState = IN_PROCESS;
}
break;
case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
{
bool isb = (flags & BGD_KEY) != 0,
isf = (flags & FGD_KEY) != 0;
if ( (isb || isf) && rectState == SET )
prLblsState = IN_PROCESS;
}
break;
case EVENT_LBUTTONUP:
if( rectState == IN_PROCESS )
{
rect = Rect( Point(rect.x, rect.y), Point(x,y) );
rectState = SET;
setRectInMask();
CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
showImage();
}
if( lblsState == IN_PROCESS )
{
setLblsInMask(flags, Point(x,y), false);
lblsState = SET;
showImage();
}
break;
case EVENT_RBUTTONUP:
if( prLblsState == IN_PROCESS )
{
setLblsInMask(flags, Point(x,y), true);
prLblsState = SET;
showImage();
}
break;
case EVENT_MOUSEMOVE:
if( rectState == IN_PROCESS )
{
rect = Rect( Point(rect.x, rect.y), Point(x,y) );
CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
showImage();
}
else if( lblsState == IN_PROCESS )
{
setLblsInMask(flags, Point(x,y), false);
showImage();
}
else if( prLblsState == IN_PROCESS )
{
setLblsInMask(flags, Point(x,y), true);
showImage();
}
break;
}
}
int GCApplication::nextIter()
{
if( isInitialized )
grabCut( *image, mask, rect, bgdModel, fgdModel, 1 );
else
{
if( rectState != SET )
return iterCount;
if( lblsState == SET || prLblsState == SET )
grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK );
else
grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT );
isInitialized = true;
}
iterCount++;
bgdPxls.clear(); fgdPxls.clear();
prBgdPxls.clear(); prFgdPxls.clear();
return iterCount;
}
GCApplication gcapp;
static void on_mouse( int event, int x, int y, int flags, void* param )
{
gcapp.mouseClick( event, x, y, flags, param );
}
int main( int argc, char** argv )
{
string filename = argv[1];
if( filename.empty() )
{
cout << "\nDurn, empty filename" << endl;
return 1;
}
Mat image = imread( filename, 1 );
origFrame = image.clone();
if(image.cols>1200)
{
resize(image, image, Size(), 0.3, 0.3);
}
if( image.empty() )
{
cout << "\n Durn, couldn't read image filename " << filename << endl;
return 1;
}
help();
frameCols = image.cols;
frameRows = image.rows;
const string winName = "image";
namedWindow( winName, WINDOW_AUTOSIZE );
setMouseCallback( winName, on_mouse, 0 );
gcapp.setImageAndWinName( image, winName );
gcapp.showImage();
for(;;)
{
int c = waitKey(0);
switch( (char) c )
{
case '\x1b':
cout << "Exiting ..." << endl;
goto exit_main;
case 'r':
cout << endl;
gcapp.reset();
gcapp.showImage();
break;
case 'n':
int iterCount = gcapp.getIterCount();
// cout << "<" << iterCount << "... ";
int newIterCount = gcapp.nextIter();
if( newIterCount > iterCount )
{
gcapp.showImage();
// cout << iterCount << ">" << endl;
}
else
cout << "rect must be determined>" << endl;
break;
}
if(!myMask.empty())
{
myFrame = origFrame.clone();
resize(myMask,myMask, origFrame.size());
Mat temp = myFrame.clone();
Mat White = Mat(myFrame.rows, myFrame.cols, CV_8UC3, Scalar(255,255,255));
myMask.convertTo(myMask, CV_8UC1);
Mat smooth;
Mat dilated;
Mat blurBin;
Mat myFrame2 = myFrame.clone();
dilate(myMask, dilated, Mat());
for(int i=1; i<myFrame.cols/300; i++)
{
dilate(dilated, dilated, Mat());
}
blur(myFrame, smooth, Size(myFrame.cols/100, myFrame.cols/100));
smooth.copyTo(myFrame, dilated);
myFrame2.copyTo(myFrame, myMask);
//dilate(myMask, myMask, Mat());
blur(myMask, blurBin, Size(myFrame.cols/200, myFrame.cols/200));
blurBin=blurBin;
cvtColor(blurBin, blurBin, CV_GRAY2BGR);
// cout<<blurBin.size()<<" "<<blurBin.channels()<<endl;
Mat background = imread(argv[2]);
double scale = myFrame.rows*1.0/background.rows;
resize(background, background, Size(), scale, scale);
background = background(Rect(0,0,myFrame.cols, myFrame.rows));
// Background image
for(int i=0; i<origFrame.cols; i++)
{
for(int j=0; j<origFrame.rows; j++)
{
myFrame.at<Vec3b>(j,i)[0] = ((blurBin.at<Vec3b>(j,i)[0])/255.0)*myFrame.at<Vec3b>(j,i)[0]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[0];
myFrame.at<Vec3b>(j,i)[1] = ((blurBin.at<Vec3b>(j,i)[1])/255.0)*myFrame.at<Vec3b>(j,i)[1]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[1];
myFrame.at<Vec3b>(j,i)[2] = ((blurBin.at<Vec3b>(j,i)[2])/255.0)*myFrame.at<Vec3b>(j,i)[2]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[2];
}
}
imshow("Result", myFrame);
imwrite("Result.jpg", myFrame);
}
}
exit_main:
destroyWindow( winName );
return 0;
}
| 27.544365 | 164 | 0.560334 | 2vin |
d50a813b21c4a7125a568638f8d335fae4043844 | 115 | cpp | C++ | imgui_glfw_binding_source.cpp | CheezLang/imgui | 984aa3e5be8d240e19ba6f2395c607320145d32e | [
"MIT"
] | null | null | null | imgui_glfw_binding_source.cpp | CheezLang/imgui | 984aa3e5be8d240e19ba6f2395c607320145d32e | [
"MIT"
] | null | null | null | imgui_glfw_binding_source.cpp | CheezLang/imgui | 984aa3e5be8d240e19ba6f2395c607320145d32e | [
"MIT"
] | null | null | null | #if !defined(DONT_DEFINE_TYPES)
#endif
#include "F:/Programming/CppLibs/imgui/imgui/examples/imgui_impl_glfw.h"
| 16.428571 | 72 | 0.791304 | CheezLang |
d50d608dc4b92b0c6251b547d8b1de3d39119f2a | 17,818 | cpp | C++ | Plugin/Source/PluginProcessor.cpp | b00leant/audiogridder | 719ba3b83befa7cb371028c592f4246757dcd31e | [
"MIT"
] | 1 | 2020-05-06T12:52:45.000Z | 2020-05-06T12:52:45.000Z | Plugin/Source/PluginProcessor.cpp | b00leant/audiogridder | 719ba3b83befa7cb371028c592f4246757dcd31e | [
"MIT"
] | null | null | null | Plugin/Source/PluginProcessor.cpp | b00leant/audiogridder | 719ba3b83befa7cb371028c592f4246757dcd31e | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 Andreas Pohl
* Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING)
*
* Author: Andreas Pohl
*/
#include "PluginProcessor.hpp"
#include <signal.h>
#include "PluginEditor.hpp"
#include "json.hpp"
using json = nlohmann::json;
AudioGridderAudioProcessor::AudioGridderAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor(BusesProperties()
#if !JucePlugin_IsMidiEffect
#if !JucePlugin_IsSynth
.withInput("Input", AudioChannelSet::stereo(), true)
#endif
.withOutput("Output", AudioChannelSet::stereo(), true)
#endif
),
#endif
m_client(this) {
signal(SIGPIPE, SIG_IGN);
File cfg(PLUGIN_CONFIG_FILE);
try {
if (cfg.exists()) {
FileInputStream fis(cfg);
json j = json::parse(fis.readEntireStreamAsString().toStdString());
if (j.find("Servers") != j.end()) {
for (auto& srv : j["Servers"]) {
m_servers.push_back(srv.get<std::string>());
}
}
if (j.find("Last") != j.end()) {
m_activeServer = j["Last"].get<int>();
}
if (j.find("NumberOfBuffers") != j.end()) {
m_client.NUM_OF_BUFFERS = j["NumberOfBuffers"].get<int>();
}
if (j.find("NumberOfAutomationSlots") != j.end()) {
m_numberOfAutomationSlots = j["NumberOfAutomationSlots"].get<int>();
}
}
} catch (json::parse_error& e) {
logln_clnt(&m_client, "parsing config failed: " << e.what());
}
m_unusedParam.name = "(unassigned)";
m_unusedDummyPlugin.name = "(unused)";
m_unusedDummyPlugin.bypassed = false;
m_unusedDummyPlugin.ok = true;
m_unusedDummyPlugin.params.add(m_unusedParam);
for (int i = 0; i < m_numberOfAutomationSlots; i++) {
addParameter(new Parameter(*this, i));
}
// load plugins on reconnect
m_client.setOnConnectCallback([this] {
int idx = 0;
for (auto& p : m_loadedPlugins) {
p.ok = m_client.addPlugin(p.id, p.presets, p.params, p.settings);
logln_clnt(&m_client, "loading " << p.name << " (" << p.id << ")... " << (p.ok ? "ok" : "failed"));
if (p.ok) {
logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples());
setLatencySamples(m_client.getLatencySamples());
if (p.bypassed) {
m_client.bypassPlugin(idx);
}
for (auto& p : p.params) {
if (p.automationSlot > -1) {
if (p.automationSlot < m_numberOfAutomationSlots) {
enableParamAutomation(idx, p.idx, p.automationSlot);
} else {
p.automationSlot = -1;
}
}
}
}
idx++;
}
MessageManager::callAsync([this] {
auto* editor = getActiveEditor();
if (editor != nullptr) {
dynamic_cast<AudioGridderAudioProcessorEditor*>(editor)->setConnected(true);
}
});
});
// handle connection close
m_client.setOnCloseCallback([this] {
MessageManager::callAsync([this] {
auto* editor = getActiveEditor();
if (editor != nullptr) {
dynamic_cast<AudioGridderAudioProcessorEditor*>(editor)->setConnected(false);
}
});
});
if (m_activeServer > -1 && m_activeServer < m_servers.size()) {
m_client.setServer(m_servers[m_activeServer]);
}
}
AudioGridderAudioProcessor::~AudioGridderAudioProcessor() {
m_client.signalThreadShouldExit();
m_client.close();
}
const String AudioGridderAudioProcessor::getName() const { return JucePlugin_Name; }
bool AudioGridderAudioProcessor::acceptsMidi() const {
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool AudioGridderAudioProcessor::producesMidi() const {
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool AudioGridderAudioProcessor::isMidiEffect() const {
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double AudioGridderAudioProcessor::getTailLengthSeconds() const { return 0.0; }
bool AudioGridderAudioProcessor::supportsDoublePrecisionProcessing() const { return true; }
int AudioGridderAudioProcessor::getNumPrograms() { return 1; }
int AudioGridderAudioProcessor::getCurrentProgram() { return 0; }
void AudioGridderAudioProcessor::setCurrentProgram(int index) {}
const String AudioGridderAudioProcessor::getProgramName(int index) { return {}; }
void AudioGridderAudioProcessor::changeProgramName(int index, const String& newName) {}
void AudioGridderAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) {
m_client.init(getTotalNumInputChannels(), sampleRate, samplesPerBlock, isUsingDoublePrecision());
}
void AudioGridderAudioProcessor::releaseResources() {
// When playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool AudioGridderAudioProcessor::isBusesLayoutSupported(const BusesLayout& layouts) const {
#if JucePlugin_IsMidiEffect
ignoreUnused(layouts);
return true;
#else
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono() &&
layouts.getMainOutputChannelSet() != AudioChannelSet::stereo()) {
return false;
}
// This checks if the input layout matches the output layout
#if !JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet()) {
return false;
}
#endif
return true;
#endif
}
#endif
template <typename T>
void AudioGridderAudioProcessor::processBlockReal(AudioBuffer<T>& buffer, MidiBuffer& midiMessages) {
ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
auto* playHead = getPlayHead();
AudioPlayHead::CurrentPositionInfo posInfo;
playHead->getCurrentPosition(posInfo);
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) {
buffer.clear(i, 0, buffer.getNumSamples());
}
if (!m_client.isReadyLockFree()) {
for (auto i = 0; i < buffer.getNumChannels(); ++i) {
buffer.clear(i, 0, buffer.getNumSamples());
}
} else {
if (buffer.getNumChannels() > 0 && buffer.getNumSamples() > 0) {
m_client.send(buffer, midiMessages, posInfo);
m_client.read(buffer, midiMessages);
if (m_client.getLatencySamples() != getLatencySamples()) {
logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples());
setLatencySamples(m_client.getLatencySamples());
}
}
}
}
bool AudioGridderAudioProcessor::hasEditor() const { return true; }
AudioProcessorEditor* AudioGridderAudioProcessor::createEditor() { return new AudioGridderAudioProcessorEditor(*this); }
void AudioGridderAudioProcessor::getStateInformation(MemoryBlock& destData) {
json j;
auto jservers = json::array();
for (auto& srv : m_servers) {
jservers.push_back(srv.toStdString());
}
j["version"] = 2;
j["servers"] = jservers;
j["activeServer"] = m_activeServer;
auto jplugs = json::array();
for (int i = 0; i < m_loadedPlugins.size(); i++) {
auto& plug = m_loadedPlugins[i];
if (m_client.isReadyLockFree()) {
auto settings = m_client.getPluginSettings(static_cast<int>(i));
if (settings.getSize() > 0) {
plug.settings = settings.toBase64Encoding();
}
}
auto jpresets = json::array();
for (auto& p : plug.presets) {
jpresets.push_back(p.toStdString());
}
auto jparams = json::array();
for (auto& p : plug.params) {
jparams.push_back(p.toJson());
}
jplugs.push_back({plug.id.toStdString(), plug.name.toStdString(), plug.settings.toStdString(), jpresets,
jparams, plug.bypassed});
}
j["loadedPlugins"] = jplugs;
auto dump = j.dump();
destData.append(dump.data(), dump.length());
saveConfig();
}
void AudioGridderAudioProcessor::saveConfig(int numOfBuffers) {
auto jservers = json::array();
for (auto& srv : m_servers) {
jservers.push_back(srv.toStdString());
}
if (numOfBuffers < 0) {
numOfBuffers = m_client.NUM_OF_BUFFERS;
}
json jcfg;
jcfg["_comment_"] = "PLEASE DO NOT CHANGE THIS FILE WHILE YOUR DAW IS RUNNING AND HAS AUDIOGRIDDER PLUGINS LOADED";
jcfg["Servers"] = jservers;
jcfg["Last"] = m_activeServer;
jcfg["NumberOfBuffers"] = numOfBuffers;
jcfg["NumberOfAutomationSlots"] = m_numberOfAutomationSlots;
File cfg(PLUGIN_CONFIG_FILE);
cfg.deleteFile();
FileOutputStream fos(cfg);
fos.writeText(jcfg.dump(4), false, false, "\n");
}
void AudioGridderAudioProcessor::setStateInformation(const void* data, int sizeInBytes) {
std::string dump(static_cast<const char*>(data), sizeInBytes);
try {
json j = json::parse(dump);
int version = 0;
if (j.find("version") != j.end()) {
version = j["version"].get<int>();
}
m_servers.clear();
if (j.find("servers") != j.end()) {
for (auto& srv : j["servers"]) {
m_servers.push_back(srv.get<std::string>());
}
}
if (j.find("activeServer") != j.end()) {
m_activeServer = j["activeServer"].get<int>();
}
if (j.find("loadedPlugins") != j.end()) {
for (auto& plug : j["loadedPlugins"]) {
if (version < 1) {
StringArray dummy;
Array<e47::Client::Parameter> dummy2;
m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(),
plug[2].get<std::string>(), dummy, dummy2, false, false});
} else if (version == 1) {
StringArray dummy;
Array<e47::Client::Parameter> dummy2;
m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(),
plug[2].get<std::string>(), dummy, dummy2, plug[3].get<bool>(), false});
} else {
StringArray presets;
for (auto& p : plug[3]) {
presets.add(p.get<std::string>());
}
Array<e47::Client::Parameter> params;
for (auto& p : plug[4]) {
params.add(e47::Client::Parameter::fromJson(p));
}
m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(),
plug[2].get<std::string>(), presets, params, plug[5].get<bool>(),
false});
}
}
}
if (m_activeServer > -1 && m_activeServer < m_servers.size()) {
m_client.setServer(m_servers[m_activeServer]);
m_client.reconnect();
}
} catch (json::parse_error& e) {
logln_clnt(&m_client, "parsing state info failed: " << e.what());
}
}
std::vector<ServerPlugin> AudioGridderAudioProcessor::getPlugins(const String& type) const {
std::vector<ServerPlugin> ret;
for (auto& plugin : getPlugins()) {
if (!plugin.getType().compare(type)) {
ret.push_back(plugin);
}
}
return ret;
}
std::set<String> AudioGridderAudioProcessor::getPluginTypes() const {
std::set<String> ret;
for (auto& plugin : m_client.getPlugins()) {
ret.insert(plugin.getType());
}
return ret;
}
bool AudioGridderAudioProcessor::loadPlugin(const String& id, const String& name) {
StringArray presets;
Array<e47::Client::Parameter> params;
logln_clnt(&m_client, "loading " << name << " (" << id << ")... ");
suspendProcessing(true);
bool success = m_client.addPlugin(id, presets, params);
suspendProcessing(false);
logln_clnt(&m_client, "..." << (success ? "ok" : "error"));
if (success) {
logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples());
setLatencySamples(m_client.getLatencySamples());
m_loadedPlugins.push_back({id, name, "", presets, params, false, true});
}
return success;
}
void AudioGridderAudioProcessor::unloadPlugin(int idx) {
suspendProcessing(true);
m_client.delPlugin(idx);
suspendProcessing(false);
logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples());
setLatencySamples(m_client.getLatencySamples());
if (idx == m_activePlugin) {
hidePlugin();
} else if (idx < m_activePlugin) {
m_activePlugin--;
}
int i = 0;
for (auto it = m_loadedPlugins.begin(); it < m_loadedPlugins.end(); it++) {
if (i++ == idx) {
m_loadedPlugins.erase(it);
return;
}
}
}
void AudioGridderAudioProcessor::editPlugin(int idx) {
m_client.editPlugin(idx);
m_activePlugin = idx;
}
void AudioGridderAudioProcessor::hidePlugin(bool updateServer) {
if (updateServer) {
m_client.hidePlugin();
}
m_activePlugin = -1;
}
bool AudioGridderAudioProcessor::isBypassed(int idx) {
if (idx > -1 && idx < m_loadedPlugins.size()) {
return m_loadedPlugins[idx].bypassed;
}
return false;
}
void AudioGridderAudioProcessor::bypassPlugin(int idx) {
if (idx > -1 && idx < m_loadedPlugins.size()) {
m_client.bypassPlugin(idx);
m_loadedPlugins[idx].bypassed = true;
}
}
void AudioGridderAudioProcessor::unbypassPlugin(int idx) {
if (idx > -1 && idx < m_loadedPlugins.size()) {
m_client.unbypassPlugin(idx);
m_loadedPlugins[idx].bypassed = false;
}
}
void AudioGridderAudioProcessor::exchangePlugins(int idxA, int idxB) {
if (idxA > -1 && idxA < m_loadedPlugins.size() && idxB > -1 && idxB < m_loadedPlugins.size()) {
suspendProcessing(true);
m_client.exchangePlugins(idxA, idxB);
suspendProcessing(false);
std::swap(m_loadedPlugins[idxA], m_loadedPlugins[idxB]);
if (idxA == m_activePlugin) {
m_activePlugin = idxB;
} else if (idxB == m_activePlugin) {
m_activePlugin = idxA;
}
for (auto* p : getParameters()) {
auto* param = dynamic_cast<Parameter*>(p);
if (param->m_idx == idxA) {
param->m_idx = idxB;
} else if (param->m_idx == idxB) {
param->m_idx = idxA;
}
}
}
}
bool AudioGridderAudioProcessor::enableParamAutomation(int idx, int paramIdx, int slot) {
auto& param = m_loadedPlugins[idx].params.getReference(paramIdx);
Parameter* pparam = nullptr;
if (slot == -1) {
for (slot = 0; slot < m_numberOfAutomationSlots; slot++) {
pparam = dynamic_cast<Parameter*>(getParameters()[slot]);
if (pparam->m_idx == -1) {
break;
}
}
} else {
pparam = dynamic_cast<Parameter*>(getParameters()[slot]);
}
if (slot < m_numberOfAutomationSlots) {
pparam->m_idx = idx;
pparam->m_paramIdx = paramIdx;
param.automationSlot = slot;
updateHostDisplay();
return true;
}
return false;
}
void AudioGridderAudioProcessor::disableParamAutomation(int idx, int paramIdx) {
auto& param = m_loadedPlugins[idx].params.getReference(paramIdx);
auto* pparam = dynamic_cast<Parameter*>(getParameters()[param.automationSlot]);
pparam->reset();
updateHostDisplay();
param.automationSlot = -1;
}
void AudioGridderAudioProcessor::delServer(int idx) {
int i = 0;
for (auto it = m_servers.begin(); it < m_servers.end(); it++) {
if (i++ == idx) {
m_servers.erase(it);
return;
}
}
}
void AudioGridderAudioProcessor::setActiveServer(int i) {
if (i > -1 && i < m_servers.size()) {
m_activeServer = i;
m_client.setServer(m_servers[i]);
}
}
float AudioGridderAudioProcessor::Parameter::getValue() const {
if (m_idx > -1 && m_paramIdx > -1) {
return m_processor.getClient().getParameterValue(m_idx, m_paramIdx);
}
return 0;
}
void AudioGridderAudioProcessor::Parameter::setValue(float newValue) {
if (m_idx > -1 && m_paramIdx > -1) {
MessageManager::callAsync(
[this, newValue] { m_processor.getClient().setParameterValue(m_idx, m_paramIdx, newValue); });
}
}
String AudioGridderAudioProcessor::Parameter::getName(int maximumStringLength) const {
String name;
name << m_slotId << ":" << getPlugin().name << ":" << getParam().name;
if (name.length() <= maximumStringLength) {
return name;
} else {
return name.dropLastCharacters(name.length() - maximumStringLength);
}
}
//==============================================================================
// This creates new instances of the plugin..
AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new AudioGridderAudioProcessor(); }
| 34.464217 | 120 | 0.599394 | b00leant |
d50f311baa5bcc6fa2ee3552adff91ceb0cc7f31 | 169 | cpp | C++ | Emerald/src/graphics/camera/camera.cpp | jodelahithit/Emerald | 880d0e4ec1ab3a14060502eeb01fc124844b909f | [
"Apache-2.0"
] | null | null | null | Emerald/src/graphics/camera/camera.cpp | jodelahithit/Emerald | 880d0e4ec1ab3a14060502eeb01fc124844b909f | [
"Apache-2.0"
] | null | null | null | Emerald/src/graphics/camera/camera.cpp | jodelahithit/Emerald | 880d0e4ec1ab3a14060502eeb01fc124844b909f | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
void Camera::UpdateProjectionMatrix() {
m_projectionMatrix = Matrix4::Perspective(m_FOV, GetApplication()->GetAspect(), m_nearPlane, m_farPlane);
} | 33.8 | 106 | 0.775148 | jodelahithit |
d514a9e055b489dbe250836cdb055956cc54c5f0 | 6,890 | cpp | C++ | Examples/UI/FileDialogs/Sources/app.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 248 | 2015-01-08T05:21:40.000Z | 2022-03-20T02:59:16.000Z | Examples/UI/FileDialogs/Sources/app.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 39 | 2015-01-14T17:37:07.000Z | 2022-03-17T12:59:26.000Z | Examples/UI/FileDialogs/Sources/app.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 82 | 2015-01-11T13:23:49.000Z | 2022-02-19T03:17:24.000Z | /*
** ClanLib SDK
** Copyright (c) 1997-2020 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
** Mark Page
** Artem Khomenko
*/
#include "precomp.h"
#include "app.h"
#include "../../../ThemeAero/Sources/theme.h"
#include <ClanLib/UI/SystemDialogs/folder_browse_dialog.h>
#include <ClanLib/UI/SystemDialogs/open_file_dialog.h>
#include <ClanLib/UI/SystemDialogs/save_file_dialog.h>
using namespace clan;
clan::ApplicationInstance<App> clanapp;
App::App()
{
#if defined(WIN32) && !defined(__MINGW32__)
clan::D3DTarget::set_current();
#else
clan::OpenGLTarget::set_current();
#endif
// Create a window:
DisplayWindowDescription desc;
desc.set_title("UICore: Hello World");
desc.set_allow_resize(true);
window = std::make_shared<TopLevelWindow>(desc);
auto pRootView = window->root_view();
pRootView->slots.connect(window->root_view()->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); });
pRootView->slots.connect(pRootView->sig_key_press(), [&](clan::KeyEvent &e)
{ if (e.key() == clan::Key::escape) RunLoop::exit(); }
);
// Need for receive a keyboard events.
pRootView->set_focus();
// Create a source for our resources
FileResourceDocument doc(FileSystem("../../ThemeAero"));
ResourceManager resources = FileResourceManager::create(doc);
// Mark this thread as the UI thread
ui_thread = UIThread(resources);
// Style the root view to use rounded corners and a bit of drop shadow
pRootView->style()->set("padding: 11px");
pRootView->style()->set("background: #efefef");
pRootView->style()->set("flex-direction: column");
// First (top) panel with button and text
//
auto panel1 = std::make_shared<View>();
panel1->style()->set("background: white");
panel1->style()->set("padding: 11px");
panel1->style()->set("flex-direction: row");
panel1->style()->set("flex: auto");
pRootView->add_child(panel1);
auto button1 = Theme::create_button();
button1->style()->set("height: 40px");
button1->style()->set("width: 120px");
button1->label()->set_text("Folder browse");
button1->style()->set("flex: none");
button1->image_view()->set_image(clan::Image(pRootView->canvas(), "./document_open.png"));
button1->func_clicked() = clan::bind_member(this, &App::on_button1_down);
panel1->add_child(button1);
label1 = std::make_shared<LabelView>();
label1->style()->set("font: 20px/40px 'Ravie'");
label1->style()->set("padding: 0px 10px");
label1->set_text("Press the button for select a folder");
panel1->add_child(label1);
// Second panel with button and text
//
auto panel2 = std::make_shared<View>();
panel2->style()->set("background: white");
panel2->style()->set("padding: 11px");
panel2->style()->set("flex-direction: row");
panel2->style()->set("flex: auto");
pRootView->add_child(panel2);
auto button2 = Theme::create_button();
button2->style()->set("height: 40px");
button2->style()->set("width: 120px");
button2->label()->set_text("Open file");
button2->style()->set("flex: none");
button2->func_clicked() = clan::bind_member(this, &App::on_button2_down);
panel2->add_child(button2);
label2 = std::make_shared<LabelView>();
label2->style()->set("font: 20px/40px 'Ravie'");
label2->style()->set("padding: 0px 10px");
label2->set_text("Press the button for select only existing file");
panel2->add_child(label2);
// Third panel with button and text
//
auto panel3 = std::make_shared<View>();
panel3->style()->set("background: white");
panel3->style()->set("padding: 11px");
panel3->style()->set("flex-direction: row");
panel3->style()->set("flex: auto");
pRootView->add_child(panel3);
auto button3 = Theme::create_button();
button3->style()->set("height: 40px");
button3->style()->set("width: 120px");
button3->label()->set_text("Save file");
button3->style()->set("flex: none");
button3->func_clicked() = clan::bind_member(this, &App::on_button3_down);
panel3->add_child(button3);
label3 = std::make_shared<LabelView>();
label3->style()->set("font: 20px/40px 'Ravie'");
label3->style()->set("padding: 0px 10px");
label3->set_text("Press the button for select existing or new file");
panel3->add_child(label3);
// Fourth panel with button and text
//
auto panel4 = std::make_shared<View>();
panel4->style()->set("background: white");
panel4->style()->set("padding: 11px");
panel4->style()->set("flex-direction: row");
panel4->style()->set("flex: auto");
pRootView->add_child(panel4);
button4 = Theme::create_button();
button4->style()->set("height: 40px");
button4->style()->set("width: 120px");
button4->label()->set_text("Sticky button");
button4->style()->set("flex: none");
button4->func_clicked() = clan::bind_member(this, &App::on_button4_down);
button4->set_sticky(true);
button4->set_pressed(true);
panel4->add_child(button4);
label4 = std::make_shared<LabelView>();
label4->style()->set("font: 20px/40px 'Ravie'");
label4->style()->set("padding: 0px 10px");
panel4->add_child(label4);
on_button4_down(); // Manual setting button's "pressed" property doesn't call user event handler automatically.
}
void App::on_button1_down()
{
auto dlg = std::make_shared<BrowseFolderDialog>(window->root_view().get());
label1->set_text(dlg->show() ? dlg->selected_path() : "Canceled");
}
void App::on_button2_down()
{
auto dlg = std::make_shared<OpenFileDialog>(window->root_view().get());
label2->set_text(dlg->show() ? dlg->filename() : "Canceled");
}
void App::on_button3_down()
{
auto dlg = std::make_shared<SaveFileDialog>(window->root_view().get());
label3->set_text(dlg->show() ? dlg->filename() : "Canceled");
}
void App::on_button4_down()
{
label4->set_text(button4->pressed() ? "Sticky button is pressed" : "Sticky button is unpressed");
}
bool App::update()
{
// This needs only if nothing is drawn. Otherwise, use display_window().flip().
window->display_window().request_repaint();
//window->display_window().flip();
return true;
} | 33.77451 | 112 | 0.697823 | xctan |
d517a7ae14c50ac5e439a7c29513aa65ab0edf66 | 3,696 | cpp | C++ | 2018/0414_ARC095/F.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2018/0414_ARC095/F.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2018/0414_ARC095/F.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | /**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2018-4-14 21:58:25
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N;
vector<int> V[100010];
int visited[100010];
vector<int> path;
vector<int> ans;
vector<int> ans2;
int longest(int v)
{
fill(visited, visited+100010, -1);
queue<int> Q;
Q.push(v);
visited[v] = 0;
while (!Q.empty())
{
int now = Q.front();
Q.pop();
for (auto x : V[now])
{
if (visited[x] == -1)
{
visited[x] = visited[now] + 1;
Q.push(x);
}
}
}
int maxi = 0;
int max_t = v;
for (auto i = 0; i < N; i++)
{
assert(visited[i] >= 0);
if (visited[i] > maxi)
{
maxi = visited[i];
max_t = i;
}
}
return max_t;
}
int main()
{
cin >> N;
for (auto i = 0; i < N-1; i++)
{
int v, w;
cin >> v >> w;
v--;
w--;
V[v].push_back(w);
V[w].push_back(v);
}
int start = longest(0);
int goal = longest(start);
assert(V[start].size() == 1 && V[goal].size() == 1);
longest(start);
int dist = visited[goal];
int now = goal;
path.push_back(goal);
while (dist > 0)
{
// cerr << "dist = " << dist << ", now = " << now << endl;
for (auto x : V[now])
{
// cerr << "visited[" << x << "] = " << visited[x] << endl;
if (visited[x] == dist - 1)
{
now = x;
path.push_back(now);
dist--;
break;
}
}
}
reverse(path.begin(), path.end());
int S = path.size();
int cnt = 2;
for (auto i = 1; i < S - 1; i++)
{
assert(V[path[i]].size() >= 2);
// cerr << "V[" << path[i] << "].size() = " << V[path[i]].size() << endl;
cnt += V[path[i]].size() - 1;
}
if (cnt != N)
{
// cerr << "N = " << N << ", cnt = " << cnt << endl;
assert(cnt < N);
cout << -1 << endl;
return 0;
}
ans.push_back(1);
int num = 1;
for (auto i = 1; i < S - 1; i++)
{
int subtree = V[path[i]].size() - 1;
vector<int> X;
for (auto j = 1; j < subtree; j++)
{
X.push_back(j);
}
X.push_back(0);
for (auto i = 0; i < subtree; i++)
{
ans.push_back(X[i] + num + 1);
}
num += subtree;
}
assert(num + 1 == N);
ans.push_back(num + 1);
assert((int)ans.size() == N);
//
reverse(path.begin(), path.end());
ans2.push_back(1);
num = 1;
for (auto i = 1; i < S - 1; i++)
{
int subtree = V[path[i]].size() - 1;
vector<int> X;
for (auto j = 1; j < subtree; j++)
{
X.push_back(j);
}
X.push_back(0);
for (auto i = 0; i < subtree; i++)
{
ans2.push_back(X[i] + num + 1);
}
num += subtree;
}
ans2.push_back(num + 1);
for (auto i = 0; i < N; i++)
{
if (ans[i] > ans2[i]) {
swap(ans, ans2);
break;
} else if (ans[i] < ans2[i]) {
break;
}
}
for (auto i = 0; i < N; i++)
{
cout << ans[i];
if (i < N-1)
{
cout << " ";
}
else
{
cout << endl;
}
}
} | 19.659574 | 77 | 0.479708 | kazunetakahashi |
d5187582d079e3d9588b50bbdcdce745ae44c5f0 | 822 | cpp | C++ | Recursion/strings_recursion.cpp | gaurav147-star/DSA-learning | 52625953e2b1421fdd550004df893b970aac9308 | [
"MIT"
] | 1 | 2022-02-15T12:53:00.000Z | 2022-02-15T12:53:00.000Z | Recursion/strings_recursion.cpp | gaurav147-star/DSA-learning | 52625953e2b1421fdd550004df893b970aac9308 | [
"MIT"
] | null | null | null | Recursion/strings_recursion.cpp | gaurav147-star/DSA-learning | 52625953e2b1421fdd550004df893b970aac9308 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class strings_recursion
{
public:
int length(char s[]);
void removeX(char s[]);
};
int strings_recursion::length(char s[])
{
if (s[0] == '\0')
{
return 0;
}
int smallStringLength = length(s + 1);
return 1 + smallStringLength;
}
void strings_recursion::removeX(char s[])
{
if (s[0] == '\0')
{
return;
}
if (s[0] != 'x')
{
removeX(s + 1);
}
else
{
int i = 1;
for (; s[i] != '\0'; i++)
{
s[i - 1] = s[i];
}
s[i - 1] = s[i];
removeX(s);
}
}
int main()
{
strings_recursion l;
char str[100];
cin >> str;
cout << l.length(str) << endl;
l.removeX(str);
cout << str << endl;
cout << l.length(str) << endl;
}
| 14.945455 | 42 | 0.457421 | gaurav147-star |
d518fb0e32ff30902f083db5a640d07acf40675c | 1,814 | cpp | C++ | Source/Add On - Apple/CCoreGraphics.cpp | StevoGTA/CppToolbox | ff53e4ecf02b283e608afc92769199104ba30bf1 | [
"MIT"
] | 1 | 2019-05-02T23:49:03.000Z | 2019-05-02T23:49:03.000Z | Source/Add On - Apple/CCoreGraphics.cpp | StevoSM/CppToolbox | 11c73e083a4510797d7674e040e096bf5dc7ea2d | [
"MIT"
] | null | null | null | Source/Add On - Apple/CCoreGraphics.cpp | StevoSM/CppToolbox | 11c73e083a4510797d7674e040e096bf5dc7ea2d | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------------------------------------------------
// CCoreGraphics.cpp ©2020 Stevo Brock All rights reserved.
//----------------------------------------------------------------------------------------------------------------------
#include "CCoreGraphics.h"
//----------------------------------------------------------------------------------------------------------------------
// MARK: CCoreGraphics
// MARK: Class methods
//----------------------------------------------------------------------------------------------------------------------
CGImageRef CCoreGraphics::newImageRef(const CBitmap& bitmap)
//----------------------------------------------------------------------------------------------------------------------
{
// Setup
const S2DSizeS32& size = bitmap.getSize();
const CData& data = bitmap.getPixelData();
CGBitmapInfo bitmapInfo;
switch (bitmap.getFormat()) {
case CBitmap::kFormatRGB888: bitmapInfo = kCGImageAlphaNone; break;
case CBitmap::kFormatRGBA8888: bitmapInfo = kCGImageAlphaPremultipliedLast; break;
case CBitmap::kFormatARGB8888: bitmapInfo = kCGImageAlphaPremultipliedFirst; break;
default: bitmapInfo = 0; break;
}
CGColorSpaceRef colorSpaceRef = ::CGColorSpaceCreateDeviceRGB();
CGDataProviderRef dataProviderRef =
::CGDataProviderCreateWithData(nil, data.getBytePtr(),
bitmap.getBytesPerRow() * size.mHeight, nil);
CGImageRef imageRef =
::CGImageCreate(size.mWidth, size.mHeight, 8, bitmap.getBytesPerPixel() * 8,
bitmap.getBytesPerRow(), colorSpaceRef, bitmapInfo, dataProviderRef, nil, 1,
kCGRenderingIntentDefault);
::CGDataProviderRelease(dataProviderRef);
::CGColorSpaceRelease(colorSpaceRef);
return imageRef;
}
| 43.190476 | 120 | 0.495039 | StevoGTA |
d51a6eb192ee41b0b8ce11d5816fe375a6e1b915 | 106,081 | cpp | C++ | lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp | nettrino/IntFlow | 0400aef5da2c154268d8b020e393c950435395b3 | [
"Unlicense"
] | 16 | 2015-09-08T08:49:11.000Z | 2019-07-20T14:46:20.000Z | lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp | nettrino/IntFlow | 0400aef5da2c154268d8b020e393c950435395b3 | [
"Unlicense"
] | 1 | 2019-02-10T08:27:48.000Z | 2019-02-10T08:27:48.000Z | lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp | nettrino/IntFlow | 0400aef5da2c154268d8b020e393c950435395b3 | [
"Unlicense"
] | 7 | 2016-05-26T17:31:46.000Z | 2020-11-04T06:39:23.000Z | //===------- LegalizeVectorTypes.cpp - Legalization of vector types -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file performs vector type splitting and scalarization for LegalizeTypes.
// Scalarization is the act of changing a computation in an illegal one-element
// vector type to be a computation in its scalar element type. For example,
// implementing <1 x f32> arithmetic in a scalar f32 register. This is needed
// as a base case when scalarizing vector arithmetic like <4 x f32>, which
// eventually decomposes to scalars if the target doesn't support v4f32 or v2f32
// types.
// Splitting is the act of changing a computation in an invalid vector type to
// be a computation in two vectors of half the size. For example, implementing
// <128 x f32> operations in terms of two <64 x f32> operations.
//
//===----------------------------------------------------------------------===//
#include "LegalizeTypes.h"
#include "llvm/DataLayout.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Result Vector Scalarization: <1 x ty> -> ty.
//===----------------------------------------------------------------------===//
void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
DEBUG(dbgs() << "Scalarize node result " << ResNo << ": ";
N->dump(&DAG);
dbgs() << "\n");
SDValue R = SDValue();
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "ScalarizeVectorResult #" << ResNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
report_fatal_error("Do not know how to scalarize the result of this "
"operator!\n");
case ISD::MERGE_VALUES: R = ScalarizeVecRes_MERGE_VALUES(N, ResNo);break;
case ISD::BITCAST: R = ScalarizeVecRes_BITCAST(N); break;
case ISD::BUILD_VECTOR: R = ScalarizeVecRes_BUILD_VECTOR(N); break;
case ISD::CONVERT_RNDSAT: R = ScalarizeVecRes_CONVERT_RNDSAT(N); break;
case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
case ISD::FP_ROUND: R = ScalarizeVecRes_FP_ROUND(N); break;
case ISD::FP_ROUND_INREG: R = ScalarizeVecRes_InregOp(N); break;
case ISD::FPOWI: R = ScalarizeVecRes_FPOWI(N); break;
case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
case ISD::LOAD: R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
case ISD::SCALAR_TO_VECTOR: R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break;
case ISD::SIGN_EXTEND_INREG: R = ScalarizeVecRes_InregOp(N); break;
case ISD::VSELECT: R = ScalarizeVecRes_VSELECT(N); break;
case ISD::SELECT: R = ScalarizeVecRes_SELECT(N); break;
case ISD::SELECT_CC: R = ScalarizeVecRes_SELECT_CC(N); break;
case ISD::SETCC: R = ScalarizeVecRes_SETCC(N); break;
case ISD::UNDEF: R = ScalarizeVecRes_UNDEF(N); break;
case ISD::VECTOR_SHUFFLE: R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
case ISD::ANY_EXTEND:
case ISD::CTLZ:
case ISD::CTPOP:
case ISD::CTTZ:
case ISD::FABS:
case ISD::FCEIL:
case ISD::FCOS:
case ISD::FEXP:
case ISD::FEXP2:
case ISD::FFLOOR:
case ISD::FLOG:
case ISD::FLOG10:
case ISD::FLOG2:
case ISD::FNEARBYINT:
case ISD::FNEG:
case ISD::FP_EXTEND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::FRINT:
case ISD::FSIN:
case ISD::FSQRT:
case ISD::FTRUNC:
case ISD::SIGN_EXTEND:
case ISD::SINT_TO_FP:
case ISD::TRUNCATE:
case ISD::UINT_TO_FP:
case ISD::ZERO_EXTEND:
R = ScalarizeVecRes_UnaryOp(N);
break;
case ISD::ADD:
case ISD::AND:
case ISD::FADD:
case ISD::FDIV:
case ISD::FMUL:
case ISD::FPOW:
case ISD::FREM:
case ISD::FSUB:
case ISD::MUL:
case ISD::OR:
case ISD::SDIV:
case ISD::SREM:
case ISD::SUB:
case ISD::UDIV:
case ISD::UREM:
case ISD::XOR:
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
R = ScalarizeVecRes_BinOp(N);
break;
case ISD::FMA:
R = ScalarizeVecRes_TernaryOp(N);
break;
}
// If R is null, the sub-method took care of registering the result.
if (R.getNode())
SetScalarizedVector(SDValue(N, ResNo), R);
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
SDValue LHS = GetScalarizedVector(N->getOperand(0));
SDValue RHS = GetScalarizedVector(N->getOperand(1));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
LHS.getValueType(), LHS, RHS);
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_TernaryOp(SDNode *N) {
SDValue Op0 = GetScalarizedVector(N->getOperand(0));
SDValue Op1 = GetScalarizedVector(N->getOperand(1));
SDValue Op2 = GetScalarizedVector(N->getOperand(2));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
Op0.getValueType(), Op0, Op1, Op2);
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_MERGE_VALUES(SDNode *N,
unsigned ResNo) {
SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
return GetScalarizedVector(Op);
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_BITCAST(SDNode *N) {
EVT NewVT = N->getValueType(0).getVectorElementType();
return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
NewVT, N->getOperand(0));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_BUILD_VECTOR(SDNode *N) {
EVT EltVT = N->getValueType(0).getVectorElementType();
SDValue InOp = N->getOperand(0);
// The BUILD_VECTOR operands may be of wider element types and
// we may need to truncate them back to the requested return type.
if (EltVT.isInteger())
return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, InOp);
return InOp;
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_CONVERT_RNDSAT(SDNode *N) {
EVT NewVT = N->getValueType(0).getVectorElementType();
SDValue Op0 = GetScalarizedVector(N->getOperand(0));
return DAG.getConvertRndSat(NewVT, N->getDebugLoc(),
Op0, DAG.getValueType(NewVT),
DAG.getValueType(Op0.getValueType()),
N->getOperand(3),
N->getOperand(4),
cast<CvtRndSatSDNode>(N)->getCvtCode());
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(),
N->getValueType(0).getVectorElementType(),
N->getOperand(0), N->getOperand(1));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_FP_ROUND(SDNode *N) {
EVT NewVT = N->getValueType(0).getVectorElementType();
SDValue Op = GetScalarizedVector(N->getOperand(0));
return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(),
NewVT, Op, N->getOperand(1));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
SDValue Op = GetScalarizedVector(N->getOperand(0));
return DAG.getNode(ISD::FPOWI, N->getDebugLoc(),
Op.getValueType(), Op, N->getOperand(1));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
// The value to insert may have a wider type than the vector element type,
// so be sure to truncate it to the element type if necessary.
SDValue Op = N->getOperand(1);
EVT EltVT = N->getValueType(0).getVectorElementType();
if (Op.getValueType() != EltVT)
// FIXME: Can this happen for floating point types?
Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, Op);
return Op;
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
assert(N->isUnindexed() && "Indexed vector load?");
SDValue Result = DAG.getLoad(ISD::UNINDEXED,
N->getExtensionType(),
N->getValueType(0).getVectorElementType(),
N->getDebugLoc(),
N->getChain(), N->getBasePtr(),
DAG.getUNDEF(N->getBasePtr().getValueType()),
N->getPointerInfo(),
N->getMemoryVT().getVectorElementType(),
N->isVolatile(), N->isNonTemporal(),
N->isInvariant(), N->getOriginalAlignment());
// Legalized the chain result - switch anything that used the old chain to
// use the new one.
ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
return Result;
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
// Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
EVT DestVT = N->getValueType(0).getVectorElementType();
SDValue Op = GetScalarizedVector(N->getOperand(0));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(), DestVT, Op);
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_InregOp(SDNode *N) {
EVT EltVT = N->getValueType(0).getVectorElementType();
EVT ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT().getVectorElementType();
SDValue LHS = GetScalarizedVector(N->getOperand(0));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(), EltVT,
LHS, DAG.getValueType(ExtVT));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) {
// If the operand is wider than the vector element type then it is implicitly
// truncated. Make that explicit here.
EVT EltVT = N->getValueType(0).getVectorElementType();
SDValue InOp = N->getOperand(0);
if (InOp.getValueType() != EltVT)
return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, InOp);
return InOp;
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) {
SDValue Cond = GetScalarizedVector(N->getOperand(0));
SDValue LHS = GetScalarizedVector(N->getOperand(1));
TargetLowering::BooleanContent ScalarBool = TLI.getBooleanContents(false);
TargetLowering::BooleanContent VecBool = TLI.getBooleanContents(true);
if (ScalarBool != VecBool) {
EVT CondVT = Cond.getValueType();
switch (ScalarBool) {
case TargetLowering::UndefinedBooleanContent:
break;
case TargetLowering::ZeroOrOneBooleanContent:
assert(VecBool == TargetLowering::UndefinedBooleanContent ||
VecBool == TargetLowering::ZeroOrNegativeOneBooleanContent);
// Vector read from all ones, scalar expects a single 1 so mask.
Cond = DAG.getNode(ISD::AND, N->getDebugLoc(), CondVT,
Cond, DAG.getConstant(1, CondVT));
break;
case TargetLowering::ZeroOrNegativeOneBooleanContent:
assert(VecBool == TargetLowering::UndefinedBooleanContent ||
VecBool == TargetLowering::ZeroOrOneBooleanContent);
// Vector reads from a one, scalar from all ones so sign extend.
Cond = DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), CondVT,
Cond, DAG.getValueType(MVT::i1));
break;
}
}
return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
LHS.getValueType(), Cond, LHS,
GetScalarizedVector(N->getOperand(2)));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
SDValue LHS = GetScalarizedVector(N->getOperand(1));
return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
LHS.getValueType(), N->getOperand(0), LHS,
GetScalarizedVector(N->getOperand(2)));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
SDValue LHS = GetScalarizedVector(N->getOperand(2));
return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), LHS.getValueType(),
N->getOperand(0), N->getOperand(1),
LHS, GetScalarizedVector(N->getOperand(3)),
N->getOperand(4));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_SETCC(SDNode *N) {
assert(N->getValueType(0).isVector() ==
N->getOperand(0).getValueType().isVector() &&
"Scalar/Vector type mismatch");
if (N->getValueType(0).isVector()) return ScalarizeVecRes_VSETCC(N);
SDValue LHS = GetScalarizedVector(N->getOperand(0));
SDValue RHS = GetScalarizedVector(N->getOperand(1));
DebugLoc DL = N->getDebugLoc();
// Turn it into a scalar SETCC.
return DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, N->getOperand(2));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
// Figure out if the scalar is the LHS or RHS and return it.
SDValue Arg = N->getOperand(2).getOperand(0);
if (Arg.getOpcode() == ISD::UNDEF)
return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
return GetScalarizedVector(N->getOperand(Op));
}
SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
assert(N->getValueType(0).isVector() &&
N->getOperand(0).getValueType().isVector() &&
"Operand types must be vectors");
SDValue LHS = GetScalarizedVector(N->getOperand(0));
SDValue RHS = GetScalarizedVector(N->getOperand(1));
EVT NVT = N->getValueType(0).getVectorElementType();
DebugLoc DL = N->getDebugLoc();
// Turn it into a scalar SETCC.
SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS,
N->getOperand(2));
// Vectors may have a different boolean contents to scalars. Promote the
// value appropriately.
ISD::NodeType ExtendCode =
TargetLowering::getExtendForContent(TLI.getBooleanContents(true));
return DAG.getNode(ExtendCode, DL, NVT, Res);
}
//===----------------------------------------------------------------------===//
// Operand Vector Scalarization <1 x ty> -> ty.
//===----------------------------------------------------------------------===//
bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
DEBUG(dbgs() << "Scalarize node operand " << OpNo << ": ";
N->dump(&DAG);
dbgs() << "\n");
SDValue Res = SDValue();
if (Res.getNode() == 0) {
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "ScalarizeVectorOperand Op #" << OpNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
llvm_unreachable("Do not know how to scalarize this operator's operand!");
case ISD::BITCAST:
Res = ScalarizeVecOp_BITCAST(N);
break;
case ISD::CONCAT_VECTORS:
Res = ScalarizeVecOp_CONCAT_VECTORS(N);
break;
case ISD::EXTRACT_VECTOR_ELT:
Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N);
break;
case ISD::STORE:
Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo);
break;
}
}
// If the result is null, the sub-method took care of registering results etc.
if (!Res.getNode()) return false;
// If the result is N, the sub-method updated N in place. Tell the legalizer
// core about this.
if (Res.getNode() == N)
return true;
assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
"Invalid operand expansion");
ReplaceValueWith(SDValue(N, 0), Res);
return false;
}
/// ScalarizeVecOp_BITCAST - If the value to convert is a vector that needs
/// to be scalarized, it must be <1 x ty>. Convert the element instead.
SDValue DAGTypeLegalizer::ScalarizeVecOp_BITCAST(SDNode *N) {
SDValue Elt = GetScalarizedVector(N->getOperand(0));
return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
N->getValueType(0), Elt);
}
/// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
/// use a BUILD_VECTOR instead.
SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
SmallVector<SDValue, 8> Ops(N->getNumOperands());
for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
Ops[i] = GetScalarizedVector(N->getOperand(i));
return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), N->getValueType(0),
&Ops[0], Ops.size());
}
/// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
/// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
/// index.
SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
SDValue Res = GetScalarizedVector(N->getOperand(0));
if (Res.getValueType() != N->getValueType(0))
Res = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0),
Res);
return Res;
}
/// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
/// scalarized, it must be <1 x ty>. Just store the element.
SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
assert(N->isUnindexed() && "Indexed store of one-element vector?");
assert(OpNo == 1 && "Do not know how to scalarize this operand!");
DebugLoc dl = N->getDebugLoc();
if (N->isTruncatingStore())
return DAG.getTruncStore(N->getChain(), dl,
GetScalarizedVector(N->getOperand(1)),
N->getBasePtr(), N->getPointerInfo(),
N->getMemoryVT().getVectorElementType(),
N->isVolatile(), N->isNonTemporal(),
N->getAlignment());
return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
N->getBasePtr(), N->getPointerInfo(),
N->isVolatile(), N->isNonTemporal(),
N->getOriginalAlignment());
}
//===----------------------------------------------------------------------===//
// Result Vector Splitting
//===----------------------------------------------------------------------===//
/// SplitVectorResult - This method is called when the specified result of the
/// specified node is found to need vector splitting. At this point, the node
/// may also have invalid operands or may have other results that need
/// legalization, we just know that (at least) one result needs vector
/// splitting.
void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
DEBUG(dbgs() << "Split node result: ";
N->dump(&DAG);
dbgs() << "\n");
SDValue Lo, Hi;
// See if the target wants to custom expand this node.
if (CustomLowerNode(N, N->getValueType(ResNo), true))
return;
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "SplitVectorResult #" << ResNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
report_fatal_error("Do not know how to split the result of this "
"operator!\n");
case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
case ISD::VSELECT:
case ISD::SELECT: SplitRes_SELECT(N, Lo, Hi); break;
case ISD::SELECT_CC: SplitRes_SELECT_CC(N, Lo, Hi); break;
case ISD::UNDEF: SplitRes_UNDEF(N, Lo, Hi); break;
case ISD::BITCAST: SplitVecRes_BITCAST(N, Lo, Hi); break;
case ISD::BUILD_VECTOR: SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
case ISD::CONCAT_VECTORS: SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
case ISD::FP_ROUND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break;
case ISD::FPOWI: SplitVecRes_FPOWI(N, Lo, Hi); break;
case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
case ISD::SCALAR_TO_VECTOR: SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break;
case ISD::SIGN_EXTEND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break;
case ISD::LOAD:
SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);
break;
case ISD::SETCC:
SplitVecRes_SETCC(N, Lo, Hi);
break;
case ISD::VECTOR_SHUFFLE:
SplitVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N), Lo, Hi);
break;
case ISD::ANY_EXTEND:
case ISD::CONVERT_RNDSAT:
case ISD::CTLZ:
case ISD::CTTZ:
case ISD::CTLZ_ZERO_UNDEF:
case ISD::CTTZ_ZERO_UNDEF:
case ISD::CTPOP:
case ISD::FABS:
case ISD::FCEIL:
case ISD::FCOS:
case ISD::FEXP:
case ISD::FEXP2:
case ISD::FFLOOR:
case ISD::FLOG:
case ISD::FLOG10:
case ISD::FLOG2:
case ISD::FNEARBYINT:
case ISD::FNEG:
case ISD::FP_EXTEND:
case ISD::FP_ROUND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::FRINT:
case ISD::FSIN:
case ISD::FSQRT:
case ISD::FTRUNC:
case ISD::SIGN_EXTEND:
case ISD::SINT_TO_FP:
case ISD::TRUNCATE:
case ISD::UINT_TO_FP:
case ISD::ZERO_EXTEND:
SplitVecRes_UnaryOp(N, Lo, Hi);
break;
case ISD::ADD:
case ISD::SUB:
case ISD::MUL:
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::SDIV:
case ISD::UDIV:
case ISD::FDIV:
case ISD::FPOW:
case ISD::AND:
case ISD::OR:
case ISD::XOR:
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
case ISD::UREM:
case ISD::SREM:
case ISD::FREM:
SplitVecRes_BinOp(N, Lo, Hi);
break;
case ISD::FMA:
SplitVecRes_TernaryOp(N, Lo, Hi);
break;
}
// If Lo/Hi is null, the sub-method took care of registering results etc.
if (Lo.getNode())
SetSplitVector(SDValue(N, ResNo), Lo, Hi);
}
void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
SDValue &Hi) {
SDValue LHSLo, LHSHi;
GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
SDValue RHSLo, RHSHi;
GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
DebugLoc dl = N->getDebugLoc();
Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, RHSLo);
Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, RHSHi);
}
void DAGTypeLegalizer::SplitVecRes_TernaryOp(SDNode *N, SDValue &Lo,
SDValue &Hi) {
SDValue Op0Lo, Op0Hi;
GetSplitVector(N->getOperand(0), Op0Lo, Op0Hi);
SDValue Op1Lo, Op1Hi;
GetSplitVector(N->getOperand(1), Op1Lo, Op1Hi);
SDValue Op2Lo, Op2Hi;
GetSplitVector(N->getOperand(2), Op2Lo, Op2Hi);
DebugLoc dl = N->getDebugLoc();
Lo = DAG.getNode(N->getOpcode(), dl, Op0Lo.getValueType(),
Op0Lo, Op1Lo, Op2Lo);
Hi = DAG.getNode(N->getOpcode(), dl, Op0Hi.getValueType(),
Op0Hi, Op1Hi, Op2Hi);
}
void DAGTypeLegalizer::SplitVecRes_BITCAST(SDNode *N, SDValue &Lo,
SDValue &Hi) {
// We know the result is a vector. The input may be either a vector or a
// scalar value.
EVT LoVT, HiVT;
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
DebugLoc dl = N->getDebugLoc();
SDValue InOp = N->getOperand(0);
EVT InVT = InOp.getValueType();
// Handle some special cases efficiently.
switch (getTypeAction(InVT)) {
case TargetLowering::TypeLegal:
case TargetLowering::TypePromoteInteger:
case TargetLowering::TypeSoftenFloat:
case TargetLowering::TypeScalarizeVector:
case TargetLowering::TypeWidenVector:
break;
case TargetLowering::TypeExpandInteger:
case TargetLowering::TypeExpandFloat:
// A scalar to vector conversion, where the scalar needs expansion.
// If the vector is being split in two then we can just convert the
// expanded pieces.
if (LoVT == HiVT) {
GetExpandedOp(InOp, Lo, Hi);
if (TLI.isBigEndian())
std::swap(Lo, Hi);
Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
return;
}
break;
case TargetLowering::TypeSplitVector:
// If the input is a vector that needs to be split, convert each split
// piece of the input now.
GetSplitVector(InOp, Lo, Hi);
Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
return;
}
// In the general case, convert the input to an integer and split it by hand.
EVT LoIntVT = EVT::getIntegerVT(*DAG.getContext(), LoVT.getSizeInBits());
EVT HiIntVT = EVT::getIntegerVT(*DAG.getContext(), HiVT.getSizeInBits());
if (TLI.isBigEndian())
std::swap(LoIntVT, HiIntVT);
SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
if (TLI.isBigEndian())
std::swap(Lo, Hi);
Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
}
void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
SDValue &Hi) {
EVT LoVT, HiVT;
DebugLoc dl = N->getDebugLoc();
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
unsigned LoNumElts = LoVT.getVectorNumElements();
SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, LoVT, &LoOps[0], LoOps.size());
SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, HiVT, &HiOps[0], HiOps.size());
}
void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
SDValue &Hi) {
assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
DebugLoc dl = N->getDebugLoc();
unsigned NumSubvectors = N->getNumOperands() / 2;
if (NumSubvectors == 1) {
Lo = N->getOperand(0);
Hi = N->getOperand(1);
return;
}
EVT LoVT, HiVT;
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, &LoOps[0], LoOps.size());
SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, &HiOps[0], HiOps.size());
}
void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
SDValue &Hi) {
SDValue Vec = N->getOperand(0);
SDValue Idx = N->getOperand(1);
DebugLoc dl = N->getDebugLoc();
EVT LoVT, HiVT;
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx);
uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec,
DAG.getIntPtrConstant(IdxVal + LoVT.getVectorNumElements()));
}
void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
SDValue &Hi) {
DebugLoc dl = N->getDebugLoc();
GetSplitVector(N->getOperand(0), Lo, Hi);
Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1));
Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1));
}
void DAGTypeLegalizer::SplitVecRes_InregOp(SDNode *N, SDValue &Lo,
SDValue &Hi) {
SDValue LHSLo, LHSHi;
GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
DebugLoc dl = N->getDebugLoc();
EVT LoVT, HiVT;
GetSplitDestVTs(cast<VTSDNode>(N->getOperand(1))->getVT(), LoVT, HiVT);
Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo,
DAG.getValueType(LoVT));
Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi,
DAG.getValueType(HiVT));
}
void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
SDValue &Hi) {
SDValue Vec = N->getOperand(0);
SDValue Elt = N->getOperand(1);
SDValue Idx = N->getOperand(2);
DebugLoc dl = N->getDebugLoc();
GetSplitVector(Vec, Lo, Hi);
if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
unsigned IdxVal = CIdx->getZExtValue();
unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
if (IdxVal < LoNumElts)
Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
Lo.getValueType(), Lo, Elt, Idx);
else
Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt,
DAG.getIntPtrConstant(IdxVal - LoNumElts));
return;
}
// Spill the vector to the stack.
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
MachinePointerInfo(), false, false, 0);
// Store the new element. This may be larger than the vector element type,
// so use a truncating store.
SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
Type *VecType = VecVT.getTypeForEVT(*DAG.getContext());
unsigned Alignment =
TLI.getDataLayout()->getPrefTypeAlignment(VecType);
Store = DAG.getTruncStore(Store, dl, Elt, EltPtr, MachinePointerInfo(), EltVT,
false, false, 0);
// Load the Lo part from the stack slot.
Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
false, false, false, 0);
// Increment the pointer to the other part.
unsigned IncrementSize = Lo.getValueType().getSizeInBits() / 8;
StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
DAG.getIntPtrConstant(IncrementSize));
// Load the Hi part from the stack slot.
Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
false, false, false, MinAlign(Alignment, IncrementSize));
}
void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
SDValue &Hi) {
EVT LoVT, HiVT;
DebugLoc dl = N->getDebugLoc();
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0));
Hi = DAG.getUNDEF(HiVT);
}
void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
SDValue &Hi) {
assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
EVT LoVT, HiVT;
DebugLoc dl = LD->getDebugLoc();
GetSplitDestVTs(LD->getValueType(0), LoVT, HiVT);
ISD::LoadExtType ExtType = LD->getExtensionType();
SDValue Ch = LD->getChain();
SDValue Ptr = LD->getBasePtr();
SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
EVT MemoryVT = LD->getMemoryVT();
unsigned Alignment = LD->getOriginalAlignment();
bool isVolatile = LD->isVolatile();
bool isNonTemporal = LD->isNonTemporal();
bool isInvariant = LD->isInvariant();
EVT LoMemVT, HiMemVT;
GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset,
LD->getPointerInfo(), LoMemVT, isVolatile, isNonTemporal,
isInvariant, Alignment);
unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
DAG.getIntPtrConstant(IncrementSize));
Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset,
LD->getPointerInfo().getWithOffset(IncrementSize),
HiMemVT, isVolatile, isNonTemporal, isInvariant, Alignment);
// Build a factor node to remember that this load is independent of the
// other one.
Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
Hi.getValue(1));
// Legalized the chain result - switch anything that used the old chain to
// use the new one.
ReplaceValueWith(SDValue(LD, 1), Ch);
}
void DAGTypeLegalizer::SplitVecRes_SETCC(SDNode *N, SDValue &Lo, SDValue &Hi) {
assert(N->getValueType(0).isVector() &&
N->getOperand(0).getValueType().isVector() &&
"Operand types must be vectors");
EVT LoVT, HiVT;
DebugLoc DL = N->getDebugLoc();
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
// Split the input.
EVT InVT = N->getOperand(0).getValueType();
SDValue LL, LH, RL, RH;
EVT InNVT = EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElementType(),
LoVT.getVectorNumElements());
LL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(0),
DAG.getIntPtrConstant(0));
LH = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(0),
DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
RL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(1),
DAG.getIntPtrConstant(0));
RH = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(1),
DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
}
void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
SDValue &Hi) {
// Get the dest types - they may not match the input types, e.g. int_to_fp.
EVT LoVT, HiVT;
DebugLoc dl = N->getDebugLoc();
GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
// If the input also splits, handle it directly for a compile time speedup.
// Otherwise split it by hand.
EVT InVT = N->getOperand(0).getValueType();
if (getTypeAction(InVT) == TargetLowering::TypeSplitVector) {
GetSplitVector(N->getOperand(0), Lo, Hi);
} else {
EVT InNVT = EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElementType(),
LoVT.getVectorNumElements());
Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
DAG.getIntPtrConstant(0));
Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
}
if (N->getOpcode() == ISD::FP_ROUND) {
Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo, N->getOperand(1));
Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi, N->getOperand(1));
} else if (N->getOpcode() == ISD::CONVERT_RNDSAT) {
SDValue DTyOpLo = DAG.getValueType(LoVT);
SDValue DTyOpHi = DAG.getValueType(HiVT);
SDValue STyOpLo = DAG.getValueType(Lo.getValueType());
SDValue STyOpHi = DAG.getValueType(Hi.getValueType());
SDValue RndOp = N->getOperand(3);
SDValue SatOp = N->getOperand(4);
ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
Lo = DAG.getConvertRndSat(LoVT, dl, Lo, DTyOpLo, STyOpLo, RndOp, SatOp,
CvtCode);
Hi = DAG.getConvertRndSat(HiVT, dl, Hi, DTyOpHi, STyOpHi, RndOp, SatOp,
CvtCode);
} else {
Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
}
}
void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
SDValue &Lo, SDValue &Hi) {
// The low and high parts of the original input give four input vectors.
SDValue Inputs[4];
DebugLoc dl = N->getDebugLoc();
GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]);
GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]);
EVT NewVT = Inputs[0].getValueType();
unsigned NewElts = NewVT.getVectorNumElements();
// If Lo or Hi uses elements from at most two of the four input vectors, then
// express it as a vector shuffle of those two inputs. Otherwise extract the
// input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
SmallVector<int, 16> Ops;
for (unsigned High = 0; High < 2; ++High) {
SDValue &Output = High ? Hi : Lo;
// Build a shuffle mask for the output, discovering on the fly which
// input vectors to use as shuffle operands (recorded in InputUsed).
// If building a suitable shuffle vector proves too hard, then bail
// out with useBuildVector set.
unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered.
unsigned FirstMaskIdx = High * NewElts;
bool useBuildVector = false;
for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
// The mask element. This indexes into the input.
int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
// The input vector this mask element indexes into.
unsigned Input = (unsigned)Idx / NewElts;
if (Input >= array_lengthof(Inputs)) {
// The mask element does not index into any input vector.
Ops.push_back(-1);
continue;
}
// Turn the index into an offset from the start of the input vector.
Idx -= Input * NewElts;
// Find or create a shuffle vector operand to hold this input.
unsigned OpNo;
for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
if (InputUsed[OpNo] == Input) {
// This input vector is already an operand.
break;
} else if (InputUsed[OpNo] == -1U) {
// Create a new operand for this input vector.
InputUsed[OpNo] = Input;
break;
}
}
if (OpNo >= array_lengthof(InputUsed)) {
// More than two input vectors used! Give up on trying to create a
// shuffle vector. Insert all elements into a BUILD_VECTOR instead.
useBuildVector = true;
break;
}
// Add the mask index for the new shuffle vector.
Ops.push_back(Idx + OpNo * NewElts);
}
if (useBuildVector) {
EVT EltVT = NewVT.getVectorElementType();
SmallVector<SDValue, 16> SVOps;
// Extract the input elements by hand.
for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
// The mask element. This indexes into the input.
int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
// The input vector this mask element indexes into.
unsigned Input = (unsigned)Idx / NewElts;
if (Input >= array_lengthof(Inputs)) {
// The mask element is "undef" or indexes off the end of the input.
SVOps.push_back(DAG.getUNDEF(EltVT));
continue;
}
// Turn the index into an offset from the start of the input vector.
Idx -= Input * NewElts;
// Extract the vector element by hand.
SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
Inputs[Input], DAG.getIntPtrConstant(Idx)));
}
// Construct the Lo/Hi output using a BUILD_VECTOR.
Output = DAG.getNode(ISD::BUILD_VECTOR,dl,NewVT, &SVOps[0], SVOps.size());
} else if (InputUsed[0] == -1U) {
// No input vectors were used! The result is undefined.
Output = DAG.getUNDEF(NewVT);
} else {
SDValue Op0 = Inputs[InputUsed[0]];
// If only one input was used, use an undefined vector for the other.
SDValue Op1 = InputUsed[1] == -1U ?
DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]];
// At least one input vector was used. Create a new shuffle vector.
Output = DAG.getVectorShuffle(NewVT, dl, Op0, Op1, &Ops[0]);
}
Ops.clear();
}
}
//===----------------------------------------------------------------------===//
// Operand Vector Splitting
//===----------------------------------------------------------------------===//
/// SplitVectorOperand - This method is called when the specified operand of the
/// specified node is found to need vector splitting. At this point, all of the
/// result types of the node are known to be legal, but other operands of the
/// node may need legalization as well as the specified one.
bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
DEBUG(dbgs() << "Split node operand: ";
N->dump(&DAG);
dbgs() << "\n");
SDValue Res = SDValue();
if (Res.getNode() == 0) {
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "SplitVectorOperand Op #" << OpNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
report_fatal_error("Do not know how to split this operator's "
"operand!\n");
case ISD::SETCC: Res = SplitVecOp_VSETCC(N); break;
case ISD::BITCAST: Res = SplitVecOp_BITCAST(N); break;
case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
case ISD::CONCAT_VECTORS: Res = SplitVecOp_CONCAT_VECTORS(N); break;
case ISD::FP_ROUND: Res = SplitVecOp_FP_ROUND(N); break;
case ISD::STORE:
Res = SplitVecOp_STORE(cast<StoreSDNode>(N), OpNo);
break;
case ISD::CTTZ:
case ISD::CTLZ:
case ISD::CTPOP:
case ISD::FP_EXTEND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::SINT_TO_FP:
case ISD::UINT_TO_FP:
case ISD::FTRUNC:
case ISD::TRUNCATE:
case ISD::SIGN_EXTEND:
case ISD::ZERO_EXTEND:
case ISD::ANY_EXTEND:
Res = SplitVecOp_UnaryOp(N);
break;
}
}
// If the result is null, the sub-method took care of registering results etc.
if (!Res.getNode()) return false;
// If the result is N, the sub-method updated N in place. Tell the legalizer
// core about this.
if (Res.getNode() == N)
return true;
assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
"Invalid operand expansion");
ReplaceValueWith(SDValue(N, 0), Res);
return false;
}
SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
// The result has a legal vector type, but the input needs splitting.
EVT ResVT = N->getValueType(0);
SDValue Lo, Hi;
DebugLoc dl = N->getDebugLoc();
GetSplitVector(N->getOperand(0), Lo, Hi);
EVT InVT = Lo.getValueType();
EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
InVT.getVectorNumElements());
Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo);
Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi);
return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
}
SDValue DAGTypeLegalizer::SplitVecOp_BITCAST(SDNode *N) {
// For example, i64 = BITCAST v4i16 on alpha. Typically the vector will
// end up being split all the way down to individual components. Convert the
// split pieces into integers and reassemble.
SDValue Lo, Hi;
GetSplitVector(N->getOperand(0), Lo, Hi);
Lo = BitConvertToInteger(Lo);
Hi = BitConvertToInteger(Hi);
if (TLI.isBigEndian())
std::swap(Lo, Hi);
return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getValueType(0),
JoinIntegers(Lo, Hi));
}
SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
// We know that the extracted result type is legal.
EVT SubVT = N->getValueType(0);
SDValue Idx = N->getOperand(1);
DebugLoc dl = N->getDebugLoc();
SDValue Lo, Hi;
GetSplitVector(N->getOperand(0), Lo, Hi);
uint64_t LoElts = Lo.getValueType().getVectorNumElements();
uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
if (IdxVal < LoElts) {
assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
"Extracted subvector crosses vector split!");
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx);
} else {
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi,
DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
}
}
SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
SDValue Vec = N->getOperand(0);
SDValue Idx = N->getOperand(1);
EVT VecVT = Vec.getValueType();
if (isa<ConstantSDNode>(Idx)) {
uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
SDValue Lo, Hi;
GetSplitVector(Vec, Lo, Hi);
uint64_t LoElts = Lo.getValueType().getVectorNumElements();
if (IdxVal < LoElts)
return SDValue(DAG.UpdateNodeOperands(N, Lo, Idx), 0);
return SDValue(DAG.UpdateNodeOperands(N, Hi,
DAG.getConstant(IdxVal - LoElts,
Idx.getValueType())), 0);
}
// Store the vector to the stack.
EVT EltVT = VecVT.getVectorElementType();
DebugLoc dl = N->getDebugLoc();
SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
MachinePointerInfo(), false, false, 0);
// Load back the required element.
StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
return DAG.getExtLoad(ISD::EXTLOAD, dl, N->getValueType(0), Store, StackPtr,
MachinePointerInfo(), EltVT, false, false, 0);
}
SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
assert(N->isUnindexed() && "Indexed store of vector?");
assert(OpNo == 1 && "Can only split the stored value");
DebugLoc DL = N->getDebugLoc();
bool isTruncating = N->isTruncatingStore();
SDValue Ch = N->getChain();
SDValue Ptr = N->getBasePtr();
EVT MemoryVT = N->getMemoryVT();
unsigned Alignment = N->getOriginalAlignment();
bool isVol = N->isVolatile();
bool isNT = N->isNonTemporal();
SDValue Lo, Hi;
GetSplitVector(N->getOperand(1), Lo, Hi);
EVT LoMemVT, HiMemVT;
GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
if (isTruncating)
Lo = DAG.getTruncStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
LoMemVT, isVol, isNT, Alignment);
else
Lo = DAG.getStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
isVol, isNT, Alignment);
// Increment the pointer to the other half.
Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
DAG.getIntPtrConstant(IncrementSize));
if (isTruncating)
Hi = DAG.getTruncStore(Ch, DL, Hi, Ptr,
N->getPointerInfo().getWithOffset(IncrementSize),
HiMemVT, isVol, isNT, Alignment);
else
Hi = DAG.getStore(Ch, DL, Hi, Ptr,
N->getPointerInfo().getWithOffset(IncrementSize),
isVol, isNT, Alignment);
return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
}
SDValue DAGTypeLegalizer::SplitVecOp_CONCAT_VECTORS(SDNode *N) {
DebugLoc DL = N->getDebugLoc();
// The input operands all must have the same type, and we know the result the
// result type is valid. Convert this to a buildvector which extracts all the
// input elements.
// TODO: If the input elements are power-two vectors, we could convert this to
// a new CONCAT_VECTORS node with elements that are half-wide.
SmallVector<SDValue, 32> Elts;
EVT EltVT = N->getValueType(0).getVectorElementType();
for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
SDValue Op = N->getOperand(op);
for (unsigned i = 0, e = Op.getValueType().getVectorNumElements();
i != e; ++i) {
Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
Op, DAG.getIntPtrConstant(i)));
}
}
return DAG.getNode(ISD::BUILD_VECTOR, DL, N->getValueType(0),
&Elts[0], Elts.size());
}
SDValue DAGTypeLegalizer::SplitVecOp_VSETCC(SDNode *N) {
assert(N->getValueType(0).isVector() &&
N->getOperand(0).getValueType().isVector() &&
"Operand types must be vectors");
// The result has a legal vector type, but the input needs splitting.
SDValue Lo0, Hi0, Lo1, Hi1, LoRes, HiRes;
DebugLoc DL = N->getDebugLoc();
GetSplitVector(N->getOperand(0), Lo0, Hi0);
GetSplitVector(N->getOperand(1), Lo1, Hi1);
unsigned PartElements = Lo0.getValueType().getVectorNumElements();
EVT PartResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, PartElements);
EVT WideResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 2*PartElements);
LoRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Lo0, Lo1, N->getOperand(2));
HiRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Hi0, Hi1, N->getOperand(2));
SDValue Con = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideResVT, LoRes, HiRes);
return PromoteTargetBoolean(Con, N->getValueType(0));
}
SDValue DAGTypeLegalizer::SplitVecOp_FP_ROUND(SDNode *N) {
// The result has a legal vector type, but the input needs splitting.
EVT ResVT = N->getValueType(0);
SDValue Lo, Hi;
DebugLoc DL = N->getDebugLoc();
GetSplitVector(N->getOperand(0), Lo, Hi);
EVT InVT = Lo.getValueType();
EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
InVT.getVectorNumElements());
Lo = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Lo, N->getOperand(1));
Hi = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Hi, N->getOperand(1));
return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
}
//===----------------------------------------------------------------------===//
// Result Vector Widening
//===----------------------------------------------------------------------===//
void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) {
DEBUG(dbgs() << "Widen node result " << ResNo << ": ";
N->dump(&DAG);
dbgs() << "\n");
// See if the target wants to custom widen this node.
if (CustomWidenLowerNode(N, N->getValueType(ResNo)))
return;
SDValue Res = SDValue();
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "WidenVectorResult #" << ResNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
llvm_unreachable("Do not know how to widen the result of this operator!");
case ISD::MERGE_VALUES: Res = WidenVecRes_MERGE_VALUES(N, ResNo); break;
case ISD::BITCAST: Res = WidenVecRes_BITCAST(N); break;
case ISD::BUILD_VECTOR: Res = WidenVecRes_BUILD_VECTOR(N); break;
case ISD::CONCAT_VECTORS: Res = WidenVecRes_CONCAT_VECTORS(N); break;
case ISD::CONVERT_RNDSAT: Res = WidenVecRes_CONVERT_RNDSAT(N); break;
case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break;
case ISD::FP_ROUND_INREG: Res = WidenVecRes_InregOp(N); break;
case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break;
case ISD::LOAD: Res = WidenVecRes_LOAD(N); break;
case ISD::SCALAR_TO_VECTOR: Res = WidenVecRes_SCALAR_TO_VECTOR(N); break;
case ISD::SIGN_EXTEND_INREG: Res = WidenVecRes_InregOp(N); break;
case ISD::VSELECT:
case ISD::SELECT: Res = WidenVecRes_SELECT(N); break;
case ISD::SELECT_CC: Res = WidenVecRes_SELECT_CC(N); break;
case ISD::SETCC: Res = WidenVecRes_SETCC(N); break;
case ISD::UNDEF: Res = WidenVecRes_UNDEF(N); break;
case ISD::VECTOR_SHUFFLE:
Res = WidenVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N));
break;
case ISD::ADD:
case ISD::AND:
case ISD::BSWAP:
case ISD::FADD:
case ISD::FCOPYSIGN:
case ISD::FDIV:
case ISD::FMUL:
case ISD::FPOW:
case ISD::FREM:
case ISD::FSUB:
case ISD::MUL:
case ISD::MULHS:
case ISD::MULHU:
case ISD::OR:
case ISD::SDIV:
case ISD::SREM:
case ISD::UDIV:
case ISD::UREM:
case ISD::SUB:
case ISD::XOR:
Res = WidenVecRes_Binary(N);
break;
case ISD::FPOWI:
Res = WidenVecRes_POWI(N);
break;
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
Res = WidenVecRes_Shift(N);
break;
case ISD::ANY_EXTEND:
case ISD::FP_EXTEND:
case ISD::FP_ROUND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::SIGN_EXTEND:
case ISD::SINT_TO_FP:
case ISD::TRUNCATE:
case ISD::UINT_TO_FP:
case ISD::ZERO_EXTEND:
Res = WidenVecRes_Convert(N);
break;
case ISD::CTLZ:
case ISD::CTPOP:
case ISD::CTTZ:
case ISD::FABS:
case ISD::FCEIL:
case ISD::FCOS:
case ISD::FEXP:
case ISD::FEXP2:
case ISD::FFLOOR:
case ISD::FLOG:
case ISD::FLOG10:
case ISD::FLOG2:
case ISD::FNEARBYINT:
case ISD::FNEG:
case ISD::FRINT:
case ISD::FSIN:
case ISD::FSQRT:
case ISD::FTRUNC:
Res = WidenVecRes_Unary(N);
break;
case ISD::FMA:
Res = WidenVecRes_Ternary(N);
break;
}
// If Res is null, the sub-method took care of registering the result.
if (Res.getNode())
SetWidenedVector(SDValue(N, ResNo), Res);
}
SDValue DAGTypeLegalizer::WidenVecRes_Ternary(SDNode *N) {
// Ternary op widening.
DebugLoc dl = N->getDebugLoc();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
SDValue InOp1 = GetWidenedVector(N->getOperand(0));
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
SDValue InOp3 = GetWidenedVector(N->getOperand(2));
return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, InOp3);
}
SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) {
// Binary op widening.
unsigned Opcode = N->getOpcode();
DebugLoc dl = N->getDebugLoc();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
EVT WidenEltVT = WidenVT.getVectorElementType();
EVT VT = WidenVT;
unsigned NumElts = VT.getVectorNumElements();
while (!TLI.isTypeLegal(VT) && NumElts != 1) {
NumElts = NumElts / 2;
VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
}
if (NumElts != 1 && !TLI.canOpTrap(N->getOpcode(), VT)) {
// Operation doesn't trap so just widen as normal.
SDValue InOp1 = GetWidenedVector(N->getOperand(0));
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2);
}
// No legal vector version so unroll the vector operation and then widen.
if (NumElts == 1)
return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements());
// Since the operation can trap, apply operation on the original vector.
EVT MaxVT = VT;
SDValue InOp1 = GetWidenedVector(N->getOperand(0));
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
unsigned CurNumElts = N->getValueType(0).getVectorNumElements();
SmallVector<SDValue, 16> ConcatOps(CurNumElts);
unsigned ConcatEnd = 0; // Current ConcatOps index.
int Idx = 0; // Current Idx into input vectors.
// NumElts := greatest legal vector size (at most WidenVT)
// while (orig. vector has unhandled elements) {
// take munches of size NumElts from the beginning and add to ConcatOps
// NumElts := next smaller supported vector size or 1
// }
while (CurNumElts != 0) {
while (CurNumElts >= NumElts) {
SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp1,
DAG.getIntPtrConstant(Idx));
SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp2,
DAG.getIntPtrConstant(Idx));
ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, VT, EOp1, EOp2);
Idx += NumElts;
CurNumElts -= NumElts;
}
do {
NumElts = NumElts / 2;
VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
} while (!TLI.isTypeLegal(VT) && NumElts != 1);
if (NumElts == 1) {
for (unsigned i = 0; i != CurNumElts; ++i, ++Idx) {
SDValue EOp1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
InOp1, DAG.getIntPtrConstant(Idx));
SDValue EOp2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
InOp2, DAG.getIntPtrConstant(Idx));
ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, WidenEltVT,
EOp1, EOp2);
}
CurNumElts = 0;
}
}
// Check to see if we have a single operation with the widen type.
if (ConcatEnd == 1) {
VT = ConcatOps[0].getValueType();
if (VT == WidenVT)
return ConcatOps[0];
}
// while (Some element of ConcatOps is not of type MaxVT) {
// From the end of ConcatOps, collect elements of the same type and put
// them into an op of the next larger supported type
// }
while (ConcatOps[ConcatEnd-1].getValueType() != MaxVT) {
Idx = ConcatEnd - 1;
VT = ConcatOps[Idx--].getValueType();
while (Idx >= 0 && ConcatOps[Idx].getValueType() == VT)
Idx--;
int NextSize = VT.isVector() ? VT.getVectorNumElements() : 1;
EVT NextVT;
do {
NextSize *= 2;
NextVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NextSize);
} while (!TLI.isTypeLegal(NextVT));
if (!VT.isVector()) {
// Scalar type, create an INSERT_VECTOR_ELEMENT of type NextVT
SDValue VecOp = DAG.getUNDEF(NextVT);
unsigned NumToInsert = ConcatEnd - Idx - 1;
for (unsigned i = 0, OpIdx = Idx+1; i < NumToInsert; i++, OpIdx++) {
VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NextVT, VecOp,
ConcatOps[OpIdx], DAG.getIntPtrConstant(i));
}
ConcatOps[Idx+1] = VecOp;
ConcatEnd = Idx + 2;
} else {
// Vector type, create a CONCAT_VECTORS of type NextVT
SDValue undefVec = DAG.getUNDEF(VT);
unsigned OpsToConcat = NextSize/VT.getVectorNumElements();
SmallVector<SDValue, 16> SubConcatOps(OpsToConcat);
unsigned RealVals = ConcatEnd - Idx - 1;
unsigned SubConcatEnd = 0;
unsigned SubConcatIdx = Idx + 1;
while (SubConcatEnd < RealVals)
SubConcatOps[SubConcatEnd++] = ConcatOps[++Idx];
while (SubConcatEnd < OpsToConcat)
SubConcatOps[SubConcatEnd++] = undefVec;
ConcatOps[SubConcatIdx] = DAG.getNode(ISD::CONCAT_VECTORS, dl,
NextVT, &SubConcatOps[0],
OpsToConcat);
ConcatEnd = SubConcatIdx + 1;
}
}
// Check to see if we have a single operation with the widen type.
if (ConcatEnd == 1) {
VT = ConcatOps[0].getValueType();
if (VT == WidenVT)
return ConcatOps[0];
}
// add undefs of size MaxVT until ConcatOps grows to length of WidenVT
unsigned NumOps = WidenVT.getVectorNumElements()/MaxVT.getVectorNumElements();
if (NumOps != ConcatEnd ) {
SDValue UndefVal = DAG.getUNDEF(MaxVT);
for (unsigned j = ConcatEnd; j < NumOps; ++j)
ConcatOps[j] = UndefVal;
}
return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0], NumOps);
}
SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) {
SDValue InOp = N->getOperand(0);
DebugLoc DL = N->getDebugLoc();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
unsigned WidenNumElts = WidenVT.getVectorNumElements();
EVT InVT = InOp.getValueType();
EVT InEltVT = InVT.getVectorElementType();
EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
unsigned Opcode = N->getOpcode();
unsigned InVTNumElts = InVT.getVectorNumElements();
if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
InOp = GetWidenedVector(N->getOperand(0));
InVT = InOp.getValueType();
InVTNumElts = InVT.getVectorNumElements();
if (InVTNumElts == WidenNumElts) {
if (N->getNumOperands() == 1)
return DAG.getNode(Opcode, DL, WidenVT, InOp);
return DAG.getNode(Opcode, DL, WidenVT, InOp, N->getOperand(1));
}
}
if (TLI.isTypeLegal(InWidenVT)) {
// Because the result and the input are different vector types, widening
// the result could create a legal type but widening the input might make
// it an illegal type that might lead to repeatedly splitting the input
// and then widening it. To avoid this, we widen the input only if
// it results in a legal type.
if (WidenNumElts % InVTNumElts == 0) {
// Widen the input and call convert on the widened input vector.
unsigned NumConcat = WidenNumElts/InVTNumElts;
SmallVector<SDValue, 16> Ops(NumConcat);
Ops[0] = InOp;
SDValue UndefVal = DAG.getUNDEF(InVT);
for (unsigned i = 1; i != NumConcat; ++i)
Ops[i] = UndefVal;
SDValue InVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InWidenVT,
&Ops[0], NumConcat);
if (N->getNumOperands() == 1)
return DAG.getNode(Opcode, DL, WidenVT, InVec);
return DAG.getNode(Opcode, DL, WidenVT, InVec, N->getOperand(1));
}
if (InVTNumElts % WidenNumElts == 0) {
SDValue InVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InWidenVT,
InOp, DAG.getIntPtrConstant(0));
// Extract the input and convert the shorten input vector.
if (N->getNumOperands() == 1)
return DAG.getNode(Opcode, DL, WidenVT, InVal);
return DAG.getNode(Opcode, DL, WidenVT, InVal, N->getOperand(1));
}
}
// Otherwise unroll into some nasty scalar code and rebuild the vector.
SmallVector<SDValue, 16> Ops(WidenNumElts);
EVT EltVT = WidenVT.getVectorElementType();
unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
unsigned i;
for (i=0; i < MinElts; ++i) {
SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, InEltVT, InOp,
DAG.getIntPtrConstant(i));
if (N->getNumOperands() == 1)
Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val);
else
Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val, N->getOperand(1));
}
SDValue UndefVal = DAG.getUNDEF(EltVT);
for (; i < WidenNumElts; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, DL, WidenVT, &Ops[0], WidenNumElts);
}
SDValue DAGTypeLegalizer::WidenVecRes_POWI(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
SDValue InOp = GetWidenedVector(N->getOperand(0));
SDValue ShOp = N->getOperand(1);
return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp, ShOp);
}
SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
SDValue InOp = GetWidenedVector(N->getOperand(0));
SDValue ShOp = N->getOperand(1);
EVT ShVT = ShOp.getValueType();
if (getTypeAction(ShVT) == TargetLowering::TypeWidenVector) {
ShOp = GetWidenedVector(ShOp);
ShVT = ShOp.getValueType();
}
EVT ShWidenVT = EVT::getVectorVT(*DAG.getContext(),
ShVT.getVectorElementType(),
WidenVT.getVectorNumElements());
if (ShVT != ShWidenVT)
ShOp = ModifyToType(ShOp, ShWidenVT);
return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp, ShOp);
}
SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) {
// Unary op widening.
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
SDValue InOp = GetWidenedVector(N->getOperand(0));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp);
}
SDValue DAGTypeLegalizer::WidenVecRes_InregOp(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
cast<VTSDNode>(N->getOperand(1))->getVT()
.getVectorElementType(),
WidenVT.getVectorNumElements());
SDValue WidenLHS = GetWidenedVector(N->getOperand(0));
return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
WidenVT, WidenLHS, DAG.getValueType(ExtVT));
}
SDValue DAGTypeLegalizer::WidenVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) {
SDValue WidenVec = DisintegrateMERGE_VALUES(N, ResNo);
return GetWidenedVector(WidenVec);
}
SDValue DAGTypeLegalizer::WidenVecRes_BITCAST(SDNode *N) {
SDValue InOp = N->getOperand(0);
EVT InVT = InOp.getValueType();
EVT VT = N->getValueType(0);
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
DebugLoc dl = N->getDebugLoc();
switch (getTypeAction(InVT)) {
case TargetLowering::TypeLegal:
break;
case TargetLowering::TypePromoteInteger:
// If the incoming type is a vector that is being promoted, then
// we know that the elements are arranged differently and that we
// must perform the conversion using a stack slot.
if (InVT.isVector())
break;
// If the InOp is promoted to the same size, convert it. Otherwise,
// fall out of the switch and widen the promoted input.
InOp = GetPromotedInteger(InOp);
InVT = InOp.getValueType();
if (WidenVT.bitsEq(InVT))
return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
break;
case TargetLowering::TypeSoftenFloat:
case TargetLowering::TypeExpandInteger:
case TargetLowering::TypeExpandFloat:
case TargetLowering::TypeScalarizeVector:
case TargetLowering::TypeSplitVector:
break;
case TargetLowering::TypeWidenVector:
// If the InOp is widened to the same size, convert it. Otherwise, fall
// out of the switch and widen the widened input.
InOp = GetWidenedVector(InOp);
InVT = InOp.getValueType();
if (WidenVT.bitsEq(InVT))
// The input widens to the same size. Convert to the widen value.
return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
break;
}
unsigned WidenSize = WidenVT.getSizeInBits();
unsigned InSize = InVT.getSizeInBits();
// x86mmx is not an acceptable vector element type, so don't try.
if (WidenSize % InSize == 0 && InVT != MVT::x86mmx) {
// Determine new input vector type. The new input vector type will use
// the same element type (if its a vector) or use the input type as a
// vector. It is the same size as the type to widen to.
EVT NewInVT;
unsigned NewNumElts = WidenSize / InSize;
if (InVT.isVector()) {
EVT InEltVT = InVT.getVectorElementType();
NewInVT = EVT::getVectorVT(*DAG.getContext(), InEltVT,
WidenSize / InEltVT.getSizeInBits());
} else {
NewInVT = EVT::getVectorVT(*DAG.getContext(), InVT, NewNumElts);
}
if (TLI.isTypeLegal(NewInVT)) {
// Because the result and the input are different vector types, widening
// the result could create a legal type but widening the input might make
// it an illegal type that might lead to repeatedly splitting the input
// and then widening it. To avoid this, we widen the input only if
// it results in a legal type.
SmallVector<SDValue, 16> Ops(NewNumElts);
SDValue UndefVal = DAG.getUNDEF(InVT);
Ops[0] = InOp;
for (unsigned i = 1; i < NewNumElts; ++i)
Ops[i] = UndefVal;
SDValue NewVec;
if (InVT.isVector())
NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl,
NewInVT, &Ops[0], NewNumElts);
else
NewVec = DAG.getNode(ISD::BUILD_VECTOR, dl,
NewInVT, &Ops[0], NewNumElts);
return DAG.getNode(ISD::BITCAST, dl, WidenVT, NewVec);
}
}
return CreateStackStoreLoad(InOp, WidenVT);
}
SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) {
DebugLoc dl = N->getDebugLoc();
// Build a vector with undefined for the new nodes.
EVT VT = N->getValueType(0);
EVT EltVT = VT.getVectorElementType();
unsigned NumElts = VT.getVectorNumElements();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end());
NewOps.reserve(WidenNumElts);
for (unsigned i = NumElts; i < WidenNumElts; ++i)
NewOps.push_back(DAG.getUNDEF(EltVT));
return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &NewOps[0], NewOps.size());
}
SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) {
EVT InVT = N->getOperand(0).getValueType();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
DebugLoc dl = N->getDebugLoc();
unsigned WidenNumElts = WidenVT.getVectorNumElements();
unsigned NumInElts = InVT.getVectorNumElements();
unsigned NumOperands = N->getNumOperands();
bool InputWidened = false; // Indicates we need to widen the input.
if (getTypeAction(InVT) != TargetLowering::TypeWidenVector) {
if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) {
// Add undef vectors to widen to correct length.
unsigned NumConcat = WidenVT.getVectorNumElements() /
InVT.getVectorNumElements();
SDValue UndefVal = DAG.getUNDEF(InVT);
SmallVector<SDValue, 16> Ops(NumConcat);
for (unsigned i=0; i < NumOperands; ++i)
Ops[i] = N->getOperand(i);
for (unsigned i = NumOperands; i != NumConcat; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &Ops[0], NumConcat);
}
} else {
InputWidened = true;
if (WidenVT == TLI.getTypeToTransformTo(*DAG.getContext(), InVT)) {
// The inputs and the result are widen to the same value.
unsigned i;
for (i=1; i < NumOperands; ++i)
if (N->getOperand(i).getOpcode() != ISD::UNDEF)
break;
if (i == NumOperands)
// Everything but the first operand is an UNDEF so just return the
// widened first operand.
return GetWidenedVector(N->getOperand(0));
if (NumOperands == 2) {
// Replace concat of two operands with a shuffle.
SmallVector<int, 16> MaskOps(WidenNumElts, -1);
for (unsigned i = 0; i < NumInElts; ++i) {
MaskOps[i] = i;
MaskOps[i + NumInElts] = i + WidenNumElts;
}
return DAG.getVectorShuffle(WidenVT, dl,
GetWidenedVector(N->getOperand(0)),
GetWidenedVector(N->getOperand(1)),
&MaskOps[0]);
}
}
}
// Fall back to use extracts and build vector.
EVT EltVT = WidenVT.getVectorElementType();
SmallVector<SDValue, 16> Ops(WidenNumElts);
unsigned Idx = 0;
for (unsigned i=0; i < NumOperands; ++i) {
SDValue InOp = N->getOperand(i);
if (InputWidened)
InOp = GetWidenedVector(InOp);
for (unsigned j=0; j < NumInElts; ++j)
Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
DAG.getIntPtrConstant(j));
}
SDValue UndefVal = DAG.getUNDEF(EltVT);
for (; Idx < WidenNumElts; ++Idx)
Ops[Idx] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
}
SDValue DAGTypeLegalizer::WidenVecRes_CONVERT_RNDSAT(SDNode *N) {
DebugLoc dl = N->getDebugLoc();
SDValue InOp = N->getOperand(0);
SDValue RndOp = N->getOperand(3);
SDValue SatOp = N->getOperand(4);
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
unsigned WidenNumElts = WidenVT.getVectorNumElements();
EVT InVT = InOp.getValueType();
EVT InEltVT = InVT.getVectorElementType();
EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
SDValue DTyOp = DAG.getValueType(WidenVT);
SDValue STyOp = DAG.getValueType(InWidenVT);
ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
unsigned InVTNumElts = InVT.getVectorNumElements();
if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
InOp = GetWidenedVector(InOp);
InVT = InOp.getValueType();
InVTNumElts = InVT.getVectorNumElements();
if (InVTNumElts == WidenNumElts)
return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
SatOp, CvtCode);
}
if (TLI.isTypeLegal(InWidenVT)) {
// Because the result and the input are different vector types, widening
// the result could create a legal type but widening the input might make
// it an illegal type that might lead to repeatedly splitting the input
// and then widening it. To avoid this, we widen the input only if
// it results in a legal type.
if (WidenNumElts % InVTNumElts == 0) {
// Widen the input and call convert on the widened input vector.
unsigned NumConcat = WidenNumElts/InVTNumElts;
SmallVector<SDValue, 16> Ops(NumConcat);
Ops[0] = InOp;
SDValue UndefVal = DAG.getUNDEF(InVT);
for (unsigned i = 1; i != NumConcat; ++i)
Ops[i] = UndefVal;
InOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT, &Ops[0],NumConcat);
return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
SatOp, CvtCode);
}
if (InVTNumElts % WidenNumElts == 0) {
// Extract the input and convert the shorten input vector.
InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT, InOp,
DAG.getIntPtrConstant(0));
return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
SatOp, CvtCode);
}
}
// Otherwise unroll into some nasty scalar code and rebuild the vector.
SmallVector<SDValue, 16> Ops(WidenNumElts);
EVT EltVT = WidenVT.getVectorElementType();
DTyOp = DAG.getValueType(EltVT);
STyOp = DAG.getValueType(InEltVT);
unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
unsigned i;
for (i=0; i < MinElts; ++i) {
SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
DAG.getIntPtrConstant(i));
Ops[i] = DAG.getConvertRndSat(WidenVT, dl, ExtVal, DTyOp, STyOp, RndOp,
SatOp, CvtCode);
}
SDValue UndefVal = DAG.getUNDEF(EltVT);
for (; i < WidenNumElts; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
}
SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
EVT VT = N->getValueType(0);
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SDValue InOp = N->getOperand(0);
SDValue Idx = N->getOperand(1);
DebugLoc dl = N->getDebugLoc();
if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
InOp = GetWidenedVector(InOp);
EVT InVT = InOp.getValueType();
// Check if we can just return the input vector after widening.
uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
if (IdxVal == 0 && InVT == WidenVT)
return InOp;
// Check if we can extract from the vector.
unsigned InNumElts = InVT.getVectorNumElements();
if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts)
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx);
// We could try widening the input to the right length but for now, extract
// the original elements, fill the rest with undefs and build a vector.
SmallVector<SDValue, 16> Ops(WidenNumElts);
EVT EltVT = VT.getVectorElementType();
unsigned NumElts = VT.getVectorNumElements();
unsigned i;
for (i=0; i < NumElts; ++i)
Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
DAG.getIntPtrConstant(IdxVal+i));
SDValue UndefVal = DAG.getUNDEF(EltVT);
for (; i < WidenNumElts; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
}
SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) {
SDValue InOp = GetWidenedVector(N->getOperand(0));
return DAG.getNode(ISD::INSERT_VECTOR_ELT, N->getDebugLoc(),
InOp.getValueType(), InOp,
N->getOperand(1), N->getOperand(2));
}
SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
ISD::LoadExtType ExtType = LD->getExtensionType();
SDValue Result;
SmallVector<SDValue, 16> LdChain; // Chain for the series of load
if (ExtType != ISD::NON_EXTLOAD)
Result = GenWidenVectorExtLoads(LdChain, LD, ExtType);
else
Result = GenWidenVectorLoads(LdChain, LD);
// If we generate a single load, we can use that for the chain. Otherwise,
// build a factor node to remember the multiple loads are independent and
// chain to that.
SDValue NewChain;
if (LdChain.size() == 1)
NewChain = LdChain[0];
else
NewChain = DAG.getNode(ISD::TokenFactor, LD->getDebugLoc(), MVT::Other,
&LdChain[0], LdChain.size());
// Modified the chain - switch anything that used the old chain to use
// the new one.
ReplaceValueWith(SDValue(N, 1), NewChain);
return Result;
}
SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
return DAG.getNode(ISD::SCALAR_TO_VECTOR, N->getDebugLoc(),
WidenVT, N->getOperand(0));
}
SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SDValue Cond1 = N->getOperand(0);
EVT CondVT = Cond1.getValueType();
if (CondVT.isVector()) {
EVT CondEltVT = CondVT.getVectorElementType();
EVT CondWidenVT = EVT::getVectorVT(*DAG.getContext(),
CondEltVT, WidenNumElts);
if (getTypeAction(CondVT) == TargetLowering::TypeWidenVector)
Cond1 = GetWidenedVector(Cond1);
if (Cond1.getValueType() != CondWidenVT)
Cond1 = ModifyToType(Cond1, CondWidenVT);
}
SDValue InOp1 = GetWidenedVector(N->getOperand(1));
SDValue InOp2 = GetWidenedVector(N->getOperand(2));
assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT);
return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
WidenVT, Cond1, InOp1, InOp2);
}
SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) {
SDValue InOp1 = GetWidenedVector(N->getOperand(2));
SDValue InOp2 = GetWidenedVector(N->getOperand(3));
return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
InOp1.getValueType(), N->getOperand(0),
N->getOperand(1), InOp1, InOp2, N->getOperand(4));
}
SDValue DAGTypeLegalizer::WidenVecRes_SETCC(SDNode *N) {
assert(N->getValueType(0).isVector() ==
N->getOperand(0).getValueType().isVector() &&
"Scalar/Vector type mismatch");
if (N->getValueType(0).isVector()) return WidenVecRes_VSETCC(N);
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
SDValue InOp1 = GetWidenedVector(N->getOperand(0));
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
return DAG.getNode(ISD::SETCC, N->getDebugLoc(), WidenVT,
InOp1, InOp2, N->getOperand(2));
}
SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) {
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
return DAG.getUNDEF(WidenVT);
}
SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N) {
EVT VT = N->getValueType(0);
DebugLoc dl = N->getDebugLoc();
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
unsigned NumElts = VT.getVectorNumElements();
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SDValue InOp1 = GetWidenedVector(N->getOperand(0));
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
// Adjust mask based on new input vector length.
SmallVector<int, 16> NewMask;
for (unsigned i = 0; i != NumElts; ++i) {
int Idx = N->getMaskElt(i);
if (Idx < (int)NumElts)
NewMask.push_back(Idx);
else
NewMask.push_back(Idx - NumElts + WidenNumElts);
}
for (unsigned i = NumElts; i != WidenNumElts; ++i)
NewMask.push_back(-1);
return DAG.getVectorShuffle(WidenVT, dl, InOp1, InOp2, &NewMask[0]);
}
SDValue DAGTypeLegalizer::WidenVecRes_VSETCC(SDNode *N) {
assert(N->getValueType(0).isVector() &&
N->getOperand(0).getValueType().isVector() &&
"Operands must be vectors");
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SDValue InOp1 = N->getOperand(0);
EVT InVT = InOp1.getValueType();
assert(InVT.isVector() && "can not widen non vector type");
EVT WidenInVT = EVT::getVectorVT(*DAG.getContext(),
InVT.getVectorElementType(), WidenNumElts);
InOp1 = GetWidenedVector(InOp1);
SDValue InOp2 = GetWidenedVector(N->getOperand(1));
// Assume that the input and output will be widen appropriately. If not,
// we will have to unroll it at some point.
assert(InOp1.getValueType() == WidenInVT &&
InOp2.getValueType() == WidenInVT &&
"Input not widened to expected type!");
(void)WidenInVT;
return DAG.getNode(ISD::SETCC, N->getDebugLoc(),
WidenVT, InOp1, InOp2, N->getOperand(2));
}
//===----------------------------------------------------------------------===//
// Widen Vector Operand
//===----------------------------------------------------------------------===//
bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned OpNo) {
DEBUG(dbgs() << "Widen node operand " << OpNo << ": ";
N->dump(&DAG);
dbgs() << "\n");
SDValue Res = SDValue();
// See if the target wants to custom widen this node.
if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
return false;
switch (N->getOpcode()) {
default:
#ifndef NDEBUG
dbgs() << "WidenVectorOperand op #" << OpNo << ": ";
N->dump(&DAG);
dbgs() << "\n";
#endif
llvm_unreachable("Do not know how to widen this operator's operand!");
case ISD::BITCAST: Res = WidenVecOp_BITCAST(N); break;
case ISD::CONCAT_VECTORS: Res = WidenVecOp_CONCAT_VECTORS(N); break;
case ISD::EXTRACT_SUBVECTOR: Res = WidenVecOp_EXTRACT_SUBVECTOR(N); break;
case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break;
case ISD::STORE: Res = WidenVecOp_STORE(N); break;
case ISD::SETCC: Res = WidenVecOp_SETCC(N); break;
case ISD::FP_EXTEND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::SINT_TO_FP:
case ISD::UINT_TO_FP:
case ISD::TRUNCATE:
case ISD::SIGN_EXTEND:
case ISD::ZERO_EXTEND:
case ISD::ANY_EXTEND:
Res = WidenVecOp_Convert(N);
break;
}
// If Res is null, the sub-method took care of registering the result.
if (!Res.getNode()) return false;
// If the result is N, the sub-method updated N in place. Tell the legalizer
// core about this.
if (Res.getNode() == N)
return true;
assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
"Invalid operand expansion");
ReplaceValueWith(SDValue(N, 0), Res);
return false;
}
SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) {
// Since the result is legal and the input is illegal, it is unlikely
// that we can fix the input to a legal type so unroll the convert
// into some scalar code and create a nasty build vector.
EVT VT = N->getValueType(0);
EVT EltVT = VT.getVectorElementType();
DebugLoc dl = N->getDebugLoc();
unsigned NumElts = VT.getVectorNumElements();
SDValue InOp = N->getOperand(0);
if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
InOp = GetWidenedVector(InOp);
EVT InVT = InOp.getValueType();
EVT InEltVT = InVT.getVectorElementType();
unsigned Opcode = N->getOpcode();
SmallVector<SDValue, 16> Ops(NumElts);
for (unsigned i=0; i < NumElts; ++i)
Ops[i] = DAG.getNode(Opcode, dl, EltVT,
DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
DAG.getIntPtrConstant(i)));
return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
}
SDValue DAGTypeLegalizer::WidenVecOp_BITCAST(SDNode *N) {
EVT VT = N->getValueType(0);
SDValue InOp = GetWidenedVector(N->getOperand(0));
EVT InWidenVT = InOp.getValueType();
DebugLoc dl = N->getDebugLoc();
// Check if we can convert between two legal vector types and extract.
unsigned InWidenSize = InWidenVT.getSizeInBits();
unsigned Size = VT.getSizeInBits();
// x86mmx is not an acceptable vector element type, so don't try.
if (InWidenSize % Size == 0 && !VT.isVector() && VT != MVT::x86mmx) {
unsigned NewNumElts = InWidenSize / Size;
EVT NewVT = EVT::getVectorVT(*DAG.getContext(), VT, NewNumElts);
if (TLI.isTypeLegal(NewVT)) {
SDValue BitOp = DAG.getNode(ISD::BITCAST, dl, NewVT, InOp);
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp,
DAG.getIntPtrConstant(0));
}
}
return CreateStackStoreLoad(InOp, VT);
}
SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) {
// If the input vector is not legal, it is likely that we will not find a
// legal vector of the same size. Replace the concatenate vector with a
// nasty build vector.
EVT VT = N->getValueType(0);
EVT EltVT = VT.getVectorElementType();
DebugLoc dl = N->getDebugLoc();
unsigned NumElts = VT.getVectorNumElements();
SmallVector<SDValue, 16> Ops(NumElts);
EVT InVT = N->getOperand(0).getValueType();
unsigned NumInElts = InVT.getVectorNumElements();
unsigned Idx = 0;
unsigned NumOperands = N->getNumOperands();
for (unsigned i=0; i < NumOperands; ++i) {
SDValue InOp = N->getOperand(i);
if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
InOp = GetWidenedVector(InOp);
for (unsigned j=0; j < NumInElts; ++j)
Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
DAG.getIntPtrConstant(j));
}
return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
}
SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
SDValue InOp = GetWidenedVector(N->getOperand(0));
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(),
N->getValueType(0), InOp, N->getOperand(1));
}
SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
SDValue InOp = GetWidenedVector(N->getOperand(0));
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(),
N->getValueType(0), InOp, N->getOperand(1));
}
SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) {
// We have to widen the value but we want only to store the original
// vector type.
StoreSDNode *ST = cast<StoreSDNode>(N);
SmallVector<SDValue, 16> StChain;
if (ST->isTruncatingStore())
GenWidenVectorTruncStores(StChain, ST);
else
GenWidenVectorStores(StChain, ST);
if (StChain.size() == 1)
return StChain[0];
else
return DAG.getNode(ISD::TokenFactor, ST->getDebugLoc(),
MVT::Other,&StChain[0],StChain.size());
}
SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) {
SDValue InOp0 = GetWidenedVector(N->getOperand(0));
SDValue InOp1 = GetWidenedVector(N->getOperand(1));
DebugLoc dl = N->getDebugLoc();
// WARNING: In this code we widen the compare instruction with garbage.
// This garbage may contain denormal floats which may be slow. Is this a real
// concern ? Should we zero the unused lanes if this is a float compare ?
// Get a new SETCC node to compare the newly widened operands.
// Only some of the compared elements are legal.
EVT SVT = TLI.getSetCCResultType(InOp0.getValueType());
SDValue WideSETCC = DAG.getNode(ISD::SETCC, N->getDebugLoc(),
SVT, InOp0, InOp1, N->getOperand(2));
// Extract the needed results from the result vector.
EVT ResVT = EVT::getVectorVT(*DAG.getContext(),
SVT.getVectorElementType(),
N->getValueType(0).getVectorNumElements());
SDValue CC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
ResVT, WideSETCC, DAG.getIntPtrConstant(0));
return PromoteTargetBoolean(CC, N->getValueType(0));
}
//===----------------------------------------------------------------------===//
// Vector Widening Utilities
//===----------------------------------------------------------------------===//
// Utility function to find the type to chop up a widen vector for load/store
// TLI: Target lowering used to determine legal types.
// Width: Width left need to load/store.
// WidenVT: The widen vector type to load to/store from
// Align: If 0, don't allow use of a wider type
// WidenEx: If Align is not 0, the amount additional we can load/store from.
static EVT FindMemType(SelectionDAG& DAG, const TargetLowering &TLI,
unsigned Width, EVT WidenVT,
unsigned Align = 0, unsigned WidenEx = 0) {
EVT WidenEltVT = WidenVT.getVectorElementType();
unsigned WidenWidth = WidenVT.getSizeInBits();
unsigned WidenEltWidth = WidenEltVT.getSizeInBits();
unsigned AlignInBits = Align*8;
// If we have one element to load/store, return it.
EVT RetVT = WidenEltVT;
if (Width == WidenEltWidth)
return RetVT;
// See if there is larger legal integer than the element type to load/store
unsigned VT;
for (VT = (unsigned)MVT::LAST_INTEGER_VALUETYPE;
VT >= (unsigned)MVT::FIRST_INTEGER_VALUETYPE; --VT) {
EVT MemVT((MVT::SimpleValueType) VT);
unsigned MemVTWidth = MemVT.getSizeInBits();
if (MemVT.getSizeInBits() <= WidenEltWidth)
break;
if (TLI.isTypeLegal(MemVT) && (WidenWidth % MemVTWidth) == 0 &&
isPowerOf2_32(WidenWidth / MemVTWidth) &&
(MemVTWidth <= Width ||
(Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
RetVT = MemVT;
break;
}
}
// See if there is a larger vector type to load/store that has the same vector
// element type and is evenly divisible with the WidenVT.
for (VT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
VT >= (unsigned)MVT::FIRST_VECTOR_VALUETYPE; --VT) {
EVT MemVT = (MVT::SimpleValueType) VT;
unsigned MemVTWidth = MemVT.getSizeInBits();
if (TLI.isTypeLegal(MemVT) && WidenEltVT == MemVT.getVectorElementType() &&
(WidenWidth % MemVTWidth) == 0 &&
isPowerOf2_32(WidenWidth / MemVTWidth) &&
(MemVTWidth <= Width ||
(Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
if (RetVT.getSizeInBits() < MemVTWidth || MemVT == WidenVT)
return MemVT;
}
}
return RetVT;
}
// Builds a vector type from scalar loads
// VecTy: Resulting Vector type
// LDOps: Load operators to build a vector type
// [Start,End) the list of loads to use.
static SDValue BuildVectorFromScalar(SelectionDAG& DAG, EVT VecTy,
SmallVector<SDValue, 16>& LdOps,
unsigned Start, unsigned End) {
DebugLoc dl = LdOps[Start].getDebugLoc();
EVT LdTy = LdOps[Start].getValueType();
unsigned Width = VecTy.getSizeInBits();
unsigned NumElts = Width / LdTy.getSizeInBits();
EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), LdTy, NumElts);
unsigned Idx = 1;
SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT,LdOps[Start]);
for (unsigned i = Start + 1; i != End; ++i) {
EVT NewLdTy = LdOps[i].getValueType();
if (NewLdTy != LdTy) {
NumElts = Width / NewLdTy.getSizeInBits();
NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewLdTy, NumElts);
VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, VecOp);
// Readjust position and vector position based on new load type
Idx = Idx * LdTy.getSizeInBits() / NewLdTy.getSizeInBits();
LdTy = NewLdTy;
}
VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOps[i],
DAG.getIntPtrConstant(Idx++));
}
return DAG.getNode(ISD::BITCAST, dl, VecTy, VecOp);
}
SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVector<SDValue, 16> &LdChain,
LoadSDNode *LD) {
// The strategy assumes that we can efficiently load powers of two widths.
// The routines chops the vector into the largest vector loads with the same
// element type or scalar loads and then recombines it to the widen vector
// type.
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
unsigned WidenWidth = WidenVT.getSizeInBits();
EVT LdVT = LD->getMemoryVT();
DebugLoc dl = LD->getDebugLoc();
assert(LdVT.isVector() && WidenVT.isVector());
assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType());
// Load information
SDValue Chain = LD->getChain();
SDValue BasePtr = LD->getBasePtr();
unsigned Align = LD->getAlignment();
bool isVolatile = LD->isVolatile();
bool isNonTemporal = LD->isNonTemporal();
bool isInvariant = LD->isInvariant();
int LdWidth = LdVT.getSizeInBits();
int WidthDiff = WidenWidth - LdWidth; // Difference
unsigned LdAlign = (isVolatile) ? 0 : Align; // Allow wider loads
// Find the vector type that can load from.
EVT NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
int NewVTWidth = NewVT.getSizeInBits();
SDValue LdOp = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo(),
isVolatile, isNonTemporal, isInvariant, Align);
LdChain.push_back(LdOp.getValue(1));
// Check if we can load the element with one instruction
if (LdWidth <= NewVTWidth) {
if (!NewVT.isVector()) {
unsigned NumElts = WidenWidth / NewVTWidth;
EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp);
return DAG.getNode(ISD::BITCAST, dl, WidenVT, VecOp);
}
if (NewVT == WidenVT)
return LdOp;
assert(WidenWidth % NewVTWidth == 0);
unsigned NumConcat = WidenWidth / NewVTWidth;
SmallVector<SDValue, 16> ConcatOps(NumConcat);
SDValue UndefVal = DAG.getUNDEF(NewVT);
ConcatOps[0] = LdOp;
for (unsigned i = 1; i != NumConcat; ++i)
ConcatOps[i] = UndefVal;
return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0],
NumConcat);
}
// Load vector by using multiple loads from largest vector to scalar
SmallVector<SDValue, 16> LdOps;
LdOps.push_back(LdOp);
LdWidth -= NewVTWidth;
unsigned Offset = 0;
while (LdWidth > 0) {
unsigned Increment = NewVTWidth / 8;
Offset += Increment;
BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
DAG.getIntPtrConstant(Increment));
SDValue L;
if (LdWidth < NewVTWidth) {
// Our current type we are using is too large, find a better size
NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
NewVTWidth = NewVT.getSizeInBits();
L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
LD->getPointerInfo().getWithOffset(Offset), isVolatile,
isNonTemporal, isInvariant, MinAlign(Align, Increment));
LdChain.push_back(L.getValue(1));
if (L->getValueType(0).isVector()) {
SmallVector<SDValue, 16> Loads;
Loads.push_back(L);
unsigned size = L->getValueSizeInBits(0);
while (size < LdOp->getValueSizeInBits(0)) {
Loads.push_back(DAG.getUNDEF(L->getValueType(0)));
size += L->getValueSizeInBits(0);
}
L = DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0),
&Loads[0], Loads.size());
}
} else {
L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
LD->getPointerInfo().getWithOffset(Offset), isVolatile,
isNonTemporal, isInvariant, MinAlign(Align, Increment));
LdChain.push_back(L.getValue(1));
}
LdOps.push_back(L);
LdWidth -= NewVTWidth;
}
// Build the vector from the loads operations
unsigned End = LdOps.size();
if (!LdOps[0].getValueType().isVector())
// All the loads are scalar loads.
return BuildVectorFromScalar(DAG, WidenVT, LdOps, 0, End);
// If the load contains vectors, build the vector using concat vector.
// All of the vectors used to loads are power of 2 and the scalars load
// can be combined to make a power of 2 vector.
SmallVector<SDValue, 16> ConcatOps(End);
int i = End - 1;
int Idx = End;
EVT LdTy = LdOps[i].getValueType();
// First combine the scalar loads to a vector
if (!LdTy.isVector()) {
for (--i; i >= 0; --i) {
LdTy = LdOps[i].getValueType();
if (LdTy.isVector())
break;
}
ConcatOps[--Idx] = BuildVectorFromScalar(DAG, LdTy, LdOps, i+1, End);
}
ConcatOps[--Idx] = LdOps[i];
for (--i; i >= 0; --i) {
EVT NewLdTy = LdOps[i].getValueType();
if (NewLdTy != LdTy) {
// Create a larger vector
ConcatOps[End-1] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewLdTy,
&ConcatOps[Idx], End - Idx);
Idx = End - 1;
LdTy = NewLdTy;
}
ConcatOps[--Idx] = LdOps[i];
}
if (WidenWidth == LdTy.getSizeInBits()*(End - Idx))
return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
&ConcatOps[Idx], End - Idx);
// We need to fill the rest with undefs to build the vector
unsigned NumOps = WidenWidth / LdTy.getSizeInBits();
SmallVector<SDValue, 16> WidenOps(NumOps);
SDValue UndefVal = DAG.getUNDEF(LdTy);
{
unsigned i = 0;
for (; i != End-Idx; ++i)
WidenOps[i] = ConcatOps[Idx+i];
for (; i != NumOps; ++i)
WidenOps[i] = UndefVal;
}
return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &WidenOps[0],NumOps);
}
SDValue
DAGTypeLegalizer::GenWidenVectorExtLoads(SmallVector<SDValue, 16>& LdChain,
LoadSDNode * LD,
ISD::LoadExtType ExtType) {
// For extension loads, it may not be more efficient to chop up the vector
// and then extended it. Instead, we unroll the load and build a new vector.
EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
EVT LdVT = LD->getMemoryVT();
DebugLoc dl = LD->getDebugLoc();
assert(LdVT.isVector() && WidenVT.isVector());
// Load information
SDValue Chain = LD->getChain();
SDValue BasePtr = LD->getBasePtr();
unsigned Align = LD->getAlignment();
bool isVolatile = LD->isVolatile();
bool isNonTemporal = LD->isNonTemporal();
EVT EltVT = WidenVT.getVectorElementType();
EVT LdEltVT = LdVT.getVectorElementType();
unsigned NumElts = LdVT.getVectorNumElements();
// Load each element and widen
unsigned WidenNumElts = WidenVT.getVectorNumElements();
SmallVector<SDValue, 16> Ops(WidenNumElts);
unsigned Increment = LdEltVT.getSizeInBits() / 8;
Ops[0] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr,
LD->getPointerInfo(),
LdEltVT, isVolatile, isNonTemporal, Align);
LdChain.push_back(Ops[0].getValue(1));
unsigned i = 0, Offset = Increment;
for (i=1; i < NumElts; ++i, Offset += Increment) {
SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
BasePtr, DAG.getIntPtrConstant(Offset));
Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr,
LD->getPointerInfo().getWithOffset(Offset), LdEltVT,
isVolatile, isNonTemporal, Align);
LdChain.push_back(Ops[i].getValue(1));
}
// Fill the rest with undefs
SDValue UndefVal = DAG.getUNDEF(EltVT);
for (; i != WidenNumElts; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], Ops.size());
}
void DAGTypeLegalizer::GenWidenVectorStores(SmallVector<SDValue, 16>& StChain,
StoreSDNode *ST) {
// The strategy assumes that we can efficiently store powers of two widths.
// The routines chops the vector into the largest vector stores with the same
// element type or scalar stores.
SDValue Chain = ST->getChain();
SDValue BasePtr = ST->getBasePtr();
unsigned Align = ST->getAlignment();
bool isVolatile = ST->isVolatile();
bool isNonTemporal = ST->isNonTemporal();
SDValue ValOp = GetWidenedVector(ST->getValue());
DebugLoc dl = ST->getDebugLoc();
EVT StVT = ST->getMemoryVT();
unsigned StWidth = StVT.getSizeInBits();
EVT ValVT = ValOp.getValueType();
unsigned ValWidth = ValVT.getSizeInBits();
EVT ValEltVT = ValVT.getVectorElementType();
unsigned ValEltWidth = ValEltVT.getSizeInBits();
assert(StVT.getVectorElementType() == ValEltVT);
int Idx = 0; // current index to store
unsigned Offset = 0; // offset from base to store
while (StWidth != 0) {
// Find the largest vector type we can store with
EVT NewVT = FindMemType(DAG, TLI, StWidth, ValVT);
unsigned NewVTWidth = NewVT.getSizeInBits();
unsigned Increment = NewVTWidth / 8;
if (NewVT.isVector()) {
unsigned NumVTElts = NewVT.getVectorNumElements();
do {
SDValue EOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT, ValOp,
DAG.getIntPtrConstant(Idx));
StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
ST->getPointerInfo().getWithOffset(Offset),
isVolatile, isNonTemporal,
MinAlign(Align, Offset)));
StWidth -= NewVTWidth;
Offset += Increment;
Idx += NumVTElts;
BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
DAG.getIntPtrConstant(Increment));
} while (StWidth != 0 && StWidth >= NewVTWidth);
} else {
// Cast the vector to the scalar type we can store
unsigned NumElts = ValWidth / NewVTWidth;
EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
SDValue VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, ValOp);
// Readjust index position based on new vector type
Idx = Idx * ValEltWidth / NewVTWidth;
do {
SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT, VecOp,
DAG.getIntPtrConstant(Idx++));
StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
ST->getPointerInfo().getWithOffset(Offset),
isVolatile, isNonTemporal,
MinAlign(Align, Offset)));
StWidth -= NewVTWidth;
Offset += Increment;
BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
DAG.getIntPtrConstant(Increment));
} while (StWidth != 0 && StWidth >= NewVTWidth);
// Restore index back to be relative to the original widen element type
Idx = Idx * NewVTWidth / ValEltWidth;
}
}
}
void
DAGTypeLegalizer::GenWidenVectorTruncStores(SmallVector<SDValue, 16>& StChain,
StoreSDNode *ST) {
// For extension loads, it may not be more efficient to truncate the vector
// and then store it. Instead, we extract each element and then store it.
SDValue Chain = ST->getChain();
SDValue BasePtr = ST->getBasePtr();
unsigned Align = ST->getAlignment();
bool isVolatile = ST->isVolatile();
bool isNonTemporal = ST->isNonTemporal();
SDValue ValOp = GetWidenedVector(ST->getValue());
DebugLoc dl = ST->getDebugLoc();
EVT StVT = ST->getMemoryVT();
EVT ValVT = ValOp.getValueType();
// It must be true that we the widen vector type is bigger than where
// we need to store.
assert(StVT.isVector() && ValOp.getValueType().isVector());
assert(StVT.bitsLT(ValOp.getValueType()));
// For truncating stores, we can not play the tricks of chopping legal
// vector types and bit cast it to the right type. Instead, we unroll
// the store.
EVT StEltVT = StVT.getVectorElementType();
EVT ValEltVT = ValVT.getVectorElementType();
unsigned Increment = ValEltVT.getSizeInBits() / 8;
unsigned NumElts = StVT.getVectorNumElements();
SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
DAG.getIntPtrConstant(0));
StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr,
ST->getPointerInfo(), StEltVT,
isVolatile, isNonTemporal, Align));
unsigned Offset = Increment;
for (unsigned i=1; i < NumElts; ++i, Offset += Increment) {
SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
BasePtr, DAG.getIntPtrConstant(Offset));
SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
DAG.getIntPtrConstant(0));
StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, NewBasePtr,
ST->getPointerInfo().getWithOffset(Offset),
StEltVT, isVolatile, isNonTemporal,
MinAlign(Align, Offset)));
}
}
/// Modifies a vector input (widen or narrows) to a vector of NVT. The
/// input vector must have the same element type as NVT.
SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, EVT NVT) {
// Note that InOp might have been widened so it might already have
// the right width or it might need be narrowed.
EVT InVT = InOp.getValueType();
assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
"input and widen element type must match");
DebugLoc dl = InOp.getDebugLoc();
// Check if InOp already has the right width.
if (InVT == NVT)
return InOp;
unsigned InNumElts = InVT.getVectorNumElements();
unsigned WidenNumElts = NVT.getVectorNumElements();
if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) {
unsigned NumConcat = WidenNumElts / InNumElts;
SmallVector<SDValue, 16> Ops(NumConcat);
SDValue UndefVal = DAG.getUNDEF(InVT);
Ops[0] = InOp;
for (unsigned i = 1; i != NumConcat; ++i)
Ops[i] = UndefVal;
return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, &Ops[0], NumConcat);
}
if (WidenNumElts < InNumElts && InNumElts % WidenNumElts)
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp,
DAG.getIntPtrConstant(0));
// Fall back to extract and build.
SmallVector<SDValue, 16> Ops(WidenNumElts);
EVT EltVT = NVT.getVectorElementType();
unsigned MinNumElts = std::min(WidenNumElts, InNumElts);
unsigned Idx;
for (Idx = 0; Idx < MinNumElts; ++Idx)
Ops[Idx] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
DAG.getIntPtrConstant(Idx));
SDValue UndefVal = DAG.getUNDEF(EltVT);
for ( ; Idx < WidenNumElts; ++Idx)
Ops[Idx] = UndefVal;
return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &Ops[0], WidenNumElts);
}
| 38.971712 | 81 | 0.639172 | nettrino |
d51a8fe0a2f169cda115e9ac3721afcf1e9d24d5 | 5,873 | cc | C++ | src/run_crown/deref_expression.cc | Clown-FM/CROWN | 7690d59d9459ffa1be7226edd0bede7546412da9 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2019-09-07T09:58:26.000Z | 2019-09-07T09:58:26.000Z | src/run_crown/deref_expression.cc | kunwoo1209/CROWN | 7690d59d9459ffa1be7226edd0bede7546412da9 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/run_crown/deref_expression.cc | kunwoo1209/CROWN | 7690d59d9459ffa1be7226edd0bede7546412da9 | [
"MIT",
"BSD-3-Clause"
] | 4 | 2019-09-07T09:53:17.000Z | 2021-09-04T16:11:20.000Z | // This file is part of CROWN, which is distributed under the revised
// BSD license. A copy of this license can be found in the file LICENSE.
//
// 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 LICENSE
// for details.
/***
* Author: Sudeep juvekar (sjuvekar@eecs.berkeley.edu)
* 4/17/09
*/
#include <assert.h>
#include <cstdlib>
#include <cstring>
#include <z3.h>
#include <iostream>
#include "base/basic_functions.h"
#include "run_crown/deref_expression.h"
#include "run_crown/symbolic_object.h"
#include "run_crown/object_tracker.h"
#include "run_crown/symbolic_expression_factory.h"
namespace crown {
DerefExpr::DerefExpr(SymbolicExpr *c, size_t managerIdx, size_t snapshotIdx,
size_t s, Value_t v)
: SymbolicExpr(s,v), managerIdx_(managerIdx), snapshotIdx_(snapshotIdx), addr_(c) { }
DerefExpr::DerefExpr(const DerefExpr& de)
: SymbolicExpr(de.size(), de.value()),
managerIdx_(de.managerIdx_), snapshotIdx_(de.snapshotIdx_),
object_(de.object_), addr_(de.addr_->Clone())
{ }
DerefExpr::~DerefExpr() {
delete addr_;
}
DerefExpr* DerefExpr::Clone() const {
return new DerefExpr(*this);
}
void DerefExpr::AppendVars(set<var_t>* vars) const {
ObjectTracker* tracker = global_tracker_;
assert(tracker->snapshotManager().size() > managerIdx_);
assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_);
SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_);
addr_->AppendVars(vars);
for(size_t i = 0; i < object->writes().size(); i++){
SymbolicExpr *index = object->writes()[i].first;
SymbolicExpr *exp = object->writes()[i].second;
index->AppendVars(vars);
exp->AppendVars(vars);
}
}
bool DerefExpr::DependsOn(const map<var_t,type_t>& vars) const {
ObjectTracker* tracker = global_tracker_;
assert(tracker->snapshotManager().size() > managerIdx_);
assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_);
SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_);
for(size_t i = 0; i < object->writes().size(); i++){
SymbolicExpr *index = object->writes()[i].first;
SymbolicExpr *exp = object->writes()[i].second;
bool res = index->DependsOn(vars) || exp->DependsOn(vars);
if(res == true){
return true;
}
}
return addr_->DependsOn(vars);
}
void DerefExpr::AppendToString(string *s) const {
char buff[92];
s->append("(a!");
sprintf(buff, "%d%d[ ", managerIdx_,snapshotIdx_);
s->append(buff);
// s->append(", ");
addr_->AppendToString(s);
s->append(" ])");
}
Z3_ast DerefExpr::ConvertToSMT(Z3_context ctx, Z3_solver sol) const {
#ifdef DEBUG
printf("ConvertToSMT Deref %d %d\n",managerIdx_, snapshotIdx_);
#endif
global_numOfOperator_++;
size_t size_ = size();
Value_t value_ = value();
ObjectTracker* tracker = global_tracker_;
assert(tracker->snapshotManager().size() > managerIdx_);
assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_);
SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_);
//If the snapshots are not created as a SMT, then create dummy SMT
if(tracker->isASTInit == false){
char name[24] = "t0";
Z3_sort ty = Z3_mk_bv_sort(ctx, 32);
Z3_ast con = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, name), ty);
for(size_t iter = 0; iter < tracker->snapshotManager().size(); iter++){
size_t objSize = tracker->snapshotManager()[iter]->size();
for(size_t iter2 = 0; iter2 < objSize; iter2++){
tracker->astManager()[iter]->push_back(con);
tracker->isCreateAST()[iter]->push_back(false);
}
}
tracker->isASTInit = true;
}
//size_t mem_length = object->writes().size();
//Naming the uninterpreted function
char c[32];
sprintf(c, "a%ld",(unsigned long)this);
//Bit-blast the address
Z3_ast args_z3_f[1] = {addr_->ConvertToSMT(ctx, sol)};
Z3_sort input_type = Z3_mk_bv_sort(ctx, addr_->size() * 8);
Z3_sort output_type;
//Output values of a[x] needs to be registered. (e.g. double a[4])
if(value_.type == types::FLOAT){
output_type = Z3_mk_fpa_sort_single(ctx);
}else if(value_.type == types::DOUBLE){
output_type = Z3_mk_fpa_sort_double(ctx);
}else{
output_type = Z3_mk_bv_sort(ctx, size_*8);
}
Z3_symbol array_symbol = Z3_mk_string_symbol(ctx, c);
Z3_sort array_sort = Z3_mk_array_sort(ctx, input_type, output_type);
Z3_ast array = Z3_mk_const(ctx, array_symbol, array_sort);
//If the object isn't already created as SMT, then create it.
if(tracker->isCreateAST()[managerIdx_]->at(snapshotIdx_) == false){
array = object->ConvertToSMT(ctx, sol, array, output_type);
tracker->astManager()[managerIdx_]->at(snapshotIdx_) = array;
tracker->isCreateAST()[managerIdx_]->at(snapshotIdx_) = true;
}else{
array = tracker->astManager()[managerIdx_]->at(snapshotIdx_);
}
//Dereference has to be in array (e.g. a[4] -> index can be 0,1,2,3)
int sortSizeOfArray = Z3_get_bv_sort_size(ctx, Z3_get_sort(ctx, args_z3_f[0]));
Z3_ast startAST = Z3_mk_int64(ctx, object->start(), Z3_mk_bv_sort(ctx, sortSizeOfArray));
Z3_ast endAST = Z3_mk_int64(ctx, object->start()+object->size(), Z3_mk_bv_sort(ctx, sortSizeOfArray));
Z3_ast startAST2 = Z3_mk_bvuge(ctx, args_z3_f[0], startAST);
Z3_ast endAST2 = Z3_mk_bvult(ctx, args_z3_f[0], endAST);
global_numOfExpr_+=2;
//Assert that symbolic address is equal to at one of the values in domain
Z3_solver_assert(ctx, sol,startAST2);
Z3_solver_assert(ctx, sol,endAST2);
//Return the application of the function to addr_
Z3_ast tmp = Z3_mk_select(ctx, array, args_z3_f[0]);
return tmp;
}
bool DerefExpr::Equals(const SymbolicExpr& e) const {
const DerefExpr* d = e.CastDerefExpr();
return ((d != NULL)
&& addr_->Equals(*d->addr_)
&& object_->Equals(*d->object_));
}
} // namespace crown
| 32.269231 | 103 | 0.715307 | Clown-FM |
d51d1caa2d631123f846b1530b8e5e05133e36c2 | 62,133 | cpp | C++ | WDL/win32_curses/eel_edit.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 1,305 | 2018-07-28T08:48:47.000Z | 2022-03-31T23:06:59.000Z | WDL/win32_curses/eel_edit.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 582 | 2019-01-01T15:37:55.000Z | 2022-03-30T22:57:16.000Z | WDL/win32_curses/eel_edit.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 284 | 2018-10-17T22:16:26.000Z | 2022-03-30T15:38:19.000Z | #ifdef _WIN32
#include <windows.h>
#include <windowsx.h>
#else
#include "../swell/swell.h"
#endif
#include <stdlib.h>
#include <string.h>
#ifndef CURSES_INSTANCE
#define CURSES_INSTANCE ((win32CursesCtx *)m_cursesCtx)
#endif
#include "curses.h"
#include "eel_edit.h"
#include "../wdlutf8.h"
#include "../win32_utf8.h"
#include "../wdlcstring.h"
#include "../eel2/ns-eel-int.h"
int g_eel_editor_max_vis_suggestions = 50;
EEL_Editor::EEL_Editor(void *cursesCtx) : WDL_CursesEditor(cursesCtx)
{
m_suggestion_curline_comment_state=0;
m_suggestion_x=m_suggestion_y=-1;
m_case_sensitive=false;
m_comment_str="//"; // todo IsWithinComment() or something?
m_function_prefix = "function ";
m_suggestion_hwnd=NULL;
m_code_func_cache_lines=0;
m_code_func_cache_time=0;
}
EEL_Editor::~EEL_Editor()
{
if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd);
m_code_func_cache.Empty(true,free);
}
#define sh_func_ontoken(x,y)
int EEL_Editor::namedTokenHighlight(const char *tokStart, int len, int state)
{
if (len == 4 && !strnicmp(tokStart,"this",4)) return SYNTAX_KEYWORD;
if (len == 7 && !strnicmp(tokStart,"_global",7)) return SYNTAX_KEYWORD;
if (len == 5 && !strnicmp(tokStart,"local",5)) return SYNTAX_KEYWORD;
if (len == 8 && !strnicmp(tokStart,"function",8)) return SYNTAX_KEYWORD;
if (len == 6 && !strnicmp(tokStart,"static",6)) return SYNTAX_KEYWORD;
if (len == 8 && !strnicmp(tokStart,"instance",8)) return SYNTAX_KEYWORD;
if (len == 6 && !strnicmp(tokStart,"global",6)) return SYNTAX_KEYWORD;
if (len == 7 && !strnicmp(tokStart,"globals",7)) return SYNTAX_KEYWORD;
if (len == 5 && !strnicmp(tokStart,"while",5)) return SYNTAX_KEYWORD;
if (len == 4 && !strnicmp(tokStart,"loop",4)) return SYNTAX_KEYWORD;
if (len == 17 && !strnicmp(tokStart,"__denormal_likely",17)) return SYNTAX_FUNC;
if (len == 19 && !strnicmp(tokStart,"__denormal_unlikely",19)) return SYNTAX_FUNC;
char buf[512];
lstrcpyn_safe(buf,tokStart,wdl_min(sizeof(buf),len+1));
NSEEL_VMCTX vm = peek_want_VM_funcs() ? peek_get_VM() : NULL;
if (nseel_getFunctionByName((compileContext*)vm,buf,NULL)) return SYNTAX_FUNC;
return A_NORMAL;
}
int EEL_Editor::parse_format_specifier(const char *fmt_in, int *var_offs, int *var_len)
{
const char *fmt = fmt_in+1;
*var_offs = 0;
*var_len = 0;
if (fmt_in[0] != '%') return 0; // passed a non-specifier
while (*fmt)
{
const char c = *fmt++;
if (c>0 && isalpha(c))
{
return (int) (fmt - fmt_in);
}
if (c == '.' || c == '+' || c == '-' || c == ' ' || (c>='0' && c<='9'))
{
}
else if (c == '{')
{
if (*var_offs!=0) return 0; // already specified
*var_offs = (int)(fmt-fmt_in);
if (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) return 0; // symbol name can't start with 0-9 or .
while (*fmt != '}')
{
if ((*fmt >= 'a' && *fmt <= 'z') ||
(*fmt >= 'A' && *fmt <= 'Z') ||
(*fmt >= '0' && *fmt <= '9') ||
*fmt == '_' || *fmt == '.' || *fmt == '#')
{
fmt++;
}
else
{
return 0; // bad character in variable name
}
}
*var_len = (int)((fmt-fmt_in) - *var_offs);
fmt++;
}
else
{
break;
}
}
return 0;
}
void EEL_Editor::draw_string(int *skipcnt, const char *str, int amt, int *attr, int newAttr, int comment_string_state)
{
if (amt > 0 && comment_string_state=='"')
{
while (amt > 0 && *str)
{
const char *str_scan = str;
int varpos,varlen,l=0;
while (!l && *str_scan)
{
while (*str_scan && *str_scan != '%' && str_scan < str+amt) str_scan++;
if (str_scan >= str+amt) break;
l = parse_format_specifier(str_scan,&varpos,&varlen);
if (!l && *str_scan) if (*++str_scan == '%') str_scan++;
}
if (!*str_scan || str_scan >= str+amt) break; // allow default processing to happen if we reached the end of the string
if (l > amt) l=amt;
if (str_scan > str)
{
const int sz=wdl_min((int)(str_scan-str),amt);
draw_string_urlchk(skipcnt,str,sz,attr,newAttr);
str += sz;
amt -= sz;
}
{
const int sz=(varlen>0) ? wdl_min(varpos,amt) : wdl_min(l,amt);
if (sz>0)
{
draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT2);
str += sz;
amt -= sz;
}
}
if (varlen>0)
{
int sz = wdl_min(varlen,amt);
if (sz>0)
{
draw_string_internal(skipcnt,str,sz,attr,*str == '#' ? SYNTAX_STRINGVAR : SYNTAX_HIGHLIGHT1);
amt -= sz;
str += sz;
}
sz = wdl_min(l - varpos - varlen, amt);
if (sz>0)
{
draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT2);
amt-=sz;
str+=sz;
}
}
}
}
draw_string_urlchk(skipcnt,str,amt,attr,newAttr);
}
void EEL_Editor::draw_string_urlchk(int *skipcnt, const char *str, int amt, int *attr, int newAttr)
{
if (amt > 0 && (newAttr == SYNTAX_COMMENT || newAttr == SYNTAX_STRING))
{
const char *sstr=str;
while (amt > 0 && *str)
{
const char *str_scan = str;
int l=0;
while (l < 10 && *str_scan)
{
str_scan += l;
l=0;
while (*str_scan &&
(strncmp(str_scan,"http://",7) || (sstr != str_scan && str_scan[-1] > 0 && isalnum(str_scan[-1]))) &&
str_scan < str+amt) str_scan++;
if (!*str_scan || str_scan >= str+amt) break;
while (str_scan[l] && str_scan[l] != ')' && str_scan[l] != '\"' && str_scan[l] != ')' && str_scan[l] != ' ' && str_scan[l] != '\t') l++;
}
if (!*str_scan || str_scan >= str+amt) break; // allow default processing to happen if we reached the end of the string
if (l > amt) l=amt;
if (str_scan > str)
{
const int sz=wdl_min((int)(str_scan-str),amt);
draw_string_internal(skipcnt,str,sz,attr,newAttr);
str += sz;
amt -= sz;
}
const int sz=wdl_min(l,amt);
if (sz>0)
{
draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT1);
str += sz;
amt -= sz;
}
}
}
draw_string_internal(skipcnt,str,amt,attr,newAttr);
}
void EEL_Editor::draw_string_internal(int *skipcnt, const char *str, int amt, int *attr, int newAttr)
{
// *skipcnt is in characters, amt is in bytes
while (*skipcnt > 0 && amt > 0)
{
const int clen = wdl_utf8_parsechar(str,NULL);
str += clen;
amt -= clen;
*skipcnt -= 1;
}
if (amt>0)
{
if (*attr != newAttr)
{
attrset(newAttr);
*attr = newAttr;
}
addnstr(str,amt);
}
}
WDL_TypedBuf<char> EEL_Editor::s_draw_parentokenstack;
bool EEL_Editor::sh_draw_parenttokenstack_pop(char c)
{
int sz = s_draw_parentokenstack.GetSize();
while (--sz >= 0)
{
char tc = s_draw_parentokenstack.Get()[sz];
if (tc == c)
{
s_draw_parentokenstack.Resize(sz,false);
return false;
}
switch (c)
{
case '?':
// any open paren or semicolon is enough to cause error for ?:
return true;
case '(':
if (tc == '[') return true;
break;
case '[':
if (tc == '(') return true;
break;
}
}
return true;
}
bool EEL_Editor::sh_draw_parentokenstack_update(const char *tok, int toklen)
{
if (toklen == 1)
{
switch (*tok)
{
case '(':
case '[':
case ';':
case '?':
s_draw_parentokenstack.Add(*tok);
break;
case ':': return sh_draw_parenttokenstack_pop('?');
case ')': return sh_draw_parenttokenstack_pop('(');
case ']': return sh_draw_parenttokenstack_pop('[');
}
}
return false;
}
void EEL_Editor::draw_line_highlight(int y, const char *p, int *c_comment_state, int line_n)
{
if (line_n == m_curs_y)
m_suggestion_curline_comment_state = *c_comment_state;
int last_attr = A_NORMAL;
attrset(last_attr);
move(y, 0);
int rv = do_draw_line(p, c_comment_state, last_attr);
attrset(rv< 0 ? SYNTAX_ERROR : A_NORMAL);
clrtoeol();
if (rv < 0) attrset(A_NORMAL);
}
int EEL_Editor::do_draw_line(const char *p, int *c_comment_state, int last_attr)
{
//skipcnt = m_offs_x
if (is_code_start_line(p))
{
*c_comment_state=0;
s_draw_parentokenstack.Resize(0,false);
}
int skipcnt = m_offs_x;
int ignoreSyntaxState = overrideSyntaxDrawingForLine(&skipcnt, &p, c_comment_state, &last_attr);
if (ignoreSyntaxState>0)
{
int len = (int)strlen(p);
draw_string(&skipcnt,p,len,&last_attr,ignoreSyntaxState==100 ? SYNTAX_ERROR :
ignoreSyntaxState==2 ? SYNTAX_COMMENT : A_NORMAL);
return len-m_offs_x < COLS;
}
// syntax highlighting
const char *endptr = p+strlen(p);
const char *tok;
const char *lp = p;
int toklen=0;
int last_comment_state=*c_comment_state;
while (NULL != (tok = sh_tokenize(&p,endptr,&toklen,c_comment_state)) || lp < endptr)
{
if (tok && *tok < 0 && toklen == 1)
{
while (tok[toklen] < 0) {p++; toklen++; } // utf-8 skip
}
if (last_comment_state>0) // if in a multi-line string or comment
{
// draw empty space between lp and p as a string. in this case, tok/toklen includes our string, so we quickly finish after
draw_string(&skipcnt,lp,(int)(p-lp),&last_attr, last_comment_state==1 ? SYNTAX_COMMENT:SYNTAX_STRING, last_comment_state);
last_comment_state=0;
lp = p;
continue;
}
sh_func_ontoken(tok,toklen);
// draw empty space between lp and tok/endptr as normal
const char *adv_to = tok ? tok : endptr;
if (adv_to > lp) draw_string(&skipcnt,lp,(int)(adv_to-lp),&last_attr, A_NORMAL);
if (adv_to >= endptr) break;
last_comment_state=0;
lp = p;
if (adv_to == p) continue;
// draw token
int attr = A_NORMAL;
int err_left=0;
int err_right=0;
int start_of_tok = 0;
if (tok[0] == '/' && toklen > 1 && (tok[1] == '*' || tok[1] == '/'))
{
attr = SYNTAX_COMMENT;
}
else if (tok[0] > 0 && (isalpha(tok[0]) || tok[0] == '_' || tok[0] == '#'))
{
int def_attr = A_NORMAL;
bool isf=true;
if (tok[0] == '#')
{
def_attr = SYNTAX_STRINGVAR;
draw_string(&skipcnt,tok,1,&last_attr,def_attr);
tok++;
toklen--;
}
while (toklen > 0)
{
// divide up by .s, if any
int this_len=0;
while (this_len < toklen && tok[this_len] != '.') this_len++;
if (this_len > 0)
{
int attr=isf?namedTokenHighlight(tok,this_len,*c_comment_state):def_attr;
if (isf && attr == A_NORMAL)
{
int ntok_len=0, cc = *c_comment_state;
const char *pp=lp,*ntok = sh_tokenize(&pp,endptr,&ntok_len,&cc);
if (ntok && ntok_len>0 && *ntok == '(') def_attr = attr = SYNTAX_FUNC2;
}
draw_string(&skipcnt,tok,this_len,&last_attr,attr==A_NORMAL?def_attr:attr);
tok += this_len;
toklen -= this_len;
}
if (toklen > 0)
{
draw_string(&skipcnt,tok,1,&last_attr,SYNTAX_HIGHLIGHT1);
tok++;
toklen--;
}
isf=false;
}
continue;
}
else if (tok[0] == '.' ||
(tok[0] >= '0' && tok[0] <= '9') ||
(toklen > 1 && tok[0] == '$' && (tok[1] == 'x' || tok[1]=='X')))
{
attr = SYNTAX_HIGHLIGHT2;
int x=1,mode=0;
if (tok[0] == '.') mode=1;
else if (toklen > 1 && (tok[0] == '$' || tok[0] == '0') && (tok[1] == 'x' || tok[1] == 'X')) { mode=2; x++; }
for(;x<toklen;x++)
{
if (tok[x] == '.' && !mode) mode=1;
else if (tok[x] < '0' || tok[x] > '9')
{
if (mode != 2 || ((tok[x] < 'a' || tok[x] > 'f') && (tok[x] < 'A' || tok[x] > 'F')))
break;
}
}
if (x<toklen) err_right=toklen-x;
}
else if (tok[0] == '\'' || tok[0] == '\"')
{
start_of_tok = tok[0];
attr = SYNTAX_STRING;
}
else if (tok[0] == '$')
{
attr = SYNTAX_HIGHLIGHT2;
if (toklen >= 3 && !strnicmp(tok,"$pi",3)) err_right = toklen - 3;
else if (toklen >= 2 && !strnicmp(tok,"$e",2)) err_right = toklen - 2;
else if (toklen >= 4 && !strnicmp(tok,"$phi",4)) err_right = toklen - 4;
else if (toklen == 4 && tok[1] == '\'' && tok[3] == '\'') { }
else if (toklen > 1 && tok[1] == '~')
{
int x;
for(x=2;x<toklen;x++) if (tok[x] < '0' || tok[x] > '9') break;
if (x<toklen) err_right=toklen-x;
}
else err_right = toklen;
}
else if (ignoreSyntaxState==-1 && (tok[0] == '{' || tok[0] == '}'))
{
attr = SYNTAX_HIGHLIGHT1;
}
else
{
const char *h="()+*-=/,|&%;!<>?:^!~[]";
while (*h && *h != tok[0]) h++;
if (*h)
{
if (*c_comment_state != STATE_BEFORE_CODE && sh_draw_parentokenstack_update(tok,toklen))
attr = SYNTAX_ERROR;
else
attr = SYNTAX_HIGHLIGHT1;
}
else
{
err_left=1;
if (tok[0] < 0) while (err_left < toklen && tok[err_left]<0) err_left++; // utf-8 skip
}
}
if (ignoreSyntaxState) err_left = err_right = 0;
if (err_left > 0)
{
if (err_left > toklen) err_left=toklen;
draw_string(&skipcnt,tok,err_left,&last_attr,SYNTAX_ERROR);
tok+=err_left;
toklen -= err_left;
}
if (err_right > toklen) err_right=toklen;
draw_string(&skipcnt, tok, toklen - err_right, &last_attr, attr, start_of_tok);
if (err_right > 0)
draw_string(&skipcnt,tok+toklen-err_right,err_right,&last_attr,SYNTAX_ERROR);
if (ignoreSyntaxState == -1 && tok[0] == '>')
{
draw_string(&skipcnt,p,strlen(p),&last_attr,ignoreSyntaxState==2 ? SYNTAX_COMMENT : A_NORMAL);
break;
}
}
return 1;
}
int EEL_Editor::GetCommentStateForLineStart(int line)
{
if (m_write_leading_tabs<=0) m_indent_size=2;
const bool uses_code_start_lines = !!is_code_start_line(NULL);
int state=0;
int x=0;
if (uses_code_start_lines)
{
state=STATE_BEFORE_CODE;
for (;;x++)
{
WDL_FastString *t = m_text.Get(x);
if (!t || is_code_start_line(t->Get())) break;
const char *p=t->Get();
if (!strnicmp(p,"tabsize:",8))
{
int a = atoi(p+8);
if (a>0 && a < 32) m_indent_size = a;
}
}
// scan backwards to find line starting with @
for (x=line;x>=0;x--)
{
WDL_FastString *t = m_text.Get(x);
if (!t) break;
if (is_code_start_line(t->Get()))
{
state=0;
break;
}
}
x++;
}
s_draw_parentokenstack.Resize(0,false);
for (;x<line;x++)
{
WDL_FastString *t = m_text.Get(x);
const char *p = t?t->Get():"";
if (is_code_start_line(p))
{
s_draw_parentokenstack.Resize(0,false);
state=0;
}
else if (state != STATE_BEFORE_CODE)
{
const int ll=t?t->GetLength():0;
const char *endp = p+ll;
int toklen;
const char *tok;
while (NULL != (tok=sh_tokenize(&p,endp,&toklen,&state))) // eat all tokens, updating state
{
sh_func_ontoken(tok,toklen);
sh_draw_parentokenstack_update(tok,toklen);
}
}
}
return state;
}
const char *EEL_Editor::sh_tokenize(const char **ptr, const char *endptr, int *lenOut, int *state)
{
return nseel_simple_tokenizer(ptr, endptr, lenOut, state);
}
bool EEL_Editor::LineCanAffectOtherLines(const char *txt, int spos, int slen) // if multiline comment etc
{
const char *special_start = txt + spos;
const char *special_end = txt + spos + slen;
while (*txt)
{
if (txt >= special_start-1 && txt < special_end)
{
const char c = txt[0];
if (c == '*' && txt[1] == '/') return true;
if (c == '/' && (txt[1] == '/' || txt[1] == '*')) return true;
if (c == '\\' && (txt[1] == '\"' || txt[1] == '\'')) return true;
if (txt >= special_start)
{
if (c == '\"' || c == '\'') return true;
if (c == '(' || c == '[' || c == ')' || c == ']' || c == ':' || c == ';' || c == '?') return true;
}
}
txt++;
}
return false;
}
struct eel_sh_token
{
int line, col, end_col;
unsigned int data; // packed char for token type, plus 24 bits for linecnt (0=single line, 1=extra line, etc)
eel_sh_token(int _line, int _col, int toklen, unsigned char c)
{
line = _line;
col = _col;
end_col = col + toklen;
data = c;
}
~eel_sh_token() { }
void add_linecnt(int endcol) { data += 256; end_col = endcol; }
int get_linecnt() const { return (data >> 8); }
char get_c() const { return (char) (data & 255); }
bool is_comment() const {
return get_c() == '/' && (get_linecnt() || end_col>col+1);
};
};
static int eel_sh_get_token_for_pos(const WDL_TypedBuf<eel_sh_token> *toklist, int line, int col, bool *is_after)
{
const int sz = toklist->GetSize();
int x;
for (x=0; x < sz; x ++)
{
const eel_sh_token *tok = toklist->Get()+x;
const int first_line = tok->line;
const int last_line = first_line+tok->get_linecnt(); // last affected line (usually same as first)
if (last_line >= line) // if this token doesn't end before the line we care about
{
// check to see if the token starts after our position
if (first_line > line || (first_line == line && tok->col > col)) break;
// token started before line/col, see if it ends after line/col
if (last_line > line || tok->end_col > col)
{
// direct hit
*is_after = false;
return x;
}
}
}
*is_after = true;
return x-1;
}
static void eel_sh_generate_token_list(const WDL_PtrList<WDL_FastString> *lines, WDL_TypedBuf<eel_sh_token> *toklist, int start_line, EEL_Editor *editor)
{
toklist->Resize(0,false);
int state=0;
int l;
int end_line = lines->GetSize();
if (editor->is_code_start_line(NULL))
{
for (l = start_line; l < end_line; l ++)
{
WDL_FastString *s = lines->Get(l);
if (s && editor->is_code_start_line(s->Get()))
{
end_line = l;
break;
}
}
for (; start_line >= 0; start_line--)
{
WDL_FastString *s = lines->Get(start_line);
if (s && editor->is_code_start_line(s->Get())) break;
}
if (start_line < 0) return; // before any code
start_line++;
}
else
{
start_line = 0;
}
for (l=start_line;l<end_line;l++)
{
WDL_FastString *t = lines->Get(l);
const int ll = t?t->GetLength():0;
const char *start_p = t?t->Get():"";
const char *p = start_p;
const char *endp = start_p+ll;
const char *tok;
int last_state=state;
int toklen;
while (NULL != (tok=editor->sh_tokenize(&p,endp,&toklen,&state))||last_state)
{
if (last_state == '\'' || last_state == '"' || last_state==1)
{
const int sz=toklist->GetSize();
// update last token to include this data
if (sz) toklist->Get()[sz-1].add_linecnt((int) ((tok ? p:endp) - start_p));
}
else
{
if (tok) switch (tok[0])
{
case '{':
case '}':
case '?':
case ':':
case ';':
case '(':
case '[':
case ')':
case ']':
case '\'':
case '"':
case '/': // comment
{
eel_sh_token t(l,(int)(tok-start_p),toklen,tok[0]);
toklist->Add(t);
}
break;
}
}
last_state=0;
}
}
}
static bool eel_sh_get_matching_pos_for_pos(WDL_PtrList<WDL_FastString> *text, int curx, int cury, int *newx, int *newy, const char **errmsg, EEL_Editor *editor)
{
static WDL_TypedBuf<eel_sh_token> toklist;
eel_sh_generate_token_list(text,&toklist, cury,editor);
bool is_after;
const int hit_tokidx = eel_sh_get_token_for_pos(&toklist, cury, curx, &is_after);
const eel_sh_token *hit_tok = hit_tokidx >= 0 ? toklist.Get() + hit_tokidx : NULL;
if (!is_after && hit_tok && (hit_tok->get_c() == '"' || hit_tok->get_c() == '\'' || hit_tok->is_comment()))
{
eel_sh_token tok = *hit_tok; // save a copy, toklist might get destroyed recursively here
hit_tok = &tok;
//if (tok.get_c() == '"')
{
// the user could be editing code in code, tokenize it and see if we can make sense of it
WDL_FastString start, end;
WDL_PtrList<WDL_FastString> tmplist;
WDL_FastString *s = text->Get(tok.line);
if (s && s->GetLength() > tok.col+1)
{
int maxl = tok.get_linecnt()>0 ? 0 : tok.end_col - tok.col - 2;
start.Set(s->Get() + tok.col+1, maxl);
}
tmplist.Add(&start);
const int linecnt = tok.get_linecnt();
if (linecnt>0)
{
for (int a=1; a < linecnt; a ++)
{
s = text->Get(tok.line + a);
if (s) tmplist.Add(s);
}
s = text->Get(tok.line + linecnt);
if (s)
{
if (tok.end_col>1) end.Set(s->Get(), tok.end_col-1);
tmplist.Add(&end);
}
}
int lx = curx, ly = cury - tok.line;
if (cury == tok.line) lx -= (tok.col+1);
// this will destroy the token
if (eel_sh_get_matching_pos_for_pos(&tmplist, lx, ly, newx, newy, errmsg, editor))
{
*newy += tok.line;
if (cury == tok.line) *newx += tok.col + 1;
return true;
}
}
// if within a string or comment, move to start, unless already at start, move to end
if (cury == hit_tok->line && curx == hit_tok->col)
{
*newx=hit_tok->end_col-1;
*newy=hit_tok->line + hit_tok->get_linecnt();
}
else
{
*newx=hit_tok->col;
*newy=hit_tok->line;
}
return true;
}
if (!hit_tok) return false;
const int toksz=toklist.GetSize();
int tokpos = hit_tokidx;
int pc1=0,pc2=0; // (, [ count
int pc3=0; // : or ? count depending on mode
int dir=-1, mode=0; // default to scan to previous [(
if (!is_after)
{
switch (hit_tok->get_c())
{
case '(': mode=1; dir=1; break;
case '[': mode=2; dir=1; break;
case ')': mode=3; dir=-1; break;
case ']': mode=4; dir=-1; break;
case '?': mode=5; dir=1; break;
case ':': mode=6; break;
case ';': mode=7; break;
}
// if hit a token, exclude this token from scanning
tokpos += dir;
}
while (tokpos>=0 && tokpos<toksz)
{
const eel_sh_token *tok = toklist.Get() + tokpos;
const char this_c = tok->get_c();
if (!pc1 && !pc2)
{
bool match=false, want_abort=false;
switch (mode)
{
case 0: match = this_c == '(' || this_c == '['; break;
case 1: match = this_c == ')'; break;
case 2: match = this_c == ']'; break;
case 3: match = this_c == '('; break;
case 4: match = this_c == '['; break;
case 5:
// scan forward to nearest : or ;
if (this_c == '?') pc3++;
else if (this_c == ':')
{
if (pc3>0) pc3--;
else match=true;
}
else if (this_c == ';') match=true;
else if (this_c == ')' || this_c == ']')
{
want_abort=true; // if you have "(x<y?z)", don't match for the ?
}
break;
case 6: // scanning back from : to ?, if any
case 7: // semicolon searches same as colon, effectively
if (this_c == ':') pc3++;
else if (this_c == '?')
{
if (pc3>0) pc3--;
else match = true;
}
else if (this_c == ';' || this_c == '(' || this_c == '[')
{
want_abort=true;
}
break;
}
if (want_abort) break;
if (match)
{
*newx=tok->col;
*newy=tok->line;
return true;
}
}
switch (this_c)
{
case '[': pc2++; break;
case ']': pc2--; break;
case '(': pc1++; break;
case ')': pc1--; break;
}
tokpos+=dir;
}
if (errmsg)
{
if (!mode) *errmsg = "Could not find previous [ or (";
else if (mode == 1) *errmsg = "Could not find matching )";
else if (mode == 2) *errmsg = "Could not find matching ]";
else if (mode == 3) *errmsg = "Could not find matching (";
else if (mode == 4) *errmsg = "Could not find matching [";
else if (mode == 5) *errmsg = "Could not find matching : or ; for ?";
else if (mode == 6) *errmsg = "Could not find matching ? for :";
else if (mode == 7) *errmsg = "Could not find matching ? for ;";
}
return false;
}
void EEL_Editor::doParenMatching()
{
WDL_FastString *curstr;
const char *errmsg = "";
if (NULL != (curstr=m_text.Get(m_curs_y)))
{
int bytex = WDL_utf8_charpos_to_bytepos(curstr->Get(),m_curs_x);
if (bytex >= curstr->GetLength()) bytex=curstr->GetLength()-1;
if (bytex<0) bytex = 0;
int new_x,new_y;
if (eel_sh_get_matching_pos_for_pos(&m_text, bytex,m_curs_y,&new_x,&new_y,&errmsg,this))
{
curstr = m_text.Get(new_y);
if (curstr) new_x = WDL_utf8_bytepos_to_charpos(curstr->Get(),new_x);
m_curs_x=new_x;
m_curs_y=new_y;
m_want_x=-1;
draw();
setCursor(1);
}
else if (errmsg[0])
{
draw_message(errmsg);
setCursor(0);
}
}
}
static int word_len(const char *p)
{
int l = 0;
if (*p >= 'a' && *p <='z')
{
l++;
// lowercase word
while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'A' && p[l] <='Z')) l++;
}
else if (*p >= 'A' && *p <= 'Z')
{
if (!strcmp(p,"MIDI")) return 4;
l++;
if (p[l] >= 'A' && p[l] <='Z') // UPPERCASE word
while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'a' && p[l] <='z')) l++;
else // Titlecase word
while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'A' && p[l] <='Z')) l++;
}
return l;
}
static int search_str_partial(const char *str, int reflen, const char *word, int wordlen)
{
// find the longest leading segment of word in str
int best_len = 0;
for (int y = 0; y < reflen; y ++)
{
while (y < reflen && !strnicmp(str+y,word,best_len+1))
{
if (++best_len >= wordlen) return best_len;
reflen--;
}
}
return best_len;
}
static int fuzzy_match2(const char *codestr, int codelen, const char *refstr, int reflen)
{
// codestr is user-typed, refstr is the reference function name
// our APIs are gfx_blah_blah or TrackBlahBlah so breaking the API up by words
// and searching the user-entered code should be effective
int lendiff = reflen - codelen;
if (lendiff < 0) lendiff = -lendiff;
const char *word = refstr;
int score = 0;
for (;;)
{
while (*word == '_' || *word == '.') word++;
const int wordlen = word_len(word);
if (!wordlen) break;
char word_buf[128];
lstrcpyn_safe(word_buf,word,wordlen+1);
if (WDL_stristr(refstr,word_buf)==word)
{
int max_match_len = search_str_partial(codestr,codelen,word,wordlen);
if (max_match_len < 2 && wordlen == 5 && !strnicmp(word,"Count",5))
{
max_match_len = search_str_partial(codestr,codelen,"Num",3);
}
if (max_match_len > (wordlen <= 2 ? 1 : 2))
score += max_match_len;
}
word += wordlen;
}
if (!score) return 0;
return score * 1000 + 1000 - wdl_clamp(lendiff*2,0,200);
}
int EEL_Editor::fuzzy_match(const char *codestr, const char *refstr)
{
const int codestr_len = (int)strlen(codestr), refstr_len = (int)strlen(refstr);
if (refstr_len >= codestr_len && !strnicmp(codestr,refstr,codestr_len)) return 1000000000;
int score1 = fuzzy_match2(refstr,refstr_len,codestr,codestr_len);
int score2 = fuzzy_match2(codestr,codestr_len,refstr,refstr_len);
if (score2 > score1) return score2 | 1;
return score1&~1;
}
static int eeledit_varenumfunc(const char *name, EEL_F *val, void *ctx)
{
void **parms = (void **)ctx;
int score = ((EEL_Editor*)parms[2])->fuzzy_match((const char *)parms[1], name);
if (score > 0) ((suggested_matchlist*)parms[0])->add(name,score,suggested_matchlist::MODE_VAR);
return 1;
}
void EEL_Editor::get_suggested_token_names(const char *fname, int chkmask, suggested_matchlist *list)
{
int x;
if (chkmask & (KEYWORD_MASK_BUILTIN_FUNC|KEYWORD_MASK_USER_VAR))
{
peek_lock();
NSEEL_VMCTX vm = peek_get_VM();
compileContext *fvm = vm && peek_want_VM_funcs() ? (compileContext*)vm : NULL;
if (chkmask&KEYWORD_MASK_BUILTIN_FUNC) for (x=0;;x++)
{
functionType *p = nseel_enumFunctions(fvm,x);
if (!p) break;
int score = fuzzy_match(fname,p->name);
if (score>0) list->add(p->name,score);
}
if (vm && (chkmask&KEYWORD_MASK_USER_VAR))
{
const void *parms[3] = { list, fname, this };
NSEEL_VM_enumallvars(vm, eeledit_varenumfunc, parms);
}
peek_unlock();
}
if (chkmask & KEYWORD_MASK_USER_FUNC)
{
ensure_code_func_cache_valid();
for (int x=0;x< m_code_func_cache.GetSize();x++)
{
const char *k = m_code_func_cache.Get(x) + 4;
if (WDL_NORMALLY(k))
{
int score = fuzzy_match(fname,k);
if (score > 0) list->add(k,score,suggested_matchlist::MODE_USERFUNC);
}
}
}
}
int EEL_Editor::peek_get_token_info(const char *name, char *sstr, size_t sstr_sz, int chkmask, int ignoreline)
{
if (chkmask&KEYWORD_MASK_USER_FUNC)
{
ensure_code_func_cache_valid();
for (int i = 0; i < m_code_func_cache.GetSize(); i ++)
{
const char *cacheptr = m_code_func_cache.Get(i);
const char *nameptr = cacheptr + sizeof(int);
if (!(m_case_sensitive ? strcmp(nameptr, name):stricmp(nameptr,name)) &&
*(int *)cacheptr != ignoreline)
{
const char *parms = nameptr+strlen(nameptr)+1;
const char *trail = parms+strlen(parms)+1;
snprintf(sstr,sstr_sz,"%s%s%s%s",nameptr,parms,*trail?" " :"",trail);
return 4;
}
}
}
if (chkmask & (KEYWORD_MASK_BUILTIN_FUNC|KEYWORD_MASK_USER_VAR))
{
int rv = 0;
peek_lock();
NSEEL_VMCTX vm = peek_want_VM_funcs() ? peek_get_VM() : NULL;
functionType *f = (chkmask&KEYWORD_MASK_BUILTIN_FUNC) ? nseel_getFunctionByName((compileContext*)vm,name,NULL) : NULL;
double v;
if (f)
{
snprintf(sstr,sstr_sz,"'%s' is a function that requires %d parameters", f->name,f->nParams&0xff);
rv = KEYWORD_MASK_BUILTIN_FUNC;
}
else if (chkmask & KEYWORD_MASK_USER_VAR)
{
if (!vm) vm = peek_get_VM();
EEL_F *vptr=NSEEL_VM_getvar(vm,name);
if (vptr)
{
v = *vptr;
rv = KEYWORD_MASK_USER_VAR;
}
}
peek_unlock();
if (rv == KEYWORD_MASK_USER_VAR)
{
int good_len=-1;
snprintf(sstr,sstr_sz,"%s=%.14f",name,v);
if (v > -1.0 && v < NSEEL_RAM_ITEMSPERBLOCK*NSEEL_RAM_BLOCKS)
{
const unsigned int w = (unsigned int) (v+NSEEL_CLOSEFACTOR);
EEL_F *dv = NSEEL_VM_getramptr_noalloc(vm,w,NULL);
if (dv)
{
snprintf_append(sstr,sstr_sz," [0x%06x]=%.14f",w,*dv);
good_len=-2;
}
else
{
good_len = strlen(sstr);
snprintf_append(sstr,sstr_sz," [0x%06x]=<uninit>",w);
}
}
char buf[512];
buf[0]=0;
if (peek_get_numbered_string_value(v,buf,sizeof(buf)))
{
if (good_len==-2)
snprintf_append(sstr,sstr_sz," %.0f(str)=%s",v,buf);
else
{
if (good_len>=0) sstr[good_len]=0; // remove [addr]=<uninit> if a string and no ram
snprintf_append(sstr,sstr_sz," (str)=%s",buf);
}
}
}
if (rv) return rv;
}
return 0;
}
void EEL_Editor::doWatchInfo(int c)
{
// determine the word we are on, check its value in the effect
char sstr[512], buf[512];
lstrcpyn_safe(sstr,"Use this on a valid symbol name", sizeof(sstr));
WDL_FastString *t=m_text.Get(m_curs_y);
char curChar=0;
if (t)
{
const char *p=t->Get();
const int bytex = WDL_utf8_charpos_to_bytepos(p,m_curs_x);
if (bytex >= 0 && bytex < t->GetLength()) curChar = p[bytex];
if (c != KEY_F1 && (m_selecting ||
curChar == '(' ||
curChar == '[' ||
curChar == ')' ||
curChar == ']'
))
{
WDL_FastString code;
int miny,maxy,minx,maxx;
bool ok = false;
if (!m_selecting)
{
if (eel_sh_get_matching_pos_for_pos(&m_text,minx=m_curs_x,miny=m_curs_y,&maxx, &maxy,NULL,this))
{
if (maxy==miny)
{
if (maxx < minx)
{
int tmp = minx;
minx=maxx;
maxx=tmp;
}
}
else if (maxy < miny)
{
int tmp=maxy;
maxy=miny;
miny=tmp;
tmp = minx;
minx=maxx;
maxx=tmp;
}
ok = true;
minx++; // skip leading (
}
}
else
{
ok=true;
getselectregion(minx,miny,maxx,maxy);
WDL_FastString *s;
s = m_text.Get(miny);
if (s) minx = WDL_utf8_charpos_to_bytepos(s->Get(),minx);
s = m_text.Get(maxy);
if (s) maxx = WDL_utf8_charpos_to_bytepos(s->Get(),maxx);
}
if (ok)
{
int x;
for (x = miny; x <= maxy; x ++)
{
WDL_FastString *s=m_text.Get(x);
if (s)
{
const char *str=s->Get();
int sx,ex;
if (x == miny) sx=wdl_max(minx,0);
else sx=0;
int tmp=s->GetLength();
if (sx > tmp) sx=tmp;
if (x == maxy) ex=wdl_min(maxx,tmp);
else ex=tmp;
if (code.GetLength()) code.Append("\r\n");
code.Append(ex-sx?str+sx:"",ex-sx);
}
}
}
if (code.Get()[0])
{
if (m_selecting && (GetAsyncKeyState(VK_SHIFT)&0x8000))
{
peek_lock();
NSEEL_CODEHANDLE ch;
NSEEL_VMCTX vm = peek_get_VM();
if (vm && (ch = NSEEL_code_compile_ex(vm,code.Get(),1,0)))
{
codeHandleType *p = (codeHandleType*)ch;
code.Ellipsize(3,20);
const char *errstr = "failed writing to";
if (p->code)
{
buf[0]=0;
GetTempPath(sizeof(buf)-64,buf);
lstrcatn(buf,"jsfx-out",sizeof(buf));
FILE *fp = fopen(buf,"wb");
if (fp)
{
errstr="wrote to";
fwrite(p->code,1,p->code_size,fp);
fclose(fp);
}
}
snprintf(sstr,sizeof(sstr),"Expression '%s' compiled to %d bytes, %s temp/jsfx-out",code.Get(),p->code_size, errstr);
NSEEL_code_free(ch);
}
else
{
code.Ellipsize(3,20);
snprintf(sstr,sizeof(sstr),"Expression '%s' could not compile",code.Get());
}
peek_unlock();
}
else
{
WDL_FastString code2;
code2.Set("__debug_watch_value = (((((");
code2.Append(code.Get());
code2.Append(")))));");
peek_lock();
NSEEL_VMCTX vm = peek_get_VM();
EEL_F *vptr=NULL;
double v=0.0;
const char *err="Invalid context";
if (vm)
{
NSEEL_CODEHANDLE ch = NSEEL_code_compile_ex(vm,code2.Get(),1,0);
if (!ch) err = "Error parsing";
else
{
NSEEL_code_execute(ch);
NSEEL_code_free(ch);
vptr = NSEEL_VM_getvar(vm,"__debug_watch_value");
if (vptr) v = *vptr;
}
}
peek_unlock();
{
// remove whitespace from code for display
int x;
bool lb=true;
for (x=0;x<code.GetLength();x++)
{
if (isspace(code.Get()[x]))
{
if (lb) code.DeleteSub(x--,1);
lb=true;
}
else
{
lb=false;
}
}
if (lb && code.GetLength()>0) code.SetLen(code.GetLength()-1);
}
code.Ellipsize(3,20);
if (vptr)
{
snprintf(sstr,sizeof(sstr),"Expression '%s' evaluates to %.14f",code.Get(),v);
}
else
{
snprintf(sstr,sizeof(sstr),"Error evaluating '%s': %s",code.Get(),err?err:"Unknown error");
}
}
}
// compile+execute code within () as debug_watch_value = ( code )
// show value (or err msg)
}
else if (curChar>0 && (isalnum(curChar) || curChar == '_' || curChar == '.' || curChar == '#'))
{
const int bytex = WDL_utf8_charpos_to_bytepos(p,m_curs_x);
const char *lp=p+bytex;
const char *rp=lp + WDL_utf8_charpos_to_bytepos(lp,1);
while (lp >= p && *lp > 0 && (isalnum(*lp) || *lp == '_' || (*lp == '.' && (lp==p || lp[-1]!='.')))) lp--;
if (lp < p || *lp != '#') lp++;
while (*rp && *rp > 0 && (isalnum(*rp) || *rp == '_' || (*rp == '.' && rp[1] != '.'))) rp++;
if (*lp == '#' && rp > lp+1)
{
WDL_FastString n;
lp++;
n.Set(lp,(int)(rp-lp));
int idx;
if ((idx=peek_get_named_string_value(n.Get(),buf,sizeof(buf)))>=0) snprintf(sstr,sizeof(sstr),"#%s(%d)=%s",n.Get(),idx,buf);
else snprintf(sstr,sizeof(sstr),"#%s not found",n.Get());
}
else if (*lp > 0 && (isalpha(*lp) || *lp == '_') && rp > lp)
{
WDL_FastString n;
n.Set(lp,(int)(rp-lp));
if (c==KEY_F1)
{
if (m_suggestion.GetLength())
goto help_from_sug;
on_help(n.Get(),0);
return;
}
int f = peek_get_token_info(n.Get(),sstr,sizeof(sstr),~0,-1);
if (!f) snprintf(sstr,sizeof(sstr),"'%s' NOT FOUND",n.Get());
}
}
}
if (c==KEY_F1)
{
help_from_sug:
WDL_FastString t;
if (m_suggestion.GetLength())
{
const char *p = m_suggestion.Get();
int l;
for (l = 0; isalnum(p[l]) || p[l] == '_' || p[l] == '.'; l ++);
if (l>0) t.Set(m_suggestion.Get(),l);
}
on_help(t.GetLength() > 2 ? t.Get() : NULL,(int)curChar);
return;
}
setCursor();
draw_message(sstr);
}
void EEL_Editor::draw_bottom_line()
{
#define BOLD(x) { attrset(COLOR_BOTTOMLINE|A_BOLD); addstr(x); attrset(COLOR_BOTTOMLINE&~A_BOLD); }
addstr("ma"); BOLD("T"); addstr("ch");
BOLD(" S"); addstr("ave");
if (peek_get_VM())
{
addstr(" pee"); BOLD("K");
}
if (GetTabCount()>1)
{
addstr(" | tab: ");
BOLD("[], F?"); addstr("=switch ");
BOLD("W"); addstr("=close");
}
#undef BOLD
}
#define CTRL_KEY_DOWN (GetAsyncKeyState(VK_CONTROL)&0x8000)
#define SHIFT_KEY_DOWN (GetAsyncKeyState(VK_SHIFT)&0x8000)
#define ALT_KEY_DOWN (GetAsyncKeyState(VK_MENU)&0x8000)
static const char *suggestion_help_text = "(up/down to select, tab to insert)";
static const char *suggestion_help_text2 = "(tab or return to insert)";
static LRESULT WINAPI suggestionProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
EEL_Editor *editor;
switch (uMsg)
{
case WM_DESTROY:
editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA);
if (editor) editor->m_suggestion_hwnd = NULL;
break;
case WM_LBUTTONDOWN:
case WM_MOUSEMOVE:
editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA);
if (editor)
{
win32CursesCtx *ctx = (win32CursesCtx *)editor->m_cursesCtx;
if (ctx && ctx->m_font_h)
{
RECT r;
GetClientRect(hwnd,&r);
SetForegroundWindow(GetParent(hwnd));
SetFocus(GetParent(hwnd));
const int max_vis = r.bottom / ctx->m_font_h - 1, sel = editor->m_suggestion_hwnd_sel;
int hit = GET_Y_LPARAM(lParam) / ctx->m_font_h;
if (hit >= max_vis) return 0;
if (sel >= max_vis) hit += 1 + sel - max_vis;
if (uMsg == WM_LBUTTONDOWN && !SHIFT_KEY_DOWN && !ALT_KEY_DOWN && !CTRL_KEY_DOWN)
{
editor->m_suggestion_hwnd_sel = hit;
editor->onChar('\t');
}
else if (sel != hit)
{
editor->m_suggestion_hwnd_sel = hit;
InvalidateRect(hwnd,NULL,FALSE);
char sug[512];
sug[0]=0;
const char *p = editor->m_suggestion_list.get(hit);
if (p && editor->peek_get_token_info(p,sug,sizeof(sug),~0,-1))
{
editor->m_suggestion.Set(sug);
editor->draw_top_line();
editor->setCursor();
}
}
}
}
return 0;
case WM_PAINT:
editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA);
if (editor)
{
PAINTSTRUCT ps;
if (BeginPaint(hwnd,&ps))
{
RECT r;
GetClientRect(hwnd,&r);
win32CursesCtx *ctx = (win32CursesCtx *)editor->m_cursesCtx;
HBRUSH br = CreateSolidBrush(ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][1]);
FillRect(ps.hdc,&r,br);
DeleteObject(br);
suggested_matchlist *ml = &editor->m_suggestion_list;
HGDIOBJ oldObj = SelectObject(ps.hdc,ctx->mOurFont);
SetBkMode(ps.hdc,TRANSPARENT);
const int fonth = wdl_max(ctx->m_font_h,1);
const int maxv = r.bottom / fonth - 1;
const int selpos = wdl_max(editor->m_suggestion_hwnd_sel,0);
int ypos = 0;
const bool show_scores = (GetAsyncKeyState(VK_SHIFT)&0x8000) && (GetAsyncKeyState(VK_CONTROL)&0x8000) && (GetAsyncKeyState(VK_MENU)&0x8000);
for (int x = (selpos >= maxv ? 1+selpos-maxv : 0); x < ml->get_size() && ypos <= r.bottom-fonth*2; x ++)
{
int mode, score;
const char *p = ml->get(x,&mode,&score);
if (WDL_NORMALLY(p))
{
const bool sel = x == selpos;
SetTextColor(ps.hdc,ctx->colortab[
(mode == suggested_matchlist::MODE_VAR ? WDL_CursesEditor::COLOR_TOPLINE :
mode == suggested_matchlist::MODE_USERFUNC ? WDL_CursesEditor::SYNTAX_FUNC2 :
mode == suggested_matchlist::MODE_REGVAR ? WDL_CursesEditor::SYNTAX_REGVAR :
WDL_CursesEditor::SYNTAX_KEYWORD)
| (sel ? A_BOLD:0)][0]);
RECT tr = {4, ypos, r.right-4, ypos+fonth };
DrawTextUTF8(ps.hdc,p,-1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_LEFT);
if (show_scores)
{
char tmp[128];
snprintf(tmp,sizeof(tmp),"(%d)",score);
DrawTextUTF8(ps.hdc,tmp,-1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_RIGHT);
}
}
ypos += fonth;
}
{
const COLORREF mix = ((ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][1]&0xfefefe)>>1) +
((ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][0]&0xfefefe)>>1);
SetTextColor(ps.hdc,mix);
RECT tr = {4, r.bottom-fonth, r.right-4, r.bottom };
DrawTextUTF8(ps.hdc,
editor->m_suggestion_hwnd_sel >= 0 ? suggestion_help_text2 : suggestion_help_text,
-1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_CENTER);
}
SelectObject(ps.hdc,oldObj);
EndPaint(hwnd,&ps);
}
}
return 0;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
void EEL_Editor::open_import_line()
{
WDL_FastString *txtstr=m_text.Get(m_curs_y);
const char *txt=txtstr?txtstr->Get():NULL;
char fnp[2048];
if (txt && line_has_openable_file(txt,WDL_utf8_charpos_to_bytepos(txt,m_curs_x),fnp,sizeof(fnp)))
{
WDL_CursesEditor::OpenFileInTab(fnp);
}
}
int EEL_Editor::onChar(int c)
{
if ((m_ui_state == UI_STATE_NORMAL || m_ui_state == UI_STATE_MESSAGE) &&
(c == 'K'-'A'+1 || c == 'S'-'A'+1 || c == 'R'-'A'+1 || !SHIFT_KEY_DOWN) && !ALT_KEY_DOWN) switch (c)
{
case KEY_F1:
if (CTRL_KEY_DOWN) break;
case 'K'-'A'+1:
doWatchInfo(c);
return 0;
case 'S'-'A'+1:
{
WDL_DestroyCheck chk(&destroy_check);
if(updateFile())
{
if (chk.isOK())
draw_message("Error writing file, changes not saved!");
}
if (chk.isOK())
setCursor();
}
return 0;
// case 'I': note stupidly we map Ctrl+I to VK_TAB, bleh
case 'R'-'A'+1:
if (!SHIFT_KEY_DOWN) break;
if (!m_selecting)
{
open_import_line();
}
return 0;
case KEY_F4:
case 'T'-'A'+1:
doParenMatching();
return 0;
}
int rv = 0;
int do_sug = (g_eel_editor_max_vis_suggestions > 0 &&
m_ui_state == UI_STATE_NORMAL &&
!m_selecting && m_top_margin > 0 &&
(c == 'L'-'A'+1 || (!CTRL_KEY_DOWN && !ALT_KEY_DOWN))) ? 1 : 0;
bool did_fuzzy = false;
char sug[1024];
sug[0]=0;
if (do_sug)
{
if (m_suggestion_hwnd)
{
// insert if tab or shift+enter or (enter if arrow-navigated)
if ((c == '\t' && !SHIFT_KEY_DOWN) ||
(c == '\r' && (m_suggestion_hwnd_sel>=0 || SHIFT_KEY_DOWN)))
{
char buf[512];
int sug_mode;
const char *ptr = m_suggestion_list.get(wdl_max(m_suggestion_hwnd_sel,0), &sug_mode);
lstrcpyn_safe(buf,ptr?ptr:"",sizeof(buf));
DestroyWindow(m_suggestion_hwnd);
WDL_FastString *l=m_text.Get(m_curs_y);
if (buf[0] && l &&
WDL_NORMALLY(m_suggestion_tokpos>=0 && m_suggestion_tokpos < l->GetLength()) &&
WDL_NORMALLY(m_suggestion_toklen>0) &&
WDL_NORMALLY(m_suggestion_tokpos+m_suggestion_toklen <= l->GetLength()))
{
preSaveUndoState();
l->DeleteSub(m_suggestion_tokpos,m_suggestion_toklen);
l->Insert(buf,m_suggestion_tokpos);
int pos = m_suggestion_tokpos + strlen(buf);
if (sug_mode == suggested_matchlist::MODE_FUNC || sug_mode == suggested_matchlist::MODE_USERFUNC)
{
if (pos >= l->GetLength() || l->Get()[pos] != '(')
l->Insert("(",pos++);
}
m_curs_x = WDL_utf8_bytepos_to_charpos(l->Get(),pos);
draw();
saveUndoState();
setCursor();
goto run_suggest;
}
return 0;
}
if ((c == KEY_UP || c==KEY_DOWN || c == KEY_NPAGE || c == KEY_PPAGE) && !SHIFT_KEY_DOWN)
{
m_suggestion_hwnd_sel = wdl_max(m_suggestion_hwnd_sel,0) +
(c==KEY_UP ? -1 : c==KEY_DOWN ? 1 : c==KEY_NPAGE ? 4 : -4);
if (m_suggestion_hwnd_sel >= m_suggestion_list.get_size())
m_suggestion_hwnd_sel = m_suggestion_list.get_size()-1;
if (m_suggestion_hwnd_sel < 0)
m_suggestion_hwnd_sel=0;
InvalidateRect(m_suggestion_hwnd,NULL,FALSE);
const char *p = m_suggestion_list.get(m_suggestion_hwnd_sel);
if (p) peek_get_token_info(p,sug,sizeof(sug),~0,m_curs_y);
goto finish_sug;
}
}
if (c==27 ||
c=='L'-'A'+1 ||
c=='\r' ||
c=='\t' ||
(c>=KEY_DOWN && c<= KEY_F12 && c!=KEY_DC)) do_sug = 2; // no fuzzy window
else if (c=='\b' && !m_suggestion_hwnd) do_sug=2; // backspace will update but won't show suggestions
}
rv = WDL_CursesEditor::onChar(c);
run_suggest:
if (do_sug)
{
WDL_FastString *l=m_text.Get(m_curs_y);
if (l)
{
const int MAX_TOK=512;
struct {
const char *tok;
int toklen;
} token_list[MAX_TOK];
const char *cursor = l->Get() + WDL_utf8_charpos_to_bytepos(l->Get(),m_curs_x);
int ntok = 0;
{
const char *p = l->Get(), *endp = p + l->GetLength();
int state = m_suggestion_curline_comment_state, toklen = 0, bcnt = 0, pcnt = 0;
const char *tok;
// if no parens/brackets are open, use a peekable token that starts at cursor
while ((tok=sh_tokenize(&p,endp,&toklen,&state)) && cursor > tok-(!pcnt && !bcnt && (tok[0] < 0 || tok[0] == '_' || isalpha(tok[0]))))
{
if (!state)
{
if (WDL_NOT_NORMALLY(ntok >= MAX_TOK))
{
memmove(token_list,token_list+1,sizeof(token_list) - sizeof(token_list[0]));
ntok--;
}
switch (*tok)
{
case '[': bcnt++; break;
case ']': bcnt--; break;
case '(': pcnt++; break;
case ')': pcnt--; break;
}
token_list[ntok].tok = tok;
token_list[ntok].toklen = toklen;
ntok++;
}
}
}
int t = ntok;
int comma_cnt = 0;
while (--t >= 0)
{
const char *tok = token_list[t].tok;
int toklen = token_list[t].toklen;
const int lc = tok[0], ac = lc==')' ? '(' : lc==']' ? '[' : 0;
if (ac)
{
int cnt=1;
while (--t>=0)
{
const int c = token_list[t].tok[0];
if (c == lc) cnt++;
else if (c == ac && !--cnt) break;
}
if (t > 0)
{
const int c = token_list[t-1].tok[0];
if (c != ',' && c != ')' && c != ']') t--;
continue;
}
}
if (t<0) break;
if (tok[0] == ',') comma_cnt++;
else if ((tok[0] < 0 || tok[0] == '_' || isalpha(tok[0])) && (cursor <= tok + toklen || (t < ntok-1 && token_list[t+1].tok[0] == '(')))
{
// if cursor is within or at end of token, or is a function (followed by open-paren)
char buf[512];
lstrcpyn_safe(buf,tok,wdl_min(toklen+1, sizeof(buf)));
if (peek_get_token_info(buf,sug,sizeof(sug),~0,m_curs_y))
{
if (comma_cnt > 0)
{
// hide previous parameters from sug's parameter fields so we know which parameters
// we are (hopefully on)
char *pstart = sug;
while (*pstart && *pstart != '(') pstart++;
if (*pstart == '(') pstart++;
int comma_pos = 0;
char *p = pstart;
while (comma_pos < comma_cnt)
{
while (*p == ' ') p++;
while (*p && *p != ',' && *p != ')') p++;
if (*p == ')') break;
if (*p) p++;
comma_pos++;
}
if (*p && *p != ')')
{
*pstart=0;
lstrcpyn_safe(buf,p,sizeof(buf));
snprintf_append(sug,sizeof(sug), "... %s",buf);
}
}
break;
}
// only use token up to cursor for suggestions
if (cursor >= tok && cursor <= tok+toklen)
{
toklen = (int) (cursor-tok);
lstrcpyn_safe(buf,tok,wdl_min(toklen+1, sizeof(buf)));
}
if (c == '\b' && cursor == tok)
{
}
else if (do_sug != 2 && t == ntok-1 && toklen >= 3 && cursor <= tok + toklen)
{
m_suggestion_list.clear();
get_suggested_token_names(buf,~0,&m_suggestion_list);
win32CursesCtx *ctx = (win32CursesCtx *)m_cursesCtx;
if (m_suggestion_list.get_size()>0 &&
WDL_NORMALLY(ctx->m_hwnd) && WDL_NORMALLY(ctx->m_font_w) && WDL_NORMALLY(ctx->m_font_h))
{
m_suggestion_toklen = toklen;
m_suggestion_tokpos = (int)(tok-l->Get());
m_suggestion_hwnd_sel = -1;
if (!m_suggestion_hwnd)
{
#ifdef _WIN32
static HINSTANCE last_inst;
const char *classname = "eel_edit_predicto";
HINSTANCE inst = (HINSTANCE)GetWindowLongPtr(ctx->m_hwnd,GWLP_HINSTANCE);
if (inst != last_inst)
{
last_inst = inst;
WNDCLASS wc={CS_DBLCLKS,suggestionProc,};
wc.lpszClassName=classname;
wc.hInstance=inst;
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
RegisterClass(&wc);
}
m_suggestion_hwnd = CreateWindowEx(0,classname,"", WS_CHILD, 0,0,0,0, ctx->m_hwnd, NULL, inst, NULL);
#else
m_suggestion_hwnd = CreateDialogParam(NULL,NULL,ctx->m_hwnd, suggestionProc, 0);
#endif
if (m_suggestion_hwnd) SetWindowLongPtr(m_suggestion_hwnd,GWLP_USERDATA,(LPARAM)this);
}
if (m_suggestion_hwnd)
{
const int fontw = ctx->m_font_w, fonth = ctx->m_font_h;
int xpos = (WDL_utf8_bytepos_to_charpos(l->Get(),m_suggestion_tokpos) - m_offs_x) * fontw;
RECT par_cr;
GetClientRect(ctx->m_hwnd,&par_cr);
int use_w = (int)strlen(suggestion_help_text);
int use_h = (wdl_min(g_eel_editor_max_vis_suggestions,m_suggestion_list.get_size()) + 1)*fonth;
for (int x = 0; x < m_suggestion_list.get_size(); x ++)
{
const char *p = m_suggestion_list.get(x);
if (WDL_NORMALLY(p!=NULL))
{
const int l = (int) strlen(p);
if (l > use_w) use_w=l;
}
}
use_w = 8 + use_w * fontw;
if (use_w > par_cr.right - xpos)
{
xpos = wdl_max(par_cr.right - use_w,0);
use_w = par_cr.right - xpos;
}
const int cursor_line_y = ctx->m_cursor_y * fonth;
int ypos = cursor_line_y + fonth;
if (ypos + use_h > par_cr.bottom)
{
if (cursor_line_y-fonth > par_cr.bottom - ypos)
{
// more room at the top, but enough?
ypos = cursor_line_y - use_h;
if (ypos<fonth)
{
ypos = fonth;
use_h = cursor_line_y-fonth;
}
}
else
use_h = par_cr.bottom - ypos;
}
SetWindowPos(m_suggestion_hwnd,NULL,xpos,ypos,use_w,use_h, SWP_NOZORDER|SWP_NOACTIVATE);
InvalidateRect(m_suggestion_hwnd,NULL,FALSE);
ShowWindow(m_suggestion_hwnd,SW_SHOWNA);
}
did_fuzzy = true;
const char *p = m_suggestion_list.get(wdl_max(m_suggestion_hwnd_sel,0));
if (p && peek_get_token_info(p,sug,sizeof(sug),~0,m_curs_y)) break;
}
}
}
}
}
}
if (!did_fuzzy && m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd);
finish_sug:
if (strcmp(sug,m_suggestion.Get()) && m_ui_state == UI_STATE_NORMAL)
{
m_suggestion.Set(sug);
if (sug[0])
{
m_suggestion_x=m_curs_x;
m_suggestion_y=m_curs_y;
draw_top_line();
setCursor();
}
}
if (!sug[0] && m_suggestion_y>=0 && m_ui_state == UI_STATE_NORMAL)
{
m_suggestion_x=m_suggestion_y=-1;
m_suggestion.Set("");
if (m_top_margin>0) draw_top_line();
else draw();
setCursor();
}
return rv;
}
void EEL_Editor::draw_top_line()
{
if (m_curs_x >= m_suggestion_x && m_curs_y == m_suggestion_y && m_suggestion.GetLength() && m_ui_state == UI_STATE_NORMAL)
{
const char *p=m_suggestion.Get();
char str[512];
if (WDL_utf8_get_charlen(m_suggestion.Get()) > COLS)
{
int l = WDL_utf8_charpos_to_bytepos(m_suggestion.Get(),COLS-4);
if (l > sizeof(str)-6) l = sizeof(str)-6;
lstrcpyn(str, m_suggestion.Get(), l+1);
strcat(str, "...");
p=str;
}
attrset(COLOR_TOPLINE|A_BOLD);
bkgdset(COLOR_TOPLINE);
move(0, 0);
addstr(p);
clrtoeol();
attrset(0);
bkgdset(0);
}
else
{
m_suggestion_x=m_suggestion_y=-1;
if (m_suggestion.GetLength()) m_suggestion.Set("");
WDL_CursesEditor::draw_top_line();
}
}
void EEL_Editor::onRightClick(HWND hwnd)
{
WDL_LogicalSortStringKeyedArray<int> flist(m_case_sensitive);
int i;
if (!(GetAsyncKeyState(VK_CONTROL)&0x8000))
{
m_code_func_cache_lines = -1; // invalidate cache
ensure_code_func_cache_valid();
for (i = 0; i < m_code_func_cache.GetSize(); i ++)
{
const char *p = m_code_func_cache.Get(i);
const int line = *(int *)p;
p += sizeof(int);
const char *q = p+strlen(p)+1;
char buf[512];
snprintf(buf,sizeof(buf),"%s%s",p,q);
flist.AddUnsorted(buf,line);
p += 4;
}
}
if (flist.GetSize())
{
flist.Resort();
if (m_case_sensitive) flist.Resort(WDL_LogicalSortStringKeyedArray<int>::cmpistr);
HMENU hm=CreatePopupMenu();
int pos=0;
for (i=0; i < flist.GetSize(); ++i)
{
const char* fname=NULL;
int line=flist.Enumerate(i, &fname);
InsertMenu(hm, pos++, MF_STRING|MF_BYPOSITION, line+1, fname);
}
POINT p;
GetCursorPos(&p);
int ret=TrackPopupMenu(hm, TPM_NONOTIFY|TPM_RETURNCMD, p.x, p.y, 0, hwnd, NULL);
DestroyMenu(hm);
if (ret > 0)
{
GoToLine(ret-1,true);
}
}
else
{
doWatchInfo(0);
}
}
void EEL_Editor::ensure_code_func_cache_valid()
{
const char *prefix = m_function_prefix;
if (!prefix || !*prefix) return;
const DWORD now = GetTickCount();
if (m_text.GetSize()==m_code_func_cache_lines && (now-m_code_func_cache_time)<5000) return;
m_code_func_cache_lines = m_text.GetSize();
m_code_func_cache_time = now;
m_code_func_cache.Empty(true,free);
const int prefix_len = (int) strlen(m_function_prefix);
for (int i=0; i < m_text.GetSize(); ++i)
{
WDL_FastString* s=m_text.Get(i);
if (WDL_NORMALLY(s))
{
const char *p = s->Get();
while (*p)
{
if (m_case_sensitive ? !strncmp(p,prefix,prefix_len) : !strnicmp(p,prefix,prefix_len))
{
p+=prefix_len;
while (*p == ' ') p++;
if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_')
{
const char *q = p+1;
while ((*q >= '0' && *q <= '9') ||
(*q >= 'a' && *q <= 'z') ||
(*q >= 'A' && *q <= 'Z') ||
*q == ':' || // lua
*q == '_' || *q == '.') q++;
const char *endp = q;
while (*q == ' ') q++;
if (*q == '(')
{
const char *endq = q;
while (*endq && *endq != ')') endq++;
if (*endq) endq++;
const char *r = endq;
while (*r == ' ') r++;
const int p_len = (int) (endp - p);
const int q_len = (int) (endq - q);
const int r_len = (int) strlen(r);
// add function
char *v = (char *)malloc(sizeof(int) + p_len + q_len + r_len + 3), *wr = v;
if (WDL_NORMALLY(v))
{
*(int *)wr = i; wr += sizeof(int);
lstrcpyn_safe(wr,p,p_len+1); wr += p_len+1;
lstrcpyn_safe(wr,q,q_len+1); wr += q_len+1;
lstrcpyn_safe(wr,r,r_len+1); wr += r_len+1;
m_code_func_cache.Add(v);
}
p = r; // continue parsing after parentheses
}
}
}
if (*p) p++;
}
}
}
}
#ifdef WDL_IS_FAKE_CURSES
LRESULT EEL_Editor::onMouseMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_LBUTTONDBLCLK:
if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd);
if (CURSES_INSTANCE && CURSES_INSTANCE->m_font_w && CURSES_INSTANCE->m_font_h)
{
const int y = ((short)HIWORD(lParam)) / CURSES_INSTANCE->m_font_h - m_top_margin;
//const int x = ((short)LOWORD(lParam)) / CURSES_INSTANCE->m_font_w + m_offs_x;
WDL_FastString *fs=m_text.Get(y + m_paneoffs_y[m_curpane]);
if (fs && y >= 0)
{
if (!strncmp(fs->Get(),"import",6) && isspace(fs->Get()[6]))
{
open_import_line();
return 1;
}
}
// ctrl+doubleclicking a function goes to it
if (CTRL_KEY_DOWN)
{
WDL_FastString *l=m_text.Get(m_curs_y);
if (l)
{
const char *p = l->Get(), *endp = p + l->GetLength(), *cursor = p + WDL_utf8_charpos_to_bytepos(p,m_curs_x);
int state = 0, toklen = 0;
const char *tok;
while ((tok=sh_tokenize(&p,endp,&toklen,&state)) && cursor > tok+toklen);
if (tok && cursor <= tok+toklen)
{
ensure_code_func_cache_valid();
while (toklen > 0)
{
for (int i = 0; i < m_code_func_cache.GetSize(); i ++)
{
const char *p = m_code_func_cache.Get(i);
int line = *(int *)p;
p+=sizeof(int);
if (line != m_curs_y && strlen(p) == toklen && (m_case_sensitive ? !strncmp(p,tok,toklen) : !strnicmp(p,tok,toklen)))
{
GoToLine(line,true);
return 0;
}
}
// try removing any foo. prefixes
while (toklen > 0 && *tok != '.') { tok++; toklen--; }
tok++;
toklen--;
}
}
}
}
}
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd);
break;
}
return WDL_CursesEditor::onMouseMessage(hwnd,uMsg,wParam,lParam);
}
#endif
| 29.657757 | 161 | 0.530362 | badi91 |
d51daa9e1e70d6408cdfb4d7a4b61f0e565ff340 | 29,952 | cc | C++ | modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc | IsaacZhang123/apollo | 174d17df316a0c30fdeb38c87deb9293791e0f5f | [
"Apache-2.0"
] | 2 | 2021-01-19T02:27:59.000Z | 2021-08-18T06:56:32.000Z | modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc | IsaacZhang123/apollo | 174d17df316a0c30fdeb38c87deb9293791e0f5f | [
"Apache-2.0"
] | null | null | null | modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc | IsaacZhang123/apollo | 174d17df316a0c30fdeb38c87deb9293791e0f5f | [
"Apache-2.0"
] | 1 | 2020-06-22T12:46:39.000Z | 2020-06-22T12:46:39.000Z | /* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.h"
#include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h"
namespace {
double ToMPS(double speed) { return speed * 1000.0 / 3600.0; }
bool IsReferenceLane(int lane_id) { return lane_id == 0; }
}; // namespace
namespace apollo {
namespace hdmap {
namespace adapter {
Status LanesXmlParser::Parse(const tinyxml2::XMLElement& xml_node,
const std::string& road_id,
std::vector<RoadSectionInternal>* sections) {
CHECK_NOTNULL(sections);
const auto lanes_node = xml_node.FirstChildElement("lanes");
CHECK_NOTNULL(lanes_node);
const tinyxml2::XMLElement* sub_node =
lanes_node->FirstChildElement("laneSection");
CHECK_NOTNULL(sub_node);
size_t section_cnt = 0;
while (sub_node) {
RoadSectionInternal section_internal;
std::string section_id = std::to_string(++section_cnt);
section_internal.id = section_id;
section_internal.section.mutable_id()->set_id(section_id);
RETURN_IF_ERROR(ParseLaneSection(*sub_node, §ion_internal.lanes));
RETURN_IF_ERROR(ParseSectionBoundary(
*sub_node,
section_internal.section.mutable_boundary()->mutable_outer_polygon()));
sections->push_back(section_internal);
sub_node = sub_node->NextSiblingElement("laneSection");
}
CHECK_GT(sections->size(), 0);
return Status::OK();
}
Status LanesXmlParser::ParseSectionBoundary(
const tinyxml2::XMLElement& xml_node, PbBoundaryPolygon* boundary) {
CHECK_NOTNULL(boundary);
auto boundaries_node = xml_node.FirstChildElement("boundaries");
if (boundaries_node == nullptr) {
std::string err_msg = "Error parse boundaries";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
auto sub_node = boundaries_node->FirstChildElement("boundary");
while (sub_node) {
PbBoundaryEdge* boundary_edge = boundary->add_edge();
RETURN_IF_ERROR(
UtilXmlParser::ParseCurve(*sub_node, boundary_edge->mutable_curve()));
std::string type;
int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "type", &type);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse boundary type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbBoundaryEdgeType boundary_type;
RETURN_IF_ERROR(ToPbBoundaryType(type, &boundary_type));
boundary_edge->set_type(boundary_type);
sub_node = sub_node->NextSiblingElement("boundary");
}
return Status::OK();
}
Status LanesXmlParser::ToPbBoundaryType(const std::string& type,
PbBoundaryEdgeType* boundary_type) {
CHECK_NOTNULL(boundary_type);
std::string upper_type = UtilXmlParser::ToUpper(type);
if (upper_type == "LEFTBOUNDARY") {
*boundary_type = hdmap::BoundaryEdge::LEFT_BOUNDARY;
} else if (upper_type == "RIGHTBOUNDARY") {
*boundary_type = hdmap::BoundaryEdge::RIGHT_BOUNDARY;
} else {
*boundary_type = hdmap::BoundaryEdge::NORMAL;
}
return Status::OK();
}
Status LanesXmlParser::ParseLaneSection(const tinyxml2::XMLElement& xml_node,
std::vector<LaneInternal>* lanes) {
CHECK_NOTNULL(lanes);
// left
const tinyxml2::XMLElement* sub_node = xml_node.FirstChildElement("left");
if (sub_node) {
sub_node = sub_node->FirstChildElement("lane");
while (sub_node) {
LaneInternal lane_internal;
RETURN_IF_ERROR(ParseLane(*sub_node, &lane_internal));
*(lane_internal.lane.mutable_left_boundary()) =
lane_internal.lane.right_boundary();
lane_internal.lane.clear_right_boundary();
if (lanes->size() > 0) {
PbLane& left_neighbor_lane = lanes->back().lane;
*(left_neighbor_lane.mutable_right_boundary()) =
lane_internal.lane.left_boundary();
}
lanes->push_back(lane_internal);
sub_node = sub_node->NextSiblingElement("lane");
}
}
// center
LaneInternal reference_lane_internal;
sub_node = xml_node.FirstChildElement("center");
CHECK_NOTNULL(sub_node);
sub_node = sub_node->FirstChildElement("lane");
CHECK_NOTNULL(sub_node);
RETURN_IF_ERROR(ParseLane(*sub_node, &reference_lane_internal));
*(reference_lane_internal.lane.mutable_left_boundary()) =
reference_lane_internal.lane.right_boundary();
if (lanes->size() > 0) {
PbLane& left_neighbor_lane = lanes->back().lane;
*(left_neighbor_lane.mutable_right_boundary()) =
reference_lane_internal.lane.left_boundary();
}
// right
sub_node = xml_node.FirstChildElement("right");
if (sub_node) {
sub_node = sub_node->FirstChildElement("lane");
PbLane* left_neighbor_lane = &reference_lane_internal.lane;
while (sub_node) {
// PbLane lane
LaneInternal lane_internal;
RETURN_IF_ERROR(ParseLane(*sub_node, &lane_internal));
*(lane_internal.lane.mutable_left_boundary()) =
left_neighbor_lane->right_boundary();
lanes->push_back(lane_internal);
left_neighbor_lane = &lanes->back().lane;
sub_node = sub_node->NextSiblingElement("lane");
}
}
return Status::OK();
}
Status LanesXmlParser::ParseLane(const tinyxml2::XMLElement& xml_node,
LaneInternal* lane_internal) {
CHECK_NOTNULL(lane_internal);
PbLane* lane = &lane_internal->lane;
// lane id
int id = 0;
int checker = xml_node.QueryIntAttribute("id", &id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane id";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
std::string lane_id;
checker = UtilXmlParser::QueryStringAttribute(xml_node, "uid", &lane_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane uid";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->mutable_id()->set_id(lane_id);
// lane type
std::string lane_type;
checker = UtilXmlParser::QueryStringAttribute(xml_node, "type", &lane_type);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbLaneType pb_lane_type;
Status success = ToPbLaneType(lane_type, &pb_lane_type);
if (!success.ok()) {
std::string err_msg = "Error convert lane type to pb lane type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->set_type(pb_lane_type);
// border
const tinyxml2::XMLElement* sub_node = xml_node.FirstChildElement("border");
if (sub_node) {
PbLaneBoundary* lane_boundary = lane->mutable_right_boundary();
CHECK(lane_boundary != nullptr);
success =
UtilXmlParser::ParseCurve(*sub_node, lane_boundary->mutable_curve());
if (!success.ok()) {
std::string err_msg = "Error parse lane border";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane_boundary->set_length(
UtilXmlParser::CurveLength(*lane_boundary->mutable_curve()));
bool is_virtual = false;
std::string virtual_border = "FALSE";
checker = UtilXmlParser::QueryStringAttribute(*sub_node, "virtual",
&virtual_border);
if (checker == tinyxml2::XML_SUCCESS) {
if (virtual_border == "TRUE") {
is_virtual = true;
}
}
lane_boundary->set_virtual_(is_virtual);
}
// road mark
if (sub_node) {
sub_node = sub_node->FirstChildElement("borderType");
}
while (sub_node) {
PbLaneBoundary* lane_boundary = lane->mutable_right_boundary();
PbLaneBoundaryTypeType boundary_type;
success = ParseLaneBorderMark(*sub_node, &boundary_type);
if (!success.ok()) {
std::string err_msg = "Error parse lane border type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
double s_offset = 0.0;
checker = sub_node->QueryDoubleAttribute("sOffset", &s_offset);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane boundary type offset.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
auto lane_boundary_type = lane_boundary->add_boundary_type();
lane_boundary_type->set_s(s_offset);
lane_boundary_type->add_types(boundary_type);
sub_node = sub_node->NextSiblingElement("borderType");
}
// reference line
if (IsReferenceLane(id)) {
return Status::OK();
}
// turn type
std::string turn_type;
checker =
UtilXmlParser::QueryStringAttribute(xml_node, "turnType", &turn_type);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane turn type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbTurnType pb_turn_type;
success = ToPbTurnType(turn_type, &pb_turn_type);
if (!success.ok()) {
std::string err_msg = "Error convert turn type to pb turn type.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->set_turn(pb_turn_type);
// direction
RETURN_IF_ERROR(ParseDirection(xml_node, lane));
// link
sub_node = xml_node.FirstChildElement("link");
if (sub_node) {
ParseLaneLink(*sub_node, lane);
}
// center curve
RETURN_IF_ERROR(ParseCenterCurve(xml_node, lane));
// speed
RETURN_IF_ERROR(ParseSpeed(xml_node, lane));
// sample association
RETURN_IF_ERROR(ParseSampleAssociates(xml_node, lane));
// road sample association
RETURN_IF_ERROR(ParseRoadSampleAssociates(xml_node, lane));
// overlap object
ParseObjectOverlapGroup(xml_node, &lane_internal->overlap_objects);
// overlap signal
ParseSignalOverlapGroup(xml_node, &lane_internal->overlap_signals);
// overlap junction
ParseJunctionOverlapGroup(xml_node, &lane_internal->overlap_junctions);
// overlap lane
ParseLaneOverlapGroup(xml_node, &lane_internal->overlap_lanes);
return Status::OK();
}
Status LanesXmlParser::ParseDirection(const tinyxml2::XMLElement& xml_node,
PbLane* lane) {
CHECK_NOTNULL(lane);
std::string direction;
int checker =
UtilXmlParser::QueryStringAttribute(xml_node, "direction", &direction);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane direction.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbLaneDirection pb_lane_direction;
Status success = ToPbDirection(direction, &pb_lane_direction);
if (!success.ok()) {
std::string err_msg = "Error convert direction to pb direction";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->set_direction(pb_lane_direction);
return Status::OK();
}
Status LanesXmlParser::ParseCenterCurve(const tinyxml2::XMLElement& xml_node,
PbLane* lane) {
CHECK_NOTNULL(lane);
auto sub_node = xml_node.FirstChildElement("centerLine");
if (!sub_node) {
std::string err_msg = "Error parse lane center curve";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
PbCurve* center_curve = lane->mutable_central_curve();
Status success = UtilXmlParser::ParseCurve(*sub_node, center_curve);
if (!success.ok()) {
std::string err_msg = "Error parse lane center curve";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->set_length(UtilXmlParser::CurveLength(*center_curve));
return Status::OK();
}
Status LanesXmlParser::ParseSpeed(const tinyxml2::XMLElement& xml_node,
PbLane* lane) {
double max_speed = 0.0;
auto sub_node = xml_node.FirstChildElement("speed");
if (sub_node) {
int checker = sub_node->QueryDoubleAttribute("max", &max_speed);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane speed attribute";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
lane->set_speed_limit(ToMPS(max_speed));
}
return Status::OK();
}
Status LanesXmlParser::ParseSampleAssociates(
const tinyxml2::XMLElement& xml_node, PbLane* lane) {
CHECK_NOTNULL(lane);
auto sub_node = xml_node.FirstChildElement("sampleAssociates");
if (sub_node == nullptr) {
std::string err_msg = "Error parse sample associates";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
sub_node = sub_node->FirstChildElement("sampleAssociate");
if (sub_node == nullptr) {
std::string err_msg = "Error parse sample associate";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
while (sub_node) {
double left_width = 0.0;
double right_width = 0.0;
double s = 0.0;
int checker = sub_node->QueryDoubleAttribute("sOffset", &s);
checker += sub_node->QueryDoubleAttribute("leftWidth", &left_width);
checker += sub_node->QueryDoubleAttribute("rightWidth", &right_width);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane sample associate attribute";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
auto left_sample = lane->add_left_sample();
left_sample->set_s(s);
left_sample->set_width(left_width);
auto right_sample = lane->add_right_sample();
right_sample->set_s(s);
right_sample->set_width(right_width);
sub_node = sub_node->NextSiblingElement("sampleAssociate");
}
return Status::OK();
}
Status LanesXmlParser::ParseRoadSampleAssociates(
const tinyxml2::XMLElement& xml_node, PbLane* lane) {
CHECK_NOTNULL(lane);
auto sub_node = xml_node.FirstChildElement("roadSampleAssociations");
if (sub_node == nullptr) {
std::string err_msg = "Error parse road sample associations";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
sub_node = sub_node->FirstChildElement("sampleAssociation");
if (sub_node == nullptr) {
std::string err_msg = "Error parse road sample association";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
while (sub_node) {
double left_width = 0.0;
double right_width = 0.0;
double s = 0.0;
int checker = sub_node->QueryDoubleAttribute("sOffset", &s);
checker += sub_node->QueryDoubleAttribute("leftWidth", &left_width);
checker += sub_node->QueryDoubleAttribute("rightWidth", &right_width);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse road sample association attribute";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
auto left_road_sample = lane->add_left_road_sample();
left_road_sample->set_s(s);
left_road_sample->set_width(left_width);
auto right_road_sample = lane->add_right_road_sample();
right_road_sample->set_s(s);
right_road_sample->set_width(right_width);
sub_node = sub_node->NextSiblingElement("sampleAssociation");
}
return Status::OK();
}
Status LanesXmlParser::ParseObjectOverlapGroup(
const tinyxml2::XMLElement& xml_node,
std::vector<OverlapWithLane>* object_overlaps) {
CHECK_NOTNULL(object_overlaps);
auto object_overlap = xml_node.FirstChildElement("objectOverlapGroup");
if (object_overlap) {
auto sub_node = object_overlap->FirstChildElement("objectReference");
while (sub_node) {
std::string object_id;
double start_s = 0.0;
double end_s = 0.0;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id);
checker += sub_node->QueryDoubleAttribute("startOffset", &start_s);
checker += sub_node->QueryDoubleAttribute("endOffset", &end_s);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane object overlap";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
bool is_merge = false;
checker = sub_node->QueryBoolAttribute("isMerge", &is_merge);
if (checker != tinyxml2::XML_SUCCESS) {
is_merge = false;
}
OverlapWithLane overlap_with_lane;
overlap_with_lane.object_id = object_id;
overlap_with_lane.start_s = start_s;
overlap_with_lane.end_s = end_s;
overlap_with_lane.is_merge = is_merge;
RETURN_IF_ERROR(
ParseRegionOverlap(*sub_node, &overlap_with_lane.region_overlaps));
if (overlap_with_lane.region_overlaps.size() > 0) {
UtilXmlParser::QueryStringAttribute(
*sub_node, "regionOverlapId", &overlap_with_lane.region_overlap_id);
}
object_overlaps->push_back(overlap_with_lane);
sub_node = sub_node->NextSiblingElement("objectReference");
}
}
return Status::OK();
}
Status LanesXmlParser::ParseSignalOverlapGroup(
const tinyxml2::XMLElement& xml_node,
std::vector<OverlapWithLane>* signal_overlaps) {
CHECK_NOTNULL(signal_overlaps);
auto signal_overlap = xml_node.FirstChildElement("signalOverlapGroup");
if (signal_overlap) {
auto sub_node = signal_overlap->FirstChildElement("signalReference");
while (sub_node) {
std::string object_id;
double start_s = 0.0;
double end_s = 0.0;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id);
checker += sub_node->QueryDoubleAttribute("startOffset", &start_s);
checker += sub_node->QueryDoubleAttribute("endOffset", &end_s);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane signal overlap";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
bool is_merge = false;
checker = sub_node->QueryBoolAttribute("isMerge", &is_merge);
if (checker != tinyxml2::XML_SUCCESS) {
is_merge = false;
}
OverlapWithLane overlap_with_lane;
overlap_with_lane.object_id = object_id;
overlap_with_lane.start_s = start_s;
overlap_with_lane.end_s = end_s;
overlap_with_lane.is_merge = is_merge;
signal_overlaps->push_back(overlap_with_lane);
sub_node = sub_node->NextSiblingElement("signalReference");
}
}
return Status::OK();
}
Status LanesXmlParser::ParseJunctionOverlapGroup(
const tinyxml2::XMLElement& xml_node,
std::vector<OverlapWithLane>* junction_overlaps) {
CHECK_NOTNULL(junction_overlaps);
auto overlap_group = xml_node.FirstChildElement("junctionOverlapGroup");
if (overlap_group) {
auto sub_node = overlap_group->FirstChildElement("junctionReference");
while (sub_node) {
std::string object_id;
double start_s = 0.0;
double end_s = 0.0;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id);
checker += sub_node->QueryDoubleAttribute("startOffset", &start_s);
checker += sub_node->QueryDoubleAttribute("endOffset", &end_s);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane junction overlap";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
bool is_merge = false;
checker = sub_node->QueryBoolAttribute("isMerge", &is_merge);
if (checker != tinyxml2::XML_SUCCESS) {
is_merge = false;
}
OverlapWithLane overlap_with_lane;
overlap_with_lane.object_id = object_id;
overlap_with_lane.start_s = start_s;
overlap_with_lane.end_s = end_s;
overlap_with_lane.is_merge = is_merge;
junction_overlaps->push_back(overlap_with_lane);
sub_node = sub_node->NextSiblingElement("junctionReference");
}
}
return Status::OK();
}
Status LanesXmlParser::ParseLaneOverlapGroup(
const tinyxml2::XMLElement& xml_node,
std::vector<OverlapWithLane>* lane_overlaps) {
CHECK_NOTNULL(lane_overlaps);
auto overlap_node = xml_node.FirstChildElement("laneOverlapGroup");
if (overlap_node) {
auto sub_node = overlap_node->FirstChildElement("laneReference");
while (sub_node) {
std::string lane_id;
double start_s = 0.0;
double end_s = 0.0;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id);
checker += sub_node->QueryDoubleAttribute("startOffset", &start_s);
checker += sub_node->QueryDoubleAttribute("endOffset", &end_s);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error parse lane lane overlap";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
bool is_merge = false;
checker = sub_node->QueryBoolAttribute("isMerge", &is_merge);
if (checker != tinyxml2::XML_SUCCESS) {
is_merge = false;
}
OverlapWithLane overlap_with_lane;
overlap_with_lane.object_id = lane_id;
overlap_with_lane.start_s = start_s;
overlap_with_lane.end_s = end_s;
overlap_with_lane.is_merge = is_merge;
lane_overlaps->push_back(overlap_with_lane);
sub_node = sub_node->NextSiblingElement("laneReference");
}
}
return Status::OK();
}
Status LanesXmlParser::ToPbLaneType(const std::string& type,
PbLaneType* lane_type) {
CHECK_NOTNULL(lane_type);
std::string upper_str = UtilXmlParser::ToUpper(type);
if (upper_str == "NONE") {
*lane_type = hdmap::Lane::NONE;
} else if (upper_str == "DRIVING") {
*lane_type = hdmap::Lane::CITY_DRIVING;
} else if (upper_str == "BIKING") {
*lane_type = hdmap::Lane::BIKING;
} else if (upper_str == "PARKING") {
*lane_type = hdmap::Lane::PARKING;
} else if (upper_str == "SHOULDER") {
*lane_type = hdmap::Lane::SHOULDER;
} else if (upper_str == "SIDEWALK") {
*lane_type = hdmap::Lane::SIDEWALK;
} else {
std::string err_msg = "Error or unsupport lane type:" + type;
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status LanesXmlParser::ToPbTurnType(const std::string& type,
PbTurnType* pb_turn_type) {
CHECK_NOTNULL(pb_turn_type);
std::string upper_str = UtilXmlParser::ToUpper(type);
if (upper_str == "NOTURN") {
*pb_turn_type = hdmap::Lane::NO_TURN;
} else if (upper_str == "LEFTTURN") {
*pb_turn_type = hdmap::Lane::LEFT_TURN;
} else if (upper_str == "RIGHTTURN") {
*pb_turn_type = hdmap::Lane::RIGHT_TURN;
} else if (upper_str == "UTURN") {
*pb_turn_type = hdmap::Lane::U_TURN;
} else {
std::string err_msg = "Error or unsupport turn type:" + type;
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status LanesXmlParser::ToPbDirection(const std::string& type,
PbLaneDirection* pb_direction) {
CHECK_NOTNULL(pb_direction);
std::string upper_str = UtilXmlParser::ToUpper(type);
if (upper_str == "FORWARD") {
*pb_direction = hdmap::Lane::FORWARD;
} else if (upper_str == "BACKWARD") {
*pb_direction = hdmap::Lane::BACKWARD;
} else if (upper_str == "BIDIRECTION") {
*pb_direction = hdmap::Lane::BIDIRECTION;
} else {
std::string err_msg = "Error or unsupport dirction:" + type;
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
void LanesXmlParser::ParseLaneLink(const tinyxml2::XMLElement& xml_node,
PbLane* lane) {
CHECK_NOTNULL(lane);
const tinyxml2::XMLElement* sub_node =
xml_node.FirstChildElement("predecessor");
while (sub_node) {
std::string lane_id;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id);
if (checker == tinyxml2::XML_SUCCESS) {
PbID* pb_lane_id = lane->add_predecessor_id();
pb_lane_id->set_id(lane_id);
}
sub_node = sub_node->NextSiblingElement("predecessor");
}
sub_node = xml_node.FirstChildElement("successor");
while (sub_node) {
std::string lane_id;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id);
if (checker == tinyxml2::XML_SUCCESS) {
PbID* pb_lane_id = lane->add_successor_id();
pb_lane_id->set_id(lane_id);
}
sub_node = sub_node->NextSiblingElement("successor");
}
sub_node = xml_node.FirstChildElement("neighbor");
while (sub_node) {
std::string side;
std::string direction;
std::string lane_id;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id);
checker += UtilXmlParser::QueryStringAttribute(*sub_node, "side", &side);
checker +=
UtilXmlParser::QueryStringAttribute(*sub_node, "direction", &direction);
if (checker == tinyxml2::XML_SUCCESS) {
if (side == "left") {
if (direction == "same") {
lane->add_left_neighbor_forward_lane_id()->set_id(lane_id);
} else {
lane->add_left_neighbor_reverse_lane_id()->set_id(lane_id);
}
} else if (side == "right") {
if (direction == "same") {
lane->add_right_neighbor_forward_lane_id()->set_id(lane_id);
} else {
lane->add_right_neighbor_reverse_lane_id()->set_id(lane_id);
}
}
}
sub_node = sub_node->NextSiblingElement("neighbor");
}
sub_node = xml_node.FirstChildElement("selfReverse");
while (sub_node) {
std::string lane_id;
int checker =
UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id);
if (checker == tinyxml2::XML_SUCCESS) {
lane->add_self_reverse_lane_id()->set_id(lane_id);
}
sub_node = sub_node->NextSiblingElement("selfReverse");
}
}
Status LanesXmlParser::ParseLaneBorderMark(
const tinyxml2::XMLElement& xml_node,
PbLaneBoundaryTypeType* boundary_type) {
CHECK_NOTNULL(boundary_type);
std::string type;
std::string color;
int checker = UtilXmlParser::QueryStringAttribute(xml_node, "type", &type);
checker += UtilXmlParser::QueryStringAttribute(xml_node, "color", &color);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error to parse lane border mark";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
Status success = ToPbLaneMarkType(type, color, boundary_type);
if (!success.ok()) {
std::string err_msg = "fail to convert to pb lane border mark";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status LanesXmlParser::ToPbLaneMarkType(const std::string& type,
const std::string& color,
PbLaneBoundaryTypeType* boundary_type) {
CHECK_NOTNULL(boundary_type);
std::string upper_type = UtilXmlParser::ToUpper(type);
std::string upper_color = UtilXmlParser::ToUpper(color);
if (upper_type == "CURB") {
*boundary_type = hdmap::LaneBoundaryType::CURB;
return Status::OK();
}
if (upper_type == "NONE") {
*boundary_type = hdmap::LaneBoundaryType::UNKNOWN;
return Status::OK();
}
if (upper_color == "YELLOW") {
if (upper_type == "SOLID") {
*boundary_type = hdmap::LaneBoundaryType::SOLID_YELLOW;
} else if (upper_type == "BROKEN") {
*boundary_type = hdmap::LaneBoundaryType::DOTTED_YELLOW;
} else {
std::string err_msg = "Error or unsupport lane boundary type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
} else if (upper_color == "WHITE") {
if (upper_type == "SOLID") {
*boundary_type = hdmap::LaneBoundaryType::SOLID_WHITE;
} else if (upper_type == "BROKEN") {
*boundary_type = hdmap::LaneBoundaryType::DOTTED_WHITE;
} else {
std::string err_msg = "Error or unsupport lane boundary type";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
} else {
std::string err_msg = "Error or unsupport lane boundary color.";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
return Status::OK();
}
Status LanesXmlParser::ParseRegionOverlap(
const tinyxml2::XMLElement& xml_node,
std::vector<PbRegionOverlap>* region_overlaps) {
CHECK_NOTNULL(region_overlaps);
auto region_overlap_node = xml_node.FirstChildElement("regionOverlap");
while (region_overlap_node != nullptr) {
PbRegionOverlap region_overlap;
std::string region_overlap_id;
int checker = UtilXmlParser::QueryStringAttribute(*region_overlap_node,
"id", ®ion_overlap_id);
if (checker != tinyxml2::XML_SUCCESS) {
std::string err_msg = "Error to parse region overlap id";
return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg);
}
region_overlap.mutable_id()->set_id(region_overlap_id);
auto outline_node = region_overlap_node->FirstChildElement("outline");
while (outline_node != nullptr) {
RETURN_IF_ERROR(UtilXmlParser::ParseOutline(
*outline_node, region_overlap.add_polygon()));
outline_node = outline_node->NextSiblingElement("outline");
}
region_overlap_node =
region_overlap_node->NextSiblingElement("regionOverlap");
region_overlaps->emplace_back(region_overlap);
}
return Status::OK();
}
} // namespace adapter
} // namespace hdmap
} // namespace apollo
| 35.0726 | 80 | 0.685831 | IsaacZhang123 |
d51ec1720ee2162fa6b160278ebe048b09a56fd0 | 577 | cpp | C++ | test/src/doctest_main.cpp | karnkaul/veg | a6b54484b162a188f7abae8ae27d2c1f04fda16c | [
"MIT"
] | 8 | 2021-07-16T18:07:15.000Z | 2022-01-31T19:17:10.000Z | test/src/doctest_main.cpp | karnkaul/veg | a6b54484b162a188f7abae8ae27d2c1f04fda16c | [
"MIT"
] | 1 | 2022-01-18T23:02:26.000Z | 2022-01-18T23:02:30.000Z | test/src/doctest_main.cpp | karnkaul/veg | a6b54484b162a188f7abae8ae27d2c1f04fda16c | [
"MIT"
] | 2 | 2022-01-18T15:45:18.000Z | 2022-01-26T09:53:19.000Z | #define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
#include <cstdio>
#include <backward.hpp>
namespace veg {
int argc = 0;
char** argv = nullptr;
} // namespace veg
auto main(int argc, char** argv) -> int {
veg::argc = argc;
veg::argv = argv;
char argname[] = "--veg-death-assertion-id";
if (argc >= 3 && //
(std::strcmp(argv[argc - 2], argname) == 0)) {
std::FILE* _{};
_ = std::freopen("/dev/null", "w", stderr);
_ = std::freopen("/dev/null", "w", stdout);
} else {
backward::SignalHandling const sh;
}
return doctest::Context(argc, argv).run();
}
| 21.37037 | 51 | 0.616984 | karnkaul |
d52047756e66a3c16b8efa635ce2d1f323bae298 | 2,910 | cpp | C++ | src/stc/scope.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | 3 | 2020-03-01T06:30:30.000Z | 2021-05-01T05:11:48.000Z | src/stc/scope.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | 96 | 2020-01-18T18:25:48.000Z | 2022-03-26T12:26:50.000Z | src/stc/scope.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Name: scope.cpp
// Purpose: Implementation of class wex::scope
// Author: Anton van Wezenbeek
// Copyright: (c) 2020-2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <wex/log.h>
#include <wex/stc.h>
#include "scope.h"
wex::scope::scope(stc* s)
: m_stc(s)
{
}
void wex::scope::check_levels(check_t type)
{
bool changed = false;
const auto level(m_stc->get_fold_level());
const auto size(m_filters.size());
if (type[LEVEL_DOWN] && size >= 1 && level < size - 1)
{
m_filters.erase(m_filters.begin() + level + 1, m_filters.end());
changed = true;
log::debug("scope::check_levels erased level")
<< size - m_filters.size() << "current:" << level
<< "size:" << m_filters.size();
}
if (!changed && type[LEVEL_UP] && level >= size)
{
map_t m;
m[std::string()] = ctags_entry();
m_filters.insert(m_filters.end(), level - size + 1, m);
changed = true;
log::debug("scope::check_levels inserted level")
<< m_filters.size() - size << "current:" << level
<< "size:" << m_filters.size();
}
if (changed)
{
m_it = m_filters[level].end();
}
}
const std::string wex::scope::class_name(const std::string& name) const
{
const auto level(m_stc->get_fold_level());
if (m_filters.empty() || level > m_filters.size())
{
return std::string();
}
log::debug("scope::class_name") << name << level << m_filters[level].size();
if (const auto& it = iterator(name); !end())
{
return it->second.class_name();
}
else
{
return std::string();
}
}
bool wex::scope::end() const
{
const auto level(m_stc->get_fold_level());
return level >= m_filters.size() || m_it == m_filters[level].end();
}
bool wex::scope::find(const std::string& text)
{
m_it = iterator(text);
return !end();
}
wex::ctags_entry& wex::scope::get(const std::string& text)
{
if (m_filters.empty())
{
sync();
}
const auto level(m_stc->get_fold_level());
return m_filters[level][text];
}
void wex::scope::insert(const std::string& text, const ctags_entry& ce)
{
assert(!text.empty());
const auto level(m_stc->get_fold_level());
m_filters[level].insert({text, ce});
find(text);
log::debug("scope::insert") << text << level << ce;
}
wex::scope::map_t::const_iterator
wex::scope::iterator(const std::string& text) const
{
const auto level(m_stc->get_fold_level());
if (text.empty())
{
return m_filters[level].end();
}
for (int i = std::min(level, m_filters.size() - 1); i >= 0; i--)
{
if (const auto& it = m_filters[i].find(text); it != m_filters[i].end())
{
return it;
}
}
return m_filters[level].end();
}
void wex::scope::sync()
{
log::debug("scope::sync");
check_levels();
}
| 21.086957 | 80 | 0.576289 | antonvw |
d520fecc7313fd00060c3bd0391a55885087991f | 6,931 | hpp | C++ | c++/src/objtools/align_format/unit_test/blast_test_util.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/objtools/align_format/unit_test/blast_test_util.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/objtools/align_format/unit_test/blast_test_util.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: blast_test_util.hpp 354597 2012-02-28 16:45:09Z ucko $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/** @file blast_test_util.hpp
* Utilities to develop and debug unit tests for BLAST
*/
#ifndef _BLAST_TEST_UTIL_HPP
#define _BLAST_TEST_UTIL_HPP
#include <string>
#include <exception>
#include <assert.h>
#include <corelib/ncbistd.hpp>
#include <serial/serial.hpp>
#include <serial/objostr.hpp>
#include <util/random_gen.hpp>
#include <util/format_guess.hpp>
#include <serial/serial.hpp>
#include <objtools/data_loaders/blastdb/bdbloader.hpp>
#ifndef ASSERT
#define ASSERT assert
#endif
// forward declarations
namespace ncbi {
namespace objects {
class CSeq_id;
class CSeq_align_set;
class CSeqVector;
class CScope;
class CObjectManager;
}
namespace blast {
struct SSeqLoc;
}
}
namespace TestUtil {
// Random integer generator for use with std::generate
#if defined(__ICC) || defined(NCBI_OS_IRIX) || defined(__clang__)
template <int lowest_value = 0, int highest_value = INT_MAX>
#else
template <int lowest_value = 0, int highest_value = ncbi::CRandom::GetMax()>
#endif
struct CRandomIntGen {
CRandomIntGen() : m_Gen(::time(0)) {}
int operator()() {
return m_Gen.GetRand(lowest_value, highest_value);
}
private:
ncbi::CRandom m_Gen;
};
ncbi::objects::CSeq_id* GenerateRandomSeqid_Gi();
template <class T>
ncbi::CRef<T> ReadObject(const std::string& filename) {
ncbi::CNcbiIfstream in(filename.c_str());
if ( !in ) {
throw std::runtime_error("Failed to open " + filename);
}
ncbi::CRef<T> retval(new T);
switch (ncbi::CFormatGuess().Format(in)) {
case ncbi::CFormatGuess::eTextASN:
in >> ncbi::MSerial_AsnText >> *retval;
break;
case ncbi::CFormatGuess::eBinaryASN:
in >> ncbi::MSerial_AsnBinary >> *retval;
break;
case ncbi::CFormatGuess::eXml:
in >> ncbi::MSerial_Xml >> *retval;
break;
default:
throw std::runtime_error("Unsupported format");
}
return retval;
}
/// Convenience template function to print ASN.1 objects to a new file
template <class T>
void PrintTextAsn1Object(std::string filename, T* obj) {
std::ofstream out(filename.c_str());
if ( !out )
throw std::runtime_error("Could not open " + filename);
out << ncbi::MSerial_AsnText << *obj;
}
/** Converts bl2seq and blast style seq-align-sets to the seq-align-set format
* that the new formatter understands (same flat format as C toolkit
* seq-aligns) */
ncbi::CRef<ncbi::objects::CSeq_align_set>
FlattenSeqAlignSet(const ncbi::objects::CSeq_align_set& sset);
/// Assumes that the sas argument is a bl2seq and blast style seq-align-set
void PrintFormattedSeqAlign(std::ostream& out,
const ncbi::objects::CSeq_align_set* sas,
ncbi::objects::CScope& scope);
/// Endianness independent hash function.
///
/// This function computes a hash value for an array of any primitive
/// type. The hash assumes the data is the array is in "host" order
/// with respect to endianness and should produce the same value on
/// any platform for the same numerical values of the array
/// elements.<P>
///
/// The algorithm attempts to be robust against changes in values in
/// the array, the length of the array, zeroes appended to the array),
/// and will not normally be fooled by naturally occurring patterns in
/// the buffer. 9However, it is not intended to be secure against
/// deliberate attempts to produce a collision).<P>
///
/// The size of an element of the array must be uniform and is
/// specified as an argument to the function. It must exactly divide
/// the byte length of the array. If the size element is specified as
/// 1, no swapping will be done. This can be used to hash a string.
///
/// @param buffer
/// Points to the beginning of the array.
/// @param byte_length
/// The length of the array in bytes.
/// @param swap_size
/// The size of one array element (specify 1 to disable swapping).
/// @param hash_seed.
/// The starting value of the hash.
Uint4 EndianIndependentBufferHash(const char * buffer,
Uint4 byte_length,
Uint4 swap_size = 1,
Uint4 hash_seed = 1);
/** Class which registers the BLAST database and Genbank data loaders as a
* non-default data loaders with the object manager upon construction.
* Designed so that the scopes created by this object are configured properly
* to obtain the sequences in the expected priorities in the BLAST code.
*/
class CBlastOM
{
public:
enum ELocation {
eRemote,
eLocal
};
typedef ncbi::CBlastDbDataLoader::EDbType EDbType;
CBlastOM(const std::string& dbname, EDbType db_type, ELocation location = eLocal);
/// Create a new scope with the default set to the BLAST database data
/// loader for the BLAST database specified in the constructor (if found),
/// then set to the Genbank data loader
ncbi::CRef<ncbi::objects::CScope> NewScope();
/// Removes the BLAST database data loader from the object manager.
void RevokeBlastDbDataLoader();
private:
ncbi::CRef<ncbi::objects::CObjectManager> m_ObjMgr;
std::string m_BlastDbLoaderName;
std::string m_GbLoaderName;
void x_InitBlastDatabaseDataLoader(const std::string& dbname,
EDbType dbtype,
ELocation location);
void x_InitGenbankDataLoader();
};
}
#endif // _BLAST_TEST_UTIL_HPP
| 33.97549 | 86 | 0.665416 | OpenHero |
d527fabc2345d9850127221c934ccf808739c9d3 | 860 | cpp | C++ | Raspi backup/final/real_real_final/system_management.cpp | radii-dev/rpi3-self-driving-model-shuttle-bus | f3f050f517b33c09f0552d09fc5094d795226c75 | [
"MIT"
] | null | null | null | Raspi backup/final/real_real_final/system_management.cpp | radii-dev/rpi3-self-driving-model-shuttle-bus | f3f050f517b33c09f0552d09fc5094d795226c75 | [
"MIT"
] | null | null | null | Raspi backup/final/real_real_final/system_management.cpp | radii-dev/rpi3-self-driving-model-shuttle-bus | f3f050f517b33c09f0552d09fc5094d795226c75 | [
"MIT"
] | null | null | null | #include "system_management.h"
std::ofstream fileout("log");
System_resource::System_resource()
{
sysinfo(&memInfo);
totalVirtualMem = memInfo.totalram;
totalVirtualMem += memInfo.totalswap;
totalVirtualMem *= memInfo.mem_unit;
totalPhysMem = memInfo.totalram;
totalPhysMem *= memInfo.mem_unit;
}
uint64_t System_resource::getTotalVirtualMem()
{
return totalVirtualMem;
}
uint64_t System_resource::getVirtualMemUsed()
{
virtualMemUsed = memInfo.totalram - memInfo.freeram;
virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
virtualMemUsed *= memInfo.mem_unit;
return virtualMemUsed;
}
uint64_t System_resource::getTotalPhysMem()
{
return totalPhysMem;
}
uint64_t System_resource::getPhysMemUsed()
{
physMemUsed = memInfo.totalram - memInfo.freeram;
physMemUsed *= memInfo.mem_unit;
return physMemUsed;
}
System_resource system_resource;
| 23.243243 | 56 | 0.790698 | radii-dev |
d52a2e3d7bc726d86fdc5b6f25baffcad0df83ff | 7,246 | cpp | C++ | BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp | wafflehammer/MonoInjector | bc7680a2ec8be606f5fdc8614c0c991a1d074382 | [
"MIT"
] | 354 | 2018-08-13T18:19:21.000Z | 2022-03-20T10:37:20.000Z | Protection/BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp | Bia10/ZzukBot_V3 | 55abfb38fd07ba970d4b4020d8d96b87559509db | [
"Unlicense"
] | 6 | 2017-08-03T03:40:56.000Z | 2021-10-18T22:12:58.000Z | Protection/BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp | Bia10/ZzukBot_V3 | 55abfb38fd07ba970d4b4020d8d96b87559509db | [
"Unlicense"
] | 90 | 2018-11-15T12:37:51.000Z | 2022-02-14T11:12:39.000Z | #include "LocalHookBase.h"
namespace blackbone
{
std::unordered_map<void*, DetourBase*> DetourBase::_breakpoints;
void* DetourBase::_vecHandler = nullptr;
DetourBase::DetourBase()
{
}
DetourBase::~DetourBase()
{
VirtualFree( _buf, 0, MEM_RELEASE );
}
/// <summary>
/// Allocate detour buffer as close to target as possible
/// </summary>
/// <param name="nearest">Target address</param>
/// <returns>true on success</returns>
bool DetourBase::AllocateBuffer( uint8_t* nearest )
{
if (_buf != nullptr)
return true;
MEMORY_BASIC_INFORMATION mbi = { 0 };
for (SIZE_T addr = (SIZE_T)nearest; addr > (SIZE_T)nearest - 0x80000000; addr = (SIZE_T)mbi.BaseAddress - 1)
{
if (!VirtualQuery( (LPCVOID)addr, &mbi, sizeof( mbi ) ))
break;
if (mbi.State == MEM_FREE)
{
_buf = (uint8_t*)VirtualAlloc(
(uint8_t*)mbi.BaseAddress + mbi.RegionSize - 0x1000, 0x1000,
MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE
);
if (_buf)
break;
}
}
// If allocating a memory page failed, allocate first suitable
if (_buf == nullptr)
_buf = (uint8_t*)VirtualAlloc( nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE );
_origCode = _buf + 0x100;
_newCode = _buf + 0x200;
return _buf != nullptr;
}
/// <summary>
/// Temporarily disable hook
/// </summary>
/// <returns>true on success</returns>
bool DetourBase::DisableHook()
{
if (_type == HookType::InternalInline || _type == HookType::Int3)
WriteProcessMemory( GetCurrentProcess(), _original, _origCode, _origSize, NULL );
else if (_type == HookType::HWBP)
ToggleHBP( _hwbpIdx[GetCurrentThreadId()], false );
return true;
}
/// <summary>
/// Enable disabled hook
/// </summary>
/// <returns>true on success</returns>
bool DetourBase::EnableHook()
{
if (_type == HookType::InternalInline || _type == HookType::Int3)
WriteProcessMemory( GetCurrentProcess(), _original, _newCode, _origSize, NULL );
else if (_type == HookType::HWBP)
ToggleHBP( _hwbpIdx[GetCurrentThreadId()], true );
return true;
}
/// <summary>
/// Toggle hardware breakpoint for current thread
/// </summary>
/// <param name="index">Breakpoint index ( 0-4 )</param>
/// <param name="enable">true to enable, false to disable</param>
/// <returns>true on success</returns>
bool DetourBase::ToggleHBP( int index, bool enable )
{
CONTEXT context = { 0 };
context.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if (GetThreadContext( GetCurrentThread(), &context ) != TRUE)
return FALSE;
if (enable)
BitTestAndSetT( (LONG_PTR*)&context.Dr7, 2 * index );
else
BitTestAndResetT( (LONG_PTR*)&context.Dr7, 2 * index );
return (SetThreadContext( GetCurrentThread(), &context ) != FALSE);
}
/// <summary>
/// Copy original function bytes
/// </summary>
/// <param name="Ptr">Origianl function address</param>
void DetourBase::CopyOldCode( uint8_t* ptr )
{
// Store original bytes
uint8_t* src = ptr;
uint8_t* old = (uint8_t*)_origCode;
uint32_t all_len = 0;
ldasm_data ld = { 0 };
do
{
uint32_t len = ldasm( src, &ld, is_x64 );
// Determine code end
if (ld.flags & F_INVALID
|| (len == 1 && (src[ld.opcd_offset] == 0xCC || src[ld.opcd_offset] == 0xC3))
|| (len == 3 && src[ld.opcd_offset] == 0xC2)
|| len + all_len > 128)
{
break;
}
// move instruction
memcpy( old, src, len );
// if instruction has relative offset, calculate new offset
if (ld.flags & F_RELATIVE)
{
int32_t diff = 0;
const uintptr_t ofst = (ld.disp_offset != 0 ? ld.disp_offset : ld.imm_offset);
const uintptr_t sz = ld.disp_size != 0 ? ld.disp_size : ld.imm_size;
memcpy( &diff, src + ofst, sz );
#ifdef USE64
// exit if jump is greater then 2GB
if (_abs64( src + len + diff - old ) > INT_MAX)
{
break;
}
else
{
diff += static_cast<int32_t>(src - old);
memcpy( old + ofst, &diff, sz );
}
#else
diff += src - old;
memcpy( old + ofst, &diff, sz );
#endif
}
src += len;
old += len;
all_len += len;
} while (all_len < _origSize);
// Failed to copy old code, use backup plan
if (all_len < _origSize)
{
_type = HookType::InternalInline;
memcpy( _origCode, ptr, _origSize );
}
else
{
SET_JUMP( old, src );
_callOriginal = _origCode;
}
}
/// <summary>
/// Exception handler
/// </summary>
/// <param name="excpt">Exception information</param>
/// <returns>Exception disposition</returns>
LONG NTAPI DetourBase::VectoredHandler( PEXCEPTION_POINTERS excpt )
{
switch (excpt->ExceptionRecord->ExceptionCode)
{
case static_cast<DWORD>(EXCEPTION_BREAKPOINT):
return Int3Handler( excpt );
case static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION):
return AVHandler( excpt );
case static_cast<DWORD>(EXCEPTION_SINGLE_STEP):
return StepHandler( excpt );
default:
return EXCEPTION_CONTINUE_SEARCH;
}
}
/// <summary>
/// Int3 exception handler
/// </summary>
/// <param name="excpt">Exception information</param>
/// <returns>Exception disposition</returns>
LONG NTAPI DetourBase::Int3Handler( PEXCEPTION_POINTERS excpt )
{
if (_breakpoints.count( excpt->ExceptionRecord->ExceptionAddress ))
{
DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress];
((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst;
excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler;
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
/// <summary>
/// Access violation handler
/// </summary>
/// <param name="excpt">Exception information</param>
/// <returns>Exception disposition</returns>
LONG NTAPI DetourBase::AVHandler( PEXCEPTION_POINTERS /*excpt*/ )
{
return EXCEPTION_CONTINUE_SEARCH;
}
/// <summary>
/// Single step exception handler
/// </summary>
/// <param name="excpt">Exception information</param>
/// <returns>Exception disposition</returns>
LONG NTAPI DetourBase::StepHandler( PEXCEPTION_POINTERS excpt )
{
DWORD index = 0;
int found = _BitScanForward( &index, static_cast<DWORD>(excpt->ContextRecord->Dr6) );
if (found != 0 && index < 4 && _breakpoints.count( excpt->ExceptionRecord->ExceptionAddress ))
{
DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress];
// Disable breakpoint at current index
BitTestAndResetT( (LONG_PTR*)&excpt->ContextRecord->Dr7, 2 * index );
((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst;
excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler;
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
} | 28.085271 | 112 | 0.616202 | wafflehammer |
d52a8639b282d5cb9e6c66ba5def09ad823af4b9 | 3,195 | cpp | C++ | csr_uint.cpp | LazyShion/ScaleSCAN | af553f88209e2f1ceb7be93dd349d380a4196e43 | [
"MIT"
] | null | null | null | csr_uint.cpp | LazyShion/ScaleSCAN | af553f88209e2f1ceb7be93dd349d380a4196e43 | [
"MIT"
] | null | null | null | csr_uint.cpp | LazyShion/ScaleSCAN | af553f88209e2f1ceb7be93dd349d380a4196e43 | [
"MIT"
] | 1 | 2021-11-22T16:33:50.000Z | 2021-11-22T16:33:50.000Z | #include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<cstdlib>
#include<algorithm>
#include<set>
#define CH printf("check!!\n");
using namespace std;
int main(int argc,char *argv[])
{
ifstream infile1(argv[1]);
ofstream outfile(argv[2],ios_base::out | ios_base::binary);
string str1,str2;
unsigned int node1,node2;
map<unsigned int , unsigned int> mp2;
unsigned int node_count;
node_count = 0;
unsigned int index_size = 0;
cout << "create_node_number_map" << endl;
while(getline(infile1,str1,'\t')){
getline(infile1,str2);
node1 = atoi(str1.c_str());
node2 = atoi(str2.c_str());
if(node1 != node2){
if(mp2.find(node1) == mp2.end()){
mp2[node1] = node_count;
node_count++;
}
index_size++;
if(mp2.find(node2) == mp2.end()){
mp2[node2] = node_count;
node_count++;
}
}
}
ifstream infile2(argv[1]);
unsigned int *edge_list = new unsigned int[index_size*2];
unsigned int edge_count = 0;
cout << "create_edge_list" << endl;
while(getline(infile2,str1,'\t')){
getline(infile2,str2);
node1 = atoi(str1.c_str());
node2 = atoi(str2.c_str());
if(node1 != node2){
edge_list[edge_count] = mp2[node1];
edge_count++;
edge_list[edge_count] = mp2[node2];
edge_count++;
}
}
mp2.clear();
unsigned int c = 0;
unsigned int *node = new unsigned int[node_count + 1];
node[0] = 0;
ofstream log("logfile.txt",ios_base::out | ios_base::binary);
cout << "create_node_array" << endl;
while(c < node_count){
map<unsigned int,set<unsigned int>> mp;
unsigned int c0 = c;
unsigned int c2 = c+100000;
if(c2 >= node_count){
c2 = node_count;
}
for(unsigned int i = 0;i < index_size*2;i+=2){
if(c <= edge_list[i] && edge_list[i] < c2){
mp[edge_list[i]].insert(edge_list[i+1]);
}
if(c <= edge_list[i+1] && edge_list[i+1] < c2){
mp[edge_list[i+1]].insert(edge_list[i]);
}
}
while(c<c2){
unsigned int index = mp[c].size();
node[c+1] = node[c] + index;
c++;
}
unsigned int edgesize = node[c] - node[c0];
cout << edgesize << endl;
unsigned int *edge_log = new unsigned int[edgesize];
unsigned int n = 0;
// cout << "aaa" << endl;
while(c0 < c2){
for(auto itr = mp[c0].begin();itr != mp[c0].end();++itr){
edge_log[n] = *itr;
n++;
}
c0++;
}
log.write((const char*)&edge_log[0],sizeof(unsigned int)*edgesize);
delete[] edge_log;
mp.clear();
}
cout << "write_file" << endl;
unsigned int node_total = node_count + 1;
unsigned int edge_total = node[node_count];
outfile.write((const char*)&node_count,sizeof(int));
outfile.write((const char*)&edge_total,sizeof(int));
outfile.write((const char*)&node[0],sizeof(int)*(node_total));
delete[] node;
ifstream infile3("logfile.txt",ios_base::in | ios_base::binary);
unsigned int *edge = new unsigned int[edge_total];
infile3.read((char*)&edge[0],sizeof(int)*(edge_total));
outfile.write((const char*)(edge),sizeof(int)*(edge_total));
log.close();
remove("logfile.txt");
}
| 23.492647 | 71 | 0.600939 | LazyShion |
d52ba182a9c2333b3469ec0a46922d3f0c6a6a4c | 250 | cpp | C++ | test/unit/math/mix/fun/log1m_test.cpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | test/unit/math/mix/fun/log1m_test.cpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | test/unit/math/mix/fun/log1m_test.cpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-05-10T12:55:07.000Z | 2020-05-10T12:55:07.000Z | #include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, log1m) {
auto f = [](const auto& x1) { return stan::math::log1m(x1); };
stan::test::expect_common_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, -21.5, -21, -1, 0.9, 3);
}
| 31.25 | 65 | 0.672 | bayesmix-dev |
d52ec5d95e092e53994be0f0e575ee1eb387cb9d | 22,717 | cpp | C++ | src/RayTracer/RayTracer.cpp | yuphin/Lumen | a210b5a923b684ed1fc6f047544b82af4fdfe2db | [
"MIT"
] | 1 | 2022-01-07T21:25:53.000Z | 2022-01-07T21:25:53.000Z | src/RayTracer/RayTracer.cpp | yuphin/Lumen | a210b5a923b684ed1fc6f047544b82af4fdfe2db | [
"MIT"
] | null | null | null | src/RayTracer/RayTracer.cpp | yuphin/Lumen | a210b5a923b684ed1fc6f047544b82af4fdfe2db | [
"MIT"
] | null | null | null | #include "LumenPCH.h"
#include <regex>
#include <stb_image.h>
#define TINYEXR_IMPLEMENTATION
#include <zlib.h>
#include <tinyexr.h>
#define TINYGLTF_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define TINYOBJLOADER_IMPLEMENTATION
#include "RayTracer.h"
RayTracer* RayTracer::instance = nullptr;
static void fb_resize_callback(GLFWwindow* window, int width, int height) {
auto app = reinterpret_cast<RayTracer*>(glfwGetWindowUserPointer(window));
app->resized = true;
}
RayTracer::RayTracer(int width, int height, bool debug, int argc, char* argv[])
: LumenInstance(width, height, debug) {
this->instance = this;
parse_args(argc, argv);
}
void RayTracer::init(Window* window) {
srand((uint32_t)time(NULL));
this->window = window;
vkb.ctx.window_ptr = window->get_window_ptr();
glfwSetFramebufferSizeCallback(vkb.ctx.window_ptr, fb_resize_callback);
// Init with ray tracing extensions
vkb.add_device_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
vkb.add_device_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME);
vkb.add_device_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
vkb.add_device_extension(VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME);
vkb.add_device_extension(VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME);
vkb.add_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
vkb.create_instance();
if (vkb.enable_validation_layers) {
vkb.setup_debug_messenger();
}
vkb.create_surface();
vkb.pick_physical_device();
vkb.create_logical_device();
vkb.create_swapchain();
create_default_render_pass(vkb.ctx);
vkb.create_framebuffers(vkb.ctx.default_render_pass);
vkb.create_command_pool();
vkb.create_command_buffers();
vkb.create_sync_primitives();
initialized = true;
scene.load_scene(scene_name);
switch (scene.config.integrator_type) {
case IntegratorType::Path :
integrator = std::make_unique<Path>(this, &scene);
break;
case IntegratorType::BDPT:
integrator = std::make_unique<BDPT>(this, &scene);
break;
case IntegratorType::SPPM:
integrator = std::make_unique<SPPM>(this, &scene);
break;
case IntegratorType::VCM:
integrator = std::make_unique<VCM>(this, &scene);
break;
case IntegratorType::PSSMLT:
integrator = std::make_unique<PSSMLT>(this, &scene);
break;
case IntegratorType::SMLT:
integrator = std::make_unique<SMLT>(this, &scene);
break;
case IntegratorType::VCMMLT:
integrator = std::make_unique<VCMMLT>(this, &scene);
break;
case IntegratorType::ReSTIR:
integrator = std::make_unique<ReSTIR>(this, &scene);
break;
case IntegratorType::ReSTIRGI:
integrator = std::make_unique<ReSTIRGI>(this, &scene);
break;
case IntegratorType::DDGI:
integrator = std::make_unique<DDGI>(this, &scene);
break;
default:
break;
}
integrator->init();
init_resources();
create_post_descriptor();
update_post_desc_set();
create_post_pipeline();
create_compute_pipelines();
init_imgui();
VkPhysicalDeviceMemoryProperties2 props = {};
props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2;
VkPhysicalDeviceMemoryBudgetPropertiesEXT budget_props = {};
budget_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT;
props.pNext = &budget_props;
vkGetPhysicalDeviceMemoryProperties2(vk_ctx.physical_device, &props);
printf("Memory usage %f MB\n", budget_props.heapUsage[0] * 1e-6);
}
void RayTracer::update() {
if (instance->window->is_key_down(KeyInput::KEY_F10)) {
write_exr = true;
}
float frame_time = draw_frame();
cpu_avg_time = (1. - 1./ (cnt)) * cpu_avg_time + frame_time / (float)cnt;
cpu_avg_time = 0.95 * cpu_avg_time + 0.05 * frame_time;
integrator->update();
}
void RayTracer::render(uint32_t i) {
// Render image
integrator->render();
auto cmdbuf = vkb.ctx.command_buffers[i];
VkCommandBufferBeginInfo begin_info = vk::command_buffer_begin_info(
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
vk::check(vkBeginCommandBuffer(cmdbuf, &begin_info));
if (write_exr) {
// Copy to host visible storage buffer
{
VkBufferImageCopy region = {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageExtent.width = instance->width;
region.imageExtent.height = instance->height;
region.imageExtent.depth = 1;
transition_image_layout(cmdbuf, integrator->output_tex.img,
VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
output_img_buffer_cpu.handle, 1, ®ion);
transition_image_layout(cmdbuf, integrator->output_tex.img,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL);
}
}
if (calc_rmse && has_gt) {
// Calculate RMSE
{
VkBufferImageCopy region = {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageExtent.width = instance->width;
region.imageExtent.height = instance->height;
region.imageExtent.depth = 1;
transition_image_layout(cmdbuf, integrator->output_tex.img,
VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
output_img_buffer.handle, 1, ®ion);
auto barrier = buffer_barrier(output_img_buffer.handle,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT);
vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_DEPENDENCY_BY_REGION_BIT, 0, 0, 1, &barrier, 0, 0);
// Calculate and reduce
{
vkCmdBindDescriptorSets(
cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, calc_rmse_pipeline->pipeline_layout,
0, 1, &post_desc_set, 0, nullptr);
vkCmdBindDescriptorSets(
cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, reduce_rmse_pipeline->pipeline_layout,
0, 1, &post_desc_set, 0, nullptr);
vkCmdBindDescriptorSets(
cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, output_rmse_pipeline->pipeline_layout,
0, 1, &post_desc_set, 0, nullptr);
vkCmdPushConstants(cmdbuf, calc_rmse_pipeline->pipeline_layout,
VK_SHADER_STAGE_COMPUTE_BIT,
0, sizeof(PostPC), &post_pc);
vkCmdPushConstants(cmdbuf, reduce_rmse_pipeline->pipeline_layout,
VK_SHADER_STAGE_COMPUTE_BIT,
0, sizeof(PostPC), &post_pc);
vkCmdPushConstants(cmdbuf, output_rmse_pipeline->pipeline_layout,
VK_SHADER_STAGE_COMPUTE_BIT,
0, sizeof(PostPC), &post_pc);
reduce(cmdbuf, residual_buffer, counter_buffer, *calc_rmse_pipeline, *reduce_rmse_pipeline,
instance->width * instance->height);
vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE,
output_rmse_pipeline->handle);
auto num_wgs = 1;
vkCmdDispatch(cmdbuf, num_wgs, 1, 1);
transition_image_layout(cmdbuf, integrator->output_tex.img,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL);
}
}
}
// Apply Post FX and present
VkClearValue clear_color = { 0.25f, 0.25f, 0.25f, 1.0f };
VkClearValue clear_depth = { 1.0f, 0 };
VkViewport viewport = vk::viewport((float)width, (float)height, 0.0f, 1.0f);
VkClearValue clear_values[] = { clear_color, clear_depth };
VkRenderPassBeginInfo post_rpi{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
post_rpi.clearValueCount = 2;
post_rpi.pClearValues = clear_values;
post_rpi.renderPass = vkb.ctx.default_render_pass;
post_rpi.framebuffer = vkb.ctx.swapchain_framebuffers[i];
post_rpi.renderArea = { {0, 0}, vkb.ctx.swapchain_extent };
pc_post_settings.enable_tonemapping = settings.enable_tonemapping;
vkCmdBeginRenderPass(cmdbuf, &post_rpi, VK_SUBPASS_CONTENTS_INLINE);
vkCmdSetViewport(cmdbuf, 0, 1, &viewport);
VkRect2D scissor = vk::rect2D(width, height, 0, 0);
vkCmdSetScissor(cmdbuf, 0, 1, &scissor);
vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS,
post_pipeline->handle);
vkCmdBindDescriptorSets(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS,
post_pipeline_layout, 0, 1, &post_desc_set, 0,
nullptr);
vkCmdPushConstants(cmdbuf, post_pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(PushConstantPost), &pc_post_settings);
vkCmdDraw(cmdbuf, 3, 1, 0, 0);
ImGui::Render();
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmdbuf);
vkCmdEndRenderPass(cmdbuf);
VkClearColorValue val = { 0,0,0,1 };
VkImageSubresourceRange range;
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseMipLevel = 0;
range.levelCount = 1;
range.baseArrayLayer = 0;
range.layerCount = 1;
vk::check(vkEndCommandBuffer(cmdbuf), "Failed to record command buffer");
}
float RayTracer::draw_frame() {
if (cnt == 0) {
start = clock();
}
auto t_begin = glfwGetTime() * 1000;
bool updated = false;
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Text("Frame time %f ms ( %f FPS )", cpu_avg_time,
1000 / cpu_avg_time);
if (ImGui::Button("Reload shaders")) {
integrator->reload();
updated |= true;
}
bool gui_updated = integrator->gui();
updated |=
ImGui::Checkbox("Enable ACES tonemapping", &settings.enable_tonemapping);
if (updated || gui_updated) {
ImGui::Render();
auto t_end = glfwGetTime() * 1000;
auto t_diff = t_end - t_begin;
integrator->updated = true;
return (float)t_diff;
}
ImGui::Checkbox("Show camera statistics", &show_cam_stats);
if (show_cam_stats) {
ImGui::PushItemWidth(170);
ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[0]), 0.05f);
ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[1]), 0.05f);
ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[2]), 0.05f);
ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[3]), 0.05f);
}
uint32_t image_idx = vkb.prepare_frame();
if (image_idx == UINT32_MAX) {
auto t_end = glfwGetTime() * 1000;
auto t_diff = t_end - t_begin;
return (float)t_diff;
}
render(image_idx);
vkb.submit_frame(image_idx, resized);
auto now = clock();
auto diff = ((float)now - start);
if (write_exr) {
write_exr = false;
save_exr((float*)output_img_buffer_cpu.data, instance->width, instance->height,
"out.exr");
}
bool time_limit = (abs(diff / CLOCKS_PER_SEC - 5)) < 0.1;
//calc_rmse = cnt % 30 == 0 || time_limit;
//calc_rmse = time_limit;
//bool t2 = (abs(diff / CLOCKS_PER_SEC - 10.0)) < 0.1;
//if (t2) {
// printf("Go!\n");
// t2 = false;
//}
//printf("Time %f\n", diff / CLOCKS_PER_SEC);
//calc_rmse = true;
//write_exr = time_limit;
if (calc_rmse && has_gt) {
float rmse = *(float*)rmse_val_buffer.data;
printf("%RMSE: %f - %f\n", rmse * 1e6, diff);
}
auto t_end = glfwGetTime() * 1000;
auto t_diff = t_end - t_begin;
cnt++;
return (float)t_diff;
}
void RayTracer::create_post_descriptor() {
constexpr int OUTPUT_COLOR_BINDING = 0;
constexpr int POST_DESC_BINDING = 1;
std::vector<VkDescriptorPoolSize> pool_sizes = {
vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1),
vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), };
auto descriptor_pool_ci =
vk::descriptor_pool_CI(pool_sizes.size(), pool_sizes.data(), 1);
vk::check(vkCreateDescriptorPool(vkb.ctx.device, &descriptor_pool_ci,
nullptr, &post_desc_pool),
"Failed to create descriptor pool");
std::vector<VkDescriptorSetLayoutBinding> set_layout_bindings = {
vk::descriptor_set_layout_binding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT, OUTPUT_COLOR_BINDING),
vk::descriptor_set_layout_binding(
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT, POST_DESC_BINDING),
};
auto set_layout_ci = vk::descriptor_set_layout_CI(
set_layout_bindings.data(), set_layout_bindings.size());
vk::check(vkCreateDescriptorSetLayout(vkb.ctx.device, &set_layout_ci,
nullptr, &post_desc_layout),
"Failed to create descriptor set layout");
auto set_allocate_info =
vk::descriptor_set_allocate_info(post_desc_pool, &post_desc_layout, 1);
vk::check(vkAllocateDescriptorSets(vkb.ctx.device, &set_allocate_info,
&post_desc_set),
"Failed to allocate descriptor sets");
}
void RayTracer::update_post_desc_set() {
std::array<VkWriteDescriptorSet, 2> sets = {
vk::write_descriptor_set(
post_desc_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0,
&integrator->output_tex.descriptor_image_info),
vk::write_descriptor_set(
post_desc_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1,
&post_desc_buffer.descriptor)
};
vkUpdateDescriptorSets(vkb.ctx.device, sets.size(), sets.data(), 0, nullptr);
}
void RayTracer::create_post_pipeline() {
GraphicsPipelineSettings post_settings;
VkPipelineLayoutCreateInfo create_info{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
create_info.setLayoutCount = 1;
create_info.pSetLayouts = &post_desc_layout;
create_info.pushConstantRangeCount = 1;
VkPushConstantRange pc_range = {
VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstantPost)
};
create_info.pPushConstantRanges = &pc_range;
vkCreatePipelineLayout(vkb.ctx.device, &create_info, nullptr,
&post_pipeline_layout);
post_settings.pipeline_layout = post_pipeline_layout;
post_settings.render_pass = vkb.ctx.default_render_pass;
post_settings.shaders = { {"src/shaders/post.vert"},
{"src/shaders/post.frag"} };
for (auto& shader : post_settings.shaders) {
if (shader.compile()) {
LUMEN_ERROR("Shader compilation failed");
}
}
post_settings.cull_mode = VK_CULL_MODE_NONE;
post_settings.enable_tracking = false;
post_settings.dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR };
post_pipeline = std::make_unique<Pipeline>(vkb.ctx.device);
post_pipeline->create_gfx_pipeline(post_settings);
}
void RayTracer::create_compute_pipelines() {
calc_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device);
reduce_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device);
output_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device);
std::vector<Shader> shaders = {
{"src/shaders/rmse/calc_rmse.comp"},
{"src/shaders/rmse/reduce_rmse.comp"},
{"src/shaders/rmse/output_rmse.comp"}
};
for (auto& shader : shaders) {
shader.compile();
}
ComputePipelineSettings settings;
settings.desc_set_layouts = &post_desc_layout;
settings.desc_set_layout_cnt = 1;
settings.push_const_size = sizeof(PostPC);
settings.shader = shaders[0];
calc_rmse_pipeline->create_compute_pipeline(settings);
settings.shader = shaders[1];
reduce_rmse_pipeline->create_compute_pipeline(settings);
settings.shader = shaders[2];
output_rmse_pipeline->create_compute_pipeline(settings);
}
void RayTracer::init_imgui() {
VkDescriptorPoolSize pool_sizes[] = {
{VK_DESCRIPTOR_TYPE_SAMPLER, 1000},
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000},
{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000},
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000},
{VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000},
{VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000},
{VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000} };
VkDescriptorPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
pool_info.maxSets = 1000;
pool_info.poolSizeCount = (uint32_t)std::size(pool_sizes);
pool_info.pPoolSizes = pool_sizes;
vk::check(vkCreateDescriptorPool(vkb.ctx.device, &pool_info, nullptr,
&imgui_pool));
IMGUI_CHECKVERSION();
ImGui::CreateContext();
// Setup Platform/Renderer backends
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForVulkan(window->get_window_ptr(), true);
ImGui_ImplVulkan_InitInfo init_info = {};
init_info.Instance = vkb.ctx.instance;
init_info.PhysicalDevice = vkb.ctx.physical_device;
init_info.Device = vkb.ctx.device;
init_info.Queue = vkb.ctx.queues[(int)QueueType::GFX];
init_info.DescriptorPool = imgui_pool;
init_info.MinImageCount = 2;
init_info.ImageCount = 2;
init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
ImGui_ImplVulkan_Init(&init_info, vkb.ctx.default_render_pass);
CommandBuffer cmd(&vkb.ctx, true);
ImGui_ImplVulkan_CreateFontsTexture(cmd.handle);
cmd.submit(vkb.ctx.queues[(int)QueueType::GFX]);
ImGui_ImplVulkan_DestroyFontUploadObjects();
}
void RayTracer::init_resources() {
PostDesc desc;
output_img_buffer.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE,
instance->width * instance->height * 4 * 4
);
output_img_buffer_cpu.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_SHARING_MODE_EXCLUSIVE,
instance->width * instance->height * 4 * 4
);
residual_buffer.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE,
instance->width * instance->height * 4
);
counter_buffer.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE,
sizeof(int)
);
rmse_val_buffer.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_SHARING_MODE_EXCLUSIVE,
sizeof(float)
);
if (load_exr) {
// Load the ground truth image
const char* img_name = "out.exr";
float* data;
int width;
int height;
const char* err = nullptr;
int ret = LoadEXR(&data, &width, &height, img_name, &err);
if (ret != TINYEXR_SUCCESS) {
if (err) {
fprintf(stderr, "ERR : %s\n", err);
FreeEXRErrorMessage(err); // release memory of error message.
}
} else {
std::vector<vec4> pixels;
int img_res = width * height;
pixels.resize(img_res);
for (int i = 0; i < img_res; i++) {
pixels[i].x = data[4 * i + 0];
pixels[i].y = data[4 * i + 1];
pixels[i].z = data[4 * i + 2];
pixels[i].w = 1.;
}
auto gt_size = pixels.size() * 4 * 4;
gt_img_buffer.create(
&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE,
gt_size,
pixels.data(),
true
);
desc.gt_img_addr = gt_img_buffer.get_device_address();
has_gt = true;
}
if (has_gt) {
free(data);
}
}
desc.out_img_addr = output_img_buffer.get_device_address();
desc.residual_addr = residual_buffer.get_device_address();
desc.counter_addr = counter_buffer.get_device_address();
desc.rmse_val_addr = rmse_val_buffer.get_device_address();
post_desc_buffer.create(&instance->vkb.ctx,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
VK_SHARING_MODE_EXCLUSIVE, sizeof(PostDesc),
&desc, true);
post_pc.size = instance->width * instance->height;
}
void RayTracer::parse_args(int argc, char* argv[]){
scene_name = "scenes/caustics.json";
std::regex fn("(.*).(.json|.xml)");
for (int i = 0; i < argc; i++) {
if (std::regex_match(argv[i], fn)) {
scene_name = argv[i];
}
}
}
void RayTracer::save_exr(const float* rgb, int width, int height, const char* outfilename) {
EXRHeader header;
InitEXRHeader(&header);
EXRImage image;
InitEXRImage(&image);
image.num_channels = 3;
std::vector<float> images[3];
images[0].resize(width * height);
images[1].resize(width * height);
images[2].resize(width * height);
// Split RGBRGBRGB... into R, G and B layer
for (int i = 0; i < width * height; i++) {
images[0][i] = rgb[4 * i + 0];
images[1][i] = rgb[4 * i + 1];
images[2][i] = rgb[4 * i + 2];
}
float* image_ptr[3];
image_ptr[0] = &(images[2].at(0)); // B
image_ptr[1] = &(images[1].at(0)); // G
image_ptr[2] = &(images[0].at(0)); // R
image.images = (unsigned char**)image_ptr;
image.width = width;
image.height = height;
header.num_channels = 3;
header.channels = (EXRChannelInfo*)malloc(sizeof(EXRChannelInfo) * header.num_channels);
// Must be (A)BGR order, since most of EXR viewers expect this channel order.
strncpy_s(header.channels[0].name, "B", 255); header.channels[0].name[strlen("B")] = '\0';
strncpy_s(header.channels[1].name, "G", 255); header.channels[1].name[strlen("G")] = '\0';
strncpy_s(header.channels[2].name, "R", 255); header.channels[2].name[strlen("R")] = '\0';
header.pixel_types = (int*)malloc(sizeof(int) * header.num_channels);
header.requested_pixel_types = (int*)malloc(sizeof(int) * header.num_channels);
for (int i = 0; i < header.num_channels; i++) {
header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // pixel type of output image to be stored in .EXR
}
const char* err = NULL; // or nullptr in C++11 or later.
int ret = SaveEXRImageToFile(&image, &header, outfilename, &err);
if (ret != TINYEXR_SUCCESS) {
fprintf(stderr, "Save EXR err: %s\n", err);
FreeEXRErrorMessage(err); // free's buffer for an error message
}
printf("Saved exr file. [ %s ] \n", outfilename);
free(header.channels);
free(header.pixel_types);
free(header.requested_pixel_types);
}
void RayTracer::cleanup() {
const auto device = vkb.ctx.device;
vkDeviceWaitIdle(device);
if (initialized) {
vkDestroyDescriptorSetLayout(device, post_desc_layout, nullptr);
vkDestroyDescriptorPool(device, post_desc_pool, nullptr);
vkDestroyDescriptorPool(device, imgui_pool, nullptr);
vkDestroyPipelineLayout(device, post_pipeline_layout, nullptr);
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
gt_img_buffer.destroy();
output_img_buffer.destroy();
integrator->destroy();
post_pipeline->cleanup();
vkb.cleanup();
}
}
| 34.842025 | 110 | 0.74693 | yuphin |
d52fe3d5cf2a04ed0a8620de3137866eaebdb5dc | 19,044 | cpp | C++ | Source/Diagnostics/Diagnostics.cpp | PhilMiller/WarpX | 66b01e54771322eae7a7f0ccd697c599452fbd88 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Diagnostics/Diagnostics.cpp | PhilMiller/WarpX | 66b01e54771322eae7a7f0ccd697c599452fbd88 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Diagnostics/Diagnostics.cpp | PhilMiller/WarpX | 66b01e54771322eae7a7f0ccd697c599452fbd88 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "Diagnostics.H"
#include "Diagnostics/ComputeDiagFunctors/ComputeDiagFunctor.H"
#include "ComputeDiagFunctors/BackTransformParticleFunctor.H"
#include "Diagnostics/FlushFormats/FlushFormat.H"
#include "Diagnostics/ParticleDiag/ParticleDiag.H"
#include "FlushFormats/FlushFormatAscent.H"
#include "FlushFormats/FlushFormatCheckpoint.H"
#ifdef WARPX_USE_OPENPMD
# include "FlushFormats/FlushFormatOpenPMD.H"
#endif
#include "FlushFormats/FlushFormatPlotfile.H"
#include "FlushFormats/FlushFormatSensei.H"
#include "Particles/MultiParticleContainer.H"
#include "Parallelization/WarpXCommUtil.H"
#include "Utils/TextMsg.H"
#include "Utils/WarpXAlgorithmSelection.H"
#include "Utils/WarpXProfilerWrapper.H"
#include "Utils/WarpXUtil.H"
#include "WarpX.H"
#include <AMReX.H>
#include <AMReX_BLassert.H>
#include <AMReX_Config.H>
#include <AMReX_Geometry.H>
#include <AMReX_MultiFab.H>
#include <AMReX_ParallelDescriptor.H>
#include <AMReX_ParmParse.H>
#include <AMReX_Print.H>
#include <AMReX_Vector.H>
#include <algorithm>
#include <string>
using namespace amrex::literals;
Diagnostics::Diagnostics (int i, std::string name)
: m_diag_name(name), m_diag_index(i)
{
}
Diagnostics::~Diagnostics ()
{
}
bool
Diagnostics::BaseReadParameters ()
{
auto & warpx = WarpX::GetInstance();
amrex::ParmParse pp_diag_name(m_diag_name);
m_file_prefix = "diags/" + m_diag_name;
pp_diag_name.query("file_prefix", m_file_prefix);
queryWithParser(pp_diag_name, "file_min_digits", m_file_min_digits);
pp_diag_name.query("format", m_format);
pp_diag_name.query("dump_last_timestep", m_dump_last_timestep);
amrex::ParmParse pp_geometry("geometry");
std::string dims;
pp_geometry.get("dims", dims);
// Query list of grid fields to write to output
bool varnames_specified = pp_diag_name.queryarr("fields_to_plot", m_varnames_fields);
if (!varnames_specified){
if( dims == "RZ" and m_format == "openpmd" ) {
m_varnames_fields = {"Er", "Et", "Ez", "Br", "Bt", "Bz", "jr", "jt", "jz"};
}
else {
m_varnames_fields = {"Ex", "Ey", "Ez", "Bx", "By", "Bz", "jx", "jy", "jz"};
}
}
// Sanity check if user requests to plot phi
if (WarpXUtilStr::is_in(m_varnames_fields, "phi")){
WARPX_ALWAYS_ASSERT_WITH_MESSAGE(
warpx.do_electrostatic==ElectrostaticSolverAlgo::LabFrame,
"plot phi only works if do_electrostatic = labframe");
}
// Sanity check if user requests to plot F
if (WarpXUtilStr::is_in(m_varnames_fields, "F")){
WARPX_ALWAYS_ASSERT_WITH_MESSAGE(
warpx.do_dive_cleaning,
"plot F only works if warpx.do_dive_cleaning = 1");
}
// G can be written to file only if WarpX::do_divb_cleaning = 1
if (WarpXUtilStr::is_in(m_varnames_fields, "G"))
{
WARPX_ALWAYS_ASSERT_WITH_MESSAGE(
warpx.do_divb_cleaning, "G can be written to file only if warpx.do_divb_cleaning = 1");
}
// If user requests to plot proc_number for a serial run,
// delete proc_number from fields_to_plot
if (amrex::ParallelDescriptor::NProcs() == 1){
m_varnames_fields.erase(
std::remove(m_varnames_fields.begin(), m_varnames_fields.end(), "proc_number"),
m_varnames_fields.end());
}
// Get names of particle quantities to average at each grid point
const bool pfield_varnames_specified = pp_diag_name.queryarr("particle_fields_to_plot", m_pfield_varnames);
if (!pfield_varnames_specified){
m_pfield_varnames = {};
}
#ifdef WARPX_DIM_RZ
if (m_pfield_varnames.size() != 0) {
amrex::Abort("Input error: cannot use particle_fields_to_plot not implemented for RZ");
}
#endif
// Get parser strings for particle fields and generate map of parsers
std::string parser_str;
std::string filter_parser_str = "";
bool do_parser_filter;
amrex::ParmParse pp_diag_pfield(m_diag_name + ".particle_fields");
for (const auto& var : m_pfield_varnames) {
Store_parserString(pp_diag_pfield, (var + "(x,y,z,ux,uy,uz)").c_str(), parser_str);
if (parser_str != "") {
m_pfield_strings.insert({var, parser_str});
}
else {
amrex::Abort("Input error: cannot find parser string for " + var + "." +
m_diag_name + ".particle_fields." + var + " in file");
}
// Look for and record filter functions. If one is not found, the empty string will be
// stored as the filter string, and will be ignored.
do_parser_filter = pp_diag_pfield.query((var + ".filter(x,y,z,ux,uy,uz)").c_str(), filter_parser_str);
m_pfield_dofilter.insert({var, do_parser_filter});
m_pfield_filter_strings.insert({var, filter_parser_str});
}
// Names of all species in the simulation
m_all_species_names = warpx.GetPartContainer().GetSpeciesNames();
// Get names of species to average at each grid point
const bool pfield_species_specified = pp_diag_name.queryarr("particle_fields_species", m_pfield_species);
if (!pfield_species_specified){
m_pfield_species = m_all_species_names;
}
// Check that species names specified in m_pfield_species are valid
bool p_species_name_is_wrong;
// Loop over all species specified above
for (const auto& species : m_pfield_species) {
// Boolean used to check if species name was misspelled
p_species_name_is_wrong = true;
// Loop over all species
for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) {
if (species == m_all_species_names[i]) {
// Store species index: will be used in ParticleReductionFunctor to calculate
// averages for this species
m_pfield_species_index.push_back(i);
p_species_name_is_wrong = false;
}
}
// If species name was misspelled, abort with error message
if (p_species_name_is_wrong) {
amrex::Abort("Input error: string " + species + " in " + m_diag_name +
".particle_fields_species does not match any species");
}
}
m_varnames = m_varnames_fields;
// Generate names of averaged particle fields and append to m_varnames
for (int ivar=0; ivar<m_pfield_varnames.size(); ivar++) {
for (int ispec=0; ispec < int(m_pfield_species.size()); ispec++) {
m_varnames.push_back(m_pfield_varnames[ivar] + '_' + m_pfield_species[ispec]);
}
}
// Read user-defined physical extents for the output and store in m_lo and m_hi.
m_lo.resize(AMREX_SPACEDIM);
m_hi.resize(AMREX_SPACEDIM);
bool lo_specified = queryArrWithParser(pp_diag_name, "diag_lo", m_lo, 0, AMREX_SPACEDIM);
if (!lo_specified) {
for (int idim=0; idim < AMREX_SPACEDIM; ++idim) {
m_lo[idim] = warpx.Geom(0).ProbLo(idim);
}
}
bool hi_specified = queryArrWithParser(pp_diag_name, "diag_hi", m_hi, 0, AMREX_SPACEDIM);
if (!hi_specified) {
for (int idim =0; idim < AMREX_SPACEDIM; ++idim) {
m_hi[idim] = warpx.Geom(0).ProbHi(idim);
}
}
// For a moving window simulation, the user-defined m_lo and m_hi must be converted.
if (warpx.do_moving_window) {
#if defined(WARPX_DIM_3D)
amrex::Vector<int> dim_map {0, 1, 2};
#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ)
amrex::Vector<int> dim_map {0, 2};
#else
amrex::Vector<int> dim_map {2};
#endif
if (warpx.boost_direction[ dim_map[warpx.moving_window_dir] ] == 1) {
// Convert user-defined lo and hi for diagnostics to account for boosted-frame
// simulations with moving window
amrex::Real convert_factor = 1._rt/(warpx.gamma_boost * (1._rt - warpx.beta_boost) );
// Assuming that the window travels with speed c
m_lo[warpx.moving_window_dir] *= convert_factor;
m_hi[warpx.moving_window_dir] *= convert_factor;
}
}
// Initialize cr_ratio with default value of 1 for each dimension.
amrex::Vector<int> cr_ratio(AMREX_SPACEDIM, 1);
// Read user-defined coarsening ratio for the output MultiFab.
bool cr_specified = queryArrWithParser(pp_diag_name, "coarsening_ratio", cr_ratio, 0, AMREX_SPACEDIM);
if (cr_specified) {
for (int idim =0; idim < AMREX_SPACEDIM; ++idim) {
m_crse_ratio[idim] = cr_ratio[idim];
}
}
// Names of species to write to output
bool species_specified = pp_diag_name.queryarr("species", m_output_species_names);
// Auxiliary variables
std::string species;
bool species_name_is_wrong;
// Loop over all fields stored in m_varnames
for (const auto& var : m_varnames) {
// Check if m_varnames contains a string of the form rho_<species_name>
if (var.rfind("rho_", 0) == 0) {
// Extract species name from the string rho_<species_name>
species = var.substr(var.find("rho_") + 4);
// Boolean used to check if species name was misspelled
species_name_is_wrong = true;
// Loop over all species
for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) {
// Check if species name extracted from the string rho_<species_name>
// matches any of the species in the simulation
if (species == m_all_species_names[i]) {
// Store species index: will be used in RhoFunctor to dump
// rho for this species
m_rho_per_species_index.push_back(i);
species_name_is_wrong = false;
}
}
// If species name was misspelled, abort with error message
if (species_name_is_wrong) {
amrex::Abort("Input error: string " + var + " in " + m_diag_name +
".fields_to_plot does not match any species");
}
}
}
bool checkpoint_compatibility = false;
if (m_format == "checkpoint"){
if ( varnames_specified == false &&
pfield_varnames_specified == false &&
pfield_species_specified == false &&
lo_specified == false &&
hi_specified == false &&
cr_specified == false &&
species_specified == false ) checkpoint_compatibility = true;
}
return checkpoint_compatibility;
}
void
Diagnostics::InitData ()
{
// initialize member variables and arrays in base class::Diagnostics
InitBaseData();
// initialize member variables and arrays specific to each derived class
// (FullDiagnostics, BTDiagnostics, etc.)
DerivedInitData();
amrex::ParmParse pp_geometry("geometry");
std::string dims;
pp_geometry.get("dims", dims);
for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) {
// loop over all levels
// This includes full diagnostics and BTD as well as cell-center functors for BTD.
// Note that the cell-centered data for BTD is computed for all levels and hence
// the corresponding functor is also initialized for all the levels
for (int lev = 0; lev < nmax_lev; ++lev) {
// allocate and initialize m_all_field_functors depending on diag type
if (dims == "RZ" and m_format == "openpmd") {
InitializeFieldFunctorsRZopenPMD(lev);
} else {
InitializeFieldFunctors(lev);
}
}
// loop over the levels selected for output
// This includes all the levels for full diagnostics
// and only the coarse level (mother grid) for BTD
for (int lev = 0; lev < nlev_output; ++lev) {
// Initialize buffer data required for particle and/or fields
InitializeBufferData(i_buffer, lev);
}
}
amrex::ParmParse pp_diag_name(m_diag_name);
// default for writing species output is 1
int write_species = 1;
pp_diag_name.query("write_species", write_species);
if (write_species == 1) {
// When particle buffers, m_particle_boundary_buffer are included,
// they will be initialized here
InitializeParticleBuffer();
InitializeParticleFunctors();
}
if (write_species == 0) {
if (m_format == "checkpoint"){
amrex::Abort("For checkpoint format, write_species flag must be 1.");
}
// if user-defined value for write_species == 0, then clear species vector
for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) {
m_output_species.at(i_buffer).clear();
}
m_output_species_names.clear();
} else {
amrex::Vector <amrex::Real> dummy_val(AMREX_SPACEDIM);
if ( queryArrWithParser(pp_diag_name, "diag_lo", dummy_val, 0, AMREX_SPACEDIM) ||
queryArrWithParser(pp_diag_name, "diag_hi", dummy_val, 0, AMREX_SPACEDIM) ) {
// set geometry filter for particle-diags to true when the diagnostic domain-extent
// is specified by the user.
// Note that the filter is set for every ith snapshot, and the number of snapshots
// for full diagnostics is 1, while for BTD it is user-defined.
for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) {
for (auto& v : m_output_species.at(i_buffer)) {
v.m_do_geom_filter = true;
}
// Disabling particle-io for reduced domain diagnostics by reducing
// the particle-diag vector to zero.
// This is a temporary fix until particle_buffer is supported in diagnostics.
m_output_species.at(i_buffer).clear();
}
std::string warnMsg = "For full diagnostics on a reduced domain, particle I/O is not ";
warnMsg += "supported, yet! Therefore, particle I/O is disabled for this diagnostics: ";
warnMsg += m_diag_name;
WarpX::GetInstance().RecordWarning("Diagnostics", warnMsg);
}
}
}
void
Diagnostics::InitBaseData ()
{
auto & warpx = WarpX::GetInstance();
// Number of levels in the simulation at the current timestep
nlev = warpx.finestLevel() + 1;
// default number of levels to be output = nlev
nlev_output = nlev;
// Maximum number of levels that will be allocated in the simulation
nmax_lev = warpx.maxLevel() + 1;
m_all_field_functors.resize( nmax_lev );
// For restart, move the m_lo and m_hi of the diag consistent with the
// current moving_window location
if (warpx.do_moving_window) {
int moving_dir = warpx.moving_window_dir;
int shift_num_base = static_cast<int>((warpx.getmoving_window_x() - m_lo[moving_dir]) / warpx.Geom(0).CellSize(moving_dir) );
m_lo[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir);
m_hi[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir);
}
// Construct Flush class.
if (m_format == "plotfile"){
m_flush_format = std::make_unique<FlushFormatPlotfile>() ;
} else if (m_format == "checkpoint"){
// creating checkpoint format
m_flush_format = std::make_unique<FlushFormatCheckpoint>() ;
} else if (m_format == "ascent"){
m_flush_format = std::make_unique<FlushFormatAscent>();
} else if (m_format == "sensei"){
#ifdef AMREX_USE_SENSEI_INSITU
m_flush_format = std::make_unique<FlushFormatSensei>(
dynamic_cast<amrex::AmrMesh*>(const_cast<WarpX*>(&warpx)),
m_diag_name);
#else
amrex::Abort("To use SENSEI in situ, compile with USE_SENSEI=TRUE");
#endif
} else if (m_format == "openpmd"){
#ifdef WARPX_USE_OPENPMD
m_flush_format = std::make_unique<FlushFormatOpenPMD>(m_diag_name);
#else
amrex::Abort("To use openpmd output format, need to compile with USE_OPENPMD=TRUE");
#endif
} else {
amrex::Abort("unknown output format");
}
// allocate vector of buffers then allocate vector of levels for each buffer
m_mf_output.resize( m_num_buffers );
for (int i = 0; i < m_num_buffers; ++i) {
m_mf_output[i].resize( nmax_lev );
}
// allocate vector of geometry objects corresponding to each output multifab.
m_geom_output.resize( m_num_buffers );
for (int i = 0; i < m_num_buffers; ++i) {
m_geom_output[i].resize( nmax_lev );
}
// allocate vector of particle buffers
m_output_species.resize(m_num_buffers);
}
void
Diagnostics::ComputeAndPack ()
{
PrepareBufferData();
// prepare the field-data necessary to compute output data
PrepareFieldDataForOutput();
// Prepare the particle data necessary to compute output data
// Field-data is called first for BTD, since the z-slice location is used to prepare particle data
// to determine if the transform is to be done this step.
PrepareParticleDataForOutput();
auto & warpx = WarpX::GetInstance();
// compute the necessary fields and store result in m_mf_output.
for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) {
for(int lev=0; lev<nlev_output; lev++){
int icomp_dst = 0;
const auto n = static_cast<int>(m_all_field_functors[lev].size());
for (int icomp=0; icomp<n; icomp++){
// Call all functors in m_all_field_functors[lev]. Each of them computes
// a diagnostics and writes in one or more components of the output
// multifab m_mf_output[lev].
m_all_field_functors[lev][icomp]->operator()(m_mf_output[i_buffer][lev], icomp_dst, i_buffer);
// update the index of the next component to fill
icomp_dst += m_all_field_functors[lev][icomp]->nComp();
}
// Check that the proper number of components of mf_avg were updated.
AMREX_ALWAYS_ASSERT( icomp_dst == m_varnames.size() );
// needed for contour plots of rho, i.e. ascent/sensei
if (m_format == "sensei" || m_format == "ascent") {
WarpXCommUtil::FillBoundary(m_mf_output[i_buffer][lev], warpx.Geom(lev).periodicity());
}
}
// Call Particle functor
for (int isp = 0; isp < m_all_particle_functors.size(); ++isp) {
m_all_particle_functors[isp]->operator()(*m_particles_buffer[i_buffer][isp], m_totalParticles_in_buffer[i_buffer][isp], i_buffer);
}
}
UpdateBufferData();
}
void
Diagnostics::FilterComputePackFlush (int step, bool force_flush)
{
WARPX_PROFILE("Diagnostics::FilterComputePackFlush()");
MovingWindowAndGalileanDomainShift (step);
if ( DoComputeAndPack (step, force_flush) ) {
ComputeAndPack();
}
for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) {
if ( !DoDump (step, i_buffer, force_flush) ) continue;
Flush(i_buffer);
}
}
| 40.433121 | 142 | 0.646765 | PhilMiller |
d5333c8297dff93bb9e32e00f2dc3310dead2358 | 5,159 | cxx | C++ | resip/recon/UserAgentServerAuthManager.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | resip/recon/UserAgentServerAuthManager.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | resip/recon/UserAgentServerAuthManager.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #include <cassert>
#include "UserAgent.hxx"
#include "UserAgentServerAuthManager.hxx"
#include <resip/dum/DialogUsageManager.hxx>
#include <resip/dum/ServerAuthManager.hxx>
#include <resip/dum/UserAuthInfo.hxx>
#include <resip/dum/UserProfile.hxx>
#include <rutil/MD5Stream.hxx>
#include <rutil/WinLeakCheck.hxx>
#define RESIPROCATE_SUBSYSTEM Subsystem::RECON
using namespace recon;
using namespace resip;
UserAgentServerAuthManager::UserAgentServerAuthManager(UserAgent& userAgent) :
ServerAuthManager(userAgent.getDialogUsageManager(), userAgent.getDialogUsageManager().dumIncomingTarget()),
mUserAgent(userAgent)
{
}
UserAgentServerAuthManager::~UserAgentServerAuthManager()
{
}
bool
UserAgentServerAuthManager::useAuthInt() const
{
return true;
}
bool
UserAgentServerAuthManager::proxyAuthenticationMode() const
{
return false; // Challenge with 401
}
const Data&
UserAgentServerAuthManager::getChallengeRealm(const SipMessage& msg)
{
return mUserAgent.getIncomingConversationProfile(msg)->getDefaultFrom().uri().host();
}
bool
UserAgentServerAuthManager::isMyRealm(const Data& realm)
{
return true; // .slg. this means we will try to find credentials for any authorization headers
// could improve this by looking through all active conversation profiles to see if realm exists
}
bool
UserAgentServerAuthManager::authorizedForThisIdentity(const resip::Data &user,
const resip::Data &realm,
resip::Uri &fromUri)
{
return true; // We don't care who the request came from
}
ServerAuthManager::AsyncBool
UserAgentServerAuthManager::requiresChallenge(const SipMessage& msg)
{
assert(msg.isRequest());
ConversationProfile* profile = mUserAgent.getIncomingConversationProfile(msg).get();
// We want to challenge OOD Refer requests and Invite Requests with Auto-Answer indications
switch(msg.method())
{
case REFER:
if(profile->challengeOODReferRequests() && !msg.header(h_To).exists(p_tag))
{
// Don't challenge OOD Refer requests have a valid TargetDialog header
if(!msg.exists(h_TargetDialog) || mUserAgent.getDialogUsageManager().findInviteSession(msg.header(h_TargetDialog)).first == InviteSessionHandle::NotValid())
{
return True;
}
}
break;
case INVITE:
if(profile->challengeAutoAnswerRequests() && profile->shouldAutoAnswer(msg))
{
return True;
}
break;
default:
break;
}
// Default to not challenge
return False;
}
void
UserAgentServerAuthManager::requestCredential(const Data& user,
const Data& realm,
const SipMessage& msg,
const Auth& auth,
const Data& transactionId )
{
const UserProfile::DigestCredential& digestCredential =
mUserAgent.getIncomingConversationProfile(msg)->getDigestCredential(realm);
MD5Stream a1;
a1 << digestCredential.user
<< Symbols::COLON
<< digestCredential.realm
<< Symbols::COLON
<< digestCredential.password;
a1.flush();
UserAuthInfo* userAuthInfo = new UserAuthInfo(user,realm,a1.getHex(),transactionId);
mUserAgent.getDialogUsageManager().post( userAuthInfo );
}
/* ====================================================================
Copyright (c) 2007-2008, Plantronics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
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 Plantronics 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.
==================================================================== */
| 34.393333 | 165 | 0.686373 | dulton |
d53733bd8ae0d7c5652718dc3012ca238400ae83 | 9,224 | cpp | C++ | tools/converter/source/onnx/onnxOpConverter.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | tools/converter/source/onnx/onnxOpConverter.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | tools/converter/source/onnx/onnxOpConverter.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | //
// onnxOpConverter.cpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "onnxOpConverter.hpp"
#include "OpCount.hpp"
using namespace MNN;
static int32_t _limit(int64_t i64) {
if (i64 > (int64_t)(1 << 30)) {
return 1 << 30;
}
if (i64 < (int64_t)(-(1 << 30))) {
return (-(1 << 30));
}
return i64;
}
class DefaultonnxOpConverter : public onnxOpConverter {
public:
virtual void run(MNN::OpT* dstOp, const onnx::NodeProto* onnxNode,
std::vector<const onnx::TensorProto*> initializers) override {
auto extra = new ExtraT;
dstOp->main.type = OpParameter_Extra;
dstOp->main.value = extra;
extra->engine = "ONNX";
extra->type = onnxNode->op_type();
for (auto srcAttr : onnxNode->attribute()) {
std::unique_ptr<AttributeT> attr(new AttributeT);
attr->key = srcAttr.name();
switch (srcAttr.type()) {
case onnx::AttributeProto_AttributeType_INTS:
attr->list.reset(new ListValueT);
attr->list->i.resize(srcAttr.ints_size());
for (int i = 0; i < srcAttr.ints_size(); ++i) {
attr->list->i[i] = _limit(srcAttr.ints(i));
}
break;
case onnx::AttributeProto_AttributeType_FLOATS:
attr->list.reset(new ListValueT);
attr->list->f.resize(srcAttr.floats_size());
for (int i = 0; i < srcAttr.floats_size(); ++i) {
attr->list->f[i] = srcAttr.floats(i);
}
break;
case onnx::AttributeProto_AttributeType_TENSOR:
attr->tensor.reset(convertTensorToBlob(&srcAttr.t()));
break;
default:
break;
}
attr->i = _limit(srcAttr.i());
attr->s = srcAttr.s();
attr->f = srcAttr.f();
extra->attr.emplace_back(std::move(attr));
}
}
virtual MNN::OpParameter type() override {
return OpParameter_Extra;
}
virtual MNN::OpType opType() override {
return OpType_Extra;
}
};
onnxOpConverterSuit::onnxOpConverterSuit() {
}
onnxOpConverterSuit::~onnxOpConverterSuit() {
for (auto& iter : mConverterContainer) {
delete iter.second;
}
mConverterContainer.clear();
}
onnxOpConverterSuit* onnxOpConverterSuit::global = nullptr;
onnxOpConverterSuit* onnxOpConverterSuit::get() {
if (global == nullptr) {
global = new onnxOpConverterSuit;
}
return global;
}
void onnxOpConverterSuit::insert(onnxOpConverter* t, const char* name) {
MNN::OpCount::get()->insertOp("ONNX", std::string(name));
mConverterContainer.insert(std::make_pair(name, t));
}
onnxOpConverter* onnxOpConverterSuit::search(const std::string& name) {
auto iter = mConverterContainer.find(name);
if (iter == mConverterContainer.end()) {
static DefaultonnxOpConverter defaultConverter;
return &defaultConverter;
}
return iter->second;
}
MNN::DataType onnxOpConverter::convertDataType(::onnx::TensorProto_DataType type) {
static std::map<::onnx::TensorProto_DataType, MNN::DataType> dataTypeMap{
{onnx::TensorProto_DataType_FLOAT, MNN::DataType_DT_FLOAT},
{onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8},
{onnx::TensorProto_DataType_INT32, MNN::DataType_DT_INT32},
{onnx::TensorProto_DataType_INT64, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int64
{onnx::TensorProto_DataType_DOUBLE, MNN::DataType_DT_FLOAT}, // For compability, use float instead of double
{onnx::TensorProto_DataType_UINT8, MNN::DataType_DT_UINT8},
{onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8},
{onnx::TensorProto_DataType_BOOL, MNN::DataType_DT_INT32}, // For compability, use int32 instead of bool
{onnx::TensorProto_DataType_INT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int16
{onnx::TensorProto_DataType_UINT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of uint16
};
if (dataTypeMap.find(type) != dataTypeMap.end()) {
return dataTypeMap[type];
}
return MNN::DataType_DT_INVALID;
}
MNN::BlobT* onnxOpConverter::convertTensorToBlob(const onnx::TensorProto* constantTp) {
auto constantParam = new MNN::BlobT;
auto dataType = convertDataType(constantTp->data_type());
// printf("origindataType = %d, dataType = %s\n", constantTp->data_type(), MNN::EnumNameDataType(dataType));
constantParam->dataType = dataType;
constantParam->dataFormat = MNN::MNN_DATA_FORMAT_NCHW;
size_t dimSize = constantTp->dims().size();
constantParam->dims.resize(dimSize);
size_t dataSize = 1;
for (int i = 0; i < dimSize; ++i) {
constantParam->dims[i] = constantTp->dims(i);
dataSize = dataSize * constantTp->dims(i);
}
std::vector<int64_t> alignContent((constantTp->raw_data().size() + sizeof(int64_t) - 1) / sizeof(int64_t));
::memcpy(alignContent.data(), constantTp->raw_data().data(), constantTp->raw_data().size());
const void* tensor_content = (const void*)alignContent.data();
switch (constantTp->data_type()) {
#define CASE_DATA_TYPE(src, dst) \
case src: \
if (constantTp->dst##_data_size() != 0) { \
tensor_content = constantTp->dst##_data().data(); \
} \
break;
CASE_DATA_TYPE(onnx::TensorProto_DataType_DOUBLE, double);
CASE_DATA_TYPE(onnx::TensorProto_DataType_INT64, int64);
CASE_DATA_TYPE(onnx::TensorProto_DataType_INT32, int32);
CASE_DATA_TYPE(onnx::TensorProto_DataType_FLOAT, float);
default:
break;
}
if (0 == dataSize) {
// Empty blob
return constantParam;
}
if (!tensor_content) {
DLOG(FATAL) << "Convert no data, "
"Please make sure ";
}
switch (constantTp->data_type()) {
case onnx::TensorProto_DataType_DOUBLE: {
constantParam->float32s.resize(dataSize);
auto source = (double*)tensor_content;
for (int i = 0; i < dataSize; ++i) {
constantParam->float32s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_INT64: {
constantParam->int32s.resize(dataSize);
auto source = (int64_t*)tensor_content;
for (int i = 0; i < dataSize; ++i) {
constantParam->int32s[i] = _limit(source[i]);
}
break;
}
case onnx::TensorProto_DataType_INT32: {
auto source = (int32_t*)tensor_content;
constantParam->int32s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->int32s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_UINT16: {
auto source = (uint16_t*)tensor_content;
constantParam->int32s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->int32s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_INT16: {
auto source = (int16_t*)tensor_content;
constantParam->int32s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->int32s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_BOOL: {
auto source = (bool*)tensor_content;
constantParam->int32s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->int32s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_INT8: {
auto source = (int8_t*)tensor_content;
constantParam->int8s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->int8s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_UINT8: {
auto source = (uint8_t*)tensor_content;
constantParam->uint8s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->uint8s[i] = source[i];
}
break;
}
case onnx::TensorProto_DataType_FLOAT: {
float* tempFloatData = (float*)tensor_content;
constantParam->float32s.resize(dataSize);
for (int i = 0; i < dataSize; ++i) {
constantParam->float32s[i] = tempFloatData[i];
}
break;
}
default: {
DLOG(FATAL) << "Don't support " << constantTp->data_type();
break;
}
}
return constantParam;
}
| 37.803279 | 116 | 0.568517 | foreverlms |
d539757ef23d4c01ba4e3355d1ccf2d0a166d96d | 20,382 | hxx | C++ | Modules/IO/ImageBase/include/itkImageFileReader.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/IO/ImageBase/include/itkImageFileReader.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/IO/ImageBase/include/itkImageFileReader.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkImageFileReader_hxx
#define itkImageFileReader_hxx
#include "itkImageFileReader.h"
#include "itkObjectFactory.h"
#include "itkImageIOFactory.h"
#include "itkConvertPixelBuffer.h"
#include "itkPixelTraits.h"
#include "itkVectorImage.h"
#include "itkMetaDataObject.h"
#include "itksys/SystemTools.hxx"
#include <memory> // For unique_ptr
#include <fstream>
namespace itk
{
template <typename TOutputImage, typename ConvertPixelTraits>
ImageFileReader<TOutputImage, ConvertPixelTraits>::ImageFileReader()
{
m_ImageIO = nullptr;
this->SetFileName("");
m_UserSpecifiedImageIO = false;
m_UseStreaming = true;
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
itkPrintSelfObjectMacro(ImageIO);
os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n";
os << indent << "m_UseStreaming: " << m_UseStreaming << "\n";
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::SetImageIO(ImageIOBase * imageIO)
{
itkDebugMacro("setting ImageIO to " << imageIO);
if (this->m_ImageIO != imageIO)
{
this->m_ImageIO = imageIO;
this->Modified();
}
m_UserSpecifiedImageIO = true;
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateOutputInformation()
{
typename TOutputImage::Pointer output = this->GetOutput();
itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << this->GetFileName());
// Check to see if we can read the file given the name or prefix
//
if (this->GetFileName().empty())
{
throw ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION);
}
// Test if the file exists and if it can be opened.
// An exception will be thrown otherwise.
// We catch the exception because some ImageIO's may not actually
// open a file. Still reports file error if no ImageIO is loaded.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch (const itk::ExceptionObject & err)
{
m_ExceptionMessage = err.GetDescription();
}
if (m_UserSpecifiedImageIO == false) // try creating via factory
{
m_ImageIO = ImageIOFactory::CreateImageIO(this->GetFileName().c_str(), ImageIOFactory::IOFileModeEnum::ReadMode);
}
if (m_ImageIO.IsNull())
{
std::ostringstream msg;
msg << " Could not create IO object for reading file " << this->GetFileName().c_str() << std::endl;
if (!m_ExceptionMessage.empty())
{
msg << m_ExceptionMessage;
}
else
{
std::list<LightObject::Pointer> allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase");
if (!allobjects.empty())
{
msg << " Tried to create one of the following:" << std::endl;
for (auto & allobject : allobjects)
{
auto * io = dynamic_cast<ImageIOBase *>(allobject.GetPointer());
msg << " " << io->GetNameOfClass() << std::endl;
}
msg << " You probably failed to set a file suffix, or" << std::endl;
msg << " set the suffix to an unsupported type." << std::endl;
}
else
{
msg << " There are no registered IO factories." << std::endl;
msg << " Please visit https://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem."
<< std::endl;
}
}
ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION);
throw e;
return;
}
// Got to allocate space for the image. Determine the characteristics of
// the image.
//
m_ImageIO->SetFileName(this->GetFileName().c_str());
m_ImageIO->ReadImageInformation();
SizeType dimSize;
double spacing[TOutputImage::ImageDimension];
double origin[TOutputImage::ImageDimension];
typename TOutputImage::DirectionType direction;
std::vector<std::vector<double>> directionIO;
const unsigned int numberOfDimensionsIO = m_ImageIO->GetNumberOfDimensions();
if (numberOfDimensionsIO > TOutputImage::ImageDimension)
{
for (unsigned int k = 0; k < numberOfDimensionsIO; ++k)
{
directionIO.push_back(m_ImageIO->GetDefaultDirection(k));
}
}
else
{
for (unsigned int k = 0; k < numberOfDimensionsIO; ++k)
{
directionIO.push_back(m_ImageIO->GetDirection(k));
}
}
std::vector<double> axis;
for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i)
{
if (i < numberOfDimensionsIO)
{
dimSize[i] = m_ImageIO->GetDimensions(i);
spacing[i] = m_ImageIO->GetSpacing(i);
origin[i] = m_ImageIO->GetOrigin(i);
// Please note: direction cosines are stored as columns of the
// direction matrix
axis = directionIO[i];
for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j)
{
if (j < numberOfDimensionsIO)
{
direction[j][i] = axis[j];
}
else
{
direction[j][i] = 0.0;
}
}
}
else
{
// Number of dimensions in the output is more than number of dimensions
// in the ImageIO object (the file). Use default values for the size,
// spacing, origin and direction for the final (degenerate) dimensions.
dimSize[i] = 1;
spacing[i] = 1.0;
origin[i] = 0.0;
for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j)
{
if (i == j)
{
direction[j][i] = 1.0;
}
else
{
direction[j][i] = 0.0;
}
}
}
}
MetaDataDictionary & thisDic = m_ImageIO->GetMetaDataDictionary();
// Store original directions and spacing
EncapsulateMetaData<std::vector<double>>(
thisDic, "ITK_original_spacing", std::vector<double>(spacing, spacing + TOutputImage::ImageDimension));
EncapsulateMetaData<typename TOutputImage::DirectionType>(thisDic, "ITK_original_direction", direction);
// Spacing is expected to be greater than 0
// If negative, flip image direction along this axis.
// and store this information in the metadata
for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i)
{
if (spacing[i] < 0)
{
spacing[i] = -spacing[i];
for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j)
{
direction[j][i] = -direction[j][i];
}
}
}
output->SetSpacing(spacing); // Set the image spacing
output->SetOrigin(origin); // Set the image origin
output->SetDirection(direction); // Set the image direction cosines
// Copy MetaDataDictionary from instantiated reader to output image.
output->SetMetaDataDictionary(thisDic);
this->SetMetaDataDictionary(thisDic);
IndexType start;
start.Fill(0);
ImageRegionType region;
region.SetSize(dimSize);
region.SetIndex(start);
// If a VectorImage, this requires us to set the
// VectorLength before allocate
if (strcmp(output->GetNameOfClass(), "VectorImage") == 0)
{
using AccessorFunctorType = typename TOutputImage::AccessorFunctorType;
AccessorFunctorType::SetVectorLength(output, m_ImageIO->GetNumberOfComponents());
}
output->SetLargestPossibleRegion(region);
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::TestFileExistanceAndReadability()
{
// Test if the file exists.
if (!itksys::SystemTools::FileExists(this->GetFileName().c_str()))
{
ImageFileReaderException e(__FILE__, __LINE__);
std::ostringstream msg;
msg << "The file doesn't exist. " << std::endl << "Filename = " << this->GetFileName() << std::endl;
e.SetDescription(msg.str().c_str());
throw e;
return;
}
// Test if the file can be open for reading access.
std::ifstream readTester;
readTester.open(this->GetFileName().c_str());
if (readTester.fail())
{
readTester.close();
std::ostringstream msg;
msg << "The file couldn't be opened for reading. " << std::endl << "Filename: " << this->GetFileName() << std::endl;
ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION);
throw e;
return;
}
readTester.close();
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::EnlargeOutputRequestedRegion(DataObject * output)
{
itkDebugMacro(<< "Starting EnlargeOutputRequestedRegion() ");
typename TOutputImage::Pointer out = dynamic_cast<TOutputImage *>(output);
typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion();
ImageRegionType streamableRegion;
// The following code converts the ImageRegion (templated over dimension)
// into an ImageIORegion (not templated over dimension).
ImageRegionType imageRequestedRegion = out->GetRequestedRegion();
ImageIORegion ioRequestedRegion(TOutputImage::ImageDimension);
using ImageIOAdaptor = ImageIORegionAdaptor<TOutputImage::ImageDimension>;
ImageIOAdaptor::Convert(imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex());
// Tell the IO if we should use streaming while reading
m_ImageIO->SetUseStreamedReading(m_UseStreaming);
// Delegate to the ImageIO the computation of how the
// requested region must be enlarged.
m_ActualIORegion = m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion(ioRequestedRegion);
// the m_ActualIORegion may be more dimensions then the output
// Image, in which case we still need to read this larger region to
// support reading the "first slice" of a larger image
// see bug 9212
// convert the IORegion to a ImageRegion (which is dimension templated)
// if the ImageIO must read a higher dimension region, this will
// truncate the last dimensions
ImageIOAdaptor::Convert(m_ActualIORegion, streamableRegion, largestRegion.GetIndex());
// Check whether the imageRequestedRegion is fully contained inside the
// streamable region. Since, ImageRegion::IsInside regards zero
// sized regions, as not being inside any other region, we must
// specially check this condition to enable zero sized regions to
// pass the region propagation phase of the pipeline.
if (!streamableRegion.IsInside(imageRequestedRegion) && imageRequestedRegion.GetNumberOfPixels() != 0)
{
// we must use a InvalidRequestedRegionError since
// DataObject::PropagateRequestedRegion() has an exception
// specification
std::ostringstream message;
message << "ImageIO returns IO region that does not fully contain the requested region"
<< "Requested region: " << imageRequestedRegion << "StreamableRegion region: " << streamableRegion;
InvalidRequestedRegionError e(__FILE__, __LINE__);
e.SetLocation(ITK_LOCATION);
e.SetDescription(message.str().c_str());
throw e;
}
itkDebugMacro(<< "RequestedRegion is set to:" << streamableRegion
<< " while the m_ActualIORegion is: " << m_ActualIORegion);
out->SetRequestedRegion(streamableRegion);
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateData()
{
this->UpdateProgress(0.0f);
typename TOutputImage::Pointer output = this->GetOutput();
itkDebugMacro(<< "ImageFileReader::GenerateData() \n"
<< "Allocating the buffer with the EnlargedRequestedRegion \n"
<< output->GetRequestedRegion() << "\n");
// allocated the output image to the size of the enlarge requested region
this->AllocateOutputs();
// Test if the file exists and if it can be opened.
// An exception will be thrown otherwise, since we can't
// successfully read the file. We catch the exception because some
// ImageIO's may not actually open a file. Still
// reports file error if no ImageIO is loaded.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch (const itk::ExceptionObject & err)
{
m_ExceptionMessage = err.GetDescription();
}
// Tell the ImageIO to read the file
m_ImageIO->SetFileName(this->GetFileName().c_str());
itkDebugMacro(<< "Setting imageIO IORegion to: " << m_ActualIORegion);
m_ImageIO->SetIORegion(m_ActualIORegion);
// the size of the buffer is computed based on the actual number of
// pixels to be read and the actual size of the pixels to be read
// (as opposed to the sizes of the output)
size_t sizeOfActualIORegion =
m_ActualIORegion.GetNumberOfPixels() * (m_ImageIO->GetComponentSize() * m_ImageIO->GetNumberOfComponents());
IOComponentEnum ioType = ImageIOBase::MapPixelType<typename ConvertPixelTraits::ComponentType>::CType;
if (m_ImageIO->GetComponentType() != ioType ||
(m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents()))
{
// the pixel types don't match so a type conversion needs to be
// performed
itkDebugMacro(<< "Buffer conversion required from: "
<< m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType())
<< " to: " << m_ImageIO->GetComponentTypeAsString(ioType) << " ConvertPixelTraits::NumComponents "
<< ConvertPixelTraits::GetNumberOfComponents() << " m_ImageIO->NumComponents "
<< m_ImageIO->GetNumberOfComponents());
const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]);
m_ImageIO->Read(static_cast<void *>(loadBuffer.get()));
// See note below as to why the buffered region is needed and
// not actualIOregion
this->DoConvertBuffer(static_cast<void *>(loadBuffer.get()), output->GetBufferedRegion().GetNumberOfPixels());
}
else if (m_ActualIORegion.GetNumberOfPixels() != output->GetBufferedRegion().GetNumberOfPixels())
{
// NOTE:
// for the number of pixels read and the number of pixels
// requested to not match, the dimensions of the two regions may
// be different, therefore we buffer and copy the pixels
itkDebugMacro(<< "Buffer required because file dimension is greater then image dimension");
OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer();
const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]);
m_ImageIO->Read(static_cast<void *>(loadBuffer.get()));
// we use std::copy_n here as it should be optimized to memcpy for
// plain old data, but still is oop
std::copy_n(reinterpret_cast<const OutputImagePixelType *>(loadBuffer.get()),
output->GetBufferedRegion().GetNumberOfPixels(),
outputBuffer);
}
else
{
itkDebugMacro(<< "No buffer conversion required.");
OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer();
m_ImageIO->Read(outputBuffer);
}
this->UpdateProgress(1.0f);
}
template <typename TOutputImage, typename ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>::DoConvertBuffer(void * inputData, size_t numberOfPixels)
{
// get the pointer to the destination buffer
OutputImagePixelType * outputData = this->GetOutput()->GetPixelContainer()->GetBufferPointer();
bool isVectorImage(strcmp(this->GetOutput()->GetNameOfClass(), "VectorImage") == 0);
// TODO:
// Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to
// scalar conversion be type specific. i.e. RGB to scalar would use
// a formula to convert to luminance, VECTOR to scalar would use
// vector magnitude.
// Create a macro as this code is a bit lengthy and repetitive
// if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer
// class to convert the data block to TOutputImage's pixel type
// see DefaultConvertPixelTraits and ConvertPixelBuffer
// The first else if block applies only to images of type itk::VectorImage
// VectorImage needs to copy out the buffer differently.. The buffer is of
// type InternalPixelType, but each pixel is really 'k' consecutive pixels.
#define ITK_CONVERT_BUFFER_IF_BLOCK(_CType, type) \
else if (m_ImageIO->GetComponentType() == _CType) \
{ \
if (isVectorImage) \
{ \
ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::ConvertVectorImage( \
static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \
} \
else \
{ \
ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::Convert( \
static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \
} \
}
if (false)
{
}
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UCHAR, unsigned char)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::CHAR, char)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::USHORT, unsigned short)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::SHORT, short)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UINT, unsigned int)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::INT, int)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONG, unsigned long)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONG, long)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONGLONG, unsigned long long)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONGLONG, long long)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::FLOAT, float)
ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::DOUBLE, double)
else
{
#define TYPENAME(x) m_ImageIO->GetComponentTypeAsString(ImageIOBase::MapPixelType<x>::CType)
ImageFileReaderException e(__FILE__, __LINE__);
std::ostringstream msg;
msg << "Couldn't convert component type: " << std::endl
<< " " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType()) << std::endl
<< "to one of: " << std::endl
<< " " << TYPENAME(unsigned char) << std::endl
<< " " << TYPENAME(char) << std::endl
<< " " << TYPENAME(unsigned short) << std::endl
<< " " << TYPENAME(short) << std::endl
<< " " << TYPENAME(unsigned int) << std::endl
<< " " << TYPENAME(int) << std::endl
<< " " << TYPENAME(unsigned long) << std::endl
<< " " << TYPENAME(long) << std::endl
<< " " << TYPENAME(unsigned long long) << std::endl
<< " " << TYPENAME(long long) << std::endl
<< " " << TYPENAME(float) << std::endl
<< " " << TYPENAME(double) << std::endl;
e.SetDescription(msg.str().c_str());
e.SetLocation(ITK_LOCATION);
throw e;
return;
}
#undef ITK_CONVERT_BUFFER_IF_BLOCK
}
} // namespace itk
#endif
| 38.675522 | 120 | 0.659356 | bradking |
d53a87a9e6e27378f7ec05288766cada1296d53f | 1,628 | cpp | C++ | cpp/logger/Logger.cpp | yukonfb/profilo | baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375 | [
"Apache-2.0"
] | null | null | null | cpp/logger/Logger.cpp | yukonfb/profilo | baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375 | [
"Apache-2.0"
] | null | null | null | cpp/logger/Logger.cpp | yukonfb/profilo | baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2004-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Logger.h"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <stdexcept>
#include <util/common.h>
namespace facebook {
namespace profilo {
using namespace entries;
Logger::EntryIDCounter& Logger::getGlobalEntryID() {
static EntryIDCounter global_instance{kDefaultInitialID};
return global_instance;
}
Logger::Logger(logger::TraceBufferProvider provider, EntryIDCounter& counter)
: entryID_(counter), logger_(provider) {}
int32_t Logger::writeBytes(
EntryType type,
int32_t arg1,
const uint8_t* arg2,
size_t len) {
if (len > kMaxVariableLengthEntry) {
throw std::overflow_error("len is bigger than kMaxVariableLengthEntry");
}
if (arg2 == nullptr) {
throw std::invalid_argument("arg2 is null");
}
return write(BytesEntry{
.id = 0,
.type = type,
.matchid = arg1,
.bytes = {
.values = const_cast<uint8_t*>(arg2),
.size = static_cast<uint16_t>(len)}});
}
} // namespace profilo
} // namespace facebook
| 26.258065 | 77 | 0.702703 | yukonfb |
d53ae992b6472b93886c119c8ad83a6aeb8a5983 | 35,578 | cpp | C++ | display-caf/sdm/libs/core/fb/hw_device.cpp | rahulsnair/android_device_motorola_athenecaf | 52399442131dc51ea35cc6fcae1e49683b2bc60b | [
"FTL"
] | null | null | null | display-caf/sdm/libs/core/fb/hw_device.cpp | rahulsnair/android_device_motorola_athenecaf | 52399442131dc51ea35cc6fcae1e49683b2bc60b | [
"FTL"
] | null | null | null | display-caf/sdm/libs/core/fb/hw_device.cpp | rahulsnair/android_device_motorola_athenecaf | 52399442131dc51ea35cc6fcae1e49683b2bc60b | [
"FTL"
] | null | null | null | /*
* Copyright (c) 2014 - 2015, 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 <math.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fb.h>
#include <utils/constants.h>
#include <utils/debug.h>
#include "hw_device.h"
#define __CLASS__ "HWDevice"
namespace sdm {
HWDevice::HWDevice(BufferSyncHandler *buffer_sync_handler)
: fb_node_index_(-1), fb_path_("/sys/devices/virtual/graphics/fb"), hotplug_enabled_(false),
buffer_sync_handler_(buffer_sync_handler), synchronous_commit_(false) {
#ifndef SDM_VIRTUAL_DRIVER
// Pointer to actual driver interfaces.
ioctl_ = ::ioctl;
open_ = ::open;
close_ = ::close;
poll_ = ::poll;
pread_ = ::pread;
pwrite_ = ::pwrite;
fopen_ = ::fopen;
fclose_ = ::fclose;
getline_ = ::getline;
#else
// Point to virtual driver interfaces.
extern int virtual_ioctl(int fd, int cmd, ...);
extern int virtual_open(const char *file_name, int access, ...);
extern int virtual_close(int fd);
extern int virtual_poll(struct pollfd *fds, nfds_t num, int timeout);
extern ssize_t virtual_pread(int fd, void *data, size_t count, off_t offset);
extern ssize_t virtual_pwrite(int fd, const void *data, size_t count, off_t offset);
extern FILE* virtual_fopen(const char *fname, const char *mode);
extern int virtual_fclose(FILE* fileptr);
extern ssize_t virtual_getline(char **lineptr, size_t *linelen, FILE *stream);
ioctl_ = virtual_ioctl;
open_ = virtual_open;
close_ = virtual_close;
poll_ = virtual_poll;
pread_ = virtual_pread;
pwrite_ = virtual_pwrite;
fopen_ = virtual_fopen;
fclose_ = virtual_fclose;
getline_ = virtual_getline;
#endif
}
DisplayError HWDevice::Init() {
DisplayError error = kErrorNone;
// Read the fb node index
fb_node_index_ = GetFBNodeIndex(device_type_);
if (fb_node_index_ == -1) {
DLOGE("%s should be present", device_name_);
return kErrorHardware;
}
// Populate Panel Info (Used for Partial Update)
PopulateHWPanelInfo();
// Populate HW Capabilities
hw_resource_ = HWResourceInfo();
hw_info_intf_->GetHWResourceInfo(&hw_resource_);
return error;
}
DisplayError HWDevice::Open(HWEventHandler *eventhandler) {
DisplayError error = kErrorNone;
char device_name[64] = {0};
// Store EventHandlers for two Physical displays, i.e., Primary and HDMI
// TODO(user): Need to revisit for HDMI as Primary usecase
event_handler_ = eventhandler;
snprintf(device_name, sizeof(device_name), "%s%d", "/dev/graphics/fb", fb_node_index_);
device_fd_ = open_(device_name, O_RDWR);
if (device_fd_ < 0) {
DLOGE("open %s failed err = %d errstr = %s", device_name, errno, strerror(errno));
return kErrorResources;
}
return error;
}
DisplayError HWDevice::Close() {
if (device_fd_ > 0) {
close_(device_fd_);
}
return kErrorNone;
}
DisplayError HWDevice::GetNumDisplayAttributes(uint32_t *count) {
*count = 1;
return kErrorNone;
}
DisplayError HWDevice::GetDisplayAttributes(HWDisplayAttributes *display_attributes,
uint32_t index) {
return kErrorNone;
}
DisplayError HWDevice::GetHWPanelInfo(HWPanelInfo *panel_info) {
*panel_info = hw_panel_info_;
return kErrorNone;
}
DisplayError HWDevice::SetDisplayAttributes(uint32_t index) {
return kErrorNone;
}
DisplayError HWDevice::GetConfigIndex(uint32_t mode, uint32_t *index) {
return kErrorNone;
}
DisplayError HWDevice::PowerOn() {
DTRACE_SCOPED();
if (ioctl_(device_fd_, FBIOBLANK, FB_BLANK_UNBLANK) < 0) {
IOCTL_LOGE(FB_BLANK_UNBLANK, device_type_);
return kErrorHardware;
}
// Need to turn on HPD
if (!hotplug_enabled_) {
hotplug_enabled_ = EnableHotPlugDetection(1);
}
return kErrorNone;
}
DisplayError HWDevice::PowerOff() {
return kErrorNone;
}
DisplayError HWDevice::Doze() {
return kErrorNone;
}
DisplayError HWDevice::DozeSuspend() {
return kErrorNone;
}
DisplayError HWDevice::Standby() {
return kErrorNone;
}
DisplayError HWDevice::Validate(HWLayers *hw_layers) {
DTRACE_SCOPED();
DisplayError error = kErrorNone;
HWLayersInfo &hw_layer_info = hw_layers->info;
LayerStack *stack = hw_layer_info.stack;
DLOGV_IF(kTagDriverConfig, "************************** %s Validate Input ***********************",
device_name_);
DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count);
mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1;
uint32_t &mdp_layer_count = mdp_commit.input_layer_cnt;
DLOGI_IF(kTagDriverConfig, "left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x,
mdp_commit.left_roi.y, mdp_commit.left_roi.w, mdp_commit.left_roi.h);
DLOGI_IF(kTagDriverConfig, "right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x,
mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h);
for (uint32_t i = 0; i < hw_layer_info.count; i++) {
uint32_t layer_index = hw_layer_info.index[i];
Layer &layer = stack->layers[layer_index];
LayerBuffer *input_buffer = layer.input_buffer;
HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe;
HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe;
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
bool is_rotator_used = (hw_rotator_session->hw_block_count != 0);
mdp_input_layer mdp_layer;
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_rotate_info->valid) {
input_buffer = &hw_rotator_session->output_buffer;
}
if (pipe_info->valid) {
mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_count];
mdp_layer_buffer &mdp_buffer = mdp_layer.buffer;
mdp_buffer.width = input_buffer->width;
mdp_buffer.height = input_buffer->height;
mdp_buffer.comp_ratio.denom = 1000;
mdp_buffer.comp_ratio.numer = UINT32(hw_layers->config[i].compression * 1000);
error = SetFormat(input_buffer->format, &mdp_buffer.format);
if (error != kErrorNone) {
return error;
}
mdp_layer.alpha = layer.plane_alpha;
mdp_layer.z_order = UINT16(pipe_info->z_order);
mdp_layer.transp_mask = 0xffffffff;
SetBlending(layer.blending, &mdp_layer.blend_op);
mdp_layer.pipe_ndx = pipe_info->pipe_id;
mdp_layer.horz_deci = pipe_info->horizontal_decimation;
mdp_layer.vert_deci = pipe_info->vertical_decimation;
SetRect(pipe_info->src_roi, &mdp_layer.src_rect);
SetRect(pipe_info->dst_roi, &mdp_layer.dst_rect);
SetMDPFlags(layer, is_rotator_used, &mdp_layer.flags);
SetColorSpace(layer.color_space, &mdp_layer.color_space);
if (pipe_info->scale_data.enable_pixel_ext) {
if ((mdp_layer.flags & MDP_LAYER_DEINTERLACE) && (layer.transform.rotation == 90.0f)) {
mdp_buffer.width = pipe_info->scale_data.src_width;
}
SetHWScaleData(pipe_info->scale_data, mdp_layer_count);
}
// Send scale data to MDP driver
mdp_layer.scale = GetScaleDataRef(mdp_layer_count);
mdp_layer_count++;
DLOGV_IF(kTagDriverConfig, "******************* Layer[%d] %s pipe Input ******************",
i, count ? "Right" : "Left");
DLOGV_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d", mdp_buffer.width, mdp_buffer.height,
mdp_buffer.format);
DLOGV_IF(kTagDriverConfig, "plane_alpha %d, zorder %d, blending %d, horz_deci %d, "
"vert_deci %d, pipe_id = 0x%x, mdp_flags 0x%x", mdp_layer.alpha, mdp_layer.z_order,
mdp_layer.blend_op, mdp_layer.horz_deci, mdp_layer.vert_deci, mdp_layer.pipe_ndx,
mdp_layer.flags);
DLOGV_IF(kTagDriverConfig, "src_rect [%d, %d, %d, %d]", mdp_layer.src_rect.x,
mdp_layer.src_rect.y, mdp_layer.src_rect.w, mdp_layer.src_rect.h);
DLOGV_IF(kTagDriverConfig, "dst_rect [%d, %d, %d, %d]", mdp_layer.dst_rect.x,
mdp_layer.dst_rect.y, mdp_layer.dst_rect.w, mdp_layer.dst_rect.h);
for (int j = 0; j < 4; j++) {
DLOGV_IF(kTagDriverConfig, "Scale Data[%d]: Phase=[%x %x %x %x] Pixel_Ext=[%d %d %d %d]",
j, mdp_layer.scale->init_phase_x[j], mdp_layer.scale->phase_step_x[j],
mdp_layer.scale->init_phase_y[j], mdp_layer.scale->phase_step_y[j],
mdp_layer.scale->num_ext_pxls_left[j], mdp_layer.scale->num_ext_pxls_top[j],
mdp_layer.scale->num_ext_pxls_right[j], mdp_layer.scale->num_ext_pxls_btm[j]);
DLOGV_IF(kTagDriverConfig, "Fetch=[%d %d %d %d] Repeat=[%d %d %d %d] roi_width = %d",
mdp_layer.scale->left_ftch[j], mdp_layer.scale->top_ftch[j],
mdp_layer.scale->right_ftch[j], mdp_layer.scale->btm_ftch[j],
mdp_layer.scale->left_rpt[j], mdp_layer.scale->top_rpt[j],
mdp_layer.scale->right_rpt[j], mdp_layer.scale->btm_rpt[j],
mdp_layer.scale->roi_w[j]);
}
DLOGV_IF(kTagDriverConfig, "*************************************************************");
}
}
}
if (device_type_ == kDeviceVirtual) {
LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer;
// TODO(user): Need to assign the writeback id from the resource manager, since the support
// has not been added hard coding it to 2 for now.
mdp_out_layer_.writeback_ndx = 2;
mdp_out_layer_.buffer.width = output_buffer->width;
mdp_out_layer_.buffer.height = output_buffer->height;
mdp_out_layer_.buffer.comp_ratio.denom = 1000;
mdp_out_layer_.buffer.comp_ratio.numer = UINT32(hw_layers->output_compression * 1000);
SetFormat(output_buffer->format, &mdp_out_layer_.buffer.format);
DLOGI_IF(kTagDriverConfig, "********************* Output buffer Info ************************");
DLOGI_IF(kTagDriverConfig, "out_w %d, out_h %d, out_f %d, wb_id %d",
mdp_out_layer_.buffer.width, mdp_out_layer_.buffer.height,
mdp_out_layer_.buffer.format, mdp_out_layer_.writeback_ndx);
DLOGI_IF(kTagDriverConfig, "*****************************************************************");
}
mdp_commit.flags |= MDP_VALIDATE_LAYER;
if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) {
IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_);
DumpLayerCommit(mdp_disp_commit_);
return kErrorHardware;
}
return kErrorNone;
}
void HWDevice::DumpLayerCommit(const mdp_layer_commit &layer_commit) {
const mdp_layer_commit_v1 &mdp_commit = layer_commit.commit_v1;
const mdp_input_layer *mdp_layers = mdp_commit.input_layers;
DLOGE("mdp_commit: flags = %x, release fence = %x", mdp_commit.flags, mdp_commit.release_fence);
DLOGE("left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x, mdp_commit.left_roi.y,
mdp_commit.left_roi.w, mdp_commit.left_roi.h);
DLOGE("right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x,
mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h);
for (uint32_t i = 0; i < mdp_commit.input_layer_cnt; i++) {
DLOGE("mdp_commit: layer_cnt = %d, pipe_ndx = %x, zorder = %d, flags = %x",
i, mdp_layers[i].pipe_ndx, mdp_layers[i].z_order, mdp_layers[i].flags);
const mdp_rect &src_rect = mdp_layers[i].src_rect;
DLOGE("src rect: x = %d, y = %d, w = %d, h = %d",
src_rect.x, src_rect.y, src_rect.w, src_rect.h);
const mdp_rect &dst_rect = mdp_layers[i].dst_rect;
DLOGE("dst rect: x = %d, y = %d, w = %d, h = %d",
dst_rect.x, dst_rect.y, dst_rect.w, dst_rect.h);
}
}
DisplayError HWDevice::Commit(HWLayers *hw_layers) {
DTRACE_SCOPED();
HWLayersInfo &hw_layer_info = hw_layers->info;
LayerStack *stack = hw_layer_info.stack;
DLOGV_IF(kTagDriverConfig, "*************************** %s Commit Input ************************",
device_name_);
DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count);
mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1;
uint32_t mdp_layer_index = 0;
for (uint32_t i = 0; i < hw_layer_info.count; i++) {
uint32_t layer_index = hw_layer_info.index[i];
LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer;
HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe;
HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe;
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
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_rotate_info->valid) {
input_buffer = &hw_rotator_session->output_buffer;
}
if (pipe_info->valid) {
mdp_layer_buffer &mdp_buffer = mdp_in_layers_[mdp_layer_index].buffer;
mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_index];
if (input_buffer->planes[0].fd >= 0) {
mdp_buffer.plane_count = 1;
mdp_buffer.planes[0].fd = input_buffer->planes[0].fd;
mdp_buffer.planes[0].offset = input_buffer->planes[0].offset;
SetStride(device_type_, input_buffer->format, input_buffer->planes[0].stride,
&mdp_buffer.planes[0].stride);
} else {
DLOGW("Invalid buffer fd, setting plane count to 0");
mdp_buffer.plane_count = 0;
}
mdp_buffer.fence = input_buffer->acquire_fence_fd;
mdp_layer_index++;
DLOGV_IF(kTagDriverConfig, "****************** Layer[%d] %s pipe Input *******************",
i, count ? "Right" : "Left");
DLOGI_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d, horz_deci %d, vert_deci %d",
mdp_buffer.width, mdp_buffer.height, mdp_buffer.format, mdp_layer.horz_deci,
mdp_layer.vert_deci);
DLOGI_IF(kTagDriverConfig, "in_buf_fd %d, in_buf_offset %d, in_buf_stride %d, " \
"in_plane_count %d, in_fence %d, layer count %d", mdp_buffer.planes[0].fd,
mdp_buffer.planes[0].offset, mdp_buffer.planes[0].stride, mdp_buffer.plane_count,
mdp_buffer.fence, mdp_commit.input_layer_cnt);
DLOGV_IF(kTagDriverConfig, "*************************************************************");
}
}
}
if (device_type_ == kDeviceVirtual) {
LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer;
if (output_buffer->planes[0].fd >= 0) {
mdp_out_layer_.buffer.planes[0].fd = output_buffer->planes[0].fd;
mdp_out_layer_.buffer.planes[0].offset = output_buffer->planes[0].offset;
SetStride(device_type_, output_buffer->format, output_buffer->planes[0].stride,
&mdp_out_layer_.buffer.planes[0].stride);
mdp_out_layer_.buffer.plane_count = 1;
} else {
DLOGW("Invalid output buffer fd, setting plane count to 0");
mdp_out_layer_.buffer.plane_count = 0;
}
mdp_out_layer_.buffer.fence = output_buffer->acquire_fence_fd;
DLOGI_IF(kTagDriverConfig, "********************** Output buffer Info ***********************");
DLOGI_IF(kTagDriverConfig, "out_fd %d, out_offset %d, out_stride %d, acquire_fence %d",
mdp_out_layer_.buffer.planes[0].fd, mdp_out_layer_.buffer.planes[0].offset,
mdp_out_layer_.buffer.planes[0].stride, mdp_out_layer_.buffer.fence);
DLOGI_IF(kTagDriverConfig, "*****************************************************************");
}
mdp_commit.release_fence = -1;
mdp_commit.flags &= ~MDP_VALIDATE_LAYER;
if (synchronous_commit_) {
mdp_commit.flags |= MDP_COMMIT_WAIT_FOR_FINISH;
}
if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) {
IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_);
DumpLayerCommit(mdp_disp_commit_);
synchronous_commit_ = false;
return kErrorHardware;
}
stack->retire_fence_fd = mdp_commit.retire_fence;
// MDP returns only one release fence for the entire layer stack. Duplicate this fence into all
// layers being composed by MDP.
for (uint32_t i = 0; i < hw_layer_info.count; i++) {
uint32_t layer_index = hw_layer_info.index[i];
LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer;
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
if (hw_rotator_session->hw_block_count) {
input_buffer = &hw_rotator_session->output_buffer;
}
input_buffer->release_fence_fd = dup(mdp_commit.release_fence);
}
DLOGI_IF(kTagDriverConfig, "*************************** %s Commit Input ************************",
device_name_);
DLOGI_IF(kTagDriverConfig, "retire_fence_fd %d", stack->retire_fence_fd);
DLOGI_IF(kTagDriverConfig, "*******************************************************************");
close_(mdp_commit.release_fence);
if (synchronous_commit_) {
// A synchronous commit can be requested when changing the display mode so we need to update
// panel info.
PopulateHWPanelInfo();
synchronous_commit_ = false;
}
return kErrorNone;
}
DisplayError HWDevice::Flush() {
ResetDisplayParams();
mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1;
mdp_commit.input_layer_cnt = 0;
mdp_commit.output_layer = NULL;
mdp_commit.flags &= ~MDP_VALIDATE_LAYER;
if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) {
IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_);
DumpLayerCommit(mdp_disp_commit_);
return kErrorHardware;
}
return kErrorNone;
}
DisplayError HWDevice::SetFormat(const LayerBufferFormat &source, uint32_t *target) {
switch (source) {
case kFormatARGB8888: *target = MDP_ARGB_8888; break;
case kFormatRGBA8888: *target = MDP_RGBA_8888; break;
case kFormatBGRA8888: *target = MDP_BGRA_8888; break;
case kFormatRGBX8888: *target = MDP_RGBX_8888; break;
case kFormatBGRX8888: *target = MDP_BGRX_8888; break;
case kFormatRGBA5551: *target = MDP_RGBA_5551; break;
case kFormatRGBA4444: *target = MDP_RGBA_4444; break;
case kFormatRGB888: *target = MDP_RGB_888; break;
case kFormatBGR888: *target = MDP_BGR_888; break;
case kFormatRGB565: *target = MDP_RGB_565; break;
case kFormatYCbCr420Planar: *target = MDP_Y_CB_CR_H2V2; break;
case kFormatYCrCb420Planar: *target = MDP_Y_CR_CB_H2V2; break;
case kFormatYCbCr420SemiPlanar: *target = MDP_Y_CBCR_H2V2; break;
case kFormatYCrCb420SemiPlanar: *target = MDP_Y_CRCB_H2V2; break;
case kFormatYCbCr422H1V2SemiPlanar: *target = MDP_Y_CBCR_H1V2; break;
case kFormatYCrCb422H1V2SemiPlanar: *target = MDP_Y_CRCB_H1V2; break;
case kFormatYCbCr422H2V1SemiPlanar: *target = MDP_Y_CBCR_H2V1; break;
case kFormatYCrCb422H2V1SemiPlanar: *target = MDP_Y_CRCB_H2V1; break;
case kFormatYCbCr422H2V1Packed: *target = MDP_YCBYCR_H2V1; break;
case kFormatYCbCr420SemiPlanarVenus: *target = MDP_Y_CBCR_H2V2_VENUS; break;
case kFormatRGBA8888Ubwc: *target = MDP_RGBA_8888_UBWC; break;
case kFormatRGBX8888Ubwc: *target = MDP_RGBX_8888_UBWC; break;
case kFormatRGB565Ubwc: *target = MDP_RGB_565_UBWC; break;
case kFormatYCbCr420SPVenusUbwc: *target = MDP_Y_CBCR_H2V2_UBWC; break;
default:
DLOGE("Unsupported format type %d", source);
return kErrorParameters;
}
return kErrorNone;
}
DisplayError HWDevice::SetStride(HWDeviceType device_type, LayerBufferFormat format,
uint32_t width, uint32_t *target) {
// TODO(user): This SetStride function is a workaround to satisfy the driver expectation for
// rotator and virtual devices. Eventually this will be taken care in the driver.
if (device_type != kDeviceRotator && device_type != kDeviceVirtual) {
*target = width;
return kErrorNone;
}
switch (format) {
case kFormatARGB8888:
case kFormatRGBA8888:
case kFormatBGRA8888:
case kFormatRGBX8888:
case kFormatBGRX8888:
case kFormatRGBA8888Ubwc:
case kFormatRGBX8888Ubwc:
*target = width * 4;
break;
case kFormatRGB888:
case kFormatBGR888:
*target = width * 3;
break;
case kFormatRGB565:
case kFormatRGB565Ubwc:
*target = width * 2;
break;
case kFormatYCbCr420SemiPlanarVenus:
case kFormatYCbCr420SPVenusUbwc:
case kFormatYCbCr420Planar:
case kFormatYCrCb420Planar:
case kFormatYCbCr420SemiPlanar:
case kFormatYCrCb420SemiPlanar:
*target = width;
break;
case kFormatYCbCr422H2V1Packed:
case kFormatYCrCb422H2V1SemiPlanar:
case kFormatYCrCb422H1V2SemiPlanar:
case kFormatYCbCr422H2V1SemiPlanar:
case kFormatYCbCr422H1V2SemiPlanar:
case kFormatRGBA5551:
case kFormatRGBA4444:
*target = width * 2;
break;
default:
DLOGE("Unsupported format type %d", format);
return kErrorParameters;
}
return kErrorNone;
}
void HWDevice::SetBlending(const LayerBlending &source, mdss_mdp_blend_op *target) {
switch (source) {
case kBlendingPremultiplied: *target = BLEND_OP_PREMULTIPLIED; break;
case kBlendingCoverage: *target = BLEND_OP_COVERAGE; break;
default: *target = BLEND_OP_NOT_DEFINED; break;
}
}
void HWDevice::SetRect(const LayerRect &source, mdp_rect *target) {
target->x = UINT32(source.left);
target->y = UINT32(source.top);
target->w = UINT32(source.right) - target->x;
target->h = UINT32(source.bottom) - target->y;
}
void HWDevice::SetMDPFlags(const Layer &layer, const bool &is_rotator_used,
uint32_t *mdp_flags) {
LayerBuffer *input_buffer = layer.input_buffer;
// Flips will be taken care by rotator, if layer uses rotator for downscale/rotation. So ignore
// flip flags for MDP.
if (!is_rotator_used) {
if (layer.transform.flip_vertical) {
*mdp_flags |= MDP_LAYER_FLIP_UD;
}
if (layer.transform.flip_horizontal) {
*mdp_flags |= MDP_LAYER_FLIP_LR;
}
}
if (input_buffer->flags.interlace) {
*mdp_flags |= MDP_LAYER_DEINTERLACE;
}
if (input_buffer->flags.secure) {
*mdp_flags |= MDP_LAYER_SECURE_SESSION;
}
if (input_buffer->flags.secure_display) {
*mdp_flags |= MDP_SECURE_DISPLAY_OVERLAY_SESSION;
}
}
void HWDevice::SyncMerge(const int &fd1, const int &fd2, int *target) {
if (fd1 >= 0 && fd2 >= 0) {
buffer_sync_handler_->SyncMerge(fd1, fd2, target);
} else if (fd1 >= 0) {
*target = fd1;
} else if (fd2 >= 0) {
*target = fd2;
}
}
int HWDevice::GetFBNodeIndex(HWDeviceType device_type) {
int fb_node_index = -1;
for (int i = 0; i <= kDeviceVirtual; i++) {
HWPanelInfo *panel_info = new HWPanelInfo();
GetHWPanelInfoByNode(i, panel_info);
switch (device_type) {
case kDevicePrimary:
if (panel_info->is_primary_panel) {
fb_node_index = i;
}
break;
case kDeviceHDMI:
if (panel_info->port == kPortDTv) {
fb_node_index = i;
}
break;
case kDeviceVirtual:
if (panel_info->port == kPortWriteBack) {
fb_node_index = i;
}
break;
default:
break;
}
}
return fb_node_index;
}
void HWDevice::PopulateHWPanelInfo() {
hw_panel_info_ = HWPanelInfo();
GetHWPanelInfoByNode(fb_node_index_, &hw_panel_info_);
DLOGI("Device type = %d, Display Port = %d, Display Mode = %d, Device Node = %d, Is Primary = %d",
device_type_, hw_panel_info_.port, hw_panel_info_.mode, fb_node_index_,
hw_panel_info_.is_primary_panel);
DLOGI("Partial Update = %d, Dynamic FPS = %d",
hw_panel_info_.partial_update, hw_panel_info_.dynamic_fps);
DLOGI("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("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("FPS: min = %d, max =%d", hw_panel_info_.min_fps, hw_panel_info_.max_fps);
DLOGI("Left Split = %d, Right Split = %d", hw_panel_info_.split_info.left_split,
hw_panel_info_.split_info.right_split);
DLOGI("Source Split Always = %d", hw_panel_info_.split_info.always_src_split);
}
void HWDevice::GetHWPanelInfoByNode(int device_node, HWPanelInfo *panel_info) {
if (!panel_info) {
DLOGE("PanelInfo pointer in invalid.");
return;
}
char stringbuffer[kMaxStringLength];
FILE *fileptr = NULL;
snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_panel_info", fb_path_, device_node);
fileptr = fopen(stringbuffer, "r");
if (!fileptr) {
DLOGW("Failed to open msm_fb_panel_info node device node %d", device_node);
return;
}
size_t len = kMaxStringLength;
ssize_t read;
char *line = NULL;
while ((read = getline(&line, &len, fileptr)) != -1) {
uint32_t token_count = 0;
const uint32_t max_count = 10;
char *tokens[max_count] = { NULL };
if (!ParseLine(line, tokens, max_count, &token_count)) {
if (!strncmp(tokens[0], "pu_en", strlen("pu_en"))) {
panel_info->partial_update = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "xstart", strlen("xstart"))) {
panel_info->left_align = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "walign", strlen("walign"))) {
panel_info->width_align = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "ystart", strlen("ystart"))) {
panel_info->top_align = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "halign", strlen("halign"))) {
panel_info->height_align = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "min_w", strlen("min_w"))) {
panel_info->min_roi_width = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "min_h", strlen("min_h"))) {
panel_info->min_roi_height = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "roi_merge", strlen("roi_merge"))) {
panel_info->needs_roi_merge = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "dyn_fps_en", strlen("dyn_fps_en"))) {
panel_info->dynamic_fps = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "min_fps", strlen("min_fps"))) {
panel_info->min_fps = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "max_fps", strlen("max_fps"))) {
panel_info->max_fps = atoi(tokens[1]);
} else if (!strncmp(tokens[0], "primary_panel", strlen("primary_panel"))) {
panel_info->is_primary_panel = atoi(tokens[1]);
}
}
}
fclose(fileptr);
free(line);
panel_info->port = GetHWDisplayPort(device_node);
panel_info->mode = GetHWDisplayMode(device_node);
GetSplitInfo(device_node, panel_info);
}
HWDisplayPort HWDevice::GetHWDisplayPort(int device_node) {
char stringbuffer[kMaxStringLength];
DisplayError error = kErrorNone;
char *line = NULL;
size_t len = kMaxStringLength;
ssize_t read;
HWDisplayPort port = kPortDefault;
snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node);
FILE *fileptr = fopen(stringbuffer, "r");
if (!fileptr) {
DLOGW("File not found %s", stringbuffer);
return port;
}
read = getline(&line, &len, fileptr);
if (read == -1) {
fclose(fileptr);
return port;
}
if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) {
port = kPortDSI;
} else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) {
port = kPortDSI;
} else if ((strncmp(line, "lvds panel", strlen("lvds panel")) == 0)) {
port = kPortLVDS;
} else if ((strncmp(line, "edp panel", strlen("edp panel")) == 0)) {
port = kPortEDP;
} else if ((strncmp(line, "dtv panel", strlen("dtv panel")) == 0)) {
port = kPortDTv;
} else if ((strncmp(line, "writeback panel", strlen("writeback panel")) == 0)) {
port = kPortWriteBack;
} else {
port = kPortDefault;
}
fclose(fileptr);
free(line);
return port;
}
HWDisplayMode HWDevice::GetHWDisplayMode(int device_node) {
char stringbuffer[kMaxStringLength];
DisplayError error = kErrorNone;
char *line = NULL;
size_t len = kMaxStringLength;
ssize_t read;
HWDisplayMode mode = kModeDefault;
snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node);
FILE *fileptr = fopen(stringbuffer, "r");
if (!fileptr) {
DLOGW("File not found %s", stringbuffer);
return mode;
}
read = getline(&line, &len, fileptr);
if (read == -1) {
fclose(fileptr);
return mode;
}
if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) {
mode = kModeCommand;
} else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) {
mode = kModeVideo;
} else {
mode = kModeDefault;
}
fclose(fileptr);
free(line);
return mode;
}
void HWDevice::GetSplitInfo(int device_node, HWPanelInfo *panel_info) {
char stringbuffer[kMaxStringLength];
FILE *fileptr = NULL;
size_t len = kMaxStringLength;
ssize_t read;
char *line = NULL;
uint32_t token_count = 0;
const uint32_t max_count = 10;
char *tokens[max_count] = { NULL };
// Split info - for MDSS Version 5 - No need to check version here
snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_split", fb_path_, device_node);
fileptr = fopen(stringbuffer, "r");
if (!fileptr) {
DLOGW("File not found %s", stringbuffer);
return;
}
// Format "left right" space as delimiter
read = getline(&line, &len, fileptr);
if (read != -1) {
if (!ParseLine(line, tokens, max_count, &token_count)) {
panel_info->split_info.left_split = atoi(tokens[0]);
panel_info->split_info.right_split = atoi(tokens[1]);
}
}
fclose(fileptr);
// SourceSplit enabled - Get More information
snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_src_split_info", fb_path_,
device_node);
fileptr = fopen(stringbuffer, "r");
if (!fileptr) {
DLOGW("File not found %s", stringbuffer);
return;
}
read = getline(&line, &len, fileptr);
if (read != -1) {
if (!strncmp(line, "src_split_always", strlen("src_split_always"))) {
panel_info->split_info.always_src_split = true;
}
}
fclose(fileptr);
free(line);
}
int HWDevice::ParseLine(char *input, char *tokens[], const uint32_t max_token, uint32_t *count) {
char *tmp_token = NULL;
char *temp_ptr;
uint32_t index = 0;
const char *delim = ", =\n";
if (!input) {
return -1;
}
tmp_token = strtok_r(input, delim, &temp_ptr);
while (tmp_token && index < max_token) {
tokens[index++] = tmp_token;
tmp_token = strtok_r(NULL, delim, &temp_ptr);
}
*count = index;
return 0;
}
bool HWDevice::EnableHotPlugDetection(int enable) {
bool ret_value = true;
char hpdpath[kMaxStringLength];
int hdmi_node_index = GetFBNodeIndex(kDeviceHDMI);
snprintf(hpdpath , sizeof(hpdpath), "%s%d/hpd", fb_path_, hdmi_node_index);
int hpdfd = open_(hpdpath, O_RDWR, 0);
if (hpdfd < 0) {
DLOGE("Open failed = %s", hpdpath);
return kErrorHardware;
}
char value = enable ? '1' : '0';
ssize_t length = pwrite_(hpdfd, &value, 1, 0);
if (length <= 0) {
DLOGE("Write failed 'hpd' = %d", enable);
ret_value = false;
}
close_(hpdfd);
return ret_value;
}
void HWDevice::ResetDisplayParams() {
memset(&mdp_disp_commit_, 0, sizeof(mdp_disp_commit_));
memset(&mdp_in_layers_, 0, sizeof(mdp_in_layers_));
memset(&mdp_out_layer_, 0, sizeof(mdp_out_layer_));
memset(&scale_data_, 0, sizeof(scale_data_));
for (uint32_t i = 0; i < kMaxSDELayers * 2; i++) {
mdp_in_layers_[i].buffer.fence = -1;
}
mdp_disp_commit_.version = MDP_COMMIT_VERSION_1_0;
mdp_disp_commit_.commit_v1.input_layers = mdp_in_layers_;
mdp_disp_commit_.commit_v1.output_layer = &mdp_out_layer_;
mdp_disp_commit_.commit_v1.release_fence = -1;
mdp_disp_commit_.commit_v1.retire_fence = -1;
}
void HWDevice::SetHWScaleData(const ScaleData &scale, uint32_t index) {
mdp_scale_data *mdp_scale = GetScaleDataRef(index);
mdp_scale->enable_pxl_ext = scale.enable_pixel_ext;
for (int i = 0; i < 4; i++) {
const HWPlane &plane = scale.plane[i];
mdp_scale->init_phase_x[i] = plane.init_phase_x;
mdp_scale->phase_step_x[i] = plane.phase_step_x;
mdp_scale->init_phase_y[i] = plane.init_phase_y;
mdp_scale->phase_step_y[i] = plane.phase_step_y;
mdp_scale->num_ext_pxls_left[i] = plane.left.extension;
mdp_scale->left_ftch[i] = plane.left.overfetch;
mdp_scale->left_rpt[i] = plane.left.repeat;
mdp_scale->num_ext_pxls_top[i] = plane.top.extension;
mdp_scale->top_ftch[i] = plane.top.overfetch;
mdp_scale->top_rpt[i] = plane.top.repeat;
mdp_scale->num_ext_pxls_right[i] = plane.right.extension;
mdp_scale->right_ftch[i] = plane.right.overfetch;
mdp_scale->right_rpt[i] = plane.right.repeat;
mdp_scale->num_ext_pxls_btm[i] = plane.bottom.extension;
mdp_scale->btm_ftch[i] = plane.bottom.overfetch;
mdp_scale->btm_rpt[i] = plane.bottom.repeat;
mdp_scale->roi_w[i] = plane.roi_width;
}
}
void HWDevice::SetColorSpace(LayerColorSpace source, mdp_color_space *color_space) {
switch (source) {
case kLimitedRange601: *color_space = MDP_CSC_ITU_R_601; break;
case kFullRange601: *color_space = MDP_CSC_ITU_R_601_FR; break;
case kLimitedRange709: *color_space = MDP_CSC_ITU_R_709; break;
}
}
} // namespace sdm
| 37.728526 | 100 | 0.669093 | rahulsnair |
d53c45114c8012f5752f54f4512f150a527c151e | 13,132 | cpp | C++ | Modules/Scene/vaCameraControllers.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 110 | 2018-09-04T20:33:59.000Z | 2021-12-17T08:46:11.000Z | Modules/Scene/vaCameraControllers.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 5 | 2018-09-05T20:57:08.000Z | 2021-02-24T09:02:31.000Z | Modules/Scene/vaCameraControllers.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 20 | 2018-09-05T00:41:13.000Z | 2021-08-04T01:31:50.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Author(s): Filip Strugar (filip.strugar@intel.com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "vaCameraControllers.h"
#include "vaCameraBase.h"
#include "Core/vaInput.h"
#include "IntegratedExternals/vaImguiIntegration.h"
using namespace VertexAsylum;
void vaCameraControllerBase::CameraAttached( const shared_ptr<vaCameraBase> & camera )
{
if( camera == nullptr )
{
assert( !m_attachedCamera.expired() );
m_attachedCamera.reset();
}
else
{
assert( m_attachedCamera.expired() );
m_attachedCamera = camera;
}
}
vaCameraControllerFreeFlight::vaCameraControllerFreeFlight( )
// orient the camera so that X is forward, Z is up, Y is right
: m_baseOrientation( vaMatrix4x4::RotationZ( VA_PIf * 0.5f ) * vaMatrix4x4::RotationY( VA_PIf * 0.5f ) )
{
// m_hasFocus = true; // temporary
m_accumMouseDeltaX = 0.0f;
m_accumMouseDeltaY = 0.0f;
m_accumMove = vaVector3( 0.0f, 0.0f, 0.0f );
m_rotationSpeed = 0.5f;
m_movementSpeed = 20.0f;
m_inputSmoothingLerpK = 200.0f;
m_yaw = 0.0f;
m_pitch = 0.0f; // look towards x
m_roll = 0.0f; // y is right
m_movementSpeedAccelerationModifier = 0.0f;
m_moveWhileNotCaptured = true;
}
vaCameraControllerFreeFlight::~vaCameraControllerFreeFlight( )
{
}
void vaCameraControllerFreeFlight::CameraAttached( const shared_ptr<vaCameraBase> & camera )
{
vaCameraControllerBase::CameraAttached( camera );
if( camera != nullptr )
{
// extract yaw/pitch from attached camera
vaMatrix4x4 debasedOrientation = m_baseOrientation.Inverse() * vaMatrix4x4::FromQuaternion( camera->GetOrientation() );
debasedOrientation.DecomposeRotationYawPitchRoll( m_yaw, m_pitch, m_roll );
m_roll = 0;
}
}
void vaCameraControllerFreeFlight::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus )
{
if( ( vaInputMouseBase::GetCurrent( ) == NULL ) || ( vaInputKeyboardBase::GetCurrent( ) == NULL ) )
return;
vaVector3 objectPos = camera.GetPosition();
vaQuaternion objectOri = camera.GetOrientation();
vaInputMouseBase & mouse = *vaInputMouseBase::GetCurrent();
vaInputKeyboardBase & keyboard = *vaInputKeyboardBase::GetCurrent( );
{
float smoothingLerpK = vaMath::TimeIndependentLerpF( deltaTime, m_inputSmoothingLerpK );
float speedBoost = 1.0f;
if( hasFocus )
{
speedBoost *= (keyboard.IsKeyDown( KK_SHIFT ))?(12.0f):(1.0f);
speedBoost *= keyboard.IsKeyDown( KK_CONTROL )?(0.08f):(1.0f);
if( keyboard.IsKeyDown( KK_SHIFT ) && keyboard.IsKeyDown( KK_MENU ) )
speedBoost *= 10.0f;
}
//
///////////////////////////////////////////////////////////////////////////
// Update camera range/speed changes
if( hasFocus )
{
if( keyboard.IsKeyDown( KK_SUBTRACT ) ) m_movementSpeed *= 0.95f;
if( keyboard.IsKeyDown( KK_ADD ) ) m_movementSpeed *= 1.05f;
m_movementSpeed = vaMath::Clamp( m_movementSpeed, 1.0f, 5000.0f );
//if( vaIsKeyClicked( kcViewRangeDown ) ) m_viewRange *= 0.99f;
//if( vaIsKeyClicked( kcViewRangeUp ) ) m_viewRange *= 1.01f;
//m_viewRange = vaMath::Clamp( m_viewRange, 1000.0f, 1000000.0f );
//
}
///////////////////////////////////////////////////////////////////////////
// Update camera rotation
vaVector2 cdelta = vaVector2( 0.0f, 0.0f );
if( hasFocus )
cdelta = (vaVector2)mouse.GetCursorDelta( ) * m_rotationSpeed;
//
// smoothing
{
m_accumMouseDeltaX += cdelta.x;
m_accumMouseDeltaY += cdelta.y;
cdelta.x = smoothingLerpK * m_accumMouseDeltaX;
cdelta.y = smoothingLerpK * m_accumMouseDeltaY;
m_accumMouseDeltaX = (1 - smoothingLerpK) * m_accumMouseDeltaX;
m_accumMouseDeltaY = (1 - smoothingLerpK) * m_accumMouseDeltaY;
}
//
// Rotate
if( mouse.IsCaptured( ) )
{
if( mouse.IsKeyDown( MK_Middle ) )
m_roll -= cdelta.x * 0.005f;
else
m_yaw += cdelta.x * 0.005f;
m_pitch += cdelta.y * 0.003f;
m_yaw = vaMath::AngleWrap( m_yaw );
m_pitch = vaMath::Clamp( m_pitch, -(float)VA_PIf/2 + 1e-1f, +(float)VA_PIf/2 - 1e-1f );
m_roll = vaMath::AngleWrap( m_roll );
}
#if 1
{ // round yaw/pitch/roll slightly to avoid precision errors causing non-determinism when saving/loading cameras; 5 is precise enough for 10x zoom sniping (fov/10) but stepping could potential be seen with 100x
int precisionTrimDecimals = 5;
float k = vaMath::Pow( 10, (float)precisionTrimDecimals );
m_yaw = vaMath::Round(m_yaw * k)/k;
m_pitch = vaMath::Round(m_pitch * k)/k;
m_roll = vaMath::Round(m_roll * k)/k;
}
#endif
//
vaMatrix4x4 cameraWorld = vaMatrix4x4::FromYawPitchRoll( m_yaw, m_pitch, m_roll );
//
// Move
if( mouse.IsCaptured() || m_moveWhileNotCaptured )
{
///////////////////////////////////////////////////////////////////////////
// Update camera movement
bool hasInput = false;
if( hasFocus )
{
hasInput = keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) ||
keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'E' );
}
m_movementSpeedAccelerationModifier = (hasInput)?(vaMath::Min(m_movementSpeedAccelerationModifier + deltaTime * 0.5f, 1.0f)):(0.0f);
float moveSpeed = m_movementSpeed * deltaTime * ( 0.3f + 0.7f * m_movementSpeedAccelerationModifier ) * speedBoost;
vaVector3 forward( cameraWorld.GetAxisX() );
vaVector3 right( cameraWorld.GetAxisY() );
vaVector3 up( cameraWorld.GetAxisZ() );
vaVector3 accumMove = m_accumMove;
if( hasFocus )
{
if( keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( KK_UP ) ) accumMove += forward * moveSpeed;
if( keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( KK_DOWN ) ) accumMove -= forward * moveSpeed;
if( keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( KK_RIGHT ) ) accumMove += right * moveSpeed;
if( keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) || keyboard.IsKeyDown( KK_LEFT ) ) accumMove -= right * moveSpeed;
if( keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) ) accumMove -= up * moveSpeed;
if( keyboard.IsKeyDown( (vaKeyboardKeys)'E' ) ) accumMove += up * moveSpeed;
}
objectPos += accumMove * smoothingLerpK;
m_accumMove = accumMove * (1-smoothingLerpK);
}
objectOri = vaQuaternion::FromRotationMatrix( m_baseOrientation * cameraWorld );
}
camera.SetPosition( objectPos );
camera.SetOrientation( objectOri );
}
vaCameraControllerFlythrough::vaCameraControllerFlythrough( )
{
m_currentTime = 0.0f;
m_totalTime = 0.0f;
//m_userParam0 = 0.0f;
//m_userParam1 = 0.0f;
m_playSpeed = 1.0f;
m_enableLoop = true;
m_fixedUp = false;
m_fixedUpVec = vaVector3( 0.0f, 0.0f, 1.0f );
}
vaCameraControllerFlythrough::~vaCameraControllerFlythrough( )
{
}
void vaCameraControllerFlythrough::CameraAttached( const shared_ptr<vaCameraBase> & camera )
{
vaCameraControllerBase::CameraAttached( camera );
}
bool vaCameraControllerFlythrough::FindKeys( float time, int & keyIndexFrom, int & keyIndexTo )
{
time = vaMath::Clamp( time, 0.0f, m_totalTime );
if( m_keys.size() == 0 )
return false;
keyIndexFrom = 0;
keyIndexTo = 0;
if( m_keys.size() == 1 )
return true;
// linear search - find binary in std:: algorithms when more perf needed :)
for( keyIndexTo = 1; keyIndexTo < m_keys.size(); keyIndexTo++ )
{
if( m_keys[keyIndexTo].Time >= time )
break;
}
keyIndexFrom = keyIndexTo-1;
return true;
}
void vaCameraControllerFlythrough::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus )
{
hasFocus; //unreferenced
if( m_keys.size( ) == 0 )
return;
SetPlayTime( GetPlayTime() + deltaTime * GetPlaySpeed() );
int indexFrom, indexTo;
if( !FindKeys( GetPlayTime(), indexFrom, indexTo ) )
return;
Keyframe & keyFrom = m_keys[indexFrom];
Keyframe & keyTo = m_keys[indexTo];
float timeBetweenKeys = keyTo.Time - keyFrom.Time;
timeBetweenKeys = vaMath::Max( 0.00001f, timeBetweenKeys );
float lerpK = vaMath::Clamp( (m_currentTime-keyFrom.Time) / timeBetweenKeys, 0.0f, 1.0f );
//lerpK = vaMath::Smoothstep( lerpK );
vaVector3 pos = vaVector3::Lerp( keyFrom.Position, keyTo.Position, lerpK );
vaQuaternion rot = vaQuaternion::Slerp( keyFrom.Orientation, keyTo.Orientation, lerpK );
#if 1
int index0 = vaMath::Max( 0, indexFrom-1 );
int index1 = indexFrom;
int index2 = indexTo;
int index3 = vaMath::Min( (int)m_keys.size()-1, indexTo+1 );
Keyframe & key0 = m_keys[index0];
Keyframe & key1 = m_keys[index1];
Keyframe & key2 = m_keys[index2];
Keyframe & key3 = m_keys[index3];
pos = vaVector3::CatmullRom( key0.Position, key1.Position, key2.Position, key3.Position, lerpK );
//pos = vaVector3::Hermite( key1.Position, (key2.Position - key0.Position).Normalized(), key2.Position, (key3.Position - key1.Position).Normalized(), lerpK );
//rot = vaQuaternion::Squad( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK );
//rot = vaQuaternion::Slerp( key0.Orientation, key1.Orientation, lerpK );
rot = vaQuaternion::CatmullRom( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK );
#endif
if( m_fixedUp )
{
vaVector3 currentUp = rot.GetAxisY();
vaVector3 rotAxis = vaVector3::Cross( currentUp, m_fixedUpVec );
float rotAngle = vaVector3::AngleBetweenVectors( currentUp, m_fixedUpVec );
rot *= vaQuaternion::RotationAxis( rotAxis, rotAngle );
}
// float lf = vaMath::TimeIndependentLerpF( deltaTime, 5.0f / (currentKey.ShowTime+2.0f) );
//
// pos = vaMath::Lerp( camera.GetPosition(), pos, lf );
// rot = vaQuaternion::Slerp( camera.GetOrientation(), rot, lf );
camera.SetPosition( pos );
camera.SetOrientation( rot );
}
void vaCameraControllerFlythrough::AddKey( const Keyframe & newKey )
{
vector< Keyframe >::iterator it = std::lower_bound( m_keys.begin( ), m_keys.end( ), newKey, ( [ this ]( const Keyframe & a, const Keyframe & b ) { return a.Time < b.Time; } ) );
m_keys.insert( it, newKey ); // insert before iterator it
m_totalTime = m_keys.back().Time;
}
void vaCameraControllerFlythrough::UIPropertiesItemDraw( )
{
#ifdef VA_IMGUI_INTEGRATION_ENABLED
//ImGui::Text( "Time: %", m_currentTime );
ImGui::SliderFloat( "Playback position", &m_currentTime, 0.0f, m_totalTime );
m_currentTime = vaMath::Clamp( m_currentTime, 0.0f, m_totalTime );
ImGui::InputFloat( "Playback speed", &m_playSpeed, 0.2f );
m_playSpeed = vaMath::Clamp( m_playSpeed, -10.0f, 10.0f );
#endif
} | 41.0375 | 216 | 0.611407 | magcius |
d5411a6e6847c2c0491ca39d39d322e459ea5dec | 1,055 | cpp | C++ | library/view/widget/default_theme_provider.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 39 | 2019-06-22T12:25:54.000Z | 2022-03-14T05:42:44.000Z | library/view/widget/default_theme_provider.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 5 | 2019-06-29T10:58:43.000Z | 2020-09-04T08:44:09.000Z | library/view/widget/default_theme_provider.cpp | topillar/PuTTY-ng | 1f5bf26de0f42e03ef4f100fa879b16216d61abf | [
"MIT"
] | 10 | 2019-08-07T06:08:23.000Z | 2022-03-14T05:42:47.000Z |
#include "default_theme_provider.h"
#include "ui_base/resource/resource_bundle.h"
#include "view/widget/native_widget_win.h"
namespace view
{
DefaultThemeProvider::DefaultThemeProvider() {}
DefaultThemeProvider::~DefaultThemeProvider() {}
void DefaultThemeProvider::Init(Profile* profile) {}
SkBitmap* DefaultThemeProvider::GetBitmapNamed(int id) const
{
return ui::ResourceBundle::GetSharedInstance().GetBitmapNamed(id);
}
SkColor DefaultThemeProvider::GetColor(int id) const
{
// Return debugging-blue.
return 0xff0000ff;
}
bool DefaultThemeProvider::GetDisplayProperty(int id, int* result) const
{
return false;
}
bool DefaultThemeProvider::ShouldUseNativeFrame() const
{
return NativeWidgetWin::IsAeroGlassEnabled();
}
bool DefaultThemeProvider::HasCustomImage(int id) const
{
return false;
}
RefCountedMemory* DefaultThemeProvider::GetRawData(int id) const
{
return NULL;
}
} //namespace view | 21.979167 | 76 | 0.685308 | topillar |
d5440368d4912236ac2556e9f1b5b13b571bc46e | 8,329 | hxx | C++ | include/semaphore.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | include/semaphore.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | include/semaphore.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*-
//===--------------------------- semaphore --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_SEMAPHORE
#define _LIBCPP_SEMAPHORE
/*
semaphore synopsis
namespace std {
template<ptrdiff_t least_max_value = implementation-defined>
class counting_semaphore
{
public:
static constexpr ptrdiff_t max() noexcept;
constexpr explicit counting_semaphore(ptrdiff_t desired);
~counting_semaphore();
counting_semaphore(const counting_semaphore&) = delete;
counting_semaphore& operator=(const counting_semaphore&) = delete;
void release(ptrdiff_t update = 1);
void acquire();
bool try_acquire() noexcept;
template<class Rep, class Period>
bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time);
template<class Clock, class Duration>
bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time);
private:
ptrdiff_t counter; // exposition only
};
using binary_semaphore = counting_semaphore<1>;
}
*/
#ifndef __simt__
#include <__config.hxx>
#include <__threading_support.hxx>
#include <atomic.hxx>
#include <cassert.hxx>
#endif
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifdef _LIBCPP_HAS_NO_THREADS
# error <semaphore> is not supported on this single threaded system
#endif
#if _LIBCPP_STD_VER < 11
# error <semaphore> is requires C++11 or later
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
template<int _Sco>
class __atomic_semaphore_base
{
__atomic_base<ptrdiff_t, _Sco> __count;
#ifndef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE
__libcpp_contention_t __contention;
#endif
public:
_LIBCPP_INLINE_VISIBILITY
__atomic_semaphore_base(ptrdiff_t __count) : __count(__count) { }
~__atomic_semaphore_base() = default;
__atomic_semaphore_base(__atomic_semaphore_base const&) = delete;
__atomic_semaphore_base& operator=(__atomic_semaphore_base const&) = delete;
_LIBCPP_INLINE_VISIBILITY
void release(ptrdiff_t __update = 1)
{
if(0 < __count.fetch_add(__update, memory_order_release))
;
#ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE
else if(__update > 1)
__cxx_atomic_notify_all(&__count.__a_);
else
__cxx_atomic_notify_one(&__count.__a_);
#else
else if(__update > 1)
__cxx_atomic_notify_all(&__count.__a_, &__contention);
else
__cxx_atomic_notify_one(&__count.__a_, &__contention);
#endif
}
_LIBCPP_INLINE_VISIBILITY
void acquire()
{
ptrdiff_t __old = __count.load(memory_order_relaxed);
while (1) {
if(__old == 0) {
#ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE
__cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed);
#else
__cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed, &__contention);
#endif
__old = __count.load(memory_order_relaxed);
continue;
}
if(__count.compare_exchange_weak(__old, __old - 1,
memory_order_acquire, memory_order_relaxed))
break;
}
}
template <class Rep, class Period>
_LIBCPP_INLINE_VISIBILITY
bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
{
return __libcpp_thread_poll_with_backoff([=]() {
ptrdiff_t __old = __count.load(memory_order_acquire);
if (__old == 0)
return false;
return __count.compare_exchange_weak(__old, __old - 1,
memory_order_acquire, memory_order_relaxed);
}, __rel_time);
}
};
#ifndef _LIBCPP_HAS_NO_SEMAPHORES
class __sem_semaphore_basic_base {
#ifdef __APPLE__
atomic<ptrdiff_t> __balance = {0};
#endif
__libcpp_semaphore_t __semaphore;
public:
_LIBCPP_EXPORTED_FROM_ABI
__sem_semaphore_basic_base(ptrdiff_t __count);
_LIBCPP_EXPORTED_FROM_ABI
~__sem_semaphore_basic_base();
_LIBCPP_EXPORTED_FROM_ABI
void release(ptrdiff_t __update);
_LIBCPP_EXPORTED_FROM_ABI
void acquire();
_LIBCPP_EXPORTED_FROM_ABI
bool try_acquire_for(chrono::nanoseconds __rel_time);
};
#ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER
class __sem_semaphore_back_buffered_base {
_LIBCPP_INLINE_VISIBILITY
void __backfill();
__sem_semaphore_basic_base __semaphore;
atomic<ptrdiff_t> __backbuffer;
public:
_LIBCPP_EXPORTED_FROM_ABI
__sem_semaphore_back_buffered_base(ptrdiff_t __count);
_LIBCPP_EXPORTED_FROM_ABI
~__sem_semaphore_back_buffered_base();
_LIBCPP_EXPORTED_FROM_ABI
void release(ptrdiff_t __update);
_LIBCPP_EXPORTED_FROM_ABI
void acquire();
_LIBCPP_EXPORTED_FROM_ABI
bool try_acquire_for(chrono::nanoseconds __rel_time);
};
#endif //_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER
#ifndef _LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER
class __sem_semaphore_front_buffered_base {
_LIBCPP_INLINE_VISIBILITY
bool __try_acquire_fast();
_LIBCPP_INLINE_VISIBILITY
void __try_done();
#ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER
__sem_semaphore_back_buffered_base __semaphore;
#else
__sem_semaphore_basic_base __semaphore;
#endif
atomic<ptrdiff_t> __frontbuffer;
public:
_LIBCPP_EXPORTED_FROM_ABI
__sem_semaphore_front_buffered_base(ptrdiff_t __count);
_LIBCPP_EXPORTED_FROM_ABI
~__sem_semaphore_front_buffered_base();
_LIBCPP_EXPORTED_FROM_ABI
void release(ptrdiff_t __update);
_LIBCPP_EXPORTED_FROM_ABI
void acquire();
_LIBCPP_EXPORTED_FROM_ABI
bool try_acquire_for(chrono::nanoseconds __rel_time);
};
#endif //_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER
#endif //_LIBCPP_HAS_NO_SEMAPHORES
#if defined(_LIBCPP_HAS_NO_SEMAPHORES)
template<int _Sco, ptrdiff_t>
using __semaphore_base = __atomic_semaphore_base<_Sco>;
#else
# if !defined(_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER)
using __sem_semaphore_base = __sem_semaphore_front_buffered_base;
# elif !defined(_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER)
using __sem_semaphore_base = __sem_semaphore_back_buffered_base;
# else
using __sem_semaphore_base = __sem_semaphore_basic_base;
# endif
template<int _Sco, ptrdiff_t __least_max_value>
using __semaphore_base =
typename conditional<(__least_max_value > 1 && __least_max_value <= _LIBCPP_SEMAPHORE_MAX),
__sem_semaphore_base,
__atomic_semaphore_base<_Sco>>::type;
#endif
template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
class counting_semaphore
{
__semaphore_base<0, __least_max_value> __semaphore;
public:
static constexpr ptrdiff_t max() noexcept {
return __least_max_value;
}
_LIBCPP_INLINE_VISIBILITY
counting_semaphore(ptrdiff_t __count = 0) : __semaphore(__count) { }
~counting_semaphore() = default;
counting_semaphore(const counting_semaphore&) = delete;
counting_semaphore& operator=(const counting_semaphore&) = delete;
_LIBCPP_INLINE_VISIBILITY
void release(ptrdiff_t __update = 1)
{
__semaphore.release(__update);
}
_LIBCPP_INLINE_VISIBILITY
void acquire()
{
__semaphore.acquire();
}
template<class Rep, class Period>
_LIBCPP_INLINE_VISIBILITY
bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
{
return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
}
_LIBCPP_INLINE_VISIBILITY
bool try_acquire()
{
return try_acquire_for(chrono::nanoseconds::zero());
}
template <class Clock, class Duration>
_LIBCPP_INLINE_VISIBILITY
bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time)
{
auto const current = Clock::now();
if(current >= __abs_time)
return try_acquire();
else
return try_acquire_for(__abs_time - current);
}
};
using binary_semaphore = counting_semaphore<1>;
_LIBCPP_END_NAMESPACE_STD
#endif //_LIBCPP_SEMAPHORE
| 29.122378 | 100 | 0.715452 | K-Wu |
d5449f863e08673cc00b0f7277f890cb4164ab98 | 34,521 | cpp | C++ | Testing/Marlin-2.0.x/Marlin/src/HAL/shared/backtrace/unwarm_thumb.cpp | qisback/Geeetech-i3-B-pro-configs | a2c309923c4e68103addda677fda190238a1abe0 | [
"CC-BY-4.0"
] | 5 | 2020-05-17T21:16:41.000Z | 2021-06-11T04:46:31.000Z | Testing/Marlin-2.0.x/Marlin/src/HAL/shared/backtrace/unwarm_thumb.cpp | qisback/Geeetech-i3-B-pro-configs | a2c309923c4e68103addda677fda190238a1abe0 | [
"CC-BY-4.0"
] | 1 | 2020-09-27T14:53:34.000Z | 2020-09-27T14:53:34.000Z | src/HAL/shared/backtrace/unwarm_thumb.cpp | Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3 | d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20 | [
"MIT"
] | 2 | 2019-07-22T20:31:15.000Z | 2021-08-01T00:15:38.000Z | /***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for it's use or misuse - this software is without warranty.
***************************************************************************
* File Description: Abstract interpretation for Thumb mode.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWARM_THUMB"
#include <stdio.h>
#include "unwarm.h"
/** Sign extend an 11 bit value.
* This function simply inspects bit 11 of the input \a value, and if
* set, the top 5 bits are set to give a 2's compliment signed value.
* \param value The value to sign extend.
* \return The signed-11 bit value stored in a 16bit data type.
*/
static int32_t signExtend11(const uint16_t value) {
return (value & 0x400) ? value | 0xFFFFF800 : value;
}
UnwResult UnwStartThumb(UnwState * const state) {
bool found = false;
uint16_t t = UNW_MAX_INSTR_COUNT;
uint32_t lastJumpAddr = 0; // Last JUMP address, to try to detect infinite loops
bool loopDetected = false; // If a loop was detected
do {
uint16_t instr;
/* Attempt to read the instruction */
if (!state->cb->readH(state->regData[15].v & (~0x1), &instr))
return UNWIND_IREAD_H_FAIL;
UnwPrintd4("T %x %x %04x:", state->regData[13].v, state->regData[15].v, instr);
/* Check that the PC is still on Thumb alignment */
if (!(state->regData[15].v & 0x1)) {
UnwPrintd1("\nError: PC misalignment\n");
return UNWIND_INCONSISTENT;
}
/* Check that the SP and PC have not been invalidated */
if (!M_IsOriginValid(state->regData[13].o) || !M_IsOriginValid(state->regData[15].o)) {
UnwPrintd1("\nError: PC or SP invalidated\n");
return UNWIND_INCONSISTENT;
}
/*
* Detect 32bit thumb instructions
*/
if ((instr & 0xE000) == 0xE000 && (instr & 0x1800) != 0) {
uint16_t instr2;
/* Check next address */
state->regData[15].v += 2;
/* Attempt to read the 2nd part of the instruction */
if (!state->cb->readH(state->regData[15].v & (~0x1), &instr2))
return UNWIND_IREAD_H_FAIL;
UnwPrintd3(" %x %04x:", state->regData[15].v, instr2);
/*
* Load/Store multiple: Only interpret
* PUSH and POP
*/
if ((instr & 0xFE6F) == 0xE82D) {
bool L = !!(instr & 0x10);
uint16_t rList = instr2;
if (L) {
uint8_t r;
/* Load from memory: POP */
UnwPrintd1("POP {Rlist}\n");
/* Load registers from stack */
for (r = 0; r < 16; r++) {
if (rList & (0x1 << r)) {
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o)) {
state->regData[r].o = REG_VAL_FROM_STACK;
/* If restoring the PC */
if (r == 15) {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
} else {
if (r == 15) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
}
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
}
}
else {
int8_t r;
/* Store to memory: PUSH */
UnwPrintd1("PUSH {Rlist}");
for (r = 15; r >= 0; r--) {
if (rList & (0x1 << r)) {
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
}
}
}
/*
* PUSH register
*/
else if (instr == 0xF84D && (instr2 & 0x0FFF) == 0x0D04) {
uint8_t r = instr2 >> 12;
/* Store to memory: PUSH */
UnwPrintd2("PUSH {R%d}\n", r);
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
/*
* POP register
*/
else if (instr == 0xF85D && (instr2 & 0x0FFF) == 0x0B04) {
uint8_t r = instr2 >> 12;
/* Load from memory: POP */
UnwPrintd2("POP {R%d}\n", r);
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o)) {
state->regData[r].o = REG_VAL_FROM_STACK;
/* If restoring the PC */
if (r == 15) {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
} else {
if (r == 15) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
}
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
/*
* TBB / TBH
*/
else if ((instr & 0xFFF0) == 0xE8D0 && (instr2 & 0xFFE0) == 0xF000) {
/* We are only interested in
* the forms
* TBB [PC, ...]
* TBH [PC, ..., LSL #1]
* as those are used by the C compiler to implement
* the switch clauses
*/
uint8_t rn = instr & 0xF;
bool H = !!(instr2 & 0x10);
UnwPrintd5("TB%c [r%d,r%d%s]\n", H ? 'H' : 'B', rn, (instr2 & 0xF), H ? ",LSL #1" : "");
// We are only interested if the RN is the PC. Let's choose the 1st destination
if (rn == 15) {
if (H) {
uint16_t rv;
if (!state->cb->readH((state->regData[15].v & (~1)) + 2, &rv))
return UNWIND_DREAD_H_FAIL;
state->regData[15].v += rv * 2;
}
else {
uint8_t rv;
if (!state->cb->readB((state->regData[15].v & (~1)) + 2, &rv))
return UNWIND_DREAD_B_FAIL;
state->regData[15].v += rv * 2;
}
}
}
/*
* Unconditional branch
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x9000) {
uint32_t v;
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm10 = (instr & 0x3FF);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFE000000;
UnwPrintd2("B %d \n", imm32);
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Compute the jump address */
v = state->regData[15].v + 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", v);
/* Did we detect an infinite loop ? */
loopDetected = lastJumpAddr == v;
/* Remember the last address we jumped to */
lastJumpAddr = v;
}
/*
* Branch with link
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0xD000) {
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm10 = (instr & 0x3FF);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFE000000;
UnwPrintd2("BL %d \n", imm32);
/* Never taken, as we are unwinding the stack */
if (0) {
/* Store return address in LR register */
state->regData[14].v = state->regData[15].v + 2;
state->regData[14].o = REG_VAL_FROM_CONST;
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" Return PC=%x", state->regData[15].v);
/* Report the return address, including mode bit */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Determine the new mode */
if (state->regData[15].v & 0x1) {
/* Branching to THUMB */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 2;
}
else {
/* Branch to ARM */
return UnwStartArm(state);
}
}
}
/*
* Conditional branches. Usually not taken, unless infinite loop is detected
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x8000) {
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm6 = (instr & 0x3F);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 20) | (I1 << 19) | (I2 << 18) |(imm6 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFFE00000;
UnwPrintd2("Bcond %d\n", imm32);
/* Take the jump only if a loop is detected */
if (loopDetected) {
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", state->regData[15].v + 2);
}
}
/*
* PC-relative load
* LDR Rd,[PC, #+/-imm]
*/
else if ((instr & 0xFF7F) == 0xF85F) {
uint8_t rt = (instr2 & 0xF000) >> 12;
uint8_t imm12 = (instr2 & 0x0FFF);
bool A = !!(instr & 0x80);
uint32_t address;
/* Compute load address, adding a word to account for prefetch */
address = (state->regData[15].v & (~0x3)) + 4;
if (A) address += imm12;
else address -= imm12;
UnwPrintd4("LDR r%d,[PC #%c0x%08x]", rt, A?'+':'-', address);
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
/*
* LDR immediate.
* We are only interested when destination is PC.
* LDR Rt,[Rn , #n]
*/
else if ((instr & 0xFFF0) == 0xF8D0) {
uint8_t rn = (instr & 0xF);
uint8_t rt = (instr2 & 0xF000) >> 12;
uint16_t imm12 = (instr2 & 0xFFF);
/* If destination is PC and we don't know the source value, then fail */
if (!M_IsOriginValid(state->regData[rn].o)) {
state->regData[rt].o = state->regData[rn].o;
}
else {
uint32_t address = state->regData[rn].v + imm12;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
}
/*
* LDR immediate
* We are only interested when destination is PC.
* LDR Rt,[Rn , #-n]
* LDR Rt,[Rn], #+/-n]
* LDR Rt,[Rn, #+/-n]!
*/
else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0800) == 0x0800) {
uint8_t rn = (instr & 0xF);
uint8_t rt = (instr2 & 0xF000) >> 12;
uint16_t imm8 = (instr2 & 0xFF);
bool P = !!(instr2 & 0x400);
bool U = !!(instr2 & 0x200);
bool W = !!(instr2 & 0x100);
if (!M_IsOriginValid(state->regData[rn].o))
state->regData[rt].o = state->regData[rn].o;
else {
uint32_t offaddress = state->regData[rn].v + (U ? imm8 + imm8 : 0),
address = P ? offaddress : state->regData[rn].v;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
if (W) state->regData[rn].v = offaddress;
}
}
/*
* LDR (register).
* We are interested in the form
* ldr Rt, [Rn, Rm, lsl #x]
* Where Rt is PC, Rn value is known, Rm is not known or unknown
*/
else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0FC0) == 0x0000) {
const uint8_t rn = (instr & 0xF),
rt = (instr2 & 0xF000) >> 12,
rm = (instr2 & 0xF),
imm2 = (instr2 & 0x30) >> 4;
if (!M_IsOriginValid(state->regData[rn].o) || !M_IsOriginValid(state->regData[rm].o)) {
/* If Rt is PC, and Rn is known, then do an exception and assume
Rm equals 0 => This takes the first case in a switch() */
if (rt == 15 && M_IsOriginValid(state->regData[rn].o)) {
uint32_t address = state->regData[rn].v;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
else /* Propagate unknown value */
state->regData[rt].o = state->regData[rn].o;
}
else {
uint32_t address = state->regData[rn].v + (state->regData[rm].v << imm2);
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
}
else {
UnwPrintd1("???? (32)");
/* Unknown/undecoded. May alter some register, so invalidate file */
UnwInvalidateRegisterFile(state->regData);
}
/* End of thumb 32bit code */
}
/* Format 1: Move shifted register
* LSL Rd, Rs, #Offset5
* LSR Rd, Rs, #Offset5
* ASR Rd, Rs, #Offset5
*/
else if ((instr & 0xE000) == 0x0000 && (instr & 0x1800) != 0x1800) {
bool signExtend;
const uint8_t op = (instr & 0x1800) >> 11,
offset5 = (instr & 0x07C0) >> 6,
rs = (instr & 0x0038) >> 3,
rd = (instr & 0x0007);
switch (op) {
case 0: /* LSL */
UnwPrintd6("LSL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
state->regData[rd].v = state->regData[rs].v << offset5;
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 1: /* LSR */
UnwPrintd6("LSR r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
state->regData[rd].v = state->regData[rs].v >> offset5;
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 2: /* ASR */
UnwPrintd6("ASL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
signExtend = !!(state->regData[rs].v & 0x8000);
state->regData[rd].v = state->regData[rs].v >> offset5;
if (signExtend) state->regData[rd].v |= 0xFFFFFFFF << (32 - offset5);
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 2: add/subtract
* ADD Rd, Rs, Rn
* ADD Rd, Rs, #Offset3
* SUB Rd, Rs, Rn
* SUB Rd, Rs, #Offset3
*/
else if ((instr & 0xF800) == 0x1800) {
bool I = !!(instr & 0x0400);
bool op = !!(instr & 0x0200);
uint8_t rn = (instr & 0x01C0) >> 6;
uint8_t rs = (instr & 0x0038) >> 3;
uint8_t rd = (instr & 0x0007);
/* Print decoding */
UnwPrintd6("%s r%d, r%d, %c%d\t;",op ? "SUB" : "ADD",rd, rs,I ? '#' : 'r',rn);
UnwPrintd5("r%d %s, r%d %s",rd, M_Origin2Str(state->regData[rd].o),rs, M_Origin2Str(state->regData[rs].o));
if (!I) {
UnwPrintd3(", r%d %s", rn, M_Origin2Str(state->regData[rn].o));
/* Perform calculation */
state->regData[rd].v = state->regData[rs].v + (op ? -state->regData[rn].v : state->regData[rn].v);
/* Propagate the origin */
if (M_IsOriginValid(state->regData[rs].o) && M_IsOriginValid(state->regData[rn].o)) {
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
else
state->regData[rd].o = REG_VAL_INVALID;
}
else {
/* Perform calculation */
state->regData[rd].v = state->regData[rs].v + (op ? -rn : rn);
/* Propagate the origin */
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
}
/* Format 3: move/compare/add/subtract immediate
* MOV Rd, #Offset8
* CMP Rd, #Offset8
* ADD Rd, #Offset8
* SUB Rd, #Offset8
*/
else if ((instr & 0xE000) == 0x2000) {
uint8_t op = (instr & 0x1800) >> 11;
uint8_t rd = (instr & 0x0700) >> 8;
uint8_t offset8 = (instr & 0x00FF);
switch (op) {
case 0: /* MOV */
UnwPrintd3("MOV r%d, #0x%x", rd, offset8);
state->regData[rd].v = offset8;
state->regData[rd].o = REG_VAL_FROM_CONST;
break;
case 1: /* CMP */
/* Irrelevant to unwinding */
UnwPrintd1("CMP ???");
break;
case 2: /* ADD */
UnwPrintd5("ADD r%d, #0x%x\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o));
state->regData[rd].v += offset8;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 3: /* SUB */
UnwPrintd5("SUB r%d, #0x%d\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o));
state->regData[rd].v -= offset8;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 4: ALU operations
* AND Rd, Rs
* EOR Rd, Rs
* LSL Rd, Rs
* LSR Rd, Rs
* ASR Rd, Rs
* ADC Rd, Rs
* SBC Rd, Rs
* ROR Rd, Rs
* TST Rd, Rs
* NEG Rd, Rs
* CMP Rd, Rs
* CMN Rd, Rs
* ORR Rd, Rs
* MUL Rd, Rs
* BIC Rd, Rs
* MVN Rd, Rs
*/
else if ((instr & 0xFC00) == 0x4000) {
uint8_t op = (instr & 0x03C0) >> 6;
uint8_t rs = (instr & 0x0038) >> 3;
uint8_t rd = (instr & 0x0007);
#ifdef UNW_DEBUG
static const char * const mnu[16] = {
"AND", "EOR", "LSL", "LSR",
"ASR", "ADC", "SBC", "ROR",
"TST", "NEG", "CMP", "CMN",
"ORR", "MUL", "BIC", "MVN" };
#endif
/* Print the mnemonic and registers */
switch (op) {
case 0: /* AND */
case 1: /* EOR */
case 2: /* LSL */
case 3: /* LSR */
case 4: /* ASR */
case 7: /* ROR */
case 9: /* NEG */
case 12: /* ORR */
case 13: /* MUL */
case 15: /* MVN */
UnwPrintd8("%s r%d ,r%d\t; r%d %s, r%d %s",mnu[op],rd, rs, rd, M_Origin2Str(state->regData[rd].o), rs, M_Origin2Str(state->regData[rs].o));
break;
case 5: /* ADC */
case 6: /* SBC */
UnwPrintd4("%s r%d, r%d", mnu[op], rd, rs);
break;
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
/* Irrelevant to unwinding */
UnwPrintd2("%s ???", mnu[op]);
break;
case 14: /* BIC */
UnwPrintd5("r%d ,r%d\t; r%d %s", rd, rs, rs, M_Origin2Str(state->regData[rs].o));
break;
}
/* Perform operation */
switch (op) {
case 0: /* AND */
state->regData[rd].v &= state->regData[rs].v;
break;
case 1: /* EOR */
state->regData[rd].v ^= state->regData[rs].v;
break;
case 2: /* LSL */
state->regData[rd].v <<= state->regData[rs].v;
break;
case 3: /* LSR */
state->regData[rd].v >>= state->regData[rs].v;
break;
case 4: /* ASR */
if (state->regData[rd].v & 0x80000000) {
state->regData[rd].v >>= state->regData[rs].v;
state->regData[rd].v |= 0xFFFFFFFF << (32 - state->regData[rs].v);
}
else {
state->regData[rd].v >>= state->regData[rs].v;
}
break;
case 5: /* ADC */
case 6: /* SBC */
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
break;
case 7: /* ROR */
state->regData[rd].v = (state->regData[rd].v >> state->regData[rs].v) |
(state->regData[rd].v << (32 - state->regData[rs].v));
break;
case 9: /* NEG */
state->regData[rd].v = -state->regData[rs].v;
break;
case 12: /* ORR */
state->regData[rd].v |= state->regData[rs].v;
break;
case 13: /* MUL */
state->regData[rd].v *= state->regData[rs].v;
break;
case 14: /* BIC */
state->regData[rd].v &= ~state->regData[rs].v;
break;
case 15: /* MVN */
state->regData[rd].v = ~state->regData[rs].v;
break;
}
/* Propagate data origins */
switch (op) {
case 0: /* AND */
case 1: /* EOR */
case 2: /* LSL */
case 3: /* LSR */
case 4: /* ASR */
case 7: /* ROR */
case 12: /* ORR */
case 13: /* MUL */
case 14: /* BIC */
if (M_IsOriginValid(state->regData[rd].o) && M_IsOriginValid(state->regData[rs].o)) {
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
else
state->regData[rd].o = REG_VAL_INVALID;
break;
case 5: /* ADC */
case 6: /* SBC */
/* C-bit not tracked */
state->regData[rd].o = REG_VAL_INVALID;
break;
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
/* Nothing propagated */
break;
case 9: /* NEG */
case 15: /* MVN */
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 5: Hi register operations/branch exchange
* ADD Rd, Hs
* CMP Hd, Rs
* MOV Hd, Hs
*/
else if ((instr & 0xFC00) == 0x4400) {
uint8_t op = (instr & 0x0300) >> 8;
bool h1 = (instr & 0x0080) ? true: false;
bool h2 = (instr & 0x0040) ? true: false;
uint8_t rhs = (instr & 0x0038) >> 3;
uint8_t rhd = (instr & 0x0007);
/* Adjust the register numbers */
if (h2) rhs += 8;
if (h1) rhd += 8;
switch (op) {
case 0: /* ADD */
UnwPrintd5("ADD r%d, r%d\t; r%d %s", rhd, rhs, rhs, M_Origin2Str(state->regData[rhs].o));
state->regData[rhd].v += state->regData[rhs].v;
state->regData[rhd].o = state->regData[rhs].o;
state->regData[rhd].o |= REG_VAL_ARITHMETIC;
break;
case 1: /* CMP */
/* Irrelevant to unwinding */
UnwPrintd1("CMP ???");
break;
case 2: /* MOV */
UnwPrintd5("MOV r%d, r%d\t; r%d %s", rhd, rhs, rhd, M_Origin2Str(state->regData[rhs].o));
state->regData[rhd].v = state->regData[rhs].v;
state->regData[rhd].o = state->regData[rhd].o;
break;
case 3: /* BX */
UnwPrintd4("BX r%d\t; r%d %s\n", rhs, rhs, M_Origin2Str(state->regData[rhs].o));
/* Only follow BX if the data was from the stack or BX LR */
if (rhs == 14 || state->regData[rhs].o == REG_VAL_FROM_STACK) {
UnwPrintd2(" Return PC=0x%x\n", state->regData[rhs].v & (~0x1));
/* Report the return address, including mode bit */
if (!UnwReportRetAddr(state, state->regData[rhs].v))
return UNWIND_TRUNCATED;
/* Update the PC */
state->regData[15].v = state->regData[rhs].v;
/* Determine the new mode */
if (state->regData[rhs].v & 0x1) {
/* Branching to THUMB */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 2;
}
else /* Branch to ARM */
return UnwStartArm(state);
}
else {
UnwPrintd4("\nError: BX to invalid register: r%d = 0x%x (%s)\n", rhs, state->regData[rhs].o, M_Origin2Str(state->regData[rhs].o));
return UNWIND_FAILURE;
}
}
}
/* Format 9: PC-relative load
* LDR Rd,[PC, #imm]
*/
else if ((instr & 0xF800) == 0x4800) {
uint8_t rd = (instr & 0x0700) >> 8;
uint8_t word8 = (instr & 0x00FF);
uint32_t address;
/* Compute load address, adding a word to account for prefetch */
address = (state->regData[15].v & (~0x3)) + 4 + (word8 << 2);
UnwPrintd3("LDR r%d, 0x%08x", rd, address);
if (!UnwMemReadRegister(state, address, &state->regData[rd]))
return UNWIND_DREAD_W_FAIL;
}
/* Format 13: add offset to Stack Pointer
* ADD sp,#+imm
* ADD sp,#-imm
*/
else if ((instr & 0xFF00) == 0xB000) {
uint8_t value = (instr & 0x7F) * 4;
/* Check the negative bit */
if ((instr & 0x80) != 0) {
UnwPrintd2("SUB sp,#0x%x", value);
state->regData[13].v -= value;
}
else {
UnwPrintd2("ADD sp,#0x%x", value);
state->regData[13].v += value;
}
}
/* Format 14: push/pop registers
* PUSH {Rlist}
* PUSH {Rlist, LR}
* POP {Rlist}
* POP {Rlist, PC}
*/
else if ((instr & 0xF600) == 0xB400) {
bool L = !!(instr & 0x0800);
bool R = !!(instr & 0x0100);
uint8_t rList = (instr & 0x00FF);
if (L) {
uint8_t r;
/* Load from memory: POP */
UnwPrintd2("POP {Rlist%s}\n", R ? ", PC" : "");
for (r = 0; r < 8; r++) {
if (rList & (0x1 << r)) {
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o))
state->regData[r].o = REG_VAL_FROM_STACK;
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
}
/* Check if the PC is to be popped */
if (R) {
/* Get the return address */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[15]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (!M_IsOriginValid(state->regData[15].o)) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
else {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Update the pc */
state->regData[13].v += 4;
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
}
}
else {
int8_t r;
/* Store to memory: PUSH */
UnwPrintd2("PUSH {Rlist%s}", R ? ", LR" : "");
/* Check if the LR is to be pushed */
if (R) {
UnwPrintd3("\n lr = 0x%08x\t; %s", state->regData[14].v, M_Origin2Str(state->regData[14].o));
state->regData[13].v -= 4;
/* Write the register value to memory */
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[14]))
return UNWIND_DWRITE_W_FAIL;
}
for (r = 7; r >= 0; r--) {
if (rList & (0x1 << r)) {
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
}
}
}
/*
* Conditional branches
* Bcond
*/
else if ((instr & 0xF000) == 0xD000) {
int32_t branchValue = (instr & 0xFF);
if (branchValue & 0x80) branchValue |= 0xFFFFFF00;
/* Branch distance is twice that specified in the instruction. */
branchValue *= 2;
UnwPrintd2("Bcond %d \n", branchValue);
/* Only take the branch if a loop was detected */
if (loopDetected) {
/* Update PC */
state->regData[15].v += branchValue;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", state->regData[15].v + 2);
}
}
/* Format 18: unconditional branch
* B label
*/
else if ((instr & 0xF800) == 0xE000) {
uint32_t v;
int32_t branchValue = signExtend11(instr & 0x07FF);
/* Branch distance is twice that specified in the instruction. */
branchValue *= 2;
UnwPrintd2("B %d \n", branchValue);
/* Update PC */
state->regData[15].v += branchValue;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Compute the jump address */
v = state->regData[15].v + 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", v);
/* Did we detect an infinite loop ? */
loopDetected = lastJumpAddr == v;
/* Remember the last address we jumped to */
lastJumpAddr = v;
}
else {
UnwPrintd1("????");
/* Unknown/undecoded. May alter some register, so invalidate file */
UnwInvalidateRegisterFile(state->regData);
}
UnwPrintd1("\n");
/* Should never hit the reset vector */
if (state->regData[15].v == 0) return UNWIND_RESET;
/* Check next address */
state->regData[15].v += 2;
/* Garbage collect the memory hash (used only for the stack) */
UnwMemHashGC(state);
if (--t == 0) return UNWIND_EXHAUSTED;
} while (!found);
return UNWIND_SUCCESS;
}
#endif // __arm__ || __thumb__
| 32.323034 | 149 | 0.499261 | qisback |
d54606df4cb1464acde729e0b0d7c31afe675644 | 2,401 | cpp | C++ | test/Euclid/Geometry/Test.Axis.cpp | kurocha/euclid | 932e4a01043442becc696eb337e796ae9578a078 | [
"Unlicense",
"MIT"
] | 7 | 2015-10-16T20:49:20.000Z | 2019-04-17T09:34:35.000Z | test/Euclid/Geometry/Test.Axis.cpp | kurocha/euclid | 932e4a01043442becc696eb337e796ae9578a078 | [
"Unlicense",
"MIT"
] | null | null | null | test/Euclid/Geometry/Test.Axis.cpp | kurocha/euclid | 932e4a01043442becc696eb337e796ae9578a078 | [
"Unlicense",
"MIT"
] | null | null | null |
#include <UnitTest/UnitTest.hpp>
#include <Euclid/Geometry/Axis.hpp>
namespace Euclid
{
namespace Geometry
{
UnitTest::Suite AxisTestSuite {
"Euclid::Geometry::Axis",
{"Construction",
[](UnitTest::Examiner & examiner) {
auto a1 = Axis<RealT>{IDENTITY};
examiner << "Identity axis has zero translation." << std::endl;
examiner.check(a1.translation().equivalent(0));
examiner << "Identity axis has zero rotation." << std::endl;
examiner.check(a1.rotation().angle().equivalent(0_deg));
auto a2 = Axis<RealT>{{1, 2, 3}, rotate<Z>(R90)};
examiner << "Axis has correct translation." << std::endl;
examiner.check(a2.translation().equivalent({1, 2, 3}));
examiner << "Axis has correct rotation." << std::endl;
examiner.check(a2.rotation().equivalent((Quat)rotate<Z>(R90)));
// This transform should move any points from axis-space to origin-space
auto p1 = a2.to_origin() * Vec3(1, 2, 3);
/// This transform should move any points from origin-space to axis-space
auto p2 = a2.from_origin() * Vec3(0);
examiner << "Point is transformed to origin." << std::endl;
examiner.check(p1.equivalent(0));
examiner << "Point is transformed from origin." << std::endl;
examiner.check(p2.equivalent({1, 2, 3}));
auto p3 = a2.to_origin() * Vec3(2, 2, 3);
examiner << "Point is rotated correctly around Z." << std::endl;
examiner.check(p3.equivalent({0, 1, 0}));
}
},
{"Axis-Axis Mating",
[](UnitTest::Examiner & examiner) {
auto a1 = Axis<RealT>({10, 10, 10}, IDENTITY);
auto a2 = Axis<RealT>({-5, -5, -5}, rotate<Z>(R90));
auto m1 = a1.mate_with(a2);
auto p1 = m1 * Vec3(10, 10, 10);
examiner << "Point is translated." << std::endl;
examiner.check(p1.equivalent({-5, -5, -5}));
auto p2 = m1 * Vec3(10, 10, 15);
examiner << "Point is translated." << std::endl;
examiner.check(p2.equivalent({-5, -5, 0}));
auto p3 = m1 * Vec3(10, 15, 10);
examiner << "Point is translated and rotated." << std::endl;
examiner.check(p3.equivalent({-10, -5, -5}));
auto m2 = a1.mate_with(a2, translate(Vec3{1, 1, 1}));
auto p4 = m2 * Vec3(10, 10, 10);
examiner << "Point is transformed with intermediate translation." << std::endl;
examiner.check(p4.equivalent({-6, -4, -4}));
}
},
};
}
}
| 28.927711 | 84 | 0.602249 | kurocha |
d5480991c16607bdb60b2f0c4de714ceb7538ddc | 3,136 | cpp | C++ | game/Controller.cpp | eslingsby/SimpleEngine | 60b07c235f57388b7b0c6db44cedb8f21b921bea | [
"MIT"
] | null | null | null | game/Controller.cpp | eslingsby/SimpleEngine | 60b07c235f57388b7b0c6db44cedb8f21b921bea | [
"MIT"
] | null | null | null | game/Controller.cpp | eslingsby/SimpleEngine | 60b07c235f57388b7b0c6db44cedb8f21b921bea | [
"MIT"
] | null | null | null | #include "Controller.hpp"
#include "Transform.hpp"
#include "Window.hpp"
Controller::Controller(Engine& engine) : _engine(engine), _possessed(engine) {
SYSFUNC_ENABLE(SystemInterface, update, 0);
SYSFUNC_ENABLE(SystemInterface, cursorPosition, 0);
SYSFUNC_ENABLE(SystemInterface, keyInput, 0);
SYSFUNC_ENABLE(SystemInterface, cursorEnter, 0);
SYSFUNC_ENABLE(SystemInterface, mousePress, 0);
SYSFUNC_ENABLE(SystemInterface, windowOpen, 0);
SYSFUNC_ENABLE(SystemInterface, scrollWheel, 0);
assert(_engine.hasSystem<Window>());
}
void Controller::update(double dt) {
Transform* transform = nullptr;
if (_possessed.valid())
transform = _possessed.get<Transform>();
if (transform && _locked) {
transform->globalRotate(glm::quat({ 0.0, 0.0, -_dMousePos.x * dt }));
transform->localRotate(glm::quat({ -_dMousePos.y * dt, 0.0, 0.0 }));
float moveSpeed = 300.f * dt;
if (_boost)
moveSpeed = 1000.f * dt;
transform->localTranslate(glm::vec3(0.f, 0.f, -_flash * 100.f));
if (_forward)
transform->localTranslate(Transform::localForward * (float)moveSpeed);
if (_back)
transform->localTranslate(Transform::localBack * (float)moveSpeed);
if (_left)
transform->localTranslate(Transform::localLeft * (float)moveSpeed);
if (_right)
transform->localTranslate(Transform::localRight * (float)moveSpeed);
if (_up)
transform->globalTranslate(Transform::globalUp * (float)moveSpeed);
if (_down)
transform->globalTranslate(Transform::globalDown * (float)moveSpeed);
}
_flash = 0;
_dMousePos = { 0.0, 0.0 };
}
void Controller::cursorPosition(glm::dvec2 position){
/*
glm::vec2 newMousePos = position;
if (_mousePos == glm::vec2(0.0, 0.0))
_mousePos = newMousePos;
_dMousePos = newMousePos - _mousePos;
_mousePos = newMousePos;
*/
_dMousePos = position;
}
void Controller::keyInput(uint32_t key, Action action, uint8_t mods){
if (action == Action::Release && key == Key::Key_Escape) {
if (_locked) {
_engine.system<Window>().setLockedCursor(false);
_locked = false;
}
else if (!_locked) {
_engine.quit();
}
return;
}
if (!_possessed.valid())
return;
bool value;
if (action == Action::Press)
value = true;
else if (action == Action::Release)
value = false;
else
return;
switch (key) {
case Key::Key_W:
_forward = value;
return;
case Key::Key_S:
_back = value;
return;
case Key::Key_A:
_left = value;
return;
case Key::Key_D:
_right = value;
return;
case Key::Key_Space:
_up = value;
return;
case Key::Key_LCtrl:
_down = value;
return;
case Key::Key_LShift:
_boost = value;
return;
}
}
void Controller::cursorEnter(bool enterered) {
_cursorInside = enterered;
}
void Controller::mousePress(uint32_t button, Action action, uint8_t mods) {
if (action == Action::Release && !_locked && _cursorInside) {
_engine.system<Window>().setLockedCursor(true);
_locked = true;
}
}
void Controller::windowOpen(bool opened){
if (!opened)
_engine.quit();
}
void Controller::scrollWheel(glm::dvec2 offset){
_flash += (float)offset.y;
}
void Controller::setPossessed(uint64_t id) {
_possessed.set(id);
} | 22.4 | 78 | 0.695791 | eslingsby |
d54ed2bd0cc8105b0a7363378b193d40fdc25943 | 3,021 | hpp | C++ | master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:49.000Z | 2018-12-27T03:20:31.000Z |
//*****************************************************************************
// Copyright (c) 2003. All rights reserved.
// Developed by Jarl Lindrud.
// Contact: jlindrud@hotmail.com .
//*****************************************************************************
#ifndef _UTIL_READWRITEPROTECT_HPP_
#define _UTIL_READWRITEPROTECT_HPP_
#include "ThreadLibrary.hpp"
namespace util {
// Utility for applying the readers/writer synchronization pattern.
// Currently no bias for writers over readers.
// To give multiple read access and single write access to a class X:
//
//class X {
// void read()
// {
// ReadLock lock(rwp);
// // ...
// }
// void write()
// {
// WriteLock lock(rwp);
// // ...
// }
// ReadWriteProtect rwp;
//}
class ReadWriteProtect {
public:
typedef Platform::Threads::recursive_mutex Mutex;
typedef Platform::Threads::condition Event;
ReadWriteProtect() : readerCount(0) {}
Mutex &getReadMutex() { return readMutex; }
Mutex &getWriteMutex() { return writeMutex; }
int &getReaderCount() { return readerCount; }
void waitOnReadUnlock() { Mutex::scoped_lock lock( readUnlockMutex ); readUnlockEvent.wait(lock); }
void notifyReadUnlock() { readUnlockEvent.notify_all(); }
private:
Mutex readMutex;
Mutex writeMutex;
Mutex readUnlockMutex;
Event readUnlockEvent;
int readerCount;
};
class ReadLock {
public:
ReadLock( ReadWriteProtect &rwp ) : rwp( rwp )
{
ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() );
rwp.getReaderCount()++;
}
~ReadLock()
{
{
ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() );
rwp.getReaderCount()--;
}
rwp.notifyReadUnlock();
}
private:
ReadWriteProtect &rwp;
};
class WriteLock {
public:
WriteLock( ReadWriteProtect &rwp )
: rwp( rwp ),
read_lock( rwp.getWriteMutex(), false ),
write_lock( rwp.getWriteMutex(), false )
{
read_lock.lock();
while (rwp.getReaderCount() > 0) {
read_lock.unlock();
rwp.waitOnReadUnlock();
read_lock.lock();
}
write_lock.lock();
}
~WriteLock()
{
write_lock.unlock();
read_lock.unlock();
}
private:
ReadWriteProtect &rwp;
ReadWriteProtect::Mutex::scoped_lock read_RCF_UNUSED_VARIABLE(lock);
ReadWriteProtect::Mutex::scoped_lock write_RCF_UNUSED_VARIABLE(lock);
};
} // namespace util
#endif // ! _UTIL_READWRITEPROTECT_HPP_
| 27.216216 | 108 | 0.506124 | importlib |
d54f794032c0ebf8cba0066e0f27bfec5c6166dc | 172 | hpp | C++ | src/common.hpp | Southclaws/samp-bitmapper | 17807d2bd2955eb7747c989ecd7c10dc43231821 | [
"MIT"
] | 7 | 2017-12-31T13:16:57.000Z | 2020-12-28T12:56:15.000Z | src/common.hpp | Southclaws/samp-bitmapper | 17807d2bd2955eb7747c989ecd7c10dc43231821 | [
"MIT"
] | 2 | 2017-12-31T11:55:22.000Z | 2017-12-31T16:57:00.000Z | src/common.hpp | Southclaws/samp-bitmapper | 17807d2bd2955eb7747c989ecd7c10dc43231821 | [
"MIT"
] | 2 | 2018-07-07T12:34:04.000Z | 2020-11-01T21:58:02.000Z | #pragma warning(default:4005)
extern void** ppPluginData;
extern void* pAMXFunctions;
typedef void (*logprintf_t)(const char* szFormat, ...);
extern logprintf_t logprintf;
| 28.666667 | 55 | 0.77907 | Southclaws |
d5525677ee9f048d3c6f48de9f70c9f385e038f7 | 4,529 | cc | C++ | flecsi/execution/legion/runtime_main.cc | scothalverson/flecsi | a7b2c289b99ecadd0c75cabc491f5c66e543345c | [
"Unlicense"
] | null | null | null | flecsi/execution/legion/runtime_main.cc | scothalverson/flecsi | a7b2c289b99ecadd0c75cabc491f5c66e543345c | [
"Unlicense"
] | null | null | null | flecsi/execution/legion/runtime_main.cc | scothalverson/flecsi | a7b2c289b99ecadd0c75cabc491f5c66e543345c | [
"Unlicense"
] | null | null | null | /*
@@@@@@@@ @@ @@@@@@ @@@@@@@@ @@
/@@///// /@@ @@////@@ @@////// /@@
/@@ /@@ @@@@@ @@ // /@@ /@@
/@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@
/@@//// /@@/@@@@@@@/@@ ////////@@/@@
/@@ /@@/@@//// //@@ @@ /@@/@@
/@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@
// /// ////// ////// //////// //
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
*/
/*! @file */
#include <flecsi-config.h>
#if !defined(FLECSI_ENABLE_MPI)
#error FLECSI_ENABLE_MPI not defined! This file depends on MPI!
#endif
#include <mpi.h>
#include <flecsi/execution/context.h>
// Boost command-line options
#if defined(FLECSI_ENABLE_BOOST)
#include <boost/program_options.hpp>
using namespace boost::program_options;
#endif
#if defined(ENABLE_CALIPER)
#include <caliper/cali-mpi.h>
#include <caliper/cali.h>
#endif
//----------------------------------------------------------------------------//
//! FleCSI runtime main function.
//----------------------------------------------------------------------------//
int
main(int argc, char ** argv) {
#if defined(FLECSI_ENABLE_MPI)
// Get the MPI version
int version, subversion;
MPI_Get_version(&version, &subversion);
#if defined(GASNET_CONDUIT_MPI)
if(version == 3 && subversion > 0) {
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
// If you fail this assertion, then your version of MPI
// does not support calls from multiple threads and you
// cannot use the GASNet MPI conduit
if(provided < MPI_THREAD_MULTIPLE)
printf("ERROR: Your implementation of MPI does not support "
"MPI_THREAD_MULTIPLE which is required for use of the "
"GASNet MPI conduit with the Legion-MPI Interop!\n");
assert(provided == MPI_THREAD_MULTIPLE);
}
else {
// Initialize the MPI runtime
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
if(provided < MPI_THREAD_MULTIPLE)
printf("ERROR: Your implementation of MPI does not support "
"MPI_THREAD_MULTIPLE which is required for use of the "
"GASNet MPI conduit with the Legion-MPI Interop!\n");
assert(provided == MPI_THREAD_MULTIPLE);
} // if
#else
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
if(provided < MPI_THREAD_MULTIPLE)
printf("ERROR: Your implementation of MPI does not support "
"MPI_THREAD_MULTIPLE which is required for use of the "
"GASNet MPI conduit with the Legion-MPI Interop!\n");
assert(provided == MPI_THREAD_MULTIPLE);
#endif
//#if defined(ENABLE_CALIPER)
// cali_mpi_init();
//#endif
// get the rank
int rank{0};
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif // FLECSI_ENABLE_MPI
//--------------------------------------------------------------------------//
// INIT CLOG
//--------------------------------------------------------------------------//
// Initialize tags to output all tag groups from CLOG
std::string tags("all");
#if defined(FLECSI_ENABLE_BOOST)
options_description desc("Cinch test options");
// Add command-line options
desc.add_options()("help,h", "Print this message and exit.")("tags,t",
value(&tags)->implicit_value("0"),
"Enable the specified output tags, e.g., --tags=tag1,tag2."
" Passing --tags by itself will print the available tags.");
variables_map vm;
parsed_options parsed =
command_line_parser(argc, argv).options(desc).allow_unregistered().run();
store(parsed, vm);
notify(vm);
if(vm.count("help")) {
if(rank == 0) {
std::cout << desc << std::endl;
} // if
MPI_Finalize();
return 1;
} // if
#endif // FLECSI_ENABLE_BOOST
int result{0};
if(tags == "0") {
// Output the available tags
if(rank == 0) {
std::cout << "Available tags (CLOG):" << std::endl;
for(auto t : clog_tag_map()) {
std::cout << " " << t.first << std::endl;
} // for
} // if
}
else {
// Initialize the cinchlog runtime
clog_init(tags);
// Execute the flecsi runtime.
result = flecsi::execution::context_t::instance().initialize(argc, argv);
} // if
#if defined(FLECSI_ENABLE_MPI)
// Shutdown the MPI runtime
#ifndef GASNET_CONDUIT_MPI
MPI_Finalize();
#endif
#endif // FLECSI_ENABLE_MPI
return result;
} // main
| 28.664557 | 80 | 0.552661 | scothalverson |
d553f7526b1e3b55b887e22c97422f60792033fb | 7,117 | hpp | C++ | structures/linkedlist.hpp | Dannnno/DataStructures | 898e16acc4d05e7c387972f1aef252b298fc4f81 | [
"MIT"
] | null | null | null | structures/linkedlist.hpp | Dannnno/DataStructures | 898e16acc4d05e7c387972f1aef252b298fc4f81 | [
"MIT"
] | null | null | null | structures/linkedlist.hpp | Dannnno/DataStructures | 898e16acc4d05e7c387972f1aef252b298fc4f81 | [
"MIT"
] | null | null | null | /**
* \file linkedlist.hpp
* \author Dan Obermiller
* \brief Implementation of a singly-linked list.
*/
#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP 1
#include <cstddef>
#include <iterator>
#include "list.hpp"
#include "../exceptions.hpp"
/**
* \brief A paramaterized singly-linked list
*/
template <typename T>
class LinkedList : public List<T>
{
private:
/**
* \brief Iterator for a linkedlist.
*/
class Iterator;
/**
* \brief Constant iterator for a linkedlist.
*/
class ConstIterator;
/**
* \brief Node of a linkedlist
*/
struct ListNode;
public:
/**
* \brief A default constructor for a linked list.
*/
LinkedList();
/**
* \brief A constructor from an array.
*/
LinkedList(T* arr, std::size_t length);
/**
* \brief Copy constructor.
*/
LinkedList(const LinkedList<T>& orig);
/**
* \brief Move constructor.
*/
LinkedList(LinkedList<T>&& other);
/**
* \brief Assignment to a list;
*/
LinkedList<T>& operator=(LinkedList<T> rhs);
/**
* \brief The destructor for a linked list.
*/
~LinkedList();
/**
* \brief Non-member function version of swap.
*/
template <class P>
friend void swap(LinkedList<P>& lhs, LinkedList<P>& rhs);
/**
* \brief The head (first item) of the list.
*/
T& getHead();
/**
* \brief Constant version of getHead()
*/
const T& getHead() const;
/**
* \brief The tail (last item) of the list.
*/
T& getTail();
/**
* \brief Constant version of getTail()
*/
const T& getTail() const;
/**
* \brief Returns the size of the list
*/
std::size_t size() const;
/**
* \brief Returns whether or not the list is empty.
*/
bool isEmpty() const;
/**
* \brief Adds a node to the end of the list.
* \post All nodes have the appropriate "next_" and the list has
* the appropriate size.
*/
void append(T value);
/**
* \brief Removes the first item in the list.
*/
void remove();
/**
* \brief Removes the nth item in the list.
*/
void remove(std::size_t n);
/**
* \brief Removes and returns a copy of the value of the first item
* in the list.
*/
T pop();
/**
* \brief Removes and returns a copy of the value of the nth item
* in the list.
*/
T pop(std::size_t n);
/**
* \brief inserts an item at the indicated index.
*/
void insert(std::size_t index, T value);
/**
* \brief Determines the index of an element.
*/
std::size_t index_of(T const& value) const;
/**
* \brief Determines whether or not the value is present.
*/
bool contains(T const& value) const;
/**
* \brief Overloads the addition operator.
* \details Adds two lists together and returns the result.
*/
template <typename P>
friend LinkedList<P> operator+(LinkedList<P> lhs, LinkedList<P> rhs);
/**
* \brief Overloads the multiplication operator.
* \details Allows us to make the list repeat n times.
*/
template <typename P>
friend LinkedList<P> operator*(LinkedList<P> lhs, std::size_t n);
/**
* \brief Overloads the mutable subscript operator.
*/
T& operator[](std::size_t index);
/**
* \brief Overloads the immutable subscript operator.
*/
const T& operator[](std::size_t index) const;
/**
* \brief Overloads the equivalence operator.
*/
bool operator==(const LinkedList<T>& rhs) const;
/**
* \brief Overloads the inequivalence operator.
*/
bool operator!=(const LinkedList<T>& rhs) const;
/**
* \brief Returns an array of the values within the list.
* \details This is a dynamically allocated array and needs to be
* explicitly deleted.
*/
T* asArray() const;
/**
* \brief Overloads the << operator.
*/
template <class P>
friend std::ostream& operator<<(
std::ostream& str, const LinkedList<P>& list);
typedef Iterator iterator;
typedef ConstIterator const_iterator;
/**
* \brief Returns the start of the ListIterator.
*/
iterator begin();
/**
* \brief Returns the end of the ListIterator.
*/
iterator end();
/**
* \brief Returns a costant version of the ListIterator (from the start)
*/
const_iterator begin() const;
/**
* \brief Returns a constant version of the ListIterator (at the end).
*/
const_iterator end() const;
/**
* \brief Sorts the current list.
*/
void sort();
/**
* \brief Returns a copy of the list in sorted order.
* \post The original list is unchanged.
*/
LinkedList<T> sorted() const;
/**
* \brief Reverses the order of the list.
*/
void reverse();
/**
* \brief Returns a copy of the list, reversed.
* \post The original list is unchanged.
*/
LinkedList<T> reversed() const;
/**
* \brief Returns an array of the items in the list.
*/
T* toArray() const;
private:
class Iterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
/**
* \brief Prefix increment operator overloading.
*/
Iterator& operator++();
/**
* \brief Postfix increment operator overloading.
*/
Iterator operator++(int) const;
/**
* \brief Dereferencing operator overloading.
*/
const T& operator*() const;
/**
* \brief Member access operator overriding.
*/
const T* operator->() const;
/**
* \brief Equality operator overriding.
*/
bool operator==(const Iterator& rhs) const;
/**
* \brief Inequality operator overriding.
*/
bool operator!=(const Iterator& rhs) const;
private:
friend class LinkedList;
/**
* \brief The default constructor.
*/
Iterator() = delete;
/**
* \brief All iterators should have a current node.
*/
Iterator(ListNode* node) : current_{node}
{
}
ListNode* current_;
};
class ConstIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
/**
* \brief Prefix increment operator overloading.
*/
ConstIterator& operator++();
/**
* \brief Postfix increment operator overloading.
*/
ConstIterator operator++(int) const;
/**
* \brief Dereferencing operator overloading.
*/
const T& operator*() const;
/**
* \brief Member access operator overriding.
*/
const T* operator->() const;
/**
* \brief Equality operator overriding.
*/
bool operator==(const ConstIterator& rhs) const;
/**
* \brief Inequality operator overriding.
*/
bool operator!=(const ConstIterator& rhs) const;
private:
friend class LinkedList;
/**
* \brief The default constructor.
*/
ConstIterator() = delete;
/**
* \brief All iterators should have a current node.
*/
ConstIterator(ListNode* node) : current_{node}
{
}
ListNode* current_;
};
/**
* \brief Node of a linkedlist
*/
struct ListNode
{
T value_;
ListNode* next_;
};
/**
* \brief Gets a list node at the given index
*/
LinkedList<T>::ListNode* getListNode(std::size_t index) const;
std::size_t numElements_;
ListNode* head_;
ListNode* tail_;
};
#include "_linkedlist.hpp"
#endif
| 19.287263 | 76 | 0.620627 | Dannnno |
d554bd45d843cb76d265f6338a1d1a4f5b3618ea | 10,916 | cpp | C++ | components/cpp_utils/TFTP.cpp | klaus-liebler/esp32 | f6ad2b92153f64d2467f0256c6d2fe776d9d7145 | [
"MIT"
] | null | null | null | components/cpp_utils/TFTP.cpp | klaus-liebler/esp32 | f6ad2b92153f64d2467f0256c6d2fe776d9d7145 | [
"MIT"
] | null | null | null | components/cpp_utils/TFTP.cpp | klaus-liebler/esp32 | f6ad2b92153f64d2467f0256c6d2fe776d9d7145 | [
"MIT"
] | null | null | null | /*
* TFTP.cpp
*
* See also:
* * https://tools.ietf.org/html/rfc1350
* Created on: May 21, 2017
* Author: kolban
*/
#include "TFTP.h"
#include <esp_log.h>
#include <FreeRTOS.h>
#include <GeneralUtils.h>
#include <string>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <Socket.h>
#include "sdkconfig.h"
extern "C" {
extern uint16_t lwip_ntohs(uint16_t);
extern uint32_t lwip_ntohl(uint32_t);
extern uint16_t lwip_htons(uint16_t);
extern uint32_t lwip_htonl(uint32_t);
}
static const char* LOG_TAG = "TFTP";
enum opcode {
TFTP_OPCODE_RRQ = 1, // Read request
TFTP_OPCODE_WRQ = 2, // Write request
TFTP_OPCODE_DATA = 3, // Data
TFTP_OPCODE_ACK = 4, // Acknowledgement
TFTP_OPCODE_ERROR = 5 // Error
};
enum ERRORCODE {
ERROR_CODE_NOTDEFINED = 0,
ERROR_CODE_FILE_NOT_FOUND = 1,
ERROR_CODE_ACCESS_VIOLATION = 2,
ERROR_CODE_NO_SPACE = 3,
ERROR_CODE_ILLEGAL_OPERATION = 4,
ERROR_CODE_UNKNOWN_ID = 5,
ERROR_CODE_FILE_EXISTS = 6,
ERROR_CODE_UNKNOWN_USER = 7
};
/**
* Size of the TFTP data payload.
*/
const int TFTP_DATA_SIZE = 512;
struct data_packet {
uint16_t blockNumber;
std::string data;
};
TFTP::TFTP() {
m_baseDir = "";
}
TFTP::~TFTP() {
}
/**
* @brief Start a TFTP transaction.
* @return N/A.
*/
TFTP::TFTP_Transaction::TFTP_Transaction() {
m_baseDir = "";
m_filename = "";
m_mode = "";
m_opCode = -1;
} // TFTP_Transaction
/**
* @brief Process a client read request.
* @return N/A.
*/
void TFTP::TFTP_Transaction::processRRQ() {
/*
* 2 bytes 2 bytes n bytes
* ----------------------------------
* | Opcode | Block # | Data |
* ----------------------------------
*
*/
FILE* file;
bool finished = false;
ESP_LOGD(LOG_TAG, "Reading TFTP data from file: %s", m_filename.c_str());
std::string tmpName = m_baseDir + "/" + m_filename;
/*
struct stat buf;
if (stat(tmpName.c_str(), &buf) != 0) {
ESP_LOGE(LOG_TAG, "Stat file: %s: %s", tmpName.c_str(), strerror(errno));
return;
}
int length = buf.st_size;
*/
int blockNumber = 1;
file = fopen(tmpName.c_str(), "r");
if (file == nullptr) {
ESP_LOGE(LOG_TAG, "Failed to open file for reading: %s: %s", tmpName.c_str(), strerror(errno));
sendError(ERROR_CODE_FILE_NOT_FOUND, tmpName);
return;
}
struct {
uint16_t opCode;
uint16_t blockNumber;
uint8_t buf[TFTP_DATA_SIZE];
} record;
record.opCode = htons(TFTP_OPCODE_DATA); // Set the op code to be DATA.
while (!finished) {
record.blockNumber = htons(blockNumber);
int sizeRead = fread(record.buf, 1, TFTP_DATA_SIZE, file);
ESP_LOGD(LOG_TAG, "Sending data to %s, blockNumber=%d, size=%d",
Socket::addressToString(&m_partnerAddress).c_str(), blockNumber, sizeRead);
m_partnerSocket.sendTo((uint8_t*) &record, sizeRead + 4, &m_partnerAddress);
if (sizeRead < TFTP_DATA_SIZE) {
finished = true;
} else {
waitForAck(blockNumber);
}
blockNumber++; // Increment the block number.
}
ESP_LOGD(LOG_TAG, "File sent");
} // processRRQ
/**
* @brief Process a client write request.
* @return N/A.
*/
void TFTP::TFTP_Transaction::processWRQ() {
/*
* 2 bytes 2 bytes n bytes
* ---------------------------------
* DATA | 03 | Block # | Data |
* ---------------------------------
* The opcode for data is 0x03 - TFTP_OPCODE_DATA
*/
struct recv_data {
uint16_t opCode;
uint16_t blockNumber;
uint8_t data;
} *pRecv_data;
struct sockaddr recvAddr;
uint8_t dataBuffer[TFTP_DATA_SIZE + 2 + 2];
bool finished = false;
FILE* file;
ESP_LOGD(LOG_TAG, "Writing TFTP data to file: %s", m_filename.c_str());
std::string tmpName = m_baseDir + "/" + m_filename;
file = fopen(tmpName.c_str(), "w");
if (file == nullptr) {
ESP_LOGE(LOG_TAG, "Failed to open file for writing: %s: %s", tmpName.c_str(), strerror(errno));
return;
}
while(!finished) {
pRecv_data = (struct recv_data*) dataBuffer;
int receivedSize = m_partnerSocket.receiveFrom(dataBuffer, sizeof(dataBuffer), &recvAddr);
if (receivedSize == -1) {
ESP_LOGE(LOG_TAG, "rc == -1 from receive_from");
}
struct data_packet dp;
dp.blockNumber = ntohs(pRecv_data->blockNumber);
dp.data = std::string((char*) &pRecv_data->data, receivedSize - 4);
fwrite(dp.data.data(), dp.data.length(), 1, file);
sendAck(dp.blockNumber);
ESP_LOGD(LOG_TAG, "Block size: %d", dp.data.length());
if (dp.data.length() < TFTP_DATA_SIZE) {
finished = true;
}
} // Finished
fclose(file);
m_partnerSocket.close();
} // process
/**
* @brief Send an acknowledgment back to the partner.
* A TFTP acknowledgment packet contains an opcode (4) and a block number.
*
* @param [in] blockNumber The block number to send.
* @return N/A.
*/
void TFTP::TFTP_Transaction::sendAck(uint16_t blockNumber) {
struct {
uint16_t opCode;
uint16_t blockNumber;
} ackData;
ackData.opCode = htons(TFTP_OPCODE_ACK);
ackData.blockNumber = htons(blockNumber);
ESP_LOGD(LOG_TAG, "Sending ack to %s, blockNumber=%d", Socket::addressToString(&m_partnerAddress).c_str(), blockNumber);
m_partnerSocket.sendTo((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress);
} // sendAck
/**
* @brief Start being a TFTP server.
*
* This function does not return.
*
* @param [in] port The port number on which to listen. The default is 69.
* @return N/A.
*/
void TFTP::start(uint16_t port) {
/*
* Loop forever. At the start of the loop we block waiting for an incoming client request.
* The requests that we are expecting are either a request to read a file from the server
* or write a file to the server. Once we have received a request we then call the appropriate
* handler to handle that type of request. When the request has been completed, we start again.
*/
ESP_LOGD(LOG_TAG, "Starting TFTP::start() on port %d", port);
Socket serverSocket;
serverSocket.listen(port, true); // Create a listening socket that is a datagram.
while (true) {
// This would be a good place to start a transaction in the background.
TFTP_Transaction* pTFTPTransaction = new TFTP_Transaction();
pTFTPTransaction->setBaseDir(m_baseDir);
uint16_t receivedOpCode = pTFTPTransaction->waitForRequest(&serverSocket);
switch (receivedOpCode) {
// Handle the write request (client file upload)
case opcode::TFTP_OPCODE_WRQ: {
pTFTPTransaction->processWRQ();
break;
}
// Handle the read request (server file download)
case opcode::TFTP_OPCODE_RRQ: {
pTFTPTransaction->processRRQ();
break;
}
default:
ESP_LOGE(LOG_TAG, "Unknown opcode: %d", receivedOpCode);
break;
}
delete pTFTPTransaction;
} // End while loop
} // run
/**
* @brief Set the base dir for file access.
* If we are asked to put a file to the file system, this is the base relative directory.
* @param baseDir Base directory for file access.
* @return N/A.
*/
void TFTP::TFTP_Transaction::setBaseDir(std::string baseDir) {
m_baseDir = baseDir;
} // setBaseDir
/**
* @brief Set the base dir for file access.
* If we are asked to put a file to the file system, this is the base relative directory.
* @param baseDir Base directory for file access.
* @return N/A.
*/
void TFTP::setBaseDir(std::string baseDir) {
m_baseDir = baseDir;
} // setBaseDir
/**
* @brief Wait for an acknowledgment from the client.
* After having sent data to the client, we expect an acknowledment back from the client.
* This function causes us to wait for an incoming acknowledgment.
*/
void TFTP::TFTP_Transaction::waitForAck(uint16_t blockNumber) {
struct {
uint16_t opCode;
uint16_t blockNumber;
} ackData;
ESP_LOGD(LOG_TAG, "TFTP: Waiting for an acknowledgment request");
int sizeRead = m_partnerSocket.receiveFrom((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress);
ESP_LOGD(LOG_TAG, "TFTP: Received some data.");
if (sizeRead != sizeof(ackData)) {
ESP_LOGE(LOG_TAG, "waitForAck: Received %d but expected %d", sizeRead, sizeof(ackData));
sendError(ERROR_CODE_NOTDEFINED, "Ack not correct size");
return;
}
ackData.opCode = ntohs(ackData.opCode);
ackData.blockNumber = ntohs(ackData.blockNumber);
if (ackData.opCode != opcode::TFTP_OPCODE_ACK) {
ESP_LOGE(LOG_TAG, "waitForAck: Received opcode %d but expected %d", ackData.opCode, opcode::TFTP_OPCODE_ACK);
return;
}
if (ackData.blockNumber != blockNumber) {
ESP_LOGE(LOG_TAG, "waitForAck: Blocknumber received %d but expected %d", ackData.blockNumber, blockNumber);
return;
}
} // waitForAck
/**
* @brief Wait for a client request.
* A %TFTP server waits for requests to send or receive files. A request can be
* either WRQ (write request) which is a request from the client to write a new local
* file or it can be a RRQ (read request) which is a request from the client to
* read a local file.
* @param pServerSocket The server socket on which to listen for client requests.
* @return The op code received.
*/
/*
* 2 bytes string 1 byte string 1 byte
* -----------------------------------------------
* RRQ/ | 01/02 | Filename | 0 | Mode | 0 |
* WRQ -----------------------------------------------
*/
uint16_t TFTP::TFTP_Transaction::waitForRequest(Socket* pServerSocket) {
union {
uint8_t buf[TFTP_DATA_SIZE];
uint16_t opCode;
} record;
size_t length = 100;
ESP_LOGD(LOG_TAG, "TFTP: Waiting for a request");
pServerSocket->receiveFrom(record.buf, length, &m_partnerAddress);
// Save the filename, mode and op code.
m_filename = std::string((char*) (record.buf + 2));
m_mode = std::string((char*) (record.buf + 3 + m_filename.length()));
m_opCode = ntohs(record.opCode);
switch (m_opCode) {
// Handle the Write Request command.
case TFTP_OPCODE_WRQ: {
m_partnerSocket.createSocket(true);
m_partnerSocket.bind(0, INADDR_ANY);
sendAck(0);
break;
}
// Handle the Read request command.
case TFTP_OPCODE_RRQ: {
m_partnerSocket.createSocket(true);
m_partnerSocket.bind(0, INADDR_ANY);
break;
}
default: {
ESP_LOGD(LOG_TAG, "Un-handled opcode: %d", m_opCode);
break;
}
}
return m_opCode;
} // waitForRequest
/**
* @brief Send an error indication to the client.
* @param [in] code Error code to send to the client.
* @param [in] message Explanation message.
* @return N/A.
*/
void TFTP::TFTP_Transaction::sendError(uint16_t code, std::string message) {
/*
* 2 bytes 2 bytes string 1 byte
* -----------------------------------------
* | Opcode | ErrorCode | ErrMsg | 0 |
* -----------------------------------------
*/
int size = 2 + 2 + message.length() + 1;
uint8_t* buf = (uint8_t*) malloc(size);
*(uint16_t*) (&buf[0]) = htons(opcode::TFTP_OPCODE_ERROR);
*(uint16_t*) (&buf[2]) = htons(code);
strcpy((char*) (&buf[4]), message.c_str());
m_partnerSocket.sendTo(buf, size, &m_partnerAddress);
free(buf);
} // sendError
| 27.496222 | 121 | 0.661964 | klaus-liebler |
d55625faab4a967a87ef961045f4929c16c50e77 | 6,462 | cpp | C++ | DrvApp/HookEngine/distorm/textdefs.cpp | jackqk/mystudy | 84313c1eaed7351d37b609288d1d32bf3b808859 | [
"Apache-2.0"
] | 15 | 2017-05-27T16:02:51.000Z | 2018-11-30T07:02:22.000Z | DrvApp/HookEngine/distorm/textdefs.cpp | jackqk/mystudy | 84313c1eaed7351d37b609288d1d32bf3b808859 | [
"Apache-2.0"
] | null | null | null | DrvApp/HookEngine/distorm/textdefs.cpp | jackqk/mystudy | 84313c1eaed7351d37b609288d1d32bf3b808859 | [
"Apache-2.0"
] | 11 | 2017-11-10T01:28:59.000Z | 2018-11-15T11:59:33.000Z | /*
textdefs.c
diStorm3 - Powerful disassembler for X86/AMD64
http://ragestorm.net/distorm/
distorm at gmail dot com
Copyright (C) 2003-2016 Gil Dabah
This library is licensed under the BSD license. See the file COPYING.
*/
#include <stdafx.h>
#include "textdefs.h"
#ifndef DISTORM_LIGHT
static uint8_t Nibble2ChrTable[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
#define NIBBLE_TO_CHR Nibble2ChrTable[t]
void _FASTCALL_ str_hex_b(_WString* s, unsigned int x)
{
/*
* def prebuilt():
* s = ""
* for i in xrange(256):
* if ((i % 0x10) == 0):
* s += "\r\n"
* s += "\"%02x\", " % (i)
* return s
*/
static int8_t TextBTable[256][3] = {
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
"b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
"c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
"d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
"e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
};
/*
* Fixed length of 3 including null terminate character.
*/
memcpy(&s->p[s->length], TextBTable[x & 255], 3);
s->length += 2;
}
void _FASTCALL_ str_code_hb(_WString* s, unsigned int x)
{
static int8_t TextHBTable[256][5] = {
/*
* def prebuilt():
* s = ""
* for i in xrange(256):
* if ((i % 0x10) == 0):
* s += "\r\n"
* s += "\"0x%x\", " % (i)
* return s
*/
"0x0", "0x1", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xa", "0xb", "0xc", "0xd", "0xe", "0xf",
"0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1a", "0x1b", "0x1c", "0x1d", "0x1e", "0x1f",
"0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2a", "0x2b", "0x2c", "0x2d", "0x2e", "0x2f",
"0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3a", "0x3b", "0x3c", "0x3d", "0x3e", "0x3f",
"0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4a", "0x4b", "0x4c", "0x4d", "0x4e", "0x4f",
"0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5a", "0x5b", "0x5c", "0x5d", "0x5e", "0x5f",
"0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6a", "0x6b", "0x6c", "0x6d", "0x6e", "0x6f",
"0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7a", "0x7b", "0x7c", "0x7d", "0x7e", "0x7f",
"0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8a", "0x8b", "0x8c", "0x8d", "0x8e", "0x8f",
"0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9a", "0x9b", "0x9c", "0x9d", "0x9e", "0x9f",
"0xa0", "0xa1", "0xa2", "0xa3", "0xa4", "0xa5", "0xa6", "0xa7", "0xa8", "0xa9", "0xaa", "0xab", "0xac", "0xad", "0xae", "0xaf",
"0xb0", "0xb1", "0xb2", "0xb3", "0xb4", "0xb5", "0xb6", "0xb7", "0xb8", "0xb9", "0xba", "0xbb", "0xbc", "0xbd", "0xbe", "0xbf",
"0xc0", "0xc1", "0xc2", "0xc3", "0xc4", "0xc5", "0xc6", "0xc7", "0xc8", "0xc9", "0xca", "0xcb", "0xcc", "0xcd", "0xce", "0xcf",
"0xd0", "0xd1", "0xd2", "0xd3", "0xd4", "0xd5", "0xd6", "0xd7", "0xd8", "0xd9", "0xda", "0xdb", "0xdc", "0xdd", "0xde", "0xdf",
"0xe0", "0xe1", "0xe2", "0xe3", "0xe4", "0xe5", "0xe6", "0xe7", "0xe8", "0xe9", "0xea", "0xeb", "0xec", "0xed", "0xee", "0xef",
"0xf0", "0xf1", "0xf2", "0xf3", "0xf4", "0xf5", "0xf6", "0xf7", "0xf8", "0xf9", "0xfa", "0xfb", "0xfc", "0xfd", "0xfe", "0xff"
};
if (x < 0x10) { /* < 0x10 has a fixed length of 4 including null terminate. */
memcpy(&s->p[s->length], TextHBTable[x & 255], 4);
s->length += 3;
} else { /* >= 0x10 has a fixed length of 5 including null terminate. */
memcpy(&s->p[s->length], TextHBTable[x & 255], 5);
s->length += 4;
}
}
void _FASTCALL_ str_code_hdw(_WString* s, uint32_t x)
{
int8_t* buf;
int i = 0, shift = 0;
unsigned int t = 0;
buf = (int8_t*)&s->p[s->length];
buf[0] = '0';
buf[1] = 'x';
buf += 2;
for (shift = 28; shift != 0; shift -= 4) {
t = (x >> shift) & 0xf;
if (i | t) buf[i++] = NIBBLE_TO_CHR;
}
t = x & 0xf;
buf[i++] = NIBBLE_TO_CHR;
s->length += i + 2;
buf[i] = '\0';
}
void _FASTCALL_ str_code_hqw(_WString* s, uint8_t src[8])
{
int8_t* buf;
int i = 0, shift = 0;
uint32_t x = RULONG(&src[sizeof(int32_t)]);
int t;
buf = (int8_t*)&s->p[s->length];
buf[0] = '0';
buf[1] = 'x';
buf += 2;
for (shift = 28; shift != -4; shift -= 4) {
t = (x >> shift) & 0xf;
if (i | t) buf[i++] = NIBBLE_TO_CHR;
}
x = RULONG(src);
for (shift = 28; shift != 0; shift -= 4) {
t = (x >> shift) & 0xf;
if (i | t) buf[i++] = NIBBLE_TO_CHR;
}
t = x & 0xf;
buf[i++] = NIBBLE_TO_CHR;
s->length += i + 2;
buf[i] = '\0';
}
#ifdef SUPPORT_64BIT_OFFSET
void _FASTCALL_ str_off64(_WString* s, OFFSET_INTEGER x)
{
int8_t* buf;
int i = 0, shift = 0;
OFFSET_INTEGER t = 0;
buf = (int8_t*)&s->p[s->length];
buf[0] = '0';
buf[1] = 'x';
buf += 2;
for (shift = 60; shift != 0; shift -= 4) {
t = (x >> shift) & 0xf;
if (i | t) buf[i++] = NIBBLE_TO_CHR;
}
t = x & 0xf;
buf[i++] = NIBBLE_TO_CHR;
s->length += i + 2;
buf[i] = '\0';
}
#endif /* SUPPORT_64BIT_OFFSET */
#endif /* DISTORM_LIGHT */
| 37.352601 | 129 | 0.476787 | jackqk |
d556755ab874ea2f78040cb781cfb7a03579ce09 | 898 | cpp | C++ | lib/plog/samples/UtcTime/Main.cpp | hsbsw/hAIR | d7fa988dd639ced63acae3b1e980d39ee3c8412e | [
"MIT"
] | null | null | null | lib/plog/samples/UtcTime/Main.cpp | hsbsw/hAIR | d7fa988dd639ced63acae3b1e980d39ee3c8412e | [
"MIT"
] | null | null | null | lib/plog/samples/UtcTime/Main.cpp | hsbsw/hAIR | d7fa988dd639ced63acae3b1e980d39ee3c8412e | [
"MIT"
] | null | null | null | //
// UtcTime - shows how to use UTC time in logs.
//
#include <plog/Log.h>
#include <plog/Init.h>
#include <plog/Formatters/CsvFormatter.h>
#include <plog/Formatters/TxtFormatter.h>
#include <plog/Appenders/ColorConsoleAppender.h>
#include <plog/Appenders/RollingFileAppender.h>
int main()
{
static plog::ColorConsoleAppender<plog::TxtFormatterUtcTime> consoleAppender; // TxtFormatter in UTC
static plog::RollingFileAppender<plog::CsvFormatterUtcTime> fileAppender("UtcTime.csv", 10000, 2); // CsvFormatter in UTC
plog::init(plog::verbose, &consoleAppender).addAppender(&fileAppender);
PLOG_VERBOSE << "This is a VERBOSE message";
PLOG_DEBUG << "This is a DEBUG message";
PLOG_INFO << "This is an INFO message";
PLOG_WARNING << "This is a WARNING message";
PLOG_ERROR << "This is an ERROR message";
PLOG_FATAL << "This is a FATAL message";
return 0;
}
| 33.259259 | 125 | 0.721604 | hsbsw |
d55a3c2c148ef28a162c3886742247fd169362ee | 12,690 | cpp | C++ | Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | 2 | 2018-04-30T09:58:48.000Z | 2018-05-14T10:13:42.000Z | Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | null | null | null | Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "CompoundStorageComponent_Cell.h"
#include "Character_SingleCelled.h"
#include "Logging.h"
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"
#include "Meta_CellStage.h"
// Sets default values for this component's properties
UCompoundStorageComponent_Cell::UCompoundStorageComponent_Cell()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UCompoundStorageComponent_Cell::BeginPlay()
{
Super::BeginPlay();
SetCompounds();
StartLowCompoundCycle();
lowCompound = "Carbon";
_protein.maximum = 100;
_protein.current = 25;
}
// Called every frame
void UCompoundStorageComponent_Cell::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
/*---------------------------------------------------------------------------------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////
///////////////////////////////// PRIVATE ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void UCompoundStorageComponent_Cell::EnforceCompoundBalance()
{
AddCompound(_playerCompounds._CO2.balance, ECompound::ECO2);
AddCompound(_playerCompounds._O2.balance, ECompound::EO2);
AddCompound(_playerCompounds._AminoAcid.balance, ECompound::EAminoAcid);
AddCompound(_playerCompounds._Glucose.balance, ECompound::EGlucose);
AddCompound(_playerCompounds._Lipid.balance, ECompound::ELipid);
//First of all set the volume back on the player
ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(this->GetOwner());
if (controller != nullptr)
{
controller->GetWorldTimerManager().SetTimer(consumptionTimer, this, &UCompoundStorageComponent_Cell::EnforceCompoundBalance, SURROUNDINGS_DELTA_TIME, false);
}
}
FString UCompoundStorageComponent_Cell::GetCompoundName(ECompound compound)
{
return FString();
}
void UCompoundStorageComponent_Cell::UpdateLowCompound()
{
ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
if (controller != nullptr)
{
TArray<bool> isLow = {
false, //CO2
false, //oxygen
false, //amino acid
false, //glucose
false //lipid
};
//cycle through all compounds and see if the are <= than 10% of their maximum
//if they are set, their value in the array to true
//after this is done:
//check if maybe there are no compounds that are low
// in that case set lowCompound to ""
//most likely that won't be the case so:
//check what currently is in lowCompound
//start at that value in the array and go to the next one that is low and set it
// current amount / maximum <= 0.1f
isLow[0] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, true)) <= 0.1f;
isLow[1] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, true)) <= 0.1f;
isLow[2] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, true)) <= 0.1f;
isLow[3] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, true)) <= 0.1f;
isLow[4] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, true)) <= 0.1f;
if (!isLow[0] && !isLow[1] && !isLow[2] && !isLow[3] && !isLow[4])
{
lowCompound = "";
_eLowCompound = ECompound::ENothing;
}
else
{
int start = 0;
if (_eLowCompound == ECompound::ENothing)
{
start = 0;
}
else if (_eLowCompound == ECompound::ECO2)
{
start = 1;
}
else if (_eLowCompound == ECompound::EO2)
{
start = 2;
}
else if (_eLowCompound == ECompound::EAminoAcid)
{
start = 3;
}
else if (_eLowCompound == ECompound::EGlucose)
{
start = 4;
}
else if (_eLowCompound == ECompound::ELipid)
{
start = 0;
}
//6 so it can return to the starting position if there are not other compounds
int position = 0;
for (position; position < 6; position++)
{
if (isLow[(start + position) % 5])
{
break;
}
}
switch ((start + position) % 5)
{
case 0:
lowCompound = "CO2";
_eLowCompound = ECompound::ECO2;
break;
case 1:
lowCompound = "Oxygen";
_eLowCompound = ECompound::EO2;
break;
case 2:
lowCompound = "Amino Acids";
_eLowCompound = ECompound::EAminoAcid;
break;
case 3:
lowCompound = "Glucose";
_eLowCompound = ECompound::EGlucose;
break;
case 4:
lowCompound = "Lipids";
_eLowCompound = ECompound::ELipid;
break;
default:
_eLowCompound = ECompound::ENothing;
lowCompound = "ERROR";
break;
}
}
controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &UCompoundStorageComponent_Cell::UpdateLowCompound, 2.f, false);
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////// PROTECTED ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void UCompoundStorageComponent_Cell::StartLowCompoundCycle()
{
//ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
//if (controller != nullptr)
//{
// controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &AGameMode_Cell::UpdateLowCompound, 2.f, false);
//}
UpdateLowCompound();
}
//////////////////////////////////////////////////////////////////////////////
///////////////////////////////// PUBLIC /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void UCompoundStorageComponent_Cell::SetCompounds()
{
//CO2
_playerCompounds._CO2.maximum = 10000.f;
_playerCompounds._CO2.current = 1000.f;
_playerCompounds._CO2.balance = -1;
//Oxygen
_playerCompounds._O2.maximum = 10000.f;
_playerCompounds._O2.current = 1000.f;
_playerCompounds._O2.balance = -1;
//Amino Acid
_playerCompounds._AminoAcid.maximum = 10000.f;
_playerCompounds._AminoAcid.current = 1000.f;
_playerCompounds._AminoAcid.balance = -1;
//Glucose
_playerCompounds._Glucose.maximum = 10000.f;
_playerCompounds._Glucose.current = 1000.f;
_playerCompounds._Glucose.balance = -1;
//Lipid
_playerCompounds._Lipid.maximum = 10000.f;
_playerCompounds._Lipid.current = 1000.f;
_playerCompounds._Lipid.balance = -1;
}
void UCompoundStorageComponent_Cell::AddCompound(int amount, ECompound compound)
{
//find the right compound to add the amount
if (compound == ECompound::ECO2)
{
Logging::Log(_playerCompounds._CO2.current);
Logging::Log(amount);
//add the amount
_playerCompounds._CO2.current = _playerCompounds._CO2.current + amount;
//check if it's greater than the maximum or smaller than 0 and correct that
if (_playerCompounds._CO2.current > _playerCompounds._CO2.maximum)
{
_playerCompounds._CO2.current = _playerCompounds._CO2.maximum;
}
else if (_playerCompounds._CO2.current < 0)
{
_playerCompounds._CO2.current = 0;
}
}
else if (compound == ECompound::EO2)
{
Logging::Log(_playerCompounds._O2.current);
Logging::Log(amount);
_playerCompounds._O2.current = _playerCompounds._O2.current + amount;
if (_playerCompounds._O2.current > _playerCompounds._O2.maximum)
{
_playerCompounds._O2.current = _playerCompounds._O2.maximum;
}
else if (_playerCompounds._O2.current < 0)
{
_playerCompounds._O2.current = 0;
}
}
else if (compound == ECompound::EAminoAcid)
{
Logging::Log(_playerCompounds._AminoAcid.current);
Logging::Log(amount);
_playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.current + amount;
if (_playerCompounds._AminoAcid.current > _playerCompounds._AminoAcid.maximum)
{
_playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.maximum;
}
else if (_playerCompounds._AminoAcid.current < 0)
{
_playerCompounds._AminoAcid.current = 0;
}
}
else if (compound == ECompound::EGlucose)
{
Logging::Log(_playerCompounds._Glucose.current);
Logging::Log(amount);
_playerCompounds._Glucose.current = _playerCompounds._Glucose.current + amount;
if (_playerCompounds._Glucose.current > _playerCompounds._Glucose.maximum)
{
_playerCompounds._Glucose.current = _playerCompounds._Glucose.maximum;
}
else if (_playerCompounds._Glucose.current < 0)
{
_playerCompounds._Glucose.current = 0;
}
}
else if (compound == ECompound::ELipid)
{
Logging::Log(_playerCompounds._Lipid.current);
Logging::Log(amount);
_playerCompounds._Lipid.current = _playerCompounds._Lipid.current + amount;
if (_playerCompounds._Lipid.current > _playerCompounds._Lipid.maximum)
{
_playerCompounds._Lipid.current = _playerCompounds._Lipid.maximum;
}
else if (_playerCompounds._Lipid.current < 0)
{
_playerCompounds._Lipid.current = 0;
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at AddCompound()"), *GetCompoundName(compound));
}
}
int UCompoundStorageComponent_Cell::GetCompound(ECompound compound, bool bMax)
{
if (bMax)
{
if (compound == ECompound::ECO2)
{
return _playerCompounds._CO2.maximum;
}
else if (compound == ECompound::EO2)
{
return _playerCompounds._O2.maximum;
}
else if (compound == ECompound::EAminoAcid)
{
return _playerCompounds._AminoAcid.maximum;
}
else if (compound == ECompound::EGlucose)
{
return _playerCompounds._Glucose.maximum;
}
else if (compound == ECompound::ELipid)
{
return _playerCompounds._Lipid.maximum;
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound));
return 0;
}
}
else
{
if (compound == ECompound::ECO2)
{
return _playerCompounds._CO2.current;
}
else if (compound == ECompound::EO2)
{
return _playerCompounds._O2.current;
}
else if (compound == ECompound::EAminoAcid)
{
return _playerCompounds._AminoAcid.current;
}
else if (compound == ECompound::EGlucose)
{
return _playerCompounds._Glucose.current;
}
else if (compound == ECompound::ELipid)
{
return _playerCompounds._Lipid.current;
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound));
return 0;
}
}
}
int UCompoundStorageComponent_Cell::GetCompoundBalance(ECompound compound)
{
if (compound == ECompound::ECO2)
{
if (GetCompound(compound, false) == 0)
{
return 0;
}
else
{
return _playerCompounds._CO2.balance;
}
}
else if (compound == ECompound::EO2)
{
if (GetCompound(compound, false) == 0)
{
return 0;
}
else
{
return _playerCompounds._O2.balance;
}
}
else if (compound == ECompound::EAminoAcid)
{
if (GetCompound(compound, false) == 0)
{
return 0;
}
else
{
return _playerCompounds._AminoAcid.balance;
}
}
else if (compound == ECompound::EGlucose)
{
if (GetCompound(compound, false) == 0)
{
return 0;
}
else
{
return _playerCompounds._Glucose.balance;
}
}
else if (compound == ECompound::ELipid)
{
if (GetCompound(compound, false) == 0)
{
return 0;
}
else
{
return _playerCompounds._Lipid.balance;
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompoundBalance()"), *GetCompoundName(compound));
return 0;
}
}
void UCompoundStorageComponent_Cell::AddProtein(int amount)
{
_protein.current += amount;
if (_protein.current > _protein.maximum)
{
_protein.current = _protein.maximum;
}
else if (_protein.current < 0)
{
_protein.current = 0;
}
}
int UCompoundStorageComponent_Cell::GetProtein(bool bMax)
{
if (bMax)
{
return _protein.maximum;
}
else
{
return _protein.current;
}
}
FString UCompoundStorageComponent_Cell::GetLowCompound()
{
return lowCompound;
} | 27.467532 | 190 | 0.665406 | GameAboutThings |
f65c6a13cd9a587638b413bd044a30d92a398b53 | 1,230 | cpp | C++ | local_remote_attestation/host/enclave_b.cpp | VictorDebray/azure-tee-attestation-samples | 38964c6023586dcc5014bd088daba0fa336c5a46 | [
"MIT"
] | 6 | 2020-03-28T16:46:47.000Z | 2021-11-23T16:27:47.000Z | local_remote_attestation/host/enclave_b.cpp | VictorDebray/azure-tee-attestation-samples | 38964c6023586dcc5014bd088daba0fa336c5a46 | [
"MIT"
] | 1 | 2021-02-10T13:48:52.000Z | 2021-02-10T13:49:32.000Z | local_remote_attestation/host/enclave_b.cpp | VictorDebray/azure-tee-attestation-samples | 38964c6023586dcc5014bd088daba0fa336c5a46 | [
"MIT"
] | 5 | 2020-07-31T10:38:44.000Z | 2021-11-10T08:24:20.000Z | #include "enclave.h"
int enclave_b_flow(oe_enclave_t* enclave, const char* input_file) {
int ret = 0;
const char* encrypted_file = "./out.encrypted";
const char* decrypted_file = "./out.decrypted";
// encrypt a file
std::cout << "Host: decrypting file:" << decrypted_file << std::endl;
ret = encrypt_file(enclave,
DECRYPT_OPERATION, encrypted_file, decrypted_file);
if (ret != 0)
{
std::cerr << "Host: processFile(DECRYPT_OPERATION) failed with " << ret
<< std::endl;
return 1;
}
// Make sure the decryption is successfull. Input and decrypted files
// are equal
std::cout << "Host: compared file:" << decrypted_file
<< " to file:" << input_file << std::endl;
ret = compare_2_files(input_file, decrypted_file);
if (ret != 0)
{
std::cerr << "Host: checking failed! " << decrypted_file
<< "'s contents are supposed to be same as " << input_file
<< std::endl;
return 1;
}
std::cout << "Host: " << decrypted_file << " is equal to " << input_file
<< " as expected" << std::endl;
std::cout << "Host: decryption was done successfully" << std::endl;
return ret;
} | 35.142857 | 79 | 0.590244 | VictorDebray |
f65ce637d77ce183f83b70dce6da8d0b4b8b8e71 | 16,444 | cpp | C++ | src/master/main.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | src/master/main.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | src/master/main.cpp | j143/mesos | a85a22baa32f66ecaa13c4602a195d57f6abf9be | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <mesos/mesos.hpp>
#include <mesos/authorizer/authorizer.hpp>
#include <mesos/allocator/allocator.hpp>
#include <mesos/master/contender.hpp>
#include <mesos/master/detector.hpp>
#include <mesos/module/anonymous.hpp>
#include <mesos/module/authorizer.hpp>
#include <mesos/state/in_memory.hpp>
#ifndef __WINDOWS__
#include <mesos/state/log.hpp>
#endif // __WINDOWS__
#include <mesos/state/state.hpp>
#include <mesos/state/storage.hpp>
#include <mesos/zookeeper/detector.hpp>
#include <process/limiter.hpp>
#include <process/owned.hpp>
#include <process/pid.hpp>
#include <stout/check.hpp>
#include <stout/duration.hpp>
#include <stout/exit.hpp>
#include <stout/flags.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include <stout/version.hpp>
#include "common/build.hpp"
#include "common/http.hpp"
#include "common/protobuf_utils.hpp"
#include "hook/manager.hpp"
#include "logging/flags.hpp"
#include "logging/logging.hpp"
#include "master/master.hpp"
#include "master/registrar.hpp"
#include "master/allocator/mesos/hierarchical.hpp"
#include "master/detector/standalone.hpp"
#include "module/manager.hpp"
#include "version/version.hpp"
using namespace mesos::internal;
#ifndef __WINDOWS__
using namespace mesos::internal::log;
#endif // __WINDOWS__
using namespace mesos::internal::master;
using namespace zookeeper;
using mesos::Authorizer;
using mesos::MasterInfo;
using mesos::Parameter;
using mesos::Parameters;
#ifndef __WINDOWS__
using mesos::log::Log;
#endif // __WINDOWS__
using mesos::allocator::Allocator;
using mesos::master::contender::MasterContender;
using mesos::master::detector::MasterDetector;
using mesos::master::detector::StandaloneMasterDetector;
using mesos::modules::Anonymous;
using mesos::modules::ModuleManager;
using mesos::state::InMemoryStorage;
#ifndef __WINDOWS__
using mesos::state::LogStorage;
#endif // __WINDOWS__
using mesos::state::Storage;
using process::Owned;
using process::RateLimiter;
using process::UPID;
using process::firewall::DisabledEndpointsFirewallRule;
using process::firewall::FirewallRule;
using std::cerr;
using std::cout;
using std::endl;
using std::move;
using std::ostringstream;
using std::set;
using std::shared_ptr;
using std::string;
using std::vector;
int main(int argc, char** argv)
{
// The order of initialization of various master components is as follows:
// * Validate flags.
// * Logging.
// * Log build information.
// * Libprocess.
// * Version process.
// * Firewall rules: should be initialized before initializing HTTP endpoints.
// * Modules: Load module libraries and manifests before they
// can be instantiated.
// * Anonymous modules: Later components such as Allocators, and master
// contender/detector might depend upon anonymous modules.
// * Hooks.
// * Allocator.
// * Registry storage.
// * State.
// * Master contender.
// * Master detector.
// * Authorizer.
// * Slave removal rate limiter.
// * `Master` process.
//
// TODO(avinash): Add more comments discussing the rationale behind for this
// particular component ordering.
GOOGLE_PROTOBUF_VERIFY_VERSION;
master::Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_", argc, argv);
if (flags.help) {
cout << flags.usage() << endl;
return EXIT_SUCCESS;
}
if (flags.version) {
cout << "mesos" << " " << MESOS_VERSION << endl;
return EXIT_SUCCESS;
}
if (load.isError()) {
cerr << flags.usage(load.error()) << endl;
return EXIT_FAILURE;
}
logging::initialize(argv[0], true, flags); // Catch signals.
// Log any flag warnings (after logging is initialized).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
// Check that master's version has the expected format (SemVer).
{
Try<Version> version = Version::parse(MESOS_VERSION);
if (version.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to parse Mesos version '" << MESOS_VERSION << "': "
<< version.error();
}
}
if (flags.ip_discovery_command.isSome() && flags.ip.isSome()) {
EXIT(EXIT_FAILURE) << flags.usage(
"Only one of `--ip` or `--ip_discovery_command` should be specified");
}
if (flags.ip_discovery_command.isSome()) {
Try<string> ipAddress = os::shell(flags.ip_discovery_command.get());
if (ipAddress.isError()) {
EXIT(EXIT_FAILURE) << ipAddress.error();
}
os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get()));
} else if (flags.ip.isSome()) {
os::setenv("LIBPROCESS_IP", flags.ip.get());
}
os::setenv("LIBPROCESS_PORT", stringify(flags.port));
if (flags.advertise_ip.isSome()) {
os::setenv("LIBPROCESS_ADVERTISE_IP", flags.advertise_ip.get());
}
if (flags.advertise_port.isSome()) {
os::setenv("LIBPROCESS_ADVERTISE_PORT", flags.advertise_port.get());
}
if (flags.zk.isNone()) {
if (flags.master_contender.isSome() ^ flags.master_detector.isSome()) {
EXIT(EXIT_FAILURE)
<< flags.usage("Both --master_contender and --master_detector should "
"be specified or omitted.");
}
} else {
if (flags.master_contender.isSome() || flags.master_detector.isSome()) {
EXIT(EXIT_FAILURE)
<< flags.usage("Only one of --zk or the "
"--master_contender/--master_detector "
"pair should be specified.");
}
}
// Log build information.
LOG(INFO) << "Build: " << build::DATE << " by " << build::USER;
LOG(INFO) << "Version: " << MESOS_VERSION;
if (build::GIT_TAG.isSome()) {
LOG(INFO) << "Git tag: " << build::GIT_TAG.get();
}
if (build::GIT_SHA.isSome()) {
LOG(INFO) << "Git SHA: " << build::GIT_SHA.get();
}
// This should be the first invocation of `process::initialize`. If it returns
// `false`, then it has already been called, which means that the
// authentication realm for libprocess-level HTTP endpoints was not set to the
// correct value for the master.
if (!process::initialize(
"master",
READWRITE_HTTP_AUTHENTICATION_REALM,
READONLY_HTTP_AUTHENTICATION_REALM)) {
EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the master's "
<< "`main()` was not the function's first invocation";
}
spawn(new VersionProcess(), true);
// Initialize firewall rules.
if (flags.firewall_rules.isSome()) {
vector<Owned<FirewallRule>> rules;
const Firewall firewall = flags.firewall_rules.get();
if (firewall.has_disabled_endpoints()) {
hashset<string> paths;
foreach (const string& path, firewall.disabled_endpoints().paths()) {
paths.insert(path);
}
rules.emplace_back(new DisabledEndpointsFirewallRule(paths));
}
process::firewall::install(move(rules));
}
// Initialize modules.
if (flags.modules.isSome() && flags.modulesDir.isSome()) {
EXIT(EXIT_FAILURE) <<
flags.usage("Only one of --modules or --modules_dir should be specified");
}
if (flags.modulesDir.isSome()) {
Try<Nothing> result = ModuleManager::load(flags.modulesDir.get());
if (result.isError()) {
EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error();
}
}
if (flags.modules.isSome()) {
Try<Nothing> result = ModuleManager::load(flags.modules.get());
if (result.isError()) {
EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error();
}
}
// Create anonymous modules.
foreach (const string& name, ModuleManager::find<Anonymous>()) {
Try<Anonymous*> create = ModuleManager::create<Anonymous>(name);
if (create.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create anonymous module named '" << name << "'";
}
// We don't bother keeping around the pointer to this anonymous
// module, when we exit that will effectively free its memory.
//
// TODO(benh): We might want to add explicit finalization (and
// maybe explicit initialization too) in order to let the module
// do any housekeeping necessary when the master is cleanly
// terminating.
}
// Initialize hooks.
if (flags.hooks.isSome()) {
Try<Nothing> result = HookManager::initialize(flags.hooks.get());
if (result.isError()) {
EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error();
}
}
// Create an instance of allocator.
const string allocatorName = flags.allocator;
Try<Allocator*> allocator = Allocator::create(allocatorName);
if (allocator.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create '" << allocatorName
<< "' allocator: " << allocator.error();
}
CHECK_NOTNULL(allocator.get());
LOG(INFO) << "Using '" << allocatorName << "' allocator";
Storage* storage = nullptr;
#ifndef __WINDOWS__
Log* log = nullptr;
#endif // __WINDOWS__
if (flags.registry == "in_memory") {
storage = new InMemoryStorage();
#ifndef __WINDOWS__
} else if (flags.registry == "replicated_log" ||
flags.registry == "log_storage") {
// TODO(bmahler): "log_storage" is present for backwards
// compatibility, can be removed before 0.19.0.
if (flags.work_dir.isNone()) {
EXIT(EXIT_FAILURE)
<< "--work_dir needed for replicated log based registry";
}
Try<Nothing> mkdir = os::mkdir(flags.work_dir.get());
if (mkdir.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create work directory '" << flags.work_dir.get()
<< "': " << mkdir.error();
}
if (flags.zk.isSome()) {
// Use replicated log with ZooKeeper.
if (flags.quorum.isNone()) {
EXIT(EXIT_FAILURE)
<< "Need to specify --quorum for replicated log based"
<< " registry when using ZooKeeper";
}
Try<zookeeper::URL> url = zookeeper::URL::parse(flags.zk.get());
if (url.isError()) {
EXIT(EXIT_FAILURE) << "Error parsing ZooKeeper URL: " << url.error();
}
log = new Log(
flags.quorum.get(),
path::join(flags.work_dir.get(), "replicated_log"),
url.get().servers,
flags.zk_session_timeout,
path::join(url.get().path, "log_replicas"),
url.get().authentication,
flags.log_auto_initialize,
"registrar/");
} else {
// Use replicated log without ZooKeeper.
log = new Log(
1,
path::join(flags.work_dir.get(), "replicated_log"),
set<UPID>(),
flags.log_auto_initialize,
"registrar/");
}
storage = new LogStorage(log);
#endif // __WINDOWS__
} else {
EXIT(EXIT_FAILURE)
<< "'" << flags.registry << "' is not a supported"
<< " option for registry persistence";
}
CHECK_NOTNULL(storage);
mesos::state::State* state = new mesos::state::State(storage);
Registrar* registrar =
new Registrar(flags, state, READONLY_HTTP_AUTHENTICATION_REALM);
MasterContender* contender;
MasterDetector* detector;
Try<MasterContender*> contender_ = MasterContender::create(
flags.zk, flags.master_contender, flags.zk_session_timeout);
if (contender_.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create a master contender: " << contender_.error();
}
contender = contender_.get();
Try<MasterDetector*> detector_ = MasterDetector::create(
flags.zk, flags.master_detector, flags.zk_session_timeout);
if (detector_.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create a master detector: " << detector_.error();
}
detector = detector_.get();
Option<Authorizer*> authorizer_ = None();
auto authorizerNames = strings::split(flags.authorizers, ",");
if (authorizerNames.empty()) {
EXIT(EXIT_FAILURE) << "No authorizer specified";
}
if (authorizerNames.size() > 1) {
EXIT(EXIT_FAILURE) << "Multiple authorizers not supported";
}
string authorizerName = authorizerNames[0];
// NOTE: The flag --authorizers overrides the flag --acls, i.e. if
// a non default authorizer is requested, it will be used and
// the contents of --acls will be ignored.
// TODO(arojas): Consider adding support for multiple authorizers.
Result<Authorizer*> authorizer((None()));
if (authorizerName != master::DEFAULT_AUTHORIZER) {
LOG(INFO) << "Creating '" << authorizerName << "' authorizer";
authorizer = Authorizer::create(authorizerName);
} else {
// `authorizerName` is `DEFAULT_AUTHORIZER` at this point.
if (flags.acls.isSome()) {
LOG(INFO) << "Creating default '" << authorizerName << "' authorizer";
authorizer = Authorizer::create(flags.acls.get());
}
}
if (authorizer.isError()) {
EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName
<< "' authorizer: " << authorizer.error();
} else if (authorizer.isSome()) {
authorizer_ = authorizer.get();
// Set the authorization callbacks for libprocess HTTP endpoints.
// Note that these callbacks capture `authorizer_.get()`, but the master
// creates a copy of the authorizer during construction. Thus, if in the
// future it becomes possible to dynamically set the authorizer, this would
// break.
process::http::authorization::setCallbacks(
createAuthorizationCallbacks(authorizer_.get()));
}
Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_);
Option<shared_ptr<RateLimiter>> slaveRemovalLimiter = None();
if (flags.agent_removal_rate_limit.isSome()) {
// Parse the flag value.
// TODO(vinod): Move this parsing logic to flags once we have a
// 'Rate' abstraction in stout.
vector<string> tokens =
strings::tokenize(flags.agent_removal_rate_limit.get(), "/");
if (tokens.size() != 2) {
EXIT(EXIT_FAILURE)
<< "Invalid agent_removal_rate_limit: "
<< flags.agent_removal_rate_limit.get()
<< ". Format is <Number of agents>/<Duration>";
}
Try<int> permits = numify<int>(tokens[0]);
if (permits.isError()) {
EXIT(EXIT_FAILURE)
<< "Invalid agent_removal_rate_limit: "
<< flags.agent_removal_rate_limit.get()
<< ". Format is <Number of agents>/<Duration>"
<< ": " << permits.error();
}
Try<Duration> duration = Duration::parse(tokens[1]);
if (duration.isError()) {
EXIT(EXIT_FAILURE)
<< "Invalid agent_removal_rate_limit: "
<< flags.agent_removal_rate_limit.get()
<< ". Format is <Number of agents>/<Duration>"
<< ": " << duration.error();
}
slaveRemovalLimiter = new RateLimiter(permits.get(), duration.get());
}
Master* master =
new Master(
allocator.get(),
registrar,
&files,
contender,
detector,
authorizer_,
slaveRemovalLimiter,
flags);
if (flags.zk.isNone() && flags.master_detector.isNone()) {
// It means we are using the standalone detector so we need to
// appoint this Master as the leader.
dynamic_cast<StandaloneMasterDetector*>(detector)->appoint(master->info());
}
process::spawn(master);
process::wait(master->self());
delete master;
delete allocator.get();
delete registrar;
delete state;
delete storage;
#ifndef __WINDOWS__
delete log;
#endif // __WINDOWS__
delete contender;
delete detector;
if (authorizer_.isSome()) {
delete authorizer_.get();
}
return EXIT_SUCCESS;
}
| 29.68231 | 80 | 0.662977 | j143 |
f65e1081d2a574e654796d99e4dae40e79bc1848 | 1,743 | cpp | C++ | src/MapGenerator/Math/LineEquation.cpp | USCcorpuscallosum/spiky | 38b2d73ae8def2180e9e84f5c9b6ba814468abc9 | [
"MIT"
] | 2 | 2018-11-10T20:56:22.000Z | 2019-02-10T13:14:05.000Z | src/MapGenerator/Math/LineEquation.cpp | FutureVR/ResponsiveTerrain | f5e631539e886dffb0b4b3f398803730db31f8d7 | [
"MIT"
] | null | null | null | src/MapGenerator/Math/LineEquation.cpp | FutureVR/ResponsiveTerrain | f5e631539e886dffb0b4b3f398803730db31f8d7 | [
"MIT"
] | null | null | null | // MapGenerator
// from https://github.com/Rellikiox/MapGenerator
/*
* LineEquation.cc
*
* Created on: Mar 5, 2012
* Author: rellik
*/
#include "LineEquation.h"
equ::equ(Vec2 p1, Vec2 p2) {
// Calculamos la pendiente
if (p1.x != p2.x) {
vertical = false;
m = (p2.y - p1.y) / (p2.x - p1.x);
b = p1.y - p1.y * m;
} else {
vertical = true;
m = 0;
b = p1.x;
}
}
equ::equ(Vec2 p, double m_){
m = m_;
if(m != 0){
vertical = false;
b = p.y - p.x * m;
}else{
vertical = true;
b = p.x;
}
}
equ::equ(const equ& e) {
m = e.m;
b = e.b;
vertical = e.vertical;
}
equ & equ::operator=(const equ &e) {
if (this != &e) {
m = e.m;
b = e.b;
vertical = e.vertical;
}
return *this;
}
equ::~equ() {
m = 0;
b = 0;
vertical = false;
}
double equ::operator()(const double x) {
return (x * m + b);
}
void equ::Move(const Vec2 vec) {
Vec2 p0, p1;
if (vertical) {
p0 = Vec2(b, 0);
p1 = Vec2(b, 1);
} else {
p0 = Vec2(0, b);
p1 = Vec2(1, m + b);
}
p0 += Vec2(vec.x, vec.y);
p1 += Vec2(vec.x, vec.y);
*this = equ(p0, p1);
}
Vec2 equ::Intersection(equ &e) const {
double x;
double y;
if (this->m != e.m) {
if (this->vertical) {
x = this->b;
y = e(x);
} else if (e.vertical) {
x = e.b;
y = x * this->m + this->b;
} else {
x = (e.b - this->b) / (this->m - e.m);
y = e(x);
}
} else {
if (this->vertical == e.vertical) {
x = 0;
y = 0;
} else {
if (this->vertical) { // this es vertical, e es horizontal
x = this->b;
y = e.b;
} else { // this es horizontal, e es vertical
x = e.b;
y = this->b;
}
}
}
return Vec2(x, y);
}
bool equ::Vertical(){
return vertical;
}
bool equ::Horizontal(){
return !vertical && m == 0;
}
| 14.056452 | 61 | 0.507745 | USCcorpuscallosum |
f6609f6d03e7978270d4bf9a093b009cf884c0cd | 3,145 | cpp | C++ | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | #include <common.h>
#pragma hdrstop
#include <OpenGlRenderMechanism.h>
#include <GlContextManager.h>
#include <GlWindowUtils.h>
#include <DrawEnums.h>
#include <State.h>
#include <Framebuffer.h>
namespace Gin {
//////////////////////////////////////////////////////////////////////////
COpenGlRenderMechanism::COpenGlRenderMechanism( CGlContextManager& _glContextManager ) :
glContextManager( _glContextManager )
{
backgroundBrush = ::CreateSolidBrush( RGB( 0, 0, 0 ) );
}
COpenGlRenderMechanism::~COpenGlRenderMechanism()
{
::DeleteObject( backgroundBrush );
}
void COpenGlRenderMechanism::AttachNewWindow( const CGlWindow& newWindow )
{
assert( newWindow.IsCreated() );
targetWindow = &newWindow;
OnWindowResize( newWindow.WindowSize() );
}
void COpenGlRenderMechanism::ActivateWindowTarget()
{
glContextManager.SetContextTarget( targetWindow->GetDeviceContext() );
}
void COpenGlRenderMechanism::SetBackgroundColor( CColor newValue )
{
backgroundColor = newValue;
::DeleteObject( backgroundBrush );
backgroundBrush = ::CreateSolidBrush( RGB( newValue.R, newValue.G, newValue.B ) );
}
void COpenGlRenderMechanism::OnWindowResize( CVector2<int> )
{
}
LRESULT COpenGlRenderMechanism::OnEraseBackground( HWND, WPARAM wParam, LPARAM )
{
RECT bgRect{ INT_MIN, INT_MIN, INT_MAX, INT_MAX };
HDC bgDC = reinterpret_cast<HDC>( wParam );
::FillRect( bgDC, &bgRect, backgroundBrush );
return 1;
}
void COpenGlRenderMechanism::OnDraw( const IState& currentState ) const
{
const auto windowSize = targetWindow->WindowSize();
CViewportSwitcher::SetBaseViewport( CVector2<int>{}, windowSize );
// Set the clear values.
gl::ClearColor( backgroundColor.GetRed(), backgroundColor.GetGreen(), backgroundColor.GetBlue(), backgroundColor.GetAlpha() );
gl::ClearDepth( glContextManager.GetDepthZFar() );
gl::Enable( gl::DEPTH_TEST );
gl::Disable( gl::BLEND );
// Clear the buffer.
gl::Clear( gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT );
currentState.Draw( COpenGlRenderParameters( *targetWindow ) );
}
void COpenGlRenderMechanism::OnPostDraw() const
{
::SwapBuffers( targetWindow->GetDeviceContext() );
}
LRESULT COpenGlRenderMechanism::OnPaintMessage( HWND window, WPARAM wParam, LPARAM lParam, const IState& ) const
{
return ::DefWindowProc( window, WM_PAINT, wParam, lParam );
}
CArray<BYTE> COpenGlRenderMechanism::ReadScreenBuffer( TTexelFormat format, CVector2<int>& bufferSize ) const
{
assert( CFramebufferSwitcher::GetReadTarget() == 0 );
const auto viewportSize = CViewportSwitcher::GetViewportSize();
const int rowSize = CeilTo( 3 * viewportSize.X(), 4 );
const int dataSize = rowSize * viewportSize.Y();
CArray<BYTE> data;
data.IncreaseSizeNoInitialize( dataSize );
gl::PixelStorei( AT_Pack, 4 );
gl::ReadPixels( 0, 0, viewportSize.X(), viewportSize.Y(), format, TDT_UnsignedByte, data.Ptr() );
gl::PixelStorei( AT_Pack, 1 );
bufferSize = viewportSize;
return data;
}
//////////////////////////////////////////////////////////////////////////
} // namespace Gin.
| 30.240385 | 128 | 0.694118 | Remag |
f6647e6a84681938cef7fe76635a019510ae7d6a | 11,230 | cpp | C++ | llvm/lib/Target/Mips/MipsRegisterInfo.cpp | haohua-li/t-sgx-mirror | 49188063f3cb5300cda8a03255cfe800e8266ace | [
"MIT"
] | 26 | 2017-04-18T15:51:16.000Z | 2022-03-29T07:03:37.000Z | llvm/lib/Target/Mips/MipsRegisterInfo.cpp | haohua-li/t-sgx-mirror | 49188063f3cb5300cda8a03255cfe800e8266ace | [
"MIT"
] | 2 | 2017-10-27T21:29:04.000Z | 2019-06-12T01:23:38.000Z | 3.7.0/llvm-3.7.0.src/lib/Target/Mips/MipsRegisterInfo.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 9 | 2017-10-02T19:54:36.000Z | 2021-11-22T00:48:18.000Z | //===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsInstrInfo.h"
#include "MipsMachineFunction.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
#define DEBUG_TYPE "mips-reg-info"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
MipsRegisterInfo::MipsRegisterInfo() : MipsGenRegisterInfo(Mips::RA) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
const TargetRegisterClass *
MipsRegisterInfo::getPointerRegClass(const MachineFunction &MF,
unsigned Kind) const {
MipsABIInfo ABI = MF.getSubtarget<MipsSubtarget>().getABI();
return ABI.ArePtrs64bit() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass;
}
unsigned
MipsRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
MachineFunction &MF) const {
switch (RC->getID()) {
default:
return 0;
case Mips::GPR32RegClassID:
case Mips::GPR64RegClassID:
case Mips::DSPRRegClassID: {
const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
return 28 - TFI->hasFP(MF);
}
case Mips::FGR32RegClassID:
return 32;
case Mips::AFGR64RegClassID:
return 16;
case Mips::FGR64RegClassID:
return 32;
}
}
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const MCPhysReg *
MipsRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
const MipsSubtarget &Subtarget = MF->getSubtarget<MipsSubtarget>();
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_SaveList;
if (Subtarget.isABI_N64())
return CSR_N64_SaveList;
if (Subtarget.isABI_N32())
return CSR_N32_SaveList;
if (Subtarget.isFP64bit())
return CSR_O32_FP64_SaveList;
if (Subtarget.isFPXX())
return CSR_O32_FPXX_SaveList;
return CSR_O32_SaveList;
}
const uint32_t *
MipsRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
CallingConv::ID) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_RegMask;
if (Subtarget.isABI_N64())
return CSR_N64_RegMask;
if (Subtarget.isABI_N32())
return CSR_N32_RegMask;
if (Subtarget.isFP64bit())
return CSR_O32_FP64_RegMask;
if (Subtarget.isFPXX())
return CSR_O32_FPXX_RegMask;
return CSR_O32_RegMask;
}
const uint32_t *MipsRegisterInfo::getMips16RetHelperMask() {
return CSR_Mips16RetHelper_RegMask;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const MCPhysReg ReservedGPR32[] = {
Mips::ZERO, Mips::K0, Mips::K1, Mips::SP
};
static const MCPhysReg ReservedGPR64[] = {
Mips::ZERO_64, Mips::K0_64, Mips::K1_64, Mips::SP_64
};
BitVector Reserved(getNumRegs());
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
typedef TargetRegisterClass::const_iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedGPR32); ++I)
Reserved.set(ReservedGPR32[I]);
// Reserve registers for the NaCl sandbox.
if (Subtarget.isTargetNaCl()) {
Reserved.set(Mips::T6); // Reserved for control flow mask.
Reserved.set(Mips::T7); // Reserved for memory access mask.
Reserved.set(Mips::T8); // Reserved for thread pointer.
}
for (unsigned I = 0; I < array_lengthof(ReservedGPR64); ++I)
Reserved.set(ReservedGPR64[I]);
// For mno-abicalls, GP is a program invariant!
if (!Subtarget.isABICalls()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
if (Subtarget.isFP64bit()) {
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegClass.begin(),
EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
} else {
// Reserve all registers in FGR64.
for (RegIter Reg = Mips::FGR64RegClass.begin(),
EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
}
// Reserve FP if this function should have a dedicated frame pointer register.
if (Subtarget.getFrameLowering()->hasFP(MF)) {
if (Subtarget.inMips16Mode())
Reserved.set(Mips::S0);
else {
Reserved.set(Mips::FP);
Reserved.set(Mips::FP_64);
// Reserve the base register if we need to both realign the stack and
// allocate variable-sized objects at runtime. This should test the
// same conditions as MipsFrameLowering::hasBP().
if (needsStackRealignment(MF) &&
MF.getFrameInfo()->hasVarSizedObjects()) {
Reserved.set(Mips::S7);
Reserved.set(Mips::S7_64);
}
}
}
// Reserve hardware registers.
Reserved.set(Mips::HWR29);
// Reserve DSP control register.
Reserved.set(Mips::DSPPos);
Reserved.set(Mips::DSPSCount);
Reserved.set(Mips::DSPCarry);
Reserved.set(Mips::DSPEFI);
Reserved.set(Mips::DSPOutFlag);
// Reserve MSA control registers.
Reserved.set(Mips::MSAIR);
Reserved.set(Mips::MSACSR);
Reserved.set(Mips::MSAAccess);
Reserved.set(Mips::MSASave);
Reserved.set(Mips::MSAModify);
Reserved.set(Mips::MSARequest);
Reserved.set(Mips::MSAMap);
Reserved.set(Mips::MSAUnmap);
// Reserve RA if in mips16 mode.
if (Subtarget.inMips16Mode()) {
const MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
Reserved.set(Mips::RA);
Reserved.set(Mips::RA_64);
Reserved.set(Mips::T0);
Reserved.set(Mips::T1);
if (MF.getFunction()->hasFnAttribute("saveS2") || MipsFI->hasSaveS2())
Reserved.set(Mips::S2);
}
// Reserve GP if small section is used.
if (Subtarget.useSmallSection()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
if (Subtarget.isABI_O32() && !Subtarget.useOddSPReg()) {
for (const auto &Reg : Mips::OddSPRegClass)
Reserved.set(Reg);
}
return Reserved;
}
bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
return true;
}
bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
return true;
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
unsigned FIOperandNum, RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
DEBUG(errs() << "\nFunction : " << MF.getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
uint64_t stackSize = MF.getFrameInfo()->getStackSize();
int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
eliminateFI(MI, FIOperandNum, FrameIndex, stackSize, spOffset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
bool IsN64 =
static_cast<const MipsTargetMachine &>(MF.getTarget()).getABI().IsN64();
if (Subtarget.inMips16Mode())
return TFI->hasFP(MF) ? Mips::S0 : Mips::SP;
else
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
bool MipsRegisterInfo::canRealignStack(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
unsigned FP = Subtarget.isGP32bit() ? Mips::FP : Mips::FP_64;
unsigned BP = Subtarget.isGP32bit() ? Mips::S7 : Mips::S7_64;
// Support dynamic stack realignment only for targets with standard encoding.
if (!Subtarget.hasStandardEncoding())
return false;
// We can't perform dynamic stack realignment if we can't reserve the
// frame pointer register.
if (!MF.getRegInfo().canReserveReg(FP))
return false;
// We can realign the stack if we know the maximum call frame size and we
// don't have variable sized objects.
if (Subtarget.getFrameLowering()->hasReservedCallFrame(MF))
return true;
// We have to reserve the base pointer register in the presence of variable
// sized objects.
return MF.getRegInfo().canReserveReg(BP);
}
bool MipsRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
const MachineFrameInfo *MFI = MF.getFrameInfo();
bool CanRealign = canRealignStack(MF);
// Avoid realigning functions that explicitly do not want to be realigned.
// Normally, we should report an error when a function should be dynamically
// realigned but also has the attribute no-realign-stack. Unfortunately,
// with this attribute, MachineFrameInfo clamps each new object's alignment
// to that of the stack's alignment as specified by the ABI. As a result,
// the information of whether we have objects with larger alignment
// requirement than the stack's alignment is already lost at this point.
if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
return false;
const Function *F = MF.getFunction();
if (F->hasFnAttribute(Attribute::StackAlignment)) {
#ifdef DEBUG
if (!CanRealign)
DEBUG(dbgs() << "It's not possible to realign the stack of the function: "
<< F->getName() << "\n");
#endif
return CanRealign;
}
unsigned StackAlignment = Subtarget.getFrameLowering()->getStackAlignment();
if (MFI->getMaxAlignment() > StackAlignment) {
#ifdef DEBUG
if (!CanRealign)
DEBUG(dbgs() << "It's not possible to realign the stack of the function: "
<< F->getName() << "\n");
#endif
return CanRealign;
}
return false;
}
| 32.270115 | 80 | 0.675779 | haohua-li |