hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
06de7b15e43ae69bb8a7e09d89b5ad3bd211abda | 3,379 | cpp | C++ | modules/parsers/nasm/NasmPreproc.cpp | rpavlik/assembler | 08480a71611c1b077630897a93407b7e371f8074 | [
"BSD-2-Clause"
] | 1 | 2019-12-17T01:47:08.000Z | 2019-12-17T01:47:08.000Z | modules/parsers/nasm/NasmPreproc.cpp | rpavlik/assembler | 08480a71611c1b077630897a93407b7e371f8074 | [
"BSD-2-Clause"
] | null | null | null | modules/parsers/nasm/NasmPreproc.cpp | rpavlik/assembler | 08480a71611c1b077630897a93407b7e371f8074 | [
"BSD-2-Clause"
] | null | null | null | //
// NASM-compatible preprocessor implementation
//
// Copyright (C) 2009 Peter Johnson
//
// Based on the LLVM Compiler Infrastructure
// (distributed under the University of Illinois Open Source License.
// See Copying/LLVM.txt for details).
//
// 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 AUTHOR AND OTHER 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 AUTHOR OR OTHER 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 "NasmPreproc.h"
#include "NasmLexer.h"
using namespace yasm;
using namespace yasm::parser;
NasmPreproc::NasmPreproc(Diagnostic& diags,
SourceManager& sm,
HeaderSearch& headers)
: Preprocessor(diags, sm, headers)
{
}
NasmPreproc::~NasmPreproc()
{
}
void
NasmPreproc::PreInclude(llvm::StringRef filename)
{
Predef p = { Predef::PREINC, filename };
m_predefs.push_back(p);
}
void
NasmPreproc::PredefineMacro(llvm::StringRef macronameval)
{
Predef p = { Predef::PREDEF, macronameval };
m_predefs.push_back(p);
}
void
NasmPreproc::UndefineMacro(llvm::StringRef macroname)
{
Predef p = { Predef::UNDEF, macroname };
m_predefs.push_back(p);
}
void
NasmPreproc::DefineBuiltin(llvm::StringRef macronameval)
{
Predef p = { Predef::BUILTIN, macronameval };
m_predefs.push_back(p);
}
/// RegisterBuiltinMacro - Register the specified identifier in the identifier
/// table and mark it as a builtin macro to be expanded.
static IdentifierInfo*
RegisterBuiltinMacro(NasmPreproc& pp, const char* name)
{
// Get the identifier.
IdentifierInfo* id = pp.getIdentifierInfo(name);
#if 0
// Mark it as being a macro that is builtin.
MacroInfo* mi = pp.AllocateMacroInfo(SourceLocation());
mi->setIsBuiltinMacro();
pp.setMacroInfo(id, mi);
#endif
return id;
}
void
NasmPreproc::RegisterBuiltinMacros()
{
m_LINE = RegisterBuiltinMacro(*this, "__LINE__");
m_FILE = RegisterBuiltinMacro(*this, "__FILE__");
m_DATE = RegisterBuiltinMacro(*this, "__DATE__");
m_TIME = RegisterBuiltinMacro(*this, "__TIME__");
m_BITS = RegisterBuiltinMacro(*this, "__BITS__");
}
Lexer*
NasmPreproc::CreateLexer(FileID fid, const llvm::MemoryBuffer* input_buffer)
{
return new NasmLexer(fid, input_buffer, *this);
}
| 30.718182 | 78 | 0.73069 | rpavlik |
06dfc0582f793f5f27279eb9d1d563a42e50c592 | 8,670 | hpp | C++ | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | 8 | 2016-11-17T00:39:03.000Z | 2016-11-29T14:46:27.000Z | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | #pragma once
#include <Collections/List.hpp>
#include <Core/String.hpp>
#include <Core/Manager.hpp>
#include "Platform.hpp"
#include "Module.hpp"
namespace Tenshi { namespace Compiler {
class MCodeGen;
// Linking target type (executable, dynamic library, static library)
enum class ELinkTarget
{
// No linking will take place
None,
// The output will be a native executable (Windows: .exe)
Executable,
// The output will be a dynamic library (Windows: .dll; Mac: .dylib; Linux: .so)
DynamicLibrary,
// The output will be a static library (.a)
StaticLibrary
};
// Environment the target is to run in
enum class ETargetEnv
{
// Text mode / terminal (e.g., server or pipeline tool)
Terminal,
// GUI mode (no default console box in Windows)
Windowed,
// Platform framework (e.g., phone or store app)
Platform
};
// Link-Time Optimization configuration
enum class ELTOConfig
{
Disabled,
Enabled
};
// Level of debugging support in compilation
enum class EDebugConfig
{
Disabled,
Enabled
};
// Level of optimization support in compilation
enum class EOptimizeConfig
{
Disabled,
PerFunction,
PerModule
};
// Settings for any given compilation
struct SCompileSettings
{
EDebugConfig Debug;
EOptimizeConfig Optimize;
inline bool DebugEnabled() const
{
return Debug != EDebugConfig::Disabled;
}
inline bool OptimizationEnabled() const
{
return Optimize != EOptimizeConfig::Disabled;
}
};
// A single compilation unit, with all relevant settings
struct SCompilation
{
typedef Ax::TList< SCompilation > List;
typedef Ax::TList< SCompilation >::Iterator Iter;
// Settings for the source file
SCompileSettings Settings;
// Input source filename
Ax::String SourceFilename;
// Optional object filename (outputs to the object file format)
Ax::String ObjectFilename;
// Optional bitcode filename (outputs to LLVM bitcode file; .bc)
Ax::String LLVMBCFilename;
// Optional IR listing filename (outputs text representation of the module's LLVM IR; .ll)
Ax::String IRListFilename;
// Optional assembly listing filename (outputs to target machine assembly representation; .s)
Ax::String ASListFilename;
// Modules referenced by this compilation (only valid while this is active)
SModule::IntrList Modules;
inline SCompilation()
: Settings()
, SourceFilename()
, ObjectFilename()
, LLVMBCFilename()
, IRListFilename()
, ASListFilename()
, Modules()
{
}
inline ~SCompilation()
{
}
bool Build();
};
// Token used when parsing the project file
struct SProjToken
{
const char * s;
const char * e;
inline bool IsQuote() const
{
return s != nullptr && *s != '\"';
}
inline bool Cmp( const char *pszCmp ) const
{
AX_ASSERT_NOT_NULL( s );
AX_ASSERT_NOT_NULL( pszCmp );
const Ax::uintptr myLen = e - s;
const Ax::uintptr n = strlen( pszCmp );
if( myLen != n ) {
return false;
}
return strncmp( s, pszCmp, n ) == 0;
}
inline bool operator==( const char *pszCmp ) const
{
return Cmp( pszCmp );
}
inline bool operator!=( const char *pszCmp ) const
{
return !Cmp( pszCmp );
}
bool Unquote( Ax::String &Dst, bool bAppend = false ) const;
};
// Diagnostic state for the project file parser
struct SProjDiagState
{
const char * pszFilename;
Ax::uint32 uLine;
const char * pszLineStart;
inline Ax::uint32 Column( const char *p ) const
{
return 1 + ( Ax::uint32 )( p - pszLineStart );
}
inline bool Error( const char *p, const char *pszError )
{
AX_ASSERT_NOT_NULL( p );
Ax::g_ErrorLog( pszFilename, uLine, Column( p ) ) += pszError;
return false;
}
inline bool Error( const char *p, const Ax::String &ErrorStr )
{
AX_ASSERT_NOT_NULL( p );
Ax::g_ErrorLog( pszFilename, uLine, Column( p ) ) += ErrorStr;
return false;
}
inline bool Error( const SProjToken &Tok, const char *pszError )
{
Ax::g_ErrorLog( pszFilename, uLine, Column( Tok.s ) ) += pszError;
return false;
}
inline bool Error( const SProjToken &Tok, const Ax::String &ErrorStr )
{
Ax::g_ErrorLog( pszFilename, uLine, Column( Tok.s ) ) += ErrorStr;
return false;
}
};
// Whether variable arguments can be used
enum class EVarArgs
{
No,
Yes
};
// Encapsulation of an individual target
class CProject
{
public:
typedef Ax::TList< CProject > List;
typedef Ax::TList< CProject >::Iterator Iter;
typedef Ax::TList< CProject * > PtrList;
typedef Ax::TList< CProject * >::Iterator PtrIter;
// Load the project's settings from a file
bool LoadFromFile( const char *pszFilename );
// Apply a single line (as though it were from a project file)
bool ApplyLine( const char *pszFilename, Ax::uint32 uLine, const char *pszLineStart, const char *pszLineEnd = nullptr );
// Build the project (returns false if it failed)
bool Build();
// Add the module to the current compilation/project
void TouchModule( SModule &Mod );
private:
friend class MProjects;
friend List;
CProject();
~CProject();
private:
friend class MCodeGen;
// Name of this project (this is mostly meaningless)
Ax::String m_Name;
// Path to the source files
Ax::String m_SourceDir;
// Path to the temporary object files
Ax::String m_ObjectDir;
// Full path to the target file
Ax::String m_TargetPath;
// Whether a prefix should be applied when setting the target path
bool m_bTargetPrefix:1;
// Whether a suffix should be applied when setting the target path
bool m_bTargetSuffix:1;
// Whether an assembly file listing should be produced
bool m_bASMList:1;
// Whether a LLVM IR file listing should be produced
bool m_bIRList:1;
// Target link type (e.g., executable)
ELinkTarget m_TargetType;
// Target environment (e.g., gui)
ETargetEnv m_TargetEnv;
// Link-time optimization (LTO) setting for this project
ELTOConfig m_LTO;
// Build information for this project
SBuildInfo m_BuildInfo;
// Current settings -- applied as the default settings when new translation units are added
SCompileSettings m_Settings;
// Compilation units
SCompilation::List m_Compilations;
// Current compilation
SCompilation * m_pCurrentCompilation;
// Modules used by this project (only valid while project is being built)
SModule::IntrList m_Modules;
AX_DELETE_COPYFUNCS(CProject);
};
// Project manager
class MProjects
{
public:
static MProjects &GetInstance();
bool AddProjectDirectory( const char *pszProjDir );
CProject &Current();
CProject *Add();
CProject *Load( const char *pszProjFile );
CProject *FindExisting( const char *pszName, const char *pszNameEnd = nullptr ) const;
inline CProject *FindExisting( const Ax::String &Name ) const
{
return FindExisting( Name.CString(), Name.CString() + Name.Len() );
}
// Remove the given project (freeing its memory) -- returns nullptr
CProject *Remove( CProject *pProj );
void Clear();
bool Build();
private:
Ax::TList< Ax::String > m_ProjectDirs;
CProject::List m_Projects;
CProject::Iter m_CurrProj;
MProjects();
~MProjects();
AX_DELETE_COPYFUNCS(MProjects);
};
static Ax::TManager< MProjects > Projects;
// Push a token to a static array of tokens
template< Ax::uintptr kNumTokens >
inline bool PushToken( SProjToken( &Tokens )[ kNumTokens ], Ax::uintptr &uIndex, const char *s, const char *e )
{
AX_ASSERT_NOT_NULL( s );
AX_ASSERT_NOT_NULL( e );
AX_ASSERT_MSG( Ax::uintptr( s ) < Ax::uintptr( e ), "Invalid token string" );
if( uIndex >= kNumTokens ) {
return false;
}
Tokens[ uIndex ].s = s;
Tokens[ uIndex ].e = e;
++uIndex;
return true;
}
// Check for a parameter in an array of parameters
template< Ax::uintptr kNumTokens >
inline bool HasParm( SProjToken( &Tokens )[ kNumTokens ], Ax::uintptr cTokens, SProjDiagState &Diag, const SProjToken &CmdTok, Ax::uintptr cParms = 1, EVarArgs VarArgs = EVarArgs::No, Ax::uintptr cMaxParms = ~Ax::uintptr( 0 ) )
{
AX_ASSERT( cTokens <= kNumTokens );
AX_ASSERT( &CmdTok >= &Tokens[0] && &CmdTok < &Tokens[kNumTokens] );
const Ax::uintptr uCmd = &CmdTok - &Tokens[0];
AX_ASSERT( uCmd < kNumTokens );
const Ax::uintptr cArgs = cTokens - uCmd - 1;
if( ( cArgs == cParms || ( VarArgs == EVarArgs::Yes && cArgs > cParms ) ) && cArgs <= cMaxParms ) {
return true;
}
if( cArgs < cParms ) {
Diag.Error( CmdTok, "Too few parameters" );
return false;
}
Diag.Error( CmdTok, "Too many parameters" );
return false;
}
}}
| 24.700855 | 228 | 0.677393 | NotKyon |
06e48436d3955f2cdcaadfc0b35ea6898116a8e8 | 2,995 | cc | C++ | chainerx_cc/chainerx/native/native_device/binary.cc | tkerola/chainer | 572f6eef2c3f1470911ac08332c2b5c3440edf44 | [
"MIT"
] | 1 | 2021-02-26T10:27:25.000Z | 2021-02-26T10:27:25.000Z | chainerx_cc/chainerx/native/native_device/binary.cc | tkerola/chainer | 572f6eef2c3f1470911ac08332c2b5c3440edf44 | [
"MIT"
] | null | null | null | chainerx_cc/chainerx/native/native_device/binary.cc | tkerola/chainer | 572f6eef2c3f1470911ac08332c2b5c3440edf44 | [
"MIT"
] | 2 | 2019-07-16T00:24:47.000Z | 2021-02-26T10:27:27.000Z | #include "chainerx/native/native_device.h"
#include "chainerx/array.h"
#include "chainerx/device.h"
#include "chainerx/dtype.h"
#include "chainerx/kernels/binary.h"
#include "chainerx/native/elementwise.h"
#include "chainerx/native/kernel_regist.h"
#include "chainerx/routines/binary.h"
#include "chainerx/scalar.h"
namespace chainerx {
namespace native {
namespace {
CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseAndKernel, { out = x1 & x2; }, VisitIntegralDtype);
class NativeBitwiseAndASKernel : public BitwiseAndASKernel {
public:
void Call(const Array& x1, Scalar x2, const Array& out) override {
Device& device = x1.device();
device.CheckDevicesCompatible(x1, out);
const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype());
VisitIntegralDtype(out.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
struct Impl {
void operator()(int64_t /*i*/, T x1, T& out) { out = x1 & x2; }
T x2;
};
Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out);
});
}
};
CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseAndASKernel, NativeBitwiseAndASKernel);
CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseOrKernel, { out = x1 | x2; }, VisitIntegralDtype);
class NativeBitwiseOrASKernel : public BitwiseOrASKernel {
public:
void Call(const Array& x1, Scalar x2, const Array& out) override {
Device& device = x1.device();
device.CheckDevicesCompatible(x1, out);
const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype());
VisitIntegralDtype(out.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
struct Impl {
void operator()(int64_t /*i*/, T x1, T& out) { out = x1 | x2; }
T x2;
};
Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out);
});
}
};
CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseOrASKernel, NativeBitwiseOrASKernel);
CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseXorKernel, { out = x1 ^ x2; }, VisitIntegralDtype);
class NativeBitwiseXorASKernel : public BitwiseXorASKernel {
public:
void Call(const Array& x1, Scalar x2, const Array& out) override {
Device& device = x1.device();
device.CheckDevicesCompatible(x1, out);
const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype());
VisitIntegralDtype(out.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
struct Impl {
void operator()(int64_t /*i*/, T x1, T& out) { out = x1 ^ x2; }
T x2;
};
Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out);
});
}
};
CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseXorASKernel, NativeBitwiseXorASKernel);
} // namespace
} // namespace native
} // namespace chainerx
| 36.52439 | 111 | 0.639399 | tkerola |
06ea19d888bd64669712ffba8122371d2f6b91e6 | 357 | cpp | C++ | acmicpc/1919.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/1919.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/1919.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
using namespace std;
int dict1[26], dict2[26], ans;
int main()
{
string a, b;
cin >> a >> b;
for (int i=0; i<a.length(); ++i)
dict1[a[i]-'a']++;
for (int i=0; i<b.length(); ++i)
dict2[b[i]-'a']++;
for (int i=0; i<26; ++i)
if (dict1[i] != dict2[i])
ans += abs(dict1[i] - dict2[i]);
cout << ans << '\n';
return 0;
}
| 14.28 | 35 | 0.507003 | juseongkr |
06ebf7ec5f14bcaef99d055302d23ecd80862c2d | 643 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-03-18T17:22:09.000Z | 2022-03-18T17:22:09.000Z | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | null | null | null | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-02-13T01:44:55.000Z | 2022-02-13T01:44:55.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/Scripting/Natives/Generated/ink/WidgetLogicController.hpp>
namespace RED4ext
{
namespace game::ui {
struct TutorialArea : ink::WidgetLogicController
{
static constexpr const char* NAME = "gameuiTutorialArea";
static constexpr const char* ALIAS = "TutorialArea";
uint8_t unk78[0x80 - 0x78]; // 78
CName bracketID; // 80
};
RED4EXT_ASSERT_SIZE(TutorialArea, 0x88);
} // namespace game::ui
using TutorialArea = game::ui::TutorialArea;
} // namespace RED4ext
| 25.72 | 76 | 0.744946 | jackhumbert |
06ec114313a6aa630fbfd8bba17b4652f84bf784 | 623 | cpp | C++ | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa11121 Base -2
// Rujia Liu
// 题意:已知正整数和负整数都有惟一的-2进制表示,而且不带符号位。输入整数n,输出它的-2进制表示
// 算法:按照b0, b1, ... 这样的顺序求解,每次对-2取余,然后把余数调整成0和1。
#include<cstdio>
void div_negative(int n, int m, int& q, int& r) {
q = n / m;
r = n - q * m;
while(r < 0) { r -= m; q++; }
}
int b[10];
void solve(int n) {
int k = 0, q, r;
do {
div_negative(n, -2, q, r);
b[k++] = r;
n = q;
} while(n);
for(int i = k-1; i >= 0; i--) printf("%d", b[i]);
printf("\n");
}
int main() {
int T, n, kase = 0;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
printf("Case #%d: ", ++kase);
solve(n);
}
return 0;
}
| 17.8 | 51 | 0.489567 | Anyrainel |
06f2f84d8bf40c097c7a64c438db1e020f4aa5a3 | 8,357 | cpp | C++ | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | #include "mitkPAIOUtil.h"
#include "mitkIOUtil.h"
#include "mitkImageReadAccessor.h"
#include <string>
#include <sstream>
#include <vector>
#include "mitkPAComposedVolume.h"
#include "mitkPASlicedVolumeGenerator.h"
#include "mitkPANoiseGenerator.h"
#include "mitkPAVolumeManipulator.h"
#include <mitkProperties.h>
#include <itkDirectory.h>
#include <itksys/SystemTools.hxx>
static std::vector<int> splitString(const std::string &s, const char* delim) {
std::vector<int> elems;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, *delim))
{
int numb;
std::stringstream(item) >> numb;
elems.push_back(numb);
}
return elems;
}
bool mitk::pa::IOUtil::DoesFileHaveEnding(std::string const &fullString, std::string const &ending) {
if (fullString.length() == 0 || ending.length() == 0 || fullString.length() < ending.length())
return false;
return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
}
mitk::pa::IOUtil::IOUtil() {}
mitk::pa::IOUtil::~IOUtil() {}
mitk::pa::Volume::Pointer mitk::pa::IOUtil::LoadNrrd(std::string filename, double blur)
{
if (filename.empty() || filename == "")
return nullptr;
mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(filename);
if (inputImage.IsNull())
return nullptr;
auto returnImage = Volume::New(inputImage);
VolumeManipulator::GaussianBlur3D(returnImage, blur);
return returnImage;
}
std::map<mitk::pa::IOUtil::Position, mitk::pa::Volume::Pointer>
mitk::pa::IOUtil::LoadFluenceContributionMaps(std::string foldername, double blur, int* progress, bool doLog10)
{
std::map<IOUtil::Position, Volume::Pointer> resultMap;
itk::Directory::Pointer directoryHandler = itk::Directory::New();
directoryHandler->Load(foldername.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string filename = std::string(directoryHandler->GetFile(fileIndex));
if (itksys::SystemTools::FileIsDirectory(filename))
continue;
if (!DoesFileHaveEnding(filename, ".nrrd"))
continue;
size_t s = filename.find("_p");
size_t e = filename.find("Fluence", s);
std::string sub = filename.substr(s + 2, e - s - 2);
std::vector<int> coords = splitString(sub, ",");
if (coords.size() != 3)
{
MITK_ERROR << "Some of the data to read was corrupted or did not match the " <<
"naming pattern *_pN,N,NFluence*.nrrd";
mitkThrow() << "Some of the data to read was corrupted or did not match the" <<
" naming pattern *_pN,N,NFluence*.nrrd";
}
else
{
MITK_DEBUG << "Extracted coords: " << coords[0] << "|" << coords[1] << "|" << coords[2] << " from string " << sub;
Volume::Pointer nrrdFile = LoadNrrd(foldername + filename, blur);
if (doLog10)
VolumeManipulator::Log10Image(nrrdFile);
resultMap[Position{ coords[0], coords[2] }] = nrrdFile;
*progress = *progress + 1;
}
}
return resultMap;
}
int mitk::pa::IOUtil::GetNumberOfNrrdFilesInDirectory(std::string directory)
{
return GetListOfAllNrrdFilesInDirectory(directory).size();
}
std::vector<std::string> mitk::pa::IOUtil::GetListOfAllNrrdFilesInDirectory(std::string directory, bool keepFileFormat)
{
std::vector<std::string> filenames;
itk::Directory::Pointer directoryHandler = itk::Directory::New();
directoryHandler->Load(directory.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string filename = std::string(directoryHandler->GetFile(fileIndex));
if (itksys::SystemTools::FileIsDirectory(filename))
continue;
if (!DoesFileHaveEnding(filename, ".nrrd"))
continue;
if (keepFileFormat)
{
filenames.push_back(filename);
}
else
{
filenames.push_back(filename.substr(0, filename.size() - 5));
}
}
return filenames;
}
std::vector<std::string> mitk::pa::IOUtil::GetAllChildfoldersFromFolder(std::string folderPath)
{
std::vector<std::string> returnVector;
itksys::Directory directoryHandler;
directoryHandler.Load(folderPath.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler.GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string foldername = std::string(directoryHandler.GetFile(fileIndex));
std::string filename = folderPath + "/" + foldername;
if (itksys::SystemTools::FileIsDirectory(filename))
{
if (foldername != std::string(".") && foldername != std::string(".."))
{
MITK_INFO << filename;
returnVector.push_back(filename);
}
continue;
}
//If there is a nrrd file in the directory we assume that a bottom level directory was chosen.
if (DoesFileHaveEnding(filename, ".nrrd"))
{
returnVector.clear();
returnVector.push_back(folderPath);
return returnVector;
}
}
return returnVector;
}
mitk::pa::InSilicoTissueVolume::Pointer mitk::pa::IOUtil::LoadInSilicoTissueVolumeFromNrrdFile(std::string nrrdFile)
{
MITK_INFO << "Initializing ComposedVolume by nrrd...";
auto inputImage = mitk::IOUtil::Load<mitk::Image>(nrrdFile);
auto tissueParameters = TissueGeneratorParameters::New();
unsigned int xDim = inputImage->GetDimensions()[1];
unsigned int yDim = inputImage->GetDimensions()[0];
unsigned int zDim = inputImage->GetDimensions()[2];
tissueParameters->SetXDim(xDim);
tissueParameters->SetYDim(yDim);
tissueParameters->SetZDim(zDim);
double xSpacing = inputImage->GetGeometry(0)->GetSpacing()[1];
double ySpacing = inputImage->GetGeometry(0)->GetSpacing()[0];
double zSpacing = inputImage->GetGeometry(0)->GetSpacing()[2];
if ((xSpacing - ySpacing) > mitk::eps || (xSpacing - zSpacing) > mitk::eps || (ySpacing - zSpacing) > mitk::eps)
{
throw mitk::Exception("Cannot handle unequal spacing.");
}
tissueParameters->SetVoxelSpacingInCentimeters(xSpacing);
mitk::PropertyList::Pointer propertyList = inputImage->GetPropertyList();
mitk::ImageReadAccessor readAccess0(inputImage, inputImage->GetVolumeData(0));
auto* m_AbsorptionArray = new double[xDim*yDim*zDim];
memcpy(m_AbsorptionArray, readAccess0.GetData(), xDim*yDim*zDim * sizeof(double));
auto absorptionVolume = Volume::New(m_AbsorptionArray, xDim, yDim, zDim, xSpacing);
mitk::ImageReadAccessor readAccess1(inputImage, inputImage->GetVolumeData(1));
auto* m_ScatteringArray = new double[xDim*yDim*zDim];
memcpy(m_ScatteringArray, readAccess1.GetData(), xDim*yDim*zDim * sizeof(double));
auto scatteringVolume = Volume::New(m_ScatteringArray, xDim, yDim, zDim, xSpacing);
mitk::ImageReadAccessor readAccess2(inputImage, inputImage->GetVolumeData(2));
auto* m_AnisotropyArray = new double[xDim*yDim*zDim];
memcpy(m_AnisotropyArray, readAccess2.GetData(), xDim*yDim*zDim * sizeof(double));
auto anisotropyVolume = Volume::New(m_AnisotropyArray, xDim, yDim, zDim, xSpacing);
Volume::Pointer segmentationVolume;
if (inputImage->GetDimension() == 4)
{
mitk::ImageReadAccessor readAccess3(inputImage, inputImage->GetVolumeData(3));
auto* m_SegmentationArray = new double[xDim*yDim*zDim];
memcpy(m_SegmentationArray, readAccess3.GetData(), xDim*yDim*zDim * sizeof(double));
segmentationVolume = Volume::New(m_SegmentationArray, xDim, yDim, zDim, xSpacing);
}
return mitk::pa::InSilicoTissueVolume::New(absorptionVolume, scatteringVolume,
anisotropyVolume, segmentationVolume, tissueParameters, propertyList);
}
mitk::pa::FluenceYOffsetPair::Pointer mitk::pa::IOUtil::LoadFluenceSimulation(std::string fluenceSimulation)
{
MITK_INFO << "Adding slice...";
mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(fluenceSimulation);
auto yOffsetProperty = inputImage->GetProperty("y-offset");
if (yOffsetProperty.IsNull())
mitkThrow() << "No \"y-offset\" property found in fluence file!";
std::string yOff = yOffsetProperty->GetValueAsString();
MITK_INFO << "Reading y Offset: " << yOff;
#ifdef __linux__
std::replace(yOff.begin(), yOff.end(), '.', ',');
#endif // __linux__
double yOffset = std::stod(yOff);
MITK_INFO << "Converted offset " << yOffset;
return FluenceYOffsetPair::New(Volume::New(inputImage), yOffset);
}
| 34.676349 | 120 | 0.703123 | wyyrepo |
06f2fdf42fc342f4fabfa0933e662c8482f1adfb | 4,425 | cpp | C++ | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | 9 | 2021-01-11T10:43:58.000Z | 2022-02-17T10:09:10.000Z | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | null | null | null | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | 5 | 2021-03-07T00:32:08.000Z | 2022-02-17T10:15:16.000Z | ////////////////////////////////////////////////////////////////////////////////
// IME - Infinite Motion Engine
//
// Copyright (c) 2020-2021 Kwena Mashamaite (kwena.mashamaite1@gmail.com)
//
// 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 "IME/common/Preference.h"
#include "IME/core/exceptions/Exceptions.h"
#include "IME/utility/DiskFileReader.h"
#include <sstream>
namespace ime {
namespace {
std::string convertToString(Preference::Type type) {
switch (type) {
case Preference::Type::Bool: return "BOOL";
case Preference::Type::String: return "STRING";
case Preference::Type::Int: return "INT";
case Preference::Type::Double: return "DOUBLE";
case Preference::Type::Float: return "FLOAT";
default:
return "UNSUPPORTED";
}
}
std::string convertToString(Preference::Type type, const Preference& pref) {
try {
switch (type) {
case Preference::Type::Bool: return std::to_string(pref.getValue<bool>());
case Preference::Type::String: return pref.getValue<std::string>();
case Preference::Type::Int: return std::to_string(pref.getValue<int>());
case Preference::Type::Double: return std::to_string(pref.getValue<double>());
case Preference::Type::Float: return std::to_string(pref.getValue<float>());
default:
return "UNSUPPORTED";
}
} catch (...) {
throw InvalidArgument("The value of '" + pref.getKey() + "' is not a '" + convertToString(type) + "'");
}
}
}
Preference::Preference(const std::string &key, Preference::Type type) :
property_{key},
type_{type}
{
if (property_.getName().empty())
throw InvalidArgument("Preference key cannot be an an empty string");
if (property_.getName().find_first_of(' ') != std::string::npos)
throw InvalidArgument("Preference key must not have whitespaces");
}
Preference::Type Preference::getType() const {
return type_;
}
const std::string &Preference::getKey() const {
return property_.getName();
}
bool Preference::hasValue() const {
return property_.hasValue();
}
void Preference::setDescription(const std::string &description) {
if (description.find_first_of('\n') != std::string::npos)
throw InvalidArgument("Preference description must not be multiline");
description_ = description;
}
const std::string &Preference::getDescription() const {
return description_;
}
void savePref(const Preference &pref, const std::string &filename) {
std::string entry{pref.getDescription().empty() ? "\n\n" : "\n\n# " + pref.getDescription() + "\n"};
entry += pref.getKey() + ":" + convertToString(pref.getType()) + "=" + convertToString(pref.getType(), pref);
auto configurations = std::stringstream{entry};
utility::DiskFileReader().writeToFile(configurations, filename, utility::WriteMode::Append);
}
}
| 43.382353 | 119 | 0.602938 | KwenaMashamaite |
06f304c1aee397cbff5bbe9e1d0e961873b9eae0 | 443 | cpp | C++ | September LeetCode Challenge/Day_24.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | September LeetCode Challenge/Day_24.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | September LeetCode Challenge/Day_24.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char, int>mp;
for (int i = 0; i < s.length(); i++)
{
mp[s[i]]++;
}
char x;
for (int i = 0; i < t.length(); i++)
{
if (!mp[t[i]]) {
x = t[i];
break;
}
else
mp[t[i]]--;
}
return x;
}
}; | 21.095238 | 48 | 0.334086 | mishrraG |
06f36dcb18f781b9264b1e5d2a730ba728f28ac4 | 453 | hpp | C++ | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | 1 | 2016-12-09T08:00:01.000Z | 2016-12-09T08:00:01.000Z | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | 1 | 2016-12-09T08:03:43.000Z | 2018-11-15T15:04:35.000Z | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | null | null | null | #include <cstdlib>
#pragma once
enum class Ore {
COPPER,
TIN,
IRON,
SILVER,
GOLD,
RUBY,
DIAMOND,
ROCK,
NUM_ORE_TYPES,
NONE
};
class Block {
Ore ore;
bool _drilled;
bool _drillable;
public:
Block(bool);
size_t texture();
bool drillable();
bool drilled();
bool has_ore();
void drill();
void reserve();
static void load();
};
namespace ORE {
int value_of(Ore);
}
| 12.243243 | 23 | 0.565121 | marchelzo |
06f52b78d0d958cbf5abc481772fc1658500a3a5 | 194 | cpp | C++ | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | 8 | 2019-10-09T14:33:42.000Z | 2020-12-03T00:49:29.000Z | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | #include<iostream> // Same as P4-1/9
using namespace std;
int main(){
int s=0,n,i=2,q,j=2;
for(cin>>n;s+i<=n;s+=i++);
for(i--;j++<=i;cout<<j+((q=i-n+s)?-(j<=-~q):j>i)<<" \n"[j>i]);
} | 27.714286 | 66 | 0.484536 | Guyutongxue |
06f877892408d012f4926c6eb73b5e69a9b85c60 | 3,147 | cpp | C++ | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 2 | 2016-04-28T10:01:02.000Z | 2016-06-13T20:27:16.000Z | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 1 | 2016-06-13T20:52:23.000Z | 2016-06-14T00:09:19.000Z | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 2 | 2017-07-26T13:13:48.000Z | 2017-10-18T13:04:41.000Z | /*
Copyright (c), Helios
All rights reserved.
Distributed under a permissive license. See COPYING.txt for details.
*/
#include "RotateDialog.h"
#include "Misc.h"
#include <cmath>
#include <QMessageBox>
const double log_125 = log(1.25);
RotateDialog::RotateDialog(MainWindow &parent) :
QDialog(parent.centralWidget()),
ui(new Ui_RotateDialog),
main_window(parent),
result(false),
in_do_transform(false){
this->setModal(true);
this->ui->setupUi(this);
this->transform = parent.get_image_transform();
connect(this->ui->rotation_slider, SIGNAL(valueChanged(int)), this, SLOT(rotation_slider_changed(int)));
connect(this->ui->scale_slider, SIGNAL(valueChanged(int)), this, SLOT(scale_slider_changed(int)));
connect(this->ui->buttonBox, SIGNAL(rejected()), this, SLOT(rejected_slot()));
this->last_scale = this->original_scale = this->scale = this->main_window.get_image_zoom();
this->rotation_slider_changed(0);
this->set_scale();
this->geometry_set = false;
auto desktop = this->main_window.get_app().desktop();
auto h = 22 * desktop->logicalDpiY() / 96;
this->ui->rotation_slider->setMinimumHeight(h);
this->ui->scale_slider->setMinimumHeight(h);
auto image_size = this->main_window.get_image().size();
auto min_zoom = 1.0 / image_size.width();
auto current_min = pow(1.25, this->ui->scale_slider->minimum() / 1000.0);
if (min_zoom > current_min)
this->ui->scale_slider->setMinimum((int)ceil(log(min_zoom) / log_125 * 1000.0));
}
void RotateDialog::resizeEvent(QResizeEvent *e){
if (this->geometry_set){
QDialog::resizeEvent(e);
return;
}
this->geometry_set = true;
auto size = this->size();
size.setWidth(size.height() * 400 / 143);
this->setMinimumWidth(size.width());
this->setMinimumHeight(size.height());
this->setMaximumHeight(size.height());
this->updateGeometry();
}
void RotateDialog::do_transform(bool set_zoom){
auto scale = this->main_window.set_image_transform(this->transform * QMatrix().rotate(this->rotation));
if (!this->main_window.current_zoom_mode_is_auto() || set_zoom && !this->in_do_transform)
this->main_window.set_image_zoom(this->scale);
else{
this->in_do_transform = true;
this->scale = scale;
this->set_scale();
this->in_do_transform = false;
}
}
void RotateDialog::set_scale(){
this->ui->scale_slider->setValue((int)(log(this->scale) / log_125 * 1000.0));
this->set_scale_label();
}
void RotateDialog::rotation_slider_changed(int value){
double theta = value / 100.0;
QString s = QString::fromStdString(itoac(theta));
s += " deg";
this->ui->rotation_label->setText(s);
this->rotation = theta;
this->do_transform();
}
void RotateDialog::set_scale_label(){
QString s = QString::fromStdString(itoac(this->scale));
s += "x";
this->ui->scale_label->setText(s);
}
void RotateDialog::scale_slider_changed(int value){
double x = value / 1000.0;
this->scale = pow(1.25, x);
this->set_scale_label();
this->do_transform(true);
}
void RotateDialog::rejected_slot(){
this->rotation = 0;
this->scale = this->original_scale;
this->do_transform();
}
| 31.158416 | 106 | 0.698443 | Helios-vmg |
06fb25a25110444df4a5f2b1ec74b8e9ac82351f | 799 | cpp | C++ | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | #include "flopch.h"
#include "OpenGLContext.h"
#include "Flongo/Core.h"
#include "Flongo/Log.h"
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace Flongo
{
OpenGLContext::OpenGLContext(GLFWwindow* windowHandle)
: windowHandle(windowHandle)
{
FLO_CORE_ASSERT(windowHandle, "windowHandle is null!");
}
void OpenGLContext::init()
{
glfwMakeContextCurrent(windowHandle);
int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
FLO_CORE_ASSERT(status, "Failed to initialize Glad!");
FLO_CORE_INFO("Vendor: {0}", glGetString(GL_VENDOR));
FLO_CORE_INFO("OpenGL Info:");
FLO_CORE_INFO("Renderer: {0}", glGetString(GL_RENDERER));
FLO_CORE_INFO("Version: {0}", glGetString(GL_VERSION));
}
void OpenGLContext::swapBuffers()
{
glfwSwapBuffers(windowHandle);
}
} | 23.5 | 66 | 0.740926 | Hans-Jeiger |
06fc1dfda4198d9101269691cbdca967bf8ebbf1 | 734 | hpp | C++ | templates/Group.hpp | emiliev/IS-OOP-2018 | f280baff30e84b04b3aeec64af2f8eb0e785cb16 | [
"MIT"
] | null | null | null | templates/Group.hpp | emiliev/IS-OOP-2018 | f280baff30e84b04b3aeec64af2f8eb0e785cb16 | [
"MIT"
] | null | null | null | templates/Group.hpp | emiliev/IS-OOP-2018 | f280baff30e84b04b3aeec64af2f8eb0e785cb16 | [
"MIT"
] | null | null | null | //
// Group.hpp
// templates
//
// Created by Emil Iliev on 4/13/18.
// Copyright © 2018 Emil Iliev. All rights reserved.
//
#ifndef Group_hpp
#define Group_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include "DynamicArray.hpp"
#include "Student.hpp"
using namespace std;
#define MAX_BUFFER_SIZE 1000
class Group {
DynamicArray<Student> students;
public:
Group(){}
Student& getStudentAt(int index);
int numStudents();
int studentCap();
void readFromFile(char* fileName);
void addStudent(const Student& student, bool shouldWriteToFile = true);
void writeToFile(char* fileName, const Student& other);
void print();
};
#endif /* Group_hpp */
| 18.35 | 75 | 0.685286 | emiliev |
06fc94d0f452cd8af8f9ab9fdfea9384bc463e90 | 9,264 | hh | C++ | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 379 | 2015-01-02T20:27:33.000Z | 2022-03-26T23:18:17.000Z | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 81 | 2015-01-08T13:18:52.000Z | 2021-12-21T14:02:21.000Z | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 75 | 2015-01-06T09:08:20.000Z | 2021-12-17T09:40:18.000Z | class DictionaryLike {
public:
DictionaryLike(RichNode self) : _self(self) {}
DictionaryLike(UnstableNode& self) : _self(self) {}
DictionaryLike(StableNode& self) : _self(self) {}
bool isDictionary(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().isDictionary(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::isDictionary", "isDictionary", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().isDictionary(_self, vm);
}
}
bool dictIsEmpty(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictIsEmpty(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictIsEmpty", "dictIsEmpty", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictIsEmpty(_self, vm);
}
}
bool dictMember(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictMember(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictMember", "dictMember", feature, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictMember(_self, vm, feature);
}
}
class mozart::UnstableNode dictGet(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictGet(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictGet", "dictGet", feature, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictGet(_self, vm, feature);
}
}
class mozart::UnstableNode dictCondGet(VM vm, class mozart::RichNode feature, class mozart::RichNode defaultValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictCondGet(vm, feature, defaultValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictCondGet", "dictCondGet", feature, defaultValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictCondGet(_self, vm, feature, defaultValue);
}
}
void dictPut(VM vm, class mozart::RichNode feature, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictPut(vm, feature, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictPut", "dictPut", feature, newValue))
return;
}
return Interface<DictionaryLike>().dictPut(_self, vm, feature, newValue);
}
}
class mozart::UnstableNode dictExchange(VM vm, class mozart::RichNode feature, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictExchange(vm, feature, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictExchange", "dictExchange", feature, newValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictExchange(_self, vm, feature, newValue);
}
}
class mozart::UnstableNode dictCondExchange(VM vm, class mozart::RichNode feature, class mozart::RichNode defaultValue, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictCondExchange(vm, feature, defaultValue, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictCondExchange", "dictCondExchange", feature, defaultValue, newValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictCondExchange(_self, vm, feature, defaultValue, newValue);
}
}
void dictRemove(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictRemove(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictRemove", "dictRemove", feature))
return;
}
return Interface<DictionaryLike>().dictRemove(_self, vm, feature);
}
}
void dictRemoveAll(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictRemoveAll(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictRemoveAll", "dictRemoveAll"))
return;
}
return Interface<DictionaryLike>().dictRemoveAll(_self, vm);
}
}
class mozart::UnstableNode dictKeys(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictKeys(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictKeys", "dictKeys", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictKeys(_self, vm);
}
}
class mozart::UnstableNode dictEntries(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictEntries(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictEntries", "dictEntries", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictEntries(_self, vm);
}
}
class mozart::UnstableNode dictItems(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictItems(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictItems", "dictItems", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictItems(_self, vm);
}
}
class mozart::UnstableNode dictClone(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictClone(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictClone", "dictClone", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictClone(_self, vm);
}
}
protected:
RichNode _self;
};
| 40.103896 | 201 | 0.635255 | Ahzed11 |
06fe339a1f9eac884c9ca0977b03760bc7013dda | 1,638 | cpp | C++ | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | #include "windz/base/Thread.h"
#include "windz/base/Util.h"
#include "windz/net/Channel.h"
#include "windz/net/EventLoop.h"
#include "windz/net/TcpClient.h"
#include <iostream>
#include <memory>
#include <vector>
using namespace windz;
int main(int argc, char **argv) {
EventLoop loop;
InetAddr addr("127.0.0.1", 2019);
TcpClient client(&loop, addr, "client");
auto channel = std::make_shared<Channel>(&loop, STDIN_FILENO);
client.SetConnectionCallBack([&loop, channel](const TcpConnectionPtr &conn) {
std::cout << conn->local_addr().IpPortString() << " -> " << conn->peer_addr().IpPortString()
<< (conn->connected() ? " Connect.\n" : " Disconnect.\n");
if (conn->connected()) {
std::weak_ptr<TcpConnection> weak_conn(conn);
channel->SetReadHandler([weak_conn, channel] {
auto conn = weak_conn.lock();
if (conn) {
std::string msg;
util::SetNonBlockAndCloseOnExec(STDIN_FILENO);
net::ReadFd(STDIN_FILENO, msg);
conn->Send(msg);
}
});
channel->SetErrorHandler([conn] {
conn->Send("STDIN EOF ERROR\n");
sleep(60);
});
channel->EnableRead();
} else {
channel->DisableRead();
}
});
client.SetMessageCallBack([](const TcpConnectionPtr &conn, Buffer &buffer) {
std::string msg(buffer.ReadAll());
std::cout << msg << std::flush;
});
client.EnableRetry();
client.Connect();
loop.Loop();
}
| 32.76 | 100 | 0.551893 | Crystalwindz |
06fe9b2301f34ae2c75be2b2b4cc8705da75a3ca | 2,832 | cpp | C++ | copasi/bindings/cpp_examples/changeValues/changeValues.cpp | MedAnisse/COPASI | 561f591f8231b1c4880ce554d0197ff21ef4734c | [
"Artistic-2.0"
] | 64 | 2015-03-14T14:06:18.000Z | 2022-02-04T23:19:08.000Z | copasi/bindings/cpp_examples/changeValues/changeValues.cpp | MedAnisse/COPASI | 561f591f8231b1c4880ce554d0197ff21ef4734c | [
"Artistic-2.0"
] | 4 | 2017-08-16T10:26:46.000Z | 2020-01-08T12:05:54.000Z | copasi/bindings/cpp_examples/changeValues/changeValues.cpp | MedAnisse/COPASI | 561f591f8231b1c4880ce554d0197ff21ef4734c | [
"Artistic-2.0"
] | 28 | 2015-04-16T14:14:59.000Z | 2022-03-28T12:04:14.000Z | // Copyright (C) 2019 - 2021 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
/**
* This reads a copasi file and a parameter file, assigns those parameters
* and writes them into a new COPASI file
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#define COPASI_MAIN
#include "copasi/CopasiTypes.h"
using namespace std;
/**
* This function will read in reaction parameters in the form
*
* reaction_id parameterId value
*
* and will reparameterize the model with those values
*/
void changeParameters(CDataModel* pDataModel, const std::string& parameterSet)
{
ifstream ifs(parameterSet.c_str(), std::ios_base::in);
if (!ifs.good())
{
cerr << "Couldn't open file with parameters" << endl;
exit(1);
}
auto& reactions = pDataModel->getModel()->getReactions();
while (ifs.good())
{
string reactionId; string parameterId; double value;
ifs >> reactionId >> parameterId >> value;
if (reactionId.empty() || parameterId.empty()) break;
// find model value ... change value
try
{
reactions[reactionId].setParameterValue(parameterId, value);
reactions[reactionId].compile();
pDataModel->getModel()->setCompileFlag();
}
catch (...)
{
cerr << "Couldn't change parameter '" << reactionId << "." << parameterId << "'." << endl;
exit(1);
}
}
pDataModel->getModel()->compileIfNecessary(NULL);
}
int main(int argc, char** argv)
{
// initialize the backend library
CRootContainer::init(argc, argv);
assert(CRootContainer::getRoot() != NULL);
// create a new datamodel
CDataModel* pDataModel = CRootContainer::addDatamodel();
assert(CRootContainer::getDatamodelList()->size() == 1);
// the only argument to the main routine should be the name of an SBML file
if (argc != 4)
{
std::cerr << "Usage: changeValues <copasi file> <parameter set> <output copasi file>" << std::endl;
CRootContainer::destroy();
return 1;
}
std::string filename = argv[1];
std::string parameterSet = argv[2];
std::string oututFile = argv[3];
bool result = false;
try
{
// load the model without progress report
result = pDataModel->loadFromFile(filename);
}
catch (...)
{
}
if (!result)
{
std::cerr << "Error while opening the file named \"" << filename << "\"." << std::endl;
CRootContainer::destroy();
return 1;
}
// changeParameters
changeParameters(pDataModel, parameterSet);
// save to output file
pDataModel->saveModel(oututFile, NULL, true);
// clean up the library
CRootContainer::destroy();
return 0;
}
| 24.842105 | 105 | 0.641596 | MedAnisse |
06ff64fed4b79226cbc69a7c9129b5ce117d3a04 | 4,492 | cpp | C++ | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | 2 | 2022-01-18T21:31:01.000Z | 2022-01-20T21:02:09.000Z | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | #include "implementation/engine/components/RigidDynamicComponent.hpp"
#include "implementation/misc/Logger.hpp"
#include <extensions/PxDefaultStreams.h>
#include <extensions/PxRigidActorExt.h>
#include <PxMaterial.h>
#define PX_RELEASE(x) if(x) { x->release(); x = nullptr; }
namespace orbit
{
RigidDynamicComponent::RigidDynamicComponent(GameObject* boundObject, ResourceId meshId) :
Physically(boundObject)
{
m_mesh = std::make_shared<Mesh<Vertex>>();
m_mesh->SetId(meshId);
m_mesh->Load();
}
RigidDynamicComponent::~RigidDynamicComponent()
{
ORBIT_INFO_LEVEL(ORBIT_LEVEL_DEBUG, "Releasing RigidStaticComponent");
std::vector<PxMaterial*> materials;
materials.resize(m_shape->getNbMaterials());
m_shape->getMaterials(materials.data(), materials.size());
PX_RELEASE(m_shape);
for (auto material : materials)
{
PX_RELEASE(material);
}
materials.clear();
m_bodies.clear();
m_nextId = 0;
}
void RigidDynamicComponent::Update(size_t millis)
{
for (auto& [id, body] : m_bodies)
{
if (!body->isSleeping())
{
m_transforms[id]->SetTranslation(orbit::Math<float>::PxToEigen(body->getGlobalPose().p));
m_transforms[id]->SetRotation(orbit::Math<float>::PxToEigen(body->getGlobalPose().q));
}
}
}
std::shared_ptr<RigidDynamicComponent> RigidDynamicComponent::create(GameObject* boundObject, ResourceId meshId)
{
return std::make_shared<RigidDynamicComponent>(boundObject, meshId);
}
void RigidDynamicComponent::CookBody(MaterialProperties material_p, Vector3f meshScale, size_t vertexPositionOffset)
{
const auto& vertexData = m_mesh->GetVertexBuffer();
const auto& indexData = m_mesh->GetIndexBuffer();
std::vector<Vector3f> colliderPositions;
colliderPositions.reserve(vertexData->NumVertices());
const auto stride = vertexData->GetBufferSize() / vertexData->NumVertices();
for (auto i = 0u; i < vertexData->NumVertices(); ++i)
{
auto position = vertexData->GetVertices().at(i).position;
colliderPositions.emplace_back(position);
}
PxTriangleMeshDesc meshDesc;
meshDesc.points.count = static_cast<PxU32>(colliderPositions.size());
meshDesc.points.stride = sizeof(Vector3f);
meshDesc.points.data = colliderPositions.data();
meshDesc.triangles.count = static_cast<PxU32>(indexData->NumIndices() / 3);
meshDesc.triangles.stride = 3 * sizeof(uint32_t);
meshDesc.triangles.data = indexData->GetIndices().data();
PxDefaultMemoryOutputStream writeBuffer;
PxTriangleMeshCookingResult::Enum result;
auto status = Engine::Get()->GetCooking()->cookTriangleMesh(meshDesc, writeBuffer, &result);
if (status)
{
PxDefaultMemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize());
auto colliderMesh = Engine::Get()->GetPhysics()->createTriangleMesh(readBuffer);
auto material = Engine::Get()->GetPhysics()->createMaterial(
material_p.staticFriction,
material_p.dynamicFriction,
material_p.restitution
);
m_geometry.triangleMesh = colliderMesh;
m_geometry.scale = PxMeshScale(Math<float>::EigenToPx3(meshScale));
m_shape = std::unique_ptr<PxShape, PxDelete<PxShape>>(ENGINE->GetPhysics()->createShape(
m_geometry,
*material,
false,
PxShapeFlag::eSCENE_QUERY_SHAPE));
}
else
{
ORBIT_ERROR("Failed to cook triangle mesh.");
}
}
unsigned RigidDynamicComponent::AddActor(std::shared_ptr<Transform> transform)
{
auto body = ENGINE->GetPhysics()->createRigidDynamic(PxTransform(
Math<float>::EigenToPx3(transform->GetCombinedTranslation()),
Math<float>::EigenToPx(Quaternionf(transform->GetCombinedRotation()))));
auto id = m_nextId++;
m_bodies[id] = std::unique_ptr<PxRigidDynamic, PxDelete<PxRigidDynamic>>(body);
m_transforms[id] = transform;
body->attachShape(*m_shape);
body->setMass(0.5f);
ENGINE->GetPhysXScene()->addActor(*body);
return id;
}
} | 37.433333 | 120 | 0.633793 | LarsHagemann |
6600c25fe9b97c39731e2b1d07ad13cdc66e18de | 490 | cpp | C++ | LeetCode/784.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | LeetCode/784.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | LeetCode/784.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
private:
int t;
vector<string> ans;
public:
void backtrack(string s,int i){
if(i==t)
ans.push_back(s);
else{
if(s[i]<='z' && s[i]>='a'){
backtrack(s,i+1);
s[i] = s[i]-'a'+'A';
backtrack(s,i+1);
}else if(s[i]<='Z' && s[i]>='A'){
backtrack(s,i+1);
s[i] = s[i]-'A'+'a';
backtrack(s,i+1);
}else
backtrack(s,i+1);
}
}
vector<string> letterCasePermutation(string S) {
t = S.size();
backtrack(S,0);
return ans;
}
}; | 17.5 | 52 | 0.514286 | LauZyHou |
6602e314d374652be6b1e721f6135f0c129265e2 | 3,126 | cc | C++ | Fireworks/ParticleFlow/plugins/FWPFClusterLegoProxyBuilder.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Fireworks/ParticleFlow/plugins/FWPFClusterLegoProxyBuilder.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Fireworks/ParticleFlow/plugins/FWPFClusterLegoProxyBuilder.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "FWPFClusterLegoProxyBuilder.h"
#include "Fireworks/Candidates/interface/FWLegoCandidate.h"
//______________________________________________________________________________
void
FWPFClusterLegoProxyBuilder::localModelChanges( const FWModelId &iId, TEveElement *parent, FWViewType::EType viewType, const FWViewContext *vc )
{
// Line set marker is not the same colour as line, fixed here
if( ( parent )->HasChildren() )
{
for( TEveElement::List_i j = parent->BeginChildren(); j != parent->EndChildren(); j++ )
{
FWLegoCandidate *cluster = dynamic_cast<FWLegoCandidate*>( *j );
cluster->SetMarkerColor( FWProxyBuilderBase::item()->modelInfo( iId.index() ).displayProperties().color() );
cluster->ElementChanged();
}
}
}
//______________________________________________________________________________
void
FWPFClusterLegoProxyBuilder::scaleProduct( TEveElementList* parent, FWViewType::EType type, const FWViewContext* vc )
{
for (TEveElement::List_i i = parent->BeginChildren(); i!= parent->EndChildren(); ++i)
{
if ((*i)->HasChildren())
{
TEveElement* el = (*i)->FirstChild(); // there is only one child added in this proxy builder
FWLegoCandidate *cluster = dynamic_cast<FWLegoCandidate*>( el );
cluster->updateScale(vc, context());
}
}
}
//______________________________________________________________________________
void
FWPFClusterLegoProxyBuilder::sharedBuild( const reco::PFCluster &iData, TEveElement &oItemHolder, const FWViewContext *vc )
{
TEveVector centre = TEveVector( iData.x(), iData.y(), iData.z() );
float energy = iData.energy();
float et = FWPFMaths::calculateEt( centre, energy );
float pt = et;
float eta = iData.eta();
float phi = iData.phi();
context().voteMaxEtAndEnergy( et, energy );
FWLegoCandidate *cluster = new FWLegoCandidate( vc, FWProxyBuilderBase::context(), energy, et, pt, eta, phi );
cluster->SetMarkerColor( FWProxyBuilderBase::item()->defaultDisplayProperties().color() );
setupAddElement( cluster, &oItemHolder );
}
//______________________________ECAL____________________________________________
void
FWPFEcalClusterLegoProxyBuilder::build( const reco::PFCluster &iData, unsigned int iIndex, TEveElement &oItemHolder, const FWViewContext *vc )
{
PFLayer::Layer layer = iData.layer();
if( layer < 0 )
sharedBuild( iData, oItemHolder, vc );
}
//______________________________HCAL____________________________________________
void
FWPFHcalClusterLegoProxyBuilder::build( const reco::PFCluster &iData, unsigned int iIndex, TEveElement &oItemHolder, const FWViewContext *vc )
{
PFLayer::Layer layer = iData.layer();
if( layer > 0 )
sharedBuild( iData, oItemHolder, vc );
}
//______________________________________________________________________________
REGISTER_FWPROXYBUILDER( FWPFEcalClusterLegoProxyBuilder, reco::PFCluster, "PF Cluster", FWViewType::kLegoPFECALBit );
REGISTER_FWPROXYBUILDER( FWPFHcalClusterLegoProxyBuilder, reco::PFCluster, "PF Cluster", FWViewType::kLegoBit );
| 42.243243 | 144 | 0.740883 | bisnupriyasahu |
6609650e7ec6d5aeeeeb2b420cbeed07e3e68d60 | 739 | cpp | C++ | StaticBody.cpp | elix22/Urho3DPhysX | 4f0a21e76ab4aa1779e273cfe64122699e08f5bc | [
"MIT"
] | 8 | 2019-08-21T09:23:36.000Z | 2021-12-23T07:07:57.000Z | StaticBody.cpp | elix22/Urho3DPhysX | 4f0a21e76ab4aa1779e273cfe64122699e08f5bc | [
"MIT"
] | 2 | 2019-08-21T13:58:08.000Z | 2019-08-25T11:57:29.000Z | StaticBody.cpp | elix22/Urho3DPhysX | 4f0a21e76ab4aa1779e273cfe64122699e08f5bc | [
"MIT"
] | 6 | 2019-08-18T20:54:15.000Z | 2020-08-11T02:35:37.000Z | #include "StaticBody.h"
#include "Physics.h"
#include <Urho3D/IO/Log.h>
#include <Urho3D/Core/Context.h>
Urho3DPhysX::StaticBody::StaticBody(Context * context) : RigidActor(context)
{
auto* physics = GetSubsystem<Physics>();
if (physics)
{
auto* px = physics->GetPhysics();
if (px)
{
actor_ = px->createRigidStatic(PxTransform(PxVec3(0.0f, 0.0f, 0.0f)));
actor_->userData = this;
}
}
else
{
URHO3D_LOGERROR("Physics subsystem must be registred before creating physx objects.");
}
}
Urho3DPhysX::StaticBody::~StaticBody()
{
}
void Urho3DPhysX::StaticBody::RegisterObject(Context * context)
{
context->RegisterFactory<StaticBody>("PhysX");
}
| 23.09375 | 94 | 0.637348 | elix22 |
660acd622b4db8af5a7e6b68eb959bc6070d760e | 266 | cpp | C++ | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "activityxingzuoyiji.hpp"
#include "config/logicconfigmanager.hpp"
ActivityXingzuoYiji::ActivityXingzuoYiji(ActivityManager *activity_manager)
: Activity(activity_manager, ACTIVITY_TYPE_XINGZUOYIJI)
{
}
ActivityXingzuoYiji::~ActivityXingzuoYiji()
{
}
| 16.625 | 75 | 0.823308 | mage-game |
660cd55dc07f60003792f554033b93e4caa76776 | 3,228 | cpp | C++ | TAO/examples/RTCORBA/Activity/Periodic_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/examples/RTCORBA/Activity/Periodic_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/examples/RTCORBA/Activity/Periodic_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | //$Id: Periodic_Task.cpp 83023 2008-10-09 18:34:53Z johnnyw $
#include "Periodic_Task.h"
#include "ace/High_Res_Timer.h"
#include "tao/debug.h"
#include "Task_Stats.h"
Periodic_Task::Periodic_Task (void)
:barrier_ (0),
task_priority_ (0),
period_ (0),
exec_time_ (0),
phase_ (0),
iter_ (0),
load_ (0),
task_stats_ (0)
{
}
Periodic_Task::~Periodic_Task ()
{
delete task_stats_;
}
int
Periodic_Task::init_task (ACE_Arg_Shifter& arg_shifter)
{
const ACE_TCHAR *current_arg = 0;
while (arg_shifter.is_anything_left ())
{
if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-JobName"))))
{
name_ = ACE_TEXT_ALWAYS_CHAR(current_arg);
arg_shifter.consume_arg ();
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Priority"))))
{
task_priority_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Period"))))
{
period_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-ExecTime"))))
{
exec_time_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Phase"))))
{
phase_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Iter"))))
{
iter_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
// create the stat object.
ACE_NEW_RETURN (task_stats_, Task_Stats (iter_), -1);
if (task_stats_->init () == -1)
return -1;
}
else if (0 != (current_arg = arg_shifter.get_the_parameter (ACE_TEXT("-Load"))))
{
load_ = ACE_OS::atoi (current_arg);
arg_shifter.consume_arg ();
return 0;
}
else
{
ACE_DEBUG ((LM_DEBUG, "parse Task unknown option %s\n",
arg_shifter.get_current ()));
if (TAO_debug_level > 0)
ACE_DEBUG ((LM_DEBUG, "name %s, priority %d, period %duS, exec_time %duS, phase %duS, iter %d, load %d\n",
name_.c_str(), task_priority_, period_, exec_time_, phase_, iter_, load_));
break;
}
}
return 0;
}
const char*
Periodic_Task::job (void)
{
return name_.c_str ();
}
void
Periodic_Task::job (Job_ptr job)
{
job_ = Job::_duplicate (job);
}
void
Periodic_Task::dump_stats (ACE_TCHAR* msg)
{
ACE_TCHAR buf[BUFSIZ];
ACE_OS::sprintf (buf, ACE_TEXT("%s%s"), name_.c_str (), ACE_TEXT(".dat"));
ACE_TString fname (buf);
ACE_OS::sprintf (buf,ACE_TEXT("#%s #name %s, priority %d, period %ld, exec_time %ld, phase %ld, iter_ %d , load_ %d"),
msg, name_.c_str(), task_priority_, period_, exec_time_, phase_, iter_, load_);
task_stats_->dump_samples (fname.c_str (), buf,
ACE_High_Res_Timer::global_scale_factor ());
}
| 27.827586 | 120 | 0.590149 | cflowe |
6615746073f17a2f1e720c04a6e30c0dd63d1e22 | 239 | cpp | C++ | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 4 | 2019-11-10T21:56:40.000Z | 2021-12-11T20:10:55.000Z | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | null | null | null | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 1 | 2019-11-11T08:38:59.000Z | 2019-11-11T08:38:59.000Z | #include "AtIncludes.h"
#include "AtUtf8Lit.h"
namespace At
{
namespace Utf8
{
namespace Lit
{
Seq const BOM { "\xEF\xBB\xBF", 3 }; // U+FEFF
Seq const Ellipsis { "\xE2\x80\xA6", 3 }; // U+2026
}
}
}
| 14.058824 | 55 | 0.535565 | denisbider |
66166a6b354ad4503185ffc58c129fa07cc8a896 | 219 | cpp | C++ | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | 1 | 2022-03-06T18:27:58.000Z | 2022-03-06T18:27:58.000Z | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | null | null | null | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
int x,y;
cin>>x>>y;
if((x+y)&1)
cout<<"Jay"<<endl;
else
cout<<"Janmansh"<<endl;
}
return 0;
}
| 11.526316 | 28 | 0.484018 | tarunbisht-24 |
66193bd7bea2e37f3120b4ae867a51dc34c0a7d5 | 1,047 | cpp | C++ | cpp/autodiff/src/Variable.cpp | andreaswitsch/cnlcsplib | 5350cd094c4867e7d6b33d2dda22b21425729dd2 | [
"Apache-2.0"
] | null | null | null | cpp/autodiff/src/Variable.cpp | andreaswitsch/cnlcsplib | 5350cd094c4867e7d6b33d2dda22b21425729dd2 | [
"Apache-2.0"
] | null | null | null | cpp/autodiff/src/Variable.cpp | andreaswitsch/cnlcsplib | 5350cd094c4867e7d6b33d2dda22b21425729dd2 | [
"Apache-2.0"
] | null | null | null | /*
* Variable.cpp
*
* Created on: Jun 5, 2014
* Author: psp
*/
#include "Variable.h"
#include "TermBuilder.h"
#include <limits>
namespace autodiff
{
int Variable::var_id = 0;
Variable::Variable()
{
globalMin = -numeric_limits<double>::infinity();
globalMax = numeric_limits<double>::infinity();
ownId = var_id++;
}
int Variable::accept(shared_ptr<ITermVisitor> visitor)
{
shared_ptr<Variable> thisCasted = dynamic_pointer_cast<Variable>(shared_from_this());
return visitor->visit(thisCasted);
}
shared_ptr<Term> Variable::aggregateConstants()
{
return shared_from_this();
}
shared_ptr<Term> Variable::derivative(shared_ptr<Variable> v)
{
if (shared_from_this() == v)
{
return TermBuilder::constant(1);
}
else
{
return TermBuilder::constant(0);
}
}
string Variable::toString()
{
string str;
if (ownId < 0) {
str.append("Var_");
str.append(to_string(-ownId));
} else {
str.append("Var");
str.append(to_string(ownId));
}
return str;
}
} /* namespace autodiff */
| 17.163934 | 87 | 0.663801 | andreaswitsch |
661b3510e9315a377658178ea8054a7ba0aac6c2 | 4,320 | cc | C++ | lib/sk/util/test/collection/HolderTest.cc | stemkit-collection/stemkit-cpp | dfa77d831f49916ba6d134f407a4dcd0983328f6 | [
"MIT"
] | 4 | 2019-02-19T16:48:41.000Z | 2022-01-31T07:57:54.000Z | lib/sk/util/test/collection/HolderTest.cc | stemkit-collection/stemkit-cpp | dfa77d831f49916ba6d134f407a4dcd0983328f6 | [
"MIT"
] | 1 | 2019-01-30T04:48:35.000Z | 2019-01-30T04:48:35.000Z | lib/sk/util/test/collection/HolderTest.cc | stemkit-collection/stemkit-cpp | dfa77d831f49916ba6d134f407a4dcd0983328f6 | [
"MIT"
] | null | null | null | /* vi: sw=2:
* Copyright (c) 2006, Gennady Bystritsky <bystr@mac.com>
*
* Distributed under the MIT Licence.
* This is free software. See 'LICENSE' for details.
* You must read and accept the license prior to use.
*/
#include "HolderTest.h"
#include <sk/util/Holder.cxx>
#include <sk/util/MissingResourceException.h>
#include <sk/util/UnsupportedOperationException.h>
#include <sk/util/test/Probe.hxx>
CPPUNIT_TEST_SUITE_REGISTRATION(sk::util::test::HolderTest);
sk::util::test::HolderTest::
HolderTest()
{
}
sk::util::test::HolderTest::
~HolderTest()
{
}
void
sk::util::test::HolderTest::
setUp()
{
test::Probe<String>::resetCounter();
}
void
sk::util::test::HolderTest::
tearDown()
{
test::Probe<String>::resetCounter();
}
void
sk::util::test::HolderTest::
testCreateWithReference()
{
test::Probe<String> probe("abc");
Holder<test::Probe<String> > holder(probe);
CPPUNIT_ASSERT_EQUAL(&probe, &holder.getMutable());
CPPUNIT_ASSERT_EQUAL(false, holder.isEmpty());
CPPUNIT_ASSERT_EQUAL(true, holder.contains(probe));
CPPUNIT_ASSERT_EQUAL(false, holder.contains(test::Probe<String>("bbb")));
CPPUNIT_ASSERT_EQUAL(false, holder.isOwner());
}
void
sk::util::test::HolderTest::
testCreateWithPointer()
{
test::Probe<String>* probe = new test::Probe<String>("abc");
{
Holder<test::Probe<String> > holder(probe);
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(probe, &holder.getMutable());
CPPUNIT_ASSERT_EQUAL(false, holder.isEmpty());
CPPUNIT_ASSERT_EQUAL(true, holder.contains(*probe));
CPPUNIT_ASSERT_EQUAL(false, holder.contains(test::Probe<String>("bbb")));
CPPUNIT_ASSERT_EQUAL(true, holder.isOwner());
}
CPPUNIT_ASSERT_EQUAL(0, test::Probe<String>::getCounter());
}
void
sk::util::test::HolderTest::
testCreateEmpty()
{
Holder<test::Probe<String> > holder;
CPPUNIT_ASSERT_EQUAL(true, holder.isEmpty());
CPPUNIT_ASSERT_EQUAL(false, holder.contains(test::Probe<String>("bbb")));
CPPUNIT_ASSERT_THROW(holder.get(), MissingResourceException);
CPPUNIT_ASSERT_EQUAL(false, holder.remove());
}
void
sk::util::test::HolderTest::
testRemove()
{
test::Probe<String>* probe = new test::Probe<String>("abc");
Holder<test::Probe<String> > holder(probe);
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(true, holder.remove());
CPPUNIT_ASSERT_EQUAL(true, holder.isEmpty());
CPPUNIT_ASSERT_EQUAL(0, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(false, holder.remove());
}
void
sk::util::test::HolderTest::
testRelease()
{
test::Probe<String>* probe = new test::Probe<String>("abc");
Holder<test::Probe<String> > holder(probe);
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(true, holder.isOwner());
test::Probe<String>* released = holder.release();
CPPUNIT_ASSERT_EQUAL(false, holder.isOwner());
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(false, holder.isEmpty());
CPPUNIT_ASSERT_EQUAL(probe, released);
CPPUNIT_ASSERT_EQUAL(probe, &holder.getMutable());
CPPUNIT_ASSERT_THROW(holder.release(), UnsupportedOperationException);
delete released;
CPPUNIT_ASSERT_EQUAL(0, test::Probe<String>::getCounter());
}
void
sk::util::test::HolderTest::
testSet()
{
Holder<test::Probe<String> > holder(new test::Probe<String>("abc"));
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL("abc", holder.get());
test::Probe<String>* probe = new test::Probe<String>("zzz");
CPPUNIT_ASSERT_EQUAL(2, test::Probe<String>::getCounter());
holder.set(probe);
CPPUNIT_ASSERT_EQUAL(1, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL("zzz", holder.get());
holder.set(0);
CPPUNIT_ASSERT_EQUAL(0, test::Probe<String>::getCounter());
CPPUNIT_ASSERT_EQUAL(true, holder.isEmpty());
}
void
sk::util::test::HolderTest::
testInspect()
{
sk::util::String s("abcd");
sk::util::Holder<sk::util::String> holder;
CPPUNIT_ASSERT_EQUAL("()", holder.inspect());
holder.set(s);
CPPUNIT_ASSERT_EQUAL("(&\"abcd\")", holder.inspect());
holder.set(new sk::util::String("zzz"));
CPPUNIT_ASSERT_EQUAL("(*\"zzz\")", holder.inspect());
delete holder.deprive();
CPPUNIT_ASSERT_EQUAL("(*<null>)", holder.inspect());
}
| 26.666667 | 77 | 0.71412 | stemkit-collection |
66200635a948bc973c086e585dfc52faaba9fa4f | 333 | cpp | C++ | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <iostream>
const int MAXN = 3000000;
int main() {
int n, p;
std::cin >> n >> p;
static long long inv[MAXN + 1];
inv[1] = 1;
puts("1");
for(int i = 2; i <= n; i++) {
inv[i] = ((long long)p - p / i) * inv[p % i] % p;
printf("%lld\n", inv[i]);
}
return 0;
} | 17.526316 | 57 | 0.456456 | XenonWZH |
66214b60e0a23807b04b06fb548a9118d68dda53 | 6,086 | cpp | C++ | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "SharedD3D12.h"
#include "DescriptorPoolD3D12.h"
#include "DeviceD3D12.h"
#include "PipelineLayoutD3D12.h"
using namespace nri;
extern D3D12_DESCRIPTOR_HEAP_TYPE GetDescriptorHeapType(DescriptorType descriptorType);
DescriptorPoolD3D12::DescriptorPoolD3D12(DeviceD3D12& device)
: m_Device(device)
, m_DescriptorSets(device.GetStdAllocator())
{}
DescriptorPoolD3D12::~DescriptorPoolD3D12()
{
for (size_t i = 0; i < m_DescriptorSetNum; i++)
Deallocate(m_Device.GetStdAllocator(), m_DescriptorSets[i]);
}
Result DescriptorPoolD3D12::Create(const DescriptorPoolDesc& descriptorPoolDesc)
{
uint32_t descriptorHeapSize[DescriptorHeapType::MAX_NUM] = {};
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.constantBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.textureMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageTextureMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.bufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.structuredBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageStructuredBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.accelerationStructureMaxNum;
descriptorHeapSize[DescriptorHeapType::SAMPLER] += descriptorPoolDesc.samplerMaxNum;
for (uint32_t i = 0; i < DescriptorHeapType::MAX_NUM; i++)
{
if (descriptorHeapSize[i])
{
ComPtr<ID3D12DescriptorHeap> descriptorHeap;
D3D12_DESCRIPTOR_HEAP_DESC desc = { (D3D12_DESCRIPTOR_HEAP_TYPE)i, descriptorHeapSize[i], D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NRI_TEMP_NODE_MASK };
HRESULT hr = ((ID3D12Device*)m_Device)->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&descriptorHeap));
if (FAILED(hr))
{
REPORT_ERROR(m_Device.GetLog(), "ID3D12Device::CreateDescriptorHeap() failed, return code %d.", hr);
return Result::FAILURE;
}
m_DescriptorHeapDescs[i].descriptorHeap = descriptorHeap;
m_DescriptorHeapDescs[i].descriptorPointerCPU = descriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr;
m_DescriptorHeapDescs[i].descriptorPointerGPU = descriptorHeap->GetGPUDescriptorHandleForHeapStart().ptr;
m_DescriptorHeapDescs[i].descriptorSize = ((ID3D12Device*)m_Device)->GetDescriptorHandleIncrementSize((D3D12_DESCRIPTOR_HEAP_TYPE)i);
m_DescriptorHeaps[m_DescriptorHeapNum] = descriptorHeap;
m_DescriptorHeapNum++;
}
}
m_DescriptorSets.resize(descriptorPoolDesc.descriptorSetMaxNum);
return Result::SUCCESS;
}
void DescriptorPoolD3D12::Bind(ID3D12GraphicsCommandList* graphicsCommandList) const
{
graphicsCommandList->SetDescriptorHeaps(m_DescriptorHeapNum, m_DescriptorHeaps.data());
}
uint32_t DescriptorPoolD3D12::AllocateDescriptors(DescriptorHeapType descriptorHeapType, uint32_t descriptorNum)
{
uint32_t descriptorOffset = m_DescriptorNum[descriptorHeapType];
m_DescriptorNum[descriptorHeapType] += descriptorNum;
return descriptorOffset;
}
DescriptorPointerCPU DescriptorPoolD3D12::GetDescriptorPointerCPU(DescriptorHeapType descriptorHeapType, uint32_t offset) const
{
const DescriptorHeapDesc& descriptorHeapDesc = m_DescriptorHeapDescs[descriptorHeapType];
DescriptorPointerCPU descriptorPointer = descriptorHeapDesc.descriptorPointerCPU + offset * descriptorHeapDesc.descriptorSize;
return descriptorPointer;
}
DescriptorPointerGPU DescriptorPoolD3D12::GetDescriptorPointerGPU(DescriptorHeapType descriptorHeapType, uint32_t offset) const
{
const DescriptorHeapDesc& descriptorHeapDesc = m_DescriptorHeapDescs[descriptorHeapType];
DescriptorPointerGPU descriptorPointer = descriptorHeapDesc.descriptorPointerGPU + offset * descriptorHeapDesc.descriptorSize;
return descriptorPointer;
}
inline void DescriptorPoolD3D12::SetDebugName(const char* name)
{
MaybeUnused(name);
}
inline Result DescriptorPoolD3D12::AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** const descriptorSets, uint32_t instanceNum, uint32_t physicalDeviceMask, uint32_t variableDescriptorNum)
{
MaybeUnused(variableDescriptorNum);
if (m_DescriptorSetNum + instanceNum > m_DescriptorSets.size())
return Result::FAILURE;
const PipelineLayoutD3D12& pipelineLayoutD3D12 = (PipelineLayoutD3D12&)pipelineLayout;
const DescriptorSetMapping& descriptorSetMapping = pipelineLayoutD3D12.GetDescriptorSetMapping(setIndex);
const DynamicConstantBufferMapping& dynamicConstantBufferMapping = pipelineLayoutD3D12.GetDynamicConstantBufferMapping(setIndex);
for (uint32_t i = 0; i < instanceNum; i++)
{
DescriptorSetD3D12* descriptorSet = Allocate<DescriptorSetD3D12>(m_Device.GetStdAllocator(), m_Device, *this, descriptorSetMapping, dynamicConstantBufferMapping.constantNum);
m_DescriptorSets[m_DescriptorSetNum + i] = descriptorSet;
descriptorSets[i] = (DescriptorSet*)descriptorSet;
}
m_DescriptorSetNum += instanceNum;
return Result::SUCCESS;
}
inline void DescriptorPoolD3D12::Reset()
{
for (uint32_t i = 0; i < DescriptorHeapType::MAX_NUM; i++)
m_DescriptorNum[i] = 0;
for (uint32_t i = 0; i < m_DescriptorSetNum; i++)
Deallocate(m_Device.GetStdAllocator(), m_DescriptorSets[i]);
m_DescriptorSetNum = 0;
}
| 43.784173 | 235 | 0.781794 | jayrulez |
662382512402483c434b97928f9c85ad59240c61 | 5,374 | cpp | C++ | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 2,313 | 2017-03-24T16:25:28.000Z | 2022-03-31T03:00:30.000Z | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 952 | 2017-03-28T07:05:58.000Z | 2022-03-30T09:54:02.000Z | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 714 | 2017-03-24T22:21:51.000Z | 2022-03-18T19:49:57.000Z | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "src/common/utils/LegacySupport.h"
namespace arm_compute
{
namespace detail
{
namespace
{
DataType convert_to_legacy_data_type(AclDataType data_type)
{
switch(data_type)
{
case AclDataType::AclFloat32:
return DataType::F32;
case AclDataType::AclFloat16:
return DataType::F16;
case AclDataType::AclBFloat16:
return DataType::BFLOAT16;
default:
return DataType::UNKNOWN;
}
}
AclDataType convert_to_c_data_type(DataType data_type)
{
switch(data_type)
{
case DataType::F32:
return AclDataType::AclFloat32;
case DataType::F16:
return AclDataType::AclFloat16;
case DataType::BFLOAT16:
return AclDataType::AclBFloat16;
default:
return AclDataType::AclDataTypeUnknown;
}
}
TensorShape create_legacy_tensor_shape(int32_t ndims, int32_t *shape)
{
TensorShape legacy_shape{};
for(int32_t d = 0; d < ndims; ++d)
{
legacy_shape.set(d, shape[d], false);
}
return legacy_shape;
}
int32_t *create_tensor_shape_array(const TensorInfo &info)
{
const auto num_dims = info.num_dimensions();
if(num_dims <= 0)
{
return nullptr;
}
int32_t *shape_array = new int32_t[num_dims];
for(size_t d = 0; d < num_dims; ++d)
{
shape_array[d] = info.tensor_shape()[d];
}
return shape_array;
}
} // namespace
TensorInfo convert_to_legacy_tensor_info(const AclTensorDescriptor &desc)
{
TensorInfo legacy_desc;
legacy_desc.init(create_legacy_tensor_shape(desc.ndims, desc.shape), 1, convert_to_legacy_data_type(desc.data_type));
return legacy_desc;
}
AclTensorDescriptor convert_to_descriptor(const TensorInfo &info)
{
const auto num_dims = info.num_dimensions();
AclTensorDescriptor desc
{
static_cast<int32_t>(num_dims),
create_tensor_shape_array(info),
convert_to_c_data_type(info.data_type()),
nullptr,
0
};
return desc;
}
ActivationLayerInfo convert_to_activation_info(const AclActivationDescriptor &desc)
{
ActivationLayerInfo::ActivationFunction act;
switch(desc.type)
{
case AclActivationType::AclIdentity:
act = ActivationLayerInfo::ActivationFunction::IDENTITY;
break;
case AclActivationType::AclLogistic:
act = ActivationLayerInfo::ActivationFunction::LOGISTIC;
break;
case AclActivationType::AclTanh:
act = ActivationLayerInfo::ActivationFunction::TANH;
break;
case AclActivationType::AclRelu:
act = ActivationLayerInfo::ActivationFunction::RELU;
break;
case AclActivationType::AclBoundedRelu:
act = ActivationLayerInfo::ActivationFunction::BOUNDED_RELU;
break;
case AclActivationType::AclLuBoundedRelu:
act = ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU;
break;
case AclActivationType::AclLeakyRelu:
act = ActivationLayerInfo::ActivationFunction::LEAKY_RELU;
break;
case AclActivationType::AclSoftRelu:
act = ActivationLayerInfo::ActivationFunction::SOFT_RELU;
break;
case AclActivationType::AclElu:
act = ActivationLayerInfo::ActivationFunction::ELU;
break;
case AclActivationType::AclAbs:
act = ActivationLayerInfo::ActivationFunction::ABS;
break;
case AclActivationType::AclSquare:
act = ActivationLayerInfo::ActivationFunction::SQUARE;
break;
case AclActivationType::AclSqrt:
act = ActivationLayerInfo::ActivationFunction::SQRT;
break;
case AclActivationType::AclLinear:
act = ActivationLayerInfo::ActivationFunction::LINEAR;
break;
case AclActivationType::AclHardSwish:
act = ActivationLayerInfo::ActivationFunction::HARD_SWISH;
break;
default:
return ActivationLayerInfo();
}
return ActivationLayerInfo(act, desc.a, desc.b);
}
} // namespace detail
} // namespace arm_compute
| 32.373494 | 121 | 0.673986 | MaximMilashchenko |
662a91f276e5295f180a0acfe97af4f2be967f18 | 413 | hpp | C++ | Svc/PassiveL2PrmDb/PassiveL2PrmDbImplCfg.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 5 | 2019-10-22T03:41:02.000Z | 2022-01-16T12:48:31.000Z | Svc/PassiveL2PrmDb/PassiveL2PrmDbImplCfg.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 27 | 2019-02-07T17:58:58.000Z | 2019-08-13T00:46:24.000Z | Svc/PassiveL2PrmDb/PassiveL2PrmDbImplCfg.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 3 | 2019-01-01T18:44:37.000Z | 2019-08-01T01:19:39.000Z | /*
* PassiveL2PrmDblImplCfg.hpp
*
* Created on: Jun 19, 2019
* Author: kubiak
*/
#ifndef PASSIVE_L2_PRMDB_PRMDBLIMPLCFG_HPP_
#define PASSIVE_L2_PRMDB_PRMDBLIMPLCFG_HPP_
// Anonymous namespace for configuration parameters
namespace {
enum {
PASSIVE_L2_PRMDB_SEND_BUFFER_ENTRIES = 64, // !< Number of parameter entries to queue
};
}
#endif /* PASSIVE_PRMDB_PRMDBLIMPLCFG_HPP_ */
| 16.52 | 93 | 0.726392 | genemerewether |
662c49c56d4c908d0daabaae80c328f22ebe1bc6 | 1,399 | cpp | C++ | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-08-30T06:53:23.000Z | 2019-08-30T06:53:23.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
out << '[';
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin())
out << ',';
out << *it;
}
out << ']';
return out;
}
class Solution {
vector<int> doDiffWaysToCompute(string::const_iterator begin,
string::const_iterator end) {
vector<int> result;
for (auto it = begin; it != end; ++it) {
char c = *it;
if (isdigit(c))
continue;
auto left = doDiffWaysToCompute(begin, it);
auto right = doDiffWaysToCompute(it + 1, end);
for (auto l: left) {
for (auto r: right) {
int v = 0;
switch (c) {
case '+':
v = l + r;
break;
case '-':
v = l - r;
break;
case '*':
v = l * r;
break;
default:
break;
}
result.push_back(v);
}
}
}
if (result.empty())
result.push_back(stoi(string(begin, end)));
return result;
}
public:
vector<int> diffWaysToCompute(const string& s) {
return doDiffWaysToCompute(s.begin(), s.end());
}
};
int main()
{
string input[] = {
"2", // [2]
"2+1", // [3]
"2-1-1", // [0, 2]
"2*3-4*5", // [-34, -14, -10, -10, 10]
};
Solution solution;
for (const auto& s: input) {
cout << '"' << s << "\" => " <<
solution.diffWaysToCompute(s) << endl;
}
return 0;
}
| 18.653333 | 62 | 0.531094 | locker |
662e664e38befd8ae3bd7f798b1092712bb7c15e | 2,035 | hpp | C++ | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | #ifndef DATA_STRUCTURE_HPP
#define DATA_STRUCTURE_HPP
#include <array>
#include <iostream>
#include "TH1.h"
namespace sf_g {
template<class ... Ts> struct composite : Ts... {
void value() {
int expander[] = {0, ( static_cast<Ts&>(*this).value(), void(), 0)...};
}
};
// ------------------------------raw----------------------------------
struct raw_waveform {
int channel_id;
int event_id;
int fcr;
float baseline;
float amplitude;
float charge;
float leading_edge;
float trailing_edge;
float rate_counter;
std::array<short, 1024> sample_c;
};
struct event_data {
int event_id;
double epoch_time;
struct date_t{
int year;
int month;
int day;
} date;
struct time_t{
int hour;
int minute;
int second;
int millisecond;
} time;
int tdc;
int corrected_tdc;
int channel_count;
};
struct metadata {
int channel_count;
double sampling_period;
};
//-------------------------------------------transformed-------------------------------------------
struct waveform {
TH1D data;
};
struct linked_waveform {
TH1D data;
std::size_t channel_number;
};
struct amplitude { double amplitude; void value() const { std::cout << amplitude << '\n';} };
struct baseline { double baseline; void value() const { std::cout << baseline << '\n';} };
struct cfd_time { double time; void value() const { std::cout << time << '\n';} };
struct charge { double charge; void value() const { std::cout << charge << '\n';} };
struct rise_time { double rise_time; void value() const { std::cout << rise_time << '\n';} };
struct fall_time { double fall_time; void value() const { std::cout << fall_time << '\n';} };
struct mean { double mean; void value() const { std::cout << mean << '\n';} };
struct sigma { double sigma; void value() const { std::cout << sigma << '\n';} };
struct gamma_response{
double gamma_energy;
double deposited_energy;
};
}
#endif
| 25.123457 | 99 | 0.56855 | Pumpkrin |
662ff6c224fc697a3d838e19865d2a3c9ca65c36 | 4,921 | cpp | C++ | Backend/Networking/service.cpp | Gattic/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | 3 | 2021-07-31T15:16:39.000Z | 2022-02-07T21:12:36.000Z | Backend/Networking/service.cpp | MeeseeksLookAtMe/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | null | null | null | Backend/Networking/service.cpp | MeeseeksLookAtMe/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | 1 | 2020-05-28T02:46:43.000Z | 2020-05-28T02:46:43.000Z | // Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan
//
// 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 "service.h"
#include "connection.h"
#include "socket.h"
using namespace GNet;
// services
#include "../../services/bad_request.h"
#include "../../services/handshake_client.h"
#include "../../services/handshake_server.h"
#include "../../services/logout_client.h"
#include "../../services/logout_server.h"
/*!
* @brief Service constructor
* @details creates a Service object and initialize timeExecuted
*/
Service::Service()
{
timeExecuted = 0;
}
/*!
* @brief Service deconstructor
* @details deconstructs a Service object
*/
Service::~Service()
{
timeExecuted = 0;
}
/*!
* @brief Run execute() asynchronusly as a Service
* @details launch new service thread (command)
* @param sockData a package of network data
* @param cConnection the current connection
*/
void Service::ExecuteService(GServer* serverInstance, const shmea::ServiceData* sockData,
Connection* cConnection)
{
// set the args to pass in
newServiceArgs* x = new newServiceArgs[sizeof(newServiceArgs)];
x->serverInstance = serverInstance;
x->cConnection = cConnection;
x->sockData = sockData;
x->sThread = new pthread_t[sizeof(pthread_t)];
// launch a new service thread
pthread_create(x->sThread, NULL, &launchService, (void*)x);
if (x->sThread)
pthread_detach(*x->sThread);
}
/*!
* @brief Launch a new service
* @details launch service wrapper
* @param y points to memory location for serviceArgs data
*/
void* Service::launchService(void* y)
{
// Helper function for pthread_create
// set the service args
newServiceArgs* x = (newServiceArgs*)y;
if (!x->serverInstance)
return NULL;
GServer* serverInstance = x->serverInstance;
// Get the command in order to tell the service what to do
x->command = x->sockData->getCommand();
if(x->command.length() == 0)//Uncomment this before commit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return NULL;
// Connection is dead so ignore it
Connection* cConnection = x->cConnection;
if (!cConnection)
return NULL;
if (!cConnection->isFinished())
{
Service* cService = serverInstance->ServiceLookup(x->command);
if (cService)
{
// start the service
cService->StartService(x);
// execute the service
shmea::ServiceData* retData = cService->execute(x->sockData);
if(!retData)
{
serverInstance->socks->addResponseList(serverInstance, cConnection, retData);
}
// exit the service
cService->ExitService(x);
delete cService;
}
}
if (x)
delete x;
// delete the Connection
if (cConnection->isFinished())
delete cConnection;
return NULL;
}
/*!
* @brief Start a service
* @details start a service and set variables
* @param x pointer to new service arguments memory location
*/
void Service::StartService(newServiceArgs* x)
{
// set the start time
timeExecuted = time(NULL);
// Get the ip address
Connection* cConnection = x->cConnection;
shmea::GString ipAddress = "";
if (!cConnection->isFinished())
ipAddress = cConnection->getIP();
// const shmea::GString& command = x->command;
// printf("---------Service Start: %s (%s)---------\n", ipAddress.c_str(), command.c_str());
// add the thread to the connection's active thread vector
cThread = x->sThread;
}
/*!
* @brief Exit Service
* @details exit from a service
* @param x points to memory location for serviceArgs data
*/
void Service::ExitService(newServiceArgs* x)
{
// Get the ip address
Connection* cConnection = x->cConnection;
shmea::GString ipAddress = "";
if (!cConnection->isFinished())
ipAddress = cConnection->getIP();
// Set and print the execution time
timeExecuted = time(NULL) - timeExecuted;
// printf("---------Service Exit: %s (%s); %llds---------\n", ipAddress.c_str(),
// x->command.c_str(), timeExecuted);
pthread_exit(0);
}
| 28.947059 | 119 | 0.704328 | Gattic |
6630145e284f5646da7ad33363a6dc353ad52b2c | 584 | cpp | C++ | test/opengl/inline_reduction.cpp | rafaelravedutti/Halide | 9417210e7eca49b224028834dbed09cb2d62b1cd | [
"Apache-2.0"
] | 107 | 2018-08-16T05:32:52.000Z | 2022-02-11T19:44:25.000Z | test/opengl/inline_reduction.cpp | rafaelravedutti/Halide | 9417210e7eca49b224028834dbed09cb2d62b1cd | [
"Apache-2.0"
] | 79 | 2019-02-22T03:27:45.000Z | 2022-02-24T23:03:28.000Z | test/opengl/inline_reduction.cpp | rafaelravedutti/Halide | 9417210e7eca49b224028834dbed09cb2d62b1cd | [
"Apache-2.0"
] | 22 | 2017-04-16T11:44:34.000Z | 2022-03-26T13:27:10.000Z | #include "Halide.h"
#include <stdio.h>
#include "testing.h"
using namespace Halide;
int main() {
// This test must be run with an OpenGL target.
const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL);
Func f;
Var x, y, c;
RDom r(0, 10);
f(x, y, c) = sum(cast<float>(r));
f.bound(c, 0, 3).glsl(x, y, c);
Buffer<float> result = f.realize(100, 100, 3, target);
if (!Testing::check_result<float>(result, [&](int x, int y, int c) { return 45; })) {
return 1;
}
printf("Success!\n");
return 0;
}
| 20.857143 | 89 | 0.592466 | rafaelravedutti |
663225b9fb2dff4edf74c89bb3e1d5eaefac2d99 | 1,740 | cc | C++ | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | null | null | null | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | 1 | 2017-12-05T18:00:56.000Z | 2017-12-05T18:00:56.000Z | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | null | null | null | /*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include "goods_stats_t.h"
#include "../simcolor.h"
#include "../simworld.h"
#include "../bauer/goods_manager.h"
#include "../descriptor/goods_desc.h"
#include "../dataobj/translator.h"
#include "components/gui_button.h"
#include "components/gui_colorbox.h"
#include "components/gui_label.h"
karte_ptr_t goods_stats_t::welt;
void goods_stats_t::update_goodslist(vector_tpl<const goods_desc_t*>goods, int bonus)
{
scr_size size = get_size();
remove_all();
set_table_layout(6,0);
FOR(vector_tpl<const goods_desc_t*>, wtyp, goods) {
new_component<gui_colorbox_t>(wtyp->get_color())->set_max_size(scr_size(D_INDICATOR_WIDTH, D_INDICATOR_HEIGHT));
new_component<gui_label_t>(wtyp->get_name());
const sint32 grundwert128 = (sint32)wtyp->get_value() * welt->get_settings().get_bonus_basefactor(); // bonus price will be always at least this
const sint32 grundwert_bonus = (sint32)wtyp->get_value()*(1000l+(bonus-100l)*wtyp->get_speed_bonus());
const sint32 price = (grundwert128>grundwert_bonus ? grundwert128 : grundwert_bonus);
gui_label_buf_t *lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().append_money(price/300000.0);
lb->update();
lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().printf("%d%%", wtyp->get_speed_bonus());
lb->update();
new_component<gui_label_t>(wtyp->get_catg_name());
lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().printf("%dKg", wtyp->get_weight_per_unit());
lb->update();
}
scr_size min_size = get_min_size();
set_size(scr_size(max(size.w, min_size.w), min_size.h) );
}
| 32.222222 | 146 | 0.737931 | soukouki |
66341ff1311714c78d412efe93749a26ce9f5d89 | 17,134 | cpp | C++ | src/sdk/hl2_csgo/game/missionchooser/layout_system/tilegen_layout_system.cpp | newcommerdontblame/ionlib | 47ca829009e1529f62b2134aa6c0df8673864cf3 | [
"MIT"
] | 51 | 2016-03-18T01:48:07.000Z | 2022-03-21T20:02:02.000Z | src/game/missionchooser/layout_system/tilegen_layout_system.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | null | null | null | src/game/missionchooser/layout_system/tilegen_layout_system.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | 26 | 2016-03-17T21:20:37.000Z | 2022-03-24T10:21:30.000Z | //============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// Definitions for the rule- and state-based level generation system.
//
//===============================================================================
#include "MapLayout.h"
#include "Room.h"
#include "tilegen_class_factories.h"
#include "tilegen_mission_preprocessor.h"
#include "tilegen_listeners.h"
#include "tilegen_ranges.h"
#include "tilegen_layout_system.h"
#include "asw_npcs.h"
ConVar tilegen_break_on_iteration( "tilegen_break_on_iteration", "-1", FCVAR_CHEAT, "If set to a non-negative value, tilegen will break at the start of iteration #N if a debugger is attached." );
DEFINE_LOGGING_CHANNEL_NO_TAGS( LOG_TilegenLayoutSystem, "TilegenLayoutSystem", 0, LS_MESSAGE, Color( 192, 255, 192, 255 ) );
void AddListeners( CLayoutSystem *pLayoutSystem )
{
// @TODO: need a better mechanism to detect which of these listeners are required. For now, add them all.
pLayoutSystem->AddListener( new CTilegenListener_NumTilesPlaced() );
}
CTilegenState *CTilegenStateList::FindState( const char *pStateName )
{
for ( int i = 0; i < m_States.Count(); ++ i )
{
if ( Q_stricmp( pStateName, m_States[i]->GetStateName() ) == 0 )
{
return m_States[i];
}
CTilegenState *pState = m_States[i]->GetStateList()->FindState( pStateName );
if ( pState != NULL )
{
return pState;
}
}
return NULL;
}
CTilegenState *CTilegenStateList::GetNextState( CTilegenState *pState )
{
int i;
for ( i = 0; i < m_States.Count(); ++ i )
{
if ( m_States[i] == pState )
break;
}
if ( i < ( m_States.Count() - 1 ) )
{
return m_States[i + 1];
}
else if ( i == m_States.Count() )
{
// This should never happen unless there's a bug in the layout code
Log_Warning( LOG_TilegenLayoutSystem, "State %s not found in state list.\n", pState->GetStateName() );
m_pLayoutSystem->OnError();
return NULL;
}
else if ( i == ( m_States.Count() - 1 ) )
{
// We're on the last state
CTilegenStateList *pParentStateList = GetParentStateList();
if ( pParentStateList == NULL )
{
// No more states left in the layout system.
return NULL;
}
else
{
Assert( pState->GetParentState() != NULL );
return pParentStateList->GetNextState( pState->GetParentState() );
}
}
UNREACHABLE();
return NULL;
}
CTilegenStateList *CTilegenStateList::GetParentStateList()
{
if ( m_pOwnerState == NULL )
{
// No parent state implies that this state list is owned by the layout system, so there
// is no parent state list.
return NULL;
}
else if ( m_pOwnerState->GetParentState() == NULL )
{
// A parent state with a NULL parent state implies that this list is owned by a top-level
// state, so the parent state list belongs to the layout system.
return m_pLayoutSystem->GetStateList();
}
else
{
return m_pOwnerState->GetParentState()->GetStateList();
}
}
void CTilegenStateList::OnBeginGeneration()
{
for ( int i = 0; i < m_States.Count(); ++ i )
{
m_States[i]->OnBeginGeneration( m_pLayoutSystem );
}
}
CTilegenState::~CTilegenState()
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
delete m_Actions[i].m_pAction;
delete m_Actions[i].m_pCondition;
}
}
bool CTilegenState::LoadFromKeyValues( KeyValues *pKeyValues )
{
const char *pStateName = pKeyValues->GetString( "name", NULL );
if ( pStateName == NULL )
{
Log_Warning( LOG_TilegenLayoutSystem, "No state name found in State key values.\n" );
return false;
}
m_StateName[0] = '\0';
// @TODO: support nested state names?
// if ( pParentStateName != NULL )
// {
// Q_strncat( m_StateName, pParentStateName, MAX_TILEGEN_IDENTIFIER_LENGTH );
// Q_strncat( m_StateName, ".", MAX_TILEGEN_IDENTIFIER_LENGTH );
// }
Q_strncat( m_StateName, pStateName, MAX_TILEGEN_IDENTIFIER_LENGTH );
for ( KeyValues *pSubKey = pKeyValues->GetFirstSubKey(); pSubKey != NULL; pSubKey = pSubKey->GetNextKey() )
{
if ( Q_stricmp( pSubKey->GetName(), "action" ) == 0 )
{
if ( !ParseAction( pSubKey ) )
{
return false;
}
}
else if ( Q_stricmp( pSubKey->GetName(), "state") == 0 )
{
// Nested state
CTilegenState *pNewState = new CTilegenState( GetLayoutSystem(), this );
if ( !pNewState->LoadFromKeyValues( pSubKey ) )
{
delete pNewState;
return false;
}
m_ChildStates.AddState( pNewState );
}
}
return true;
}
void CTilegenState::ExecuteIteration( CLayoutSystem *pLayoutSystem )
{
if ( m_Actions.Count() == 0 )
{
// No actions in this state, go to the first nested state if one exists
// or move on to the next sibling state.
if ( m_ChildStates.GetStateCount() > 0 )
{
Log_Msg( LOG_TilegenLayoutSystem, "No actions found in state %s, transitioning to first child state.\n", GetStateName() );
pLayoutSystem->TransitionToState( m_ChildStates.GetState( 0 ) );
}
else
{
// Try to switch to the next sibling state.
CTilegenState *pNextState = m_ChildStates.GetParentStateList()->GetNextState( this );
if ( pNextState != NULL )
{
Log_Msg( LOG_TilegenLayoutSystem, "No actions or child states found in state %s, transitioning to next state.\n", GetStateName() );
pLayoutSystem->TransitionToState( pNextState );
}
else
{
// This must be the last state in the entire layout system.
Log_Msg( LOG_TilegenLayoutSystem, "No more states to which to transition." );
pLayoutSystem->OnFinished();
}
}
}
else
{
pLayoutSystem->GetFreeVariables()->SetOrCreateFreeVariable( "CurrentState", this );
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
if ( pLayoutSystem->ShouldStopProcessingActions() )
{
break;
}
pLayoutSystem->ExecuteAction( m_Actions[i].m_pAction, m_Actions[i].m_pCondition );
}
pLayoutSystem->GetFreeVariables()->SetOrCreateFreeVariable( "CurrentState", NULL );
}
}
void CTilegenState::OnBeginGeneration( CLayoutSystem *pLayoutSystem )
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
m_Actions[i].m_pAction->OnBeginGeneration( pLayoutSystem );
}
m_ChildStates.OnBeginGeneration();
}
void CTilegenState::OnStateChanged( CLayoutSystem *pLayoutSystem )
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
m_Actions[i].m_pAction->OnStateChanged( pLayoutSystem );
}
}
bool CTilegenState::ParseAction( KeyValues *pKeyValues )
{
ITilegenAction *pNewAction = NULL;
ITilegenExpression< bool > *pCondition = NULL;
if ( CreateActionAndCondition( pKeyValues, &pNewAction, &pCondition ) )
{
AddAction( pNewAction, pCondition );
return true;
}
else
{
return false;
}
}
CLayoutSystem::CLayoutSystem() :
m_nRandomSeed( 0 ),
m_pGlobalActionState( NULL ),
m_pCurrentState( NULL ),
m_pMapLayout( NULL ),
m_ActionData( DefLessFunc( ITilegenAction *) ),
m_bLayoutError( false ),
m_bGenerating( false ),
m_nIterations( 0 )
{
m_States.SetLayoutSystem( this );
}
CLayoutSystem::~CLayoutSystem()
{
m_TilegenListeners.PurgeAndDeleteElements();
delete m_pGlobalActionState;
}
bool CLayoutSystem::LoadFromKeyValues( KeyValues *pKeyValues )
{
// Make sure all tilegen class factories have been registered.
RegisterAllTilegenClasses();
for ( KeyValues *pSubKey = pKeyValues->GetFirstSubKey(); pSubKey != NULL; pSubKey = pSubKey->GetNextKey() )
{
if ( Q_stricmp( pSubKey->GetName(), "state" ) == 0 )
{
CTilegenState *pNewState = new CTilegenState( this, NULL );
if ( !pNewState->LoadFromKeyValues( pSubKey ) )
{
delete pNewState;
return false;
}
m_States.AddState( pNewState );
}
else if ( Q_stricmp( pSubKey->GetName(), "action" ) == 0 )
{
// Global actions, executed at the beginning of every state
ITilegenAction *pNewAction = NULL;
ITilegenExpression< bool > *pCondition = NULL;
if ( CreateActionAndCondition( pSubKey, &pNewAction, &pCondition ) )
{
if ( m_pGlobalActionState == NULL )
{
m_pGlobalActionState = new CTilegenState( this, NULL );
}
m_pGlobalActionState->AddAction( pNewAction, pCondition );
}
else
{
return false;
}
}
else if ( Q_stricmp( pSubKey->GetName(), "mission_settings" ) == 0 )
{
m_nRandomSeed = pSubKey->GetInt( "RandomSeed", 0 );
}
}
return true;
}
// @TODO: add rotation/mirroring support here by adding rotation argument
bool CLayoutSystem::TryPlaceRoom( const CRoomCandidate *pRoomCandidate )
{
int nX = pRoomCandidate->m_iXPos;
int nY = pRoomCandidate->m_iYPos;
const CRoomTemplate *pRoomTemplate = pRoomCandidate->m_pRoomTemplate;
CRoom *pSourceRoom = pRoomCandidate->m_pExit ? pRoomCandidate->m_pExit->pSourceRoom : NULL;
if ( m_pMapLayout->TemplateFits( pRoomTemplate, nX, nY, false ) )
{
// This has the side-effect of attaching itself to the layout; no need to keep track of it.
CRoom *pRoom = new CRoom( m_pMapLayout, pRoomTemplate, nX, nY );
// Remove exits covered up by the room
for ( int i = m_OpenExits.Count() - 1; i >= 0; -- i )
{
CExit *pExit = &m_OpenExits[i];
if ( pExit->X >= nX && pExit->Y >= nY &&
pExit->X < nX + pRoomTemplate->GetTilesX() &&
pExit->Y < nY + pRoomTemplate->GetTilesY() )
{
m_OpenExits.FastRemove( i );
}
}
if ( pSourceRoom != NULL )
{
++ pSourceRoom->m_iNumChildren;
}
AddOpenExitsFromRoom( pRoom );
OnRoomPlaced();
GetFreeVariables()->SetOrCreateFreeVariable( "LastPlacedRoomTemplate", ( void * )pRoomTemplate );
return true;
}
return false;
}
void CLayoutSystem::TransitionToState( const char *pStateName )
{
CTilegenState *pState = m_States.FindState( pStateName );
if ( pState == NULL )
{
Log_Warning( LOG_TilegenLayoutSystem, "Tilegen state %s not found.\n", pStateName );
OnError();
}
else
{
TransitionToState( pState );
}
}
void CLayoutSystem::TransitionToState( CTilegenState *pState )
{
CTilegenState *pOldState = m_pCurrentState;
m_pCurrentState = pState;
m_CurrentIterationState.m_bStopIteration = true;
OnStateChanged( pOldState );
Log_Msg( LOG_TilegenLayoutSystem, "Transitioning to state %s.\n", pState->GetStateName() );
StopProcessingActions();
}
void CLayoutSystem::OnError()
{
m_bLayoutError = true;
m_bGenerating = false;
Log_Warning( LOG_TilegenLayoutSystem, "An error occurred during level generation.\n" );
}
void CLayoutSystem::OnFinished()
{
m_bGenerating = false;
m_CurrentIterationState.m_bStopIteration = true;
Log_Msg( LOG_TilegenLayoutSystem, "CLayoutSystem: finished layout generation.\n" );
// Temp hack to setup fixed alien spawns
// TODO: Move this into a required rule
CASWMissionChooserNPCs::InitFixedSpawns( this, m_pMapLayout );
}
void CLayoutSystem::ExecuteAction( ITilegenAction *pAction, ITilegenExpression< bool > *pCondition )
{
Assert( pAction != NULL );
// Since actions can be nested, only expose the inner-most nested action.
ITilegenAction *pOldAction = ( ITilegenAction * )GetFreeVariables()->GetFreeVariableOrNULL( "Action" );
GetFreeVariables()->SetOrCreateFreeVariable( "Action", pAction );
// Get data associated with the current action and set it to free variables
int nIndex = m_ActionData.Find( pAction );
if ( nIndex == m_ActionData.InvalidIndex() )
{
ActionData_t actionData = { 0 };
actionData.m_nNumTimesExecuted = 0;
nIndex = m_ActionData.Insert( pAction, actionData );
Assert( nIndex != m_ActionData.InvalidIndex() );
}
GetFreeVariables()->SetOrCreateFreeVariable( "NumTimesExecuted", ( void * )m_ActionData[nIndex].m_nNumTimesExecuted );
// Execute the action if the condition is met
if ( pCondition == NULL || pCondition->Evaluate( GetFreeVariables() ) )
{
// Log_Msg( LOG_TilegenLayoutSystem, "Executing action %s.\n", pAction->GetTypeName() );
pAction->Execute( this );
++ m_ActionData[nIndex].m_nNumTimesExecuted;
OnActionExecuted( pAction );
}
// Restore free variable state
GetFreeVariables()->SetOrCreateFreeVariable( "Action", pOldAction );
nIndex = m_ActionData.Find( pOldAction );
Assert( nIndex != m_ActionData.InvalidIndex() );
GetFreeVariables()->SetOrCreateFreeVariable( "NumTimesExecuted", ( void * )m_ActionData[nIndex].m_nNumTimesExecuted );
}
void CLayoutSystem::OnActionExecuted( const ITilegenAction *pAction )
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnActionExecuted( this, pAction, GetFreeVariables() );
}
}
void CLayoutSystem::OnRoomPlaced()
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnRoomPlaced( this, GetFreeVariables() );
}
}
void CLayoutSystem::OnStateChanged( const CTilegenState *pOldState )
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnStateChanged( this, pOldState, GetFreeVariables() );
}
m_pCurrentState->OnStateChanged( this );
}
void CLayoutSystem::BeginGeneration( CMapLayout *pMapLayout )
{
if ( m_States.GetStateCount() == 0 )
{
Log_Warning( LOG_TilegenLayoutSystem, "No states in layout system!\n" );
OnError();
return;
}
// Reset random generator
int nSeed;
m_Random = CUniformRandomStream();
if ( m_nRandomSeed != 0 )
{
nSeed = m_nRandomSeed;
}
else
{
// @TODO: this is rather unscientific, but it gets us desired randomness for now.
nSeed = RandomInt( 1, 1000000000 );
}
m_Random.SetSeed( nSeed );
Log_Msg( LOG_TilegenLayoutSystem, "Beginning generation with random seed " );
Log_Msg( LOG_TilegenLayoutSystem, Color( 255, 255, 0, 255 ), "%d.\n", nSeed );
m_bLayoutError = false;
m_bGenerating = true;
m_nIterations = 0;
m_pMapLayout = pMapLayout;
m_pCurrentState = m_States.GetState( 0 );
m_OpenExits.RemoveAll();
m_ActionData.RemoveAll();
m_FreeVariables.RemoveAll();
// Initialize with sentinel value
ActionData_t nullActionData = { 0 };
m_ActionData.Insert( NULL, nullActionData );
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnBeginGeneration( this, GetFreeVariables() );
}
if ( m_pGlobalActionState != NULL )
{
m_pGlobalActionState->OnBeginGeneration( this );
}
m_States.OnBeginGeneration();
GetFreeVariables()->SetOrCreateFreeVariable( "LayoutSystem", this );
GetFreeVariables()->SetOrCreateFreeVariable( "MapLayout", GetMapLayout() );
}
void CLayoutSystem::ExecuteIteration()
{
Assert( m_pCurrentState != NULL && m_pMapLayout != NULL );
const int nMaxIterations = 200;
if ( m_nIterations > nMaxIterations )
{
Log_Warning( LOG_TilegenLayoutSystem, "Exceeded %d iterations, may be in an infinite loop.\n", nMaxIterations );
OnError();
return;
}
// Debugging assistant
int nBreakOnIteration = tilegen_break_on_iteration.GetInt();
if ( nBreakOnIteration >= 0 )
{
Log_Msg( LOG_TilegenLayoutSystem, "Iteration #%d\n", m_nIterations );
}
if ( m_nIterations == nBreakOnIteration )
{
DebuggerBreakIfDebugging();
}
// Initialize state scoped to the current iteration
m_CurrentIterationState.m_bStopIteration = false;
CUtlVector< CRoomCandidate > roomCandidateList;
m_CurrentIterationState.m_pRoomCandidateList = &roomCandidateList;
// Execute global actions first, if any are present.
if ( m_pGlobalActionState != NULL )
{
m_pGlobalActionState->ExecuteIteration( this );
}
// Now process actions in the current state
if ( !ShouldStopProcessingActions() )
{
// Executing an iteration may have a number of side-effects on the layout system,
// such as placing rooms, changing state, etc.
m_pCurrentState->ExecuteIteration( this );
}
++ m_nIterations;
m_CurrentIterationState.m_pRoomCandidateList = NULL;
}
// This function adds an open exit for every un-mated exit in the given room.
// The exits are added to the grid tile where a new room would connect
// (e.g., a north exit from a room tile at (x, y) is actually added to location (x, y+1)
void CLayoutSystem::AddOpenExitsFromRoom( CRoom *pRoom )
{
const CRoomTemplate *pTemplate = pRoom->m_pRoomTemplate;
// Go through each exit in the room.
for ( int i = 0; i < pTemplate->m_Exits.Count(); ++ i )
{
const CRoomTemplateExit *pExit = pTemplate->m_Exits[i];
int nExitX, nExitY;
if ( GetExitPosition( pTemplate, pRoom->m_iPosX, pRoom->m_iPosY, i, &nExitX, &nExitY ) )
{
// If no room exists where the exit interface goes, then consider the exit open.
// NOTE: this function assumes that the caller has already verified that the template fits, which means
// that if a room exists where this exit goes, it must be a matching exit (and thus not open).
if ( !m_pMapLayout->GetRoom( nExitX, nExitY ) )
{
AddOpenExit( pRoom, nExitX, nExitY, pExit->m_ExitDirection, pExit->m_szExitTag, pExit->m_bChokepointGrowSource );
}
}
}
}
void CLayoutSystem::AddOpenExit( CRoom *pSourceRoom, int nX, int nY, ExitDirection_t exitDirection, const char *pExitTag, bool bChokepointGrowSource )
{
// Check to make sure exit isn't already in the list.
for ( int i = 0; i < m_OpenExits.Count(); ++ i )
{
const CExit *pExit = &m_OpenExits[i];
if ( pExit->X == nX && pExit->Y == nY && pExit->ExitDirection == exitDirection )
{
// Exit already exists.
Assert( pExit->pSourceRoom == pSourceRoom && Q_stricmp( pExitTag, pExit->m_szExitTag ) == 0 );
return;
}
}
m_OpenExits.AddToTail( CExit( nX, nY, exitDirection, pExitTag, pSourceRoom, bChokepointGrowSource ) );
}
| 29.288889 | 195 | 0.701938 | newcommerdontblame |
6639e244a80c32b0acb4bfa129f5492b23bb4118 | 101,632 | cc | C++ | lullaby/systems/render/next/render_system_next.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | 1 | 2018-11-09T03:45:25.000Z | 2018-11-09T03:45:25.000Z | lullaby/systems/render/next/render_system_next.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | lullaby/systems/render/next/render_system_next.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/systems/render/next/render_system_next.h"
#include <inttypes.h>
#include <stdio.h>
#include <algorithm>
#include <cctype>
#include <memory>
#include "fplbase/gpu_debug.h"
#include "lullaby/events/render_events.h"
#include "lullaby/modules/config/config.h"
#include "lullaby/modules/dispatcher/dispatcher.h"
#include "lullaby/modules/ecs/entity_factory.h"
#include "lullaby/modules/file/asset_loader.h"
#include "lullaby/modules/flatbuffers/mathfu_fb_conversions.h"
#include "lullaby/modules/render/mesh_util.h"
#include "lullaby/modules/script/function_binder.h"
#include "lullaby/systems/dispatcher/dispatcher_system.h"
#include "lullaby/systems/dispatcher/event.h"
#include "lullaby/systems/render/detail/profiler.h"
#include "lullaby/systems/render/next/detail/glplatform.h"
#include "lullaby/systems/render/next/gl_helpers.h"
#include "lullaby/systems/render/next/render_state.h"
#include "lullaby/systems/render/render_helpers.h"
#include "lullaby/systems/render/render_stats.h"
#include "lullaby/systems/render/simple_font.h"
#include "lullaby/util/filename.h"
#include "lullaby/util/logging.h"
#include "lullaby/util/make_unique.h"
#include "lullaby/util/math.h"
#include "lullaby/util/trace.h"
#include "lullaby/generated/render_def_generated.h"
namespace lull {
namespace {
constexpr int kRenderPoolPageSize = 32;
const HashValue kRenderDefHash = ConstHash("RenderDef");
constexpr int kNumVec4sInAffineTransform = 3;
constexpr const char* kColorUniform = "color";
constexpr const char* kTextureBoundsUniform = "uv_bounds";
constexpr const char* kClampBoundsUniform = "clamp_bounds";
constexpr const char* kBoneTransformsUniform = "bone_transforms";
constexpr const char* kDefaultMaterialShaderDirectory = "shaders/";
// Shader attribute hashes.
constexpr HashValue kAttributeHashPosition = ConstHash("ATTR_POSITION");
constexpr HashValue kAttributeHashUV = ConstHash("ATTR_UV");
constexpr HashValue kAttributeHashColor = ConstHash("ATTR_COLOR");
constexpr HashValue kAttributeHashNormal = ConstHash("ATTR_NORMAL");
constexpr HashValue kAttributeHashOrientation = ConstHash("ATTR_ORIENTATION");
constexpr HashValue kAttributeHashTangent = ConstHash("ATTR_TANGENT");
constexpr HashValue kAttributeHashBoneIndices = ConstHash("ATTR_BONE_INDICES");
constexpr HashValue kAttributeHashBoneWeights = ConstHash("ATTR_BONE_WEIGHTS");
// Shader feature hashes.
constexpr HashValue kFeatureHashTransform = ConstHash("Transform");
constexpr HashValue kFeatureHashVertexColor = ConstHash("VertexColor");
constexpr HashValue kFeatureHashTexture = ConstHash("Texture");
constexpr HashValue kFeatureHashLight = ConstHash("Light");
constexpr HashValue kFeatureHashSkin = ConstHash("Skin");
constexpr HashValue kFeatureHashUniformColor = ConstHash("UniformColor");
bool IsSupportedUniformDimension(int dimension) {
return (dimension == 1 || dimension == 2 || dimension == 3 ||
dimension == 4 || dimension == 9 || dimension == 16);
}
// TODO(b/78301332) Add more types when supported.
bool IsSupportedUniformType(ShaderDataType type) {
return type >= ShaderDataType_MIN && type <= ShaderDataType_Float4x4;
}
void SetDebugUniform(Shader* shader, const char* name, const float values[4]) {
shader->SetUniform(shader->FindUniform(name), values, 4);
}
HashValue RenderPassObjectEnumToHashValue(RenderPass pass) {
if (pass == RenderPass_Pano) {
return ConstHash("Pano");
} else if (pass == RenderPass_Opaque) {
return ConstHash("Opaque");
} else if (pass == RenderPass_Main) {
return ConstHash("Main");
} else if (pass == RenderPass_OverDraw) {
return ConstHash("OverDraw");
} else if (pass == RenderPass_Debug) {
return ConstHash("Debug");
} else if (pass == RenderPass_Invisible) {
return ConstHash("Invisible");
} else if (pass == RenderPass_OverDrawGlow) {
return ConstHash("OverDrawGlow");
}
return static_cast<HashValue>(pass);
}
fplbase::CullState::FrontFace CullStateFrontFaceFromFrontFace(
RenderFrontFace face) {
switch (face) {
case RenderFrontFace::kClockwise:
return fplbase::CullState::FrontFace::kClockWise;
case RenderFrontFace::kCounterClockwise:
return fplbase::CullState::FrontFace::kCounterClockWise;
}
return fplbase::CullState::FrontFace::kCounterClockWise;
}
bool IsAlphaEnabled(const Material& material) {
auto* blend_state = material.GetBlendState();
if (blend_state && blend_state->enabled) {
return true;
}
return false;
}
bool CheckMeshForBoneIndices(const MeshPtr& mesh) {
if (!mesh) {
return false;
}
return mesh->GetVertexFormat().GetAttributeWithUsage(
VertexAttributeUsage_BoneIndices) != nullptr;
}
// Return environment flags constructed from a vertex format.
std::set<HashValue> CreateEnvironmentFlagsFromVertexFormat(
const VertexFormat& vertex_format) {
std::set<HashValue> environment_flags;
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Position) !=
nullptr) {
environment_flags.insert(kAttributeHashPosition);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_TexCoord) !=
nullptr) {
environment_flags.insert(kAttributeHashUV);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Color) !=
nullptr) {
environment_flags.insert(kAttributeHashColor);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Normal) !=
nullptr) {
environment_flags.insert(kAttributeHashNormal);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Orientation) !=
nullptr) {
environment_flags.insert(kAttributeHashOrientation);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Tangent) !=
nullptr) {
environment_flags.insert(kAttributeHashTangent);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_BoneIndices) !=
nullptr) {
environment_flags.insert(kAttributeHashBoneIndices);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_BoneWeights) !=
nullptr) {
environment_flags.insert(kAttributeHashBoneWeights);
}
return environment_flags;
}
// Return feature flags constructed from a vertex format.
std::set<HashValue> CreateFeatureFlagsFromVertexFormat(
const VertexFormat& vertex_format) {
std::set<HashValue> feature_flags;
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Position) !=
nullptr) {
feature_flags.insert(kFeatureHashTransform);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_TexCoord) !=
nullptr) {
feature_flags.insert(kFeatureHashTexture);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Color) !=
nullptr) {
feature_flags.insert(kFeatureHashVertexColor);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_Normal) !=
nullptr) {
feature_flags.insert(kFeatureHashLight);
}
if (vertex_format.GetAttributeWithUsage(VertexAttributeUsage_BoneIndices) !=
nullptr) {
feature_flags.insert(kFeatureHashSkin);
}
return feature_flags;
}
ShaderDataType FloatDimensionsToUniformType(int dimensions) {
switch (dimensions) {
case 1:
return ShaderDataType_Float1;
case 2:
return ShaderDataType_Float2;
case 3:
return ShaderDataType_Float3;
case 4:
return ShaderDataType_Float4;
case 9:
return ShaderDataType_Float3x3;
case 16:
return ShaderDataType_Float4x4;
default:
LOG(DFATAL) << "Failed to convert dimensions to uniform type.";
return ShaderDataType_Float4;
}
}
} // namespace
RenderSystemNext::RenderPassObject::RenderPassObject()
: components(kRenderPoolPageSize) {
// Initialize the default render state based on an older implementation to
// maintain backwards compatibility.
render_state.cull_state.emplace();
render_state.cull_state->enabled = true;
render_state.cull_state->face = CullFace_Back;
render_state.cull_state->front = FrontFace_CounterClockwise;
render_state.depth_state.emplace();
render_state.depth_state->test_enabled = true;
render_state.depth_state->write_enabled = true;
render_state.depth_state->function = RenderFunction_Less;
render_state.stencil_state.emplace();
render_state.stencil_state->front_function.mask = ~0u;
render_state.stencil_state->back_function.mask = ~0u;
}
RenderSystemNext::RenderSystemNext(Registry* registry,
const RenderSystem::InitParams& init_params)
: System(registry),
sort_order_manager_(registry_),
shading_model_path_(kDefaultMaterialShaderDirectory),
clip_from_model_matrix_func_(CalculateClipFromModelMatrix) {
texture_flag_hashes_.resize(
static_cast<size_t>(MaterialTextureUsage_MAX + 1));
for (int i = MaterialTextureUsage_MIN; i <= MaterialTextureUsage_MAX; ++i) {
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(i);
texture_flag_hashes_[i] =
Hash("Texture_" + std::string(EnumNameMaterialTextureUsage(usage)));
}
if (init_params.enable_stereo_multiview) {
renderer_.EnableMultiview();
}
mesh_factory_ = new MeshFactoryImpl(registry);
registry->Register(std::unique_ptr<MeshFactory>(mesh_factory_));
texture_factory_ = new TextureFactoryImpl(registry);
registry->Register(std::unique_ptr<TextureFactory>(texture_factory_));
shader_factory_ = registry->Create<ShaderFactory>(registry);
texture_atlas_factory_ = registry->Create<TextureAtlasFactory>(registry);
auto* dispatcher = registry->Get<Dispatcher>();
dispatcher->Connect(this, [this](const ParentChangedEvent& event) {
UpdateSortOrder(event.target);
});
dispatcher->Connect(this, [this](const ChildIndexChangedEvent& event) {
UpdateSortOrder(event.target);
});
FunctionBinder* binder = registry->Get<FunctionBinder>();
if (binder) {
binder->RegisterMethod("lull.Render.Show", &RenderSystem::Show);
binder->RegisterMethod("lull.Render.Hide", &RenderSystem::Hide);
binder->RegisterFunction("lull.Render.GetTextureId", [this](Entity entity) {
TexturePtr texture = GetTexture(entity, 0);
return texture ? static_cast<int>(texture->GetResourceId().Get()) : 0;
});
binder->RegisterMethod("lull.Render.SetColor", &RenderSystem::SetColor);
}
}
RenderSystemNext::~RenderSystemNext() {
FunctionBinder* binder = registry_->Get<FunctionBinder>();
if (binder) {
binder->UnregisterFunction("lull.Render.Show");
binder->UnregisterFunction("lull.Render.Hide");
binder->UnregisterFunction("lull.Render.GetTextureId");
binder->UnregisterFunction("lull.Render.SetColor");
}
registry_->Get<Dispatcher>()->DisconnectAll(this);
}
void RenderSystemNext::Initialize() {
InitDefaultRenderPassObjects();
initialized_ = true;
}
void RenderSystemNext::SetStereoMultiviewEnabled(bool enabled) {
if (enabled) {
renderer_.EnableMultiview();
} else {
renderer_.DisableMultiview();
}
}
const TexturePtr& RenderSystemNext::GetWhiteTexture() const {
return texture_factory_->GetWhiteTexture();
}
const TexturePtr& RenderSystemNext::GetInvalidTexture() const {
return texture_factory_->GetInvalidTexture();
}
TexturePtr RenderSystemNext::LoadTexture(const std::string& filename,
bool create_mips) {
TextureParams params;
params.generate_mipmaps = create_mips;
return texture_factory_->LoadTexture(filename, params);
}
TexturePtr RenderSystemNext::GetTexture(HashValue texture_hash) const {
return texture_factory_->GetTexture(texture_hash);
}
void RenderSystemNext::LoadTextureAtlas(const std::string& filename) {
const bool create_mips = false;
texture_atlas_factory_->LoadTextureAtlas(filename, create_mips);
}
MeshPtr RenderSystemNext::LoadMesh(const std::string& filename) {
return mesh_factory_->LoadMesh(filename);
}
TexturePtr RenderSystemNext::CreateTexture(const ImageData& image,
bool create_mips) {
TextureParams params;
params.generate_mipmaps = create_mips;
return texture_factory_->CreateTexture(&image, params);
}
ShaderPtr RenderSystemNext::LoadShader(const std::string& filename) {
ShaderCreateParams params;
params.shading_model = RemoveExtensionFromFilename(filename);
return LoadShader(params);
}
ShaderPtr RenderSystemNext::LoadShader(const ShaderCreateParams& params) {
return shader_factory_->LoadShader(params);
}
void RenderSystemNext::Create(Entity e, HashValue pass) {
RenderPassObject* render_pass = GetRenderPassObject(pass);
if (!render_pass) {
LOG(DFATAL) << "Render pass " << pass << " does not exist!";
return;
}
RenderComponent* component = render_pass->components.Emplace(e);
if (component) {
SetSortOrderOffset(e, pass, 0);
}
}
void RenderSystemNext::Create(Entity e, HashValue type, const Def* def) {
if (type != kRenderDefHash) {
LOG(DFATAL) << "Invalid type passed to Create. Expecting RenderDef!";
return;
}
const RenderDef& data = *ConvertDef<RenderDef>(def);
if (data.font()) {
LOG(DFATAL) << "Deprecated.";
}
HashValue pass_hash = RenderPassObjectEnumToHashValue(data.pass());
RenderPassObject* render_pass = GetRenderPassObject(pass_hash);
if (!render_pass) {
LOG(DFATAL) << "Render pass " << pass_hash << " does not exist!";
}
RenderComponent* component = render_pass->components.Emplace(e);
if (!component) {
LOG(DFATAL) << "RenderComponent for Entity " << e << " inside pass "
<< pass_hash << " already exists.";
return;
}
component->hidden = data.hidden();
if (data.shader()) {
SetShader(e, pass_hash, LoadShader(data.shader()->str()));
}
if (data.textures()) {
for (unsigned int i = 0; i < data.textures()->size(); ++i) {
TextureParams params;
params.generate_mipmaps = data.create_mips();
TexturePtr texture = texture_factory_->LoadTexture(
data.textures()->Get(i)->c_str(), params);
SetTexture(e, pass_hash, i, texture);
}
} else if (data.texture() && data.texture()->size() > 0) {
TextureParams params;
params.generate_mipmaps = data.create_mips();
TexturePtr texture =
texture_factory_->LoadTexture(data.texture()->c_str(), params);
SetTexture(e, pass_hash, 0, texture);
} else if (data.external_texture()) {
SetTextureExternal(e, pass_hash, 0);
}
if (data.color()) {
mathfu::vec4 color;
MathfuVec4FromFbColor(data.color(), &color);
SetUniform(e, pass_hash, kColorUniform, &color[0], 4, 1);
component->default_color = color;
} else if (data.color_hex()) {
mathfu::vec4 color;
MathfuVec4FromFbColorHex(data.color_hex()->c_str(), &color);
SetUniform(e, pass_hash, kColorUniform, &color[0], 4, 1);
component->default_color = color;
}
if (data.uniforms()) {
for (const UniformDef* uniform : *data.uniforms()) {
if (!uniform->name() || !uniform->float_value()) {
LOG(DFATAL) << "Missing required uniform name or value";
continue;
}
if (uniform->dimension() <= 0) {
LOG(DFATAL) << "Uniform dimension must be positive: "
<< uniform->dimension();
continue;
}
if (uniform->count() <= 0) {
LOG(DFATAL) << "Uniform count must be positive: " << uniform->count();
continue;
}
if (uniform->float_value()->size() !=
static_cast<size_t>(uniform->dimension() * uniform->count())) {
LOG(DFATAL) << "Uniform must have dimension x count values: "
<< uniform->float_value()->size();
continue;
}
SetUniform(e, pass_hash, uniform->name()->c_str(),
uniform->float_value()->data(), uniform->dimension(),
uniform->count());
}
}
SetSortOrderOffset(e, pass_hash, data.sort_order_offset());
}
void RenderSystemNext::SetTextureExternal(Entity e, HashValue pass, int unit) {
const TexturePtr texture = texture_factory_->CreateExternalTexture();
SetTexture(e, pass, unit, texture);
}
void RenderSystemNext::PostCreateInit(Entity e, HashValue type,
const Def* def) {
if (type == kRenderDefHash) {
auto& data = *ConvertDef<RenderDef>(def);
HashValue pass_hash = RenderPassObjectEnumToHashValue(data.pass());
if (data.mesh()) {
SetMesh(e, pass_hash, mesh_factory_->LoadMesh(data.mesh()->c_str()));
}
if (data.text()) {
LOG(DFATAL) << "Deprecated.";
} else if (data.quad()) {
const QuadDef& quad_def = *data.quad();
RenderQuad quad;
quad.size = mathfu::vec2(quad_def.size_x(), quad_def.size_y());
quad.verts = mathfu::vec2i(quad_def.verts_x(), quad_def.verts_y());
quad.has_uv = quad_def.has_uv();
quad.corner_radius = quad_def.corner_radius();
quad.corner_verts = quad_def.corner_verts();
if (data.shape_id()) {
quad.id = Hash(data.shape_id()->c_str());
}
SetQuadImpl(e, pass_hash, quad);
}
}
}
void RenderSystemNext::Destroy(Entity e) {
deformations_.erase(e);
for (auto& pass : render_passes_) {
const detail::EntityIdPair entity_id_pair(e, pass.first);
pass.second.components.Destroy(e);
sort_order_manager_.Destroy(entity_id_pair);
}
}
void RenderSystemNext::Destroy(Entity e, HashValue pass) {
const detail::EntityIdPair entity_id_pair(e, pass);
RenderPassObject* render_pass = FindRenderPassObject(pass);
if (!render_pass) {
LOG(DFATAL) << "Render pass " << pass << " does not exist!";
return;
}
render_pass->components.Destroy(e);
deformations_.erase(e);
sort_order_manager_.Destroy(entity_id_pair);
}
void RenderSystemNext::CreateDeferredMeshes() {
while (!deferred_meshes_.empty()) {
DeferredMesh& defer = deferred_meshes_.front();
DeformMesh(defer.entity, defer.pass, &defer.mesh);
SetMesh(defer.entity, defer.pass, defer.mesh, defer.mesh_id);
deferred_meshes_.pop();
}
}
void RenderSystemNext::ProcessTasks() {
LULLABY_CPU_TRACE_CALL();
CreateDeferredMeshes();
}
void RenderSystemNext::WaitForAssetsToLoad() {
CreateDeferredMeshes();
while (registry_->Get<AssetLoader>()->Finalize()) {
}
}
const mathfu::vec4& RenderSystemNext::GetDefaultColor(Entity entity) const {
const RenderComponent* component = FindRenderComponentForEntity(entity);
if (component) {
return component->default_color;
}
return mathfu::kOnes4f;
}
void RenderSystemNext::SetDefaultColor(Entity entity,
const mathfu::vec4& color) {
ForEachComponentOfEntity(
entity, [color](RenderComponent* component, HashValue pass_hash) {
component->default_color = color;
});
}
bool RenderSystemNext::GetColor(Entity entity, mathfu::vec4* color) const {
return GetUniform(entity, kColorUniform, 4, &(*color)[0]);
}
void RenderSystemNext::SetColor(Entity entity, const mathfu::vec4& color) {
SetUniform(entity, kColorUniform, &color[0], 4, 1);
}
void RenderSystemNext::SetUniform(Entity entity, Optional<HashValue> pass,
Optional<int> submesh_index, string_view name,
ShaderDataType type, Span<uint8_t> data,
int count) {
const int material_index = submesh_index ? *submesh_index : -1;
if (pass) {
RenderComponent* component = GetComponent(entity, *pass);
if (component) {
SetUniformImpl(component, material_index, name, type, data, count);
}
} else {
ForEachComponentOfEntity(
entity, [=](RenderComponent* component, HashValue pass) {
SetUniformImpl(component, material_index, name, type, data, count);
});
}
}
void RenderSystemNext::SetUniform(Entity e, const char* name, const float* data,
int dimension, int count) {
SetUniform(e, NullOpt, NullOpt, name, FloatDimensionsToUniformType(dimension),
{reinterpret_cast<const uint8_t*>(data),
static_cast<size_t>(dimension * count * sizeof(float))},
count);
}
void RenderSystemNext::SetUniform(Entity e, HashValue pass, const char* name,
const float* data, int dimension, int count) {
SetUniform(e, pass, NullOpt, name, FloatDimensionsToUniformType(dimension),
{reinterpret_cast<const uint8_t*>(data),
static_cast<size_t>(dimension * count * sizeof(float))},
count);
}
bool RenderSystemNext::GetUniform(Entity entity, Optional<HashValue> pass,
Optional<int> submesh_index, string_view name,
size_t length, uint8_t* data_out) const {
const int material_index = submesh_index ? *submesh_index : -1;
const RenderComponent* component =
pass ? GetComponent(entity, *pass) : FindRenderComponentForEntity(entity);
return GetUniformImpl(component, material_index, name, length, data_out);
}
bool RenderSystemNext::GetUniform(Entity e, const char* name, size_t length,
float* data_out) const {
return GetUniform(e, NullOpt, NullOpt, name, length * sizeof(float),
reinterpret_cast<uint8_t*>(data_out));
}
bool RenderSystemNext::GetUniform(Entity e, HashValue pass, const char* name,
size_t length, float* data_out) const {
return GetUniform(e, pass, NullOpt, name, length * sizeof(float),
reinterpret_cast<uint8_t*>(data_out));
}
void RenderSystemNext::SetUniformImpl(RenderComponent* component,
int material_index, string_view name,
ShaderDataType type, Span<uint8_t> data,
int count) {
if (component == nullptr) {
return;
}
if (!IsSupportedUniformType(type)) {
LOG(DFATAL) << "ShaderDataType not supported: " << type;
return;
}
// Do not allow partial data in this function.
if (data.size() != UniformData::ShaderDataTypeToBytesSize(type) * count) {
LOG(DFATAL) << "Partial uniform data is not allowed through "
"RenderSystem::SetUniform.";
return;
}
if (material_index < 0) {
for (const std::shared_ptr<Material>& material : component->materials) {
SetUniformImpl(material.get(), name, type, data, count);
}
SetUniformImpl(&component->default_material, name, type, data, count);
} else if (material_index < static_cast<int>(component->materials.size())) {
const std::shared_ptr<Material>& material =
component->materials[material_index];
SetUniformImpl(material.get(), name, type, data, count);
} else {
LOG(DFATAL);
return;
}
if (component->uniform_changed_callback) {
component->uniform_changed_callback(material_index, name, type, data,
count);
}
}
void RenderSystemNext::SetUniformImpl(Material* material,
string_view name, ShaderDataType type,
Span<uint8_t> data, int count) {
if (material == nullptr) {
return;
}
CHECK(count == data.size() / UniformData::ShaderDataTypeToBytesSize(type));
material->SetUniform(Hash(name), type, data);
}
bool RenderSystemNext::GetUniformImpl(const RenderComponent* component,
int material_index, string_view name,
size_t length, uint8_t* data_out) const {
if (component == nullptr) {
return false;
}
if (material_index < 0) {
for (const std::shared_ptr<Material>& material : component->materials) {
if (GetUniformImpl(material.get(), name, length, data_out)) {
return true;
}
}
return GetUniformImpl(&component->default_material, name, length, data_out);
} else if (material_index < static_cast<int>(component->materials.size())) {
const std::shared_ptr<Material>& material =
component->materials[material_index];
return GetUniformImpl(material.get(), name, length, data_out);
}
return false;
}
bool RenderSystemNext::GetUniformImpl(const Material* material,
string_view name, size_t length,
uint8_t* data_out) const {
if (material == nullptr) {
return false;
}
const UniformData* uniform = material->GetUniformData(Hash(name));
if (uniform == nullptr) {
return false;
}
if (length > uniform->Size()) {
return false;
}
memcpy(data_out, uniform->GetData<uint8_t>(), length);
return true;
}
void RenderSystemNext::CopyUniforms(Entity entity, Entity source) {
LOG(WARNING) << "CopyUniforms is going to be deprecated! Do not use this.";
RenderComponent* component = FindRenderComponentForEntity(entity);
const RenderComponent* source_component =
FindRenderComponentForEntity(source);
if (!component || component->materials.empty() || !source_component ||
source_component->materials.empty()) {
return;
}
// TODO(b/68673920): Copied data may not be correct.
const bool copy_per_material =
(source_component->materials.size() == component->materials.size());
for (size_t index = 0; index < component->materials.size(); ++index) {
Material& destination_material = *component->materials[index];
const Material& source_material = copy_per_material
? *source_component->materials[index]
: *source_component->materials[0];
destination_material.CopyUniforms(source_material);
}
}
void RenderSystemNext::SetUniformChangedCallback(
Entity entity, HashValue pass,
RenderSystem::UniformChangedCallback callback) {
RenderComponent* component = GetComponent(entity, pass);
if (!component) {
return;
}
component->uniform_changed_callback = std::move(callback);
}
void RenderSystemNext::OnTextureLoaded(const RenderComponent& component,
HashValue pass, int unit,
const TexturePtr& texture) {
const Entity entity = component.GetEntity();
const mathfu::vec4 clamp_bounds = texture->CalculateClampBounds();
SetUniform(entity, kClampBoundsUniform, &clamp_bounds[0], 4, 1);
if (texture && texture->GetResourceId()) {
// TODO(b/38130323) Add CheckTextureSizeWarning that does not depend on HMD.
SendEvent(registry_, entity, TextureReadyEvent(entity, unit));
if (IsReadyToRenderImpl(component)) {
SendEvent(registry_, entity, ReadyToRenderEvent(entity, pass));
}
}
}
void RenderSystemNext::SetTexture(Entity e, int unit,
const TexturePtr& texture) {
ForEachComponentOfEntity(e, [&](RenderComponent* component, HashValue pass) {
SetTexture(e, pass, unit, texture);
});
}
void RenderSystemNext::SetTexture(Entity e, HashValue pass, int unit,
const TexturePtr& texture) {
auto* render_component = GetComponent(e, pass);
if (!render_component) {
return;
}
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(unit);
render_component->default_material.SetTexture(usage, texture);
for (auto& material : render_component->materials) {
const bool new_texture_usage =
material->GetTexture(usage) != nullptr && texture != nullptr;
material->SetTexture(usage, texture);
if (new_texture_usage) {
// Update the shader to add the new texture usage environment flag.
ShaderPtr shader = material->GetShader();
if (shader && !shader->GetDescription().shading_model.empty()) {
const ShaderCreateParams shader_params = CreateShaderParams(
shader->GetDescription().shading_model, render_component, material);
shader = shader_factory_->LoadShader(shader_params);
material->SetShader(shader);
}
}
}
// Add subtexture coordinates so the vertex shaders will pick them up. These
// are known when the texture is created; no need to wait for load.
if (texture) {
SetUniform(e, pass, kTextureBoundsUniform, &texture->UvBounds()[0], 4, 1);
}
}
TexturePtr RenderSystemNext::CreateProcessedTexture(
const TexturePtr& texture, bool create_mips,
const RenderSystem::TextureProcessor& processor,
const mathfu::vec2i& output_dimensions) {
LULLABY_CPU_TRACE_CALL();
if (!texture) {
LOG(DFATAL) << "null texture passed to CreateProcessedTexture()";
return TexturePtr();
}
// Make and bind a framebuffer for rendering to texture.
GLuint framebuffer_id, current_framebuffer_id;
GL_CALL(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING,
reinterpret_cast<GLint*>(¤t_framebuffer_id)));
GL_CALL(glGenFramebuffers(1, &framebuffer_id));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id));
// Make an empty FPL texture for the render target, sized to the specified
// dimensions.
mathfu::vec2i size = output_dimensions;
bool target_is_subtexture = false;
float texture_u_bound = 1.f;
float texture_v_bound = 1.f;
// If the input texture is a subtexture, scale the size appropriately.
if (texture->IsSubtexture()) {
auto scale = mathfu::vec2(texture->UvBounds().z, texture->UvBounds().w);
auto size_f = scale * mathfu::vec2(static_cast<float>(size.x),
static_cast<float>(size.y));
size =
mathfu::vec2i(static_cast<int>(size_f.x), static_cast<int>(size_f.y));
}
// If we don't support NPOT and the texture is NPOT, use UV bounds to work
// around this.
if (!GlSupportsTextureNpot() &&
(!IsPowerOf2(size.x) || !IsPowerOf2(size.y))) {
target_is_subtexture = true;
uint32_t next_power_of_two_x =
mathfu::RoundUpToPowerOf2(static_cast<uint32_t>(size.x));
uint32_t next_power_of_two_y =
mathfu::RoundUpToPowerOf2(static_cast<uint32_t>(size.y));
texture_u_bound =
static_cast<float>(size.x) / static_cast<float>(next_power_of_two_x);
texture_v_bound =
static_cast<float>(size.y) / static_cast<float>(next_power_of_two_y);
size = mathfu::vec2i(next_power_of_two_x, next_power_of_two_y);
}
TextureParams params;
params.format = ImageData::kRgba8888;
params.generate_mipmaps = create_mips;
TexturePtr out_ptr = texture_factory_->CreateTexture(size, params);
if (target_is_subtexture) {
const mathfu::vec4 bounds(0.f, 0.f, texture_u_bound, texture_v_bound);
out_ptr = texture_factory_->CreateSubtexture(out_ptr, bounds);
}
// Bind the output texture to the framebuffer as the color attachment.
GL_CALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, out_ptr->GetResourceId().Get(),
0));
#if defined(DEBUG)
// Check for completeness of the framebuffer.
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
LOG(DFATAL) << "Failed to create offscreen framebuffer: " << std::hex
<< glCheckFramebufferStatus(GL_FRAMEBUFFER);
}
#endif
// Subtexturing on output texture can pick up sample noise around the edges
// of the rendered area. Clear to transparent black.
if (target_is_subtexture) {
GL_CALL(glClearColor(0.f, 0.f, 0.f, 0.f));
GL_CALL(glClear(GL_COLOR_BUFFER_BIT));
}
processor(out_ptr);
// Setup viewport, input texture, shader, and draw quad.
SetViewport(mathfu::recti(mathfu::kZeros2i, size));
// We render a quad starting in the lower left corner and extending up and
// right for as long as the output subtexture is needed.
const float width = texture_u_bound * 2.f;
const float height = texture_v_bound * 2.f;
const mathfu::vec4& uv_rect = texture->UvBounds();
DrawQuad(mathfu::vec3(-1.f, -1.f, 0.f),
mathfu::vec3(width - 1.f, height - 1.f, 0),
mathfu::vec2(uv_rect.x, uv_rect.y),
mathfu::vec2(uv_rect.x + uv_rect.z, uv_rect.y + uv_rect.w));
// Delete framebuffer, we retain the texture.
GL_CALL(glDeleteFramebuffers(1, &framebuffer_id));
// Regenerate Mipmaps on the processed texture.
if (create_mips) {
out_ptr->Bind(0);
GL_CALL(glGenerateMipmap(GL_TEXTURE_2D));
}
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, current_framebuffer_id));
return out_ptr;
}
TexturePtr RenderSystemNext::CreateProcessedTexture(
const TexturePtr& texture, bool create_mips,
const RenderSystem::TextureProcessor& processor) {
auto size = texture->GetDimensions();
return CreateProcessedTexture(texture, create_mips, processor, size);
}
void RenderSystemNext::SetTextureId(Entity e, int unit, uint32_t texture_target,
uint32_t texture_id) {
ForEachComponentOfEntity(
e, [this, e, unit, texture_target, texture_id](
RenderComponent* render_component, HashValue pass) {
SetTextureId(e, pass, unit, texture_target, texture_id);
});
}
void RenderSystemNext::SetTextureId(Entity e, HashValue pass, int unit,
uint32_t texture_target,
uint32_t texture_id) {
auto* render_component = GetComponent(e, pass);
if (!render_component) {
return;
}
auto texture = texture_factory_->CreateTexture(texture_target, texture_id);
SetTexture(e, pass, unit, texture);
}
TexturePtr RenderSystemNext::GetTexture(Entity entity, int unit) const {
const auto* render_component = FindRenderComponentForEntity(entity);
if (!render_component || render_component->materials.empty()) {
return TexturePtr();
}
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(unit);
return render_component->materials[0]->GetTexture(usage);
}
bool RenderSystemNext::GetQuad(Entity e, RenderQuad* quad) const {
const auto* render_component = FindRenderComponentForEntity(e);
if (!render_component) {
return false;
}
*quad = render_component->quad;
return true;
}
void RenderSystemNext::SetQuad(Entity e, const RenderQuad& quad) {
ForEachComponentOfEntity(
e, [this, e, quad](RenderComponent* render_component, HashValue pass) {
SetQuadImpl(e, pass, quad);
});
}
void RenderSystemNext::SetQuadImpl(Entity e, HashValue pass,
const RenderQuad& quad) {
const detail::EntityIdPair entity_id_pair(e, pass);
auto* render_component = GetComponent(e, pass);
if (!render_component) {
LOG(WARNING) << "Missing entity for SetQuad: " << entity_id_pair.entity
<< ", with id: " << entity_id_pair.id;
return;
}
render_component->quad = quad;
MeshData mesh;
if (quad.has_uv) {
mesh = CreateQuadMesh<VertexPT>(quad.size.x, quad.size.y, quad.verts.x,
quad.verts.y, quad.corner_radius,
quad.corner_verts, quad.corner_mask);
} else {
mesh = CreateQuadMesh<VertexP>(quad.size.x, quad.size.y, quad.verts.x,
quad.verts.y, quad.corner_radius,
quad.corner_verts, quad.corner_mask);
}
auto iter = deformations_.find(e);
if (iter != deformations_.end()) {
DeferredMesh defer;
defer.entity = e;
defer.pass = pass;
defer.mesh_id = quad.id;
defer.mesh = std::move(mesh);
deferred_meshes_.push(std::move(defer));
} else {
SetMesh(e, pass, mesh, quad.id);
}
}
void RenderSystemNext::SetMesh(Entity e, const MeshData& mesh) {
ForEachComponentOfEntity(e, [&](RenderComponent* render_component,
HashValue pass) { SetMesh(e, pass, mesh); });
}
void RenderSystemNext::SetMesh(Entity entity, HashValue pass,
const MeshData& mesh, HashValue mesh_id) {
MeshPtr gpu_mesh;
if (mesh_id != 0) {
gpu_mesh = mesh_factory_->CreateMesh(mesh_id, &mesh);
} else {
gpu_mesh = mesh_factory_->CreateMesh(&mesh);
}
SetMesh(entity, pass, gpu_mesh);
}
void RenderSystemNext::SetMesh(Entity entity, HashValue pass,
const MeshData& mesh) {
const HashValue mesh_id = 0;
SetMesh(entity, pass, mesh, mesh_id);
}
void RenderSystemNext::SetAndDeformMesh(Entity entity, const MeshData& mesh) {
ForEachComponentOfEntity(
entity, [&](RenderComponent* render_component, HashValue pass) {
SetAndDeformMesh(entity, pass, mesh);
});
}
void RenderSystemNext::SetAndDeformMesh(Entity entity, HashValue pass,
const MeshData& mesh) {
if (mesh.GetVertexBytes() == nullptr) {
LOG(WARNING) << "Can't deform mesh without read access.";
SetMesh(entity, pass, mesh);
return;
}
auto iter = deformations_.find(entity);
if (iter != deformations_.end()) {
DeferredMesh defer;
defer.entity = entity;
defer.pass = pass;
defer.mesh = mesh.CreateHeapCopy();
deferred_meshes_.emplace(std::move(defer));
} else {
SetMesh(entity, pass, mesh);
}
}
void RenderSystemNext::SetMesh(Entity e, const std::string& file) {
SetMesh(e, mesh_factory_->LoadMesh(file));
}
RenderSortOrder RenderSystemNext::GetSortOrder(Entity e) const {
const auto* component = FindRenderComponentForEntity(e);
if (!component) {
return 0;
}
return component->sort_order;
}
RenderSortOrderOffset RenderSystemNext::GetSortOrderOffset(Entity e) const {
return sort_order_manager_.GetOffset(e);
}
void RenderSystemNext::SetSortOrderOffset(
Entity e, RenderSortOrderOffset sort_order_offset) {
ForEachComponentOfEntity(
e, [this, e, sort_order_offset](RenderComponent* render_component,
HashValue pass) {
SetSortOrderOffset(e, pass, sort_order_offset);
});
}
void RenderSystemNext::SetSortOrderOffset(
Entity e, HashValue pass, RenderSortOrderOffset sort_order_offset) {
const detail::EntityIdPair entity_id_pair(e, pass);
sort_order_manager_.SetOffset(entity_id_pair, sort_order_offset);
sort_order_manager_.UpdateSortOrder(
entity_id_pair, [this](detail::EntityIdPair entity_id_pair) {
return GetComponent(entity_id_pair.entity, entity_id_pair.id);
});
}
bool RenderSystemNext::IsTextureSet(Entity e, int unit) const {
auto* render_component = FindRenderComponentForEntity(e);
if (!render_component || render_component->materials.empty()) {
return false;
}
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(unit);
return render_component->materials[0]->GetTexture(usage) != nullptr;
}
bool RenderSystemNext::IsTextureLoaded(Entity e, int unit) const {
const auto* render_component = FindRenderComponentForEntity(e);
if (!render_component || render_component->materials.empty()) {
return false;
}
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(unit);
if (!render_component->materials[0]->GetTexture(usage)) {
return false;
}
return render_component->materials[0]->GetTexture(usage)->IsLoaded();
}
bool RenderSystemNext::IsTextureLoaded(const TexturePtr& texture) const {
return texture->IsLoaded();
}
bool RenderSystemNext::IsReadyToRender(Entity entity) const {
const auto* render_component = FindRenderComponentForEntity(entity);
if (!render_component) {
// No component, no textures, no fonts, no problem.
return true;
}
return IsReadyToRenderImpl(*render_component);
}
bool RenderSystemNext::IsReadyToRender(Entity entity, HashValue pass) const {
const auto* render_component = GetComponent(entity, pass);
return !render_component || IsReadyToRenderImpl(*render_component);
}
bool RenderSystemNext::IsReadyToRenderImpl(
const RenderComponent& component) const {
if (component.mesh && !component.mesh->IsLoaded()) {
return false;
}
for (const auto& material : component.materials) {
if (material->GetShader() == nullptr) {
return false;
}
for (int i = MaterialTextureUsage_MIN; i <= MaterialTextureUsage_MAX; ++i) {
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(i);
TexturePtr texture = material->GetTexture(usage);
if (texture && !texture->IsLoaded()) {
return false;
}
}
}
return true;
}
bool RenderSystemNext::IsHidden(Entity e) const {
const auto* render_component = FindRenderComponentForEntity(e);
const bool render_component_hidden =
render_component && render_component->hidden;
// If there are no models associated with this entity, then it is hidden.
// Otherwise, it is hidden if the RenderComponent is hidden.
return (render_component_hidden || !render_component);
}
ShaderPtr RenderSystemNext::GetShader(Entity entity, HashValue pass) const {
const RenderComponent* component = GetComponent(entity, pass);
if (!component || component->materials.empty()) {
return ShaderPtr();
}
return component->materials[0]->GetShader();
}
ShaderPtr RenderSystemNext::GetShader(Entity entity) const {
const RenderComponent* component = FindRenderComponentForEntity(entity);
if (!component || component->materials.empty()) {
return ShaderPtr();
}
return component->materials[0]->GetShader();
}
void RenderSystemNext::SetShader(Entity e, const ShaderPtr& shader) {
ForEachComponentOfEntity(
e, [this, e, shader](RenderComponent* render_component, HashValue pass) {
SetShader(e, pass, shader);
});
}
void RenderSystemNext::SetShader(Entity e, HashValue pass,
const ShaderPtr& shader) {
auto* render_component = GetComponent(e, pass);
if (!render_component) {
return;
}
// If there are no materials, resize to have at least one. This is needed
// because the mesh loading is asynchronous and the materials may not have
// been set. Without this, the shader setting will not be saved.
// This is also needed when only a RenderDef is used.
if (render_component->materials.empty()) {
render_component->materials.emplace_back(
std::make_shared<Material>(render_component->default_material));
}
for (auto& material : render_component->materials) {
material->SetShader(shader);
}
render_component->default_material.SetShader(shader);
}
void RenderSystemNext::SetShadingModelPath(const std::string& path) {
shading_model_path_ = path;
}
std::shared_ptr<Material> RenderSystemNext::CreateMaterialFromMaterialInfo(
RenderComponent* render_component, const MaterialInfo& info) {
std::shared_ptr<Material> material =
std::make_shared<Material>(render_component->default_material);
for (int i = MaterialTextureUsage_MIN; i <= MaterialTextureUsage_MAX; ++i) {
MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(i);
const std::string& name = info.GetTexture(usage);
if (!name.empty()) {
TextureParams params;
params.generate_mipmaps = true;
TexturePtr texture = texture_factory_->LoadTexture(name, params);
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(i);
material->SetTexture(usage, texture);
material->SetUniform<float>(Hash(kTextureBoundsUniform),
ShaderDataType_Float4,
{&texture->UvBounds()[0], 1});
}
}
material->ApplyProperties(info.GetProperties());
const std::string shading_model =
shading_model_path_ + info.GetShadingModel();
ShaderPtr shader;
if (render_component->mesh && render_component->mesh->IsLoaded()) {
const ShaderCreateParams shader_params =
CreateShaderParams(shading_model, render_component, material);
shader = shader_factory_->LoadShader(shader_params);
} else {
shader = std::make_shared<Shader>(Shader::Description(shading_model));
}
material->SetShader(shader);
return material;
}
void RenderSystemNext::SetMaterial(Entity e, Optional<HashValue> pass,
Optional<int> submesh_index,
const MaterialInfo& material_info) {
if (pass) {
auto* render_component = GetComponent(e, *pass);
if (submesh_index) {
SetMaterialImpl(render_component, *pass, *submesh_index, material_info);
} else {
SetMaterialImpl(render_component, *pass, material_info);
}
} else {
ForEachComponentOfEntity(
e, [&](RenderComponent* render_component, HashValue pass_hash) {
if (submesh_index) {
SetMaterialImpl(render_component, pass_hash, *submesh_index,
material_info);
} else {
SetMaterialImpl(render_component, pass_hash, material_info);
}
});
}
}
void RenderSystemNext::SetMaterialImpl(RenderComponent* render_component,
HashValue pass_hash,
const MaterialInfo& material_info) {
if (!render_component) {
return;
}
if (render_component->materials.empty()) {
render_component->default_material =
*CreateMaterialFromMaterialInfo(render_component, material_info);
} else {
for (int i = 0; i < render_component->materials.size(); ++i) {
SetMaterialImpl(render_component, pass_hash, i, material_info);
}
}
}
void RenderSystemNext::SetMaterialImpl(RenderComponent* render_component,
HashValue pass_hash, int submesh_index,
const MaterialInfo& material_info) {
if (!render_component) {
return;
}
std::shared_ptr<Material> material =
CreateMaterialFromMaterialInfo(render_component, material_info);
if (render_component->materials.size() <=
static_cast<size_t>(submesh_index)) {
render_component->materials.resize(submesh_index + 1);
}
render_component->materials[submesh_index] = material;
for (int i = MaterialTextureUsage_MIN; i <= MaterialTextureUsage_MAX; ++i) {
const auto usage = static_cast<MaterialTextureUsage>(i);
TexturePtr texture = material->GetTexture(usage);
if (!texture) {
continue;
}
const Entity entity = render_component->GetEntity();
auto callback = [this, usage, entity, pass_hash, texture]() {
RenderComponent* render_component = GetComponent(entity, pass_hash);
if (render_component) {
for (auto& material : render_component->materials) {
if (material->GetTexture(usage) == texture) {
OnTextureLoaded(*render_component, pass_hash, usage, texture);
}
}
}
};
texture->AddOrInvokeOnLoadCallback(callback);
}
}
void RenderSystemNext::OnMeshLoaded(RenderComponent* render_component,
HashValue pass) {
const Entity entity = render_component->GetEntity();
auto* transform_system = registry_->Get<TransformSystem>();
transform_system->SetAabb(entity, render_component->mesh->GetAabb());
MeshPtr& mesh = render_component->mesh;
if (render_component->materials.size() != mesh->GetNumSubmeshes()) {
std::shared_ptr<Material> copy_material;
if (render_component->materials.empty()) {
copy_material =
std::make_shared<Material>(render_component->default_material);
} else {
copy_material = render_component->materials[0];
}
render_component->materials.resize(mesh->GetNumSubmeshes());
if (mesh->GetNumSubmeshes() != 0) {
render_component->materials[0] = copy_material;
for (size_t i = 1; i < mesh->GetNumSubmeshes(); ++i) {
render_component->materials[i] =
std::make_shared<Material>(*copy_material);
}
}
}
for (auto& material : render_component->materials) {
if (material->GetShader() &&
!material->GetShader()->GetDescription().shading_model.empty()) {
const ShaderCreateParams shader_params = CreateShaderParams(
material->GetShader()->GetDescription().shading_model,
render_component, material);
material->SetShader(shader_factory_->LoadShader(shader_params));
}
}
auto* rig_system = registry_->Get<RigSystem>();
const size_t num_shader_bones =
std::max(mesh->TryUpdateRig(rig_system, entity),
CheckMeshForBoneIndices(mesh) ? size_t(1) : size_t(0));
if (num_shader_bones > 0) {
// By default, clear the bone transforms to identity.
const int count =
kNumVec4sInAffineTransform * static_cast<int>(num_shader_bones);
const mathfu::AffineTransform identity =
mathfu::mat4::ToAffineTransform(mathfu::mat4::Identity());
shader_transforms_.clear();
shader_transforms_.resize(num_shader_bones, identity);
constexpr int dimension = 4;
const float* data = &(shader_transforms_[0][0]);
SetUniform(entity, pass, kBoneTransformsUniform, data, dimension, count);
}
if (IsReadyToRenderImpl(*render_component)) {
SendEvent(registry_, entity, ReadyToRenderEvent(entity, pass));
}
}
void RenderSystemNext::SetMesh(Entity e, const MeshPtr& mesh) {
ForEachComponentOfEntity(e, [&](RenderComponent* render_component,
HashValue pass) { SetMesh(e, pass, mesh); });
}
void RenderSystemNext::SetMesh(Entity e, HashValue pass, const MeshPtr& mesh) {
auto* render_component = GetComponent(e, pass);
if (!render_component) {
LOG(WARNING) << "Missing RenderComponent, "
<< "skipping mesh update for entity: " << e
<< ", inside pass: " << pass;
return;
}
render_component->mesh = mesh;
if (render_component->mesh) {
MeshPtr callback_mesh = render_component->mesh;
auto callback = [this, e, pass, callback_mesh]() {
RenderComponent* render_component = GetComponent(e, pass);
if (render_component && render_component->mesh == callback_mesh) {
OnMeshLoaded(render_component, pass);
}
};
render_component->mesh->AddOrInvokeOnLoadCallback(callback);
}
SendEvent(registry_, e, MeshChangedEvent(e, pass));
}
MeshPtr RenderSystemNext::GetMesh(Entity e, HashValue pass) {
auto* render_component = GetComponent(e, pass);
if (!render_component) {
LOG(WARNING) << "Missing RenderComponent for entity: " << e
<< ", inside pass: " << pass;
return nullptr;
}
return render_component->mesh;
}
void RenderSystemNext::DeformMesh(Entity entity, HashValue pass,
MeshData* mesh) {
auto iter = deformations_.find(entity);
const RenderSystem::DeformationFn deform =
iter != deformations_.end() ? iter->second : nullptr;
if (deform) {
deform(mesh);
}
}
void RenderSystemNext::SetStencilMode(Entity e, RenderStencilMode mode,
int value) {
ForEachComponentOfEntity(
e, [this, e, mode, value](RenderComponent* render_component,
HashValue pass) {
SetStencilMode(e, pass, mode, value);
});
}
void RenderSystemNext::SetStencilMode(Entity e, HashValue pass,
RenderStencilMode mode, int value) {
// Stencil mask setting all the bits to be 1.
static constexpr uint32_t kStencilMaskAllBits = ~0;
auto* render_component = GetComponent(e, pass);
if (!render_component) {
return;
}
StencilStateT stencil_state;
switch (mode) {
case RenderStencilMode::kDisabled:
stencil_state.enabled = false;
break;
case RenderStencilMode::kTest:
stencil_state.enabled = true;
stencil_state.front_function.function = RenderFunction_Equal;
stencil_state.front_function.ref = value;
stencil_state.front_function.mask = kStencilMaskAllBits;
stencil_state.back_function = stencil_state.front_function;
stencil_state.front_op.stencil_fail = StencilAction_Keep;
stencil_state.front_op.depth_fail = StencilAction_Keep;
stencil_state.front_op.pass = StencilAction_Keep;
stencil_state.back_op = stencil_state.front_op;
break;
case RenderStencilMode::kWrite:
stencil_state.enabled = true;
stencil_state.front_function.function = RenderFunction_Always;
stencil_state.front_function.ref = value;
stencil_state.front_function.mask = kStencilMaskAllBits;
stencil_state.back_function = stencil_state.front_function;
stencil_state.front_op.stencil_fail = StencilAction_Keep;
stencil_state.front_op.depth_fail = StencilAction_Keep;
stencil_state.front_op.pass = StencilAction_Replace;
stencil_state.back_op = stencil_state.front_op;
break;
}
for (auto& material : render_component->materials) {
material->SetStencilState(&stencil_state);
}
}
void RenderSystemNext::SetDeformationFunction(
Entity e, const RenderSystem::DeformationFn& deform) {
if (deform) {
deformations_.emplace(e, deform);
} else {
deformations_.erase(e);
}
}
void RenderSystemNext::Hide(Entity e) {
ForEachComponentOfEntity(
e, [this, e](RenderComponent* render_component, HashValue pass_hash) {
if (!render_component->hidden) {
render_component->hidden = true;
SendEvent(registry_, e, HiddenEvent(e));
}
});
}
void RenderSystemNext::Show(Entity e) {
ForEachComponentOfEntity(
e, [this, e](RenderComponent* render_component, HashValue pass_hash) {
if (render_component->hidden) {
render_component->hidden = false;
SendEvent(registry_, e, UnhiddenEvent(e));
}
});
}
HashValue RenderSystemNext::GetRenderPass(Entity entity) const {
LOG(ERROR) << "GetRenderPass is not supported in render system next.";
return 0;
}
std::vector<HashValue> RenderSystemNext::GetRenderPasses(Entity entity) const {
std::vector<HashValue> passes;
ForEachComponentOfEntity(
entity, [&passes](const RenderComponent& /*component*/, HashValue pass) {
passes.emplace_back(pass);
});
return passes;
}
void RenderSystemNext::SetRenderPass(Entity e, HashValue pass) {
LOG(ERROR) << "SetRenderPass is not supported in render system next.";
}
void RenderSystemNext::SetClearParams(HashValue pass,
const RenderClearParams& clear_params) {
RenderPassObject* render_pass = GetRenderPassObject(pass);
if (!render_pass) {
LOG(DFATAL) << "Render pass " << pass << " does not exist!";
return;
}
render_pass->clear_params = clear_params;
}
void RenderSystemNext::SetDefaultRenderPass(HashValue pass) {
default_pass_ = pass;
}
HashValue RenderSystemNext::GetDefaultRenderPass() const {
return default_pass_;
}
SortMode RenderSystemNext::GetSortMode(HashValue pass) const {
const RenderPassObject* render_pass_object = FindRenderPassObject(pass);
if (render_pass_object) {
return render_pass_object->sort_mode;
}
return SortMode_None;
}
void RenderSystemNext::SetSortMode(HashValue pass, SortMode mode) {
RenderPassObject* render_pass_object = GetRenderPassObject(pass);
if (render_pass_object) {
render_pass_object->sort_mode = mode;
}
}
void RenderSystemNext::SetSortVector(HashValue pass,
const mathfu::vec3& vector) {
LOG(DFATAL) << "Unimplemented";
}
RenderCullMode RenderSystemNext::GetCullMode(HashValue pass) {
const RenderPassObject* render_pass_object = FindRenderPassObject(pass);
if (render_pass_object) {
return render_pass_object->cull_mode;
}
return RenderCullMode::kNone;
}
void RenderSystemNext::SetCullMode(HashValue pass, RenderCullMode mode) {
RenderPassObject* render_pass_object = GetRenderPassObject(pass);
if (render_pass_object) {
render_pass_object->cull_mode = mode;
}
}
void RenderSystemNext::SetDefaultFrontFace(RenderFrontFace face) {
CHECK(!initialized_) << "Must set the default FrontFace before Initialize";
default_front_face_ = face;
}
void RenderSystemNext::SetRenderState(HashValue pass,
const fplbase::RenderState& state) {
RenderPassObject* render_pass_object = GetRenderPassObject(pass);
if (render_pass_object) {
render_pass_object->render_state = Convert(state);
}
}
void RenderSystemNext::SetViewport(const RenderView& view) {
LULLABY_CPU_TRACE_CALL();
SetViewport(mathfu::recti(view.viewport, view.dimensions));
}
void RenderSystemNext::SetClipFromModelMatrix(const mathfu::mat4& mvp) {
model_view_projection_ = mvp;
}
void RenderSystemNext::SetClipFromModelMatrixFunction(
const RenderSystem::ClipFromModelMatrixFn& func) {
if (!func) {
clip_from_model_matrix_func_ = CalculateClipFromModelMatrix;
return;
}
clip_from_model_matrix_func_ = func;
}
mathfu::vec4 RenderSystemNext::GetClearColor() const { return clear_color_; }
void RenderSystemNext::SetClearColor(float r, float g, float b, float a) {
RenderClearParams clear_params;
clear_params.clear_options = RenderClearParams::kColor |
RenderClearParams::kDepth |
RenderClearParams::kStencil;
clear_params.color_value = mathfu::vec4(r, g, b, a);
SetClearParams(ConstHash("ClearDisplay"), clear_params);
}
void RenderSystemNext::SubmitRenderData() {
RenderData* data = render_data_buffer_.LockWriteBuffer();
if (!data) {
return;
}
data->clear();
const auto* transform_system = registry_->Get<TransformSystem>();
for (const auto& iter : render_passes_) {
RenderPassDrawContainer& pass_container = (*data)[iter.first];
// Copy the pass' properties.
pass_container.clear_params = iter.second.clear_params;
auto target = render_targets_.find(iter.second.render_target);
if (target != render_targets_.end()) {
pass_container.render_target = target->second.get();
}
RenderLayer& opaque_layer =
pass_container.layers[RenderPassDrawContainer::kOpaque];
RenderLayer& blend_layer =
pass_container.layers[RenderPassDrawContainer::kBlendEnabled];
// Assign sort modes.
if (iter.second.sort_mode == SortMode_Optimized) {
// If user set optimized, set the best expected sort modes depending on
// the blend mode.
opaque_layer.sort_mode = SortMode_AverageSpaceOriginFrontToBack;
blend_layer.sort_mode = SortMode_AverageSpaceOriginBackToFront;
} else {
// Otherwise assign the user's chosen sort modes.
for (RenderLayer& layer : pass_container.layers) {
layer.cull_mode = iter.second.cull_mode;
layer.sort_mode = iter.second.sort_mode;
}
}
// Set the render states.
// Opaque remains as is.
const RenderStateT& pass_render_state = iter.second.render_state;
opaque_layer.render_state = pass_render_state;
if (pass_render_state.blend_state &&
pass_render_state.blend_state->enabled) {
blend_layer.render_state = pass_render_state;
} else {
// Blend requires z-write off and blend mode on.
RenderStateT render_state = pass_render_state;
if (!render_state.blend_state) {
render_state.blend_state.emplace();
}
if (!render_state.depth_state) {
render_state.depth_state.emplace();
}
render_state.blend_state->enabled = true;
render_state.blend_state->src_alpha = BlendFactor_One;
render_state.blend_state->src_color = BlendFactor_One;
render_state.blend_state->dst_alpha = BlendFactor_OneMinusSrcAlpha;
render_state.blend_state->dst_color = BlendFactor_OneMinusSrcAlpha;
render_state.depth_state->write_enabled = false;
// Assign the render state.
blend_layer.render_state = render_state;
}
iter.second.components.ForEach(
[&](const RenderComponent& render_component) {
if (render_component.hidden) {
return;
}
if (!render_component.mesh ||
render_component.mesh->GetNumSubmeshes() == 0) {
return;
}
const Entity entity = render_component.GetEntity();
if (entity == kNullEntity) {
return;
}
const mathfu::mat4* world_from_entity_matrix =
transform_system->GetWorldFromEntityMatrix(entity);
if (world_from_entity_matrix == nullptr ||
!transform_system->IsEnabled(entity)) {
return;
}
RenderObject obj;
obj.mesh = render_component.mesh;
obj.world_from_entity_matrix = *world_from_entity_matrix;
// Add each material as a single render object where each material
// references a submesh.
for (size_t i = 0; i < render_component.materials.size(); ++i) {
obj.material = render_component.materials[i];
if (!obj.material || !obj.material->GetShader()) {
continue;
}
obj.submesh_index = static_cast<int>(i);
const RenderPassDrawContainer::LayerType type =
((pass_render_state.blend_state &&
pass_render_state.blend_state->enabled) ||
IsAlphaEnabled(*obj.material))
? RenderPassDrawContainer::kBlendEnabled
: RenderPassDrawContainer::kOpaque;
pass_container.layers[type].render_objects.push_back(obj);
}
});
// Sort only objects with "static" sort order, such as explicit sort order
// or absolute z-position.
for (RenderLayer& layer : pass_container.layers) {
if (IsSortModeViewIndependent(layer.sort_mode)) {
SortObjects(&layer.render_objects, layer.sort_mode);
}
}
}
render_data_buffer_.UnlockWriteBuffer();
}
void RenderSystemNext::BeginRendering() {
active_render_data_ = render_data_buffer_.LockReadBuffer();
}
void RenderSystemNext::EndRendering() {
render_data_buffer_.UnlockReadBuffer();
active_render_data_ = nullptr;
}
void RenderSystemNext::RenderAt(const RenderObject* render_object,
const RenderView* views, size_t num_views) {
LULLABY_CPU_TRACE_CALL();
static const size_t kMaxNumViews = 2;
if (views == nullptr || num_views == 0 || num_views > kMaxNumViews) {
return;
}
const std::shared_ptr<Mesh>& mesh = render_object->mesh;
if (mesh == nullptr) {
return;
}
const std::shared_ptr<Material>& material = render_object->material;
if (material == nullptr) {
return;
}
const std::shared_ptr<Shader>& shader = material->GetShader();
if (shader == nullptr) {
return;
}
BindShader(shader);
constexpr HashValue kModel = ConstHash("model");
shader->SetUniform(kModel, &render_object->world_from_entity_matrix[0], 16);
// Compute the normal matrix. This is the transposed matrix of the inversed
// world position. This is done to avoid non-uniform scaling of the normal.
// A good explanation of this can be found here:
// http://www.lighthouse3d.com/tutorials/glsl-12-tutorial/the-normal-matrix/
constexpr HashValue kMatNormal = ConstHash("mat_normal");
mathfu::vec3_packed normal_matrix[3];
ComputeNormalMatrix(render_object->world_from_entity_matrix)
.Pack(normal_matrix);
shader->SetUniform(kMatNormal, normal_matrix[0].data, 9);
// The following uniforms support multiview arrays. Ensure data is tightly
// packed so that it correctly gets set in the uniform.
int is_right_eye[kMaxNumViews] = {0};
mathfu::vec3_packed camera_dir[kMaxNumViews];
mathfu::vec3_packed camera_pos[kMaxNumViews];
mathfu::mat4 clip_from_entity_matrix[kMaxNumViews];
mathfu::mat4 view_matrix[kMaxNumViews];
const int count = static_cast<int>(num_views);
for (int i = 0; i < count; ++i) {
is_right_eye[i] = views[i].eye == 1 ? 1 : 0;
view_matrix[i] = views[i].eye_from_world_matrix;
views[i].world_from_eye_matrix.TranslationVector3D().Pack(&camera_pos[i]);
CalculateCameraDirection(views[i].world_from_eye_matrix)
.Pack(&camera_dir[i]);
clip_from_entity_matrix[i] =
clip_from_model_matrix_func_(render_object->world_from_entity_matrix,
views[i].clip_from_world_matrix);
}
constexpr HashValue kView = ConstHash("view");
shader->SetUniform(kView, &(view_matrix[0][0]), 16, count);
constexpr HashValue kModelViewProjection = ConstHash("model_view_projection");
shader->SetUniform(kModelViewProjection, &(clip_from_entity_matrix[0][0]), 16,
count);
constexpr HashValue kCameraDir = ConstHash("camera_dir");
shader->SetUniform(kCameraDir, camera_dir[0].data, 3, count);
constexpr HashValue kCameraPos = ConstHash("camera_pos");
// camera_pos is not currently multiview enabled, so only set 1 value.
shader->SetUniform(kCameraPos, camera_pos[0].data, 3, 1);
// We break the naming convention here for compatibility with early VR apps.
constexpr HashValue kIsRightEye = ConstHash("uIsRightEye");
shader->SetUniform(kIsRightEye, is_right_eye, 1, count);
renderer_.ApplyMaterial(render_object->material);
renderer_.Draw(mesh, render_object->world_from_entity_matrix,
render_object->submesh_index);
detail::Profiler* profiler = registry_->Get<detail::Profiler>();
if (profiler) {
profiler->RecordDraw(material->GetShader(), mesh->GetNumVertices(),
mesh->GetNumTriangles());
}
}
void RenderSystemNext::Render(const RenderView* views, size_t num_views) {
// Assume a max of 2 views, one for each eye.
RenderView pano_views[2];
CHECK_LE(num_views, 2);
GenerateEyeCenteredViews({views, num_views}, pano_views);
Render(pano_views, num_views, ConstHash("Pano"));
Render(views, num_views, ConstHash("Opaque"));
Render(views, num_views, ConstHash("Main"));
Render(views, num_views, ConstHash("OverDraw"));
Render(views, num_views, ConstHash("OverDrawGlow"));
}
void RenderSystemNext::Render(const RenderView* views, size_t num_views,
HashValue pass) {
LULLABY_CPU_TRACE_CALL();
if (!active_render_data_) {
LOG(DFATAL) << "Render between BeginRendering() and EndRendering()!";
return;
}
auto iter = active_render_data_->find(pass);
if (iter == active_render_data_->end()) {
// No data associated with this pass.
return;
}
RenderPassDrawContainer& draw_container = iter->second;
renderer_.Begin(draw_container.render_target);
renderer_.Clear(draw_container.clear_params);
// Draw the elements.
if (pass == ConstHash("Debug")) {
RenderDebugStats(views, num_views);
} else {
for (RenderLayer& layer : draw_container.layers) {
if (!IsSortModeViewIndependent(layer.sort_mode)) {
SortObjectsUsingView(&layer.render_objects, layer.sort_mode, views,
num_views);
}
RenderObjects(layer.render_objects, layer.render_state, views, num_views);
}
}
renderer_.End();
}
void RenderSystemNext::RenderObjects(const std::vector<RenderObject>& objects,
const RenderStateT& render_state,
const RenderView* views,
size_t num_views) {
if (objects.empty()) {
return;
}
renderer_.GetRenderStateManager().SetRenderState(render_state);
if (renderer_.IsMultiviewEnabled()) {
SetViewport(views[0]);
for (const RenderObject& obj : objects) {
RenderAt(&obj, views, num_views);
}
} else {
for (size_t i = 0; i < num_views; ++i) {
SetViewport(views[i]);
for (const RenderObject& obj : objects) {
RenderAt(&obj, &views[i], 1);
}
}
}
}
void RenderSystemNext::BindShader(const ShaderPtr& shader) {
shader_ = shader;
shader->Bind();
// Initialize color to white and allow individual materials to set it
// differently.
constexpr HashValue kColor = ConstHash("color");
shader->SetUniform(kColor, &mathfu::kOnes4f[0], 4);
// Set the MVP matrix to the one explicitly set by the user and override
// during draw calls if needed.
constexpr HashValue kModelViewProjection = ConstHash("model_view_projection");
shader->SetUniform(kModelViewProjection, &model_view_projection_[0], 16);
}
void RenderSystemNext::BindTexture(int unit, const TexturePtr& texture) {
if (unit < 0) {
LOG(ERROR) << "BindTexture called with negative unit.";
return;
}
// Ensure there is enough size in the cache.
if (gpu_cache_.bound_textures.size() <= unit) {
gpu_cache_.bound_textures.resize(unit + 1);
}
if (texture) {
texture->Bind(unit);
} else if (gpu_cache_.bound_textures[unit]) {
GL_CALL(glActiveTexture(GL_TEXTURE0 + static_cast<GLenum>(unit)));
GL_CALL(glBindTexture(gpu_cache_.bound_textures[unit]->GetTarget(), 0));
}
gpu_cache_.bound_textures[unit] = texture;
}
void RenderSystemNext::BindUniform(const char* name, const float* data,
int dimension) {
if (!IsSupportedUniformDimension(dimension)) {
LOG(DFATAL) << "Unsupported uniform dimension " << dimension;
return;
}
if (!shader_) {
LOG(DFATAL) << "Cannot bind uniform on unbound shader!";
return;
}
shader_->SetUniform(shader_->FindUniform(name), data, dimension);
}
void RenderSystemNext::DrawMesh(const MeshData& mesh) { DrawMeshData(mesh); }
void RenderSystemNext::UpdateDynamicMesh(
Entity entity, MeshData::PrimitiveType primitive_type,
const VertexFormat& vertex_format, const size_t max_vertices,
const size_t max_indices, MeshData::IndexType index_type,
const size_t max_ranges,
const std::function<void(MeshData*)>& update_mesh) {
if (max_vertices > 0) {
DataContainer vertex_data = DataContainer::CreateHeapDataContainer(
max_vertices * vertex_format.GetVertexSize());
DataContainer index_data = DataContainer::CreateHeapDataContainer(
max_indices * MeshData::GetIndexSize(index_type));
DataContainer range_data = DataContainer::CreateHeapDataContainer(
max_ranges * sizeof(MeshData::IndexRange));
MeshData data(primitive_type, vertex_format, std::move(vertex_data),
index_type, std::move(index_data), std::move(range_data));
update_mesh(&data);
MeshPtr mesh = mesh_factory_->CreateMesh(std::move(data));
ForEachComponentOfEntity(
entity,
[this, entity, mesh](RenderComponent* component, HashValue pass) {
component->mesh = mesh;
SendEvent(registry_, entity, MeshChangedEvent(entity, pass));
});
} else {
ForEachComponentOfEntity(
entity, [this, entity](RenderComponent* component, HashValue pass) {
component->mesh.reset();
SendEvent(registry_, entity, MeshChangedEvent(entity, pass));
});
}
}
void RenderSystemNext::RenderDebugStats(const RenderView* views,
size_t num_views) {
RenderStats* render_stats = registry_->Get<RenderStats>();
if (!render_stats || num_views == 0) {
return;
}
const bool stats_enabled =
render_stats->IsLayerEnabled(RenderStats::Layer::kRenderStats);
const bool fps_counter =
render_stats->IsLayerEnabled(RenderStats::Layer::kFpsCounter);
if (!stats_enabled && !fps_counter) {
return;
}
SimpleFont* font = render_stats->GetFont();
if (!font || !font->GetShader()) {
return;
}
// Calculate the position and size of the text from the projection matrix.
const bool is_perspective = views[0].clip_from_eye_matrix[15] == 0.0f;
const bool is_stereo = (num_views == 2 && is_perspective &&
views[1].clip_from_eye_matrix[15] == 0.0f);
mathfu::vec3 start_pos;
float font_size;
// TODO(b/29914331) Separate, tested matrix decomposition util functions.
if (is_perspective) {
const float kTopOfTextScreenScale = .45f;
const float kFontScreenScale = .075f;
const float z = -1.0f;
const float tan_half_fov = 1.0f / views[0].clip_from_eye_matrix[5];
font_size = .5f * kFontScreenScale * -z * tan_half_fov;
start_pos =
mathfu::vec3(-.5f, kTopOfTextScreenScale * -z * tan_half_fov, z);
} else {
const float kNearPlaneOffset = .0001f;
const float bottom = (-1.0f - views[0].clip_from_eye_matrix[13]) /
views[0].clip_from_eye_matrix[5];
const float top = bottom + 2.0f / views[0].clip_from_eye_matrix[5];
const float near_z = (1.0f + views[0].clip_from_eye_matrix[14]) /
views[0].clip_from_eye_matrix[10];
const float padding = 20.f;
font_size = 16.f;
start_pos =
mathfu::vec3(padding, top - padding, -(near_z - kNearPlaneOffset));
}
// Setup shared render state.
font->GetTexture()->Bind(0);
font->SetSize(font_size);
const float uv_bounds[4] = {0, 0, 1, 1};
SetDebugUniform(font->GetShader().get(), kTextureBoundsUniform, uv_bounds);
const float color[4] = {1, 1, 1, 1};
SetDebugUniform(font->GetShader().get(), kColorUniform, color);
SetDepthTest(false);
SetDepthWrite(false);
char buf[512] = "";
// Draw in each view.
for (size_t i = 0; i < num_views; ++i) {
SetViewport(views[i]);
model_view_projection_ = views[i].clip_from_eye_matrix;
// Shader needs to be bound after setting MVP.
BindShader(font->GetShader());
mathfu::vec3 pos = start_pos;
if (is_stereo && i > 0) {
// Reposition text so that it's consistently placed in both eye views.
pos = views[i].world_from_eye_matrix.Inverse() *
(views[0].world_from_eye_matrix * start_pos);
}
SimpleFontRenderer text(font);
text.SetCursor(pos);
// Draw basic render stats.
const detail::Profiler* profiler = registry_->Get<detail::Profiler>();
if (profiler && stats_enabled) {
snprintf(buf, sizeof(buf),
"FPS %0.2f\n"
"CPU ms %0.2f\n"
"GPU ms %0.2f\n"
"# draws %d\n"
"# shader swaps %d\n"
"# verts %d\n"
"# tris %d",
profiler->GetFilteredFps(), profiler->GetCpuFrameMs(),
profiler->GetGpuFrameMs(), profiler->GetNumDraws(),
profiler->GetNumShaderSwaps(), profiler->GetNumVerts(),
profiler->GetNumTris());
text.Print(buf);
} else if (profiler) {
DCHECK(fps_counter);
snprintf(buf, sizeof(buf), "FPS %0.2f\n", profiler->GetFilteredFps());
text.Print(buf);
}
registry_->Get<RenderSystem>()->DrawMesh(text.GetMesh());
}
// Cleanup render state.
SetDepthTest(true);
SetDepthWrite(true);
}
void RenderSystemNext::UpdateSortOrder(Entity entity) {
ForEachComponentOfEntity(
entity, [&](RenderComponent* render_component, HashValue pass) {
const detail::EntityIdPair entity_id_pair(entity, pass);
sort_order_manager_.UpdateSortOrder(
entity_id_pair, [this](detail::EntityIdPair entity_id_pair) {
return GetComponent(entity_id_pair.entity, entity_id_pair.id);
});
});
}
const fplbase::RenderState& RenderSystemNext::GetCachedRenderState() const {
return render_state_;
}
void RenderSystemNext::UpdateCachedRenderState(
const fplbase::RenderState& render_state) {
renderer_.GetRenderStateManager().Reset();
renderer_.ResetGpuState();
UnsetDefaultAttributes();
shader_.reset();
render_state_ = render_state;
SetAlphaTestState(render_state.alpha_test_state);
SetBlendState(render_state.blend_state);
SetCullState(render_state.cull_state);
SetDepthState(render_state.depth_state);
SetPointState(render_state.point_state);
SetScissorState(render_state.scissor_state);
SetStencilState(render_state.stencil_state);
SetViewport(render_state.viewport);
ValidateRenderState();
}
void RenderSystemNext::ValidateRenderState() {
#ifdef LULLABY_VERIFY_GPU_STATE
DCHECK(renderer_.GetRenderStateManager().Validate());
fplbase::ValidateRenderState(render_state_);
#endif
}
void RenderSystemNext::SetDepthTest(const bool enabled) {
if (enabled) {
SetDepthFunction(fplbase::kDepthFunctionLess);
} else {
SetDepthFunction(fplbase::kDepthFunctionDisabled);
}
}
void RenderSystemNext::SetViewport(const mathfu::recti& viewport) {
renderer_.GetRenderStateManager().SetViewport(viewport);
render_state_.viewport = viewport;
}
void RenderSystemNext::SetDepthWrite(bool depth_write) {
fplbase::DepthState depth_state = render_state_.depth_state;
depth_state.write_enabled = depth_write;
SetDepthState(depth_state);
}
void RenderSystemNext::SetDepthFunction(fplbase::DepthFunction depth_function) {
fplbase::DepthState depth_state = render_state_.depth_state;
switch (depth_function) {
case fplbase::kDepthFunctionDisabled:
depth_state.test_enabled = false;
break;
case fplbase::kDepthFunctionNever:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderNever;
break;
case fplbase::kDepthFunctionAlways:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderAlways;
break;
case fplbase::kDepthFunctionLess:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderLess;
break;
case fplbase::kDepthFunctionLessEqual:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderLessEqual;
break;
case fplbase::kDepthFunctionGreater:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderGreater;
break;
case fplbase::kDepthFunctionGreaterEqual:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderGreaterEqual;
break;
case fplbase::kDepthFunctionEqual:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderEqual;
break;
case fplbase::kDepthFunctionNotEqual:
depth_state.test_enabled = true;
depth_state.function = fplbase::kRenderNotEqual;
break;
case fplbase::kDepthFunctionUnknown:
// Do nothing.
break;
default:
assert(false); // Invalid depth function.
break;
}
SetDepthState(depth_state);
}
void RenderSystemNext::SetBlendMode(fplbase::BlendMode blend_mode) {
fplbase::AlphaTestState alpha_test_state = render_state_.alpha_test_state;
fplbase::BlendState blend_state = render_state_.blend_state;
switch (blend_mode) {
case fplbase::kBlendModeOff:
alpha_test_state.enabled = false;
blend_state.enabled = false;
break;
case fplbase::kBlendModeTest:
alpha_test_state.enabled = true;
alpha_test_state.function = fplbase::kRenderGreater;
alpha_test_state.ref = 0.5f;
blend_state.enabled = false;
break;
case fplbase::kBlendModeAlpha:
alpha_test_state.enabled = false;
blend_state.enabled = true;
blend_state.src_alpha = fplbase::BlendState::kSrcAlpha;
blend_state.src_color = fplbase::BlendState::kSrcAlpha;
blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
break;
case fplbase::kBlendModeAdd:
alpha_test_state.enabled = false;
blend_state.enabled = true;
blend_state.src_alpha = fplbase::BlendState::kOne;
blend_state.src_color = fplbase::BlendState::kOne;
blend_state.dst_alpha = fplbase::BlendState::kOne;
blend_state.dst_color = fplbase::BlendState::kOne;
break;
case fplbase::kBlendModeAddAlpha:
alpha_test_state.enabled = false;
blend_state.enabled = true;
blend_state.src_alpha = fplbase::BlendState::kSrcAlpha;
blend_state.src_color = fplbase::BlendState::kSrcAlpha;
blend_state.dst_alpha = fplbase::BlendState::kOne;
blend_state.dst_color = fplbase::BlendState::kOne;
break;
case fplbase::kBlendModeMultiply:
alpha_test_state.enabled = false;
blend_state.enabled = true;
blend_state.src_alpha = fplbase::BlendState::kDstColor;
blend_state.src_color = fplbase::BlendState::kDstColor;
blend_state.dst_alpha = fplbase::BlendState::kZero;
blend_state.dst_color = fplbase::BlendState::kZero;
break;
case fplbase::kBlendModePreMultipliedAlpha:
alpha_test_state.enabled = false;
blend_state.enabled = true;
blend_state.src_alpha = fplbase::BlendState::kOne;
blend_state.src_color = fplbase::BlendState::kOne;
blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
break;
case fplbase::kBlendModeUnknown:
// Do nothing.
break;
default:
assert(false); // Not yet implemented.
break;
}
SetBlendState(blend_state);
SetAlphaTestState(alpha_test_state);
}
void RenderSystemNext::SetStencilMode(fplbase::StencilMode mode, int ref,
uint32_t mask) {
fplbase::StencilState stencil_state = render_state_.stencil_state;
switch (mode) {
case fplbase::kStencilDisabled:
stencil_state.enabled = false;
break;
case fplbase::kStencilCompareEqual:
stencil_state.enabled = true;
stencil_state.front_function.function = fplbase::kRenderEqual;
stencil_state.front_function.ref = ref;
stencil_state.front_function.mask = mask;
stencil_state.back_function = stencil_state.front_function;
stencil_state.front_op.stencil_fail = fplbase::StencilOperation::kKeep;
stencil_state.front_op.depth_fail = fplbase::StencilOperation::kKeep;
stencil_state.front_op.pass = fplbase::StencilOperation::kKeep;
stencil_state.back_op = stencil_state.front_op;
break;
case fplbase::kStencilWrite:
stencil_state.enabled = true;
stencil_state.front_function.function = fplbase::kRenderAlways;
stencil_state.front_function.ref = ref;
stencil_state.front_function.mask = mask;
stencil_state.back_function = stencil_state.front_function;
stencil_state.front_op.stencil_fail = fplbase::StencilOperation::kKeep;
stencil_state.front_op.depth_fail = fplbase::StencilOperation::kKeep;
stencil_state.front_op.pass = fplbase::StencilOperation::kReplace;
stencil_state.back_op = stencil_state.front_op;
break;
case fplbase::kStencilUnknown:
// Do nothing.
break;
default:
assert(false);
}
SetStencilState(stencil_state);
}
void RenderSystemNext::SetCulling(fplbase::CullingMode mode) {
fplbase::CullState cull_state = render_state_.cull_state;
switch (mode) {
case fplbase::kCullingModeNone:
cull_state.enabled = false;
break;
case fplbase::kCullingModeBack:
cull_state.enabled = true;
cull_state.face = fplbase::CullState::kBack;
break;
case fplbase::kCullingModeFront:
cull_state.enabled = true;
cull_state.face = fplbase::CullState::kFront;
break;
case fplbase::kCullingModeFrontAndBack:
cull_state.enabled = true;
cull_state.face = fplbase::CullState::kFrontAndBack;
break;
case fplbase::kCullingModeUnknown:
// Do nothing.
break;
default:
// Unknown culling mode.
assert(false);
}
SetCullState(cull_state);
}
void RenderSystemNext::SetAlphaTestState(
const fplbase::AlphaTestState& alpha_test_state) {
AlphaTestStateT state = Convert(alpha_test_state);
renderer_.GetRenderStateManager().SetAlphaTestState(state);
render_state_.alpha_test_state = alpha_test_state;
}
void RenderSystemNext::SetBlendState(const fplbase::BlendState& blend_state) {
BlendStateT state = Convert(blend_state);
renderer_.GetRenderStateManager().SetBlendState(state);
render_state_.blend_state = blend_state;
}
void RenderSystemNext::SetCullState(const fplbase::CullState& cull_state) {
CullStateT state = Convert(cull_state);
renderer_.GetRenderStateManager().SetCullState(state);
render_state_.cull_state = cull_state;
}
void RenderSystemNext::SetDepthState(const fplbase::DepthState& depth_state) {
DepthStateT state = Convert(depth_state);
renderer_.GetRenderStateManager().SetDepthState(state);
render_state_.depth_state = depth_state;
}
void RenderSystemNext::SetPointState(const fplbase::PointState& point_state) {
PointStateT state = Convert(point_state);
renderer_.GetRenderStateManager().SetPointState(state);
render_state_.point_state = point_state;
}
void RenderSystemNext::SetScissorState(
const fplbase::ScissorState& scissor_state) {
ScissorStateT state = Convert(scissor_state);
renderer_.GetRenderStateManager().SetScissorState(state);
render_state_.scissor_state = scissor_state;
}
void RenderSystemNext::SetStencilState(
const fplbase::StencilState& stencil_state) {
StencilStateT state = Convert(stencil_state);
renderer_.GetRenderStateManager().SetStencilState(state);
render_state_.stencil_state = stencil_state;
}
bool RenderSystemNext::IsSortModeViewIndependent(SortMode mode) {
switch (mode) {
case SortMode_AverageSpaceOriginBackToFront:
case SortMode_AverageSpaceOriginFrontToBack:
return false;
default:
return true;
}
}
namespace {
inline float GetZBackToFrontXOutToMiddleDistance(const mathfu::vec3& pos) {
return pos.z - std::abs(pos.x);
}
} // namespace
void RenderSystemNext::SortObjects(std::vector<RenderObject>* objects,
SortMode mode) {
switch (mode) {
case SortMode_Optimized:
case SortMode_None:
// Do nothing.
break;
case SortMode_SortOrderDecreasing:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.sort_order > b.sort_order;
});
break;
case SortMode_SortOrderIncreasing:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.sort_order < b.sort_order;
});
break;
case SortMode_WorldSpaceZBackToFront:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.world_from_entity_matrix.TranslationVector3D().z <
b.world_from_entity_matrix.TranslationVector3D().z;
});
break;
case SortMode_WorldSpaceZFrontToBack:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return a.world_from_entity_matrix.TranslationVector3D().z >
b.world_from_entity_matrix.TranslationVector3D().z;
});
break;
case SortMode_WorldSpaceZBackToFrontXOutToMiddle:
std::sort(objects->begin(), objects->end(),
[](const RenderObject& a, const RenderObject& b) {
return GetZBackToFrontXOutToMiddleDistance(
a.world_from_entity_matrix.TranslationVector3D()) <
GetZBackToFrontXOutToMiddleDistance(
b.world_from_entity_matrix.TranslationVector3D());
});
break;
default:
LOG(DFATAL) << "SortObjects called with unsupported sort mode!";
break;
}
}
void RenderSystemNext::SortObjectsUsingView(std::vector<RenderObject>* objects,
SortMode mode,
const RenderView* views,
size_t num_views) {
// Get the average camera position.
if (num_views <= 0) {
LOG(DFATAL) << "Must have at least 1 view.";
return;
}
mathfu::vec3 avg_pos = mathfu::kZeros3f;
mathfu::vec3 avg_z(0, 0, 0);
for (size_t i = 0; i < num_views; ++i) {
avg_pos += views[i].world_from_eye_matrix.TranslationVector3D();
avg_z += GetMatrixColumn3D(views[i].world_from_eye_matrix, 2);
}
avg_pos /= static_cast<float>(num_views);
avg_z.Normalize();
// Give relative values to the elements.
for (RenderObject& obj : *objects) {
const mathfu::vec3 world_pos =
obj.world_from_entity_matrix.TranslationVector3D();
obj.z_sort_order = mathfu::vec3::DotProduct(world_pos - avg_pos, avg_z);
}
switch (mode) {
case SortMode_AverageSpaceOriginBackToFront:
std::sort(objects->begin(), objects->end(),
[&](const RenderObject& a, const RenderObject& b) {
return a.z_sort_order < b.z_sort_order;
});
break;
case SortMode_AverageSpaceOriginFrontToBack:
std::sort(objects->begin(), objects->end(),
[&](const RenderObject& a, const RenderObject& b) {
return a.z_sort_order > b.z_sort_order;
});
break;
default:
LOG(DFATAL) << "SortObjectsUsingView called with unsupported sort mode!";
break;
}
}
void RenderSystemNext::InitDefaultRenderPassObjects() {
fplbase::RenderState render_state;
RenderClearParams clear_params;
// Create a pass that clears the display.
clear_params.clear_options = RenderClearParams::kColor |
RenderClearParams::kDepth |
RenderClearParams::kStencil;
SetClearParams(ConstHash("ClearDisplay"), clear_params);
// RenderPass_Pano. Premultiplied alpha blend state, everything else default.
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
SetRenderState(ConstHash("Pano"), render_state);
// RenderPass_Opaque. Depth test and write on. BlendMode disabled, face cull
// mode back.
render_state.blend_state.enabled = false;
render_state.depth_state.test_enabled = true;
render_state.depth_state.write_enabled = true;
render_state.depth_state.function = fplbase::kRenderLessEqual;
render_state.cull_state.enabled = true;
render_state.cull_state.front =
CullStateFrontFaceFromFrontFace(default_front_face_);
render_state.cull_state.face = fplbase::CullState::kBack;
render_state.point_state.point_sprite_enabled = true;
render_state.point_state.program_point_size_enabled = true;
SetRenderState(ConstHash("Opaque"), render_state);
// RenderPass_Main. Depth test on, write off. Premultiplied alpha blend state,
// face cull mode back.
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.depth_state.test_enabled = true;
render_state.depth_state.function = fplbase::kRenderLessEqual;
render_state.depth_state.write_enabled = false;
render_state.cull_state.enabled = true;
render_state.cull_state.front =
CullStateFrontFaceFromFrontFace(default_front_face_);
render_state.cull_state.face = fplbase::CullState::kBack;
render_state.point_state.point_sprite_enabled = true;
render_state.point_state.program_point_size_enabled = true;
SetRenderState(ConstHash("Main"), render_state);
// RenderPass_OverDraw. Depth test and write false, premultiplied alpha, back
// face culling.
render_state.depth_state.test_enabled = false;
render_state.depth_state.write_enabled = false;
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha;
render_state.cull_state.enabled = true;
render_state.cull_state.front =
CullStateFrontFaceFromFrontFace(default_front_face_);
render_state.cull_state.face = fplbase::CullState::kBack;
render_state.point_state.point_sprite_enabled = false;
render_state.point_state.program_point_size_enabled = false;
SetRenderState(ConstHash("OverDraw"), render_state);
// RenderPass_OverDrawGlow. Depth test and write off, additive blend mode, no
// face culling.
render_state.depth_state.test_enabled = false;
render_state.depth_state.write_enabled = false;
render_state.blend_state.enabled = true;
render_state.blend_state.src_alpha = fplbase::BlendState::kOne;
render_state.blend_state.src_color = fplbase::BlendState::kOne;
render_state.blend_state.dst_alpha = fplbase::BlendState::kOne;
render_state.blend_state.dst_color = fplbase::BlendState::kOne;
render_state.cull_state.front =
CullStateFrontFaceFromFrontFace(default_front_face_);
render_state.cull_state.enabled = false;
SetRenderState(ConstHash("OverDrawGlow"), render_state);
SetSortMode(ConstHash("Opaque"), SortMode_AverageSpaceOriginFrontToBack);
SetSortMode(ConstHash("Main"), SortMode_SortOrderIncreasing);
}
void RenderSystemNext::CreateRenderTarget(
HashValue render_target_name,
const RenderTargetCreateParams& create_params) {
DCHECK_EQ(render_targets_.count(render_target_name), 0);
// Create the render target.
auto render_target = MakeUnique<RenderTarget>(create_params);
// Create a bindable texture.
TexturePtr texture = texture_factory_->CreateTexture(
GL_TEXTURE_2D, *render_target->GetTextureId());
texture_factory_->CacheTexture(render_target_name, texture);
// Store the render target.
render_targets_[render_target_name] = std::move(render_target);
}
void RenderSystemNext::SetRenderTarget(HashValue pass,
HashValue render_target_name) {
RenderPassObject* pass_object = GetRenderPassObject(pass);
if (!pass_object) {
return;
}
pass_object->render_target = render_target_name;
}
ImageData RenderSystemNext::GetRenderTargetData(HashValue render_target_name) {
auto iter = render_targets_.find(render_target_name);
if (iter == render_targets_.end()) {
LOG(DFATAL) << "SetRenderTarget called with non-existent render target: "
<< render_target_name;
return ImageData();
}
return iter->second->GetFrameBufferData();
}
void RenderSystemNext::ForEachComponentOfEntity(
Entity entity, const std::function<void(RenderComponent*, HashValue)>& fn) {
for (auto& pass : render_passes_) {
RenderComponent* component = pass.second.components.Get(entity);
if (component) {
fn(component, pass.first);
}
}
}
void RenderSystemNext::ForEachComponentOfEntity(
Entity entity,
const std::function<void(const RenderComponent&, HashValue)>& fn) const {
for (const auto& pass : render_passes_) {
const RenderComponent* component = pass.second.components.Get(entity);
if (component) {
fn(*component, pass.first);
}
}
}
RenderComponent* RenderSystemNext::FindRenderComponentForEntity(Entity e) {
RenderComponent* component = GetComponent(e, ConstHash("Opaque"));
if (component) {
return component;
}
component = GetComponent(e, ConstHash("Main"));
if (component) {
return component;
}
for (auto& pass : render_passes_) {
component = pass.second.components.Get(e);
if (component) {
return component;
}
}
return nullptr;
}
const RenderComponent* RenderSystemNext::FindRenderComponentForEntity(
Entity e) const {
const RenderComponent* component = GetComponent(e, ConstHash("Opaque"));
if (component) {
return component;
}
component = GetComponent(e, ConstHash("Main"));
if (component) {
return component;
}
for (const auto& pass : render_passes_) {
component = pass.second.components.Get(e);
if (component) {
return component;
}
}
return nullptr;
}
RenderComponent* RenderSystemNext::GetComponent(Entity e, HashValue pass) {
// TODO(b/68871848) some apps are feeding pass=0 because they are used to
// component id.
if (pass == 0) {
LOG(WARNING) << "Tried find render component by using pass = 0. Support "
"for this will be deprecated. Apps should identify the "
"correct pass the entity lives in.";
return FindRenderComponentForEntity(e);
}
RenderPassObject* pass_object = FindRenderPassObject(pass);
if (!pass_object) {
return nullptr;
}
return pass_object->components.Get(e);
}
const RenderComponent* RenderSystemNext::GetComponent(Entity e,
HashValue pass) const {
// TODO(b/68871848) some apps are feeding pass=0 because they are used to
// component id.
if (pass == 0) {
LOG(WARNING) << "Tried find render component by using pass = 0. Support "
"for this will be deprecated. Apps should identify the "
"correct pass the entity lives in.";
return FindRenderComponentForEntity(e);
}
const RenderPassObject* pass_object = FindRenderPassObject(pass);
if (!pass_object) {
return nullptr;
}
return pass_object->components.Get(e);
}
RenderSystemNext::RenderPassObject* RenderSystemNext::GetRenderPassObject(
HashValue pass) {
if (pass == RenderSystem::kDefaultPass) {
pass = default_pass_;
}
return &render_passes_[pass];
}
RenderSystemNext::RenderPassObject* RenderSystemNext::FindRenderPassObject(
HashValue pass) {
if (pass == RenderSystem::kDefaultPass) {
pass = default_pass_;
}
auto iter = render_passes_.find(pass);
if (iter == render_passes_.end()) {
return nullptr;
}
return &iter->second;
}
const RenderSystemNext::RenderPassObject*
RenderSystemNext::FindRenderPassObject(HashValue pass) const {
if (pass == RenderSystem::kDefaultPass) {
pass = default_pass_;
}
const auto iter = render_passes_.find(pass);
if (iter == render_passes_.end()) {
return nullptr;
}
return &iter->second;
}
int RenderSystemNext::GetNumBones(Entity entity) const {
LOG(DFATAL) << "Deprecated.";
return 0;
}
const uint8_t* RenderSystemNext::GetBoneParents(Entity e, int* num) const {
LOG(DFATAL) << "Deprecated.";
return nullptr;
}
const std::string* RenderSystemNext::GetBoneNames(Entity e, int* num) const {
LOG(DFATAL) << "Deprecated.";
return nullptr;
}
const mathfu::AffineTransform*
RenderSystemNext::GetDefaultBoneTransformInverses(Entity e, int* num) const {
LOG(DFATAL) << "Deprecated.";
return nullptr;
}
void RenderSystemNext::SetBoneTransforms(
Entity entity, const mathfu::AffineTransform* transforms,
int num_transforms) {
LOG(DFATAL) << "Deprecated.";
}
void RenderSystemNext::SetBoneTransforms(
Entity entity, HashValue component_id,
const mathfu::AffineTransform* transforms, int num_transforms) {
LOG(DFATAL) << "Deprecated.";
}
void RenderSystemNext::SetPano(Entity entity, const std::string& filename,
float heading_offset_deg) {
LOG(DFATAL) << "Deprecated.";
}
void RenderSystemNext::SetText(Entity e, const std::string& text) {
LOG(DFATAL) << "Deprecated.";
}
void RenderSystemNext::PreloadFont(const char* name) {
LOG(DFATAL) << "Deprecated.";
}
Optional<HashValue> RenderSystemNext::GetGroupId(Entity entity) const {
// Does nothing.
return Optional<HashValue>();
}
void RenderSystemNext::SetGroupId(Entity entity,
const Optional<HashValue>& group_id) {
// Does nothing.
}
const RenderSystem::GroupParams* RenderSystemNext::GetGroupParams(
HashValue group_id) const {
// Does nothing.
return nullptr;
}
void RenderSystemNext::SetGroupParams(
HashValue group_id, const RenderSystem::GroupParams& group_params) {
// Does nothing.
}
ShaderCreateParams RenderSystemNext::CreateShaderParams(
const std::string& shading_model, const RenderComponent* component,
const std::shared_ptr<Material>& material) {
ShaderCreateParams params;
params.shading_model.resize(shading_model.size());
std::transform(shading_model.begin(), shading_model.end(),
params.shading_model.begin(), ::tolower);
if (component) {
if (component->mesh) {
params.environment = CreateEnvironmentFlagsFromVertexFormat(
component->mesh->GetVertexFormat());
params.features = CreateFeatureFlagsFromVertexFormat(
component->mesh->GetVertexFormat());
}
}
if (material) {
for (int i = MaterialTextureUsage_MIN; i <= MaterialTextureUsage_MAX; ++i) {
const MaterialTextureUsage usage = static_cast<MaterialTextureUsage>(i);
if (material->GetTexture(usage)) {
params.environment.insert(texture_flag_hashes_[i]);
params.features.insert(texture_flag_hashes_[i]);
}
}
}
params.features.insert(kFeatureHashUniformColor);
params.environment.insert(renderer_.GetEnvironmentFlags().cbegin(),
renderer_.GetEnvironmentFlags().cend());
return params;
}
} // namespace lull
| 35.009301 | 80 | 0.691436 | dd181818 |
663d734fe72edfd509c99a8869846b79f2103a59 | 737 | hxx | C++ | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | //
// Watchable.hxx
// Aries
//
// Created by Brandon on 2018-02-25.
// Copyright © 2018 Brandon. All rights reserved.
//
#ifndef Watchable_hxx
#define Watchable_hxx
#include "Array.hxx"
#include "Object.hxx"
namespace java::nio::file
{
using java::lang::Object;
using java::nio::file::WatchEvent;
using java::nio::file::WatchKey;
using java::nio::file::WatchService;
class Watchable : public Object
{
public:
Watchable(JVM* vm, jobject instance);
WatchKey register(WatchService arg0, Array<WatchEvent::Kind>& arg1, Array<WatchEvent::Modifier>& arg2);
WatchKey register(WatchService arg0, Array<WatchEvent::Kind>& arg1);
};
}
#endif /* Watchable_hxx */
| 21.057143 | 111 | 0.654003 | Brandon-T |
663ec8c79d479b0973d36908c7f196590b3f19d6 | 574 | cpp | C++ | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | #include "Program.h"
#include "memtrace.h"
size_t Program::cmdPtr = 0;
void Program::addNewCommand(Command * cmd) {
this->commands.push_back(cmd);
}
void Program::setCmdPtr(int v) {
v = v - 2;
if (v < -1) {
throw std::out_of_range("Wrong tag at Goto");
}
cmdPtr = v;
}
void Program::Run() {
while (this->cmdPtr != this->commands.size()) {
Command* a = this->commands[this->cmdPtr];
a->Execute();
this->cmdPtr++;
}
}
Program::~Program() {
for (auto i : this->commands) {
i->clear();
delete i;
}
} | 13.666667 | 49 | 0.559233 | bgorzsony |
66438d6561c06e5ee14906bfc7e51754649f150a | 244 | hpp | C++ | pythran/pythonic/utils/fwd.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,647 | 2015-01-13T01:45:38.000Z | 2022-03-28T01:23:41.000Z | pythran/pythonic/utils/fwd.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,116 | 2015-01-01T09:52:05.000Z | 2022-03-18T21:06:40.000Z | pythran/pythonic/utils/fwd.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 180 | 2015-02-12T02:47:28.000Z | 2022-03-14T10:28:18.000Z | #ifndef PYTHONIC_UTILS_FWD_HPP
#define PYTHONIC_UTILS_FWD_HPP
#include "pythonic/include/utils/fwd.hpp"
PYTHONIC_NS_BEGIN
namespace utils
{
template <typename... Types>
void fwd(Types const &... types)
{
}
}
PYTHONIC_NS_END
#endif
| 12.842105 | 41 | 0.75 | davidbrochart |
66475d3b68ca2c22cbb0824b4ffece85ce5542ff | 189 | hpp | C++ | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | 3 | 2020-11-10T16:54:58.000Z | 2021-06-05T13:14:15.000Z | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | null | null | null | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | null | null | null | #ifndef GAMEBIRD
#define GAMEBIRD
#include <iostream>
#include <SFML/Graphics.hpp>
class GameBird
{
public:
sf::Vector2f acc = sf::Vector2f(0.f,0.f);
float angle = 0.f;
};
#endif | 13.5 | 45 | 0.677249 | Xnork |
66478fc0a7ff8787021f5f64ea1bb45407bb6154 | 182 | hh | C++ | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | 24 | 2018-04-26T20:06:31.000Z | 2022-03-19T18:45:57.000Z | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | null | null | null | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | 9 | 2018-01-22T11:40:53.000Z | 2022-03-23T20:03:19.000Z | #ifndef SPI_D_HH
#define SPI_D_HH
namespace hal {
using spi1 = spi_d<0x40013000>;
using spi2 = spi_d<0x40003800>;
using spi3 = spi_d<0x40003c00>;
}
#endif // SPI_D_HH
| 15.166667 | 35 | 0.686813 | no111u3 |
6647f2fdbb48bbef51f577d6cb103c99fc765917 | 225 | cpp | C++ | src/pycropml/transpiler/antlr_py/csharp/examples/testfib.cpp | brichet/PyCrop2ML | 7177996f72a8d95fdbabb772a16f1fd87b1d033e | [
"MIT"
] | 5 | 2020-06-21T18:58:04.000Z | 2022-01-29T21:32:28.000Z | src/pycropml/transpiler/antlr_py/csharp/examples/testfib.cpp | brichet/PyCrop2ML | 7177996f72a8d95fdbabb772a16f1fd87b1d033e | [
"MIT"
] | 27 | 2018-12-04T15:35:44.000Z | 2022-03-11T08:25:03.000Z | src/pycropml/transpiler/antlr_py/csharp/examples/testfib.cpp | brichet/PyCrop2ML | 7177996f72a8d95fdbabb772a16f1fd87b1d033e | [
"MIT"
] | 7 | 2019-04-20T02:25:22.000Z | 2021-11-04T07:52:35.000Z | #include<iostream>
#include<vector>
using namespace std;
int testfib(int a)
{
vector<int> h = {15};
int j;
for (j=10 ; j!=6 ; j+=-2)
{
a = j;
}
std::cout<< testfib(10)<<endl;
return a;
}
| 13.235294 | 34 | 0.506667 | brichet |
6648a203f9f473a246049bcdee9a861e93bf0f74 | 129 | cpp | C++ | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:8b3f8015d6166788ea5c3ad03dfb8f09b860a264c927e806ea111d551fe3ed21
size 2121
| 32.25 | 75 | 0.883721 | Diksha-agg |
6649166c1893e84b987cf7b243fae796f84bec6f | 12,675 | cpp | C++ | torch/csrc/jit/operator.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | 1 | 2019-07-21T02:13:22.000Z | 2019-07-21T02:13:22.000Z | torch/csrc/jit/operator.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | torch/csrc/jit/operator.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | #include "ATen/ATen.h"
#include "torch/csrc/jit/script/lexer.h"
#include "torch/csrc/jit/script/tree.h"
#include "torch/csrc/jit/operator.h"
#include "torch/csrc/jit/script/error_report.h"
namespace torch { namespace jit {
namespace script {
struct SchemaParser {
SchemaParser(const std::string& str)
: L(str) {}
FunctionSchema parseDeclaration() {
auto name = L.expect(TK_IDENT).text();
if(L.nextIf(':')) {
L.expect(':');
name = name + "::" + L.expect(TK_IDENT).text();
}
std::vector<Argument> arguments;
std::vector<Argument> returns;
kwarg_only = false;
parseList('(', ',', ')', arguments, &SchemaParser::parseArgument);
L.expect(TK_ARROW);
if(L.cur().kind == '(') {
parseList('(', ',', ')', returns, &SchemaParser::parseReturn);
} else {
parseReturn(returns);
}
return FunctionSchema { name, arguments, returns };
}
std::vector<FunctionSchema> parseDeclarations() {
std::vector<FunctionSchema> results;
do {
results.push_back(parseDeclaration());
} while(L.nextIf(TK_NEWLINE));
L.expect(TK_EOF);
return results;
}
TreeRef parseIdent() {
return String::create(L.expect(TK_IDENT).text());
}
TypePtr parseBaseType() {
static std::unordered_map<std::string, TypePtr> type_map = {
{"Tensor", DynamicType::get() },
{"Generator", DynamicType::get() },
{"ScalarType", IntType::get() },
{"Layout", IntType::get() },
{"Device", ListType::ofInts() },
{"Scalar", NumberType::get() },
{"float", FloatType::get() },
{"int", IntType::get() },
{"bool", IntType::get() }, // TODO: add separate bool type
};
auto tok = L.expect(TK_IDENT);
auto text = tok.text();
auto it = type_map.find(text);
if(it == type_map.end())
throw ErrorReport(tok.range) << "unknown type specifier";
return it->second;
}
void parseType(Argument& arg) {
arg.type = parseBaseType();
if(L.nextIf('[')) {
arg.type = ListType::create(arg.type);
if(L.cur().kind == TK_NUMBER) {
arg.N = std::stoll(L.next().text());
}
L.expect(']');
}
}
void parseArgument(std::vector<Argument>& arguments) {
// varargs
if(L.nextIf('*')) {
kwarg_only = true;
return;
}
Argument arg;
parseType(arg);
// nullability is ignored for now, since the JIT never cares about it
L.nextIf('?');
arg.name = L.expect(TK_IDENT).text();
if(L.nextIf('=')) {
parseDefaultValue(arg);
}
arg.kwarg_only = kwarg_only;
arguments.push_back(std::move(arg));
}
void parseReturn(std::vector<Argument>& args) {
Argument arg("ret" + std::to_string(args.size()));
parseType(arg);
args.push_back(std::move(arg));
}
IValue parseSingleConstant(TypeKind kind) {
switch(L.cur().kind) {
case TK_TRUE:
L.next();
return true;
case TK_FALSE:
L.next();
return false;
case TK_NONE:
L.next();
return IValue();
case TK_IDENT: {
auto tok = L.next();
auto text = tok.text();
if("float" == text) {
return static_cast<int64_t>(at::kFloat);
} else if("cpu" == text) {
return static_cast<int64_t>(at::Device::Type::CPU);
} else if("strided" == text) {
return static_cast<int64_t>(at::kStrided);
} else if("ElementwiseMean" == text) {
return static_cast<int64_t>(Reduction::ElementwiseMean);
} else {
throw ErrorReport(L.cur().range) << "invalid numeric default value";
}
}
default:
std::string n;
if(L.nextIf('-'))
n = "-" + L.expect(TK_NUMBER).text();
else
n = L.expect(TK_NUMBER).text();
if(kind == TypeKind::FloatType || n.find(".") != std::string::npos || n.find("e") != std::string::npos) {
return std::stod(n);
} else {
int64_t v = std::stoll(n);
return v;
}
}
}
IValue convertToList(TypeKind kind, const SourceRange& range, std::vector<IValue> vs) {
switch(kind) {
case TypeKind::FloatType:
return fmap(vs, [](IValue v) {
return v.toDouble();
});
case TypeKind::IntType:
return fmap(vs, [](IValue v) {
return v.toInt();
});
default:
throw ErrorReport(range) << "lists are only supported for float or int types.";
}
}
IValue parseConstantList(TypeKind kind) {
auto tok = L.expect('[');
std::vector<IValue> vs;
if(L.cur().kind != ']') {
do {
vs.push_back(parseSingleConstant(kind));
} while(L.nextIf(','));
}
L.expect(']');
return convertToList(kind, tok.range, std::move(vs));
}
IValue parseTensorDefault(const SourceRange& range) {
L.expect(TK_NONE);
return IValue();
}
void parseDefaultValue(Argument& arg) {
auto range = L.cur().range;
switch(arg.type->kind()) {
case TypeKind::DynamicType: {
arg.default_value = parseTensorDefault(range);
} break;
case TypeKind::NumberType:
case TypeKind::IntType:
case TypeKind::FloatType:
arg.default_value = parseSingleConstant(arg.type->kind());
break;
case TypeKind::ListType: {
auto elem_kind = arg.type->cast<ListType>()->getElementType();
if(L.cur().kind == TK_IDENT) {
arg.default_value = parseTensorDefault(range);
} else if(arg.N && L.cur().kind != '[') {
IValue v = parseSingleConstant(elem_kind->kind());
std::vector<IValue> repeated(*arg.N, v);
arg.default_value = convertToList(elem_kind->kind(), range, repeated);
} else {
arg.default_value = parseConstantList(elem_kind->kind());
}
} break;
default:
throw ErrorReport(range) << "unexpected type, file a bug report";
}
}
template<typename T>
void parseList(int begin, int sep, int end, std::vector<T>& result, void (SchemaParser::*parse)(std::vector<T>&)) {
auto r = L.cur().range;
if (begin != TK_NOTHING)
L.expect(begin);
if (L.cur().kind != end) {
do {
(this->*parse)(result);
} while (L.nextIf(sep));
}
if (end != TK_NOTHING)
L.expect(end);
}
Lexer L;
bool kwarg_only;
};
} // namespace script
namespace {
std::string canonicalSchemaString(const FunctionSchema& schema) {
std::ostringstream out;
out << schema.name;
out << "(";
bool seen_kwarg_only = false;
for(size_t i = 0; i < schema.arguments.size(); ++i) {
if (i > 0) out << ", ";
if (schema.arguments[i].kwarg_only && !seen_kwarg_only) {
out << "*, ";
seen_kwarg_only = true;
}
const auto & arg = schema.arguments[i];
out << arg.type->str() << " " << arg.name;
}
out << ") -> ";
if (schema.returns.size() == 1) {
out << schema.returns.at(0).type->str();
} else if (schema.returns.size() > 1) {
out << "(";
for (size_t i = 0; i < schema.returns.size(); ++i) {
if (i > 0) out << ", ";
out << schema.returns[i].type->str();
}
out << ")";
}
return out.str();
}
using OperatorMap = std::unordered_map<Symbol, std::vector<std::shared_ptr<Operator>>>;
struct OperatorRegistry {
private:
std::mutex lock;
OperatorMap operators;
// list of operators whose schema have not yet been parsed, and must
// be registered before any call to lookup an opeator
std::vector<std::shared_ptr<Operator>> to_register;
// Those two maps are used to implement lookupByLiteral, which is needed for the n->match(...) calls.
// Basically, every function schema is assigned a unique string you can use to match it. However,
// parsing those strings or comparing and hashing them character by character would be very slow, so
// we use a trick here! Every string literal in your program is guaranteed to have static storage
// duration and so its address won't change at runtime. This allows us to memoize answerts for every
// pointer, which is done by the operators_by_sig_literal map. Still, this map is initially
// empty, and so we still need to do the complete string matching at the first time, which is implemented
// by performing a lookup in the operators_by_sig map.
std::unordered_map<std::string, std::shared_ptr<Operator>> operators_by_sig;
std::unordered_map<const char *, std::shared_ptr<Operator>> operators_by_sig_literal;
// XXX - caller must be holding lock
void registerPendingOperators() {
for(auto op : to_register) {
Symbol sym = Symbol::fromQualString(op->schema().name);
operators[sym].push_back(op);
operators_by_sig[canonicalSchemaString(op->schema())] = op;
}
to_register.clear();
}
public:
void registerOperator(Operator&& op) {
std::lock_guard<std::mutex> guard(lock);
to_register.push_back(std::make_shared<Operator>(std::move(op)));
}
const std::shared_ptr<Operator>& lookupByLiteral(const char * name) {
std::lock_guard<std::mutex> guard(lock);
registerPendingOperators();
auto it = operators_by_sig_literal.find(name);
if (it == operators_by_sig_literal.end()) {
auto op_ptr_it = operators_by_sig.find(name);
// Handy debugging code that dumps all operators we know about on mismatch
#if 0
if (op_ptr_it == operators_by_sig.end()) {
for (auto & entry : operators_by_sig) {
std::cout << entry.first << std::endl;
}
}
#endif
JIT_ASSERTM(op_ptr_it != operators_by_sig.end(), "Couldn't find an operator for ", name);
it = operators_by_sig_literal.emplace_hint(it, name, op_ptr_it->second);
}
return it->second;
}
const std::vector<std::shared_ptr<Operator>>& getOperators(Symbol name) {
std::lock_guard<std::mutex> guard(lock);
registerPendingOperators();
static std::vector<std::shared_ptr<Operator>> empty;
auto it = operators.find(name);
if(it != operators.end())
return it->second;
return empty;
}
};
OperatorRegistry& getRegistry() {
static OperatorRegistry r;
return r;
}
} // anonymous namespace
void registerOperator(Operator&& op) {
getRegistry().registerOperator(std::move(op));
}
const std::vector<std::shared_ptr<Operator>>& getAllOperatorsFor(Symbol name) {
return getRegistry().getOperators(name);
}
Operator& sig(const char *signature) {
return *getRegistry().lookupByLiteral(signature);
}
FunctionSchema parseSchema(const std::string& schema) {
return script::SchemaParser(schema).parseDeclarations().at(0);
}
bool Operator::matches(const Node* node) const {
// wrong name
if (node->kind().toQualString() != schema().name) {
return false;
}
at::ArrayRef<const Value*> actuals = node->inputs();
const auto& formals = schema().arguments;
// not enough inputs
if(actuals.size() < formals.size())
return false;
for(size_t i = 0; i < formals.size(); ++i) {
// mismatched input type
if (!actuals[i]->type()->isSubtypeOf(formals[i].type)) {
return false;
}
}
// too many inputs
if(!schema().is_vararg && actuals.size() != formals.size()) {
// std::cout << "not all inputs used\n" << input_i << " " << inputs_size << "\n";
return false;
}
return true;
}
std::shared_ptr<Operator> findOperatorFor(const Node* node) {
const auto& candidates = getAllOperatorsFor(node->kind());
for(const auto& candidate : candidates) {
if(candidate->matches(node)) {
return candidate;
}
}
return nullptr;
}
const Operator& getOperatorFor(const Node* node) {
auto op = findOperatorFor(node);
if(op)
return *op;
auto er = script::ErrorReport(node->getSourceLocation());
er << "Schema not found for node. File a bug report.\n";
er << "Node: " << *node << "\n";
er << "Input types:";
for(size_t i = 0; i < node->inputs().size(); ++i) {
if(i > 0)
er << ", ";
er << *node->inputs()[i]->type();
}
er << "\ncandidates were:\n";
const auto& candidates = getAllOperatorsFor(node->kind());
for(auto & candidate : candidates) {
er << " " << candidate->schema() << "\n";
}
throw er;
}
OperatorSet::OperatorSet(std::initializer_list<const char *> sig_literals) {
auto & registry = getRegistry();
for (const char * sig : sig_literals) {
auto op = registry.lookupByLiteral(sig);
ops[Symbol::fromQualString(op->schema().name)].push_back(op);
}
}
Operator* OperatorSet::find(Node *n) {
auto it = ops.find(n->kind());
if (it == ops.end()) {
return nullptr;
}
for (auto & op : it->second) {
if (op->matches(n)) {
return op.get();
}
}
return nullptr;
}
}}
| 30.035545 | 117 | 0.610335 | DavidKo3 |
664990c2959f6a9675929a52bb9ad8993eee0361 | 586 | hpp | C++ | libs/core/include/fcppt/range/end.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/range/end.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/range/end.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_RANGE_END_HPP_INCLUDED
#define FCPPT_RANGE_END_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <iterator>
#include <fcppt/config/external_end.hpp>
namespace fcppt::range
{
/**
\brief Calls end via ADL.
\ingroup fcpptrange
*/
template <typename Range>
auto end(Range &_range)
{
using std::end;
return end(_range);
}
}
#endif
| 18.903226 | 61 | 0.725256 | freundlich |
664a1e03a1b03027acf3babf1890b394a827fb91 | 175 | cpp | C++ | build/tests/progs/prog9/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | build/tests/progs/prog9/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | build/tests/progs/prog9/main.cpp | pg83/zm | ef9027bd9ee260118fdf80e8b53361da1b7892f3 | [
"MIT"
] | null | null | null | #include <libs/io/file.h>
#include <iostream>
using namespace io;
using namespace std;
int main(int, char** argv) {
cout << file_input_t(argv[1]).read_all() << endl;
}
| 15.909091 | 53 | 0.668571 | pg83 |
664c7e1f325db23e84fb2456f456563f2b62094e | 3,169 | cxx | C++ | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 2 | 2018-06-29T18:11:22.000Z | 2018-08-14T15:45:05.000Z | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 8 | 2018-07-04T00:22:53.000Z | 2018-09-07T03:31:14.000Z | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 3 | 2018-06-29T18:11:37.000Z | 2018-09-05T22:57:27.000Z | #include "vtkSRepExportPolyDataProperties.h"
#include <vtkObjectFactory.h>
//----------------------------------------------------------------------
vtkStandardNewMacro(vtkSRepExportPolyDataProperties);
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::PrintSelf(ostream& os, vtkIndent indent) {
os << indent << "vtkSRepExportPolyDataProperties {" << std::endl
<< indent << " IncludeUpSpokes: " << IncludeUpSpokes << std::endl
<< indent << " IncludeDownSpokes: " << IncludeDownSpokes << std::endl
<< indent << " IncludeCrestSpokes: " << IncludeCrestSpokes << std::endl
<< indent << " IncludeCrestCurve: " << IncludeCrestCurve << std::endl
<< indent << " IncludeSkeletalSheet: " << IncludeSkeletalSheet << std::endl
<< indent << " IncludeSkeletonToCrestConnection: " << IncludeSkeletonToCrestConnection << std::endl
<< indent << " IncludeSpine: " << IncludeSpine << std::endl
<< indent << "}";
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetSRepDataArray(vtkDataArray* name) {
if (this->SRepDataArray != name) {
this->SRepDataArray = name;
this->Modified();
}
}
//----------------------------------------------------------------------
vtkDataArray* vtkSRepExportPolyDataProperties::GetSRepDataArray() const {
return this->SRepDataArray;
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetPointTypeArrayName(const std::string& name) {
if (this->PointTypeArrayName != name) {
this->PointTypeArrayName = name;
this->Modified();
}
}
//----------------------------------------------------------------------
std::string vtkSRepExportPolyDataProperties::GetPointTypeArrayName() const {
return this->PointTypeArrayName;
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetLineTypeArrayName(const std::string& name) {
if (this->LineTypeArrayName != name) {
this->LineTypeArrayName = name;
this->Modified();
}
}
//----------------------------------------------------------------------
std::string vtkSRepExportPolyDataProperties::GetLineTypeArrayName() const {
return this->LineTypeArrayName;
}
//----------------------------------------------------------------------
#define SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(name) \
void vtkSRepExportPolyDataProperties::Set##name(bool include) { \
if (this->name != include) { \
this->name = include; \
this->Modified(); \
} \
} \
bool vtkSRepExportPolyDataProperties::Get##name() const { \
return this->name; \
}
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeUpSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeDownSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeCrestSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeCrestCurve)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSkeletalSheet)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSkeletonToCrestConnection)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSpine)
| 40.628205 | 105 | 0.592616 | Connor-Bowley |
664e0dc1e65be67a2076ac4bc7b5ed508d3dcacb | 5,593 | cpp | C++ | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 2,939 | 2019-08-29T16:52:20.000Z | 2022-03-31T05:42:30.000Z | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 235 | 2019-08-29T23:44:13.000Z | 2022-03-17T11:43:25.000Z | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 95 | 2019-08-29T19:11:28.000Z | 2022-01-03T05:14:16.000Z | #if defined(_WIN32)
#include "lumen/llvm/raw_win32_handle_ostream.h"
#include "Windows/WindowsSupport.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Process.h"
raw_win32_handle_ostream::raw_win32_handle_ostream(HANDLE h, bool isStdIo,
bool shouldClose,
bool unbuffered)
: raw_pwrite_stream(unbuffered), Handle(h), ShouldClose(shouldClose) {
IsConsole = ::GetFileType(Handle) == FILE_TYPE_CHAR;
if (IsConsole) {
ShouldClose = false;
return;
}
// Get the current position
DWORD loc =
::SetFilePointer(Handle, (LONG)0, nullptr,
FILE_CURRENT) if (loc == INVALID_SET_FILE_POINTER) {
SupportsSeeking = false;
pos = 0;
}
else {
pos = static_cast<uint64_t>(loc);
}
}
raw_win32_handle_ostream::~raw_win32_handle_ostream() {
if (Handle != (HANDLE) nullptr) {
flush();
if (ShouldClose) {
if (::CloseHandle(Handle)) {
EC = std::error_code(::GetLastError());
error_detected(EC);
}
}
}
if (has_error()) {
report_fatal_error("IO failure on output stream: " + error().message(),
/*gen_crash_diag=*/false);
}
}
static bool write_console_impl(HANDLE handle, StringRef data) {
SmallVector<wchar_t, 256> wideText;
if (auto ec = sys::windows::UTF8ToUTF16(data, wideText)) return false;
// On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data
// that can be written to the console at a time.
size_t maxWriteSize = wideText.size();
if (!RunningWindows8OrGreater()) maxWriteSize = 32767;
size_t wCharsWritten = 0;
do {
size_t wCharsToWrite =
std::min(maxWriteSize, wideText.size() - wCharsWritten);
DWORD actuallyWritten;
bool success =
::WriteConsoleW(handle, &wideText[wCharsWritten], wCharsToWrite,
&actuallyWritten, /*reserved=*/nullptr);
// The most likely reason to fail is that the handle does not point to a
// console, fall back to write
if (!success) return false;
wCharsWritten += actuallyWritten;
} while (wCharsWritten != wideText.size());
return true;
}
void raw_win32_handle_ostream::write_impl(const char *ptr, size_t size) {
assert(Handle != (HANDLE) nullptr && "File already closed.");
pos += size;
if (IsConsole)
if (write_console_impl(Handle, StringRef(ptr, size))) return;
DWORD bytesWritten = 0;
bool pending = true;
do {
if (!::WriteFile(Handle, (LPCVOID)ptr, (DWORD)size, &bytesWritten,
nullptr)) {
auto err = ::GetLastError();
// Async write
if (err == ERROR_IO_PENDING) {
continue;
} else {
EC = std::error_code(err);
error_detected(EC);
break;
}
} else {
pending = false;
}
} while (pending);
}
void raw_win32_handle_ostream::close() {
assert(ShouldClose);
ShouldClose = false;
flush();
if (::CloseHandle(Handle)) {
EC = std::error_code(::GetLastError());
error_detected(EC);
}
Handle = (HANDLE) nullptr;
}
uint64_t raw_win32_handle_ostream::seek(uint64_t off) {
assert(SupportsSeeking && "Stream does not support seeking!");
flush();
LARGE_INTEGER li;
li.QuadPart = off;
li.LowPart = ::SetFilePointer(Handle, li.LowPart, &li.HighPart, FILE_BEGIN);
if (li.LowPart == INVALID_SET_FILE_POINTER) {
auto err = ::GetLastError();
if (err != NO_ERROR) {
pos = (uint64_t)-1;
li.QuadPart = -1;
error_detected(err);
return pos;
}
}
pos = li.QuadPart;
return pos;
}
void raw_win32_handle_ostream::pwrite_impl(const char *ptr, size_t size,
uint64_t offset) {
uint64_t position = tell();
seek(offset);
write(ptr, size);
seek(position);
}
size_t raw_win32_handle_ostream::preferred_buffer_size() const {
if (IsConsole) return 0;
return raw_ostream::preferred_buffer_size();
}
raw_ostream &raw_win32_handle_ostream::changeColor(enum Colors colors,
bool bold, bool bg) {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode =
(colors == SAVEDCOLOR)
? sys::Process::OutputBold(bg)
: sys::Process::OutputColor(static_cast<char>(colors), bold, bg);
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
raw_ostream &raw_win32_handle_ostream::resetColor() {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode = sys::Process::ResetColor();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
raw_ostream &raw_win32_handle_ostream::reverseColor() {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode = sys::Process::OutputReverse();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
bool raw_win32_handle_ostream::is_displayed() const { return IsConsole; }
bool raw_win32_handle_ostream::has_colors() const { return ColorEnabled; }
void raw_win32_handle_ostream::anchor() {}
#endif
| 27.825871 | 78 | 0.640086 | mlwilkerson |
593eb42e14fd501046309fb833d95580660df15f | 6,375 | cxx | C++ | admin/netui/common/src/blt/blt/bltlbsel.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/src/blt/blt/bltlbsel.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/src/blt/blt/bltlbsel.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
bltlbsel.cxx
BLT listbox selection control classes: implementation
FILE HISTORY:
beng 07-Aug-1991 Created
*/
#include "pchblt.hxx" // Precompiled header
/*******************************************************************
NAME: LB_SELECTION::LB_SELECTION
SYNOPSIS: Constructor
ENTRY: Pointer to host listbox
EXIT: Constructed
NOTES:
HISTORY:
beng 07-Aug-1991 Created
********************************************************************/
LB_SELECTION::LB_SELECTION( LISTBOX* plb )
: _plb(plb),
_cilbSelected(0),
_pilbSelected(NULL)
{
if (plb->IsMultSel())
{
_cilbSelected = plb->QuerySelCount();
_pilbSelected = new INT[_cilbSelected];
if (_pilbSelected == NULL)
{
ReportError(ERROR_NOT_ENOUGH_MEMORY;
return;
}
plb->QuerySelItems(_cilbSelected, _pilbSelected);
}
else
{
INT ilbSelected = plb->QueryCurrentItem();
if (ilbSelected != -1)
{
_cilbSelected = 1;
_pilbSelected = new INT;
_pilbSelected[0] = ilbSelected;
}
}
}
/*******************************************************************
NAME: LB_SELECTION::~LB_SELECTION
SYNOPSIS: Destructor
NOTES:
HISTORY:
beng 14-Aug-1991 Created
********************************************************************/
LB_SELECTION::~LB_SELECTION()
{
if (_cilbSelected > 0)
delete[_cilbSelected] _pilbSelected;
}
/*******************************************************************
NAME: LB_SELECTION::QueryCount
SYNOPSIS: Returns the number of items in the selection
NOTES:
HISTORY:
beng 14-Aug-1991 Created
********************************************************************/
UINT LB_SELECTION::QueryCount()
{
return _cilbSelected;
}
/*******************************************************************
NAME: LB_SELECTION::Select
SYNOPSIS: Add a line in the listbox to the selection
ENTRY: iIndex - index into the listbox
EXIT:
NOTES:
HISTORY:
beng 14-Aug-1991 Created
********************************************************************/
VOID LB_SELECTION::Select( INT iIndex )
{
plb->ChangeSel(iIndex, TRUE);
}
/*******************************************************************
NAME: LB_SELECTION::Unselect
SYNOPSIS: Remove a line in the listbox from the selection
ENTRY: iIndex - index into the listbox
EXIT: Line named is no longer selected.
NOTES:
HISTORY:
********************************************************************/
VOID LB_SELECTION::Unselect( INT iIndex )
{
plb->ChangeSel(iIndex, FALSE);
}
/*******************************************************************
NAME: LB_SELECTION::UnselectAll
SYNOPSIS: Render the listbox without selection
EXIT: Nothing in the listbox is selected.
The selection is empty.
NOTES:
HISTORY:
********************************************************************/
VOID LB_SELECTION::UnselectAll()
{
for (INT iilb = 0; iilb < _cilbSelected; iilb++)
plb->ChangeSel(_pilbSelected[iilb], FALSE);
}
/*******************************************************************
NAME: LB_SELECTION::AddItem
SYNOPSIS: Adds an item to the listbox, leaving it selected.
ENTRY: plbi - pointer to listbox item for new line
EXIT: Line added to listbox.
Line is selected.
RETURNS:
NOTES:
HISTORY:
********************************************************************/
INT LB_SELECTION::AddItem(const LBI* plbi)
{
}
/*******************************************************************
NAME: LB_SELECTION::DeleteAllItems
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
VOID LB_SELECTION::DeleteAllItems()
{
}
/*******************************************************************
NAME: ITER_LB::ITER_LB
SYNOPSIS: Constructor
ENTRY: Several forms exist; may take any one of
plb - pointer to source listbox. Resulting iterator will
count all items in listbox
psel - pointer to listbox selection. Iterator will count
all items in selection
iter - another listbox iterator. Iterator will count
whatever the source iterator counts, and will do
so from the last point of the source iterator.
EXIT: Constructed
NOTES:
HISTORY:
********************************************************************/
ITER_LB::ITER_LB(const BLT_LISTBOX * plb)
{
}
ITER_LB::ITER_LB(const LB_SELECTION * psel)
{
}
ITER_LB::ITER_LB(const ITER_LB & iter)
{
}
/*******************************************************************
NAME: ITER_LB::Reset
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
VOID ITER_LB::Reset()
{
}
/*******************************************************************
NAME: ITER_LB::Next
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
LBI* ITER_LB::Next()
{
}
/*******************************************************************
NAME: ITER_LB::DeleteThis
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
VOID ITER_LB::DeleteThis()
{
}
/*******************************************************************
NAME: ITER_LB::UnselectThis
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
VOID ITER_LB::UnselectThis()
{
}
| 17.857143 | 73 | 0.405804 | npocmaka |
593f7dc01e3074c63c5c7980e45c8f97755e5664 | 1,088 | cpp | C++ | COCI/coci07c3p5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | COCI/coci07c3p5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | COCI/coci07c3p5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define MM 17
#define sc(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
using namespace std;
typedef long long ll;
ll ans = LLONG_MAX, dp[MM][140][2][2];
int S, a[MM], b[MM], n;
char as[MM], bs[MM];
ll go(int pos, int sum, int l, int r, ll num){
if(pos == n){
if(sum == S){
ans = min(ans, num);
return 1;
}
return 0;
}
if(dp[pos][sum][l][r] != -1)
return dp[pos][sum][l][r];
ll ret = 0;
for(int i = (l? a[pos]: 0); i <= (r? b[pos]: 9); i++)
ret += go(pos+1, sum+i, l&&(i == a[pos]), r&&(i == b[pos]), num*10 + i);
return dp[pos][sum][l][r] = ret;
}
int main(){
memset(dp,-1,sizeof dp);
scanf("%s%s%d",as,bs,&S);
n = strlen(bs);
for(int i = 0; i < n; i++)
b[i] = bs[i] - '0';
int dif = n - strlen(as);
for(int i = 0; i < n-dif; i++)
a[i+dif] = as[i] - '0';
printf("%lld\n", go(0,0,1,1,0));
printf("%lld\n", ans);
return 0;
} | 28.631579 | 108 | 0.435662 | crackersamdjam |
594042536411504d4d0fe5baff4539954238728f | 4,211 | cpp | C++ | tools/rcbscape-c++/rcbscapeView.cpp | codetorex/reAction | 6fa95a6666f00a17ba557384a3c67808f6548fe1 | [
"MIT"
] | null | null | null | tools/rcbscape-c++/rcbscapeView.cpp | codetorex/reAction | 6fa95a6666f00a17ba557384a3c67808f6548fe1 | [
"MIT"
] | null | null | null | tools/rcbscape-c++/rcbscapeView.cpp | codetorex/reAction | 6fa95a6666f00a17ba557384a3c67808f6548fe1 | [
"MIT"
] | null | null | null | // rcbscapeView.cpp : implementation of the CRcbscapeView class
//
#include "stdafx.h"
#include "rcbscape.h"
#include "rcbscapeDoc.h"
#include "rcbscapeView.h"
#include "Array.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView
IMPLEMENT_DYNCREATE(CRcbscapeView, CListView)
BEGIN_MESSAGE_MAP(CRcbscapeView, CListView)
//{{AFX_MSG_MAP(CRcbscapeView)
ON_WM_DROPFILES()
ON_WM_CREATE()
ON_NOTIFY_REFLECT(HDN_ITEMDBLCLICK, OnItemdblclick)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CListView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CListView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CListView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView construction/destruction
CRcbscapeView::CRcbscapeView()
{
// TODO: add construction code here
}
CRcbscapeView::~CRcbscapeView()
{
}
BOOL CRcbscapeView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CListView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView drawing
void CRcbscapeView::OnDraw(CDC* pDC)
{
CRcbscapeDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CListCtrl& refCtrl = GetListCtrl();
// refCtrl.InsertItem(0, "Item!");
// TODO: add draw code for native data here
}
void CRcbscapeView::OnInitialUpdate()
{
CListView::OnInitialUpdate();
// GetListCtrl().DeleteColumn(0);
GetDocument()->rig = this;
GetListCtrl().SetImageList(&GetDocument()->imglist_big,LVSIL_NORMAL);
GetListCtrl().SetImageList(&GetDocument()->imglist,LVSIL_SMALL);
GetListCtrl().DeleteAllItems();
// TODO: You may populate your ListView with items by directly accessing
// its list control through a call to GetListCtrl().
}
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView printing
BOOL CRcbscapeView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CRcbscapeView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CRcbscapeView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView diagnostics
#ifdef _DEBUG
void CRcbscapeView::AssertValid() const
{
CListView::AssertValid();
}
void CRcbscapeView::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
CRcbscapeDoc* CRcbscapeView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRcbscapeDoc)));
return (CRcbscapeDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CRcbscapeView message handlers
void CRcbscapeView::OnStyleChanged(int nStyleType, LPSTYLESTRUCT lpStyleStruct)
{
//TODO: add code to react to the user changing the view style of your window
}
void CRcbscapeView::OnDropFiles(HDROP hDropInfo)
{
// TODO: Add your message handler code here and/or call default
//CListView::OnDropFilolsun es(hDropInfo);
}
int CRcbscapeView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CListView::OnCreate(lpCreateStruct) == -1)
return -1;
GetListCtrl().InsertColumn(0,"File Name",LVCFMT_LEFT,230);
GetListCtrl().InsertColumn(1,"Size",LVCFMT_RIGHT,100);
GetListCtrl().InsertColumn(2,"Type",LVCFMT_LEFT,90);
GetListCtrl().InsertColumn(3,"Version",LVCFMT_LEFT,60);
// TODO: Add your specialized creation code here
return 0;
}
void CRcbscapeView::OnItemdblclick(NMHDR* pNMHDR, LRESULT* pResult)
{
HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;
//phdn->pitem->pszText
HTREEITEM a;
MessageBox("bur");
a = IsItemExist( &GetDocument()->lft->GetTreeCtrl() ,GetDocument()->ld,phdn->pitem->pszText);
if (a > 0)
{
GetDocument()->lft->GetTreeCtrl().SelectItem(a);
}
// TODO: Add your control notification handler code here
*pResult = 0;
}
| 24.625731 | 94 | 0.668487 | codetorex |
59420c676a687e1b61b340ed81552567359bd49f | 712 | cpp | C++ | Algorithms/Backtracking/allPermutations.cpp | dipta1010/Algorithm-and-DataStructure | 74bd2041525572109d5058aa03828d9a920aee67 | [
"MIT"
] | 2 | 2018-06-26T07:19:42.000Z | 2019-04-05T19:59:22.000Z | Algorithms/Backtracking/allPermutations.cpp | dipta1010/Algorithm-and-DataStructure | 74bd2041525572109d5058aa03828d9a920aee67 | [
"MIT"
] | null | null | null | Algorithms/Backtracking/allPermutations.cpp | dipta1010/Algorithm-and-DataStructure | 74bd2041525572109d5058aa03828d9a920aee67 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
void permutations(string str, int i, int n) {
if (i == n - 1) {
cout << str << endl;
return;
}
// process each character of the remaining string
for (int j = i; j < n; j++) {
// swap character at index i with current character
swap(str[i], str[j]); // STL swap() used
// recurse for string [i+1, n-1]
permutations(str, i + 1, n);
// backtrack (restore the string to its original state)
swap(str[i], str[j]);
}
}
// Find all Permutations of a string
int main()
{
string str = "abcd";
permutations(str, 0, str.length());
return 0;
}
| 22.25 | 64 | 0.526685 | dipta1010 |
59438814c22f8f8d7d5566c8df865978069e5cab | 2,768 | hpp | C++ | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | 3 | 2019-03-07T21:31:32.000Z | 2020-03-10T21:14:50.000Z | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | null | null | null | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | 1 | 2020-03-10T21:14:56.000Z | 2020-03-10T21:14:56.000Z | #ifndef MULTIPLAYER_PEER_NATIVE
#define MULTIPLAYER_PEER_NATIVE
#include <Godot.hpp>
#include <Reference.hpp>
#include <MultiplayerPeerGDNative.hpp>
#include <net/godot_net.h>
namespace godot {
namespace net {
/* Forward declare interface functions (PacketPeer) */
godot_error get_packet_bind_mp(void *, const uint8_t **, int *);
godot_error put_packet_bind_mp(void *, const uint8_t *, int);
godot_int get_available_packet_count_bind_mp(const void *);
godot_int get_max_packet_size_bind_mp(const void *);
/* Forward declare interface functions (MultiplayerPeer) */
void set_transfer_mode_bind_mp(void *, godot_int);
godot_int get_transfer_mode_bind_mp(const void *);
void set_target_peer_bind_mp(void *, godot_int); // 0 = broadcast, 1 = server, <0 = all but abs(value)
godot_int get_packet_peer_bind_mp(const void *);
godot_bool is_server_bind_mp(const void *);
void poll_bind_mp(void *);
int32_t get_unique_id_bind_mp(const void *); // Must be > 0, 1 is for server
void set_refuse_new_connections_bind_mp(void *, godot_bool);
godot_bool is_refusing_new_connections_bind_mp(const void *);
godot_int get_connection_status_bind_mp(const void *);
class MultiplayerPeerNative : public MultiplayerPeerGDNative {
GODOT_CLASS(MultiplayerPeerNative, MultiplayerPeerGDNative);
protected:
godot_net_multiplayer_peer interface = {
{3, 1},
this,
&get_packet_bind_mp,
&put_packet_bind_mp,
&get_available_packet_count_bind_mp,
&get_max_packet_size_bind_mp,
&set_transfer_mode_bind_mp,
&get_transfer_mode_bind_mp,
&set_target_peer_bind_mp, // 0 = broadcast, 1 = server, <0 = all but abs(value)
&get_packet_peer_bind_mp,
&is_server_bind_mp,
&poll_bind_mp,
&get_unique_id_bind_mp, // Must be > 0, 1 is for server
&set_refuse_new_connections_bind_mp,
&is_refusing_new_connections_bind_mp,
&get_connection_status_bind_mp,
NULL
};
public:
static void _register_methods();
void _init();
~MultiplayerPeerNative();
/* PacketPeer */
virtual godot_error get_packet(const uint8_t **r_buffer, int *r_len) = 0;
virtual godot_error put_packet(const uint8_t *p_buffer, int p_len) = 0;
virtual godot_int get_available_packet_count() const = 0;
virtual godot_int get_max_packet_size() const = 0;
/* MultiplayerPeer */
virtual void set_transfer_mode(godot_int p_mode) = 0;
virtual godot_int get_transfer_mode() const = 0;
virtual void set_target_peer(godot_int p_peer_id) = 0;
virtual int get_packet_peer() const = 0;
virtual bool is_server() const = 0;
virtual void poll() = 0;
virtual int get_unique_id() const = 0;
virtual void set_refuse_new_connections(godot_bool p_enable) = 0;
virtual bool is_refusing_new_connections() const = 0;
virtual godot_int get_connection_status() const = 0;
};
}
}
#endif // MULTIPLAYER_PEER_NATIVE
| 33.349398 | 102 | 0.781792 | Faless |
5944cc57bfbfefadd520283552374f2359965d52 | 15,030 | cpp | C++ | src/UiCrt_Keyboard.cpp | jtbattle/wangemu | 12c760fa04456304282b966e757e2595d8f29576 | [
"MIT"
] | 6 | 2018-08-28T06:17:03.000Z | 2021-11-26T14:00:37.000Z | src/UiCrt_Keyboard.cpp | BOBBYWY/wangemu | 12c760fa04456304282b966e757e2595d8f29576 | [
"MIT"
] | null | null | null | src/UiCrt_Keyboard.cpp | BOBBYWY/wangemu | 12c760fa04456304282b966e757e2595d8f29576 | [
"MIT"
] | 1 | 2021-11-26T04:15:09.000Z | 2021-11-26T04:15:09.000Z | // This is not its own class -- it just implements the keyboard part of
// the Crt class. It catches keyboard events and then maps that into the
// emulated function.
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "IoCardKeyboard.h" // to pick up core_* keyboard functions
#include "TerminalState.h" // m_crt_state definition
#include "Ui.h" // emulator interface
#include "UiCrt.h" // just the display part
#include "UiCrtFrame.h" // emulated terminal
#include "UiSystem.h" // sharing info between UI_wxgui modules
#include "system2200.h"
#include "tokens.h" // keymap tokens
// ----------------------------------------------------------------------------
// code
// ----------------------------------------------------------------------------
// PC_keycode (shift/non-shift flag) --> Wang_keycode Keyword/A, Wang_keycode A/a
#define KC_ANY 0x0000 // this mapping applies any time
#define KC_NOSHIFT 0x0001 // this mapping applies only if SHIFT isn't present
#define KC_SHIFT 0x0002 // this mapping applies only if SHIFT is present
#define KC_NOCTRL 0x0004 // this mapping applies only if CONTROL isn't present
#define KC_CTRL 0x0008 // this mapping applies only if CONTROL is present
struct kd_keymap_t {
int wxKey;
int wxKeyFlags;
int wangKey;
};
static constexpr kd_keymap_t keydown_keymap_table[] = {
// --------------------------- keyword keys -------------------------------
// most of these don't have a natural mapping, so just use Ctrl-<letter>
// where the letter is mnemonic and doesn't conflict with other Ctrl keys.
//
// key modifier mapping
#ifdef __WXMAC__
{ WXK_CLEAR, KC_ANY, TOKEN_CLEAR },
#endif
{ 'C', KC_CTRL | KC_NOSHIFT, TOKEN_CLEAR },
{ 'L', KC_CTRL | KC_NOSHIFT, TOKEN_LOAD },
{ 'P', KC_CTRL | KC_NOSHIFT, TOKEN_PRINT },
{ 'R', KC_CTRL | KC_NOSHIFT, TOKEN_RUN },
{ 'Z', KC_CTRL | KC_NOSHIFT, TOKEN_CONTINUE },
// ----------------------- various control keys ---------------------------
// key modifier mapping
{ WXK_BACK, KC_ANY, 0x08 },
{ WXK_RETURN, KC_ANY, 0x0D },
{ WXK_NUMPAD_ENTER, KC_ANY, 0x0D },
// clear line
{ WXK_HOME, KC_ANY, 0xE5 },
// next highest line # (in 6367 keyboard controller mode)
// FN (in MXD mode; Terminal.cpp takes care of remapping it)
{ WXK_TAB, KC_ANY, 0xE6 },
// halt/step
{ 'S', /*step*/ KC_CTRL | KC_NOSHIFT, IoCardKeyboard::KEYCODE_HALT },
#ifdef __WXMSW__
{ WXK_PAUSE, KC_ANY, IoCardKeyboard::KEYCODE_HALT },
#endif
// ----------------------- special function keys ---------------------------
// key modifier mapping
{ WXK_ESCAPE, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x00 },
{ WXK_ESCAPE, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x10 },
{ WXK_F1, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x01 },
{ WXK_F1, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x11 },
{ WXK_F2, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x02 },
{ WXK_F2, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x12 },
{ WXK_F3, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x03 },
{ WXK_F3, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x13 },
// edit mode: end of line
{ WXK_F4, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x04 },
{ WXK_F4, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x14 },
#ifdef __WXMAC__
{ WXK_DOWN, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x04 },
#else
{ WXK_RIGHT, KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x04 },
#endif
// edit mode: down a line
{ WXK_DOWN, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x05 },
{ WXK_F5, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x05 },
{ WXK_F5, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x15 },
// edit mode: up a line
{ WXK_UP, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x06 },
{ WXK_F6, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x06 },
{ WXK_F6, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x16 },
// edit mode: beginning of line
{ WXK_F7, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x07 },
{ WXK_F7, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x17 },
#ifdef __WXMAC__
{ WXK_UP, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x07 },
#else
{ WXK_LEFT, KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x07 },
#endif
// edit mode: erase to end of line
{ 'K', KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x08 },
{ WXK_END, KC_ANY, IoCardKeyboard::KEYCODE_SF | 0x08 },
{ WXK_F8, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x08 },
{ WXK_F8, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x18 },
// edit mode: delete a character
{ 'D', KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x09 },
{ WXK_DELETE, KC_ANY, IoCardKeyboard::KEYCODE_SF | 0x09 },
{ WXK_F9, KC_NOSHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x09 },
{ WXK_F9, KC_SHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x19 },
// edit mode: insert a character
{ 'I', KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x0A },
{ WXK_INSERT, KC_ANY, IoCardKeyboard::KEYCODE_SF | 0x0A },
{ WXK_F10, KC_NOSHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x0A },
{ WXK_F10, KC_SHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x1A },
// edit mode: skip five spaces right
{ WXK_RIGHT, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x0B },
{ WXK_F11, KC_NOSHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x0B },
{ WXK_F11, KC_SHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x1B },
// edit mode: skip one space right
{ WXK_RIGHT, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x0C },
{ WXK_F12, KC_NOSHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x0C },
{ WXK_F12, KC_SHIFT | KC_NOCTRL, IoCardKeyboard::KEYCODE_SF | 0x1C },
// edit mode: skip one space left
{ WXK_LEFT, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x0D },
{ WXK_F13, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x0D },
{ WXK_F13, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x1D },
#ifdef __WXMSW__
{ WXK_F9, KC_NOSHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x0D },
{ WXK_F9, KC_SHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x1D },
#endif
// edit mode: skip five spaces left
{ WXK_LEFT, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x0E },
{ WXK_F14, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x0E },
{ WXK_F14, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x1E },
#ifdef __WXMSW__
{ WXK_F10, KC_NOSHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x0E },
{ WXK_F10, KC_SHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x1E },
#endif
// edit mode: recall
{ 'F', KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x0F },
{ WXK_F15, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | 0x0F },
{ WXK_F15, KC_SHIFT, IoCardKeyboard::KEYCODE_SF | 0x1F },
#ifdef __WXMSW__
{ WXK_F11, KC_NOSHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x0F },
{ WXK_F11, KC_SHIFT | KC_CTRL, IoCardKeyboard::KEYCODE_SF | 0x1F },
#endif
// edit mode toggle
{ 'E', KC_CTRL, IoCardKeyboard::KEYCODE_SF | IoCardKeyboard::KEYCODE_EDIT },
#ifdef __WXMSW__
{ WXK_F12, KC_CTRL, IoCardKeyboard::KEYCODE_SF | IoCardKeyboard::KEYCODE_EDIT },
#endif
#ifdef __WXMAC__
{ WXK_F16, KC_NOSHIFT, IoCardKeyboard::KEYCODE_SF | IoCardKeyboard::KEYCODE_EDIT },
#endif
/*
-- numeric keypad:
NUM_LOCK, TOKEN_PRINT,
NUM_LOCK+SHIFT, TOKEN_ARC,
'(', TOKEN_SIN,
')', TOKEN_COS,
'^', TOKEN_TAN,
'*', TOKEN_SQR,
'-', TOKEN_EXP,
'+', TOKEN_LOG,
'/', TOKEN_PI,
-- figure out how to map these in:
',', TOKEN_RENUMBER,
'.', TOKEN_LIST,
*/
};
struct oc_keymap_t {
int wxKey;
int wangKey_KW_mode;
int wangKey_Aa_mode;
};
static constexpr oc_keymap_t onchar_keymap_table[] = {
// key Keyword/A mapping A/a mapping
{ 'a', 'A', 'a' },
{ 'A', TOKEN_HEX, 'A' },
{ 'b', 'B', 'b' },
{ 'B', TOKEN_SKIP, 'B' },
{ 'c', 'C', 'c' },
{ 'C', TOKEN_REWIND, 'C' },
{ 'd', 'D', 'd' },
{ 'D', TOKEN_DATA, 'D' },
{ 'e', 'E', 'e' },
{ 'E', TOKEN_DEFFN, 'E' },
{ 'f', 'F', 'f' },
{ 'F', TOKEN_RESTORE, 'F' },
{ 'g', 'G', 'g' },
{ 'G', TTOKEN_READ, 'G' },
{ 'h', 'H', 'h' },
{ 'H', TOKEN_IF, 'H' },
{ 'i', 'I', 'i' },
{ 'I', TOKEN_FOR, 'I' },
{ 'j', 'J', 'j' },
{ 'J', TOKEN_THEN, 'J' },
{ 'k', 'K', 'k' },
{ 'K', TOKEN_STOP, 'K' },
{ 'l', 'L', 'l' },
{ 'L', TOKEN_END, 'L' },
{ 'm', 'M', 'm' },
{ 'M', TOKEN_GOTO, 'M' },
{ 'n', 'N', 'n' },
{ 'N', TOKEN_TRACE, 'N' },
{ 'o', 'O', 'o' },
{ 'O', TOKEN_STEP, 'O' },
{ 'p', 'P', 'p' },
{ 'P', TOKEN_NEXT, 'P' },
{ 'q', 'Q', 'q' },
{ 'Q', TOKEN_COM, 'Q' },
{ 'r', 'R', 'r' },
{ 'R', TOKEN_GOSUB, 'R' },
{ 's', 'S', 's' },
{ 'S', TOKEN_STR, 'S' },
{ 't', 'T', 't' },
{ 'T', TOKEN_RETURN, 'T' },
{ 'u', 'U', 'u' },
{ 'U', TOKEN_INPUT, 'U' },
{ 'v', 'V', 'v' },
{ 'V', TOKEN_SAVE, 'V' },
{ 'w', 'W', 'w' },
{ 'W', TOKEN_DIM, 'W' },
{ 'x', 'X', 'x' },
{ 'X', TOKEN_BACKSPACE, 'X' },
{ 'y', 'Y', 'y' },
{ 'Y', TOKEN_REM, 'Y' },
{ 'z', 'Z', 'z' },
{ 'Z', TOKEN_SELECT, 'Z' },
};
void
Crt::OnChar(wxKeyEvent &event)
{
// don't swallow keystrokes that we can't handle
if (event.AltDown()) {
event.Skip();
return;
}
const int wxKey = event.GetKeyCode();
const bool shift = event.ShiftDown();
const bool ctrl = event.RawControlDown();
// map ctrl-A through ctrl-Z to 'A' to 'Z'
const int baseKey = (ctrl && (1 <= wxKey) && (wxKey <= 26)) ? (wxKey | 64) : wxKey;
int key = 0x00; // key value we stuff into emulator
bool found_map = false;
for (auto const &kkey : keydown_keymap_table) {
if (kkey.wxKey != baseKey) {
continue;
}
if ( shift && ((kkey.wxKeyFlags & KC_NOSHIFT) != 0)) {
continue;
}
if (!shift && ((kkey.wxKeyFlags & KC_SHIFT) != 0)) {
continue;
}
if ( ctrl && ((kkey.wxKeyFlags & KC_NOCTRL) != 0)) {
continue;
}
if (!ctrl && ((kkey.wxKeyFlags & KC_CTRL) != 0)) {
continue;
}
key = kkey.wangKey;
found_map = true;
break;
}
if (!found_map) {
const bool keyword_mode = m_parent->getKeywordMode();
const bool smart_term = (m_crt_state->screen_type == UI_SCREEN_2236DE);
if (smart_term) {
// the 2236 doesn't support keyword mode, just caps lock
if (keyword_mode && ('a' <= baseKey && baseKey <= 'z')) {
key = baseKey - 'a' + 'A'; // force to uppercase
found_map = true;
}
} else {
// the first generation keyboards had a keyword associated with
// each letter A-Z
for (auto const &kkey : onchar_keymap_table) {
if (kkey.wxKey == baseKey) {
key = (keyword_mode) ? kkey.wangKey_KW_mode
: kkey.wangKey_Aa_mode;
found_map = true;
break;
}
}
}
if (!found_map && (wxKey >= 32) && (wxKey < 128)) {
// non-mapped simple ASCII key
key = wxKey;
found_map = true;
}
}
if (found_map) {
system2200::dispatchKeystroke(m_parent->getTiedAddr(),
m_parent->getTermNum(),
key);
} else {
// percolate the event up to the parent
event.Skip();
}
}
// vim: ts=8:et:sw=4:smarttab
| 40.953678 | 116 | 0.435928 | jtbattle |
5946fdc94e10dbfd0a5c58d24cd4f04eea0be14f | 3,190 | cpp | C++ | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 69 | 2019-04-17T04:03:31.000Z | 2021-11-08T10:29:54.000Z | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 113 | 2019-04-13T06:46:32.000Z | 2021-11-02T01:45:06.000Z | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 46 | 2019-04-17T04:03:36.000Z | 2021-09-26T13:11:37.000Z | #ifndef _PRAGMA_COPYRIGHT_
#define _PRAGMA_COPYRIGHT_
#pragma comment(copyright, "%Z% %I% %W% %D% %T%\0")
#endif /* _PRAGMA_COPYRIGHT_ */
/****************************************************************************
* Copyright (c) 2008, 2010 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0s
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
Classes: FilterProcessor
Description: Properties of class 'FilterProcessor':
input: a. a message queue
output: a. a stream
b. a message queue
action: use user-defined filter handlers to process the messages
Author: Nicole Nie
History:
Date Who ID Description
-------- --- --- -----------
02/10/09 nieyy Initial code (D153875)
****************************************************************************/
#include "filterproc.hpp"
#include <assert.h>
#include "log.hpp"
#include "exception.hpp"
#include "socket.hpp"
#include "atomic.hpp"
#include "ctrlblock.hpp"
#include "message.hpp"
#include "stream.hpp"
#include "filter.hpp"
#include "filterlist.hpp"
#include "queue.hpp"
#include "eventntf.hpp"
#include "observer.hpp"
FilterProcessor::FilterProcessor(int hndl, FilterList *flist)
: Processor(hndl), filterList(flist), filtered(false), curFilterID(SCI_FILTER_NULL)
{
name = "UpstreamFilter";
inQueue = NULL;
outQueue = NULL;
observer = NULL;
}
FilterProcessor::~FilterProcessor()
{
delete inQueue;
}
Message * FilterProcessor::read()
{
assert(inQueue);
Message *msg = NULL;
filtered = false;
msg = inQueue->consume();
return msg;
}
void FilterProcessor::process(Message * msg)
{
int id = msg->getFilterID();
if (id != SCI_FILTER_NULL) {
Filter *filter = filterList->getFilter(id);
// call user's filter handler
if (filter != NULL) {
curFilterID = id;
filtered = true;
filter->input(msg->getGroup(), msg->getContentBuf(), msg->getContentLen());
}
}
}
void FilterProcessor::write(Message * msg)
{
assert(outQueue);
if (filtered) {
inQueue->remove();
return;
}
if (observer) {
observer->notify();
}
incRefCount(msg->getRefCount());
outQueue->produce(msg);
inQueue->remove();
}
void FilterProcessor::seize()
{
setState(false);
}
int FilterProcessor::recover()
{
// TODO
return -1;
}
void FilterProcessor::clean()
{
}
void FilterProcessor::deliever(Message * msg)
{
if (observer) {
observer->notify();
}
outQueue->produce(msg);
}
int FilterProcessor::getCurFilterID()
{
return curFilterID;
}
void FilterProcessor::setInQueue(MessageQueue * queue)
{
inQueue = queue;
}
void FilterProcessor::setOutQueue(MessageQueue * queue)
{
outQueue = queue;
}
void FilterProcessor::setObserver(Observer * ob)
{
observer = ob;
}
MessageQueue * FilterProcessor::getInQueue()
{
return inQueue;
}
MessageQueue * FilterProcessor::getOutQueue()
{
return outQueue;
}
| 19.813665 | 87 | 0.619749 | hongsenliu |
594b18824959e5ef5ba9bc20d987098e72a21400 | 1,768 | cpp | C++ | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 11 | 2016-11-15T20:06:19.000Z | 2021-03-31T01:04:01.000Z | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 1 | 2016-11-06T23:53:05.000Z | 2016-11-07T08:06:07.000Z | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 2 | 2017-09-03T11:18:46.000Z | 2019-03-10T06:27:49.000Z | #include "Engine.h"
//Renderer Includes
#include "Renderer.h"
//Event Manager
#include "EventManager.h"
//SceneManager
#include "SceneManager.h"
//Other includes
#include <string>
Engine::Engine() :m_bInitialized(false)
{
m_strApplicationName = "Set name for application";
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Initialize(int WindowWidth, int WindowsHeight, LRESULT(CALLBACK MainWindowProc)(HWND, UINT, WPARAM, LPARAM), bool bFullscreen)
{
m_pRenderer = new Renderer;
//m_pAudioComponent = new AudioComponent;
m_pEventManager = new EventManager;
m_pSceneManager = new SceneManager;
//m_pSoundManager = new SoundManager;
m_iScreenWidth = WindowWidth;
m_iScreenHeight = WindowsHeight;
//Initialize QueryPerfomance counter
QueryPerformanceCounter(&m_StartTime);
QueryPerformanceFrequency(&m_Freq);
// Initialize Renderer
if (m_pRenderer->VInitRenderer(WindowWidth, WindowsHeight, false, HandleWindowMessages));
{
}
//Everything is initialized
m_bInitialized = true;
}
void Engine::Frame()
{
}
void Engine::Shutdown()
{
if (m_bInitialized)
{
//The order of deletion is important
delete m_pSceneManager;
m_pSceneManager = nullptr;
delete m_pAudioComponent;
m_pAudioComponent = nullptr;
delete m_pRenderer;
m_pRenderer = nullptr;
delete m_pEventManager;
m_pEventManager = nullptr;
delete m_pSoundManager;
m_pSoundManager = nullptr;
//UnregisterClass(m_strApplicationName.c_str(), m_wc.hInstance);
}
}
int Engine::GetTimeInMS()
{
LARGE_INTEGER ms;
QueryPerformanceCounter(&ms);
return ((ms.QuadPart - m_StartTime.QuadPart) * 1000) / m_Freq.QuadPart;
}
void Engine::GetMousePos(float &x, float &y)
{
//POINT p;
//GetCursorPos(&p);
//ScreenToClient(m_hWnd, &p);
//x = p.x;
//y = p.y;
} | 18.040816 | 139 | 0.738688 | TywyllSoftware |
594d4f6bd893ab1ea917409e8cbd38436ce469c7 | 8,381 | hpp | C++ | DGLib/implementations/DGBarControlFunc.hpp | graphisoft-python/DGLib | 66d8717eb4422b968444614ff1c0c6c1bf50d080 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | DGLib/implementations/DGBarControlFunc.hpp | graphisoft-python/DGLib | 66d8717eb4422b968444614ff1c0c6c1bf50d080 | [
"Apache-2.0"
] | null | null | null | DGLib/implementations/DGBarControlFunc.hpp | graphisoft-python/DGLib | 66d8717eb4422b968444614ff1c0c6c1bf50d080 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../stdafx.h"
#include "DGItem.hpp"
#include "DGBarControl.hpp"
using namespace DG;
// --- PyBarControlObserver --------------------------------------------------------------------
class PyBarControlObserver : BarControlObserver {
public:
PyBarControlObserver(BarControl &item)
:m_parent(item) {
this->m_parent.Attach(*this);
this->m_state = GetCurrentAppState();
}
~PyBarControlObserver() {
this->m_parent.Detach(*this);
}
ITEMOBSERVER_METHODS
void BarControlChanged(const BarControlChangeEvent& ev) override {
OBSERVER_CALL_EVENT("BarControlChanged", ev);
}
void BarControlTrackEntered(const BarControlTrackEvent& ev) override {
OBSERVER_CALL_EVENT("BarControlTrackEntered", ev);
}
void BarControlTracked(const BarControlTrackEvent& ev) override {
OBSERVER_CALL_EVENT("BarControlTracked", ev);
}
void BarControlTrackExited(const BarControlTrackEvent& ev) override {
OBSERVER_CALL_EVENT("BarControlTrackExited", ev);
}
private:
BarControl &m_parent;
PyThreadState *m_state;
};
// --- PyScrollBarObserver ---------------------------------------------------------------------
class PyScrollBarObserver : ScrollBarObserver {
public:
PyScrollBarObserver(ScrollBar &item)
:m_parent(item) {
this->m_parent.Attach(*this);
this->m_state = GetCurrentAppState();;
}
~PyScrollBarObserver() {
this->m_parent.Detach(*this);
}
ITEMOBSERVER_METHODS
void ScrollBarChanged(const ScrollBarChangeEvent& ev) override {
OBSERVER_CALL_EVENT("ScrollBarChanged", ev);
}
void ScrollBarTrackEntered(const ScrollBarTrackEvent& ev) override {
OBSERVER_CALL_EVENT("ScrollBarTrackEntered", ev);
}
void ScrollBarTracked(const ScrollBarTrackEvent& ev) override {
OBSERVER_CALL_EVENT("ScrollBarTracked", ev);
}
void ScrollBarTrackExited(const ScrollBarTrackEvent& ev) override {
OBSERVER_CALL_EVENT("ScrollBarTrackExited", ev);
}
private:
ScrollBar &m_parent;
PyThreadState *m_state;
};
// --- BarControl ------------------------------------------------------------------------------
void load_BarControl(py::module m) {
// --- BarControl --------------------------------------------------------------------------
py::class_<BarControl, Item>(m, "BarControl")
.def("SetMin", &BarControl::SetMin)
.def("SetMax", &BarControl::SetMax)
.def("SetValue", &BarControl::SetValue)
.def("GetMin", &BarControl::GetMin)
.def("GetMax", &BarControl::GetMax)
.def("GetValue", &BarControl::GetValue);
// --- BarControlChangeEvent ---------------------------------------------------------------
py::class_<BarControlChangeEvent, ItemChangeEvent>(m, "BarControlChangeEvent")
.def("GetSource", &BarControlChangeEvent::GetSource, py::return_value_policy::reference)
.def("GetPreviousValue", &BarControlChangeEvent::GetPreviousValue);
// --- BarControlTrackEvent ----------------------------------------------------------------
py::class_<BarControlTrackEvent, ItemTrackEvent>(m, "BarControlTrackEvent")
.def("GetSource", &BarControlTrackEvent::GetSource, py::return_value_policy::reference);
// --- BarControlObserver ------------------------------------------------------------------
py::class_<PyBarControlObserver>(m, "BarControlObserver", py::dynamic_attr())
.def(py::init<BarControl &>());
}
// --- BarControlEX ----------------------------------------------------------------------------
void load_BarControlEX(py::module m) {
// --- SingleSpin --------------------------------------------------------------------------
py::class_<SingleSpin, BarControl>(m, "SingleSpin")
.def(py::init<Panel &, Rect &>());
// --- EditSpin ----------------------------------------------------------------------------
py::class_<EditSpin, BarControl>(m, "EditSpin")
.def(py::init<Panel &, Rect &, PosIntEdit &>())
.def(py::init<Panel &, Rect &, IntEdit &>());
// --- Slider ------------------------------------------------------------------------------
py::class_<Slider, BarControl> m_Slider(m, "Slider");
py::enum_<Slider::SliderType>(m_Slider, "SliderType")
.value("BottomRight", Slider::SliderType::BottomRight)
.value("TopLeft", Slider::SliderType::TopLeft)
.export_values();
m_Slider
.def(py::init<Panel &, Rect &, short, Slider::SliderType>(),
py::arg("panel"),
py::arg("rect"),
py::arg("ticks"),
py::arg("type") = Slider::SliderType::BottomRight);
}
// --- ScrollBar -------------------------------------------------------------------------------
void load_ScrollBar(py::module m) {
// --- ScrollBar ---------------------------------------------------------------------------
py::class_<ScrollBar, Item> m_scrollBar(m, "ScrollBar");
py::enum_<ScrollBar::ThumbType>(m_scrollBar, "ThumbType")
.value("Normal", ScrollBar::ThumbType::Normal)
.value("Proportional", ScrollBar::ThumbType::Proportional)
.export_values();
py::enum_<ScrollBar::FocusableType>(m_scrollBar, "FocusableType")
.value("Focusable", ScrollBar::FocusableType::Focusable)
.value("NonFocusable", ScrollBar::FocusableType::NonFocusable)
.export_values();
py::enum_<ScrollBar::AutoScrollType>(m_scrollBar, "AutoScrollType")
.value("AutoScroll", ScrollBar::AutoScrollType::AutoScroll)
.value("NoAutoScroll", ScrollBar::AutoScrollType::NoAutoScroll)
.export_values();
m_scrollBar
.def(py::init<Panel &, Rect &, ScrollBar::ThumbType, ScrollBar::FocusableType, ScrollBar::AutoScrollType>(),
py::arg("panel"),
py::arg("rect"),
py::arg("thumb") = ScrollBar::ThumbType::Normal,
py::arg("focus") = ScrollBar::FocusableType::Focusable,
py::arg("autoScroll") = ScrollBar::AutoScrollType::AutoScroll)
.def("SetMin", &ScrollBar::SetMin)
.def("SetMax", &ScrollBar::SetMax)
.def("SetValue", &ScrollBar::SetValue)
.def("GetMin", &ScrollBar::GetMin)
.def("GetMax", &ScrollBar::GetMax)
.def("GetValue", &ScrollBar::GetValue)
.def("SetPageSize", &ScrollBar::SetPageSize)
.def("GetPageSize", &ScrollBar::GetPageSize);
// --- ScrollBarChangeEvent ----------------------------------------------------------------
py::class_<ScrollBarChangeEvent, ItemChangeEvent>(m, "ScrollBarChangeEvent")
.def("GetSource", &ScrollBarChangeEvent::GetSource, py::return_value_policy::reference)
.def("GetPreviousValue", &ScrollBarChangeEvent::GetPreviousValue);
// --- ScrollBarTrackEvent -----------------------------------------------------------------
py::class_<ScrollBarTrackEvent, ItemTrackEvent>(m, "ScrollBarTrackEvent")
.def("GetSource", &ScrollBarTrackEvent::GetSource, py::return_value_policy::reference)
.def("IsLineUp", &ScrollBarTrackEvent::IsLineUp)
.def("IsLineLeft", &ScrollBarTrackEvent::IsLineLeft)
.def("IsLineDown", &ScrollBarTrackEvent::IsLineDown)
.def("IsLineRight", &ScrollBarTrackEvent::IsLineRight)
.def("IsPageUp", &ScrollBarTrackEvent::IsPageUp)
.def("IsPageLeft", &ScrollBarTrackEvent::IsPageLeft)
.def("IsPageDown", &ScrollBarTrackEvent::IsPageDown)
.def("IsPageRight", &ScrollBarTrackEvent::IsPageRight)
.def("IsTop", &ScrollBarTrackEvent::IsTop)
.def("IsLeft", &ScrollBarTrackEvent::IsLeft)
.def("IsBottom", &ScrollBarTrackEvent::IsBottom)
.def("IsRight", &ScrollBarTrackEvent::IsRight)
.def("IsThumbTrack", &ScrollBarTrackEvent::IsThumbTrack);
// --- ScrollBarObserver -------------------------------------------------------------------
py::class_<PyScrollBarObserver>(m, "ScrollBarObserver", py::dynamic_attr())
.def(py::init<ScrollBar &>());
}
// --- ProgressBar -----------------------------------------------------------------------------
void load_ProgressBar(py::module m) {
py::class_<ProgressBar, Item> m_progressBar(m, "ProgressBar");
py::enum_<ProgressBar::FrameType>(m_progressBar, "FrameType")
.value("NoFrame", ProgressBar::FrameType::NoFrame)
.value("StaticFrame", ProgressBar::FrameType::StaticFrame)
.value("ClientFrame", ProgressBar::FrameType::ClientFrame)
.value("ModalFrame", ProgressBar::FrameType::ModalFrame)
.export_values();
m_progressBar
.def(py::init<Panel &, Rect &, ProgressBar::FrameType>(),
py::arg("panel"),
py::arg("rect"),
py::arg("autoScroll") = ProgressBar::FrameType::NoFrame)
.def("SetMin", &ProgressBar::SetMin)
.def("SetMax", &ProgressBar::SetMax)
.def("SetValue", &ProgressBar::SetValue)
.def("GetMin", &ProgressBar::GetMin)
.def("GetMax", &ProgressBar::GetMax)
.def("GetValue", &ProgressBar::GetValue);
} | 36.43913 | 110 | 0.618303 | graphisoft-python |
594f65a9fb216909fc79575012dc292393ab79c9 | 1,784 | hxx | C++ | com/oleutest/cachetst/genforc.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/oleutest/cachetst/genforc.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/oleutest/cachetst/genforc.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1993.
//
// File: genforc.hxx
//
// Contents: C exposure for the generice enumerator object
//
// Classes: CEnumeratorTestForC
//
// Functions:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
//--------------------------------------------------------------------------
#ifndef _GENFORC_HXX
#define _GENFORC_HXX
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <ole2.h>
#include "genenum.h"
//+-------------------------------------------------------------------------
//
// Class: CEnumeratorTestForC
//
// Purpose: enumerator test class
//
// Interface:
//
// History: dd-mmm-yy Author Comment
// 23-May-94 kennethm author
//
// Notes:
//
//--------------------------------------------------------------------------
class CEnumeratorTestForC : public CEnumeratorTest
{
public:
// static create function
static HRESULT Create(
CEnumeratorTestForC **ppEnumTest,
void *penum,
size_t ElementSize,
LONG ElementCount,
BOOL (*verify)(void*),
BOOL (*verifyall)(void*,LONG),
void (*cleanup)(void*));
private:
CEnumeratorTestForC();
BOOL (*m_fnVerify)(void*);
BOOL (*m_fnVerifyAll)(void*,LONG);
void (*m_fnCleanup)(void*);
virtual BOOL Verify(void *);
virtual BOOL VerifyAll(void*, LONG);
virtual void Cleanup(void *);
};
#endif // !_GENFORC_HXX
| 23.786667 | 77 | 0.472534 | npocmaka |
59511cd65b3f9e5c8f5c180ae9ea2048f7cc073c | 33,675 | cxx | C++ | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | 7 | 2020-03-17T13:18:49.000Z | 2022-03-03T17:34:16.000Z | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | null | null | null | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | 1 | 2021-09-22T12:10:06.000Z | 2021-09-22T12:10:06.000Z | #include "data_loaders/DataLoaderDTU.h"
//loguru
#define LOGURU_REPLACE_GLOG 1
#include <loguru.hpp>
//configuru
#define CONFIGURU_WITH_EIGEN 1
#define CONFIGURU_IMPLICIT_CONVERSIONS 1
#include <configuru.hpp>
using namespace configuru;
//cnpy
#include "cnpy.h"
#include <opencv2/core/eigen.hpp>
//my stuff
#include "data_loaders/DataTransformer.h"
#include "easy_pbr/Frame.h"
#include "Profiler.h"
#include "string_utils.h"
#include "numerical_utils.h"
#include "opencv_utils.h"
#include "eigen_utils.h"
#include "RandGenerator.h"
#include "easy_pbr/LabelMngr.h"
#include "UtilsGL.h"
//json
// #include "json11/json11.hpp"
//boost
namespace fs = boost::filesystem;
// using namespace er::utils;
using namespace radu::utils;
using namespace easy_pbr;
DataLoaderDTU::DataLoaderDTU(const std::string config_file):
m_is_running(false),
m_autostart(false),
m_idx_scene_to_read(0),
m_nr_resets(0),
m_rand_gen(new RandGenerator),
m_nr_scenes_read_so_far(0)
{
init_params(config_file);
if(m_autostart){
start();
}
// init_data_reading();
// start_reading_next_scene();
}
DataLoaderDTU::~DataLoaderDTU(){
m_is_running=false;
m_loader_thread.join();
}
void DataLoaderDTU::init_params(const std::string config_file){
//read all the parameters
std::string config_file_abs;
if (fs::path(config_file).is_relative()){
config_file_abs=(fs::path(PROJECT_SOURCE_DIR) / config_file).string();
}else{
config_file_abs=config_file;
}
Config cfg = configuru::parse_file(config_file_abs, CFG);
Config loader_config=cfg["loader_dtu"];
m_autostart=loader_config["autostart"];
m_read_with_bg_thread = loader_config["read_with_bg_thread"];
m_shuffle=loader_config["shuffle"];
m_subsample_factor=loader_config["subsample_factor"];
m_do_overfit=loader_config["do_overfit"];
// m_restrict_to_object= (std::string)loader_config["restrict_to_object"]; //makes it load clouds only from a specific object
m_dataset_path = (std::string)loader_config["dataset_path"]; //get the path where all the off files are
m_restrict_to_scan_idx= loader_config["restrict_to_scan_idx"];
m_load_as_shell= loader_config["load_as_shell"];
m_mode= (std::string)loader_config["mode"];
m_scene_scale_multiplier= loader_config["scene_scale_multiplier"];
}
void DataLoaderDTU::start(){
CHECK(m_scene_folders.empty()) << " The loader has already been started before. Make sure that you have m_autostart to false";
init_data_reading();
read_poses_and_intrinsics();
start_reading_next_scene();
}
void DataLoaderDTU::init_data_reading(){
if(!fs::is_directory(m_dataset_path)) {
LOG(FATAL) << "No directory " << m_dataset_path;
}
//load the corresponding file and get from there the scene that we need to read
fs::path scene_file_path= m_dataset_path/("new_"+m_mode+".lst");
std::ifstream scene_file(scene_file_path.string() );
if(!scene_file.is_open()){
LOG(FATAL) << "Could not open labels file " << scene_file_path;
}
// int nr_scenes_read=0;
for( std::string line; getline( scene_file, line ); ){
if(line.empty()){
continue;
}
std::string scan=trim_copy(line); //this scan is a string with format "scanNUMBER". We want just the number
int scan_idx=std::stoi(radu::utils::erase_substring(scan, "scan"));
VLOG(1) << "from scan line " << scan << "scan idx is " << scan_idx;
//if we want to load only one of the scans except for all of them
//push only one of the scenes
if(m_restrict_to_scan_idx>=0){
if(m_restrict_to_scan_idx==scan_idx){
m_scene_folders.push_back(m_dataset_path/scan);;
}
}else{
//push all scenes
m_scene_folders.push_back(m_dataset_path/scan);
}
// nr_scenes_read++;
}
VLOG(1) << "loaded nr of scenes " << m_scene_folders.size() << " for mode " << m_mode;
// shuffle the data if neccsary
if(m_shuffle){
unsigned seed = m_nr_resets;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_scene_folders), std::end(m_scene_folders), rng_0);
}
CHECK(m_scene_folders.size()!=0 ) << "We have read zero scene folders";
}
void DataLoaderDTU::start_reading_next_scene(){
CHECK(m_is_running==false) << "The loader thread is already running. Wait until the scene is finished loading before loading a new one. You can check this with finished_reading_scene()";
std::string scene_path;
if ( m_idx_scene_to_read< m_scene_folders.size()){
scene_path=m_scene_folders[m_idx_scene_to_read].string();
}
// VLOG(1) << " mode "<< m_mode << "m dof overfit" << m_do_overfit << " scnee size "<< m_scene_folders.size() << " scnee path is " << scene_path;
if(!m_do_overfit){
m_idx_scene_to_read++;
}
//start the reading
if (m_loader_thread.joinable()){
m_loader_thread.join(); //join the thread from the previous iteration of running
}
if(!scene_path.empty()){
if(m_read_with_bg_thread){
m_is_running=true;
m_loader_thread=std::thread(&DataLoaderDTU::read_scene, this, scene_path); //starts to read in another thread
}else{
read_scene(scene_path);
}
}
}
void DataLoaderDTU::read_scene(const std::string scene_path){
// VLOG(1) <<" read from path " << scene_path;
TIME_SCOPE("read_scene");
m_frames_for_scene.clear();
std::vector<fs::path> paths;
for (fs::directory_iterator itr( fs::path(scene_path)/"image"); itr!=fs::directory_iterator(); ++itr){
fs::path img_path= itr->path();
paths.push_back(img_path);
}
//shuffle the images from this scene
unsigned seed1 = m_nr_scenes_read_so_far;
auto rng_1 = std::default_random_engine(seed1);
if(m_mode=="train"){
std::shuffle(std::begin(paths), std::end(paths), rng_1);
}
//load all the scene for the chosen object
// for (fs::directory_iterator itr(scene_path); itr!=fs::directory_iterator(); ++itr){
for (size_t i=0; i<paths.size(); i++){
// fs::path img_path= itr->path();
fs::path img_path= paths[i];
//get only files that end in png
// VLOG(1) << "img_path" <<img_path;
if(img_path.filename().string().find("png")!= std::string::npos){
// VLOG(1) << "png img path " << img_path;
int img_idx=std::stoi( img_path.stem().string() );
// VLOG(1) << "img idx is " << img_idx;
Frame frame;
frame.frame_idx=img_idx;
//sets the paths and all the things necessary for the loading of images
frame.rgb_path=img_path.string();
frame.subsample_factor=m_subsample_factor;
//load the images if necessary or delay it for whne it's needed
frame.load_images=[this]( easy_pbr::Frame& frame ) -> void{ this->load_images_in_frame(frame); };
if (m_load_as_shell){
//set the function to load the images whenever it's neede
frame.is_shell=true;
}else{
frame.is_shell=false;
frame.load_images(frame);
}
// //read pose and camera params needs to be read from the camera.npz
// std::string pose_and_intrinsics_path=(fs::path(scene_path)/"cameras.npz").string();
// //read npz
// cnpy::npz_t npz_file = cnpy::npz_load( pose_and_intrinsics_path );
// cnpy::NpyArray projection_mat_array = npz_file["world_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// cnpy::NpyArray scale_array = npz_file["scale_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// // VLOG(1) << " projection_mat_array size" << projection_mat_array.shape.size();
// // VLOG(1) << " scale_array size" << scale_array.shape.size();
// // VLOG(1) << " projection_mat_array shape0 " << projection_mat_array.shape[0];
// // VLOG(1) << " projection_mat_array shape1 " << projection_mat_array.shape[1];
// // VLOG(1) << " scale_array shape0 " << scale_array.shape[0];
// // VLOG(1) << " scale_array shape1 " << scale_array.shape[1];
// //get the P matrix which containst both K and the pose
// Eigen::Affine3d P;
// double* projection_mat_data = projection_mat_array.data<double>();
// P.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(projection_mat_data);
// // VLOG(1) << "P is " << P.matrix();
// Eigen::Matrix<double,3,4> P_block = P.matrix().block<3,4>(0,0);
// // VLOG(1) << P_block;
// //get scale
// Eigen::Affine3d S;
// double* scale_array_data = scale_array.data<double>();
// S.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(scale_array_data);
// // VLOG(1) << "S is " << S.matrix();
// //Get the P_block into K and R and T as done in this line: K, R, t = cv2.decomposeProjectionMatrix(P)[:3]
// cv::Mat P_mat;
// cv::eigen2cv(P_block, P_mat);
// cv::Mat K_mat, R_mat, t_mat;
// cv::decomposeProjectionMatrix(P_mat, K_mat, R_mat, t_mat);
// // VLOG(1) << "K_Mat has size " << K_mat.rows << " " << K_mat.cols;
// // VLOG(1) << "T_Mat has size " << R_mat.rows << " " << R_mat.cols;
// // VLOG(1) << "t_Mat has size " << t_mat.rows << " " << t_mat.cols;
// Eigen::Matrix3d K, R;
// Eigen::Vector4d t_full;
// cv::cv2eigen(K_mat, K);
// cv::cv2eigen(R_mat, R);
// cv::cv2eigen(t_mat, t_full);
// K = K / K(2, 2);
// // VLOG(1) << "K is " << K;
// // VLOG(1) << "R is " << R;
// // VLOG(1) << "t_full is " << t_full;
// Eigen::Vector3d t;
// t.x()= t_full.x()/t_full.w();
// t.y()= t_full.y()/t_full.w();
// t.z()= t_full.z()/t_full.w();
// // VLOG(1) << "t is "<<t;
// // //get the pose into a mat
// Eigen::Affine3f tf_cam_world;
// tf_cam_world.linear() = R.transpose().cast<float>();
// tf_cam_world.translation() = t.cast<float>();
// // VLOG(1) << "tf_cam_world " << tf_cam_world.matrix();
// //get S
// // Eigen::Matrix3d S_block=
// Eigen::Vector3d norm_trans=S.translation();
// // VLOG(1) << "norm trans is " << norm_trans;
// Eigen::Vector3d norm_scale;
// norm_scale << S(0,0), S(1,1), S(2,2);
// // VLOG(1) << "norm scale " << norm_scale;
// tf_cam_world.translation()-=norm_trans.cast<float>();
// tf_cam_world.translation()=tf_cam_world.translation().array()/norm_scale.cast<float>().array();
// // VLOG(1) << "pose after the weird scaling " << tf_cam_world.matrix();
// //transform so the up is in the positive y for a right handed system
// // self._coord_trans_world = torch.tensor(
// // [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
// // dtype=torch.float32,
// // )
// // Eigen::Affine3f rot_world, rot_cam;
// // rot_world.matrix()<< 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1;
// // rot_cam.matrix()<< 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1;
// // tf_cam_world= rot_world*tf_cam_world*rot_cam;
// //atteptm2
// //rotate
// Eigen::Quaternionf q = Eigen::Quaternionf( Eigen::AngleAxis<float>( -60 * M_PI / 180.0 , Eigen::Vector3f::UnitX() ) );
// Eigen::Affine3f tf_rot;
// tf_rot.setIdentity();
// tf_rot.linear()=q.toRotationMatrix();
// // tf_world_cam=tf_rot*tf_world_cam;
// tf_cam_world=tf_rot*tf_cam_world;
// //flip
// Eigen::Affine3f tf_world_cam=tf_cam_world.inverse();
// Eigen::DiagonalMatrix<float, 4> diag;
// diag.diagonal() <<1, -1, 1, 1;
// tf_world_cam.matrix()=diag*tf_world_cam.matrix()*diag;
// //flip again the x
// diag.diagonal() <<-1, 1, 1, 1;
// tf_world_cam.matrix()=tf_world_cam.matrix()*diag;
// //flip locally
// tf_cam_world=tf_world_cam.inverse();
// frame.K=K.cast<float>();
// frame.tf_cam_world=tf_cam_world.inverse();
///////////////////////////////////////just get it from the hashmap
frame.K = m_scene2frame_idx2K[scene_path][img_idx];
frame.tf_cam_world = m_scene2frame_idx2tf_cam_world[scene_path][img_idx];
if(m_subsample_factor>1){
frame.K/=m_subsample_factor;
frame.K(2,2)=1.0;
}
// if (img_idx==0){
// exit(1);
// }
// CHECK(arr.shape.size()==2) << "arr should have 2 dimensions and it has " << arr.shape.size();
// CHECK(arr.shape[1]==4) << "arr second dimension should be 4 (x,y,z,label) but it is " << arr.shape[1];
// //read intensity
// fs::path absolute_path=fs::absolute(npz_filename).parent_path();
// fs::path file_name=npz_filename.stem();
// // fs::path npz_intensity_path=absolute_path/(file_name.string()+"_i"+".npz");
// // cnpy::npz_t npz_intensity_file = cnpy::npz_load(npz_intensity_path.string());
// // cnpy::NpyArray arr_intensity = npz_intensity_file["arr_0"]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// // CHECK(arr_intensity.shape.size()==1) << "arr should have 1 dimensions and it has " << arr.shape.size();
// //copy into EigenMatrix
// int nr_points=arr.shape[0];
// MeshSharedPtr cloud=Mesh::create();
// cloud->V.resize(nr_points,3);
// cloud->V.setZero();
// cloud->L_gt.resize(nr_points,1);
// cloud->L_gt.setZero();
// // cloud->I.resize(nr_points,1);
// // cloud->I.setZero();
// double* arr_data = arr.data<double>();
// // float* arr_intensity_data = arr_intensity.data<float>(); //the intensities are as floats while xyz is double. You can check by reading the npz in python
// for(int i=0; i<nr_points*4; i=i+4){
// int row_insert=i/4;
// double x=arr_data[i];
// double y=arr_data[i+1];
// double z=arr_data[i+2];
// int label=arr_data[i+3];
// // double intensity=arr_intensity_data[row_insert];
// cloud->V.row(row_insert) << x,y,z;
// cloud->L_gt.row(row_insert) << label;
// // cloud->I.row(row_insert) << intensity;
// // VLOG(1) << "xyz is " << x << " " << y << " " << z << " " << label;
// // exit(1);
// }
//rescale things if necessary
if(m_scene_scale_multiplier>0.0){
Eigen::Affine3f tf_world_cam_rescaled = frame.tf_cam_world.inverse();
tf_world_cam_rescaled.translation()*=m_scene_scale_multiplier;
frame.tf_cam_world=tf_world_cam_rescaled.inverse();
}
m_frames_for_scene.push_back(frame);
// if(m_nr_imgs_to_read>0 && m_frames_for_scene.size()>=m_nr_imgs_to_read){
// break; //we finished reading how many images we need so we stop the thread
// }
}
}
// VLOG(1) << "loaded a scene with nr of frames " << m_frames_for_scene.size();
CHECK(m_frames_for_scene.size()!=0) << "Clouldn't load any images for this scene in path " << scene_path;
m_nr_scenes_read_so_far++;
//shuffle the images from this scene
unsigned seed = m_nr_scenes_read_so_far;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_frames_for_scene), std::end(m_frames_for_scene), rng_0);
m_is_running=false;
}
void DataLoaderDTU::load_images_in_frame(easy_pbr::Frame& frame){
frame.is_shell=false;
// VLOG(1) << "load image from" << frame.rgb_path ;
cv::Mat rgb_8u=cv::imread(frame.rgb_path );
if(frame.subsample_factor>1){
cv::Mat resized;
cv::resize(rgb_8u, resized, cv::Size(), 1.0/frame.subsample_factor, 1.0/frame.subsample_factor, cv::INTER_AREA);
rgb_8u=resized;
}
frame.rgb_8u=rgb_8u;
// VLOG(1) << "img type is " << radu::utils::type2string( frame.rgb_8u.type() );
frame.rgb_8u.convertTo(frame.rgb_32f, CV_32FC3, 1.0/255.0);
frame.width=frame.rgb_32f.cols;
frame.height=frame.rgb_32f.rows;
// VLOG(1) << " frame width ad height " << frame.width << " " << frame.height;
}
void DataLoaderDTU::read_poses_and_intrinsics(){
// std::unordered_map<std::string, std::unordered_map<int, Eigen::Affine3f> > m_scene2frame_idx2tf_cam_world;
// std::unordered_map<std::string, std::unordered_map<int, Eigen::Matrix3f> > m_scene2frame_idx2K;
for(size_t scene_idx; scene_idx<m_scene_folders.size(); scene_idx++){
std::string scene_path=m_scene_folders[scene_idx].string();
VLOG(1) << "reading poses and intrinsics for scene " << fs::path(scene_path).stem();
std::vector<fs::path> paths;
for (fs::directory_iterator itr( fs::path(scene_path)/"image"); itr!=fs::directory_iterator(); ++itr){
fs::path img_path= itr->path();
paths.push_back(img_path);
}
//read pose and camera params needs to be read from the camera.npz
std::string pose_and_intrinsics_path=(fs::path(scene_path)/"cameras.npz").string();
cnpy::npz_t npz_file = cnpy::npz_load( pose_and_intrinsics_path );
//load all the scene for the chosen object
// for (fs::directory_iterator itr(scene_path); itr!=fs::directory_iterator(); ++itr){
for (size_t i=0; i<paths.size(); i++){
// fs::path img_path= itr->path();
fs::path img_path= paths[i];
//get only files that end in png
// VLOG(1) << "img_path" <<img_path;
if(img_path.filename().string().find("png")!= std::string::npos){
// VLOG(1) << "png img path " << img_path;
int img_idx=std::stoi( img_path.stem().string() );
// VLOG(1) << "img idx is " << img_idx;
//read npz
cnpy::NpyArray projection_mat_array = npz_file["world_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
cnpy::NpyArray scale_array = npz_file["scale_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// VLOG(1) << " projection_mat_array size" << projection_mat_array.shape.size();
// VLOG(1) << " scale_array size" << scale_array.shape.size();
// VLOG(1) << " projection_mat_array shape0 " << projection_mat_array.shape[0];
// VLOG(1) << " projection_mat_array shape1 " << projection_mat_array.shape[1];
// VLOG(1) << " scale_array shape0 " << scale_array.shape[0];
// VLOG(1) << " scale_array shape1 " << scale_array.shape[1];
//get the P matrix which containst both K and the pose
Eigen::Affine3d P;
double* projection_mat_data = projection_mat_array.data<double>();
P.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(projection_mat_data);
// VLOG(1) << "P is " << P.matrix();
Eigen::Matrix<double,3,4> P_block = P.matrix().block<3,4>(0,0);
// VLOG(1) << P_block;
//get scale
Eigen::Affine3d S;
double* scale_array_data = scale_array.data<double>();
S.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(scale_array_data);
// VLOG(1) << "S is " << S.matrix();
//Get the P_block into K and R and T as done in this line: K, R, t = cv2.decomposeProjectionMatrix(P)[:3]
cv::Mat P_mat;
cv::eigen2cv(P_block, P_mat);
cv::Mat K_mat, R_mat, t_mat;
cv::decomposeProjectionMatrix(P_mat, K_mat, R_mat, t_mat);
// VLOG(1) << "K_Mat has size " << K_mat.rows << " " << K_mat.cols;
// VLOG(1) << "T_Mat has size " << R_mat.rows << " " << R_mat.cols;
// VLOG(1) << "t_Mat has size " << t_mat.rows << " " << t_mat.cols;
Eigen::Matrix3d K, R;
Eigen::Vector4d t_full;
cv::cv2eigen(K_mat, K);
cv::cv2eigen(R_mat, R);
cv::cv2eigen(t_mat, t_full);
K = K / K(2, 2);
// VLOG(1) << "K is " << K;
// VLOG(1) << "R is " << R;
// VLOG(1) << "t_full is " << t_full;
Eigen::Vector3d t;
t.x()= t_full.x()/t_full.w();
t.y()= t_full.y()/t_full.w();
t.z()= t_full.z()/t_full.w();
// VLOG(1) << "t is "<<t;
// //get the pose into a mat
Eigen::Affine3f tf_world_cam;
tf_world_cam.linear() = R.transpose().cast<float>();
tf_world_cam.translation() = t.cast<float>();
// VLOG(1) << "tf_world_cam " << tf_world_cam.matrix();
//get S
// Eigen::Matrix3d S_block=
Eigen::Vector3d norm_trans=S.translation();
// VLOG(1) << "norm trans is " << norm_trans;
Eigen::Vector3d norm_scale;
norm_scale << S(0,0), S(1,1), S(2,2);
// VLOG(1) << "norm scale " << norm_scale;
tf_world_cam.translation()-=norm_trans.cast<float>();
tf_world_cam.translation()=tf_world_cam.translation().array()/norm_scale.cast<float>().array();
// VLOG(1) << "pose after the weird scaling " << tf_world_cam.matrix();
//atteptm2
//rotate
Eigen::Quaternionf q = Eigen::Quaternionf( Eigen::AngleAxis<float>( -60 * M_PI / 180.0 , Eigen::Vector3f::UnitX() ) );
Eigen::Affine3f tf_rot;
tf_rot.setIdentity();
tf_rot.linear()=q.toRotationMatrix();
// tf_world_cam=tf_rot*tf_world_cam;
tf_world_cam=tf_rot*tf_world_cam;
//flip
Eigen::Affine3f tf_cam_world=tf_world_cam.inverse();
Eigen::DiagonalMatrix<float, 4> diag;
diag.diagonal() <<1, -1, 1, 1;
tf_cam_world.matrix()=diag*tf_cam_world.matrix()*diag;
//flip again the x
diag.diagonal() <<-1, 1, 1, 1;
tf_cam_world.matrix()=tf_cam_world.matrix()*diag;
//flip locally
// tf_world_cam=tf_cam_world.inverse();
//add it to the hashmaps
m_scene2frame_idx2tf_cam_world[scene_path][img_idx]=tf_cam_world;
m_scene2frame_idx2K[scene_path][img_idx]=K.cast<float>();
}
}
}
}
bool DataLoaderDTU::finished_reading_scene(){
return !m_is_running;
}
bool DataLoaderDTU::has_data(){
return finished_reading_scene();
}
Frame DataLoaderDTU::get_random_frame(){
int random_idx=m_rand_gen->rand_int(0, m_frames_for_scene.size()-1);
// int random_idx=0;
return m_frames_for_scene[random_idx];
}
Frame DataLoaderDTU::get_frame_at_idx( const int idx){
CHECK(idx<m_frames_for_scene.size()) << "idx is out of bounds. It is " << idx << " while m_frames has size " << m_frames_for_scene.size();
Frame frame= m_frames_for_scene[idx];
return frame;
}
bool DataLoaderDTU::is_finished(){
//check if this loader has loaded everything
if(m_idx_scene_to_read<m_scene_folders.size()){
return false; //there is still more files to read
}
return true; //there is nothing more to read and nothing more in the buffer so we are finished
}
void DataLoaderDTU::reset(){
m_nr_resets++;
//reshuffle for the next epoch
if(m_shuffle){
unsigned seed = m_nr_resets;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_scene_folders), std::end(m_scene_folders), rng_0);
}
m_idx_scene_to_read=0;
}
int DataLoaderDTU::nr_samples(){
return m_frames_for_scene.size();
}
int DataLoaderDTU::nr_scenes(){
return m_scene_folders.size();
}
void DataLoaderDTU::set_restrict_to_scan_idx(const int scan_idx){
m_restrict_to_scan_idx=scan_idx;
}
void DataLoaderDTU::set_mode_train(){
m_mode="train";
}
void DataLoaderDTU::set_mode_test(){
m_mode="test";
}
void DataLoaderDTU::set_mode_validation(){
m_mode="val";
}
std::unordered_map<std::string, std::string> DataLoaderDTU::create_mapping_classnr2classname(){
//from https://github.com/NVIDIAGameWorks/kaolin/blob/master/kaolin/datasets/shapenet.py
std::unordered_map<std::string, std::string> classnr2classname;
classnr2classname["04379243"]="table";
classnr2classname["03211117"]="monitor";
classnr2classname["04401088"]="phone";
classnr2classname["04530566"]="watercraft";
classnr2classname["03001627"]="chair";
classnr2classname["03636649"]="lamp";
classnr2classname["03691459"]="speaker";
classnr2classname["02828884"]="bench";
classnr2classname["02691156"]="plane";
classnr2classname["02808440"]="bathtub";
classnr2classname["02871439"]="bookcase";
classnr2classname["02773838"]="bag";
classnr2classname["02801938"]="basket";
classnr2classname["02880940"]="bowl";
classnr2classname["02924116"]="bus";
classnr2classname["02933112"]="cabinet";
classnr2classname["02942699"]="camera";
classnr2classname["02958343"]="car";
classnr2classname["03207941"]="dishwasher";
classnr2classname["03337140"]="file";
classnr2classname["03624134"]="knife";
classnr2classname["03642806"]="laptop";
classnr2classname["03710193"]="mailbox";
classnr2classname["03761084"]="microwave";
classnr2classname["03928116"]="piano";
classnr2classname["03938244"]="pillow";
classnr2classname["03948459"]="pistol";
classnr2classname["04004475"]="printer";
classnr2classname["04099429"]="rocket";
classnr2classname["04256520"]="sofa";
classnr2classname["04554684"]="washer";
classnr2classname["04090263"]="rifle";
classnr2classname["02946921"]="can";
return classnr2classname;
}
Eigen::Affine3f DataLoaderDTU::process_extrinsics_line(const std::string line){
// //remove any "[" or "]" in the line
// std::string line_processed=line;
// line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), '['), line_processed.end());
// line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), ']'), line_processed.end());
// // std::vector<std::string> tokens = radu::utils::split(line_processed, " ");
// std::vector<std::string> tokens = radu::utils::split(line_processed, ",");
// float azimuth = std::stof(tokens[0]);
// float elevation = std::stof(tokens[1]);
// float distance = std::stof(tokens[3]);
// VLOG(1) << "line is " << line;
// VLOG(1) << "azimuth elev and dist " << azimuth << " " << elevation << " " << distance;
// Eigen::Affine3f tf;
// //from compute_camera_params() in https://github.com/NVIDIAGameWorks/kaolin/blob/a76a004ada95280c6a0a821678cf1b886bcb3625/kaolin/mathutils/geometry/transformations.py
// float theta = radu::utils::degrees2radians(azimuth);
// float phi = radu::utils::degrees2radians(elevation);
// float camY = distance * std::sin(phi);
// float temp = distance * std::cos(phi);
// float camX = temp * std::cos(theta);
// float camZ = temp * std::sin(theta);
// // cam_pos = np.array([camX, camY, camZ])
// Eigen::Vector3f t;
// t << camX,camY,camZ;
// Eigen::Vector3f axisZ = t;
// Eigen::Vector3f axisY = Eigen::Vector3f::UnitY();
// Eigen::Vector3f axisX = axisY.cross(axisZ);
// axisY = axisZ.cross(axisX);
// // cam_mat = np.array([axisX, axisY, axisZ])
// Eigen::Matrix3f R;
// R.col(0)=axisX;
// R.col(1)=axisY;
// R.col(2)=-axisZ;
// // l2 = np.atleast_1d(np.linalg.norm(cam_mat, 2, 1))
// // l2[l2 == 0] = 1
// // cam_mat = cam_mat / np.expand_dims(l2, 1)
// Eigen::Vector3f norm_vec=R.colwise().norm();
// VLOG(1) << "norm is " << norm_vec;
// // R=R.colwise()/norm;
// for (int i=0; i<3; i++){
// float norm=norm_vec(i);
// for (int j=0; j<3; j++){
// // R(i,j) = R(i,j)/norm;
// R(j,i) = R(j,i)/norm;
// }
// }
// norm_vec=R.colwise().norm();
// VLOG(1) << "norm is " << norm_vec;
// tf.translation() = t;
// tf.linear() = R;
// //just to make sure it's orthogonal
// // Eigen::AngleAxisf aa(R); // RotationMatrix to AxisAngle
// // R = aa.toRotationMatrix(); // AxisAngle to RotationMatrix
// // tf.linear() = R;
// Eigen::Affine3f tf_ret=tf.inverse();
// // Eigen::Affine3f tf_ret=tf;
//attempt 2 by looking at https://github.com/Xharlie/ShapenetRender_more_variation/blob/master/cam_read.py
// F_MM = 35. # Focal length
// SENSOR_SIZE_MM = 32.
// PIXEL_ASPECT_RATIO = 1. # pixel_aspect_x / pixel_aspect_y
// RESOLUTION_PCT = 100.
// SKEW = 0.
// CAM_MAX_DIST = 1.75
// CAM_ROT = np.asarray([[1.910685676922942e-15, 4.371138828673793e-08, 1.0],
// [1.0, -4.371138828673793e-08, -0.0],
// [4.371138828673793e-08, 1.0, -4.371138828673793e-08]])
float cam_max_dist=1.75;
Eigen::Matrix3f cam_rot;
cam_rot <<1.910685676922942e-15, 4.371138828673793e-08, 1.0,
1.0, -4.371138828673793e-08, -0.0,
4.371138828673793e-08, 1.0, -4.371138828673793e-08;
std::string line_processed=line;
line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), '['), line_processed.end());
line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), ']'), line_processed.end());
// std::vector<std::string> tokens = radu::utils::split(line_processed, " ");
std::vector<std::string> tokens = radu::utils::split(line_processed, ",");
float az = std::stof(tokens[0]);
float el = std::stof(tokens[1]);
float distance_ratio = std::stof(tokens[3]);
// float ox = std::stof(tokens[7]);
// float oy = std::stof(tokens[8]);
// float oz = std::stof(tokens[9]);
// # Calculate rotation and translation matrices.
// # Step 1: World coordinate to object coordinate.
float sa = std::sin(radu::utils::degrees2radians(-az));
float ca = std::cos(radu::utils::degrees2radians(-az));
float se = std::sin(radu::utils::degrees2radians(-el));
float ce = std::cos(radu::utils::degrees2radians(-el));
// R_world2obj = np.transpose(np.matrix(((ca * ce, -sa, ca * se),
// (sa * ce, ca, sa * se),
// (-se, 0, ce))))
Eigen::Matrix3f R_world2obj;
R_world2obj <<ca * ce, -sa, ca * se,
sa * ce, ca, sa * se,
-se, 0, ce;
Eigen::Matrix3f trans;
trans=R_world2obj.transpose();
R_world2obj=trans;
// # Step 2: Object coordinate to camera coordinate.
// R_obj2cam = np.transpose(np.matrix(CAM_ROT))
Eigen::Matrix3f R_obj2cam=cam_rot.transpose();
Eigen::Matrix3f R_world2cam = R_obj2cam * R_world2obj;
// cam_location = np.transpose(np.matrix((distance_ratio * CAM_MAX_DIST,
// 0,
// 0)))
Eigen::Vector3f cam_location;
cam_location << distance_ratio * cam_max_dist, 0, 0;
// # print('distance', distance_ratio * CAM_MAX_DIST)
Eigen::Vector3f T_world2cam = -1 * R_obj2cam * cam_location;
// // # Step 3: Fix blender camera's y and z axis direction.
// R_camfix = np.matrix(((1, 0, 0), (0, -1, 0), (0, 0, -1)))
Eigen::Matrix3f R_camfix;
R_camfix <<1, 0, 0,
0,1,0,
0,0,-1;
R_world2cam = R_camfix * R_world2cam;
T_world2cam = R_camfix * T_world2cam;
Eigen::Affine3f tf_ret;
tf_ret.linear()=R_world2cam;
tf_ret.translation()=T_world2cam;
//rotate 90 degrees
Eigen::Affine3f tf_worldGL_worldROS;
tf_worldGL_worldROS.setIdentity();
Eigen::Matrix3f worldGL_worldROS_rot;
worldGL_worldROS_rot = Eigen::AngleAxisf(-0.5*M_PI, Eigen::Vector3f::UnitX());
tf_worldGL_worldROS.matrix().block<3,3>(0,0)=worldGL_worldROS_rot;
Eigen::Affine3f tf_worldROS_worldGL=tf_worldGL_worldROS.inverse();
Eigen::Affine3f tf_ret_cor=tf_worldGL_worldROS*tf_ret.inverse();
tf_ret=tf_ret_cor.inverse();
return tf_ret;
}
| 35.559662 | 190 | 0.586607 | Eruvae |
595388775ccc89d35b4d11c0e38fa5a17a088c38 | 314 | cpp | C++ | esphome/components/copy/button/copy_button.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/copy/button/copy_button.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/copy/button/copy_button.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #include "copy_button.h"
#include "esphome/core/log.h"
namespace esphome {
namespace copy {
static const char *const TAG = "copy.button";
void CopyButton::dump_config() { LOG_BUTTON("", "Copy Button", this); }
void CopyButton::press_action() { source_->press(); }
} // namespace copy
} // namespace esphome
| 20.933333 | 71 | 0.697452 | OttoWinter |
595508697faace165fb9f47e9acd6df3f26d71c5 | 13,262 | cpp | C++ | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | 2 | 2015-11-05T01:16:28.000Z | 2021-12-20T04:30:08.000Z | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | null | null | null | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | null | null | null | #include "all_defines.hpp"
#include "types.hpp"
#include "processes.hpp"
#include "executors.hpp"
#include "history.hpp"
#include <iostream>
/*-----------------------------------------------------------------------------
Cons
-----------------------------------------------------------------------------*/
Object::ref Cons::len() {
int l = 1;
Object::ref next = cdr();
Object::ref p2 = next;
while (maybe_type<Cons>(next)) {
next = ::cdr(next);
p2 = ::cdr(::cdr(p2));
if(next == p2 && next != Object::nil()) return Object::to_ref(0); // fail on infinite lists
l++;
}
// !! there could be an overflow, but we don't expect to have lists so long
return Object::to_ref(l);
}
/*-----------------------------------------------------------------------------
Closure
-----------------------------------------------------------------------------*/
Closure* Closure::NewClosure(Heap & h, size_t n) {
Closure *c = h.create_variadic<Closure>(n);
c->body = Object::nil();
c->nonreusable = true;
c->kontinuation.reset();
return c;
}
Closure* Closure::NewKClosure(Heap & h, size_t n) {
Closure *c = h.lifo_create_variadic<Closure>(n);
c->body = Object::nil();
c->nonreusable = false;
c->kontinuation.reset(new History::InnerRing);
return c;
}
/*-----------------------------------------------------------------------------
HlTable
-----------------------------------------------------------------------------*/
#include"hashes.hpp"
HashingClass::HashingClass(void)
: a(0x9e3779b9), b(0x9e3779b9), c(0) { }
void HashingClass::enhash(size_t x) {
c = c ^ (uint32_t)x;
mix(a, b, c);
}
/*is-compatible hashing*/
size_t hash_is(Object::ref o) {
/*if it's not a heap object, hash directly*/
if(!is_a<Generic*>(o)) {
/*32-bit, even on 64-bit systems; shouldn't be
a problem in practice, since we don't expect hash
tables to have more than 4,294,967,296 entries.
At least not *yet*.
*/
return (size_t) int_hash((uint32_t) o.dat);
} else {
HashingClass hc;
as_a<Generic*>(o)->enhash(&hc);
return (size_t) hc.c;
}
}
inline Object::ref* HlTable::linear_lookup(Object::ref k) const {
HlArray& A = *known_type<HlArray>(impl);
for(size_t i = 0; i < pairs; ++i) {
if(::is(k, A[i * 2])) {
return &A[i * 2 + 1];
}
}
return NULL;
}
inline Object::ref* HlTable::arrayed_lookup(Object::ref k) const {
if(!is_a<int>(k)) return NULL;
HlArray& A = *known_type<HlArray>(impl);
int x = as_a<int>(k);
if(x < 0 || x >= A.size()) return NULL;
return &A[x];
}
inline Object::ref* HlTable::hashed_lookup(Object::ref k) const {
HlArray& A = *known_type<HlArray>(impl);
size_t I = hash_is(k) % A.size();
size_t J = I;
Object::ref key;
loop:
if(!A[I]) return NULL;
if(::is(k, car(A[I]))) {
return &known_type<Cons>(A[I])->cdr();
}
++I; if(I >= A.size()) I = 0;
if(J == I) return NULL; //wrapped already
goto loop;
}
Object::ref* HlTable::location_lookup(Object::ref k) const {
if(tbtype == hl_table_empty) return NULL;
switch(tbtype) {
case hl_table_linear:
return linear_lookup(k);
break;
case hl_table_arrayed:
return arrayed_lookup(k);
break;
case hl_table_hashed:
return hashed_lookup(k);
break;
}
}
/*Inserts a key-value cons pair to the correct hashed
location in the specified array.
*/
static inline void add_kv_to_array(HlArray& A, Cons& kv, size_t sz) {
size_t I = hash_is(kv.car()) % sz;
find_loop:
if(!A[I]) {
A[I] = Object::to_ref(&kv);
return;
}
++I; if(I >= sz) I = 0;
goto find_loop;
}
void HlTable::insert(Heap& hp, ProcessStack& stack) {
HlTable& T = *known_type<HlTable>(stack.top(3));
if(T.tbtype == hl_table_empty) {
/*either we become an hl_table_arrayed,
or a hl_table_linear
*/
Object::ref k = stack.top(1);
/*maybe we become arrayed*/
if(is_a<int>(k)) {
int I = as_a<int>(k);
if(I >= 0 && I < ARRAYED_LEVEL) {
HlArray& A = *hp.create_variadic<HlArray>(ARRAYED_LEVEL);
A[I] = stack.top(2);
/*need to re-read, we might have gotten GC'ed*/
HlTable& T = *known_type<HlTable>(stack.top(3));
T.impl = Object::to_ref(&A);
T.tbtype = hl_table_arrayed;
goto clean_up;
}
}
/*nah, we have to become linear*/
HlArray& A = *hp.create_variadic<HlArray>(LINEAR_LEVEL * 2);
A[0] = stack.top(1); /*key*/
A[1] = stack.top(2); /*value*/
/*need to re-read, we might have gotten GC'ed*/
HlTable& T = *known_type<HlTable>(stack.top(3));
T.impl = Object::to_ref(&A);
T.tbtype = hl_table_linear;
T.pairs = 1;
goto clean_up;
} else {
/*if the key already exists, we just have
to replace its value
*/
Object::ref* op = T.location_lookup(stack.top(1));
if(op) {
*op = stack.top(2);
goto clean_up;
}
/*not a value replacement. Well, if the given value is
nil, we don't actually insert anything
Note that this checking needs to be done after we
determine we're not replacing a value
*/
if(!stack.top(2)) goto clean_up;
/*No, we have to insert it. First figure out what to do*/
switch(T.tbtype) {
case hl_table_arrayed:
/*Can we still insert into the array?*/
if(is_a<int>(stack.top(1))) {
int k = as_a<int>(stack.top(1));
if(k >= 0) {
HlArray& A = *known_type<HlArray>(
T.impl
);
size_t sz = A.size();
if(k < sz) {
A[k] = stack.top(2);
goto clean_up;
} else if(k < sz + ARRAYED_LEVEL) {
/*copy the implementation into
a new array.
*/
HlArray& NA =
*hp.create_variadic
<HlArray>(
sz + ARRAYED_LEVEL
);
/*re-read*/
HlTable& T =
*known_type<HlTable>(
stack.top(3)
);
HlArray& OA =
*known_type<HlArray>(
T.impl
);
for(size_t i = 0; i < sz; ++i)
{
NA[i] = OA[i];
}
NA[k] = stack.top(2);
T.impl = Object::to_ref(&NA);
goto clean_up;
}
}
}
/*failed to insert... transform into hashed*/
goto transform_arrayed_to_hashed;
break;
case hl_table_linear:
/*check if there's still space*/
if(T.pairs < LINEAR_LEVEL) {
int i = T.pairs;
HlArray& A = *known_type<HlArray>(T.impl);
A[i * 2] = stack.top(1); /*key*/
A[i * 2 + 1] = stack.top(2); /*value*/
T.pairs++;
goto clean_up;
}
/*failed to insert... transform to hashed*/
goto transform_linear_to_hashed;
case hl_table_hashed:
/*first, determine if we have to re-hash*/
HlArray& A = *known_type<HlArray>(T.impl);
if(T.pairs < A.size() / 2) {
/*no re-hash, just insert*/
/*first create Cons cell for k-v pair*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
/*re-read*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
add_kv_to_array(A, *cp, A.size());
++T.pairs;
goto clean_up;
}
goto rehash;
}
}
transform_arrayed_to_hashed: {
/*decide what the new size must be*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
size_t old_size = A.size();
size_t new_size = 4 * old_size;
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create a new array*/
HlArray* ap = hp.create_variadic<HlArray>(new_size);
stack.top(2) = Object::to_ref(ap);
/*enhash*/
T.pairs = 0;
for(size_t i = 0; i < old_size; ++i) {
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
if(A[i]) {
Cons& newkv = *hp.create<Cons>();
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
newkv.car() = Object::to_ref((int) i);
newkv.cdr() = A[i];
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
newkv,
new_size
);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
*known_type<Cons>(stack.top(1)),
new_size
);
{HlTable& T = *known_type<HlTable>(stack.top(3));
++T.pairs;
/*replace implementation*/
T.impl = stack.top(2);
T.tbtype = hl_table_hashed;
}
/*clean up stack*/
stack.top(3) = cdr(stack.top(1));
stack.pop(2);
return;
}
transform_linear_to_hashed: {
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create a new array*/
HlArray* ap = hp.create_variadic<HlArray>(
4 * LINEAR_LEVEL
);
stack.top(2) = Object::to_ref(ap);
/*enhash*/
known_type<HlTable>(stack.top(3))->pairs = 0;
for(size_t i = 0; i < LINEAR_LEVEL; ++i) {
/*have to read it in each time, because
of GC clobbering pointers
NOTE: can probably be rearranged somewhat
*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
/*if value is non-nil, create Cons pair and insert*/
if(A[i * 2 + 1]) {
Cons& newkv = *hp.create<Cons>();
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
newkv.car() = A[i * 2];
newkv.cdr() = A[i * 2 + 1];
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
newkv,
4 * LINEAR_LEVEL
);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
*known_type<Cons>(stack.top(1)),
4 * LINEAR_LEVEL
);
HlTable& T = *known_type<HlTable>(stack.top(3));
++T.pairs;
/*replace implementation*/
T.impl = stack.top(2);
T.tbtype = hl_table_hashed;
/*clean up stack*/
stack.top(3) = cdr(stack.top(1));
stack.pop(2);
return;
}
rehash: {
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create the new array*/
HlArray* NAp;
{
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
NAp = hp.create_variadic<HlArray>(A.size() * 2);
}
HlArray& NA = *NAp;
/*re-read*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
Cons& new_kv = *known_type<Cons>(stack.top(1));
/*rehash*/
size_t sz = NA.size();
T.pairs = 0;
for(size_t i = 0; i < A.size(); ++i) {
if(A[i] && cdr(A[i])) {
add_kv_to_array(NA, *known_type<Cons>(A[i]), sz);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(NA, new_kv, sz);
++T.pairs;
/*replace implementation*/
T.impl = Object::to_ref(&NA);
goto clean_up;
}
clean_up:
stack.top(3) = stack.top(2);
stack.pop(2);
return;
}
/*returns the keys of a table in a list*/
void HlTable::keys(Heap& hp, ProcessStack& stack) {
/*determine the table type*/
HlTableType type;
{HlTable& t = *expect_type<HlTable>(stack.top());
type = t.tbtype;
if(type == hl_table_empty) {
stack.top() = Object::nil();
return;
}
}
/*determine the size of the HlArray implementation*/
size_t sz;
{HlTable& t = *known_type<HlTable>(stack.top());
HlArray& a = *known_type<HlArray>(t.impl);
sz = a.size();
}
/*create a temporary Cons pair
car = table
cdr = list of keys being built
why? because we want to avoid having to
push a new item on the stack. in the
future, JITted code might prefer to have
a statically-located stack; obviously a
statically-located stack would also be
statically-sized.
*/
{Cons& c = *hp.create<Cons>();
c.car() = stack.top();
stack.top() = Object::to_ref<Generic*>(&c);
}
switch(type){
case hl_table_arrayed:
for(size_t i = 0; i < sz; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i]) {
Cons& c = *hp.create<Cons>();
c.car() = Object::to_ref<int>(i);
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
}
}
stack.top() = cdr(stack.top());
return;
case hl_table_linear:
{/*have to look up pairs*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
size_t pairs = t.pairs;
for(size_t i = 0; i < pairs; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i * 2 + 1]) {
/*add a list element to the
list of keys
*/
Cons& c = *hp.create<Cons>();
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
/*re-read*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(
t.impl
);
c.car() = a[i * 2];
}
}
}
stack.top() = cdr(stack.top());
return;
case hl_table_hashed:
for(size_t i = 0; i < sz; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i] && cdr(a[i])) {
/*add a list element to the list of keys*/
Cons& c = *hp.create<Cons>();
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
/*re-read*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*add the key to list of keys*/
c.car() = car(a[i]);
}
}
stack.top() = cdr(stack.top());
return;
}
}
| 25.552987 | 95 | 0.583622 | AmkG |
5956bdc5c76cb1fc482645443a7209f133144427 | 693 | cpp | C++ | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 1 | 2018-10-06T15:33:06.000Z | 2018-10-06T15:33:06.000Z | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 7 | 2019-02-24T08:50:30.000Z | 2019-03-02T15:41:01.000Z | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 2 | 2019-02-22T21:10:00.000Z | 2019-02-24T08:01:33.000Z | #include "Scene.h"
namespace alpha {
Scene::Scene() {
}
void Scene::AddGameObject(GameObject &object) {
m_gameObjects.push_back(&object);
}
void Scene::UpdateGameObjects(float dt) {
for (size_t i = 0; i < m_gameObjects.size(); i++) {
if (m_gameObjects[i])
m_gameObjects[i]->Update(dt);
else
m_gameObjectRemovalQueue.push_back(m_gameObjects[i]);
}
while (m_gameObjectRemovalQueue.size() > 0) {
m_gameObjects.erase(std::find(m_gameObjects.begin(), m_gameObjects.end(), m_gameObjectRemovalQueue[0]));
m_gameObjectRemovalQueue.erase(m_gameObjectRemovalQueue.begin());
}
}
void Scene::_SetGame(Game *game) {
MainGame = game;
}
Scene::~Scene() {
}
} | 21 | 107 | 0.689755 | JFrap |
59575fd2a8635745d27714e9aba89c172ddba767 | 3,901 | cpp | C++ | demo/dictdump/emtdictdump/dictdump.cpp | anyex-net/openctp | d2eae215ce63e546874247f8cc011161b888594a | [
"BSD-3-Clause"
] | 1 | 2022-03-30T09:17:33.000Z | 2022-03-30T09:17:33.000Z | demo/dictdump/emtdictdump/dictdump.cpp | Ivan087/openctp | d849c92b953ad0ecfe0527419e9c56f6405c8b64 | [
"BSD-3-Clause"
] | null | null | null | demo/dictdump/emtdictdump/dictdump.cpp | Ivan087/openctp | d849c92b953ad0ecfe0527419e9c56f6405c8b64 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <locale>
#include <codecvt>
#include "EMT/emt_quote_api.h"
#pragma comment(lib,"EMT/emt_quote_api.lib")
#define EMT_CLIENT_ID 82
using namespace EMT::API;
class CApplication : public QuoteSpi
{
public:
CApplication(std::string host, std::string user, std::string password) :
m_host(host),
m_user(user),
m_password(password)
{
m_pUserApi = QuoteApi::CreateQuoteApi(EMT_CLIENT_ID, ".", EMT_LOG_LEVEL_WARNING);
m_pUserApi->RegisterSpi(this);
m_pUserApi->SetHeartBeatInterval(16);//设定交易服务器超时时间,单位为秒,此为1.1.16新增接口
}
~CApplication()
{
}
void OnQueryAllTickers(EMTQuoteStaticInfo* ticker_info, EMTRspInfoStruct* error_info, bool is_last)
{
if (error_info && error_info->error_id != 0) {
OnError(error_info);
return;
}
if (ticker_info)
m_vInstruments.push_back(*ticker_info);
if (ticker_info->exchange_id == EMT_EXCHANGE_SH && is_last) {
// 上海查完查深圳
m_pUserApi->QueryAllTickers(EMT_EXCHANGE_SZ);
}
if (ticker_info->exchange_id == EMT_EXCHANGE_SZ && is_last) {
// 深圳查完dump到文件
printf("%u Instruments received.\n", (unsigned int)m_vInstruments.size());
std::ofstream outfile;
outfile.open("dict.csv", std::ios::out | std::ios::trunc);
for (auto iter = m_vInstruments.begin(); iter != m_vInstruments.end(); iter++) {
switch (iter->ticker_type) {
case EMT_TICKER_TYPE_STOCK:
case EMT_TICKER_TYPE_TECH_STOCK:
break;
case EMT_TICKER_TYPE_FUND:
break;
case EMT_TICKER_TYPE_BOND:
break;
case EMT_TICKER_TYPE_INDEX:
break;
default:
continue;
}
outfile << GetExchangeID(iter->exchange_id) << "," << GetProductClass(iter->ticker_type) << "," << iter->ticker << "," << iter->ticker_name << "," << iter->price_tick << "," << iter->pre_close_price << std::endl;
}
outfile.close();
printf("Dump completed.\n");
//exit(0);
}
}
const std::string GetExchangeID(EMT_EXCHANGE_TYPE exchange_id)
{
std::string str;
switch (exchange_id) {
case EMT_EXCHANGE_SH:
str = "SSE";
break;
case EMT_EXCHANGE_SZ:
str = "SZSE";
break;
default:
break;
}
return std::move(str);
}
const std::string GetProductClass(EMT_TICKER_TYPE ticker_type)
{
std::string str;
switch (ticker_type) {
case EMT_TICKER_TYPE_STOCK:
case EMT_TICKER_TYPE_TECH_STOCK:
str = 'E';
break;
case EMT_TICKER_TYPE_BOND:
str = 'B';
break;
case EMT_TICKER_TYPE_FUND:
str = 'D';
break;
case EMT_TICKER_TYPE_INDEX:
str = 'I';
break;
default:
break;
}
return std::move(str);
}
int Run()
{
std::string ip = m_host.substr(0, m_host.find(':'));
std::string port = m_host.substr(m_host.find(':') + 1);
if (m_pUserApi->Login(ip.c_str(), atol(port.c_str()), m_user.c_str(), m_password.c_str(), EMT_PROTOCOL_TCP,"127.0.0.1")!=0) {
printf("Login failed.\n");
OnError(m_pUserApi->GetApiLastError());
return -1;
}
printf("Login succeeded.\n");
// 查询合约
printf("Query Instruments ...\n");
m_pUserApi->QueryAllTickers(EMT_EXCHANGE_SH);
return 0;
}
virtual void OnDisconnected(uint64_t session_id, int reason)
{
printf("Disconnected.\n");
}
///错误响应
virtual void OnError(EMTRspInfoStruct* error_info)
{
if (!error_info)
return;
printf("Error: %d - %s\n", error_info->error_id, error_info->error_msg);
}
private:
std::string m_host;
std::string m_user;
std::string m_password;
std::vector<EMTQuoteStaticInfo> m_vInstruments;
EMT::API::QuoteApi* m_pUserApi;
};
void display_usage()
{
printf("usage:dictdump host user password\n");
printf("example:dictdump 119.3.103.38:6002 000001 888888\n");
}
int main(int argc, char* argv[])
{
if (argc != 4) {
display_usage();
return -1;
}
CApplication Spi(argv[1], argv[2], argv[3]);
// 启动
if (Spi.Run() < 0)
return -1;
getchar();
return 0;
}
| 21.434066 | 216 | 0.671879 | anyex-net |
595ce0f6c6177fc8b59a94d3ba0e41b843daf44a | 3,227 | cpp | C++ | src/tests/legacystore/jrnl/_ut_txn_map.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | 1 | 2017-11-29T09:19:02.000Z | 2017-11-29T09:19:02.000Z | src/tests/legacystore/jrnl/_ut_txn_map.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | src/tests/legacystore/jrnl/_ut_txn_map.cpp | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "../unit_test.h"
#include <iomanip>
#include <iostream>
#include "qpid/legacystore/jrnl/txn_map.h"
#include <sstream>
using namespace boost::unit_test;
using namespace mrg::journal;
using namespace std;
QPID_AUTO_TEST_SUITE(txn_map_suite)
const string test_filename("_ut_txn_map");
// === Helper functions ===
const string make_xid(u_int64_t rid)
{
stringstream ss;
ss << "XID-" << setfill('0') << setw(16) << hex << rid;
ss << "-0123456789abcdef";
return ss.str();
}
void check_td_equal(txn_data& td1, txn_data& td2)
{
BOOST_CHECK_EQUAL(td1._rid, td2._rid);
BOOST_CHECK_EQUAL(td1._drid, td2._drid);
BOOST_CHECK_EQUAL(td1._pfid, td2._pfid);
BOOST_CHECK_EQUAL(td1._enq_flag, td2._enq_flag);
BOOST_CHECK_EQUAL(td1._aio_compl, td2._aio_compl);
}
// === Test suite ===
QPID_AUTO_TEST_CASE(constructor)
{
cout << test_filename << ".constructor: " << flush;
const u_int64_t rid = 0x123456789abcdef0ULL;
const u_int64_t drid = 0xfedcba9876543210ULL;
const u_int16_t pfid = 0xfedcU;
const bool enq_flag = true;
txn_data td(rid, drid, pfid, enq_flag);
BOOST_CHECK_EQUAL(td._rid, rid);
BOOST_CHECK_EQUAL(td._drid, drid);
BOOST_CHECK_EQUAL(td._pfid, pfid);
BOOST_CHECK_EQUAL(td._enq_flag, enq_flag);
BOOST_CHECK_EQUAL(td._aio_compl, false);
txn_map t1;
BOOST_CHECK(t1.empty());
BOOST_CHECK_EQUAL(t1.size(), u_int32_t(0));
cout << "ok" << endl;
}
QPID_AUTO_TEST_CASE(insert_get)
{
cout << test_filename << ".insert_get: " << flush;
u_int16_t fid;
u_int64_t rid;
u_int16_t pfid_start = 0x2000U;
u_int64_t rid_begin = 0xffffffff00000000ULL;
u_int64_t rid_end = 0xffffffff00000200ULL;
// insert with no dups
u_int64_t rid_incr_1 = 4ULL;
txn_map t2;
t2.set_num_jfiles(pfid_start + (rid_end - rid_begin)/rid_incr_1);
for (rid = rid_begin, fid = pfid_start; rid < rid_end; rid += rid_incr_1, fid++)
t2.insert_txn_data(make_xid(rid), txn_data(rid, ~rid, fid, false));
BOOST_CHECK(!t2.empty());
BOOST_CHECK_EQUAL(t2.size(), u_int32_t(128));
// get
u_int64_t rid_incr_2 = 6ULL;
for (u_int64_t rid = rid_begin; rid < rid_end; rid += rid_incr_2)
{
string xid = make_xid(rid);
BOOST_CHECK_EQUAL(t2.in_map(xid), (rid%rid_incr_1 ? false : true));
}
cout << "ok" << endl;
}
QPID_AUTO_TEST_SUITE_END()
| 30.158879 | 84 | 0.694143 | irinabov |
595cf7d38f17f13f0e30759c17d647a73bb7128d | 14,473 | cpp | C++ | ISA/ldap.cpp | thanhdolong/VUT-FIT-BIT-Projects | 077164a2b1493f9223b25e7fc51bc0e3e90020b2 | [
"MIT"
] | null | null | null | ISA/ldap.cpp | thanhdolong/VUT-FIT-BIT-Projects | 077164a2b1493f9223b25e7fc51bc0e3e90020b2 | [
"MIT"
] | null | null | null | ISA/ldap.cpp | thanhdolong/VUT-FIT-BIT-Projects | 077164a2b1493f9223b25e7fc51bc0e3e90020b2 | [
"MIT"
] | null | null | null | // ISA Project
// Variant: LDAP server
//
// Author: Do Long Thanh
// <xdolon00@stud.fit.vutbr.cz>
#include <unistd.h>
#include <algorithm>
#include <regex>
#include "ldap.hpp"
#include "tools.hpp"
std::set<std::shared_ptr<person>> universe;
size_t position = 0;
/**
* Parse messages incoming from LDAP client.
* The implementation is based on finite-state automaton.
* @param fd Socket for sending message
*/
void service(int fd) {
char buf[BUFFER];
int n;
while ((n = (int) read(fd, buf, 1)) > 0) {
// Check if it is LDAP message
if (buf[0] == 0x30) {
FILE *stream = fdopen(fd, "r+");
if (stream == nullptr) callError("fdopen error");
//get length of LDAP message
getLength(stream);
unsigned char actualChar = (unsigned char) fgetc(stream);
unsigned char lengthOfMessageId = (unsigned char) fgetc(stream);
if (actualChar == 0x02 && (lengthOfMessageId >= 0x01 || lengthOfMessageId <= 0x04)) {
// Reading MessageID
for (int i = 0; i < (int) lengthOfMessageId; ++i) {
fgetc(stream);
}
}
actualChar = (unsigned char) fgetc(stream);
switch (actualChar) {
/**
* 0x60 - BindRequest
*/
case BIND_REQUEST: {
ldapResponse(fd, LDAP_BIND_RESPONSE);
break;
}
/**
* 0x63 - SearchRequest
*/
case SEARCH_REQUEST: {
size_t len = 0;
int sizeLimit = parseSearchResponseHeader(fd, stream);
std::shared_ptr<std::set<std::shared_ptr<person>>> results = processSearchRequest(stream, &len, fd);
searchResultEntry(results, fd, sizeLimit);
break;
}
/**
* 0x42 - UnbindRequest
*/
case UNBIND_REQUEST: break;
default:
ldapResponse(fd, LDAP_PROTOCOL_ERROR);
break;
}
}
} if (n == -1) callError("read()");
}
/**
* Parse header from SearchRequest
* @param fd Socket for sending message
* @param stream The pointer to a FILE object that identifies the stream
* @return The maximum number of entries that should be returned as a result of search.
*/
int parseSearchResponseHeader(int fd, FILE *stream) {
int sizeLimit = 0;
for (int state = 0; state < 6; ++state) {
switch (state) {
/**
* Only the base object is examined
* Base object is not supported
*/
case BASE_OBJECT: {
getLength(stream);
if (fgetc(stream) != 0x04) {
state = SEARCH_REQUEST_ERROR;
break;
}
fgetc(stream);
break;
}
/**
* Specifies how deep within the DIT to search from the base object
* Scope is not supported
*/
case SCOPE: {
unsigned char actualChar = (unsigned char) fgetc(stream);
unsigned char nextChar = (unsigned char) fgetc(stream);
if((actualChar != 0x0A) && (nextChar != 0x01)) {
state = SEARCH_REQUEST_ERROR;
break;
}
fgetc(stream);
break;
}
/**
* Specifies if aliases are dereferenced
* Alias dereferencing is not supported
*/
case DEREF_ALIASES: {
unsigned char actualChar = (unsigned char) fgetc(stream);
unsigned char nextChar = (unsigned char) fgetc(stream);
if((actualChar != 0x0A) && (nextChar != 0x01)) {
state = SEARCH_REQUEST_ERROR;
break;
}
fgetc(stream);
break;
}
/**
* The maximum number of entries that should be returned as a result of search.
* SizeLimit is supported
*/
case SIZE_LIMIT: {
if (fgetc(stream) != 0x02) {
state = SEARCH_REQUEST_ERROR;
break;
}
unsigned char numberOfChar = (unsigned char) fgetc(stream);
if (numberOfChar > 0x04 || numberOfChar < 0x01) {
state = SEARCH_REQUEST_ERROR;
break;
}
for (int i = 0; i < numberOfChar; ++i) {
sizeLimit = (sizeLimit << 8) | (fgetc(stream) & 0xff);
}
break;
}
/**
* The maximum number of seconds allowed to perform the search
* TimeLimit is not supported
*/
case TIME_LIMIT: {
if(fgetc(stream) != 0x02) {
state = SEARCH_REQUEST_ERROR;
break;
}
unsigned char numberOfChar = (unsigned char) fgetc(stream);
if (numberOfChar > 0x04 || numberOfChar < 0x01) {
state = SEARCH_REQUEST_ERROR;
break;
}
for (int i = 0; i < numberOfChar; ++i) {
fgetc(stream);
}
break;
}
/**
* Specifies typesonly
* typesonly is not supported
*/
case TYPES_ONLY: {
unsigned char actualChar = (unsigned char) fgetc(stream);
unsigned char nextChar = (unsigned char) fgetc(stream);
if ((actualChar != 0x01) && (nextChar != 0x01)) {
state = SEARCH_REQUEST_ERROR;
break;
}
fgetc(stream);
break;
}
case SEARCH_REQUEST_ERROR: {
ldapResponse(fd, LDAP_PROTOCOL_ERROR);
break;
}
default: break;
}
}
return sizeLimit;
}
/**
* Find match a given set of criteria.
* @param stream The pointer to a FILE object that identifies the stream
* @param len
* @param fd Socket for sending message
* @return zero or more entries
*/
std::shared_ptr<std::set<std::shared_ptr<person>>> processSearchRequest (FILE* stream, size_t* len, int fd) {
auto begin = position;
unsigned char op = (unsigned char) customFgetc(stream);
size_t local_len = (size_t) getLength(stream);
std::shared_ptr<std::set<std::shared_ptr<person>>> set = nullptr;
switch(op) {
case SUBSTRINGS_FILTER: {
//warning, size may be coded in more bytes
customFgetc(stream); //should be 04
size_t l = (size_t) getLength(stream);
std::string column;
column.reserve(l+1);
for (unsigned i = 0; i < l; ++i)
column.push_back(customFgetc(stream));
customFgetc(stream); //should be 30
l = (size_t) getLength(stream);
std::string pattern = "";
while (l > 0) {
convertSubstringToRegex(stream, &l, pattern, fd);
}
std::regex regex(pattern);
set = std::make_shared<std::set<std::shared_ptr<person>>>();
for (auto & element: universe) {
std::string* member = nullptr;
if (column == "cn")
member = &(element->cn);
else if (column == "uid")
member = &(element->uid);
else if (column == "mail")
member = &(element->email);
else break;
if (std::regex_match(*member, regex))
set->insert(element);
}
} break;
case EQUALITY_MATCH_FILTER: {
//warning, size may be coded in more bytes
customFgetc(stream); //should be 04
size_t l = (size_t) getLength(stream);
std::string column;
column.reserve(l+1);
for (unsigned i = 0; i < l; ++i)
column.push_back(customFgetc(stream));
customFgetc(stream); //should be 04
l = (size_t) getLength(stream);
std::string value;
value.reserve(l+1);
for (unsigned i = 0; i < l; ++i)
value.push_back(customFgetc(stream));
set = std::make_shared<std::set<std::shared_ptr<person>>>();
for (auto & element: universe) {
std::string* member = nullptr;
if (column == "cn")
member = &(element->cn);
else if (column == "uid")
member = &(element->uid);
else if (column == "mail")
member = &(element->email);
else break;
if (*member == value)
set->insert(element);
}
} break;
case NOT_FILTER: {
set = std::make_shared<std::set<std::shared_ptr<person>>>();
auto s = processSearchRequest(stream, &local_len, fd);
std::set_difference(universe.begin(), universe.end(), s->begin(), s->end(), std::inserter(*set, set->begin()));
} break;
case OR_FILTER: {
set = processSearchRequest(stream, &local_len, fd);
while (local_len > 0) {
auto second = processSearchRequest(stream, &local_len, fd);
auto result = std::make_shared<std::set<std::shared_ptr<person>>>();
std::set_union(set->begin(), set->end(), second->begin(), second->end(), std::inserter(*result, result->begin()));
set = result;
}
} break;
case AND_FILTER: {
set = processSearchRequest(stream, &local_len, fd);
while (local_len > 0) {
auto second = processSearchRequest(stream, &local_len, fd);
auto result = std::make_shared<std::set<std::shared_ptr<person>>>();
std::set_intersection(set->begin(), set->end(), second->begin(), second->end(), std::inserter(*result, result->begin()));
set = result;
}
} break;
default:
ldapResponse(fd, LDAP_PROTOCOL_ERROR);
break;
}
*len -= position - begin;
return set;
}
/**
* Each LDAPMessage searchResEntry() is a result from the ldap server.
* It will contain at least the DN of the entry, and may contain zero or more attributes.
* @param results
* @param fd Socket for sending message
* @param sizeLimit
*/
void searchResultEntry(std::shared_ptr<std::set<std::shared_ptr<person>>> results, int fd, int sizeLimit) {
int numberOfSendEntry = 0;
int numberOfAnswers = (int) results->size();
for (auto user = results->begin(); user != results->end() ; user++) {
std::string searchResponse = {};
std::string uid = (*user)->uid;
std::string cn = (*user)->cn;
std::string email = (*user)->email;
searchResponse += 0x30;
searchResponse += cn.length() + email.length() + uid.length() + 35;
searchResponse += {0x02, 0x01, 0x02, 0x64};
searchResponse += cn.length() + email.length() + uid.length() + 30;
searchResponse += 0x04;
searchResponse += uid.length() + 4;
searchResponse += {"uid"};
searchResponse += 0x3d;
while(!uid.empty()) {
searchResponse += uid.front();
uid.erase(0,1);
}
searchResponse += 0x30;
searchResponse += cn.length() + email.length() + 22;
searchResponse += 0x30;
searchResponse += cn.length() + 8;
searchResponse += {0x04, 0x02};
searchResponse += {"cn"};
searchResponse += 0x31;
searchResponse += cn.length() + 2;
searchResponse += 0x4;
searchResponse += cn.length();
while(!cn.empty()) {
searchResponse += cn.front();
cn.erase(0,1);
}
searchResponse += 0x30;
searchResponse += email.length() + 10;
searchResponse += {0x04, 0x04};
searchResponse += {"mail"};
searchResponse += 0x31;
searchResponse += email.length() + 2;
searchResponse += 0x04;
searchResponse += email.length();
while(!email.empty()) {
searchResponse += email.front();
email.erase(0,1);
}
if ((sizeLimit == 0) || (numberOfSendEntry < sizeLimit)) {
numberOfSendEntry++; int r = (int) write(fd, searchResponse.c_str(), searchResponse.length());
if (r == -1) callError("write()");
if (r != (int) searchResponse.length()) callError("write(): Buffer written just partially");
} else results->end();
}
/**
* If user set size limit, it is neccessary to check if it is send incomplete results.
*/
if(numberOfSendEntry < numberOfAnswers) ldapResponse(fd, LDAP_SIZELIMIT_EXCEEDED);
else ldapResponse(fd, LDAP_SUCCESS);
}
/**
* Responses from LDAP server
* @param fd
* @param reply
*/
void ldapResponse(int fd, int reply){
std::string searchResponse;
switch(reply){
case LDAP_SUCCESS:
searchResponse = {0x30, 0x0C, 0x02, 0x01, 0x02, 0x65, 0x07, 0x0A, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
break;
case LDAP_SIZELIMIT_EXCEEDED:
searchResponse = {0x30, 0x0C, 0x02, 0x01, 0x02, 0x65, 0x07, 0x0A, 0x01, 0x04, 0x04, 0x00, 0x04, 0x00};
break;
case LDAP_PROTOCOL_ERROR:
searchResponse = {0x30, 0x0C, 0x02, 0x01, 0x02, 0x65, 0x07, 0x0A, 0x01, 0x02, 0x04, 0x00, 0x04, 0x00};
break;
case LDAP_BIND_RESPONSE:
searchResponse = {0x30, 0x0c, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0a, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
break;
default:break;
}
int r = (int) write(fd, searchResponse.c_str(), searchResponse.length());
if (r == -1) callError("write()");
if (r != (int) searchResponse.length()) callError("write(): Buffer written just partially");
} | 32.818594 | 137 | 0.506046 | thanhdolong |
595d479b2f1283b411a456e96221798b53843669 | 3,239 | cc | C++ | bin/db/dbresample/dbresample.cc | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 30 | 2015-02-20T21:44:29.000Z | 2021-09-27T02:53:14.000Z | bin/db/dbresample/dbresample.cc | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 14 | 2015-07-07T19:17:24.000Z | 2020-12-19T19:18:53.000Z | bin/db/dbresample/dbresample.cc | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 46 | 2015-02-06T16:22:41.000Z | 2022-03-30T11:46:37.000Z | #include<string>
#include "stock.h"
#include "elog.h"
#include "db.h"
#include "pf.h"
#include "glputil.h"
#include "resample.h"
#include "SeisppError.h"
#include "seispp.h"
using namespace SEISPP;
#include "resample.h"
void usage()
{
cerr<<"dbresample dbin dbout [-pf pffile -notrim -V]"<<endl;
exit(-1);
}
bool SEISPP::SEISPP_verbose(false);
int main(int argc, char **argv)
{
Dbptr db;
Pf *pf;
string pffile("dbresample");
bool trim=true;
string chan;
string dfile_name;
ios::sync_with_stdio();
// Standard argument parsing in C++ form
elog_init(argc,argv);
if(argc<3)
usage();
try
{
string dbname(argv[1]);
string dboname(argv[2]);
string tag("dbprocess_commands");
for(int i=3;i<argc;++i)
{
string test(argv[i]);
if(test=="-pf")
{
++i;
pffile=string(argv[i]);
}
else if(test=="-notrim")
trim = false;
else if(test=="-V")
SEISPP_verbose=true;
else
{
cerr<<"Illegal argument = "<<argv[i]<<endl;
usage();
}
if(i>=argc) usage();
}
if(pfread(const_cast<char *>(pffile.c_str()),&pf))
die(0,"Failure reading parameter file %s\n",pffile.c_str());
// local variables used below
double dtout;
dtout = 1.0/pfget_double(pf,"output_sample_rate");
char *chan_code;
chan_code=pfget_string(pf,"output_channel_code");
cout << "Output channels will be coded as "<<chan_code<<endl;
if(strlen(chan_code)!=1)
{
cerr << "Warning: input channel code is more than one character long"
<< "Only the first character "
<< chan_code[0] << " will be used"<<endl;
}
// This object defines mapping from external to internal namespace
// old form: AttributeMap am(pf,string("AttributeMap"));
AttributeMap am("css3.0");
// This defines the list of internal names actually extracted from db
MetadataList md_to_input=pfget_mdlist(pf,
"input_list");
// This is the list saved
MetadataList md_to_output=pfget_mdlist(pf,
"output_list");
// Input and output database handles
DatascopeHandle dbhi(dbname,false);
dbhi=DatascopeHandle(dbhi,pf,tag);
DatascopeHandle dbho(dboname,false);
// Builds the object that defines how decimation is
// and resampling is to be done.
ResamplingDefinitions rsampdef(pf);
dbhi.rewind();
for(int i=0;i<dbhi.number_tuples();++i,++dbhi)
{
TimeSeries *tin;
TimeSeries traceout;
string table("wfdisc");
tin = new TimeSeries(dynamic_cast<DatabaseHandle&>(dbhi),
md_to_input,am);
traceout = ResampleTimeSeries(*tin,rsampdef,dtout,trim);
// Simple method to change channel code
// only does right thing for SEED chan codes
chan=traceout.get_string("chan");
chan[0]=chan_code[0];
traceout.put("chan",chan);
// a crude way to alter files to preserve original structure
// append the string ".resampled"
dfile_name = traceout.get_string("dfile");
dfile_name = dfile_name + string(".resampled");
traceout.put("dfile",dfile_name);
dbsave(traceout,dbho.db,table,md_to_output,am);
delete tin;
}
}
// for now we exit on any exception. Some errors may
// need to be caught and handled without exits
catch (MetadataError spe)
{
spe.log_error();
exit(-1);
}
catch (SeisppError se)
{
se.log_error();
exit(-1);
}
}
| 25.503937 | 73 | 0.673356 | jreyes1108 |
595f49945b7c47530cfa7d8dd3069ca79db217e6 | 988 | cpp | C++ | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | 2 | 2020-04-21T23:52:31.000Z | 2020-04-24T13:37:28.000Z | #include <iostream>
#include <vector>
void rotate(std::vector<std::vector<int>>& matrix) {
int size = (int)matrix.size();
for (int i = 0; i < size / 2; ++i)
{
for (int j = i; j < size - 1 - i; ++j)
{
int tmp = matrix[i][j];
matrix[i][j] = matrix[size - 1 - j][i];
matrix[size - 1 - j][i] = matrix[size - 1 - i][size - 1 - j];
matrix[size - 1 - i][size - 1 - j] = matrix[j][size - 1 - i];
matrix[j][size - 1 - i] = tmp;
}
}
}
int main(void)
{
std::vector<int> row1{1,2,3};
std::vector<int> row2{4,5,6};
std::vector<int> row3{7,8,9};
std::vector<std::vector<int>> input{row1, row2, row3};
std::cout << "Before rotate" << std::endl;
for (auto input_idx : input) {
for (auto row : input_idx) {
std::cout << row << " ";
}
std::cout << std::endl;
}
rotate(input);
std::cout << "After rotate" << std::endl;
for (auto input_idx : input) {
for (auto row : input_idx) {
std::cout << row << " ";
}
std::cout << std::endl;
}
return 0;
} | 20.583333 | 64 | 0.538462 | DaechurJeong |
596015903c5251c55df77f7afc45c0558db954e5 | 7,019 | cpp | C++ | test/test_pc_merger.cpp | Jenifen/pointcloud_merger | f3d3aecf3844d8dc9fcf23231108850e1c147db0 | [
"BSD-3-Clause"
] | 6 | 2021-03-07T04:43:46.000Z | 2022-03-26T08:11:03.000Z | test/test_pc_merger.cpp | Jenifen/pointcloud_merger | f3d3aecf3844d8dc9fcf23231108850e1c147db0 | [
"BSD-3-Clause"
] | 1 | 2021-05-18T06:56:17.000Z | 2021-05-18T06:56:17.000Z | test/test_pc_merger.cpp | Jenifen/pointcloud_merger | f3d3aecf3844d8dc9fcf23231108850e1c147db0 | [
"BSD-3-Clause"
] | 6 | 2021-05-16T20:34:46.000Z | 2022-03-26T08:11:04.000Z | #include <gtest/gtest.h>
#include <iostream>
#include <string>
// ROS
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/point_cloud.h>
#include <ros/ros.h>
// PCL
#include <pcl/filters/filter.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include "test_pc_merger.h"
#define NB_ITER 50
#define MAX_DISTANCE 5
TEST(UnitTest, checkSumClouds) {
// Loading pointclouds
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(
new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(
new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud3(
new pcl::PointCloud<pcl::PointXYZ>);
if (pcl::io::loadPCDFile<pcl::PointXYZ>("data/cloud1.pcd", *cloud1) ==
-1) //* load the file
{
PCL_ERROR("Couldn't read file data/cloud1.pcd \n");
ASSERT_FALSE(true);
}
#ifdef DEBUG
std::cout << "Loaded " << cloud1->width * cloud1->height
<< " data points from data/cloud1.pcd with the following fields: "
<< std::endl;
#endif
if (pcl::io::loadPCDFile<pcl::PointXYZ>("data/cloud2.pcd", *cloud2) ==
-1) //* load the file
{
PCL_ERROR("Couldn't read file data/cloud2.pcd \n");
ASSERT_FALSE(true);
}
#ifdef DEBUG
std::cout << "Loaded " << cloud2->width * cloud2->height
<< " data points from data/cloud2.pcd with the following fields: "
<< std::endl;
#endif
if (pcl::io::loadPCDFile<pcl::PointXYZ>("data/cloud_out.pcd", *cloud3) ==
-1) //* load the file
{
PCL_ERROR("Couldn't read file data/cloud_out.pcd \n");
ASSERT_FALSE(true);
}
#ifdef DEBUG
std::cout
<< "Loaded " << cloud3->width * cloud3->height
<< " data points from data/cloud_out.pcd with the following fields: "
<< std::endl;
#endif
std::vector<int> indices;
pcl::removeNaNFromPointCloud(*cloud1, *cloud1, indices);
pcl::removeNaNFromPointCloud(*cloud2, *cloud2, indices);
pcl::removeNaNFromPointCloud(*cloud3, *cloud3, indices);
// Help ICP by transform into the same frame
Eigen::Affine3f transform_cloud1, transform_cloud2, transform_cloud3;
transform_cloud3 = Eigen::Affine3f::Identity();
// transform_cloud1 = Eigen::Affine3f::Identity();
// transform_cloud2 = Eigen::Affine3f::Identity();
// transform_cloud1.translation() << 0.948, 0.566, 0.065;
// transform_cloud1.rotate(Eigen::Quaternionf(0.249, -0.420, 0.750, 0.445));
// transform_cloud2.translation() << -0.948, 0.566, 0.065;
// transform_cloud2.rotate(Eigen::Quaternionf(0.420, -0.249, 0.445, 0.763));
// To match frames with cloud 1 and 2, getting close.
transform_cloud3.rotate(
Eigen::AngleAxisf(-M_PI / 2, Eigen::Vector3f::UnitY()));
transform_cloud3.rotate(
Eigen::AngleAxisf(M_PI / 2, Eigen::Vector3f::UnitX()));
pcl::transformPointCloud(*cloud3, *cloud3, transform_cloud3);
pcl::io::savePCDFile<pcl::PointXYZ>("data/cloud_out_updated.pcd", *cloud3);
#ifdef DEBUG
// Print the transformation
std::cout << transform_cloud1.matrix() << std::endl;
std::cout << transform_cloud2.matrix() << std::endl;
std::cout << transform_cloud3.matrix() << std::endl;
#endif
// Registration cloud1 in cloud3
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setEuclideanFitnessEpsilon(0.000000000001);
icp.setTransformationEpsilon(0.0000001);
icp.setMaximumIterations(2);
icp.setMaxCorrespondenceDistance(MAX_DISTANCE);
icp.setInputTarget(cloud3);
// Run the same optimization in a loop and visualize the results
Eigen::Matrix4f Ti = Eigen::Matrix4f::Identity(), prev, targetToSource;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_copy(
new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*cloud1, *cloud_copy);
pcl::PointCloud<pcl::PointXYZ>::Ptr reg_result = cloud_copy;
#ifdef DEBUG
PCL_INFO("Press q for cloud 1\n");
p->spin();
#endif
for (int i = 0; i < NB_ITER; ++i) {
#ifdef DEBUG
PCL_INFO("Iteration Nr. %d.\n", i);
#endif
// save cloud for visualization purpose
cloud_copy = reg_result;
// Estimate
icp.setInputSource(cloud_copy);
icp.align(*reg_result);
// accumulate transformation between each Iteration
Ti = icp.getFinalTransformation() * Ti;
// if the difference between this transformation and the previous one
// is smaller than the threshold, refine the process by reducing
// the maximal correspondence distance
if (std::abs((icp.getLastIncrementalTransformation() - prev).sum()) <
icp.getTransformationEpsilon())
icp.setMaxCorrespondenceDistance(icp.getMaxCorrespondenceDistance() *
0.8);
prev = icp.getLastIncrementalTransformation();
#ifdef DEBUG
// visualize current state
showCloudsRight(cloud3, cloud_copy);
std::cout << "has converged:" << icp.hasConverged()
<< " score: " << icp.getFitnessScore() << std::endl;
#endif
if (icp.hasConverged() == 0) {
icp.setMaxCorrespondenceDistance(icp.getMaxCorrespondenceDistance() * 2);
}
}
EXPECT_TRUE(icp.getFitnessScore() < 0.0001);
//CLOUD2
#ifdef DEBUG
PCL_INFO("Press q for cloud 2\n");
p->spin();
#endif
pcl::copyPointCloud(*cloud2, *cloud_copy);
icp.setMaxCorrespondenceDistance(MAX_DISTANCE); // reset to MAX_DISTANCE
reg_result = cloud_copy;
for (int i = 0; i < NB_ITER; ++i) {
#ifdef DEBUG
PCL_INFO("Iteration Nr. %d.\n", i);
#endif
cloud_copy = reg_result;
// Estimate
icp.setInputSource(cloud_copy);
icp.align(*reg_result);
// accumulate transformation between each Iteration
Ti = icp.getFinalTransformation() * Ti;
// if the difference between this transformation and the previous one
// is smaller than the threshold, refine the process by reducing
// the maximal correspondence distance
if (std::abs((icp.getLastIncrementalTransformation() - prev).sum()) <
icp.getTransformationEpsilon())
icp.setMaxCorrespondenceDistance(icp.getMaxCorrespondenceDistance() *
0.8);
prev = icp.getLastIncrementalTransformation();
#ifdef DEBUG
// visualize current state
showCloudsRight(cloud3, cloud_copy);
std::cout << "has converged:" << icp.hasConverged()
<< " score: " << icp.getFitnessScore() << std::endl;
#endif
if (icp.hasConverged() == 0) {
icp.setMaxCorrespondenceDistance(icp.getMaxCorrespondenceDistance() * 2);
}
}
EXPECT_TRUE(icp.getFitnessScore() < 0.0001);
#ifdef DEBUG
PCL_INFO("Press q to quit\n");
p->spin();
#endif
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv) {
#ifdef DEBUG
// Create a PCLVisualizer object
p = new pcl::visualization::PCLVisualizer(argc, argv, "Check ICP ");
p->addCoordinateSystem(10.0, "global");
p->createViewPort(0.0, 0, 0.5, 1.0, vp_1);
p->createViewPort(0.5, 0, 1.0, 1.0, vp_2);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.124464 | 79 | 0.671606 | Jenifen |
596221e05ebadf598879c2268a826139fb3ed001 | 942 | hpp | C++ | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 2 | 2017-03-31T17:18:45.000Z | 2017-05-15T19:19:12.000Z | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 4 | 2018-06-24T00:39:05.000Z | 2018-07-03T21:55:02.000Z | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 6 | 2017-04-03T00:12:32.000Z | 2019-01-05T14:36:22.000Z | #ifndef __ENGINE_COMPONENTS_COMPONENT__
#define __ENGINE_COMPONENTS_COMPONENT__
#include "gameobject.hpp"
namespace engine {
class Component {
friend bool GameObject::add_component(Component & component);
public:
enum class State {
enabled,
disabled,
invalid
};
Component() : m_game_object(NULL), m_state(State::invalid) {}
virtual ~Component() {}
virtual bool init() { return true; }
virtual void setup() { return; }
virtual bool shutdown() { return true; }
virtual void update() { return; }
virtual void draw() { return; }
inline State state() { return m_state; }
inline const GameObject * game_object() { return m_game_object; }
inline void enable() { m_state = State::enabled; }
inline void disable() { m_state = State::disabled; }
protected:
GameObject * m_game_object;
State m_state;
};
}
#endif
| 22.428571 | 69 | 0.63482 | Eduardolimr |
5965a4d927773765a1a0b7bd5b6a726665ed4914 | 815 | cpp | C++ | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | 7 | 2018-11-15T07:51:21.000Z | 2020-03-20T04:31:33.000Z | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | null | null | null | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | 3 | 2018-11-15T06:39:53.000Z | 2021-07-20T02:09:18.000Z | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int e[100][100];
int E(int o,int n,int k)
{
//usleep(500000);
// cout<<"Checking for : n = "<<n<<" and k = "<<k<<endl;
int min=INT_MAX;
if(e[n][k]!=-1)
return e[n][k];
if(n==0||k==0)
{
return 0;
}
// if(n==1)
// return 1;
if(k==1)
return n;
if(n>o)
return 0;
for(int i=n;i>=1;i--)
{
int a=E(o,n-i,k);
int b=E(o,i-1,k-1);
if(min>1+max(a,b))
{
min=1+max(a,b);
}
}
//cout<<"Returning min = "<<min<<" For n = "<<n<<" and k = "<<k<<" \n***************************\n";
e[n][k]=min;
return min;
}
int main()
{
int t;
cin>>t;
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
e[i][j]=-1;
while(t--)
{
int n,k;
cin>>k>>n;
cout<<E(n,n,k)<<endl;
}
return 0;
}
| 10.584416 | 102 | 0.442945 | Pradyuman7 |
5967719b26b96d2f5cc7597d51f2cf79090a0a1f | 7,221 | cc | C++ | AM/src/RIU.cc | abhineet123/MTF | 6cb45c88d924fb2659696c3375bd25c683802621 | [
"BSD-3-Clause"
] | 100 | 2016-12-11T00:34:06.000Z | 2022-01-27T23:03:40.000Z | AM/src/RIU.cc | abhineet123/MTF | 6cb45c88d924fb2659696c3375bd25c683802621 | [
"BSD-3-Clause"
] | 21 | 2017-09-04T06:27:13.000Z | 2021-07-14T19:07:23.000Z | AM/src/RIU.cc | abhineet123/MTF | 6cb45c88d924fb2659696c3375bd25c683802621 | [
"BSD-3-Clause"
] | 21 | 2017-02-19T02:12:11.000Z | 2020-09-23T03:47:55.000Z | #include "mtf/AM/RIU.h"
#include "mtf/Utilities/miscUtils.h"
#define RIU_DEBUG false
_MTF_BEGIN_NAMESPACE
//! value constructor
RIUParams::RIUParams(const AMParams *am_params,
bool _debug_mode) :
AMParams(am_params), debug_mode(_debug_mode){}
//! default/copy constructor
RIUParams::RIUParams(const RIUParams *params) :
AMParams(params),
debug_mode(RIU_DEBUG){
if(params){
debug_mode = params->debug_mode;
}
}
RIUDist::RIUDist(const string &_name, const bool _dist_from_likelihood,
const double _likelihood_alpha,
const unsigned int _patch_size) : AMDist(_name),
dist_from_likelihood(_dist_from_likelihood),
likelihood_alpha(_likelihood_alpha), patch_size(_patch_size){}
RIU::RIU(const ParamType *riu_params, const int _n_channels) :
AppearanceModel(riu_params, _n_channels), params(riu_params){
name = "riu";
printf("\n");
printf("Using Ratio Image Uniformity AM with...\n");
printf("likelihood_alpha: %f\n", params.likelihood_alpha);
printf("dist_from_likelihood: %d\n", params.dist_from_likelihood);
printf("debug_mode: %d\n", params.debug_mode);
printf("grad_eps: %e\n", grad_eps);
printf("hess_eps: %e\n", hess_eps);
N_inv = 1.0 / patch_size;
}
double RIU::getLikelihood() const{
return exp(params.likelihood_alpha * f);
}
void RIU::initializeSimilarity(){
if(is_initialized.similarity){ return; }
r = VectorXd::Ones(patch_size);
r_cntr = VectorXd::Zero(patch_size);
r_mean = 1;
r_var = 0;
f = 0;
is_initialized.similarity = true;
}
void RIU::initializeGrad(){
if(is_initialized.grad){ return; }
df_dIt.resize(patch_size);
df_dI0.resize(patch_size);
df_dr.resize(patch_size);
dr_dI0.resize(patch_size);
dr_dIt.resize(patch_size);
df_dI0.fill(0);
df_dIt.fill(0);
dr_dI0 = 1.0 / (1 + I0.array());
dr_dIt = dr_dI0;
is_initialized.grad = true;
}
void RIU::updateSimilarity(bool prereq_only){
r = (1 + It.array()) / (1 + I0.array());
r_mean = r.mean();
r_cntr = r.array() - r_mean;
r_var = r_cntr.squaredNorm() / patch_size;
r_mean_inv = 1.0 / r_mean;
f = -r_var * r_mean_inv;
}
void RIU::updateInitGrad(){
df_dr = (f * N_inv - 2 * r_cntr.array())*(N_inv*r_mean_inv);
dr_dI0 = -r.array() / (1 + I0.array());
df_dI0 = df_dr.array() * dr_dI0.array();
//df_dI0 = -r.array() * (f / patch_size - 2 * r_cntr.array())
// *
// ((N_inv*r_mean_inv)*(1 + I0.array()));
}
void RIU::updateCurrGrad(){
df_dr = (f * N_inv - 2 * r_cntr.array())*(N_inv*r_mean_inv);
df_dIt = df_dr.array() * dr_dIt.array();
}
void RIU::cmptInitHessian(MatrixXd &d2f_dp2, const MatrixXd &dI0_dp){
assert(d2f_dp2.cols() == d2f_dp2.rows());
assert(d2f_dp2.cols() == dI0_dp.cols());
assert(dI0_dp.rows() == patch_size);
MatrixXd dr_dp = dI0_dp.array().colwise() * dr_dI0.array();
MatrixXd dr_dp_sum = dr_dp.colwise().sum();
VectorXd d2r_dI02 = -2 * dr_dI0.array() / (1 + I0.array());
MatrixXd dr_dp2 = (dI0_dp.array().colwise() * (d2r_dI02.array()*df_dr.array()).array()).colwise().sum();
d2f_dp2 =
-(
(
(dr_dp.transpose() * dr_dp * r_mean_inv)
-
(dr_dp.transpose() * r * dr_dp_sum) * (N_inv*r_mean_inv*r_mean_inv)
) * 2
-
(
dr_dp_sum.transpose()*
((df_dr.array() - (f * r_mean_inv * N_inv)).matrix().transpose())
* dr_dp * r_mean_inv * N_inv
)
) * N_inv
+
dr_dp2.transpose() * dr_dp2;
}
void RIU::cmptInitHessian(MatrixXd &d2f_dp2, const MatrixXd &dI0_dp,
const MatrixXd &d2I0_dp2){
int p_size = static_cast<int>(d2f_dp2.rows());
assert(d2f_dp2.cols() == p_size);
assert(d2I0_dp2.rows() == p_size * p_size);
cmptInitHessian(d2f_dp2, dI0_dp);
for(unsigned int patch_id = 0; patch_id < patch_size; ++patch_id){
d2f_dp2 += Map<const MatrixXd>(d2I0_dp2.col(patch_id).data(), p_size, p_size) * df_dI0(patch_id);;
}
}
void RIU::cmptCurrHessian(MatrixXd &d2f_dp2, const MatrixXd &dIt_dp){
assert(d2f_dp2.cols() == d2f_dp2.rows());
//mtf_clock_get(d2f_dp2_start);
MatrixXd dr_dp = dIt_dp.array().colwise() * dr_dIt.array();
MatrixXd dr_dp_sum = dr_dp.colwise().sum();
d2f_dp2 =
-(
(
(dr_dp.transpose() * dr_dp * r_mean_inv)
-
(dr_dp.transpose() * r * dr_dp_sum) * (N_inv*r_mean_inv*r_mean_inv)
) * 2
-
(
dr_dp_sum.transpose()*
((df_dr.array() - (f * r_mean_inv * N_inv)).matrix().transpose())
* dr_dp * r_mean_inv * N_inv
)
) * N_inv;
//mtf_clock_get(d2f_dp2_end);
/*
mtf_clock_get(d2f_dp2_2_start);
MatrixXd d2f_dp2_2 = -dIt_dp.transpose() *
(
(
(
(
(
(MatrixXd::Identity(patch_size, patch_size)*r_mean_inv).colwise()
-
(r * (N_inv*r_mean_inv*r_mean_inv))
) * 2
).rowwise()
-
(
(df_dr.array() - (f * r_mean_inv * N_inv))*r_mean_inv * N_inv
).matrix().transpose()
) * N_inv
).array().rowwise()
*
(dr_dIt.array()*dr_dIt.array()).transpose()
).matrix()
*dIt_dp;
mtf_clock_get(d2f_dp2_2_end);
double d2f_dp2_time, d2f_dp2_2_time;
mtf_clock_measure(d2f_dp2_start, d2f_dp2_end, d2f_dp2_time);
mtf_clock_measure(d2f_dp2_2_start, d2f_dp2_2_end, d2f_dp2_2_time);
utils::printScalar(d2f_dp2_time, "d2f_dp2_time");
utils::printScalar(d2f_dp2_2_time, "d2f_dp2_2_time");
utils::printScalar(d2f_dp2_time / d2f_dp2_2_time, "d2f_dp2_speedup");
MatrixXd d2f_dp2_diff = d2f_dp2_2 - d2f_dp2;
utils::printMatrix(d2f_dp2, "d2f_dp2");
utils::printMatrix(d2f_dp2_2, "d2f_dp2_2");
utils::printMatrix(d2f_dp2_diff, "d2f_dp2_diff");
*/
}
void RIU::cmptCurrHessian(MatrixXd &d2f_dp2, const MatrixXd &dIt_dp,
const MatrixXd &d2It_dp2){
int p_size = static_cast<int>(d2f_dp2.rows());
assert(d2f_dp2.cols() == p_size);
assert(d2It_dp2.rows() == p_size * p_size);
cmptCurrHessian(d2f_dp2, dIt_dp);
for(unsigned int patch_id = 0; patch_id < patch_size; ++patch_id){
d2f_dp2 += Map<const MatrixXd>(d2It_dp2.col(patch_id).data(), p_size, p_size) * df_dIt(patch_id);
}
//utils::printMatrix(curr_hessian, "second order curr_hessian");
}
void RIU::cmptSelfHessian(MatrixXd &d2f_dp2, const MatrixXd &dIt_dp){
assert(d2f_dp2.cols() == d2f_dp2.rows());
MatrixXd dr_dp = dIt_dp.array().colwise() * dr_dIt.array();
MatrixXd dr_dp_sum = dr_dp.colwise().sum();
d2f_dp2 =
-(
(dr_dp.transpose() * dr_dp)
-
(dr_dp_sum.transpose() * dr_dp_sum) * N_inv
) * 2 * N_inv;
}
void RIU::cmptSelfHessian(MatrixXd &self_hessian, const MatrixXd &curr_pix_jacobian,
const MatrixXd &curr_pix_hessian){
cmptSelfHessian(self_hessian, curr_pix_jacobian);
}
double RIUDist::operator()(const double* a, const double* b, size_t size, double worst_dist) const{
assert(size == patch_size + 1);
const double* _I0, *_It;
if(a[0] == 1){
_I0 = a + 1;
_It = b + 1;
} else{
_I0 = b + 1;
_It = a + 1;
}
VectorXd _r = Map<const VectorXd>(_It, size - 1).array() / Map<const VectorXd>(_I0, size - 1).array();
double _r_mean = _r.mean();
double dist = ((_r.array() - _r_mean).matrix().squaredNorm() / size) / (_r_mean);
return dist_from_likelihood ?
-exp(-likelihood_alpha * dist) : dist;
}
void RIU::updateDistFeat(double* feat_addr){
*feat_addr++ = 0;
for(size_t pix_id = 0; pix_id < patch_size; ++pix_id) {
*feat_addr++ = 1 + It(pix_id);
}
}
_MTF_END_NAMESPACE
| 28.654762 | 106 | 0.669298 | abhineet123 |
596ac4018597865c6d6e8b2cbd87f16bc348d44d | 270 | cpp | C++ | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_FlexFluidSurface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_FlexFluidSurface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_FlexFluidSurface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2013 Epic Games, Inc. All Rights Reserved.
#include "AssetTypeActions_FlexFluidSurface.h"
#include "PhysicsEngine/FlexFluidSurface.h"
UClass* FAssetTypeActions_FlexFluidSurface::GetSupportedClass() const
{
return UFlexFluidSurface::StaticClass();
} | 27 | 69 | 0.814815 | windystrife |
596bfcad01e09452c583978a1d27a05ccbbf5426 | 6,098 | cpp | C++ | src/cge/cge/ws_server.cpp | UMU618/liuguang | 3a5e9db8dad759c30b307223c85e0a01f09a88bd | [
"Apache-2.0"
] | 2 | 2021-08-07T10:49:17.000Z | 2022-03-30T06:40:12.000Z | src/cge/cge/ws_server.cpp | sdgdsffdsfff/liuguang | 3ec7d3c9f9fd75fa614009a99c4ecdd08ff321bc | [
"Apache-2.0"
] | null | null | null | src/cge/cge/ws_server.cpp | sdgdsffdsfff/liuguang | 3ec7d3c9f9fd75fa614009a99c4ecdd08ff321bc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020-present Ksyun
*
* 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 "pch.h"
#include "ws_server.h"
struct ProtocolHeader {
uint32_t type : 8;
uint32_t ts : 24;
uint32_t size;
float elapsed;
};
namespace {
inline void ListenerFail(beast::error_code ec, std::string_view what) {
std::cerr << "WsListener# " << what << ": " << ec.message() << '\n';
}
inline void ListenerFail(beast::error_code ec,
const tcp::endpoint& endpoint,
std::string_view what) {
std::cerr << "WsListener# " << endpoint << " " << what << ": " << ec.message()
<< '\n';
}
inline void SessionFail(beast::error_code ec,
const tcp::endpoint& endpoint,
std::string_view what) {
std::cerr << "WsSession# " << endpoint << " " << what << ": "
<< "(#" << ec.value() << ')' << ec.message() << '\n';
}
} // namespace
#pragma region "WsServer"
WsServer::WsServer(Engine& engine, const tcp::endpoint& endpoint) noexcept
: engine_(engine), acceptor_(engine.GetIoContext()) {
beast::error_code ec;
if (acceptor_.open(endpoint.protocol(), ec)) {
ListenerFail(ec, "open");
return;
}
if (acceptor_.set_option(net::socket_base::reuse_address(true), ec)) {
ListenerFail(ec, "set_option");
return;
}
if (acceptor_.bind(endpoint, ec)) {
ListenerFail(ec, "bind");
return;
}
if (acceptor_.listen(net::socket_base::max_listen_connections, ec)) {
ListenerFail(ec, "listen");
return;
}
}
bool WsServer::Join(std::shared_ptr<WsSession> session) noexcept {
bool inserted = false;
bool first = false;
{
std::lock_guard<std::mutex> lock(session_mutex_);
first = sessions_.size() == 0;
if (first) {
sessions_.insert(session);
inserted = true;
}
}
if (first) {
engine_.EncoderRun();
} else {
// Only one websocket client
session->Stop();
}
return inserted;
}
void WsServer::Leave(std::shared_ptr<WsSession> session) noexcept {
bool last = false;
{
std::lock_guard<std::mutex> lock(session_mutex_);
if (sessions_.erase(session) > 0) {
last = sessions_.size() == 0;
}
}
if (last) {
engine_.EncoderStop();
}
}
size_t WsServer::Send(std::string&& buffer) {
std::lock_guard<std::mutex> lock(session_mutex_);
for (const auto& session : sessions_) {
// Only one websocket client
session->Write(std::move(buffer));
return 1;
}
return 0;
}
void WsServer::OnAccept(beast::error_code ec, tcp::socket socket) {
if (ec) {
return ListenerFail(ec, socket.remote_endpoint(), "accept");
}
std::cout << "Accept " << socket.remote_endpoint() << '\n';
socket.set_option(tcp::no_delay(true));
std::make_shared<WsSession>(std::move(socket), shared_from_this())->Run();
Accept();
}
#pragma endregion
#pragma region "WsSession"
void WsSession::OnRun() {
ws_.set_option(
websocket::stream_base::timeout::suggested(beast::role_type::server));
ws_.set_option(
websocket::stream_base::decorator([](websocket::response_type& res) {
res.set(http::field::sec_websocket_protocol, "webgame");
}));
ws_.async_accept(
beast::bind_front_handler(&WsSession::OnAccept, shared_from_this()));
}
void WsSession::Stop() {
if (ws_.is_open()) {
std::cout << "Closing " << ws_.next_layer().socket().remote_endpoint()
<< '\n';
ws_.async_close(
websocket::close_reason(websocket::close_code::try_again_later),
beast::bind_front_handler(&WsSession::OnAccept, shared_from_this()));
}
}
void WsSession::Write(std::string&& buffer) {
std::lock_guard<std::mutex> lock(queue_mutex_);
write_queue_.emplace(buffer);
if (write_queue_.size() > 1) {
return;
}
ws_.async_write(
net::buffer(write_queue_.front()),
beast::bind_front_handler(&WsSession::OnWrite, shared_from_this()));
}
void WsSession::OnAccept(beast::error_code ec) {
if (ec == websocket::error::closed) {
std::cout << "Close " << ws_.next_layer().socket().remote_endpoint()
<< '\n';
return;
}
if (ec) {
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(),
"accept");
}
if (!server_->Join(shared_from_this())) {
return;
}
#if _DEBUG
std::cout << __func__ << "\n";
#endif
// Write("Hello world!");
Read();
}
void WsSession::OnStop(beast::error_code ec) {
server_->Leave(shared_from_this());
}
void WsSession::OnRead(beast::error_code ec, std::size_t bytes_transferred) {
if (ec) {
server_->Leave(shared_from_this());
if (ec == websocket::error::closed) {
return;
}
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(), "read");
}
#if _DEBUG
std::cout << __func__ << ": " << bytes_transferred << '\n';
#endif
Read();
}
void WsSession::OnWrite(beast::error_code ec, std::size_t bytes_transferred) {
if (ec) {
server_->Leave(shared_from_this());
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(),
"write");
}
#if _DEBUG
if (bytes_transferred != write_queue_.front().size()) {
std::cout << "bytes_transferred: " << bytes_transferred
<< ", size: " << write_queue_.front().size() << '\n';
}
#endif
std::lock_guard<std::mutex> lock(queue_mutex_);
write_queue_.pop();
if (!write_queue_.empty()) {
ws_.async_write(
net::buffer(write_queue_.front()),
beast::bind_front_handler(&WsSession::OnWrite, shared_from_this()));
}
}
#pragma endregion
| 26.171674 | 80 | 0.631519 | UMU618 |
596fd110d5a9c88cd5826fa13c024440585ffc5c | 4,050 | cc | C++ | vowpalwabbit/config/options.cc | hex-plex/AutoMLScreenExercise | 93a58e496f584bcc4cb35b8d6280d11605a695d6 | [
"BSD-3-Clause"
] | 1 | 2015-11-12T06:11:44.000Z | 2015-11-12T06:11:44.000Z | vowpalwabbit/config/options.cc | chrinide/vowpal_wabbit | 40e1fef676ca6a461d71cf0631ab5c63d1af5d8a | [
"BSD-3-Clause"
] | null | null | null | vowpalwabbit/config/options.cc | chrinide/vowpal_wabbit | 40e1fef676ca6a461d71cf0631ab5c63d1af5d8a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.
#include "config/options.h"
#include "config/option_group_definition.h"
#include "config/option.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <stdexcept>
#include <utility>
using namespace VW::config;
std::vector<std::shared_ptr<base_option>> options_i::get_all_options()
{
std::vector<std::shared_ptr<base_option>> output_values;
std::transform(m_options.begin(), m_options.end(), std::back_inserter(output_values),
[](std::pair<const std::string, std::shared_ptr<base_option>>& kv) { return kv.second; });
return output_values;
}
std::vector<std::shared_ptr<const base_option>> VW::config::options_i::get_all_options() const
{
std::vector<std::shared_ptr<const base_option>> output_values;
output_values.reserve(m_options.size());
for (const auto& kv : m_options) { output_values.push_back(kv.second); }
return output_values;
}
// This function is called by both the const and non-const version. The const version will implicitly upgrade the
// shared_ptr to const
std::shared_ptr<base_option> internal_get_option(
const std::string& key, const std::map<std::string, std::shared_ptr<VW::config::base_option>>& options)
{
auto it = options.find(key);
if (it != options.end()) { return it->second; }
throw std::out_of_range(key + " was not found.");
}
std::shared_ptr<base_option> VW::config::options_i::get_option(const std::string& key)
{
return internal_get_option(key, m_options);
}
std::shared_ptr<const base_option> VW::config::options_i::get_option(const std::string& key) const
{
// shared_ptr can implicitly upgrade to const from non-const
return internal_get_option(key, m_options);
}
void options_i::add_and_parse(const option_group_definition& group)
{
// Add known options before parsing so impl can make use of them.
m_option_group_definitions.push_back(group);
m_option_group_dic[m_current_reduction_tint].push_back(group);
for (const auto& option : group.m_options)
{
// The last definition is kept. There was a bug where using .insert at a later pointer changed the command line but
// the previously defined option's default value was serialized into the model. This resolves that state info.
m_options[option->m_name] = option;
if (!option->m_short_name.empty())
{
assert(option->m_short_name.size() == 1);
m_short_options[option->m_short_name[0]] = option;
}
}
internal_add_and_parse(group);
group.check_one_of();
}
bool options_i::add_parse_and_check_necessary(const option_group_definition& group)
{
// Add known options before parsing so impl can make use of them.
m_option_group_definitions.push_back(group);
m_option_group_dic[m_current_reduction_tint].push_back(group);
for (const auto& option : group.m_options)
{
// The last definition is kept. There was a bug where using .insert at a later pointer changed the command line but
// the previously defined option's default value was serialized into the model. This resolves that state info.
m_options[option->m_name] = option;
if (!option->m_short_name.empty())
{
assert(option->m_short_name.size() == 1);
m_short_options[option->m_short_name[0]] = option;
}
}
internal_add_and_parse(group);
auto necessary_enabled = group.check_necessary_enabled(*this);
if (necessary_enabled) { group.check_one_of(); }
return necessary_enabled;
}
void options_i::tint(const std::string& reduction_name) { m_current_reduction_tint = reduction_name; }
void options_i::reset_tint() { m_current_reduction_tint = m_default_tint; }
std::map<std::string, std::vector<option_group_definition>> options_i::get_collection_of_options() const
{
return m_option_group_dic;
}
const std::vector<option_group_definition>& options_i::get_all_option_group_definitions() const
{
return m_option_group_definitions;
}
| 34.913793 | 119 | 0.747407 | hex-plex |
5972d8993df633d4bca13453a18a81bfe662bc06 | 2,569 | hpp | C++ | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | 8 | 2017-06-06T19:55:20.000Z | 2021-11-14T16:55:43.000Z | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | null | null | null | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | 4 | 2017-08-03T18:06:18.000Z | 2021-06-23T18:22:23.000Z | // Kevin Angstadt
// angstadt {at} umich.edu
//
// MNRLUpCounter Object
#ifndef MNRLUPCOUNTER_HPP
#define MNRLUPCOUNTER_HPP
#include <string>
#include <utility>
#include <vector>
#include <map>
#include "MNRLDefs.hpp"
#include "MNRLNode.hpp"
#include "MNRLReportId.hpp"
namespace MNRL {
class MNRLUpCounter : public MNRLNode {
public:
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
int reportId,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportIdInt(reportId)) {}
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
std::string reportId,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportIdString(reportId)) {}
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportId()) {}
virtual ~MNRLUpCounter() {
delete reportId;
reportId = nullptr;
}
virtual MNRLDefs::NodeType getNodeType() { return MNRLDefs::NodeType::UPCOUNTER; }
MNRLReportId *getReportId() { return reportId; }
void setReportId(std::string &id) {
delete reportId;
reportId = nullptr;
reportId = new MNRLReportIdString(id);
}
void setReportId(int id) {
delete reportId;
reportId = nullptr;
reportId = new MNRLReportIdInt(id);
}
MNRLDefs::CounterMode getMode() { return mode; }
void setMode(MNRLDefs::CounterMode m) { mode = m; }
int getThreshold() { return threshold; }
void setThreshold(int t) { threshold = t; }
protected:
int threshold;
MNRLDefs::CounterMode mode;
MNRLReportId *reportId;
private:
static port_def gen_input() {
port_def in;
in.emplace_back(
MNRLDefs::UP_COUNTER_COUNT,
1
);
in.emplace_back(
MNRLDefs::UP_COUNTER_RESET,
1
);
return in;
}
static port_def gen_output() {
port_def outs;
outs.emplace_back(
MNRLDefs::UP_COUNTER_OUTPUT,
1
);
return outs;
}
};
}
#endif
| 20.070313 | 84 | 0.668743 | tjt7a |
597309c27f9b3bfb03eb3e308f90e84dbc6841cb | 5,704 | cpp | C++ | oshgui/Drawing/OpenGL/OpenGLTextureTarget.cpp | sdkabuser/DEADCELL-CSGO | dfcd31394c5348529b3c098640466db136b89e0c | [
"MIT"
] | 506 | 2019-03-16T08:34:47.000Z | 2022-03-29T14:08:59.000Z | OSHGui/Drawing/OpenGL/OpenGLTextureTarget.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 124 | 2019-03-17T02:54:57.000Z | 2021-03-29T01:51:05.000Z | OSHGui/Drawing/OpenGL/OpenGLTextureTarget.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 219 | 2019-03-16T21:39:01.000Z | 2022-03-30T08:59:24.000Z | #include <GL/glew.h>
#include "OpenGLTextureTarget.hpp"
#include "OpenGLRenderer.hpp"
#include "OpenGLTexture.hpp"
namespace OSHGui
{
namespace Drawing
{
const float OpenGLTextureTarget::DefaultSize = 128.0f;
//---------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------
OpenGLTextureTarget::OpenGLTextureTarget(OpenGLRenderer &owner)
: OpenGLRenderTarget<TextureTarget>(owner)
{
if (!GLEW_EXT_framebuffer_object)
{
throw;
}
CreateTexture();
InitialiseRenderTexture();
DeclareRenderSize(SizeF(DefaultSize, DefaultSize));
}
//---------------------------------------------------------------------------
OpenGLTextureTarget::~OpenGLTextureTarget()
{
glDeleteFramebuffersEXT(1, &frameBuffer);
}
//---------------------------------------------------------------------------
//Getter/Setter
//---------------------------------------------------------------------------
void OpenGLTextureTarget::DeclareRenderSize(const SizeF &size)
{
if (area.GetWidth() >= size.Width && area.GetHeight() >= size.Height)
{
return;
}
SetArea(RectangleF(area.GetLocation(), owner.GetAdjustedSize(size)));
ResizeRenderTexture();
Clear();
}
//---------------------------------------------------------------------------
bool OpenGLTextureTarget::IsImageryCache() const
{
return true;
}
//---------------------------------------------------------------------------
TexturePtr OpenGLTextureTarget::GetTexture() const
{
return oglTexture;
}
//---------------------------------------------------------------------------
bool OpenGLTextureTarget::IsRenderingInverted() const
{
return true;
}
//---------------------------------------------------------------------------
//Runtime-Functions
//---------------------------------------------------------------------------
void OpenGLTextureTarget::CreateTexture()
{
oglTexture = std::static_pointer_cast<OpenGLTexture>(owner.CreateTexture());
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Activate()
{
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFrameBuffer));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
OpenGLRenderTarget::Activate();
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Deactivate()
{
OpenGLRenderTarget::Deactivate();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFrameBuffer);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Clear()
{
if (area.GetWidth() < 1 || area.GetHeight() < 1)
{
return;
}
GLfloat oldColor[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, oldColor);
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFBO));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
glClearColor(oldColor[0], oldColor[1], oldColor[2], oldColor[3]);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::InitialiseRenderTexture()
{
GLuint oldTexture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&oldTexture));
glGenFramebuffersEXT(1, &frameBuffer);
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFBO));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(DefaultSize), static_cast<GLsizei>(DefaultSize), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
oglTexture->SetOpenGLTexture(texture);
oglTexture->SetOriginalDataSize(area.GetSize());
glBindTexture(GL_TEXTURE_2D, oldTexture);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::ResizeRenderTexture()
{
GLuint oldTexture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&oldTexture));
auto sz = area.GetSize();
if (sz.Width < 1.0f || sz.Height < 1.0f)
{
sz.Width = 1.0f;
sz.Height = 1.0f;
}
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(sz.Width), static_cast<GLsizei>(sz.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
Clear();
oglTexture->SetOpenGLTexture(texture);
oglTexture->SetOriginalDataSize(sz);
glBindTexture(GL_TEXTURE_2D, oldTexture);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::PreReset()
{
glDeleteFramebuffersEXT(1, &frameBuffer);
frameBuffer = 0;
if (oglTexture)
{
texture = 0;
oglTexture = nullptr;
}
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::PostReset()
{
if (!oglTexture)
{
CreateTexture();
}
InitialiseRenderTexture();
ResizeRenderTexture();
}
//---------------------------------------------------------------------------
}
}
| 31.340659 | 147 | 0.545757 | sdkabuser |
5974fed636c0a02c58a934726bf158382caf7559 | 217 | cc | C++ | test/abc054/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | test/abc054/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | test/abc054/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | #include "abc054/c.cc"
#include <gtest/gtest.h>
TEST(abc054c, 1) { EXPECT_EQ(2, solve(3, 3, {1, 1, 2}, {2, 3, 3})); }
TEST(abc054c, 2) {
EXPECT_EQ(1, solve(7, 7, {1, 2, 3, 4, 4, 5, 6}, {3, 7, 4, 5, 6, 6, 7}));
} | 27.125 | 76 | 0.516129 | nryotaro |
59750edab218c7f631701ce0951495019527e4b2 | 515 | cpp | C++ | RCBigCar/catkin_ws/src/rcbigcar/src/robot/robot.cpp | HisenZhang/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 17 | 2019-07-30T01:49:40.000Z | 2021-05-13T09:17:23.000Z | RCBigCar/catkin_ws/src/rcbigcar/src/robot/robot.cpp | HisenZhang/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 1 | 2019-08-01T10:07:12.000Z | 2019-08-02T05:39:17.000Z | RCBigCar/catkin_ws/src/rcbigcar/src/robot/robot.cpp | QiayuanLiao/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 5 | 2019-07-27T05:46:36.000Z | 2021-03-15T13:00:17.000Z | #include "chassis.h"
#include "motion.h"
#include "hardware.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "robot");
ros::NodeHandle nh;
//Create Nodes
Chassis chassis;
Motion motion;
ros::Rate loop_rate(ROBOT_SAMPLING_RATE);
//Process Jobs
while (ros::ok())
{
//Update Subnodes
chassis.update();
motion.update();
//Update Hardware
Hardware()->update();
//Spin
ros::spinOnce();
loop_rate.sleep();
}
//Release Nodes
//Release Hardware
ReleaseHardware();
return 0;
} | 13.918919 | 42 | 0.660194 | HisenZhang |
5977d1a87bc57855ebb41ce8f61020187a7eaf3e | 2,064 | hpp | C++ | modules/core/euler/include/nt2/toolbox/euler/functions/simd/common/beta.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/core/euler/include/nt2/toolbox/euler/functions/simd/common/beta.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | modules/core/euler/include/nt2/toolbox/euler/functions/simd/common/beta.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_EULER_FUNCTIONS_SIMD_COMMON_BETA_HPP_INCLUDED
#define NT2_TOOLBOX_EULER_FUNCTIONS_SIMD_COMMON_BETA_HPP_INCLUDED
#include <nt2/toolbox/euler/functions/beta.hpp>
#include <nt2/sdk/meta/as_floating.hpp>
#include <nt2/sdk/simd/meta/is_real_convertible.hpp>
#include <nt2/include/functions/simd/signgam.hpp>
#include <nt2/include/functions/simd/gammaln.hpp>
#include <nt2/include/functions/simd/exp.hpp>
#include <nt2/include/functions/simd/tofloat.hpp>
/**
* \ingroup euler_beta
* \defgroup euler_beta_simd Notes on the SIMD implementation
*
* \par Specificities
*
* Some info on \c beta in SIMD mode
**/
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::beta_, tag::cpu_
, (A0)(X)
, ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))
)
{
typedef typename meta::as_floating<A0>::type result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
return nt2::beta(tofloat(a0), tofloat(a1));
}
};
} }
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::beta_, tag::cpu_
, (A0)(X)
, ((simd_<floating_<A0>,X>))((simd_<floating_<A0>,X>))
)
{
typedef typename meta::as_floating<A0>::type result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
const A0 y = a0+a1;
const A0 sign = signgam(a0)*signgam(a1)*signgam(y);
return sign*exp(gammaln(a0)+gammaln(a1)-gammaln(y));
}
};
} }
#endif
| 30.352941 | 86 | 0.57655 | timblechmann |
597813da472a1863f0d0b6aec8459c7d41afd534 | 635 | hpp | C++ | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | //
// LocalizedNrField.hpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 3/14/20.
// Copyright © 2020 Kuangdai Leng. All rights reserved.
//
// base class of Nr(s,z)
#ifndef LocalizedNrFieldPointwise_hpp
#define LocalizedNrFieldPointwise_hpp
#include "LocalizedNrField.hpp"
class LocalizedNr;
class LocalizedNrFieldPointwise: public LocalizedNrField {
public:
LocalizedNrFieldPointwise(const std::string &fname, double distTol);
// get nr by (s, z)
LocalizedNr getWindowsAtPoint(const eigen::DCol2 &sz) const;
// verbose
std::string verbose() const;
};
#endif /* LocalizedNrFieldPointwise_hpp */
| 21.166667 | 72 | 0.724409 | chaindl |
597c6b9aef5891ec0d6aa64ea1d757e469d937b7 | 471 | cxx | C++ | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | /**
* @file scene.cxx
* @desc Base game scene module.
*/
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include "../game.hxx"
#include "scene.hxx"
Scene::~Scene()
{
SDL_Log("Scene::~Scene()");
}
Scene::Scene()
{
SDL_Log("Scene::Scene()");
}
bool Scene::handleKey(SDL_KeyboardEvent key)
{
SDL_Log("Scene::handleKey(%d)", key.keysym.sym);
return false;
}
void Scene::render(int timeUsed)
{
}
| 14.71875 | 50 | 0.609342 | taworn |
597e456dd8a740b5558ada162f9383e1901c4f31 | 506 | hpp | C++ | module-services/service-bluetooth/service-bluetooth/ServiceBluetoothCommon.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 1 | 2021-11-11T22:56:43.000Z | 2021-11-11T22:56:43.000Z | module-services/service-bluetooth/service-bluetooth/ServiceBluetoothCommon.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | null | null | null | module-services/service-bluetooth/service-bluetooth/ServiceBluetoothCommon.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <Bluetooth/Device.hpp>
#include <FreeRTOS.h>
#include <queue.h>
class BluetoothStreamData
{
public:
QueueHandle_t in = nullptr;
QueueHandle_t out = nullptr;
DeviceMetadata_t metadata;
BluetoothStreamData(QueueHandle_t in, QueueHandle_t out, DeviceMetadata_t metadata)
: in(in), out(out), metadata(metadata)
{}
};
| 24.095238 | 87 | 0.713439 | bitigchi |
59884bc98e70f934e01505b0567b684f1bd99435 | 1,027 | cpp | C++ | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | #include "fifo.h"
namespace mardev::rfm69
{
void read_fifo(uint8_t* const buffer)
{
uint8_t i = 0;
while(!fifo_is_empty())
{
buffer[i++] = read(registers::FIFO);
}
return;
}
uint8_t read_fifo(uint8_t* const buffer,
const uint8_t max_bytes)
{
uint8_t i = 0;
while(!fifo_is_empty() && i < max_bytes)
{
buffer[i++] = read(registers::FIFO);
}
return i;
}
uint8_t write_fifo(const uint8_t* const buffer,
const uint8_t size)
{
// Limit for the library is at 66 bytes (at least for now).
if (size > 66)
return 1;
// FIFO full
if (read(registers::IRQFlags2) & 128)
return 2;
// TODO: turn this into a single burst-write.
uint8_t i = 0;
while(i < size && !(read(registers::IRQFlags2) & 128))
write(registers::FIFO, buffer[i++]);
return 0;
}
}
| 21.851064 | 67 | 0.493671 | mdclyburn |
598a89796869177762430ea15e462818ece7f367 | 2,315 | cc | C++ | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 349 | 2017-11-15T22:51:00.000Z | 2022-03-21T13:43:57.000Z | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 12 | 2018-08-28T21:38:29.000Z | 2021-12-11T16:24:36.000Z | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 28 | 2018-06-10T07:31:13.000Z | 2022-03-21T10:54:26.000Z | #include "record.h"
#include "nes/joy/controllers/standard.h"
#include <cassert>
#include <cstdio>
#include <cstring>
FM2_Record::~FM2_Record() {
if (this->own_file) fclose(this->file);
}
FM2_Record::FM2_Record() {
memset(&this->joy, 0, sizeof this->joy);
this->own_file = false;
this->file = nullptr;
this->enabled = false;
this->frame = 0;
}
bool FM2_Record::init(const char* filename, bool binary) {
(void)binary; // TODO: support fm2 binary format
this->own_file = false;
this->file = fopen(filename, "w");
this->enabled = bool(this->file);
return this->enabled;
}
bool FM2_Record::init(FILE* file, bool binary) {
(void)binary; // TODO: support fm2 binary format
this->own_file = false;
this->file = file;
this->enabled = bool(this->file);
return this->enabled;
}
void FM2_Record::set_joy(uint port, FM2_Controller::Type type, Memory* joy) {
assert(port < 3);
this->joy[port].type = type;
this->joy[port]._mem = joy;
}
bool FM2_Record::is_enabled() const { return this->enabled; }
void FM2_Record::output_header() {
// Output fm2 header
for (uint port = 0; port < 3; port++) {
fprintf(this->file, "port%u %u\n",
port,
uint(this->joy[port].type)
);
}
}
void FM2_Record::step_frame() {
if (this->frame == 0) {
this->output_header();
}
// Output control signal
fprintf(this->file, "|%d", 0); // TODO: implement me
// Output Controller Status
for (uint port = 0; port < 3; port++) {
switch (this->joy[port].type) {
case FM2_Controller::SI_NONE: {
fprintf(this->file, "|");
} break;
case FM2_Controller::SI_GAMEPAD: {
using namespace JOY_Standard_Button;
char buf [9];
buf[8] = '\0';
#define OUTPUT(i, btn, c) \
buf[i] = this->joy[port].standard->get_button(btn) ? c : '.';
OUTPUT(0, Right, 'R');
OUTPUT(1, Left, 'L');
OUTPUT(2, Down, 'D');
OUTPUT(3, Up, 'U');
OUTPUT(4, Start, 'T');
OUTPUT(5, Select, 'S');
OUTPUT(6, B, 'B');
OUTPUT(7, A, 'A');
#undef OUTPUT
fprintf(this->file, "|%s", buf);
} break;
}
// case FM2_Controller::SI_ZAPPER: {
// using namespace JOY_Zapper_Button;
// } break;
}
fprintf(this->file, "\n");
this->frame++;
}
| 21.635514 | 77 | 0.587473 | MrKOSMOS |
598cb943f49e7820c093702f53cadd5b459ca336 | 20 | cpp | C++ | dev/cmake-3.5.1/Tests/CompileFeatures/cxx_final.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | dev/cmake-3.5.1/Tests/CompileFeatures/cxx_final.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | dev/cmake-3.5.1/Tests/CompileFeatures/cxx_final.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 1 | 2020-11-04T04:56:50.000Z | 2020-11-04T04:56:50.000Z |
struct A final {};
| 6.666667 | 18 | 0.6 | hlzz |
5991715fffaf08c76cdd149c62840668c4833544 | 415 | cpp | C++ | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 12 | 2016-09-21T19:07:13.000Z | 2021-12-13T06:17:36.000Z | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 3 | 2020-11-09T08:25:40.000Z | 2021-04-12T10:49:39.000Z | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 12 | 2018-06-10T10:52:56.000Z | 2020-12-08T15:47:13.000Z | //
// Created by dupes on 12/9/15.
//
#include "JobSlow.h"
JobSlow::JobSlow(MockGlobalTime *globalTime) :
m_globalTime(globalTime)
{
}
/********************************************************************************/
JobSlow::~JobSlow()
{
}
/********************************************************************************/
void JobSlow::execute(time_t now)
{
m_globalTime->setNow(now + 200);
}
| 16.6 | 82 | 0.387952 | beroset |
5994bed3e95118faac90f3ec2805a4bcfa1333d4 | 10,237 | cc | C++ | android/art/runtime/dexopt_test.cc | Solotov/deoptfuscator | 8a54119e81517bcef73d2d6dfefba910ae2446e7 | [
"MIT"
] | 206 | 2020-04-13T03:19:33.000Z | 2022-03-27T13:52:25.000Z | android/art/runtime/dexopt_test.cc | Solotov/deoptfuscator | 8a54119e81517bcef73d2d6dfefba910ae2446e7 | [
"MIT"
] | 9 | 2020-06-07T12:51:09.000Z | 2022-03-28T23:55:09.000Z | android/art/runtime/dexopt_test.cc | Solotov/deoptfuscator | 8a54119e81517bcef73d2d6dfefba910ae2446e7 | [
"MIT"
] | 42 | 2020-04-13T03:37:58.000Z | 2022-03-23T15:08:12.000Z | /*
* Copyright (C) 2017 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.
*/
#include <string>
#include <vector>
#include <backtrace/BacktraceMap.h>
#include <gtest/gtest.h>
#include "base/file_utils.h"
#include "common_runtime_test.h"
#include "compiler_callbacks.h"
#include "dex2oat_environment_test.h"
#include "dexopt_test.h"
#include "gc/space/image_space.h"
#include "mem_map.h"
namespace art {
void DexoptTest::SetUp() {
ReserveImageSpace();
Dex2oatEnvironmentTest::SetUp();
}
void DexoptTest::PreRuntimeCreate() {
std::string error_msg;
ASSERT_TRUE(PreRelocateImage(GetImageLocation(), &error_msg)) << error_msg;
ASSERT_TRUE(PreRelocateImage(GetImageLocation2(), &error_msg)) << error_msg;
UnreserveImageSpace();
}
void DexoptTest::PostRuntimeCreate() {
ReserveImageSpace();
}
void DexoptTest::GenerateOatForTest(const std::string& dex_location,
const std::string& oat_location_in,
CompilerFilter::Filter filter,
bool relocate,
bool pic,
bool with_alternate_image,
const char* compilation_reason) {
std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(kRuntimeISA));
std::string dalvik_cache_tmp = dalvik_cache + ".redirected";
std::string oat_location = oat_location_in;
if (!relocate) {
// Temporarily redirect the dalvik cache so dex2oat doesn't find the
// relocated image file.
ASSERT_EQ(0, rename(dalvik_cache.c_str(), dalvik_cache_tmp.c_str())) << strerror(errno);
// If the oat location is in dalvik cache, replace the cache path with the temporary one.
size_t pos = oat_location.find(dalvik_cache);
if (pos != std::string::npos) {
oat_location = oat_location.replace(pos, dalvik_cache.length(), dalvik_cache_tmp);
}
}
std::vector<std::string> args;
args.push_back("--dex-file=" + dex_location);
args.push_back("--oat-file=" + oat_location);
args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
args.push_back("--runtime-arg");
// Use -Xnorelocate regardless of the relocate argument.
// We control relocation by redirecting the dalvik cache when needed
// rather than use this flag.
args.push_back("-Xnorelocate");
ScratchFile profile_file;
if (CompilerFilter::DependsOnProfile(filter)) {
args.push_back("--profile-file=" + profile_file.GetFilename());
}
if (pic) {
args.push_back("--compile-pic");
}
std::string image_location = GetImageLocation();
if (with_alternate_image) {
args.push_back("--boot-image=" + GetImageLocation2());
}
if (compilation_reason != nullptr) {
args.push_back("--compilation-reason=" + std::string(compilation_reason));
}
std::string error_msg;
ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, &error_msg)) << error_msg;
if (!relocate) {
// Restore the dalvik cache if needed.
ASSERT_EQ(0, rename(dalvik_cache_tmp.c_str(), dalvik_cache.c_str())) << strerror(errno);
oat_location = oat_location_in;
}
// Verify the odex file was generated as expected.
std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
oat_location.c_str(),
oat_location.c_str(),
nullptr,
nullptr,
false,
/*low_4gb*/false,
dex_location.c_str(),
&error_msg));
ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
EXPECT_EQ(pic, odex_file->IsPic());
EXPECT_EQ(filter, odex_file->GetCompilerFilter());
std::unique_ptr<ImageHeader> image_header(
gc::space::ImageSpace::ReadImageHeader(image_location.c_str(),
kRuntimeISA,
&error_msg));
ASSERT_TRUE(image_header != nullptr) << error_msg;
const OatHeader& oat_header = odex_file->GetOatHeader();
uint32_t combined_checksum = image_header->GetOatChecksum();
if (CompilerFilter::DependsOnImageChecksum(filter)) {
if (with_alternate_image) {
EXPECT_NE(combined_checksum, oat_header.GetImageFileLocationOatChecksum());
} else {
EXPECT_EQ(combined_checksum, oat_header.GetImageFileLocationOatChecksum());
}
}
if (!with_alternate_image) {
if (CompilerFilter::IsAotCompilationEnabled(filter)) {
if (relocate) {
EXPECT_EQ(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()),
oat_header.GetImageFileLocationOatDataBegin());
EXPECT_EQ(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta());
} else {
EXPECT_NE(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()),
oat_header.GetImageFileLocationOatDataBegin());
EXPECT_NE(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta());
}
}
}
}
void DexoptTest::GenerateOdexForTest(const std::string& dex_location,
const std::string& odex_location,
CompilerFilter::Filter filter) {
GenerateOatForTest(dex_location,
odex_location,
filter,
/*relocate*/false,
/*pic*/false,
/*with_alternate_image*/false);
}
void DexoptTest::GeneratePicOdexForTest(const std::string& dex_location,
const std::string& odex_location,
CompilerFilter::Filter filter,
const char* compilation_reason) {
GenerateOatForTest(dex_location,
odex_location,
filter,
/*relocate*/false,
/*pic*/true,
/*with_alternate_image*/false,
compilation_reason);
}
void DexoptTest::GenerateOatForTest(const char* dex_location,
CompilerFilter::Filter filter,
bool relocate,
bool pic,
bool with_alternate_image) {
std::string oat_location;
std::string error_msg;
ASSERT_TRUE(OatFileAssistant::DexLocationToOatFilename(
dex_location, kRuntimeISA, &oat_location, &error_msg)) << error_msg;
GenerateOatForTest(dex_location,
oat_location,
filter,
relocate,
pic,
with_alternate_image);
}
void DexoptTest::GenerateOatForTest(const char* dex_location, CompilerFilter::Filter filter) {
GenerateOatForTest(dex_location,
filter,
/*relocate*/true,
/*pic*/false,
/*with_alternate_image*/false);
}
bool DexoptTest::PreRelocateImage(const std::string& image_location, std::string* error_msg) {
std::string dalvik_cache;
bool have_android_data;
bool dalvik_cache_exists;
bool is_global_cache;
GetDalvikCache(GetInstructionSetString(kRuntimeISA),
true,
&dalvik_cache,
&have_android_data,
&dalvik_cache_exists,
&is_global_cache);
if (!dalvik_cache_exists) {
*error_msg = "Failed to create dalvik cache";
return false;
}
std::string patchoat = GetAndroidRoot();
patchoat += kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat";
std::vector<std::string> argv;
argv.push_back(patchoat);
argv.push_back("--input-image-location=" + image_location);
argv.push_back("--output-image-directory=" + dalvik_cache);
argv.push_back("--instruction-set=" + std::string(GetInstructionSetString(kRuntimeISA)));
argv.push_back("--base-offset-delta=0x00008000");
return Exec(argv, error_msg);
}
void DexoptTest::ReserveImageSpace() {
MemMap::Init();
// Ensure a chunk of memory is reserved for the image space.
// The reservation_end includes room for the main space that has to come
// right after the image in case of the GSS collector.
uint64_t reservation_start = ART_BASE_ADDRESS;
uint64_t reservation_end = ART_BASE_ADDRESS + 384 * MB;
std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid(), true));
ASSERT_TRUE(map.get() != nullptr) << "Failed to build process map";
for (BacktraceMap::iterator it = map->begin();
reservation_start < reservation_end && it != map->end(); ++it) {
const backtrace_map_t* entry = *it;
ReserveImageSpaceChunk(reservation_start, std::min(entry->start, reservation_end));
reservation_start = std::max(reservation_start, entry->end);
}
ReserveImageSpaceChunk(reservation_start, reservation_end);
}
void DexoptTest::ReserveImageSpaceChunk(uintptr_t start, uintptr_t end) {
if (start < end) {
std::string error_msg;
image_reservation_.push_back(std::unique_ptr<MemMap>(
MemMap::MapAnonymous("image reservation",
reinterpret_cast<uint8_t*>(start), end - start,
PROT_NONE, false, false, &error_msg)));
ASSERT_TRUE(image_reservation_.back().get() != nullptr) << error_msg;
LOG(INFO) << "Reserved space for image " <<
reinterpret_cast<void*>(image_reservation_.back()->Begin()) << "-" <<
reinterpret_cast<void*>(image_reservation_.back()->End());
}
}
void DexoptTest::UnreserveImageSpace() {
image_reservation_.clear();
}
} // namespace art
| 38.197761 | 94 | 0.628602 | Solotov |
599d7e77ca79c5ac86e19294bb7d38d370ac092c | 135 | cpp | C++ | Problems/AtCoder/Contests/Beginner_Contests/Contest_180/A.Box.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/AtCoder/Contests/Beginner_Contests/Contest_180/A.Box.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/AtCoder/Contests/Beginner_Contests/Contest_180/A.Box.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n,a,b;
int main() {
scanf("%d%d%d",&n,&a,&b);
printf("%d\n",n-a+b);
return 0;
}
| 12.272727 | 26 | 0.555556 | metehkaya |
599f874a59e2936cc96c2b27582498ddff6eaaa0 | 2,713 | hpp | C++ | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | //
// Created by Bernardo Clavijo (EI) on 12/05/2018.
//
#ifndef BSG_PAIREDREADMAPPER_HPP
#define BSG_PAIREDREADMAPPER_HPP
#include <map>
#include <fstream>
#include "sglib/types/MappingTypes.hpp"
#include "sglib/factories/KMerIDXFactory.h"
#include "sglib/readers/SequenceGraphReader.h"
#include "sglib/SMR.h"
#include <sglib/datastores/PairedReadsDatastore.hpp>
class PairedReadConnectivityDetail; //Forward declaration
/**
* @brief A mapper for linked reads from a PairedReadsDatastore.
*
* Supports partial remapping of unmapped reads or of a selection list.
*/
class PairedReadMapper {
const SequenceGraph & sg;
public:
PairedReadMapper(SequenceGraph &_sg, PairedReadsDatastore &_datastore) : sg(_sg),datastore(_datastore){
reads_in_node.resize(sg.nodes.size());
};
void write(std::ofstream & output_file);
void read(std::ifstream & input_file);
void map_reads(std::unordered_set<uint64_t> const & reads_to_remap={});
void remap_all_reads();
//void map_read(uint64_t readID);
void remove_obsolete_mappings();
std::vector<uint64_t> size_distribution();
void populate_orientation();
/*void remap_reads();
uint64_t process_reads_from_file(uint8_t, uint16_t, std::unordered_map<uint64_t , graphPosition> &, std::string , uint64_t, bool tags=false, std::unordered_set<uint64_t> const & reads_to_remap={});
void save_to_disk(std::string filename);
void load_from_disk(std::string filename);*/
void print_stats();
PairedReadMapper operator=(const PairedReadMapper &other);
const PairedReadsDatastore & datastore;
std::vector<std::vector<ReadMapping>> reads_in_node;
std::vector<sgNodeID_t> read_to_node;//id of the main node if mapped, set to 0 to remap on next process
//TODO: reading and writing this would simplify things??
std::vector<bool> read_direction_in_node;//0-> fw, 1->rev;
std::vector<uint64_t> rfdist;
std::vector<uint64_t> frdist;
};
/**
* @brief Analysis of all reads connecting two particular nodes.
*/
class PairedReadConnectivityDetail {
public:
PairedReadConnectivityDetail(){};
PairedReadConnectivityDetail(const PairedReadMapper & prm, sgNodeID_t source, sgNodeID_t dest);
PairedReadConnectivityDetail& operator+=(const PairedReadConnectivityDetail& rhs){
this->orientation_paircount[0] += rhs.orientation_paircount[0];
this->orientation_paircount[1] += rhs.orientation_paircount[1];
this->orientation_paircount[2] += rhs.orientation_paircount[2];
this->orientation_paircount[3] += rhs.orientation_paircount[3];
return *this;
}
uint64_t orientation_paircount[4]={0,0,0,0};
};
#endif //BSG_PAIREDREADMAPPER_HPP
| 35.697368 | 201 | 0.736454 | BenJWard |
59a3ed513c38ffda9a70045f8f21852ffc1c77b1 | 2,494 | cpp | C++ | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | 4 | 2015-01-13T09:55:02.000Z | 2016-09-10T03:42:23.000Z | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | null | null | null | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | 2 | 2015-01-22T02:30:29.000Z | 2021-05-10T06:56:49.000Z | #include "mruby_script_engine.h"
namespace cor
{
namespace cocos2dx_mruby_interface
{
struct MrubyScriptEngineItnl
{
CocosRefTable object_table;
mruby_interface::MrubyState mrb;
};
MrubyScriptEngine::MrubyScriptEngine() : itnl(new MrubyScriptEngineItnl())
{
ref_instance_ptr() = this;
itnl->mrb.init();
}
MrubyScriptEngine::~MrubyScriptEngine()
{
}
MrubyScriptEnginePtr& MrubyScriptEngine::ref_instance_ptr()
{
static MrubyScriptEnginePtr instance;
return instance;
}
MrubyScriptEnginePtr MrubyScriptEngine::get_instance()
{
//static MrubyScriptEngine instance;
return ref_instance_ptr();
//return &instance;
}
mruby_interface::MrubyState& MrubyScriptEngine::ref_mrb()
{
return itnl->mrb;
}
CocosRefTable& MrubyScriptEngine::ref_object_table()
{
return itnl->object_table;
}
void MrubyScriptEngine::removeScriptObjectByObject(cocos2d::Ref* obj)
{
auto r = itnl->object_table[obj];
if(auto sp = r.lock())
{
sp->release_ref();
}
itnl->object_table.erase(obj);
}
void MrubyScriptEngine::removeScriptHandler(int handler)
{
}
int MrubyScriptEngine::reallocateScriptHandler(int handler)
{
return 0;
}
int MrubyScriptEngine::executeString(const char* codes)
{
itnl->mrb.load_string(codes);
MrubyRef e = itnl->mrb.get_last_exception();
if(e.test())
{
return 1;
}
return 0;
}
int MrubyScriptEngine::executeScriptFile(const char* filename)
{
return 1;
}
int MrubyScriptEngine::executeGlobalFunction(const char* functionName)
{
return 1;
}
int MrubyScriptEngine::sendEvent(cocos2d::ScriptEvent* evt)
{
return 1;
}
bool MrubyScriptEngine::handleAssert(const char *msg)
{
return false;
}
bool MrubyScriptEngine::parseConfig(ConfigType type, const std::string& str)
{
return false;
}
}
}
| 23.528302 | 84 | 0.526063 | rmake |
59a615de4ac81e6f0bd3c62c23e17755753754cd | 3,119 | cpp | C++ | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | #include "system.hpp"
#include <iostream>
#define ARCH_X86 "x86"
#define ARCH_X64 "x64"
#define ARCH_ARM "arm"
#define ARCH_ARM64 "arm64"
#define ARCH_CURRENT "current"
#define OS_WINDOWS "windows"
#define OS_LINUX "linux"
#define OS_DARWIN "osx"
#define OS_UWP "uwp"
#define LINK_DYNAMIC "dynamic"
#define LINK_STATIC "static"
std::string VCPMP::ToStr(VCPMP::ARCH arch) {
switch (arch) {
case VCPMP::ARCH::X86: return ARCH_X86;
case VCPMP::ARCH::X64: return ARCH_X64;
case VCPMP::ARCH::ARM: return ARCH_ARM;
case VCPMP::ARCH::ARM64: return ARCH_ARM64;
default: exit(EXIT_FAILURE);
}
}
std::string VCPMP::ToStr(VCPMP::OS os) {
switch (os) {
case VCPMP::OS::WINDOWS: return OS_WINDOWS;
case VCPMP::OS::LINUX: return OS_LINUX;
case VCPMP::OS::DARWIN: return OS_DARWIN;
case VCPMP::OS::UWP: return OS_UWP;
default: exit(EXIT_FAILURE);
}
}
std::string VCPMP::ToStr(VCPMP::LINK link) {
switch (link) {
case VCPMP::LINK::DYNAMIC: return LINK_DYNAMIC;
case VCPMP::LINK::STATIC: return LINK_STATIC;
default: exit(EXIT_FAILURE);
}
}
VCPMP::ARCH VCPMP::StrToARCH(std::string str) {
if (str.compare(ARCH_X86) == 0) {
return VCPMP::ARCH::X86;
} else if (str.compare(ARCH_X64) == 0) {
return VCPMP::ARCH::X64;
} else if (str.compare(ARCH_ARM) == 0) {
return VCPMP::ARCH::ARM;
} else if (str.compare(ARCH_ARM64) == 0) {
return VCPMP::ARCH::ARM64;
} else if (str.compare(ARCH_CURRENT) == 0) {
return VCPMP::getArch();
}
return VCPMP::ARCH::ERROR;
}
VCPMP::OS VCPMP::StrToOS(std::string str) {
if (str.compare(OS_WINDOWS) == 0) {
return VCPMP::OS::WINDOWS;
} else if (str.compare(OS_LINUX) == 0) {
return VCPMP::OS::LINUX;
} else if (str.compare(OS_DARWIN) == 0) {
return VCPMP::OS::DARWIN;
} else if (str.compare(OS_UWP) == 0) {
return VCPMP::OS::UWP;
}
return VCPMP::OS::ERROR;
}
VCPMP::LINK VCPMP::StrToLINK(std::string str) {
if (str.compare(LINK_DYNAMIC) == 0) {
return VCPMP::LINK::DYNAMIC;
} else if (str.compare(LINK_STATIC) == 0) {
return VCPMP::LINK::STATIC;
}
return VCPMP::LINK::ERROR;
}
VCPMP::ARCH VCPMP::getArch() {
switch (sizeof(void*)) {
case 4: return VCPMP::ARCH::X86;
case 8: return VCPMP::ARCH::X64;
}
return VCPMP::ARCH::ERROR;
}
VCPMP::OS VCPMP::getOS() {
#if defined(_WIN32) || defined(_WIN64)
return VCPMP::OS::WINDOWS;
#elif __APPLE__ || __MACH__
return VCPMP::OS::DARWIN;
#else
return VCPMP::OS::LINUX;
#endif
}
void VCPMP::install_vcpkg_library(const char* vcpkg_root, std::string name, VCPMP::ARCH arch, VCPMP::OS os, VCPMP::LINK link) {
std::string command_str = vcpkg_root;
command_str += "/vcpkg install " + name + ":" + VCPMP::ToStr(arch) + "-" + VCPMP::ToStr(os);
if (link == VCPMP::LINK::STATIC) {
command_str += + "-" + VCPMP::ToStr(link);
}
const char* command = command_str.c_str();
system(command);
}
| 27.121739 | 127 | 0.612376 | yunik1004 |
59b031457ba8dcbacb65a4611d193ff41677c658 | 168 | hpp | C++ | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | 6 | 2022-03-23T23:26:04.000Z | 2022-03-27T06:33:22.000Z | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | null | null | null | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | 6 | 2022-03-25T22:56:04.000Z | 2022-03-26T09:32:08.000Z |
#pragma once
#include <switch.h>
namespace vmod::sf::fs {
Result Initialize();
void Finalize();
Result OpenSdCardFileSystem(FsFileSystem &out_sd_fs);
} | 14 | 57 | 0.690476 | MarioPossamato |
59b2aab7a78d3de791666f1d83c8d4c71ac7a0c5 | 1,649 | cpp | C++ | Konsole/source/Graphics/ColoredString.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | Konsole/source/Graphics/ColoredString.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | Konsole/source/Graphics/ColoredString.cpp | mooviies/TetrisConsole | 4468df779c74cb30d4543eb50d89c491839998bb | [
"MIT"
] | null | null | null | #include "ColoredString.h"
#include <exception>
using namespace konsole;
using namespace std;
ColoredChar konsole::toColoredChar(char c, Color textColor, Color backgroundColor)
{
return ColoredChar(c, textColor, backgroundColor);
}
ColoredString::ColoredString()
{
}
ColoredString::ColoredString(char c)
{
assign(1, c);
}
ColoredString::ColoredString(size_t n, char c)
{
assign(n, c);
}
ColoredString::ColoredString(const char* str)
{
size_t index = 0;
while (str[index] != '\0')
{
append(1, str[index++]);
}
}
ColoredString::ColoredString(const std::string& str)
{
for (int i = 0; i < str.length(); i++)
{
append(1, str[i]);
}
}
std::string ColoredString::toString() const
{
string str;
for (int i = 0; i < length(); i++)
str.append(1, at(i).value);
return str;
}
Color ColoredString::getColor(size_t index) const
{
return at(index).textColor;
}
Color ColoredString::getBackgroundColor(size_t index) const
{
return at(index).backgroundColor;
}
ColoredString& ColoredString::setColor(Color color)
{
for (int i = 0; i < length(); i++)
at(i).textColor = color;
return *this;
}
ColoredString& ColoredString::setColor(Color color, size_t index, size_t len)
{
for (int i = index; i < length() && len > 0; i++, len--)
at(i).textColor = color;
return *this;
}
ColoredString& ColoredString::setBackgroundColor(Color color)
{
for (int i = 0; i < length(); i++)
at(i).backgroundColor = color;
return *this;
}
ColoredString& ColoredString::setBackgroundColor(Color color, size_t index, size_t len)
{
for (int i = index; i < length() && len > 0; i++, len--)
at(i).backgroundColor = color;
return *this;
} | 17.731183 | 87 | 0.681019 | mooviies |
59b35cce3591b0205fdb697b2884f67b3ee9daf7 | 1,663 | cxx | C++ | Testing/igstkDefaultWidget.cxx | ipa/IGSTK | d31f77b04aa72469e18e8a989ed8316bad39ed7a | [
"BSD-3-Clause"
] | 5 | 2016-02-12T18:55:20.000Z | 2022-02-05T09:23:07.000Z | Testing/igstkDefaultWidget.cxx | ipa/IGSTK | d31f77b04aa72469e18e8a989ed8316bad39ed7a | [
"BSD-3-Clause"
] | 1 | 2018-01-26T10:39:31.000Z | 2018-01-26T10:39:31.000Z | Testing/igstkDefaultWidget.cxx | ipa/IGSTK | d31f77b04aa72469e18e8a989ed8316bad39ed7a | [
"BSD-3-Clause"
] | 4 | 2017-09-24T01:19:32.000Z | 2021-06-20T18:02:42.000Z | /*=========================================================================
Program: Image Guided Surgery Software Toolkit
Module: igstkDefaultWidget.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) ISC Insight Software Consortium. All rights reserved.
See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "igstkDefaultWidget.h"
#include "vtkRenderWindow.h"
namespace igstk
{
DefaultWidget
::DefaultWidget(unsigned int width, unsigned int height):m_ProxyView(this)
{
this->m_Width = width;
this->m_Height = height;
}
void
DefaultWidget
::RequestSetView( ViewType * view )
{
this->m_View = view;
this->m_ProxyView.Connect( this->m_View );
m_ProxyView.SetRenderWindowSize(
this->m_View, this->m_Width, this->m_Height );
}
void
DefaultWidget
::TestProxy()
{
std::cout << this->m_ProxyView.GetNameOfClass() << std::endl;
const double px = 1.3;
const double py = 1.8;
this->m_ProxyView.SetPickedPointCoordinates( this->m_View, px, py );
}
void
DefaultWidget
::SetRenderer( vtkRenderer * )
{
}
void
DefaultWidget
::SetRenderWindowInteractor( vtkRenderWindowInteractor * iren )
{
vtkRenderWindow* renWin = iren->GetRenderWindow();
if (renWin != NULL)
{
renWin->BordersOn();
renWin->SetWindowName( "IGSTK DefaultWidget" );
}
}
} // end namespace igstk
| 23.757143 | 75 | 0.651834 | ipa |
59b41ae634a2eb99918ab949787ece5a09f0c54b | 1,152 | cpp | C++ | NaoTHSoccer/Source/Representations/Motion/CollisionPercept.cpp | tarsoly/NaoTH | dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | NaoTHSoccer/Source/Representations/Motion/CollisionPercept.cpp | tarsoly/NaoTH | dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | NaoTHSoccer/Source/Representations/Motion/CollisionPercept.cpp | tarsoly/NaoTH | dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* @file CollisionPercept.h
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
*
*/
#include "CollisionPercept.h"
#include <Messages/Representations.pb.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
void Serializer<CollisionPercept>::serialize(const CollisionPercept& representation, std::ostream& stream)
{
naothmessages::CollisionPercept message;
message.set_timecollisionarmleft(representation.timeCollisionArmLeft);
message.set_timecollisionarmright(representation.timeCollisionArmRight);
google::protobuf::io::OstreamOutputStream buf(&stream);
message.SerializeToZeroCopyStream(&buf);
}
void Serializer<CollisionPercept>::deserialize(std::istream& stream, CollisionPercept& representation)
{
naothmessages::CollisionPercept message;
google::protobuf::io::IstreamInputStream buf(&stream);
if(message.ParseFromZeroCopyStream(&buf))
{
representation.timeCollisionArmLeft = message.timecollisionarmleft();
representation.timeCollisionArmRight = message.timecollisionarmright();
}
else
{
THROW("Serializer<CollisionPercept>::deserialize failed");
}
}
| 29.538462 | 106 | 0.782986 | tarsoly |
59b5d4b10475f88192c9af0f22839a1ee74a5ad9 | 10,102 | cpp | C++ | blades/xbmc/xbmc/music/dialogs/GUIDialogSongInfo.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/music/dialogs/GUIDialogSongInfo.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/music/dialogs/GUIDialogSongInfo.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "GUIDialogSongInfo.h"
#include "utils/URIUtils.h"
#include "utils/StringUtils.h"
#include "utils/Variant.h"
#include "dialogs/GUIDialogFileBrowser.h"
#include "dialogs/GUIDialogSelect.h"
#include "GUIPassword.h"
#include "GUIUserMessages.h"
#include "music/MusicDatabase.h"
#include "music/windows/GUIWindowMusicBase.h"
#include "music/tags/MusicInfoTag.h"
#include "guilib/GUIWindowManager.h"
#include "input/Key.h"
#include "filesystem/File.h"
#include "filesystem/CurlFile.h"
#include "FileItem.h"
#include "settings/MediaSourceSettings.h"
#include "guilib/LocalizeStrings.h"
#include "music/Album.h"
#include "storage/MediaManager.h"
#include "GUIDialogMusicInfo.h"
using namespace XFILE;
#define CONTROL_USERRATING 7
#define CONTROL_ALBUMINFO 12
#define CONTROL_GETTHUMB 13
CGUIDialogSongInfo::CGUIDialogSongInfo(void)
: CGUIDialog(WINDOW_DIALOG_SONG_INFO, "DialogSongInfo.xml")
, m_song(new CFileItem)
{
m_cancelled = false;
m_needsUpdate = false;
m_startUserrating = -1;
m_loadType = KEEP_IN_MEMORY;
}
CGUIDialogSongInfo::~CGUIDialogSongInfo(void)
{
}
bool CGUIDialogSongInfo::OnMessage(CGUIMessage& message)
{
switch (message.GetMessage())
{
case GUI_MSG_WINDOW_DEINIT:
{
if (m_startUserrating != m_song->GetMusicInfoTag()->GetUserrating())
{
CMusicDatabase db;
if (db.Open()) // OpenForWrite() ?
{
m_needsUpdate = true;
db.SetSongUserrating(m_song->GetPath(), m_song->GetMusicInfoTag()->GetUserrating());
db.Close();
}
}
break;
}
case GUI_MSG_WINDOW_INIT:
m_cancelled = false;
break;
case GUI_MSG_CLICKED:
{
int iControl = message.GetSenderId();
if (iControl == CONTROL_USERRATING)
{
OnSetUserrating();
}
else if (iControl == CONTROL_ALBUMINFO)
{
CGUIWindowMusicBase *window = (CGUIWindowMusicBase *)g_windowManager.GetWindow(WINDOW_MUSIC_NAV);
if (window)
{
CFileItem item(*m_song);
std::string path = StringUtils::Format("musicdb://albums/%li",m_albumId);
item.SetPath(path);
item.m_bIsFolder = true;
window->OnItemInfo(&item, true);
}
return true;
}
else if (iControl == CONTROL_GETTHUMB)
{
OnGetThumb();
return true;
}
}
break;
}
return CGUIDialog::OnMessage(message);
}
bool CGUIDialogSongInfo::OnAction(const CAction &action)
{
char rating = m_song->GetMusicInfoTag()->GetUserrating();
if (action.GetID() == ACTION_INCREASE_RATING)
{
SetUserrating(rating + 1);
return true;
}
else if (action.GetID() == ACTION_DECREASE_RATING)
{
SetUserrating(rating - 1);
return true;
}
else if (action.GetID() == ACTION_SHOW_INFO)
{
Close();
return true;
}
return CGUIDialog::OnAction(action);
}
bool CGUIDialogSongInfo::OnBack(int actionID)
{
m_cancelled = true;
return CGUIDialog::OnBack(actionID);
}
void CGUIDialogSongInfo::OnInitWindow()
{
CMusicDatabase db;
db.Open();
// no known db info - check if parent dir is an album
if (m_song->GetMusicInfoTag()->GetDatabaseId() == -1)
{
std::string path = URIUtils::GetDirectory(m_song->GetPath());
m_albumId = db.GetAlbumIdByPath(path);
}
else
{
CAlbum album;
db.GetAlbumFromSong(m_song->GetMusicInfoTag()->GetDatabaseId(),album);
m_albumId = album.idAlbum;
}
CONTROL_ENABLE_ON_CONDITION(CONTROL_ALBUMINFO, m_albumId > -1);
CGUIDialog::OnInitWindow();
}
void CGUIDialogSongInfo::SetUserrating(char rating)
{
if (rating < '0') rating = '0';
if (rating > '5') rating = '5';
if (rating != m_song->GetMusicInfoTag()->GetUserrating())
{
m_song->GetMusicInfoTag()->SetUserrating(rating);
// send a message to all windows to tell them to update the fileitem (eg playlistplayer, media windows)
CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, m_song);
g_windowManager.SendMessage(msg);
}
}
void CGUIDialogSongInfo::SetSong(CFileItem *item)
{
*m_song = *item;
m_song->LoadMusicTag();
m_startUserrating = m_song->GetMusicInfoTag()->GetUserrating();
MUSIC_INFO::CMusicInfoLoader::LoadAdditionalTagInfo(m_song.get());
// set artist thumb as well
CMusicDatabase db;
db.Open();
if (item->IsMusicDb())
{
std::vector<int> artists;
CVariant artistthumbs;
db.GetArtistsBySong(item->GetMusicInfoTag()->GetDatabaseId(), true, artists);
for (std::vector<int>::const_iterator artistId = artists.begin(); artistId != artists.end(); ++artistId)
{
std::string thumb = db.GetArtForItem(*artistId, MediaTypeArtist, "thumb");
if (!thumb.empty())
artistthumbs.push_back(thumb);
}
if (artistthumbs.size())
{
m_song->SetProperty("artistthumbs", artistthumbs);
m_song->SetProperty("artistthumb", artistthumbs[0]);
}
}
else if (m_song->HasMusicInfoTag() && !m_song->GetMusicInfoTag()->GetArtist().empty())
{
int idArtist = db.GetArtistByName(m_song->GetMusicInfoTag()->GetArtist()[0]);
std::string thumb = db.GetArtForItem(idArtist, MediaTypeArtist, "thumb");
if (!thumb.empty())
m_song->SetProperty("artistthumb", thumb);
}
m_needsUpdate = false;
}
CFileItemPtr CGUIDialogSongInfo::GetCurrentListItem(int offset)
{
return m_song;
}
bool CGUIDialogSongInfo::DownloadThumbnail(const std::string &thumbFile)
{
// TODO: Obtain the source...
std::string source;
CCurlFile http;
http.Download(source, thumbFile);
return true;
}
// Get Thumb from user choice.
// Options are:
// 1. Current thumb
// 2. AllMusic.com thumb
// 3. Local thumb
// 4. No thumb (if no Local thumb is available)
// TODO: Currently no support for "embedded thumb" as there is no easy way to grab it
// without sending a file that has this as it's album to this class
void CGUIDialogSongInfo::OnGetThumb()
{
CFileItemList items;
// Grab the thumbnail from the web
/*
std::string thumbFromWeb;
thumbFromWeb = URIUtils::AddFileToFolder(g_advancedSettings.m_cachePath, "allmusicThumb.jpg");
if (DownloadThumbnail(thumbFromWeb))
{
CFileItemPtr item(new CFileItem("thumb://allmusic.com", false));
item->SetArt("thumb", thumbFromWeb);
item->SetLabel(g_localizeStrings.Get(20055));
items.Add(item);
}*/
// Current thumb
if (CFile::Exists(m_song->GetArt("thumb")))
{
CFileItemPtr item(new CFileItem("thumb://Current", false));
item->SetArt("thumb", m_song->GetArt("thumb"));
item->SetLabel(g_localizeStrings.Get(20016));
items.Add(item);
}
// local thumb
std::string cachedLocalThumb;
std::string localThumb(m_song->GetUserMusicThumb(true));
if (m_song->IsMusicDb())
{
CFileItem item(m_song->GetMusicInfoTag()->GetURL(), false);
localThumb = item.GetUserMusicThumb(true);
}
if (CFile::Exists(localThumb))
{
CFileItemPtr item(new CFileItem("thumb://Local", false));
item->SetArt("thumb", localThumb);
item->SetLabel(g_localizeStrings.Get(20017));
items.Add(item);
}
else
{ // no local thumb exists, so we are just using the allmusic.com thumb or cached thumb
// which is probably the allmusic.com thumb. These could be wrong, so allow the user
// to delete the incorrect thumb
CFileItemPtr item(new CFileItem("thumb://None", false));
item->SetArt("thumb", "DefaultAlbumCover.png");
item->SetLabel(g_localizeStrings.Get(20018));
items.Add(item);
}
std::string result;
VECSOURCES sources(*CMediaSourceSettings::GetInstance().GetSources("music"));
CGUIDialogMusicInfo::AddItemPathToFileBrowserSources(sources, *m_song);
g_mediaManager.GetLocalDrives(sources);
if (!CGUIDialogFileBrowser::ShowAndGetImage(items, sources, g_localizeStrings.Get(1030), result))
return; // user cancelled
if (result == "thumb://Current")
return; // user chose the one they have
// delete the thumbnail if that's what the user wants, else overwrite with the
// new thumbnail
std::string newThumb;
if (result == "thumb://None")
newThumb = "-";
else if (result == "thumb://allmusic.com")
newThumb.clear();
else if (result == "thumb://Local")
newThumb = localThumb;
else
newThumb = result;
// update thumb in the database
CMusicDatabase db;
if (db.Open())
{
db.SetArtForItem(m_song->GetMusicInfoTag()->GetDatabaseId(), m_song->GetMusicInfoTag()->GetType(), "thumb", newThumb);
db.Close();
}
m_song->SetArt("thumb", newThumb);
// tell our GUI to completely reload all controls (as some of them
// are likely to have had this image in use so will need refreshing)
CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_REFRESH_THUMBS);
g_windowManager.SendMessage(msg);
// m_hasUpdatedThumb = true;
}
void CGUIDialogSongInfo::OnSetUserrating()
{
CGUIDialogSelect *dialog = (CGUIDialogSelect *)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
if (dialog)
{
dialog->SetHeading(CVariant{ 38023 });
dialog->Add(g_localizeStrings.Get(38022));
for (int i = 1; i <= 5; i++)
dialog->Add(StringUtils::Format("%s: %i", g_localizeStrings.Get(563).c_str(), i));
dialog->Open();
int iItem = dialog->GetSelectedLabel();
if (iItem < 0)
return;
SetUserrating('0' + iItem); // This is casting the int rating to char
}
}
| 28.945559 | 122 | 0.682934 | krattai |
59b66be34aab0f121932cbbda90ac1eaf71bccdc | 12,011 | cpp | C++ | libnd4j/include/ops/declarable/generic/convo/ismax.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 2 | 2018-11-26T15:30:37.000Z | 2018-11-26T15:30:39.000Z | libnd4j/include/ops/declarable/generic/convo/ismax.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 16 | 2018-12-03T11:37:19.000Z | 2018-12-03T19:47:25.000Z | libnd4j/include/ops/declarable/generic/convo/ismax.cpp | nutonchain/Deeplearning | 20f222c1eff95205c6c9c9b666b04402405e4442 | [
"Apache-2.0"
] | 2 | 2021-03-01T07:46:24.000Z | 2021-09-26T17:08:40.000Z | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by raver119 on 29/10/17.
//
#include <op_boilerplate.h>
#if NOT_EXCLUDED(OP_ismax)
#include <ops/declarable/CustomOperations.h>
namespace nd4j {
namespace ops {
CONFIGURABLE_OP_IMPL(ismax, 1, 1, true, 0, -1) {
NDArray<T>* x = INPUT_VARIABLE(0);
NDArray<T>* z = OUTPUT_VARIABLE(0);
std::vector<int> dimensions = *(block.getIArguments()); // argI
// FIXME: this should be moved to helpers!
if (x->isVector()) {
int dimensionsLength = dimensions.size();
int length = x->lengthOf();
if ((x->shapeOf())[dimensions[0]] == 1) {
for (int i = 0; i < length; i++)
z->putScalar(i, 1.f);
}
else {
int eleStride = shape::elementWiseStride(x->getShapeInfo());
if (eleStride == 1) {
int maxIdx = 0;
T currMax = x->getScalar(0);
if (length < ELEMENT_THRESHOLD) {
//#pragma omp simd reduction(max:maxIdx,currMax)
for (int i = 0; i < length; i++) {
if (currMax < x->getScalar(i)) {
currMax = x->getScalar(i);
maxIdx = i;
}
x->putScalar(i, 0.f);
}
}
else {
#pragma omp parallel proc_bind(AFFINITY) default(shared)
{
int maxIdxLocal = maxIdx;
T currMaxLocal = currMax;
//#pragma omp simd reduction(max:maxIdxLocal,currMaxLocal)
for (int i = 0; i < length; i++) {
if (currMaxLocal < x->getScalar(i)) {
currMaxLocal = x->getScalar(i);
maxIdxLocal = i;
}
z->putScalar(i, 0.f);
}
#pragma omp critical
{
if (currMax < currMaxLocal) {
currMax = currMaxLocal;
maxIdx = maxIdxLocal;
}
}
}
}
z->putScalar(maxIdx, 1.f);
}
else {
int maxIdx = 0;
T currMax = x->getScalar(0);
if (length < ELEMENT_THRESHOLD) {
//#pragma omp parallel for reduction(max:maxIdx,currMax) proc_bind(AFFINITY)
for (int i = 0; i < length; i++) {
if (currMax < x->getScalar(i*eleStride)) {
currMax = x->getScalar(i*eleStride);
maxIdx = i;
}
z->putScalar(i, 0.f);
}
}
else {
#pragma omp parallel proc_bind(AFFINITY) default(shared)
{
int maxIdxLocal = maxIdx;
T currMaxLocal = currMax;
//#pragma omp parallel for reduction(max:maxIdx,currMax) proc_bind(AFFINITY)
for (int i = 0; i < length; i++) {
if (currMaxLocal < x->getScalar(i*eleStride)) {
currMaxLocal = x->getScalar(i*eleStride);
maxIdxLocal = i;
}
z->putScalar(i, 0.f);
}
#pragma omp critical
{
if (currMax < currMaxLocal) {
currMax = currMaxLocal;
maxIdx = maxIdxLocal;
}
}
}
}
z->putScalar(maxIdx, 1.f);
}
}
}
else {
int dimensionsLength = dimensions.size();
// int tads = tad.numTads;
//decompose in to several sub tads after
//moving all dimensions (in sorted order)
//to the back.
//permuted version of the x shape info for setting up the tad problem
shape::TAD tad(x->getShapeInfo(), dimensions.data(), dimensionsLength);
tad.createTadOnlyShapeInfo();
tad.createOffsets();
Nd4jLong *tadShapeShapeInfo = tad.tadOnlyShapeInfo;
Nd4jLong* tadOffsets = tad.tadOffsets;
int tadLength = shape::tadLength(x->getShapeInfo(), dimensions.data(), dimensionsLength);
int tads = x->lengthOf() / tadLength;
int tadsPerThread = tads / TAD_THRESHOLD;
int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread);
num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads());
auto tadEWS = shape::elementWiseStride(tadShapeShapeInfo);
auto zEWS = tadEWS;
int span = (tads / num_threads) + 8;
#pragma omp parallel num_threads(num_threads) if (num_threads>1) proc_bind(AFFINITY)
{
int tid = omp_get_thread_num();
int start = span * tid;
int end = span * (tid + 1);
if (end > tads) end = tads;
for (int r = start; r < end; r++) {
if (tadEWS > 0 && zEWS > 0 && dimensionsLength == 1) {
T *rX = x->getBuffer() + tadOffsets[r];
T *rZ = z->getBuffer() + tadOffsets[r];
T maxValue = rX[0];
int maxIdx = 0;
if (tadEWS == 1 && zEWS == 1) {
//#pragma omp simd reduction(max:maxValue,maxIdx)
for (int i = 0; i < tadLength; i++) {
if (rX[i] > maxValue) {
maxIdx = i;
maxValue = rX[i];
}
}
#pragma omp simd
for (int i = 0; i < tadLength; i++) {
rZ[i] = maxIdx == i ? (T) 1.0 : (T) 0.0;
}
} else {
//#pragma omp parallel for reduction(max:maxValue,maxIdx) default(shared)
for (int i = 0; i < tadLength; i++) {
if (rX[i * tadEWS] > maxValue) {
maxIdx = i;
maxValue = rX[i * tadEWS];
}
}
#pragma omp simd
for (int i = 0; i < tadLength; i++) {
rZ[i * zEWS] = maxIdx == i ? (T) 1.0 : (T) 0.0;
}
}
} else {
int tadsPerThread = tads / TAD_THRESHOLD;
int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread);
num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads());
Nd4jLong offset = tadOffsets[r];
Nd4jLong shapeIter[MAX_RANK];
Nd4jLong coord[MAX_RANK];
int dim;
Nd4jLong xStridesIter[MAX_RANK];
Nd4jLong resultStridesIter[MAX_RANK];
Nd4jLong *xShape = shape::shapeOf(tadShapeShapeInfo);
Nd4jLong *xStride = shape::stride(tadShapeShapeInfo);
Nd4jLong *resultStride = shape::stride(tadShapeShapeInfo);
int rank = shape::rank(tadShapeShapeInfo);
T *xPointer = x->getBuffer() + offset;
T *resultPointer = z->getBuffer() + offset;
T maxValue = xPointer[0];
T *maxCursor = resultPointer;
Nd4jPointer maxCursorLong = reinterpret_cast<Nd4jPointer>(maxCursor);
if (PrepareTwoRawArrayIter<T>(rank,
xShape,
xPointer,
xStride,
resultPointer,
resultStride,
&rank,
shapeIter,
&xPointer,
xStridesIter,
&resultPointer,
resultStridesIter) >= 0) {
ND4J_RAW_ITER_START(dim, rank, coord, shapeIter); {
if (maxValue < xPointer[0]) {
maxCursor = resultPointer;
maxCursorLong = reinterpret_cast<Nd4jPointer>(resultPointer);
maxValue = xPointer[0];
}
resultPointer[0] = 0.0;
}
ND4J_RAW_ITER_TWO_NEXT(dim,
rank,
coord,
shapeIter,
xPointer,
xStridesIter,
resultPointer,
resultStridesIter);
maxCursor = reinterpret_cast<T *>(maxCursorLong);
maxCursor[0] = 1.0;
}
}
}
}
}
return ND4J_STATUS_OK;
}
DECLARE_SYN(IsMax, ismax);
}
}
#endif | 47.662698 | 105 | 0.360253 | nutonchain |
59ba956272b192f553ab85e8f4e4cf12bf2b9714 | 2,732 | cpp | C++ | B2G/gecko/widget/os2/nsScreenOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/widget/os2/nsScreenOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/widget/os2/nsScreenOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsScreenOS2.h"
nsScreenOS2 :: nsScreenOS2 ( )
{
// nothing else to do. I guess we could cache a bunch of information
// here, but we want to ask the device at runtime in case anything
// has changed.
}
nsScreenOS2 :: ~nsScreenOS2()
{
// nothing to see here.
}
NS_IMETHODIMP
nsScreenOS2 :: GetRect(int32_t *outLeft, int32_t *outTop, int32_t *outWidth, int32_t *outHeight)
{
LONG alArray[2];
HPS hps = ::WinGetScreenPS( HWND_DESKTOP);
HDC hdc = ::GpiQueryDevice (hps);
::DevQueryCaps(hdc, CAPS_WIDTH, 2, alArray);
::WinReleasePS(hps);
*outTop = 0;
*outLeft = 0;
*outWidth = alArray[0];
*outHeight = alArray[1];
return NS_OK;
} // GetRect
NS_IMETHODIMP
nsScreenOS2 :: GetAvailRect(int32_t *outLeft, int32_t *outTop, int32_t *outWidth, int32_t *outHeight)
{
static APIRET rc = 0;
static BOOL (APIENTRY * pfnQueryDesktopWorkArea)(HWND hwndDesktop, PWRECT pwrcWorkArea) = NULL;
GetRect(outLeft, outTop, outWidth, outHeight);
// This height is different based on whether or not
// "Show on top of maximed windows" is checked
LONG lWorkAreaHeight = *outHeight;
if ( !rc && !pfnQueryDesktopWorkArea )
{
HMODULE hmod = 0;
rc = DosQueryModuleHandle( "PMMERGE", &hmod );
if ( !rc )
{
rc = DosQueryProcAddr( hmod, 5469, NULL, (PFN*) &pfnQueryDesktopWorkArea ); // WinQueryDesktopWorkArea
}
}
if ( pfnQueryDesktopWorkArea && !rc )
{
RECTL rectl;
pfnQueryDesktopWorkArea( HWND_DESKTOP, &rectl );
lWorkAreaHeight = rectl.yTop - rectl.yBottom;
}
HWND hwndWarpCenter = WinWindowFromID( HWND_DESKTOP, 0x555 );
if (hwndWarpCenter) {
/* If "Show on top of maximized windows is checked" */
if (lWorkAreaHeight != *outHeight) {
SWP swp;
WinQueryWindowPos( hwndWarpCenter, &swp );
if (swp.y != 0) {
/* WarpCenter is at the top */
*outTop += swp.cy;
}
*outHeight -= swp.cy;
}
}
return NS_OK;
} // GetAvailRect
NS_IMETHODIMP
nsScreenOS2 :: GetPixelDepth(int32_t *aPixelDepth)
{
LONG lCap;
HPS hps = ::WinGetScreenPS( HWND_DESKTOP);
HDC hdc = ::GpiQueryDevice (hps);
::DevQueryCaps(hdc, CAPS_COLOR_BITCOUNT, 1, &lCap);
*aPixelDepth = (int32_t)lCap;
::WinReleasePS(hps);
return NS_OK;
} // GetPixelDepth
NS_IMETHODIMP
nsScreenOS2 :: GetColorDepth(int32_t *aColorDepth)
{
return GetPixelDepth ( aColorDepth );
} // GetColorDepth
| 23.152542 | 112 | 0.660688 | wilebeast |