blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
086df1ba8995428a2622ef98bb41ace66de38d04 | ac250666993ac5ed1c6f9196ad15e4f59d5278fb | /Intermediate/Plugins/WindowsNoEditor/NativizedAssets/Intermediate/Build/Win64/UE4/Inc/NativizedAssets/Popxup__pfG1863595755.gen.cpp | 163ade1dc1bf59cec8e27e4dc05d5ec45b4340bc | [] | no_license | wcthscgda/BP_PVehicles-4.17 | ac1ccfce5864efb145ef8bc0f0e2d44949dd8dde | 24019b14b160ffcb785adc3ef42d680eb5ae6c23 | refs/heads/master | 2020-05-30T01:33:26.394426 | 2019-06-12T12:22:17 | 2019-06-12T12:22:17 | 189,473,094 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,277 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "Private/NativizedAssets.h"
#include "Public/Popxup__pfG1863595755.h"
PRAGMA_DISABLE_OPTIMIZATION
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodePopxup__pfG1863595755() {}
// Cross Module References
NATIVIZEDASSETS_API UFunction* Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__Construct__pf();
NATIVIZEDASSETS_API UClass* Z_Construct_UClass_UPopxup_C__pfG1863595755();
NATIVIZEDASSETS_API UFunction* Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__ExecuteUbergraph_Popxup__pfG_0();
NATIVIZEDASSETS_API UClass* Z_Construct_UClass_UPopxup_C__pfG1863595755_NoRegister();
UMG_API UClass* Z_Construct_UClass_UUserWidget();
UMG_API UClass* Z_Construct_UClass_UEditableText_NoRegister();
UMG_API UClass* Z_Construct_UClass_UBorder_NoRegister();
UMG_API UClass* Z_Construct_UClass_UWidgetAnimation_NoRegister();
// End Cross Module References
static FName NAME_UPopxup_C__pfG1863595755_bpf__Construct__pf = FName(TEXT("Construct"));
void UPopxup_C__pfG1863595755::eventbpf__Construct__pf()
{
ProcessEvent(FindFunctionChecked(NAME_UPopxup_C__pfG1863595755_bpf__Construct__pf),NULL);
}
void UPopxup_C__pfG1863595755::StaticRegisterNativesUPopxup_C__pfG1863595755()
{
UClass* Class = UPopxup_C__pfG1863595755::StaticClass();
static const TNameNativePtrPair<TCHAR> TCharFuncs[] = {
{ TEXT("Construct"), (Native)&UPopxup_C__pfG1863595755::execbpf__Construct__pf },
{ TEXT("ExecuteUbergraph_Pop-up_0"), (Native)&UPopxup_C__pfG1863595755::execbpf__ExecuteUbergraph_Popxup__pfG_0 },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, TCharFuncs, ARRAY_COUNT(TCharFuncs));
}
UFunction* Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__Construct__pf()
{
UObject* Outer = Z_Construct_UClass_UPopxup_C__pfG1863595755();
UFunction* ReturnFunction = static_cast<UFunction*>(StaticFindObjectFast( UFunction::StaticClass(), Outer, TEXT("Construct") ));
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("Construct"), RF_Public|RF_Transient) UFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x00020C09, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("User Interface"));
MetaData->SetValue(ReturnFunction, TEXT("CppFromBpEvent"), TEXT(""));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("Begin Play"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(ReturnFunction, TEXT("OverrideNativeName"), TEXT("Construct"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Called after the underlying slate widget is constructed. Depending on how the slate object is usedthis event may be called multiple times due to adding and removing from the hierarchy."));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__ExecuteUbergraph_Popxup__pfG_0()
{
struct Popxup_C__pfG1863595755_eventbpf__ExecuteUbergraph_Popxup__pfG_0_Parms
{
int32 bpp__EntryPoint__pf;
};
UObject* Outer = Z_Construct_UClass_UPopxup_C__pfG1863595755();
UFunction* ReturnFunction = static_cast<UFunction*>(StaticFindObjectFast( UFunction::StaticClass(), Outer, TEXT("ExecuteUbergraph_Pop-up_0") ));
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ExecuteUbergraph_Pop-up_0"), RF_Public|RF_Transient) UFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x00020401, 65535, sizeof(Popxup_C__pfG1863595755_eventbpf__ExecuteUbergraph_Popxup__pfG_0_Parms));
UProperty* NewProp_bpp__EntryPoint__pf = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("bpp__EntryPoint__pf"), RF_Public|RF_Transient) UIntProperty(CPP_PROPERTY_BASE(bpp__EntryPoint__pf, Popxup_C__pfG1863595755_eventbpf__ExecuteUbergraph_Popxup__pfG_0_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(ReturnFunction, TEXT("OverrideNativeName"), TEXT("ExecuteUbergraph_Pop-up_0"));
#endif
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UPopxup_C__pfG1863595755_NoRegister()
{
return UPopxup_C__pfG1863595755::StaticClass();
}
UClass* Z_Construct_UClass_UPopxup_C__pfG1863595755()
{
UPackage* OuterPackage = FindOrConstructDynamicTypePackage(TEXT("/Game/UMG/Pop-up"));
UClass* OuterClass = Cast<UClass>(StaticFindObjectFast(UClass::StaticClass(), OuterPackage, TEXT("Pop-up_C")));
if (!OuterClass || !(OuterClass->ClassFlags & CLASS_Constructed))
{
Z_Construct_UClass_UUserWidget();
OuterClass = UPopxup_C__pfG1863595755::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= (EClassFlags)0x20A01080u;
OuterClass->LinkChild(Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__Construct__pf());
OuterClass->LinkChild(Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__ExecuteUbergraph_Popxup__pfG_0());
UProperty* NewProp_bpv__Text__pf = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Text"), RF_Public|RF_Transient) UTextProperty(CPP_PROPERTY_BASE(bpv__Text__pf, UPopxup_C__pfG1863595755), 0x0011000000000005);
UProperty* NewProp_bpv__Duration__pf = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Duration"), RF_Public|RF_Transient) UFloatProperty(CPP_PROPERTY_BASE(bpv__Duration__pf, UPopxup_C__pfG1863595755), 0x0011000000000005);
UProperty* NewProp_bpv__Popup_Text__pf = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Popup_Text"), RF_Public|RF_Transient) UObjectProperty(CPP_PROPERTY_BASE(bpv__Popup_Text__pf, UPopxup_C__pfG1863595755), 0x001000000008000c, Z_Construct_UClass_UEditableText_NoRegister());
UProperty* NewProp_bpv__Border_86__pf = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Border_86"), RF_Public|RF_Transient) UObjectProperty(CPP_PROPERTY_BASE(bpv__Border_86__pf, UPopxup_C__pfG1863595755), 0x001000000008000c, Z_Construct_UClass_UBorder_NoRegister());
UProperty* NewProp_bpv__Fadexin__pfT = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Fade in"), RF_Public|RF_Transient) UObjectProperty(CPP_PROPERTY_BASE(bpv__Fadexin__pfT, UPopxup_C__pfG1863595755), 0x001000000008001c, Z_Construct_UClass_UWidgetAnimation_NoRegister());
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__Construct__pf(), TEXT("Construct")); // 868031800
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UPopxup_C__pfG1863595755_bpf__ExecuteUbergraph_Popxup__pfG_0(), TEXT("ExecuteUbergraph_Pop-up_0")); // 2551178735
OuterClass->ClassConfigName = FName(TEXT("Engine"));
static TCppClassTypeInfo<TCppClassTypeTraits<UPopxup_C__pfG1863595755> > StaticCppClassTypeInfo;
OuterClass->SetCppTypeInfo(&StaticCppClassTypeInfo);
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("BlueprintType"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("Popxup__pfG1863595755.h"));
MetaData->SetValue(OuterClass, TEXT("IsBlueprintBase"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(OuterClass, TEXT("ObjectInitializerConstructorDeclared"), TEXT(""));
MetaData->SetValue(OuterClass, TEXT("OverrideNativeName"), TEXT("Pop-up_C"));
MetaData->SetValue(OuterClass, TEXT("ReplaceConverted"), TEXT("/Game/UMG/Pop-up.Pop-up_C"));
MetaData->SetValue(NewProp_bpv__Text__pf, TEXT("Category"), TEXT("Default"));
MetaData->SetValue(NewProp_bpv__Text__pf, TEXT("DisplayName"), TEXT("Text"));
MetaData->SetValue(NewProp_bpv__Text__pf, TEXT("ExposeOnSpawn"), TEXT("true"));
MetaData->SetValue(NewProp_bpv__Text__pf, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(NewProp_bpv__Text__pf, TEXT("OverrideNativeName"), TEXT("Text"));
MetaData->SetValue(NewProp_bpv__Duration__pf, TEXT("Category"), TEXT("Default"));
MetaData->SetValue(NewProp_bpv__Duration__pf, TEXT("DisplayName"), TEXT("Duration"));
MetaData->SetValue(NewProp_bpv__Duration__pf, TEXT("ExposeOnSpawn"), TEXT("true"));
MetaData->SetValue(NewProp_bpv__Duration__pf, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(NewProp_bpv__Duration__pf, TEXT("OverrideNativeName"), TEXT("Duration"));
MetaData->SetValue(NewProp_bpv__Popup_Text__pf, TEXT("Category"), TEXT("Pop-up"));
MetaData->SetValue(NewProp_bpv__Popup_Text__pf, TEXT("DisplayName"), TEXT("Popup_Text"));
MetaData->SetValue(NewProp_bpv__Popup_Text__pf, TEXT("EditInline"), TEXT("true"));
MetaData->SetValue(NewProp_bpv__Popup_Text__pf, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(NewProp_bpv__Popup_Text__pf, TEXT("OverrideNativeName"), TEXT("Popup_Text"));
MetaData->SetValue(NewProp_bpv__Border_86__pf, TEXT("Category"), TEXT("Pop-up"));
MetaData->SetValue(NewProp_bpv__Border_86__pf, TEXT("DisplayName"), TEXT("Border_86"));
MetaData->SetValue(NewProp_bpv__Border_86__pf, TEXT("EditInline"), TEXT("true"));
MetaData->SetValue(NewProp_bpv__Border_86__pf, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(NewProp_bpv__Border_86__pf, TEXT("OverrideNativeName"), TEXT("Border_86"));
MetaData->SetValue(NewProp_bpv__Fadexin__pfT, TEXT("Category"), TEXT("Animations"));
MetaData->SetValue(NewProp_bpv__Fadexin__pfT, TEXT("EditInline"), TEXT("true"));
MetaData->SetValue(NewProp_bpv__Fadexin__pfT, TEXT("ModuleRelativePath"), TEXT("Public/Popxup__pfG1863595755.h"));
MetaData->SetValue(NewProp_bpv__Fadexin__pfT, TEXT("OverrideNativeName"), TEXT("Fade in"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
IMPLEMENT_DYNAMIC_CLASS(UPopxup_C__pfG1863595755, TEXT("Pop-up_C"), 2540750571);
static FCompiledInDefer Z_CompiledInDefer_UClass_UPopxup_C__pfG1863595755(Z_Construct_UClass_UPopxup_C__pfG1863595755, &UPopxup_C__pfG1863595755::StaticClass, TEXT("/Game/UMG/Pop-up"), TEXT("Pop-up_C"), true, TEXT("/Game/UMG/Pop-up"), TEXT("/Game/UMG/Pop-up.Pop-up_C"), nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UPopxup_C__pfG1863595755);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
PRAGMA_ENABLE_OPTIMIZATION
| [
"43680366+wcthscgda@users.noreply.github.com"
] | 43680366+wcthscgda@users.noreply.github.com |
9649ea4d916ed57224665f814842f6f31aa85959 | 798dd8cc7df5833999dfceb0215bec7384783e6a | /unit_tests/querymerge.cpp | ac2a82b9718133cc03aab602a08392b7aff82fdb | [
"BSD-3-Clause"
] | permissive | sblanas/pythia | 8cf85b39d555c6ce05445d9d690d5462d0e80007 | b138eaa0fd5917cb4665094b963abe458bd33d0f | refs/heads/master | 2016-09-06T03:43:26.647265 | 2014-02-10T21:39:24 | 2014-02-10T21:39:24 | 16,710,063 | 15 | 8 | null | 2014-03-08T05:29:34 | 2014-02-10T21:31:16 | C++ | UTF-8 | C++ | false | false | 4,525 | cpp | /*
* Copyright 2014, Pythia authors (see AUTHORS file).
* 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.
*/
#include "libconfig.h++"
#include "../query.h"
#include "../operators/operators.h"
#include "../visitors/allvisitors.h"
#include "common.h"
const char* tempfilename = "artzimpourtzikaioloulas.tmp";
// #define VERBOSE
const int TUPLES=20;
using namespace std;
using namespace libconfig;
Query q;
PartitionedScanOp node1;
MergeOp node2;
int verify[TUPLES];
void compute()
{
for (int i=0; i<TUPLES; ++i) {
verify[i] = 0;
}
q.threadInit();
Operator::Page* out;
Operator::GetNextResultT result;
if (q.scanStart() != Operator::Ready) {
fail("Scan initialization failed.");
}
while(result.first == Operator::Ready) {
result = q.getNext();
out = result.second;
Operator::Page::Iterator it = out->createIterator();
void* tuple;
while ( (tuple = it.next()) ) {
#ifdef VERBOSE
cout << q.getOutSchema().prettyprint(tuple, ' ') << endl;
#endif
long long v = q.getOutSchema().asLong(tuple, 0);
if (v <= 0 || v > TUPLES || q.getOutSchema().asLong(tuple, 1) != v)
fail("Values that never were generated appear in the output stream.");
verify[v-1]++;
}
}
assert(result.first != Operator::Error);
if (q.scanStop() != Operator::Ready) {
fail("Scan stop failed.");
}
q.threadClose();
}
void test(const int threads)
{
const int buffsize = 1 << 4;
createfile(tempfilename, TUPLES);
Config cfg;
// init node1
cfg.getRoot().add("path", Setting::TypeString) = "./";
cfg.getRoot().add("buffsize", Setting::TypeInt) = buffsize;
Setting& scannode = cfg.getRoot().add("scan", Setting::TypeGroup);
scannode.add("filetype", Setting::TypeString) = "text";
Setting& files = scannode.add("files", Setting::TypeList);
for (int i=0; i<threads; ++i) {
files.add(Setting::TypeString) = tempfilename;
}
Setting& schemanode = scannode.add("schema", Setting::TypeList);
schemanode.add(Setting::TypeString) = "long";
schemanode.add(Setting::TypeString) = "long";
// init node2
Setting& mergenode = cfg.getRoot().add("merge", Setting::TypeGroup);
mergenode.add("threads", Setting::TypeInt) = threads;
// build plan tree
q.tree = &node2;
node2.nextOp = &node1;
// initialize each node
node1.init(cfg, scannode);
node2.init(cfg, mergenode);
#ifdef VERBOSE
cout << "---------- QUERY PLAN START ----------" << endl;
PrettyPrinterVisitor ppv;
q.accept(&ppv);
cout << "----------- QUERY PLAN END -----------" << endl;
#endif
compute();
for (int i=0; i<TUPLES; ++i) {
if (verify[i] < threads) {
#ifdef VERBOSE
cout << "threads:" << threads
<< " verify[" << i << "]:" << verify[i] << endl;
#endif
fail("Tuples are missing from output.");
}
if (verify[i] > threads)
fail("Extra tuples are in output.");
}
q.destroynofree();
deletefile(tempfilename);
}
int main()
{
int retries = 2;
srand48(time(0));
for (int i=0; i<retries; ++i) {
#ifdef VERBOSE
cout << "Iteration " << i << endl;
#endif
test((lrand48() & 0x2F) + 1);
}
return 0;
}
| [
"blanas.2@osu.edu"
] | blanas.2@osu.edu |
b6bb2d61003fbde24ac063d22dd56cf191cfad44 | 9e74558700c669c0cc6b8163798138c25d7b2da6 | /BuildVMByteCode.cpp | b51eb692936e8f0e7d6a71b5b1dd5675abda17cc | [] | no_license | qiantangbanmu/WProtectvs | e040cf4a989565a191bae913d4dcb4825a92f4a2 | dc50eefe8329bf671297c22474b2353f39ef64b2 | refs/heads/master | 2021-08-15T03:48:19.043995 | 2017-11-17T08:37:10 | 2017-11-17T08:37:10 | 110,064,249 | 30 | 17 | null | null | null | null | GB18030 | C++ | false | false | 99,646 | cpp | /************************************************************
* *
* *
* 2015年7月31日 *
* By:XiaoWei *
* *
* *
*****************************************************/
#include <list>
#include <map>
#include <vector>
#define _STDINT_H
#include "BuildVMByteCode.hpp"
#include "VirtualMachine.h"
#include "CombosVMCode.hpp"
#include "VMAddressTable.hpp"
#include "VMCodeBuffer.hpp"
#include "PCode.hpp"
#include "Analysis.hpp"
#include "OutDetailedInformation.hpp"
#include "AsmJit/opcode_table.h"
#include "VOperand.hpp"
#pragma warning(disable:4309)
#define get_operand1(x) x.operand[0]
#define get_operand2(x) x.operand[1]
#define get_operand1_type(x) x.operand[0].type
#define get_operand2_type(x) x.operand[1].type
#define read_mem(x) if(x.type == UD_OP_MEM) { \
switch (x.size) { \
case 0:\
printf("大小为0\n");\
break;\
case 8:\
var_combos_vm_code.b_read_mem();\
break;\
case 16:\
var_combos_vm_code.w_read_mem();\
break;\
case 32:\
var_combos_vm_code.d_read_mem();\
break;\
case 64:\
int low_tmp_addr = var_combos_vm_code.get_tmp_vmregister();\
var_combos_vm_code.push_vsp();\
var_combos_vm_code.d_read_mem();\
var_combos_vm_code.pop(low_tmp_addr);\
var_combos_vm_code.b_push_imm_zx(4);\
var_combos_vm_code.d_add();\
var_combos_vm_code.pop(T_INVALID);\
var_combos_vm_code.d_read_mem();\
var_combos_vm_code.push(low_tmp_addr | T_E32X);\
var_combos_vm_code.d_read_mem();\
var_combos_vm_code.unlock_tmp_vmregister(low_tmp_addr);\
break;} \
}
#define write_mem(x) if(x.type == UD_OP_MEM){ \
switch (x.size){ \
case 8:\
var_combos_vm_code.b_write_mem();\
break;\
case 16:\
var_combos_vm_code.w_write_mem();\
break;\
case 32:\
var_combos_vm_code.d_write_mem();\
break;\
case 64:\
int higt_tmp_addr = var_combos_vm_code.get_tmp_vmregister();\
var_combos_vm_code.push_vsp();\
var_combos_vm_code.d_read_mem();\
var_combos_vm_code.b_push_imm_zx(4);\
var_combos_vm_code.d_add();\
var_combos_vm_code.pop(T_INVALID);\
var_combos_vm_code.pop(higt_tmp_addr| T_E32X);\
var_combos_vm_code.d_write_mem();\
var_combos_vm_code.push(higt_tmp_addr | T_E32X);\
var_combos_vm_code.d_write_mem();\
var_combos_vm_code.unlock_tmp_vmregister(higt_tmp_addr);\
break;}}
// 根据operand[0]的size,调整operand[1]中的立即数的值
#define set_imm_operand_size(dst,src) if (dst.type == UD_OP_IMM)\
{\
switch (src.size)\
{\
case 8:\
break;\
case 16:\
if (dst.size == 8)\
dst.lval.sword = (signed short)dst.lval.sbyte;\
break;\
case 32:\
if (dst.size == 8)\
{\
dst.lval.sdword = (signed int)dst.lval.sbyte;\
}\
else if (dst.size == 16)\
{\
dst.lval.sdword = (signed int)dst.lval.sword;\
}\
break;\
}\
dst.size = src.size;\
}
void printf_map_register_store(
std::map<int,RegisterStore> & _p_map_in,
std::map<int,RegisterStore> & _p_map_out)
{
int i = 0;
while (_p_map_in.find(i) != _p_map_in.end())
{
printf("标签:%x\n",i);
printf("In Key:%08x\n",_p_map_in[i].get_key());
OutDI di;
di.set_begin_text("");
di.set_end_text(" ");
di.print_vmregister_information(_p_map_in[i]);
printf("\nOut Key:%08x\n",_p_map_out[i].get_key());
di.set_begin_text("");
di.set_end_text(" ");
di.print_vmregister_information(_p_map_out[i]);
i++;
printf("\n");
}
}
void printf_map_register_store(std::map<int,RegisterStore> & _p_map,
char *sz)
{/*{{{*/
std::map<int,RegisterStore>::iterator iter = _p_map.begin();
for (iter; iter!=_p_map.end();iter++)
{
printf("标签:%x\n",iter->first);
printf("%s Key:%08x\n\n",sz,iter->second.get_key());
OutDI di;
di.set_begin_text(sz);
di.set_end_text("\n");
di.print_vmregister_information(iter->second);
}
}/*}}}*/
long BuildVMByteCode::get_vmcode_address(int _label_index)
{
long result = 0;
if (var_map_label_vmcode_addr.find(_label_index) !=
var_map_label_vmcode_addr.end())
{
result = var_map_label_vmcode_addr[_label_index];
}
return result;
}
long BuildVMByteCode::create_vm_entry(int _piece_label)
{
long opcode_addr = get_vmcode_address(_piece_label);
long init_de_key = 0x12345678;
bool t_sign = ptr_addr_table->get_sign();
ptr_addr_table->set_sign(true);
long head_address = ptr_addr_table->assign_address(0x70);
ptr_addr_table->set_sign(t_sign);
VMCodeBufferManage * buffer_manage = var_map_label_vmbuffer_manage[_piece_label];
ppcode_block_info info = pVM->create_function_head(
head_address,
opcode_addr,
&(buffer_manage->get_pcode()),
123,
123456,
init_de_key); //pcode位置有问题
ptr_addr_table->copy(head_address,info->buf,info->size);
printf("VM入口点地址:%x\n",head_address);
return head_address;
}
long BuildVMByteCode::build_vmcode(bool b_allocator)
{
long vm_byte_code_head = 0;
newlabel_count = 0;
for (std::vector<CodePiece>::iterator iter = var_list_code_piece.begin();
iter != var_list_code_piece.end();
iter++)
{
int var_cur_label = iter->get_label();
VMCodeBufferManage * cur_vmbuffer_manage = NULL;
if (b_allocator)
{
cur_vmbuffer_manage = new VMCodeBufferManage(pVM);
cur_vmbuffer_manage->set_vmcode_label(var_cur_label);
var_vmcode_manager_list.push_back(cur_vmbuffer_manage);
var_map_label_vmbuffer_manage.insert(
std::make_pair(
var_cur_label,cur_vmbuffer_manage));
}
else
{
if (var_map_label_vmbuffer_manage.find(var_cur_label) !=
var_map_label_vmbuffer_manage.end())
{
cur_vmbuffer_manage = var_map_label_vmbuffer_manage[var_cur_label];
}
else
{
__asm int 3;
}
}
PCode & var_pcode = cur_vmbuffer_manage->get_pcode();
VCombosVMCode & var_combos_vm_code = cur_vmbuffer_manage->get_generator();
VTable var_vmcode_info;
if (b_allocator)
{
var_vmcode_info.key = var_pcode.get_original_key();
var_vmcode_info.v = &var_combos_vm_code;
var_pcode.count_vmcode_begin();
var_pcode.set_key(0x12345678);
}
else
{
#ifdef _DEBUG
char file_name[256];
memset(&file_name,0,256);
sprintf_s(file_name, 256, "virtual_machine_Label%d,%08x\n",
iter->get_label(),
var_map_label_vmcode_addr[iter->get_label()]);
var_pcode.out_log_file(file_name);
#endif
}
var_pcode.register_store_in = var_map_label_vmreg_store_in[iter->get_label()];
var_pcode.register_store_out = var_map_label_vmreg_store_out[iter->get_label()];
printf("save_vm_context->\n");
var_combos_vm_code.save_vm_context();
printf(" <-save_vm_context()\n");
for (std::list<ud_t>::iterator uiter = iter->get_piece().begin();
uiter != iter->get_piece().end();
uiter++)
{
if (b_allocator == false)
for (std::vector<long*>::iterator entry_iter = var_entry_address.begin();
entry_iter != var_entry_address.end();
entry_iter++)
{
long * addr = *entry_iter;
if (uiter->insn_offset == *addr)
{
if (get_vmcode_address(var_cur_label))
*addr = create_vm_entry(var_cur_label);
else
{
printf("没有找到地址%x\n",*addr);
_asm int 3;
}
}
}
std::list<ud_t>::iterator uiter_check_end = uiter;
if (++uiter_check_end == iter->get_piece().end()) //是否是最后一条指令
{
printf("最后一条指令\n");
long next_addr = 0;
long jmp_addr = 0;
bool test_find_addr_next = var_map_label_vmreg_store_in.find(iter->get_label() + 1) !=
var_map_label_vmreg_store_in.end();
bool test_find_addr_jmp = var_map_label_vmreg_store_in.find(iter->get_jmplabel()) !=
var_map_label_vmreg_store_in.end();
if (test_find_addr_next)
next_addr = get_vmcode_address(iter->get_label() + 1);
if (test_find_addr_jmp)
jmp_addr = get_vmcode_address(iter->get_jmplabel());
long ignore_build_code_addr = 0;
ignore_build_code_addr = iter->get_jmplabel();
switch (iter->get_opcode_attribute())
{
case OPCODE_ATTRIBUTE_JCC: //虚拟机内部条件跳转
{
var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.d_push_imm(next_addr);
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_JMPINSADDR);
build(var_combos_vm_code,*uiter);
var_combos_vm_code.recover_vm_context();
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.set_pc(0x12345678);
}
break;
case OPCODE_ATTRIBUTE_JMP: //虚拟机内部跳转
{
var_combos_vm_code.recover_vm_context();
var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.set_pc(0x12345678);
}
break;
case OPCODE_ATTRIBUTE_CALL: //虚拟机内部call
{
_asm int 3;
}
break;
case OPCODE_ATTRIBUTE_EXTERNAL_JMP: //跳转到虚拟机外部
{
if (iter->get_jmplabel() != PC_NONE)
{
var_combos_vm_code.d_push_imm(ignore_build_code_addr);
}
else
{
read_vm_operand(var_combos_vm_code,uiter->operand[0]);
}
//var_combos_vm_code.recover_vm_context();
var_combos_vm_code.ret();
}
break;
case OPCODE_ATTRIBUTE_EXTERNAL_CALL:
{
int next_pcode_addr = 0;
if (get_vmcode_address(iter->get_label() + 1))
next_pcode_addr = create_vm_entry(iter->get_label() + 1);
else
next_pcode_addr = (int)uiter->pc;
var_combos_vm_code.d_push_imm(next_pcode_addr);
if (iter->get_jmplabel() != PC_NONE)
{
var_combos_vm_code.d_push_imm(ignore_build_code_addr);
}
else
{
read_vm_operand(var_combos_vm_code,uiter->operand[0]);
}
//var_combos_vm_code.recover_vm_context();
var_combos_vm_code.ret();
// printf("处理OPCODE_ATTRIBUTE_EXTERNAL_CALL\n");
}
break;
case OPCODE_ATTRIBUTE_EXTERNAL_JCC:
{
_asm int 3;
}
break;
case OPCODE_ATTRIBUTE_NORMAL:
{
build(var_combos_vm_code,*uiter);
var_combos_vm_code.recover_vm_context();
//var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.d_push_imm(next_addr);
var_combos_vm_code.set_pc(0x12345678);
}
break;
case OPCODE_ATTRIBUTE_RET:
{
build(var_combos_vm_code,*uiter);
}
break;
case OPCODE_ATTRIBUTE_EXIT:
{
build(var_combos_vm_code,*uiter);
var_combos_vm_code.d_push_imm(ignore_build_code_addr);
//var_combos_vm_code.recover_vm_context();
var_combos_vm_code.ret();
}
break;
default:
break;
}
}
else { //不是最后一条指令
if (ud_insn_mnemonic(&*uiter) != UD_Inop)
printf("build %s\n",uiter->insn_buffer);
build(var_combos_vm_code,*uiter);
}
#ifdef _DEBUG
if (b_allocator == false )
{
fprintf(var_pcode.get_log(),"\nbuild %-30s\n\n",uiter->insn_buffer);
printf("build %-30s ...done\n",uiter->insn_buffer);
}
#endif
}
if (b_allocator)
{
unsigned long vm_piece_size = (unsigned long)var_pcode.count_vmcode_end();
unsigned long t_byte_code_addr = ptr_addr_table->assign_address(vm_piece_size,var_vmcode_info);
printf("标签%d,大小:%d, addr:%08x\n", iter->get_label(), vm_piece_size, t_byte_code_addr);
if(vm_byte_code_head == 0)
vm_byte_code_head = t_byte_code_addr;
if (ptr_addr_table->get_sign())
printf("分配到的PCODE地址%08x - %08x,标志:%d\n",
t_byte_code_addr,
t_byte_code_addr + vm_piece_size,
ptr_addr_table->get_sign());
else
printf("分配到的PCODE地址%08x - %08x,标志:%d\n",
t_byte_code_addr - vm_piece_size,
t_byte_code_addr,
ptr_addr_table->get_sign());
var_map_label_vmcode_addr.insert(std::make_pair(iter->get_label(),t_byte_code_addr));
}
}
return vm_byte_code_head;
}
void BuildVMByteCode::register_mapped_init()
{
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RAX,T_RAX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RBX,T_RBX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RCX,T_RCX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RDX,T_RDX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RSP,T_RSP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RBP,T_RBP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RSI,T_RSI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_RDI,T_RDI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_EAX,T_EAX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_EBX,T_EBX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_ECX,T_ECX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_EDX,T_EDX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_ESP,T_ESP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_EBP,T_EBP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_ESI,T_ESI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_EDI,T_EDI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_AX,T_AX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_BX,T_BX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_CX,T_CX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_DX,T_DX));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_SP,T_SP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_BP,T_BP));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_SI,T_SI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_DI,T_DI));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_AL,T_AL));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_AH,T_AH));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_BL,T_BL));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_CL,T_CL));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_DL,T_DL));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_BH,T_BH));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_CH,T_CH));
mapped_vm_register.insert(make_pair<ud_type,long>(UD_R_DH,T_DH));
}
BuildVMByteCode::BuildVMByteCode(VirtualMachineManage * ptr_vmmanage,
pCodeBufferInfo ptr_info,
VMAddressTable *ptr_address_table,
std::vector<long*> & entry_address)
:newlabel_count(0)
{
var_entry_address = entry_address;
if (!ptr_info->size)
return;
register_mapped_init();
Analysis var_analysis;
var_analysis.disasm(ptr_info,var_list_code_piece);
var_analysis.printf_piece(var_list_code_piece); //输出解析到的信息
pVM = ptr_vmmanage->rand_virtual_machine();
ptr_addr_table = ptr_address_table;
full_register_store(var_list_code_piece,
var_map_label_vmreg_store_in,var_map_label_vmreg_store_out);
printf_map_register_store(var_map_label_vmreg_store_in,var_map_label_vmreg_store_out);
long vm_byte_code_head = build_vmcode(true);
build_vmcode(false);
ptr_address_table->copy();
bool t_sign = ptr_address_table->get_sign();
ptr_address_table->set_sign(true);
long head_address = ptr_address_table->assign_address(0x70);
ptr_address_table->set_sign(t_sign);
ppcode_block_info info = pVM->create_function_head(head_address,
vm_byte_code_head,
&(var_vmcode_manager_list[0]->get_pcode()),
1,//ptr_info->addr + ptr_info->size,
123456,
0x12345678); // init_vm_key = 0x12345678;
ptr_address_table->copy(head_address,info->buf,info->size);
ptr_info->addr = head_address;
}
BuildVMByteCode::BuildVMByteCode(VirtualMachineManage * ptr_vmmanage,
pCodeBufferInfo ptr_info,
VMAddressTable *ptr_address_table)
:newlabel_count(0)
{
if (!ptr_info->size)
return;
register_mapped_init();
Analysis var_analysis;
var_analysis.disasm(ptr_info,var_list_code_piece);
var_analysis.printf_piece(var_list_code_piece);
pVM = ptr_vmmanage->rand_virtual_machine();
ptr_addr_table = ptr_address_table;
full_register_store(var_list_code_piece,
var_map_label_vmreg_store_in,var_map_label_vmreg_store_out);
printf_map_register_store(var_map_label_vmreg_store_in,var_map_label_vmreg_store_out);
long vm_byte_code_head = build_vmcode(true);
build_vmcode(false);
ptr_address_table->copy();
long init_vm_key = 0x12345678;
bool t_sign = ptr_address_table->get_sign();
ptr_address_table->set_sign(true);
long head_address = ptr_address_table->assign_address(0x70);
ptr_address_table->set_sign(t_sign);
ppcode_block_info info = pVM->create_function_head(head_address,
vm_byte_code_head,
&(var_vmcode_manager_list[0]->get_pcode()),
1,//ptr_info->addr + ptr_info->size,
123456,
init_vm_key); //pcode位置有问题
ptr_address_table->copy(head_address,info->buf,info->size);
ptr_info->addr = head_address;
}
BuildVMByteCode::~BuildVMByteCode()
{
for (std::vector<VMCodeBufferManage*>::iterator iter = var_vmcode_manager_list.begin();
iter != var_vmcode_manager_list.end();
iter++)
{
delete *iter;
}
}
void BuildVMByteCode::vm_operand(
VCombosVMCode & var_combos_vm_code, ud_operand & var_operand)
{
var_combos_vm_code.impact_vmregister(false);
switch (var_operand.type)
{
case UD_OP_MEM:
{
int count = 0;
if (mapped_vm_register.find(var_operand.base) == mapped_vm_register.end())
{
//printf("没有base\n");
}
else
{
long base = mapped_vm_register[var_operand.base];
var_combos_vm_code.push(base);
count++;
}
if (mapped_vm_register.find(var_operand.index) == mapped_vm_register.end())
{
//printf("没有index\n");
}
else
{
long index = mapped_vm_register[var_operand.index];
var_combos_vm_code.push(index);
switch (var_operand.scale)
{
case 1:
var_combos_vm_code.b_push_imm(0);
break;
case 2:
var_combos_vm_code.b_push_imm(1);
break;
case 4:
var_combos_vm_code.b_push_imm(2);
break;
case 8:
var_combos_vm_code.b_push_imm(3);
break;
}
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
count++;
}
if (var_operand.lval.sdword)
{
count++;
if (var_operand.offset == 8)
{
signed char lval = var_operand.lval.sbyte;
var_combos_vm_code.b_push_imm_sx(lval);
}
else
{
long lval = var_operand.lval.sdword;
var_combos_vm_code.d_push_imm(lval);
}
}
for (int i = 1; i < count ; i++)
{
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
}
}
break;
case UD_OP_IMM:
{
switch (var_operand.size)
{
case 8:
{
signed char lval = var_operand.lval.sbyte;
var_combos_vm_code.b_push_imm(lval);
}
break;
case 16:
{
signed short lval = var_operand.lval.sword;
var_combos_vm_code.w_push_imm(lval);
}
break;
case 32:
{
int lval = var_operand.lval.sdword;
var_combos_vm_code.d_push_imm(lval);
}
break;
}
}
break;
case UD_OP_REG:
{
if (mapped_vm_register.find(var_operand.base) == mapped_vm_register.end())
{
printf("没有寄存器\n");
__asm int 3;
}
else
{
long base = mapped_vm_register[var_operand.base];
var_combos_vm_code.push(base);
}
}
break;
} // switch (var_operand.type)
var_combos_vm_code.impact_vmregister(true);
}
long BuildVMByteCode::get_vm_register(ud_type _register)
{
long result = T_INVALID;
if (mapped_vm_register.find(_register) == mapped_vm_register.end())
{
printf("无法识别的寄存器\n");
}
else
{
result = mapped_vm_register[_register];
}
return result;
}
void BuildVMByteCode::copy_exec_code_to_stack(VCombosVMCode & var_combos_vm_code,
const uint8_t * var_code_buffer,
size_t var_code_size)
{
var_combos_vm_code.b_push_imm(0xc3);
for (int i = (int)var_code_size - 1; i >= 0; i--)
{
//printf("%x ",code_addr[i]);
var_combos_vm_code.b_push_imm(var_code_buffer[i]);
}
var_combos_vm_code.b_push_imm((char)var_code_size + 1);
var_combos_vm_code.run_stack();
}
void BuildVMByteCode::build_fpu(VCombosVMCode & var_combos_vm_code,ud_t &var_ud)
{
// printf ("instruction_table size %d\n",sizeof(instruction_table));
switch (get_operand1_type(var_ud))
{
case UD_OP_IMM:
copy_exec_code_to_stack(var_combos_vm_code,ud_insn_ptr(&var_ud),ud_insn_len(&var_ud));
break;
case UD_OP_MEM:
if (get_operand1(var_ud).base == UD_NONE &&
get_operand1(var_ud).index == UD_NONE &&
get_operand1(var_ud).scale == 0) //like mnemonic [addr]
{
copy_exec_code_to_stack(var_combos_vm_code,ud_insn_ptr(&var_ud),ud_insn_len(&var_ud));
}
else{
const char * mnemonic_name = ud_lookup_mnemonic(ud_insn_mnemonic(&var_ud));
bool find = false;
//printf ("mnemonic :%s\n",mnemonic_name);
for (unsigned int index = 0; index < instruction_table_count; index++)
{
if (_stricmp(instruction_table[index],mnemonic_name) == 0)
{
read_vm_operand(var_combos_vm_code,get_operand1(var_ud));
find = true;
//read_vm_operand(var_combos_vm_code,var_ud);
AsmJit::Assembler a;
AsmJit::Operand o1;
switch (get_operand1(var_ud).size) {
case 32:
o1 = AsmJit::dword_ptr(AsmJit::nbp);
break;
case 64:
o1 = AsmJit::qword_ptr(AsmJit::nbp);
break;
default:
#ifdef _DEBUG
printf("未知的FPU指令操作数大小%d\n",get_operand1(var_ud).size);
#endif
break;
}
a._emitInstruction(index,&o1);
copy_exec_code_to_stack(var_combos_vm_code,
a.getCode(),
a.getCodeSize());
break;
}
}
if (find == false)
printf("没有找到%s指令\n",mnemonic_name);
else
write_vm_operand(var_combos_vm_code,get_operand1(var_ud));
}
break;
case UD_OP_REG:
if (mapped_vm_register.find(get_operand1(var_ud).base) == mapped_vm_register.end()) //like mnemonic st1,st2
copy_exec_code_to_stack(var_combos_vm_code,ud_insn_ptr(&var_ud),ud_insn_len(&var_ud));
break;
case UD_NONE:
copy_exec_code_to_stack(var_combos_vm_code,ud_insn_ptr(&var_ud),ud_insn_len(&var_ud));
break;
}
}
//编译前缀
void BuildVMByteCode::build_pfx(VCombosVMCode & var_combos_vm_code,ud_t &var_ud,CodePiece & var_cur_piece,bool b_allocator)
{
VMCodeBufferManage * code_buf = NULL;
if (b_allocator)
{
code_buf = create_newvm_piece();
}
else
{
code_buf = get_newvm_piece();
}
VCombosVMCode & new_combos_vm_code = code_buf->get_generator();
PCode & new_pcode = code_buf->get_pcode();
if (b_allocator)
{
new_pcode.count_vmcode_begin();
//cur_vmcode -> new_combos or next
//new_combos -> cur_vmcode
RegisterStore t_store;
new_combos_vm_code.upset_register_array(t_store);
new_combos_vm_code.set_vmregister_store_in(t_store);
new_combos_vm_code.set_vmregister_store_out(t_store);
new_pcode.set_key(0x12345678);
}
else
{
new_combos_vm_code.set_vmregister_store_in(
var_map_label_vmreg_store_out[var_cur_piece.get_label()]);
new_combos_vm_code.set_vmregister_store_out(
var_map_label_vmreg_store_in[var_cur_piece.get_label()]);
#ifdef _DEBUG
char file_name[256];
memset(&file_name,0,256);
sprintf_s(file_name, 256,
"virtual_machine_assembly/NewLabel%d,%08x\n",
get_newvm_cur_label(),var_map_newlabel_vmcode_addr[get_newvm_cur_label()]);
new_pcode.out_log_file(file_name);
#endif
}
new_combos_vm_code.save_vm_context();
build(new_combos_vm_code,var_ud);
if (var_ud.pfx_rep)
{
if (b_allocator)
{
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_push_imm(0);
} else {
long jmp_addr = var_map_label_vmcode_addr[var_cur_piece.get_jmplabel()];
long next_addr = var_map_newlabel_vmcode_addr[get_newvm_cur_label()];
//var_combos_vm_code.d_push_imm(next_addr);
//var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.d_push_imm(next_addr);
}
//var_combos_vm_code.ptr_pcode->out_info("cmp ecx,0 \njz store\n");
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push_vsp();
var_combos_vm_code.push(T_ECX); //cmp ecx,0
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_cmp();
var_combos_vm_code.get_zf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem(); //读取地址
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
//用这个的话计算到最后ecx会少一个
/*
var_combos_vm_code.d_push_imm(1) ;
var_combos_vm_code.push(T_ECX); //sub ecx,1
var_combos_vm_code.d_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_ECX);
*/
new_combos_vm_code.d_push_imm(1);
new_combos_vm_code.push(T_ECX); //sub ecx,1
new_combos_vm_code.d_sub();
new_combos_vm_code.pop(T_INVALID);
new_combos_vm_code.pop(T_ECX);
//var_combos_vm_code.set_pc(0x12345678);
new_combos_vm_code.recover_vm_context();
if (b_allocator)
{
new_combos_vm_code.d_push_imm(0);
//new_combos_vm_code.d_push_imm(0);
}
else
{
int next_addr = get_vmcode_address(var_cur_piece.get_label());//var_map_label_vmcode_addr[var_cur_piece.get_label()];
new_combos_vm_code.d_push_imm(next_addr);
}
new_combos_vm_code.set_pc(0x12345678);
}
else if (var_ud.pfx_repe)
{
//while (ecx != 0)
//{
// oldcode();
//}
if (b_allocator)
{
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_push_imm(0);
} else {
long jmp_addr = var_map_label_vmcode_addr[var_cur_piece.get_jmplabel()];
long next_addr = var_map_newlabel_vmcode_addr[get_newvm_cur_label()];
var_combos_vm_code.d_push_imm(next_addr);
var_combos_vm_code.d_push_imm(jmp_addr);
//var_combos_vm_code.d_push_imm(jmp_addr);
//var_combos_vm_code.d_push_imm(next_addr);
}
//var_combos_vm_code.ptr_pcode->out_info("cmp ecx,0 \njz store\n");
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push_vsp();
var_combos_vm_code.push(T_ECX); //cmp ecx,0
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_cmp();
var_combos_vm_code.get_zf();
var_combos_vm_code.pushf();
var_combos_vm_code.impact_vmregister(true);
var_combos_vm_code.get_zf();
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem(); //读取地址
//var_combos_vm_code.int3();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
//用这个的话计算到最后ecx会少一个
/*
var_combos_vm_code.d_push_imm(1) ;
var_combos_vm_code.push(T_ECX); //sub ecx,1
var_combos_vm_code.d_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_ECX);
*/
new_combos_vm_code.d_push_imm(1);
new_combos_vm_code.push(T_ECX); //sub ecx,1
new_combos_vm_code.d_sub();
new_combos_vm_code.pop(T_INVALID);
new_combos_vm_code.pop(T_ECX);
//var_combos_vm_code.set_pc(0x12345678);
new_combos_vm_code.recover_vm_context();
if (b_allocator)
{
new_combos_vm_code.d_push_imm(0);
//new_combos_vm_code.d_push_imm(0);
}
else
{
int next_addr = get_vmcode_address(var_cur_piece.get_label());//var_map_label_vmcode_addr[var_cur_piece.get_label()];
new_combos_vm_code.d_push_imm(next_addr);
}
new_combos_vm_code.set_pc(0x12345678);
}
else if (var_ud.pfx_repne)
{
//while (ecx != 0)
//{
// oldcode();
//}
if (b_allocator)
{
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_push_imm(0);
} else {
long jmp_addr = var_map_label_vmcode_addr[var_cur_piece.get_jmplabel()];
long next_addr = var_map_newlabel_vmcode_addr[get_newvm_cur_label()];
//var_combos_vm_code.d_push_imm(next_addr);
//var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.d_push_imm(jmp_addr);
var_combos_vm_code.d_push_imm(next_addr);
}
//var_combos_vm_code.ptr_pcode->out_info("cmp ecx,0 \njz store\n");
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push_vsp();
var_combos_vm_code.push(T_ECX); //cmp ecx,0
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_cmp();
var_combos_vm_code.get_zf();
var_combos_vm_code.pushf();
var_combos_vm_code.impact_vmregister(true);
var_combos_vm_code.get_zf();
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem(); //读取地址
//var_combos_vm_code.int3();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
//用这个的话计算到最后ecx会少一个
/*
var_combos_vm_code.d_push_imm(1) ;
var_combos_vm_code.push(T_ECX); //sub ecx,1
var_combos_vm_code.d_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_ECX);
*/
new_combos_vm_code.d_push_imm(1);
new_combos_vm_code.push(T_ECX); //sub ecx,1
new_combos_vm_code.d_sub();
new_combos_vm_code.pop(T_INVALID);
new_combos_vm_code.pop(T_ECX);
//var_combos_vm_code.set_pc(0x12345678);
new_combos_vm_code.recover_vm_context();
if (b_allocator)
{
new_combos_vm_code.d_push_imm(0);
//new_combos_vm_code.d_push_imm(0);
}
else
{
int next_addr = get_vmcode_address(var_cur_piece.get_label());//var_map_label_vmcode_addr[var_cur_piece.get_label()];
new_combos_vm_code.d_push_imm(next_addr);
}
new_combos_vm_code.set_pc(0x12345678);
//var_combos_vm_code.push()
//var_combos_vm_code
}
if (b_allocator)
{
int new_pcode_size = (int)new_pcode.count_vmcode_end();
VTable table;
table.v = &new_combos_vm_code;
long new_pcode_addr = ptr_addr_table->assign_address(new_pcode_size,table);
var_map_newlabel_vmcode_addr.insert(std::make_pair(get_newvm_cur_label(),new_pcode_addr));
//printf("NewLabel分配到PCODE地址:%x - %x\n",new_pcode_addr - new_pcode_size,new_pcode_addr);
if (ptr_addr_table->get_sign())
printf("分配到的NEWPCODE地址%08x - %08x,标志:%d\n",
new_pcode_addr,
new_pcode_addr + new_pcode_size,
ptr_addr_table->get_sign());
else
printf("分配到的NEWPCODE地址%08x - %08x,标志:%d\n",
new_pcode_addr - new_pcode_size,
new_pcode_addr,
ptr_addr_table->get_sign());
}
else
{
//ptr_addr_table->copy();
//int a = new_combos_vm_code.get_code_size();
//printf("代码大小%d\n",a);
}
}
VMCodeBufferManage * BuildVMByteCode::create_newvm_piece()
{
var_vmcode_manager_list.push_back(new VMCodeBufferManage(pVM));
var_map_newlabel_vmbuffer_manage.insert(
std::make_pair(newlabel_count,var_vmcode_manager_list.back()));
newlabel_count++;
return var_vmcode_manager_list.back();
}
VMCodeBufferManage * BuildVMByteCode::get_newvm_piece()
{
VMCodeBufferManage * result = NULL;
if (var_map_newlabel_vmbuffer_manage.find(newlabel_count) !=
var_map_newlabel_vmbuffer_manage.end())
{
result = var_map_newlabel_vmbuffer_manage[newlabel_count];
}
newlabel_count++;
return result;
}
long BuildVMByteCode::get_newvm_cur_label()
{
return newlabel_count;
}
void BuildVMByteCode::write_vm_operand(VCombosVMCode & var_combos_vm_code,ud_operand & var_operand)
{
switch (var_operand.type)
{
case UD_OP_MEM:
vm_operand(var_combos_vm_code,var_operand);
write_mem(var_operand);
break;
case UD_OP_REG:
if (var_operand.base == UD_R_ESP)
{
var_combos_vm_code.pop_vsp();
}
else
var_combos_vm_code.pop(get_vm_register(var_operand.base));
break;
}
}
void BuildVMByteCode::read_vm_operand(VCombosVMCode & var_combos_vm_code,ud_operand & var_operand)
{
vm_operand(var_combos_vm_code,var_operand);
read_mem(var_operand);
}
void BuildVMByteCode::build(VCombosVMCode & var_combos_vm_code,ud_t &ud)
{
if( get_operand1(ud).base == UD_R_ESP ||
get_operand1(ud).index == UD_R_ESP ||
get_operand2(ud).base == UD_R_ESP ||
get_operand2(ud).index == UD_R_ESP )
{
var_combos_vm_code.push_vsp();
var_combos_vm_code.pop(T_ESP);
}
switch(ud_insn_mnemonic(&ud))
{
case UD_Inop:
break;
case UD_Imov:
{
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
read_vm_operand(var_combos_vm_code,get_operand2(ud));
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Ixchg:
{
read_vm_operand(var_combos_vm_code,get_operand2(ud));
read_vm_operand(var_combos_vm_code,get_operand1(ud));
write_vm_operand(var_combos_vm_code,get_operand2(ud));
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Ilea:
{/*{{{*/
vm_operand(var_combos_vm_code,get_operand2(ud));
//var_combos_vm_code.pop(mapped_vm_register[get_operand1(var_ud).base]);
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}/*}}}*/
break;
case UD_Ipush:
{/*{{{*/
ud_operand o;
o.size = 32; //默认用32位
set_imm_operand_size(get_operand1(ud),o);
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
}/*}}}*/
break;
case UD_Icmp:
{/*{{{*/
/*操作
temp SRC1 - SignExtend(SRC2);
ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)
影响的标志
CF、OF、SF、ZF、AF 及 PF 标志根据结果设置。
*/ set_imm_operand_size(get_operand2(ud),get_operand1(ud));
read_vm_operand(var_combos_vm_code,get_operand2(ud));
read_vm_operand(var_combos_vm_code,get_operand1(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_sub();
var_combos_vm_code.popf();
var_combos_vm_code.pop(T_INVALID | T_E32X | T_16X | T_8L);
break;
case 16:
var_combos_vm_code.w_sub();
var_combos_vm_code.popf();
var_combos_vm_code.pop(T_INVALID | T_E32X | T_16X);
break;
case 32:
var_combos_vm_code.d_sub();
var_combos_vm_code.popf();
var_combos_vm_code.pop(T_INVALID | T_E32X);
break;
}
}/*}}}*/
break;
case UD_Iret:
{
var_combos_vm_code.ret();
}
break;
case UD_Iadd:
{
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_add();
break;
case 16:
var_combos_vm_code.w_add();
break;
case 32:
var_combos_vm_code.d_add();
break;
}
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Isub:
{/*{{{*/
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_sub();
break;
case 16:
var_combos_vm_code.w_sub();
break;
case 32:
var_combos_vm_code.d_sub();
break;
}
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
/*
switch(get_operand1_type(var_ud))
{
case UD_OP_MEM:
vm_operand(var_combos_vm_code,get_operand1(var_ud));
write_mem(get_operand1(var_ud));
break;
case UD_OP_REG:
var_combos_vm_code.pop(get_vm_register(get_operand1(var_ud).base));
break;
}*/
}/*}}}*/
break;
case UD_Inot:
{/*{{{*/
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_not();
break;
case 16:
var_combos_vm_code.w_not();
break;
case 32:
var_combos_vm_code.d_not();
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
/*
switch (get_operand1_type(var_ud))
{
case UD_OP_MEM:
vm_operand(var_combos_vm_code,get_operand1(var_ud));
write_mem(get_operand1(var_ud));
break;
case UD_OP_REG:
var_combos_vm_code.pop(get_vm_register(get_operand1(var_ud)));
break;
} */
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}/*}}}*/
break;
case UD_Iand:
{/*{{{*/
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_and();
break;
case 16:
var_combos_vm_code.w_and();
break;
case 32:
var_combos_vm_code.d_and();
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}/*}}}*/
break;
case UD_Ixor:
{/*{{{*/
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_xor();
break;
case 16:
var_combos_vm_code.w_xor();
break;
case 32:
var_combos_vm_code.d_xor();
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}/*}}}*/
break;
case UD_Ior:
{/*{{{*/
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_or();
break;
case 16:
var_combos_vm_code.w_or();
break;
case 32:
var_combos_vm_code.d_or();
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}/*}}}*/
break;
case UD_Itest:
{/*{{{*/
set_imm_operand_size(get_operand2(ud),get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code,get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_and();
break;
case 16:
var_combos_vm_code.w_and();
break;
case 32:
var_combos_vm_code.d_and();
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.pop(T_INVALID|T_E32X|T_16X|T_8H);
break;
case 16:
var_combos_vm_code.pop(T_INVALID|T_E32X|T_16X);
break;
case 32:
var_combos_vm_code.pop(T_INVALID|T_E32X);
break;
}
}/*}}}*/
break;
case UD_Ipop:
{/*{{{*/
//vm_operand(var_combos_vm_code,get_operand1(var_ud));
ud_operand o;
o.size = 32;
set_imm_operand_size(get_operand1(ud),o);
write_vm_operand(var_combos_vm_code,get_operand1(ud));
//write_mem(get_operand1(var_ud));
//if (get_operand1_type(var_ud) )
//var_combos_vm_code.pop
}/*}}}*/
break;
case UD_Iinc:
{/*{{{*/
vm_operand(var_combos_vm_code,get_operand1(ud));
read_mem(get_operand1(ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_push_imm(1);
var_combos_vm_code.b_add();
break;
case 16:
var_combos_vm_code.w_push_imm(1);
var_combos_vm_code.w_add();
break;
case 32:
var_combos_vm_code.d_push_imm(1);
var_combos_vm_code.d_add();
break;
}
var_combos_vm_code.d_push_imm(~((1 << 0) | (1 << 10)));
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pushf();
var_combos_vm_code.d_push_imm((1 << 0) | (1 << 10));
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
/*switch (get_operand1_type(var_ud))
{
case UD_OP_REG:
var_combos_vm_code.pop(get_vm_register(get_operand1(var_ud).base));
break;
case UD_OP_MEM:
vm_operand(var_combos_vm_code,get_operand1(var_ud));
write_mem(get_operand1(var_ud));
break;
}*/
}/*}}}*/
break;
case UD_Idec:
{/*{{{*/
//read_mem(get_operand1(var_ud));
switch (get_operand1(ud).size)
{
case 8:
var_combos_vm_code.b_push_imm(1);
read_vm_operand(var_combos_vm_code,get_operand1(ud));
var_combos_vm_code.b_sub();
break;
case 16:
var_combos_vm_code.w_push_imm(1);
read_vm_operand(var_combos_vm_code,get_operand1(ud));
var_combos_vm_code.w_sub();
break;
case 32:
var_combos_vm_code.b_push_imm_zx(1);
read_vm_operand(var_combos_vm_code,get_operand1(ud));
var_combos_vm_code.d_sub();
break;
}
var_combos_vm_code.d_push_imm(~((1 << 0) | (1 << 10)));
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pushf();
var_combos_vm_code.d_push_imm((1 << 0) | (1 << 10));
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
/*
switch (get_operand1_type(var_ud))
{
case UD_OP_REG:
var_combos_vm_code.pop(get_vm_register(get_operand1(var_ud).base));
break;
case UD_OP_MEM:
vm_operand(var_combos_vm_code,get_operand1(var_ud));
write_mem(get_operand1(var_ud));
break;
} */
}/*}}}*/
break;
case UD_Ishl:
{
vm_operand(var_combos_vm_code, get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code, get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size) {
case 8:
var_combos_vm_code.b_shl();
break;
case 16:
var_combos_vm_code.w_shl();
break;
case 32:
var_combos_vm_code.d_shl();
break;
default:
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Ishr:
{
vm_operand(var_combos_vm_code, get_operand1(ud));
read_mem(get_operand1(ud));
vm_operand(var_combos_vm_code, get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size) {
case 8:
var_combos_vm_code.b_shr();
break;
case 16:
var_combos_vm_code.w_shr();
break;
case 32:
var_combos_vm_code.d_shr();
break;
default:
break;
}
//var_combos_vm_code.popf();
var_combos_vm_code.popf();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Isar:
{
/*
* sar 10101110,2
* 最高位 = 1
* 11111111 sub 0,最高位 -> diff
* 11111000 shl diff << 右移位数 + 1
* 11111001 add diff,最高位
* 00000111 neg diff
* 11100000 shl diff,目标操作数位数(7) - 右移位数 + 1
* shr 目标操作数,右移位数
* add 目标操作数,diff
*/
var_combos_vm_code.impact_vmregister(false);
vm_operand(var_combos_vm_code, get_operand1(ud));
read_mem(get_operand1(ud));
int dest_reg = var_combos_vm_code.get_tmp_vmregister();
int highest_bit = var_combos_vm_code.get_tmp_vmregister();
int count_reg = var_combos_vm_code.get_tmp_vmregister();
int tmp_cf_reg = var_combos_vm_code.get_tmp_vmregister();
vm_operand(var_combos_vm_code, get_operand2(ud));
read_mem(get_operand2(ud));
switch (get_operand1(ud).size) {
case 8:
var_combos_vm_code.pop(count_reg|T_E32X|T_16X|T_8H);//save count
//and o1,10000000b
var_combos_vm_code.push_vsp();
var_combos_vm_code.b_read_mem(); //copy dest
var_combos_vm_code.pop(dest_reg|T_E32X|T_16X|T_8H); //save dest
var_combos_vm_code.b_push_imm(1<<7);
var_combos_vm_code.b_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.b_push_imm(7);
var_combos_vm_code.b_shr();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push_vsp();
var_combos_vm_code.b_read_mem();
var_combos_vm_code.pop(highest_bit|T_E32X|T_16X|T_8H);
//neg diff
var_combos_vm_code.b_neg();
var_combos_vm_code.pop(T_INVALID);
//add count,1
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(1);
var_combos_vm_code.b_add();
var_combos_vm_code.pop(T_INVALID);
//shl diff,count+1
var_combos_vm_code.b_shl();
var_combos_vm_code.pop(T_INVALID);
//add diff,最高位
var_combos_vm_code.push(highest_bit|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_add();
var_combos_vm_code.pop(T_INVALID);
//neg diff
var_combos_vm_code.b_neg();
var_combos_vm_code.pop(T_INVALID);
//shl diff,7 - count_reg
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(8-1);
var_combos_vm_code.b_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.b_shl();
var_combos_vm_code.pop(T_INVALID);
//shr dest_reg,count_reg
var_combos_vm_code.push(dest_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_shr();
//var_combos_vm_code.pop(T_INVALID);
//get_cf();
//var_combos_vm_code.d_push_imm(1);
var_combos_vm_code.b_push_imm_zx(1);
var_combos_vm_code.d_and(); //获取shr的cf标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(tmp_cf_reg);
//or dest_reg,diff
var_combos_vm_code.b_or();
var_combos_vm_code.push(tmp_cf_reg);
var_combos_vm_code.d_or(); //合并shr的cf和or的其他标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.popf(); //设置标志位
write_vm_operand(var_combos_vm_code,get_operand1(ud));
break;
case 16:
var_combos_vm_code.pop(count_reg|T_E32X|T_16X|T_8H);//save count
//and o1,10000000b
var_combos_vm_code.push_vsp();
var_combos_vm_code.w_read_mem(); //copy dest
var_combos_vm_code.pop(dest_reg|T_E32X|T_16X); //save dest
var_combos_vm_code.w_push_imm(1<<15);
var_combos_vm_code.w_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.b_push_imm(15);
var_combos_vm_code.w_shr();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push_vsp();
var_combos_vm_code.w_read_mem();
var_combos_vm_code.pop(highest_bit|T_E32X|T_16X);
//neg diff
var_combos_vm_code.w_neg();
var_combos_vm_code.pop(T_INVALID);
//add count,1
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(1);
var_combos_vm_code.b_add();
var_combos_vm_code.pop(T_INVALID);
//shl diff,count+1
var_combos_vm_code.w_shl();
var_combos_vm_code.pop(T_INVALID);
//add diff,最高位
var_combos_vm_code.push(highest_bit|T_E32X|T_16X);
var_combos_vm_code.w_add();
var_combos_vm_code.pop(T_INVALID);
//neg diff
var_combos_vm_code.w_neg();
var_combos_vm_code.pop(T_INVALID);
//shl diff,7 - count_reg
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(16-1);
var_combos_vm_code.b_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.w_shl();
var_combos_vm_code.pop(T_INVALID);
//shr dest_reg,count_reg
var_combos_vm_code.push(dest_reg|T_E32X|T_16X);
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.w_shr();
//var_combos_vm_code.pop(T_INVALID);
//get_cf();
//var_combos_vm_code.d_push_imm(1);
var_combos_vm_code.b_push_imm_zx(1);
var_combos_vm_code.d_and(); //获取shr的cf标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(tmp_cf_reg);
//or dest_reg,diff
var_combos_vm_code.w_or();
var_combos_vm_code.push(tmp_cf_reg);
var_combos_vm_code.d_or(); //合并shr的cf和or的其他标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.popf(); //设置标志位
write_vm_operand(var_combos_vm_code,get_operand1(ud));
break;
case 32:
var_combos_vm_code.pop(count_reg|T_E32X|T_16X|T_8H);//save count
//and o1,10000000b
var_combos_vm_code.push_vsp();
var_combos_vm_code.d_read_mem(); //copy dest
var_combos_vm_code.pop(dest_reg|T_E32X); //save dest
var_combos_vm_code.d_push_imm(1<<31);
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
//shr o1,31
var_combos_vm_code.b_push_imm(31);
var_combos_vm_code.d_shr();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push_vsp();
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(highest_bit|T_E32X);
//neg diff
var_combos_vm_code.d_neg();
var_combos_vm_code.pop(T_INVALID);
//add count,1
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(1);
var_combos_vm_code.b_add();
var_combos_vm_code.pop(T_INVALID);
//shl diff,count+1
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
//add diff,最高位
var_combos_vm_code.push(highest_bit|T_E32X);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
//neg diff
var_combos_vm_code.d_neg();
var_combos_vm_code.pop(T_INVALID);
//shl diff,7 - count_reg
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.b_push_imm(32-1);
var_combos_vm_code.b_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
//shr dest_reg,count_reg
var_combos_vm_code.push(dest_reg|T_E32X);
var_combos_vm_code.push(count_reg|T_E32X|T_16X|T_8H);
var_combos_vm_code.d_shr();
//var_combos_vm_code.pop(T_INVALID);
//get_cf();
//var_combos_vm_code.d_push_imm(1);
var_combos_vm_code.b_push_imm_zx(1);
var_combos_vm_code.d_and(); //获取shr的cf标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(tmp_cf_reg);
//or dest_reg,diff
var_combos_vm_code.d_or();
var_combos_vm_code.push(tmp_cf_reg);
var_combos_vm_code.d_or(); //合并shr的cf和or的其他标志位
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.popf(); //设置标志位
write_vm_operand(var_combos_vm_code,get_operand1(ud));
break;
default:
break;
}
var_combos_vm_code.unlock_tmp_vmregister(count_reg);
var_combos_vm_code.unlock_tmp_vmregister(dest_reg);
var_combos_vm_code.unlock_tmp_vmregister(highest_bit);
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Iscasb: //edi - ~df + df
{
/*
*
* df = 1
* neg df ;0xffffffff
* add edi,df
* not df ;0
* sub edi,df
*
* df = 0
* neg df ;0
* add edi,df
* not df ;0xffffffff
* sub edi,df
*
*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_EDI);
//var_combos_vm_code.pushf();
var_combos_vm_code.b_read_mem();
var_combos_vm_code.push(T_AL);
var_combos_vm_code.b_cmp();
var_combos_vm_code.popf();
var_combos_vm_code.get_string_ins_diff();
var_combos_vm_code.b_push_imm(0);
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
/*
//sub 0,df
int tmp_vmregister_df = var_combos_vm_code.get_tmp_vmregister();
var_combos_vm_code.pushf(); //t_edi
var_combos_vm_code.get_df();
var_combos_vm_code.d_push_imm(0);
var_combos_vm_code.d_sub();
//var_combos_vm_code.int3();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push_vsp();
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(tmp_vmregister_df | T_E32X);
//add edi,df
int tmp_vmregister_edi = var_combos_vm_code.get_tmp_vmregister();
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(tmp_vmregister_edi | T_E32X);
//not df
//var_combos_vm_code.pushf();
var_combos_vm_code.push(tmp_vmregister_df | T_E32X);
//var_combos_vm_code.get_df();
var_combos_vm_code.d_not();
var_combos_vm_code.pop(T_INVALID);
//sub edi,df
var_combos_vm_code.push(tmp_vmregister_edi | T_E32X);
var_combos_vm_code.d_sub();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
//var_combos_vm_code.int3(); //
var_combos_vm_code.unlock_tmp_vmregister(tmp_vmregister_edi);
var_combos_vm_code.unlock_tmp_vmregister(tmp_vmregister_df);
//var_combos_vm_code.int3(); //sub edi,~df
*/
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Iscasw: //edi - ~df + df
{
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_EDI);
//var_combos_vm_code.pushf();
var_combos_vm_code.w_read_mem();
var_combos_vm_code.push(T_AX);
var_combos_vm_code.w_cmp();
var_combos_vm_code.popf();
var_combos_vm_code.get_string_ins_diff();
var_combos_vm_code.b_push_imm(1);
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
//var_combos_vm_code.int3(); //sub edi,~df
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Iscasd: //edi - ~df + df
{
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_EDI);
//var_combos_vm_code.pushf();
var_combos_vm_code.d_read_mem();
var_combos_vm_code.push(T_EAX);
var_combos_vm_code.d_cmp();
var_combos_vm_code.popf();
var_combos_vm_code.get_string_ins_diff();
var_combos_vm_code.b_push_imm(2);
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Imovsb:
{
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_ESI);
var_combos_vm_code.b_read_mem();
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.b_write_mem();
var_combos_vm_code.get_string_ins_diff();
var_combos_vm_code.push_vsp();
var_combos_vm_code.d_read_mem();
//var_combos_vm_code.b_push_imm(0);
//var_combos_vm_code.d_shl();
//var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.push(T_ESI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_ESI);
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Imovsd:
{
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_ESI);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_write_mem();
var_combos_vm_code.get_string_ins_diff();
var_combos_vm_code.b_push_imm(2);
var_combos_vm_code.d_shl();
var_combos_vm_code.pop(T_INVALID);
//var_combos_vm_code.int3();
var_combos_vm_code.push_vsp();
var_combos_vm_code.d_read_mem();
var_combos_vm_code.push(T_ESI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_ESI);
var_combos_vm_code.push(T_EDI);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_EDI);
var_combos_vm_code.impact_vmregister(true);
}
break;
case UD_Ijnz: //ZF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.d_push_imm(0x40);
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.b_push_imm(4);
var_combos_vm_code.d_shr();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijz: //ZF != 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.d_push_imm(0x40);
var_combos_vm_code.d_and();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.b_push_imm(4);
var_combos_vm_code.d_shr();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ija: //CF = 0 && ZF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_cf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_zf();
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijae: // CF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_cf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijb://CF = 1
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
//var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_cf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijbe: //CF = 1 || ZF = 1
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
//var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_cf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_zf();
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijcxz: //CX = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.w_push_imm(0);
var_combos_vm_code.push(T_CX);
var_combos_vm_code.w_cmp();
var_combos_vm_code.get_zf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijg: //ZF = 0 && SF = OF
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_zf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.d_xor();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijge: //SF = OF
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.d_xor();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijl: // OF != SF
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.d_xor();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijle: // ZF = 1 || SF != OF
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_zf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.d_xor();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_or();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijno: // OF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijnp: // PF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_pf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijns: // SF = 0
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijo: // OF = 1
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
//var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_of();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijp: // PF = 1
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_pf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijs: // SF = 1
{/*{{{*/
var_combos_vm_code.impact_vmregister(false);
var_combos_vm_code.push(T_JMPINSADDR);
var_combos_vm_code.push(T_NEXTINSADDR);
var_combos_vm_code.push_vsp();
var_combos_vm_code.pushf();
var_combos_vm_code.get_sf();
var_combos_vm_code.d_add();
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.d_read_mem();
var_combos_vm_code.pop(T_NEXTINSADDR);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.pop(T_INVALID);
var_combos_vm_code.impact_vmregister(true);
}/*}}}*/
break;
case UD_Ijmp:
{
}
break;
case UD_Imovzx:
{
for (int i = get_operand2(ud).size; i < get_operand1(ud).size;i+=8)
{
var_combos_vm_code.b_push_imm(0);
}
read_vm_operand(var_combos_vm_code,get_operand2(ud));
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_If2xm1:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifabs:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifadd:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifaddp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifbld:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifbstp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifchs:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifclex:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovb:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmove:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovbe:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovu:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovnb:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovne:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovnbe:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcmovnu:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifucomi:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcom:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcom2:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcomp3:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcomi:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifucomip:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcomip:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcomp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcomp5:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcompp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifcos:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifdecstp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifdiv:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifdivp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifdivr:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifdivrp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifemms:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Iffree:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Iffreep:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ificom:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ificomp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifild:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifincstp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifninit:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifiadd:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifidivr:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifidiv:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifisub:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifisubr:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifist:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifistp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifisttp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifld:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifld1:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldl2t:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldl2e:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldpi:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldlg2:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldln2:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldz:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldcw:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifldenv:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifmul:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifmulp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifimul:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifnop:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifpatan:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifprem:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifprem1:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifptan:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifrndint:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifrstor:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifnsave:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifscale:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsin:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsincos:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsqrt:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifstp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifstp1:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifstp8:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifstp9:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifst:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifnstcw:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifnstenv:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifnstsw:
{
var_combos_vm_code.fstsw();
write_vm_operand(var_combos_vm_code,get_operand1(ud));
}
break;
case UD_Ifsub:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsubp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsubr:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifsubrp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Iftst:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifucom:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifucomp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifucompp:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxam:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxch:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxch4:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxch7:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxrstor:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxsave:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifxtract:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifyl2x:
build_fpu(var_combos_vm_code,ud);
break;
case UD_Ifyl2xp1:
build_fpu(var_combos_vm_code,ud);
break;
default:
printf("没有处理%s\n",ud_lookup_mnemonic(ud.mnemonic));
break;
}
}
void BuildVMByteCode::full_vmregister_store(std::vector<CodePiece> & var_list_code_piece,
std::map<int,RegisterStore> & var_map_label_vmreg_store_in,
std::map<int,RegisterStore> & var_map_label_vmreg_store_out)
{
size_t var_list_size = var_list_code_piece.size();
for (size_t i = 0; i < var_list_size; i++)
{
set_vmregister_store(var_list_code_piece,
var_map_label_vmreg_store_in,
var_map_label_vmreg_store_out,
(int)i);
}
}
void BuildVMByteCode::set_vmregister_store(std::vector<CodePiece> & var_list_code_piece,
std::map<int,RegisterStore> & var_map_label_vmreg_store_in,
std::map<int,RegisterStore> & var_map_label_vmreg_store_out,
int var_cur_label)
{/*{{{*/
std::vector<CodePiece>::iterator iter = var_list_code_piece.begin();
bool find_out = false;
bool find_in = false;
std::vector<int> var_label_in;
std::vector<int> var_label_out;
RegisterStore var_store_in;
RegisterStore var_store_out;
for (iter;iter != var_list_code_piece.end();iter++)
{
//查找是否有指令跳转到这里
if (iter->get_jmplabel() == var_cur_label)
{
if (var_map_label_vmreg_store_out.find(iter->get_label()) != var_map_label_vmreg_store_out.end())
{
if (var_store_in.get_key() != var_map_label_vmreg_store_out[iter->get_label()].get_key())
{
_asm int 3;
}
var_store_in = var_map_label_vmreg_store_out[iter->get_label()];
var_map_label_vmreg_store_in.insert(std::make_pair(var_cur_label,
var_map_label_vmreg_store_out[iter->get_label()]));
find_in = true;
}
else
{
//if (iter->get_jmplabel_type() == TYPE_LABEL)
var_label_out.push_back(iter->get_label());
}
}
//查找上条指令
if (iter->get_label() + 1 == var_cur_label && iter->get_opcode_attribute() == OPCODE_ATTRIBUTE_NORMAL)//iter->get_jmplabel_type() == TYPE_LABEL)
{
if (var_store_in.get_key() != var_map_label_vmreg_store_out[iter->get_label()].get_key())
{
_asm int 3;
}
if (var_map_label_vmreg_store_out.find(iter->get_label()) != var_map_label_vmreg_store_out.end())
{
var_store_in = var_map_label_vmreg_store_out[iter->get_label()];
var_map_label_vmreg_store_in.insert(std::make_pair(var_cur_label,
var_map_label_vmreg_store_out[iter->get_label()]));
find_in = true;
}
else
{
//if (iter->get_jmplabel_type() == TYPE_LABEL)
var_label_out.push_back(iter->get_label());
}
}
if (iter->get_label() == var_cur_label)
{
if (var_store_out.get_key() != var_map_label_vmreg_store_in[iter->get_label()].get_key())
{
_asm int 3;
}
if (var_map_label_vmreg_store_in.find(iter->get_jmplabel()) != var_map_label_vmreg_store_in.end())
{
var_store_out = var_map_label_vmreg_store_in[iter->get_jmplabel()];
var_map_label_vmreg_store_out.insert(std::make_pair(var_cur_label,
var_store_out));
find_out = true;
}
else{
//if (iter->get_jmplabel_type() == TYPE_LABEL)
if (iter->get_opcode_attribute() == OPCODE_ATTRIBUTE_NORMAL)
var_label_in.push_back(iter->get_jmplabel());
}
}
//
if (iter->get_label() - 1 == var_cur_label)
{
if (var_store_out.get_key() != var_map_label_vmreg_store_in[iter->get_label()].get_key())
{
_asm int 3;
}
if (var_map_label_vmreg_store_in.find(iter->get_label()) != var_map_label_vmreg_store_in.end())
{
var_store_out = var_map_label_vmreg_store_in[iter->get_label()];
var_map_label_vmreg_store_out.insert(std::make_pair(var_cur_label,
var_map_label_vmreg_store_in[iter->get_label()]));
find_out = true;
}
else
{
//pe() == TYPE_LABEL)
var_label_in.push_back(iter->get_label());
}
}
}
if (find_out == false)
{
VCombosVMCode var_t;
var_t.upset_register_array(var_store_out);
var_map_label_vmreg_store_in.insert(std::make_pair(var_cur_label,var_store_out));
}
for (std::vector<int>::iterator iter = var_label_out.begin();
iter != var_label_out.end();iter++)
{
var_map_label_vmreg_store_out.insert(std::make_pair(*iter,var_store_out));
}
if (find_in == false)
{
VCombosVMCode var_t;
//RegisterStore var_store;
var_t.upset_register_array(var_store_in);
var_map_label_vmreg_store_out.insert(std::make_pair(var_cur_label,var_store_in));
}
for (std::vector<int>::iterator iter = var_label_in.begin();
iter != var_label_in.end();iter++)
{
var_map_label_vmreg_store_in.insert(std::make_pair(*iter,var_store_in));
}
}/*}}}*/
void BuildVMByteCode::set_lastpiece_register_store(
std::vector<CodePiece> &var_list_code_piece,
std::map<int,RegisterStore> & var_map_label_vmreg_store)
{
VCombosVMCode var_t;
RegisterStore var_store;
var_t.upset_register_array(var_store);
std::vector<CodePiece>::iterator iter = var_list_code_piece.begin();
for (iter;iter != var_list_code_piece.end();iter++)
{
bool set_exit = false;
if (iter->get_opcode_attribute() == OPCODE_ATTRIBUTE_RET ||
iter->get_opcode_attribute() == OPCODE_ATTRIBUTE_EXIT)
{
printf("LastPieceLabel:%d\n",iter->get_label());
var_map_label_vmreg_store.insert( std::make_pair(
iter->get_label(),
var_store));
}
}
}
void BuildVMByteCode::full_register_store(std::vector<CodePiece> &var_list_code_piece,
std::map<int,RegisterStore> & var_map_label_vmreg_store_in,
std::map<int,RegisterStore> & var_map_label_vmreg_store_out
)
{
VCombosVMCode combs;
RegisterStore regstore;
combs.upset_register_array(regstore);//初始化所有的寄存器,并进行乱序排列
for (int i = 0; i < (int)var_list_code_piece.size(); i++)
{
var_map_label_vmreg_store_in.insert(std::make_pair(i,regstore));
var_map_label_vmreg_store_out.insert(std::make_pair(i,regstore));
}
}
void BuildVMByteCode::set_register_store(std::vector<CodePiece> &var_list_code_piece,
std::map<int,RegisterStore> & var_map_label_vmreg_store_in,
std::map<int,RegisterStore> & var_map_label_vmreg_store_out,
std::map<int,RegisterStore> & var_map_lastpiece_vmreg_store)
{
std::map<int,RegisterStore>::iterator lastpiece_iter = var_map_lastpiece_vmreg_store.begin();
std::map<int,RegisterStore>::iterator store_in_iter = var_map_label_vmreg_store_in.begin();
std::map<int,RegisterStore>::iterator store_out_iter = var_map_label_vmreg_store_out.begin();
//printf_map_register_store(var_map_lastpiece_vmreg_store,"var_map_lastpiece_vmreg_store");
int i = 0;
// printf("var_map_lastpiece_vmreg_store大小:%d\n",var_map_lastpiece_vmreg_store.size());
while (!var_map_lastpiece_vmreg_store.empty())
{
printf("第%d次进入循环,var_map_lastpiece_vmreg_store大小:%d\n",i++,var_map_lastpiece_vmreg_store.size());
std::map<int,RegisterStore>::iterator var_iter_map_t = lastpiece_iter;
std::vector<CodePiece>::iterator codepiece_iter = var_list_code_piece.begin();
for (codepiece_iter; codepiece_iter != var_list_code_piece.end(); codepiece_iter++)
{
if (lastpiece_iter->first == codepiece_iter->get_jmplabel() ||
(lastpiece_iter->first == (codepiece_iter->get_label() + 1 )) //&&
//codepiece_iter->get_jmplabel_type() != TYPE_MEM)
) {
var_map_label_vmreg_store_out.insert(std::make_pair(
codepiece_iter->get_label(),
lastpiece_iter->second
));
var_map_label_vmreg_store_in.insert(std::make_pair(
codepiece_iter->get_label() + 1,
lastpiece_iter->second
));
if (var_map_label_vmreg_store_in.find(codepiece_iter->get_label()) !=
var_map_label_vmreg_store_in.end())
{
if (codepiece_iter->get_label() != codepiece_iter->get_jmplabel())
var_map_lastpiece_vmreg_store.insert(std::make_pair(
codepiece_iter->get_label() + 1,
lastpiece_iter->second
));
//printf("aaaaaaaaaaaa %s,%x,%x\n" ,var_list_code_piece[codepiece_iter->get_label() + 1 ]
// .get_piece().back().insn_buffer,codepiece_iter->get_label(),codepiece_iter->get_jmplabel());
}
std::map<int,RegisterStore> var_out;
std::vector<CodePiece> var_t_CodePiece;
for (std::vector<CodePiece>::iterator iter_t_codepiece = var_list_code_piece.begin();
iter_t_codepiece!= var_list_code_piece.end();
iter_t_codepiece++)
{
if (var_map_label_vmreg_store_out.find(iter_t_codepiece->get_label()) !=
var_map_label_vmreg_store_out.end())
{
bool b1 = (var_map_lastpiece_vmreg_store.find(iter_t_codepiece->get_jmplabel()) ==
var_map_lastpiece_vmreg_store.end());
bool b2 = (var_map_label_vmreg_store_in.find(iter_t_codepiece->get_jmplabel()) ==
var_map_label_vmreg_store_in.end());
bool b3 = iter_t_codepiece->get_opcode_attribute() == OPCODE_ATTRIBUTE_NORMAL; //iter_t_codepiece->get_jmplabel_type() == TYPE_LABEL;
if (b1 && b2 && b3)
{
var_map_lastpiece_vmreg_store.insert(std::make_pair(
iter_t_codepiece->get_jmplabel(),
lastpiece_iter->second
));
var_map_label_vmreg_store_in.insert(std::make_pair(
iter_t_codepiece->get_jmplabel(),
lastpiece_iter->second
));
}
}
}
}
}
var_map_lastpiece_vmreg_store.erase(lastpiece_iter);
lastpiece_iter = var_map_lastpiece_vmreg_store.begin();
}
}
| [
"455736921@qq.com"
] | 455736921@qq.com |
18de133644e549f478b0ef781c8615b28e61f2f1 | 475ff35268ac4c337f8e6ad0791266bffe6bdbc2 | /src/qt/bitcoinunits.h | a2a3e82544c78cefc5e49cc560e9e6c8203d5591 | [
"MIT"
] | permissive | dequant-project/dequant | 5618311084f0ea80981d2d9a39d8bb24e7fbb054 | b69aa204f6c1774d6d16d4537920dd70bd18b142 | refs/heads/main | 2021-06-16T08:56:04.882807 | 2021-03-01T21:49:31 | 2021-03-01T21:49:31 | 173,586,676 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,712 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019-2020 The MasterWin developers
// Copyright (c) 2018-2021 The Dequant developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_BITCOINUNITS_H
#define BITCOIN_QT_BITCOINUNITS_H
#include "amount.h"
#include <QAbstractListModel>
#include <QString>
// U+2009 THIN SPACE = UTF-8 E2 80 89
#define REAL_THIN_SP_CP 0x2009
#define REAL_THIN_SP_UTF8 "\xE2\x80\x89"
#define REAL_THIN_SP_HTML " "
// U+200A HAIR SPACE = UTF-8 E2 80 8A
#define HAIR_SP_CP 0x200A
#define HAIR_SP_UTF8 "\xE2\x80\x8A"
#define HAIR_SP_HTML " "
// U+2006 SIX-PER-EM SPACE = UTF-8 E2 80 86
#define SIXPEREM_SP_CP 0x2006
#define SIXPEREM_SP_UTF8 "\xE2\x80\x86"
#define SIXPEREM_SP_HTML " "
// U+2007 FIGURE SPACE = UTF-8 E2 80 87
#define FIGURE_SP_CP 0x2007
#define FIGURE_SP_UTF8 "\xE2\x80\x87"
#define FIGURE_SP_HTML " "
// QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces
// correctly. Workaround is to display a space in a small font. If you
// change this, please test that it doesn't cause the parent span to start
// wrapping.
#define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>"
// Define THIN_SP_* variables to be our preferred type of thin space
#define THIN_SP_CP REAL_THIN_SP_CP
#define THIN_SP_UTF8 REAL_THIN_SP_UTF8
#define THIN_SP_HTML HTML_HACK_SP
/** Dequant unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class BitcoinUnits : public QAbstractListModel
{
Q_OBJECT
public:
explicit BitcoinUnits(QObject* parent);
/** Dequant units.
@note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones
*/
enum Unit {
DEQ,
mDEQ,
uDEQ
};
enum SeparatorStyle {
separatorNever,
separatorStandard,
separatorAlways
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Identifier, e.g. for image names
static QString id(int unit);
//! Short name
static QString name(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString simpleFormat(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Format as string (with unit)
static QString formatWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Format as string (with unit) but floor value up to "digits" settings
static QString floorWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Parse string to coin amount
static bool parse(int unit, const QString& value, CAmount* val_out);
//! Gets title for amount column including current display unit if optionsModel reference available */
static QString getAmountColumnTitle(int unit);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
///@}
static QString removeSpaces(QString text)
{
text.remove(' ');
text.remove(QChar(THIN_SP_CP));
#if (THIN_SP_CP != REAL_THIN_SP_CP)
text.remove(QChar(REAL_THIN_SP_CP));
#endif
return text;
}
//! Return maximum number of base units (Satoshis)
static CAmount maxMoney();
private:
QList<BitcoinUnits::Unit> unitlist;
};
typedef BitcoinUnits::Unit BitcoinUnit;
#endif // BITCOIN_QT_BITCOINUNITS_H
| [
"dequant@gmx.net"
] | dequant@gmx.net |
7250ff8e1f3ba61cb8af8408c2b0b53abb63687c | 6a0b41268cc5efc8ce9c2ef08b9b55ee15eb0f54 | /2_menu_projeto.cpp | 800a2693fd56238ad4f6fd876de142a94bbc457c | [] | no_license | Rian-Sm/LG1A1-projeto-c | ea3772014880e472e8b638a6c3cf6b9c7f80cc62 | a01eb40ff8380f5ca32cec085d377358065383c6 | refs/heads/master | 2020-07-05T08:55:24.205984 | 2019-11-28T03:55:30 | 2019-11-28T03:55:30 | 202,598,233 | 0 | 0 | null | 2019-11-28T03:52:34 | 2019-08-15T19:16:22 | C++ | UTF-8 | C++ | false | false | 892 | cpp | //menu_projeto
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void menu(char *choice){
printf ("\n============================================================================");
printf ("\n\t\t\tTESTE DOS SISTEMAS REPRESENTACIONIS ");
printf ("\n============================================================================");
printf ("\n\t\t\t1. CADASTRAR QUETIONARIO ");
printf ("\n\t\t\t2. VISUALIZAR QUESIONARIO ");
printf ("\n\t\t\t3. REALIZAR TESTE ");
printf ("\n\t\t\t4. SOBRE O TESTE ");
printf ("\n\t\t\tF. FIM ");
printf ("\n============================================================================");
printf ("\n\t\t\tescolha ->");
fflush(stdin);
scanf("%c", &*choice);
}
int main(){
char choice;
menu(&choice);
printf("%c", choice);
return 0;
}
| [
"riansm100@gmail.com"
] | riansm100@gmail.com |
6b39d16221ff64166537620b7d0e210f50a3fb61 | 0483a4940aa8e5fa6c5cbbd567a246764c5733e5 | /tests/pbo_tests.cpp | f520870d1edd1b9bd83a40bc69ef83400e18a783 | [
"MIT"
] | permissive | gruppe-adler/grad_aff | 7c51f67b325c6ebcab787b649d0432d14b676150 | 109dff4c28d0d80b273a3a8954e37cbf4f891d01 | refs/heads/master | 2021-11-27T15:02:59.690591 | 2020-02-08T18:24:02 | 2020-02-08T18:24:02 | 233,841,072 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,522 | cpp | #pragma once
#include <catch2/catch.hpp>
#include "grad_aff/pbo/pbo.h"
TEST_CASE("empty pbo read", "[empty-read-pbo]") {
grad_aff::Pbo testPbo("");
REQUIRE_THROWS_WITH(testPbo.readPbo(), "Invalid file/magic number");
}
TEST_CASE("extract single file", "[single-extract-pbo]") {
grad_aff::Pbo testPbo("A3.pbo");
REQUIRE_NOTHROW(testPbo.readPbo());
testPbo.extractPbo("unpack");
testPbo.extractSingleFile("data\\env_cloth_neutral_co.paa", "unpack2");
testPbo.extractSingleFile("data\\env_cloth_neutral_co.paa", "unpack3", false);
}
TEST_CASE("prefix read pbo", "[prefix-read-pbo]") {
grad_aff::Pbo testPbo("map_altis_data_layers_00_01.pbo");
REQUIRE(testPbo.getEntryData("a3\\map_altis\\data\\layers\\00_01\\m_003_037_lca.paa").size() > 0);
}
TEST_CASE("meh", "[meh]") {
grad_aff::Pbo mehPbo("grad_meh_main.pbo");
REQUIRE_NOTHROW(mehPbo.readPbo());
REQUIRE_NOTHROW(mehPbo.writePbo(""));
}
TEST_CASE("Test has entry", "[has-entry]") {
grad_aff::Pbo mehPbo("A3.pbo");
REQUIRE_NOTHROW(mehPbo.readPbo());
REQUIRE_FALSE(mehPbo.hasEntry("1337"));
REQUIRE_FALSE(mehPbo.hasEntry("config.cpp"));
REQUIRE(mehPbo.hasEntry("config.bin"));
REQUIRE(mehPbo.hasEntry("data\\env_co.paa"));
REQUIRE_FALSE(mehPbo.hasEntry("data\\test.paa"));
}
#ifdef GRAD_AFF_USE_OPENSSL
TEST_CASE("Hash Test", "[hash-test]") {
grad_aff::Pbo mehPbo("map_altis_data_layers_00_01.pbo");
REQUIRE_NOTHROW(mehPbo.readPbo());
REQUIRE(mehPbo.checkHash());
}
#endif | [
"sven0215@hotmail.com"
] | sven0215@hotmail.com |
2bf6e9884920903e1cc5ecbda89da33fc6eebd93 | 4701dbab00775b60b7da58c2bec695cc427a8eca | /tools/TaintTracker/TaintTracker.cpp | da6fb1b46b82bc6c99289fbb6a9daf3d3761310f | [] | no_license | 00mjk/vmill | 2e3fbe13881363f5c193fa3e93b76e70ae6148e6 | 818d2485c02e49d69f07fa5d62305b6946103d3e | refs/heads/master | 2023-02-24T19:35:36.181009 | 2021-01-28T21:09:26 | 2021-01-28T21:09:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,595 | cpp | /*
* Copyright (c) 2017 Trail of Bits, 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 <glog/logging.h>
#include <cstring>
#include <cstdlib>
#include <cinttypes>
#include <string>
#include <sstream>
#include <unordered_set>
#include <vector>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GetElementPtrTypeIterator.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include "remill/BC/Util.h"
#include "tools/TaintTracker/TaintTracker.h"
// TODO(pag): Eventual idea would be to move the core instrumentation into
// lots of helper functions, so that instead of real and tainted
// operations being interleaved, we do a series of real operations,
// perhaps recording key things like memory addresses accessed,
// then call a function that represents all the taint propagation
// calls that need to happen.
namespace vmill {
namespace {
static uint64_t ReturnUntainted(void) {
return 0;
}
static const uint8_t gZeroStuff[64] = {};
} // namespace
TaintTrackerTool::TaintTrackerTool(size_t num_bits_)
: num_bits(num_bits_),
void_type(nullptr),
taint_type(nullptr),
intptr_type(nullptr),
int32_type(nullptr),
taint_block(nullptr),
func(nullptr),
module(nullptr),
context(nullptr) {}
TaintTrackerTool::~TaintTrackerTool(void) {}
uintptr_t TaintTrackerTool::FindIntConstantTaint(uint64_t const_val) {
return reinterpret_cast<uintptr_t>(&(gZeroStuff[0]));
}
uintptr_t TaintTrackerTool::FindFloatConstantTaint(float const_val) {
return reinterpret_cast<uintptr_t>(&(gZeroStuff[0]));
}
uintptr_t TaintTrackerTool::FindDoubleConstantTaint(double const_val) {
return reinterpret_cast<uintptr_t>(&(gZeroStuff[0]));
}
uintptr_t TaintTrackerTool::FindTaintTransferFunc(const std::string &name) {
return reinterpret_cast<uintptr_t>(ReturnUntainted);
}
// Called when lifted bitcode or the runtime needs to resolve an external
// symbol.
uint64_t TaintTrackerTool::FindSymbolForLinking(
const std::string &name, uint64_t resolved) {
auto c_name = name.c_str();
if (c_name != strstr(c_name, "__taint")) {
return Tool::FindSymbolForLinking(name, resolved);
// Deal with tainted constants.
} else if (c_name == strstr(c_name, "__tainted_")) {
auto &addr = tainted_consts[name];
if (!addr) {
if (c_name == strstr(c_name, "__tainted_float_")) {
uint32_t val = 0;
CHECK(1 == sscanf(c_name, "__tainted_float_%" SCNx32, &val));
addr = FindFloatConstantTaint(reinterpret_cast<float &>(val));
} else if (c_name == strstr(c_name, "__tainted_double_")) {
uint64_t val = 0;
CHECK(1 == sscanf(c_name, "__tainted_double_%" SCNx64, &val));
addr = FindDoubleConstantTaint(reinterpret_cast<double &>(val));
} else if (c_name == strstr(c_name, "__tainted_int_")) {
uint64_t val = 0;
CHECK(1 == sscanf(c_name, "__tainted_int_%" SCNx64, &val));
addr = FindIntConstantTaint(val);
}
}
if (addr) {
return addr;
}
addr = Tool::FindSymbolForLinking(name, resolved);
if (addr) {
return addr;
}
LOG(ERROR)
<< "Missing taint symbol " << name << " for immediate constant";
addr = reinterpret_cast<uintptr_t>(&(gZeroStuff[0]));
return addr;
// Deal with taint transfer functions.
} else {
auto &addr = tainted_funcs[name];
if (addr) {
return addr;
}
addr = FindTaintTransferFunc(name);
if (addr) {
return addr;
}
addr = Tool::FindSymbolForLinking(name, resolved);
if (addr) {
return addr;
}
LOG(ERROR)
<< "Missing address for taint transfer function " << name;
addr = reinterpret_cast<uintptr_t>(ReturnUntainted);
return addr;
}
}
// Prepare the module for instrumentation.
void TaintTrackerTool::PrepareModule(llvm::Module *module_) {
module = module_;
context = &(module->getContext());
void_type = llvm::Type::getVoidTy(*context);
taint_type = llvm::Type::getIntNTy(*context, num_bits);
int32_type = llvm::Type::getInt32Ty(*context);
llvm::DataLayout dl(module);
intptr_type = llvm::Type::getIntNTy(*context, dl.getPointerSizeInBits());
func = nullptr;
}
// Instrument the runtime module.
bool TaintTrackerTool::InstrumentRuntime(llvm::Module *module_) {
for (auto &runtime_func : *module) {
func = &runtime_func;
VisitRuntimeFunction();
}
return true;
}
// Instrument a lifted function/trace.
bool TaintTrackerTool::InstrumentTrace(llvm::Function *func_, uint64_t pc) {
func = func_;
VisitLiftedFunction();
return true;
}
void TaintTrackerTool::VisitRuntimeFunction(void) {
if (!func->isDeclaration()) {
VisitFunction(func);
}
}
void TaintTrackerTool::VisitLiftedFunction(void) {
VisitFunction(func);
}
// Get a taint function.
llvm::Constant *TaintTrackerTool::GetFunc(
llvm::Type *ret_type, const std::string &name,
const std::vector<llvm::Type *> &arg_types) {
auto func_type = llvm::FunctionType::get(ret_type, arg_types, false);
return module->getOrInsertFunction(name, func_type);
}
// Get a pure taint function, i.e. one that neither reads nor writes to
// memory.
llvm::Constant *TaintTrackerTool::GetPureFunc(
llvm::Type *ret_type, const std::string &name,
const std::vector<llvm::Type *> &arg_types) {
auto func_ = GetFunc(ret_type, name, arg_types);
if (auto func = llvm::dyn_cast<llvm::Function>(func_)) {
func->addFnAttr(llvm::Attribute::ReadNone);
}
return func_;
}
// Call one of the taint propagation functions.
llvm::Value *TaintTrackerTool::CallFunc(
llvm::IRBuilder<> &ir, llvm::Constant *func,
std::vector<llvm::Value *> ¶ms) {
return ir.CreateCall(func, params);
}
int TaintTrackerTool::UnfoldConstantExpressions(llvm::Instruction *inst,
llvm::Use &use) {
auto val = use.get();
if (auto ce = llvm::dyn_cast<llvm::ConstantExpr>(val)) {
auto ce_inst = ce->getAsInstruction();
ce_inst->insertBefore(inst);
auto ret = UnfoldConstantExpressions(ce_inst);
use.set(ce_inst);
return ret + 1;
} else {
return 0;
}
}
// Unfold constant expressions into instructions so that we can accumulate
// the taint information of the constants.
int TaintTrackerTool::UnfoldConstantExpressions(llvm::Instruction *inst) {
int ret = 0;
for (auto &use : inst->operands()) {
ret += UnfoldConstantExpressions(inst, use);
}
if (auto call = llvm::dyn_cast<llvm::CallInst>(inst)) {
for (auto &use : call->arg_operands()) {
ret += UnfoldConstantExpressions(inst, use);
}
}
return ret;
}
// Expand a GetElementPtrInst into several other instructions.
void TaintTrackerTool::ExpandGEP(llvm::GetElementPtrInst *inst) {
llvm::DataLayout dl(module);
llvm::APInt offset(dl.getPointerSizeInBits(0), 0, true);
llvm::IRBuilder<> ir(inst);
llvm::Value *addr = nullptr;
llvm::Value *ptr = nullptr;
auto base = inst->getPointerOperand()->stripPointerCasts();
// Try to do some basic folding here.
if (auto inttoptr = llvm::dyn_cast<llvm::IntToPtrInst>(base)) {
addr = inttoptr->getOperand(0);
} else {
addr = ir.Insert(new llvm::PtrToIntInst(base, intptr_type));
}
// Convenient case, the indexes of this GEP are all constant integers.
if (inst->accumulateConstantOffset(dl, offset)) {
auto offset_int = offset.getSExtValue();
auto offset_uint = static_cast<uint64_t>(offset_int);
if (offset_uint) {
addr = ir.Insert(llvm::BinaryOperator::CreateAdd(
addr, llvm::ConstantInt::get(intptr_type, offset_uint, true)));
ptr = ir.Insert(new llvm::IntToPtrInst(addr, inst->getType()));
} else {
ptr = ir.Insert(new llvm::BitCastInst(base, inst->getType()));
}
// Inconvenient, split this GEP out into smaller operations which can then
// be individually taint-tracked.
} else {
auto it_end = llvm::gep_type_end(inst);
for (auto it = llvm::gep_type_begin(inst); it != it_end; ++it) {
auto index = it.getOperand();
auto element_type = it.getIndexedType();
if (auto struct_type = llvm::dyn_cast<llvm::StructType>(element_type)) {
auto ci = llvm::dyn_cast<llvm::ConstantInt>(index);
auto elem_index = ci->getZExtValue();
auto layout = dl.getStructLayout(struct_type);
auto offset = layout->getElementOffset(elem_index);
addr = ir.CreateAdd(
addr, llvm::ConstantInt::get(intptr_type, offset, false));
continue;
}
auto indexed_type = it.getIndexedType();
CHECK(index->getType()->isIntegerTy());
if (index->getType() != intptr_type) {
index = ir.CreateSExt(index, intptr_type);
}
auto type_size = dl.getTypeAllocSize(indexed_type);
addr = ir.CreateAdd(
addr,
ir.CreateMul(
index, llvm::ConstantInt::get(intptr_type, type_size, false)));
}
ptr = ir.CreateIntToPtr(addr, inst->getType());
}
inst->replaceAllUsesWith(ptr);
}
void TaintTrackerTool::VisitFunction(llvm::Function *func) {
DCHECK(taint_type != nullptr);
CHECK(!func->isDeclaration());
std::vector<llvm::Instruction *> insts;
auto &context = func->getContext();
auto entry_block = &(func->getEntryBlock());
taint_block = llvm::BasicBlock::Create(context, "taints", func, entry_block);
auto int32_type = llvm::Type::getInt32Ty(context);
auto arg_taint_func = GetFunc(taint_type, "__taint_load_arg", int32_type);
llvm::DataLayout dl(module);
llvm::IRBuilder<> ir(taint_block);
func_taints.clear();
auto untainted = llvm::Constant::getNullValue(taint_type);
// Create taint locations for each function argument.
unsigned arg_index = 0;
for (auto &arg : func->args()) {
auto arg_taint = ir.CreateAlloca(taint_type);
ir.CreateStore(untainted, arg_taint);
auto arg_num = llvm::ConstantInt::get(int32_type, arg_index++);
func_taints[&arg] = arg_taint;
ir.CreateStore(
CallFunc(ir, arg_taint_func, arg_num),
arg_taint);
};
std::vector<llvm::GetElementPtrInst *> geps;
int num_rounds = 0;
for (auto changed = true; changed; ++num_rounds) {
changed = false;
for (auto &block : *func) {
if (&block == taint_block) {
continue;
}
insts.clear();
for (auto &inst : block) {
insts.push_back(&inst);
}
// Unfold any constant expressions in the operand list of an instruction
// into individual instructions that can be taint tracked. This might
// introduce GEPs.
for (auto inst : insts) {
if (0 < UnfoldConstantExpressions(inst)) {
changed = true;
}
}
// Expand GEPs into either bitcasts or equivalent addressing artihmetic
// instructions.
geps.clear();
for (auto &inst : block) {
if (auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(&inst)) {
geps.push_back(gep);
}
}
// Expand GEP index lists into a bunch of individual instructions that
// can be tainted.
for (auto gep : geps) {
ExpandGEP(gep);
gep->eraseFromParent();
changed = true;
}
}
}
insts.clear();
for (auto &block : *func) {
if (&block != taint_block) {
for (auto &inst : block) {
CHECK(!llvm::isa<llvm::GetElementPtrInst>(inst));
func_taints[&inst] = ir.CreateAlloca(taint_type);
insts.push_back(&inst);
}
}
}
ir.CreateBr(entry_block);
for (auto inst : insts) {
visit(inst);
}
}
// Load the taint associated with some value.
llvm::Value *TaintTrackerTool::LoadTaint(llvm::IRBuilder<> &ir,
llvm::Value *val) {
// The taint of an instruction is stored in an `alloca`.
if (auto inst = llvm::dyn_cast<llvm::Instruction>(val)) {
CHECK(inst->getParent()->getParent() == ir.GetInsertBlock()->getParent());
auto &taint_alloca = func_taints[inst];
if (!taint_alloca) {
}
return ir.CreateLoad(taint_alloca);
// Argument to the current function.
} else if (auto arg = llvm::dyn_cast<llvm::Argument>(val)) {
CHECK(arg->getParent() == ir.GetInsertBlock()->getParent());
return ir.CreateLoad(func_taints[arg]);
// The taint of a constant is the result of a call to something like
// `__taint_constant_i8(val)`.
} else if (auto ci = llvm::dyn_cast<llvm::ConstantInt>(val)) {
std::stringstream ss;
ss << "__tainted_int_" << std::hex << ci->getZExtValue();
auto name = ss.str();
auto global = module->getOrInsertGlobal(name, taint_type);
return ir.CreateLoad(global);
}
auto not_tainted = llvm::Constant::getNullValue(taint_type);
if (auto cf = llvm::dyn_cast<llvm::ConstantFP>(val)) {
auto &apf = cf->getValueAPF();
std::stringstream ss;
ss << "__tainted_";
auto type = cf->getType();
if (type->isFloatTy()) {
auto fv = apf.convertToFloat();
ss << "float_" << std::hex << reinterpret_cast<uint32_t &>(fv);
} else if (type->isDoubleTy()) {
auto dv = apf.convertToDouble();
ss << "double_" << std::hex << reinterpret_cast<uint64_t &>(dv);
} else {
LOG(ERROR)
<< "Can't taint constant of type " << remill::LLVMThingToString(type);
return not_tainted;
}
auto name = ss.str();
auto global = module->getOrInsertGlobal(name, taint_type);
return ir.CreateLoad(global);
// The taint of a global variable is the `__taint_global(addr, size)`, where
// `addr` is the address of the global variable, and `size` is the size in
// bytes of the data pointed to by `addr`.
//
// TODO(pag): These taints should really be initialized once, globally.
} else if (auto gv = llvm::dyn_cast<llvm::GlobalVariable>(val)) {
llvm::DataLayout dl(module);
auto taint_func = GetPureFunc(taint_type, "__taint_global",
intptr_type, intptr_type);
auto val_type = gv->getType()->getElementType();
return CallFunc(
ir, taint_func, ir.CreatePtrToInt(gv, intptr_type),
llvm::ConstantInt::get(intptr_type, dl.getTypeAllocSize(val_type)));
}
// Functions don't really need to be tainted, they can't be changed or
// indexed into.
if (llvm::isa<llvm::Function>(val)) {
return not_tainted;
// Probably from the runtime.
} else if (llvm::isa<llvm::UndefValue>(val)) {
return not_tainted;
// Some kind of constant.
} else if (auto cv = llvm::dyn_cast<llvm::Constant>(val)) {
if (cv->isNullValue()) {
return not_tainted;
}
auto ce = llvm::dyn_cast<llvm::ConstantExpr>(val);
if (!ce) {
LOG(ERROR)
<< "Can't load taint for constant " << remill::LLVMThingToString(cv);
return not_tainted;
}
// If it's a global, basted to an integer, then lets use that and
// treat is like we treat other such taints.
if (llvm::Instruction::PtrToInt == ce->getOpcode() ||
llvm::Instruction::IntToPtr == ce->getOpcode()) {
auto base = ce->getOperand(0)->stripPointerCasts();
return LoadTaint(ir, base);
// Hopefully it's a zero-index GEP.
} else if (llvm::Instruction::GetElementPtr == ce->getOpcode()) {
auto base = ce->stripPointerCasts();
if (base != ce) {
return LoadTaint(ir, base);
}
}
LOG(ERROR)
<< "Can't load taint for constant " << remill::LLVMThingToString(cv);
return not_tainted;
// Something else, not sure what.
} else {
LOG(ERROR)
<< "Can't load taint for " << remill::LLVMThingToString(val);
return not_tainted;
}
}
// Set up the taints for allocas, which in this case mean, the taint on
// the *address* of the stack-allocated data, not the data itself. The
// taints on the data are handled by load/store and shadow memory.
void TaintTrackerTool::visitAllocaInst(llvm::AllocaInst &inst) {
llvm::IRBuilder<> ir(&*++inst.getIterator());
llvm::DataLayout dl(module);
std::stringstream ss;
auto name = ss.str();
auto taint_func = GetPureFunc(taint_type, "__taint_local",
intptr_type, intptr_type);
auto val_type = inst.getType()->getElementType();
auto alloca_size = dl.getTypeAllocSize(val_type);
auto alloca_taint = CallFunc(
ir, taint_func, ir.CreatePtrToInt(&inst, intptr_type),
llvm::ConstantInt::get(intptr_type, alloca_size));
ir.CreateStore(alloca_taint, func_taints[&inst]);
}
void TaintTrackerTool::visitLoadInst(llvm::LoadInst &inst) {
llvm::DataLayout dl(module);
std::stringstream ss;
ss << "__taint_load_" << dl.getTypeAllocSizeInBits(inst.getType());
auto name = ss.str();
auto func = GetPureFunc(taint_type, name, taint_type, intptr_type);
llvm::IRBuilder<> ir(&inst);
auto addr = inst.getPointerOperand();
auto addr_taint = LoadTaint(ir, addr);
auto taint = CallFunc(ir, func, addr_taint,
ir.CreatePtrToInt(addr, intptr_type));
ir.CreateStore(taint, func_taints[&inst]);
}
void TaintTrackerTool::visitStoreInst(llvm::StoreInst &inst) {
llvm::DataLayout dl(module);
std::stringstream ss;
auto stored_val = inst.getValueOperand();
auto stored_type = stored_val->getType();
ss << "__taint_store_" << dl.getTypeAllocSizeInBits(stored_type);
auto name = ss.str();
auto func = GetFunc(void_type, name, taint_type, intptr_type, taint_type);
llvm::IRBuilder<> ir(&inst);
auto addr = inst.getPointerOperand();
auto addr_taint = LoadTaint(ir, addr);
auto taint = LoadTaint(ir, stored_val);
(void) CallFunc(ir, func, addr_taint, ir.CreatePtrToInt(addr, intptr_type),
taint);
}
void TaintTrackerTool::visitCastInst(llvm::CastInst &inst) {
llvm::IRBuilder<> ir(&inst);
auto taint = LoadTaint(ir, inst.getOperand(0));
switch (inst.getOpcode()) {
case llvm::Instruction::Trunc:
case llvm::Instruction::ZExt:
case llvm::Instruction::SExt:
case llvm::Instruction::FPTrunc:
case llvm::Instruction::FPExt:
case llvm::Instruction::FPToUI:
case llvm::Instruction::FPToSI:
case llvm::Instruction::UIToFP:
case llvm::Instruction::SIToFP: {
std::stringstream ss;
ss << "__taint_" << inst.getOpcodeName() << "_to_"
<< remill::LLVMThingToString(inst.getType());
auto name = ss.str();
auto func = GetPureFunc(taint_type, name, taint_type);
auto conv_taint = CallFunc(ir, func, taint);
ir.CreateStore(conv_taint, func_taints[&inst]);
break;
}
// Size shouldn't change.
case llvm::Instruction::IntToPtr:
case llvm::Instruction::PtrToInt:
case llvm::Instruction::BitCast: {
ir.CreateStore(taint, func_taints[&inst]);
break;
}
default:
LOG(ERROR)
<< "Unsupported cast instruction "
<< remill::LLVMThingToString(&inst);
break;
}
}
void TaintTrackerTool::visitBinaryOperator(llvm::BinaryOperator &inst) {
llvm::DataLayout dl(module);
std::stringstream ss;
ss << "__taint_" << inst.getOpcodeName() << "_"
<< remill::LLVMThingToString(inst.getType());
auto name = ss.str();
auto func = GetPureFunc(taint_type, name, taint_type, taint_type);
llvm::IRBuilder<> ir(&inst);
auto lhs = inst.getOperand(0);
auto rhs = inst.getOperand(1);
auto lhs_taint = LoadTaint(ir, lhs);
auto rhs_taint = lhs == rhs ? lhs_taint : LoadTaint(ir, rhs);
std::vector<llvm::Value *> args = {lhs_taint, rhs_taint};
ir.CreateStore(CallFunc(ir, func, lhs_taint, rhs_taint), func_taints[&inst]);
}
namespace {
static const char *GetPredicateName(llvm::CmpInst &inst) {
switch (inst.getPredicate()) {
case llvm::FCmpInst::FCMP_FALSE: return "false";
case llvm::FCmpInst::FCMP_OEQ: return "oeq";
case llvm::FCmpInst::FCMP_OGT: return "ogt";
case llvm::FCmpInst::FCMP_OGE: return "oge";
case llvm::FCmpInst::FCMP_OLT: return "olt";
case llvm::FCmpInst::FCMP_OLE: return "ole";
case llvm::FCmpInst::FCMP_ONE: return "one";
case llvm::FCmpInst::FCMP_ORD: return "ord";
case llvm::FCmpInst::FCMP_UNO: return "uno";
case llvm::FCmpInst::FCMP_UEQ: return "ueq";
case llvm::FCmpInst::FCMP_UGT: return "ugt";
case llvm::FCmpInst::FCMP_UGE: return "uge";
case llvm::FCmpInst::FCMP_ULT: return "ult";
case llvm::FCmpInst::FCMP_ULE: return "ule";
case llvm::FCmpInst::FCMP_UNE: return "une";
case llvm::FCmpInst::FCMP_TRUE: return "true";
case llvm::ICmpInst::ICMP_EQ: return "eq";
case llvm::ICmpInst::ICMP_NE: return "ne";
case llvm::ICmpInst::ICMP_SGT: return "sgt";
case llvm::ICmpInst::ICMP_SGE: return "sge";
case llvm::ICmpInst::ICMP_SLT: return "slt";
case llvm::ICmpInst::ICMP_SLE: return "sle";
case llvm::ICmpInst::ICMP_UGT: return "ugt";
case llvm::ICmpInst::ICMP_UGE: return "uge";
case llvm::ICmpInst::ICMP_ULT: return "ult";
case llvm::ICmpInst::ICMP_ULE: return "ule";
default: return "unknown";
}
}
} // namespace
void TaintTrackerTool::visitCmpInst(llvm::CmpInst &inst) {
llvm::DataLayout dl(module);
std::stringstream ss;
auto cmp_type = inst.getOperand(0)->getType();
if (cmp_type->isPointerTy()) {
cmp_type = llvm::Type::getIntNTy(*context, dl.getPointerSizeInBits(0));
}
ss << "__taint_" << inst.getOpcodeName() << "_" << GetPredicateName(inst)
<< "_" << remill::LLVMThingToString(cmp_type);
auto name = ss.str();
auto func = GetPureFunc(taint_type, name, taint_type, taint_type);
llvm::IRBuilder<> ir(&inst);
auto lhs = inst.getOperand(0);
auto rhs = inst.getOperand(1);
auto lhs_taint = LoadTaint(ir, lhs);
auto rhs_taint = lhs == rhs ? lhs_taint : LoadTaint(ir, rhs);
ir.CreateStore(CallFunc(ir, func, lhs_taint, rhs_taint), func_taints[&inst]);
}
void TaintTrackerTool::visitGetElementPtrInst(llvm::GetElementPtrInst &inst) {
llvm::DataLayout dl(module);
llvm::APInt offset(dl.getPointerSizeInBits(0), 0, true);
llvm::IRBuilder<> ir(&inst);
auto base = inst.getPointerOperand()->stripPointerCasts();
llvm::Value *taint = llvm::Constant::getNullValue(taint_type);
// Convenient case, the indexes of this GEP are all constant integers.
if (inst.accumulateConstantOffset(dl, offset)) {
if (offset.getZExtValue()) {
LOG(ERROR)
<< "Cannot taint GEP instruction: "
<< remill::LLVMThingToString(&inst);
} else {
taint = LoadTaint(ir, base);
}
// Inconvenient, split this GEP out into smaller operations which can then
// be individually taint-tracked.
} else {
LOG(ERROR)
<< "Cannot taint GEP instruction: " << remill::LLVMThingToString(&inst);
}
ir.CreateStore(taint, func_taints[&inst]);
}
void TaintTrackerTool::visitIntrinsicInst(llvm::IntrinsicInst &inst) {
std::vector<llvm::Value *> args;
std::vector<llvm::Type *> arg_types;
llvm::IRBuilder<> ir(&inst);
for (unsigned i = 0; i < inst.getNumArgOperands(); ++i) {
auto arg = inst.getArgOperand(i);
auto taint_arg = LoadTaint(ir, arg);
args.push_back(taint_arg);
arg_types.push_back(taint_type);
}
auto intrinsic_name = llvm::Intrinsic::getName(inst.getIntrinsicID());
std::stringstream ss;
ss << "__taint_";
for (auto c : intrinsic_name) {
if (isalnum(c)) {
ss << c;
} else {
ss << '_';
}
}
auto ret_type = inst.getType();
if (!ret_type->isVoidTy()) {
ss << "_" << remill::LLVMThingToString(ret_type);
}
auto name = ss.str();
if (inst.getType() == void_type) {
auto taint_func = GetFunc(void_type, name, arg_types);
(void) CallFunc(ir, taint_func, args);
} else {
auto taint_func = GetPureFunc(taint_type, name, arg_types);
auto taint = CallFunc(ir, taint_func, args);
ir.CreateStore(taint, func_taints[&inst]);
}
}
void TaintTrackerTool::visitCallInst(llvm::CallInst &inst) {
auto called_val = inst.getCalledValue();
llvm::IRBuilder<> ir(&inst);
// Don't try to pass taints for varargs functions or to inline assembly.
if (llvm::isa<llvm::InlineAsm>(called_val)) {
ir.CreateStore(llvm::Constant::getNullValue(taint_type),
func_taints[&inst]);
return;
}
auto taint_func = GetFunc(void_type, "__taint_store_arg", int32_type,
taint_type);
unsigned i = 0;
for (auto &arg : inst.arg_operands()) {
CallFunc(ir, taint_func, llvm::ConstantInt::get(int32_type, i++),
LoadTaint(ir, arg.get()));
}
if (func->getReturnType() != void_type) {
taint_func = GetFunc(taint_type, "__taint_load_ret");
ir.SetInsertPoint(&*++(inst.getIterator()));
ir.CreateStore(CallFunc(ir, taint_func), func_taints[&inst]);
}
}
void TaintTrackerTool::visitReturnInst(llvm::ReturnInst &inst) {
if (auto val = inst.getReturnValue()) {
auto taint_func = GetFunc(void_type, "__taint_store_ret", taint_type);
llvm::IRBuilder<> ir(&inst);
CallFunc(ir, taint_func, LoadTaint(ir, val));
}
}
// Forwards the taints from the source block to the phi node.
void TaintTrackerTool::visitPHINode(llvm::PHINode &inst) {
for (auto &op : inst.operands()) {
auto block = inst.getIncomingBlock(op);
auto val = op.get();
llvm::IRBuilder<> ir(block->getTerminator());
ir.CreateStore(LoadTaint(ir, val), func_taints[&inst]);
}
}
void TaintTrackerTool::visitSelectInst(llvm::SelectInst &inst) {
auto cond = inst.getCondition();
auto cond_type = cond->getType();
if (llvm::isa<llvm::VectorType>(cond_type)) {
LOG(ERROR)
<< "Taint tracking of vector-based selects is not yet supported.";
return;
}
llvm::IRBuilder<> ir(&inst);
auto taint_func = GetPureFunc(taint_type, "__taint_select",
taint_type, cond_type, taint_type, taint_type);
auto select_taint = CallFunc(ir, taint_func, LoadTaint(ir, cond), cond,
LoadTaint(ir, inst.getTrueValue()),
LoadTaint(ir, inst.getFalseValue()));
ir.CreateStore(select_taint, func_taints[&inst]);
}
void TaintTrackerTool::visitBranchInst(llvm::BranchInst &inst) {
if (inst.isUnconditional()) {
return;
}
auto cond = inst.getCondition();
auto bool_type = llvm::Type::getInt1Ty(*context);
CHECK(bool_type == cond->getType());
auto taint_func = GetFunc(void_type, "__taint_branch",
taint_type, bool_type);
llvm::IRBuilder<> ir(&inst);
(void) CallFunc(ir, taint_func, LoadTaint(ir, cond), cond);
}
void TaintTrackerTool::visitIndirectBrInst(llvm::IndirectBrInst &inst) {
LOG(ERROR)
<< "Indirect branches not yet handled: "
<< remill::LLVMThingToString(&inst);
}
void TaintTrackerTool::visitSwitchInst(llvm::SwitchInst &inst) {
auto cond = inst.getCondition();
std::vector<uint64_t> vals;
for (auto &case_entry : inst.cases()) {
auto case_val = case_entry.getCaseValue()->getZExtValue();
vals.push_back(case_val);
}
auto int64_type = llvm::Type::getInt64Ty(*context);
auto int64_ptr_type = llvm::PointerType::get(int64_type, 0);
auto cases = llvm::ConstantDataArray::get(*context, vals);
auto case_array = new llvm::GlobalVariable(
*module, cases->getType(), true, llvm::GlobalValue::PrivateLinkage,
cases);
auto first_entry = llvm::ConstantExpr::getGetElementPtr(
int64_type, case_array, llvm::ConstantInt::get(intptr_type, 0));
auto after_last_entry = llvm::ConstantExpr::getGetElementPtr(
int64_type, case_array, llvm::ConstantInt::get(intptr_type, 1));
auto taint_func = GetFunc(void_type, "__taint_switch",
taint_type, int64_type, int64_ptr_type,
int64_ptr_type);
llvm::IRBuilder<> ir(&inst);
(void) CallFunc(ir, taint_func, LoadTaint(ir, cond),
ir.CreateZExt(cond, int64_type),
first_entry, after_last_entry);
}
void TaintTrackerTool::visitExtractElementInst(llvm::ExtractElementInst &inst) {
LOG(ERROR)
<< "Unsupported " << remill::LLVMThingToString(&inst);
auto not_tainted = llvm::Constant::getNullValue(taint_type);
llvm::IRBuilder<> ir(&inst);
ir.CreateStore(not_tainted, func_taints[&inst]);
}
void TaintTrackerTool::visitInsertElementInst(llvm::InsertElementInst &inst) {
LOG(ERROR)
<< "Unsupported " << remill::LLVMThingToString(&inst);
auto not_tainted = llvm::Constant::getNullValue(taint_type);
llvm::IRBuilder<> ir(&inst);
ir.CreateStore(not_tainted, func_taints[&inst]);
}
void TaintTrackerTool::visitMemSetInst(llvm::MemSetInst &inst) {
llvm::IRBuilder<> ir(&inst);
auto taint_addr = LoadTaint(ir, inst.getDest());
auto taint_length = LoadTaint(ir, inst.getLength());
auto taint_val = LoadTaint(ir, inst.getValue());
auto addr = ir.CreatePtrToInt(inst.getDest(), intptr_type);
auto length = ir.CreateZExt(inst.getLength(), intptr_type);
auto val = ir.CreateZExt(inst.getValue(), intptr_type);
auto taint_func = GetFunc(
void_type, "__taint_memset",
taint_type, intptr_type, // Destination address.
taint_type, intptr_type, // Value.
taint_type, intptr_type); // Destination size.
(void) CallFunc(ir, taint_func, taint_addr, addr,
taint_val, val, taint_length, length);
}
void TaintTrackerTool::visitMemCpyInst(llvm::MemCpyInst &inst) {
llvm::IRBuilder<> ir(&inst);
auto taint_dest_addr = LoadTaint(ir, inst.getDest());
auto taint_src_addr = LoadTaint(ir, inst.getSource());
auto taint_length = LoadTaint(ir, inst.getLength());
auto dest_addr = ir.CreatePtrToInt(inst.getDest(), intptr_type);
auto src_addr = ir.CreatePtrToInt(inst.getSource(), intptr_type);
auto length = ir.CreateZExt(inst.getLength(), intptr_type);
auto taint_func = GetFunc(
void_type, "__taint_memcpy",
taint_type, intptr_type, // Destination address.
taint_type, intptr_type, // Source address.
taint_type, intptr_type); // Destination size.
(void) CallFunc(ir, taint_func, taint_dest_addr, dest_addr,
taint_src_addr, src_addr, taint_length, length);
}
void TaintTrackerTool::visitMemMoveInst(llvm::MemMoveInst &inst) {
llvm::IRBuilder<> ir(&inst);
auto taint_dest_addr = LoadTaint(ir, inst.getDest());
auto taint_src_addr = LoadTaint(ir, inst.getSource());
auto taint_length = LoadTaint(ir, inst.getLength());
auto dest_addr = ir.CreatePtrToInt(inst.getDest(), intptr_type);
auto src_addr = ir.CreatePtrToInt(inst.getSource(), intptr_type);
auto length = ir.CreateZExt(inst.getLength(), intptr_type);
auto taint_func = GetFunc(
void_type, "__taint_memmove",
taint_type, intptr_type, // Destination address.
taint_type, intptr_type, // Source address.
taint_type, intptr_type); // Destination size.
(void) CallFunc(ir, taint_func, taint_dest_addr, dest_addr,
taint_src_addr, src_addr, taint_length, length);
}
} // namespace vmill
| [
"peter.goodman@gmail.com"
] | peter.goodman@gmail.com |
a550bb18a7ba8cbf240cf445ef5fc77320786e82 | 8f17b34aa5c1ee123302096c279581834ccdf213 | /1007.cpp | a909915867ade7122d531fb1b351ba42153be10b | [] | no_license | Honlan/poj-org-c-plus-plus | 58b005c302e24a7ec765227f0b88956bfafb5bbf | 2441a1c92ec6c0753f582ce5e2b79fb4d1d3d3d9 | refs/heads/master | 2021-01-10T17:52:26.149808 | 2015-11-05T02:47:54 | 2015-11-05T02:47:54 | 45,180,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | cpp | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct dna
{
int unorder;
string s;
}DNA[105];
int inversionNum(string s){
int result = 0;
int A, C, G;
A = C = G = 0;
for (int i = s.length() - 1; i >= 0; i--)
{
switch(s[i]){
case 'A':
A++;
break;
case 'C':
C++;
result += A;
break;
case 'G':
G++;
result += A;
result += C;
break;
case 'T':
result += A;
result += C;
result += G;
}
}
return result;
}
bool operator < (struct dna a, struct dna b){
return a.unorder < b.unorder;
}
int main()
{
int L, N, i = 0;
cin >> L >> N;
while(i < N){
cin >> DNA[i].s;
DNA[i].unorder = inversionNum(DNA[i].s);
i++;
}
sort(DNA, DNA + N);
for (i = 0; i < N; ++i)
{
cout << DNA[i].s << endl;
}
return 0;
} | [
"honlan@HonlandeMacBook-Air.local"
] | honlan@HonlandeMacBook-Air.local |
02c8c2482e1dcdc415b2243dc82b47389f977b7a | 5b7ac84e78e13f81568d3771a353d24c0b52d9e6 | /07_Brackets.cpp | e634c7e2dc2550cd2fe4cdbdbc15e86478555211 | [] | no_license | msavvop/codility_solutions | 17c5d71ffb23145a2175bc63c8c8ebafb39d39a6 | a1c7a1a19b34fd5d4c2b44f772095346b8a64b9a | refs/heads/master | 2020-03-08T04:11:31.052562 | 2018-04-03T14:59:19 | 2018-04-03T14:59:19 | 127,914,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,537 | cpp | /*
7. Stacks and Queues
Brackets
100 out of 100 points
*/
#include<string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <deque>
# include <stack>
using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::copy;
using std::deque;
using std::stack;
int solution(string &S)
{
// 100%
stack<char> a;
// Εδώ μπορούμε να χρησιμοποιήσουμε ένα stack από χαρακτήρες.
// Σαρώνουμε το διάνυσμα από την αρχή μέχρι το τέλος και κάθε φορά που βρίσκουμε χαρακτήρες ανοίγματος ({[ τους τοποθετούμε στη κορυφή του σωρού.
// Αντίστοιχα, κάθε φορά που βρίσκουμε χαρακτήρες κλεισίματος )}], απομακρύνουμε τον χαρακτήρα που βρίσκεται στην κορυφή.
// Κατά την απομάκρυνση πρέπει απαραίτητα να ελέγχουμε ποιός χαρακτήρας βρίσκεται στην κορυφή του σωρού. Αν πχ έχουμε να απομακρύνουμε παρένθεση
// και στην κορυφή του σωρού υπάρχει { ή [ τότε μπορούμε να σταματήσουμε την σάρωση της συμβολοσειράς και να επιστρέψουμε 0
// καθώς έχουμε εντοπίσει αταίριαστο ζεύγος {)...
// Αν στο τέλος της σάρωσης της συμβολοσειράς το μέγεθος του stack είναι 0, τα σύμβολα ()[]{} ζευγαρώνουν σε ορθή σειρά και επιστρέφουμε 1.
for (int i = 0; i<S.size(); i++)
{
if (S[i] == '(' || S[i] == '{' || S[i] == '[')
a.push(S[i]);
else if (S[i] == ')')
{
if (a.size() == 0 || a.top() != '(') return 0;
else a.pop();
}
else if (S[i] == ']')
{
if (a.size() == 0 || a.top() != '[') return 0;
else a.pop();
}
else if (S[i] == '}')
{
if (a.size() == 0 || a.top() != '{') return 0;
else a.pop();
}
}
if (a.size() == 0)
return 1;
else
return 0;
}
/*
int solution(string &S)
{
// 100%
int count1{}, count2{}, count3{};
for (int i=0; i<S.size(); i++)
{
if (S[i]=='(')
count1++;
else if (S[i]==')')
{
count1--;
if (count1<0) return 0;
if ( S[i-1] == '[' || S[i-1]=='{') return 0;
}
else if (S[i]=='{')
count2++;
else if (S[i]=='}')
{
count2--;
if (count2<0) return 0;
if ( S[i-1] == '(' || S[i-1]=='[') return 0;
}
else if (S[i]=='[')
count3++;
else
{
count3--;
if (count3<0) return 0;
if ( S[i-1] == '(' || S[i-1]=='{') return 0;
}
}
if (count1==0 && count2==0 && count3==0)
return 1;
else
return 0;
}
*/
/*
deque<char> str(deque <char>&S)
{
//87%
char ch;
char lookfor;
int count = 0;
if (S.size() == 0) return S;
if (S.size() % 2 == 1) return S;
ch = S[0];
switch (ch)
{
case '(':
lookfor = ')';
break;
case '{':
lookfor = '}';
break;
case '[':
lookfor = ']';
break;
default:
return S;
}
for (auto iter = S.begin(); iter != S.end(); iter++)
{
if (*iter == ch) count++;
if (*iter == lookfor) count--;
if (*iter == lookfor&&count == 0)
{
if ((iter - 1 - S.begin()) % 2 == 1) return S;
S.erase(iter);
S.pop_front();
return str(S);
}
}
return S;
}
int solution(string &S)
{
deque <char>A(S.length());
deque <char>B;
copy(S.begin(), S.end(), A.begin());
B = str(A);
if (B.size() == 0)
{
// cout << A << endl;
return 1;
}
else
{
// cout << A << endl;
return 0;
}
}
*/
/*
vector<char> str(vector <char>S)
{
//50%
char ch;
char lookfor;
int count = 0;
vector <char> A;
vector<char> B;
vector <char> C;
vector<char> D;
if (S.size() == 0) return S;
ch = S[0];
// if (S.size() % 2 == 1) return S;
switch (ch)
{
case '(':
lookfor = ')';
break;
case '{':
lookfor = '}';
break;
case '[':
lookfor = ']';
break;
default:
return S;
}
for (auto iter=S.begin(); iter!=S.end(); iter++)
{
if (*iter == ch) count++;
if (*iter == lookfor) count--;
if (*iter == lookfor&&count == 0)
{
if( (iter-1 - S.begin()) % 2 == 1) return S;
S.erase(iter);
S.erase(S.begin());
return str(S);
}
}
return S;
}
int solution(string &S)
{
vector <char>A;
vector <char>B;
if (S.length() % 2 == 1) return 0;
for (int i = 0; i < S.length(); i++)
{
A.push_back(S[i]);
}
// copy(S.begin(), S.end(), A.begin());
B = str(A);
if (B.size() == 0)
{
// cout << A << endl;
return 1;
}
else
{
// cout << A << endl;
return 0;
}
}
*/
/*
string str(string S)
{
//75%
char ch;
char lookfor;
int count = 0;
string A;
string B;
string C;
string D;
ch = S[0];
if (S == "") return "";
switch (ch)
{
case '(':
lookfor = ')';
break;
case '{':
lookfor = '}';
break;
case '[':
lookfor = ']';
break;
default:
return S;
}
for (int i = 0; i < S.length(); i++)
{
if (S[i] == ch) count++;
if (S[i] == lookfor) count--;
if (S[i]==lookfor&&count == 0)
{
A = string(S, 1, i - 1);
B=str(A);
if (B.length() % 2 == 1) return B;
if (i < S.length()-1)
{
D = string(S, i+1, S.length() - 1);
C=str(D);
if (C.length() % 2 == 1) return C;
}
return str(B + C);
}
}
return S;
}
int solution(string &S)
{
string A;
if (S.length() % 2 == 1) return 0;
A = str(S);
if (A == "")
{
// cout << A << endl;
return 1;
}
else
{
// cout << A << endl;
return 0;
}
}
*/
int main(void)
{
string S = "{[([{)(}])]}";
// string S = "{[()()]}";
// string S = "([)()]";
cout << solution(S) << endl;
return 0;
} | [
"m_savvop@otenet.gr"
] | m_savvop@otenet.gr |
aaa7f3fb248ca8de48c454ad4108929ae17456c5 | aeb4944c75923c8e087d160da5ed7980a8ead072 | /seg7/main.cpp | bb1dac7d7599f8007ad98de6a46d63466d14d2ba | [] | no_license | jaymzee/sdl | b283550f24b703d278b25fd90c08fa7264fcd254 | 122c4519843af391fbbddf55a11596a2ecd00be5 | refs/heads/master | 2023-07-12T18:42:44.957006 | 2021-08-05T00:33:40 | 2021-08-05T00:33:40 | 309,839,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | cpp | #include <SDL2/SDL.h>
#include <stdio.h>
#include "scene.h"
int main(int argc, char *argv[])
{
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
int renderer_flags = SDL_RENDERER_ACCELERATED;
// process program arguments
if (argc > 1) {
if (strcmp(argv[1], "-s") == 0) {
fprintf(stderr, "using software rendering\n");
renderer_flags = SDL_RENDERER_SOFTWARE;
}
}
// Initialize SDL and create a winodw, renderer, and font
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "SDL Init: %s\n", SDL_GetError());
return 1;
}
/*
if (TTF_Init() < 0) {
printf("TTF Init: %s\n", TTF_GetError());
return 1;
}
*/
window = SDL_CreateWindow(
"initializing SDL ...",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN
);
if (!window) {
fprintf(stderr, "Create Window: %s\n", SDL_GetError());
return 1;
}
renderer = SDL_CreateRenderer(window, -1, renderer_flags);
if (!renderer) {
fprintf(stderr, "Create Renderer: %s\n", SDL_GetError());
return 1;
}
Scene scene{};
try {
scene.Loop(window, renderer);
} catch (const char *err) {
fprintf(stderr, "Scene Loop: %s\n", err);
}
// Cleanup and exit
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
| [
"jaymzee@users.noreply.github.com"
] | jaymzee@users.noreply.github.com |
c0b51809a7623dd65bea4a379492ac4ec6dc0c59 | 58639b83a04874df3e199f76f866432d5eeeee7f | /src/Websites/GeeksForGeeks/Arrays/page 3/FloorAndCeil.cpp | 135ebef16ead3c0b8e076b4927015ed1bcb85c1a | [] | no_license | avikodak/ProgramsV3 | 0b2047dcd914b2c87b726255e3527a3e6173ca61 | ba578d59b56a0a13f4b21631e071e6948a22ef3f | refs/heads/master | 2016-09-06T13:38:23.294513 | 2013-03-19T09:19:54 | 2013-03-19T09:19:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | /*
* FloorAndCeil.cpp
*
* Created on: Feb 14, 2013
* Author: Avinash
*/
//
// Testing Status
//
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
using namespace std;
using namespace __gnu_cxx;
#define null NULL
int *FindFloorAndCeilOfSortedArray(int userInput[],int sizeOfArray,int key){
int ceilOfKey,floorOfKey;
int result[2];
for(int crawler=0;crawler < sizeOfArray;crawler++){
if(userInput[crawler] == key){
result[0] = result[1] = userInput[crawler];
return result;
}
if(userInput[crawler] < key){
if(ceilOfKey - userInput[crawler] > key - userInput[crawler] ){
ceilOfKey = userInput[crawler];
}
}
if(userInput[crawler] > key){
if(floorOfKey - userInput[crawler] > key - userInput[crawler] ){
floorOfKey = userInput[crawler];
}
}
}
result[0] = floorOfKey;
result[1] = ceilOfKey;
return result;
}
int * FindCeilAndFloorBinarySearch(int userInput[],int sizeOfArray,int startIndex,int endIndex,int key){
int result[2];
if(startIndex < endIndex){
if(startIndex > 0 && startIndex < sizeOfArray){
if(userInput[startIndex] > key){
result[0] = INT_MIN;
result[1] = userInput[startIndex];
}else{
result[0] = userInput[startIndex];
result[1] = INT_MAX;
}
return result;
}
if(endIndex > 0 && endIndex < sizeOfArray){
if(userInput[endIndex] > key){
result[0] = INT_MIN;
result[1] = userInput[startIndex];
}else{
result[0] = userInput[startIndex];
result[1] = INT_MAX;
}
return result;
}
}
int middleIndex = (startIndex + endIndex)/2;
if(userInput[middleIndex] == key){
result[0] = userInput[middleIndex];
result[1] = userInput[middleIndex];
return result;
}
if(middleIndex-1 > 0){
if(key < userInput[middleIndex] && userInput[middleIndex-1] > key){
result[0] = userInput[middleIndex-1];
result[1] = userInput[middleIndex];
return result;
}
}
if(middleIndex+1 < sizeOfArray){
if(key < userInput[middleIndex+1] && userInput[middleIndex] < key){
result[0] = userInput[middleIndex];
result[1] = userInput[middleIndex+1];
return result;
}
}
if(userInput[middleIndex] > key){
return FindCeilAndFloorBinarySearch(userInput,sizeOfArray,0,middleIndex-1,key);
}else{
return FindCeilAndFloorBinarySearch(userInput,sizeOfArray,middleIndex+1,endIndex,key);
}
}
int *FloorAndCeilUsingMaxMinHeap(){
// Use two heaps one to store the min heap and
// other the max heap
// get the max and min of the two heaps
}
//int main(){
// return -1;
//}
| [
"avikodak@gmail.com"
] | avikodak@gmail.com |
948281ff262e4df6e829bc5e0730dc8420a79b49 | f848f0cd52b20c0452567aff0e30b4d627d10b0d | /src/vor2d/Voronoi.h | 1269c4a02892dd6eff08cda1df411549e9acecd9 | [
"MIT"
] | permissive | mohamed-abdelhameed/voroffset | 729344001e7ef182f95b3f25e419af7d4bce1ef1 | 96f04a8bb263eaf69641540fbff3cebe019deedf | refs/heads/master | 2022-12-06T13:03:36.775064 | 2020-09-01T02:24:26 | 2020-09-01T02:24:26 | 291,872,590 | 0 | 0 | MIT | 2020-09-01T02:14:26 | 2020-09-01T02:14:26 | null | UTF-8 | C++ | false | false | 3,910 | h | #pragma once
////////////////////////////////////////////////////////////////////////////////
#include "vor2d/Common.h"
#include "vor2d/Image.h"
#include <vector>
#include <array>
#include <set>
////////////////////////////////////////////////////////////////////////////////
namespace voroffset
{
struct VoronoiMorpho
{
////////////////
// Data types //
////////////////
// A 2D point
typedef std::complex<int> Point;
// A horizontal segment
struct Segment
{
int x, y1, y2;
Segment(int _x, int _y1, int _y2)
: x(_x), y1(_y1), y2(_y2)
{ }
inline Point left() const { return Point(x, y1); }
inline Point right() const { return Point(x, y2); }
inline Point any() const { return Point(x, y1); }
bool operator <(const Segment &s) const
{
return (y1 + y2 < s.y1 + s.y2) || (y1 + y2 == s.y1 + s.y2 && x < s.x);
}
inline bool contains(const Segment &o) const
{
return y1 <= o.y1 && o.y2 <= y2;
}
inline bool isPoint() const
{
return y1 == y2;
}
};
//////////////////
// Data members //
//////////////////
// Constant parameters for the current dilation
const int m_XMax, m_YMax;
const double m_Radius;
// Seeds above sorted by ascending y of their midpoint
std::set<Segment> m_S;
// Candidate Voronoi vertices sorted by ascending x
std::vector<std::vector<Segment> > m_Q;
// Typedefs
typedef std::set<Segment>::const_iterator S_const_iter;
/////////////
// Methods //
/////////////
// Assumes that y_p < y_q < y_r
int rayIntersect(Point p, Point q, Point r) const;
// Assumes that y_lp < y_ab < y_qr
int treatSegments(Segment lp, Segment ab, Segment qr) const;
// Assumes that it != m_S.end()
void exploreLeft(S_const_iter it, Segment qr, int i);
// Assumes that it != m_S.end()
void exploreRight(S_const_iter it, Segment lp, int i);
// Insert a new seed segment [(i,j1), (i,j2)]
void insertSegment(int i, int j1, int j2);
// Remove seeds that are not contributing anymore to the current sweep line (y==i)
void removeInactiveSegments(int i);
// Extract the result for the current line
void getLine(int i, std::vector<int> &nl, int ysize);
VoronoiMorpho(int _xmax, int _ymax, double _radius)
: m_XMax(_xmax)
, m_YMax(_ymax)
, m_Radius(_radius)
, m_Q(m_XMax)
{ }
};
////////////////////////////////////////////////////////////////////////////////
// Forward sweep for dilation operation
template<typename Iterator>
void voronoi_half_dilate(
int xsize, int ysize, double radius,
Iterator it, std::vector<std::vector<int> > &result)
{
VoronoiMorpho voronoi(xsize, ysize, radius);
result.assign(xsize, std::vector<int>());
for (int i = 0; i < xsize; ++i)
{
voronoi.removeInactiveSegments(i);
vor_assert(it[i].size() % 2 == 0);
for (int k = (int) it[i].size() - 2; k >= 0; k -= 2)
{
voronoi.insertSegment(i, it[i][k], it[i][k + 1] - 1);
}
voronoi.getLine(i, result[i], ysize);
}
}
// -----------------------------------------------------------------------------
// Forward sweep for erosion operation
template<typename Iterator>
void voronoi_half_erode(
int xsize, int ysize, double radius,
Iterator it, std::vector<std::vector<int> > &result)
{
VoronoiMorpho voronoi(xsize, ysize + 1, radius);
result.assign(xsize, std::vector<int>());
if (xsize == 0) { return; }
// Extra segment before first row
voronoi.insertSegment(-1, -1, ysize);
for (int i = 0; i < xsize; ++i)
{
voronoi.removeInactiveSegments(i);
vor_assert(it[i].size() % 2 == 0);
// Flip segments + insert an extra one at the extremities
int j2 = ysize;
for (int k = (int) it[i].size() - 2; k >= 0; k -= 2)
{
voronoi.insertSegment(i, it[i][k + 1], j2);
j2 = it[i][k] - 1;
}
voronoi.insertSegment(i, -1, j2);
// Retrieve result
voronoi.getLine(i, result[i], ysize);
}
}
////////////////////////////////////////////////////////////////////////////////
} // namespace voroffset
| [
"jeremie.dumas@ens-lyon.org"
] | jeremie.dumas@ens-lyon.org |
ccf0054034c7227ea925437fc8fc5bbcae08e571 | 06bea69d7e3ef28796afc03593eeeeb3879e50bd | /simulation.cpp | 33429861237260e000ca6cc28125503ce9e1180d | [
"Apache-2.0"
] | permissive | cphyc/MHD_simulation | 5c91ae5786fd621f8adb1b88ac02bcfd3ab4469d | 235428190ca3e3f56d79f25cc172235143e90f0d | refs/heads/master | 2021-01-01T06:39:11.740355 | 2014-06-05T04:28:18 | 2014-06-05T04:28:18 | 19,848,630 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,653 | cpp | #include <iostream>
#include <fstream>
#include <array>
#include <cmath>
#include <string>
#include "classes.hpp"
#include "misc.hpp"
Simulation::Simulation (int save_freq, int save_freq_growth,
int max_niter, double max_time,
double init_time, int init_niter,
double dt_security, double dt_additional_cfl_security,
double init_dt){
this->save_freq = save_freq;
this->t = init_time;
this->niter = init_niter;
this->save_freq_growth = save_freq_growth;
this->max_niter = max_niter;
this->max_time = max_time;
this->dt_security = dt_security;
this->dt_additional_cfl_security = dt_additional_cfl_security;
this->dt = init_dt;
T = new Temp(0, 0, this);
w = new Vort(0, 0, this);
psi = new Stream(0, 0, this);
}
// Get an array of T, w, psi and return a string containing :
// T0 w0 psi0 T1 w1 psi1 ... Tn wn psin
void Simulation::dump(){
// make a FFT transform
do_FFT();
// write the header
std::cout << "# time\t" << t << std::endl;
std::cout << "# niter\t" << niter << std::endl;
// count the columns
std::cout << "# Cols ";
for (int nc = 1; nc < (NMAX-1)*4+1; nc++)
std::cout << nc << "\t";
std::cout << std::endl;
// print the title
std::cout << "# Header k" ;
for (int kx = 0; kx < NX; kx++)
std::cout << "\tT(x=" << kx << ")\tω(x=" << kx << ")\tψ(x=" << kx << ")" ;
// get back to the next line
std::cout << "\n";
// write the data (one line = one k)
for (int k = 0; k < NZ; k++){
std::cout << k << "\t";
for (int kx = 0; kx < NX; kx++){
//std::cout << "#k:n :\t" << k <<":"<< n << "\n";
std::cout << (T->real_val[kx][k]) << "\t" ;
std::cout << (w->real_val[kx][k]) << "\t";
std::cout << (psi->real_val[kx][k]) << "\t";
}
// ended one n, we get back to the next line for the next k
std::cout<< "\n";
}
std::cout << "\n";
}
void Simulation::cfl() {
// Check for the cfl each cfl_freq
if (cfl_freq == 0 || niter % cfl_freq == 0) {
do_FFT();
dt_old = dt;
bool is_along_x;
double vmax = 0, vx = 0, vz = 0, new_dt = 0;
// get the maximum of the speed (derivative of psi)
for (int z = 1; z < NX-1; z++){
for (int x = 1; x < NX-1; x++){
vx = (this->psi->real_val[x+1][z] - this->psi->real_val[x-1][z])/(2*DX);
vz = (this->psi->real_val[x][z+1] - this->psi->real_val[x][z-1])/(2*DZ);
if (vx > vmax && vx >= vz) {
vmax = vx;
is_along_x = true;
}
else if (vz > vmax && vz > vx) {
vmax = vz;
is_along_x = false;
}
}
}
//dt = dt_security * pow(DZ,2)/4*max(1,Pr);
if (is_along_x)
new_dt= dt_additional_cfl_security * dt_security * DX/vmax;
else
new_dt= dt_additional_cfl_security * dt_security * DZ/vmax;
double dt_non_cfl = dt_security*(DZ*DZ)/(4*max(Pr,1));
if (dt_non_cfl < new_dt)
this->dt= dt_non_cfl;
std::cout << "# CFL: Updated dt from " << dt_old << " to " << dt << std::endl;
}
}
void Simulation::unset_FFT() {
w->unset_FFT();
psi->unset_FFT();
T->unset_FFT();
}
void Simulation::do_FFT() {
w->FFT();
psi->FFT();
T->FFT();
}
// Iterator of the simulation. Stops when the MAX_TIME or MAX_ITER is reached.
bool Simulation::iter(){
// Compute dt
cfl();
// Say that the FFT has not been done
unset_FFT();
// Save every save_freq except if <= 0
if (save_freq > 0 && niter % save_freq == 0) {
this->dump();
}
// Save the growth rate every save_freq_growth except if <=0
if (save_freq_growth > 0 && niter % save_freq_growth == 0){
// Growth rate calculated at a third of the heigth
int third = NZ / 3;
// Save the initial fields
if (niter == 0) {
for (int n = 1; n < NMAX; n++){
old_T[n] = T->val[n][third];
old_w[n] = w->val[n][third];
old_psi[n] = psi->val[n][third];
}
}
// Iterate over all the modes
for (int n = 1; n < NMAX; n++){
// compute log | T_old | / | T |
double gr_T = log( abs(T->val[n][third])) - log(abs(old_T[n]) );
double gr_w = log(abs(w->val[n][third])) - log(abs(old_w[n]));
double gr_psi = log(abs(psi->val[n][third])) - log(abs(old_psi[n]));
// output it
std::cout << "# Growth rate :\t" << n << "\t";
std::cout << niter << "\t" << gr_T;
std::cout << "\t" << gr_w << "\t" << gr_psi << "\n";
// save it for the next output
old_T[n] = T->val[n][third];
old_w[n] = w->val[n][third];
old_psi[n] = psi->val[n][third];
}
}
// move of one time step and check we can continue
niter ++;
t += dt;
if ((max_time > 0 && t > max_time) || (max_niter > 0 && niter > max_niter)) return false;
return true;
}
| [
"admin@cphyc.me"
] | admin@cphyc.me |
5b182112197da9271bf2e965a9c5cb9832d51885 | 5ff4719617da4cbea4fd025b2f0ba527270d3f4c | /CPP_CW2015/src/mainfunction.cpp | c1342ce0eca68d3f388fedad6b6d1fdfdb04e65d | [] | no_license | justinkong94/Y2CPP_Project | 050acb4f314c04e95d94ec6bb9c11901c3dcae43 | 2860694ff20ee4239343bd285ab27865deb8be01 | refs/heads/master | 2020-07-06T22:47:36.168622 | 2016-11-17T16:10:53 | 2016-11-17T16:10:53 | 74,043,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | cpp | #include "header.h"
#include <ctime>
#include "templates.h"
// Needs one of the following #includes, to include the class definition
#include "BouncingBallMain.h"
#include "SimpleDemo.h"
#include "Demo1Main.h"
#include "Demo2Main.h"
#include "Demo3Main.h"
#include "DemoAMain.h"
#include "Demo4Main.h"
#include "Jwk04uMain.h"
#define BASE_SCREEN_WIDTH 900
#define BASE_SCREEN_HEIGHT 600
int main(int argc, char *argv[])
{
int iResult;
// Send random number generator with current time
::srand(time(0));
// Needs just one of the two following lines:
//BouncingBallMain oMain;
//SimpleDemo oMain;
Jwk04uMain oMain;
//Demo1Main oMain;
//Demo2Main oMain;
//Demo3Main oMain;
//Demo4Main oMain;
//DemoAMain oMain;
char buf[1024];
sprintf( buf, "Alien Defender : Size %d x %d", BASE_SCREEN_WIDTH, BASE_SCREEN_HEIGHT );
iResult = oMain.Initialise( buf, BASE_SCREEN_WIDTH, BASE_SCREEN_HEIGHT, "Cornerstone Regular.ttf", 24 );
iResult = oMain.MainLoop();
oMain.Deinitialise();
return iResult;
}
| [
"justinkong24@yahoo.com"
] | justinkong24@yahoo.com |
32bc2ce126a83cdec621b77701408b71a6ed6a41 | 10dc75a6f2e8028f91673746fcc0d55cf590a2d4 | /GameEngine2/Main.cpp | 1997e4efa475031dbdf05c16639afc4b25955810 | [] | no_license | YamadaShuto/DirectXTK | 3c0bc2344c4e49810a875b47a8211695ea415650 | 943eee02113f0a0194500e3b565fcbc1fdf9a0f8 | refs/heads/master | 2021-08-24T04:01:10.794210 | 2017-12-08T00:44:27 | 2017-12-08T00:44:27 | 113,513,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | cpp | //
// Main.cpp
//
#include <windows.h>
#include <wrl/client.h>
#include <d3d11_1.h>
#include <memory>
#include "Game.h"
// Indicates to hybrid graphics systems to prefer the discrete part by default
extern "C"
{
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
std::unique_ptr<MyLibrary::Framework> framework;
HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
if (FAILED(hr))
return 1;
try {
framework = std::make_unique<Game>(hInstance, nCmdShow);
}
catch (...)
{
return 1;
}
framework->Initialize();
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
framework->Tick();
}
}
framework->Finalize();
framework.reset();
CoUninitialize();
return (int) msg.wParam;
}
// Exit helper
void ExitGame()
{
PostQuitMessage(0);
} | [
"kilito.shuto.bb@gmail.com"
] | kilito.shuto.bb@gmail.com |
c68c6596bc74604d3dc7d356c95449ee1924f4bd | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14482/function14482_schedule_3/function14482_schedule_3_wrapper.cpp | a84ddd1bbd12e195b04766f956b0da5b53f7b060 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | cpp | #include "Halide.h"
#include "function14482_schedule_3_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64, 64, 64);
Halide::Buffer<int32_t> buf01(64);
Halide::Buffer<int32_t> buf02(64, 64, 64);
Halide::Buffer<int32_t> buf03(64, 64);
Halide::Buffer<int32_t> buf04(64);
Halide::Buffer<int32_t> buf05(64, 64, 64);
Halide::Buffer<int32_t> buf06(64, 64);
Halide::Buffer<int32_t> buf07(64);
Halide::Buffer<int32_t> buf08(64, 128);
Halide::Buffer<int32_t> buf0(64, 128, 64, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14482_schedule_3(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14482/function14482_schedule_3/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
3f40bb3b9958482686e234bb43a5f56145637781 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /yuki/0001-1000/201-300/233.cpp | c2196b496ba84bfe1582c94da9f5807a773d0272 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,163 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N;
set<string> S;
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N;
FOR(i,N) cin>>s, S.insert(s);
string a,b;
a="iaaeuu";
b="nbmgr";
sort(ALL(a));
sort(ALL(b));
do {
do {
string c=" ";
FOR(i,5) c[i*2]=b[i],c[i*2+1]=a[i];
FOR(i,11) {
s=c.substr(0,i)+a[5]+c.substr(i);
if(S.count(s)==0) return _P("%s\n",s.c_str());
}
} while(next_permutation(ALL(b)));
} while(next_permutation(ALL(a)));
return _P("NO\n");
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false);
FOR(i,argc-1) s+=argv[i+1],s+='\n';
FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
f9c088a7de15bb07f51a6183abbab986bcabe9f7 | 710a0a40c31a966d224656e531e32a39b4ba985a | /Programming Languages/C++2/Arrays/Rotate_an_Array.cpp | 47f0c41a747e54bb91285a7d6e594bd62b5c5749 | [] | no_license | Lord-Aman/GFG | b0c2b8ee2a164945af7aac595caa8333bc57ac36 | 8b8ada89d1869d0f32a269146b76e6ea16630b3c | refs/heads/master | 2023-03-07T15:40:44.194695 | 2021-02-25T20:11:21 | 2021-02-25T20:11:21 | 306,515,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,309 | cpp | // Rotate an Arrays
/*
Question
1. You are given a number n, representing the size of array a.
2. You are given n numbers, representing elements of array a.
3. You are given a number k.
4. Rotate the array a, k times to the right (for positive values of k), and to
the left for negative values of k.
*/
#include <iostream>
using namespace std;
void reverse(int arr[], int low, int high){
while(low < high){
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
low++;
high--;
}
}
void Rotate(int arr[], int arrSize, int noOfRotation){
noOfRotation = noOfRotation % arrSize; // Coz, the array repeats itself after it's original length
if(noOfRotation < 0)
noOfRotation += arrSize; // We do not need to rotate inversely, just add -ve to arrSize and you will get the right answer
//Reverse first part
reverse(arr,0,arrSize - noOfRotation - 1);
//Reverse Second part
reverse(arr,arrSize - noOfRotation, arrSize -1);
//Reverse whole array
reverse(arr,0,arrSize-1);
}
int main(){
int arrSize;
cin >> arrSize;
int arr[arrSize];
for(int i=0; i < arrSize; i++)
cin >> arr[i];
int noOfRotation;
cin >> noOfRotation;
Rotate(arr,arrSize,noOfRotation);
for(int i =0; i < arrSize; i++)
cout << arr[i] << " ";
return 0;
}
| [
"aakashaman1770@gmail.com"
] | aakashaman1770@gmail.com |
45a53731a3da96ba54cada6be7bf7d857b12d796 | d688cbeeeb219d149b16b7e19fd968d3e5117c63 | /server/main.cpp | 441beb6b8043c3ca7e33d5873f7c7d2ec4133595 | [] | no_license | rc2524/Homework7 | f2227c21ec22ee6206d7ae34c657618f7e76836b | fa916cccadc39e8193f588d597a807447e86d9a4 | refs/heads/master | 2021-03-12T20:18:09.131021 | 2012-12-10T03:51:16 | 2012-12-10T03:51:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | /****************************************************************************
From Qt examples
****************************************************************************/
#include <QApplication>
#include <QtCore>
#include <stdlib.h>
#include "server.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Server server;
// server.show();
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
return app.exec();
}
| [
"richard@richard-Virtual-Machine.(none)"
] | richard@richard-Virtual-Machine.(none) |
ec65fb23241ad7bc766cdb0d3f5c2342dbc89106 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/bigneuron_siqi_stalker_v3d/lib/ITK_include/itkGiplImageIOFactory.h | 4ee764cd4fa382c2027d955601fd630da0f88c8f | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 2,213 | h | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkGiplImageIOFactory_h
#define __itkGiplImageIOFactory_h
#include "ITKIOGIPLExport.h"
#include "itkObjectFactoryBase.h"
#include "itkImageIOBase.h"
namespace itk
{
/** \class GiplImageIOFactory
* \brief Create instances of GiplImageIO objects using an object factory.
* \ingroup ITKIOGIPL
*/
class ITKIOGIPL_EXPORT GiplImageIOFactory:public ObjectFactoryBase
{
public:
/** Standard class typedefs. */
typedef GiplImageIOFactory Self;
typedef ObjectFactoryBase Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Class methods used to interface with the registered factories. */
virtual const char * GetITKSourceVersion(void) const;
virtual const char * GetDescription(void) const;
/** Method for class instantiation. */
itkFactorylessNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(GiplImageIOFactory, ObjectFactoryBase);
/** Register one factory of this type */
static void RegisterOneFactory(void)
{
GiplImageIOFactory::Pointer GiplFactory = GiplImageIOFactory::New();
ObjectFactoryBase::RegisterFactoryInternal(GiplFactory);
}
protected:
GiplImageIOFactory();
~GiplImageIOFactory();
private:
GiplImageIOFactory(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
};
} // end namespace itk
#endif
| [
"sliu4512@uni.sydney.edu.au"
] | sliu4512@uni.sydney.edu.au |
5c18fe03fcda79a56b81b8a017f2dc03f4c933d0 | 385eebbc221a5f33f3ccff4316c79d5078c89a61 | /src/qt/askpassphrasedialog.cpp | bd269ab48f48b9f66398d8941695f6e2967febb5 | [
"MIT"
] | permissive | FendiProduction/SHIELD | b5cc0da404cc2045c6e63ecc20de241e612ed7ba | 508a6f0b87eb8203597487e1b8d7b52326c70ede | refs/heads/master | 2020-03-15T22:54:03.105830 | 2018-04-05T14:06:39 | 2018-04-05T14:06:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,770 | cpp | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
case UnlockMinting:
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("SHIELD will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
case UnlockMinting:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case UnlockMinting:
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"contact@shieldx.sh"
] | contact@shieldx.sh |
3b9fc89ba07e4741a4fbffe09305eb5ccff7d5c1 | c05ec6793dc48b2e966f204989a32a65623288f9 | /src/scene/q3bsp.cpp | 46099d0ccf7bfcccaabc5d1eda5036fc85834c39 | [] | no_license | pkamenarsky/hastegame | b29741a7f2f38d51ce445f14a3dd4f656e204102 | 5320863576804e51f799bdeacf29321ed50a0962 | refs/heads/master | 2021-01-13T02:06:26.613636 | 2015-08-17T13:18:40 | 2015-08-17T13:18:40 | 40,895,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80,876 | cpp | #include <string.h>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include "../base/datablock.hh"
#include "../base/physfsfile.hh"
#include "../base/log.hh"
#include "../math/quadraticbezier.hh"
#include "../video/indexiterator.hh"
#include "../video/picloader.hh"
#include "q3bsp.hh"
#include "renderjobqueue.hh"
#include "renderquery.hh"
#include "renderer.hh"
namespace ion {
namespace scene {
///////////////////////////
// BSPRenderable methods //
///////////////////////////
Q3BSP::BSPRenderable::BSPRenderable(Q3BSP& rBSP,Renderable &rRenderable,const ion_uint32 renderableidx):
m_rQ3BSP(rBSP),m_rRenderable(rRenderable),m_Renderableindex(renderableidx)
{
m_pLeaves=new std::vector < Leaf* >;
update();
m_rRenderable.transformAlterationFunctor(this);
}
Q3BSP::BSPRenderable::~BSPRenderable()
{
clearLeafList();
delete m_pLeaves;
}
const Renderable& Q3BSP::BSPRenderable::renderable() const
{
return m_rRenderable;
}
Renderable& Q3BSP::BSPRenderable::renderable()
{
return m_rRenderable;
}
void Q3BSP::BSPRenderable::transformAltered(const bool rotationAltered,const bool positionAltered)
{
update();
}
void Q3BSP::BSPRenderable::update()
{
updateLeafList();
}
void Q3BSP::BSPRenderable::updateLeafList()
{
// First, remove all leaf entries (and remove this renderable from all leaves)
clearLeafList();
// Now, find the leaves in range, add them to the list, and add this renderable to their lists
addRenderableToLeaves(0);
}
void Q3BSP::BSPRenderable::clearLeafList()
{
for (std::vector < Leaf* >::iterator it=m_pLeaves->begin();it!=m_pLeaves->end();++it) {
Leaf* pLeaf=(*it);
std::set < ion_uint32 >::iterator itrenderable=pLeaf->m_pRenderables->find(m_Renderableindex);
if (itrenderable!=pLeaf->m_pRenderables->end()) pLeaf->m_pRenderables->erase(itrenderable);
}
m_pLeaves->clear();
}
void Q3BSP::BSPRenderable::addRenderableToLeaves(const ion_int32 nodeNum)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_rQ3BSP.m_pLeaves-(nodeNum+1);
math::Vector3f minV((float)(pLeaf->m_Mincoord[0]),(float)(pLeaf->m_Mincoord[1]),(float)(pLeaf->m_Mincoord[2]));
math::Vector3f maxV((float)(pLeaf->m_Maxcoord[0]),(float)(pLeaf->m_Maxcoord[1]),(float)(pLeaf->m_Maxcoord[2]));
minV-=m_rRenderable.transform().position();
maxV-=m_rRenderable.transform().position();
if (m_rRenderable.boundingSphere().intersectsWith(minV,maxV)) {
m_pLeaves->push_back(pLeaf);
pLeaf->m_pRenderables->insert(m_Renderableindex);
}
} else {
Q3BSP::Node *pNode=&(m_rQ3BSP.m_pNodes[nodeNum]);
math::Vector3f minV((float)(pNode->m_Mincoord[0]),(float)(pNode->m_Mincoord[1]),(float)(pNode->m_Mincoord[2]));
math::Vector3f maxV((float)(pNode->m_Maxcoord[0]),(float)(pNode->m_Maxcoord[1]),(float)(pNode->m_Maxcoord[2]));
minV-=m_rRenderable.transform().position();
maxV-=m_rRenderable.transform().position();
if (m_rRenderable.boundingSphere().intersectsWith(minV,maxV)) {
addRenderableToLeaves(pNode->m_FrontChild);
addRenderableToLeaves(pNode->m_BackChild);
}
}
}
//////////////////////
// BSPLight methods //
//////////////////////
const ion_uint32 Q3BSP::BSPLight::s_IndexPadding=1024*3;
Q3BSP::BSPLight::BSPLight(Q3BSP& rBSP,Light &rLight,const ion_uint32 lightidx):m_rQ3BSP(rBSP),m_pIndices(0),m_rLight(rLight),
m_NumActiveJobs(0),m_Lightindex(lightidx)
{
m_pLeaves=new std::vector < Leaf* >;
m_pBezierPatches=new std::vector < BezierPatch* >;
m_NumJobs=(rBSP.m_NumSurfaces==0) ? 1 : rBSP.m_NumSurfaces;
m_pJobs=new Renderjob*[m_NumJobs];
m_pActiveJobs=new Renderjob*[m_NumJobs];
for (ion_uint32 j=0;j<m_NumJobs;++j) {
m_pJobs[j]=new Renderjob(m_rQ3BSP);
m_pActiveJobs[j]=new Renderjob(m_rQ3BSP);
}
rLight.renderablelist().clear();
rLight.renderableIndicesList().clear();
rLight.renderablelist().addRenderable(m_rQ3BSP);
rLight.renderableIndicesList().addIndex(0);
update();
m_rLight.transformAlterationFunctor(this);
}
Q3BSP::BSPLight::~BSPLight()
{
clearLeafList();
for (ion_uint32 j=0;j<m_NumJobs;++j) {
delete m_pActiveJobs[j];
delete m_pJobs[j];
}
delete [] m_pActiveJobs;
delete [] m_pJobs;
delete m_pBezierPatches;
delete m_pLeaves;
if (m_pIndices) delete m_pIndices;
}
ion_uint32 Q3BSP::BSPLight::numLightingjobs() const
{
return m_NumActiveJobs+(ion_uint32)(m_pBezierPatches->size());
}
Renderjob* Q3BSP::BSPLight::lightingjob(const ion_uint32 jobnr)
{
if (jobnr<m_NumActiveJobs)
return m_pActiveJobs[jobnr];
else
return (*m_pBezierPatches)[jobnr-m_NumActiveJobs]->m_pRenderjob;
}
const Light& Q3BSP::BSPLight::light() const
{
return m_rLight;
}
Light& Q3BSP::BSPLight::light()
{
return m_rLight;
}
void Q3BSP::BSPLight::transformAltered(const bool rotationAltered,const bool positionAltered)
{
update();
}
void Q3BSP::BSPLight::update()
{
//std::set<ion_uint32> renderableIndices;
updateLeafList(/*renderableIndices*/);
/*for (std::set<ion_uint32>::iterator it=renderableIndices.begin();it!=renderableIndices.end();++it) {
ion_uint32 ridx=(*it);
Renderable &rRenderable=(*(m_rQ3BSP.m_pRenderables))[ridx-1]->renderable();
m_rLight.renderablelist().addRenderable(rRenderable);
m_rLight.renderableIndicesList().addIndex(ridx);
}*/
}
/*void Q3BSP::BSPLight::newLightindex(const ion_uint32 lightidx)
{
m_Lightindex=lightidx;
addLightToLeaves(0);
}*/
//#define DEBUG_CHECK_BSPLIGHT_INDEXSTREAM_BOUNDARIES
void Q3BSP::BSPLight::updateLeafList(/*std::set<ion_uint32> &renderableIndices*/)
{
// First, remove all leaf entries (and remove this light from all leaves)
clearLeafList();
// Now, find the leaves in range, add them to the list, and add this light to their lists
ion_uint32 numIndices=0; // This counts the total amount of indices of all leaffaces
// This is necessary for eventual IB resize
std::vector < bool > alreadyVisible;
alreadyVisible.resize(m_rQ3BSP.m_NumFaces);
addLightToLeaves(0,numIndices,alreadyVisible/*,renderableIndices*/);
ion_uint32 currentNumIndices=0;
if (m_pIndices)
currentNumIndices=(m_pIndices->capacity()==0) ? s_IndexPadding : ((m_pIndices->capacity()-1)/s_IndexPadding+1)*s_IndexPadding;
#ifdef DEBUG_CHECK_BSPLIGHT_INDEXSTREAM_BOUNDARIES
base::logstream() << numIndices << " /// " << currentNumIndices << "\n";
#endif
numIndices=(numIndices==0) ? s_IndexPadding : (numIndices/s_IndexPadding+1)*s_IndexPadding;
if (numIndices>currentNumIndices) { // TODO: Should this reallocate the indexstream only when the amount of indices increases?
#ifdef DEBUG_CHECK_BSPLIGHT_INDEXSTREAM_BOUNDARIES
base::logstream() << "m_rQ3BSP.renderer()->videodevice()->createIndexstream()" << currentNumIndices << " -> " << numIndices << "\n";
#endif
if (m_pIndices) delete m_pIndices;
m_pIndices=m_rQ3BSP.renderer()->videodevice()->createIndexstream(
numIndices,
(m_rQ3BSP.m_NumBSPVertices>65535) ? video::Indexformat_32bit : video::Indexformat_16bit,
video::Streamflags_Dynamic|video::Streamflags_Writeonly,
video::Mempool_Default
);
}
std::fill(alreadyVisible.begin(),alreadyVisible.end(),false);
m_NumActiveJobs=0;
std::vector < std::vector < Q3BSP::Face* > > faces;
faces.resize(m_NumJobs);
for (std::vector < Leaf* >::iterator itleaf=m_pLeaves->begin();itleaf!=m_pLeaves->end();++itleaf) {
Leaf *pLeaf=(*itleaf);
for (ion_int32 f=0;f<pLeaf->m_NumLeaffaces;++f) {
int faceidx=m_rQ3BSP.m_pLeaffaces[f+pLeaf->m_Leafface];
if ((faceidx<0) || (faceidx>=(int)(m_rQ3BSP.m_NumFaces))) continue;
if (alreadyVisible[faceidx]) continue;
alreadyVisible[faceidx]=true;
Q3BSP::Face &rFace=m_rQ3BSP.m_pFaces[faceidx];
if ((rFace.m_Surfaceindex<0) || (rFace.m_Surfaceindex>=(ion_int32)m_NumJobs)) continue;
if (m_rQ3BSP.m_pSurfaces[rFace.m_Surfaceindex].m_IsSky) continue;
bool fullAABB=false;
math::Vector3f minV((float)(pLeaf->m_Mincoord[0]),(float)(pLeaf->m_Mincoord[1]),(float)(pLeaf->m_Mincoord[2]));
math::Vector3f maxV((float)(pLeaf->m_Maxcoord[0]),(float)(pLeaf->m_Maxcoord[1]),(float)(pLeaf->m_Maxcoord[2]));
float rr=m_rLight.range()*m_rLight.range();
fullAABB=((m_rLight.transform().position()-minV).lengthSquared()<rr) &&
((m_rLight.transform().position()-maxV).lengthSquared()<rr); // If the entire AABB is in range, add all lights
if ((rFace.m_Type==Q3BSP::Facetype_Polygon) || (rFace.m_Type==Q3BSP::Facetype_Mesh)) {
bool inLight=fullAABB;
// TODO: Uncomment this and include a WORKING sphere-polygon test
// (One that also checks for plane-polygonarea intersections etc.)
if (!fullAABB) {
/*for (ion_int32 j=0;j<rFace.m_NumMeshverts;++j) {
ion_uint32 idx=m_rQ3BSP.m_pMeshverts[rFace.m_FirstMeshvert+j]+rFace.m_FirstVertex;
const math::Vector3f &v=m_rQ3BSP.m_pBSPVertices[idx].m_Position;
float d=(m_rLight.transform().position()-v).lengthSquared();
if (d<m_rLight.range()*m_rLight.range()) {
inLight=true;
break;
}
}*/
for (ion_int32 j=0;j<rFace.m_NumMeshverts/3;++j) {
const math::Vector3f* vv[3];
for (int iij=0;iij<3;++iij) {
ion_uint32 idx=m_rQ3BSP.m_pMeshverts[rFace.m_FirstMeshvert+j*3+iij]+rFace.m_FirstVertex;
//const math::Vector3f &v1=m_rQ3BSP.m_pBSPVertices[idx].m_Position;
vv[iij]=&(m_rQ3BSP.m_pBSPVertices[idx].m_Position);
}
if (sphereTriangleIntersection(m_rLight.range(),m_rLight.transform().position(),
*(vv[0]),*(vv[1]),*(vv[2]))) {
inLight=true;
break;
}
}
}
if (inLight)
faces[rFace.m_Surfaceindex].push_back(&rFace);
} else if (rFace.m_Type==Q3BSP::Facetype_Patch) {
minV=rFace.m_pBezierPatch->m_Mincoord-m_rLight.transform().position();
maxV=rFace.m_pBezierPatch->m_Maxcoord-m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV))
m_pBezierPatches->push_back(rFace.m_pBezierPatch);
}
}
}
{
ion_uint32 numTriangles=0,indexOffset=0,currentIdx=0;
m_pIndices->map(video::Map_Writeonly|video::Map_Discard);
std::vector < std::vector < Q3BSP::Face* > >::iterator itflist=faces.begin();
for (;itflist!=faces.end();++itflist) {
std::vector < Q3BSP::Face* >& rFList=(*itflist);
if (rFList.size()==0) continue;
//ion_uint32 matidx=(ion_uint32)(itflist-faces.begin());
ion_uint32 matidx=(*rFList.begin())->m_Surfaceindex;
Renderjob *pJob=m_pActiveJobs[m_NumActiveJobs];
++m_NumActiveJobs;
numTriangles=0;
for (std::vector < Q3BSP::Face* >::iterator itface=rFList.begin();itface!=rFList.end();++itface) {
Q3BSP::Face *pFace=(*itface);
for (ion_int32 j=0;j<pFace->m_NumMeshverts;++j) {
assert(currentIdx<m_pIndices->capacity());
m_pIndices->index(currentIdx,
m_rQ3BSP.m_pMeshverts[pFace->m_FirstMeshvert+j]+pFace->m_FirstVertex);
++currentIdx;
}
numTriangles+=pFace->m_NumMeshverts/3;
}
pJob->primitivestype(video::Primitives_Triangles);
pJob->indexstream(m_pIndices);
pJob->vertexstream(*(m_rQ3BSP.m_pVertices));
pJob->shader(0);
pJob->rendertargetCamera(0);
pJob->propertytable(0);
pJob->viewerDistance(0);
pJob->firstElement(0);
pJob->indexOffset(indexOffset);
pJob->numElements(numTriangles);
pJob->propertytable(&(m_rQ3BSP.m_pSurfaces[matidx].m_Material));
indexOffset+=numTriangles*3;
}
m_pIndices->unmap();
}
}
inline float angleBetweenVectors(const math::Vector3f& c,const math::Vector3f& p1,const math::Vector3f& p2) {
math::Vector3f v1=p1-c,v2=p2-c;
return acosf((v1*v2)/(v1.length()*v2.length()));
}
bool Q3BSP::BSPLight::sphereTriangleIntersection(const float radius,const math::Vector3f& center,
const math::Vector3f& p1,const math::Vector3f& p2,const math::Vector3f& p3)
{
const math::Vector3f* points[3]={&p1,&p2,&p3};
// First test if any point is within the radius
{
float rr=radius*radius;
for (int i=0;i<3;++i) {
float dist=(center-*(points[i])).lengthSquared();
if (dist<rr) return true;
}
}
// Note: n and D are plane coefficients and could be precalculated
math::Vector3f v1=p3-p1;
math::Vector3f v2=p2-p1;
/*math::Vector3f n(
v1.y*v2.z-v1.z*v2.y,
v1.z*v2.x-v1.x*v2.z,
v1.x*v2.y-v1.y*v2.x
);*/
math::Vector3f n=v1^v2;
n.normalize();
float D=p1*n;
float d=n*center-D;
if (d>radius) return false;
math::Vector3f cp=center-n*d;
float theta=angleBetweenVectors(cp,p1,p2)+angleBetweenVectors(cp,p2,p3)+angleBetweenVectors(cp,p3,p1);
// if its 2*pi, then the projected center is in the triangle
// -> polygon is in sphere
return (theta-2*3.1415926535897932384626433832795<=0.0001);
}
void Q3BSP::BSPLight::clearLeafList()
{
for (std::vector < Leaf* >::iterator it=m_pLeaves->begin();it!=m_pLeaves->end();++it) {
Leaf* pLeaf=(*it);
std::set < ion_uint32 >::iterator itlight=pLeaf->m_pLights->find(m_Lightindex);
if (itlight!=pLeaf->m_pLights->end()) pLeaf->m_pLights->erase(itlight);
}
m_pLeaves->clear();
m_pBezierPatches->clear();
}
void Q3BSP::BSPLight::addLightToLeaves(const ion_int32 nodeNum,ion_uint32& indicesCounter,std::vector < bool >& alreadyVisible/*,
std::set<ion_uint32> &renderableIndices*/)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_rQ3BSP.m_pLeaves-(nodeNum+1);
math::Vector3f minV((float)(pLeaf->m_Mincoord[0]),(float)(pLeaf->m_Mincoord[1]),(float)(pLeaf->m_Mincoord[2]));
math::Vector3f maxV((float)(pLeaf->m_Maxcoord[0]),(float)(pLeaf->m_Maxcoord[1]),(float)(pLeaf->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
/*for (std::set<ion_uint32>::iterator itridx=pLeaf->m_pRenderables->begin();itridx!=pLeaf->m_pRenderables->end();++itridx) {
ion_uint32 ridx=(*itridx);
Renderable &rRenderable=(*m_rQ3BSP.m_pRenderables)[ridx-1]->renderable();
const math::SphereVolume &sphere=rRenderable.boundingSphere();
float distSq1=(m_rLight.transform().position()-(rRenderable.transform().position()+sphere.center())).lengthSquared();
float distSq2=m_rLight.range()+sphere.radius(); distSq2*=distSq2;
if (distSq1<distSq2)
renderableIndices.insert(ridx);
}*/
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
m_pLeaves->push_back(pLeaf);
pLeaf->m_pLights->insert(m_Lightindex);
for (ion_int32 f=0;f<pLeaf->m_NumLeaffaces;++f) {
int faceidx=m_rQ3BSP.m_pLeaffaces[f+pLeaf->m_Leafface];
if ((faceidx<0) || (faceidx>=(int)(m_rQ3BSP.m_NumFaces))) continue;
if (alreadyVisible[faceidx]) continue;
alreadyVisible[faceidx]=true;
Q3BSP::Face &rFace=m_rQ3BSP.m_pFaces[faceidx];
// TODO: Support patches & billboards
if ((rFace.m_Type==Q3BSP::Facetype_Polygon) || (rFace.m_Type==Q3BSP::Facetype_Mesh))
indicesCounter+=rFace.m_NumMeshverts;
}
}
} else {
Q3BSP::Node *pNode=&(m_rQ3BSP.m_pNodes[nodeNum]);
math::Vector3f minV((float)(pNode->m_Mincoord[0]),(float)(pNode->m_Mincoord[1]),(float)(pNode->m_Mincoord[2]));
math::Vector3f maxV((float)(pNode->m_Maxcoord[0]),(float)(pNode->m_Maxcoord[1]),(float)(pNode->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
addLightToLeaves(pNode->m_FrontChild,indicesCounter,alreadyVisible/*,renderableIndices*/);
addLightToLeaves(pNode->m_BackChild,indicesCounter,alreadyVisible/*,renderableIndices*/);
}
}
}
/*void Q3BSP::BSPLight::addLightToLeaves(const ion_int32 nodeNum)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_rQ3BSP.m_pLeaves-(nodeNum+1);
math::Vector3f minV((float)(pLeaf->m_Mincoord[0]),(float)(pLeaf->m_Mincoord[1]),(float)(pLeaf->m_Mincoord[2]));
math::Vector3f maxV((float)(pLeaf->m_Maxcoord[0]),(float)(pLeaf->m_Maxcoord[1]),(float)(pLeaf->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
m_pLeaves->push_back(pLeaf);
pLeaf->m_pLights->insert(m_Lightindex);
}
} else {
Q3BSP::Node *pNode=&(m_rQ3BSP.m_pNodes[nodeNum]);
math::Vector3f minV((float)(pNode->m_Mincoord[0]),(float)(pNode->m_Mincoord[1]),(float)(pNode->m_Mincoord[2]));
math::Vector3f maxV((float)(pNode->m_Maxcoord[0]),(float)(pNode->m_Maxcoord[1]),(float)(pNode->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
addLightToLeaves(pNode->m_FrontChild);
addLightToLeaves(pNode->m_BackChild);
}
}
}*/
//////////////////////
// Progress methods //
//////////////////////
Q3BSP::Progress::Progress()
{
}
Q3BSP::Progress::~Progress()
{
}
//////////////////////////////////
// BSPVertex operator overloads //
//////////////////////////////////
Q3BSP::BSPVertex operator *(const Q3BSP::BSPVertex& a,const float f)
{
Q3BSP::BSPVertex v;
v.m_Position=a.m_Position*f;
v.m_Texcoord[0]=a.m_Texcoord[0]*f;
v.m_Texcoord[1]=a.m_Texcoord[1]*f;
v.m_Normal=a.m_Normal*f;
v.m_Tangent=a.m_Tangent*f;
v.m_Binormal=a.m_Binormal*f;
for (int i=0;i<4;++i) v.m_ColorRGBA[i]=(int)( ((float)(a.m_ColorRGBA[i]))*f );
return v;
}
Q3BSP::BSPVertex operator +(const Q3BSP::BSPVertex& a,const Q3BSP::BSPVertex& b)
{
Q3BSP::BSPVertex v;
v.m_Position=a.m_Position+b.m_Position;
v.m_Texcoord[0]=a.m_Texcoord[0]+b.m_Texcoord[0];
v.m_Texcoord[1]=a.m_Texcoord[1]+b.m_Texcoord[1];
v.m_Normal=a.m_Normal+b.m_Normal;
v.m_Tangent=a.m_Tangent+b.m_Tangent;
v.m_Binormal=a.m_Binormal+b.m_Binormal;
for (int i=0;i<4;++i) v.m_ColorRGBA[i]=a.m_ColorRGBA[i]+b.m_ColorRGBA[i];
return v;
}
//////////////////
// Leaf methods //
//////////////////
Q3BSP::Leaf::Leaf()
{
m_pLights=new std::set < ion_uint32 >;
m_pRenderables=new std::set < ion_uint32 >;
}
Q3BSP::Leaf::~Leaf()
{
delete m_pRenderables;
delete m_pLights;
}
///////////////////
// Model methods //
///////////////////
bool Q3BSP::BSPModel::isValid() const
{
return m_pIndices!=0;
}
const char* Q3BSP::BSPModel::type() const
{
return "BSPModel";
}
void Q3BSP::BSPModel::respawn(base::Streamable& source)
{
}
void Q3BSP::BSPModel::serialize(base::Streamable& dest)
{
}
ion_uint32 Q3BSP::BSPModel::numJobs() const
{
return m_NumRenderjobs;
}
Renderjob* Q3BSP::BSPModel::job(const ion_uint32 jobnr)
{
return m_pRenderjobs[jobnr];
}
void Q3BSP::BSPModel::restoreVideoResources()
{
}
Q3BSP::BSPModel::BSPModel():Renderable("BSPModel"),m_pQ3BSP(0),m_pIndices(0),m_pRenderjobs(0),m_NumRenderjobs(0)
{
}
Q3BSP::BSPModel::~BSPModel()
{
if (m_pIndices) delete m_pIndices;
if (m_pRenderjobs) {
for (ion_uint32 i=0;i<m_NumRenderjobs;++i) {
delete m_pRenderjobs[i];
}
delete [] m_pRenderjobs;
}
}
const math::SphereVolume& Q3BSP::BSPModel::boundingSphere() const
{
return m_BoundingSphere;
}
void Q3BSP::BSPModel::init(Q3BSP &rQ3BSP)
{
m_pQ3BSP=&rQ3BSP;
renderer(*(rQ3BSP.renderer()));
std::vector<std::vector< const Q3BSP::Face* > > faces;
faces.resize(rQ3BSP.m_NumSurfaces);
m_NumRenderjobs=0;
ion_uint32 numtris=0;
{
std::set <ion_uint32> tmpsss;
for (ion_int32 i=0;i<m_NumFaces;++i) {
const Q3BSP::Face &rFace=rQ3BSP.faces()[i+m_FirstFace];
if ((rFace.m_Type!=Q3BSP::Facetype_Polygon) && (rFace.m_Type!=Q3BSP::Facetype_Mesh)) continue;
numtris+=rFace.m_NumMeshverts/3;
if ((rFace.m_Surfaceindex>=0) && (rFace.m_Surfaceindex<(ion_int32)(rQ3BSP.m_NumSurfaces))) {
faces[rFace.m_Surfaceindex].push_back(&rFace);
tmpsss.insert(rFace.m_Surfaceindex);
}
}
m_NumRenderjobs=(ion_uint32)(tmpsss.size());
m_pRenderjobs=new Renderjob*[m_NumRenderjobs];
for (ion_uint32 r=0;r<m_NumRenderjobs;++r) {
m_pRenderjobs[r]=new Renderjob(*this);
}
}
//(const ion_uint32 numIndices,const Indexformat format,const ion_uint32 flags,const Memorypool pool)=0;
m_pIndices=renderer()->videodevice()->createIndexstream(numtris*3,
(rQ3BSP.numBSPVertices()<65536) ? video::Indexformat_16bit : video::Indexformat_32bit,
video::Streamflags_Writeonly,video::Mempool_Managed);
/*m_pIndices->map(video::Map_Writeonly);
video::Indexiterator idx(*m_pIndices);
for (ion_int32 i=0;i<m_NumFaces;++i) {
const Q3BSP::Face &rFace=rQ3BSP.faces()[i+m_FirstFace];
for (ion_int32 vtx=0;vtx<rFace.m_NumMeshverts;++vtx) {
idx=rQ3BSP.meshverts()[vtx+rFace.m_FirstMeshvert];
++idx;
}
}
m_pIndices->unmap();*/
math::Vector3f minc,maxc;
{
ion_uint32 numTriangles=0,indexOffset=0,currentIdx=0;
bool firstvertex=true;
Renderjob **pJobs=m_pRenderjobs;
m_pIndices->map(video::Map_Writeonly);
std::vector < std::vector < const Q3BSP::Face* > >::iterator itflist=faces.begin();
for (;itflist!=faces.end();++itflist) {
std::vector < const Q3BSP::Face* >& rFList=(*itflist);
if (rFList.size()==0) continue;
//ion_uint32 matidx=(ion_uint32)(itflist-faces.begin());
ion_uint32 matidx=(*rFList.begin())->m_Surfaceindex;
Renderjob *pJob=*pJobs;
++pJobs;
numTriangles=0;
for (std::vector < const Q3BSP::Face* >::iterator itface=rFList.begin();itface!=rFList.end();++itface) {
const Q3BSP::Face *pFace=(*itface);
for (ion_int32 j=0;j<pFace->m_NumMeshverts;++j) {
assert(currentIdx<m_pIndices->capacity());
ion_uint32 meshvertidx=rQ3BSP.m_pMeshverts[pFace->m_FirstMeshvert+j]+pFace->m_FirstVertex;
m_pIndices->index(currentIdx,meshvertidx);
++currentIdx;
math::Vector3f &vv=rQ3BSP.m_pBSPVertices[meshvertidx].m_Position;
if (firstvertex) {
minc=maxc=vv;
firstvertex=false;
} else {
if (minc.x()>vv.x()) minc.x()=vv.x();
if (minc.y()>vv.y()) minc.y()=vv.y();
if (minc.z()>vv.z()) minc.z()=vv.z();
if (maxc.x()<vv.x()) maxc.x()=vv.x();
if (maxc.y()<vv.y()) maxc.y()=vv.y();
if (maxc.z()<vv.z()) maxc.z()=vv.z();
}
}
numTriangles+=pFace->m_NumMeshverts/3;
}
pJob->primitivestype(video::Primitives_Triangles);
pJob->indexstream(m_pIndices);
pJob->vertexstream(*(rQ3BSP.m_pVertices));
pJob->shader(0);
pJob->rendertargetCamera(0);
pJob->propertytable(0);
pJob->viewerDistance(0);
pJob->firstElement(0);
pJob->indexOffset(indexOffset);
pJob->numElements(numTriangles);
pJob->propertytable(&(rQ3BSP.m_pSurfaces[matidx].m_Material));
indexOffset+=numTriangles*3;
}
m_pIndices->unmap();
}
m_BoundingSphere.center((maxc+minc)*0.5f);
m_BoundingSphere.radius((maxc-minc).length()*0.5f);
// TODO: remove this when model transformations work properly
//m_pBSPRenderable=rQ3BSP.addRenderable(*this);
}
void Q3BSP::BSPModel::rendererChanging(const bool videodeviceIsDifferent,Renderer *pNewRenderer)
{
}
struct Q3BSP::BezierList {
std::vector< BezierPatch* > m_Patches;
};
///////////////////////////////
// MAIN Q3BSP IMPLEMENTATION //
///////////////////////////////
Q3BSP::Q3BSP(const base::String& bspname,Renderer& rRenderer,Progress* pProgress,const float mapscale):Renderable(bspname),
m_pSurfaces(0),m_NumSurfaces(0),m_pPlanes(0),m_pNodes(0),m_pLeaves(0),m_pLeaffaces(0),m_pLeafbrushes(0),
m_pBSPModels(0),m_pBrushes(0),m_pBrushsides(0),m_pBSPVertices(0),m_pMeshverts(0),m_pEffects(0),m_pFaces(0),
m_pVisdata(0),m_Mapscale(mapscale),m_IsValid(false),m_UsesFrustumCulling(true),m_pBezierList(0),m_pIndices(0),
m_pVertices(0),m_pOpaqueRenderjobs(0)
{
m_AmbientColor.r(0.9f);
m_AmbientColor.g(0.9f);
m_AmbientColor.b(0.9f);
m_AmbientColor.a(1);
m_pBezierList=new BezierList;
m_pLights=new std::vector < BSPLight* >;
m_pRenderables=new std::vector < BSPRenderable* >;
renderer(rRenderer);
load(bspname,pProgress);
}
Q3BSP::~Q3BSP()
{
cleanup();
delete m_pBezierList;
delete m_pRenderables;
delete m_pLights;
}
void Q3BSP::ambientColor(const video::Color& color)
{
m_AmbientColor=color;
for (ion_uint32 surface=0;surface<m_NumSurfaces;++surface) {
m_pSurfaces[surface].m_Material.addColorRGB("ambientColor",m_AmbientColor.r(),m_AmbientColor.g(),m_AmbientColor.b());
}
}
const video::Color& Q3BSP::ambientColor() const
{
return m_AmbientColor;
}
void Q3BSP::cleanup()
{
{
for (std::vector < BSPLight* >::iterator it=m_pLights->begin();it!=m_pLights->end();++it)
delete (*it);
m_pLights->clear();
}
{
for (std::vector < BSPRenderable* >::iterator it=m_pRenderables->begin();it!=m_pRenderables->end();++it)
delete (*it);
m_pRenderables->clear();
}
if (m_pOpaqueRenderjobs!=0) {
for (ion_uint32 i=0;i<m_NumSurfaces;++i) {
delete m_pOpaqueRenderjobs[i];
}
delete [] m_pOpaqueRenderjobs;
m_pOpaqueRenderjobs=0;
}
if (m_pSurfaces!=0) {
for (ion_uint32 i=0;i<m_NumSurfaces;++i) {
video::Texture2D *pTex=0;
m_pSurfaces[i].m_Material.fetch2DTexture("diffuseTexture",pTex);
if (pTex!=0) delete pTex; pTex=0;
m_pSurfaces[i].m_Material.fetch2DTexture("normalMap",pTex);
if (pTex!=0) delete pTex; pTex=0;
}
}
if (m_pFaces!=0) {
for (ion_uint32 i=0;i<m_NumFaces;++i) {
if (m_pFaces[i].m_pBezierPatch!=0) {
delete m_pFaces[i].m_pBezierPatch->m_pIndexstream;
delete m_pFaces[i].m_pBezierPatch->m_pVertexstream;
delete m_pFaces[i].m_pBezierPatch->m_pRenderjob;
delete m_pFaces[i].m_pBezierPatch;
}
}
}
#define CLEANUPARRAY(arrayvar,countvar) { if (arrayvar!=0) delete [] (arrayvar); (arrayvar)=0; (countvar)=0; }
CLEANUPARRAY(m_pSurfaces,m_NumSurfaces);
CLEANUPARRAY(m_pPlanes,m_NumPlanes);
CLEANUPARRAY(m_pNodes,m_NumNodes);
CLEANUPARRAY(m_pLeaves,m_NumLeaves);
CLEANUPARRAY(m_pLeaffaces,m_NumLeaffaces);
CLEANUPARRAY(m_pLeafbrushes,m_NumLeafbrushes);
CLEANUPARRAY(m_pBSPModels,m_NumBSPModels);
CLEANUPARRAY(m_pBrushes,m_NumBrushes);
CLEANUPARRAY(m_pBrushsides,m_NumBrushsides);
CLEANUPARRAY(m_pBSPVertices,m_NumBSPVertices);
CLEANUPARRAY(m_pMeshverts,m_NumMeshverts);
CLEANUPARRAY(m_pEffects,m_NumEffects);
CLEANUPARRAY(m_pFaces,m_NumFaces);
CLEANUPARRAY(m_pVisdata,m_NumVisVectors);
#undef CLEANUPARRAY
if (m_pVertices!=0) delete m_pVertices; m_pVertices=0;
if (m_pIndices!=0) delete m_pIndices; m_pIndices=0;
m_IsValid=false;
}
void Q3BSP::useFrustumCulling(const bool use)
{
m_UsesFrustumCulling=use;
}
bool Q3BSP::usesFrustumCulling() const
{
return m_UsesFrustumCulling;
}
Q3BSP::BSPLight* Q3BSP::addLight(Light &rLight)
{
if (rLight.lighttype()!=video::Lighttype_Point) return 0; // TODO: support spotlights & dirlights
BSPLight *pBSPLight=new BSPLight(*this,rLight,(ion_uint32)(m_pLights->size()));
m_pLights->push_back(pBSPLight);
return pBSPLight;
}
void Q3BSP::removeLight(BSPLight &rLight)
{
std::vector<BSPLight*>::iterator itlight=std::find(m_pLights->begin(),m_pLights->end(),&rLight);
if (itlight!=m_pLights->end()) {
ion_uint32 lightindex=(ion_uint32)(itlight-m_pLights->begin());
removeLightindexFromLeaves(0,lightindex);
std::vector<BSPLight*>::iterator itlight2=m_pLights->begin();
for (;itlight2!=m_pLights->end();++itlight2) {
if (itlight2==itlight) continue;
BSPLight* pLight2=(*itlight2);
if (pLight2->m_Lightindex>lightindex)
pLight2->m_Lightindex--;
}
delete (*itlight);
m_pLights->erase(itlight);
rLight.light().transformAlterationFunctor(0);
}
}
void Q3BSP::removeLight(Light &rLight)
{
std::vector<BSPLight*>::iterator itlight=m_pLights->begin();
for (;itlight!=m_pLights->end();++itlight) {
Light *pLight=&((*itlight)->light());
if (pLight==&rLight) break;
}
if (itlight!=m_pLights->end()) {
ion_uint32 lightindex=(ion_uint32)(itlight-m_pLights->begin());
removeLightindexFromLeaves(0,lightindex);
std::vector<BSPLight*>::iterator itlight2=m_pLights->begin();
for (;itlight2!=m_pLights->end();++itlight2) {
if (itlight2==itlight) continue;
BSPLight* pLight2=(*itlight2);
if (pLight2->m_Lightindex>lightindex)
pLight2->m_Lightindex--;
}
delete (*itlight);
m_pLights->erase(itlight);
rLight.transformAlterationFunctor(0);
}
}
void Q3BSP::updateLightGeometry()
{
std::vector<BSPLight*>::iterator itlight=m_pLights->begin();
for (;itlight!=m_pLights->end();++itlight) {
BSPLight *pBSPLight=(*itlight);
pBSPLight->update();
}
}
Q3BSP::BSPRenderable* Q3BSP::addRenderable(Renderable &rRenderable)
{
BSPRenderable *pBSPRenderable=new BSPRenderable(*this,rRenderable,(ion_uint32)(m_pRenderables->size()+1)); // +1 because #0 is the BSP itself
m_pRenderables->push_back(pBSPRenderable);
return 0;
}
void Q3BSP::removeRenderable(BSPRenderable &rRenderable)
{
std::vector<BSPRenderable*>::iterator itrenderable=std::find(m_pRenderables->begin(),m_pRenderables->end(),&rRenderable);
if (itrenderable!=m_pRenderables->end()) {
ion_uint32 renderableindex=(ion_uint32)(itrenderable-m_pRenderables->begin())+1; // +1 because #0 is the BSP itself
removeRenderableindexFromLeaves(0,renderableindex);
std::vector<BSPRenderable*>::iterator itrenderable2=m_pRenderables->begin();
for (;itrenderable2!=m_pRenderables->end();++itrenderable2) {
if (itrenderable2==itrenderable) continue;
BSPRenderable* pRenderable2=(*itrenderable2);
if (pRenderable2->m_Renderableindex>renderableindex)
pRenderable2->m_Renderableindex--;
}
delete (*itrenderable);
m_pRenderables->erase(itrenderable);
rRenderable.renderable().transformAlterationFunctor(0);
}
}
void Q3BSP::removeRenderable(Renderable &rRenderable)
{
std::vector<BSPRenderable*>::iterator itrenderable=m_pRenderables->begin();
for (;itrenderable!=m_pRenderables->end();++itrenderable) {
Renderable *pRenderable=&((*itrenderable)->renderable());
if (pRenderable==&rRenderable) break;
}
if (itrenderable!=m_pRenderables->end()) {
ion_uint32 renderableindex=(ion_uint32)(itrenderable-m_pRenderables->begin())+1; // +1 because #0 is the BSP itself
removeRenderableindexFromLeaves(0,renderableindex);
std::vector<BSPRenderable*>::iterator itrenderable2=m_pRenderables->begin();
for (;itrenderable2!=m_pRenderables->end();++itrenderable2) {
if (itrenderable2==itrenderable) continue;
BSPRenderable* pRenderable2=(*itrenderable2);
if (pRenderable2->m_Renderableindex>renderableindex)
pRenderable2->m_Renderableindex--;
}
delete (*itrenderable);
m_pRenderables->erase(itrenderable);
rRenderable.transformAlterationFunctor(0);
}
}
void Q3BSP::getLeavesForNode(int nodenum, std::vector <int> &leaves)
{
const Node *node = m_pNodes + nodenum;
if(nodenum < 0)
{
leaves.push_back(-(nodenum + 1));
return;
}
getLeavesForNode(node->m_FrontChild, leaves);
getLeavesForNode(node->m_BackChild, leaves);
}
void Q3BSP::determineVisibity(Renderquery& query)
{
if (!m_IsValid) return;
query.lightlist().clear();
query.lightIndicesList().clear();
query.renderablelist().clear();
//Renderable::lightlist().clear();
query.renderablelist().addRenderable(*this);
query.renderableIndicesList().addIndex(0);
/*{
ion_uint32 l=0;
for (std::vector < BSPLight* >::iterator it=m_pLights->begin();it!=m_pLights->end();++it) {
BSPLight *pBSPLight=(*it);
Light &rLight=(pBSPLight->m_rLight);
bool add=(rLight.lighttype()==video::Lighttype_Directional);
if (!add) add=(query.camera()->frustum().checkSphere(rLight.transform().position(),rLight.range())!=math::Frustum::NotInFrustum);
if (add)
{
query.lightlist().addLight(rLight);
query.lightIndicesList().addIndex(l);
//rLight.renderablelist().addRenderable(*this);
}
++l;
}
}*/
std::vector < std::vector < const Face* > > faces;
std::vector < bool > alreadyVisible;
std::vector < bool > lightAdded,renderableAdded;
faces.resize(m_NumSurfaces);
alreadyVisible.resize(m_NumFaces);
lightAdded.resize(m_pLights->size());
renderableAdded.resize(m_pRenderables->size());
m_pBezierList->m_Patches.clear();
ion_uint32 i=0;
const Camera &camera=*(query.camera());
const Leaf& rVisLeaf=m_pLeaves[findLeaf(camera.transform().position())];
std::vector <int> r_leaves;
getLeavesForNode(0, r_leaves);
int li;
for(li = 0; li < (int)(r_leaves.size()); li++)
{
i = r_leaves[li];
// for (i=0;i<m_NumLeaves;++i) {
const Leaf& rLeaf=m_pLeaves[i];
// Check for visibility
if ((rLeaf.m_ClusterNr<0) || (rLeaf.m_Leafface<0)) continue;
if ((m_pVisdata!=0) && (rVisLeaf.m_ClusterNr!=rLeaf.m_ClusterNr))
if (!isClusterVisible(rVisLeaf.m_ClusterNr,rLeaf.m_ClusterNr)) continue;
if (m_UsesFrustumCulling) {
if (math::Frustum::NotInFrustum==camera.frustum().checkAABB(
math::Vector3f((float)(rLeaf.m_Mincoord[0]),(float)(rLeaf.m_Mincoord[1]),(float)(rLeaf.m_Mincoord[2]) ),
math::Vector3f((float)(rLeaf.m_Maxcoord[0]),(float)(rLeaf.m_Maxcoord[1]),(float)(rLeaf.m_Maxcoord[2]) ))) continue;
}
// Add lights
{
for (std::set<ion_uint32>::iterator itlidx=rLeaf.m_pLights->begin();itlidx!=rLeaf.m_pLights->end();++itlidx) {
ion_uint32 lidx=(*itlidx);
if (!lightAdded[lidx]) {
lightAdded[lidx]=true;
Light &rLight=(*m_pLights)[lidx]->m_rLight;
bool add=(rLight.lighttype()==video::Lighttype_Directional) || !m_UsesFrustumCulling;
if (!add)
add=(query.camera()->frustum().checkSphere(rLight.transform().position(),rLight.range())!=math::Frustum::NotInFrustum);
if (add) {
query.lightIndicesList().addIndex(lidx);
query.lightlist().addLight(rLight);
}
}
}
}
// Add renderables
{
for (std::set<ion_uint32>::iterator itridx=rLeaf.m_pRenderables->begin();itridx!=rLeaf.m_pRenderables->end();++itridx) {
ion_uint32 ridx=(*itridx);
if (!renderableAdded[ridx]) {
renderableAdded[ridx]=true;
Renderable &rRenderable=(*m_pRenderables)[ridx-1]->m_rRenderable; // -1 because #0 is the BSP itself
/*
const math::SphereVolume &sphere=rRenderable.boundingSphere();
math::Vector3f pos=rRenderable.transform().position()+sphere.center();
if (query.camera()->frustum().checkSphere(pos,sphere.radius()))
*/
const math::SphereVolume &sphere=rRenderable.boundingSphere();
math::Vector3f pos=rRenderable.transform().position()+sphere.center();
bool add=!m_UsesFrustumCulling;
if (!add)
add=(query.camera()->frustum().checkSphere(pos,sphere.radius())!=math::Frustum::NotInFrustum);
if (add) {
query.renderableIndicesList().addIndex(ridx);
query.renderablelist().addRenderable(rRenderable);
}
}
}
}
// Add leaf faces
for (ion_int32 j=0;j<rLeaf.m_NumLeaffaces;++j) {
if ((j+rLeaf.m_Leafface)>=(ion_int32)m_NumLeaffaces) continue;
int faceidx=m_pLeaffaces[j+rLeaf.m_Leafface];
if ((faceidx<0) || (faceidx>=(int)m_NumFaces)) continue;
if (alreadyVisible[faceidx]) continue;
alreadyVisible[faceidx]=true;
const Face& rFace=m_pFaces[faceidx];
if ((rFace.m_Surfaceindex<0) || (rFace.m_Surfaceindex>=(ion_int32)m_NumSurfaces)) continue;
if (m_pSurfaces[rFace.m_Surfaceindex].m_IsSky) continue;
switch (rFace.m_Type) {
case Facetype_Polygon:
case Facetype_Mesh:
faces[rFace.m_Surfaceindex].push_back(&rFace);
break;
case Facetype_Patch: {
if (!m_UsesFrustumCulling || math::Frustum::NotInFrustum!=camera.frustum().checkAABB(rFace.m_pBezierPatch->m_Mincoord,rFace.m_pBezierPatch->m_Maxcoord))
m_pBezierList->m_Patches.push_back(rFace.m_pBezierPatch);
} break;
default:break;
}
}
}
// Add renderables to lights
// This should be done in the PVS, but as a temporary measure, it is done here
{
for (ion_uint32 lightnr=0;lightnr<query.lightlist().numLights();++lightnr) {
Light *pLight=query.lightlist().light(lightnr);
ion_uint32 lidx=query.lightIndicesList().index(lightnr);
pLight->renderablelist().clear();
pLight->renderableIndicesList().clear();
pLight->renderablelist().addRenderable(*this);
pLight->renderableIndicesList().addIndex(0);
for (ion_uint32 renderablenr=0;renderablenr<query.renderablelist().numRenderables();++renderablenr) {
Renderable *pRenderable=query.renderablelist().renderable(renderablenr);
float distSq1=(pLight->transform().position()-(pRenderable->transform().position()+pRenderable->boundingSphere().center())).lengthSquared();
float distSq2=pLight->range()+pRenderable->boundingSphere().radius(); distSq2*=distSq2;
if (distSq1<distSq2) {
ion_uint32 ridx=query.renderableIndicesList().index(renderablenr);
pLight->renderablelist().addRenderable(*pRenderable);
pLight->renderableIndicesList().addIndex(ridx);
}
}
}
}
// Prepare the render jobs
m_pIndices->map(video::Map_Writeonly|video::Map_Discard);
video::Indexiterator idx(*m_pIndices);
ion_uint32 indexOffset=0;
m_NumVisibleTriangles=0;
m_NumOpaqueRenderjobs=0;
/*for (i=0;i<m_NumSurfaces;++i) {
ion_uint32 numTriangles=0;
const std::vector < const Face* >& f=faces[i];
for (std::vector < const Face* >::const_iterator it=f.begin();it!=f.end();++it) {
const Face& rFace=*(*it);
switch (rFace.m_Type) {
case Facetype_Polygon: {
for (ion_int32 j=0;j<rFace.m_NumMeshverts;++j) {
idx=m_pMeshverts[rFace.m_FirstMeshvert+j]+rFace.m_FirstVertex; ++idx;
}
numTriangles+=rFace.m_NumMeshverts/3;
} break;
case Facetype_Mesh: {
for (ion_int32 j=0;j<rFace.m_NumMeshverts;++j) {
idx=m_pMeshverts[rFace.m_FirstMeshvert+j]+rFace.m_FirstVertex; ++idx;
}
numTriangles+=rFace.m_NumMeshverts/3;
} break;
default:break;
}
}
m_pOpaqueRenderjobs[i]->primitivestype(video::Primitives_Triangles);
m_pOpaqueRenderjobs[i]->indexstream(m_pIndices);
m_pOpaqueRenderjobs[i]->vertexstream(*m_pVertices);
m_pOpaqueRenderjobs[i]->shader(0);
m_pOpaqueRenderjobs[i]->rendertargetCamera(0);
m_pOpaqueRenderjobs[i]->propertytable(0);
m_pOpaqueRenderjobs[i]->viewerDistance(0);
m_pOpaqueRenderjobs[i]->firstElement(0);
m_pOpaqueRenderjobs[i]->indexOffset(indexOffset);
m_pOpaqueRenderjobs[i]->numElements(numTriangles);
m_pOpaqueRenderjobs[i]->propertytable(&(m_pSurfaces[i].m_Material));
indexOffset+=numTriangles*3;
m_NumVisibleTriangles+=numTriangles;
}*/
{
ion_uint32 numTriangles=0,indexOffset=0,currentIdx=0;
Renderjob **pJobs=m_pOpaqueRenderjobs;
std::vector < std::vector < const Q3BSP::Face* > >::iterator itflist=faces.begin();
for (;itflist!=faces.end();++itflist) {
std::vector < const Q3BSP::Face* >& rFList=(*itflist);
if (rFList.size()==0) continue;
ion_uint32 matidx=(*rFList.begin())->m_Surfaceindex;
Renderjob *pJob=*pJobs;
++pJobs;
numTriangles=0;
for (std::vector < const Q3BSP::Face* >::iterator itface=rFList.begin();itface!=rFList.end();++itface) {
const Q3BSP::Face *pFace=(*itface);
for (ion_int32 j=0;j<pFace->m_NumMeshverts;++j) {
assert(currentIdx<m_pIndices->capacity());
m_pIndices->index(currentIdx,m_pMeshverts[pFace->m_FirstMeshvert+j]+pFace->m_FirstVertex);
++currentIdx;
}
numTriangles+=pFace->m_NumMeshverts/3;
}
pJob->primitivestype(video::Primitives_Triangles);
pJob->indexstream(m_pIndices);
pJob->vertexstream(*m_pVertices);
pJob->shader(0);
pJob->rendertargetCamera(0);
pJob->propertytable(0);
pJob->viewerDistance(0);
pJob->firstElement(0);
pJob->indexOffset(indexOffset);
pJob->numElements(numTriangles);
pJob->propertytable(&(m_pSurfaces[matidx].m_Material));
indexOffset+=numTriangles*3;
++m_NumOpaqueRenderjobs;
}
}
m_pIndices->unmap();
}
void Q3BSP::findInRadius(Renderquery& query,const math::Vector3f point,const float radius)
{
}
void Q3BSP::findNearest(Renderquery& query,const math::Vector3f point,const ion_uint32 maxNodes)
{
}
ion_uint32 Q3BSP::numJobs() const
{
return m_NumOpaqueRenderjobs+(ion_uint32)(m_pBezierList->m_Patches.size());
}
Renderjob* Q3BSP::job(const ion_uint32 jobnr)
{
/*if (jobnr<m_NumSurfaces)
return m_pOpaqueRenderjobs[jobnr];
else {
BezierPatch *pPatch=m_pBezierList->m_Patches[jobnr-m_NumSurfaces];
return pPatch->m_pRenderjob;
}*/
if (jobnr<m_NumOpaqueRenderjobs)
return m_pOpaqueRenderjobs[jobnr];
else {
BezierPatch *pPatch=m_pBezierList->m_Patches[jobnr-m_NumOpaqueRenderjobs];
return pPatch->m_pRenderjob;
}
}
// BUG: These methods should return BSPLight->job values
ion_uint32 Q3BSP::numLightingJobs(const ion_uint32 lightnr,const Light& rLight) const
{
return (lightnr<m_pLights->size()) ? (*m_pLights)[lightnr]->numLightingjobs() : 0;
}
Renderjob* Q3BSP::lightingjob(const ion_uint32 lightnr,const Light& rLight,const ion_uint32 jobnr)
{
return (lightnr<m_pLights->size()) ? (*m_pLights)[lightnr]->lightingjob(jobnr) : 0;
}
ion_uint32 Q3BSP::numPointlightJobs(const ion_uint32 lightnr,const Light& rLight) const
{
return numLightingJobs(lightnr,rLight);
}
Renderjob* Q3BSP::pointlightJob(const ion_uint32 lightnr,const Light& rLight,const ion_uint32 jobnr)
{
return lightingjob(lightnr,rLight,jobnr);
}
ion_uint32 Q3BSP::numDirlightJobs(const ion_uint32 lightnr,const Light& rLight) const
{
return 0;
}
Renderjob* Q3BSP::dirlightJob(const ion_uint32 lightnr,const Light& rLight,const ion_uint32 jobnr)
{
return 0;
}
ion_uint32 Q3BSP::numSpecularlightJobs(const ion_uint32 lightnr,const Light& rLight) const
{
return 0;
}
Renderjob* Q3BSP::specularlightJob(const ion_uint32 lightnr,const Light& rLight,const ion_uint32 jobnr)
{
return 0;
}
void Q3BSP::update(const Camera& camera,const Updatemode mode)
{
if (!m_IsValid) return;
// TODO: Update lights here if necessary
}
void Q3BSP::restoreVideoResources()
{
}
const char* Q3BSP::type() const
{
return "Q3BSP";
}
void Q3BSP::respawn(base::Streamable& source)
{
}
void Q3BSP::serialize(base::Streamable& dest)
{
}
bool Q3BSP::isValid() const
{
return m_IsValid;
}
////// Q3BSP world data accessors
const base::String& Q3BSP::entities() const { return m_Entities; }
const Q3BSP::Surface* Q3BSP::surfaces() const { return m_pSurfaces; }
ion_uint32 Q3BSP::numSurfaces() const { return m_NumSurfaces; }
const math::Plane* Q3BSP::planes() const { return m_pPlanes; }
ion_uint32 Q3BSP::numPlanes() const { return m_NumPlanes; }
const Q3BSP::Node* Q3BSP::nodes() const { return m_pNodes; }
ion_uint32 Q3BSP::numNodes() const { return m_NumNodes; }
const Q3BSP::Leaf* Q3BSP::leaves() const { return m_pLeaves; }
ion_uint32 Q3BSP::numLeaves() const { return m_NumLeaves; }
const ion_int32* Q3BSP::leaffaces() const { return m_pLeaffaces; }
ion_uint32 Q3BSP::numLeaffaces() const { return m_NumLeaffaces; }
const ion_int32* Q3BSP::leafbrushes() const { return m_pLeafbrushes; }
ion_uint32 Q3BSP::numLeafbrushes() const { return m_NumLeafbrushes; }
const Q3BSP::BSPModel* Q3BSP::BSPModels() const { return m_pBSPModels; }
ion_uint32 Q3BSP::numBSPModels() const { return m_NumBSPModels; }
const Q3BSP::Brush* Q3BSP::brushes() const { return m_pBrushes; }
ion_uint32 Q3BSP::numBrushes() const { return m_NumBrushes; }
const Q3BSP::Brushside* Q3BSP::brushsides() const { return m_pBrushsides; }
ion_uint32 Q3BSP::numBrushsides() const { return m_NumBrushsides; }
const Q3BSP::BSPVertex* Q3BSP::BSPVertices() const { return m_pBSPVertices; }
ion_uint32 Q3BSP::numBSPVertices() const { return m_NumBSPVertices; }
const ion_int32* Q3BSP::meshverts() const { return m_pMeshverts; }
ion_uint32 Q3BSP::numMeshverts() const { return m_NumMeshverts; }
const Q3BSP::Effect* Q3BSP::effects() const { return m_pEffects; }
ion_uint32 Q3BSP::numEffects() const { return m_NumEffects; }
const Q3BSP::Face* Q3BSP::faces() const { return m_pFaces; }
ion_uint32 Q3BSP::numFaces() const { return m_NumFaces; }
const ion_uint8* Q3BSP::visdata() const { return m_pVisdata; }
ion_uint32 Q3BSP::numVisVectors() const { return m_NumVisVectors; }
ion_uint32 Q3BSP::visvectorSize() const { return m_VisvectorSize; }
/*
void Q3BSP::BSPLight::addLightToLeaves(const ion_int32 nodeNum)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_rQ3BSP.m_pLeaves-(nodeNum+1);
math::Vector3f minV((float)(pLeaf->m_Mincoord[0]),(float)(pLeaf->m_Mincoord[1]),(float)(pLeaf->m_Mincoord[2]));
math::Vector3f maxV((float)(pLeaf->m_Maxcoord[0]),(float)(pLeaf->m_Maxcoord[1]),(float)(pLeaf->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
m_pLeaves->push_back(pLeaf);
pLeaf->m_pLights->insert(m_Lightindex);
}
} else {
Q3BSP::Node *pNode=&(m_rQ3BSP.m_pNodes[nodeNum]);
math::Vector3f minV((float)(pNode->m_Mincoord[0]),(float)(pNode->m_Mincoord[1]),(float)(pNode->m_Mincoord[2]));
math::Vector3f maxV((float)(pNode->m_Maxcoord[0]),(float)(pNode->m_Maxcoord[1]),(float)(pNode->m_Maxcoord[2]));
minV-=m_rLight.transform().position();
maxV-=m_rLight.transform().position();
if (m_rLight.boundingSphere().intersectsWith(minV,maxV)) {
addLightToLeaves(pNode->m_FrontChild);
addLightToLeaves(pNode->m_BackChild);
}
}
}
*/
void Q3BSP::removeLightindexFromLeaves(const ion_int32 nodeNum,const ion_uint32 lightindex)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_pLeaves-(nodeNum+1);
std::set<ion_uint32>::iterator itlidx=pLeaf->m_pLights->begin(),itlidxmatch=pLeaf->m_pLights->end();
while (itlidx!=pLeaf->m_pLights->end()) {
if ((*itlidx)==lightindex) itlidxmatch=itlidx;
else if ((*itlidx)>lightindex) (*itlidx)--;
itlidx++;
}
if (itlidxmatch!=pLeaf->m_pLights->end())
pLeaf->m_pLights->erase(itlidxmatch);
} else {
Q3BSP::Node *pNode=&(m_pNodes[nodeNum]);
removeLightindexFromLeaves(pNode->m_FrontChild,lightindex);
removeLightindexFromLeaves(pNode->m_BackChild,lightindex);
}
}
void Q3BSP::removeRenderableindexFromLeaves(const ion_int32 nodeNum,const ion_uint32 renderableindex)
{
if (nodeNum<0) {
Q3BSP::Leaf *pLeaf=m_pLeaves-(nodeNum+1);
std::set<ion_uint32>::iterator itridx=pLeaf->m_pRenderables->begin(),itridxmatch=pLeaf->m_pRenderables->end();
while (itridx!=pLeaf->m_pRenderables->end()) {
if ((*itridx)==renderableindex) itridxmatch=itridx;
else if ((*itridx)>renderableindex) (*itridx)--;
itridx++;
}
if (itridxmatch!=pLeaf->m_pRenderables->end())
pLeaf->m_pRenderables->erase(itridxmatch);
} else {
Q3BSP::Node *pNode=&(m_pNodes[nodeNum]);
removeRenderableindexFromLeaves(pNode->m_FrontChild,renderableindex);
removeRenderableindexFromLeaves(pNode->m_BackChild,renderableindex);
}
}
int Q3BSP::findLeaf(const math::Vector3f& camPos) const
{
int index=0;
while (index>=0) {
const Node& node=m_pNodes[index];
const math::Plane& plane=m_pPlanes[node.m_Planeindex];
// Distance from point to a plane
const float distance=(plane.normal()*camPos)-plane.distance();
index=(distance>=0) ? node.m_FrontChild : node.m_BackChild;
}
return -index - 1;
}
bool Q3BSP::isClusterVisible(const int visCluster,const int testCluster) const
{
if ((m_pVisdata==0) || (visCluster<0) || (visCluster==testCluster)) return true;
int i=(visCluster*m_VisvectorSize)+(testCluster>>3);
ion_uint8 visSet=m_pVisdata[i];
return (visSet&(1<<(testCluster&7)))!=0;
}
void Q3BSP::rendererChanging(const bool videodeviceIsDifferent,Renderer *pNewRenderer)
{
}
void Q3BSP::swizzle(math::Vector3f& v)
{
float temp=v.y();
v.y()=v.z();
v.z()=-temp;
v.x()*=-1;
}
void Q3BSP::swizzle(ion_int32 *pIntcoords)
{
ion_int32 temp=pIntcoords[1];
pIntcoords[1]=pIntcoords[2];
pIntcoords[2]=-temp;
pIntcoords[0]*=-1;
}
////// MAIN BSP LOAD METHOD
void Q3BSP::load(const base::String& bspname,Progress* pProgress)
{
base::PhysFSFile bspfile(bspname,base::PhysFSFile::OpenRead);
if (!bspfile.streamIsOk()) {
base::log("Q3BSP::load()",base::Error) << "File " << bspname << " could not be opened\n";
return;
}
char magicID[5]; magicID[4]=0;
bspfile.read(magicID,4);
if (strcmp(magicID,"IBSP")!=0) { // file is not an IBSP file
base::log("Q3BSP::load()",base::Error) << "File " << bspname << " is not a valid IBSP file\n";
return;
}
ion_int32 version; bspfile >> version;
if (version!=0x2e) { // 0x2e = Quake 3 BSP
base::log("Q3BSP::load()",base::Error) << "File " << bspname << " is not a valid Quake 3 BSP file\n";
return;
}
cleanup();
// Macro for conditioned progress report
#define REPORTPROGRESS(Stage) if (pProgress) (*pProgress)(Stage,progressStatus);
float progressStatus=0.0f;
REPORTPROGRESS(Progress::LoadingWorldData);
int i ,ii;
ion_uint32 numTriangles=0;
// Read the direntries
for (i=0;i<17;++i) {
bspfile >> m_Direntries[i].m_Offset >> m_Direntries[i].m_Length;
}
static const float entitiesProgress=0.02f;
static const float texturesProgress=0.15f; // 17
static const float planesProgress=0.04f; // 21
static const float nodesProgress=0.10f; // 31
static const float leafsProgress=0.10f; // 41
static const float leaffacesProgress=0.05f; // 46
static const float leafbrushesProgress=0.05f; // 51
static const float modelsProgress=0.05f; // 56
static const float brushesProgress=0.05f; // 61
static const float brushsidesProgress=0.02f; // 63
static const float verticesProgress=0.10f; // 73
static const float meshvertsProgress=0.05f; // 78
static const float effectsProgress=0.02f; // 80
static const float facesProgress=0.10f; // 90
static const float lightmapsProgress=0.00f; // Not used for now
static const float lightvolsProgress=0.00f; // Not used for now
static const float visdataProgress=0.05f; // 95
// The remaining percentage goes to patch tesselation
ion_uint32 numTransparentSurfaces=0;
// Read the lump contents
std::vector < Face* > patchfaces; // Temp var for patches
for (i=0;i<17;++i) {
ion_uint32 lumplen=m_Direntries[i].m_Length;
bspfile.seek(m_Direntries[i].m_Offset,base::LocalStreamable::SeekAbsolute);
switch (i) {
case Lumptype_Entities: {
char *pStr=new char[lumplen+1]; pStr[lumplen]=0;
bspfile.read(pStr,lumplen);
m_Entities=pStr;
delete [] pStr;
progressStatus+=entitiesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Textures: {
m_NumSurfaces=lumplen/(64+2*4);
m_pSurfaces=new Surface[m_NumSurfaces];
char surfname[65]; surfname[64]=0;
for (ion_uint32 j=0;j<m_NumSurfaces;++j) {
memset(surfname,0,64);
bspfile.read(surfname,64);
m_pSurfaces[j].m_Shadername=surfname;
bspfile >> m_pSurfaces[j].m_Flags >> m_pSurfaces[j].m_Contents;
m_pSurfaces[j].m_IsTransparent=false;
m_pSurfaces[j].m_IsSky=(m_pSurfaces[j].m_Shadername.STLstring().find("sky")!=std::string::npos);
//m_pSurfaces[j].m_pTexture=0;
// First try if the given file is a shader
// Then try .jpg, then .tga
// TODO: shader
bool foundShader=false;
if (!m_pSurfaces[j].m_IsSky) {
const char *ext[2]={".jpg",".tga"};
video::Texture2D *pTex=0,*pNormalmap=0;
for (ii=0;ii<2;++ii) {
base::String fn(surfname); fn+=ext[ii];
base::PhysFSFile texfile(fn,base::PhysFSFile::OpenRead);
pTex=0;
if (texfile.streamIsOk()) {
pTex=video::load2DTex(
*(renderer()->videodevice()),
fn,
texfile,
//video::Pixelformat_ARGB8888,
video::Pixelformat_Unknown,
0,0,0);
}
if (pTex!=0) {
m_pSurfaces[j].m_IsTransparent=video::pixelformatHasAlphachannel(pTex->pixelformat());
foundShader=true; break;
}
}
// Try to find normal- & gloss-maps (*_local.* & *_s.*)
if (foundShader) {
base::String nmapname=base::String(surfname)+"_local"+ext[ii];
base::String glossname=base::String(surfname)+"_s"+ext[ii];
base::PhysFSFile nmapfile(nmapname,base::PhysFSFile::OpenRead);
base::PhysFSFile glossfile(glossname,base::PhysFSFile::OpenRead);
video::SimplePicbuffer *pNMapPicbuf=video::load2DPic(nmapfile,video::Pixelformat_RGBA8888);
video::SimplePicbuffer *pGlossPicbuf=video::load2DPic(glossfile,video::Pixelformat_RGB888);
/*
if (!pNMapPicbuf) {
base::PhysFSFile nmapfile2("textures/def_local.jpg",base::PhysFSFile::OpenRead);
base::PhysFSFile glossfile2("textures/def_s.jpg",base::PhysFSFile::OpenRead);
pNMapPicbuf=video::load2DPic(nmapfile2,video::Pixelformat_RGBA8888);
pGlossPicbuf=video::load2DPic(glossfile2,video::Pixelformat_RGB888);
nmapfile2.close();
glossfile2.close();
}
*/
if (pNMapPicbuf) {
if (pGlossPicbuf) {
if ((pNMapPicbuf->width()!=pGlossPicbuf->width()) || (pNMapPicbuf->height()!=pGlossPicbuf->height())) {
video::SimplePicbuffer *pTempbuf=new video::SimplePicbuffer(pNMapPicbuf->width(),pNMapPicbuf->height(),video::Pixelformat_RGB888);
pTempbuf->transfer(*pGlossPicbuf);
delete pGlossPicbuf;
pGlossPicbuf=pTempbuf;
}
}
for (ion_uint32 y=0;y<pNMapPicbuf->height();++y) {
for (ion_uint32 x=0;x<pNMapPicbuf->width();++x) {
ion_uint8 rgba[2][4];
pNMapPicbuf->getpixelUint8(x,y,rgba[0][0],rgba[0][1],rgba[0][2],rgba[0][3]);
if (pGlossPicbuf)
pGlossPicbuf->getpixelUint8(x,y,rgba[1][0],rgba[1][1],rgba[1][2],rgba[1][3]);
else rgba[1][0]=0xff;
pNMapPicbuf->putpixelUint8(x,y,rgba[0][0],rgba[0][1],rgba[0][2],rgba[1][0]);
}
}
pNormalmap=renderer()->videodevice()->create2DTexture(base::String(surfname)+"_nmap",pNMapPicbuf->width(),
pNMapPicbuf->height(),0,0,video::Pixelformat_RGBA8888,video::Mempool_Managed);
pNormalmap->generateMipmaps(*pNMapPicbuf);
delete pNMapPicbuf;
}
if (pGlossPicbuf) delete pGlossPicbuf;
}
m_pSurfaces[j].m_Material.addColorRGB("ambientColor",
m_AmbientColor.r(),m_AmbientColor.g(),m_AmbientColor.b());
if (pTex!=0)
m_pSurfaces[j].m_Material.add2DTexture("diffuseTexture",pTex);
if (pNormalmap!=0)
m_pSurfaces[j].m_Material.add2DTexture("normalMap",pNormalmap);
}
//if (!foundShader)
// base::log("Q3BSP::load()",base::Warning) << "could not find shader " << surfname << "\n";
progressStatus+=texturesProgress*(float)(j)/(float)(m_NumSurfaces-1);
REPORTPROGRESS(Progress::LoadingWorldData);
}
base::logstream() << m_NumSurfaces << " surfaces\n";
} break;
case Lumptype_Planes: {
m_NumPlanes=lumplen/(4*4);
m_pPlanes=new math::Plane[m_NumPlanes];
for (ion_uint32 j=0;j<m_NumPlanes;++j) {
float f[4];
bspfile >> f[0] >> f[1] >> f[2] >> f[3];
m_pPlanes[j].a(f[0]);
m_pPlanes[j].b(f[1]);
m_pPlanes[j].c(f[2]);
m_pPlanes[j].d(f[3]*m_Mapscale);
swizzle(m_pPlanes[j].normal());
}
progressStatus+=planesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Nodes: {
m_NumNodes=lumplen/(4+4*2+4*3+4*3);
m_pNodes=new Node[m_NumNodes];
for (ion_uint32 j=0;j<m_NumNodes;++j) {
bspfile >> m_pNodes[j].m_Planeindex;
bspfile >> m_pNodes[j].m_FrontChild >> m_pNodes[j].m_BackChild;
bspfile >> m_pNodes[j].m_Mincoord[0] >> m_pNodes[j].m_Mincoord[1] >> m_pNodes[j].m_Mincoord[2];
bspfile >> m_pNodes[j].m_Maxcoord[0] >> m_pNodes[j].m_Maxcoord[1] >> m_pNodes[j].m_Maxcoord[2];
swizzle(m_pNodes[j].m_Mincoord);
swizzle(m_pNodes[j].m_Maxcoord);
{
ion_int32 ii;
ii=m_pNodes[j].m_Mincoord[0]; m_pNodes[j].m_Mincoord[0]=m_pNodes[j].m_Maxcoord[0]; m_pNodes[j].m_Maxcoord[0]=ii;
ii=m_pNodes[j].m_Mincoord[2]; m_pNodes[j].m_Mincoord[2]=m_pNodes[j].m_Maxcoord[2]; m_pNodes[j].m_Maxcoord[2]=ii;
}
m_pNodes[j].m_Mincoord[0]=(ion_int32)(m_pNodes[j].m_Mincoord[0]*m_Mapscale);
m_pNodes[j].m_Mincoord[1]=(ion_int32)(m_pNodes[j].m_Mincoord[1]*m_Mapscale);
m_pNodes[j].m_Mincoord[2]=(ion_int32)(m_pNodes[j].m_Mincoord[2]*m_Mapscale);
m_pNodes[j].m_Maxcoord[0]=(ion_int32)(m_pNodes[j].m_Maxcoord[0]*m_Mapscale);
m_pNodes[j].m_Maxcoord[1]=(ion_int32)(m_pNodes[j].m_Maxcoord[1]*m_Mapscale);
m_pNodes[j].m_Maxcoord[2]=(ion_int32)(m_pNodes[j].m_Maxcoord[2]*m_Mapscale);
progressStatus+=nodesProgress*(float)(j)/(float)(m_NumNodes-1);
REPORTPROGRESS(Progress::LoadingWorldData);
}
} break;
case Lumptype_Leafs: {
m_NumLeaves=lumplen/(4+4*2+4*3+4*3);
m_pLeaves=new Leaf[m_NumLeaves];
for (ion_uint32 j=0;j<m_NumLeaves;++j) {
bspfile >> m_pLeaves[j].m_ClusterNr >> m_pLeaves[j].m_AreaportalArea;
bspfile >> m_pLeaves[j].m_Mincoord[0] >> m_pLeaves[j].m_Mincoord[1] >> m_pLeaves[j].m_Mincoord[2];
bspfile >> m_pLeaves[j].m_Maxcoord[0] >> m_pLeaves[j].m_Maxcoord[1] >> m_pLeaves[j].m_Maxcoord[2];
bspfile >> m_pLeaves[j].m_Leafface >> m_pLeaves[j].m_NumLeaffaces;
bspfile >> m_pLeaves[j].m_Leafbrush >> m_pLeaves[j].m_NumLeafbrushes;
swizzle(m_pLeaves[j].m_Mincoord);
swizzle(m_pLeaves[j].m_Maxcoord);
{
ion_int32 ii;
ii=m_pLeaves[j].m_Mincoord[0]; m_pLeaves[j].m_Mincoord[0]=m_pLeaves[j].m_Maxcoord[0]; m_pLeaves[j].m_Maxcoord[0]=ii;
ii=m_pLeaves[j].m_Mincoord[2]; m_pLeaves[j].m_Mincoord[2]=m_pLeaves[j].m_Maxcoord[2]; m_pLeaves[j].m_Maxcoord[2]=ii;
}
m_pLeaves[j].m_Mincoord[0]=(ion_int32)((float)(m_pLeaves[j].m_Mincoord[0])*m_Mapscale);
m_pLeaves[j].m_Mincoord[1]=(ion_int32)((float)(m_pLeaves[j].m_Mincoord[1])*m_Mapscale);
m_pLeaves[j].m_Mincoord[2]=(ion_int32)((float)(m_pLeaves[j].m_Mincoord[2])*m_Mapscale);
m_pLeaves[j].m_Maxcoord[0]=(ion_int32)((float)(m_pLeaves[j].m_Maxcoord[0])*m_Mapscale);
m_pLeaves[j].m_Maxcoord[1]=(ion_int32)((float)(m_pLeaves[j].m_Maxcoord[1])*m_Mapscale);
m_pLeaves[j].m_Maxcoord[2]=(ion_int32)((float)(m_pLeaves[j].m_Maxcoord[2])*m_Mapscale);
progressStatus+=leafsProgress*(float)(j)/(float)(m_NumLeaves-1);
REPORTPROGRESS(Progress::LoadingWorldData);
}
} break;
case Lumptype_Leaffaces: {
m_NumLeaffaces=lumplen/4;
m_pLeaffaces=new ion_int32[m_NumLeaffaces];
bspfile.read(m_pLeaffaces,m_NumLeaffaces*4);
progressStatus+=leaffacesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Leafbrushes: {
m_NumLeafbrushes=lumplen/4;
m_pLeafbrushes=new ion_int32[m_NumLeafbrushes];
bspfile.read(m_pLeafbrushes,m_NumLeafbrushes*4);
progressStatus+=leafbrushesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Models: {
m_NumBSPModels=lumplen/(3*4+3*4+4*4);
m_pBSPModels=new BSPModel[m_NumBSPModels];
for (ion_uint32 j=0;j<m_NumBSPModels;++j) {
bspfile >> m_pBSPModels[j].m_Mincoord[0] >> m_pBSPModels[j].m_Mincoord[1] >> m_pBSPModels[j].m_Mincoord[2];
bspfile >> m_pBSPModels[j].m_Maxcoord[0] >> m_pBSPModels[j].m_Maxcoord[1] >> m_pBSPModels[j].m_Maxcoord[2];
bspfile >> m_pBSPModels[j].m_FirstFace >> m_pBSPModels[j].m_NumFaces;
bspfile >> m_pBSPModels[j].m_FirstBrush >> m_pBSPModels[j].m_NumBrushes;
swizzle(m_pBSPModels[j].m_Mincoord);
swizzle(m_pBSPModels[j].m_Maxcoord);
{
float ii;
ii=m_pBSPModels[j].m_Mincoord[0]; m_pBSPModels[j].m_Mincoord[0]=m_pBSPModels[j].m_Maxcoord[0]; m_pBSPModels[j].m_Maxcoord[0]=ii;
ii=m_pBSPModels[j].m_Mincoord[2]; m_pBSPModels[j].m_Mincoord[2]=m_pBSPModels[j].m_Maxcoord[2]; m_pBSPModels[j].m_Maxcoord[2]=ii;
}
m_pBSPModels[j].m_Mincoord*=m_Mapscale;
m_pBSPModels[j].m_Maxcoord*=m_Mapscale;
progressStatus+=modelsProgress*(float)(j)/(float)(m_NumBSPModels-1);
REPORTPROGRESS(Progress::LoadingWorldData);
}
} break;
case Lumptype_Brushes: {
m_NumBrushes=lumplen/(3*4);
m_pBrushes=new Brush[m_NumBrushes];
for (ion_uint32 j=0;j<m_NumBrushes;++j) {
bspfile >> m_pBrushes[j].m_FirstBrushside >> m_pBrushes[j].m_NumBrushsides;
bspfile >> m_pBrushes[j].m_Surfaceindex;
progressStatus+=brushesProgress*(float)(j)/(float)(m_NumBrushes-1);
REPORTPROGRESS(Progress::LoadingWorldData);
}
} break;
case Lumptype_Brushsides: {
m_NumBrushsides=lumplen/(2*4);
m_pBrushsides=new Brushside[m_NumBrushsides];
for (ion_uint32 j=0;j<m_NumBrushsides;++j) {
bspfile >> m_pBrushsides[j].m_Planeindex >> m_pBrushsides[j].m_Surfaceindex;
}
progressStatus+=brushsidesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Vertices: {
m_NumBSPVertices=lumplen/(3*4+2*2*4+3*4+1*4);
m_pBSPVertices=new BSPVertex[m_NumBSPVertices];
for (ion_uint32 j=0;j<m_NumBSPVertices;++j) {
bspfile >> m_pBSPVertices[j].m_Position[0] >> m_pBSPVertices[j].m_Position[1] >> m_pBSPVertices[j].m_Position[2];
bspfile >> m_pBSPVertices[j].m_Texcoord[0][0] >> m_pBSPVertices[j].m_Texcoord[0][1];
bspfile >> m_pBSPVertices[j].m_Texcoord[1][0] >> m_pBSPVertices[j].m_Texcoord[1][1];
bspfile >> m_pBSPVertices[j].m_Normal[0] >> m_pBSPVertices[j].m_Normal[1] >> m_pBSPVertices[j].m_Normal[2];
ion_uint8 color[4];
bspfile.read(color,4);
m_pBSPVertices[j].m_ColorRGBA[0]=color[0];
m_pBSPVertices[j].m_ColorRGBA[1]=color[1];
m_pBSPVertices[j].m_ColorRGBA[2]=color[2];
m_pBSPVertices[j].m_ColorRGBA[3]=color[3];
swizzle(m_pBSPVertices[j].m_Position);
swizzle(m_pBSPVertices[j].m_Normal);
m_pBSPVertices[j].m_Position*=m_Mapscale;
}
progressStatus+=verticesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Meshverts: {
m_NumMeshverts=lumplen/4;
m_pMeshverts=new ion_int32[m_NumMeshverts];
bspfile.read(m_pMeshverts,m_NumMeshverts*4);
progressStatus+=meshvertsProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Effects: {
m_NumEffects=lumplen/(64+4+4);
m_pEffects=new Effect[m_NumEffects];
ion_uint32 dwtemp;
char effectname[65]; effectname[64]=0;
for (ion_uint32 j=0;j<m_NumEffects;++j) {
memset(effectname,0,64);
bspfile.read(effectname,64);
m_pEffects[j].m_Name=effectname;
bspfile >> m_pEffects[j].m_Brushindex >> dwtemp;
}
progressStatus+=effectsProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Faces: {
m_NumFaces=lumplen/(8*4+2*4+2*4+3*4+2*3*4+3*4+2*4);
m_pFaces=new Face[m_NumFaces];
for (ion_uint32 j=0;j<m_NumFaces;++j) {
bspfile >> m_pFaces[j].m_Surfaceindex >> m_pFaces[j].m_Effectindex;
bspfile >> m_pFaces[j].m_Type >> m_pFaces[j].m_FirstVertex;
bspfile >> m_pFaces[j].m_NumVertices >> m_pFaces[j].m_FirstMeshvert >> m_pFaces[j].m_NumMeshverts;
bspfile >> m_pFaces[j].m_Lightmapindex >> m_pFaces[j].m_LightmapStart[0] >> m_pFaces[j].m_LightmapStart[1];
bspfile >> m_pFaces[j].m_LightmapSize[0] >> m_pFaces[j].m_LightmapSize[1];
bspfile >> m_pFaces[j].m_LightmapOrigin[0] >> m_pFaces[j].m_LightmapOrigin[1] >> m_pFaces[j].m_LightmapOrigin[2];
bspfile >> m_pFaces[j].m_SVector[0] >> m_pFaces[j].m_SVector[1] >> m_pFaces[j].m_SVector[2];
bspfile >> m_pFaces[j].m_TVector[0] >> m_pFaces[j].m_TVector[1] >> m_pFaces[j].m_TVector[2];
bspfile >> m_pFaces[j].m_Normal[0] >> m_pFaces[j].m_Normal[1] >> m_pFaces[j].m_Normal[2];
bspfile >> m_pFaces[j].m_Patchsize[0] >> m_pFaces[j].m_Patchsize[1];
m_pFaces[j].m_pBezierPatch=0;
if ((m_pFaces[j].m_Surfaceindex>=0) && (m_pFaces[j].m_Surfaceindex<(ion_int32)m_NumSurfaces)) {
if (m_pSurfaces[m_pFaces[j].m_Surfaceindex].m_IsTransparent)
++numTransparentSurfaces;
}
swizzle(m_pFaces[j].m_SVector);
swizzle(m_pFaces[j].m_TVector);
switch (m_pFaces[j].m_Type) {
case Facetype_Polygon:
numTriangles+=m_pFaces[j].m_NumMeshverts/3;
break;
case Facetype_Mesh:
numTriangles+=m_pFaces[j].m_NumMeshverts/3;
break;
case Facetype_Patch: patchfaces.push_back(&m_pFaces[j]); break;
default:break;
}
}
base::logstream() << numTransparentSurfaces << " transparent faces\n";
progressStatus+=facesProgress; REPORTPROGRESS(Progress::LoadingWorldData);
} break;
case Lumptype_Visdata:
if (lumplen>0) {
bspfile >> m_NumVisVectors >> m_VisvectorSize;
m_pVisdata=new ion_uint8[m_NumVisVectors*m_VisvectorSize];
bspfile.read(m_pVisdata,m_NumVisVectors*m_VisvectorSize);
progressStatus+=visdataProgress; REPORTPROGRESS(Progress::LoadingVisibilityData);
} break;
default:break;
}
}
video::Vertexformat vf;
vf.addEntry(video::VertexFormatEntry_Position,video::VertexFormatSemantic_Position);
vf.addEntry(video::VertexFormatEntry_Normal,video::VertexFormatSemantic_Normal);
vf.addEntry(video::VertexFormatEntry_Diffuse,video::VertexFormatSemantic_None);
vf.addEntry(video::VertexFormatEntry_Texcoord2D,video::VertexFormatSemantic_Texcoord);
//vf.addEntry(video::VertexFormatEntry_Texcoord2D,video::VertexFormatSemantic_Texcoord);
vf.addEntry(video::VertexFormatEntry_Texcoord3D,video::VertexFormatSemantic_Tangent);
vf.addEntry(video::VertexFormatEntry_Texcoord3D,video::VertexFormatSemantic_Binormal);
base::logstream() << "Tesselating " << (unsigned long)(patchfaces.size()) << " patches...\n";
// Tesselate the bezier patches
{
const int level=1;
for (std::vector< Face* >::iterator it=patchfaces.begin();it!=patchfaces.end();++it) {
Face* pFace=(*it);
BSPVertex *pControlPoints=&m_pBSPVertices[pFace->m_FirstVertex];
// Calculate tangent space vectors on control points
{
int u,v;
for (v=0;v<pFace->m_Patchsize[1];++v) {
int v2=(v+1)%pFace->m_Patchsize[1];
for (u=0;u<pFace->m_Patchsize[0];++u) {
int u2=(u+1)%pFace->m_Patchsize[0];
int ii;
math::Vector3f pVecXYZ[3];
math::Vector2f pVecUV[3];
BSPVertex *pPoints[3]={
&pControlPoints[u+v*pFace->m_Patchsize[0]],
&pControlPoints[u2+v*pFace->m_Patchsize[0]],
&pControlPoints[u+v2*pFace->m_Patchsize[0]]
};
for (ii=0;ii<3;++ii) {
pVecXYZ[ii]=pPoints[ii]->m_Position;
pVecUV[ii]=pPoints[ii]->m_Texcoord[0];
}
math::Plane planes[3];
for (ii=0;ii<3;++ii) {
math::Vector3f nvec[2];
const math::Vector3f &v0=pVecXYZ[0];
const math::Vector3f &v1=pVecXYZ[1];
const math::Vector3f &v2=pVecXYZ[2];
nvec[0]=math::Vector3f(
(v0[ii])-(v1[ii]),
pVecUV[0].x()-pVecUV[1].x(),
pVecUV[0].y()-pVecUV[1].y()
);
nvec[1]=math::Vector3f(
v0[ii]-v2[ii],
pVecUV[0].x()-pVecUV[2].x(),
pVecUV[0].y()-pVecUV[2].y()
);
const float *pXYZ=pVecXYZ[0];
planes[ii].normal(nvec[0]^nvec[1]);
planes[ii].d(
(const math::Vector3f &)(planes[ii].normal())
*
(const math::Vector3f &)(math::Vector3f(pXYZ[ii],pVecUV[0].x(),pVecUV[0].y()))
);
}
math::Vector3f tangent,binormal;
for (ii=0;ii<3;++ii) {
tangent[ii]=-planes[ii].b()/planes[ii].a();
binormal[ii]=-planes[ii].c()/planes[ii].a();
}
for (ii=0;ii<3;++ii) {
pPoints[ii]->m_Tangent+=tangent;
pPoints[ii]->m_Binormal+=binormal;
}
}
}
}
std::vector < std::vector < BSPVertex > > vrows,urows;
int u,v;
for (v=0;v<pFace->m_Patchsize[1];++v) {
std::vector < BSPVertex > row=math::calculateQuadraticBezier(
&pControlPoints[v*pFace->m_Patchsize[0]],pFace->m_Patchsize[0],level);
vrows.push_back(row);
}
BSPVertex* pCPoints=new BSPVertex[pFace->m_Patchsize[1]];
for (u=0;u<(int)(vrows[0].size());++u) {
for (v=0;v<pFace->m_Patchsize[1];++v)
pCPoints[v]=vrows[v][u];
std::vector < BSPVertex > row=math::calculateQuadraticBezier(
pCPoints,pFace->m_Patchsize[1],level);
urows.push_back(row);
}
delete [] pCPoints;
BezierPatch *pBezierPatch=new BezierPatch;
pFace->m_pBezierPatch=pBezierPatch;
int usize=(int)(urows.size());
int vsize=(int)(urows[0].size());
bool firstPoint=true;
pBezierPatch->m_pVertexstream=renderer()->videodevice()->createVertexstream(
usize*vsize,vf,video::Streamflags_Writeonly,video::Mempool_Managed);
pBezierPatch->m_pVertexstream->map(video::Map_Writeonly);
video::Vertexiterator viterator(*(pBezierPatch->m_pVertexstream));
for (std::vector < std::vector < BSPVertex > >::iterator itrow=urows.begin();itrow!=urows.end();++itrow) {
std::vector < BSPVertex >& row=(*itrow);
for (std::vector < BSPVertex >::iterator itpoint=row.begin();itpoint!=row.end();++itpoint) {
BSPVertex& point=(*itpoint);
if (firstPoint) {
pBezierPatch->m_Mincoord=pBezierPatch->m_Maxcoord=point.m_Position;
firstPoint=false;
} else {
if (pBezierPatch->m_Mincoord.x()>point.m_Position.x()) pBezierPatch->m_Mincoord.x()=point.m_Position.x();
if (pBezierPatch->m_Mincoord.y()>point.m_Position.y()) pBezierPatch->m_Mincoord.y()=point.m_Position.y();
if (pBezierPatch->m_Mincoord.z()>point.m_Position.z()) pBezierPatch->m_Mincoord.z()=point.m_Position.z();
if (pBezierPatch->m_Maxcoord.x()<point.m_Position.x()) pBezierPatch->m_Maxcoord.x()=point.m_Position.x();
if (pBezierPatch->m_Maxcoord.y()<point.m_Position.y()) pBezierPatch->m_Maxcoord.y()=point.m_Position.y();
if (pBezierPatch->m_Maxcoord.z()<point.m_Position.z()) pBezierPatch->m_Maxcoord.z()=point.m_Position.z();
}
point.m_Normal.normalize();
point.m_Tangent.normalize();
point.m_Binormal=point.m_Normal ^ point.m_Tangent;
viterator.position(point.m_Position);
viterator.normal(point.m_Normal);
viterator.diffuseColor(point.m_ColorRGBA[3],point.m_ColorRGBA[0],point.m_ColorRGBA[1],point.m_ColorRGBA[2]);
viterator.texcoord2D(0,point.m_Texcoord[0].x(),point.m_Texcoord[0].y());
viterator.texcoord3D(0,point.m_Tangent.x(),point.m_Tangent.y(),point.m_Tangent.z());
viterator.texcoord3D(1,point.m_Binormal.x(),point.m_Binormal.y(),point.m_Binormal.z());
//viterator.texcoord2D(1,point.m_Texcoord[1].x(),point.m_Texcoord[1].y());
++viterator;
}
}
pBezierPatch->m_pVertexstream->unmap();
int numtriangles=(usize-1)*(vsize-1)*2;
pBezierPatch->m_pIndexstream=renderer()->videodevice()->createIndexstream(
numtriangles*3,
((usize*vsize)>65535) ? video::Indexformat_32bit : video::Indexformat_16bit,
video::Streamflags_Writeonly,
video::Mempool_Managed
);
pBezierPatch->m_pIndexstream->map(video::Map_Writeonly);
video::Indexiterator iiterator(*(pBezierPatch->m_pIndexstream));
for (u=0;u<usize-1;++u) {
for (v=0;v<vsize-1;++v) {
ion_uint32 idx11=(ion_uint32)(v+u*vsize);
ion_uint32 idx21=(ion_uint32)((v+1)+u*vsize);
ion_uint32 idx12=(ion_uint32)(v+(u+1)*vsize);
ion_uint32 idx22=(ion_uint32)((v+1)+(u+1)*vsize);
iiterator=idx11; ++iiterator;
iiterator=idx21; ++iiterator;
iiterator=idx12; ++iiterator;
iiterator=idx12; ++iiterator;
iiterator=idx21; ++iiterator;
iiterator=idx22; ++iiterator;
}
}
pBezierPatch->m_pIndexstream->unmap();
pBezierPatch->m_pRenderjob=new Renderjob(*this);
pBezierPatch->m_pRenderjob->primitivestype(video::Primitives_Triangles);
pBezierPatch->m_pRenderjob->indexstream(pBezierPatch->m_pIndexstream);
pBezierPatch->m_pRenderjob->vertexstream(*(pBezierPatch->m_pVertexstream));
pBezierPatch->m_pRenderjob->shader(0);
pBezierPatch->m_pRenderjob->rendertargetCamera(0);
pBezierPatch->m_pRenderjob->propertytable(0);
pBezierPatch->m_pRenderjob->viewerDistance(0);
pBezierPatch->m_pRenderjob->firstElement(0);
pBezierPatch->m_pRenderjob->indexOffset(0);
pBezierPatch->m_pRenderjob->numElements(numtriangles);
pBezierPatch->m_pRenderjob->propertytable(&(m_pSurfaces[pFace->m_Surfaceindex].m_Material));
}
}
base::logstream() << "Done.\n";
progressStatus+=0.05f; REPORTPROGRESS(Progress::LoadingWorldData);
base::logstream() << "Allocating space for " << m_NumBSPVertices << " vertices...\n";
// Prepare the vertex buffer
m_pVertices=renderer()->videodevice()->createVertexstream(
m_NumBSPVertices,vf,video::Streamflags_Writeonly,video::Mempool_Managed);
base::logstream() << "Done.\n";
{
math::Vector3f *pTangents=new math::Vector3f[m_pVertices->capacity()];
math::Vector3f *pBinormal=new math::Vector3f[m_pVertices->capacity()];
for (ion_uint32 facenr=0;facenr<m_NumFaces;++facenr) {
Face &rFace=m_pFaces[facenr];
if ((rFace.m_Type!=Facetype_Polygon) && (rFace.m_Type!=Facetype_Mesh)) continue;
for (ion_int32 j=0;j<rFace.m_NumMeshverts/3;++j) {
ion_uint32 indices[3];
ion_uint32 ii;
math::Vector3f pVecXYZ[3];
math::Vector2f pVecUV[3];
for (ii=0;ii<3;++ii) {
indices[ii]=m_pMeshverts[rFace.m_FirstMeshvert+j*3+ii]+rFace.m_FirstVertex;
pVecXYZ[ii]=m_pBSPVertices[indices[ii]].m_Position;
pVecUV[ii]=m_pBSPVertices[indices[ii]].m_Texcoord[0];
}
math::Plane planes[3];
for (ii=0;ii<3;++ii) {
math::Vector3f nvec[2];
const math::Vector3f &v0=pVecXYZ[0];
const math::Vector3f &v1=pVecXYZ[1];
const math::Vector3f &v2=pVecXYZ[2];
nvec[0]=math::Vector3f(
(v0[ii])-(v1[ii]),
pVecUV[0].x()-pVecUV[1].x(),
pVecUV[0].y()-pVecUV[1].y()
);
nvec[1]=math::Vector3f(
v0[ii]-v2[ii],
pVecUV[0].x()-pVecUV[2].x(),
pVecUV[0].y()-pVecUV[2].y()
);
const float *pXYZ=pVecXYZ[0];
planes[ii].normal(nvec[0]^nvec[1]);
planes[ii].d(
(const math::Vector3f &)(planes[ii].normal())
*
(const math::Vector3f &)(math::Vector3f(pXYZ[ii],pVecUV[0].x(),pVecUV[0].y()))
);
}
// tangent = ( -B0/A0,-B1/A1,-B2/A2 )
// binormal = ( -C0/A0,-C1/A1,-C2/A2 )
math::Vector3f tangent,binormal;
for (ii=0;ii<3;++ii) {
if (planes[ii].a()!=0.0f) {
tangent[ii]=-planes[ii].b()/planes[ii].a();
binormal[ii]=-planes[ii].c()/planes[ii].a();
}
}
for (ii=0;ii<3;++ii) {
pTangents[indices[ii]]+=tangent;
pBinormal[indices[ii]]+=binormal;
}
}
//phil
// Does not work correctly with haste0402.bsp
/*BSPVertex *vert = m_pBSPVertices + rFace.m_FirstVertex;
math::Vector3f t, b;
calculateTangents(vert[0].m_Normal, t, b, vert[0].m_Position, vert[1].m_Position, vert[2].m_Position, vert[0].m_Texcoord[0], vert[1].m_Texcoord[0], vert[2].m_Texcoord[0]);
for(int ii = 0; ii < rFace.m_NumVertices; ii++)
{
pTangents[rFace.m_FirstVertex + ii] = t;
pBinormal[rFace.m_FirstVertex + ii] = b;
}*/
}
m_pVertices->map(video::Map_Writeonly);
for (ion_uint32 vtx=0;vtx<m_pVertices->capacity();++vtx) {
const BSPVertex &rBSPVtx=m_pBSPVertices[vtx];
m_pVertices->position(vtx,rBSPVtx.m_Position);
m_pVertices->normal(vtx,rBSPVtx.m_Normal.normalizedVector());
m_pVertices->diffuseColor(vtx,
rBSPVtx.m_ColorRGBA[3],rBSPVtx.m_ColorRGBA[0],rBSPVtx.m_ColorRGBA[1],rBSPVtx.m_ColorRGBA[2]);
m_pVertices->texcoord2D(vtx,0,rBSPVtx.m_Texcoord[0]);
//m_pVertices->texcoord2D(vtx,1,rBSPVtx.m_Texcoord[1]);
m_pVertices->texcoord3D(vtx,0,pTangents[vtx].normalizedVector());
m_pVertices->texcoord3D(vtx,1,/*pBinormal[vtx]*/rBSPVtx.m_Normal.normalizedVector() ^ pTangents[vtx].normalizedVector());
}
m_pVertices->unmap();
delete [] pBinormal;
delete [] pTangents;
}
// Prepare the renderjobs
{
m_pOpaqueRenderjobs=new Renderjob* [m_NumSurfaces];
for (ion_uint32 i=0;i<m_NumSurfaces;++i) {
m_pOpaqueRenderjobs[i]=new Renderjob(*this);
}
}
base::logstream() << "Min map coord: " << m_pBSPModels[0].m_Mincoord.x() << " " << m_pBSPModels[0].m_Mincoord.y() << " " << m_pBSPModels[0].m_Mincoord.z() << "\n";
base::logstream() << "Max map coord: " << m_pBSPModels[0].m_Maxcoord.x() << " " << m_pBSPModels[0].m_Maxcoord.y() << " " << m_pBSPModels[0].m_Maxcoord.z() << "\n";
base::logstream() << "Allocating space for " << numTriangles << " triangles...\n";
// Allocate the index buffer
m_pIndices=renderer()->videodevice()->createIndexstream(
numTriangles*3,
(m_NumBSPVertices>65535) ? video::Indexformat_32bit : video::Indexformat_16bit,
video::Streamflags_Dynamic|video::Streamflags_Writeonly,
video::Mempool_Default);
/*for (ion_uint32 j=0;j<m_NumBSPModels;++j) {
if ((j>=1) && (m_pBSPModels[j].m_NumFaces>0)) { // j>=1 because #0 is the map itself
m_pBSPModels[j].init(*this);
}
}*/
base::logstream() << "Done.\n";
m_IsValid=true;
}
void Q3BSP::calculateTangents(
math::Vector3f& normal,
math::Vector3f& tangent,
math::Vector3f& binormal,
math::Vector3f& vt1, math::Vector3f& vt2, math::Vector3f& vt3, // vertices
math::Vector2f& tc1, math::Vector2f& tc2, math::Vector2f& tc3) // texture coords
{
math::Vector3f v1 = vt1 - vt2;
math::Vector3f v2 = vt3 - vt1;
normal = v2 ^ v1;
normal.normalize();
// binormal
float deltaX1 = tc1[0] - tc2[0];
float deltaX2 = tc3[0] - tc1[0];
binormal = (v1 * deltaX2) - (v2 * deltaX1);
binormal.normalize();
// tangent
float deltaY1 = tc1[1] - tc2[1];
float deltaY2 = tc3[1] - tc1[1];
tangent = (v1 * deltaY2) - (v2 * deltaY1);
tangent.normalize();
// adjust
math::Vector3f txb = tangent ^ binormal;
if (txb * normal < 0.0f)
{
tangent *= -1.0f;
binormal *= -1.0f;
}
}
}
}
| [
"trevo.palev@2706c42f-771c-0410-b8f5-5191b43d0857"
] | trevo.palev@2706c42f-771c-0410-b8f5-5191b43d0857 |
697f65489285335165c47cc001e94c329ab5dd7f | d8dde07d7c9cf75f7f18a91ab1dd74a4a261a9e7 | /contest/poj/vol_11/2022.cc | f94a33f03e0fecf52d4a7f6f380c8c0b9251a471 | [] | no_license | tiankonguse/ACM | 349109d3804e5b1a1de109ec48a2cb3b0dceaafc | ef70b8794c560cb87a6ba8f267e0cc5e9d06c31b | refs/heads/master | 2022-10-09T19:58:38.805515 | 2022-09-30T06:59:53 | 2022-09-30T06:59:53 | 8,998,504 | 82 | 51 | null | 2020-11-09T05:17:09 | 2013-03-25T04:04:26 | C++ | UTF-8 | C++ | false | false | 4,583 | cc | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
using namespace std;
bool isHtml(string s);
bool isBody(string s);
bool isText(string s);
bool isString(string s);
bool isTag(string s);
bool isBold(string s);
bool isItalics(string s);
bool isLink(string s);
bool isUrl(string s);
bool isHref(string s);
bool isHtml(string s){
int n = s.length();
if(n < 13) return false;
string s1 = s.substr(0, 6);
string s2 = s.substr(n - 7);
string s3 = s.substr(6, n - 13);
if(s1 != "<HTML>" || s2 != "</HTML>") return false;
else return isBody(s3);
}
bool isBody(string s){
int n = s.length();
if(n < 13) return false;
string s1 = s.substr(0, 6);
string s2 = s.substr(n - 7);
string s3 = s.substr(6, n - 13);
if(s1 != "<BODY>" || s2 != "</BODY>") return false;
else return isText(s3);
}
struct node{
int l, d;
node(){}
node(int _l, int _d){ l = _l, d = _d; }
}tmp;
bool isText(string s){
int n = s.length();
int p = 0, q, r = 0, d;
int top = 0;
stack <node> st;
string s1, s2;
bool flag = false;
for(int i=0;i<n;i++){
if(s[i] == '<'){
if(top == 0){
s1 = s.substr(p, i - p);
if(!isString(s1)) return false;
}
q = i;
while(i < n && s[i] != '>') i++;
if(s[i] != '>') return false;
p = i + 1;
s1 = s.substr(q, i - q + 1);
if(s1 == "<B>") st.push( node(q, 1) );
else if(s1 == "<I>") st.push( node(q, 2) );
else if(isHref(s1)) st.push( node(q, 3) );
else if(s1 == "</B>"){
if(st.empty()) return false;
tmp = st.top();
st.pop();
s2 = s.substr(tmp.l, i - tmp.l + 1);
if(!isBold(s2)) return false;
}
else if(s1 == "</I>"){
if(st.empty()) return false;
tmp = st.top();
st.pop();
s2 = s.substr(tmp.l, i - tmp.l + 1);
if(!isItalics(s2)) return false;
}
else if(s1 == "</A>"){
if(st.empty()) return false;
tmp = st.top();
st.pop();
s2 = s.substr(tmp.l, i - tmp.l + 1);
if(!isLink(s2)) return false;
}
else return false;
}
}
if(!st.empty()) return false;
s1 = s.substr(p);
if(!isString(s1) && !isTag(s1)) return false;
else return true;
}
bool isString(string s){
int n = s.length();
for(int i=0;i<n;i++){
if(s[i] == '<' || s[i] == '>') return false;
}
return true;
}
bool isTag(string s){
return isBold(s) || isItalics(s) || isLink(s);
}
bool isBold(string s){
int n = s.length();
if(n < 7) return false;
string s1 = s.substr(0, 3);
string s2 = s.substr(n - 4);
string s3 = s.substr(3, n - 7);
if(s1 != "<B>" || s2 != "</B>") return false;
else return isText(s3);
}
bool isItalics(string s){
int n = s.length();
if(n < 7) return false;
string s1 = s.substr(0, 3);
string s2 = s.substr(n - 4);
string s3 = s.substr(3, n - 7);
if(s1 != "<I>" || s2 != "</I>") return false;
else return isText(s3);
}
bool isLink(string s){
int n = s.length();
if(n < 13) return false;
string s1 = s.substr(0, 8);
string s2 = s.substr(n - 4);
if(s1 != "<A HREF=" || s2 != "</A>") return false;
int p;
for(p=8;p<n-4;p++) if(s[p] == '>') break;
string s3 = s.substr(8, p - 8);
string s4 = s.substr(p + 1, n - p - 5);
return isUrl(s3) && isText(s4);
}
bool isUrl(string s){
int n = s.length();
if(n < 11) return false;
string s1 = s.substr(0, 7);
string s2 = s.substr(n - 4);
string s3 = s.substr(7, n - 11);
if(s1 != "http://" || s2 != ".com") return false;
else return isString(s3);
}
bool isHref(string s){
int n = s.length();
if(n < 9) return false;
string s1 = s.substr(0, 8);
string s2 = s.substr(n - 1);
string s3 = s.substr(8, n - 9);
if(s1 != "<A HREF=" || s2 != ">") return false;
else return isString(s3);
}
int main(){
int n;
string s;
cin>>n;
cin.ignore();
while(n--){
getline(cin, s);
if(isHtml(s)) cout<<"Syntax Included"<<endl;
else cout<<"No Syntax Included"<<endl;
}
return 0;
}
| [
"i@tiankonguse.com"
] | i@tiankonguse.com |
0e395c3338fa72b089338dec024cc82e7af0724b | 4c8c13eb891b514037d3adb1be7f28af53144e85 | /mjolnir/input/read_observer.hpp | 70d0600adb6ee7a362717f3c78bb5bd2d2e2e0ed | [
"MIT"
] | permissive | Mjolnir-MD/Mjolnir | f07b501cf60d6d1ca7cdeafc400749423dcde142 | 20dbdea5529c24a49b71e8876ac1651efc512445 | refs/heads/master | 2023-02-03T22:59:33.972243 | 2022-04-12T10:23:04 | 2022-04-12T10:23:04 | 74,558,351 | 14 | 9 | MIT | 2023-01-27T04:46:54 | 2016-11-23T08:53:31 | C++ | UTF-8 | C++ | false | false | 5,076 | hpp | #ifndef MJOLNIR_INPUT_READ_OBSERVER_HPP
#define MJOLNIR_INPUT_READ_OBSERVER_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/input/read_path.hpp>
#include <mjolnir/core/ObserverContainer.hpp>
#include <mjolnir/core/EnergyObserver.hpp>
#include <mjolnir/core/XYZObserver.hpp>
#include <mjolnir/core/DCDObserver.hpp>
#include <mjolnir/core/TRRObserver.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/util/make_unique.hpp>
namespace mjolnir
{
template<typename traitsT>
void add_observer(ObserverContainer<traitsT>& observers,
const toml::value& format, const std::string& file_prefix)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
// To show the informative error message, here it uses toml::value that
// contains file location. But this function assumes that the `format`
// contains `toml::string`.
assert(format.is_string());
if(format.as_string() == "xyz")
{
using observer_type = XYZObserver<traitsT>;
MJOLNIR_LOG_NOTICE("output xyz format.");
observers.push_back(make_unique<observer_type>(file_prefix));
return;
}
else if(format.as_string() == "dcd")
{
using observer_type = DCDObserver<traitsT>;
MJOLNIR_LOG_NOTICE("output dcd format.");
observers.push_back(make_unique<observer_type>(file_prefix));
return;
}
else if(format.as_string() == "trr")
{
using observer_type = TRRObserver<traitsT>;
MJOLNIR_LOG_NOTICE("output trr format.");
observers.push_back(make_unique<observer_type>(file_prefix));
return;
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_observer: output format not supported", format,
"here", {
"expected one of the following.",
"- \"xyz\": the simplest ascii format.",
"- \"dcd\": binary format which contains normally positions."
"- \"trr\": binary format which contains positions, velocities, and forces."
}));
}
return ;
}
template<typename traitsT>
ObserverContainer<traitsT>
read_observer(const toml::value& root)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto& output = toml::find(root, "files", "output");
const auto output_path = read_output_path(root);
const auto output_prefix = toml::find<std::string>(output, "prefix");
MJOLNIR_LOG_NOTICE("output file prefix is `", output_path, output_prefix, '`');
const std::string file_prefix = output_path + output_prefix;
const auto progress_bar_activated =
toml::find_or<bool>(output, "progress_bar", true);
ObserverContainer<traitsT> observers(progress_bar_activated);
const auto& format = toml::find(output, "format");
if(format.is_string())
{
add_observer(observers, format, file_prefix);
}
else if(format.is_array())
{
for(const auto& fmt : format.as_array())
{
add_observer(observers, fmt, file_prefix);
}
}
// Energy is always written to "prefix.ene".
observers.push_back(make_unique<EnergyObserver<traitsT>>(file_prefix));
return observers;
}
} // mjolnir
#ifdef MJOLNIR_SEPARATE_BUILD
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
namespace mjolnir
{
extern template void add_observer<SimulatorTraits<double, UnlimitedBoundary> >(ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >& observers, const toml::value& format, const std::string& file_prefix);
extern template void add_observer<SimulatorTraits<float, UnlimitedBoundary> >(ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >& observers, const toml::value& format, const std::string& file_prefix);
extern template void add_observer<SimulatorTraits<double, CuboidalPeriodicBoundary>>(ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>& observers, const toml::value& format, const std::string& file_prefix);
extern template void add_observer<SimulatorTraits<float, CuboidalPeriodicBoundary>>(ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>& observers, const toml::value& format, const std::string& file_prefix);
extern template ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> > read_observer<SimulatorTraits<double, UnlimitedBoundary >>(const toml::value& data);
extern template ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> > read_observer<SimulatorTraits<float, UnlimitedBoundary >>(const toml::value& data);
extern template ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_observer<SimulatorTraits<double, CuboidalPeriodicBoundary>>(const toml::value& data);
extern template ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_observer<SimulatorTraits<float, CuboidalPeriodicBoundary>>(const toml::value& data);
} // mjolnir
#endif
#endif// MJOLNIR_READ_OBSERVER_HPP
| [
"niina.toru.68u@gmail.com"
] | niina.toru.68u@gmail.com |
f77b06f93da33e51842e9cb84a1b1cf0ecb06145 | b66ef823272e33eef2d76b145f09f0a3a15aa441 | /src/MenuProfessor.cpp | 2a7ba212bcf5db07481cbbaf2b6ed8fb8e7c2696 | [] | no_license | pds2/20191-team-11 | 33ac51c85464a5d6ae0a08114306c0224496e5d0 | 534f09981ede4c7cccc2602f5e4fc1f8782e5526 | refs/heads/master | 2020-05-16T00:52:36.405362 | 2019-06-16T01:53:08 | 2019-06-16T01:53:08 | 182,588,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,405 | cpp | #include "../include/Aluno.h"
#include "../include/Pessoa.h"
#include "../include/Professor.h"
#include "../include/Funcionario.h"
#include "../include/FuncAdm.h"
#include "../include/ManagerFuncionario.h"
#include "../include/ManagerAluno.h"
#include "../include/ManagerProfessor.h"
#include "../include/ManagerDisciplina.h"
#include "../include/ManagerTurma.h"
#include "../include/MenuAdministrativo.h"
#include <iostream>
#include <string>
#include <map>
#include <stdlib.h>
#include <iomanip>
void verNotaPorAluno(ManagerAluno &mAluno, ManagerMateria &mMateria){
string matriculaString, idMateriaString;
int matricula, idMateria;
cout << "Digite a matricula do aluno" << endl;
mAluno.geraRelatorio();
cin.ignore();
getline(cin,matriculaString);
matricula = atoi(matriculaString.c_str());
try {
mAluno.getItem(matricula);
cout << "Digite o id da materia" << endl;
mMateria.geraRelatorio();
getline(cin,idMateriaString);
idMateria = atoi(idMateriaString.c_str());
try{
mMateria.getItem(idMateria);
mMateria.listarMateriaPorAluno(matricula , idMateria,mAluno);
}catch (const std::invalid_argument& e){
cout << e.what() << endl;
return;
}
}catch (const std::invalid_argument& e){
cout << e.what() << endl;
return;
}
}
void gerarRelatorios(ManagerAluno &mAluno, ManagerProfessor &mProfessor , ManagerDisciplina &mDisciplina, ManagerMateria &mMateria){
int option;
bool sair = false;
while(!sair){
cout << "Relatórios" << endl;
cout << "[1] Listar notas de um aluno" << endl;
cout << "[0] Voltar para menu anterior" << endl;
cin >> option;
switch(option){
case 0:
sair = true;
break;
case 1:
verNotaPorAluno(mAluno,mMateria);
break;
default:
cout << "Opção não existe!" << endl;
}
}
}
void professor(ManagerAluno &mAluno, ManagerProfessor &mProfessor , ManagerDisciplina &mDisciplina, ManagerTurma &mTurma, ManagerMateria &mMateria){
int value;
Professor *professor;
cout << "Digite seu número de registro: ";
cin >> value;
try {
professor = mProfessor.getItem(value);
cout << "Nome: " << professor->getNome() << endl;
cout << "Disciplina: " << mDisciplina.getItem(professor->getDisciplina())->getNome() << endl;
bool sair = false;
while(!sair){
cout << "Ola, o que voce deseja fazer?" << endl;
cout << "[1] - Lançar a nota do aluno" << endl;
cout << "[2] - Relatorios "<< endl;
cout << "[0] Voltar para menu anterior" << endl;
cin >> value;
switch(value){
case 0:
sair = true;
break;
case 1:
mMateria.lancarNotaAluno(mAluno,mProfessor, value);
break;
case 2:
gerarRelatorios(mAluno , mProfessor, mDisciplina,mMateria);
break;
default:
cout << "Opção não cadastrada!" << endl;
break;
}
}
}catch(std::exception &e){
cout << e.what() << endl;
}
} | [
"imsp@dcc.ufmg.br"
] | imsp@dcc.ufmg.br |
8880531feb9245b5d93492b4cf73e3da8f24ab1b | 0f28324306f321795cadee3e78203da91ed1be85 | /ID3v2/source/Frame/v23/ID3v2-Frame-TFLT.cpp | 54f24567ed2aba111f1710eda458e5d21e2b55e1 | [
"MIT"
] | permissive | DigiDNA/ID3v2 | c37b3be83007614f7d886d537105bddd4b7e7e02 | be8022a5ee94197a58710a55931aea7d89ae3f71 | refs/heads/main | 2021-11-26T09:46:47.311154 | 2021-11-11T11:51:03 | 2021-11-11T11:51:03 | 24,659,502 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,219 | cpp | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Jean-David Gadina - www.xs-labs.com / www.digidna.net
*
* 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.
******************************************************************************/
/*!
* @header ID3v2-Frame-TFLT.cpp
* @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
* @abstract ID3v2 TFLT frame
*/
#include <ID3v2.h>
namespace ID3v2
{
namespace Frame
{
namespace v23
{
class TFLT::IMPL
{
public:
IMPL( void );
};
TFLT::TFLT( void ): impl( new IMPL )
{}
TFLT::~TFLT( void )
{
delete this->impl;
}
void TFLT::ProcessData( void )
{}
std::string TFLT::GetDescription( void ) const
{
return "File type";
}
TFLT::IMPL::IMPL( void )
{}
}
}
}
| [
"macmade@xs-labs.com"
] | macmade@xs-labs.com |
109f72466013e80e1a58e534c5c6c1344f5fda52 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/ServiceProcess/tests/ServiceProcess.Tests/UNIX_ServiceProcessFixture.cpp | 57384be06eb1b511b3bd49b5667b7d71cdb6604e | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,449 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_ServiceProcessFixture.h"
#include <ServiceProcess/UNIX_ServiceProcessProvider.h>
UNIX_ServiceProcessFixture::UNIX_ServiceProcessFixture()
{
}
UNIX_ServiceProcessFixture::~UNIX_ServiceProcessFixture()
{
}
void UNIX_ServiceProcessFixture::Run()
{
CIMName className("UNIX_ServiceProcess");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_ServiceProcess _p;
UNIX_ServiceProcessProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
if (propertyItem.getType() == CIMTYPE_REFERENCE) {
CIMValue subValue = propertyItem.getValue();
CIMInstance subInstance;
subValue.get(subInstance);
CIMObjectPath subPath = subInstance.getPath();
cout << " Name: " << propertyItem.getName().getString() << ": " << subPath.toString() << endl;
Uint32 subPropertyCount = subInstance.getPropertyCount();
for(Uint32 j = 0; j < subPropertyCount; j++)
{
CIMProperty subPropertyItem = subInstance.getProperty(j);
cout << " Name: " << subPropertyItem.getName().getString() << " - Value: " << subPropertyItem.getValue().toString() << endl;
}
}
else {
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
20184ec7c98d4c7d4c8b66c8fd428637a478261a | 90ef8a860d581420eac62e22aeadf25566473a2c | /c++/2/2.cpp | 3af547c0d7dc44ff81b4334385907e79ef3af1a1 | [] | no_license | osotn/Tutorial | dfd665493cbfcd4eb16033aa5ba1eb6307ae9002 | 804ecdebf828cc71dbf1715f1b4f2578d5edc586 | refs/heads/master | 2021-07-23T11:26:07.444667 | 2021-07-06T17:15:15 | 2021-07-06T17:15:15 | 47,759,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ifstream in("2.cpp");
string word;
vector<string> v;
while (in >> word)
v.push_back(word);
for(int i=0; i < v.size(); i++)
cout << i << ":" << v[i] << endl;
}
| [
"oleksandr.v.sotnikov@gmail.com"
] | oleksandr.v.sotnikov@gmail.com |
71094467b7960ae418fa219dcf2fcc5491466955 | 611099b10e66f3dcfdf9093251cb63cde87ece5a | /All programs/SOOPROEV.CPP | e0469d3c52259a90c73106ee5f0f5d67dd912ec0 | [] | no_license | gillgurvijay01/Grade12-CS | 785be7106ca8fd73eb01105c2bf125b0a146e7fe | cd98eb0a7c373ee09aafcbebed5ea636df60b174 | refs/heads/main | 2023-08-07T19:42:57.193567 | 2021-10-12T04:42:42 | 2021-10-12T04:42:42 | 370,397,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | /*Program to make an array of ten nubers display sum of odd nubers and
product of even numbers*/
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x[10]; //Size of array
int sum=0;
float prod=1;
for (int j=0;j<=9;j++)
{
cout<<"\nPlease enter number :";
cin>>x[j]; //accaeptance of element
}
for (int z=0;z<=9;z++)
{
if (x[z]%2==0) //if the number is even
prod=prod*x[z];
if(x[z]%2!=0) //if the number is odd
sum=sum+x[z];
}
cout<<"\nSum of odd elements =="<<sum;
cout<<"\nProduct of even elements =="<<prod;
getch();
} | [
"67116971+gillgurvijay01@users.noreply.github.com"
] | 67116971+gillgurvijay01@users.noreply.github.com |
f73908cd994a7978f3ca210cbb56ec0dc933a04f | 170754ddc76e9b622126dda036dd7c7cfff1e5bc | /L1TriggerDPGUpgrade/L1TMuon/macros/include/EffiEvent.h | ebb713c8a98fb6a704525c91fe7e0679299fe42b | [] | no_license | StefanSchwartz/RPCInclusion | e98851331b43016d5256ec129acbeb744c62be23 | 40d7744766f8b569a662435e1e0f5658199db7c3 | refs/heads/master | 2021-01-25T06:06:11.677320 | 2015-05-29T13:52:12 | 2015-05-29T13:52:12 | 30,252,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,749 | h | #ifndef __EFFIEVENT_H__
#define __EFFIEVENT_H__
#include <vector>
#include "TFile.h"
#include "TTree.h"
using namespace std;
class EffiEvent{
public:
EffiEvent();
//----------------------------------------------------------------------------
// Useful Methods
//----------------------------------------------------------------------------
void AttachToFile(TFile *file);
void CloseFile(TFile *file);
long int GetEntries() { return CSCtree ->GetEntries(); }
void GetEntry(long int iEvt);
TTree *CSCtree;
// Pt assignment methods
float pt_13(TTree CSCtree, int iCSCTrk, int printLevel);
//----------------------------------------------------------------------------
// Access the needed variables
//----------------------------------------------------------------------------
#define MAX_CSCTF_TRK 36 // max # of CSCTF tracks per BX
#define MAX_LCTS_PER_TRK 4 // max # of LCTS which form a CSCTF track
#define MAX_RPC_LCTS_EVT 36
#define MAX_MUONS 100
// Put generated muons in CSC tree
float gen_pt;
float gen_eta;
float gen_phi;
unsigned int gen_chg;
int Event;
int Lumi;
int Run;
int Run_Test;
// Reco Objects -----------------------------------------------------------
int muonSize;
double muon_pt[MAX_MUONS];
double muon_eta[MAX_MUONS];
double muon_phi[MAX_MUONS];
float muon_chg[MAX_MUONS];
int muon_match[MAX_MUONS];
// CSC objects ------------------------------------------------------------
int SizeTrk;
float PtTrk [MAX_CSCTF_TRK];
double EtaTrk [MAX_CSCTF_TRK];
double PhiTrk [MAX_CSCTF_TRK];
int EtaBitTrk [MAX_CSCTF_TRK];
int PhiBitTrk [MAX_CSCTF_TRK];
int PtBitTrk [MAX_CSCTF_TRK];
int ModeTrk [MAX_CSCTF_TRK];
int ChgTrk [MAX_CSCTF_TRK];
// These store track pT info from PtAddtess.h
int PtTrk_reco_front [MAX_CSCTF_TRK][MAX_RPC_LCTS_EVT];
int PtTrk_reco_rear [MAX_CSCTF_TRK][MAX_RPC_LCTS_EVT];
int PtTrk_reco_best_two [MAX_CSCTF_TRK][MAX_RPC_LCTS_EVT];
int rpcIsmatched [MAX_CSCTF_TRK][MAX_RPC_LCTS_EVT];
int trkIsMatched [MAX_CSCTF_TRK];
int RpcMatchedID [MAX_CSCTF_TRK];
//Added by Scott for looking at efficiency
int PtTrk_reco_front_three [MAX_CSCTF_TRK];
int PtTrk_reco_rear_three [MAX_CSCTF_TRK];
int PtTrk_reco_best [MAX_CSCTF_TRK];
int isGoodTrk [MAX_CSCTF_TRK];
// Info about LCTs forming the track
// Stored in 2D array [track x] [LCT y] - each event has x tracks containing y Lcts
int NumLctsTrk[MAX_CSCTF_TRK]; // How many Lcts made up track
double trLctglobalPhi [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
double trLctglobalEta [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctPhiBit [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctEtaBit [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
//int trLctEtaBitMatt [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctSector [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctSubSector [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctStation [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctChamber [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctEndcap [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctBx [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctCSCId [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
int trLctRing [MAX_CSCTF_TRK][MAX_LCTS_PER_TRK];
// RPC objects ------------------------------------------------------------
int PtTrk_reco_rpc_csc [MAX_CSCTF_TRK][3][MAX_RPC_LCTS_EVT];
int csc_rpc_match [MAX_CSCTF_TRK][3][MAX_RPC_LCTS_EVT];
// Trigger Primitve variables
int rpc_NumLctsTrk;
double rpc_gblEta [MAX_RPC_LCTS_EVT];
double rpc_gblPhi [MAX_RPC_LCTS_EVT];
// unsigned rpc_strip [MAX_RPC_LCTS_EVT];
// unsigned rpc_Layer [MAX_RPC_LCTS_EVT];
int rpc_bx [MAX_RPC_LCTS_EVT];
int rpc_Station [MAX_RPC_LCTS_EVT];
int rpc_Sector [MAX_RPC_LCTS_EVT];
int rpc_Phibit [MAX_RPC_LCTS_EVT];
//int rpc_Etabit [MAX_RPC_LCTS_EVT];
};
int eta_dphi_ME1toME2[64] = {127, 127, 127, 127, 127, 127, 40, 80, 80, 64,
127, 127, 62, 41, 41, 45, 47, 48, 47, 46,
47, 50, 52, 51, 53, 54, 55, 73, 82, 91,
91, 94, 100, 99, 95, 94, 95, 91, 96, 96,
94, 94, 88, 88, 80, 80, 84, 84, 79, 78,
80, 78, 75, 72, 70, 71, 69, 71, 71, 66,
61, 60, 43, 127};
// RPC phi: calculating rpc global phi in CSC bit form
int CalcIntegerPhi(float GblPhi,int sector,int station,int ring){
if (sector > 6) sector -= 6;
float slope[3][4][6] = {{{3783.79,3784.91,3784.06,3784.56,3784.05,3784.86},{3783.79,3784.91,3784.06,3784.56,3784.05,3784.86},\
{3784.54,3784.61,3784.54,3785.22,3784.56,3784.51},{3783.79,3784.91,3784.06,3784.56,3784.05,3784.86}},
{{0,0,0,0,0,0},{3784.07,3784.65,3784.17,3784.59,3784.17,3785.08},{0,0,0,0,0,0},{0,0,0,0,0,0}},
{{0,0,0,0,0,0},{3784.36,3784.68,3784.09,3784.61,3784.14,3785.02},{0,0,0,0,0,0},{0,0,0,0,0,0}}};
float offset[3][4][6] = {{{-924.362,-4888.94,-8849.91,10964.5,7000.71,3038.25},{-924.362,-4888.94,-8849.91,10964.5,7000.71,3038.25},
{-925.02,-4888.23,-8851.1,10966.2,7001.31,3038.31}, {-925.02,-4888.23,-8851.1,10966.2,7001.31,3038.31}},
{{0,0,0,0,0,0},{-924.479,-4888.28,-8850.11,10964.6,7001.03,3038.3},{0,0,0,0,0,0},{0,0,0,0,0,0}},
{{0,0,0,0,0,0},{-924.573,-4888.41,-8849.93,10964.6,7000.99,3038.31},{0,0,0,0,0,0},{0,0,0,0,0,0}}};
int phi_out = -1;
if (sector == 3 and GblPhi < 0) GblPhi += 2*3.14159;
phi_out = (GblPhi*slope[ring-1][station-1][sector-1]) + offset[ring-1][station-1][sector-1];
if (phi_out < 0) phi_out += 4096;
if (phi_out > 4096) phi_out -= 4096;
return phi_out;
}
#endif
| [
"schwartz.st@husky.neu.edu"
] | schwartz.st@husky.neu.edu |
0111c25af36c90801b6b5652f375f0eee9de6715 | 2dfe0f1c0c45effcc2e28cf226400fa71466d78a | /src/MDIFormApp/MainFrm.cpp | 8ac111cf4007cef3eb570408ef83832899dcc1f4 | [
"MIT"
] | permissive | andreabalducci/MFCTraining | 72d30c5fa335ac4d78b11cdee2ff4165f05b219d | 9751c2f730ba525b309186385cedb8f48d211bab | refs/heads/master | 2020-12-04T10:19:33.322593 | 2016-09-12T05:59:15 | 2016-09-12T05:59:15 | 67,869,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,936 | cpp |
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "MDIFormApp.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWndEx)
const int iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWndEx)
ON_WM_CREATE()
ON_COMMAND(ID_WINDOW_MANAGER, &CMainFrame::OnWindowManager)
ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize)
ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew)
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWndEx::OnCreate(lpCreateStruct) == -1)
return -1;
BOOL bNameValid;
CMDITabInfo mdiTabParams;
mdiTabParams.m_style = CMFCTabCtrl::STYLE_3D_ONENOTE; // other styles available...
mdiTabParams.m_bActiveTabCloseButton = TRUE; // set to FALSE to place close button at right of tab area
mdiTabParams.m_bTabIcons = FALSE; // set to TRUE to enable document icons on MDI taba
mdiTabParams.m_bAutoColor = TRUE; // set to FALSE to disable auto-coloring of MDI tabs
mdiTabParams.m_bDocumentMenu = TRUE; // enable the document menu at the right edge of the tab area
EnableMDITabbedGroups(TRUE, mdiTabParams);
if (!m_wndMenuBar.Create(this))
{
TRACE0("Failed to create menubar\n");
return -1; // fail to create
}
m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY);
// prevent the menu bar from taking the focus on activation
CMFCPopupMenu::SetForceMenuFocus(FALSE);
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
CString strToolBarName;
bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD);
ASSERT(bNameValid);
m_wndToolBar.SetWindowText(strToolBarName);
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
// Allow user-defined toolbars operations:
InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId);
if (!m_wndStatusBar.Create(this))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: Delete these five lines if you don't want the toolbar and menubar to be dockable
m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY);
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndMenuBar);
DockPane(&m_wndToolBar);
// enable Visual Studio 2005 style docking window behavior
CDockingManager::SetDockingMode(DT_SMART);
// enable Visual Studio 2005 style docking window auto-hide behavior
EnableAutoHidePanes(CBRS_ALIGN_ANY);
// set the visual manager used to draw all user interface elements
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008));
// Enable enhanced windows management dialog
EnableWindowsDialog(ID_WINDOW_MANAGER, ID_WINDOW_MANAGER, TRUE);
// Enable toolbar and docking window menu replacement
EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR);
// enable quick (Alt+drag) toolbar customization
CMFCToolBar::EnableQuickCustomization();
if (CMFCToolBar::GetUserImages() == NULL)
{
// load user-defined toolbar images
if (m_UserImages.Load(_T(".\\UserImages.bmp")))
{
CMFCToolBar::SetUserImages(&m_UserImages);
}
}
// enable menu personalization (most-recently used commands)
// TODO: define your own basic commands, ensuring that each pulldown menu has at least one basic command.
CList<UINT, UINT> lstBasicCommands;
lstBasicCommands.AddTail(ID_FILE_NEW);
lstBasicCommands.AddTail(ID_FILE_OPEN);
lstBasicCommands.AddTail(ID_FILE_SAVE);
lstBasicCommands.AddTail(ID_FILE_PRINT);
lstBasicCommands.AddTail(ID_APP_EXIT);
lstBasicCommands.AddTail(ID_EDIT_CUT);
lstBasicCommands.AddTail(ID_EDIT_PASTE);
lstBasicCommands.AddTail(ID_EDIT_UNDO);
lstBasicCommands.AddTail(ID_APP_ABOUT);
lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR);
lstBasicCommands.AddTail(ID_VIEW_TOOLBAR);
CMFCToolBar::SetBasicCommands(lstBasicCommands);
// Switch the order of document name and application name on the window title bar. This
// improves the usability of the taskbar because the document name is visible with the thumbnail.
ModifyStyle(0, FWS_PREFIXTITLE);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWndEx::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWndEx::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWndEx::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnWindowManager()
{
ShowWindowsDialog();
}
void CMainFrame::OnViewCustomize()
{
CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* scan menus */);
pDlgCust->EnableUserDefinedToolbars();
pDlgCust->Create();
}
LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp)
{
LRESULT lres = CMDIFrameWndEx::OnToolbarCreateNew(wp,lp);
if (lres == 0)
{
return 0;
}
CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres;
ASSERT_VALID(pUserToolbar);
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
return lres;
}
BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext)
{
// base class does the real work
if (!CMDIFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext))
{
return FALSE;
}
// enable customization button for all user toolbars
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
for (int i = 0; i < iMaxUserToolbars; i ++)
{
CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i);
if (pUserToolbar != NULL)
{
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
}
}
return TRUE;
}
| [
"mtb.snowboard@gmail.com"
] | mtb.snowboard@gmail.com |
82002824fb00cc397b98a195cb578a1000d3b751 | f50a1d498053b6c3206b8847a8dae6a2fac5c03d | /verilator_project/tb_friet_lwc_fpga_lut6.cpp | bf0c27874c4a8f14d306b79b1a29ac0f2d1f21f5 | [
"CC0-1.0"
] | permissive | Arthurvdmerwe/hw-friet | 97367b1a5e2ec7b760fa1eb9b135cda49eb770aa | 48afe356f3a1b22cda93185a2d2177fbb1ec2264 | refs/heads/main | 2023-06-30T00:50:59.495392 | 2021-07-25T17:04:08 | 2021-07-25T17:04:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,370 | cpp | /*--------------------------------------------------------------------------------*/
/* Implementation by Pedro Maat C. Massolino, */
/* hereby denoted as "the implementer". */
/* */
/* To the extent possible under law, the implementer has waived all copyright */
/* and related or neighboring rights to the source code in this file. */
/* http://creativecommons.org/publicdomain/zero/1.0/ */
/*--------------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include "Vfriet_lwc_fpga_lut6.h"
#include "verilated.h"
#ifdef DUMP_TRACE_ON
#ifdef DUMP_TRACE_FST
#include "verilated_fst_c.h"
#else
#include "verilated_vcd_c.h"
#endif
#endif
#define MAX_SIMULATION_TICKS 100000000
#define G_MAXIMUM_BUFFER_SIZE_ARRAY 2048
#define G_MAXIMUM_MESSAGE_SIZE_HASH 1024
#define G_MAXIMUM_HASH_SIZE 32
#define G_MAXIMUM_KEY_SIZE 32
#define G_MAXIMUM_NONCE_SIZE 16
#define G_MAXIMUM_ASSOCIATED_DATA_SIZE 32
#define G_MAXIMUM_PLAINTEXT_SIZE 32
#define G_MAXIMUM_TAG_SIZE 16
#define G_MAXIMUM_CIPHERTEXT_SIZE (G_MAXIMUM_PLAINTEXT_SIZE + G_MAXIMUM_TAG_SIZE)
#define G_MAXIMUM_DATA_SEGMENT_SIZE ((1U << 15)+1)
#define G_FNAME_AEAD_KAT "../data_tests/LWC_AEAD_KAT_256_128.txt"
#define G_MAXIMUM_NUMBER_OF_TESTS 2000
#define G_SKIP_AEAD_TEST 0 // 1 - True, 0 - False
#define PRINT_CURRENT_TEST_NUMBER 1
#define ASYNC_RST 0
#define G_PWIDTH 32
#define G_SWIDTH 32
#define G_PWIDTH_MASK ((1UL << (G_PWIDTH)) - 1)
#define G_SWIDTH_MASK ((1UL << (G_SWIDTH)) - 1)
#define G_SEGMENT_DATA_SIZE_MASK ((1U << 16)-1)
#define SKIPPING_TESTS_MAX 40
class Testbench {
public:
vluint64_t time_count;
int stop_time_enable;
vluint64_t stop_time;
Vfriet_lwc_fpga_lut6 *dut;
#ifdef DUMP_TRACE_ON
#ifdef DUMP_TRACE_FST
VerilatedFstC* tfp;
#else
VerilatedVcdC* tfp;
#endif
#endif
Testbench(long long stop_time_value=-1) {
dut = new Vfriet_lwc_fpga_lut6;
time_count = 1;
dut->clk = 0;
#ifdef DUMP_TRACE_ON
if(stop_time_value != -1){
stop_time_enable = 1;
stop_time = stop_time_value;
}
else{
stop_time_enable = 0;
stop_time = 0;
}
#ifdef DUMP_TRACE_FST
tfp = new VerilatedFstC;
dut->trace(tfp, 99);
tfp->open("tb_friet_lwc_fpga_lut6.fst");
#else
tfp = new VerilatedVcdC;
dut->trace(tfp, 99);
tfp->open("tb_friet_lwc_fpga_lut6.vcd");
#endif
#else
stop_time_enable = 0;
stop_time = 0;
#endif
}
~Testbench(void) {
#ifdef DUMP_TRACE_ON
tfp->flush();
tfp->close();
delete tfp;
tfp = NULL;
#endif
dut->final();
delete dut;
dut = NULL;
}
void reset(void) {
int i;
if(ASYNC_RST == 0){
dut->rst = 1;
} else {
dut->rst = 0;
}
dut->pdi_data = 0;
dut->pdi_valid = 0;
dut->sdi_data = 0;
dut->sdi_valid = 0;
dut->do_ready = 0;
for(i = 0; i < 10; i++){
clock_tick();
}
if(ASYNC_RST == 0){
dut->rst = 0;
} else {
dut->rst = 1;
}
clock_tick();
}
void clock_tick(void){
time_count++;
dut->clk = 0;
dut->eval();
#ifdef DUMP_TRACE_ON
tfp->dump(time_count);
#endif
time_count++;
dut->clk = 1;
dut->eval();
#ifdef DUMP_TRACE_ON
tfp->dump(time_count);
if((stop_time_enable != 0) && (time_count > stop_time)){
tfp->flush();
tfp->close();
delete tfp;
tfp = NULL;
printf("Finishing simulation because stop time has been reached\n");
dut->final();
delete dut;
dut = NULL;
exit(1);
}
#endif
}
void add_instruction_to_buffer(char * buffer, int * buffer_length, int buffer_width, int instruction){
int i;
buffer[*buffer_length] = instruction & 0x00FF;
*buffer_length = *buffer_length + 1;
for(i = 8; i < buffer_width; i += 8){
buffer[*buffer_length] = 0;
*buffer_length = *buffer_length + 1;
}
}
void add_status_to_buffer(char * buffer, int * buffer_length, int buffer_width, int status){
int i;
buffer[*buffer_length] = status & 0x00FF;
*buffer_length = *buffer_length + 1;
for(i = 8; i < buffer_width; i += 8){
buffer[*buffer_length] = 0;
*buffer_length = *buffer_length + 1;
}
}
void add_header_to_buffer(char * buffer, int * buffer_length, int buffer_width, int header){
int i;
for(i = 0; i < 32; i += 8){
buffer[*buffer_length] = (header >> (24 - i)) & 0x00FF;
*buffer_length = *buffer_length + 1;
}
}
void add_data_to_buffer(char * buffer, int * buffer_length, int buffer_width, char * data, int data_length){
int i, j;
for(j = 0; j < data_length;){
for(i = 0; i < buffer_width; i += 8){
if(j < data_length){
buffer[*buffer_length] = data[j];
*buffer_length = *buffer_length + 1;
j++;
}
else{
buffer[*buffer_length] = 0;
*buffer_length = *buffer_length + 1;
}
}
}
}
void send_pdi_sdi_buffers_receive_do(char * pdi_buffer, int pdi_buffer_length_bytes, char * sdi_buffer, int sdi_buffer_length_bytes, char * do_buffer, int do_buffer_length_bytes, int skipping_cycles, int * time_cycles){
int j;
int pdi_iter, sdi_iter, do_iter;
unsigned int temp_data;
int last_block;
int state_pdi_sending = 0;
int state_pdi_sending_skipping = 0;
int state_sdi_sending = 0;
int state_sdi_sending_skipping = 0;
int state_do_receiving = 0;
int state_do_receiving_skipping = 0;
pdi_iter = sdi_iter = do_iter = 0;
*time_cycles = 0;
while((pdi_iter < pdi_buffer_length_bytes) || (sdi_iter < sdi_buffer_length_bytes) || (do_iter < do_buffer_length_bytes) || (state_do_receiving != 0) || (state_sdi_sending != 0) || (state_pdi_sending != 0)){
if((pdi_iter < pdi_buffer_length_bytes) || (state_pdi_sending != 0)){
if(state_pdi_sending == 0){
temp_data = 0;
for(j = 0; (j < G_PWIDTH); j += 8){
if((pdi_iter < pdi_buffer_length_bytes)){
temp_data = temp_data << 8;
temp_data |= ((pdi_buffer[pdi_iter]) & 0x00FF);
pdi_iter++;
}
}
dut->pdi_data = temp_data;
dut->pdi_valid = 1;
if(dut->pdi_ready == 0){
state_pdi_sending = 1;
}
else{
if(skipping_cycles > 0){
state_pdi_sending = 2;
state_pdi_sending_skipping = 0;
} else {
state_pdi_sending = 0;
}
}
}
else if(state_pdi_sending == 1){
if(dut->pdi_ready == 0){
state_pdi_sending = 1;
}
else{
if(skipping_cycles > 0){
state_pdi_sending = 2;
state_pdi_sending_skipping = 0;
} else {
state_pdi_sending = 0;
}
}
}
else if(state_pdi_sending == 2){
dut->pdi_data = 0;
dut->pdi_valid = 0;
if(state_pdi_sending_skipping < skipping_cycles){
state_pdi_sending_skipping++;
} else{
state_pdi_sending = 0;
}
}
else{
state_pdi_sending = 0;
}
}
else{
dut->pdi_data = 0;
dut->pdi_valid = 0;
}
if((sdi_iter < sdi_buffer_length_bytes) || (state_sdi_sending != 0)){
if(state_sdi_sending == 0){
temp_data = 0;
for(j = 0; (j < G_SWIDTH); j += 8){
if((sdi_iter < sdi_buffer_length_bytes)){
temp_data = temp_data << 8;
temp_data |= ((sdi_buffer[sdi_iter]) & 0x00FF);
sdi_iter++;
}
}
dut->sdi_data = temp_data;
dut->sdi_valid = 1;
if(dut->sdi_ready == 0){
state_sdi_sending = 1;
}
else{
if(skipping_cycles > 0){
state_sdi_sending = 2;
state_sdi_sending_skipping = 0;
} else {
state_sdi_sending = 0;
}
}
}
else if(state_sdi_sending == 1){
if(dut->sdi_ready == 0){
state_sdi_sending = 1;
}
else{
if(skipping_cycles > 0){
state_sdi_sending = 2;
state_sdi_sending_skipping = 0;
} else {
state_sdi_sending = 0;
}
}
}
else if(state_sdi_sending == 2){
dut->sdi_data = 0;
dut->sdi_valid = 0;
if(state_sdi_sending_skipping < skipping_cycles){
state_sdi_sending_skipping++;
} else{
state_sdi_sending = 0;
}
}
else{
state_sdi_sending = 0;
}
}
else{
dut->sdi_data = 0;
dut->sdi_valid = 0;
}
if((do_iter < do_buffer_length_bytes) || (state_do_receiving != 0)){
if(state_do_receiving == 0){
dut->do_ready = 1;
if(dut->do_valid == 0){
state_do_receiving = 0;
}
else{
temp_data = dut->do_data;
last_block = dut->do_last;
for(j = 0; (j < G_PWIDTH); j += 8){
do_buffer[do_iter] = (temp_data >> (G_PWIDTH - 8 - j)) & 0xFF;
do_iter++;
}
state_do_receiving = 0;
if(state_do_receiving_skipping < skipping_cycles){
state_do_receiving_skipping++;
state_do_receiving = 1;
} else{
state_do_receiving_skipping = 0;
state_do_receiving = 0;
}
}
}
else if(state_do_receiving == 1){
dut->do_ready = 0;
if(state_do_receiving_skipping < skipping_cycles){
state_do_receiving_skipping++;
state_do_receiving = 1;
} else{
state_do_receiving_skipping = 0;
state_do_receiving = 0;
}
}
}
else{
dut->do_ready = 0;
}
*time_cycles = *time_cycles + 1;
clock_tick();
}
dut->pdi_data = 0;
dut->pdi_valid = 0;
dut->sdi_data = 0;
dut->sdi_valid = 0;
dut->do_ready = 0;
}
int dut_hash(char * message_in, int message_in_length_bytes, char * true_hash_out, int hash_out_length_bytes){
int temp_header, temp_status, temp_instruction;
int temp_message_in_amount_sent, temp_message_in_amount_remaining, temp_message_in_amount_to_send, temp_hash_out_amount_received, temp_hash_out_amount_remaining;
char pdi_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int pdi_buffer_size;
char true_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int true_do_buffer_size;
char test_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int test_do_buffer_size;
int i;
int skipping_cycles;
int time_cycles;
pdi_buffer_size = true_do_buffer_size = test_do_buffer_size = 0;
temp_message_in_amount_sent = 0;
temp_hash_out_amount_received = 0;
// Hash instruction
temp_instruction = 0x80;
add_instruction_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_instruction);
do{
temp_message_in_amount_remaining = message_in_length_bytes - temp_message_in_amount_sent;
temp_message_in_amount_to_send = (((temp_message_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_message_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of message to hash
// header type (hash message)
temp_header = 0x7 << 28;
// header partial
temp_header |= ((((temp_message_in_amount_remaining) > 0) && ((temp_message_in_amount_remaining) < G_MAXIMUM_DATA_SEGMENT_SIZE)) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((temp_message_in_amount_remaining) < G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_message_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= (((temp_message_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 24;
temp_header |= temp_message_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send hash data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &message_in[temp_message_in_amount_sent], temp_message_in_amount_to_send);
temp_message_in_amount_sent += temp_message_in_amount_to_send;
} while(temp_message_in_amount_sent < message_in_length_bytes);
// Assume there is only one segment for the hash output.
add_header_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0x93000000 + hash_out_length_bytes);
add_data_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, true_hash_out, hash_out_length_bytes);
add_status_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0xE0);
for (skipping_cycles = 0; skipping_cycles < SKIPPING_TESTS_MAX; skipping_cycles++){
send_pdi_sdi_buffers_receive_do(pdi_buffer, pdi_buffer_size, pdi_buffer, 0, test_do_buffer, true_do_buffer_size, skipping_cycles, &time_cycles);
if(skipping_cycles == 0){
printf("Total time for hashing %d cycles, skip %d \n", time_cycles, skipping_cycles);
}
if(memcmp(test_do_buffer, true_do_buffer, true_do_buffer_size) != 0){
printf("Do buffers do no match\n");
printf("Skipping value set = %d\n", skipping_cycles);
printf("Expected buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (true_do_buffer[i] & 0x00FF));
}
printf("\n");
printf("Received buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (test_do_buffer[i] & 0x00FF));
}
printf("\n");
return 1;
}
}
return 0;
}
int dut_aead_enc(char * key_in, int key_in_length_bytes, char * nonce_in, int nonce_in_length_bytes, char * associated_data_in, int associated_data_in_length_bytes, char * plaintext_in, int plaintext_in_length_bytes, char * ciphertext_out, int ciphertext_out_length_bytes){
int temp_header, temp_status, temp_instruction;
int temp_key_in_amount_sent, temp_key_in_amount_remaining, temp_key_in_amount_to_send;
int temp_nonce_in_amount_sent, temp_nonce_in_amount_remaining, temp_nonce_in_amount_to_send;
int temp_associated_data_in_amount_sent, temp_associated_data_in_amount_remaining, temp_associated_data_in_amount_to_send;
int temp_plaintext_in_amount_sent, temp_plaintext_in_amount_remaining, temp_plaintext_in_amount_to_send;
int temp_ciphertext_out_length_bytes, temp_ciphertext_out_amount_received, temp_ciphertext_out_amount_remaining;
int temp_tag_out_length_bytes;
char pdi_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int pdi_buffer_size;
char sdi_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int sdi_buffer_size;
char true_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int true_do_buffer_size;
char test_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int test_do_buffer_size;
int i;
int skipping_cycles;
int time_cycles;
pdi_buffer_size = sdi_buffer_size = true_do_buffer_size = test_do_buffer_size = 0;
temp_key_in_amount_sent = 0;
temp_nonce_in_amount_sent = 0;
temp_associated_data_in_amount_sent = 0;
temp_plaintext_in_amount_sent = 0;
temp_ciphertext_out_amount_received = 0;
// Activate key instruction
temp_instruction = 0x70;
add_instruction_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_instruction);
// Send key instruction
temp_instruction = 0x40;
add_instruction_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, temp_instruction);
// Send key data
do{
temp_key_in_amount_remaining = key_in_length_bytes - temp_key_in_amount_sent;
temp_key_in_amount_to_send = (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_key_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of key to encrypt
// header type (key message)
temp_header = 0xC << 28;
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((temp_key_in_amount_remaining) > 0) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 24;
temp_header |= temp_key_in_amount_to_send;
add_header_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, temp_header);
// Send key data
add_data_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, &key_in[temp_key_in_amount_sent], temp_key_in_amount_to_send);
temp_key_in_amount_sent += temp_key_in_amount_to_send;
}
while(temp_key_in_amount_sent < key_in_length_bytes);
// Start encryption instruction
temp_instruction = 0x20;
add_instruction_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_instruction);
// Send nonce data
do{
temp_nonce_in_amount_remaining = nonce_in_length_bytes - temp_nonce_in_amount_sent;
temp_nonce_in_amount_to_send = (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_nonce_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of nonce to encrypt
// header type (nonce message)
temp_header = 0xD << 28;
temp_header |= (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((associated_data_in_length_bytes == 0) && (plaintext_in_length_bytes == 0) && (temp_nonce_in_amount_sent == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= 0 << 24;
temp_header |= temp_nonce_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send nonce data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &nonce_in[temp_nonce_in_amount_sent], temp_nonce_in_amount_to_send);
temp_nonce_in_amount_sent += temp_nonce_in_amount_to_send;
}
while(temp_nonce_in_amount_sent < nonce_in_length_bytes);
// Send associated data
do{
temp_associated_data_in_amount_remaining = associated_data_in_length_bytes - temp_associated_data_in_amount_sent;
temp_associated_data_in_amount_to_send = (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_associated_data_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of associated data to encrypt
// header type (associated data message)
temp_header = 0x1 << 28;
temp_header |= (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((associated_data_in_length_bytes > 0) && (temp_associated_data_in_amount_sent == 0) && (plaintext_in_length_bytes == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= 0 << 24;
temp_header |= temp_associated_data_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send associated data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &associated_data_in[temp_associated_data_in_amount_sent], temp_associated_data_in_amount_to_send);
temp_associated_data_in_amount_sent += temp_associated_data_in_amount_to_send;
}
while(temp_associated_data_in_amount_sent < associated_data_in_length_bytes);
// Send plaintext
// Receive ciphertext
do{
temp_plaintext_in_amount_remaining = plaintext_in_length_bytes - temp_plaintext_in_amount_sent;
temp_ciphertext_out_amount_remaining = ciphertext_out_length_bytes - temp_ciphertext_out_amount_received;
temp_plaintext_in_amount_to_send = (((temp_plaintext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_plaintext_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of plaintext to encrypt
// header type (plaintext message)
temp_header = 0x4 << 28;
temp_header |= (((temp_plaintext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((plaintext_in_length_bytes > 0) && (temp_plaintext_in_amount_sent == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_plaintext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= (((temp_plaintext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 24;;
temp_header |= temp_plaintext_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Receive ciphertext header
add_header_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0x50000000 + ((((temp_plaintext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25) + temp_plaintext_in_amount_to_send);
// Send plaintext data
// Receive ciphertext data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &plaintext_in[temp_plaintext_in_amount_sent], temp_plaintext_in_amount_to_send);
add_data_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, &ciphertext_out[temp_ciphertext_out_amount_received], temp_plaintext_in_amount_to_send);
temp_plaintext_in_amount_sent += temp_plaintext_in_amount_to_send;
temp_ciphertext_out_amount_received += temp_plaintext_in_amount_to_send;
}
while(temp_plaintext_in_amount_sent < plaintext_in_length_bytes);
// Receive tag header
temp_ciphertext_out_amount_remaining = ciphertext_out_length_bytes - temp_ciphertext_out_amount_received;
add_header_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0x83000000 + temp_ciphertext_out_amount_remaining);
// Receive tag
add_data_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, &ciphertext_out[temp_ciphertext_out_amount_received], temp_ciphertext_out_amount_remaining);
add_status_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0xE0);
// Perform all operations
for (skipping_cycles = 0; skipping_cycles < SKIPPING_TESTS_MAX; skipping_cycles++){
send_pdi_sdi_buffers_receive_do(pdi_buffer, pdi_buffer_size, sdi_buffer, sdi_buffer_size, test_do_buffer, true_do_buffer_size, skipping_cycles, &time_cycles);
clock_tick();
clock_tick();
if(skipping_cycles == 0){
printf("Total time for AEAD encryption %d cycles\n", time_cycles);
}
if(memcmp(test_do_buffer, true_do_buffer, true_do_buffer_size) != 0){
printf("Do buffers do no match\n");
printf("Skipping value set = %d\n", skipping_cycles);
printf("Expected buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (true_do_buffer[i] & 0x00FF));
}
printf("\n");
printf("Received buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (test_do_buffer[i] & 0x00FF));
}
printf("\n");
return 1;
}
}
return 0;
}
int dut_aead_dec(char * key_in, int key_in_length_bytes, char * nonce_in, int nonce_in_length_bytes, char * associated_data_in, int associated_data_in_length_bytes, char * ciphertext_in, int ciphertext_in_length_bytes, char * plaintext_out, int plaintext_out_length_bytes, int true_core_status){
int temp_header, temp_status, temp_instruction;
int temp_key_in_amount_sent, temp_key_in_amount_remaining, temp_key_in_amount_to_send;
int temp_nonce_in_amount_sent, temp_nonce_in_amount_remaining, temp_nonce_in_amount_to_send;
int temp_associated_data_in_amount_sent, temp_associated_data_in_amount_remaining, temp_associated_data_in_amount_to_send;
int temp_ciphertext_in_amount_sent, temp_ciphertext_in_amount_remaining, temp_ciphertext_in_amount_to_send;
int temp_plaintext_out_amount_received, temp_plaintext_out_amount_remaining, temp_plaintext_out_amount_to_receive;
int temp_tag_in_length_bytes;
char pdi_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int pdi_buffer_size;
char sdi_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int sdi_buffer_size;
char true_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int true_do_buffer_size;
char test_do_buffer[G_MAXIMUM_BUFFER_SIZE_ARRAY];
int test_do_buffer_size;
int i;
int skipping_cycles;
int time_cycles;
pdi_buffer_size = sdi_buffer_size = true_do_buffer_size = test_do_buffer_size = 0;
temp_key_in_amount_sent = 0;
temp_nonce_in_amount_sent = 0;
temp_associated_data_in_amount_sent = 0;
temp_ciphertext_in_amount_sent = 0;
temp_plaintext_out_amount_received = 0;
// Activate key instruction
temp_instruction = 0x70;
add_instruction_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_instruction);
// Send key instruction
temp_instruction = 0x40;
add_instruction_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, temp_instruction);
// Send key data
do{
temp_key_in_amount_remaining = key_in_length_bytes - temp_key_in_amount_sent;
temp_key_in_amount_to_send = (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_key_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of key to decrypt
// header type (key message)
temp_header = 0xC << 28;
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((temp_key_in_amount_remaining) > 0) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= (((temp_key_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 24;
temp_header |= temp_key_in_amount_to_send;
add_header_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, temp_header);
// Send key data
add_data_to_buffer(sdi_buffer, &sdi_buffer_size, G_SWIDTH, &key_in[temp_key_in_amount_sent], temp_key_in_amount_to_send);
temp_key_in_amount_sent += temp_key_in_amount_to_send;
}
while(temp_key_in_amount_sent < key_in_length_bytes);
// Start decryption instruction
temp_instruction = 0x30;
add_instruction_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_instruction);
// Send nonce data
do{
temp_nonce_in_amount_remaining = nonce_in_length_bytes - temp_nonce_in_amount_sent;
temp_nonce_in_amount_to_send = (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_nonce_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of nonce to decrypt
// header type (nonce message)
temp_header = 0xD << 28;
temp_header |= (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((associated_data_in_length_bytes == 0) && (plaintext_out_length_bytes == 0) && (temp_nonce_in_amount_sent == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_nonce_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= 0 << 24;
temp_header |= temp_nonce_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send nonce data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &nonce_in[temp_nonce_in_amount_sent], temp_nonce_in_amount_to_send);
temp_nonce_in_amount_sent += temp_nonce_in_amount_to_send;
}
while(temp_nonce_in_amount_sent < nonce_in_length_bytes);
// Send associated data
do{
temp_associated_data_in_amount_remaining = associated_data_in_length_bytes - temp_associated_data_in_amount_sent;
temp_associated_data_in_amount_to_send = (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_associated_data_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of associated data to decrypt
// header type (associated data message)
temp_header = 0x1 << 28;
temp_header |= (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((associated_data_in_length_bytes > 0) && (temp_associated_data_in_amount_sent == 0) && (plaintext_out_length_bytes == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_associated_data_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= 0 << 24;
temp_header |= temp_associated_data_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send associated data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &associated_data_in[temp_associated_data_in_amount_sent], temp_associated_data_in_amount_to_send);
temp_associated_data_in_amount_sent += temp_associated_data_in_amount_to_send;
}
while(temp_associated_data_in_amount_sent < associated_data_in_length_bytes);
// Send ciphertext
// Receive plaintext
do{
temp_ciphertext_in_amount_remaining = plaintext_out_length_bytes - temp_ciphertext_in_amount_sent;
temp_plaintext_out_amount_remaining = plaintext_out_length_bytes - temp_plaintext_out_amount_received;
temp_ciphertext_in_amount_to_send = (((temp_ciphertext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? G_MAXIMUM_DATA_SEGMENT_SIZE-1 : (temp_ciphertext_in_amount_remaining)) & G_SEGMENT_DATA_SIZE_MASK;
// Send header of ciphertext to decrypt
// header type (ciphertext message)
temp_header = 0x5 << 28;
temp_header |= (((temp_ciphertext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 1 : 0) << 27;
// header end of input (active high)
temp_header |= (((plaintext_out_length_bytes > 0) && (temp_ciphertext_in_amount_sent == 0)) ? 1 : 0) << 26;
// header end of type (active high)
temp_header |= (((temp_ciphertext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25;
// header last (active high)
temp_header |= 0 << 24;
temp_header |= temp_ciphertext_in_amount_to_send;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Receive plaintext header
add_header_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, 0x40000000 + ((((temp_ciphertext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 25) + ((((temp_ciphertext_in_amount_remaining) >= G_MAXIMUM_DATA_SEGMENT_SIZE) ? 0 : 1) << 24) + temp_ciphertext_in_amount_to_send);
// Send ciphertext data
// Receive plaintext data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &ciphertext_in[temp_ciphertext_in_amount_sent], temp_ciphertext_in_amount_to_send);
add_data_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, &plaintext_out[temp_plaintext_out_amount_received], temp_ciphertext_in_amount_to_send);
temp_ciphertext_in_amount_sent += temp_ciphertext_in_amount_to_send;
temp_plaintext_out_amount_received += temp_ciphertext_in_amount_to_send;
}
while(temp_ciphertext_in_amount_sent < plaintext_out_length_bytes);
temp_tag_in_length_bytes = ciphertext_in_length_bytes - plaintext_out_length_bytes;
// Send tag
// Send header of tag to verify
// header type (tag message)
temp_header = 0x8 << 28;
temp_header |= 0 << 27;
// header end of input (active high)
temp_header |= 0 << 26;
// header end of type (active high)
temp_header |= 1 << 25;
// header last (active high)
temp_header |= 1 << 24;
temp_header |= temp_tag_in_length_bytes;
add_header_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, temp_header);
// Send tag data
add_data_to_buffer(pdi_buffer, &pdi_buffer_size, G_PWIDTH, &ciphertext_in[temp_ciphertext_in_amount_sent], temp_tag_in_length_bytes);
// Receive status header
add_status_to_buffer(true_do_buffer, &true_do_buffer_size, G_PWIDTH, true_core_status);
// Perform all operations
for (skipping_cycles = 0; skipping_cycles < SKIPPING_TESTS_MAX; skipping_cycles++){
send_pdi_sdi_buffers_receive_do(pdi_buffer, pdi_buffer_size, sdi_buffer, sdi_buffer_size, test_do_buffer, true_do_buffer_size, skipping_cycles, &time_cycles);
if(skipping_cycles == 0){
printf("Total time for AEAD decryption %d cycles\n", time_cycles);
}
if(memcmp(test_do_buffer, true_do_buffer, true_do_buffer_size) != 0){
printf("Do buffers do no match\n");
printf("Skipping value set = %d\n", skipping_cycles);
printf("Expected buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (true_do_buffer[i] & 0x00FF));
}
printf("\n");
printf("Received buffer:\n");
for(i = 0; i < true_do_buffer_size; i++){
printf("%02x", (test_do_buffer[i] & 0x00FF));
}
printf("\n");
return 1;
}
}
return 0;
}
};
void read_until_get_character(FILE * file_read, char character_to_be_found){
char temp_char;
temp_char = fgetc(file_read);
while((temp_char != character_to_be_found) && (!feof(file_read))){
temp_char = fgetc(file_read);
}
}
void read_ignore_character(FILE * file_read, char character_to_be_ignored, char * last_character){
char temp_char;
temp_char = fgetc(file_read);
while((temp_char == character_to_be_ignored) && (!feof(file_read))){
temp_char = fgetc(file_read);
}
*last_character = temp_char;
}
void decode_hex_character(char t1, char t2, char * out){
if((t1 >= '0') && (t1 <= '9')){
*out = t1 - '0';
} else {
*out = t1 - 'A' + 10;
}
*out = *out << 4;
if((t2 >= '0') && (t2 <= '9')){
*out += t2 - '0';
} else {
*out += t2 - 'A' + 10;
}
}
int main(int argc, char **argv) {
FILE * hash_file;
FILE * aead_file;
char buffer_read [G_MAXIMUM_BUFFER_SIZE_ARRAY];
char temp_char1, temp_char2, temp_value;
int count;
int key_size, nonce_size, pt_size, ad_size, ct_size;
int test_verification;
int test_error;
int core_status;
int i, j;
char test_input_key_enc [G_MAXIMUM_KEY_SIZE];
char test_input_nonce_enc [G_MAXIMUM_NONCE_SIZE];
char test_input_pt_enc [G_MAXIMUM_PLAINTEXT_SIZE];
char test_input_ad_enc [G_MAXIMUM_ASSOCIATED_DATA_SIZE];
char test_output_ct_enc [G_MAXIMUM_CIPHERTEXT_SIZE];
char true_output_ct_enc [G_MAXIMUM_CIPHERTEXT_SIZE];
char test_input_key_dec [G_MAXIMUM_KEY_SIZE];
char test_input_nonce_dec [G_MAXIMUM_NONCE_SIZE];
char test_input_ct_dec [G_MAXIMUM_CIPHERTEXT_SIZE];
char test_input_ad_dec [G_MAXIMUM_ASSOCIATED_DATA_SIZE];
char test_output_pt_dec [G_MAXIMUM_PLAINTEXT_SIZE];
char true_output_pt_dec [G_MAXIMUM_PLAINTEXT_SIZE];
Testbench * tb;
// Call commandArgs first!
Verilated::commandArgs(argc, argv);
#ifdef DUMP_TRACE_ON
Verilated::traceEverOn(true);
#endif
// Instantiate our design
tb = new Testbench(MAX_SIMULATION_TICKS);
test_verification = 0;
test_error = 0;
memset(test_input_key_enc, 0, sizeof(char)*G_MAXIMUM_KEY_SIZE);
memset(test_input_nonce_enc, 0, sizeof(char)*G_MAXIMUM_NONCE_SIZE);
memset(test_input_pt_enc, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
memset(test_input_ad_enc, 0, sizeof(char)*G_MAXIMUM_ASSOCIATED_DATA_SIZE);
memset(test_output_ct_enc, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(true_output_ct_enc, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(test_input_key_dec, 0, sizeof(char)*G_MAXIMUM_KEY_SIZE);
memset(test_input_nonce_dec, 0, sizeof(char)*G_MAXIMUM_NONCE_SIZE);
memset(test_input_ct_dec, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(test_input_ad_dec, 0, sizeof(char)*G_MAXIMUM_ASSOCIATED_DATA_SIZE);
memset(test_output_pt_dec, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
memset(true_output_pt_dec, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
tb->reset();
count = 0;
test_error = 0;
#if G_SKIP_AEAD_TEST == 0
printf("Start of the aead test\n");
aead_file = fopen(G_FNAME_AEAD_KAT, "r");
if(!aead_file != 0){
printf("Could not open file %s\n", G_FNAME_AEAD_KAT);
}
while(!feof(aead_file) && (count < G_MAXIMUM_NUMBER_OF_TESTS) && (test_error == 0)) {
read_until_get_character(aead_file, '=');
fscanf(aead_file, "%d", &count);
#if PRINT_CURRENT_TEST_NUMBER != 0
printf("Test number %d\n", count);
#endif
memset(test_input_key_enc, 0, sizeof(char)*G_MAXIMUM_KEY_SIZE);
memset(test_input_nonce_enc, 0, sizeof(char)*G_MAXIMUM_NONCE_SIZE);
memset(test_input_pt_enc, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
memset(test_input_ad_enc, 0, sizeof(char)*G_MAXIMUM_ASSOCIATED_DATA_SIZE);
memset(test_output_ct_enc, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(true_output_ct_enc, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(test_input_key_dec, 0, sizeof(char)*G_MAXIMUM_KEY_SIZE);
memset(test_input_nonce_dec, 0, sizeof(char)*G_MAXIMUM_NONCE_SIZE);
memset(test_input_ct_dec, 0, sizeof(char)*G_MAXIMUM_CIPHERTEXT_SIZE);
memset(test_input_ad_dec, 0, sizeof(char)*G_MAXIMUM_ASSOCIATED_DATA_SIZE);
memset(test_output_pt_dec, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
memset(true_output_pt_dec, 0, sizeof(char)*G_MAXIMUM_PLAINTEXT_SIZE);
// Read key
read_until_get_character(aead_file, '=');
read_ignore_character(aead_file, ' ', &temp_char1);
key_size = 0;
while(temp_char1 != '\n') {
temp_char2 = fgetc(aead_file);
decode_hex_character(temp_char1, temp_char2, &test_input_key_enc[key_size]);
temp_char1 = fgetc(aead_file);
key_size++;
}
// Read nonce
read_until_get_character(aead_file, '=');
read_ignore_character(aead_file, ' ', &temp_char1);
nonce_size = 0;
while(temp_char1 != '\n') {
temp_char2 = fgetc(aead_file);
decode_hex_character(temp_char1, temp_char2, &test_input_nonce_enc[nonce_size]);
temp_char1 = fgetc(aead_file);
nonce_size++;
}
// Read PT
read_until_get_character(aead_file, '=');
read_ignore_character(aead_file, ' ', &temp_char1);
pt_size = 0;
while(temp_char1 != '\n') {
temp_char2 = fgetc(aead_file);
decode_hex_character(temp_char1, temp_char2, &test_input_pt_enc[pt_size]);
temp_char1 = fgetc(aead_file);
pt_size++;
}
// Read AD
read_until_get_character(aead_file, '=');
read_ignore_character(aead_file, ' ', &temp_char1);
ad_size = 0;
while(temp_char1 != '\n') {
temp_char2 = fgetc(aead_file);
decode_hex_character(temp_char1, temp_char2, &test_input_ad_enc[ad_size]);
temp_char1 = fgetc(aead_file);
ad_size++;
}
// Read CT
read_until_get_character(aead_file, '=');
read_ignore_character(aead_file, ' ', &temp_char1);
ct_size = 0;
while(temp_char1 != '\n') {
temp_char2 = fgetc(aead_file);
decode_hex_character(temp_char1, temp_char2, &true_output_ct_enc[ct_size]);
temp_char1 = fgetc(aead_file);
ct_size++;
}
// Perform the encryption procedure
test_error += tb->dut_aead_enc(test_input_key_enc, key_size, test_input_nonce_enc, nonce_size, test_input_ad_enc, ad_size, test_input_pt_enc, pt_size, true_output_ct_enc, ct_size);
if(test_error != 0){
tb->clock_tick();
break;
}
tb->clock_tick();
// Wait the last permutation squeeze
for(j = 0; j < 25; j++){
tb->clock_tick();
}
// Decryption correct tag
memcpy(test_input_key_dec, test_input_key_enc, key_size);
memcpy(test_input_nonce_dec, test_input_nonce_enc, nonce_size);
memcpy(test_input_ad_dec, test_input_ad_enc, ad_size);
memcpy(test_input_ct_dec, true_output_ct_enc, ct_size);
memcpy(true_output_pt_dec, test_input_pt_enc, pt_size);
// Perform the decryption procedure
test_error += tb->dut_aead_dec(test_input_key_dec, key_size, test_input_nonce_dec, nonce_size, test_input_ad_dec, ad_size, test_input_ct_dec, ct_size, true_output_pt_dec, pt_size, 0xE0);
if(test_error != 0){
tb->clock_tick();
break;
}
tb->clock_tick();
// Wait the last permutation squeeze
for(j = 0; j < 25; j++){
tb->clock_tick();
}
// Decryption incorrect tag
memcpy(test_input_key_dec, test_input_key_enc, key_size);
memcpy(test_input_nonce_dec, test_input_nonce_enc, nonce_size);
memcpy(test_input_ad_dec, test_input_ad_enc, ad_size);
memcpy(test_input_ct_dec, true_output_ct_enc, ct_size);
memcpy(true_output_pt_dec, test_input_pt_enc, pt_size);
test_input_ct_dec[pt_size] = test_input_ct_dec[pt_size] ^ 0xFF;
// Perform the decryption procedure
test_error += tb->dut_aead_dec(test_input_key_dec, key_size, test_input_nonce_dec, nonce_size, test_input_ad_dec, ad_size, test_input_ct_dec, ct_size, true_output_pt_dec, pt_size, 0xF0);
if(test_error != 0){
tb->clock_tick();
break;
}
tb->clock_tick();
// Wait the last permutation squeeze
for(j = 0; j < 25; j++){
tb->clock_tick();
}
read_ignore_character(aead_file, '\n', &temp_char1);
}
fclose(aead_file);
printf("End of the aead test\n");
#endif
delete tb;
} | [
"pedro.massolino@hotmail.com"
] | pedro.massolino@hotmail.com |
c3ba03bfa92091d5f29d8d017a704d835ce605ab | 0a729f483c946538a2864fcd8f27fb7d844d7bfa | /net/service/k_net_model_service.cpp | f5985a8799e31e459883c0c662411c5b8727e235 | [
"Apache-2.0"
] | permissive | huangshihuai/hyper | 257a9e31cccb8c9b754a8a7057cadfed7d91cba3 | 609d13a990dc886d0b86e24d7ecc001c20d0cd09 | refs/heads/master | 2020-03-08T02:19:22.815765 | 2020-01-08T01:38:32 | 2020-01-08T01:38:32 | 127,856,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | cpp | #include "net/acceptor.h"
#include "net/options.h"
#include "base/macro.h"
#include "net/event_loop_thread.h"
#include "net/channel.h"
#include "net/service/k_net_model_service.h"
#include "net/socket.h"
namespace hyper {
namespace net {
namespace service {
KNetModelService::KNetModelService() {
m_socketOption = std::make_shared<SocketOption>();
}
KNetModelService::~KNetModelService() {
}
bool KNetModelService::start(std::shared_ptr<IOptions> option) {
if (m_threadNumber <= 0) {
return false;
}
m_eventLoopThreadPoll.resize(m_threadNumber);
auto socketOption = std::make_shared<SocketOption>();
socketOption->setKeepAlive(option->getKeepAlive());
socketOption->setReuseAddr(option->getReuseAddr());
socketOption->setReusePort(option->getReusePort());
socketOption->setTcpNoDelay(option->getTcpNoDelay());
socketOption->setSocketDomain(option->getSocketDomain());
socketOption->setNonBlock(true);
for (size_t index = 0; index < m_threadNumber; ++index) {
auto acceptor = new Acceptor;
auto socket = std::make_shared<Socket>();
socket->setIp(option->getIp());
socket->setPort(option->getPort());
socket->setSocketOption(socketOption);
acceptor->setSocket(socket);
acceptor->setEvents(HYPER_READ);
acceptor->setConnectorFactory(option->getConnectFactory());
acceptor->startListen();
acceptor->setProtocol(option->getProtocols());
m_eventLoopThreadPoll[index] = std::make_shared<EventLoopThread>();
HYPER_COMPARE(m_eventLoopThreadPoll[index]->init(),
0, !=, return false, "init the event loop thread failed.");
m_eventLoopThreadPoll[index]->addNotification(acceptor);
HYPER_COMPARE(m_eventLoopThreadPoll[index]->start(),
true, !=, return false, "start the event loop thread failed.");
}
return true;
}
void KNetModelService::quit() {
for (auto eventLoopThread : m_eventLoopThreadPoll) {
eventLoopThread->quit();
}
}
void KNetModelService::waitingQuit() {
for (auto eventLoopThread : m_eventLoopThreadPoll) {
eventLoopThread->waitingQuit();
}
}
}
}
}
| [
"garen.huang@ringcentral.com"
] | garen.huang@ringcentral.com |
f4d314edfa9ca273aa82546afe3768215dc4e293 | 76b9789ce1de57c582b7234cfd06b234ee3cd5aa | /template.cpp | d021a1e11096df9e6f4f9cd71dc3566d20803f0e | [] | no_license | Codom/Template-Metaprogamming | d7ac144776e565b20289e70d6a7599a617ef3ae3 | cd6e20a0a6ae8f10a910afc4c85a2c21c265133f | refs/heads/master | 2020-04-30T12:47:40.332598 | 2019-03-21T02:28:41 | 2019-03-21T02:28:41 | 176,835,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | /*
* template.cpp
* Copyright (C) 2019 chris <chris@christopher>
*
* Distributed under terms of the MIT license.
*/
#include <iostream>
template<int N> struct Factorial{
static const int result = N*Factorial<N-1>::result;
};
template <> struct Factorial<0>{
static const int result = 1;
};
template <int N, int D> struct Frak{
static const long Num = N;
static const long Dem = D;
};
template <int N, typename F> struct ScalarMultiplication{
typedef Frak<N*F::Num, N*F::Dem> result;
};
int main()
{
std::cout << "Factorial of 7 = " << Factorial<7>::result << std::endl;
typedef Frak<2, 3> TwoThirds;
typedef ScalarMultiplication<3, TwoThirds>::result ThreeTwoThirds;
std::cout << ThreeTwoThirds::Num;
return 0;
}
| [
"christopher.r.odom@gmail.com"
] | christopher.r.odom@gmail.com |
0b5eb7f2aa0a06918179c3cff31e3b12517f09b3 | bbbd742396f7e94931fa0d21673dbd79869bee01 | /binary_tree/findBottomLeftTreeValue.cpp | 84e41b59c55edfe99289332bab173c82e0e20a10 | [] | no_license | Shuyang1996/competitive_programing | 81bbc82b52cc0cf1c3debe3a7737f2709af38466 | 79bf3a89e54535715b949191ef2dbe093100725c | refs/heads/master | 2020-04-12T07:35:27.591841 | 2017-07-02T21:37:42 | 2017-07-02T21:37:42 | 58,789,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue < TreeNode *> current, next;
if( root == nullptr ){
return 0;
} else {
current.push(root);
}
vector<int> result;
while(!current.empty()){
vector<int> level;
while(!current.empty()){
TreeNode * node = current.front();
current.pop();
level.push_back(node->val);
if(node->left) next.push(node->left);
if(node->right) next.push(node->right);
}
swap(current,next);
swap(result, level);
}
return result.front();
}
}; | [
"yu2@cooper.edu"
] | yu2@cooper.edu |
a00f437a9eaa01201856da756840c096dc053a63 | 524c27e331111f07874a7fc3d35f1c0b7594db64 | /src/libtsduck/dtv/descriptors/tsServiceListDescriptor.cpp | e87333113ba6abe98313afad07b3353bb253be5c | [
"BSD-2-Clause"
] | permissive | l3akage/tsduck | 27a486b880467ad5dcc8ecb51ccf127e2040d2fa | 2f45edf3aa511487104bb78413dc65a468f82178 | refs/heads/master | 2023-07-13T01:30:21.998146 | 2021-08-17T20:28:28 | 2021-08-17T20:28:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,103 | cpp | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
#include "tsServiceListDescriptor.h"
#include "tsDescriptor.h"
#include "tsNames.h"
#include "tsTablesDisplay.h"
#include "tsPSIRepository.h"
#include "tsPSIBuffer.h"
#include "tsDuckContext.h"
#include "tsxmlElement.h"
TSDUCK_SOURCE;
#define MY_XML_NAME u"service_list_descriptor"
#define MY_CLASS ts::ServiceListDescriptor
#define MY_DID ts::DID_SERVICE_LIST
#define MY_STD ts::Standards::DVB
TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Standard(MY_DID), MY_XML_NAME, MY_CLASS::DisplayDescriptor);
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
ts::ServiceListDescriptor::ServiceListDescriptor() :
AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),
entries()
{
}
ts::ServiceListDescriptor::ServiceListDescriptor(DuckContext& duck, const Descriptor& desc) :
ServiceListDescriptor()
{
deserialize(duck, desc);
}
void ts::ServiceListDescriptor::clearContent()
{
entries.clear();
}
ts::ServiceListDescriptor::Entry::Entry(uint16_t id, uint8_t type) :
service_id(id),
service_type(type)
{
}
//----------------------------------------------------------------------------
// Check if a service is present in the descriptor.
//----------------------------------------------------------------------------
bool ts::ServiceListDescriptor::hasService(uint16_t id) const
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
if (it->service_id == id) {
return true;
}
}
return false;
}
//----------------------------------------------------------------------------
// Add or replace a service.
//----------------------------------------------------------------------------
bool ts::ServiceListDescriptor::addService(uint16_t id, uint8_t type)
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
if (it->service_id == id) {
// The service alreay exists, only overwrite the service type.
if (it->service_type == type) {
return false; // descriptor not modified
}
else {
it->service_type = type;
return true; // descriptor modified
}
}
}
// The service is not found, it an entry.
entries.push_back(Entry(id, type));
return true; // descriptor modified
}
//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------
void ts::ServiceListDescriptor::serializePayload(PSIBuffer& buf) const
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
buf.putUInt16(it->service_id);
buf.putUInt8(it->service_type);
}
}
//----------------------------------------------------------------------------
// Deserialization
//----------------------------------------------------------------------------
void ts::ServiceListDescriptor::deserializePayload(PSIBuffer& buf)
{
while (buf.canRead()) {
const uint16_t id = buf.getUInt16();
const uint8_t type = buf.getUInt8();
entries.push_back(Entry(id, type));
}
}
//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------
void ts::ServiceListDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds)
{
while (buf.canReadBytes(3)) {
disp << margin << UString::Format(u"Service id: %d (0x%<X)", {buf.getUInt16()});
disp << ", Type: " << names::ServiceType(buf.getUInt8(), names::FIRST) << std::endl;
}
}
//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------
void ts::ServiceListDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
xml::Element* e = root->addElement(u"service");
e->setIntAttribute(u"service_id", it->service_id, true);
e->setIntAttribute(u"service_type", it->service_type, true);
}
}
//----------------------------------------------------------------------------
// XML deserialization
//----------------------------------------------------------------------------
bool ts::ServiceListDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)
{
xml::ElementVector children;
bool ok = element->getChildren(children, u"service", 0, MAX_ENTRIES);
for (size_t i = 0; ok && i < children.size(); ++i) {
Entry entry;
ok = children[i]->getIntAttribute(entry.service_id, u"service_id", true, 0, 0x0000, 0xFFFF) &&
children[i]->getIntAttribute(entry.service_type, u"service_type", true, 0, 0x00, 0xFF);
entries.push_back(entry);
}
return ok;
}
//----------------------------------------------------------------------------
// These descriptors shall be merged when present in the same list.
//----------------------------------------------------------------------------
ts::DescriptorDuplication ts::ServiceListDescriptor::duplicationMode() const
{
return DescriptorDuplication::MERGE;
}
bool ts::ServiceListDescriptor::merge(const AbstractDescriptor& desc)
{
const ServiceListDescriptor* other = dynamic_cast<const ServiceListDescriptor*>(&desc);
if (other == nullptr) {
return false;
}
else {
// Loop on all service entries in "other" descriptor.
for (auto oth = other->entries.begin(); oth != other->entries.end(); ++oth) {
// Replace entry with same service id in "this" descriptor.
bool found = false;
for (auto th = entries.begin(); !found && th != entries.end(); ++th) {
found = th->service_id == oth->service_id;
if (found) {
*th = *oth;
}
}
// Add service ids which were not found at end of the list.
if (!found) {
entries.push_back(*oth);
}
}
// If the result is too large, truncate it.
bool success = entries.size() <= MAX_ENTRIES;
while (entries.size() > MAX_ENTRIES) {
entries.pop_back();
}
return success;
}
}
| [
"thierry@lelegard.fr"
] | thierry@lelegard.fr |
062efd5bd551f91a0e5a8b31433bf9ec17e9c794 | e02ebc7157802ee5b041929a70128d3afdae1761 | /Codeforces/100/160/A. Twins.cpp | d590a1e74eecfae6407ce21d2c9b92bcbedbb091 | [] | no_license | Huvok/Competitive-Programming | 027fdf6bb1cda21559a62617536e1b17669201dc | 45cd94dd0758537a56e19fd4c81df5b92f22a23d | refs/heads/master | 2020-04-05T12:36:03.754491 | 2017-12-20T22:24:55 | 2017-12-20T22:24:55 | 95,174,138 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,783 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <functional>
#include <queue>
#include <bitset>
#include <sstream>
#include <set>
#include <iomanip>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <limits.h>
using namespace std;
// //AUTHOR: Hugo Garcia
// //PURPOSE: Competitive programming template
//======================================================================================================================
#define FOR(i, a, b) for(ll i=ll(a); i<ll(b); i++)
#define RFOR(i, a, b) for(ll i=ll(a); i>=ll(b); i--)
#define pb push_back
#define mp make_pair
#define lld I64d
#define all(a) (a).begin(), (a).end()
#define ifile(a) freopen((a), "r", stdin)
#define ofile(a) freopen((a), "w", stdout)
#define sync ios_base::sync_with_stdio(false)
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll, ll> ii;
typedef vector<ii> vii;
using namespace std;
//----------------------------------------------------------------------------------------------------------------------
ll arr[105];
//----------------------------------------------------------------------------------------------------------------------
int main()
{
ll intN;
cin >> intN;
ll intSum = 0;
FOR(intI, 0, intN)
{
cin >> arr[intI];
intSum += arr[intI];
}
sort(arr, arr + intN);
reverse(arr, arr + intN);
ll intCount = 0;
ll intCur = 0;
ll idx = 0;
while (intCur <= (intSum / 2.0))
{
intCur += arr[idx];
idx++;
intCount++;
}
cout << intCount << endl;
return 0;
}
//====================================================================================================================== | [
"hugo_os_95@hotmail.com"
] | hugo_os_95@hotmail.com |
f426b0b76a363b1e0ef26a04aff1a05e1ebd7257 | 4e11b73bab277eb0776f5a5f08ae3e9e4659b41d | /Player.cpp | 612c25be0ec76b1b6eec9449d46144dde6a0be6f | [] | no_license | zzyviolette/RogueLikeGame | b3fbee7fdaa658ca02584a4e3580e5f630447f88 | 41caa0296c203b68f54769765f87169d50e5c79b | refs/heads/master | 2020-04-02T02:58:23.744743 | 2019-01-22T18:50:42 | 2019-01-22T18:50:42 | 153,938,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,644 | cpp | #include<iostream>
#include<string>
#include<ostream>
#include<stdlib.h>
#include <curses.h>
#include"Jeu.hpp"
#include<ncurses.h>
#include"Objet.hpp"
#include <stdio.h>
#include <string.h>
#include"Player.hpp"
#include"Inventaire.hpp"
#include"Ecrand.hpp"
#include"Niveaux.hpp"
#include<vector>
using namespace std;
Player::Player(Position *a,int sant,int atak,char sym,int rap,int def,int sizeInv):Creature(a,sant,atak,sym,rap,def){
this->experience = 0;
this->inv = new Inventaire(sizeInv);
}
void Player::kungFu(Monstre * m,Niveaux * niveaux,int nan) {
m->setSanter(m->operator-(this));
if(m->getSanter() <= 0){
int i=rand()%4;
niveaux->editCaseZeeMatrice(m->getPosition()->getX(),m->getPosition()->getY(),this->getObjs()[i]);
if(m->getSymbol()=='B'){
this->setExperience(this->getExperience()+10);
}else if(m->getSymbol()=='K'){
this->setExperience(this->getExperience()+2);
}else if(m->getSymbol()=='A'){
this->setExperience(this->getExperience()+5);
}
niveaux->supprimeDuVector(nan);
}
}
void Player::putPlayer(){//player setup
mvprintw(this->getPosition()->getY(),this->getPosition()->getX(),">");
move(this->getPosition()->getY(),this->getPosition()->getX());
}
void Player::setExperience(int e){
this->experience = e;
}
void Player::possibleMove(Position* pos,char m,Jeu * jeu){//check position il faut changer ca et utilisé la matrice
int cur = jeu->getCurrent();
char next=jeu->getLevels()[cur]->getZeeMatrice()[pos->getX()][pos->getY()];
if (next=='.' || next=='@' || next=='#'){//espace
jeu->getLevels()[cur]->editCaseZeeMatrice(this->getPosition()->getX(),this->getPosition()->getY(), jeu->getLevels()[cur]->getSave()[this->getPosition()->getX()][this->getPosition()->getY()]);
this->getPosition()->setY(pos->getY());
this->getPosition()->setX(pos->getX());
this->setSymbol(m);
this->putCreature(jeu->getLevels()[cur]);
}else if (next=='K' || next=='A' || next=='B'){//monstre
//ici juste la boucle
for(int i=0; i<jeu->getLevels()[cur]->getMonstres().size(); i++){
if((pos->getY() == jeu->getLevels()[cur]->getMonstres()[i]->getPosition()->getY()) && (pos->getX() == jeu->getLevels()[cur]->getMonstres()[i]->getPosition()->getX())){
this->kungFu(jeu->getLevels()[cur]->getMonstres()[i],jeu->getLevels()[cur],i);
}
this->setSymbol(m);
}
}else if(next =='S'){
erase();
jeu->getLevels()[cur]->setPlayer(new Position(this->getPosition()->getX(),this->getPosition()->getY()));
this->putCreature(jeu->getLevels()[cur]);
if(jeu->getLevels()[cur+1]->getNumMonstre()==0){
//la premier fois , dessiner le niveaux , mettre l'escalier precedent et enregister les positions
jeu->getLevels()[cur+1]->dessineNiveaux();
jeu->getLevels()[cur+1]->setEscalierPre(jeu->getLevels()[cur]);
jeu->getLevels()[cur+1]->editCaseZeeMatrice(jeu->getLevels()[cur+1]->getEscalierPre()->getX(), jeu->getLevels()[cur+1]->getEscalierPre()->getY(), 'P');
jeu->getLevels()[cur+1]->editCaseSave(jeu->getLevels()[cur+1]->getEscalierPre()->getX(), jeu->getLevels()[cur+1]->getEscalierPre()->getY(), 'P');
int x = jeu->getLevels()[cur+1]->getEscalierPre()->getX()+1;
int y = jeu->getLevels()[cur+1]->getEscalierPre()->getY();
jeu->getLevels()[cur+1]->setPlayer(new Position(x,y));
jeu->getLevels()[cur+1]->editCaseZeeMatrice(x,y, this->getSymbol());
}
this->getPosition()->setX(jeu->getLevels()[cur+1]->getPlayer()->getX());
this->getPosition()->setY(jeu->getLevels()[cur+1]->getPlayer()->getY());
jeu->setCurrent(cur+1);
}else if(next =='P'){
erase();
//afficher toutes les positions de niveaux precedent
this->putCreature(jeu->getLevels()[cur]);
this->setPosition(jeu->getLevels()[cur-1]->getPlayer());
jeu->getLevels()[cur-1]->editCaseZeeMatrice(this->getPosition()->getX(),this->getPosition()->getY(), this->getSymbol());
jeu->setCurrent(cur-1);
}else if(isContains(next,this->getObjs()) && !isSameObjet(next) && (this->getInventaire()->getTailleMax()>this->getInventaire()->getNumObjets())){
Objet *o = new Objet(pos,next);
this->getInventaire()->ajoutObjet(o);
jeu->getLevels()[cur]->editCaseZeeMatrice(this->getPosition()->getX(),this->getPosition()->getY(),jeu->getLevels()[cur]->getSave()[this->getPosition()->getX()][this->getPosition()->getY()]);
this->getPosition()->setY(pos->getY());
this->getPosition()->setX(pos->getX());
this->setSymbol(m);
this->putCreature(jeu->getLevels()[cur]);
afficherObjets();
}
//mur ou monstre
}
void Player::lireClavier(int c,Jeu * niveaux){//handle input
char m;//pour faire la forme du joueur < > v ^
if (c=='w'){ //haut
m='^';
possibleMove(new Position(this->getPosition()->getX()-1,this->getPosition()->getY()),m,niveaux);
//possible(p->getPosition()->getY()-1,p->getPosition()->getX(),p,m);
}else if (c=='s'){ //bas
m='v';
possibleMove(new Position(this->getPosition()->getX()+1,this->getPosition()->getY()),m,niveaux);
//possible(p->getPosition()->getY()+1,p->getPosition()->getX(),p,m);
}else if(c=='a'){//gauche
m='<';
possibleMove(new Position(this->getPosition()->getX(),this->getPosition()->getY()-1),m,niveaux);
//possible(p->getPosition()->getY(),p->getPosition()->getX()-1,p,m);
}else if(c=='d'){//droite
m='>';
possibleMove(new Position(this->getPosition()->getX(),this->getPosition()->getY()+1),m,niveaux);
//possible(p->getPosition()->getY(),p->getPosition()->getX()+1,p,m);
}else if(c=='i'){
//Ecrand *e = new Ecrand();
Ecrand::EcrandMaj(this,niveaux->getLevels()[niveaux->getCurrent()]);
//e->afficheMatricePourTest(niveaux->getSave());
Ecrand::afficheMatricePourJouer(niveaux->getLevels()[niveaux->getCurrent()]->getZeeMatrice());
if(this->getInventaire()->getNumObjets()!=0)
{
this->afficherObjets();
char n;
int j=12;//la position de afficher le premier objet de x
int index=0;//index de objets
move(1,12);
while(!((this->getInventaire()->getNumObjets()==0) || (n=getch())=='i')){// cliquer i une 2 eme foi pour quittez linventaire
if(n=='n'){//next
if(this->getInventaire()->getNumObjets()!=1){
if(index<this->getInventaire()->getNumObjets()-1){
index++;
j=12+2*index;
}else {//retourner le premier objet
index=0;
j=12;
}
}
move(1,j);
}
if(n=='u'){//utiliser
this->operator+(this->getInventaire()->getObjets()[index]);
this->supprimeObjet(index);
if(j!=12){
j-=2;
index--;
}
Ecrand::EcrandMaj(this,niveaux->getLevels()[niveaux->getCurrent()]);
move(1,j);
}else if(n=='s'){//supprimer l'objet
this->supprimeObjet(index);
if(j!=12){
j-=2;
index--;
}
Ecrand::EcrandMaj(this,niveaux->getLevels()[niveaux->getCurrent()]);
move(1,j);
}
}
}
}
}
void Player::supprimeObjet(int index){
this->getInventaire()->supprimeObjet(index);
this->afficherObjets();
}
bool Player::isContains(char c, char* cs){
bool res = false;
for(int i = 0; i<strlen(cs); i++){
if(c==cs[i]) return true;
}
return res;
}
bool Player::isSameObjet(char s){
bool res=false;
for(int i=0; i<this->getInventaire()->getNumObjets();i++){
if(s==this->getInventaire()->getObjets()[i]->getSymbol()){
res=false;//true ici jai modifier pour que le joueur peus prendre 2 objet pareil
}
}
return res;
}
void Player::afficherObjets(){
move(1,0);
clrtoeol();
mvprintw(1,0,"Mes objets: ");
int k = 0;
for(int i=0;i<this->getInventaire()->getNumObjets();i++){
mvprintw(1,k+12,"%c",this->getInventaire()->getObjets()[i]->getSymbol());
k+=2;
}
} | [
"zzyviolette@gmail.com"
] | zzyviolette@gmail.com |
8b85f9bb468780981875c8b1e61eb3da01923c2a | 9ef3261146a77a81db270bcdc33e4b3261beeddf | /src/3rdParty/ogdf-2020/include/ogdf/planarity/RemoveReinsertType.h | e40646d7b9793c56ce20e08bcea0b35137a139bd | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"EPL-1.0",
"LicenseRef-scancode-generic-exception",
"GPL-1.0-or-later",
"BSL-1.0",
"LGPL-2.0-only",
"BSD-2-Clause"
] | permissive | MichaelTiernan/qvge | f5464d69fc9adaec79ec46125b95bec05afd591d | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | refs/heads/master | 2020-12-30T07:58:22.867560 | 2020-09-24T22:07:10 | 2020-09-24T22:07:10 | 238,916,864 | 0 | 0 | MIT | 2020-02-07T12:31:57 | 2020-02-07T12:31:56 | null | UTF-8 | C++ | false | false | 1,613 | h | /** \file
* \brief Definition of RemoveReinsertType (used for postprocessing
* in edge insertion algorithms).
*
* \author Karsten Klein, Carsten Gutwenger
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#pragma once
namespace ogdf {
//! The postprocessing method for edge insertion algorithms.
/**
* @ingroup ga-insert
*/
enum class RemoveReinsertType {
None, //!< No postprocessing.
Inserted, //!< Postprocessing only with the edges that have to be inserted.
MostCrossed, //!< Postprocessing with the edges involved in the most crossings.
All, //!< Postproceesing with all edges.
Incremental, //!< Full postprocessing after each edge insertion.
IncInserted //!< Postprocessing for (so far) inserted edges after each edge insertion.
};
}
| [
"ars.masiuk@gmail.com"
] | ars.masiuk@gmail.com |
1f8afeb102930f9eca2255c1fd73357b6ba8f3c3 | 6d1daf69c4df028bb75dc13f38a6b9ee3f7b3f01 | /project2D/DrunkModifier.h | 3465258056c027344c84d132f81ac79148536c40 | [] | no_license | Sloth113/AIProject | 641e5fb1e427d8aba0a9d419cabdffca0c1507f7 | f61cbc50a8787aa3e9fb5c3cdfdbe594a6e6a1bf | refs/heads/master | 2021-01-01T17:41:09.100397 | 2017-08-20T02:16:47 | 2017-08-20T02:16:47 | 98,133,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | h | #pragma once
#include "IBehaviour.h"
#include "MathLibDLL.h"
#include "Input.h"
class DrunkModifier : public IBehaviour
{
public:
virtual BehaviourResult Update(Agent * agent, float deltaTime);
private:
float m_time;
}; | [
"sloth.13@hotmail.com"
] | sloth.13@hotmail.com |
996da80e4756a582e2999a0c8719d34024d81394 | 7d96c0ff22cd8534858711d16884cac84f2e90ca | /EulerCrit.cpp | 1ee06b979f417f3d0473f9a4a87db5464eaa9e3e | [] | no_license | Doruk-Aksoy/HackerRank | 55fe59997a17e26ed6050f39992742af178ee8ae | 57c2e9d60803b28d415cd8a97e97f857ed949590 | refs/heads/master | 2021-01-18T22:30:37.363037 | 2016-04-06T19:14:54 | 2016-04-06T19:14:54 | 26,663,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int LL;
LL modpow(LL a, LL b, LL mod) {
long long int x = 1, y = a;
while(b > 0) {
if(b & 1) {
x = x * y;
if(x > mod) x %= mod;
}
y = y * y;
if(y > mod) y %= mod;
b >>= 1;
}
return x;
}
int main() {
int t;
cin >> t;
for(int i = 0; i < t; i++) {
LL M, A;
cin >> A >> M;
if(!A)
cout << "YES" << endl;
else
if(modpow(A, (M-1)/2, M) == M-1) // -1 equivalent of mod M is M - 1
cout << "NO" << endl;
else
cout << "YES" << endl;
}
return 0;
}
| [
"Doruk-Aksoy@users.noreply.github.com"
] | Doruk-Aksoy@users.noreply.github.com |
5fdad3f1f33358bda97e39175f9e18e7a7d7b40e | 4afc6182476e8e381ea0913f7b1205edf384a029 | /.build/iOS-Debug/include/app/Uno.Func__Fuse_Node__bool.h | 6cce0ba5474b146b91a18632611826f90c4d1dba | [] | no_license | noircynical/soscon_demoproject | 45a4b5594582447001c2895e24cf2e6566095a63 | aab19822fb8bc46715e6b41ac785faf7a128d9e7 | refs/heads/master | 2021-01-10T05:41:33.994651 | 2015-10-28T04:27:43 | 2015-10-28T04:27:43 | 45,085,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h | // This file was generated based on '/usr/local/share/uno/Packages/UnoCore/0.13.2/Source/Uno/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#ifndef __APP_UNO_FUNC__FUSE_NODE__BOOL_H__
#define __APP_UNO_FUNC__FUSE_NODE__BOOL_H__
#include <app/Uno.Delegate.h>
#include <Uno.h>
namespace app {
namespace Uno {
::uDelegateType* Func__Fuse_Node__bool__typeof();
}}
#endif
| [
"0101rgb@gmail.com"
] | 0101rgb@gmail.com |
063bbc1117503df96c92e29f14036aec47cd20fb | 457cfb51e6b1053c852602f57acc9087629e966d | /source/BLUE/Material.cpp | b7357390b61e87fabc3223e4f28bcbf51c869e6a | [] | no_license | bluespeck/BLUE | b05eeff4958b2bf30adb0aeb2432f1c2f6c21d96 | 430d9dc0e64837007f35ce98fbface014be93678 | refs/heads/master | 2021-01-13T01:50:57.300012 | 2010-11-15T16:37:10 | 2010-11-15T16:37:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | #include "stdafx.h"
#include "Material.h"
namespace BLUE
{
CMaterial::CMaterial(void)
{
}
CMaterial::~CMaterial(void)
{
}
} //end namespace BLUE | [
"mstudorache@gmail.com"
] | mstudorache@gmail.com |
6c7606c8ae2662ae98538497245b0c5f4d919d77 | 808abdd0a37a4fd166fe442081a7e59874f59dc7 | /src/CryptoSystemRC4.h | df5ba128bfa3c34cc72eb3addc93180967694409 | [] | no_license | manuelmederos95/RC4 | 44c62e8209f9e621256c1be6519343bcf777a80b | c966f2dad02e0dc9aa57d32548d7001369b2e8db | refs/heads/master | 2020-04-02T14:18:27.770185 | 2018-10-26T18:21:36 | 2018-10-26T18:21:36 | 154,519,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | //
// Created by juan on 26/10/18.
//
#ifndef RC3_CRYPTO_SYSTEM_RC4_H
#define RC3_CRYPTO_SYSTEM_RC4_H
#endif //RC3_CRYPTO_SYSTEM_RC4_H
namespace CryptoSystem {
class CryptoSystemRC4 {
public:
void KSA() {
}
void PGSA(){
}
private:
};
} | [
"jm.anghileri@wanadoo.fr"
] | jm.anghileri@wanadoo.fr |
96507f0268a269857ab5e6a23147e80e075eea56 | a52f707f81c0f8d45d4ca72ae7b6c735ebc5320f | /D01 Demos/TestCPPInheritance/TestCPPInheritance/B2.h | 942677f4e24d518dbbf401d9ca749e2f374ac099 | [
"MIT"
] | permissive | FeniulaPyra/DSA2 | d12fdc1a91b7eb90882c8396422345f449f4d2dc | bedaa6c11c7e248a936bf5c0f07a7cb763178ed7 | refs/heads/master | 2023-04-19T23:11:24.024342 | 2021-04-08T23:14:19 | 2021-04-08T23:14:19 | 341,772,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | h | #ifndef B2_H
#define B2_H
class B2
{
public:
void test1(); // B2 test1 - Prints Class Name
void test2(); // B2 test2 - Prints Class Name
protected:
void test3(); // B2 test3 - Prints Class Name
private:
// B2 test4 - Prints Class Name
/*virtual*/ void test4(); // virtual? see v-table...
};
#endif | [
"feniuldragon@gmail.com"
] | feniuldragon@gmail.com |
cc97bf4f2668b95d43d6372c873d424ead037fb0 | f05bde6d5bdee3e9a07e34af1ce18259919dd9bd | /algorithms/kernel/kmeans/kmeans_init_csr_deterministic_distr_step1_fpt_dispatcher.cpp | 18324b9fb6d966ab90de983414c01069b9db229d | [
"Intel",
"Apache-2.0"
] | permissive | HFTrader/daal | f827c83b75cf5884ecfb6249a664ce6f091bfc57 | b18624d2202a29548008711ec2abc93d017bd605 | refs/heads/daal_2017_beta | 2020-12-28T19:08:39.038346 | 2016-04-15T17:02:24 | 2016-04-15T17:02:24 | 56,404,044 | 0 | 1 | null | 2016-04-16T20:26:14 | 2016-04-16T20:26:14 | null | UTF-8 | C++ | false | false | 1,222 | cpp | /* file: kmeans_init_csr_deterministic_distr_step1_fpt_dispatcher.cpp */
/*******************************************************************************
* Copyright 2014-2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of K-means initialization algorithm container for CSR
// methods
//--
*/
#include "kmeans_init_container.h"
namespace daal
{
namespace algorithms
{
namespace interface1
{
__DAAL_INSTANTIATE_DISPATCH_CONATINER(kmeans::init::DistributedContainer, distributed, step1Local, DAAL_FPTYPE, kmeans::init::deterministicCSR)
}
} // namespace daal::algorithms
} // namespace daal
| [
"vasily.rubtsov@intel.com"
] | vasily.rubtsov@intel.com |
b71e12daaf78d0da6fbb89ed1de5c8983ead0ca8 | 81fa1eb6488c32f6c1722bfe4e523ece9164414a | /sdk/c_prediction.h | ed823bcc57c43ab7f0296fe8ee3972cbf652e34f | [
"Apache-2.0"
] | permissive | NotPersin/lagsync | 7f95debe021b3b916860763ea94d9230ef1c6589 | 422c66530e6817e57700c70f053d0338a8ca3b0f | refs/heads/master | 2022-04-21T14:55:19.640120 | 2020-04-23T15:55:47 | 2020-04-23T15:55:47 | 258,262,002 | 4 | 0 | null | 2020-04-23T16:19:06 | 2020-04-23T16:19:05 | null | UTF-8 | C++ | false | false | 1,002 | h | #pragma once
#include "macros.h"
#include "c_move_helper.h"
#include "c_game_movement.h"
#include "c_global_vars_base.h"
class c_prediction
{
public:
vfunc(371, set_local_view_angles(c_qangle& angle), void(__thiscall*)(c_prediction*, c_qangle&))(angle)
vfunc(14, in_prediction(), bool(__thiscall*)(c_prediction*))()
vfunc(20, setup_move(c_base_entity* player, c_user_cmd* cmd, c_move_helper* helper, c_move_data* data),
void(__thiscall*)(c_prediction*, c_base_entity*, c_user_cmd*, c_move_helper*, c_move_data*))(player, cmd, helper, data)
vfunc(21, finish_move(c_base_entity* player, c_user_cmd* cmd, c_move_data* data),
void(__thiscall*)(c_prediction*, c_base_entity*, c_user_cmd*, c_move_data*))(player, cmd, data)
inline c_global_vars_base* get_unpredicted_globals() {
if (in_prediction())
return reinterpret_cast<c_global_vars_base*>(uint32_t(this) + 0x4c);
return global_vars_base;
}
};
interface_var(c_prediction, prediction, "client_panorama.dll", "VClientPrediction")
| [
"60759888+aqua0x01@users.noreply.github.com"
] | 60759888+aqua0x01@users.noreply.github.com |
250e3aecb83b50aff68b79e8b438cf2933d54608 | 32712866b5f3065b312a2ed3b4b93b452210ac5c | /MatchCardsGame/moc_statstable.cpp | b090932bb796d52e3e6f5232b61bff9623d2a885 | [] | no_license | theTytoAlba/CmpE230Project3 | 9207faff9018b1936ed430e6d53cab9e6877610e | 20c019bae085cc3958248919a644c87629159aeb | refs/heads/master | 2021-01-19T06:49:48.844477 | 2018-03-10T09:45:28 | 2018-03-10T09:45:28 | 76,360,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'statstable.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "statstable.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'statstable.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_StatsTable_t {
QByteArrayData data[1];
char stringdata0[11];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_StatsTable_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_StatsTable_t qt_meta_stringdata_StatsTable = {
{
QT_MOC_LITERAL(0, 0, 10) // "StatsTable"
},
"StatsTable"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_StatsTable[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void StatsTable::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject StatsTable::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_StatsTable.data,
qt_meta_data_StatsTable, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *StatsTable::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *StatsTable::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_StatsTable.stringdata0))
return static_cast<void*>(const_cast< StatsTable*>(this));
return QWidget::qt_metacast(_clname);
}
int StatsTable::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"irmakkavasoglu@gmail.com"
] | irmakkavasoglu@gmail.com |
e24919185f97a4456dd3fd3ec4093a1f3c85a308 | 2c78de0b151238b1c0c26e6a4d1a36c7fa09268c | /shared/yas/include/yas/serializers/json/boost/boost_unordered_multimap_serializers.hpp | 70bd9871b0b577457df47ad613b1026b4ad78cb5 | [] | no_license | bravesoftdz/realwork | 05a3b308cef59bed8a9efda4212849c391b4b267 | 19b446ce8ad2adf82ab8ce7988bc003221accad2 | refs/heads/master | 2021-06-07T23:57:22.429896 | 2016-11-01T18:30:21 | 2016-11-01T18:30:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,478 | hpp |
// Copyright (c) 2010-2014 niXman (i dot nixman dog gmail dot com). All
// rights reserved.
//
// This file is part of YAS(https://github.com/niXman/yas) project.
//
// 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)
//
//
//
// 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.
#ifndef _yas__json__boost_unordered_multimap_hpp
#define _yas__json__boost_unordered_multimap_hpp
#include <yas/detail/config/config.hpp>
#if defined(YAS_HAS_BOOST_UNORDERED)
#include <yas/detail/type_traits/type_traits.hpp>
#include <yas/detail/type_traits/properties.hpp>
#include <yas/detail/type_traits/selector.hpp>
#include <boost/unordered_map.hpp>
namespace yas {
namespace detail {
/***************************************************************************/
template<typename K, typename V>
struct serializer<
type_prop::type_prop::not_a_pod,
ser_method::use_internal_serializer,
archive_type::json,
direction::out,
boost::unordered_multimap<K, V>
> {
template<typename Archive>
static Archive& apply(Archive& ar, const boost::unordered_multimap<K, V>& multimap) {
ar & multimap.size();
typename boost::unordered_multimap<K, V>::const_iterator it = multimap.begin();
for ( ; it != multimap.end(); ++it ) {
ar & it->first
& it->second;
}
}
};
template<typename K, typename V>
struct serializer<
type_prop::type_prop::not_a_pod,
ser_method::use_internal_serializer,
archive_type::json,
direction::in,
boost::unordered_multimap<K, V>
> {
template<typename Archive>
static Archive& apply(Archive& ar, boost::unordered_multimap<K, V>& multimap) {
std::uint32_t size = 0;
ar & size;
K key = K();
V val = V();
for ( std::size_t idx = 0; idx < size; ++idx ) {
ar & key
& val;
multimap.insert(typename boost::unordered_multimap<K, V>::value_type(key, val));
}
}
};
/***************************************************************************/
} // namespace detail
} // namespace yas
#endif // defined(YAS_HAS_BOOST_UNORDERED)
#endif // _yas__json__boost_unordered_multimap_hpp
| [
"instigator21@gmail.com"
] | instigator21@gmail.com |
ae3ff918d2d02ab695725746772334c82c5d6d67 | 764861302abdfb4b92e84421d2ccb4b32ed7137a | /Objet.h | 0ecd79f89f632996eb88acc99ace74eb807e5e88 | [] | no_license | Fabian68/bgi | 80d482537ad1109c78792e49fbb1a228acda0cca | a8d97d6364314aba7347fe1ef2a5cab690ad79f4 | refs/heads/master | 2022-12-27T14:17:54.921635 | 2020-09-22T10:07:34 | 2020-09-22T10:07:34 | 227,630,110 | 0 | 1 | null | 2020-07-29T13:18:12 | 2019-12-12T14:50:11 | C++ | UTF-8 | C++ | false | false | 391 | h | #pragma once
#include <string>
class Personnage;
class Objet
{
public:
Objet();
Objet(std::string nom, int numero, int rareter, std::string effet);
std::string nom()const;
std::string effet()const;
int rareter()const;
std::string rareterTexte();
void appliquerEffet(Personnage* P);
int numero()const;
private:
std::string _nom;
std::string _effet;
int _rareter;
int _numero;
};
| [
"Fabian@PC-DE-FABIAN"
] | Fabian@PC-DE-FABIAN |
b0fb22248ea7b9f2f7a51456d43b8dfa8e6d5be8 | a9f97db0d05ecb8171f511b84a92034cbea830ac | /PAT/1016.cpp | 2f7223af066d36465333acd4ce9e22d32097fe60 | [] | no_license | bingliang-zh/PAT-Basic | a6c3727c0a7eebe9529605441f4e35aa498a3c44 | 0cbc181c0b7b085e30cb195b9268af10f44f3ea4 | refs/heads/master | 2021-05-29T08:07:57.724452 | 2015-08-10T16:32:30 | 2015-08-10T16:32:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include <iostream>
#include <string>
using namespace std;
int str_to_int(string str);
int main()
{
string A,B;
int DA,DB;
string PA,PB;
cin>>A>>DA>>B>>DB;
for(int i=0;i!=A.size();i++)
{
if(A[i]-'0'==DA)
{PA.push_back(A[i]);}
}
for(int i=0;i!=B.size();i++)
{
if(B[i]-'0'==DB)
{PB.push_back(B[i]);}
}
cout<<str_to_int(PA)+str_to_int(PB);
system("pause");
return 0;
}
int str_to_int(string str)
{
if(str.size()==0)
{return 0;}
string::iterator it;
int i;
int sum=0;
for(i=1,it=str.begin();it!=str.end();it++,i*=10)
{
sum+=(*it-'0')*i;
}
return sum;
} | [
"bl_indie@qq.com"
] | bl_indie@qq.com |
5861b8e34d90bb8dd37fec2560d4f32a193c9a3c | f6f0f87647e23507dca538760ab70e26415b8313 | /6.1.0/msvc2019_64/include/QtCore/qchar.h | 84c2f3b34207bda2fb4d17dda2eb78b35c58db4e | [] | no_license | stenzek/duckstation-ext-qt-minimal | a942c62adc5654c03d90731a8266dc711546b268 | e5c412efffa3926f7a4d5bf0ae0333e1d6784f30 | refs/heads/master | 2023-08-17T16:50:21.478373 | 2023-08-15T14:53:43 | 2023-08-15T14:53:43 | 233,179,313 | 3 | 1 | null | 2021-11-16T15:34:28 | 2020-01-11T05:05:34 | C++ | UTF-8 | C++ | false | false | 26,691 | h | /****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QCHAR_H
#define QCHAR_H
#include <QtCore/qglobal.h>
#include <functional> // for std::hash
QT_BEGIN_NAMESPACE
class QString;
struct QLatin1Char
{
public:
constexpr inline explicit QLatin1Char(char c) noexcept : ch(c) {}
constexpr inline char toLatin1() const noexcept { return ch; }
constexpr inline char16_t unicode() const noexcept { return char16_t(uchar(ch)); }
friend constexpr inline bool operator==(QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch == rhs.ch; }
friend constexpr inline bool operator!=(QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch != rhs.ch; }
friend constexpr inline bool operator<=(QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch <= rhs.ch; }
friend constexpr inline bool operator>=(QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch >= rhs.ch; }
friend constexpr inline bool operator< (QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch < rhs.ch; }
friend constexpr inline bool operator> (QLatin1Char lhs, QLatin1Char rhs) noexcept { return lhs.ch > rhs.ch; }
friend constexpr inline bool operator==(char lhs, QLatin1Char rhs) noexcept { return lhs == rhs.toLatin1(); }
friend constexpr inline bool operator!=(char lhs, QLatin1Char rhs) noexcept { return lhs != rhs.toLatin1(); }
friend constexpr inline bool operator<=(char lhs, QLatin1Char rhs) noexcept { return lhs <= rhs.toLatin1(); }
friend constexpr inline bool operator>=(char lhs, QLatin1Char rhs) noexcept { return lhs >= rhs.toLatin1(); }
friend constexpr inline bool operator< (char lhs, QLatin1Char rhs) noexcept { return lhs < rhs.toLatin1(); }
friend constexpr inline bool operator> (char lhs, QLatin1Char rhs) noexcept { return lhs > rhs.toLatin1(); }
friend constexpr inline bool operator==(QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() == rhs; }
friend constexpr inline bool operator!=(QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() != rhs; }
friend constexpr inline bool operator<=(QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() <= rhs; }
friend constexpr inline bool operator>=(QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() >= rhs; }
friend constexpr inline bool operator< (QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() < rhs; }
friend constexpr inline bool operator> (QLatin1Char lhs, char rhs) noexcept { return lhs.toLatin1() > rhs; }
private:
char ch;
};
class Q_CORE_EXPORT QChar {
public:
enum SpecialCharacter {
Null = 0x0000,
Tabulation = 0x0009,
LineFeed = 0x000a,
FormFeed = 0x000c,
CarriageReturn = 0x000d,
Space = 0x0020,
Nbsp = 0x00a0,
SoftHyphen = 0x00ad,
ReplacementCharacter = 0xfffd,
ObjectReplacementCharacter = 0xfffc,
ByteOrderMark = 0xfeff,
ByteOrderSwapped = 0xfffe,
ParagraphSeparator = 0x2029,
LineSeparator = 0x2028,
LastValidCodePoint = 0x10ffff
};
#ifdef QT_IMPLICIT_QCHAR_CONSTRUCTION
#define QCHAR_MAYBE_IMPLICIT Q_IMPLICIT
#else
#define QCHAR_MAYBE_IMPLICIT explicit
#endif
constexpr Q_IMPLICIT QChar() noexcept : ucs(0) {}
constexpr Q_IMPLICIT QChar(ushort rc) noexcept : ucs(rc) {}
constexpr QCHAR_MAYBE_IMPLICIT QChar(uchar c, uchar r) noexcept : ucs(char16_t((r << 8) | c)) {}
constexpr Q_IMPLICIT QChar(short rc) noexcept : ucs(char16_t(rc)) {}
constexpr QCHAR_MAYBE_IMPLICIT QChar(uint rc) noexcept : ucs((Q_ASSERT(rc <= 0xffff), char16_t(rc))) {}
constexpr QCHAR_MAYBE_IMPLICIT QChar(int rc) noexcept : QChar(uint(rc)) {}
constexpr Q_IMPLICIT QChar(SpecialCharacter s) noexcept : ucs(char16_t(s)) {}
constexpr Q_IMPLICIT QChar(QLatin1Char ch) noexcept : ucs(ch.unicode()) {}
constexpr Q_IMPLICIT QChar(char16_t ch) noexcept : ucs(ch) {}
#if defined(Q_OS_WIN) || defined(Q_CLANG_QDOC)
constexpr Q_IMPLICIT QChar(wchar_t ch) noexcept : ucs(char16_t(ch)) {}
#endif
#ifndef QT_NO_CAST_FROM_ASCII
// Always implicit -- allow for 'x' => QChar conversions
QT_ASCII_CAST_WARN constexpr Q_IMPLICIT QChar(char c) noexcept : ucs(uchar(c)) { }
#ifndef QT_RESTRICTED_CAST_FROM_ASCII
QT_ASCII_CAST_WARN constexpr QCHAR_MAYBE_IMPLICIT QChar(uchar c) noexcept : ucs(c) { }
#endif
#endif
#undef QCHAR_MAYBE_IMPLICIT
static constexpr QChar fromUcs2(char16_t c) noexcept { return QChar{c}; }
static constexpr inline auto fromUcs4(char32_t c) noexcept;
// Unicode information
enum Category
{
Mark_NonSpacing, // Mn
Mark_SpacingCombining, // Mc
Mark_Enclosing, // Me
Number_DecimalDigit, // Nd
Number_Letter, // Nl
Number_Other, // No
Separator_Space, // Zs
Separator_Line, // Zl
Separator_Paragraph, // Zp
Other_Control, // Cc
Other_Format, // Cf
Other_Surrogate, // Cs
Other_PrivateUse, // Co
Other_NotAssigned, // Cn
Letter_Uppercase, // Lu
Letter_Lowercase, // Ll
Letter_Titlecase, // Lt
Letter_Modifier, // Lm
Letter_Other, // Lo
Punctuation_Connector, // Pc
Punctuation_Dash, // Pd
Punctuation_Open, // Ps
Punctuation_Close, // Pe
Punctuation_InitialQuote, // Pi
Punctuation_FinalQuote, // Pf
Punctuation_Other, // Po
Symbol_Math, // Sm
Symbol_Currency, // Sc
Symbol_Modifier, // Sk
Symbol_Other // So
};
enum Script
{
Script_Unknown,
Script_Inherited,
Script_Common,
Script_Latin,
Script_Greek,
Script_Cyrillic,
Script_Armenian,
Script_Hebrew,
Script_Arabic,
Script_Syriac,
Script_Thaana,
Script_Devanagari,
Script_Bengali,
Script_Gurmukhi,
Script_Gujarati,
Script_Oriya,
Script_Tamil,
Script_Telugu,
Script_Kannada,
Script_Malayalam,
Script_Sinhala,
Script_Thai,
Script_Lao,
Script_Tibetan,
Script_Myanmar,
Script_Georgian,
Script_Hangul,
Script_Ethiopic,
Script_Cherokee,
Script_CanadianAboriginal,
Script_Ogham,
Script_Runic,
Script_Khmer,
Script_Mongolian,
Script_Hiragana,
Script_Katakana,
Script_Bopomofo,
Script_Han,
Script_Yi,
Script_OldItalic,
Script_Gothic,
Script_Deseret,
Script_Tagalog,
Script_Hanunoo,
Script_Buhid,
Script_Tagbanwa,
Script_Coptic,
// Unicode 4.0 additions
Script_Limbu,
Script_TaiLe,
Script_LinearB,
Script_Ugaritic,
Script_Shavian,
Script_Osmanya,
Script_Cypriot,
Script_Braille,
// Unicode 4.1 additions
Script_Buginese,
Script_NewTaiLue,
Script_Glagolitic,
Script_Tifinagh,
Script_SylotiNagri,
Script_OldPersian,
Script_Kharoshthi,
// Unicode 5.0 additions
Script_Balinese,
Script_Cuneiform,
Script_Phoenician,
Script_PhagsPa,
Script_Nko,
// Unicode 5.1 additions
Script_Sundanese,
Script_Lepcha,
Script_OlChiki,
Script_Vai,
Script_Saurashtra,
Script_KayahLi,
Script_Rejang,
Script_Lycian,
Script_Carian,
Script_Lydian,
Script_Cham,
// Unicode 5.2 additions
Script_TaiTham,
Script_TaiViet,
Script_Avestan,
Script_EgyptianHieroglyphs,
Script_Samaritan,
Script_Lisu,
Script_Bamum,
Script_Javanese,
Script_MeeteiMayek,
Script_ImperialAramaic,
Script_OldSouthArabian,
Script_InscriptionalParthian,
Script_InscriptionalPahlavi,
Script_OldTurkic,
Script_Kaithi,
// Unicode 6.0 additions
Script_Batak,
Script_Brahmi,
Script_Mandaic,
// Unicode 6.1 additions
Script_Chakma,
Script_MeroiticCursive,
Script_MeroiticHieroglyphs,
Script_Miao,
Script_Sharada,
Script_SoraSompeng,
Script_Takri,
// Unicode 7.0 additions
Script_CaucasianAlbanian,
Script_BassaVah,
Script_Duployan,
Script_Elbasan,
Script_Grantha,
Script_PahawhHmong,
Script_Khojki,
Script_LinearA,
Script_Mahajani,
Script_Manichaean,
Script_MendeKikakui,
Script_Modi,
Script_Mro,
Script_OldNorthArabian,
Script_Nabataean,
Script_Palmyrene,
Script_PauCinHau,
Script_OldPermic,
Script_PsalterPahlavi,
Script_Siddham,
Script_Khudawadi,
Script_Tirhuta,
Script_WarangCiti,
// Unicode 8.0 additions
Script_Ahom,
Script_AnatolianHieroglyphs,
Script_Hatran,
Script_Multani,
Script_OldHungarian,
Script_SignWriting,
// Unicode 9.0 additions
Script_Adlam,
Script_Bhaiksuki,
Script_Marchen,
Script_Newa,
Script_Osage,
Script_Tangut,
// Unicode 10.0 additions
Script_MasaramGondi,
Script_Nushu,
Script_Soyombo,
Script_ZanabazarSquare,
// Unicode 12.1 additions
Script_Dogra,
Script_GunjalaGondi,
Script_HanifiRohingya,
Script_Makasar,
Script_Medefaidrin,
Script_OldSogdian,
Script_Sogdian,
Script_Elymaic,
Script_Nandinagari,
Script_NyiakengPuachueHmong,
Script_Wancho,
// Unicode 13.0 additions
Script_Chorasmian,
Script_DivesAkuru,
Script_KhitanSmallScript,
Script_Yezidi,
ScriptCount
};
enum Direction
{
DirL, DirR, DirEN, DirES, DirET, DirAN, DirCS, DirB, DirS, DirWS, DirON,
DirLRE, DirLRO, DirAL, DirRLE, DirRLO, DirPDF, DirNSM, DirBN,
DirLRI, DirRLI, DirFSI, DirPDI
};
enum Decomposition
{
NoDecomposition,
Canonical,
Font,
NoBreak,
Initial,
Medial,
Final,
Isolated,
Circle,
Super,
Sub,
Vertical,
Wide,
Narrow,
Small,
Square,
Compat,
Fraction
};
enum JoiningType {
Joining_None,
Joining_Causing,
Joining_Dual,
Joining_Right,
Joining_Left,
Joining_Transparent
};
enum CombiningClass
{
Combining_BelowLeftAttached = 200,
Combining_BelowAttached = 202,
Combining_BelowRightAttached = 204,
Combining_LeftAttached = 208,
Combining_RightAttached = 210,
Combining_AboveLeftAttached = 212,
Combining_AboveAttached = 214,
Combining_AboveRightAttached = 216,
Combining_BelowLeft = 218,
Combining_Below = 220,
Combining_BelowRight = 222,
Combining_Left = 224,
Combining_Right = 226,
Combining_AboveLeft = 228,
Combining_Above = 230,
Combining_AboveRight = 232,
Combining_DoubleBelow = 233,
Combining_DoubleAbove = 234,
Combining_IotaSubscript = 240
};
enum UnicodeVersion {
Unicode_Unassigned,
Unicode_1_1,
Unicode_2_0,
Unicode_2_1_2,
Unicode_3_0,
Unicode_3_1,
Unicode_3_2,
Unicode_4_0,
Unicode_4_1,
Unicode_5_0,
Unicode_5_1,
Unicode_5_2,
Unicode_6_0,
Unicode_6_1,
Unicode_6_2,
Unicode_6_3,
Unicode_7_0,
Unicode_8_0,
Unicode_9_0,
Unicode_10_0,
Unicode_11_0,
Unicode_12_0,
Unicode_12_1,
Unicode_13_0
};
inline Category category() const noexcept { return QChar::category(ucs); }
inline Direction direction() const noexcept { return QChar::direction(ucs); }
inline JoiningType joiningType() const noexcept { return QChar::joiningType(ucs); }
inline unsigned char combiningClass() const noexcept { return QChar::combiningClass(ucs); }
inline QChar mirroredChar() const noexcept { return QChar(QChar::mirroredChar(ucs)); }
inline bool hasMirrored() const noexcept { return QChar::hasMirrored(ucs); }
QString decomposition() const;
inline Decomposition decompositionTag() const noexcept { return QChar::decompositionTag(ucs); }
inline int digitValue() const noexcept { return QChar::digitValue(ucs); }
inline QChar toLower() const noexcept { return QChar(QChar::toLower(ucs)); }
inline QChar toUpper() const noexcept { return QChar(QChar::toUpper(ucs)); }
inline QChar toTitleCase() const noexcept { return QChar(QChar::toTitleCase(ucs)); }
inline QChar toCaseFolded() const noexcept { return QChar(QChar::toCaseFolded(ucs)); }
inline Script script() const noexcept { return QChar::script(ucs); }
inline UnicodeVersion unicodeVersion() const noexcept { return QChar::unicodeVersion(ucs); }
constexpr inline char toLatin1() const noexcept { return ucs > 0xff ? '\0' : char(ucs); }
constexpr inline char16_t unicode() const noexcept { return ucs; }
constexpr inline char16_t &unicode() noexcept { return ucs; }
static constexpr QChar fromLatin1(char c) noexcept { return QLatin1Char(c); }
constexpr inline bool isNull() const noexcept { return ucs == 0; }
inline bool isPrint() const noexcept { return QChar::isPrint(ucs); }
constexpr inline bool isSpace() const noexcept { return QChar::isSpace(ucs); }
inline bool isMark() const noexcept { return QChar::isMark(ucs); }
inline bool isPunct() const noexcept { return QChar::isPunct(ucs); }
inline bool isSymbol() const noexcept { return QChar::isSymbol(ucs); }
constexpr inline bool isLetter() const noexcept { return QChar::isLetter(ucs); }
constexpr inline bool isNumber() const noexcept { return QChar::isNumber(ucs); }
constexpr inline bool isLetterOrNumber() const noexcept { return QChar::isLetterOrNumber(ucs); }
constexpr inline bool isDigit() const noexcept { return QChar::isDigit(ucs); }
constexpr inline bool isLower() const noexcept { return QChar::isLower(ucs); }
constexpr inline bool isUpper() const noexcept { return QChar::isUpper(ucs); }
constexpr inline bool isTitleCase() const noexcept { return QChar::isTitleCase(ucs); }
constexpr inline bool isNonCharacter() const noexcept { return QChar::isNonCharacter(ucs); }
constexpr inline bool isHighSurrogate() const noexcept { return QChar::isHighSurrogate(ucs); }
constexpr inline bool isLowSurrogate() const noexcept { return QChar::isLowSurrogate(ucs); }
constexpr inline bool isSurrogate() const noexcept { return QChar::isSurrogate(ucs); }
constexpr inline uchar cell() const noexcept { return uchar(ucs & 0xff); }
constexpr inline uchar row() const noexcept { return uchar((ucs>>8)&0xff); }
constexpr inline void setCell(uchar acell) noexcept { ucs = char16_t((ucs & 0xff00) + acell); }
constexpr inline void setRow(uchar arow) noexcept { ucs = char16_t((char16_t(arow)<<8) + (ucs&0xff)); }
static constexpr inline bool isNonCharacter(char32_t ucs4) noexcept
{
return ucs4 >= 0xfdd0 && (ucs4 <= 0xfdef || (ucs4 & 0xfffe) == 0xfffe);
}
static constexpr inline bool isHighSurrogate(char32_t ucs4) noexcept
{
return (ucs4 & 0xfffffc00) == 0xd800; // 0xd800 + up to 1023 (0x3ff)
}
static constexpr inline bool isLowSurrogate(char32_t ucs4) noexcept
{
return (ucs4 & 0xfffffc00) == 0xdc00; // 0xdc00 + up to 1023 (0x3ff)
}
static constexpr inline bool isSurrogate(char32_t ucs4) noexcept
{
return (ucs4 - 0xd800u < 2048u);
}
static constexpr inline bool requiresSurrogates(char32_t ucs4) noexcept
{
return (ucs4 >= 0x10000);
}
static constexpr inline char32_t surrogateToUcs4(char16_t high, char16_t low) noexcept
{
// 0x010000 through 0x10ffff, provided params are actual high, low surrogates.
// 0x010000 + ((high - 0xd800) << 10) + (low - 0xdc00), optimized:
return (char32_t(high)<<10) + low - 0x35fdc00;
}
static constexpr inline char32_t surrogateToUcs4(QChar high, QChar low) noexcept
{
return surrogateToUcs4(high.ucs, low.ucs);
}
static constexpr inline char16_t highSurrogate(char32_t ucs4) noexcept
{
return char16_t((ucs4>>10) + 0xd7c0);
}
static constexpr inline char16_t lowSurrogate(char32_t ucs4) noexcept
{
return char16_t(ucs4%0x400 + 0xdc00);
}
static Category QT_FASTCALL category(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static Direction QT_FASTCALL direction(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static JoiningType QT_FASTCALL joiningType(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static unsigned char QT_FASTCALL combiningClass(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static char32_t QT_FASTCALL mirroredChar(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL hasMirrored(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static QString QT_FASTCALL decomposition(char32_t ucs4);
static Decomposition QT_FASTCALL decompositionTag(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static int QT_FASTCALL digitValue(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static char32_t QT_FASTCALL toLower(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static char32_t QT_FASTCALL toUpper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static char32_t QT_FASTCALL toTitleCase(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static char32_t QT_FASTCALL toCaseFolded(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static Script QT_FASTCALL script(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static UnicodeVersion QT_FASTCALL unicodeVersion(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static UnicodeVersion QT_FASTCALL currentUnicodeVersion() noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isPrint(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static constexpr inline bool isSpace(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{
// note that [0x09..0x0d] + 0x85 are exceptional Cc-s and must be handled explicitly
return ucs4 == 0x20 || (ucs4 <= 0x0d && ucs4 >= 0x09)
|| (ucs4 > 127 && (ucs4 == 0x85 || ucs4 == 0xa0 || QChar::isSpace_helper(ucs4)));
}
static bool QT_FASTCALL isMark(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isPunct(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isSymbol(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static constexpr inline bool isLetter(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{
return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
|| (ucs4 > 127 && QChar::isLetter_helper(ucs4));
}
static constexpr inline bool isNumber(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{ return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::isNumber_helper(ucs4)); }
static constexpr inline bool isLetterOrNumber(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{
return (ucs4 >= 'A' && ucs4 <= 'z' && (ucs4 >= 'a' || ucs4 <= 'Z'))
|| (ucs4 >= '0' && ucs4 <= '9')
|| (ucs4 > 127 && QChar::isLetterOrNumber_helper(ucs4));
}
static constexpr inline bool isDigit(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{ return (ucs4 <= '9' && ucs4 >= '0') || (ucs4 > 127 && QChar::category(ucs4) == Number_DecimalDigit); }
static constexpr inline bool isLower(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{ return (ucs4 <= 'z' && ucs4 >= 'a') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Lowercase); }
static constexpr inline bool isUpper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{ return (ucs4 <= 'Z' && ucs4 >= 'A') || (ucs4 > 127 && QChar::category(ucs4) == Letter_Uppercase); }
static constexpr inline bool isTitleCase(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION
{ return ucs4 > 127 && QChar::category(ucs4) == Letter_Titlecase; }
friend constexpr inline bool operator==(QChar c1, QChar c2) noexcept { return c1.ucs == c2.ucs; }
friend constexpr inline bool operator< (QChar c1, QChar c2) noexcept { return c1.ucs < c2.ucs; }
friend constexpr inline bool operator!=(QChar c1, QChar c2) noexcept { return !operator==(c1, c2); }
friend constexpr inline bool operator>=(QChar c1, QChar c2) noexcept { return !operator< (c1, c2); }
friend constexpr inline bool operator> (QChar c1, QChar c2) noexcept { return operator< (c2, c1); }
friend constexpr inline bool operator<=(QChar c1, QChar c2) noexcept { return !operator< (c2, c1); }
friend constexpr inline bool operator==(QChar lhs, std::nullptr_t) noexcept { return lhs.isNull(); }
friend constexpr inline bool operator< (QChar, std::nullptr_t) noexcept { return false; }
friend constexpr inline bool operator==(std::nullptr_t, QChar rhs) noexcept { return rhs.isNull(); }
friend constexpr inline bool operator< (std::nullptr_t, QChar rhs) noexcept { return !rhs.isNull(); }
friend constexpr inline bool operator!=(QChar lhs, std::nullptr_t) noexcept { return !operator==(lhs, nullptr); }
friend constexpr inline bool operator>=(QChar lhs, std::nullptr_t) noexcept { return !operator< (lhs, nullptr); }
friend constexpr inline bool operator> (QChar lhs, std::nullptr_t) noexcept { return operator< (nullptr, lhs); }
friend constexpr inline bool operator<=(QChar lhs, std::nullptr_t) noexcept { return !operator< (nullptr, lhs); }
friend constexpr inline bool operator!=(std::nullptr_t, QChar rhs) noexcept { return !operator==(nullptr, rhs); }
friend constexpr inline bool operator>=(std::nullptr_t, QChar rhs) noexcept { return !operator< (nullptr, rhs); }
friend constexpr inline bool operator> (std::nullptr_t, QChar rhs) noexcept { return operator< (rhs, nullptr); }
friend constexpr inline bool operator<=(std::nullptr_t, QChar rhs) noexcept { return !operator< (rhs, nullptr); }
private:
static bool QT_FASTCALL isSpace_helper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isLetter_helper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isNumber_helper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
static bool QT_FASTCALL isLetterOrNumber_helper(char32_t ucs4) noexcept Q_DECL_CONST_FUNCTION;
#ifdef QT_NO_CAST_FROM_ASCII
QChar(char c) = delete;
QChar(uchar c) = delete;
#endif
char16_t ucs;
};
Q_DECLARE_TYPEINFO(QChar, Q_RELOCATABLE_TYPE);
#ifndef QT_NO_DATASTREAM
Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, QChar);
Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, QChar &);
#endif
QT_END_NAMESPACE
namespace std {
template <>
struct hash<QT_PREPEND_NAMESPACE(QChar)>
{
template <typename = void> // for transparent constexpr tracking
constexpr size_t operator()(QT_PREPEND_NAMESPACE(QChar) c) const
noexcept(noexcept(std::hash<char16_t>{}(u' ')))
{
return std::hash<char16_t>{}(c.unicode());
}
};
} // namespace std
#endif // QCHAR_H
#include <QtCore/qstringview.h> // for QChar::fromUcs4() definition
| [
"stenzek@gmail.com"
] | stenzek@gmail.com |
c906df51a888b8a25253f9e7f0effcc4a3f053ac | 80b8f82883a2015c8bcf0cf9a11bf3b5ec4b8812 | /src/ui/UI.h | a7b63543253d5a33cf43cf230c15e3337de6063e | [] | no_license | ZahariaLevy/opengl-quickstart | 51b3f67e3c624a01a116f066bfcf96254c9b5ba3 | 51396cd108a78e9862ec1f53a5386d71b90edc42 | refs/heads/main | 2023-02-21T00:11:21.078761 | 2021-01-08T14:44:11 | 2021-01-08T14:44:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | h |
#ifndef OPENGL_QUICKSTART_UI_H
#define OPENGL_QUICKSTART_UI_H
#include <glfw3.h>
#include <vector>
#include "Widget.h"
#include "widgets/Info.h"
class UI {
private:
std::vector<Widget*> _widgets;
public:
UI();
virtual ~UI();
void render(GLFWwindow* window);
};
#endif //OPENGL_QUICKSTART_UI_H
| [
"levian13666@gmail.com"
] | levian13666@gmail.com |
835045685edbb7f2abb0cc1f1a1de5359f67aea4 | 7abbbef9590f9c4b9469adcbae5ea8907478bf03 | /chromium_git/chromium/src/components/autofill/core/common/form_data.cc | e0930834e340701bafc872d19c82409b60223d55 | [
"BSD-3-Clause"
] | permissive | GiorgiGagnidze/CEF | 845bdc2f54833254b3454ba8f6c61449431c7884 | fbfc30b5d60f1ea7157da449e34dd9ba9c50f360 | refs/heads/master | 2021-01-10T17:32:27.640882 | 2016-03-23T07:43:04 | 2016-03-23T07:43:04 | 54,463,340 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,084 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/common/form_data.h"
#include <stddef.h>
#include <tuple>
#include "base/base64.h"
#include "base/pickle.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/common/form_field_data.h"
namespace autofill {
namespace {
const int kPickleVersion = 4;
bool ReadGURL(base::PickleIterator* iter, GURL* url) {
std::string spec;
if (!iter->ReadString(&spec))
return false;
*url = GURL(spec);
return true;
}
void SerializeFormFieldDataVector(const std::vector<FormFieldData>& fields,
base::Pickle* pickle) {
pickle->WriteInt(static_cast<int>(fields.size()));
for (size_t i = 0; i < fields.size(); ++i) {
SerializeFormFieldData(fields[i], pickle);
}
}
bool DeserializeFormFieldDataVector(base::PickleIterator* iter,
std::vector<FormFieldData>* fields) {
int size;
if (!iter->ReadInt(&size))
return false;
FormFieldData temp;
for (int i = 0; i < size; ++i) {
if (!DeserializeFormFieldData(iter, &temp))
return false;
fields->push_back(temp);
}
return true;
}
void LogDeserializationError(int version) {
DVLOG(1) << "Could not deserialize version " << version
<< " FormData from pickle.";
}
} // namespace
FormData::FormData()
: is_form_tag(true) {
}
FormData::FormData(const FormData& data)
: name(data.name),
origin(data.origin),
action(data.action),
is_form_tag(data.is_form_tag),
fields(data.fields) {
}
FormData::~FormData() {
}
bool FormData::SameFormAs(const FormData& form) const {
if (name != form.name ||
origin != form.origin ||
action != form.action ||
is_form_tag != form.is_form_tag ||
fields.size() != form.fields.size())
return false;
for (size_t i = 0; i < fields.size(); ++i) {
if (!fields[i].SameFieldAs(form.fields[i]))
return false;
}
return true;
}
bool FormData::operator<(const FormData& form) const {
return std::tie(name, origin, action, is_form_tag, fields) <
std::tie(form.name, form.origin, form.action, form.is_form_tag,
form.fields);
}
std::ostream& operator<<(std::ostream& os, const FormData& form) {
os << base::UTF16ToUTF8(form.name) << " "
<< form.origin << " "
<< form.action << " "
<< form.is_form_tag << " "
<< "Fields:";
for (size_t i = 0; i < form.fields.size(); ++i) {
os << form.fields[i] << ",";
}
return os;
}
void SerializeFormData(const FormData& form_data, base::Pickle* pickle) {
pickle->WriteInt(kPickleVersion);
pickle->WriteString16(form_data.name);
pickle->WriteString(form_data.origin.spec());
pickle->WriteString(form_data.action.spec());
SerializeFormFieldDataVector(form_data.fields, pickle);
pickle->WriteBool(form_data.is_form_tag);
}
void SerializeFormDataToBase64String(const FormData& form_data,
std::string* output) {
base::Pickle pickle;
SerializeFormData(form_data, &pickle);
Base64Encode(
base::StringPiece(static_cast<const char*>(pickle.data()), pickle.size()),
output);
}
bool DeserializeFormData(base::PickleIterator* iter, FormData* form_data) {
int version;
FormData temp_form_data;
if (!iter->ReadInt(&version)) {
DVLOG(1) << "Bad pickle of FormData, no version present";
return false;
}
if (version < 1 || version > kPickleVersion) {
DVLOG(1) << "Unknown FormData pickle version " << version;
return false;
}
if (!iter->ReadString16(&temp_form_data.name)) {
LogDeserializationError(version);
return false;
}
if (version == 1) {
base::string16 method;
if (!iter->ReadString16(&method)) {
LogDeserializationError(version);
return false;
}
}
bool unused_user_submitted;
if (!ReadGURL(iter, &temp_form_data.origin) ||
!ReadGURL(iter, &temp_form_data.action) ||
// user_submitted was removed/no longer serialized in version 4.
(version < 4 && !iter->ReadBool(&unused_user_submitted)) ||
!DeserializeFormFieldDataVector(iter, &temp_form_data.fields)) {
LogDeserializationError(version);
return false;
}
if (version >= 3) {
if (!iter->ReadBool(&temp_form_data.is_form_tag)) {
LogDeserializationError(version);
return false;
}
} else {
form_data->is_form_tag = true;
}
*form_data = temp_form_data;
return true;
}
bool DeserializeFormDataFromBase64String(const base::StringPiece& input,
FormData* form_data) {
if (input.empty())
return false;
std::string pickle_data;
Base64Decode(input, &pickle_data);
base::Pickle pickle(pickle_data.data(), static_cast<int>(pickle_data.size()));
base::PickleIterator iter(pickle);
return DeserializeFormData(&iter, form_data);
}
} // namespace autofill
| [
"ggagn12@freeuni.edu.ge"
] | ggagn12@freeuni.edu.ge |
1a967ec31edc38e01f1848001ef253946b6483a1 | a6dd54cb560dddccef0b2233fa2990f25e818c7b | /Kattis/ProgNova-2/sevenwonders.cpp | 2c0bb1e2e74e118487d696a83264eb0e0fe38517 | [] | no_license | renzov/Red_Crown | ec11106389196aac03d04167ad6703acc62aaef6 | 449fe413dbbd67cb0ca673af239f7d616249599a | refs/heads/master | 2021-07-08T04:56:22.617893 | 2021-05-14T18:41:06 | 2021-05-14T18:41:06 | 4,538,198 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | #include<cstdio>
#include<algorithm>
using namespace std;
char S[64];
int V[4];
int main(){
scanf("%s", S);
for ( int i=0; S[i]; ++i ){
switch (S[i]){
case 'T': V[0]++;
break;
case 'G': V[1]++;
break;
case 'C': V[2]++;
break;
}
}
printf("%d\n", V[0]*V[0] + V[1]*V[1] + V[2]*V[2] + 7 * ( min(V[0], min( V[1], V[2] ) ) ) );
return 0;
}
| [
"gomez.renzo@gmail.com"
] | gomez.renzo@gmail.com |
453c08fea949bfaa9858debe4597feaa25b81d50 | 0184e96e37298e01d7270afa64035ef26888dc22 | /src/types/ltiRGBAPixel.cpp | 3ce9a3e7d4ce1c6c9ccfbe1ece7b75f2a83fab1b | [] | no_license | edwinV21/LTI-LIB2 | 8f938915cc9918f55618ac7e3213862dba2ecce1 | 458cb35eedc1c0d1758416b78c112ff226116ede | refs/heads/master | 2021-01-16T21:07:49.394303 | 2017-12-04T23:51:27 | 2017-12-04T23:51:27 | 100,211,418 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,122 | cpp | /*
* Copyright (C) 1998-2004
* Lehrstuhl fuer Technische Informatik, RWTH-Aachen, Germany
*
* This file is part of the LTI-Computer Vision Library (LTI-Lib)
*
* The LTI-Lib is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* The LTI-Lib is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the LTI-Lib; see the file LICENSE. If
* not, write to the Free Software Foundation, Inc., 59 Temple Place -
* Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* \file ltiRGBAPixel.cpp
* Contains the basic template class to represent RGB pixels with
* an alpha channel
* \author Pablo Alvarado
* \date 01.11.2002
*
* $Id: ltiRGBAPixel.cpp,v 1.7 2006-09-21 08:33:14 doerfler Exp $
*/
#include "ltiRGBAPixel.h"
#include <iostream>
namespace lti {
// DO NOT INITIALIZE VALUE HERE!
// this would make constructing lti::image too expensive
rgbaPixel::rgbaPixel() {
}
rgbaPixel::rgbaPixel(const uint32 val) : value(val) {
}
rgbaPixel::rgbaPixel(const rgbaPixel& other) : value(other.value) {
}
rgbaPixel::rgbaPixel(const ubyte r,
const ubyte g,
const ubyte b,
const ubyte d)
: blue(b),
green(g),
red(r),
alpha(d) {
}
bool rgbaPixel::read(ioHandler& handler,const bool) {
int tmp;
bool b = true;
// the begin and end tokens are mandatory here! ignore the complete flag...
handler.readBegin();
b = b && handler.read(tmp);
setRed(static_cast<ubyte>(tmp));
b = b && handler.readDataSeparator();
b = b && handler.read(tmp);
setGreen(static_cast<ubyte>(tmp));
b = b && handler.readDataSeparator();
b = b && handler.read(tmp);
setBlue(static_cast<ubyte>(tmp));
if (!handler.tryEnd()) {
// the new rgbaPixel writes also the alpha value. To allow
// old stuff to be readed, the alpha value is optionally readed
b = b && handler.readDataSeparator();
b = b && handler.read(tmp);
setAlpha(static_cast<ubyte>(tmp));
// the begin and end tokens are mandatory here! ignore the
// complete flag...
b = b && handler.readEnd();
} else {
setAlpha(0);
}
return b;
}
bool rgbaPixel::write(ioHandler& handler,const bool) const {
bool b = true;
// the begin token is mandatory here, so ignore the complete flag
b = b && handler.writeBegin();
b = b && handler.write(static_cast<int>(red));
b = b && handler.writeDataSeparator();
b = b && handler.write(static_cast<int>(green));
b = b && handler.writeDataSeparator();
b = b && handler.write(static_cast<int>(blue));
b = b && handler.writeDataSeparator();
b = b && handler.write(static_cast<int>(alpha));
b = b && handler.writeEnd();
return b;
}
bool read(ioHandler& handler,rgbaPixel& p,const bool complete) {
return p.read(handler,complete);
}
bool write(ioHandler& handler,const rgbaPixel& p,const bool complete) {
return p.write(handler,complete);
}
}
namespace std {
ostream& operator<<(ostream& s,const lti::rgbaPixel& p) {
s << "(";
s << static_cast<int>(p.red);
s << ",";
s << static_cast<int>(p.green);
s << ",";
s << static_cast<int>(p.blue);
s << ")";
return s;
}
//inline ostream& operator>>(istream& s,const lti::rgbaPixel& p);
istream& operator>>(istream& s,lti::rgbaPixel& p) {
char c;
int r,g,b;
s >> c
>> r >> c
>> g >> c
>> b >> c;
p.set(static_cast<lti::ubyte>(r),
static_cast<lti::ubyte>(g),
static_cast<lti::ubyte>(b));
return s;
}
}
| [
"edvl21@gmail.com"
] | edvl21@gmail.com |
e2d7d32811f03eca4486e7f0e92b55ce610bdbb9 | d596727f31563c08e968786b8bf5c570b68def30 | /Source/TestingGrounds/Terrain/Tile.cpp | 0549673e549b5b47d4440c37c06148f446d7f1d2 | [] | no_license | RobOQ/TestingGrounds | 31dc2b6470180042d736146303dd65cf97964654 | ff13be573930b1d16ce4f3198679560c30df1127 | refs/heads/master | 2020-05-20T00:13:41.674977 | 2019-02-23T22:38:02 | 2019-02-23T22:38:02 | 116,597,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,300 | cpp | // Copyright 2019 Robert O'Quinn
#include "Tile.h"
#include "Engine/World.h"
#include "DrawDebugHelpers.h"
// Sets default values
ATile::ATile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
void ATile::PlaceActors(TSubclassOf<AActor> ToSpawn, int MinSpawn, int MaxSpawn, float Radius)
{
int NumberToSpawn = FMath::RandRange(MinSpawn, MaxSpawn);
for(int i = 0; i < NumberToSpawn; ++i)
{
FVector SpawnPoint;
bool FoundLocation = FindEmptyLocation(Radius, SpawnPoint);
if(FoundLocation)
{
PlaceActor(ToSpawn, SpawnPoint);
}
}
}
// Called when the game starts or when spawned
void ATile::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ATile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ATile::Destroyed()
{
Super::Destroyed();
TArray<AActor*> AttachedActors;
GetAttachedActors(AttachedActors);
for(int i = 0; i < AttachedActors.Num(); ++i)
{
AttachedActors[i]->Destroy();
}
}
bool ATile::FindEmptyLocation(float Radius, FVector& OutLocation)
{
FVector Min(0.0f, -2000.0f, 0.0f);
FVector Max(4000.0f, 2000.0f, 0.0f);
FBox Bounds(Min, Max);
const int MAX_ATTEMPTS = 5;
for(int i = 0; i < MAX_ATTEMPTS; i++)
{
FVector CandidatePoint = FMath::RandPointInBox(Bounds);
if(CanSpawnAtLocation(CandidatePoint, Radius))
{
OutLocation = CandidatePoint;
return true;
}
}
return false;
}
void ATile::PlaceActor(TSubclassOf<AActor> ToSpawn, FVector SpawnPoint)
{
AActor* Spawned = GetWorld()->SpawnActor<AActor>(ToSpawn);
Spawned->SetActorRelativeLocation(SpawnPoint);
Spawned->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));
}
bool ATile::CanSpawnAtLocation(FVector Location, float Radius)
{
FVector GlobalLocation = ActorToWorld().TransformPosition(Location);
FHitResult HitResult;
bool HasHit = GetWorld()->SweepSingleByChannel(
HitResult,
GlobalLocation,
GlobalLocation,
FQuat::Identity,
ECollisionChannel::ECC_GameTraceChannel2,
FCollisionShape::MakeSphere(Radius)
);
FColor ResultColor = HasHit ? FColor::Red : FColor::Green;
DrawDebugSphere(
GetWorld(),
GlobalLocation,
Radius,
16,
ResultColor,
true,
100.0f
);
return !HasHit;
}
| [
"rob.oquinn@gmail.com"
] | rob.oquinn@gmail.com |
ee67a374fc9e274ec75a111915de91073bffc541 | 928bcf947b6e05fa52075e5e24e47a7f498e5064 | /BehaviorPatterns/BehaviorPatterns/visitor.cpp | bd29ec32a65c5fb5086b5fa009e08025a24aa573 | [] | no_license | Annushka34/Patterns_2020 | 8c5824f237e9a12caa06cee2c9e8ae4e98320dc6 | 090e2915f000b242623789e4443f35d2871d99c9 | refs/heads/master | 2022-12-03T21:03:43.136284 | 2020-08-23T09:07:30 | 2020-08-23T09:07:30 | 274,476,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | cpp | //#include<iostream>
//#include<list>
//
//using namespace std;
//class Visitor;
//
//class House
//{
//public:
// virtual void accept(class Visitor*v) = 0;
//};
//
//class GirlHouse : public House
//{
//public:
//
// void accept(Visitor*v);
// void GiftDress()
// {
// cout << "such abuitiful dress\n";
// }
//};
//class BoyHouse : public House
//{
//public:
//
// void accept(Visitor*v);
// void GiftCar()
// {
// cout << "such a cool car\n";
// }
//};
//
//class Visitor
//{
// public:
// void visitGirlHouse(GirlHouse*g)
// {
// g->GiftDress();
// }
// void visitBoyHouse(BoyHouse*b)
// {
// b->GiftCar();
// }
//};
//
//class Village
//{
//public:
// list<House*>houses;
//
// void Add(House*h)
// {
// houses.push_back(h);
// }
// void Accept(Visitor*v)
// {
// for (auto el : houses)
// {
// el->accept(v);
// }
// }
////};
//void GirlHouse::accept(Visitor*v)
//{
// v->visitGirlHouse(this);
//}
//void BoyHouse::accept(Visitor*v)
//{
// v->visitBoyHouse(this);
//}
//
//void main()
//{
// Village*v = new Village();
// Visitor*santa = new Visitor();
// v->Add(new GirlHouse);
// v->Add(new GirlHouse);
// v->Add(new GirlHouse);
// v->Add(new BoyHouse);
// v->Accept(santa);
//} | [
"annsamoluk82@gmail.com"
] | annsamoluk82@gmail.com |
3cef95c3e27f094934c9a3ad20b14343616d671a | 0458840fe3ad2b17e461e21444a2fdec5ef62172 | /cocosjs/frameworks/cocos2d-x/cocos/editor-support/cocostudio/CCSSceneReader.cpp | 3b29a7a5c2c3b734e71891183e534c6abaed8e58 | [] | no_license | linyouhappy/kongkongxiyou | b204949b607def0b8918f69b7a5f5c3335b5a6c5 | 01d6f10105d74d3ed679e8eb40910d84419570d7 | refs/heads/master | 2023-04-27T18:31:40.933570 | 2023-04-26T00:36:28 | 2023-04-26T00:36:28 | 63,694,726 | 318 | 245 | null | null | null | null | UTF-8 | C++ | false | false | 19,550 | cpp | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.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 "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "audio/include/SimpleAudioEngine.h"
#include "base/ObjectFactory.h"
using namespace cocos2d;
using namespace ui;
namespace cocostudio {
SceneReader* SceneReader::s_sharedReader = nullptr;
SceneReader::SceneReader()
: _fnSelector(nullptr)
, _node(nullptr)
, _attachComponent(AttachComponentType::EMPTY_NODE)
{
ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComAttribute));
ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComRender));
ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComAudio));
ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComController));
}
SceneReader::~SceneReader()
{
}
const char* SceneReader::sceneReaderVersion()
{
return "1.0.0.0";
}
cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/)
{
std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(fileName);
if (fileExtension == ".json")
{
_node = nullptr;
rapidjson::Document jsonDict;
do {
CC_BREAK_IF(!readJson(fileName, jsonDict));
_node = createObject(jsonDict, nullptr, attachComponent);
TriggerMng::getInstance()->parse(jsonDict);
} while (0);
return _node;
}
else if(fileExtension == ".csb")
{
do {
std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(fileName);
auto fileData = FileUtils::getInstance()->getDataFromFile(binaryFilePath);
auto fileDataBytes = fileData.getBytes();
CC_BREAK_IF(fileData.isNull());
CocoLoader tCocoLoader;
if (tCocoLoader.ReadCocoBinBuff((char*)fileDataBytes))
{
stExpCocoNode *tpRootCocoNode = tCocoLoader.GetRootCocoNode();
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
CC_BREAK_IF(tpRootCocoNode->GetChildNum() == 0);
_node = Node::create();
int nCount = 0;
std::vector<Component*> _vecComs;
ComRender *pRender = nullptr;
std::string key = tpChildArray[15].GetName(&tCocoLoader);
if (key == "components")
{
nCount = tpChildArray[15].GetChildNum();
}
stExpCocoNode *pComponents = tpChildArray[15].GetChildArray(&tCocoLoader);
SerData *data = new (std::nothrow) SerData();
for (int i = 0; i < nCount; i++)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray(&tCocoLoader);
if (subDict == nullptr)
{
continue;
}
std::string key1 = subDict[1].GetName(&tCocoLoader);
const char *comName = subDict[1].GetValue(&tCocoLoader);
Component *pCom = nullptr;
if (key1 == "classname" && comName != nullptr)
{
pCom = createComponent(comName);
}
// CCLOG("classname = %s", comName);
if (pCom != nullptr)
{
data->_rData = nullptr;
data->_cocoNode = subDict;
data->_cocoLoader = &tCocoLoader;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
if (pTRender != nullptr)
{
pRender = pTRender;
}
else
{
_vecComs.push_back(pCom);
}
}
else
{
CC_SAFE_RELEASE_NULL(pCom);
}
}
if(_fnSelector != nullptr)
{
_fnSelector(pCom, (void*)(data));
}
}
setPropertyFromJsonDict(&tCocoLoader, tpRootCocoNode, _node);
for (std::vector<Component*>::iterator iter = _vecComs.begin(); iter != _vecComs.end(); ++iter)
{
_node->addComponent(*iter);
}
stExpCocoNode *pGameObjects = tpChildArray[11].GetChildArray(&tCocoLoader);
int length = tpChildArray[11].GetChildNum();
for (int i = 0; i < length; ++i)
{
createObject(&tCocoLoader, &pGameObjects[i], _node, attachComponent);
}
TriggerMng::getInstance()->parse(&tCocoLoader, tpChildArray);
}
}
}while (0);
return _node;
}
else
{
log("read file [%s] error!\n", fileName.c_str());
}
return nullptr;
}
bool SceneReader::readJson(const std::string &fileName, rapidjson::Document &doc)
{
bool ret = false;
do {
std::string jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName);
std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath);
doc.Parse<0>(contentStr.c_str());
CC_BREAK_IF(doc.HasParseError());
ret = true;
} while (0);
return ret;
}
Node* SceneReader::nodeByTag(Node *parent, int tag)
{
if (parent == nullptr)
{
return nullptr;
}
Node *_retNode = nullptr;
Vector<Node*>& Children = parent->getChildren();
Vector<Node*>::iterator iter = Children.begin();
while (iter != Children.end())
{
Node* pNode = *iter;
if(pNode != nullptr && pNode->getTag() == tag)
{
_retNode = pNode;
break;
}
else
{
_retNode = nodeByTag(pNode, tag);
if (_retNode != nullptr)
{
break;
}
}
++iter;
}
return _retNode;
}
cocos2d::Component* SceneReader::createComponent(const std::string classname)
{
std::string name = this->getComponentClassName(classname);
Ref *object = ObjectFactory::getInstance()->createObject(name);
return dynamic_cast<Component*>(object);
}
std::string SceneReader::getComponentClassName(const std::string &name)
{
std::string comName;
if (name == "CCSprite" || name == "CCTMXTiledMap" || name == "CCParticleSystemQuad" || name == "CCArmature" || name == "GUIComponent")
{
comName = "ComRender";
}
else if (name == "CCComAudio" || name == "CCBackgroundAudio")
{
comName = "ComAudio";
}
else if (name == "CCComController")
{
comName = "ComController";
}
else if (name == "CCComAttribute")
{
comName = "ComAttribute";
}
else if (name == "CCScene")
{
comName = "Scene";
}
else
{
CCASSERT(false, "Unregistered Component!");
}
return comName;
}
Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* parent, AttachComponentType attachComponent)
{
const char *className = DICTOOL->getStringValue_json(dict, "classname");
if(strcmp(className, "CCNode") == 0)
{
Node* gb = nullptr;
if(nullptr == parent)
{
gb = Node::create();
}
std::vector<Component*> vecComs;
ComRender *render = nullptr;
int count = DICTOOL->getArrayCount_json(dict, "components");
for (int i = 0; i < count; i++)
{
const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(dict, "components", i);
if (!DICTOOL->checkObjectExist_json(subDict))
{
break;
}
const char *comName = DICTOOL->getStringValue_json(subDict, "classname");
Component *com = this->createComponent(comName);
// CCLOG("classname = %s", comName);
SerData *data = new (std::nothrow) SerData();
if (com != nullptr)
{
data->_rData = &subDict;
data->_cocoNode = nullptr;
data->_cocoLoader = nullptr;
if (com->serialize(data))
{
ComRender *tRender = dynamic_cast<ComRender*>(com);
if (tRender == nullptr)
{
vecComs.push_back(com);
}
else
{
render = tRender;
}
}
}
CC_SAFE_DELETE(data);
if(_fnSelector != nullptr)
{
_fnSelector(com, data);
}
}
if (parent != nullptr)
{
if (render == nullptr || attachComponent == AttachComponentType::EMPTY_NODE)
{
gb = Node::create();
if (render != nullptr)
{
vecComs.push_back(render);
}
}
else
{
gb = render->getNode();
gb->retain();
render->setNode(nullptr);
}
parent->addChild(gb);
}
setPropertyFromJsonDict(dict, gb);
for (std::vector<Component*>::iterator iter = vecComs.begin(); iter != vecComs.end(); ++iter)
{
gb->addComponent(*iter);
}
int length = DICTOOL->getArrayCount_json(dict, "gameobjects");
for (int i = 0; i < length; ++i)
{
const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(dict, "gameobjects", i);
if (!DICTOOL->checkObjectExist_json(subDict))
{
break;
}
createObject(subDict, gb, attachComponent);
}
if(dict.HasMember("CanvasSize"))
{
const rapidjson::Value &canvasSizeDict = DICTOOL->getSubDictionary_json(dict, "CanvasSize");
if (DICTOOL->checkObjectExist_json(canvasSizeDict))
{
int width = DICTOOL->getIntValue_json(canvasSizeDict, "_width");
int height = DICTOOL->getIntValue_json(canvasSizeDict, "_height");
gb->setContentSize(Size(width, height));
}
}
return gb;
}
return nullptr;
}
cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node* parent, AttachComponentType attachComponent)
{
const char *className = nullptr;
stExpCocoNode *pNodeArray = cocoNode->GetChildArray(cocoLoader);
std::string Key = pNodeArray[1].GetName(cocoLoader);
if (Key == "classname")
{
className = pNodeArray[1].GetValue(cocoLoader);
}
if(strcmp(className, "CCNode") == 0)
{
Node* gb = nullptr;
std::vector<Component*> _vecComs;
ComRender *pRender = nullptr;
int count = 0;
std::string key = pNodeArray[13].GetName(cocoLoader);
if (key == "components")
{
count = pNodeArray[13].GetChildNum();
}
stExpCocoNode *pComponents = pNodeArray[13].GetChildArray(cocoLoader);
SerData *data = new (std::nothrow) SerData();
for (int i = 0; i < count; ++i)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray(cocoLoader);
if (subDict == nullptr)
{
continue;
}
std::string key1 = subDict[1].GetName(cocoLoader);
const char *comName = subDict[1].GetValue(cocoLoader);
Component *pCom = nullptr;
if (key1 == "classname" && comName != nullptr)
{
pCom = createComponent(comName);
}
// CCLOG("classname = %s", comName);
if (pCom != nullptr)
{
data->_rData = nullptr;
data->_cocoNode = subDict;
data->_cocoLoader = cocoLoader;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
if (pTRender != nullptr)
{
pRender = pTRender;
}
else
{
_vecComs.push_back(pCom);
}
}
else
{
CC_SAFE_RELEASE_NULL(pCom);
}
}
if(_fnSelector != nullptr)
{
_fnSelector(pCom, (void*)(data));
}
}
CC_SAFE_DELETE(data);
if (parent != nullptr)
{
if (pRender == nullptr || attachComponent == AttachComponentType::EMPTY_NODE)
{
gb = Node::create();
if (pRender != nullptr)
{
_vecComs.push_back(pRender);
}
}
else
{
gb = pRender->getNode();
gb->retain();
pRender->setNode(nullptr);
CC_SAFE_RELEASE_NULL(pRender);
}
parent->addChild(gb);
}
setPropertyFromJsonDict(cocoLoader, cocoNode, gb);
for (std::vector<Component*>::iterator iter = _vecComs.begin(); iter != _vecComs.end(); ++iter)
{
gb->addComponent(*iter);
}
stExpCocoNode *pGameObjects = pNodeArray[12].GetChildArray(cocoLoader);
if (pGameObjects != nullptr)
{
int length = pNodeArray[12].GetChildNum();
for (int i = 0; i < length; ++i)
{
createObject(cocoLoader, &pGameObjects[i], gb, attachComponent);
}
}
return gb;
}
return nullptr;
}
void SceneReader::setTarget(const std::function<void(cocos2d::Ref* obj, void* doc)>& selector)
{
_fnSelector = selector;
}
Node* SceneReader::getNodeByTag(int nTag)
{
if (_node == nullptr)
{
return nullptr;
}
if (_node->getTag() == nTag)
{
return _node;
}
return nodeByTag(_node, nTag);
}
void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d::Node *node)
{
float x = DICTOOL->getFloatValue_json(root, "x");
float y = DICTOOL->getFloatValue_json(root, "y");
node->setPosition(x, y);
const bool bVisible = (DICTOOL->getIntValue_json(root, "visible", 1) != 0);
node->setVisible(bVisible);
int nTag = DICTOOL->getIntValue_json(root, "objecttag", -1);
node->setTag(nTag);
int nZorder = DICTOOL->getIntValue_json(root, "zorder");
node->setLocalZOrder(nZorder);
float fScaleX = DICTOOL->getFloatValue_json(root, "scalex", 1.0);
float fScaleY = DICTOOL->getFloatValue_json(root, "scaley", 1.0);
node->setScaleX(fScaleX);
node->setScaleY(fScaleY);
float fRotationZ = DICTOOL->getFloatValue_json(root, "rotation");
node->setRotation(fRotationZ);
const char *sName = DICTOOL->getStringValue_json(root, "name", "");
node->setName(sName);
}
void SceneReader::setPropertyFromJsonDict(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node *node)
{
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
float x = 0.0f, y = 0.0f, fScaleX = 1.0f, fScaleY = 1.0f, fRotationZ = 1.0f;
bool bVisible = false;
const char *sName = "";
int nTag = 0, nZorder = -1;
for (int i = 0; i < cocoNode->GetChildNum(); ++i)
{
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == "x")
{
x = utils::atof(value.c_str());
node->setPositionX(x);
}
else if (key == "y")
{
y = utils::atof(value.c_str());
node->setPositionY(y);
}
else if (key == "visible")
{
bVisible = atoi(value.c_str()) != 0;
node->setVisible(bVisible);
}
else if (key == "objecttag")
{
nTag = atoi(value.c_str());
node->setTag(nTag);
}
else if (key == "zorder")
{
nZorder = atoi(value.c_str());
node->setLocalZOrder(nZorder);
}
else if(key == "scalex")
{
fScaleX = utils::atof(value.c_str());
node->setScaleX(fScaleX);
}
else if(key == "scaley")
{
fScaleY = atof(value.c_str());
node->setScaleY(fScaleY);
}
else if(key == "rotation")
{
fRotationZ = utils::atof(value.c_str());
node->setRotation(fRotationZ);
}
else if(key == "name")
{
sName = value.c_str();
node->setName(sName);
}
}
}
SceneReader* SceneReader::getInstance()
{
if (s_sharedReader == nullptr)
{
s_sharedReader = new (std::nothrow) SceneReader();
}
return s_sharedReader;
}
void SceneReader::destroyInstance()
{
DictionaryHelper::destroyInstance();
TriggerMng::destroyInstance();
CocosDenshion::SimpleAudioEngine::end();
CC_SAFE_DELETE(s_sharedReader);
}
}
| [
"linyouhappy@foxmail.com"
] | linyouhappy@foxmail.com |
74e431b8f580563e747c69775a74861dac3c6c1f | 62b96ab9a18fdb41648d454447356c806e5fc22b | /CS106/Library/graphics/gdownloader.cpp | 899ae6ee3f042477ab936ca353333f9511eaf3a9 | [] | no_license | smarttigerfly/CS106B_Assignment_2020Winter | db55421657bd091f114190422cae0236de9043b0 | 41a1627a586ac0d1bffd07d54ed3087b393b8d99 | refs/heads/master | 2023-04-02T09:37:35.176833 | 2021-04-08T03:15:11 | 2021-04-08T03:15:11 | 333,098,009 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 11,497 | cpp | /*
* File: gdownloader.cpp
* ---------------------
* This file implements the GDownloader class as declared in gdownloader.h.
* See the .h file for the declarations of each member and comments.
*
* @author Marty Stepp
* @version 2018/09/23
* - added macro checks to improve compatibility with old Qt versions
* @version 2018/09/18
* - working version; had to fix various threading / Qt signal issues
* @version 2018/08/23
* - renamed to gdownloader.cpp to replace Java version
* @version 2018/08/03
* - initial version
*/
#include "gdownloader.h"
#include <iomanip>
#include <iostream>
#include <QtGlobal>
#include <QFile>
#include <QIODevice>
#include <QTimer>
#include "error.h"
#include "gthread.h"
GDownloader::GDownloader()
: _manager(nullptr),
_reply(nullptr),
_httpStatusCode(0),
_downloadComplete(false) {
}
GDownloader::~GDownloader() {
// TODO: delete
_manager = nullptr;
_reply = nullptr;
}
std::string GDownloader::downloadAsString(const std::string& url) {
_url = url;
_filename = "";
_httpStatusCode = 0;
_lastErrorMessage = "";
// actually download the file (block/wait for it to finish)
downloadInternal();
// save download to string
saveDownloadedData("downloadAsString");
// return downloaded text as string (saved in member variable)
return _filedata;
}
void GDownloader::downloadToFile(const std::string& url, const std::string& file) {
_url = url;
_filename = file;
_httpStatusCode = 0;
_lastErrorMessage = "";
// actually download the file (block/wait for it to finish)
downloadInternal();
// save download to file
saveDownloadedData("downloadToFile", file);
}
void GDownloader::downloadInternal() {
GThread::runOnQtGuiThreadAsync([this]() {
if (!_manager) {
_manager = new QNetworkAccessManager();
// disabling Qt signal-handling because it doesn't seem to work at all
// connect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloaded(QNetworkReply*)));
}
QNetworkRequest* request = new QNetworkRequest(QUrl(QString::fromStdString(_url)));
// set up SSL / HTTPS settings, if possible
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
#if QT_CONFIG(ssl)
request->setSslConfiguration(QSslConfiguration::defaultConfiguration());
#endif // QT_CONFIG(ssl)
#endif // QT_VERSION
for (std::string headerKey : _headers) {
request->setRawHeader(QByteArray(headerKey.c_str()), QByteArray(_headers[headerKey].c_str()));
}
_reply = _manager->get(*request);
// disabling Qt signal-handling because it doesn't seem to work at all
// _reply->connect(
// _reply, SIGNAL(finished()),
// this, SLOT(fileDownloadFinished()));
// this seemingly won't be called ever (thanks, useless Qt networking tutorials!)
_reply->connect(
_reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(fileDownloadError(QNetworkReply::NetworkError)));
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
#if QT_CONFIG(ssl)
_reply->connect(
_reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(sslErrors(QList<QSslError>)));
#endif // QT_CONFIG(ssl)
#endif // QT_VERSION
});
// wait for download to finish (in student thread)
waitForDownload();
}
void GDownloader::fileDownloadError(QNetworkReply::NetworkError nerror) {
error("file download error: " + std::to_string(nerror));
}
std::string GDownloader::getErrorMessage() const {
return _lastErrorMessage;
}
int GDownloader::getHttpStatusCode() const {
// all HTTP status codes are between 1xx and 5xx, inclusive
return _httpStatusCode >= 100 && _httpStatusCode <= 599 ? _httpStatusCode : 0;
}
std::string GDownloader::getHeader(const std::string& name) const {
return _headers[name];
}
std::string GDownloader::getUserAgent() const {
if (_headers.containsKey("User-Agent")) {
return _headers["User-Agent"];
} else {
return "";
}
}
bool GDownloader::hasError() const {
if (_httpStatusCode != 0) {
// values 2xx indicate success
return _httpStatusCode < 200 || _httpStatusCode > 299;
} else {
return _lastErrorMessage.empty();
}
}
std::string GDownloader::qtNetworkErrorToString(QNetworkReply::NetworkError nerror) {
// http://doc.qt.io/qt-5/qnetworkreply.html#NetworkError-enum
switch (nerror) {
case QNetworkReply::ConnectionRefusedError: return "the remote server refused the connection (the server is not accepting requests)";
case QNetworkReply::RemoteHostClosedError: return "the remote server closed the connection prematurely, before the entire reply was received and processed";
case QNetworkReply::HostNotFoundError: return "the remote host name was not found (invalid hostname)";
case QNetworkReply::TimeoutError: return "the connection to the remote server timed out";
case QNetworkReply::OperationCanceledError: return "the operation was canceled via calls to abort() or close() before it was finished.";
case QNetworkReply::SslHandshakeFailedError: return "the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.";
case QNetworkReply::TemporaryNetworkFailureError: return "the connection was broken due to disconnection from the network, however the system has initiated roaming to another access point. The request should be resubmitted and will be processed as soon as the connection is re-established.";
case QNetworkReply::NetworkSessionFailedError: return "the connection was broken due to disconnection from the network or failure to start the network.";
case QNetworkReply::BackgroundRequestNotAllowedError: return "the background request is not currently allowed due to platform policy.";
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
case QNetworkReply::TooManyRedirectsError: return "while following redirects, the maximum limit was reached. The limit is by default set to 50 or as set by QNetworkRequest::setMaxRedirectsAllowed(). (This value was introduced in 5.6.)";
case QNetworkReply::InsecureRedirectError: return "while following redirects, the network access API detected a redirect from a encrypted protocol (https) to an unencrypted one (http). (This value was introduced in 5.6.)";
#endif // QT_VERSION
case QNetworkReply::ProxyConnectionRefusedError: return "the connection to the proxy server was refused (the proxy server is not accepting requests)";
case QNetworkReply::ProxyConnectionClosedError: return "the proxy server closed the connection prematurely, before the entire reply was received and processed";
case QNetworkReply::ProxyNotFoundError: return "the proxy host name was not found (invalid proxy hostname)";
case QNetworkReply::ProxyTimeoutError: return "the connection to the proxy timed out or the proxy did not reply in time to the request sent";
case QNetworkReply::ProxyAuthenticationRequiredError: return "the proxy requires authentication in order to honour the request but did not accept any credentials offered (if any)";
case QNetworkReply::ContentAccessDenied: return "access denied";
case QNetworkReply::ContentOperationNotPermittedError: return "the operation requested on the remote content is not permitted";
case QNetworkReply::ContentNotFoundError: return "the remote content was not found at the server";
case QNetworkReply::AuthenticationRequiredError: return "the remote server requires authentication to serve the content but the credentials provided were not accepted (if any)";
case QNetworkReply::ContentReSendError: return "the request needed to be sent again, but this failed for example because the upload data could not be read a second time.";
case QNetworkReply::ContentConflictError: return "the request could not be completed due to a conflict with the current state of the resource.";
case QNetworkReply::ContentGoneError: return "the requested resource is no longer available at the server.";
case QNetworkReply::InternalServerError: return "the server encountered an unexpected condition which prevented it from fulfilling the request.";
case QNetworkReply::OperationNotImplementedError: return "the server does not support the functionality required to fulfill the request.";
case QNetworkReply::ServiceUnavailableError: return "the server is unable to handle the request at this time.";
case QNetworkReply::ProtocolUnknownError: return "the Network Access API cannot honor the request because the protocol is not known";
case QNetworkReply::ProtocolInvalidOperationError: return "the requested operation is invalid for this protocol";
case QNetworkReply::UnknownNetworkError: return "an unknown network-related error was detected";
case QNetworkReply::UnknownProxyError: return "an unknown proxy-related error was detected";
case QNetworkReply::UnknownContentError: return "an unknown error related to the remote content was detected";
case QNetworkReply::ProtocolFailure: return "a breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.)";
case QNetworkReply::UnknownServerError: return "unknown server error";
case QNetworkReply::NoError:
break;
}
return "";
}
void GDownloader::saveDownloadedData(const std::string& member, const std::string& filename) {
if (_reply) {
QNetworkReply::NetworkError nerror = _reply->error();
if (nerror) {
// connection failed; log the error message
_lastErrorMessage = qtNetworkErrorToString(nerror);
} else if (filename.empty()) {
// save to a string
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
_filedata = _reply->readAll().toStdString();
#endif // QT_VERSION
} else {
// save to a file
QFile outfile(QString::fromStdString(filename));
if (!outfile.open(QIODevice::WriteOnly)) {
error("GDownloader::" + member + ": cannot open file " + filename + " for writing");
}
outfile.write(_reply->readAll());
outfile.close();
}
// clean up the connection
_reply->deleteLater();
_reply = nullptr;
_downloadComplete = true;
}
}
void GDownloader::setHeader(const std::string& name, const std::string& value) {
_headers[name] = value;
}
void GDownloader::setUserAgent(const std::string& userAgent) {
setHeader("User-Agent", userAgent);
}
void GDownloader::sslErrors(QList<QSslError>) {
std::cout << " DEBUG: sslErrors" << std::endl;
}
void GDownloader::waitForDownload() {
// wait for download to finish
while (!_downloadComplete) {
GThread::getCurrentThread()->sleep(10);
if (_reply && _reply->isFinished()) {
_downloadComplete = true;
break;
}
}
// grab the HTTP status code
QVariant statusCode = _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (statusCode.isValid()) {
_httpStatusCode = statusCode.toInt();
_lastErrorMessage = _reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().toStdString();
} else {
_httpStatusCode = -1;
_lastErrorMessage = "Unable to connect to URL";
}
}
| [
"hewulii@sina.com"
] | hewulii@sina.com |
9acd6b2b0ca4a99cdd3144089707882839cec2e8 | f67e465a896a19960afd5fbcbaf44d1b9d4bbeb7 | /src/ir/tac_visitor.hpp | 77440cd8770141e19adf48a62de9bef484140ea2 | [] | no_license | evanpw/enceladus | 249b318320a52c39bb8c543467206ee6d65fb86a | e1cbb4b1ce85e6321b634bd56a58ad1316dc0017 | refs/heads/master | 2021-01-22T23:10:37.397645 | 2018-09-16T14:17:22 | 2018-09-16T14:17:22 | 28,695,070 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | hpp | #ifndef TAC_VISITOR_HPP
#define TAC_VISITOR_HPP
struct BinaryOperationInst;
struct CallInst;
struct ConditionalJumpInst;
struct CopyInst;
struct IndexedLoadInst;
struct IndexedStoreInst;
struct JumpIfInst;
struct JumpInst;
struct LoadInst;
struct MemsetFn;
struct PhiInst;
struct ProgramInst;
struct ReturnInst;
struct StoreInst;
struct UnreachableInst;
struct TACVisitor
{
virtual ~TACVisitor() {}
virtual void visit(BinaryOperationInst* inst) {}
virtual void visit(CallInst* inst) {}
virtual void visit(ConditionalJumpInst* inst) {}
virtual void visit(CopyInst* inst) {}
virtual void visit(IndexedLoadInst* inst) {}
virtual void visit(IndexedStoreInst* inst) {}
virtual void visit(JumpIfInst* inst) {}
virtual void visit(JumpInst* inst) {}
virtual void visit(LoadInst* inst) {}
virtual void visit(MemsetFn* inst) {}
virtual void visit(PhiInst* inst) {}
virtual void visit(ReturnInst* inst) {}
virtual void visit(StoreInst* inst) {}
virtual void visit(UnreachableInst* inst) {}
};
#endif
| [
"evanpw@gmail.com"
] | evanpw@gmail.com |
1408c82bc137fea2e91cdc4bc99dbeb5c65d7f1d | fbaad8aa5ec47d348fa4f81304de2e3e11f8f978 | /src/toolkit/bamtools_header.cpp | aad413f29df916ec0edade03eac4206770e0bac2 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | scoutzxb/bamtools | adc88b2aa3bb0a2a67b1b98f30cf66596fd2498a | 889210eae78b7e1a186b67aa0846c038f03906ab | refs/heads/master | 2021-01-18T06:11:29.309356 | 2011-05-10T23:28:31 | 2011-05-10T23:28:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,527 | cpp | // ***************************************************************************
// bamtools_header.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 21 March 2011
// ---------------------------------------------------------------------------
// Prints the SAM-style header from a single BAM file ( or merged header from
// multiple BAM files) to stdout
// ***************************************************************************
#include "bamtools_header.h"
#include <api/BamMultiReader.h>
#include <utils/bamtools_options.h>
using namespace BamTools;
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// ---------------------------------------------
// HeaderSettings implementation
struct HeaderTool::HeaderSettings {
// flags
bool HasInputBamFilename;
// filenames
vector<string> InputFiles;
// constructor
HeaderSettings(void)
: HasInputBamFilename(false)
{ }
};
// ---------------------------------------------
// HeaderTool implementation
HeaderTool::HeaderTool(void)
: AbstractTool()
, m_settings(new HeaderSettings)
{
// set program details
Options::SetProgramInfo("bamtools header", "prints header from BAM file(s)", "[-in <filename> -in <filename> ...] ");
// set up options
OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInputBamFilename, m_settings->InputFiles, IO_Opts, Options::StandardIn());
}
HeaderTool::~HeaderTool(void) {
delete m_settings;
m_settings = 0;
}
int HeaderTool::Help(void) {
Options::DisplayHelp();
return 0;
}
int HeaderTool::Run(int argc, char* argv[]) {
// parse command line arguments
Options::Parse(argc, argv, 1);
// set to default input if none provided
if ( !m_settings->HasInputBamFilename )
m_settings->InputFiles.push_back(Options::StandardIn());
// attemp to open BAM files
BamMultiReader reader;
if ( !reader.Open(m_settings->InputFiles) ) {
cerr << "bamtools header ERROR: could not open BAM file(s) for reading... Aborting." << endl;
return 1;
}
// dump (merged) header contents to stdout
cout << reader.GetHeaderText() << endl;
// clean up & exit
reader.Close();
return 0;
}
| [
"derekwbarnett@gmail.com"
] | derekwbarnett@gmail.com |
8f55f76b97c052a37f391b375b11c9c63b9d8b03 | 2a24077d4fc3c7c93595b93f0632dcdff6b9e9ec | /math/test_rotate.cpp | 9e4aad3972690bd6d41b5dd0ac6b0824e9e42a06 | [] | no_license | ZhifeiDing/algorithm_learning | 6bf71eaf3713b3cb83bc96121e38ed2cdbe69385 | f6c4ad45e52dd58140380c862cae56bf02f7da78 | refs/heads/master | 2020-12-18T13:40:40.626037 | 2016-07-08T13:39:44 | 2016-07-08T13:39:44 | 34,025,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #include "leetcode.hpp"
void print_matrix(vector<vector<int> > & matrix, const string & s = "Matrix") {
cout << s << " : " << endl;
int n = matrix.size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
cout << matrix[i][j] << "\t";
cout << endl;
}
}
void test_rotate() {
srand((unsigned int)time(NULL));
int n = rand()%9;
vector<vector<int> > matrix(n, vector<int>(n));
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
matrix[i][j] = rand()%99;
print_matrix(matrix);
rotate(matrix);
print_matrix(matrix, "Rotate");
}
| [
"dzhf21@hotmail.com"
] | dzhf21@hotmail.com |
f8f3c05f0beb2c7e09574d18f3d56075b3840a78 | 6d1a022d7b639e9eaa8d1595a7897a70bc4b1d54 | /eyesee-mpp/awcdr/apps/cdr/tutk/wrapper/av_ctrl.h | 9ad37297a9a0893dc129d7a9bd79e869f997941b | [] | no_license | icprog/lindenis-v536-softwinner | c2673b155ab911e82c9c477be3a921c4d098c77d | 2fdf6f7aef8b5e1e24a54650fe589e5b6208b24b | refs/heads/master | 2020-12-26T06:16:25.103604 | 2020-01-20T05:32:18 | 2020-01-21T05:35:58 | 237,413,679 | 1 | 0 | null | 2020-01-31T11:08:11 | 2020-01-31T11:08:10 | null | UTF-8 | C++ | false | false | 1,378 | h | /* *******************************************************************************
* Copyright (C), 2001-2016, Allwinner Tech. Co., Ltd.
* *******************************************************************************/
/**
* @file av_ctrl.h
* @brief tutk iot/av ctrl cmd handler
* @author id:826
* @version v0.3
* @date 2016-08-26
*/
#pragma once
#include <list>
#include "AVIOCTRLDEFs.h"
class DeviceAdapter;
namespace tutk {
typedef struct tag_EventHandleInfo {
int av_index;
int sid;
int handle_id;
}EventHandleInfo;
class AVCtrl {
public:
AVCtrl(DeviceAdapter *adapter);
~AVCtrl();
void SetAdapter(DeviceAdapter *adapter);
int HandleIOTCtrlCmd(int sid, int av_index, char *buf, int type);
int SnapShotHandler(int sid, int av_index, char *buf, int type);
int RegisterEventMsg(int sid, int av_index);
int UnRegisterEventMsg(int sid, int av_index);
static void EventHandleCallBack(int chn, int event_type, void *arg);
void dumpMenuConfig(SMsgAVIoctrSDVDevConfigResp &resp);
int SendCmdData(int type,int chn,int value , void *data);
int SetClientConnectStatus(bool p_Connect);
private:
DeviceAdapter *adapter_;
std::list<EventHandleInfo> handle_info_list_;
};
}
| [
"given@lindeni.com"
] | given@lindeni.com |
694d691357796a4ab4eb0b4b83517df64ea8cf39 | 7a0760e3ebee86f131d42905d823d5a1bacdead2 | /src/noeud.h | 7c52a097346b4e064cebd4d15e9a202bf8a2947e | [] | no_license | Jujulego/othello | 4be2501f2b9c49eb8861cfefe38d085fecf5fe64 | 078422fb05e623a2e8b80e1241f1bf3aef41284f | refs/heads/master | 2020-09-08T21:52:05.839662 | 2017-04-23T20:27:16 | 2017-04-23T20:27:16 | 221,252,614 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | h | #ifndef ARBRE_H
#define ARBRE_H
// Dépendances
#include <functional>
#include <memory>
#include <vector>
// Classe
template<class T>
class Noeud : public std::enable_shared_from_this<Noeud<T>> {
private:
// Attributs
T m_val;
std::weak_ptr<Noeud<T>> m_pere;
std::vector<std::shared_ptr<Noeud<T>>> m_fils;
// Méthodes
std::weak_ptr<Noeud<T>> weak_from_this() {
return std::weak_ptr<Noeud<T>>(std::enable_shared_from_this<Noeud<T>>::shared_from_this());
}
public:
// Constructeur
Noeud(T const& val, std::weak_ptr<Noeud<T>> const& pere) : m_val(val), m_pere(pere) {
}
// Méthodes statiques
/// Crée un noeud de type T
static std::shared_ptr<Noeud<T>> creer(T const& val) {
return std::make_shared<Noeud<T>>(val, std::weak_ptr<Noeud<T>>());
}
// Opérateurs
/// Permet l'accès au fils i via les crochets
Noeud<T> operator [] (int i) {
return fils(i);
}
// Méthodes
/// Ajoute un fils contenant la valeur val
std::shared_ptr<Noeud<T>> add_fils(T const& val) {
// Création du noeud !
std::shared_ptr<Noeud<T>> pt = std::make_shared<Noeud<T>>(val, weak_from_this());
m_fils.push_back(pt);
return pt; // ref sur le dernier !
}
/// Permet l'accès au fils i
std::shared_ptr<Noeud<T>> fils(int i) {
return m_fils[i];
}
// Accesseurs
std::shared_ptr<Noeud<T>> pere() {
return m_pere;
}
typename std::add_lvalue_reference<T>::type val() {
return m_val;
}
unsigned size() const {
return m_fils.size();
}
};
#endif // ARBRE_H
| [
"julien@capellari.net"
] | julien@capellari.net |
79f12c5617decedddb46b2ae548941cb97ce8d12 | fe58c570e16f3085e63eb9582c0b4c5ed6b5b785 | /lib/gras_impl/messages.hpp | a959befd70cb45d666bad468b9e27a0b790c3ea3 | [
"BSL-1.0"
] | permissive | thatchristoph/gras | 43fdf2318beb90ce83d2a29f06ae06337ea9ff80 | 8457fa1c98db480745766b0074ef43c16f187544 | refs/heads/master | 2021-01-16T21:49:31.844449 | 2013-05-01T01:39:03 | 2013-05-01T01:39:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,140 | hpp | // Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.
#ifndef INCLUDED_LIBGRAS_IMPL_MESSAGES_HPP
#define INCLUDED_LIBGRAS_IMPL_MESSAGES_HPP
#include <gras/buffer_queue.hpp>
#include <gras/sbuffer.hpp>
#include <gras/tags.hpp>
#include <gras/sbuffer.hpp>
#include <gras_impl/token.hpp>
#include <gras_impl/stats.hpp>
namespace gras
{
//----------------------------------------------------------------------
//-- message from the top block/executor
//-- these messages must be ack'd
//----------------------------------------------------------------------
struct TopAllocMessage
{
//empty
};
struct TopActiveMessage
{
//empty
};
struct TopInertMessage
{
Token prio_token;
};
struct TopTokenMessage
{
Token token;
};
//----------------------------------------------------------------------
//-- message to an input port
//-- do not ack
//----------------------------------------------------------------------
struct InputTagMessage
{
InputTagMessage(const Tag &tag):tag(tag){}
size_t index;
Tag tag;
};
struct InputMsgMessage
{
InputMsgMessage(const PMCC &msg):msg(msg){}
size_t index;
PMCC msg;
};
struct InputBufferMessage
{
size_t index;
SBuffer buffer;
};
struct InputTokenMessage
{
size_t index;
Token token;
};
struct InputAllocMessage
{
size_t index;
SBufferConfig config;
SBufferToken token; //holds reference
};
struct InputCheckMessage
{
size_t index;
};
struct InputUpdateMessage
{
size_t index;
};
//----------------------------------------------------------------------
//-- message to an output port
//-- do not ack
//----------------------------------------------------------------------
struct OutputBufferMessage
{
size_t index;
SBuffer buffer;
};
struct OutputTokenMessage
{
size_t index;
Token token;
};
struct OutputCheckMessage
{
size_t index;
};
struct OutputHintMessage
{
size_t index;
size_t reserve_bytes;
WeakToken token;
};
struct OutputAllocMessage
{
size_t index;
BufferQueueSptr queue;
};
struct OutputUpdateMessage
{
size_t index;
};
//----------------------------------------------------------------------
//-- message to just the block
//-- do not ack
//----------------------------------------------------------------------
struct PropAccessMessage
{
Token prio_token;
bool set;
std::string key;
PMCC value;
std::string error;
};
struct SelfKickMessage
{
//empty
};
struct GetStatsMessage
{
Token prio_token;
std::string block_id;
BlockStats stats;
time_ticks_t stats_time;
};
} //namespace gras
#include <Theron/Register.h>
#include <gras/top_block.hpp>
#include <gras_impl/messages.hpp>
#include <gras_impl/interruptible_thread.hpp>
THERON_DECLARE_REGISTERED_MESSAGE(gras::TopAllocMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::TopActiveMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::TopInertMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::TopTokenMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::GlobalBlockConfig);
THERON_DECLARE_REGISTERED_MESSAGE(gras::SharedThreadGroup);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputTagMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputMsgMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputBufferMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputTokenMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputCheckMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputAllocMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::InputUpdateMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputBufferMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputTokenMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputCheckMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputHintMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputAllocMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::OutputUpdateMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::PropAccessMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::SelfKickMessage);
THERON_DECLARE_REGISTERED_MESSAGE(gras::GetStatsMessage);
#endif /*INCLUDED_LIBGRAS_IMPL_MESSAGES_HPP*/
| [
"josh@joshknows.com"
] | josh@joshknows.com |
62ed882118e27c5d9a4dbcf935b62cf45110d66e | 2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac | /POJ/2236/8366219_AC_1000ms_408kB.cpp | 24b755e2f7b2b2fcc9385d6b9093d0ce726972ff | [] | no_license | weakmale/hhabb | 9e28b1f2ed34be1ecede5b34dc2d2f62588a5528 | 649f0d2b5796ec10580428d16921879aa380e1f2 | refs/heads/master | 2021-01-01T20:19:08.062232 | 2017-07-30T17:23:21 | 2017-07-30T17:23:21 | 98,811,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | #include "cstdio"
using namespace std;
int x[1010],y[1010];
int F[1010];
bool vis[1010];
int n,k;
int Found(int x){ return F[x]==x?x:F[x]=Found(F[x]); }
void Union(int a,int b){
int nx=Found(a),ny=Found(b);
if(nx!=ny)
if((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b])<=k*k)
F[ny]=F[nx];
}
int main(){
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d %d",x+i,y+i),F[i]=i;
char s[2];
while(~scanf("%s",s)){
if(s[0]=='O'){
int num;scanf("%d",&num);
for(int i=1;i<=n;i++)
if(vis[i])
Union(i, num);
vis[num]=true;
}
else{
int a,b; scanf("%d %d",&a,&b);
if(Found(a)==Found(b))
puts("SUCCESS");
else
puts("FAIL");
}
}
return 0;
} | [
"wuweak@gmail.com"
] | wuweak@gmail.com |
4bb916a384cf84040f9e19a71bbf12f9f2d8738d | ba1225a167d19fe712889d5375fdcbceae6dc00c | /0724/singleton.cc | ba93c33aa57940ed51fd3bdd5c705d89237ff1d5 | [] | no_license | 1820286011/learngit | ab9d45da679a6cd0afba1aa25d0c2f2a02bef82b | 1c34bb29468350bdb25dca91bd62bd1b500073b4 | refs/heads/master | 2021-05-16T16:22:36.584687 | 2016-08-27T01:24:10 | 2016-08-27T01:24:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | cc | ///
/// @file singleton.cc
/// @author wyy
/// @date 2016-07-24 06:20:41
///
#include <iostream>
#include <string>
using namespace std;
class Singleton
{
public:
static Singleton * init(int x)
{
if(p==NULL)
{
p=new Singleton(x);
return p;
}else
{
return p;
}
}
void destory()
{
if(p!=NULL)
{
delete p;
// p->~Singleton();
p=NULL;
cout<<"destory()"<<endl;
}
}
~Singleton()
{
}
private:
int initx;
static Singleton * p;
Singleton(int x):initx(x)
{
cout<<" init"<<endl;}
};
Singleton* Singleton :: p=NULL;
int main()
{
Singleton *p1 = Singleton::init(2);
Singleton *p2 = Singleton::init(2);
cout<<"p1="<<p1<<" p2="<<p2<<endl;
p1->destory();
p2->destory();
}
| [
"972983449@qq.com"
] | 972983449@qq.com |
0dbf5c15d4f08870ee9429bfa4bff6c220deceac | 66a57b3b1ad1d892cde371f6fef8d74c6fce3723 | /compiler/optimizing/nodes.h | a2cb1c47aeac8b553ba232df523ae4ac26beee9c | [
"Apache-2.0"
] | permissive | DroidSim/platform_art | fc9f91acead711450b4fdc04c98600e74580013f | d3236731ca6145e0723ce8aab8c6ff634ab021c2 | refs/heads/master | 2020-04-06T21:37:42.363306 | 2014-05-21T01:08:10 | 2014-05-21T01:08:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,932 | h | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_COMPILER_OPTIMIZING_NODES_H_
#define ART_COMPILER_OPTIMIZING_NODES_H_
#include "utils/allocation.h"
#include "utils/arena_bit_vector.h"
#include "utils/growable_array.h"
namespace art {
class HBasicBlock;
class HEnvironment;
class HInstruction;
class HIntConstant;
class HGraphVisitor;
class HPhi;
class LiveInterval;
class LocationSummary;
static const int kDefaultNumberOfBlocks = 8;
static const int kDefaultNumberOfSuccessors = 2;
static const int kDefaultNumberOfPredecessors = 2;
static const int kDefaultNumberOfBackEdges = 1;
class HInstructionList {
public:
HInstructionList() : first_instruction_(nullptr), last_instruction_(nullptr) {}
void AddInstruction(HInstruction* instruction);
void RemoveInstruction(HInstruction* instruction);
private:
HInstruction* first_instruction_;
HInstruction* last_instruction_;
friend class HBasicBlock;
friend class HInstructionIterator;
friend class HBackwardInstructionIterator;
DISALLOW_COPY_AND_ASSIGN(HInstructionList);
};
// Control-flow graph of a method. Contains a list of basic blocks.
class HGraph : public ArenaObject {
public:
explicit HGraph(ArenaAllocator* arena)
: arena_(arena),
blocks_(arena, kDefaultNumberOfBlocks),
reverse_post_order_(arena, kDefaultNumberOfBlocks),
maximum_number_of_out_vregs_(0),
number_of_vregs_(0),
number_of_in_vregs_(0),
current_instruction_id_(0) { }
ArenaAllocator* GetArena() const { return arena_; }
const GrowableArray<HBasicBlock*>& GetBlocks() const { return blocks_; }
HBasicBlock* GetEntryBlock() const { return entry_block_; }
HBasicBlock* GetExitBlock() const { return exit_block_; }
void SetEntryBlock(HBasicBlock* block) { entry_block_ = block; }
void SetExitBlock(HBasicBlock* block) { exit_block_ = block; }
void AddBlock(HBasicBlock* block);
void BuildDominatorTree();
void TransformToSSA();
void SimplifyCFG();
// Find all natural loops in this graph. Aborts computation and returns false
// if one loop is not natural, that is the header does not dominate the back
// edge.
bool FindNaturalLoops() const;
void SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor);
void SimplifyLoop(HBasicBlock* header);
int GetNextInstructionId() {
return current_instruction_id_++;
}
uint16_t GetMaximumNumberOfOutVRegs() const {
return maximum_number_of_out_vregs_;
}
void UpdateMaximumNumberOfOutVRegs(uint16_t new_value) {
maximum_number_of_out_vregs_ = std::max(new_value, maximum_number_of_out_vregs_);
}
void SetNumberOfVRegs(uint16_t number_of_vregs) {
number_of_vregs_ = number_of_vregs;
}
uint16_t GetNumberOfVRegs() const {
return number_of_vregs_;
}
void SetNumberOfInVRegs(uint16_t value) {
number_of_in_vregs_ = value;
}
uint16_t GetNumberOfInVRegs() const {
return number_of_in_vregs_;
}
const GrowableArray<HBasicBlock*>& GetReversePostOrder() const {
return reverse_post_order_;
}
private:
HBasicBlock* FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const;
void VisitBlockForDominatorTree(HBasicBlock* block,
HBasicBlock* predecessor,
GrowableArray<size_t>* visits);
void FindBackEdges(ArenaBitVector* visited);
void VisitBlockForBackEdges(HBasicBlock* block,
ArenaBitVector* visited,
ArenaBitVector* visiting);
void RemoveDeadBlocks(const ArenaBitVector& visited) const;
ArenaAllocator* const arena_;
// List of blocks in insertion order.
GrowableArray<HBasicBlock*> blocks_;
// List of blocks to perform a reverse post order tree traversal.
GrowableArray<HBasicBlock*> reverse_post_order_;
HBasicBlock* entry_block_;
HBasicBlock* exit_block_;
// The maximum number of virtual registers arguments passed to a HInvoke in this graph.
uint16_t maximum_number_of_out_vregs_;
// The number of virtual registers in this method. Contains the parameters.
uint16_t number_of_vregs_;
// The number of virtual registers used by parameters of this method.
uint16_t number_of_in_vregs_;
// The current id to assign to a newly added instruction. See HInstruction.id_.
int current_instruction_id_;
DISALLOW_COPY_AND_ASSIGN(HGraph);
};
class HLoopInformation : public ArenaObject {
public:
HLoopInformation(HBasicBlock* header, HGraph* graph)
: header_(header),
back_edges_(graph->GetArena(), kDefaultNumberOfBackEdges),
blocks_(graph->GetArena(), graph->GetBlocks().Size(), false) {}
HBasicBlock* GetHeader() const {
return header_;
}
void AddBackEdge(HBasicBlock* back_edge) {
back_edges_.Add(back_edge);
}
void RemoveBackEdge(HBasicBlock* back_edge) {
back_edges_.Delete(back_edge);
}
bool IsBackEdge(HBasicBlock* block) {
for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
if (back_edges_.Get(i) == block) return true;
}
return false;
}
int NumberOfBackEdges() const {
return back_edges_.Size();
}
HBasicBlock* GetPreHeader() const;
const GrowableArray<HBasicBlock*>& GetBackEdges() const {
return back_edges_;
}
void ClearBackEdges() {
back_edges_.Reset();
}
// Find blocks that are part of this loop. Returns whether the loop is a natural loop,
// that is the header dominates the back edge.
bool Populate();
// Returns whether this loop information contains `block`.
// Note that this loop information *must* be populated before entering this function.
bool Contains(const HBasicBlock& block) const;
// Returns whether this loop information is an inner loop of `other`.
// Note that `other` *must* be populated before entering this function.
bool IsIn(const HLoopInformation& other) const;
const ArenaBitVector& GetBlocks() const { return blocks_; }
private:
// Internal recursive implementation of `Populate`.
void PopulateRecursive(HBasicBlock* block);
HBasicBlock* header_;
GrowableArray<HBasicBlock*> back_edges_;
ArenaBitVector blocks_;
DISALLOW_COPY_AND_ASSIGN(HLoopInformation);
};
static constexpr size_t kNoLifetime = -1;
// A block in a method. Contains the list of instructions represented
// as a double linked list. Each block knows its predecessors and
// successors.
class HBasicBlock : public ArenaObject {
public:
explicit HBasicBlock(HGraph* graph)
: graph_(graph),
predecessors_(graph->GetArena(), kDefaultNumberOfPredecessors),
successors_(graph->GetArena(), kDefaultNumberOfSuccessors),
loop_information_(nullptr),
dominator_(nullptr),
block_id_(-1),
lifetime_start_(kNoLifetime),
lifetime_end_(kNoLifetime) {}
const GrowableArray<HBasicBlock*>& GetPredecessors() const {
return predecessors_;
}
const GrowableArray<HBasicBlock*>& GetSuccessors() const {
return successors_;
}
void AddBackEdge(HBasicBlock* back_edge) {
if (loop_information_ == nullptr) {
loop_information_ = new (graph_->GetArena()) HLoopInformation(this, graph_);
}
DCHECK_EQ(loop_information_->GetHeader(), this);
loop_information_->AddBackEdge(back_edge);
}
HGraph* GetGraph() const { return graph_; }
int GetBlockId() const { return block_id_; }
void SetBlockId(int id) { block_id_ = id; }
HBasicBlock* GetDominator() const { return dominator_; }
void SetDominator(HBasicBlock* dominator) { dominator_ = dominator; }
int NumberOfBackEdges() const {
return loop_information_ == nullptr
? 0
: loop_information_->NumberOfBackEdges();
}
HInstruction* GetFirstInstruction() const { return instructions_.first_instruction_; }
HInstruction* GetLastInstruction() const { return instructions_.last_instruction_; }
const HInstructionList& GetInstructions() const { return instructions_; }
const HInstructionList& GetPhis() const { return phis_; }
void AddSuccessor(HBasicBlock* block) {
successors_.Add(block);
block->predecessors_.Add(this);
}
void RemovePredecessor(HBasicBlock* block, bool remove_in_successor = true) {
predecessors_.Delete(block);
if (remove_in_successor) {
block->successors_.Delete(this);
}
}
void RemoveSuccessor(HBasicBlock* block, bool remove_in_predecessor = true) {
successors_.Delete(block);
if (remove_in_predecessor) {
block->predecessors_.Delete(this);
}
}
void ClearAllPredecessors() {
predecessors_.Reset();
}
void AddPredecessor(HBasicBlock* block) {
predecessors_.Add(block);
block->successors_.Add(this);
}
size_t GetPredecessorIndexOf(HBasicBlock* predecessor) {
for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
if (predecessors_.Get(i) == predecessor) {
return i;
}
}
return -1;
}
void AddInstruction(HInstruction* instruction);
void RemoveInstruction(HInstruction* instruction);
void AddPhi(HPhi* phi);
void RemovePhi(HPhi* phi);
bool IsLoopHeader() const {
return (loop_information_ != nullptr) && (loop_information_->GetHeader() == this);
}
HLoopInformation* GetLoopInformation() const {
return loop_information_;
}
// Set the loop_information_ on this block. This method overrides the current
// loop_information if it is an outer loop of the passed loop information.
void SetInLoop(HLoopInformation* info) {
if (IsLoopHeader()) {
// Nothing to do. This just means `info` is an outer loop.
} else if (loop_information_ == nullptr) {
loop_information_ = info;
} else if (loop_information_->Contains(*info->GetHeader())) {
// Block is currently part of an outer loop. Make it part of this inner loop.
// Note that a non loop header having a loop information means this loop information
// has already been populated
loop_information_ = info;
} else {
// Block is part of an inner loop. Do not update the loop information.
// Note that we cannot do the check `info->Contains(loop_information_)->GetHeader()`
// at this point, because this method is being called while populating `info`.
}
}
// Returns wheter this block dominates the blocked passed as parameter.
bool Dominates(HBasicBlock* block) const;
size_t GetLifetimeStart() const { return lifetime_start_; }
size_t GetLifetimeEnd() const { return lifetime_end_; }
void SetLifetimeStart(size_t start) { lifetime_start_ = start; }
void SetLifetimeEnd(size_t end) { lifetime_end_ = end; }
private:
HGraph* const graph_;
GrowableArray<HBasicBlock*> predecessors_;
GrowableArray<HBasicBlock*> successors_;
HInstructionList instructions_;
HInstructionList phis_;
HLoopInformation* loop_information_;
HBasicBlock* dominator_;
int block_id_;
size_t lifetime_start_;
size_t lifetime_end_;
DISALLOW_COPY_AND_ASSIGN(HBasicBlock);
};
#define FOR_EACH_INSTRUCTION(M) \
M(Add) \
M(Equal) \
M(Exit) \
M(Goto) \
M(If) \
M(IntConstant) \
M(InvokeStatic) \
M(LoadLocal) \
M(Local) \
M(LongConstant) \
M(NewInstance) \
M(Not) \
M(ParameterValue) \
M(Phi) \
M(Return) \
M(ReturnVoid) \
M(StoreLocal) \
M(Sub) \
#define FORWARD_DECLARATION(type) class H##type;
FOR_EACH_INSTRUCTION(FORWARD_DECLARATION)
#undef FORWARD_DECLARATION
#define DECLARE_INSTRUCTION(type) \
virtual void Accept(HGraphVisitor* visitor); \
virtual const char* DebugName() const { return #type; } \
virtual H##type* As##type() { return this; } \
template <typename T>
class HUseListNode : public ArenaObject {
public:
HUseListNode(T* user, size_t index, HUseListNode* tail)
: user_(user), index_(index), tail_(tail) { }
HUseListNode* GetTail() const { return tail_; }
T* GetUser() const { return user_; }
size_t GetIndex() const { return index_; }
void SetTail(HUseListNode<T>* node) { tail_ = node; }
private:
T* const user_;
const size_t index_;
HUseListNode<T>* tail_;
DISALLOW_COPY_AND_ASSIGN(HUseListNode);
};
class HInstruction : public ArenaObject {
public:
HInstruction()
: previous_(nullptr),
next_(nullptr),
block_(nullptr),
id_(-1),
ssa_index_(-1),
uses_(nullptr),
env_uses_(nullptr),
environment_(nullptr),
locations_(nullptr),
live_interval_(nullptr),
lifetime_position_(kNoLifetime) {}
virtual ~HInstruction() { }
HInstruction* GetNext() const { return next_; }
HInstruction* GetPrevious() const { return previous_; }
HBasicBlock* GetBlock() const { return block_; }
void SetBlock(HBasicBlock* block) { block_ = block; }
virtual size_t InputCount() const = 0;
virtual HInstruction* InputAt(size_t i) const = 0;
virtual void Accept(HGraphVisitor* visitor) = 0;
virtual const char* DebugName() const = 0;
virtual Primitive::Type GetType() const { return Primitive::kPrimVoid; }
virtual void SetRawInputAt(size_t index, HInstruction* input) = 0;
virtual bool NeedsEnvironment() const { return false; }
void AddUseAt(HInstruction* user, size_t index) {
uses_ = new (block_->GetGraph()->GetArena()) HUseListNode<HInstruction>(user, index, uses_);
}
void AddEnvUseAt(HEnvironment* user, size_t index) {
env_uses_ = new (block_->GetGraph()->GetArena()) HUseListNode<HEnvironment>(
user, index, env_uses_);
}
void RemoveUser(HInstruction* user, size_t index);
HUseListNode<HInstruction>* GetUses() const { return uses_; }
HUseListNode<HEnvironment>* GetEnvUses() const { return env_uses_; }
bool HasUses() const { return uses_ != nullptr || env_uses_ != nullptr; }
size_t NumberOfUses() const {
// TODO: Optimize this method if it is used outside of the HGraphVisualizer.
size_t result = 0;
HUseListNode<HInstruction>* current = uses_;
while (current != nullptr) {
current = current->GetTail();
++result;
}
return result;
}
int GetId() const { return id_; }
void SetId(int id) { id_ = id; }
int GetSsaIndex() const { return ssa_index_; }
void SetSsaIndex(int ssa_index) { ssa_index_ = ssa_index; }
bool HasSsaIndex() const { return ssa_index_ != -1; }
bool HasEnvironment() const { return environment_ != nullptr; }
HEnvironment* GetEnvironment() const { return environment_; }
void SetEnvironment(HEnvironment* environment) { environment_ = environment; }
LocationSummary* GetLocations() const { return locations_; }
void SetLocations(LocationSummary* locations) { locations_ = locations; }
void ReplaceWith(HInstruction* instruction);
#define INSTRUCTION_TYPE_CHECK(type) \
virtual H##type* As##type() { return nullptr; }
FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
#undef INSTRUCTION_TYPE_CHECK
size_t GetLifetimePosition() const { return lifetime_position_; }
void SetLifetimePosition(size_t position) { lifetime_position_ = position; }
LiveInterval* GetLiveInterval() const { return live_interval_; }
void SetLiveInterval(LiveInterval* interval) { live_interval_ = interval; }
bool HasLiveInterval() const { return live_interval_ != nullptr; }
private:
HInstruction* previous_;
HInstruction* next_;
HBasicBlock* block_;
// An instruction gets an id when it is added to the graph.
// It reflects creation order. A negative id means the instruction
// has not beed added to the graph.
int id_;
// When doing liveness analysis, instructions that have uses get an SSA index.
int ssa_index_;
// List of instructions that have this instruction as input.
HUseListNode<HInstruction>* uses_;
// List of environments that contain this instruction.
HUseListNode<HEnvironment>* env_uses_;
HEnvironment* environment_;
// Set by the code generator.
LocationSummary* locations_;
// Set by the liveness analysis.
LiveInterval* live_interval_;
// Set by the liveness analysis, this is the position in a linear
// order of blocks where this instruction's live interval start.
size_t lifetime_position_;
friend class HBasicBlock;
friend class HInstructionList;
DISALLOW_COPY_AND_ASSIGN(HInstruction);
};
template<typename T>
class HUseIterator : public ValueObject {
public:
explicit HUseIterator(HUseListNode<T>* uses) : current_(uses) {}
bool Done() const { return current_ == nullptr; }
void Advance() {
DCHECK(!Done());
current_ = current_->GetTail();
}
HUseListNode<T>* Current() const {
DCHECK(!Done());
return current_;
}
private:
HUseListNode<T>* current_;
friend class HValue;
};
// A HEnvironment object contains the values of virtual registers at a given location.
class HEnvironment : public ArenaObject {
public:
HEnvironment(ArenaAllocator* arena, size_t number_of_vregs) : vregs_(arena, number_of_vregs) {
vregs_.SetSize(number_of_vregs);
for (size_t i = 0; i < number_of_vregs; i++) {
vregs_.Put(i, nullptr);
}
}
void Populate(const GrowableArray<HInstruction*>& env) {
for (size_t i = 0; i < env.Size(); i++) {
HInstruction* instruction = env.Get(i);
vregs_.Put(i, instruction);
if (instruction != nullptr) {
instruction->AddEnvUseAt(this, i);
}
}
}
void SetRawEnvAt(size_t index, HInstruction* instruction) {
vregs_.Put(index, instruction);
}
GrowableArray<HInstruction*>* GetVRegs() {
return &vregs_;
}
private:
GrowableArray<HInstruction*> vregs_;
DISALLOW_COPY_AND_ASSIGN(HEnvironment);
};
class HInputIterator : public ValueObject {
public:
explicit HInputIterator(HInstruction* instruction) : instruction_(instruction), index_(0) { }
bool Done() const { return index_ == instruction_->InputCount(); }
HInstruction* Current() const { return instruction_->InputAt(index_); }
void Advance() { index_++; }
private:
HInstruction* instruction_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HInputIterator);
};
class HInstructionIterator : public ValueObject {
public:
explicit HInstructionIterator(const HInstructionList& instructions)
: instruction_(instructions.first_instruction_) {
next_ = Done() ? nullptr : instruction_->GetNext();
}
bool Done() const { return instruction_ == nullptr; }
HInstruction* Current() const { return instruction_; }
void Advance() {
instruction_ = next_;
next_ = Done() ? nullptr : instruction_->GetNext();
}
private:
HInstruction* instruction_;
HInstruction* next_;
DISALLOW_COPY_AND_ASSIGN(HInstructionIterator);
};
class HBackwardInstructionIterator : public ValueObject {
public:
explicit HBackwardInstructionIterator(const HInstructionList& instructions)
: instruction_(instructions.last_instruction_) {
next_ = Done() ? nullptr : instruction_->GetPrevious();
}
bool Done() const { return instruction_ == nullptr; }
HInstruction* Current() const { return instruction_; }
void Advance() {
instruction_ = next_;
next_ = Done() ? nullptr : instruction_->GetPrevious();
}
private:
HInstruction* instruction_;
HInstruction* next_;
DISALLOW_COPY_AND_ASSIGN(HBackwardInstructionIterator);
};
// An embedded container with N elements of type T. Used (with partial
// specialization for N=0) because embedded arrays cannot have size 0.
template<typename T, intptr_t N>
class EmbeddedArray {
public:
EmbeddedArray() : elements_() { }
intptr_t GetLength() const { return N; }
const T& operator[](intptr_t i) const {
DCHECK_LT(i, GetLength());
return elements_[i];
}
T& operator[](intptr_t i) {
DCHECK_LT(i, GetLength());
return elements_[i];
}
const T& At(intptr_t i) const {
return (*this)[i];
}
void SetAt(intptr_t i, const T& val) {
(*this)[i] = val;
}
private:
T elements_[N];
};
template<typename T>
class EmbeddedArray<T, 0> {
public:
intptr_t length() const { return 0; }
const T& operator[](intptr_t i) const {
LOG(FATAL) << "Unreachable";
static T sentinel = 0;
return sentinel;
}
T& operator[](intptr_t i) {
LOG(FATAL) << "Unreachable";
static T sentinel = 0;
return sentinel;
}
};
template<intptr_t N>
class HTemplateInstruction: public HInstruction {
public:
HTemplateInstruction<N>() : inputs_() { }
virtual ~HTemplateInstruction() { }
virtual size_t InputCount() const { return N; }
virtual HInstruction* InputAt(size_t i) const { return inputs_[i]; }
protected:
virtual void SetRawInputAt(size_t i, HInstruction* instruction) {
inputs_[i] = instruction;
}
private:
EmbeddedArray<HInstruction*, N> inputs_;
friend class SsaBuilder;
};
// Represents dex's RETURN_VOID opcode. A HReturnVoid is a control flow
// instruction that branches to the exit block.
class HReturnVoid : public HTemplateInstruction<0> {
public:
HReturnVoid() { }
DECLARE_INSTRUCTION(ReturnVoid)
private:
DISALLOW_COPY_AND_ASSIGN(HReturnVoid);
};
// Represents dex's RETURN opcodes. A HReturn is a control flow
// instruction that branches to the exit block.
class HReturn : public HTemplateInstruction<1> {
public:
explicit HReturn(HInstruction* value) {
SetRawInputAt(0, value);
}
DECLARE_INSTRUCTION(Return)
private:
DISALLOW_COPY_AND_ASSIGN(HReturn);
};
// The exit instruction is the only instruction of the exit block.
// Instructions aborting the method (HTrow and HReturn) must branch to the
// exit block.
class HExit : public HTemplateInstruction<0> {
public:
HExit() { }
DECLARE_INSTRUCTION(Exit)
private:
DISALLOW_COPY_AND_ASSIGN(HExit);
};
// Jumps from one block to another.
class HGoto : public HTemplateInstruction<0> {
public:
HGoto() { }
HBasicBlock* GetSuccessor() const {
return GetBlock()->GetSuccessors().Get(0);
}
DECLARE_INSTRUCTION(Goto)
private:
DISALLOW_COPY_AND_ASSIGN(HGoto);
};
// Conditional branch. A block ending with an HIf instruction must have
// two successors.
class HIf : public HTemplateInstruction<1> {
public:
explicit HIf(HInstruction* input) {
SetRawInputAt(0, input);
}
HBasicBlock* IfTrueSuccessor() const {
return GetBlock()->GetSuccessors().Get(0);
}
HBasicBlock* IfFalseSuccessor() const {
return GetBlock()->GetSuccessors().Get(1);
}
DECLARE_INSTRUCTION(If)
private:
DISALLOW_COPY_AND_ASSIGN(HIf);
};
class HBinaryOperation : public HTemplateInstruction<2> {
public:
HBinaryOperation(Primitive::Type result_type,
HInstruction* left,
HInstruction* right) : result_type_(result_type) {
SetRawInputAt(0, left);
SetRawInputAt(1, right);
}
HInstruction* GetLeft() const { return InputAt(0); }
HInstruction* GetRight() const { return InputAt(1); }
Primitive::Type GetResultType() const { return result_type_; }
virtual bool IsCommutative() { return false; }
virtual Primitive::Type GetType() const { return GetResultType(); }
private:
const Primitive::Type result_type_;
DISALLOW_COPY_AND_ASSIGN(HBinaryOperation);
};
// Instruction to check if two inputs are equal to each other.
class HEqual : public HBinaryOperation {
public:
HEqual(HInstruction* first, HInstruction* second)
: HBinaryOperation(Primitive::kPrimBoolean, first, second) {}
virtual bool IsCommutative() { return true; }
virtual Primitive::Type GetType() const { return Primitive::kPrimBoolean; }
DECLARE_INSTRUCTION(Equal)
private:
DISALLOW_COPY_AND_ASSIGN(HEqual);
};
// A local in the graph. Corresponds to a Dex register.
class HLocal : public HTemplateInstruction<0> {
public:
explicit HLocal(uint16_t reg_number) : reg_number_(reg_number) { }
DECLARE_INSTRUCTION(Local)
uint16_t GetRegNumber() const { return reg_number_; }
private:
// The Dex register number.
const uint16_t reg_number_;
DISALLOW_COPY_AND_ASSIGN(HLocal);
};
// Load a given local. The local is an input of this instruction.
class HLoadLocal : public HTemplateInstruction<1> {
public:
explicit HLoadLocal(HLocal* local, Primitive::Type type) : type_(type) {
SetRawInputAt(0, local);
}
virtual Primitive::Type GetType() const { return type_; }
HLocal* GetLocal() const { return reinterpret_cast<HLocal*>(InputAt(0)); }
DECLARE_INSTRUCTION(LoadLocal)
private:
const Primitive::Type type_;
DISALLOW_COPY_AND_ASSIGN(HLoadLocal);
};
// Store a value in a given local. This instruction has two inputs: the value
// and the local.
class HStoreLocal : public HTemplateInstruction<2> {
public:
HStoreLocal(HLocal* local, HInstruction* value) {
SetRawInputAt(0, local);
SetRawInputAt(1, value);
}
HLocal* GetLocal() const { return reinterpret_cast<HLocal*>(InputAt(0)); }
DECLARE_INSTRUCTION(StoreLocal)
private:
DISALLOW_COPY_AND_ASSIGN(HStoreLocal);
};
// Constants of the type int. Those can be from Dex instructions, or
// synthesized (for example with the if-eqz instruction).
class HIntConstant : public HTemplateInstruction<0> {
public:
explicit HIntConstant(int32_t value) : value_(value) { }
int32_t GetValue() const { return value_; }
virtual Primitive::Type GetType() const { return Primitive::kPrimInt; }
DECLARE_INSTRUCTION(IntConstant)
private:
const int32_t value_;
DISALLOW_COPY_AND_ASSIGN(HIntConstant);
};
class HLongConstant : public HTemplateInstruction<0> {
public:
explicit HLongConstant(int64_t value) : value_(value) { }
int64_t GetValue() const { return value_; }
virtual Primitive::Type GetType() const { return Primitive::kPrimLong; }
DECLARE_INSTRUCTION(LongConstant)
private:
const int64_t value_;
DISALLOW_COPY_AND_ASSIGN(HLongConstant);
};
class HInvoke : public HInstruction {
public:
HInvoke(ArenaAllocator* arena,
uint32_t number_of_arguments,
Primitive::Type return_type,
uint32_t dex_pc)
: inputs_(arena, number_of_arguments),
return_type_(return_type),
dex_pc_(dex_pc) {
inputs_.SetSize(number_of_arguments);
}
virtual size_t InputCount() const { return inputs_.Size(); }
virtual HInstruction* InputAt(size_t i) const { return inputs_.Get(i); }
// Runtime needs to walk the stack, so Dex -> Dex calls need to
// know their environment.
virtual bool NeedsEnvironment() const { return true; }
void SetArgumentAt(size_t index, HInstruction* argument) {
SetRawInputAt(index, argument);
}
virtual void SetRawInputAt(size_t index, HInstruction* input) {
inputs_.Put(index, input);
}
virtual Primitive::Type GetType() const { return return_type_; }
uint32_t GetDexPc() const { return dex_pc_; }
protected:
GrowableArray<HInstruction*> inputs_;
const Primitive::Type return_type_;
const uint32_t dex_pc_;
private:
DISALLOW_COPY_AND_ASSIGN(HInvoke);
};
class HInvokeStatic : public HInvoke {
public:
HInvokeStatic(ArenaAllocator* arena,
uint32_t number_of_arguments,
Primitive::Type return_type,
uint32_t dex_pc,
uint32_t index_in_dex_cache)
: HInvoke(arena, number_of_arguments, return_type, dex_pc),
index_in_dex_cache_(index_in_dex_cache) {}
uint32_t GetIndexInDexCache() const { return index_in_dex_cache_; }
DECLARE_INSTRUCTION(InvokeStatic)
private:
const uint32_t index_in_dex_cache_;
DISALLOW_COPY_AND_ASSIGN(HInvokeStatic);
};
class HNewInstance : public HTemplateInstruction<0> {
public:
HNewInstance(uint32_t dex_pc, uint16_t type_index) : dex_pc_(dex_pc), type_index_(type_index) {}
uint32_t GetDexPc() const { return dex_pc_; }
uint16_t GetTypeIndex() const { return type_index_; }
virtual Primitive::Type GetType() const { return Primitive::kPrimNot; }
// Calls runtime so needs an environment.
virtual bool NeedsEnvironment() const { return true; }
DECLARE_INSTRUCTION(NewInstance)
private:
const uint32_t dex_pc_;
const uint16_t type_index_;
DISALLOW_COPY_AND_ASSIGN(HNewInstance);
};
class HAdd : public HBinaryOperation {
public:
HAdd(Primitive::Type result_type, HInstruction* left, HInstruction* right)
: HBinaryOperation(result_type, left, right) {}
virtual bool IsCommutative() { return true; }
DECLARE_INSTRUCTION(Add);
private:
DISALLOW_COPY_AND_ASSIGN(HAdd);
};
class HSub : public HBinaryOperation {
public:
HSub(Primitive::Type result_type, HInstruction* left, HInstruction* right)
: HBinaryOperation(result_type, left, right) {}
virtual bool IsCommutative() { return false; }
DECLARE_INSTRUCTION(Sub);
private:
DISALLOW_COPY_AND_ASSIGN(HSub);
};
// The value of a parameter in this method. Its location depends on
// the calling convention.
class HParameterValue : public HTemplateInstruction<0> {
public:
HParameterValue(uint8_t index, Primitive::Type parameter_type)
: index_(index), parameter_type_(parameter_type) {}
uint8_t GetIndex() const { return index_; }
virtual Primitive::Type GetType() const { return parameter_type_; }
DECLARE_INSTRUCTION(ParameterValue);
private:
// The index of this parameter in the parameters list. Must be less
// than HGraph::number_of_in_vregs_;
const uint8_t index_;
const Primitive::Type parameter_type_;
DISALLOW_COPY_AND_ASSIGN(HParameterValue);
};
class HNot : public HTemplateInstruction<1> {
public:
explicit HNot(HInstruction* input) {
SetRawInputAt(0, input);
}
virtual Primitive::Type GetType() const { return Primitive::kPrimBoolean; }
DECLARE_INSTRUCTION(Not);
private:
DISALLOW_COPY_AND_ASSIGN(HNot);
};
class HPhi : public HInstruction {
public:
HPhi(ArenaAllocator* arena, uint32_t reg_number, size_t number_of_inputs, Primitive::Type type)
: inputs_(arena, number_of_inputs),
reg_number_(reg_number),
type_(type) {
inputs_.SetSize(number_of_inputs);
}
virtual size_t InputCount() const { return inputs_.Size(); }
virtual HInstruction* InputAt(size_t i) const { return inputs_.Get(i); }
virtual void SetRawInputAt(size_t index, HInstruction* input) {
inputs_.Put(index, input);
}
void AddInput(HInstruction* input);
virtual Primitive::Type GetType() const { return type_; }
uint32_t GetRegNumber() const { return reg_number_; }
DECLARE_INSTRUCTION(Phi)
protected:
GrowableArray<HInstruction*> inputs_;
const uint32_t reg_number_;
const Primitive::Type type_;
private:
DISALLOW_COPY_AND_ASSIGN(HPhi);
};
class HGraphVisitor : public ValueObject {
public:
explicit HGraphVisitor(HGraph* graph) : graph_(graph) { }
virtual ~HGraphVisitor() { }
virtual void VisitInstruction(HInstruction* instruction) { }
virtual void VisitBasicBlock(HBasicBlock* block);
void VisitInsertionOrder();
HGraph* GetGraph() const { return graph_; }
// Visit functions for instruction classes.
#define DECLARE_VISIT_INSTRUCTION(name) \
virtual void Visit##name(H##name* instr) { VisitInstruction(instr); }
FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION)
#undef DECLARE_VISIT_INSTRUCTION
private:
HGraph* graph_;
DISALLOW_COPY_AND_ASSIGN(HGraphVisitor);
};
class HInsertionOrderIterator : public ValueObject {
public:
explicit HInsertionOrderIterator(const HGraph& graph) : graph_(graph), index_(0) {}
bool Done() const { return index_ == graph_.GetBlocks().Size(); }
HBasicBlock* Current() const { return graph_.GetBlocks().Get(index_); }
void Advance() { ++index_; }
private:
const HGraph& graph_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HInsertionOrderIterator);
};
class HReversePostOrderIterator : public ValueObject {
public:
explicit HReversePostOrderIterator(const HGraph& graph) : graph_(graph), index_(0) {}
bool Done() const { return index_ == graph_.GetReversePostOrder().Size(); }
HBasicBlock* Current() const { return graph_.GetReversePostOrder().Get(index_); }
void Advance() { ++index_; }
private:
const HGraph& graph_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HReversePostOrderIterator);
};
class HPostOrderIterator : public ValueObject {
public:
explicit HPostOrderIterator(const HGraph& graph)
: graph_(graph), index_(graph_.GetReversePostOrder().Size()) {}
bool Done() const { return index_ == 0; }
HBasicBlock* Current() const { return graph_.GetReversePostOrder().Get(index_ - 1); }
void Advance() { --index_; }
private:
const HGraph& graph_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HPostOrderIterator);
};
} // namespace art
#endif // ART_COMPILER_OPTIMIZING_NODES_H_
| [
"ngeoffray@google.com"
] | ngeoffray@google.com |
dc146cea483579a500c42722164859b4cf7b7529 | e1ad82f32e73b0a9750eb1a3eaf23b46a531cf12 | /eggs/src/main.cpp | 5403d3e114b9e77248387970a63e10f14e7cd750 | [] | no_license | markbirss/PicoQVGA | fb7f6deef67a1bed88b568fdf71528e073463c9e | 7d29c62ea1cda46bbec03f63b4d5fb8c8173700e | refs/heads/main | 2023-08-08T01:56:43.813250 | 2021-09-16T20:30:53 | 2021-09-16T20:30:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,887 | cpp |
// ****************************************************************************
//
// Main code
//
// ****************************************************************************
#include "include.h"
// game board
u8 Board[BOARDSIZE0];
// board template
const u8 BoardTemp[BOARDSIZE0] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 4, 4, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 4, 4, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
// directions
s8 DirX[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
s8 DirY[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
// players
int Stones[2]; // number of stones (player 1: number of eggs, player 2: number of hens)
int Wins[2]; // number of wins
Bool Comp[2]; // player is computer
u8 Player; // active player (0 or 1, 2=no player)
u8 CurX, CurY; // cursor position
u8 CurBlink; // blinking cursor
u8 Pos; // number of possible positions
u8 Free; // number of free positions
// get character from keyboard (0 = no key)
char GetChar()
{
char c = getchar_timeout_us(0);
if (c == (char)PICO_ERROR_TIMEOUT) c = 0;
if ((c >= 'a') && (c <= 'z')) c -= 32;
return c;
}
// flush characters from keyboard
void FlushChar()
{
while (GetChar() != 0) {}
}
// display help
void DispHelp()
{
printf("\n");
printf("%c ... right\n", KEY_R);
printf("%c ... up\n", KEY_U);
printf("%c ... left\n", KEY_L);
printf("%c ... down\n", KEY_D);
printf("%c ... help turn\n", KEY_HELP);
printf("%c ... quit, restart game\n", KEY_QUIT);
printf("%c ... 2 players\n", KEY_PLAY);
printf("%c ... demo\n", KEY_DEMO);
printf("Space ... play eggs, put stone\n");
printf("Enter ... play hens, put stone\n");
}
// draw board
void DrawBoard()
{
int i, j, x, y, b;
for (i = 0; i < BOARDH0; i++)
{
for (j = 0; j < BOARDW0; j++)
{
b = Board[i*BOARDW0 + j];
x = j*TILEW;
y = i*TILEH;
DrawImg(&TilesImg[b*TILEW*TILEH], x, y, TILEW, TILEH, TILEW);
}
}
}
// get board on coordinates (adds game start coordinate)
u8 GetBoard(s8 x, s8 y)
{
return Board[x+2 + (y+2)*BOARDW0];
}
// set board on coordinates (adds game start coordinates)
void SetBoard(s8 x, s8 y, u8 tile)
{
Board[x+2 + (y+2)*BOARDW0] = tile;
}
// set cursor on
void CurOn()
{
u8 c = GetBoard(CurX, CurY);
if ((c >= TILE_OFFMIN) && (c <= TILE_OFFMAX))
{
SetBoard(CurX, CurY, c - TILE_OFFMIN + TILE_ONMIN);
}
CurBlink = 0;
}
// set cursor off
void CurOff()
{
u8 c = GetBoard(CurX, CurY);
if ((c >= TILE_ONMIN) && (c <= TILE_ONMAX))
{
SetBoard(CurX, CurY, c - TILE_ONMIN + TILE_OFFMIN);
}
}
// discovery stones in one direction (returns number of stones; cursor must be off)
u8 GetStones1(s8 x, s8 y, s8 dx, s8 dy)
{
u8 c;
u8 steps = 0;
u8 stones = 0;
do {
// do step
x += dx;
y += dy;
// if chicken, number of steps is valid
c = GetBoard(x, y);
if (c == TILE_CHICKEN) stones = steps;
// increase number of steps
steps++;
// while tile is valid
} while ((c == TILE_EGG) || (c == TILE_CHICKEN) || (c == TILE_HEN));
return stones;
}
// discovery stones in all directions (returns number of stones; cursor must be off)
u8 GetStones(s8 x, s8 y)
{
u8 stones = 0;
int i;
for (i = 0; i < 8; i++) stones += GetStones1(x, y, DirX[i], DirY[i]);
return stones;
}
// display possible positions (cursor must be off)
void DispPos()
{
s8 x, y;
u8 stones;
u8 c;
// clear number of possible positions
Pos = 0;
// loop through all game tiles
for (y = 0; y < BOARDH; y++)
{
for (x = 0; x < BOARDW; x++)
{
// check if this tile is empty
c = GetBoard(x, y);
if ((c == TILE_EMPTY) || (c == TILE_DOT))
{
// count number of stones
if (GetStones(x, y) > 0)
{
// increase number of possible positions
Pos++;
SetBoard(x, y, TILE_DOT);
}
else
SetBoard(x, y, TILE_EMPTY);
}
}
}
}
// start open page (returns character)
char OpenScreen()
{
// copy open image
memcpy(FrameBuf, OpenImg, sizeof(OpenImg));
// play music
PlaySound(MappleSnd, sizeof(MappleSnd));
// wait for a key
int i;
char ch;
for (i = 200; i > 0; i--) // wait max. 20 seconds
{
ch = GetChar();
switch(ch)
{
// start game
case KEY_SPACE:
case KEY_PLAY:
case KEY_DEMO:
case KEY_OK:
StopSound();
return ch;
// no key
case 0:
break;
// invalid key
default:
DispHelp();
break;
}
sleep_ms(100);
}
// default returns demo
StopSound();
return KEY_DEMO;
}
// display selected player
void DispSel()
{
int play;
int y = 0;
for (play = 0; play < 2; play++)
{
// copy background
DrawImg(&FrameImg[y*FRAMEW], FRAMEX, y, FRAMEW, SELECTH, FRAMEW);
// draw computer
if (Comp[play]) DrawImg(ComputerImg, COMPX, y+COMPY, COMPW, COMPH, COMPW);
// draw selection frame
if (play == Player) DrawBlit(SelectImg, SELECTX, y+SELECTY, SELECTW, SELECTH, SELECTW, 0x61);
// shift Y coordinate
y += FRAMEY;
}
}
char NumBuf[20];
// display score
void DispScore()
{
int play;
int n;
for (play = 0; play < 2; play++)
{
n = DecNum(NumBuf, Stones[play]);
NumBuf[n++] = ' ';
NumBuf[n++] = 0;
DrawTextBg(NumBuf, SCOREX, SCOREY+play*FRAMEY, SCORECOL, SCOREBG);
}
}
// display wins
void DispWin()
{
int play;
int n;
for (play = 0; play < 2; play++)
{
n = DecNum(NumBuf, Wins[play]);
NumBuf[n++] = ' ';
NumBuf[n++] = ' ';
NumBuf[n++] = ' ';
NumBuf[n++] = 0;
DrawTextBg(NumBuf, WINX, WINY+play*FRAMEY, SCORECOL, SCOREBG);
}
}
// open game
void OpenGame(Bool comp1, Bool comp2)
{
// copy board template
memcpy(Board, BoardTemp, BOARDSIZE0);
DrawBoard();
// copy frame image
DrawImg(FrameImg, FRAMEX, 0, FRAMEW, FRAMEH, FRAMEW);
// initialize players
Stones[0] = 0;
Stones[1] = 0;
Comp[0] = comp1;
Comp[1] = comp2;
// start random player
Player = RandU8() & 1;
// cursor position
CurX = 3;
CurY = 3;
// initialize number of free positions
Free = BOARDW*BOARDH-4;
Pos = 12;
// display selected player
DispSel();
// display score
DispScore();
// display wins
DispWin();
}
// update stones in one direction
void PutStone1(s8 x, s8 y, s8 dx, s8 dy)
{
u8 c;
// check number of stones in this direction
u8 stones = GetStones1(x, y, dx, dy);
for (; stones > 0; stones--)
{
DrawBoard();
// play sound and short delay
PlaySound(BeepSnd, sizeof(BeepSnd));
sleep_ms(100);
// step
x += dx;
y += dy;
// get tile
c = GetBoard(x, y);
// player 2 is active, direction egg -> chicken -> hen
if (Player == 1)
{
// egg -> chicken
if (c == TILE_EGG)
{
Stones[0]--; // decrease number of eggs of player 1
c = TILE_CHICKEN; // change to chicken
}
// hen -> egg
else if (c == TILE_HEN)
{
Stones[1]--; // decrease number of hens of player 2
Stones[0]++; // increase number of eggs of player 1
c = TILE_EGG;
}
// chicken -> hen
else
{
Stones[1]++; // increase number of hens of player 2
c = TILE_HEN;
}
}
// player 1 is active, direction hen -> chicken -> egg
else
{
// egg -> hen
if (c == TILE_EGG)
{
Stones[0]--; // decrease number of effs of player 1
Stones[1]++; // increase number of hens of player 2
c = TILE_HEN;
}
// hen -> chicken
else if (c == TILE_HEN)
{
Stones[1]--; // decrease number of hens of player 2
c = TILE_CHICKEN;
}
// chicken -> egg
else
{
Stones[0]++; // increase number of effs of player 1
c = TILE_EGG;
}
}
// set tile
SetBoard(x, y, c);
DrawBoard();
// display score
DispScore();
}
}
// put stone (cursor must be off and current tile must be 'dot')
void PutStone()
{
int i;
// short blink cursor (must leave cursor off)
for (i = 5; i > 0; i--)
{
DrawBoard();
sleep_ms(50);
CurOn();
DrawBoard();
sleep_ms(50);
CurOff();
}
DrawBoard();
// put chicken into current position
SetBoard(CurX, CurY, TILE_CHICKEN);
// decrease free positions
Free--;
// update stones in all directions
for (i = 0; i < 8; i++) PutStone1(CurX, CurY, DirX[i], DirY[i]);
}
// get profit in one direction
s8 Profit1(s8 x, s8 y, s8 dx, s8 dy)
{
u8 c;
s8 profit = 0;
// check number of stones in this direction
u8 stones = GetStones1(x, y, dx, dy);
for (; stones > 0; stones--)
{
// step
x += dx;
y += dy;
// get tile
c = GetBoard(x, y);
// player 2 is active (egg -> chicken -> hen)
if (Player == 1)
{
// this player loses hen, opposite gains egg
if (c == TILE_HEN)
profit -= 2;
// this player gains hen or opposite loses egg
else
profit++;
}
// player 1 is active (hen -> chicken -> egg)
else
{
// this player loses egg, opposite gains hen
if (c == TILE_EGG)
profit -= 2;
// this player gains egg or opposite loses hen
else
profit++;
}
}
return profit;
}
// get tile profit
s8 Profit(s8 x, s8 y)
{
s8 profit = 0;
int i;
for (i = 0; i < 8; i++) profit += Profit1(x, y, DirX[i], DirY[i]);
return profit;
}
// find best position (cursor must be off)
void FindPos()
{
s8 x, y;
u8 c;
s8 bestprofit = -125; // profit of founded tiles
s8 profit;
// loop through all game tiles
for (y = 0; y < BOARDH; y++)
{
for (x = 0; x < BOARDW; x++)
{
// check if this tile is valid
c = GetBoard(x, y);
if (c == TILE_DOT)
{
// get profit of this field
profit = Profit(x, y);
// check better profit
if ((profit > bestprofit) ||
((profit == bestprofit) && (RandU8() < 80)))
{
// save new best state
bestprofit = profit;
CurX = x;
CurY = y;
}
}
}
}
}
// play game
void PlayGame(Bool comp1, Bool comp2)
{
int i;
char ch;
s8 x, y;
// demo mode
Bool demo = comp1 && comp2;
// open game
OpenGame(comp1, comp2);
// display possible positions
DispPos();
// display cursor on
CurOn();
DrawBoard();
// while there is some possible position
while ((Pos > 0) && (Free > 0))
{
// wait for a key
ch = GetChar();
// break demo
if (demo && (ch != 0)) return;
// player is computer
if (Comp[Player])
{
// find position
CurOff();
FindPos();
CurOn();
DrawBoard();
// put stone
if (!demo) FlushChar();
ch = KEY_OK;
}
switch (ch)
{
// break game
case KEY_QUIT:
return;
// right
case KEY_R:
if (CurX < BOARDW-1)
{
CurOff();
CurX++;
CurOn();
DrawBoard();
}
break;
// up
case KEY_U:
if (CurY > 0)
{
CurOff();
CurY--;
CurOn();
DrawBoard();
}
break;
// left
case KEY_L:
if (CurX > 0)
{
CurOff();
CurX--;
CurOn();
DrawBoard();
}
break;
// down
case KEY_D:
if (CurY < BOARDH-1)
{
CurOff();
CurY++;
CurOn();
DrawBoard();
}
break;
// help
case KEY_HELP:
CurOff();
FindPos();
CurOn();
DrawBoard();
break;
// put stone
case KEY_OK:
case KEY_SPACE:
CurOff();
if (GetBoard(CurX, CurY) == TILE_DOT)
{
// put stone
PutStone();
// update possible positions
DispPos();
// change player
Player ^= 1;
// display selected player
DispSel();
// display score
DispScore();
}
CurOn();
DrawBoard();
break;
// no key, short delay
case 0:
sleep_ms(50);
break;
// invalid key
default:
DispHelp();
break;
}
// blinking cursor
CurBlink++;
if (CurBlink == 5)
{
CurOff();
DrawBoard();
}
if (CurBlink == 8)
{
CurOn();
DrawBoard();
}
}
// cursor off
CurOff();
// select no player
Player = 2;
DispSel();
// max. time of blinking
i = demo ? 10 : 1000000000;
// player 1 (eggs) wins
if (Stones[0] > Stones[1])
{
// animate
for (y = 0; y < 8; y++)
{
for (x = 0; x < 8; x++)
{
if (GetBoard(x, y) == TILE_EGG)
{
SetBoard(x, y, TILE_EGGWIN);
PlaySound(Beep2Snd, sizeof(Beep2Snd));
DrawBoard();
sleep_ms(200);
}
}
}
// display wins
Wins[0]++;
DispWin();
// blink winner
for (; i > 0; i--)
{
Player = 0;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
Player = 2;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
}
}
// player 2 (hens) wins
else if (Stones[1] > Stones[0])
{
// animate
for (y = 0; y < 8; y++)
{
for (x = 0; x < 8; x++)
{
if (GetBoard(x, y) == TILE_HEN)
{
SetBoard(x, y, TILE_HENWIN);
PlaySound(Beep2Snd, sizeof(Beep2Snd));
DrawBoard();
sleep_ms(200);
}
}
}
// display wins
Wins[1]++;
DispWin();
// blink winner
for (; i > 0; i--)
{
Player = 1;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
Player = 2;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
}
}
// no winner
else
{
// blink winner
for (; i > 0; i--)
{
Player = 0;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
Player = 1;
DispSel();
DrawBoard();
sleep_ms(200);
if (GetChar() != 0) return;
}
}
}
// main function
int main()
{
char ch;
// clear players
Wins[0] = 0;
Wins[1] = 0;
// initialize stdio
stdio_init_all();
// initialize sound output
PWMSndInit();
// disp help
sleep_ms(200);
DispHelp();
// main loop
while (true)
{
// open screen
ch = OpenScreen();
// start new game
switch (ch)
{
// player is EGG
case KEY_SPACE:
PlayGame(False, True);
break;
// player is HEN
case KEY_OK:
PlayGame(True, False);
break;
// demo
case KEY_DEMO:
PlayGame(True, True);
break;
// 2 players
case KEY_PLAY:
PlayGame(False, False);
break;
}
}
}
| [
"Panda38@seznam.cz"
] | Panda38@seznam.cz |
ec9452b12f10e9aa34e78ee3ad9bd14fa6bbdedf | 877d507595e9054029a10ebd3cc0e67a82af751c | /src/qt/recentrequeststablemodel.h | a9984aa2aebfac393cc9d305847eacb37d32990a | [
"MIT"
] | permissive | AurumCoinHunter/AurumCoinHunter-CORE-v1.0.0.0-source | f8fe95101cee22f723e5df365f7600c957941637 | 35fa3889890741fcca7d00e09e2ef5919cb9de6f | refs/heads/master | 2020-05-05T09:09:50.957794 | 2019-04-07T14:26:45 | 2019-04-07T14:26:45 | 179,893,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,262 | h | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#define BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#include "walletmodel.h"
#include <QAbstractTableModel>
#include <QStringList>
#include <QDateTime>
class CWallet;
class RecentRequestEntry
{
public:
RecentRequestEntry() : nVersion(RecentRequestEntry::CURRENT_VERSION), id(0) { }
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t id;
QDateTime date;
SendCoinsRecipient recipient;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
unsigned int nDate = date.toTime_t();
READWRITE(this->nVersion);
READWRITE(id);
READWRITE(nDate);
READWRITE(recipient);
if (ser_action.ForRead())
date = QDateTime::fromTime_t(nDate);
}
};
class RecentRequestEntryLessThan
{
public:
RecentRequestEntryLessThan(int nColumn, Qt::SortOrder fOrder):
column(nColumn), order(fOrder) {}
bool operator()(RecentRequestEntry &left, RecentRequestEntry &right) const;
private:
int column;
Qt::SortOrder order;
};
/** Model for list of recently generated payment requests / aurumcoinhunter: URIs.
* Part of wallet model.
*/
class RecentRequestsTableModel: public QAbstractTableModel
{
Q_OBJECT
public:
explicit RecentRequestsTableModel(CWallet *wallet, WalletModel *parent);
~RecentRequestsTableModel();
enum ColumnIndex {
Date = 0,
Label = 1,
Message = 2,
Amount = 3,
NUMBER_OF_COLUMNS
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex &index) const;
/*@}*/
const RecentRequestEntry &entry(int row) const { return list[row]; }
void addNewRequest(const SendCoinsRecipient &recipient);
void addNewRequest(const std::string &recipient);
void addNewRequest(RecentRequestEntry &recipient);
public Q_SLOTS:
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void updateDisplayUnit();
private:
WalletModel *walletModel;
QStringList columns;
QList<RecentRequestEntry> list;
int64_t nReceiveRequestsMaxId;
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void updateAmountColumnTitle();
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString getAmountTitle();
};
#endif // BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
| [
"49352465+AurumCoinHunter@users.noreply.github.com"
] | 49352465+AurumCoinHunter@users.noreply.github.com |
571c0d0a007d1b45ab3d2b2a168f6eb08bd5fbd9 | 9c2f7cf6c792f8ba0b585770d978dac039f65cd6 | /src/Game/RankingManager.h | 1b3b16ca91f555b55ee53758c2a3247eadb15b02 | [] | no_license | jzxyst/volkoff_old | 84d9a1be163f2f50bb06dcf618e3df0fa4a6c43e | e28c0e1fb3ef49c252abe369d71cc33f0ce64cd3 | refs/heads/master | 2020-04-25T10:40:51.263683 | 2019-02-26T13:36:20 | 2019-02-26T13:36:20 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 8,318 | h | //=============================================================================
/*!
@addtogroup
@file RankingManager.h
@brief RankingManagerクラスヘッダ
ランキングサーバに接続し、スコアに関する処理を行うクラス
@attention -
@note -
@author Hi-ra Mizuno
@date 2011/11/22
@version 1.0.0
@par Copyright
Copyright (c) 2011 Hi-ra Mizuno. All Rights Reserved.
===============================================================================
@par History
- 2011/11/22 Hi-ra Mizuno
-# 作成
*/
//=============================================================================
//Include Guard
#ifndef __INCLUDE_RANKING_MANAGER_H__
#define __INCLUDE_RANKING_MANAGER_H__
/*! @par include */
#include <winsock2.h>
#include <list>
/*! @val global */
static const char scg_szScoreServerName[] = "www.aleibar.net";
static const char scg_szNameRefPoint[] = "Name=";
static const char scg_szScoreRefPoint[] = "Score=";
static const char scg_szTimeRefPoint[] = "Time=";
static const char scg_szStageRefPoint[] = "Stage=";
static const char scg_szDateRefPoint[] = "Date=";
static const char scg_szRankRefPoint[] = "Rank=";
static const char scg_szRankingFileName[] = "ranking.dat";
/*! @par struct */
typedef struct _TAG_SCORE_DATA
{
char szName[128];
unsigned int unScore;
unsigned int unTime;
int nStage;
char szDate[32];
int nRank;
}ScoreData;
/*! @class RankingManager
@brief RankingManagerクラス
ランキングサーバに接続し、スコアに関する処理を行うクラス
*/
class RankingManager
{
public:
/*! @par publicメンバ変数 */
private:
/*! @par privateメンバ変数 */
public:
/*! @par 例外処理 */
private:
/*! @par コンストラクタ・デストラクタ */
//---------------------------------------------------------------------------
/*!
@brief RankingManager::RankingManager
デフォルトコンストラクタ
@param[in] void
@return none
@exception none
*/
//---------------------------------------------------------------------------
RankingManager();
//---------------------------------------------------------------------------
/*!
@brief RankingManager::~RankingManager
デストラクタ
@param[in] void
@return none
@exception none
*/
//---------------------------------------------------------------------------
~RankingManager();
public:
/*! @par publicメンバ関数 */
//---------------------------------------------------------------------------
/*! @brief メンバゲッター */
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
/*! @brief メンバセッター */
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
/*!
@brief RankingManager::getInstance
インスタンスを取得する
@param[in] void
@return RankingManager* - インスタンスポインタ
@exception none
*/
//---------------------------------------------------------------------------
static RankingManager* getInstance() {static RankingManager CInstance; return &CInstance;};
//---------------------------------------------------------------------------
/*!
@brief RankingManager::Initialize
初期化処理
@param[in] void
@return bool
- true 成功
- false 失敗
@exception none
*/
//---------------------------------------------------------------------------
bool Initialize();
//---------------------------------------------------------------------------
/*!
@brief RankingManager::Release
終了処理
@param[in] void
@return bool
- true 成功
- false 失敗
@exception none
*/
//---------------------------------------------------------------------------
bool Release();
//---------------------------------------------------------------------------
/*!
@brief RankingManager::GetStoryRanking
ストーリーモードのランキングを取得する
@param[in] int nRankingNum_ - 取得数
@return std::list<ScoreData> - スコアデータリスト
@exception none
*/
//---------------------------------------------------------------------------
std::list<ScoreData> GetStoryRanking(int nRankingNum_);
//---------------------------------------------------------------------------
/*!
@brief RankingManager::GetSurvivalRanking
サバイバルモードのランキングを取得する
@param[in] int nRankingNum_ - 取得数
@return std::list<ScoreData> - スコアデータリスト
@exception none
*/
//---------------------------------------------------------------------------
std::list<ScoreData> GetSurvivalRanking(int nRankingNum_);
//---------------------------------------------------------------------------
/*!
@brief RankingManager::GetLocalStoryRanking
ストーリーモードのローカルランキングを取得する
@param[in] int nRankingNum_ - 取得数
@return std::list<ScoreData> - スコアデータリスト
@exception none
*/
//---------------------------------------------------------------------------
std::list<ScoreData> GetLocalStoryRanking(int nRankingNum_);
//---------------------------------------------------------------------------
/*!
@brief RankingManager::PostStoryScore
ストーリーモードのスコアデータを送信する
@param[in] char *pszName_ - 名前
@param[in] unsigned int unScore_ - スコア
@param[in] int nStage_ - ステージ数
@param[in] unsigned int unTime_ - クリア時間
@param[in] int nRank_ - 難易度
@return bool
- true 成功
- false 失敗
@exception none
*/
//---------------------------------------------------------------------------
bool PostStoryScore(char *pszName_,unsigned int unScore_,int nStage_,unsigned int unTime_,int nRank_);
//---------------------------------------------------------------------------
/*!
@brief RankingManager::PostSurvivalScore
サバイバルモードのスコアデータを送信する
@param[in] char *pszName_ - 名前
@param[in] unsigned int unScore_ - スコア
@param[in] int nStage_ - ステージ数
@param[in] unsigned int unTime_ - クリア時間
@param[in] int nRank_ - 難易度
@return bool
- true 成功
- false 失敗
@exception none
*/
//---------------------------------------------------------------------------
bool PostSurvivalScore(char *pszName_,unsigned int unScore_,int nStage_,unsigned int unTime_,int nRank_);
//---------------------------------------------------------------------------
/*!
@brief RankingManager::PostLocalStoryScore
ストーリーモードのスコアデータをローカルに書きこむ
@param[in] char *pszName_ - 名前
@param[in] unsigned int unScore_ - スコア
@param[in] int nStage_ - ステージ数
@param[in] unsigned int unTime_ - クリア時間
@param[in] int nRank_ - 難易度
@return bool
- true 成功
- false 失敗
@exception none
*/
//---------------------------------------------------------------------------
bool PostLocalStoryScore(char *pszName_,unsigned int unScore_,int nStage_,unsigned int unTime_,int nRank_);
};
bool ScoreDesc(const ScoreData &a_,const ScoreData &b_);
//End of Include Guard
#endif
//=============================================================================
// End of File
//============================================================================= | [
"jzxyst@gmail.com"
] | jzxyst@gmail.com |
56d2150d479f72f31f2313d4726c673902158ddc | 6717e0330ad978b8f823e78d6292b5d7de8bf468 | /src/WalletLegacy/WalletUserTransactionsCache.cpp | 49a3fde18e1c2edfc8c6b170cb03ee2bd102e858 | [] | no_license | doumdev/Hexagon | b59be393fef06aab93a2e97ebb8b382e68d7fc81 | 55c7fbf7e777b4250d26c34e820dcfb720c7b0e9 | refs/heads/master | 2021-09-04T10:16:11.935027 | 2018-01-17T21:48:22 | 2018-01-17T21:48:22 | 110,367,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,613 | cpp | // Copyright (c) 2012-2017, The CryptoNote developers, The Hexagon developers
//
// This file is part of Hexagon.
//
// Hexagon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Hexagon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Hexagon. If not, see <http://www.gnu.org/licenses/>.
#include "IWalletLegacy.h"
#include "Wallet/WalletErrors.h"
#include "WalletLegacy/WalletUserTransactionsCache.h"
#include "WalletLegacy/WalletLegacySerialization.h"
#include "WalletLegacy/WalletUtils.h"
#include "Serialization/ISerializer.h"
#include "Serialization/SerializationOverloads.h"
#include <algorithm>
using namespace Crypto;
namespace CryptoNote {
WalletUserTransactionsCache::WalletUserTransactionsCache(uint64_t mempoolTxLiveTime) : m_unconfirmedTransactions(mempoolTxLiveTime) {
}
bool WalletUserTransactionsCache::serialize(CryptoNote::ISerializer& s) {
if (s.type() == CryptoNote::ISerializer::INPUT) {
s(m_transactions, "transactions");
s(m_transfers, "transfers");
s(m_unconfirmedTransactions, "unconfirmed");
updateUnconfirmedTransactions();
deleteOutdatedTransactions();
} else {
UserTransactions txsToSave;
UserTransfers transfersToSave;
getGoodItems(txsToSave, transfersToSave);
s(txsToSave, "transactions");
s(transfersToSave, "transfers");
s(m_unconfirmedTransactions, "unconfirmed");
}
return true;
}
uint64_t WalletUserTransactionsCache::unconfirmedTransactionsAmount() const {
return m_unconfirmedTransactions.countUnconfirmedTransactionsAmount();
}
uint64_t WalletUserTransactionsCache::unconfrimedOutsAmount() const {
return m_unconfirmedTransactions.countUnconfirmedOutsAmount();
}
size_t WalletUserTransactionsCache::getTransactionCount() const {
return m_transactions.size();
}
size_t WalletUserTransactionsCache::getTransferCount() const {
return m_transfers.size();
}
TransactionId WalletUserTransactionsCache::addNewTransaction(
uint64_t amount, uint64_t fee, const std::string& extra, const std::vector<WalletLegacyTransfer>& transfers, uint64_t unlockTime) {
WalletLegacyTransaction transaction;
transaction.firstTransferId = insertTransfers(transfers);
transaction.transferCount = transfers.size();
transaction.totalAmount = -static_cast<int64_t>(amount);
transaction.fee = fee;
transaction.sentTime = time(nullptr);
transaction.isCoinbase = false;
transaction.timestamp = 0;
transaction.extra = extra;
transaction.blockHeight = WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT;
transaction.state = WalletLegacyTransactionState::Sending;
transaction.unlockTime = unlockTime;
return insertTransaction(std::move(transaction));
}
void WalletUserTransactionsCache::updateTransaction(
TransactionId transactionId, const CryptoNote::Transaction& tx, uint64_t amount, const std::list<TransactionOutputInformation>& usedOutputs) {
// update extra field from created transaction
auto& txInfo = m_transactions.at(transactionId);
txInfo.extra.assign(tx.extra.begin(), tx.extra.end());
m_unconfirmedTransactions.add(tx, transactionId, amount, usedOutputs);
}
void WalletUserTransactionsCache::updateTransactionSendingState(TransactionId transactionId, std::error_code ec) {
auto& txInfo = m_transactions.at(transactionId);
if (ec) {
txInfo.state = ec.value() == error::TX_CANCELLED ? WalletLegacyTransactionState::Cancelled : WalletLegacyTransactionState::Failed;
m_unconfirmedTransactions.erase(txInfo.hash);
} else {
txInfo.sentTime = time(nullptr); // update sending time
txInfo.state = WalletLegacyTransactionState::Active;
}
}
std::shared_ptr<WalletLegacyEvent> WalletUserTransactionsCache::onTransactionUpdated(const TransactionInformation& txInfo, int64_t txBalance) {
std::shared_ptr<WalletLegacyEvent> event;
TransactionId id = CryptoNote::WALLET_LEGACY_INVALID_TRANSACTION_ID;
if (!m_unconfirmedTransactions.findTransactionId(txInfo.transactionHash, id)) {
id = findTransactionByHash(txInfo.transactionHash);
} else {
m_unconfirmedTransactions.erase(txInfo.transactionHash);
}
bool isCoinbase = txInfo.totalAmountIn == 0;
if (id == CryptoNote::WALLET_LEGACY_INVALID_TRANSACTION_ID) {
WalletLegacyTransaction transaction;
transaction.firstTransferId = WALLET_LEGACY_INVALID_TRANSFER_ID;
transaction.transferCount = 0;
transaction.totalAmount = txBalance;
transaction.fee = isCoinbase ? 0 : txInfo.totalAmountIn - txInfo.totalAmountOut;
transaction.sentTime = 0;
transaction.hash = txInfo.transactionHash;
transaction.blockHeight = txInfo.blockHeight;
transaction.isCoinbase = isCoinbase;
transaction.timestamp = txInfo.timestamp;
transaction.extra.assign(txInfo.extra.begin(), txInfo.extra.end());
transaction.state = WalletLegacyTransactionState::Active;
transaction.unlockTime = txInfo.unlockTime;
id = insertTransaction(std::move(transaction));
// notification event
event = std::make_shared<WalletExternalTransactionCreatedEvent>(id);
} else {
WalletLegacyTransaction& tr = getTransaction(id);
tr.blockHeight = txInfo.blockHeight;
tr.timestamp = txInfo.timestamp;
tr.state = WalletLegacyTransactionState::Active;
// notification event
event = std::make_shared<WalletTransactionUpdatedEvent>(id);
}
return event;
}
std::shared_ptr<WalletLegacyEvent> WalletUserTransactionsCache::onTransactionDeleted(const Hash& transactionHash) {
TransactionId id = CryptoNote::WALLET_LEGACY_INVALID_TRANSACTION_ID;
if (m_unconfirmedTransactions.findTransactionId(transactionHash, id)) {
m_unconfirmedTransactions.erase(transactionHash);
// LOG_ERROR("Unconfirmed transaction is deleted: id = " << id << ", hash = " << transactionHash);
assert(false);
} else {
id = findTransactionByHash(transactionHash);
}
std::shared_ptr<WalletLegacyEvent> event;
if (id != CryptoNote::WALLET_LEGACY_INVALID_TRANSACTION_ID) {
WalletLegacyTransaction& tr = getTransaction(id);
tr.blockHeight = WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT;
tr.timestamp = 0;
tr.state = WalletLegacyTransactionState::Deleted;
event = std::make_shared<WalletTransactionUpdatedEvent>(id);
} else {
// LOG_ERROR("Transaction wasn't found: " << transactionHash);
assert(false);
}
return event;
}
TransactionId WalletUserTransactionsCache::findTransactionByTransferId(TransferId transferId) const
{
TransactionId id;
for (id = 0; id < m_transactions.size(); ++id) {
const WalletLegacyTransaction& tx = m_transactions[id];
if (tx.firstTransferId == WALLET_LEGACY_INVALID_TRANSFER_ID || tx.transferCount == 0)
continue;
if (transferId >= tx.firstTransferId && transferId < (tx.firstTransferId + tx.transferCount))
break;
}
if (id == m_transactions.size())
return WALLET_LEGACY_INVALID_TRANSACTION_ID;
return id;
}
bool WalletUserTransactionsCache::getTransaction(TransactionId transactionId, WalletLegacyTransaction& transaction) const
{
if (transactionId >= m_transactions.size())
return false;
transaction = m_transactions[transactionId];
return true;
}
bool WalletUserTransactionsCache::getTransfer(TransferId transferId, WalletLegacyTransfer& transfer) const
{
if (transferId >= m_transfers.size())
return false;
transfer = m_transfers[transferId];
return true;
}
TransactionId WalletUserTransactionsCache::insertTransaction(WalletLegacyTransaction&& Transaction) {
m_transactions.emplace_back(std::move(Transaction));
return m_transactions.size() - 1;
}
TransactionId WalletUserTransactionsCache::findTransactionByHash(const Hash& hash) {
auto it = std::find_if(m_transactions.begin(), m_transactions.end(), [&hash](const WalletLegacyTransaction& tx) { return tx.hash == hash; });
if (it == m_transactions.end())
return CryptoNote::WALLET_LEGACY_INVALID_TRANSACTION_ID;
return std::distance(m_transactions.begin(), it);
}
bool WalletUserTransactionsCache::isUsed(const TransactionOutputInformation& out) const {
return m_unconfirmedTransactions.isUsed(out);
}
WalletLegacyTransaction& WalletUserTransactionsCache::getTransaction(TransactionId transactionId) {
return m_transactions.at(transactionId);
}
void WalletUserTransactionsCache::getGoodItems(UserTransactions& transactions, UserTransfers& transfers) {
size_t offset = 0;
for (size_t txId = 0; txId < m_transactions.size(); ++txId) {
bool isGood =
m_transactions[txId].state != WalletLegacyTransactionState::Cancelled &&
m_transactions[txId].state != WalletLegacyTransactionState::Failed;
if (isGood) {
getGoodTransaction(txId, offset, transactions, transfers);
} else {
const WalletLegacyTransaction& t = m_transactions[txId];
offset += t.firstTransferId != WALLET_LEGACY_INVALID_TRANSFER_ID ? t.transferCount : 0;
}
}
}
void WalletUserTransactionsCache::getGoodTransaction(TransactionId txId, size_t offset, UserTransactions& transactions, UserTransfers& transfers) {
transactions.push_back(m_transactions[txId]);
WalletLegacyTransaction& tx = transactions.back();
if (tx.firstTransferId == WALLET_LEGACY_INVALID_TRANSFER_ID) {
return;
}
if (m_transfers.size() > 0) {
auto testVal = m_transfers.begin();
UserTransfers::const_iterator first = m_transfers.begin() + tx.firstTransferId;
UserTransfers::const_iterator last = first + tx.transferCount;
tx.firstTransferId -= offset;
std::copy(first, last, std::back_inserter(transfers));
}
}
void WalletUserTransactionsCache::getTransfersByTx(TransactionId id, UserTransfers& transfers) {
const WalletLegacyTransaction& tx = m_transactions[id];
if (tx.firstTransferId != WALLET_LEGACY_INVALID_TRANSFER_ID) {
UserTransfers::const_iterator first = m_transfers.begin() + tx.firstTransferId;
UserTransfers::const_iterator last = first + tx.transferCount;
std::copy(first, last, std::back_inserter(transfers));
}
}
TransferId WalletUserTransactionsCache::insertTransfers(const std::vector<WalletLegacyTransfer>& transfers) {
std::copy(transfers.begin(), transfers.end(), std::back_inserter(m_transfers));
return m_transfers.size() - transfers.size();
}
void WalletUserTransactionsCache::updateUnconfirmedTransactions() {
for (TransactionId id = 0; id < m_transactions.size(); ++id) {
if (m_transactions[id].blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
m_unconfirmedTransactions.updateTransactionId(m_transactions[id].hash, id);
}
}
}
WalletLegacyTransfer& WalletUserTransactionsCache::getTransfer(TransferId transferId) {
return m_transfers.at(transferId);
}
void WalletUserTransactionsCache::reset() {
m_transactions.clear();
m_transfers.clear();
m_unconfirmedTransactions.reset();
}
std::vector<TransactionId> WalletUserTransactionsCache::deleteOutdatedTransactions() {
auto deletedTransactions = m_unconfirmedTransactions.deleteOutdatedTransactions();
for (auto id: deletedTransactions) {
assert(id < m_transactions.size());
m_transactions[id].state = WalletLegacyTransactionState::Deleted;
}
return deletedTransactions;
}
} //namespace CryptoNote
| [
"doum@tuta.io"
] | doum@tuta.io |
d26b13a40ef4409901e3b0d66591e4001d998687 | a52812d03bf88226c5d6bdd87de6e615f47d009c | /lib/src/MBShared.h | 3647869f8ea01c6c7e5a81263776b2a0815d902f | [] | no_license | mbebenita/rustdbg | 3542ad85de1e8b7163ab273e77266fc82e195b25 | 2da16c70fa29564971478eb0b5619b61a61803a3 | refs/heads/master | 2020-04-12T03:36:00.315950 | 2010-10-16T23:03:39 | 2010-10-16T23:03:39 | 902,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,551 | h | #ifndef MBSHARED_H
#define MBSHARED_H
#include "stdio.h"
#include "pthread.h"
template<typename ReturnType, typename Parameter>
class MBCallback {
public:
virtual ReturnType execute(Parameter parameter) = 0;
};
template<class Class, typename ReturnType, typename Parameter>
class MBFunction : public MBCallback<ReturnType, Parameter> {
public:
typedef ReturnType (Class::*Method)(Parameter);
MBFunction(Class *instance, Method method) {
this->instance = instance;
this->method = method;
}
ReturnType execute(Parameter parameter) {
return (instance->*method)(parameter);
}
private:
Class* instance;
Method method;
};
template<typename T> class MBPredicate {
public:
virtual bool operator() (T value) const = 0;
};
class MBShared {
public:
MBShared();
virtual ~MBShared();
};
/**
* Thread utility class. Derive and implement your own run() method.
*/
class MBThread {
private:
volatile bool _is_running;
public:
pthread_t thread;
MBThread();
void start();
virtual void run() {
return;
}
void join();
bool isRunning();
};
template<typename T> class MBList;
class MBString {
public:
static char *trimLeft(char *str);
static char *trimRight(char *str);
static char *clone(const char *str);
static MBList<char *> *split(char *str, const char *delimiters);
static bool startsWith(const char *str, const char *with);
static char *scanReverse(const char *str, char *ptr, const char chr);
};
#endif /* MBSHARED_H */
| [
"mbebenita@mozilla.com"
] | mbebenita@mozilla.com |
5e10533cb0504111411a689c1c02f0a1545addf8 | 128968ab7131976aae9057ce1c5bf73d4a153057 | /Management/Management/Investitie.h | e636d874d9b128b8c0161da57e43dd3f1766d6d0 | [] | no_license | vladirares/Management | b0c17601f892ec78430205454edf43a12907941b | affb467799b4b5b5548182ca8b8930a7ad410284 | refs/heads/master | 2022-08-21T15:04:32.212941 | 2020-05-23T07:38:43 | 2020-05-23T07:38:43 | 264,679,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | h | #pragma once
#include "Cheltuieli.h"
#include<iostream>
#include<string>
using namespace std;
const int imprumut = 0;
const int fonduri = 1;
class Investitie final : public Cheltuieli
{
unsigned perioadaAmortizare;
string descriere;
bool sursaBani;
public:
Investitie() = delete;
Investitie(double);
Investitie(double, Data);
void setPerioadaAmortizare(unsigned);
unsigned getPerioadaAmortizare() const;
void setDescriere(string);
string getDescriere()const ;
void setSursaBani(bool) ;
bool getSursaBani() const;
string getExtra() const;
};
| [
"jeleavladimir@yahoo.ro"
] | jeleavladimir@yahoo.ro |
27c16db0cd7fcdb0e1ecd21a52a835f4d224cb50 | cc89829e63f89d225272af943054d22a6b37ed9d | /deps/common/metrics/reservoir.cpp | 6dd1995460db8343d62094ede8a3d025a05f2f9b | [] | no_license | ZZZping/minidb | 5dd5e79b2a7258e01ba2802813548e4d6def2ce8 | b9e59749f97ebbf3b14caae4b254d43d16edbdc4 | refs/heads/main | 2023-04-21T11:34:55.339151 | 2021-05-05T15:34:08 | 2021-05-05T15:34:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | cpp | // __CR__
// Copyright (c) 2021 LongdaFeng All Rights Reserved
//
// This software contains the intellectual property of LongdaFeng
// or is licensed to LongdaFeng from third parties. Use of this
// software and the intellectual property contained therein is
// expressly limited to the terms and conditions of the License Agreement
// under which it is provided by or on behalf of LongdaFeng.
// __CR__
//
// Created by Longda on 2021/4/20.
//
#include "reservoir.h"
using namespace common;
Reservoir::Reservoir(RandomGenerator& random) :
random(random)
{
}
Reservoir::~Reservoir()
{
}
int Reservoir::next(int range)
{
return random.next(range);
}
| [
"hustjackie@outlook.com"
] | hustjackie@outlook.com |
7aa37c805988b478fe73c8a9a13bac0851d6f289 | 34090b851ee2d1f12dbe13f30d199bb328fb11f6 | /src/script/script.cpp | 64fb08c9cf772f271f0ab49cc1a7237810224ac2 | [
"MIT"
] | permissive | Creddit-lol/Creddit-Core | 7e4962d1e1dfb63c56236485938f7d4bf148e54f | 2514c8867fd2bdc34ae4c5466b9a31816dcc0b6c | refs/heads/master | 2023-05-12T18:45:39.377629 | 2021-06-07T23:54:09 | 2021-06-07T23:54:09 | 370,868,857 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,601 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2020 The CREDD developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include <atomic>
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expansion
case OP_NOP1 : return "OP_NOP1"; // OP_NOP1
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY"; // OP_NOP2
case OP_NOP3 : return "OP_NOP3"; // OP_NOP3
case OP_NOP4 : return "OP_NOP4"; // OP_NOP4
case OP_NOP5 : return "OP_NOP5"; // OP_NOP5
case OP_NOP6 : return "OP_NOP6"; // OP_NOP6
case OP_NOP7 : return "OP_NOP7"; // OP_NOP7
case OP_NOP8 : return "OP_NOP8"; // OP_NOP8
case OP_NOP9 : return "OP_NOP9"; // OP_NOP9
case OP_NOP10 : return "OP_NOP10"; // OP_NOP10
// zerocoin
case OP_ZEROCOINMINT : return "OP_ZEROCOINMINT";
case OP_ZEROCOINSPEND : return "OP_ZEROCOINSPEND";
case OP_ZEROCOINPUBLICSPEND : return "OP_ZEROCOINPUBLICSPEND";
// cold staking
case OP_CHECKCOLDSTAKEVERIFY_LOF : return "OP_CHECKCOLDSTAKEVERIFY_LOF";
case OP_CHECKCOLDSTAKEVERIFY : return "OP_CHECKCOLDSTAKEVERIFY";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
std::vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsPayToPublicKeyHash() const
{
// Extra-fast test for pay-to-pubkey-hash CScripts:
return (this->size() == 25 &&
(*this)[0] == OP_DUP &&
(*this)[1] == OP_HASH160 &&
(*this)[2] == 0x14 &&
(*this)[23] == OP_EQUALVERIFY &&
(*this)[24] == OP_CHECKSIG);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
// contextual flag to guard the new rules for P2CS.
// can be removed once v6 enforcement is activated.
std::atomic<bool> g_IsV6Active{false};
// P2CS script: either with or without last output free
bool CScript::IsPayToColdStaking() const
{
return (this->size() == 51 &&
(!g_IsV6Active || (*this)[0] == OP_DUP) &&
(!g_IsV6Active || (*this)[1] == OP_HASH160) &&
(*this)[2] == OP_ROT &&
(!g_IsV6Active || (*this)[3] == OP_IF) &&
((*this)[4] == OP_CHECKCOLDSTAKEVERIFY || (*this)[4] == OP_CHECKCOLDSTAKEVERIFY_LOF) &&
(*this)[5] == 0x14 &&
(!g_IsV6Active || (*this)[26] == OP_ELSE) &&
(*this)[27] == 0x14 &&
(!g_IsV6Active || (*this)[48] == OP_ENDIF) &&
(*this)[49] == OP_EQUALVERIFY &&
(*this)[50] == OP_CHECKSIG);
}
bool CScript::IsPayToColdStakingLOF() const
{
return IsPayToColdStaking() && (*this)[4] == OP_CHECKCOLDSTAKEVERIFY_LOF;
}
bool CScript::StartsWithOpcode(const opcodetype opcode) const
{
return (!this->empty() && (*this)[0] == opcode);
}
bool CScript::IsZerocoinMint() const
{
return StartsWithOpcode(OP_ZEROCOINMINT);
}
bool CScript::IsZerocoinSpend() const
{
return StartsWithOpcode(OP_ZEROCOINSPEND);
}
bool CScript::IsZerocoinPublicSpend() const
{
return StartsWithOpcode(OP_ZEROCOINPUBLICSPEND);
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
size_t CScript::DynamicMemoryUsage() const
{
return memusage::DynamicUsage(*static_cast<const CScriptBase*>(this));
}
| [
"bobski.robertson122@gmail.com"
] | bobski.robertson122@gmail.com |
a38e2e6ea7b05de3620df4ac4e2725bf1ea11577 | 23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f | /AtlInternals2e/Chapter 08/PrimeSvr/PrimeSvr.cpp | 0c6d743005e1b1d751f12c21b44c28b25d825682 | [] | no_license | IgorYunusov/Mega-collection-cpp-1 | c7c09e3c76395bcbf95a304db6462a315db921ba | 42d07f16a379a8093b6ddc15675bf777eb10d480 | refs/heads/master | 2020-03-24T10:20:15.783034 | 2018-06-12T13:19:05 | 2018-06-12T13:19:05 | 142,653,486 | 3 | 1 | null | 2018-07-28T06:36:35 | 2018-07-28T06:36:35 | null | UTF-8 | C++ | false | false | 363 | cpp | // PrimeSvr.cpp : Implementation of WinMain
#include "stdafx.h"
#include "resource.h"
// The module attribute causes WinMain to be automatically implemented for you
[ module(EXE, uuid = "{CAE2D17F-5557-47D6-A7DC-C919C4F87EC8}",
name = "PrimeSvr",
helpstring = "PrimeSvr 1.0 Type Library",
resource_name = "IDR_PRIMESVR") ];
| [
"wyrover@gmail.com"
] | wyrover@gmail.com |
cbd8a65811a15bb476964a81abd3225b46a72924 | 4eb1561d1c47bfce5bbdfd10f979c3d386f15e33 | /hipacc_kernels/point/copy_f_f.hpp | de767cac1b819b9a0d270fcc51b4476a9a322247 | [
"MIT"
] | permissive | HipaccVX/HipaccVX | aa33cbc5b95457cb0cdd479ac02c8b43f75272c9 | 0d469748df11c95f916b5a70f0006878f8550e3c | refs/heads/master | 2023-03-27T08:55:50.315291 | 2021-03-31T09:18:32 | 2021-03-31T09:18:32 | 353,156,373 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | hpp | class Copy_f_f : public Kernel<float> {
private:
Accessor<float> &input;
public:
Copy_f_f(IterationSpace<float> &iter, Accessor<float> &input)
: Kernel(iter), input(input){
add_accessor(&input);
}
void kernel() {
output() = input();
}
};
| [
"bur0k-git@bur0k.de"
] | bur0k-git@bur0k.de |
af6a5cb7de1c128d12ef2066c38c78f315591079 | 2740b47bbd8b70c69a9104591ce8284fe18b1d04 | /chap22/gaspump/main.cpp | ba8dacee10cd3d004aaaca0c0435fa42d2a4b350 | [
"MIT"
] | permissive | mutse/qt5-book-code | d427ce5d943bd4cbda08daacb1cf4d120eb75b31 | ffc8517e28f11864e049f1dc93d098365347387a | refs/heads/master | 2022-08-27T09:56:44.261403 | 2022-07-23T15:06:00 | 2022-07-23T15:06:00 | 8,292,311 | 492 | 211 | null | 2020-02-29T01:12:33 | 2013-02-19T14:57:57 | C++ | UTF-8 | C++ | false | false | 613 | cpp | #include <QApplication>
#include <iostream>
#include "pumpwindow.h"
#include "scripting.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = QApplication::arguments();
if (args.count() >= 3 && args[1] == "-script") {
runScript(args[2], args.mid(3));
return 0;
} else if (args.count() == 1) {
PumpWindow window;
window.show();
window.resize(600, 400);
return app.exec();
} else {
std::cerr << "Usage: gaspump [-script myscript.js <arguments>]"
<< std::endl;
return 1;
}
}
| [
"yyhoo2.young@gmail.com"
] | yyhoo2.young@gmail.com |
7128689aedc9d5b65595eee8f222f0bbdc92d81a | fa182790bbbcdcfab8e52ab5faa789b61ed4f1d6 | /server/DB.cpp | 51e6b1a777d48bbcb0466eb4539d86957359d169 | [
"MIT"
] | permissive | christoph-karpowicz/Tetris | 6a7391d239a14ae9036df8340d857a9b97575ae7 | b23f9d91c07fbd61350a1fe651fac09435cad723 | refs/heads/master | 2020-04-29T09:12:14.414800 | 2019-11-25T19:24:09 | 2019-11-25T19:24:09 | 176,015,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cpp | #include <stdio.h>
#include <sqlite3.h>
#include <iostream>
#include <string>
#include "DB.h"
#include "Callback.h"
using namespace Database;
using namespace Callback;
using namespace std;
DB::DB() {
zErrMsg = 0;
db_name = "server/tetris.db";
}
bool DB::init() {
/* Open database */
conn = sqlite3_open(db_name, &db);
if( conn ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return false;
} else {
fprintf(stderr, "Opened database successfully\n");
return true;
}
}
string DB::insert(string const n, string const s, string const a) {
/* Create SQL statement */
sql = "INSERT INTO leaderboard (name, score, added) " \
"VALUES('" + n + "', '" + s + "', '" + a + "'); ";
/* Execute SQL statement */
conn = sqlite3_exec(db, sql.c_str(), insertion, 0, &zErrMsg);
if( conn != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
return "SQL error.";
} else {
fprintf(stdout, "Records created successfully\n");
return "Records created successfully\n";
}
};
void DB::select(vector<LeaderboardRecord> &res) {
/* Create SQL statement */
sql = "SELECT * from leaderboard";
/* Execute SQL statement */
conn = sqlite3_exec(db, sql.c_str(), selection, &res, &zErrMsg);
if( conn != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
}
DB::~DB() {
sqlite3_close(db);
} | [
"christoph.karpowicz@gmail.com"
] | christoph.karpowicz@gmail.com |
84f4aecb21a193298238afe6be947ea7adabcf4e | 0ef4bf79aeeb86c3cf82e7b7c4a86cbea0248788 | /include/granada/http/session/redis_session.h | 39051966759922499e6e50d97b769b85ea12d869 | [
"MIT"
] | permissive | mpomaran/cleric | 281eb20da9f70ae02e7c622d53439885297b7fee | 8f486491f5dca8d436ce366260faa1a9545a3177 | refs/heads/master | 2023-04-17T21:32:41.026223 | 2021-05-08T17:13:00 | 2021-05-08T17:13:00 | 119,304,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,535 | h | /**
* Copyright (c) <2016> granada <afernandez@cookinapps.io>
*
* This source code is licensed under the MIT license.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Session that allows to store and retrieve string values.
* Uses cache/redis_cache_driver.h
*
*/
#pragma once
#include "granada/cache/redis_cache_driver.h"
#include "granada/util/mutex.h"
#include "session.h"
namespace granada {
namespace http {
namespace session {
class RedisSessionHandler;
class RedisSession : public Session {
public:
/**
* Constructor
*/
RedisSession();
/**
* Constructor.
* Loads session.
* Retrieves the token of the session from the HTTP request
* and loads a session using the session handler.
* If session does not exist or token is not found
* a new session is created.
* This constructor is recommended for sessions that store token in cookie
*
* @param request Http request.
* @param response Http response.
*/
RedisSession(const web::http::http_request& request,
web::http::http_response& response);
/**
* Constructor.
* Loads session.
* Retrieves the token of the session from the HTTP request
* and loads a session using the session handler.
* If session does not exist or token is not found
* a new session is created.
* This constructor is recommended for sessions that use get and post values.
*
* @param request Http request.
*/
RedisSession(const web::http::http_request& request);
/**
* Constructor.
* Loads a session with the given token using the session handler.
* Use this loader if you have the token and you are not using cookies.
*
* @param token Session token.
*/
RedisSession(const std::string& token);
/**
* Destructor
*/
virtual ~RedisSession(){};
/**
* Returns a pointer to the roles of a session.
* @return Pointer to the roles of the session.
*/
virtual granada::http::session::SessionRoles* roles() override {
return roles_.get();
};
/**
* Returns the pointer of Session Handler that manages the session.
* @return Session Handler.
*/
virtual granada::http::session::SessionHandler* session_handler() override {
return session_handler_.get();
};
/**
* Returns a pointer to the collection of functions
* that are called when closing the session.
*
* @return Pointer to the collection of functions that are
* called when session is closed.
*/
virtual granada::Functions* close_callbacks() override {
return RedisSession::close_callbacks_.get();
};
private:
static granada::util::mutex::call_once init_statics_once_;
/**
* Used for loading the properties only once.
*/
static granada::util::mutex::call_once load_properties_call_once_;
/**
* Manager of the roles of the session and its properties
*/
static std::unique_ptr<granada::Functions> close_callbacks_;
/**
* Hanlder of the sessions lifetime, and where all the application sessions
* are stored.
*/
static std::unique_ptr<granada::http::session::SessionHandler>
session_handler_;
/**
* Manager of the roles of the session and its properties
*/
std::unique_ptr<granada::http::session::SessionRoles> roles_;
};
class RedisSessionRoles : public SessionRoles {
public:
/**
* Constructor
*/
RedisSessionRoles(granada::http::session::Session* session) {
session_ = session;
};
};
class RedisSessionHandler : public SessionHandler {
private:
void initializeStatics();
public:
/**
* Constructor
* Initialize the session properties and the
* session cleaner once per all the RedisSessions.
*/
RedisSessionHandler() {
RedisSessionHandler::load_properties_call_once_.call(
[this]() { this->LoadProperties(); });
initializeStatics();
// thread for cleaning the sessions.
RedisSessionHandler::clean_sessions_call_once_.call([this]() {
if (clean_sessions_frequency() > -1) {
RedisSessionHandler::clean_sessions_timer_.set(
[this] { CleanSessions(); }, clean_sessions_frequency());
}
});
};
/**
* Returns a pointer to the cache used to store the sessions' values.
* @return Pointer to the cache used to store the sessions' values.
*/
virtual granada::cache::CacheHandler* cache() override {
return RedisSessionHandler::cache_.get();
}
protected:
/**
* Returns a pointer to a nonce string generator,
* for generating unique strings tokens.
* @return Pointer to a nonce string generator,
* for generating unique strings tokens.
*/
virtual granada::crypto::NonceGenerator* nonce_generator() override {
return RedisSessionHandler::nonce_generator_.get();
}
/**
* Returns a Checkpoint Session pointer used to test sessions
* status without knowing their type.
* @return Checkpoint Session pointer used to test sessions
* status without knowing their type.
*/
virtual granada::http::session::SessionFactory* factory() override {
return RedisSessionHandler::factory_.get();
}
private:
static granada::util::mutex::call_once initialize_statics_once_;
/**
* Used for loading the properties only once.
*/
static granada::util::mutex::call_once load_properties_call_once_;
/**
* Used for calling clean sessions function only once.
*/
static granada::util::mutex::call_once clean_sessions_call_once_;
/**
* Timer for calling CleanSessions function each n seconds.
*/
static granada::util::time::timer clean_sessions_timer_;
/**
* Map where all sessions are stored.
*/
static std::unique_ptr<granada::cache::CacheHandler> cache_;
/**
* Nonce string generator, for generating unique strings tokens.
* Generate a nonce string containing random alphanumeric characters
* (A-Za-z0-9).
*/
static std::unique_ptr<granada::crypto::NonceGenerator> nonce_generator_;
/**
* Session pointer used to test sessions status without knowing
* their type.
*/
static std::unique_ptr<granada::http::session::SessionFactory> factory_;
};
class RedisSessionFactory : public SessionFactory {
public:
virtual std::unique_ptr<granada::http::session::Session> Session_unique_ptr()
override {
return granada::util::memory::make_unique<
granada::http::session::RedisSession>();
};
virtual std::unique_ptr<granada::http::session::Session> Session_unique_ptr(
const web::http::http_request& request,
web::http::http_response& response) override {
return granada::util::memory::make_unique<
granada::http::session::RedisSession>(request, response);
};
virtual std::unique_ptr<granada::http::session::Session> Session_unique_ptr(
const web::http::http_request& request) override {
return granada::util::memory::make_unique<
granada::http::session::RedisSession>(request);
};
virtual std::unique_ptr<granada::http::session::Session> Session_unique_ptr(
const std::string& token) override {
return granada::util::memory::make_unique<
granada::http::session::RedisSession>(token);
};
};
} // namespace session
} // namespace http
} // namespace granada
| [
"mpp.dev.studio@gmail.com"
] | mpp.dev.studio@gmail.com |
33164fd527d68cc0fb5838c3b40c39ffbb191f9a | e68872ddcd5e57c7082be80f5249ca51af4901f3 | /Poisson/defs.h | 3d4f700c1aed0834e27d3f8ec3c60e30343ced59 | [] | no_license | resultant-gamedev/krita-imagecomplete | 96658bc924ea255c676adb1b2c5ffa9295e4842d | 540a28ec49c6c661a76fb021334aa951fbb9f037 | refs/heads/master | 2021-01-20T00:23:33.036189 | 2010-01-25T10:43:59 | 2010-01-25T10:43:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | /*
* This file is part of the KDE project
*
* Copyright (c) 2007 Benjamin Schleimer <bensch128@yahoo.com>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#pragma once
namespace Poisson {
enum ColorEnum {
MIN_COLOR = 0,
kRed = MIN_COLOR,
kGreen,
kBlue,
MAX_COLOR = kBlue,
NUM_COLORS
};
enum SelectEnum {
kNotSelected = 0,
kSelected = 1,
};
};
| [
"bensch128@yahoo.com"
] | bensch128@yahoo.com |
d10565904478939566fb2e478b2012180cbff5a0 | b75f0c6e8e2c4caf895eb094eb48ae6913c3d2a1 | /analysis/machine_learning/include/data.hh | a057dd8b0ecb44b02205cdea475edfca87e02974 | [
"Unlicense"
] | permissive | ssrg-vt/aira | 0a76f84588b3dcf512256a79c60e2cecae51afa4 | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | refs/heads/master | 2021-05-12T17:15:34.098162 | 2018-01-11T02:51:11 | 2018-01-11T02:51:11 | 117,041,015 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,041 | hh | #ifndef _DATA_HH
#define _DATA_HH
#include "mat.hh"
#include "transform.hh"
#include <vector>
#include <string>
class DataManager {
private:
Mat32F _features;
Mat32F _labels;
TransformManager _transform;
std::vector<std::string> _label_names;
bool _higher;
bool _quiet;
public:
DataManager(Mat32F &f, Mat32F &l);
// Add more data (implementation in data.cc).
void append(const DataManager &other);
// Statistics about the data (implementations in data.cc).
int num_data() const;
int num_features() const;
int num_labels() const;
bool speedups() const { return _higher; }
void quiet(bool val) { _quiet = val; }
void describe(std::ostream &s, const std::string &msg) const;
void describe(std::ostream &s, const std::string &msg, int val) const;
// Data accessors (implementations in data.cc).
const Mat32F& features() const;
const Mat32F& labels() const;
Col32D classifications() const;
// TODO: The below four functions aren't really const. Fix it!
Row32F datapoint_features(int row) const;
Row32F datapoint_labels(int row) const;
Col32F feature(int feature) const;
Col32F label(int label) const;
const TransformManager& transform() const;
TransformManager& transform();
// Name accessors (implementations in data.cc).
const std::string& label_name(int label) const;
void set_label_name(int label, const std::string &name);
// Conversion functions (implementations in convert.cc).
void scale_labels();
void convert_labels_to_speedups();
void convert_labels_to_probabilities();
void apply_sequence(const TransformManager tm);
void apply_empty_cut();
void apply_scale_means();
void apply_scale_ranges();
void apply_pca(int dimension);
void apply_feature_cut(std::set<int>& to_cut);
void apply_label_cut(std::set<int>& to_cut);
};
DataManager load_data(const std::string &file, int num_labels);
DataManager load_data(const std::vector<std::string> &files, int num_labels);
std::ostream& operator<< (std::ostream &s, DataManager &dm);
#endif // _DATA_HH
| [
"rlyerly@vt.edu"
] | rlyerly@vt.edu |
4cad90458f069174aca863611ffdb85f4da52a35 | 892e90cacac15a00aadc48853c959b5c76e59c8b | /NexEngine/Src/Nex/LayerStack.cpp | d9cfbc82cbe70c1f06957f7b2da5324b5d8d0d64 | [
"Apache-2.0"
] | permissive | dhruvin-084/NexEngine | 47c2b10b172f488600a52abf905be806396d0032 | 61ef79232b7d98dd7ca83d7a17e93a8c9f5b4f96 | refs/heads/master | 2022-12-04T03:16:04.455709 | 2020-08-21T12:44:37 | 2020-08-21T12:44:37 | 285,875,733 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | #include"nexpch.h"
#include"LayerStack.h"
namespace Nex {
LayerStack::LayerStack() {
m_LayerInsert = m_Layers.begin();
}
LayerStack::~LayerStack() {
for (Layer* layer : m_Layers)
delete layer;
}
void LayerStack::PushLayer(Layer* layer) {
m_LayerInsert = m_Layers.emplace(m_LayerInsert, layer);
layer->OnAttach();
}
void LayerStack::PushOverlay(Layer* overlay) {
m_Layers.emplace_back(overlay);
overlay->OnAttach();
}
void LayerStack::PopLayer(Layer* layer) {
auto it = std::find(m_Layers.begin(), m_Layers.end(), layer);
if (it != m_Layers.end()) {
m_Layers.erase(it);
m_LayerInsert--;
layer->OnDetach();
}
}
void LayerStack::PopOverlay(Layer* overlay) {
auto it = std::find(m_Layers.begin(), m_Layers.end(), overlay);
if (it != m_Layers.end()) {
m_Layers.erase(it);
overlay->OnDetach();
}
}
} | [
"dhruvin084@gmail.com"
] | dhruvin084@gmail.com |
ae50eee2b9229fa49ec4a72dab440280b1e0e1a3 | e9fa760e3b253cab2312a5798d8a694af2f127b5 | /aoRefPtrHandle.h | 8612092716f4d4dc453bd7f4c02d59fd114fa6e6 | [] | no_license | kdjstudios/AO_Core_Library | 399287418f320b49448673b632110dfd76d304f8 | 583f38174a5b4592c717d143365b14e08a6431ed | refs/heads/master | 2023-02-03T21:30:36.174040 | 2020-12-26T03:02:57 | 2020-12-26T03:02:57 | 3,426,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,953 | h | /*
ONLY FILE NEEDED TO INCLUDE
*/
#ifndef AOREFPTR_H
#define AOREFPTR_H
#include <iostream>
#include <cassert>
using namespace std;
namespace ao
{
namespace core
{
//Pointers, Refrences, and Handles
//
// Handle
// (class template)
// ----------
// + Handle():
// + Handle(TYPE*t):
// + Handle(const Handle& h):
// + ~Handle()
// + operator=(const Handle&): Handle&
// + operator bool() const: Handle&
// + operator *() const: TYPE&
// + operator ->() const: TYPE
// ----------
// - p:TYPE&
// ----------
//
template <class TYPE> class Handle
{
public:
Handle():p(0) {};
Handle(const Handle& s): p(0)
{
if (s.p) p =s.p->clone();
}
Handle& operator=(const Handle&);
~Handle()
{
delete p;
}
Handle(TYPE* t):p(t) {}
operator bool() const
{
return p;
}
TYPE& operator*() const;
TYPE* operator->() const;
private:
TYPE& p;
};
//
// Ref_Handle
// (class template)
// ----------
// + Ref_Handle():
// + Ref_Handle(TYPE*t):
// + Ref_Handle(const Ref_Handle& h):
// + ~Ref_Handle()
// + operator=(const Ref_Handle&): Ref_Handle&
// + operator bool() const: Ref_Handle&
// + operator *() const: TYPE&
// + operator ->() const: TYPE
// ----------
// - p:TYPE&
// ----------
//
template <class TYPE> class Ref_Handle
{
public:
Ref_Handle(): refptr(new size_t(1)),p(0) {}
Ref_Handle(TYPE* t):refptr(new size_t(1)),p(t) {}
Ref_Handle(const Ref_Handle& h):refptr(h.refptr),p(h.p)
{
++*refptr;
}
Ref_Handle& operator=(const Ref_Handle&);
~Ref_Handle();
//
operator bool() const
{
return p;
}
TYPE& operator*() const
{
if(p)
return *p;
throw std::runtime_error(*unbound Ref_Handle*);
}
TYPE* operator->() const
{
if(p)
return p;
throw std::runtime_error(*unbound Ref_Handle*);
}
private:
TYPE* p;
size_t refptr;
};
//
// Ptr
// (class template)
// ----------
// + make_unique(): void
// + Ptr():
// + Ptr(TYPE*t):
// + Ptr(const Ptr& h):
// + ~Ptr()
// + operator=(constPtr&): Ptr&
// + operator bool() const: Ptr&
// + operator *() const: TYPE&
// + operator ->() const: TYPE
// ----------
//
// ----------
//
template <class TYPE> class Ptr
{
public:
void make_unique();
//
Ptr(): refptr(new size_t(1)),p(0) {}
Ptr(TYPE* t):refptr(new size_t(1)),p(t) {}
Ptr(const Ptr& h):refptr(h.refptr),p(h.p)
{
++*refptr;
}
Ptr& operator=(const Ptr&);
~Ptr();
operator bool() const
{
return p;
}
TYPE& operator*()const;
TYPE*operator->() const;
//
private:
TYPE*p;
size_t* refptr;
};
//Pointers, Refrences, and Handles
template <class T> Handle<T>& Handle<T>::operator=(const Handle& rhs)
{
if (&rhs !=this)
{
delete p;
p=rhs.p ? rhs.p->clone():0;
}
return *this;
}
template <class T> T& Handle<T>::operator*() const
{
if(p)
return *p;
throw runtime_error("unbound Handle");
}
template <class T> T* Handle<T>::operator->() const
{
if(p)
return *p;
throw runtime_error("unbound Handle");
}
template <class T> Ref_Handle<T>& Ref_Handle<T>::operator=(const Ref_Handle& rhs)
{
++*rhs.reptr;
if(--*refptr==0)
{
delete refptr;
delete p;
}
refptr=rhs.refptr;
p=rhs.p;
return *this;
}
template <class T> Ref_Handle<T>::~Ref_Handle()
{
if(--*refptr==0)
{
delete refptr;
delete p;
}
}
template <class T> T* clone(const T* rhs)
{
return rhs->clone();
}
template <class T> void Ptr<T>::make_unique()
{
if(*refptr!=1)
{
--*refptr;
refptr=new size_t(1);
p=p? clone(p):0;
}
}
}
}
#endif
| [
"thekylejohnson90@gmail.com"
] | thekylejohnson90@gmail.com |
53cc8e2df9ec908016e526ed7ed50b674758a4e6 | eeddea04cc4a615a4e75f52f638c5f47621dc100 | /foundations/cpp/6/evennumbers.cpp | 67c9a9e211b0fe3a06b5ff36d208a56c72533018 | [] | no_license | pernilongo/NYU | 27abd08772fb7c9642b330ac5c00b487aa0163a7 | 704373c5007f75939c4dd4067e250a1e917934cd | refs/heads/main | 2023-06-14T17:57:35.540866 | 2021-07-14T01:06:14 | 2021-07-14T01:06:14 | 328,179,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include <iostream>
using namespace std;
int main()
{
int n;
cout << "Please enter a positive integer: ";
cin >> n;
int even = 2;
while (n-- > 0)
{
cout << even << endl;
even += 2;
}
return 0;
} | [
"juan.rovirosa@gmail.com"
] | juan.rovirosa@gmail.com |
e6ee33fd61c7fcb5315b80b1419c937177fd83fd | a1b542980f7306f9b9caebfc9c71db43d9a34eb5 | /Engine/source/postFx/postEffect.h | 4ea75595fd9126d40d7ef0e5ac925a80262a7cc2 | [
"MIT"
] | permissive | jnoyola/Torque3D_GDDEast | e2a2b19f3ccedef07e78e6363bc02ea7ac5bc2e7 | 15738ed79185c45e353ea4520dee0a94872ee870 | refs/heads/master | 2021-01-02T08:46:29.721771 | 2014-11-01T23:40:15 | 2014-11-01T23:40:15 | 33,396,596 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,497 | h | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _POST_EFFECT_H_
#define _POST_EFFECT_H_
#ifndef _SIMSET_H_
#include "console/simSet.h"
#endif
#ifndef _MPOINT3_H_
#include "math/mPoint3.h"
#endif
#ifndef _MPOINT2_H_
#include "math/mPoint2.h"
#endif
#ifndef _GFXSHADER_H_
#include "gfx/gfxShader.h"
#endif
#ifndef _GFXSTATEBLOCK_H_
#include "gfx/gfxStateBlock.h"
#endif
#ifndef _GFXTEXTUREHANDLE_H_
#include "gfx/gfxTextureHandle.h"
#endif
#ifndef _GFXTARGET_H_
#include "gfx/gfxTarget.h"
#endif
#ifndef _GFXVERTEXBUFFER_H_
#include "gfx/gfxVertexBuffer.h"
#endif
#ifndef _POSTEFFECTCOMMON_H_
#include "postFx/postEffectCommon.h"
#endif
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _MATTEXTURETARGET_H_
#include "materials/matTextureTarget.h"
#endif
class GFXStateBlockData;
class Frustum;
class SceneRenderState;
class ConditionerFeature;
///
GFX_DeclareTextureProfile( PostFxTargetProfile );
///
class PostEffect : public SimGroup
{
typedef SimGroup Parent;
friend class PostEffectVis;
public:
enum
{
NumTextures = 6,
};
protected:
FileName mTexFilename[NumTextures];
GFXTexHandle mTextures[NumTextures];
NamedTexTarget mNamedTarget;
NamedTexTarget mNamedTargetDepthStencil;
GFXTextureObject *mActiveTextures[NumTextures];
NamedTexTarget *mActiveNamedTarget[NumTextures];
RectI mActiveTextureViewport[NumTextures];
GFXStateBlockData *mStateBlockData;
GFXStateBlockRef mStateBlock;
String mShaderName;
GFXShaderRef mShader;
Vector<GFXShaderMacro> mShaderMacros;
GFXShaderConstBufferRef mShaderConsts;
GFXShaderConstHandle *mRTSizeSC;
GFXShaderConstHandle *mOneOverRTSizeSC;
GFXShaderConstHandle *mTexSizeSC[NumTextures];
GFXShaderConstHandle *mRenderTargetParamsSC[NumTextures];
GFXShaderConstHandle *mViewportOffsetSC;
GFXShaderConstHandle *mTargetViewportSC;
GFXShaderConstHandle *mFogDataSC;
GFXShaderConstHandle *mFogColorSC;
GFXShaderConstHandle *mEyePosSC;
GFXShaderConstHandle *mMatWorldToScreenSC;
GFXShaderConstHandle *mMatScreenToWorldSC;
GFXShaderConstHandle *mMatPrevScreenToWorldSC;
GFXShaderConstHandle *mNearFarSC;
GFXShaderConstHandle *mInvNearFarSC;
GFXShaderConstHandle *mWorldToScreenScaleSC;
GFXShaderConstHandle *mProjectionOffsetSC;
GFXShaderConstHandle *mWaterColorSC;
GFXShaderConstHandle *mWaterFogDataSC;
GFXShaderConstHandle *mAmbientColorSC;
GFXShaderConstHandle *mWaterFogPlaneSC;
GFXShaderConstHandle *mWaterDepthGradMaxSC;
GFXShaderConstHandle *mScreenSunPosSC;
GFXShaderConstHandle *mLightDirectionSC;
GFXShaderConstHandle *mCameraForwardSC;
GFXShaderConstHandle *mAccumTimeSC;
GFXShaderConstHandle *mDeltaTimeSC;
GFXShaderConstHandle *mInvCameraMatSC;
bool mAllowReflectPass;
/// If true update the shader.
bool mUpdateShader;
GFXTextureTargetRef mTarget;
String mTargetName;
GFXTexHandle mTargetTex;
String mTargetDepthStencilName;
GFXTexHandle mTargetDepthStencil;
/// If mTargetSize is zero then this scale is
/// used to make a relative texture size to the
/// active render target.
Point2F mTargetScale;
/// If non-zero this is used as the absolute
/// texture target size.
/// @see mTargetScale
Point2I mTargetSize;
GFXFormat mTargetFormat;
/// The color to prefill the named target when
/// first created by the effect.
ColorF mTargetClearColor;
PFXRenderTime mRenderTime;
PFXTargetClear mTargetClear;
PFXTargetViewport mTargetViewport;
String mRenderBin;
F32 mRenderPriority;
/// This is true if the effect has been succesfully
/// initialized and all requirements are met for use.
bool mIsValid;
/// True if the effect has been enabled by the manager.
bool mEnabled;
/// Skip processing of this PostEffect and its children even if its parent is enabled.
/// Parent and sibling PostEffects in the chain are still processed.
/// This is intended for debugging purposes.
bool mSkip;
bool mOneFrameOnly;
bool mOnThisFrame;
U32 mShaderReloadKey;
class EffectConst
{
public:
EffectConst( const String &name, const String &val )
: mName( name ),
mHandle( NULL ),
mDirty( true )
{
set( val );
}
void set( const String &newVal );
void setToBuffer( GFXShaderConstBufferRef buff );
String mName;
GFXShaderConstHandle *mHandle;
String mStringVal;
bool mDirty;
};
typedef HashTable<StringCase,EffectConst*> EffectConstTable;
EffectConstTable mEffectConsts;
///
virtual void _updateScreenGeometry( const Frustum &frustum,
GFXVertexBufferHandle<PFXVertex> *outVB );
///
virtual void _setupStateBlock( const SceneRenderState *state );
///
virtual void _setupConstants( const SceneRenderState *state );
///
virtual void _setupTransforms();
///
virtual void _setupTarget( const SceneRenderState *state, bool *outClearTarget );
///
virtual void _setupTexture( U32 slot, GFXTexHandle &inputTex, const RectI *inTexViewport );
/// Protected set method for toggling the enabled state.
static bool _setIsEnabled( void *object, const char *index, const char *data );
/// Called from the light manager activate signal.
/// @see LightManager::addActivateCallback
void _onLMActivate( const char*, bool activate )
{
if ( activate )
mUpdateShader = true;
}
/// We handle texture events to release named rendered targets.
/// @see GFXTextureManager::addEventDelegate
void _onTextureEvent( GFXTexCallbackCode code )
{
if ( code == GFXZombify && (mNamedTarget.isRegistered() || mNamedTargetDepthStencil.isRegistered()) )
_cleanTargets();
}
///
void _updateConditioners();
///
void _cleanTargets( bool recurse = false );
///
void _checkRequirements();
///
GFXTextureObject* _getTargetTexture( U32 index );
public:
/// Constructor.
PostEffect();
/// Destructor.
virtual ~PostEffect();
DECLARE_CONOBJECT(PostEffect);
// SimObject
virtual bool onAdd();
virtual void onRemove();
static void initPersistFields();
/// @name Callbacks
/// @{
DECLARE_CALLBACK( void, onAdd, () );
DECLARE_CALLBACK( void, preProcess, () );
DECLARE_CALLBACK( void, setShaderConsts, () );
DECLARE_CALLBACK( bool, onEnabled, () );
DECLARE_CALLBACK( void, onDisabled, () );
/// @}
virtual void process( const SceneRenderState *state,
GFXTexHandle &inOutTex,
const RectI *inTexViewport = NULL );
///
void reload();
///
void enable();
///
void disable();
/// Dump the shader disassembly to a temporary text file.
/// Returns true and sets outFilename to the file if successful.
bool dumpShaderDisassembly( String &outFilename ) const;
/// Returns the SimSet which contains all PostEffects.
SimSet* getSet() const;
///
bool isEnabled() const { return mEnabled; }
/// Is set to skip rendering.
bool isSkipped() const { return mSkip; }
/// Set the effect to skip rendering.
void setSkip( bool skip ) { mSkip = skip; }
PFXRenderTime getRenderTime() const { return mRenderTime; }
const String& getRenderBin() const { return mRenderBin; }
F32 getPriority() const { return mRenderPriority; }
void setTexture( U32 index, const String &filePath );
void setShaderMacro( const String &name, const String &value = String::EmptyString );
bool removeShaderMacro( const String &name );
void clearShaderMacros();
///
void setShaderConst( const String &name, const String &val );
void setOnThisFrame( bool enabled ) { mOnThisFrame = enabled; }
bool isOnThisFrame() { return mOnThisFrame; }
void setOneFrameOnly( bool enabled ) { mOneFrameOnly = enabled; }
bool isOneFrameOnly() { return mOneFrameOnly; }
F32 getAspectRatio() const;
enum PostEffectRequirements
{
RequiresDepth = BIT(0),
RequiresNormals = BIT(1),
RequiresLightInfo = BIT(2),
};
};
#endif // _POST_EFFECT_H_ | [
"davew@garagegames.com"
] | davew@garagegames.com |
35683db8b1b03f4d2a288f549e39d9bb1c4eca1a | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/mp+o-mb-o+o-wmb-o.c.cbmc_out.cpp | e0b79177f2fff7dec0b776a5ee7ae026e48b82ab | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 28,601 | cpp | // 0:vars:2
// 2:atom_1_X0_1:1
// 3:atom_1_X2_0:1
// 4:thr0:1
// 5:thr1:1
#define ADDRSIZE 6
#define NPROC 3
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !35, metadata !DIExpression()), !dbg !44
// br label %label_1, !dbg !45
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !43), !dbg !46
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !36, metadata !DIExpression()), !dbg !47
// call void @llvm.dbg.value(metadata i64 1, metadata !39, metadata !DIExpression()), !dbg !47
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !48
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void (...) @dmbsy(), !dbg !49
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,2+0));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cw(1,4+0));
ASSUME(cdy[1] >= cw(1,5+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,2+0));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(cdy[1] >= cr(1,4+0));
ASSUME(cdy[1] >= cr(1,5+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !50
// call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !50
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !52
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !55, metadata !DIExpression()), !dbg !74
// br label %label_2, !dbg !56
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !73), !dbg !76
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !58, metadata !DIExpression()), !dbg !77
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !59
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !60, metadata !DIExpression()), !dbg !77
// %conv = trunc i64 %0 to i32, !dbg !60
// call void @llvm.dbg.value(metadata i32 %conv, metadata !56, metadata !DIExpression()), !dbg !74
// call void (...) @dmbst(), !dbg !61
// dumbst: Guess
cds[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cds[2] >= cdy[2]);
ASSUME(cds[2] >= cw(2,0+0));
ASSUME(cds[2] >= cw(2,0+1));
ASSUME(cds[2] >= cw(2,2+0));
ASSUME(cds[2] >= cw(2,3+0));
ASSUME(cds[2] >= cw(2,4+0));
ASSUME(cds[2] >= cw(2,5+0));
ASSUME(creturn[2] >= cds[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !62, metadata !DIExpression()), !dbg !81
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !63
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r1 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r1 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r1 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !64, metadata !DIExpression()), !dbg !81
// %conv4 = trunc i64 %1 to i32, !dbg !64
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !61, metadata !DIExpression()), !dbg !74
// %cmp = icmp eq i32 %conv, 1, !dbg !65
// %conv5 = zext i1 %cmp to i32, !dbg !65
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !65, metadata !DIExpression()), !dbg !74
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !66, metadata !DIExpression()), !dbg !85
// %2 = zext i32 %conv5 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !68, metadata !DIExpression()), !dbg !85
// store atomic i64 %2, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !67
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= max(creg_r0,0));
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==1);
mem(2,cw(2,2)) = (r0==1);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// %cmp7 = icmp eq i32 %conv4, 0, !dbg !68
// %conv8 = zext i1 %cmp7 to i32, !dbg !68
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !69, metadata !DIExpression()), !dbg !74
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !70, metadata !DIExpression()), !dbg !88
// %3 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !72, metadata !DIExpression()), !dbg !88
// store atomic i64 %3, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !70
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r1,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r1==0);
mem(3,cw(2,3)) = (r1==0);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !71
ret_thread_2 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !98, metadata !DIExpression()), !dbg !126
// call void @llvm.dbg.value(metadata i8** %argv, metadata !99, metadata !DIExpression()), !dbg !126
// %0 = bitcast i64* %thr0 to i8*, !dbg !69
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #6, !dbg !69
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !100, metadata !DIExpression()), !dbg !128
// %1 = bitcast i64* %thr1 to i8*, !dbg !71
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #6, !dbg !71
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !104, metadata !DIExpression()), !dbg !130
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !105, metadata !DIExpression()), !dbg !131
// call void @llvm.dbg.value(metadata i64 0, metadata !107, metadata !DIExpression()), !dbg !131
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !74
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !108, metadata !DIExpression()), !dbg !133
// call void @llvm.dbg.value(metadata i64 0, metadata !110, metadata !DIExpression()), !dbg !133
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !76
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !111, metadata !DIExpression()), !dbg !135
// call void @llvm.dbg.value(metadata i64 0, metadata !113, metadata !DIExpression()), !dbg !135
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !78
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !114, metadata !DIExpression()), !dbg !137
// call void @llvm.dbg.value(metadata i64 0, metadata !116, metadata !DIExpression()), !dbg !137
// store atomic i64 0, i64* @atom_1_X2_0 monotonic, align 8, !dbg !80
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #6, !dbg !81
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call7 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #6, !dbg !82
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !83, !tbaa !84
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r3 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r3 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r3 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// %call8 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !88
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !89, !tbaa !84
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r4 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r4 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r4 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// %call9 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !90
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !118, metadata !DIExpression()), !dbg !149
// %4 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !92
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r5 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r5 = buff(0,2);
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r5 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i64 %4, metadata !120, metadata !DIExpression()), !dbg !149
// %conv = trunc i64 %4 to i32, !dbg !93
// call void @llvm.dbg.value(metadata i32 %conv, metadata !117, metadata !DIExpression()), !dbg !126
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !122, metadata !DIExpression()), !dbg !152
// %5 = load atomic i64, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !95
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r6 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r6 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r6 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %5, metadata !124, metadata !DIExpression()), !dbg !152
// %conv13 = trunc i64 %5 to i32, !dbg !96
// call void @llvm.dbg.value(metadata i32 %conv13, metadata !121, metadata !DIExpression()), !dbg !126
// %and = and i32 %conv, %conv13, !dbg !97
creg_r7 = max(creg_r5,creg_r6);
ASSUME(active[creg_r7] == 0);
r7 = r5 & r6;
// call void @llvm.dbg.value(metadata i32 %and, metadata !125, metadata !DIExpression()), !dbg !126
// %cmp = icmp eq i32 %and, 1, !dbg !98
// br i1 %cmp, label %if.then, label %if.end, !dbg !100
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r7);
ASSUME(cctrl[0] >= 0);
if((r7==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([102 x i8], [102 x i8]* @.str.1, i64 0, i64 0), i32 noundef 56, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #7, !dbg !101
// unreachable, !dbg !101
r8 = 1;
T0BLOCK2:
// %6 = bitcast i64* %thr1 to i8*, !dbg !104
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %6) #6, !dbg !104
// %7 = bitcast i64* %thr0 to i8*, !dbg !104
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %7) #6, !dbg !104
// ret i32 0, !dbg !105
ret_thread_0 = 0;
ASSERT(r8== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
019bfd3a90afa40fb3e1d16efc275823adf707e7 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /device/fido/set_pin_request_handler.cc | e8734a8a2dfab23576adc150b934638ec7944c82 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 4,769 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "device/fido/fido_authenticator.h"
#include "device/fido/fido_constants.h"
#include "device/fido/pin.h"
#include "device/fido/set_pin_request_handler.h"
namespace device {
SetPINRequestHandler::SetPINRequestHandler(
const base::flat_set<FidoTransportProtocol>& supported_transports,
GetPINCallback get_pin_callback,
FinishedCallback finished_callback,
std::unique_ptr<FidoDiscoveryFactory> fido_discovery_factory)
: FidoRequestHandlerBase(fido_discovery_factory.get(),
supported_transports),
get_pin_callback_(std::move(get_pin_callback)),
finished_callback_(std::move(finished_callback)),
fido_discovery_factory_(std::move(fido_discovery_factory)) {
Start();
}
SetPINRequestHandler::~SetPINRequestHandler() {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
}
void SetPINRequestHandler::ProvidePIN(const std::string& old_pin,
const std::string& new_pin) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
DCHECK_EQ(State::kWaitingForPIN, state_);
DCHECK(pin::IsValid(new_pin));
if (authenticator_ == nullptr) {
// Authenticator was detached.
state_ = State::kFinished;
finished_callback_.Run(CtapDeviceResponseCode::kCtap1ErrInvalidChannel);
return;
}
state_ = State::kSettingPIN;
if (old_pin.empty()) {
authenticator_->SetPIN(
new_pin, base::BindOnce(&SetPINRequestHandler::OnSetPINComplete,
weak_factory_.GetWeakPtr()));
} else {
authenticator_->ChangePIN(
old_pin, new_pin,
base::BindOnce(&SetPINRequestHandler::OnSetPINComplete,
weak_factory_.GetWeakPtr()));
}
}
void SetPINRequestHandler::DispatchRequest(FidoAuthenticator* authenticator) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
authenticator->GetTouch(base::BindOnce(&SetPINRequestHandler::OnTouch,
weak_factory_.GetWeakPtr(),
authenticator));
}
void SetPINRequestHandler::AuthenticatorRemoved(
FidoDiscoveryBase* discovery,
FidoAuthenticator* authenticator) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
if (authenticator == authenticator_) {
authenticator_ = nullptr;
}
FidoRequestHandlerBase::AuthenticatorRemoved(discovery, authenticator);
}
void SetPINRequestHandler::OnTouch(FidoAuthenticator* authenticator) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
if (state_ != State::kWaitingForTouch) {
return;
}
authenticator_ = authenticator;
switch (authenticator_->Options()->client_pin_availability) {
case AuthenticatorSupportedOptions::ClientPinAvailability::kNotSupported:
state_ = State::kFinished;
CancelActiveAuthenticators(authenticator->GetId());
finished_callback_.Run(CtapDeviceResponseCode::kCtap1ErrInvalidCommand);
return;
case AuthenticatorSupportedOptions::ClientPinAvailability::
kSupportedAndPinSet:
state_ = State::kGettingRetries;
CancelActiveAuthenticators(authenticator->GetId());
authenticator_->GetPinRetries(
base::BindOnce(&SetPINRequestHandler::OnRetriesResponse,
weak_factory_.GetWeakPtr()));
break;
case AuthenticatorSupportedOptions::ClientPinAvailability::
kSupportedButPinNotSet:
state_ = State::kWaitingForPIN;
CancelActiveAuthenticators(authenticator->GetId());
std::move(get_pin_callback_).Run(base::nullopt);
break;
}
}
void SetPINRequestHandler::OnRetriesResponse(
CtapDeviceResponseCode status,
base::Optional<pin::RetriesResponse> response) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
DCHECK_EQ(state_, State::kGettingRetries);
if (status != CtapDeviceResponseCode::kSuccess) {
state_ = State::kFinished;
finished_callback_.Run(status);
return;
}
state_ = State::kWaitingForPIN;
std::move(get_pin_callback_).Run(response->retries);
}
void SetPINRequestHandler::OnSetPINComplete(
CtapDeviceResponseCode status,
base::Optional<pin::EmptyResponse> response) {
DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
DCHECK_EQ(state_, State::kSettingPIN);
if (status == CtapDeviceResponseCode::kCtap2ErrPinInvalid) {
// The caller may try again.
state_ = State::kWaitingForPIN;
} else {
state_ = State::kFinished;
}
finished_callback_.Run(status);
}
} // namespace device
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
6d6ce9c8b2822f61b959ba33139d0d4d76d911ea | 654e42a8405d0ee09910cf64dca8427d5ce7c680 | /neat/JModuleCanvas.h | 502be660e2a5e75728c8a838be6359304ba4f250 | [] | no_license | neattools/neattools | bbd94d46c4e5aeb1ab524bf63a9b1ac623e7fd58 | ac63c05ba1d575797303e48558fa2383a5e8ccf7 | refs/heads/master | 2020-05-29T17:34:04.002088 | 2018-03-01T15:59:04 | 2018-03-01T15:59:04 | 17,801,058 | 0 | 0 | null | 2018-03-01T15:59:05 | 2014-03-16T14:29:07 | C++ | UTF-8 | C++ | false | false | 442 | h | #if !defined( _JModuleCanvas_h )
#define _JModuleCanvas_h
#include "JCanvas.h"
#include "JModuleObj.h"
class
#include "JNEAT.hpp"
JModuleCanvas : public JCanvas {
public:
virtual const char* className() const;
virtual JObject* clone() const;
static JModuleCanvas* create(JComponent* p, JModuleObj* obj);
JModuleCanvas();
virtual void startup();
virtual void paint(JGraphics g);
JModuleObj *pmodule;
};
#endif
| [
"sam@sambaker.net"
] | sam@sambaker.net |
278092eb19c2e0eb98b985e874f6ac03cfd0dd92 | b2d726a70c84915c0daf9f36a265f611b29a5325 | /node_modules/bcrypto/src/poly1305.cc | 0648ca30640bece851519c25a01061abf60bb679 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL",
"CC0-1.0",
"ISC",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | braydonf/bcoin | 12cf29008b079fa599b1730e2c030b807c7f0445 | 1e920cb39830113c239ef1ce5cb02482613de246 | refs/heads/master | 2021-01-11T03:44:52.699611 | 2020-02-18T20:23:47 | 2020-02-18T20:23:47 | 71,415,513 | 0 | 0 | NOASSERTION | 2019-05-07T19:27:38 | 2016-10-20T01:53:39 | JavaScript | UTF-8 | C++ | false | false | 4,528 | cc | #include "common.h"
#include "poly1305.h"
static Nan::Persistent<v8::FunctionTemplate> poly1305_constructor;
BPoly1305::BPoly1305() {
memset(&ctx, 0, sizeof(bcrypto_poly1305_ctx));
}
BPoly1305::~BPoly1305() {}
void
BPoly1305::Init(v8::Local<v8::Object> &target) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl =
Nan::New<v8::FunctionTemplate>(BPoly1305::New);
poly1305_constructor.Reset(tpl);
tpl->SetClassName(Nan::New("Poly1305").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "init", BPoly1305::Init);
Nan::SetPrototypeMethod(tpl, "update", BPoly1305::Update);
Nan::SetPrototypeMethod(tpl, "final", BPoly1305::Final);
Nan::SetMethod(tpl, "auth", BPoly1305::Auth);
Nan::SetMethod(tpl, "verify", BPoly1305::Verify);
v8::Local<v8::FunctionTemplate> ctor =
Nan::New<v8::FunctionTemplate>(poly1305_constructor);
Nan::Set(target, Nan::New("Poly1305").ToLocalChecked(),
Nan::GetFunction(ctor).ToLocalChecked());
}
NAN_METHOD(BPoly1305::New) {
if (!info.IsConstructCall())
return Nan::ThrowError("Could not create Poly1305 instance.");
BPoly1305 *poly = new BPoly1305();
poly->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(BPoly1305::Init) {
BPoly1305 *poly = ObjectWrap::Unwrap<BPoly1305>(info.Holder());
if (info.Length() < 1)
return Nan::ThrowError("poly1305.init() requires arguments.");
v8::Local<v8::Object> buf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(buf))
return Nan::ThrowTypeError("First argument must be a buffer.");
const uint8_t *data = (const uint8_t *)node::Buffer::Data(buf);
size_t len = node::Buffer::Length(buf);
if (len != 32)
return Nan::ThrowRangeError("Invalid key size.");
bcrypto_poly1305_init(&poly->ctx, data);
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(BPoly1305::Update) {
BPoly1305 *poly = ObjectWrap::Unwrap<BPoly1305>(info.Holder());
if (info.Length() < 1)
return Nan::ThrowError("poly1305.update() requires arguments.");
v8::Local<v8::Object> buf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(buf))
return Nan::ThrowTypeError("First argument must be a buffer.");
const uint8_t *data = (const uint8_t *)node::Buffer::Data(buf);
size_t len = node::Buffer::Length(buf);
bcrypto_poly1305_update(&poly->ctx, data, len);
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(BPoly1305::Final) {
BPoly1305 *poly = ObjectWrap::Unwrap<BPoly1305>(info.Holder());
uint8_t mac[16];
bcrypto_poly1305_finish(&poly->ctx, &mac[0]);
info.GetReturnValue().Set(
Nan::CopyBuffer((char *)&mac[0], 16).ToLocalChecked());
}
NAN_METHOD(BPoly1305::Auth) {
if (info.Length() < 2)
return Nan::ThrowError("poly1305.auth() requires arguments.");
v8::Local<v8::Object> buf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(buf))
return Nan::ThrowTypeError("First argument must be a buffer.");
v8::Local<v8::Object> kbuf = info[1].As<v8::Object>();
if (!node::Buffer::HasInstance(kbuf))
return Nan::ThrowTypeError("Second argument must be a buffer.");
const uint8_t *data = (const uint8_t *)node::Buffer::Data(buf);
size_t len = node::Buffer::Length(buf);
const uint8_t *kdata = (const uint8_t *)node::Buffer::Data(kbuf);
size_t klen = node::Buffer::Length(kbuf);
if (klen != 32)
return Nan::ThrowRangeError("Invalid key size.");
uint8_t mac[16];
bcrypto_poly1305_auth(&mac[0], data, len, kdata);
info.GetReturnValue().Set(
Nan::CopyBuffer((char *)&mac[0], 16).ToLocalChecked());
}
NAN_METHOD(BPoly1305::Verify) {
if (info.Length() < 2)
return Nan::ThrowError("poly1305.verify() requires arguments.");
v8::Local<v8::Object> abuf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(abuf))
return Nan::ThrowTypeError("First argument must be a buffer.");
v8::Local<v8::Object> bbuf = info[1].As<v8::Object>();
if (!node::Buffer::HasInstance(bbuf))
return Nan::ThrowTypeError("Second argument must be a buffer.");
const uint8_t *adata = (const uint8_t *)node::Buffer::Data(abuf);
size_t alen = node::Buffer::Length(abuf);
const uint8_t *bdata = (const uint8_t *)node::Buffer::Data(bbuf);
size_t blen = node::Buffer::Length(bbuf);
if (alen != 16 || blen != 16)
return Nan::ThrowRangeError("Invalid mac size.");
int32_t result = bcrypto_poly1305_verify(adata, bdata);
info.GetReturnValue().Set(Nan::New<v8::Boolean>((bool)result));
}
| [
"courier@braydon.com"
] | courier@braydon.com |
61ab9037ed7a93d60e83cb7506cc0dc8741411aa | b6bd84283f5db4f27e9a745a40f4be260d0f135e | /src/qt/sendtocontract.cpp | 3b56b2943e7c35dca2de455586690e2717f2db66 | [
"MIT",
"GPL-3.0-only"
] | permissive | michelvankessel/qtum | da6f92e70755da4d6c734c67cc21f1bf48c6a977 | 8bb9cd6a8038c3e7ec3ca1f6d4dfd224bd9e167a | refs/heads/master | 2023-04-11T02:47:13.864058 | 2021-04-20T17:57:51 | 2021-04-20T17:57:51 | 295,159,719 | 0 | 0 | MIT | 2020-09-13T13:42:24 | 2020-09-13T13:42:23 | null | UTF-8 | C++ | false | false | 15,712 | cpp | #include <qt/sendtocontract.h>
#include <qt/forms/ui_sendtocontract.h>
#include <qt/platformstyle.h>
#include <qt/walletmodel.h>
#include <qt/clientmodel.h>
#include <qt/guiconstants.h>
#include <qt/rpcconsole.h>
#include <qt/execrpccommand.h>
#include <qt/bitcoinunits.h>
#include <qt/optionsmodel.h>
#include <validation.h>
#include <util/moneystr.h>
#include <qt/abifunctionfield.h>
#include <qt/contractutil.h>
#include <qt/tabbarinfo.h>
#include <qt/contractresult.h>
#include <qt/contractbookpage.h>
#include <qt/editcontractinfodialog.h>
#include <qt/contracttablemodel.h>
#include <qt/styleSheet.h>
#include <qt/guiutil.h>
#include <qt/sendcoinsdialog.h>
#include <QClipboard>
#include <interfaces/node.h>
namespace SendToContract_NS
{
// Contract data names
static const QString PRC_COMMAND = "sendtocontract";
static const QString PARAM_ADDRESS = "address";
static const QString PARAM_DATAHEX = "datahex";
static const QString PARAM_AMOUNT = "amount";
static const QString PARAM_GASLIMIT = "gaslimit";
static const QString PARAM_GASPRICE = "gasprice";
static const QString PARAM_SENDER = "sender";
static const CAmount SINGLE_STEP = 0.00000001*COIN;
static const CAmount HIGH_GASPRICE = 0.001*COIN;
}
using namespace SendToContract_NS;
SendToContract::SendToContract(const PlatformStyle *platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::SendToContract),
m_model(0),
m_clientModel(0),
m_contractModel(0),
m_execRPCCommand(0),
m_ABIFunctionField(0),
m_contractABI(0),
m_tabInfo(0),
m_results(1)
{
m_platformStyle = platformStyle;
// Setup ui components
Q_UNUSED(platformStyle);
ui->setupUi(this);
ui->saveInfoButton->setIcon(platformStyle->MultiStatesIcon(":/icons/filesave", PlatformStyle::PushButtonIcon));
ui->loadInfoButton->setIcon(platformStyle->MultiStatesIcon(":/icons/address-book", PlatformStyle::PushButtonIcon));
ui->pasteAddressButton->setIcon(platformStyle->MultiStatesIcon(":/icons/editpaste", PlatformStyle::PushButtonIcon));
// Format tool buttons
GUIUtil::formatToolButtons(ui->saveInfoButton, ui->loadInfoButton, ui->pasteAddressButton);
// Set stylesheet
SetObjectStyleSheet(ui->pushButtonClearAll, StyleSheetNames::ButtonDark);
m_ABIFunctionField = new ABIFunctionField(platformStyle, ABIFunctionField::SendTo, ui->scrollAreaFunction);
ui->scrollAreaFunction->setWidget(m_ABIFunctionField);
ui->lineEditAmount->setEnabled(true);
ui->labelContractAddress->setToolTip(tr("The contract address that will receive the funds and data."));
ui->labelAmount->setToolTip(tr("The amount in QTUM to send. Default = 0."));
ui->labelSenderAddress->setToolTip(tr("The qtum address that will be used as sender."));
m_tabInfo = new TabBarInfo(ui->stackedWidget);
m_tabInfo->addTab(0, tr("Send To Contract"));
// Set defaults
ui->lineEditGasPrice->setValue(DEFAULT_GAS_PRICE);
ui->lineEditGasPrice->setSingleStep(SINGLE_STEP);
ui->lineEditGasLimit->setMinimum(MINIMUM_GAS_LIMIT);
ui->lineEditGasLimit->setMaximum(DEFAULT_GAS_LIMIT_OP_SEND);
ui->lineEditGasLimit->setValue(DEFAULT_GAS_LIMIT_OP_SEND);
ui->textEditInterface->setIsValidManually(true);
ui->pushButtonSendToContract->setEnabled(false);
ui->lineEditSenderAddress->setSenderAddress(true);
// Create new PRC command line interface
QStringList lstMandatory;
lstMandatory.append(PARAM_ADDRESS);
lstMandatory.append(PARAM_DATAHEX);
QStringList lstOptional;
lstOptional.append(PARAM_AMOUNT);
lstOptional.append(PARAM_GASLIMIT);
lstOptional.append(PARAM_GASPRICE);
lstOptional.append(PARAM_SENDER);
QMap<QString, QString> lstTranslations;
lstTranslations[PARAM_ADDRESS] = ui->labelContractAddress->text();
lstTranslations[PARAM_AMOUNT] = ui->labelAmount->text();
lstTranslations[PARAM_GASLIMIT] = ui->labelGasLimit->text();
lstTranslations[PARAM_GASPRICE] = ui->labelGasPrice->text();
lstTranslations[PARAM_SENDER] = ui->labelSenderAddress->text();
m_execRPCCommand = new ExecRPCCommand(PRC_COMMAND, lstMandatory, lstOptional, lstTranslations, this);
m_contractABI = new ContractABI();
// Connect signals with slots
connect(ui->pushButtonClearAll, &QPushButton::clicked, this, &SendToContract::on_clearAllClicked);
connect(ui->pushButtonSendToContract, &QPushButton::clicked, this, &SendToContract::on_sendToContractClicked);
connect(ui->lineEditContractAddress, &QValidatedLineEdit::textChanged, this, &SendToContract::on_updateSendToContractButton);
connect(ui->textEditInterface, &QValidatedTextEdit::textChanged, this, &SendToContract::on_newContractABI);
connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, &SendToContract::on_updateSendToContractButton);
connect(m_ABIFunctionField, &ABIFunctionField::functionChanged, this, &SendToContract::on_functionChanged);
connect(ui->saveInfoButton, &QToolButton::clicked, this, &SendToContract::on_saveInfoClicked);
connect(ui->loadInfoButton, &QToolButton::clicked, this, &SendToContract::on_loadInfoClicked);
connect(ui->pasteAddressButton, &QToolButton::clicked, this, &SendToContract::on_pasteAddressClicked);
connect(ui->lineEditContractAddress, &QValidatedLineEdit::textChanged, this, &SendToContract::on_contractAddressChanged);
// Set contract address validator
QRegularExpression regEx;
regEx.setPattern(paternAddress);
QRegularExpressionValidator *addressValidatr = new QRegularExpressionValidator(ui->lineEditContractAddress);
addressValidatr->setRegularExpression(regEx);
ui->lineEditContractAddress->setCheckValidator(addressValidatr);
}
SendToContract::~SendToContract()
{
delete m_contractABI;
delete ui;
}
void SendToContract::setModel(WalletModel *_model)
{
m_model = _model;
m_contractModel = m_model->getContractTableModel();
ui->lineEditSenderAddress->setWalletModel(m_model);
if (m_model && m_model->getOptionsModel())
connect(m_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendToContract::updateDisplayUnit);
// update the display unit, to not use the default ("QTUM")
updateDisplayUnit();
}
bool SendToContract::isValidContractAddress()
{
ui->lineEditContractAddress->checkValidity();
return ui->lineEditContractAddress->isValid();
}
bool SendToContract::isValidInterfaceABI()
{
ui->textEditInterface->checkValidity();
return ui->textEditInterface->isValid();
}
bool SendToContract::isDataValid()
{
bool dataValid = true;
if(!isValidContractAddress())
dataValid = false;
if(!isValidInterfaceABI())
dataValid = false;
if(!m_ABIFunctionField->isValid())
dataValid = false;
return dataValid;
}
void SendToContract::setContractAddress(const QString &address)
{
ui->lineEditContractAddress->setText(address);
ui->lineEditContractAddress->setFocus();
}
void SendToContract::setClientModel(ClientModel *_clientModel)
{
m_clientModel = _clientModel;
if (m_clientModel)
{
connect(m_clientModel, SIGNAL(gasInfoChanged(quint64, quint64, quint64)), this, SLOT(on_gasInfoChanged(quint64, quint64, quint64)));
}
}
void SendToContract::on_clearAllClicked()
{
ui->lineEditContractAddress->clear();
ui->lineEditAmount->clear();
ui->lineEditAmount->setEnabled(true);
ui->lineEditGasLimit->setValue(DEFAULT_GAS_LIMIT_OP_SEND);
ui->lineEditGasPrice->setValue(DEFAULT_GAS_PRICE);
ui->lineEditSenderAddress->setCurrentIndex(-1);
ui->textEditInterface->clear();
ui->textEditInterface->setIsValidManually(true);
m_tabInfo->clear();
}
void SendToContract::on_sendToContractClicked()
{
if(isDataValid())
{
WalletModel::UnlockContext ctx(m_model->requestUnlock());
if(!ctx.isValid())
{
return;
}
// Initialize variables
QMap<QString, QString> lstParams;
QVariant result;
QString errorMessage;
QString resultJson;
int unit = BitcoinUnits::BTC;
uint64_t gasLimit = ui->lineEditGasLimit->value();
CAmount gasPrice = ui->lineEditGasPrice->value();
int func = m_ABIFunctionField->getSelectedFunction();
// Check for high gas price
if(gasPrice > HIGH_GASPRICE)
{
QString message = tr("The Gas Price is too high, are you sure you want to possibly spend a max of %1 for this transaction?");
if(QMessageBox::question(this, tr("High Gas price"), message.arg(BitcoinUnits::formatWithUnit(unit, gasLimit * gasPrice))) == QMessageBox::No)
return;
}
// Append params to the list
ExecRPCCommand::appendParam(lstParams, PARAM_ADDRESS, ui->lineEditContractAddress->text());
ExecRPCCommand::appendParam(lstParams, PARAM_DATAHEX, toDataHex(func, errorMessage));
QString amount = isFunctionPayable() ? BitcoinUnits::format(unit, ui->lineEditAmount->value(), false, BitcoinUnits::separatorNever) : "0";
ExecRPCCommand::appendParam(lstParams, PARAM_AMOUNT, amount);
ExecRPCCommand::appendParam(lstParams, PARAM_GASLIMIT, QString::number(gasLimit));
ExecRPCCommand::appendParam(lstParams, PARAM_GASPRICE, BitcoinUnits::format(unit, gasPrice, false, BitcoinUnits::separatorNever));
ExecRPCCommand::appendParam(lstParams, PARAM_SENDER, ui->lineEditSenderAddress->currentText());
QString questionString = tr("Are you sure you want to send to the contract: <br /><br />");
questionString.append(tr("<b>%1</b>?")
.arg(ui->lineEditContractAddress->text()));
SendConfirmationDialog confirmationDialog(tr("Confirm sending to contract."), questionString, "", "", SEND_CONFIRM_DELAY, tr("Send"), this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval == QMessageBox::Yes)
{
// Execute RPC command line
if(errorMessage.isEmpty() && m_execRPCCommand->exec(m_model->node(), m_model, lstParams, result, resultJson, errorMessage))
{
ContractResult *widgetResult = new ContractResult(ui->stackedWidget);
widgetResult->setResultData(result, FunctionABI(), m_ABIFunctionField->getParamsValues(), ContractResult::SendToResult);
ui->stackedWidget->addWidget(widgetResult);
int position = ui->stackedWidget->count() - 1;
m_results = position == 1 ? 1 : m_results + 1;
m_tabInfo->addTab(position, tr("Result %1").arg(m_results));
m_tabInfo->setCurrent(position);
}
else
{
QMessageBox::warning(this, tr("Send to contract"), errorMessage);
}
}
}
}
void SendToContract::on_gasInfoChanged(quint64 blockGasLimit, quint64 minGasPrice, quint64 nGasPrice)
{
Q_UNUSED(nGasPrice);
ui->labelGasLimit->setToolTip(tr("Gas limit. Default = %1, Max = %2").arg(DEFAULT_GAS_LIMIT_OP_CREATE).arg(blockGasLimit));
ui->labelGasPrice->setToolTip(tr("Gas price: QTUM price per gas unit. Default = %1, Min = %2").arg(QString::fromStdString(FormatMoney(DEFAULT_GAS_PRICE))).arg(QString::fromStdString(FormatMoney(minGasPrice))));
ui->lineEditGasPrice->SetMinValue(minGasPrice);
ui->lineEditGasLimit->setMaximum(blockGasLimit);
}
void SendToContract::on_updateSendToContractButton()
{
int func = m_ABIFunctionField->getSelectedFunction();
bool enabled = func >= -1;
if(ui->lineEditContractAddress->text().isEmpty())
{
enabled = false;
}
enabled &= ui->stackedWidget->currentIndex() == 0;
ui->pushButtonSendToContract->setEnabled(enabled);
}
void SendToContract::on_newContractABI()
{
std::string json_data = ui->textEditInterface->toPlainText().toStdString();
if(!m_contractABI->loads(json_data))
{
m_contractABI->clean();
ui->textEditInterface->setIsValidManually(false);
}
else
{
ui->textEditInterface->setIsValidManually(true);
}
m_ABIFunctionField->setContractABI(m_contractABI);
on_updateSendToContractButton();
}
void SendToContract::on_functionChanged()
{
bool payable = isFunctionPayable();
ui->lineEditAmount->setEnabled(payable);
if(!payable)
{
ui->lineEditAmount->clear();
}
}
void SendToContract::on_saveInfoClicked()
{
if(!m_contractModel)
return;
bool valid = true;
if(!isValidContractAddress())
valid = false;
if(!isValidInterfaceABI())
valid = false;
if(!valid)
return;
QString contractAddress = ui->lineEditContractAddress->text();
int row = m_contractModel->lookupAddress(contractAddress);
EditContractInfoDialog::Mode dlgMode = row > -1 ? EditContractInfoDialog::EditContractInfo : EditContractInfoDialog::NewContractInfo;
EditContractInfoDialog dlg(dlgMode, this);
dlg.setModel(m_contractModel);
if(dlgMode == EditContractInfoDialog::EditContractInfo)
{
dlg.loadRow(row);
}
dlg.setAddress(ui->lineEditContractAddress->text());
dlg.setABI(ui->textEditInterface->toPlainText());
if(dlg.exec())
{
ui->lineEditContractAddress->setText(dlg.getAddress());
ui->textEditInterface->setText(dlg.getABI());
on_contractAddressChanged();
}
}
void SendToContract::on_loadInfoClicked()
{
ContractBookPage dlg(m_platformStyle, this);
dlg.setModel(m_model->getContractTableModel());
if(dlg.exec())
{
ui->lineEditContractAddress->setText(dlg.getAddressValue());
on_contractAddressChanged();
}
}
void SendToContract::on_pasteAddressClicked()
{
setContractAddress(QApplication::clipboard()->text());
}
void SendToContract::on_contractAddressChanged()
{
if(isValidContractAddress() && m_contractModel)
{
QString contractAddress = ui->lineEditContractAddress->text();
if(m_contractModel->lookupAddress(contractAddress) > -1)
{
QString contractAbi = m_contractModel->abiForAddress(contractAddress);
if(ui->textEditInterface->toPlainText() != contractAbi)
{
ui->textEditInterface->setText(m_contractModel->abiForAddress(contractAddress));
}
}
}
}
void SendToContract::updateDisplayUnit()
{
if(m_model && m_model->getOptionsModel())
{
// Update sendAmount and gasPriceAmount with the current unit
ui->lineEditGasPrice->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
ui->lineEditAmount->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
}
}
QString SendToContract::toDataHex(int func, QString& errorMessage)
{
if(func == -1 || m_ABIFunctionField == NULL || m_contractABI == NULL)
{
std::string defSelector = FunctionABI::defaultSelector();
return QString::fromStdString(defSelector);
}
std::string strData;
std::vector<std::vector<std::string>> values = m_ABIFunctionField->getValuesVector();
FunctionABI function = m_contractABI->functions[func];
std::vector<ParameterABI::ErrorType> errors;
if(function.abiIn(values, strData, errors))
{
return QString::fromStdString(strData);
}
else
{
errorMessage = ContractUtil::errorMessage(function, errors, true);
}
return "";
}
bool SendToContract::isFunctionPayable()
{
int func = m_ABIFunctionField->getSelectedFunction();
if(func < 0) return true;
FunctionABI function = m_contractABI->functions[func];
return function.payable;
}
| [
"time.markov@qtum.com"
] | time.markov@qtum.com |
26d8f74f35b3a0db6248c53793c9cd3d1ad8ac89 | 10ecd7454a082e341eb60817341efa91d0c7fd0b | /SDK/BP_Projectile_VolcanoRockLarge_parameters.h | 32e6ddf6201b9be23be5c0d95af1ec2358dcfae2 | [] | no_license | Blackstate/Sot-SDK | 1dba56354524572894f09ed27d653ae5f367d95b | cd73724ce9b46e3eb5b075c468427aa5040daf45 | refs/heads/main | 2023-04-10T07:26:10.255489 | 2021-04-23T01:39:08 | 2021-04-23T01:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | h | #pragma once
// Name: SoT, Version: 2.1.0.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_Projectile_VolcanoRockLarge.BP_Projectile_VolcanoRockLarge_C.UserConstructionScript
struct ABP_Projectile_VolcanoRockLarge_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"ploszjanos9844@gmail.com"
] | ploszjanos9844@gmail.com |
9bcd20627ea8ec7cff8086cf261542ff9f3663ff | 96faf6fd7cfb327131018b0e238a819e028999aa | /mbed-cloud-client/update-client-hub/modules/lwm2m-mbed/update-client-lwm2m/DeviceMetadataResource.h | 205aa874559c8e2897bf9b9209949d68e8e13a4b | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KolonIoT/Pelion | 9b1b42375a6cd4050c6bd3787a0bdfc0d7cc566d | 156eab454e87b5f5bbe4a662d7beb1482051a855 | refs/heads/master | 2020-07-01T13:54:12.712655 | 2019-08-08T06:35:57 | 2019-08-08T06:35:57 | 201,188,751 | 1 | 2 | Apache-2.0 | 2020-03-07T20:02:25 | 2019-08-08T06:02:07 | C | UTF-8 | C++ | false | false | 1,449 | h | // ----------------------------------------------------------------------------
// Copyright 2016-2017 ARM Ltd.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------
#ifndef __ARM_UCS_DEVICE_METADATA_RESOURCE_H__
#define __ARM_UCS_DEVICE_METADATA_RESOURCE_H__
#include "update-client-common/arm_uc_common.h"
#include "mbed-client/m2minterfacefactory.h"
#include "mbed-client/m2mresource.h"
#include "mbed-client/m2mobject.h"
namespace DeviceMetadataResource {
void Initialize(void);
void Uninitialize(void);
M2MObject* getObject(void);
/* set bootloader hash resource /10255/0/1 */
int32_t setBootloaderHash(arm_uc_buffer_t* hash);
/* set OEM bootloader hash resource /10255/0/2 */
int32_t setOEMBootloaderHash(arm_uc_buffer_t* hash);
}
#endif // __ARM_UCS_DEVICE_METADATA_RESOURCE_H__
| [
"hyunjae_woo@kolon.com"
] | hyunjae_woo@kolon.com |
184d41a7f72b4d9c08e092bf281c138b84d44f00 | cf2db84518e78056cb08683dcc157a2aa397553b | /TrackerApp/TrackerAppDlg.cpp | d1ffdd00d07b0334d05b42b566c2fc2ed3a2911c | [] | no_license | ttyio/TrackerSim | b25eec315756a230945e7b99a610207b7824a851 | f2fdbc7d43011ffed411af27b7033aaa819affe2 | refs/heads/master | 2021-01-20T20:41:33.494081 | 2016-06-03T01:08:29 | 2016-06-03T01:08:29 | 60,306,242 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,148 | cpp |
// TrackerAppDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "TrackerApp.h"
#include "TrackerAppDlg.h"
#include "afxdialogex.h"
#include "CvvImage.h"
#include "CameraDS.h"
#include <io.h>
#include <fcntl.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
static void redirect_io_to_console()
{
const WORD MAX_CONSOLE_LINES = 500;
if (!AttachConsole(-1))
{
AllocConsole();
CONSOLE_SCREEN_BUFFER_INFO coninfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
}
long lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
FILE* fp = _fdopen(hConHandle, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);
std::ios::sync_with_stdio();
}
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CTrackerAppDlg 对话框
CTrackerAppDlg::CTrackerAppDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CTrackerAppDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTrackerAppDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTrackerAppDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(ID_RUN_CAM, &CTrackerAppDlg::OnBnClickedRunCam)
ON_BN_CLICKED(ID_STOP_CAM, &CTrackerAppDlg::OnBnClickedStopCam)
ON_BN_CLICKED(ID_LOAD_IMAGE, &CTrackerAppDlg::OnBnClickedLoadImage)
END_MESSAGE_MAP()
// CTrackerAppDlg 消息处理程序
BOOL CTrackerAppDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
CvSize ImgSize;
ImgSize.width = IMAGE_WIDTH;
ImgSize.height = IMAGE_HEIGHT;
m_image = cvCreateImage(ImgSize, IPL_DEPTH_8U, IMAGE_CHANNELS);
redirect_io_to_console();
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CTrackerAppDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CTrackerAppDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
void CTrackerAppDlg::ResizeImage(IplImage* img)
{
int w = img->width;
int h = img->height;
int max = (w > h) ? w : h;
float scale = (float)((float)max / 256.0f);
int nw = (int)(w / scale);
int nh = (int)(h / scale);
int tlx = (nw > nh) ? 0 : (int)(256 - nw) / 2;
int tly = (nw > nh) ? (int)(256 - nh) / 2 : 0;
cvSetImageROI(m_image, cvRect(tlx, tly, nw, nh));
cvResize(img, m_image);
cvResetImageROI(m_image);
}
void CTrackerAppDlg::ShowImage(IplImage* img, UINT ID) // ID 是Picture Control控件的ID号
{
CDC* pDC = GetDlgItem(ID)->GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect rect;
GetDlgItem(ID)->GetClientRect(&rect);
int rw = rect.right - rect.left;
int rh = rect.bottom - rect.top;
int iw = img->width;
int ih = img->height;
int tx = (int)(rw - iw) / 2;
int ty = (int)(rh - ih) / 2;
SetRect(rect, tx, ty, tx + iw, ty + ih);
CvvImage cimg;
cimg.CopyOf(img);
cimg.DrawToHDC(hDC, &rect);
ReleaseDC(pDC);
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CTrackerAppDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CTrackerAppDlg::OnBnClickedRunCam()
{
// TODO: Add your control notification handler code here
// TODO: Add your control notification handler code here
CStringA camName;
camName.Format("%s%d", "Camera # ", 0);
UpdateData(FALSE);
printf(("open %s\n"), camName.GetBuffer());
CCameraDS camera;
//if(! camera.OpenCamera(0, true))
if ((!camera.OpenCamera(0, false, 960, 540)))
{
AfxMessageBox(_T("Can not open camera.\n"));
return;
}
GetDlgItem(ID_RUN_CAM)->EnableWindow(FALSE);
GetDlgItem(ID_STOP_CAM)->EnableWindow(TRUE);
IplImage* cFrame;
cvNamedWindow("camera");
cvResizeWindow("camera", 1, 1);
HWND hWnd = (HWND)cvGetWindowHandle("camera");
HWND hParent = ::GetParent(hWnd);
HWND hwnd1 = ::FindWindowA("CTrackerAppDlg", "CTrackerApp");
::SetParent(hWnd, hwnd1);
::ShowWindow(hParent, SW_HIDE);
if (m_image)
cvZero(m_image);
CvFont tFont;
cvInitFont(&tFont, CV_FONT_HERSHEY_COMPLEX, 0.5f, 0.7f, 0, 1, 8);
char timestr[26];
memset(timestr, 0, 26 * sizeof(char));
m_run = 1;
while (m_run)
{
cFrame = camera.QueryFrame();
IplImage* newframe = cvCloneImage(cFrame);
ResizeImage(newframe);
ShowImage(m_image, IDC_PRV_STATIC);
if (cvWaitKey(20) == 27) break;
cvReleaseImage(&newframe);
}
if (m_image)
{
cvZero(m_image);
ShowImage(m_image, IDC_PRV_STATIC);
}
camera.CloseCamera();
cvDestroyWindow("camera");
GetDlgItem(ID_RUN_CAM)->EnableWindow(TRUE);
GetDlgItem(ID_STOP_CAM)->EnableWindow(FALSE);
}
void CTrackerAppDlg::OnBnClickedStopCam()
{
// TODO: Add your control notification handler code here
m_run = 0;
printf("close camera\n");
}
void WCSTOMBS(WCHAR*buf, CHAR*& mbsPtr, size_t& mbs_len)
{
mbs_len = WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
mbsPtr = new CHAR[mbs_len + 1]; //分配内存空间
if (mbsPtr != NULL)
{
//将char字串转换为wchar_t字串
WideCharToMultiByte(CP_ACP, 0, buf, lstrlenW(buf) + 1, mbsPtr, mbs_len + 1, NULL, NULL);
}
}
void CTrackerAppDlg::OnBnClickedLoadImage()
{
// TODO: Add your control notification handler code here
CFileDialog dlg(
TRUE, _T("*.bmp"), NULL,
OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY,
_T("image files (*.bmp; *.jpg) |*.bmp; *.jpg; *.jpeg | All Files (*.*) |*.*||"), NULL
);
dlg.m_ofn.lpstrTitle = _T("Open Image");
if (dlg.DoModal() != IDOK)
return;
CString mPath = dlg.GetPathName();
CHAR* mbsPtr;
size_t mbs_len;
WCSTOMBS(mPath.GetBuffer(), mbsPtr, mbs_len);
IplImage* ipl = cvLoadImage(mbsPtr, 1);
printf(("load image %s\n"), mbsPtr);
/*
try {
std::vector<std::string> result = api::plate_recognize(mbsPtr,
"svm.xml",
"ann.xml",
true);
for (std::vector<std::string>::iterator iter = result.begin();
iter != result.end(); ++iter){
printf("detected %s\n", iter->c_str());
}
}
catch (...)
{
printf("failed to recognize plate\n");
}*/
delete[] mbsPtr;
if (!ipl)
return;
if (m_image)
cvZero(m_image);
ResizeImage(ipl);
ShowImage(m_image, IDC_PRV_STATIC);
cvReleaseImage(&ipl);
}
| [
"ttyio@hotmail.com"
] | ttyio@hotmail.com |
82b390f7ffd0a3c7d1afb14a48147abb50f08d0a | 29c28b80cfd734d171cfcfee7bd1f1344cdca0e9 | /Round692/b.cpp | 12379a4f91c898d82f313c45d266e1e42a1fd75c | [] | no_license | Elitedj/codeforces_sloved | b2c190a2bd5b4337a17ccc835c156bec3333b87f | e8270f6ce624818f3fadaa21380919aac582f4c3 | refs/heads/master | 2023-03-31T00:43:24.313196 | 2021-04-02T08:48:10 | 2021-04-02T08:48:10 | 234,066,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
#define IO ios::sync_with_stdio(0)
#define DEBUG(x) cout << "--->" << (x) << '\n';
const double eps = 1e-9;
const double PI = acos(-1);
const ll mod = 1e9 + 7;
const int maxn = 2e5 + 5;
int T;
void slove() {
ll n;
cin >> n;
while (1) {
ll tmp = n;
vector<int> fac;
while (tmp) {
int x = tmp % 10;
if (x) fac.push_back(x);
tmp /= 10;
}
int ok = 1;
for (auto v : fac) {
if (n % v != 0) {
ok = 0;
break;
}
}
if (ok) {
cout << n << '\n';
return;
}
n++;
}
}
int main() {
// freopen("in.txt", "r", stdin);
T = 1;
cin >> T;
while (T--) slove();
return 0;
}
| [
"747527651@qq.com"
] | 747527651@qq.com |
5eb0d3c884521b9755fc8a21303e896b8f91097d | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/Chaste/2017/4/RadialCellDataDistributionWriter.cpp | 6995786f3690aa7e892d02788700a5f39020fa81 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 8,641 | cpp | /*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "RadialCellDataDistributionWriter.hpp"
#include "MeshBasedCellPopulation.hpp"
#include "CaBasedCellPopulation.hpp"
#include "NodeBasedCellPopulation.hpp"
#include "PottsBasedCellPopulation.hpp"
#include "VertexBasedCellPopulation.hpp"
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::RadialCellDataDistributionWriter()
: AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM>("radial_dist.dat"),
mVariableName(""),
mNumRadialBins(UNSIGNED_UNSET)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::VisitAnyPopulation(AbstractCellPopulation<SPACE_DIM, SPACE_DIM>* pCellPopulation)
{
// Calculate the centre of the cell population
c_vector<double, SPACE_DIM> centre = pCellPopulation->GetCentroidOfCellPopulation();
// Calculate the distance between each node and the centre of the cell population, as well as the maximum of these
std::map<double, CellPtr> radius_cell_map;
double max_distance_from_centre = 0.0;
for (typename AbstractCellPopulation<SPACE_DIM, SPACE_DIM>::Iterator cell_iter = pCellPopulation->Begin();
cell_iter != pCellPopulation->End();
++cell_iter)
{
double distance = norm_2(pCellPopulation->GetLocationOfCellCentre(*cell_iter) - centre);
radius_cell_map[distance] = *cell_iter;
if (distance > max_distance_from_centre)
{
max_distance_from_centre = distance;
}
}
// Create vector of radius intervals
std::vector<double> radius_intervals;
for (unsigned i=0; i<mNumRadialBins; i++)
{
double upper_radius = max_distance_from_centre*((double) i+1)/((double) mNumRadialBins);
radius_intervals.push_back(upper_radius);
}
// Calculate PDE solution in each radial interval
double lower_radius = 0.0;
for (unsigned i=0; i<mNumRadialBins; i++)
{
unsigned counter = 0;
double average_solution = 0.0;
for (std::map<double, CellPtr>::iterator iter = radius_cell_map.begin(); iter != radius_cell_map.end(); ++iter)
{
if (iter->first > lower_radius && iter->first <= radius_intervals[i])
{
average_solution += (iter->second)->GetCellData()->GetItem(mVariableName);
counter++;
}
}
if (counter != 0)
{
average_solution /= (double) counter;
}
// Write results to file
*this->mpOutStream << radius_intervals[i] << " " << average_solution << " ";
lower_radius = radius_intervals[i];
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::Visit(MeshBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation)
{
// Calculate the centre of the cell population
c_vector<double, SPACE_DIM> centre = pCellPopulation->GetCentroidOfCellPopulation();
// Calculate the distance between each node and the centre of the cell population, as well as the maximum of these
std::map<double, CellPtr> radius_cell_map;
double max_distance_from_centre = 0.0;
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = pCellPopulation->Begin();
cell_iter != pCellPopulation->End();
++cell_iter)
{
double distance = norm_2(pCellPopulation->GetLocationOfCellCentre(*cell_iter) - centre);
radius_cell_map[distance] = *cell_iter;
if (distance > max_distance_from_centre)
{
max_distance_from_centre = distance;
}
}
// Create vector of radius intervals
std::vector<double> radius_intervals;
for (unsigned i=0; i<mNumRadialBins; i++)
{
double upper_radius = max_distance_from_centre*((double) i+1)/((double) mNumRadialBins);
radius_intervals.push_back(upper_radius);
}
// Calculate PDE solution in each radial interval
double lower_radius = 0.0;
for (unsigned i=0; i<mNumRadialBins; i++)
{
unsigned counter = 0;
double average_solution = 0.0;
for (std::map<double, CellPtr>::iterator iter = radius_cell_map.begin(); iter != radius_cell_map.end(); ++iter)
{
if (iter->first > lower_radius && iter->first <= radius_intervals[i])
{
average_solution += (iter->second)->GetCellData()->GetItem(mVariableName);
counter++;
}
}
if (counter != 0)
{
average_solution /= (double) counter;
}
// Write results to file
*this->mpOutStream << radius_intervals[i] << " " << average_solution << " ";
lower_radius = radius_intervals[i];
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::Visit(CaBasedCellPopulation<SPACE_DIM>* pCellPopulation)
{
VisitAnyPopulation(pCellPopulation);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::Visit(NodeBasedCellPopulation<SPACE_DIM>* pCellPopulation)
{
VisitAnyPopulation(pCellPopulation);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::Visit(PottsBasedCellPopulation<SPACE_DIM>* pCellPopulation)
{
VisitAnyPopulation(pCellPopulation);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::Visit(VertexBasedCellPopulation<SPACE_DIM>* pCellPopulation)
{
VisitAnyPopulation(pCellPopulation);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::SetVariableName(std::string variableName)
{
mVariableName = variableName;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::string RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::GetVariableName() const
{
return mVariableName;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::SetNumRadialBins(unsigned numRadialBins)
{
mNumRadialBins = numRadialBins;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned RadialCellDataDistributionWriter<ELEMENT_DIM, SPACE_DIM>::GetNumRadialBins() const
{
return mNumRadialBins;
}
// Explicit instantiation
template class RadialCellDataDistributionWriter<1,1>;
template class RadialCellDataDistributionWriter<1,2>;
template class RadialCellDataDistributionWriter<2,2>;
template class RadialCellDataDistributionWriter<1,3>;
template class RadialCellDataDistributionWriter<2,3>;
template class RadialCellDataDistributionWriter<3,3>;
#include "SerializationExportWrapperForCpp.hpp"
// Declare identifier for the serializer
EXPORT_TEMPLATE_CLASS_ALL_DIMS(RadialCellDataDistributionWriter)
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
f1a874c3a58ce865869b961ac09a9f49f2c0fa4e | 2e66fc50589d666a0cd8b2938bf74178813dbdf9 | /testC++++/剑指 Offer 43. 1~n 整数中 1 出现的次数.hpp | bbcb3f837a0c107246311b048364840b8443bf05 | [] | no_license | kevinMkY/CPP_ALGO | dfae7e15d9ce75245b90ca1e6fe1e00ca13bee13 | 9bddfc60a9698e261aced5a4d6e4f90b3cc78865 | refs/heads/master | 2023-03-15T23:06:44.238375 | 2021-03-07T18:41:01 | 2021-03-07T18:41:01 | 294,155,521 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | hpp | //
// 剑指 Offer 43.hpp
// testC++++
//
// Created by yekaihua on 2021/2/27.
//
#ifndef ___Offer_43_hpp
#define ___Offer_43_hpp
void _offer_43_repeat_test();
#endif /* ___Offer_43_hpp */
| [
""
] | |
f6b6acfe8726886f8f01f6a7c8424d223eb55f7d | 41743b1a17944e44295072c5e16bec94ed0fd67a | /Artificial intelligence_暗棋遊戲/status.h | 5486f3cf568745a115d9070c11d27e1dde002d65 | [] | no_license | WeiYuChen0702/Artificial_intelligence | 0a182bbfd16a9e6b270c8a6f6e881dcd7ce52e72 | 5d4c3c05a032989ea68648c8ae543ec0025ada4f | refs/heads/master | 2023-04-09T13:35:29.840876 | 2021-04-18T13:17:41 | 2021-04-18T13:17:41 | 359,147,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | h | #ifndef STATUS_INCLUDED
#define STATUS_INCLUDED
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
class Status {
public:
Status();
Status(const Status& s);
~Status(void);
void board_setting(const int source[32]);
void colorswitch();
int get_color();
void set_color(const int cc);
void over(int moveout[2]);
void get_board(int dest[32]);
private:
int color;
int chessboard[32];
};
#endif // !status.h
#pragma once
| [
"andy07025@gmail.com"
] | andy07025@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.