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
3ebdc77b7c2396f6677a1575351482bc9ea52be5
2,820
cpp
C++
src/historywork/test/HistoryWorkTests.cpp
STORP-Inc/POGchain
3cf3de0498947fb5d2cf9d985d93a1d4d84ca831
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/historywork/test/HistoryWorkTests.cpp
STORP-Inc/POGchain
3cf3de0498947fb5d2cf9d985d93a1d4d84ca831
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/historywork/test/HistoryWorkTests.cpp
STORP-Inc/POGchain
3cf3de0498947fb5d2cf9d985d93a1d4d84ca831
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 POGchain Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "history/HistoryArchiveManager.h" #include "history/test/HistoryTestsUtils.h" #include "historywork/CheckSingleLedgerHeaderWork.h" #include "historywork/WriteVerifiedCheckpointHashesWork.h" #include "test/TestUtils.h" #include "test/test.h" #include "util/Logging.h" #include "util/Timer.h" #include "work/WorkScheduler.h" #include <lib/catch.hpp> #include <lib/json/json.h> using namespace POGchain; using namespace historytestutils; TEST_CASE("write verified checkpoint hashes", "[historywork]") { CatchupSimulation catchupSimulation{}; uint32_t nestedBatchSize = 4; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(5 * nestedBatchSize); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5 * nestedBatchSize); std::vector<LedgerNumHashPair> pairs = catchupSimulation.getAllPublishedCheckpoints(); LedgerNumHashPair pair = pairs.back(); auto tmpDir = catchupSimulation.getApp().getTmpDirManager().tmpDir( "write-checkpoint-hashes-test"); auto file = tmpDir.getName() + "/verified-ledgers.json"; auto& wm = catchupSimulation.getApp().getWorkScheduler(); { auto w = wm.executeWork<WriteVerifiedCheckpointHashesWork>( pair, file, nestedBatchSize); REQUIRE(w->getState() == BasicWork::State::WORK_SUCCESS); } // Make sure w is destroyed. wm.shutdown(); while (wm.getState() != BasicWork::State::WORK_ABORTED) { catchupSimulation.getClock().crank(); } for (auto const& p : pairs) { LOG_DEBUG(DEFAULT_LOG, "Verified {} with hash {}", p.first, hexAbbrev(*p.second)); Hash h = WriteVerifiedCheckpointHashesWork::loadHashFromJsonOutput( p.first, file); REQUIRE(h == *p.second); } } TEST_CASE("check single ledger header work", "[historywork]") { CatchupSimulation catchupSimulation{}; auto l1 = catchupSimulation.getLastCheckpointLedger(2); auto l2 = catchupSimulation.getLastCheckpointLedger(4); catchupSimulation.ensureOfflineCatchupPossible(l1); auto& app = catchupSimulation.getApp(); auto& lm = app.getLedgerManager(); auto lhhe = lm.getLastClosedLedgerHeader(); catchupSimulation.ensureOfflineCatchupPossible(l2); auto arch = app.getHistoryArchiveManager().selectRandomReadableHistoryArchive(); auto& wm = app.getWorkScheduler(); auto w = wm.executeWork<CheckSingleLedgerHeaderWork>(arch, lhhe); REQUIRE(w->getState() == BasicWork::State::WORK_SUCCESS); }
38.630137
76
0.70461
STORP-Inc
3ebe999113f9644e936e78eb1428666558156cdf
46,533
hpp
C++
SimdMask/Intrinscs/sse2.hpp
Const-me/SimdMask
53f12bae6fb0ded4d9e548400f7bb59cb952b226
[ "MIT" ]
1
2019-12-08T14:49:58.000Z
2019-12-08T14:49:58.000Z
SimdMask/Intrinscs/sse2.hpp
Const-me/SimdMask
53f12bae6fb0ded4d9e548400f7bb59cb952b226
[ "MIT" ]
null
null
null
SimdMask/Intrinscs/sse2.hpp
Const-me/SimdMask
53f12bae6fb0ded4d9e548400f7bb59cb952b226
[ "MIT" ]
null
null
null
// This file is generated automatically by a tool, please don't edit. #pragma once #include <emmintrin.h> #include <immintrin.h> #include "Implementation/utils.hpp" namespace Intrinsics { namespace Sse { // Add packed 8-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV add_epi8( __m128i a, __m128i b ) { return _mm_add_epi8( a, b ); } // Add packed 16-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV add_epi16( __m128i a, __m128i b ) { return _mm_add_epi16( a, b ); } // Add packed 32-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV add_epi32( __m128i a, __m128i b ) { return _mm_add_epi32( a, b ); } // Add packed 64-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV add_epi64( __m128i a, __m128i b ) { return _mm_add_epi64( a, b ); } // Add packed double-precision floating-point elements in "a" and "b" inline __m128d XM_CALLCONV add_pd( __m128d a, __m128d b ) { return _mm_add_pd( a, b ); } // Add the lower double-precision floating-point element in "a" and "b" inline __m128d XM_CALLCONV add_sd( __m128d a, __m128d b ) { return _mm_add_sd( a, b ); } // Add packed 8-bit integers in "a" and "b" using saturation, and store the results in "dst" inline __m128i XM_CALLCONV adds_epi8( __m128i a, __m128i b ) { return _mm_adds_epi8( a, b ); } // Add packed 16-bit integers in "a" and "b" using saturation, and store the results in "dst" inline __m128i XM_CALLCONV adds_epi16( __m128i a, __m128i b ) { return _mm_adds_epi16( a, b ); } // Add packed unsigned 8-bit integers in "a" and "b" using saturation inline __m128i XM_CALLCONV adds_epu8( __m128i a, __m128i b ) { return _mm_adds_epu8( a, b ); } // Add packed unsigned 16-bit integers in "a" and "b" using saturation inline __m128i XM_CALLCONV adds_epu16( __m128i a, __m128i b ) { return _mm_adds_epu16( a, b ); } // Compute the bitwise AND of packed double-precision floating-point elements in "a" and "b" inline __m128d XM_CALLCONV and_pd( __m128d a, __m128d b ) { return _mm_and_pd( a, b ); } // Compute the bitwise AND of 128 bits (representing integer data) in "a" and "b" inline __m128i XM_CALLCONV and_all( __m128i a, __m128i b ) { return _mm_and_si128( a, b ); } // Compute the bitwise NOT of packed double-precision floating-point elements in "a" and then AND with "b" inline __m128d XM_CALLCONV andnot_pd( __m128d a, __m128d b ) { return _mm_andnot_pd( a, b ); } // Compute the bitwise NOT of 128 bits (representing integer data) in "a" and then AND with "b" inline __m128i XM_CALLCONV andnot_all( __m128i a, __m128i b ) { return _mm_andnot_si128( a, b ); } // Average packed unsigned 8-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV avg_epu8( __m128i a, __m128i b ) { return _mm_avg_epu8( a, b ); } // Average packed unsigned 16-bit integers in "a" and "b", and store the results in "dst" inline __m128i XM_CALLCONV avg_epu16( __m128i a, __m128i b ) { return _mm_avg_epu16( a, b ); } // Shift "a" left by "imm8" bytes while shifting in zeros, and store the results in "dst" template<int imm8> inline __m128i XM_CALLCONV bslli_all( __m128i a ) { return _mm_bslli_si128( a, imm8 ); } // Shift "a" right by "imm8" bytes while shifting in zeros, and store the results in "dst" template<int imm8> inline __m128i XM_CALLCONV bsrli_all( __m128i a ) { return _mm_bsrli_si128( a, imm8 ); } // Cast vector of type __m128d to type __m128. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128 XM_CALLCONV castpd_ps( __m128d a ) { return _mm_castpd_ps( a ); } // Cast vector of type __m128d to type __m128i. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128i XM_CALLCONV castpd_all( __m128d a ) { return _mm_castpd_si128( a ); } // Cast vector of type __m128 to type __m128d. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128d XM_CALLCONV castps_pd( __m128 a ) { return _mm_castps_pd( a ); } // Cast vector of type __m128 to type __m128i. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128i XM_CALLCONV castps_all( __m128 a ) { return _mm_castps_si128( a ); } // Cast vector of type __m128i to type __m128d. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128d XM_CALLCONV castsi128_pd( __m128i a ) { return _mm_castsi128_pd( a ); } // Cast vector of type __m128i to type __m128. This intrinsic is only used for compilation and does not generate any instructions, thus it has zero latency. inline __m128 XM_CALLCONV castsi128_ps( __m128i a ) { return _mm_castsi128_ps( a ); } // Compare packed 8-bit integers in "a" and "b" for equality, and store the results in "dst" inline __m128i XM_CALLCONV cmpeq_epi8( __m128i a, __m128i b ) { return _mm_cmpeq_epi8( a, b ); } // Compare packed 16-bit integers in "a" and "b" for equality, and store the results in "dst" inline __m128i XM_CALLCONV cmpeq_epi16( __m128i a, __m128i b ) { return _mm_cmpeq_epi16( a, b ); } // Compare packed 32-bit integers in "a" and "b" for equality, and store the results in "dst" inline __m128i XM_CALLCONV cmpeq_epi32( __m128i a, __m128i b ) { return _mm_cmpeq_epi32( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for equality inline __m128d XM_CALLCONV cmpeq_pd( __m128d a, __m128d b ) { return _mm_cmpeq_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for equality inline __m128d XM_CALLCONV cmpeq_sd( __m128d a, __m128d b ) { return _mm_cmpeq_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for greater-than-or-equal inline __m128d XM_CALLCONV cmpge_pd( __m128d a, __m128d b ) { return _mm_cmpge_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for greater-than-or-equal inline __m128d XM_CALLCONV cmpge_sd( __m128d a, __m128d b ) { return _mm_cmpge_sd( a, b ); } // Compare packed 8-bit integers in "a" and "b" for greater-than, and store the results in "dst" inline __m128i XM_CALLCONV cmpgt_epi8( __m128i a, __m128i b ) { return _mm_cmpgt_epi8( a, b ); } // Compare packed 16-bit integers in "a" and "b" for greater-than, and store the results in "dst" inline __m128i XM_CALLCONV cmpgt_epi16( __m128i a, __m128i b ) { return _mm_cmpgt_epi16( a, b ); } // Compare packed 32-bit integers in "a" and "b" for greater-than, and store the results in "dst" inline __m128i XM_CALLCONV cmpgt_epi32( __m128i a, __m128i b ) { return _mm_cmpgt_epi32( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for greater-than inline __m128d XM_CALLCONV cmpgt_pd( __m128d a, __m128d b ) { return _mm_cmpgt_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for greater-than inline __m128d XM_CALLCONV cmpgt_sd( __m128d a, __m128d b ) { return _mm_cmpgt_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for less-than-or-equal inline __m128d XM_CALLCONV cmple_pd( __m128d a, __m128d b ) { return _mm_cmple_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for less-than-or-equal inline __m128d XM_CALLCONV cmple_sd( __m128d a, __m128d b ) { return _mm_cmple_sd( a, b ); } // Compare packed 8-bit integers in "a" and "b" for less-than, and store the results in "dst" inline __m128i XM_CALLCONV cmplt_epi8( __m128i a, __m128i b ) { return _mm_cmplt_epi8( a, b ); } // Compare packed 16-bit integers in "a" and "b" for less-than, and store the results in "dst" inline __m128i XM_CALLCONV cmplt_epi16( __m128i a, __m128i b ) { return _mm_cmplt_epi16( a, b ); } // Compare packed 32-bit integers in "a" and "b" for less-than, and store the results in "dst" inline __m128i XM_CALLCONV cmplt_epi32( __m128i a, __m128i b ) { return _mm_cmplt_epi32( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for less-than inline __m128d XM_CALLCONV cmplt_pd( __m128d a, __m128d b ) { return _mm_cmplt_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for less-than inline __m128d XM_CALLCONV cmplt_sd( __m128d a, __m128d b ) { return _mm_cmplt_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for not-equal inline __m128d XM_CALLCONV cmpneq_pd( __m128d a, __m128d b ) { return _mm_cmpneq_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for not-equal inline __m128d XM_CALLCONV cmpneq_sd( __m128d a, __m128d b ) { return _mm_cmpneq_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for not-greater-than-or-equal inline __m128d XM_CALLCONV cmpnge_pd( __m128d a, __m128d b ) { return _mm_cmpnge_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for not-greater-than-or-equal inline __m128d XM_CALLCONV cmpnge_sd( __m128d a, __m128d b ) { return _mm_cmpnge_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for not-greater-than inline __m128d XM_CALLCONV cmpngt_pd( __m128d a, __m128d b ) { return _mm_cmpngt_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for not-greater-than inline __m128d XM_CALLCONV cmpngt_sd( __m128d a, __m128d b ) { return _mm_cmpngt_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for not-less-than-or-equal inline __m128d XM_CALLCONV cmpnle_pd( __m128d a, __m128d b ) { return _mm_cmpnle_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for not-less-than-or-equal inline __m128d XM_CALLCONV cmpnle_sd( __m128d a, __m128d b ) { return _mm_cmpnle_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" for not-less-than inline __m128d XM_CALLCONV cmpnlt_pd( __m128d a, __m128d b ) { return _mm_cmpnlt_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" for not-less-than inline __m128d XM_CALLCONV cmpnlt_sd( __m128d a, __m128d b ) { return _mm_cmpnlt_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" to see if neither is NaN inline __m128d XM_CALLCONV cmpord_pd( __m128d a, __m128d b ) { return _mm_cmpord_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" to see if neither is NaN inline __m128d XM_CALLCONV cmpord_sd( __m128d a, __m128d b ) { return _mm_cmpord_sd( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b" to see if either is NaN inline __m128d XM_CALLCONV cmpunord_pd( __m128d a, __m128d b ) { return _mm_cmpunord_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b" to see if either is NaN inline __m128d XM_CALLCONV cmpunord_sd( __m128d a, __m128d b ) { return _mm_cmpunord_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for equality inline int XM_CALLCONV comieq_sd( __m128d a, __m128d b ) { return _mm_comieq_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for greater-than-or-equal inline int XM_CALLCONV comige_sd( __m128d a, __m128d b ) { return _mm_comige_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for greater-than inline int XM_CALLCONV comigt_sd( __m128d a, __m128d b ) { return _mm_comigt_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for less-than-or-equal inline int XM_CALLCONV comile_sd( __m128d a, __m128d b ) { return _mm_comile_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for less-than inline int XM_CALLCONV comilt_sd( __m128d a, __m128d b ) { return _mm_comilt_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for not-equal inline int XM_CALLCONV comineq_sd( __m128d a, __m128d b ) { return _mm_comineq_sd( a, b ); } // Convert packed 32-bit integers in "a" to packed double-precision floating-point elements inline __m128d XM_CALLCONV cvtepi32_pd( __m128i a ) { return _mm_cvtepi32_pd( a ); } // Convert packed 32-bit integers in "a" to packed single-precision floating-point elements inline __m128 XM_CALLCONV cvtepi32_ps( __m128i a ) { return _mm_cvtepi32_ps( a ); } // Convert packed double-precision floating-point elements in "a" to packed 32-bit integers inline __m128i XM_CALLCONV cvtpd_epi32( __m128d a ) { return _mm_cvtpd_epi32( a ); } // Convert packed double-precision floating-point elements in "a" to packed single-precision floating-point elements inline __m128 XM_CALLCONV cvtpd_ps( __m128d a ) { return _mm_cvtpd_ps( a ); } // Convert packed single-precision floating-point elements in "a" to packed 32-bit integers inline __m128i XM_CALLCONV cvtps_epi32( __m128 a ) { return _mm_cvtps_epi32( a ); } // Convert packed single-precision floating-point elements in "a" to packed double-precision floating-point elements inline __m128d XM_CALLCONV cvtps_pd( __m128 a ) { return _mm_cvtps_pd( a ); } // Copy the lower double-precision floating-point element of "a" to "dst" inline double XM_CALLCONV cvtsd_f64( __m128d a ) { return _mm_cvtsd_f64( a ); } // Convert the lower double-precision floating-point element in "a" to a 32-bit integer inline int XM_CALLCONV cvtsd_si32( __m128d a ) { return _mm_cvtsd_si32( a ); } // Convert the lower double-precision floating-point element in "b" to a single-precision floating-point element inline __m128 XM_CALLCONV cvtsd_ss( __m128 a, __m128d b ) { return _mm_cvtsd_ss( a, b ); } // Copy the lower 32-bit integer in "a" to "dst". inline int XM_CALLCONV cvtsi128_si32( __m128i a ) { return _mm_cvtsi128_si32( a ); } // Convert the 32-bit integer "b" to a double-precision floating-point element inline __m128d XM_CALLCONV cvtsi32_sd( __m128d a, int b ) { return _mm_cvtsi32_sd( a, b ); } // Copy 32-bit integer "a" to the lower elements of "dst", and zero the upper elements of "dst" inline __m128i XM_CALLCONV cvtsi32_all( int a ) { return _mm_cvtsi32_si128( a ); } // Convert the lower single-precision floating-point element in "b" to a double-precision floating-point element inline __m128d XM_CALLCONV cvtss_sd( __m128d a, __m128 b ) { return _mm_cvtss_sd( a, b ); } // Convert packed double-precision floating-point elements in "a" to packed 32-bit integers with truncation inline __m128i XM_CALLCONV cvttpd_epi32( __m128d a ) { return _mm_cvttpd_epi32( a ); } // Convert packed single-precision floating-point elements in "a" to packed 32-bit integers with truncation inline __m128i XM_CALLCONV cvttps_epi32( __m128 a ) { return _mm_cvttps_epi32( a ); } // Convert the lower double-precision floating-point element in "a" to a 32-bit integer with truncation inline int XM_CALLCONV cvttsd_si32( __m128d a ) { return _mm_cvttsd_si32( a ); } // Divide packed double-precision floating-point elements in "a" by packed elements in "b" inline __m128d XM_CALLCONV div_pd( __m128d a, __m128d b ) { return _mm_div_pd( a, b ); } // Divide the lower double-precision floating-point element in "a" by the lower double-precision floating-point element in "b" inline __m128d XM_CALLCONV div_sd( __m128d a, __m128d b ) { return _mm_div_sd( a, b ); } // Extract a 16-bit integer from "a", selected with "imm8", and store the result in the lower element of "dst" template<int imm8> inline int XM_CALLCONV extract_epi16( __m128i a ) { return _mm_extract_epi16( a, imm8 ); } // Copy "a" to "dst", and insert the 16-bit integer "i" into "dst" at the location specified by "imm8" template<int imm8> inline __m128i XM_CALLCONV insert_epi16( __m128i a, int i ) { return _mm_insert_epi16( a, i, imm8 ); } // Perform a serializing operation on all load-from-memory instructions that were issued prior to this instruction inline void XM_CALLCONV lfence() { _mm_lfence(); } // Load 128-bits (composed of 2 packed double-precision floating-point elements) from memory into "dst" inline __m128d XM_CALLCONV load_pd( const double *mem_addr ) { return _mm_load_pd( mem_addr ); } // Load a double-precision floating-point element from memory into the lower of "dst", and zero the upper element inline __m128d XM_CALLCONV load_sd( const double *mem_addr ) { return _mm_load_sd( mem_addr ); } // Load 128-bits of integer data from memory into "dst". "mem_addr" must be aligned on a 16-byte boundary or a general-protection exception may be generated. inline __m128i XM_CALLCONV load_all( const __m128i *mem_addr ) { return _mm_load_si128( mem_addr ); } // Load a double-precision floating-point element from memory into both elements of "dst" inline __m128d XM_CALLCONV load1_pd( const double *mem_addr ) { return _mm_load1_pd( mem_addr ); } // Load a double-precision floating-point element from memory into the upper element of "dst", and copy the lower element from "a" to "dst" inline __m128d XM_CALLCONV loadh_pd( __m128d a, const double *mem_addr ) { return _mm_loadh_pd( a, mem_addr ); } // Load 64-bit integer from memory into the first element of "dst". inline __m128i XM_CALLCONV loadl_epi64( const __m128i *mem_addr ) { return _mm_loadl_epi64( mem_addr ); } // Load a double-precision floating-point element from memory into the lower element of "dst", and copy the upper element from "a" to "dst" inline __m128d XM_CALLCONV loadl_pd( __m128d a, const double *mem_addr ) { return _mm_loadl_pd( a, mem_addr ); } // Load 2 double-precision floating-point elements from memory into "dst" in reverse order inline __m128d XM_CALLCONV loadr_pd( const double *mem_addr ) { return _mm_loadr_pd( mem_addr ); } // Load 128-bits (composed of 2 packed double-precision floating-point elements) from memory into "dst" inline __m128d XM_CALLCONV loadu_pd( const double *mem_addr ) { return _mm_loadu_pd( mem_addr ); } // Load 128-bits of integer data from memory into "dst". "mem_addr" does not need to be aligned on any particular boundary. inline __m128i XM_CALLCONV loadu_all( const __m128i *mem_addr ) { return _mm_loadu_si128( mem_addr ); } // Multiply packed signed 16-bit integers in "a" and "b", producing intermediate signed 32-bit integers inline __m128i XM_CALLCONV madd_epi16( __m128i a, __m128i b ) { return _mm_madd_epi16( a, b ); } // Conditionally store 8-bit integer elements from "a" into memory using "mask" (elements are not stored when the highest bit is not set in the corresponding element) and a non-temporal memory hint inline void XM_CALLCONV maskmoveu_all( __m128i a, __m128i mask, char *mem_addr ) { _mm_maskmoveu_si128( a, mask, mem_addr ); } // Compare packed 16-bit integers in "a" and "b", and store packed maximum values in "dst" inline __m128i XM_CALLCONV max_epi16( __m128i a, __m128i b ) { return _mm_max_epi16( a, b ); } // Compare packed unsigned 8-bit integers in "a" and "b", and store packed maximum values in "dst" inline __m128i XM_CALLCONV max_epu8( __m128i a, __m128i b ) { return _mm_max_epu8( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b", and store packed maximum values in "dst" inline __m128d XM_CALLCONV max_pd( __m128d a, __m128d b ) { return _mm_max_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b", store the maximum value in the lower element of "dst", and copy the upper element from "a" to the upper element of "dst" inline __m128d XM_CALLCONV max_sd( __m128d a, __m128d b ) { return _mm_max_sd( a, b ); } // Perform a serializing operation on all load-from-memory and store-to-memory instructions that were issued prior to this instruction inline void XM_CALLCONV mfence() { _mm_mfence(); } // Compare packed 16-bit integers in "a" and "b", and store packed minimum values in "dst" inline __m128i XM_CALLCONV min_epi16( __m128i a, __m128i b ) { return _mm_min_epi16( a, b ); } // Compare packed unsigned 8-bit integers in "a" and "b", and store packed minimum values in "dst" inline __m128i XM_CALLCONV min_epu8( __m128i a, __m128i b ) { return _mm_min_epu8( a, b ); } // Compare packed double-precision floating-point elements in "a" and "b", and store packed minimum values in "dst" inline __m128d XM_CALLCONV min_pd( __m128d a, __m128d b ) { return _mm_min_pd( a, b ); } // Compare the lower double-precision floating-point elements in "a" and "b", store the minimum value in the lower element of "dst", and copy the upper element from "a" to the upper element of "dst" inline __m128d XM_CALLCONV min_sd( __m128d a, __m128d b ) { return _mm_min_sd( a, b ); } // Copy the lower 64-bit integer in "a" to the lower element of "dst", and zero the upper element inline __m128i XM_CALLCONV move_epi64( __m128i a ) { return _mm_move_epi64( a ); } // Move the lower double-precision floating-point element from "b" to the lower element of "dst", and copy the upper element from "a" to the upper element of "dst" inline __m128d XM_CALLCONV move_sd( __m128d a, __m128d b ) { return _mm_move_sd( a, b ); } // Create mask from the most significant bit of each 8-bit element in "a" inline int XM_CALLCONV movemask_epi8( __m128i a ) { return _mm_movemask_epi8( a ); } // Set each bit of mask "dst" based on the most significant bit of the corresponding packed double-precision floating-point element in "a" inline int XM_CALLCONV movemask_pd( __m128d a ) { return _mm_movemask_pd( a ); } // Multiply the low unsigned 32-bit integers from each packed 64-bit element in "a" and "b", and store the unsigned 64-bit results in "dst" inline __m128i XM_CALLCONV mul_epu32( __m128i a, __m128i b ) { return _mm_mul_epu32( a, b ); } // Multiply packed double-precision floating-point elements in "a" and "b" inline __m128d XM_CALLCONV mul_pd( __m128d a, __m128d b ) { return _mm_mul_pd( a, b ); } // Multiply the lower double-precision floating-point element in "a" and "b" inline __m128d XM_CALLCONV mul_sd( __m128d a, __m128d b ) { return _mm_mul_sd( a, b ); } // Multiply the packed 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the high 16 bits of the intermediate integers in "dst" inline __m128i XM_CALLCONV mulhi_epi16( __m128i a, __m128i b ) { return _mm_mulhi_epi16( a, b ); } // Multiply the packed unsigned 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the high 16 bits of the intermediate integers in "dst" inline __m128i XM_CALLCONV mulhi_epu16( __m128i a, __m128i b ) { return _mm_mulhi_epu16( a, b ); } // Multiply the packed 16-bit integers in "a" and "b", producing intermediate 32-bit integers, and store the low 16 bits of the intermediate integers in "dst" inline __m128i XM_CALLCONV mullo_epi16( __m128i a, __m128i b ) { return _mm_mullo_epi16( a, b ); } // Compute the bitwise OR of packed double-precision floating-point elements in "a" and "b" inline __m128d XM_CALLCONV or_pd( __m128d a, __m128d b ) { return _mm_or_pd( a, b ); } // Compute the bitwise OR of 128 bits (representing integer data) in "a" and "b" inline __m128i XM_CALLCONV or_all( __m128i a, __m128i b ) { return _mm_or_si128( a, b ); } // Convert packed 16-bit integers from "a" and "b" to packed 8-bit integers using signed saturation inline __m128i XM_CALLCONV packs_epi16( __m128i a, __m128i b ) { return _mm_packs_epi16( a, b ); } // Convert packed 32-bit integers from "a" and "b" to packed 16-bit integers using signed saturation inline __m128i XM_CALLCONV packs_epi32( __m128i a, __m128i b ) { return _mm_packs_epi32( a, b ); } // Convert packed 16-bit integers from "a" and "b" to packed 8-bit integers using unsigned saturation inline __m128i XM_CALLCONV packus_epi16( __m128i a, __m128i b ) { return _mm_packus_epi16( a, b ); } // Provide a hint to the processor that the code sequence is a spin-wait loop inline void XM_CALLCONV pause() { _mm_pause(); } // Compute the absolute differences of packed unsigned 8-bit integers in "a" and "b", then horizontally sum each consecutive 8 differences to produce two unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low 16 bits of 64-bit elements in "dst" inline __m128i XM_CALLCONV sad_epu8( __m128i a, __m128i b ) { return _mm_sad_epu8( a, b ); } // Set packed 8-bit integers in "dst" with the supplied values inline __m128i XM_CALLCONV set_epi8( char e0, char e1, char e2, char e3, char e4, char e5, char e6, char e7, char e8, char e9, char e10, char e11, char e12, char e13, char e14, char e15 ) { return _mm_set_epi8( e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0 ); } // Set packed 8-bit integers in "dst" with the supplied values inline __m128i XM_CALLCONV set_epu8( uint8_t e0, uint8_t e1, uint8_t e2, uint8_t e3, uint8_t e4, uint8_t e5, uint8_t e6, uint8_t e7, uint8_t e8, uint8_t e9, uint8_t e10, uint8_t e11, uint8_t e12, uint8_t e13, uint8_t e14, uint8_t e15 ) { return _mm_set_epi8( (char)e15, (char)e14, (char)e13, (char)e12, (char)e11, (char)e10, (char)e9, (char)e8, (char)e7, (char)e6, (char)e5, (char)e4, (char)e3, (char)e2, (char)e1, (char)e0 ); } // Set packed 16-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epi16( short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7 ) { return _mm_set_epi16( e7, e6, e5, e4, e3, e2, e1, e0 ); } // Set packed 16-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epu16( uint16_t e0, uint16_t e1, uint16_t e2, uint16_t e3, uint16_t e4, uint16_t e5, uint16_t e6, uint16_t e7 ) { return _mm_set_epi16( (short)e7, (short)e6, (short)e5, (short)e4, (short)e3, (short)e2, (short)e1, (short)e0 ); } // Set packed 32-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epi32( int e0, int e1, int e2, int e3 ) { return _mm_set_epi32( e3, e2, e1, e0 ); } // Set packed 32-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epu32( uint32_t e0, uint32_t e1, uint32_t e2, uint32_t e3 ) { return _mm_set_epi32( (int)e3, (int)e2, (int)e1, (int)e0 ); } // Set packed 64-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epi64x( int64_t e0, int64_t e1 ) { return _mm_set_epi64x( (real_int64_t)e1, (real_int64_t)e0 ); } // Set packed 64-bit integers in "dst" with the supplied values. inline __m128i XM_CALLCONV set_epu64x( uint64_t e0, uint64_t e1 ) { return _mm_set_epi64x( (real_int64_t)e1, (real_int64_t)e0 ); } // Set packed double-precision floating-point elements in "dst" with the supplied values inline __m128d XM_CALLCONV set_pd( double e0, double e1 ) { return _mm_set_pd( e1, e0 ); } // Copy double-precision floating-point element "a" to the lower element of "dst", and zero the upper element inline __m128d XM_CALLCONV set_sd( double a ) { return _mm_set_sd( a ); } // Broadcast 8-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastb". inline __m128i XM_CALLCONV set1_epi8( char a ) { return _mm_set1_epi8( a ); } // Broadcast 8-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastb". inline __m128i XM_CALLCONV set1_epu8( uint8_t a ) { return _mm_set1_epi8( (char)a ); } // Broadcast 16-bit integer "a" to all all elements of "dst". This intrinsic may generate "vpbroadcastw". inline __m128i XM_CALLCONV set1_epi16( short a ) { return _mm_set1_epi16( a ); } // Broadcast 16-bit integer "a" to all all elements of "dst". This intrinsic may generate "vpbroadcastw". inline __m128i XM_CALLCONV set1_epu16( uint16_t a ) { return _mm_set1_epi16( (short)a ); } // Broadcast 32-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastd". inline __m128i XM_CALLCONV set1_epi32( int a ) { return _mm_set1_epi32( a ); } // Broadcast 32-bit integer "a" to all elements of "dst". This intrinsic may generate "vpbroadcastd". inline __m128i XM_CALLCONV set1_epu32( uint32_t a ) { return _mm_set1_epi32( (int)a ); } // Broadcast 64-bit integer "a" to all elements of "dst". This intrinsic may generate the "vpbroadcastq". inline __m128i XM_CALLCONV set1_epi64x( int64_t a ) { return _mm_set1_epi64x( (real_int64_t)a ); } // Broadcast 64-bit integer "a" to all elements of "dst". This intrinsic may generate the "vpbroadcastq". inline __m128i XM_CALLCONV set1_epu64x( uint64_t a ) { return _mm_set1_epi64x( (real_int64_t)a ); } // Broadcast double-precision floating-point value "a" to all elements of "dst" inline __m128d XM_CALLCONV set1_pd( double a ) { return _mm_set1_pd( a ); } // Return vector of type __m128d with all elements set to zero. inline __m128d XM_CALLCONV setzero_pd() { return _mm_setzero_pd(); } // Return vector of type __m128i with all elements set to zero. inline __m128i XM_CALLCONV setzero_all() { return _mm_setzero_si128(); } // Shuffle 32-bit integers in "a" using the control in "imm8", and store the results in "dst" template<int imm8> inline __m128i XM_CALLCONV shuffle_epi32( __m128i a ) { return _mm_shuffle_epi32( a, imm8 ); } // Shuffle double-precision floating-point elements using the control in "imm8" template<int imm8> inline __m128d XM_CALLCONV shuffle_pd( __m128d a, __m128d b ) { return _mm_shuffle_pd( a, b, imm8 ); } // Shuffle 16-bit integers in the high 64 bits of "a" using the control in "imm8" template<int imm8> inline __m128i XM_CALLCONV shufflehi_epi16( __m128i a ) { return _mm_shufflehi_epi16( a, imm8 ); } // Shuffle 16-bit integers in the low 64 bits of "a" using the control in "imm8" template<int imm8> inline __m128i XM_CALLCONV shufflelo_epi16( __m128i a ) { return _mm_shufflelo_epi16( a, imm8 ); } // Shift packed 16-bit integers in "a" left by "count" while shifting in zeros inline __m128i XM_CALLCONV sll_epi16( __m128i a, __m128i count ) { return _mm_sll_epi16( a, count ); } // Shift packed 32-bit integers in "a" left by "count" while shifting in zeros inline __m128i XM_CALLCONV sll_epi32( __m128i a, __m128i count ) { return _mm_sll_epi32( a, count ); } // Shift packed 64-bit integers in "a" left by "count" while shifting in zeros inline __m128i XM_CALLCONV sll_epi64( __m128i a, __m128i count ) { return _mm_sll_epi64( a, count ); } // Shift packed 16-bit integers in "a" left by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV slli_epi16( __m128i a ) { return _mm_slli_epi16( a, imm8 ); } // Shift packed 32-bit integers in "a" left by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV slli_epi32( __m128i a ) { return _mm_slli_epi32( a, imm8 ); } // Shift packed 64-bit integers in "a" left by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV slli_epi64( __m128i a ) { return _mm_slli_epi64( a, imm8 ); } // Shift "a" left by "imm8" bytes while shifting in zeros, and store the results in "dst" template<int imm8> inline __m128i XM_CALLCONV slli_all( __m128i a ) { return _mm_slli_si128( a, imm8 ); } // Compute the square root of packed double-precision floating-point elements in "a" inline __m128d XM_CALLCONV sqrt_pd( __m128d a ) { return _mm_sqrt_pd( a ); } // Compute the square root of the lower double-precision floating-point element in "b" inline __m128d XM_CALLCONV sqrt_sd( __m128d a, __m128d b ) { return _mm_sqrt_sd( a, b ); } // Shift packed 16-bit integers in "a" right by "count" while shifting in sign bits inline __m128i XM_CALLCONV sra_epi16( __m128i a, __m128i count ) { return _mm_sra_epi16( a, count ); } // Shift packed 32-bit integers in "a" right by "count" while shifting in sign bits inline __m128i XM_CALLCONV sra_epi32( __m128i a, __m128i count ) { return _mm_sra_epi32( a, count ); } // Shift packed 16-bit integers in "a" right by "imm8" while shifting in sign bits template<int imm8> inline __m128i XM_CALLCONV srai_epi16( __m128i a ) { return _mm_srai_epi16( a, imm8 ); } // Shift packed 32-bit integers in "a" right by "imm8" while shifting in sign bits template<int imm8> inline __m128i XM_CALLCONV srai_epi32( __m128i a ) { return _mm_srai_epi32( a, imm8 ); } // Shift packed 16-bit integers in "a" right by "count" while shifting in zeros inline __m128i XM_CALLCONV srl_epi16( __m128i a, __m128i count ) { return _mm_srl_epi16( a, count ); } // Shift packed 32-bit integers in "a" right by "count" while shifting in zeros inline __m128i XM_CALLCONV srl_epi32( __m128i a, __m128i count ) { return _mm_srl_epi32( a, count ); } // Shift packed 64-bit integers in "a" right by "count" while shifting in zeros inline __m128i XM_CALLCONV srl_epi64( __m128i a, __m128i count ) { return _mm_srl_epi64( a, count ); } // Shift packed 16-bit integers in "a" right by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV srli_epi16( __m128i a ) { return _mm_srli_epi16( a, imm8 ); } // Shift packed 32-bit integers in "a" right by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV srli_epi32( __m128i a ) { return _mm_srli_epi32( a, imm8 ); } // Shift packed 64-bit integers in "a" right by "imm8" while shifting in zeros template<int imm8> inline __m128i XM_CALLCONV srli_epi64( __m128i a ) { return _mm_srli_epi64( a, imm8 ); } // Shift "a" right by "imm8" bytes while shifting in zeros, and store the results in "dst" template<int imm8> inline __m128i XM_CALLCONV srli_all( __m128i a ) { return _mm_srli_si128( a, imm8 ); } // Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory inline void XM_CALLCONV store_pd( double *mem_addr, __m128d a ) { _mm_store_pd( mem_addr, a ); } // Store the lower double-precision floating-point element from "a" into memory inline void XM_CALLCONV store_sd( double *mem_addr, __m128d a ) { _mm_store_sd( mem_addr, a ); } // Store 128-bits of integer data from "a" into memory. "mem_addr" must be aligned on a 16-byte boundary or a general-protection exception may be generated. inline void XM_CALLCONV store_all( __m128i *mem_addr, __m128i a ) { _mm_store_si128( mem_addr, a ); } // Store the lower double-precision floating-point element from "a" into 2 contiguous elements in memory inline void XM_CALLCONV store1_pd( double *mem_addr, __m128d a ) { _mm_store1_pd( mem_addr, a ); } // Store the upper double-precision floating-point element from "a" into memory inline void XM_CALLCONV storeh_pd( double *mem_addr, __m128d a ) { _mm_storeh_pd( mem_addr, a ); } // Store 64-bit integer from the first element of "a" into memory. inline void XM_CALLCONV storel_epi64( __m128i *mem_addr, __m128i a ) { _mm_storel_epi64( mem_addr, a ); } // Store the lower double-precision floating-point element from "a" into memory inline void XM_CALLCONV storel_pd( double *mem_addr, __m128d a ) { _mm_storel_pd( mem_addr, a ); } // Store 2 double-precision floating-point elements from "a" into memory in reverse order inline void XM_CALLCONV storer_pd( double *mem_addr, __m128d a ) { _mm_storer_pd( mem_addr, a ); } // Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory inline void XM_CALLCONV storeu_pd( double *mem_addr, __m128d a ) { _mm_storeu_pd( mem_addr, a ); } // Store 128-bits of integer data from "a" into memory. "mem_addr" does not need to be aligned on any particular boundary. inline void XM_CALLCONV storeu_all( __m128i *mem_addr, __m128i a ) { _mm_storeu_si128( mem_addr, a ); } // Store 128-bits (composed of 2 packed double-precision floating-point elements) from "a" into memory using a non-temporal memory hint inline void XM_CALLCONV stream_pd( double *mem_addr, __m128d a ) { _mm_stream_pd( mem_addr, a ); } // Store 32-bit integer "a" into memory using a non-temporal hint to minimize cache pollution inline void XM_CALLCONV stream_si32( int *mem_addr, int a ) { _mm_stream_si32( mem_addr, a ); } // Store 128-bits of integer data from "a" into memory using a non-temporal memory hint inline void XM_CALLCONV stream_all( __m128i *mem_addr, __m128i a ) { _mm_stream_si128( mem_addr, a ); } // Subtract packed 8-bit integers in "b" from packed 8-bit integers in "a" inline __m128i XM_CALLCONV sub_epi8( __m128i a, __m128i b ) { return _mm_sub_epi8( a, b ); } // Subtract packed 16-bit integers in "b" from packed 16-bit integers in "a" inline __m128i XM_CALLCONV sub_epi16( __m128i a, __m128i b ) { return _mm_sub_epi16( a, b ); } // Subtract packed 32-bit integers in "b" from packed 32-bit integers in "a" inline __m128i XM_CALLCONV sub_epi32( __m128i a, __m128i b ) { return _mm_sub_epi32( a, b ); } // Subtract packed 64-bit integers in "b" from packed 64-bit integers in "a" inline __m128i XM_CALLCONV sub_epi64( __m128i a, __m128i b ) { return _mm_sub_epi64( a, b ); } // Subtract packed double-precision floating-point elements in "b" from packed double-precision floating-point elements in "a" inline __m128d XM_CALLCONV sub_pd( __m128d a, __m128d b ) { return _mm_sub_pd( a, b ); } // Subtract the lower double-precision floating-point element in "b" from the lower double-precision floating-point element in "a" inline __m128d XM_CALLCONV sub_sd( __m128d a, __m128d b ) { return _mm_sub_sd( a, b ); } // Subtract packed 8-bit integers in "b" from packed 8-bit integers in "a" using saturation inline __m128i XM_CALLCONV subs_epi8( __m128i a, __m128i b ) { return _mm_subs_epi8( a, b ); } // Subtract packed 16-bit integers in "b" from packed 16-bit integers in "a" using saturation inline __m128i XM_CALLCONV subs_epi16( __m128i a, __m128i b ) { return _mm_subs_epi16( a, b ); } // Subtract packed unsigned 8-bit integers in "b" from packed unsigned 8-bit integers in "a" using saturation inline __m128i XM_CALLCONV subs_epu8( __m128i a, __m128i b ) { return _mm_subs_epu8( a, b ); } // Subtract packed unsigned 16-bit integers in "b" from packed unsigned 16-bit integers in "a" using saturation inline __m128i XM_CALLCONV subs_epu16( __m128i a, __m128i b ) { return _mm_subs_epu16( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for equality inline int XM_CALLCONV ucomieq_sd( __m128d a, __m128d b ) { return _mm_ucomieq_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for greater-than-or-equal inline int XM_CALLCONV ucomige_sd( __m128d a, __m128d b ) { return _mm_ucomige_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for greater-than inline int XM_CALLCONV ucomigt_sd( __m128d a, __m128d b ) { return _mm_ucomigt_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for less-than-or-equal inline int XM_CALLCONV ucomile_sd( __m128d a, __m128d b ) { return _mm_ucomile_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for less-than inline int XM_CALLCONV ucomilt_sd( __m128d a, __m128d b ) { return _mm_ucomilt_sd( a, b ); } // Compare the lower double-precision floating-point element in "a" and "b" for not-equal inline int XM_CALLCONV ucomineq_sd( __m128d a, __m128d b ) { return _mm_ucomineq_sd( a, b ); } // Return vector of type __m128d with undefined elements. inline __m128d XM_CALLCONV undefined_pd() { return _mm_undefined_pd(); } // Return vector of type __m128i with undefined elements. inline __m128i XM_CALLCONV undefined_all() { return _mm_undefined_si128(); } // Unpack and interleave 8-bit integers from the high half of "a" and "b" inline __m128i XM_CALLCONV unpackhi_epi8( __m128i a, __m128i b ) { return _mm_unpackhi_epi8( a, b ); } // Unpack and interleave 16-bit integers from the high half of "a" and "b" inline __m128i XM_CALLCONV unpackhi_epi16( __m128i a, __m128i b ) { return _mm_unpackhi_epi16( a, b ); } // Unpack and interleave 32-bit integers from the high half of "a" and "b" inline __m128i XM_CALLCONV unpackhi_epi32( __m128i a, __m128i b ) { return _mm_unpackhi_epi32( a, b ); } // Unpack and interleave 64-bit integers from the high half of "a" and "b" inline __m128i XM_CALLCONV unpackhi_epi64( __m128i a, __m128i b ) { return _mm_unpackhi_epi64( a, b ); } // Unpack and interleave double-precision floating-point elements from the high half of "a" and "b" inline __m128d XM_CALLCONV unpackhi_pd( __m128d a, __m128d b ) { return _mm_unpackhi_pd( a, b ); } // Unpack and interleave 8-bit integers from the low half of "a" and "b" inline __m128i XM_CALLCONV unpacklo_epi8( __m128i a, __m128i b ) { return _mm_unpacklo_epi8( a, b ); } // Unpack and interleave 16-bit integers from the low half of "a" and "b" inline __m128i XM_CALLCONV unpacklo_epi16( __m128i a, __m128i b ) { return _mm_unpacklo_epi16( a, b ); } // Unpack and interleave 32-bit integers from the low half of "a" and "b" inline __m128i XM_CALLCONV unpacklo_epi32( __m128i a, __m128i b ) { return _mm_unpacklo_epi32( a, b ); } // Unpack and interleave 64-bit integers from the low half of "a" and "b" inline __m128i XM_CALLCONV unpacklo_epi64( __m128i a, __m128i b ) { return _mm_unpacklo_epi64( a, b ); } // Unpack and interleave double-precision floating-point elements from the low half of "a" and "b" inline __m128d XM_CALLCONV unpacklo_pd( __m128d a, __m128d b ) { return _mm_unpacklo_pd( a, b ); } // Compute the bitwise XOR of packed double-precision floating-point elements in "a" and "b" inline __m128d XM_CALLCONV xor_pd( __m128d a, __m128d b ) { return _mm_xor_pd( a, b ); } // Compute the bitwise XOR of 128 bits (representing integer data) in "a" and "b" inline __m128i XM_CALLCONV xor_all( __m128i a, __m128i b ) { return _mm_xor_si128( a, b ); } #if _M_X64 // Convert the lower double-precision floating-point element in "a" to a 64-bit integer inline int64_t XM_CALLCONV cvtsd_si64( __m128d a ) { return (int64_t)_mm_cvtsd_si64( a ); } // Convert the lower double-precision floating-point element in "a" to a 64-bit integer inline int64_t XM_CALLCONV cvtsd_si64x( __m128d a ) { return (int64_t)_mm_cvtsd_si64x( a ); } // Copy the lower 64-bit integer in "a" to "dst". inline int64_t XM_CALLCONV cvtsi128_si64( __m128i a ) { return (int64_t)_mm_cvtsi128_si64( a ); } // Copy the lower 64-bit integer in "a" to "dst". inline int64_t XM_CALLCONV cvtsi128_si64x( __m128i a ) { return (int64_t)_mm_cvtsi128_si64x( a ); } // Convert the 64-bit integer "b" to a double-precision floating-point element inline __m128d XM_CALLCONV cvtsi64_sd( __m128d a, int64_t b ) { return _mm_cvtsi64_sd( a, (real_int64_t)b ); } // Copy 64-bit integer "a" to the lower element of "dst", and zero the upper element inline __m128i XM_CALLCONV cvtsi64_all( int64_t a ) { return _mm_cvtsi64_si128( (real_int64_t)a ); } // Convert the 64-bit integer "b" to a double-precision floating-point element inline __m128d XM_CALLCONV cvtsi64x_sd( __m128d a, int64_t b ) { return _mm_cvtsi64x_sd( a, (real_int64_t)b ); } // Copy 64-bit integer "a" to the lower element of "dst", and zero the upper element inline __m128i XM_CALLCONV cvtsi64x_all( int64_t a ) { return _mm_cvtsi64x_si128( (real_int64_t)a ); } // Convert the lower double-precision floating-point element in "a" to a 64-bit integer with truncation inline int64_t XM_CALLCONV cvttsd_si64( __m128d a ) { return (int64_t)_mm_cvttsd_si64( a ); } // Convert the lower double-precision floating-point element in "a" to a 64-bit integer with truncation inline int64_t XM_CALLCONV cvttsd_si64x( __m128d a ) { return (int64_t)_mm_cvttsd_si64x( a ); } // Store 64-bit integer "a" into memory using a non-temporal hint to minimize cache pollution inline void XM_CALLCONV stream_si64( int64_t *mem_addr, int64_t a ) { _mm_stream_si64( (real_int64_t *)mem_addr, (real_int64_t)a ); } #endif // _M_X64 using VecInteger = __m128i; static constexpr int allValuesMask_epi8 = 0xFFFF; using VecFloat64 = __m128d; static constexpr int allValuesMask_pd = 0x3; } // namespace Intrinsics::Sse } // namespace Intrinsics
34.341697
268
0.707262
Const-me
3ebf0fda48088cd22f4ee0c2411c57f197ba861e
5,838
hpp
C++
sycl/include/CL/sycl/detail/program_manager/program_manager.hpp
nyalloc/llvm
2d6dcd09b6a418c05c02b7beb6bb042ec73daf43
[ "Apache-2.0" ]
null
null
null
sycl/include/CL/sycl/detail/program_manager/program_manager.hpp
nyalloc/llvm
2d6dcd09b6a418c05c02b7beb6bb042ec73daf43
[ "Apache-2.0" ]
null
null
null
sycl/include/CL/sycl/detail/program_manager/program_manager.hpp
nyalloc/llvm
2d6dcd09b6a418c05c02b7beb6bb042ec73daf43
[ "Apache-2.0" ]
null
null
null
//==------ program_manager.hpp --- SYCL program manager---------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #pragma once #include <CL/sycl/detail/common.hpp> #include <CL/sycl/detail/os_util.hpp> #include <CL/sycl/detail/pi.hpp> #include <CL/sycl/stl.hpp> #include <map> #include <vector> // +++ Entry points referenced by the offload wrapper object { /// Executed as a part of current module's (.exe, .dll) static initialization. /// Registers device executable images with the runtime. extern "C" void __tgt_register_lib(pi_device_binaries desc); /// Executed as a part of current module's (.exe, .dll) static /// de-initialization. /// Unregisters device executable images with the runtime. extern "C" void __tgt_unregister_lib(pi_device_binaries desc); // +++ } namespace cl { namespace sycl { class context; namespace detail { using DeviceImage = pi_device_binary_struct; // Custom deleter for the DeviceImage. Must only be called for "orphan" images // allocated by the runtime. Those Images which are part of binaries must not // be attempted to de-allocate. struct ImageDeleter; // Provides single loading and building OpenCL programs with unique contexts // that is necessary for no interoperability cases with lambda. class ProgramManager { public: // Returns the single instance of the program manager for the entire process. // Can only be called after staticInit is done. static ProgramManager &getInstance(); DeviceImage &getDeviceImage(OSModuleHandle M, const string_class &KernelName, const context &Context); RT::PiProgram createPIProgram(const DeviceImage &Img, const context &Context); RT::PiProgram getBuiltPIProgram(OSModuleHandle M, const context &Context, const string_class &KernelName); RT::PiKernel getOrCreateKernel(OSModuleHandle M, const context &Context, const string_class &KernelName); RT::PiProgram getClProgramFromClKernel(RT::PiKernel Kernel); void addImages(pi_device_binaries DeviceImages); void debugDumpBinaryImages() const; void debugDumpBinaryImage(const DeviceImage *Img) const; static string_class getProgramBuildLog(const RT::PiProgram &Program); private: ProgramManager(); ~ProgramManager() = default; ProgramManager(ProgramManager const &) = delete; ProgramManager &operator=(ProgramManager const &) = delete; DeviceImage &getDeviceImage(OSModuleHandle M, KernelSetId KSId, const context &Context); void build(RT::PiProgram Program, const string_class &Options, std::vector<RT::PiDevice> Devices); /// Provides a new kernel set id for grouping kernel names together KernelSetId getNextKernelSetId() const; /// Returns the kernel set associated with the kernel, handles some special /// cases (when reading images from file or using images with no entry info) KernelSetId getKernelSetId(OSModuleHandle M, const string_class &KernelName) const; /// Returns the format of the binary image RT::PiDeviceBinaryType getFormat(const DeviceImage &Img) const; /// Dumps image to current directory void dumpImage(const DeviceImage &Img, KernelSetId KSId) const; /// The three maps below are used during kernel resolution. Any kernel is /// identified by its name and the OS module it's coming from, allowing /// kernels with identical names in different OS modules. The following /// assumption is made: for any two device images in a SYCL application their /// kernel sets are either identical or disjoint. /// Based on this assumption, m_KernelSets is used to group kernels together /// into sets by assigning a set ID to them during device image registration. /// This ID is then mapped to a vector of device images containing kernels /// from the set (m_DeviceImages). /// An exception is made for device images with no entry information: a /// special kernel set ID is used for them which is assigned to just the OS /// module. These kernel set ids are stored in m_OSModuleKernelSets and device /// images associated with them are assumed to contain all kernels coming from /// that OS module. /// Keeps all available device executable images added via \ref addImages. /// Organizes the images as a map from a kernel set id to the vector of images /// containing kernels from that set. /// Access must be guarded by the \ref Sync::getGlobalLock() std::map<KernelSetId, std::unique_ptr<std::vector<DeviceImage *>>> m_DeviceImages; using StrToKSIdMap = std::map<string_class, KernelSetId>; /// Maps names of kernels from a specific OS module (.exe .dll) to their set /// id (the sets are disjoint). /// Access must be guarded by the \ref Sync::getGlobalLock() std::map<OSModuleHandle, StrToKSIdMap> m_KernelSets; /// Keeps kernel sets for OS modules containing images without entry info. /// Such images are assumed to contain all kernel associated with the module. /// Access must be guarded by the \ref Sync::getGlobalLock() std::map<OSModuleHandle, KernelSetId> m_OSModuleKernelSets; /// Keeps device images not bound to a particular module. Program manager /// allocated memory for these images, so they are auto-freed in destructor. /// No image can out-live the Program manager. std::vector<std::unique_ptr<DeviceImage, ImageDeleter>> m_OrphanDeviceImages; /// True iff a SPIRV file has been specified with an environment variable bool m_UseSpvFile = false; }; } // namespace detail } // namespace sycl } // namespace cl
45.255814
84
0.721651
nyalloc
3ec00cb9112f6fba6a668f397a9920e4c5825b48
1,318
cpp
C++
src/Utils/Utils/DataStructures/OctupoleMatrix.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/DataStructures/OctupoleMatrix.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/DataStructures/OctupoleMatrix.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include "OctupoleMatrix.h" #include "DipoleMatrix.h" namespace Scine { namespace Utils { void OctupoleMatrix::reset(int dimension) { std::for_each(octupoleMatrices_.begin(), octupoleMatrices_.end(), [&](auto& octupoleMatrix) { octupoleMatrix.setDimension(dimension, dimension); }); } Eigen::MatrixXd& OctupoleMatrix::operator[](int index) { return const_cast<Eigen::MatrixXd&>(const_cast<const OctupoleMatrix*>(this)->operator[](index)); } const Eigen::MatrixXd& OctupoleMatrix::operator[](int index) const { return octupoleMatrices_.at(index).get0(); } OctupoleMatrix::OctupoleMatrix(const OctupoleMatrix& rhs) = default; OctupoleMatrix& OctupoleMatrix::operator=(const OctupoleMatrix& rhs) { if (this != &rhs) { octupoleMatrices_ = rhs.octupoleMatrices_; } return *this; } OctupoleMatrix::OctupoleMatrix() = default; OctupoleMatrix::OctupoleMatrix(OctupoleMatrix&& rhs) noexcept = default; OctupoleMatrix& OctupoleMatrix::operator=(OctupoleMatrix&& rhs) noexcept = default; OctupoleMatrix::~OctupoleMatrix() = default; } // namespace Utils } // namespace Scine
33.794872
98
0.729894
DockBio
3ec11f59a85d7058c0f9a63261e4fa26f6725f5d
79,527
cpp
C++
Source/Scene/vaSceneOld.cpp
GameTechDev/XeGTAO
0d177ce06bfa642f64d8af4de1197ad1bcb862d4
[ "MIT" ]
318
2021-08-20T10:16:12.000Z
2022-03-24T03:08:16.000Z
Source/Scene/vaSceneOld.cpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
5
2021-09-03T11:40:54.000Z
2022-02-09T12:37:12.000Z
Source/Scene/vaSceneOld.cpp
s-nase/XeGTAO
11e439c33e3dd7c1e4ea0fc73733ca840bc95bec
[ "MIT" ]
22
2021-09-02T03:33:18.000Z
2022-02-23T06:36:39.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2016-2021, Intel Corporation // // SPDX-License-Identifier: MIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaSceneOld.h" #if 0 #include "Rendering/vaAssetPack.h" #include "Rendering/vaDebugCanvas.h" #include "Core/System/vaFileTools.h" #include "IntegratedExternals/vaImguiIntegration.h" #include "Rendering/vaRenderMesh.h" #include "Rendering/vaRenderMaterial.h" #include "Core/vaApplicationBase.h" #include <set> using namespace Vanilla; using namespace Vanilla::Scene; vaSceneObject::vaSceneObject( ) { } vaSceneObject::~vaSceneObject( ) { // children/parents must be disconnected! assert( m_parent == nullptr ); assert( m_children.size() == 0 ); } vaMatrix4x4 vaSceneObject::GetWorldTransform( ) const { #ifdef _DEBUG shared_ptr<vaSceneOld> scene = GetScene(); assert( scene != nullptr ); assert( m_lastSceneTickIndex == scene->GetTickIndex( ) ); // for whatever reason, you're getting stale data #endif return m_computedWorldTransform; } void vaSceneObject::FindClosestRecursive( const vaVector3 & worldLocation, shared_ptr<vaSceneObject> & currentClosest, float & currentDistance ) { // can't get any closer than this if( currentDistance == 0.0f ) return; for( int i = 0; i < m_children.size( ); i++ ) { m_children[i]->FindClosestRecursive( worldLocation, currentClosest, currentDistance ); } float distance = GetGlobalAABB().NearestDistanceToPoint( worldLocation ); if( distance < currentDistance ) { currentDistance = distance; currentClosest = this->shared_from_this(); } } void vaSceneObject::TickRecursive( vaSceneOld & scene, float deltaTime ) { assert( m_scene.lock() == scene.shared_from_this() ); assert( !m_destroyedButNotYetRemovedFromScene ); assert( !m_createdButNotYetAddedToScene ); // Update transforms (OK to rely on parent's transforms, they've already been updated) if( m_parent == nullptr ) m_computedWorldTransform = GetLocalTransform(); else m_computedWorldTransform = GetLocalTransform() * m_parent->GetWorldTransform(); if( (m_computedLocalBoundingBox == vaBoundingBox::Degenerate || m_computedLocalBoundingBoxIncomplete ) && m_renderMeshes.size( ) > 0 ) { UpdateLocalBoundingBox(); } // Update tick index (transforms ok, but beware, bounding boxes not yet) m_lastSceneTickIndex = scene.GetTickIndex(); // Our bounding box, oriented in world space vaOrientedBoundingBox oobb = vaOrientedBoundingBox( m_computedLocalBoundingBox, m_computedWorldTransform ); //vaDebugCanvas3D::GetInstance().DrawBox( oobb, 0xFF000000, 0x20FF8080 ); m_computedGlobalBoundingBox = oobb.ComputeEnclosingAABB(); //vaDebugCanvas3D::GetInstance().DrawBox( m_computedGlobalBoundingBox, 0xFF000000, 0x20FF8080 ); for( int i = 0; i < m_children.size( ); i++ ) { m_children[i]->TickRecursive( scene, deltaTime ); m_computedGlobalBoundingBox = vaBoundingBox::Combine( m_computedGlobalBoundingBox, m_children[i]->GetGlobalAABB() ); } } shared_ptr<vaRenderMesh> vaSceneObject::GetRenderMesh( int index ) const { if( index < 0 || index >= m_renderMeshes.size( ) ) { assert( false ); return nullptr; } return vaUIDObjectRegistrar::Find<vaRenderMesh>( m_renderMeshes[index] ); } void vaSceneObject::AddRenderMeshRef( const shared_ptr<vaRenderMesh> & renderMesh ) { const vaGUID & uid = renderMesh->UIDObject_GetUID(); assert( std::find( m_renderMeshes.begin(), m_renderMeshes.end(), uid ) == m_renderMeshes.end() ); m_renderMeshes.push_back( uid ); //m_cachedRenderMeshes.push_back( renderMesh ); //assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() ); m_computedLocalBoundingBox = vaBoundingBox::Degenerate; } bool vaSceneObject::RemoveRenderMeshRef( int index ) { //assert( m_cachedRenderMeshes.size( ) == m_renderMeshes.size( ) ); if( index < 0 || index >= m_renderMeshes.size( ) ) { assert( false ); return false; } m_renderMeshes[index] = m_renderMeshes.back(); m_renderMeshes.pop_back(); //m_cachedRenderMeshes[index] = m_cachedRenderMeshes.back( ); //m_cachedRenderMeshes.pop_back( ); m_computedLocalBoundingBox = vaBoundingBox::Degenerate; return true; } bool vaSceneObject::RemoveRenderMeshRef( const shared_ptr<vaRenderMesh> & renderMesh ) { //assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() ); const vaGUID & uid = renderMesh->UIDObject_GetUID(); int indexRemoved = vector_find_and_remove( m_renderMeshes, uid ); if( indexRemoved == -1 ) { assert( false ); return false; } //if( indexRemoved < (m_cachedRenderMeshes.size()-1) ) // m_cachedRenderMeshes[indexRemoved] = m_cachedRenderMeshes.back(); // m_cachedRenderMeshes.pop_back(); m_computedLocalBoundingBox = vaBoundingBox::Degenerate; return true; } bool vaSceneObject::Serialize( vaXMLSerializer & serializer ) { auto scene = m_scene.lock(); assert( scene != nullptr ); // element opened by the parent, just fill in attributes VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", m_name ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR0", m_localTransform.Row(0) ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR1", m_localTransform.Row(1) ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR2", m_localTransform.Row(2) ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector4>( "TransformR3", m_localTransform.Row(3) ) ); // VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector3>( "AABBMin", m_boundingBox.Min ) ); // VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaVector3>( "AABBSize", m_boundingBox.Size ) ); assert( serializer.GetVersion() > 0 ); serializer.SerializeArray( "RenderMeshes", m_renderMeshes ); VERIFY_TRUE_RETURN_ON_FALSE( scene->SerializeObjectsRecursive( serializer, "ChildObjects", m_children, this->shared_from_this() ) ); if( serializer.IsReading( ) ) { m_lastSceneTickIndex = -1; m_computedWorldTransform = vaMatrix4x4::Identity; m_computedLocalBoundingBox = vaBoundingBox::Degenerate; m_computedGlobalBoundingBox = vaBoundingBox::Degenerate; // m_cachedRenderMeshes.resize( m_renderMeshes.size() ); m_localTransform.Row(0).w = 0.0f; m_localTransform.Row(1).w = 0.0f; m_localTransform.Row(2).w = 0.0f; m_localTransform.Row(3).w = 1.0f; SetLocalTransform( m_localTransform ); } return true; } void vaSceneObject::MarkAsDestroyed( bool markChildrenAsWell ) { // already destroyed? this shouldn't ever happen - avoid at all cost assert( !IsDestroyed() ); m_destroyedButNotYetRemovedFromScene = true; if( markChildrenAsWell ) { for( int i = 0; i < (int)m_children.size( ); i++ ) m_children[i]->MarkAsDestroyed( true ); } } void vaSceneObject::RegisterChildAdded( const shared_ptr<vaSceneObject> & child ) { assert( std::find( m_children.begin(), m_children.end(), child ) == m_children.end() ); m_children.push_back( child ); } void vaSceneObject::RegisterChildRemoved( const shared_ptr<vaSceneObject> & child ) { bool allOk = vector_find_and_remove( m_children, child ) != -1; assert( allOk ); // if this fires, there's a serious error somewhere! allOk; } void vaSceneObject::SetParent( const shared_ptr<vaSceneObject> & parent ) { if( parent == m_parent ) { // nothing to change, nothing to do return; } auto scene = m_scene.lock(); assert( scene != nullptr ); if( scene == nullptr ) return; // changing parent? then unregister us from previous (either root or another object) if( m_parent != nullptr ) m_parent->RegisterChildRemoved( this->shared_from_this() ); else scene->RegisterRootObjectRemoved( this->shared_from_this() ); // removing parent? just register as a root object if( parent == nullptr ) { m_parent = nullptr; scene->RegisterRootObjectAdded( this->shared_from_this() ); return; } // make sure we're not setting up a no circular dependency or breaking the max node tree depth const int c_maxObjectTreeDepth = 32; bool allOk = false; shared_ptr<vaSceneObject> pp = parent; for( int i = 0; i < c_maxObjectTreeDepth; i++ ) { if( pp == nullptr ) { allOk = true; break; } if( pp.get( ) == this ) { VA_LOG_ERROR( "vaSceneObject::SetParent failed - circular dependency detected" ); allOk = false; return; } pp = pp->GetParent(); } if( !allOk ) { VA_LOG_ERROR( "vaSceneObject::SetParent failed - tree depth over the limit of %d", c_maxObjectTreeDepth ); return; } m_parent = parent; m_parent->RegisterChildAdded( this->shared_from_this() ); } // static vaBoundingSphere g_cullOutsideBS( vaVector3( 0, 0, 0 ), 0.0f ); // static vaBoundingBox g_cullInsideBox( vaVector3( 0, 0, 0 ), vaVector3( 0, 0, 0 ) ); // static bool g_doCull = false; // static int64 g_isInside = 0; // static int64 g_isOutside = 0; vaDrawResultFlags vaSceneObject::SelectForRendering( vaRenderInstanceList * opaqueList, vaRenderInstanceList * transparentList, const vaRenderInstanceList::FilterSettings & filter, const SelectionFilterCallback & customFilter ) { vaDrawResultFlags drawResults = vaDrawResultFlags::None; // first and easy one, global filter by frustum planes if( filter.FrustumPlanes.size() > 0 ) if( m_computedGlobalBoundingBox.IntersectFrustum( filter.FrustumPlanes ) == vaIntersectType::Outside ) return vaDrawResultFlags::None; vaMatrix4x4 worldTransform = GetWorldTransform( ); for( int i = 0; i < m_renderMeshes.size(); i++ ) { auto renderMesh = GetRenderMesh(i); if( renderMesh == nullptr ) { drawResults |= vaDrawResultFlags::AssetsStillLoading; continue; } // resolve material here - both easier to manage and faster (when this gets parallelized) auto renderMaterial = renderMesh->GetMaterial(); if( renderMaterial == nullptr ) { drawResults |= vaDrawResultFlags::AssetsStillLoading; renderMaterial = renderMesh->GetManager().GetRenderDevice().GetMaterialManager().GetDefaultMaterial( ); } vaOrientedBoundingBox obb = vaOrientedBoundingBox::FromAABBAndTransform( renderMesh->GetAABB(), worldTransform ); if( filter.FrustumPlanes.size() > 0 ) if( obb.IntersectFrustum( filter.FrustumPlanes ) == vaIntersectType::Outside ) continue; int baseShadingRate = 0; vaVector4 emissiveAdd = {0,0,0,1}; bool doSelect = ( customFilter != nullptr )?( customFilter( *this, worldTransform, obb, *renderMesh, *renderMaterial, baseShadingRate, emissiveAdd ) ):( true ); if( !doSelect ) continue; vaShadingRate finalShadingRate = renderMaterial->ComputeShadingRate( baseShadingRate ); vaRenderInstanceList::ItemProperties properties{ finalShadingRate, emissiveAdd, 0.0f }; vaRenderInstanceList::ItemIdentifiers identifiers{ vaRenderInstanceList::SceneRuntimeIDNull, vaRenderInstanceList::SceneEntityIDNull }; if( renderMaterial->IsTransparent() ) { if( transparentList != nullptr ) transparentList->Insert( vaFramePtr<vaRenderMesh>(renderMesh), vaFramePtr<vaRenderMaterial>(renderMaterial), worldTransform, properties, identifiers ); } else { if( opaqueList != nullptr ) opaqueList->Insert( vaFramePtr<vaRenderMesh>(renderMesh), vaFramePtr<vaRenderMaterial>(renderMaterial), worldTransform, properties, identifiers ); } } return drawResults; } void vaSceneObject::RegisterUsedAssetPacks( std::function<void( const vaAssetPack & )> registerFunction ) { for( int i = 0; i < m_renderMeshes.size(); i++ ) { auto renderMesh = GetRenderMesh(i); if( renderMesh != nullptr && renderMesh->GetParentAsset() != nullptr ) registerFunction( renderMesh->GetParentAsset()->GetAssetPack() ); } } void vaSceneObject::UpdateLocalBoundingBox( ) { //assert( m_cachedRenderMeshes.size() == m_renderMeshes.size() ); m_computedLocalBoundingBox = vaBoundingBox::Degenerate; m_computedGlobalBoundingBox = vaBoundingBox::Degenerate; m_computedLocalBoundingBoxIncomplete = false; for( int i = 0; i < m_renderMeshes.size(); i++ ) { auto renderMesh = GetRenderMesh(i); if( renderMesh != nullptr ) m_computedLocalBoundingBox = vaBoundingBox::Combine( m_computedLocalBoundingBox, renderMesh->GetAABB() ); else m_computedLocalBoundingBoxIncomplete = true; } } void vaSceneObject::UIPropertiesItemTick( vaApplicationBase &, bool , bool ) { #ifdef VA_IMGUI_INTEGRATION_ENABLED auto scene = m_scene.lock(); assert( scene != nullptr ); if( ImGui::Button( "Rename" ) ) ImGuiEx_PopupInputStringBegin( "Rename object", m_name ); ImGuiEx_PopupInputStringTick( "Rename object", m_name ); ImGui::SameLine(); if( ImGui::Button( "Delete" ) ) { scene->DestroyObject( this->shared_from_this(), false, true ); return; } bool transChanged = false; vaMatrix4x4 localTransform = m_localTransform; transChanged |= ImGui::InputFloat4( "LocalTransformRow0", &localTransform.m[0][0] ); transChanged |= ImGui::InputFloat4( "LocalTransformRow1", &localTransform.m[1][0] ); transChanged |= ImGui::InputFloat4( "LocalTransformRow2", &localTransform.m[2][0] ); transChanged |= ImGui::InputFloat4( "LocalTransformRow3", &localTransform.m[3][0] ); if( transChanged ) { SetLocalTransform( localTransform ); } /* vaVector3 raxis; float rangle; m_rotation.ToAxisAngle( raxis, rangle ); rangle = rangle * 180.0f / VA_PIf; bool changed = ImGui::InputFloat3( "Rotation axis", &raxis.x ); changed |= ImGui::InputFloat( "Rotation angle", &rangle, 5.0f, 30.0f, 3 ); if( changed ) m_rotation = vaQuaternion::RotationAxis( raxis, rangle * VA_PIf / 180.0f ); */ string parentName = (m_parent == nullptr)?("none"):(m_parent->GetName().c_str() ); ImGui::Text( "Parent: %s", parentName.c_str() ); ImGui::Text( "Child object count: %d", m_children.size() ); ImGui::Text( "Render mesh count: %d", m_renderMeshes.size() ); if( ImGui::BeginChild( "rendermeshlist", { 0, ImGui::GetFontSize() * 8 }, true ) ) { for( int meshIndex = 0; meshIndex < m_renderMeshes.size(); meshIndex++ ) { vaGUID & meshID = m_renderMeshes[meshIndex]; string prefix = vaStringTools::Format( "%03d - ", meshIndex ); if( meshID == vaGUID::Null ) { ImGui::Selectable( (prefix + "[null GUID]").c_str(), false, ImGuiSelectableFlags_Disabled ); continue; } auto renderMesh = GetRenderMesh( meshIndex ); if( renderMesh == nullptr ) // maybe still loading { ImGui::Selectable( ( prefix + "[not found]" ).c_str( ), false, ImGuiSelectableFlags_Disabled ); continue; } vaAsset * assetPtr = renderMesh->GetParentAsset(); if( assetPtr == nullptr ) { ImGui::Selectable( ( prefix + "[not an asset]" ).c_str( ), false, ImGuiSelectableFlags_Disabled ); continue; } shared_ptr<vaAsset> asset = assetPtr->GetSharedPtr( ); if( asset == nullptr ) { ImGui::Selectable( ( prefix + "[error acquiring shared_ptr]" ).c_str( ), false, ImGuiSelectableFlags_Disabled ); continue; } if( ImGui::Selectable( (prefix + assetPtr->Name( )).c_str( ), false, ImGuiSelectableFlags_AllowDoubleClick ) ) { if( ImGui::IsMouseDoubleClicked( 0 ) ) vaUIManager::GetInstance( ).SelectPropertyItem( asset ); } if( asset->GetResource( ) != nullptr && ImGui::IsItemHovered( ) ) asset->GetResource( )->SetUIShowSelectedFrameIndex( asset->GetAssetPack().GetRenderDevice().GetCurrentFrameIndex( ) + 1 ); } } ImGui::EndChild( ); #endif } int vaSceneObject::SplitMeshes( const std::vector<vaPlane> & splitPlanes, std::vector<shared_ptr<vaRenderMesh>> & outOldMeshes, std::vector<shared_ptr<vaRenderMesh>> & outNewMeshes, const int minTriangleCountThreshold, const std::vector<shared_ptr<vaRenderMesh>> & candidateMeshes, bool splitIfIntersectingTriangles ) { int totalSplitCount = 0; int splitCount; vaMatrix4x4 worldTransform = GetWorldTransform(); std::vector<uint32> newIndicesLeft, newIndicesRight; do { splitCount = 0; for( int meshIndex = 0; meshIndex < m_renderMeshes.size( ); meshIndex++ ) { auto renderMesh = GetRenderMesh(meshIndex); assert( renderMesh != nullptr ); // still loading? if( renderMesh == nullptr ) continue; // if has candidate filter, use that but also consider any newly created a candidate because they must have inherited the original one if( candidateMeshes.size() > 0 ) { bool found = false; for( int cmi = 0; cmi < candidateMeshes.size() && !found; cmi++ ) found |= candidateMeshes[cmi] == renderMesh; for( int cmi = 0; cmi < outNewMeshes.size() && !found; cmi++ ) found |= outNewMeshes[cmi] == renderMesh; if( !found ) continue; } const std::vector<vaRenderMesh::StandardVertex> & vertices = renderMesh->Vertices(); const std::vector<uint32> & indices = renderMesh->Indices(); for( int planeIndex = 0; planeIndex < splitPlanes.size(); planeIndex++ ) { const vaPlane & plane = splitPlanes[planeIndex]; newIndicesLeft.clear(); newIndicesRight.clear(); for( int triIndex = 0; triIndex < indices.size( ); triIndex += 3 ) { const vaRenderMesh::StandardVertex & a = vertices[ indices[ triIndex + 0 ] ]; const vaRenderMesh::StandardVertex & b = vertices[ indices[ triIndex + 1 ] ]; const vaRenderMesh::StandardVertex & c = vertices[ indices[ triIndex + 2 ] ]; vaVector3 posA = vaVector3::TransformCoord( a.Position, worldTransform ); vaVector3 posB = vaVector3::TransformCoord( b.Position, worldTransform ); vaVector3 posC = vaVector3::TransformCoord( c.Position, worldTransform ); float signA = vaMath::Sign( plane.DotCoord( posA ) ); float signB = vaMath::Sign( plane.DotCoord( posB ) ); float signC = vaMath::Sign( plane.DotCoord( posC ) ); int direction = 0; // 0 means no split, -1 means goes to the left, 1 means goes to the right // must all be on one or the other side, otherwise don't split if( !splitIfIntersectingTriangles ) { if( signA != signB || signA != signC ) direction = 0; else if( signA < 0 && signB < 0 && signC < 0 ) direction = -1; else { assert( signA >= 0 && signB >= 0 && signC >= 0 ); direction = 1; } } else // will split towards the one with the most { direction = ((signA+signB+signC+1)<0)?(-1):(1); } if( direction == 0 ) { //vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFFFF0000, 0x80FF0000 ); newIndicesLeft.clear(); newIndicesRight.clear(); break; } else if( direction == -1 ) { //vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFF00FF00, 0x8000FF00 ); newIndicesLeft.push_back( indices[ triIndex + 0 ] ); newIndicesLeft.push_back( indices[ triIndex + 1 ] ); newIndicesLeft.push_back( indices[ triIndex + 2 ] ); } else { assert( direction == 1 ); //vaDebugCanvas3D::GetInstance().DrawTriangle( posA, posB, posC, 0xFF0000FF, 0x800000FF ); newIndicesRight.push_back( indices[ triIndex + 0 ] ); newIndicesRight.push_back( indices[ triIndex + 1 ] ); newIndicesRight.push_back( indices[ triIndex + 2 ] ); } } if( newIndicesLeft.size( ) > (minTriangleCountThreshold*3) && newIndicesRight.size( ) > (minTriangleCountThreshold*3) ) { vaAsset * originalRenderMeshAsset = renderMesh->GetParentAsset(); VA_LOG( "Splitting mesh '%s' (%d triangles) with a plane %d into left part with %d triangles and right part with %d triangles", originalRenderMeshAsset->Name().c_str(), (int)renderMesh->Indices().size()/3, planeIndex, (int)newIndicesLeft.size()/3, (int)newIndicesRight.size()/3 ); // do the split! shared_ptr<vaRenderMesh::StandardTriangleMesh> newMeshLeft = std::make_shared<vaRenderMesh::StandardTriangleMesh>( renderMesh->GetRenderDevice() ); shared_ptr<vaRenderMesh::StandardTriangleMesh> newMeshRight = std::make_shared<vaRenderMesh::StandardTriangleMesh>( renderMesh->GetRenderDevice() ); // fill up our 'left' and 'right' meshes for( int triIndex = 0; triIndex < newIndicesLeft.size( ); triIndex += 3 ) { const vaRenderMesh::StandardVertex & a = vertices[ newIndicesLeft[ triIndex + 0 ] ]; const vaRenderMesh::StandardVertex & b = vertices[ newIndicesLeft[ triIndex + 1 ] ]; const vaRenderMesh::StandardVertex & c = vertices[ newIndicesLeft[ triIndex + 2 ] ]; newMeshLeft->AddTriangleMergeDuplicates<vaRenderMesh::StandardVertex>( a, b, c, vaRenderMesh::StandardVertex::IsDuplicate, 512 ); } for( int triIndex = 0; triIndex < newIndicesRight.size( ); triIndex += 3 ) { const vaRenderMesh::StandardVertex & a = vertices[ newIndicesRight[ triIndex + 0 ] ]; const vaRenderMesh::StandardVertex & b = vertices[ newIndicesRight[ triIndex + 1 ] ]; const vaRenderMesh::StandardVertex & c = vertices[ newIndicesRight[ triIndex + 2 ] ]; newMeshRight->AddTriangleMergeDuplicates<vaRenderMesh::StandardVertex>( a, b, c, vaRenderMesh::StandardVertex::IsDuplicate, 512 ); } // replace the current mesh with the left and the right split parts // increment the counter splitCount++; // create new meshes shared_ptr<vaRenderMesh> newRenderMeshLeft = vaRenderMesh::Create( newMeshLeft, renderMesh->GetFrontFaceWindingOrder(), renderMesh->GetMaterialID() ); shared_ptr<vaRenderMesh> newRenderMeshRight = vaRenderMesh::Create( newMeshRight, renderMesh->GetFrontFaceWindingOrder(), renderMesh->GetMaterialID() ); // add them to the original asset pack so they can get saved originalRenderMeshAsset->GetAssetPack().Add( newRenderMeshLeft, originalRenderMeshAsset->Name() + "_l", true ); originalRenderMeshAsset->GetAssetPack().Add( newRenderMeshRight, originalRenderMeshAsset->Name() + "_r", true ); // for external tracking (& removal if needed) outOldMeshes.push_back( renderMesh ); outNewMeshes.push_back( newRenderMeshLeft ); outNewMeshes.push_back( newRenderMeshRight ); // remove the current one and add the splits RemoveRenderMeshRef( meshIndex ); AddRenderMeshRef( newRenderMeshLeft ); AddRenderMeshRef( newRenderMeshRight ); // ok now reset the search to the beginning so we can re-do the split meshes if there's more splitting to be done meshIndex--; break; } } } totalSplitCount += splitCount; } while ( splitCount > 0 ); return totalSplitCount; } void vaSceneObject::ReplaceMaterialsWithXXX( ) { string prefix = "xxx_"; for( int i = 0; i < m_renderMeshes.size( ); i++ ) { auto renderMesh = GetRenderMesh( i ); auto renderMaterial = (renderMesh != nullptr)?(renderMesh->GetMaterial()):(nullptr); vaAsset * renderMaterialAsset = (renderMaterial != nullptr)?(renderMaterial->GetParentAsset()):(nullptr); if( renderMaterialAsset != nullptr ) { string name = renderMaterialAsset->Name(); if( name.substr(0, prefix.length()) == prefix ) { VA_LOG( "Skipping material '%s'...", name.c_str() ); continue; } VA_LOG( "Searching for material replacement for '%s'...", name.c_str() ); vaAssetPackManager & mgr = renderMaterial->GetRenderDevice().GetAssetPackManager( ); shared_ptr<vaAsset> replacementAsset = mgr.FindAsset( prefix+name ); if( replacementAsset == nullptr ) { VA_LOG_WARNING( " replacement not found!" ); continue; } if( replacementAsset->Type != vaAssetType::RenderMaterial ) { VA_LOG_WARNING( " replacement found but wrong type!" ); continue; } VA_LOG_SUCCESS(" replacement found!" ); renderMesh->SetMaterial( replacementAsset->GetResource<vaRenderMaterial>() ); } else { assert( false ); } } } void vaSceneObject::EnumerateUsedAssets( const std::function<void(vaAsset * asset)> & callback ) { for( int i = 0; i < m_renderMeshes.size( ); i++ ) { auto renderMesh = GetRenderMesh( i ); if( renderMesh != nullptr && renderMesh->GetParentAsset( ) != nullptr ) renderMesh->EnumerateUsedAssets( callback ); } } vaSceneOld::vaSceneOld( ) : vaUIPanel( "SceneOld", 1, true, vaUIPanel::DockLocation::DockedLeft, "SceneOlds" ) { Clear(); } vaSceneOld::vaSceneOld( const string & name ) : vaUIPanel( "Scene", 1, true, vaUIPanel::DockLocation::DockedLeft, "Scenes" ) { Clear( ); m_name = name; } vaSceneOld::~vaSceneOld( ) { // this might be ok or might not be ok - you've got some assert( m_deferredObjectActions.size() == 0 ); Clear(); } void vaSceneOld::Clear( ) { m_deferredObjectActions.clear(); DestroyAllObjects( ); ApplyDeferredObjectActions(); m_name = ""; m_lights.clear(); assert( m_allObjects.size() == 0 ); assert( m_rootObjects.size() == 0 ); m_tickIndex = 0; m_sceneTime = 0.0; assert( !m_isInTick ); m_isInTick = false; } shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const shared_ptr<vaSceneObject> & parent ) { return CreateObject( "Unnamed", vaMatrix4x4::Identity, parent ); } shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const string & name, const vaMatrix4x4 & localTransform, const shared_ptr<vaSceneObject> & parent ) { m_deferredObjectActions.push_back( DeferredObjectAction( std::make_shared<vaSceneObject>( ), parent, vaSceneOld::DeferredObjectAction::AddObject ) ); m_deferredObjectActions.back().Object->SetName( name ); m_deferredObjectActions.back().Object->SetScene( this->shared_from_this() ); m_deferredObjectActions.back().Object->SetLocalTransform( localTransform ); return m_deferredObjectActions.back().Object; } shared_ptr<vaSceneObject> vaSceneOld::CreateObject( const string & name, const vaVector3 & localScale, const vaQuaternion & localRot, const vaVector3 & localPos, const shared_ptr<vaSceneObject> & parent ) { return CreateObject( name, vaMatrix4x4::FromScaleRotationTranslation( localScale, localRot, localPos ), parent ); } void vaSceneOld::DestroyObject( const shared_ptr<vaSceneObject> & ptr, bool destroyChildrenRecursively, bool applyOwnTransformToChildren ) { assert( ptr->GetScene() != nullptr ); if( applyOwnTransformToChildren ) { // doesn't make sense to apply transform to children if you're destroying them as well assert( !destroyChildrenRecursively ); } // mark the object as no longer functional ptr->MarkAsDestroyed( destroyChildrenRecursively ); if( destroyChildrenRecursively ) { m_deferredObjectActions.push_back( DeferredObjectAction( ptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren ) ); } else { // we can do this right now if( applyOwnTransformToChildren ) { const vaMatrix4x4 & parentTransform = ptr->GetLocalTransform(); const std::vector<shared_ptr<vaSceneObject>> & children = ptr->GetChildren(); for( int i = 0; i < (int)children.size(); i++ ) { const vaMatrix4x4 newTransform = parentTransform * children[i]->GetLocalTransform(); children[i]->SetLocalTransform( newTransform ); } } m_deferredObjectActions.push_back( DeferredObjectAction( ptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveObject ) ); } //assert( m_deferredObjectActions.back().Object.unique() ); } void vaSceneOld::DestroyAllObjects( ) { m_deferredObjectActions.push_back( DeferredObjectAction( nullptr, nullptr, vaSceneOld::DeferredObjectAction::RemoveAllObjects ) ); } void vaSceneOld::RegisterRootObjectAdded( const shared_ptr<vaSceneObject> & object ) { if( m_isInTick ) { assert( false ); // Can't call this while in tick return; } assert( std::find( m_rootObjects.begin(), m_rootObjects.end(), object ) == m_rootObjects.end() ); m_rootObjects.push_back( object ); } void vaSceneOld::RegisterRootObjectRemoved( const shared_ptr<vaSceneObject> & object ) { if( m_isInTick ) { assert( false ); // Can't call this while in tick return; } bool allOk = vector_find_and_remove( m_rootObjects, object ) != -1; assert( allOk ); // if this fires, there's a serious error somewhere! allOk; } void vaSceneOld::ApplyDeferredObjectActions( ) { if( m_isInTick ) { assert( false ); // Can't call this while in tick return; } for( int i = 0; i < m_deferredObjectActions.size( ); i++ ) { const DeferredObjectAction & mod = m_deferredObjectActions[i]; if( mod.Action == vaSceneOld::DeferredObjectAction::RemoveAllObjects ) { for( int j = 0; j < (int)m_allObjects.size(); j++ ) m_allObjects[j]->NukeGraph( ); m_rootObjects.clear(); for( int j = 0; j < m_allObjects.size( ); j++ ) { // this pointer should be unique now. otherwise you're holding a pointer somewhere although the object was destroyed - is this // intended? if there's a case where this is intended, think it through in detail - there's a lot of potential for unforeseen // consequences from accessing vaSceneObject-s in this state. assert( m_allObjects[i].use_count() == 1 ); // this assert is not entirely correct for multithreaded scenarios so beware } m_allObjects.clear(); } else if( mod.Action == vaSceneOld::DeferredObjectAction::AddObject ) { // by default in root, will be removed on "add parent" - this can be optimized out if desired (no need to call if parent != nullptr) but // it leaves the object in a broken state temporarily and SetParent needs to get adjusted and maybe something else too m_rootObjects.push_back( mod.Object ); mod.Object->SetParent( mod.ParentObject ); m_allObjects.push_back( mod.Object ); mod.Object->SetAddedToScene(); } else if( mod.Action == vaSceneOld::DeferredObjectAction::RemoveObject || mod.Action == vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren ) { bool destroyChildrenRecursively = mod.Action == vaSceneOld::DeferredObjectAction::RemoveObjectAndChildren; // they should automatically remove themselves from the list as they get deleted or reattached to this object's parent if( !destroyChildrenRecursively ) { const std::vector<shared_ptr<vaSceneObject>> & children = mod.Object->GetChildren(); while( children.size() > 0 ) { // we >have< to make this a temp, as the SetParent modifies the containing array!! shared_ptr<vaSceneObject> temp = children[0]; assert( this->shared_from_this() == temp->GetScene() ); temp->SetParent( mod.Object->GetParent() ); } } DestroyObjectImmediate( mod.Object, destroyChildrenRecursively ); } } m_deferredObjectActions.clear(); } void vaSceneOld::DestroyObjectImmediate( const shared_ptr<vaSceneObject> & obj, bool recursive ) { assert( obj->IsDestroyed() ); // it must have already been destroyed //assert( obj->GetScene() == nullptr ); // it must have been already set to null obj->SetParent( nullptr ); obj->SetScene( nullptr ); bool allOk = vector_find_and_remove( m_rootObjects, obj ) != -1; assert( allOk ); allOk = vector_find_and_remove( m_allObjects, obj ) != -1; assert( allOk ); if( recursive ) { const std::vector<shared_ptr<vaSceneObject>> & children = obj->GetChildren(); while( obj->GetChildren().size( ) > 0 ) { // we >have< to make this a temp, as the DestroyObject modifies both the provided reference and the containing array!! shared_ptr<vaSceneObject> temp = children[0]; DestroyObjectImmediate( temp, true ); } } // this pointer should be unique now. otherwise you're holding a pointer somewhere although the object was destroyed - is this // intended? if there's a case where this is intended, think it through in detail - there's a lot of potential for unforeseen // consequences from accessing vaSceneObject-s in this state. assert( obj.use_count() == 1 ); // this assert is not entirely correct for multithreaded scenarios so beware } void vaSceneOld::Tick( float deltaTime ) { VA_TRACE_CPU_SCOPE( vaScene_Tick ); ApplyDeferredObjectActions(); if( deltaTime > 0 ) { m_sceneTime += deltaTime; assert( !m_isInTick ); m_isInTick = true; m_tickIndex++; for( int i = 0; i < m_rootObjects.size( ); i++ ) { m_rootObjects[i]->TickRecursive( *this, deltaTime ); } assert( m_isInTick ); m_isInTick = false; ApplyDeferredObjectActions(); m_UI_MouseClickIndicatorRemainingTime = vaMath::Max( m_UI_MouseClickIndicatorRemainingTime - deltaTime, 0.0f ); } } void vaSceneOld::ApplyToLighting( vaSceneLighting & lighting ) { VA_TRACE_CPU_SCOPE( vaScene_ApplyToLighting ); lighting.SetLights( m_lights ); // lighting.SetEnvmap( m_envmapTexture, m_envmapRotation, m_envmapColorMultiplier ); lighting.FogSettings() = m_fog; } bool vaSceneOld::SerializeObjectsRecursive( vaXMLSerializer & serializer, const string & name, std::vector<shared_ptr<vaSceneObject>> & objectList, const shared_ptr<vaSceneObject> & parent ) { if( m_isInTick ) { assert( false ); // Can't call this while in tick return false; } VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeOpenChildElement( name.c_str() ) ); uint32 count = (uint32)objectList.size(); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<uint32>( "count", count ) ); if( serializer.IsReading() ) { assert( objectList.size() == 0 ); // objectList.resize( count ); } string elementName; for( uint32 i = 0; i < count; i++ ) { elementName = vaStringTools::Format( "%s_%d", name.c_str(), i ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeOpenChildElement( elementName.c_str() ) ); shared_ptr<vaSceneObject> obj = nullptr; if( serializer.IsReading() ) obj = CreateObject( parent ); else obj = objectList[i]; obj->Serialize( serializer ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializePopToParentElement( elementName.c_str() ) ); } // if( serializer.IsReading() ) // { // // should have count additions // // assert( m_deferredObjectActions.size() == count ); // } VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializePopToParentElement( name.c_str() ) ); return true; } bool vaSceneOld::Serialize( vaXMLSerializer & serializer, bool mergeToExistingIfLoading ) { if( m_isInTick ) { assert( false ); // Can't call this while in tick return false; } if( serializer.IsWriting( ) && mergeToExistingIfLoading ) { assert( false ); // this combination makes no sense mergeToExistingIfLoading = false; } // calling Serialize with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here) assert( m_deferredObjectActions.size() == 0 ); if( m_deferredObjectActions.size() != 0 ) return false; if( serializer.SerializeOpenChildElement( "VanillaScene" ) ) { if( serializer.IsReading() && !mergeToExistingIfLoading ) Clear(); string mergingName; if( mergeToExistingIfLoading ) { VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", mergingName ) ); //vaVector3 mergingAmbientLight; //VERIFY_TRUE_RETURN_ON_FALSE( serializer.OldSerializeValue( "AmbientLight", mergingAmbientLight ) ); std::vector<shared_ptr<vaLight>> mergingLights; if( serializer.GetVersion() > 0 ) VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeArray( "Lights", mergingLights ) ); else { assert( false ); } m_lights.insert( m_lights.end(), mergingLights.begin(), mergingLights.end() ); //serializer.Serialize<string>( "DistantIBLPath", m_IBLProbeDistantImagePath ); } else { VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Name", m_name ) ); /*VERIFY_TRUE_RETURN_ON_FALSE(*/ serializer.Serialize<vaGUID>( "UID", m_UID, vaGUID::Create( ) );// ); //VERIFY_TRUE_RETURN_ON_FALSE( serializer.OldSerializeValue( "AmbientLight", m_lightAmbient ) ); if( serializer.GetVersion() > 0 ) VERIFY_TRUE_RETURN_ON_FALSE( serializer.SerializeArray( "Lights", m_lights ) ); else { assert( false ); } //serializer.SerializeArray( "Inputs", "Item", m_lights ); //serializer.Serialize<string>( "DistantIBLPath", m_IBLProbeDistantImagePath ); } VERIFY_TRUE_RETURN_ON_FALSE( SerializeObjectsRecursive( serializer, "RootObjects", m_rootObjects, nullptr ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<vaXMLSerializable>( "FogSphere", m_fog ) ); ///*VERIFY_TRUE_RETURN_ON_FALSE(*/ m_fog.Serialize( serializer ); /*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize( "IBLProbeLocal", m_IBLProbeLocal ) ); /*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize( "IBLProbeDistant", m_IBLProbeDistant ) ); // serializer.Serialize<string>( "IBLProbeDistantImagePath", m_IBLProbeDistantImagePath ); bool ok = serializer.SerializePopToParentElement( "VanillaScene" ); assert( ok ); if( serializer.IsReading() && ok ) { return PostLoadInit(); } return ok; } else { VA_LOG_WARNING( L"Unable to load scene, unexpected contents." ); } return false; } bool vaSceneOld::PostLoadInit( ) { ApplyDeferredObjectActions( ); return true; } // void vaSceneOld::UpdateUsedPackNames( ) // { // m_assetPackNames.clear(); // for( auto sceneObject : m_allObjects ) // { // sceneObject->RegisterUsedAssetPacks( std::bind( &vaSceneOld::RegisterUsedAssetPackNameCallback, this, std::placeholders::_1 ) ); // } // } void vaSceneOld::RegisterUsedAssetPackNameCallback( const vaAssetPack & assetPack ) { for( size_t i = 0; i < m_assetPackNames.size(); i++ ) { if( vaStringTools::ToLower( m_assetPackNames[i] ) == vaStringTools::ToLower( assetPack.GetName() ) ) { // found, all is good return; } } // not found, add to list m_assetPackNames.push_back( assetPack.GetName() ); } void vaSceneOld::RemoveAllUnusedAssets( const std::vector<shared_ptr<vaAssetPack>>& assetPacks ) { std::set<vaAsset*> allAssets; for( size_t i = 0; i < assetPacks.size(); i++ ) { vaAssetPack & pack = *assetPacks[i]; assert( !pack.IsBackgroundTaskActive( ) ); std::unique_lock<mutex> assetStorageMutexLock( pack.GetAssetStorageMutex( ) ); for( size_t j = 0; j < pack.Count( false ); j++ ) allAssets.insert( pack.AssetAt( j, false ).get() ); } auto removeFromSet = [ &allAssets ]( vaAsset* asset ) { if( asset != nullptr ) allAssets.erase( asset ); }; for( auto sceneObject : m_allObjects ) sceneObject->EnumerateUsedAssets( removeFromSet ); for( auto asset : allAssets ) asset->GetAssetPack().Remove( asset, true ); } // void vaSceneOld::LoadAndConnectAssets( ) // { // } #ifdef VA_IMGUI_INTEGRATION_ENABLED static shared_ptr<vaSceneObject> ImGuiDisplaySceneObjectTreeRecursive( const std::vector<shared_ptr<vaSceneObject>> & elements, const shared_ptr<vaSceneObject> & selectedObject ) { ImGuiTreeNodeFlags defaultFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; shared_ptr<vaSceneObject> ret = nullptr; for( int i = 0; i < elements.size(); i++ ) { ImGuiTreeNodeFlags nodeFlags = defaultFlags | ((elements[i] == selectedObject)?(ImGuiTreeNodeFlags_Selected):(0)) | ((elements[i]->GetChildren().size() == 0)?(ImGuiTreeNodeFlags_Leaf):(0)); bool nodeOpen = ImGui::TreeNodeEx( elements[i]->UIPropertiesItemGetUniqueID().c_str(), nodeFlags, elements[i]->GetName().c_str() ); if( ImGui::IsItemClicked() ) { ret = elements[i]; } if( nodeOpen ) { if( elements[i]->GetChildren().size() > 0 ) { shared_ptr<vaSceneObject> retRec = ImGuiDisplaySceneObjectTreeRecursive( elements[i]->GetChildren(), selectedObject ); if( retRec != nullptr ) ret = retRec; } ImGui::TreePop(); } } return ret; } #endif bool vaSceneOld::Save( const wstring & fileName ) { // calling Save with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here) assert( m_deferredObjectActions.size() == 0 ); vaFileStream fileOut; if( fileOut.Open( fileName, FileCreationMode::OpenOrCreate, FileAccessMode::Write ) ) { vaXMLSerializer serializer; VA_LOG( L"Writing '%s'.", fileName.c_str() ); if( !Serialize( serializer, false ) ) { VA_LOG_WARNING( L"Error while serializing the scene" ); fileOut.Close(); return false; } serializer.WriterSaveToFile( fileOut ); fileOut.Close(); VA_LOG( L"Scene successfully saved to '%s'.", fileName.c_str() ); return true; } else { VA_LOG_WARNING( L"Unable to save scene to '%s', file error.", fileName.c_str() ); return false; } } bool vaSceneOld::Load( const wstring & fileName, bool mergeToExisting ) { // calling Load with non-applied changes? probably a bug somewhere (if not, just call ApplyDeferredObjectActions() before getting here) assert( m_deferredObjectActions.size() == 0 ); if( m_isInTick ) { assert( false ); // Can't call this while in tick return false; } vaFileStream fileIn; if( vaFileTools::FileExists( fileName ) && fileIn.Open( fileName, FileCreationMode::Open ) ) { vaXMLSerializer serializer( fileIn ); fileIn.Close(); if( serializer.IsReading( ) ) { VA_LOG( L"Reading '%s'.", fileName.c_str() ); if( !Serialize( serializer, mergeToExisting ) ) { VA_LOG_WARNING( L"Error while serializing the scene" ); fileIn.Close(); return false; } VA_LOG( L"Scene successfully loaded from '%s', running PostLoadInit()", fileName.c_str() ); return true; } else { VA_LOG_WARNING( L"Unable to parse xml file '%s', file error.", fileName.c_str() ); return false; } } else { VA_LOG_WARNING( L"Unable to load scene from '%s', file error.", fileName.c_str() ); return false; } } void vaSceneOld::UIPanelTick( vaApplicationBase & application ) { application; #ifdef VA_IMGUI_INTEGRATION_ENABLED ImGui::PushItemWidth( 200.0f ); if( ImGui::Button( " Rename " ) ) ImGuiEx_PopupInputStringBegin( "Rename scene", m_name ); if( ImGuiEx_PopupInputStringTick( "Rename scene", m_name ) ) { //m_name = vaStringTools::ToLower( m_name ); VA_LOG( "Scene name changed to '%s'", m_name.c_str() ); } ImGui::SameLine(); if( ImGui::Button( " Delete all contents " ) ) { Clear(); return; } if( ImGui::Button( " Save As... " ) ) { wstring fileName = vaFileTools::SaveFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" ); if( fileName != L"" ) { if( vaFileTools::SplitPathExt( fileName ) == L"" ) // if no extension, add .xml fileName += L".xml"; Save( fileName ); } } ImGui::SameLine(); if( ImGui::Button( " Load... " ) ) { wstring fileName = vaFileTools::OpenFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" ); Load( fileName, false ); } ImGui::SameLine(); if( ImGui::Button( " Load and merge... " ) ) { wstring fileName = vaFileTools::OpenFileDialog( L"", vaCore::GetExecutableDirectory(), L".xml scene files\0*.xml\0\0" ); Load( fileName, true ); } ImGui::Separator(); #if 0 if( ImGui::Button( " Replace materials with xxx_" ) ) { for( auto sceneObject : m_allObjects ) sceneObject->ReplaceMaterialsWithXXX(); } if( ImGui::Button( " Remove all assets from all asset packs not used by this scene" ) ) { RemoveAllUnusedAssets( application.GetRenderDevice().GetAssetPackManager().GetAllAssetPacks() ); } ImGui::Separator( ); #endif if( m_allObjects.size() > 0 ) { ImGui::Text( "Scene objects: %d", m_allObjects.size() ); float uiListHeight = 120.0f; float uiPropertiesHeight = 180.0f; shared_ptr<vaSceneObject> selectedObject = m_UI_SelectedObject.lock(); if( m_UI_ShowObjectsAsTree ) { std::vector<shared_ptr<vaSceneObject>> elements = m_rootObjects; if( ImGui::BeginChild( "TreeFrame", ImVec2( 0.0f, uiListHeight ), true ) ) { shared_ptr<vaSceneObject> objectClicked = ImGuiDisplaySceneObjectTreeRecursive( m_rootObjects, selectedObject ); if( objectClicked != nullptr ) { if( selectedObject != objectClicked ) selectedObject = objectClicked; else selectedObject = nullptr; m_UI_SelectedObject = selectedObject; } } ImGui::EndChild(); if( ImGui::BeginChild( "PropFrame", ImVec2( 0.0f, uiPropertiesHeight ), true ) ) { if( selectedObject != nullptr ) { ImGui::PushID( selectedObject->UIPropertiesItemGetUniqueID( ).c_str( ) ); selectedObject->UIPropertiesItemTick( application, false, false ); ImGui::PopID(); } else { ImGui::TextColored( ImVec4( 0.5f, 0.5f, 0.5f, 1.0f ), "Select an item to display properties" ); } } ImGui::EndChild(); } else { vaUIPropertiesItem * ptrsToDisplay[ 65536 ]; // if this ever becomes not enough, change DrawList into a template and make it accept allObjects directly... int countToShow = std::min( (int)m_allObjects.size(), (int)_countof(ptrsToDisplay) ); int currentObject = -1; for( int i = 0; i < countToShow; i++ ) { if( m_UI_SelectedObject.lock() == m_allObjects[i] ) currentObject = i; ptrsToDisplay[i] = m_allObjects[i].get(); } vaUIPropertiesItem::DrawList( application, "Objects", ptrsToDisplay, countToShow, currentObject, 0.0f, uiListHeight, uiPropertiesHeight ); if( currentObject >= 0 && currentObject < countToShow ) m_UI_SelectedObject = m_allObjects[currentObject]; else m_UI_SelectedObject.reset(); } } else { ImGui::Text( "No objects" ); } ImGui::Separator(); ImGui::Text( "Scene lights: %d", m_lights.size() ); if( m_lights.size() > 0 ) { vaUIPropertiesItem * ptrsToDisplay[ 4096 ]; int countToShow = std::min( (int)m_lights.size(), (int)_countof(ptrsToDisplay) ); for( int i = 0; i < countToShow; i++ ) ptrsToDisplay[i] = m_lights[i].get(); int currentLight = -1; for( int i = 0; i < countToShow; i++ ) { if( m_UI_SelectedLight.lock() == m_lights[i] ) currentLight = i; ptrsToDisplay[i] = m_lights[i].get(); } vaUIPropertiesItem::DrawList( application, "Lights", ptrsToDisplay, countToShow, currentLight, 0.0f, 90, 200 ); if( currentLight >= 0 && currentLight < countToShow ) m_UI_SelectedLight = m_lights[currentLight]; if( currentLight >= 0 && currentLight < m_lights.size() ) { if( ImGui::Button( "Duplicate" ) ) { m_lights.push_back( std::make_shared<vaLight>( *m_lights[currentLight] ) ); m_lights.back()->Name += "_new"; m_UI_SelectedLight = m_lights.back(); } ImGui::SameLine(); if( ImGui::Button( "Delete" ) ) { m_lights.erase( m_lights.begin() + currentLight ); } } } else { ImGui::Text( "No lights" ); } if( ImGui::Button( "Add light" ) ) { m_lights.push_back( std::make_shared<vaLight>( vaLight::MakePoint( "NewLight", 0.2f, vaVector3( 0, 0, 0 ), 0.0f, vaVector3( 0, 0, 0 ) ) ) ); } ImGui::Checkbox( "Debug draw scene lights", &m_UI_ShowLights ); ImGui::Separator(); ImGui::Text( "Scene cleanup tools:" ); if( ImGui::Button( "Remove redundant hierarchy" ) ) { for( int i = 0; i < m_allObjects.size(); i++ ) { const shared_ptr<vaSceneObject> & obj = m_allObjects[i]; if( obj->GetRenderMeshCount( ) == 0 && obj->GetChildren().size() == 1 ) { DestroyObject( obj, false, true ); } } } if( ImGui::Button( "Remove missing render mesh references" ) ) { for( int i = 0; i < m_allObjects.size( ); i++ ) { const shared_ptr<vaSceneObject> & obj = m_allObjects[i]; for( int j = obj->GetRenderMeshCount( ) - 1; j >= 0; j-- ) { if( obj->GetRenderMesh( j ) == nullptr ) { obj->RemoveRenderMeshRef( j ); VA_LOG( "Removed mesh %d from scene object '%s'", j, obj->GetName().c_str() ); } } } } m_fog.UIPropertiesItemTickCollapsable( application, false, false ); ImGui::Separator( ); // IBL properties { vaDebugCanvas3D& canvas3D = application.GetRenderDevice( ).GetCanvas3D( ); canvas3D; string idPrefix = m_UID.ToString( ) + "_IBL_"; Scene::IBLProbe * probes[] = { &m_IBLProbeLocal, &m_IBLProbeDistant }; string probeNames[] = { "Local IBL", "Distant IBL" }; for( int i = 0; i < countof( probes ); i++ ) { Scene::IBLProbe & probe = *probes[i]; const string & probeName = probeNames[i]; ImGui::Text( probeName.c_str() ); switch( ImGuiEx_SameLineSmallButtons( probeName.c_str(), { "[props]" } ) ) { case( -1 ): break; case( 0 ): { string uniqueID = idPrefix + std::to_string(i); if( vaUIManager::GetInstance( ).FindTransientPropertyItem( uniqueID, true ) == nullptr ) { auto uiContext = std::make_shared<vaIBLProbe::UIContext>( shared_from_this( ) ); vaUIManager::GetInstance( ).CreateTransientPropertyItem( uniqueID, m_name + " : " + probeName, [ &probe, uniqueID, probeName ]( vaApplicationBase& application, const shared_ptr<void>& drawContext ) -> bool { auto uiContext = std::static_pointer_cast<vaIBLProbe::UIContext>( drawContext ); assert( uiContext != nullptr ); auto aliveToken = ( uiContext != nullptr ) ? ( uiContext->AliveToken.lock( ) ) : ( shared_ptr<void>( ) ); if( !aliveToken ) return false; vaDebugCanvas3D& canvas3D = application.GetRenderDevice( ).GetCanvas3D( ); canvas3D; if( ImGui::InputText( "Input file", &probe.ImportFilePath ) ) probe.SetImportFilePath( probe.ImportFilePath, false ); ImGui::SameLine( ); if( ImGui::Button( "..." ) ) { string fileName = vaFileTools::OpenFileDialog( probe.ImportFilePath, vaCore::GetExecutableDirectoryNarrow( ) ); if( fileName != "" ) probe.SetImportFilePath( probe.ImportFilePath, false ); } ImGui::Separator(); // capture position #if 0 // disabled due to changes in the MoveRotateScaleWidget tool { vaMatrix4x4 probeMat = vaMatrix4x4::FromTranslation( probe.Position ); bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID+"c", probeName + " [capture position]", probeMat ); if( mrsWidgetActive ) { ImGui::Text( "<MRSWidget Active>" ); probe.Position = probeMat.GetTranslation( ); canvas3D.DrawSphere( probe.Position, 0.1f, 0xFF00FF00 ); } else { vaVector3 pos = probe.Position; if( ImGui::InputFloat3( "Translate", &pos.x, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue ) ) probe.Position = pos; } } #endif ImGui::Checkbox( "Use OBB geometry proxy", &probe.UseGeometryProxy ); if( probe.UseGeometryProxy ) { vaMatrix4x4 probeMat = probe.GeometryProxy.ToScaledTransform( ); // activate move rotate scale widget #if 0 // disabled due to changes in the MoveRotateScaleWidget tool bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID+"p", probeName + " [geometry proxy]", probeMat ); if( mrsWidgetActive ) { ImGui::Text( "<MRSWidget Active>" ); probe.GeometryProxy = vaOrientedBoundingBox::FromScaledTransform( probeMat ); canvas3D.DrawBox( probe.GeometryProxy, 0xFF00FF00, 0x10808000 ); } else { if( ImGuiEx_Transform( uniqueID.c_str( ), probeMat, false, false ) ) probe.GeometryProxy = vaOrientedBoundingBox::FromScaledTransform( probeMat ); } #endif if( ImGui::Button( "Set capture center to geometry proxy center", {-1, 0} ) ) probe.Position = probe.GeometryProxy.Center; } if( ImGui::CollapsingHeader( "Local to Global transition region", ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { vaMatrix4x4 transform = probe.FadeOutProxy.ToScaledTransform( ); #if 0 // disabled due to changes in the MoveRotateScaleWidget tool bool mrsWidgetActive = vaUIManager::GetInstance( ).MoveRotateScaleWidget( uniqueID + "lgtr", "Local to global IBL transition region", transform ); if( mrsWidgetActive ) { ImGui::Text( "<MRSWidget Active>" ); probe.FadeOutProxy = vaOrientedBoundingBox::FromScaledTransform( transform ); canvas3D.DrawBox( probe.FadeOutProxy, 0xFF00FF00, 0x10008080 ); } else { if( ImGuiEx_Transform( ( uniqueID + "lgtr" ).c_str( ), transform, false, false ) ) probe.FadeOutProxy = vaOrientedBoundingBox::FromScaledTransform( transform ); } #endif } ImGui::Separator(); vaVector3 colorSRGB = vaVector3::LinearToSRGB( probe.AmbientColor ); if( ImGui::ColorEdit3( "Ambient Color", &colorSRGB.x, ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float ) ) probe.AmbientColor = vaVector3::SRGBToLinear( colorSRGB ); ImGui::InputFloat( "Ambient Color Intensity", &probe.AmbientColorIntensity ); return true; }, uiContext ); } }; break; default: assert( false ); break; } } ImGui::Separator( ); } DrawUI( application.GetUICamera( ), application.GetRenderDevice( ).GetCanvas2D( ), application.GetRenderDevice( ).GetCanvas3D( ) ); ImGui::PopItemWidth( ); #endif } void vaSceneOld::DrawUI( const vaCameraBase & camera, vaDebugCanvas2D & canvas2D, vaDebugCanvas3D & canvas3D ) { VA_TRACE_CPU_SCOPE( vaScene_DrawUI ); canvas2D; camera; float pulse = 0.5f * (float)vaMath::Sin( m_sceneTime * VA_PIf * 2.0f ) + 0.5f; auto selectedObject = m_UI_SelectedObject.lock(); if( selectedObject != nullptr ) { canvas3D.DrawBox( selectedObject->GetGlobalAABB(), vaVector4::ToBGRA( 0.0f, 0.0f + pulse, 0.0f, 1.0f ), vaVector4::ToBGRA( 0.5f, 0.5f, 0.5f, 0.1f ) ); } if( m_UI_MouseClickIndicatorRemainingTime > 0 ) { float factor = vaMath::Sin( (1.0f - m_UI_MouseClickIndicatorRemainingTime / m_UI_MouseClickIndicatorTotalTime) * VA_PIf ); canvas3D.DrawSphere( m_UI_MouseClickIndicator, factor * 0.1f, 0xA0000000, 0x2000FF00 ); } if( m_UI_ShowLights ) { string idPrefix = m_UID.ToString( ) + "_Lights_"; for( int i = 0; i < (int)m_lights.size( ); i++ ) { if( m_lights[i]->Type == vaLight::Type::Ambient || m_lights[i]->Type == vaLight::Type::Directional ) continue; string uniqueID = idPrefix + std::to_string( reinterpret_cast<uint64>( m_lights[i].get() ) ); vaVector3 vecRight = vaVector3::Cross( m_lights[i]->Up, m_lights[i]->Direction ); if( vecRight.LengthSq() < VA_EPSf ) vecRight = vaVector3::Cross( vaVector3( 0, 1, 0 ), m_lights[i]->Direction ); if( vecRight.LengthSq( ) < VA_EPSf ) vecRight = vaVector3::Cross( vaVector3( 1, 0, 0 ), m_lights[i]->Direction ); vaVector3 vecUp = vaVector3::Cross( m_lights[i]->Direction, vecRight ).Normalized( ); vaMatrix3x3 lightRotation = vaMatrix3x3( m_lights[i]->Direction.Normalized(), vecRight, vecUp ); vaMatrix4x4 lightTransform = vaMatrix4x4::FromRotationTranslation( lightRotation, m_lights[i]->Position ); #if 0 // disabled due to changes in the MoveRotateScaleWidget tool vaUIManager::GetInstance().MoveRotateScaleWidget( uniqueID, m_lights[i]->Name + "(light)", lightTransform ); #endif } for( int i = 0; i < (int)m_lights.size(); i++ ) { const vaLight & light = *m_lights[i]; vaVector4 sphereColor = vaVector4( 0.5f, 0.5f, 0.5f, 0.1f ); vaVector4 wireframeColor; switch( light.Type ) { case( vaLight::Type::Ambient ): wireframeColor = vaVector4( 0.5f, 0.5f, 0.5f, 1.0f ); break; case( vaLight::Type::Directional ): wireframeColor = vaVector4( 1.0f, 1.0f, 0.0f, 1.0f ); break; case( vaLight::Type::Point ): wireframeColor = vaVector4( 0.0f, 1.0f, 0.0f, 1.0f ); break; case( vaLight::Type::Spot ): wireframeColor = vaVector4( 0.0f, 0.0f, 1.0f, 1.0f ); break; default: assert( false ); } float sphereSize = light.Size; bool isSelected = m_lights[i] == m_UI_SelectedLight.lock(); if( isSelected ) sphereColor.w += pulse * 0.2f - 0.09f; canvas3D.DrawSphere( light.Position, sphereSize, vaVector4::ToBGRA( wireframeColor ), vaVector4::ToBGRA( sphereColor ) ); if( light.Type == vaLight::Type::Directional || light.Type == vaLight::Type::Spot ) canvas3D.DrawLine( light.Position, light.Position + 2.0f * light.Direction * sphereSize, 0xFF000000 ); if( light.Type == vaLight::Type::Spot && isSelected ) { vaVector3 lightUp = vaVector3::Cross( vaVector3( 0.0f, 0.0f, 1.0f ), light.Direction ); if( lightUp.Length() < 1e-3f ) lightUp = vaVector3::Cross( vaVector3( 0.0f, 1.0f, 0.0f ), light.Direction ); lightUp = lightUp.Normalized(); vaVector3 coneInner = vaVector3::TransformNormal( light.Direction, vaMatrix3x3::RotationAxis( lightUp, light.SpotInnerAngle ) ); vaVector3 coneOuter = vaVector3::TransformNormal( light.Direction, vaMatrix3x3::RotationAxis( lightUp, light.SpotOuterAngle ) ); float coneRadius = 0.1f + light.Range; //light.EffectiveRadius(); const int lineCount = 50; for( int j = 0; j < lineCount; j++ ) { float angle = j / (float)(lineCount-1) * VA_PIf * 2.0f; vaVector3 coneInnerR = vaVector3::TransformNormal( coneInner, vaMatrix3x3::RotationAxis( light.Direction, angle ) ); vaVector3 coneOuterR = vaVector3::TransformNormal( coneOuter, vaMatrix3x3::RotationAxis( light.Direction, angle ) ); canvas3D.DrawLine( light.Position, light.Position + coneRadius * sphereSize * coneInnerR, 0xFFFFFF00 ); canvas3D.DrawLine( light.Position, light.Position + coneRadius * sphereSize * coneOuterR, 0xFFFF0000 ); } } } } } void vaSceneOld::SetSkybox( vaRenderDevice & device, const string & texturePath, const vaMatrix3x3 & rotation, float colorMultiplier ) { shared_ptr<vaTexture> skyboxTexture = vaTexture::CreateFromImageFile( device, vaStringTools::SimpleNarrow(vaCore::GetExecutableDirectory()) + texturePath, vaTextureLoadFlags::Default ); if( skyboxTexture == nullptr ) { VA_LOG_WARNING( "vaSceneOld::SetSkybox - unable to load '%'", texturePath.c_str() ); } else { m_skyboxTexturePath = texturePath; m_skyboxTexture = skyboxTexture; m_skyboxRotation = rotation; m_skyboxColorMultiplier = colorMultiplier; } } //void vaSceneOld::SetEnvmap( vaRenderDevice & device, const string & texturePath, const vaMatrix3x3 & rotation, float colorMultiplier ) //{ // shared_ptr<vaTexture> skyboxTexture = vaTexture::CreateFromImageFile( device, vaStringTools::SimpleNarrow( vaCore::GetExecutableDirectory( ) ) + texturePath, vaTextureLoadFlags::Default ); // if( skyboxTexture == nullptr ) // { // VA_LOG_WARNING( "vaSceneOld::SetSkybox - unable to load '%'", texturePath.c_str( ) ); // } // else // { // m_envmapTexturePath = texturePath; // m_envmapTexture = skyboxTexture; // m_envmapRotation = rotation; // m_envmapColorMultiplier = colorMultiplier; // } //} vaDrawResultFlags vaSceneOld::SelectForRendering( vaRenderInstanceList * opaqueList, vaRenderInstanceList * transparentList, const vaRenderInstanceList::FilterSettings & filter, const SelectionFilterCallback & customFilter ) { VA_TRACE_CPU_SCOPE( vaScene_SelectForRendering ); if( opaqueList != nullptr ) opaqueList->Start( ); if( transparentList != nullptr ) transparentList->Start( ); for( auto object : m_allObjects ) object->SelectForRendering( opaqueList, transparentList, filter, customFilter ); //renderSelection.MeshList.Insert() vaDrawResultFlags drawResults = vaDrawResultFlags::None; if( opaqueList != nullptr ) { opaqueList->Stop(); drawResults |= opaqueList->ResultFlags(); } if( transparentList != nullptr ) { transparentList->Stop(); drawResults |= opaqueList->ResultFlags( ); } //g_doCull = false; return drawResults; } std::vector<shared_ptr<vaSceneObject>> vaSceneOld::FindObjects( std::function<bool(vaSceneObject&obj)> searchCriteria ) { std::vector<shared_ptr<vaSceneObject>> ret; for( auto object : m_allObjects ) { if( searchCriteria( *object ) ) ret.push_back( object ); } return std::move(ret); } void vaSceneOld::OnMouseClick( const vaVector3 & worldClickLocation ) { worldClickLocation; #if 0 m_UI_MouseClickIndicatorRemainingTime = m_UI_MouseClickIndicatorTotalTime; m_UI_MouseClickIndicator = worldClickLocation; shared_ptr<vaSceneObject> closestHitObj = nullptr; float maxHitDist = 0.5f; for( auto rootObj : m_rootObjects ) rootObj->FindClosestRecursive( worldClickLocation, closestHitObj, maxHitDist ); VA_LOG( "vaSceneOld - mouse clicked at (%.2f, %.2f, %.2f) world position.", worldClickLocation.x, worldClickLocation.y, worldClickLocation.z ); // if same, just de-select if( closestHitObj != nullptr && m_UI_SelectedObject.lock() == closestHitObj ) closestHitObj = nullptr; auto previousSel = m_UI_SelectedObject.lock(); if( previousSel != nullptr ) { VA_LOG( "vaSceneOld - deselecting object '%s'", previousSel->GetName().c_str() ); } if( closestHitObj != nullptr ) { VA_LOG( "vaSceneOld - selecting object '%s'", closestHitObj->GetName().c_str() ); } m_UI_SelectedObject = closestHitObj; #endif } shared_ptr<vaSceneObject> vaSceneOld::CreateObjectWithSystemMesh( vaRenderDevice & device, const string & systemMeshName, const vaMatrix4x4 & transform ) { auto renderMeshAsset = device.GetAssetPackManager().GetDefaultPack()->Find( systemMeshName ); if( renderMeshAsset == nullptr ) { VA_WARN( "InsertSystemMeshByName failed - can't find system asset '%s'", systemMeshName.c_str() ); return nullptr; } shared_ptr<vaRenderMesh> renderMesh = dynamic_cast<vaAssetRenderMesh*>(renderMeshAsset.get())->GetRenderMesh(); auto sceneObject = CreateObject( "obj_" + systemMeshName, transform ); sceneObject->AddRenderMeshRef( renderMesh ); return sceneObject; } std::vector<shared_ptr<vaSceneObject>> vaSceneOld::InsertAllPackMeshesToSceneAsObjects( vaSceneOld & scene, vaAssetPack & pack, const vaMatrix4x4 & transform ) { vaVector3 scale, translation; vaQuaternion rotation; transform.Decompose( scale, rotation, translation ); std::vector<shared_ptr<vaSceneObject>> addedObjects; assert( !pack.IsBackgroundTaskActive() ); std::unique_lock<mutex> assetStorageMutexLock( pack.GetAssetStorageMutex() ); for( size_t i = 0; i < pack.Count( false ); i++ ) { auto asset = pack.AssetAt( i, false ); if( asset->Type == vaAssetType::RenderMesh ) { shared_ptr<vaRenderMesh> renderMesh = dynamic_cast<vaAssetRenderMesh*>(asset.get())->GetRenderMesh(); if( renderMesh == nullptr ) continue; auto sceneObject = scene.CreateObject( "obj_" + asset->Name(), transform ); sceneObject->AddRenderMeshRef( renderMesh ); addedObjects.push_back( sceneObject ); } } return addedObjects; } int vaSceneOld::SplitMeshes( const std::vector<vaPlane> & splitPlanes, std::vector<shared_ptr<vaRenderMesh>> & outOldMeshes, std::vector<shared_ptr<vaRenderMesh>> & outNewMeshes, const int minTriangleCountThreshold, const std::vector<shared_ptr<vaRenderMesh>> & candidateMeshes, bool splitIfIntersectingTriangles ) { // use example: // std::vector<shared_ptr<vaRenderMesh>> oldMeshes; // std::vector<shared_ptr<vaRenderMesh>> newMeshes; // m_currentScene->SplitMeshes( choicePlanes, oldMeshes, newMeshes ); // for( int i = 0; i < oldMeshes.size(); i++ ) // oldMeshes[i]->GetParentAsset()->GetAssetPack().Remove( oldMeshes[i]->GetParentAsset(), true ); int totalSplitCount = 0; int splitCount; do { splitCount = 0; for( auto object : m_allObjects ) splitCount += object->SplitMeshes( splitPlanes, outOldMeshes, outNewMeshes, minTriangleCountThreshold, candidateMeshes, splitIfIntersectingTriangles ); totalSplitCount += splitCount; } while ( splitCount > 0 ); return totalSplitCount; } void vaSceneObject::ToNewRecursive( vaScene & scene, vaSceneObject * parentObj, entt::entity parentEntity ) { vaGUID singleMesh = (m_renderMeshes.size( ) == 1)?(m_renderMeshes[0]):(vaGUID::Null); entt::entity thisEntity = scene.CreateEntity( m_name, m_localTransform, parentEntity, singleMesh ); if( m_renderMeshes.size() > 1 ) { for( int i = 0; i < m_renderMeshes.size( ); i++ ) scene.CreateEntity( vaStringTools::Format("mesh_%04d", i), vaMatrix4x4::Identity, thisEntity, m_renderMeshes[i] ); } for( int i = 0; i < m_children.size( ); i++ ) m_children[i]->ToNewRecursive( scene, parentObj, thisEntity ); } shared_ptr<vaScene> vaSceneOld::ToNew( ) const { shared_ptr<vaScene> scene = std::make_shared<vaScene>( m_name ); entt::entity globalsParent = scene->CreateEntity( "Globals" ); if( m_fog.Enabled ) { Scene::FogSphere fogSphere; fogSphere.Enabled = m_fog.Enabled; fogSphere.UseCustomCenter = m_fog.UseCustomCenter; fogSphere.Center = m_fog.Center; fogSphere.Color = m_fog.Color; fogSphere.RadiusInner = m_fog.RadiusInner; fogSphere.RadiusOuter = m_fog.RadiusOuter; fogSphere.BlendCurvePow = m_fog.BlendCurvePow; fogSphere.BlendMultiplier = m_fog.BlendMultiplier; entt::entity fogEntity = scene->CreateEntity( "Fog", vaMatrix4x4::FromTranslation(fogSphere.Center), globalsParent ); scene->Registry().emplace<Scene::FogSphere>( fogEntity, fogSphere ); } if( m_skyboxTexturePath != "" ) { Scene::SkyboxTexture skyboxTexture; skyboxTexture.Path = m_skyboxTexturePath; skyboxTexture.ColorMultiplier = m_skyboxColorMultiplier; skyboxTexture.UID = vaGUID::Null; skyboxTexture.Enabled = true; entt::entity skyboxEntity = scene->CreateEntity( "Skybox", vaMatrix4x4(m_skyboxRotation.Transposed()), globalsParent ); scene->Registry( ).emplace<Scene::SkyboxTexture>( skyboxEntity, skyboxTexture ); } if( m_IBLProbeDistant.Enabled ) { Scene::DistantIBLProbe probe; static_cast<Scene::IBLProbe&>(probe) = m_IBLProbeDistant; entt::entity probeEntity = scene->CreateEntity( "DistantIBLProbe", vaMatrix4x4::FromTranslation( probe.Position ), globalsParent ); scene->Registry( ).emplace<Scene::DistantIBLProbe>( probeEntity, probe ); } if( m_IBLProbeLocal.Enabled ) { Scene::LocalIBLProbe probe; static_cast<Scene::IBLProbe&>( probe ) = m_IBLProbeLocal; entt::entity probeEntity = scene->CreateEntity( "LocalIBLProbe", vaMatrix4x4::FromTranslation( probe.Position ), globalsParent ); scene->Registry( ).emplace<Scene::LocalIBLProbe>( probeEntity, probe ); } for( size_t i = 0; i < m_rootObjects.size( ); i++ ) { m_rootObjects[i]->ToNewRecursive( *scene ); } entt::entity lightsParent = scene->CreateEntity( "Lights" ); for( size_t i = 0; i < m_lights.size( ); i++ ) { const vaLight & light = *m_lights[i]; vaMatrix3x3 rot = vaMatrix3x3::Identity; if( light.Type != vaLight::Type::Ambient ) { rot.Row(0) = light.Direction; rot.Row(1) = vaVector3::Cross( light.Up, light.Direction ); rot.Row(2) = light.Up; if( rot.Row(1).Length() < 0.99f ) vaVector3::ComputeOrthonormalBasis( light.Direction, rot.Row(1), rot.Row(2) ); } entt::entity lightEntity = scene->CreateEntity( /*vaStringTools::Format("light_%04d", i)*/light.Name, vaMatrix4x4::FromRotationTranslation( rot, light.Position ), lightsParent ); switch( light.Type ) { case( vaLight::Type::Ambient ): { auto & newLight = scene->Registry().emplace<Scene::LightAmbient>( lightEntity ); newLight.Color = light.Color; newLight.Intensity = light.Intensity; newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f); } break; case( vaLight::Type::Directional ): { auto & newLight = scene->Registry().emplace<Scene::LightDirectional>( lightEntity ); newLight.Color = light.Color; newLight.Intensity = light.Intensity; newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f); newLight.AngularRadius = light.AngularRadius; newLight.HaloSize = light.HaloSize; newLight.HaloFalloff = light.HaloFalloff; newLight.CastShadows = light.CastShadows; } break; case( vaLight::Type::Point ): { auto & newLight = scene->Registry().emplace<Scene::LightPoint>( lightEntity ); newLight.Color = light.Color; newLight.Intensity = light.Intensity; newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f); newLight.Size = light.Size; newLight.Range = light.Range; newLight.SpotInnerAngle = 0.0f; newLight.SpotOuterAngle = 0.0f; newLight.CastShadows = light.CastShadows; } break; case( vaLight::Type::Spot ): { auto & newLight = scene->Registry().emplace<Scene::LightPoint>( lightEntity ); newLight.Color = light.Color; newLight.Intensity = light.Intensity; newLight.FadeFactor = (light.Enabled)?(1.0f):(0.0f); newLight.Size = light.Size; newLight.Range = light.Range; newLight.SpotInnerAngle = light.SpotInnerAngle; newLight.SpotOuterAngle = light.SpotOuterAngle; newLight.CastShadows = light.CastShadows; } break; default: assert( false ); } } return scene; } #endif
40.06398
317
0.600576
GameTechDev
3ec33c63edbfe1fc15410e4eb9fc1645a8bda611
1,772
cpp
C++
projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp
vybhavramachandran/mophy
7271c12b85a324a4f1494e0ce15942dc25bc4931
[ "Apache-2.0" ]
null
null
null
projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp
vybhavramachandran/mophy
7271c12b85a324a4f1494e0ce15942dc25bc4931
[ "Apache-2.0" ]
5
2020-12-23T00:19:32.000Z
2020-12-29T20:53:58.000Z
projects/biogears/libBiogears/src/pybwrappers/cdm/patient/actions/pybSEUseInhaler.cpp
vybhavramachandran/biogears-vybhav
7271c12b85a324a4f1494e0ce15942dc25bc4931
[ "Apache-2.0" ]
null
null
null
// #include <biogears/cdm/utils/Logger.h> // #include <biogears/cdm/substance/SESubstanceManager.h> // #include <biogears/cdm/utils/DataTrack.h> // #include <biogears/cdm/scenario/requests/SEDataRequest.h> #include <biogears/exports.h> #include <string> #include <pybind11/pybind11.h> #include <biogears/cdm/patient/actions/SEPatientAction.h> #include <biogears/schema/cdm/PatientActions.hxx> #include <biogears/cdm/patient/actions/SEUseInhaler.h> // #include <biogears/cdm/patient/actions/SESubstanceAdministration.h> // #include <biogears/cdm/CommonDataModel.h> // #include <biogears/cdm/properties/SEScalar0To1.h> // #include <biogears/cdm/properties/SEScalarMassPerVolume.h> // #include <biogears/cdm/properties/SEScalarTime.h> // #include <biogears/cdm/properties/SEScalarVolume.h> // #include <biogears/cdm/substance/SESubstanceCompound.h> #include <biogears/cdm/properties/SEScalarVolumePerTime.h> #include <biogears/cdm/substance/SESubstance.h> #include <biogears/schema/cdm/Scenario.hxx> #include <biogears/cdm/patient/actions/SEConsciousRespirationCommand.h> namespace py = pybind11; PYBIND11_MODULE(pybSEUseInhaler, m) { py::class_<biogears::SEUseInhaler, biogears::SEConsciousRespirationCommand>(m, "SEUseInhaler") // .def(py::init<>()) .def("Clear",&biogears::SEUseInhaler::Clear) .def("IsValid",&biogears::SEUseInhaler::IsValid) .def("IsActive",&biogears::SEUseInhaler::IsActive) .def("Load",&biogears::SEUseInhaler::Load) .def("Unload",py::overload_cast<>(&biogears::SEUseInhaler::Unload,py::const_)) .def("ToString",py::overload_cast<std::ostream&>(&biogears::SEUseInhaler::ToString,py::const_)); #ifdef VERSION_INFO m.attr("__version__") = VERSION_INFO; #else m.attr("__version__") = "dev"; #endif }
37.702128
100
0.751129
vybhavramachandran
3ec3887154d89a4fd99033e9d5ca2bd77a2111ae
4,409
cc
C++
base/template_util_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
20
2015-08-26T06:46:00.000Z
2019-02-27T09:05:58.000Z
base/template_util_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
base/template_util_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/template_util.h" #include "base/basictypes.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { struct AStruct {}; class AClass {}; enum AnEnum {}; class Parent {}; class Child : public Parent {}; // is_pointer<Type> COMPILE_ASSERT(!is_pointer<int>::value, IsPointer); COMPILE_ASSERT(!is_pointer<int&>::value, IsPointer); COMPILE_ASSERT(is_pointer<int*>::value, IsPointer); COMPILE_ASSERT(is_pointer<const int*>::value, IsPointer); // is_array<Type> COMPILE_ASSERT(!is_array<int>::value, IsArray); COMPILE_ASSERT(!is_array<int*>::value, IsArray); COMPILE_ASSERT(!is_array<int(*)[3]>::value, IsArray); COMPILE_ASSERT(is_array<int[]>::value, IsArray); COMPILE_ASSERT(is_array<const int[]>::value, IsArray); COMPILE_ASSERT(is_array<int[3]>::value, IsArray); // is_non_const_reference<Type> COMPILE_ASSERT(!is_non_const_reference<int>::value, IsNonConstReference); COMPILE_ASSERT(!is_non_const_reference<const int&>::value, IsNonConstReference); COMPILE_ASSERT(is_non_const_reference<int&>::value, IsNonConstReference); // is_convertible<From, To> // Extra parens needed to make preprocessor macro parsing happy. Otherwise, // it sees the equivalent of: // // (is_convertible < Child), (Parent > ::value) // // Silly C++. COMPILE_ASSERT( (is_convertible<Child, Parent>::value), IsConvertible); COMPILE_ASSERT(!(is_convertible<Parent, Child>::value), IsConvertible); COMPILE_ASSERT(!(is_convertible<Parent, AStruct>::value), IsConvertible); COMPILE_ASSERT( (is_convertible<int, double>::value), IsConvertible); COMPILE_ASSERT( (is_convertible<int*, void*>::value), IsConvertible); COMPILE_ASSERT(!(is_convertible<void*, int*>::value), IsConvertible); // Array types are an easy corner case. Make sure to test that // it does indeed compile. COMPILE_ASSERT(!(is_convertible<int[10], double>::value), IsConvertible); COMPILE_ASSERT(!(is_convertible<double, int[10]>::value), IsConvertible); COMPILE_ASSERT( (is_convertible<int[10], int*>::value), IsConvertible); // is_same<Type1, Type2> COMPILE_ASSERT(!(is_same<Child, Parent>::value), IsSame); COMPILE_ASSERT(!(is_same<Parent, Child>::value), IsSame); COMPILE_ASSERT( (is_same<Parent, Parent>::value), IsSame); COMPILE_ASSERT( (is_same<int*, int*>::value), IsSame); COMPILE_ASSERT( (is_same<int, int>::value), IsSame); COMPILE_ASSERT( (is_same<void, void>::value), IsSame); COMPILE_ASSERT(!(is_same<int, double>::value), IsSame); // is_class<Type> COMPILE_ASSERT(is_class<AStruct>::value, IsClass); COMPILE_ASSERT(is_class<AClass>::value, IsClass); COMPILE_ASSERT(!is_class<AnEnum>::value, IsClass); COMPILE_ASSERT(!is_class<int>::value, IsClass); COMPILE_ASSERT(!is_class<char*>::value, IsClass); COMPILE_ASSERT(!is_class<int&>::value, IsClass); COMPILE_ASSERT(!is_class<char[3]>::value, IsClass); COMPILE_ASSERT(!is_member_function_pointer<int>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<int*>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<void*>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<AStruct>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<AStruct*>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<void(*)()>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<int(*)(int)>::value, IsMemberFunctionPointer); COMPILE_ASSERT(!is_member_function_pointer<int(*)(int, int)>::value, IsMemberFunctionPointer); COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)()>::value, IsMemberFunctionPointer); COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)(int)>::value, IsMemberFunctionPointer); COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int)>::value, IsMemberFunctionPointer); COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int) const>::value, IsMemberFunctionPointer); COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int, int)>::value, IsMemberFunctionPointer); } // namespace } // namespace base
40.081818
80
0.738943
domenic
3ec3e1137bc77c68a6870ff24cbefc1f2cb55b72
2,981
cpp
C++
thirdparty/GeometricTools/WildMagic5/LibMathematics/Distance/Wm5DistPoint2Hyperbola2.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
1
2020-07-24T23:40:01.000Z
2020-07-24T23:40:01.000Z
thirdparty/GeometricTools/WildMagic5/LibMathematics/Distance/Wm5DistPoint2Hyperbola2.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
4
2020-05-19T18:14:33.000Z
2021-03-19T15:53:43.000Z
thirdparty/GeometricTools/WildMagic5/LibMathematics/Distance/Wm5DistPoint2Hyperbola2.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.10.0 (2013/03/17) #include "Wm5MathematicsPCH.h" #include "Wm5DistPoint2Hyperbola2.h" namespace Wm5 { //---------------------------------------------------------------------------- template <typename Real> static Real H (Real t, const Vector2<Real>& point, const Vector2<Real>& resqr) { Real ratio0 = point[0]/((Real)1 + t*resqr[0]); Real ratio1 = point[1]/((Real)1 - t*resqr[1]); return ratio0*ratio0 - ratio1*ratio1 - (Real)1; } //---------------------------------------------------------------------------- template <typename Real> Real ComputeDistancePointToHyperbola (const Vector2<Real>& point, const Vector2<Real>& extent, Vector2<Real>& closest) { assertion(extent[0] > (Real)0 && extent[1] > (Real)0, "Invalid inputs"); Vector2<Real> esqr(extent[0]*extent[0], extent[1]*extent[1]); Vector2<Real> resqr(((Real)1)/esqr[0], ((Real)1)/esqr[1]); // Initialize for bisection. It is not relevant that H(-a^2) = +infinity // and H(b^2) = -infinity, so we need only initialize function values with // accordingly signed numbers. Real t0 = -esqr[0], t1 = esqr[1]; Real troot = ((Real)0.5)*(t0 + t1); Real hroot = H(troot, point, resqr); // Iterate until H(troot) is exactly zero or until one of the // floating-point endpoints does not change anymore. The latter condition // takes advantage of the nature of IEEE floating-point numbers, so the // loop must terminate in a finite number of steps. while (hroot != (Real)0 && troot != t0 && troot != t1) { if (hroot > (Real)0) { t0 = troot; troot = ((Real)0.5)*(t0 + t1); } else // hroot < (Real)0 { t1 = troot; } troot = ((Real)0.5)*(t0 + t1); hroot = H(troot, point, resqr); } closest[0] = point[0]/((Real)1 + troot*resqr[0]); closest[1] = point[1]/((Real)1 - troot*resqr[1]); Vector2<Real> diff = point - closest; Real distance = diff.Length(); return distance; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Explicit instantiation. //---------------------------------------------------------------------------- template WM5_MATHEMATICS_ITEM float ComputeDistancePointToHyperbola<float> (const Vector2<float>&, const Vector2<float>&, Vector2<float>&); template WM5_MATHEMATICS_ITEM double ComputeDistancePointToHyperbola<double> (const Vector2<double>&, const Vector2<double>&, Vector2<double>&); //---------------------------------------------------------------------------- }
37.2625
79
0.521637
SoMa-Project
3ec46d071b2cfe7d5e6c77f2940634d579514c23
3,453
hpp
C++
interfaces/IGraphicLib.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
interfaces/IGraphicLib.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
interfaces/IGraphicLib.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** arcade ** File description: ** arcade */ /*! * @file IGraphicLib.hpp * @brief Graphic libraries dedicated class interface * @authors https://github.com/EPITECH-Strasbourg-2021/CPP-Arcade-Spec * * Interface used by graphic libraries * All functions must be implemented correctly for the kernel to handle the graphic libraries. * */ #pragma once #include <string> #include "Vect.hpp" #include "PixelBox.hpp" #include "TextBox.hpp" #include "Keys.hpp" /*! * @namespace Arcade * @brief Arcade project namespace */ namespace Arcade { /*! * @class IGraphicLib * @brief Graphic libraries virtual class * * Purely virtual class that serves as the basis for all graphic libraries * */ class IGraphicLib { public: /*! * @brief Destructor * * IGraphicLib class's destructor * */ virtual ~IGraphicLib() = default; /*! * @brief Graphic library name's getter * @return a string containing the name of the graphic library */ virtual std::string getName() const = 0; /* Window handling */ /*! * @brief Specifies whether the window is open or not * @return true if open, otherwise returns false */ virtual bool isOpen() const = 0; /*! * @brief Closes the rendering support * * Usually closes a window. * Some graphic library uses other rendering support. * */ virtual void closeRenderer() = 0; /*! * @brief Opens the rendering support * @param title : Title of the rendering support if supported * * Usually opens a window. * Some graphic library uses other rendering support. * */ virtual void openRenderer(std::string const &title) = 0; /*! * @brief Clears the rendering support */ virtual void clearWindow() = 0; /*! * @brief Displays the buffered frame to the screen */ virtual void refreshWindow() = 0; /* Rendering functions */ /*! * @brief Draws a PixelBox */ virtual void drawPixelBox(PixelBox const &) = 0; /*! * @brief Draws a TextBox */ virtual void drawText(TextBox const &) = 0; /* EVENT HANDLING */ /*! * @brief Fetches the events from the user and saves it * @return true if at least one command has been fetched, otherwise returns false * * Fetched commands are usually stored inside a std::vector<Arcade::Keys> or std::list<Arcade::Keys> * */ virtual bool pollEvents() = 0; /*! * @brief Getter of the oldest command in memory * @return the first event of the list. * * The function deletes the command if it succeed to retrieves one, * using front() and pop_front() methods * */ virtual Keys getLastEvent() = 0; /*! * @brief Clears the pending commands * * The function deletes all the commands currently stored. * They wont be accessible anymore, even with the getLastEvent() method. * */ virtual void clearEvents() = 0; /* Context Info */ /*! * @brief Getter from the rendering support dimensions * @return a two dimensions vector containing the width and the height of the rendering support */ virtual Vect<size_t> getScreenSize() const = 0; /*! * @brief Getter from the rendering support height * @return the height of the rendering support */ virtual size_t getMaxY() const = 0; /*! * @brief Getter from the rendering support width * @return the width of the rendering support */ virtual size_t getMaxX() const = 0; }; };
22.717105
102
0.662612
rectoria
3ec495b668fb3126e7dae077dd21b64517cae81c
3,530
cpp
C++
src/hip_surface.cpp
Maetveis/hipamd
f5b5c4269ed9b250f9907fbdf412e2341846369e
[ "MIT" ]
null
null
null
src/hip_surface.cpp
Maetveis/hipamd
f5b5c4269ed9b250f9907fbdf412e2341846369e
[ "MIT" ]
null
null
null
src/hip_surface.cpp
Maetveis/hipamd
f5b5c4269ed9b250f9907fbdf412e2341846369e
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 - 2022 Advanced Micro Devices, Inc. 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 <hip/hip_runtime.h> #include "hip_internal.hpp" #include <hip/surface_types.h> hipError_t ihipFree(void* ptr); struct __hip_surface { uint32_t imageSRD[HIP_IMAGE_OBJECT_SIZE_DWORD]; amd::Image* image; hipResourceDesc resDesc; __hip_surface(amd::Image* image_, const hipResourceDesc& resDesc_) : image(image_), resDesc(resDesc_) { amd::Context& context = *hip::getCurrentDevice()->asContext(); amd::Device& device = *context.devices()[0]; device::Memory* imageMem = image->getDeviceMemory(device); std::memcpy(imageSRD, imageMem->cpuSrd(), sizeof(imageSRD)); } }; hipError_t ihipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject, const hipResourceDesc* pResDesc) { amd::Device* device = hip::getCurrentDevice()->devices()[0]; const device::Info& info = device->info(); // Validate input params if (pSurfObject == nullptr || pResDesc == nullptr) { return hipErrorInvalidValue; } // the type of resource must be a HIP array // hipResourceDesc::res::array::array must be set to a valid HIP array handle. if ((pResDesc->resType != hipResourceTypeArray) || (pResDesc->res.array.array == nullptr)) { return hipErrorInvalidValue; } amd::Image* image = nullptr; cl_mem memObj = reinterpret_cast<cl_mem>(pResDesc->res.array.array->data); if (!is_valid(memObj)) { return hipErrorInvalidValue; } image = as_amd(memObj)->asImage(); void* surfObjectBuffer = nullptr; hipError_t err = ihipMalloc(&surfObjectBuffer, sizeof(__hip_surface), CL_MEM_SVM_FINE_GRAIN_BUFFER); if (surfObjectBuffer == nullptr || err != hipSuccess) { return hipErrorOutOfMemory; } *pSurfObject = new (surfObjectBuffer) __hip_surface{image, *pResDesc}; return hipSuccess; } hipError_t hipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject, const hipResourceDesc* pResDesc) { HIP_INIT_API(hipCreateSurfaceObject, pSurfObject, pResDesc); HIP_RETURN(ihipCreateSurfaceObject(pSurfObject, pResDesc)); } hipError_t ihipDestroySurfaceObject(hipSurfaceObject_t surfaceObject) { if (surfaceObject == nullptr) { return hipSuccess; } return ihipFree(surfaceObject); } hipError_t hipDestroySurfaceObject(hipSurfaceObject_t surfaceObject) { HIP_INIT_API(hipDestroySurfaceObject, surfaceObject); HIP_RETURN(ihipDestroySurfaceObject(surfaceObject)); }
36.391753
94
0.737394
Maetveis
3ec4affc791f9b8036ba27fbbeed5635ff12a898
1,662
cpp
C++
buf/appl_bytes_custom.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
buf/appl_bytes_custom.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
buf/appl_bytes_custom.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
/* See LICENSE for license details */ /* */ #include <appl_status.h> #include <appl_predefines.h> #include <appl_types.h> #include <object/appl_object.h> #include <buf/appl_bytes.h> #include <buf/appl_bytes_base.h> #include <buf/appl_buf.h> #include <buf/appl_bytes_descriptor.h> #include <buf/appl_bytes_custom.h> // // // appl_bytes_custom::appl_bytes_custom( struct appl_context * const p_context) : appl_bytes_base( p_context), m_descriptor() { } // // // appl_bytes_custom::~appl_bytes_custom() { } // // // enum appl_status appl_bytes_custom::f_init( struct appl_bytes_custom_descriptor const * const p_descriptor) { enum appl_status e_status; m_descriptor = *( p_descriptor); e_status = appl_status_ok; return e_status; } // f_init() // // // appl_size_t appl_bytes_custom::v_cleanup(void) { return sizeof(class appl_bytes_custom); } // v_cleanup() // // // enum appl_status appl_bytes_custom::v_consume( unsigned char * const r_value) { enum appl_status e_status; e_status = (*(m_descriptor.p_consume))( m_descriptor.p_void, r_value); return e_status; } // v_consume() // // // enum appl_status appl_bytes_custom::v_produce( unsigned char const i_value) { enum appl_status e_status; e_status = (*(m_descriptor.p_produce))( m_descriptor.p_void, i_value); return e_status; } // v_produce() /* end-of-file: appl_bytes_custom.cpp */
13.735537
57
0.601685
fboucher9
3ec722c4dc3fa324a5993309fad30e3cc3b4c238
57,790
hpp
C++
src/signals/signal_4.hpp
Peterskhan/hydrosig
a165fb47f1caba773412ab245efcb0c35374899c
[ "MIT" ]
2
2017-05-11T20:17:27.000Z
2017-12-29T00:43:14.000Z
src/signals/signal_4.hpp
Peterskhan/hydrosig
a165fb47f1caba773412ab245efcb0c35374899c
[ "MIT" ]
null
null
null
src/signals/signal_4.hpp
Peterskhan/hydrosig
a165fb47f1caba773412ab245efcb0c35374899c
[ "MIT" ]
null
null
null
#pragma once #ifndef HYDROSIG_SIGNAL_4_HPP_INCLUDED #define HYDROSIG_SIGNAL_4_HPP_INCLUDED /* * MIT License * * Copyright (c) 2017 Peter Gyulai * * 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 <type_traits> #include "src/macros.h" #include "src/signals/signal_base/signal_base.h" #include "src/make_funs/make_fun_4.h" #include "src/comp_funs/comp_fun_4.h" #include "src/slots/slot_4.hpp" #include "src/connections/connection_4.hpp" HYDROSIG_NAMESPACE_BEGIN /** * Forward declarations: * --------------------- */ HYDROSIG_TEMPLATE_4_ARG class connection_4; /** * Class declarations: * ------------------- */ /** * @brief This class forms the base of signal types * with 4 arguments. It is responsible for * implementing the connection and disconnection * mechanism, construction and copy/move semantics. */ HYDROSIG_TEMPLATE_4_ARG class signal_4_base : public signal_base { public: /**< Typedef for the slot type */ typedef slot_4<HYDROSIG_4_ARG> slot_type; /**< Typedef for the connection type */ typedef connection_4<HYDROSIG_4_ARG> connection_type; /**< Typedef for the list of slots */ typedef HYDROSIG_LIST_TYPE<HYDROSIG_SHARED_PTR_TYPE<slot_type>> slot_list; /** * @brief Constructs a signal_4 object. */ signal_4_base(); /** * @brief Constructs a signal_4_base object by copying src. * @details Signals with connected slots are not meant * to be copied, and should be only done so when * the object encapsulating it is being copied. * Established connections are not copied into the * new object, and it is set into a default state. * @param src The signal object to copy. */ signal_4_base(const signal_4_base& /*src*/); /** * @brief Constructs a signal_4 by moving src. * @details In the moving process src loses all of * it's connections, they are transferred * to this signal. The state of the constructed * signal is matching the state of src before * the move construction. * @param src The signal to move. */ signal_4_base(signal_4_base&& src); /** * @brief Copy assigns src to this signal. * @details Signals with connected slots are not meant * to be copied, and should be only done so when * the object encapsulating it is being copied. * Established connections are not copied into the * new object, and it is set into a default state. * @param src The signal object to copy. */ signal_4_base& operator=(const signal_4_base& /*src*/); /** * @brief Move assigns src to this signal. * @details In the moving process src loses all of * it's connections, they are transferred * to this signal. The state of the constructed * signal is matching the state of src before * the move assignment. * @param src The signal to move. */ signal_4_base& operator=(signal_4_base&& src); /** * @brief Destroys the signal_4. */ virtual ~signal_4_base(); /** * @brief Returns the number of connected slots. * @return The number of connected slots. */ unsigned int size() const; /** * @brief Returns whether there are no slots * are connected to the signal. * @return True if there are no slots connected, * false otherwise. */ bool empty() const; /** * @brief Removes all slots connected to the signal. */ void clear(); /** * @brief Connects a free function to the signal. * @param function Pointer to the free function. */ connection_type connect(Return_type(*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)); /** * @brief Connects an object and it's member function * (with no specifiers) to the signal. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_UNTRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)); /** * @brief Connects an object and it's member function * (with no specifiers) to the signal. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_TRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)); /** * @brief Connects an object and it's member function * (with const specifier) to the signal. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_UNTRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const); /** * @brief Connects an object and it's member function * (with const specifier) to the signal. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_TRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const); /** * @brief Connects an object and it's member function * (with volatile specifier) to the signal. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_UNTRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile); /** * @brief Connects an object and it's member function * (with volatile specifier) to the signal. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_TRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile); /** * @brief Connects an object and it's member function * (with const volatile specifiers) to the signal. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_UNTRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile); /** * @brief Connects an object and it's member function * (with const volatile specifiers) to the signal. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. */ HYDROSIG_CONNECT_ENABLER_TRACKABLE connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile); /** * @brief Connects a callable object to the signal. * @details A copy of the callable object is made * and stored in the created slot. * @param callable The callable object. */ template<class Callable_type> connection_type connect(Callable_type callable); /** * @brief Disconnects a free function indicated by * a pointer to it. * @param function Pointer to the free function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ void disconnect(Return_type(*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll = false); /** * @brief Disconnects a member function with no * specifiers of the given object. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll = false); /** * @brief Disconnects a member function with no * specifiers of the given object. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_TRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll = false); /** * @brief Disconnects a member function with const * specifier of the given object. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const, bool disconnectAll = false); /** * @brief Disconnects a member function with const * specifier of the given object. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_TRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const, bool disconnectAll = false); /** * @brief Disconnects a member function with volatile * specifier of the given object. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile, bool disconnectAll = false); /** * @brief Disconnects a member function with volatile * specifier of the given object. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_TRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile, bool disconnectAll = false); /** * @brief Disconnects a member function with const * volatile specifier of the given object. * @details This version is used for untrackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile, bool disconnectAll = false); /** * @brief Disconnects a member function with const * volatile specifier of the given object. * @details This version is used for trackable objects. * @param object Pointer to the object. * @param function Pointer to the member function. * @param disconnectAll Whether all matching connections * should be disconnected, or only * the first match. */ HYDROSIG_DISCONNECT_ENABLER_TRACKABLE disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile, bool disconnectAll = false); /** * @brief Disconnects a slot indicated by a pointer to it. * @details This function is not designed for client code, and * is used for disconnection by connection objects. * @param slot_ptr A shared pointer to the slot. */ void disconnect(const HYDROSIG_SHARED_PTR_TYPE<slot_type> slot_ptr); /** * @brief Removes all invalidated slots from the slot-list. * @details This function is used upon signal emission, to * remove invalidated slots before emitting. You * may need to call this function manually when you * have objects connected to the signal which are * frequently destroyed without manual disconnection. * Otherwise, such connections are automatically * cleaned up upon the next emission. */ void removeInvalidated(); protected: /**< The list of slots */ slot_list m_slots; }; /** * @brief This class represents signals with 4 arguments, * using the normal (non-returning) emission mode. */ HYDROSIG_TEMPLATE_4_ARG class signal_4 : public signal_4_base<HYDROSIG_4_ARG> { public: /**< Typedef for the slot type */ typedef slot_4<HYDROSIG_4_ARG> slot_type; /**< Typedef for the list of slots */ typedef HYDROSIG_LIST_TYPE<HYDROSIG_SHARED_PTR_TYPE<slot_type>> slot_list; /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. */ void emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in reverse order * of they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. */ void emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * This is a convenience function, which * calls emit(). * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. */ void operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /**< Nested class for emitting signals with collected results */ class collected; /**< Nested class for emitting signals with combined results */ template<class Combiner_type> class combined; }; /** * @brief This class represents signals with 4 arguments, * using the collected emission mode. * @details Collected emission means, that the emitting * functions return a list of the return values * of slot activations. */ HYDROSIG_TEMPLATE_4_ARG class signal_4<HYDROSIG_4_ARG>::collected : public signal_4_base<HYDROSIG_4_ARG> { static_assert(!std::is_same<Return_type, void>::value, "Return values with type 'void' can not be collected."); public: /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The list of returned values from each slot * activation. */ HYDROSIG_LIST_TYPE<Return_type> emit( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in reverse order * of they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The list of returned values from each slot * activation. */ HYDROSIG_LIST_TYPE<Return_type> emit_reverse( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * This is a convenience function, which * calls emit(). * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The list of returned values from each slot * activation. */ HYDROSIG_LIST_TYPE<Return_type> operator()( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); }; /** * @brief This class represents signals with 4 arguments, * using the combined emission mode. * @details Combined emission means, that the emitting * functions return a combined result of the * return values of slot activations using a * custom combiner. */ HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> class signal_4<HYDROSIG_4_ARG>::combined : public signal_4_base<HYDROSIG_4_ARG> { static_assert(!std::is_same<Return_type, void>::value, "Return values with type 'void' can not be combined."); public: /** * @brief Constructs a combined signal with a * default combiner. */ combined(); /** * @brief Constructs a combined signal with a * copy of the supplied combiner. * @param combiner The combiner to use. */ combined(const Combiner_type &combiner); /** * @brief Constructs a combined signal by * copying src. * @details The combiner is being copied, for * other members, signal_base copy * semantics are applied. * @param src The other combined signal to copy. */ combined(const combined &src); /** * @brief Constructs a combined signal by * moving src. * @details The combiner is being moved, for * other members, signal_base move * semantics are applied. * @param src The other combined signal to move. */ combined(combined &&src); /** * @brief Copy assigns src to this combined signal. * @details The combiner is being copied, for * other members, signal_base copy * semantics are applied. * @param src The other combined signal to copy * assign from. */ combined& operator=(const combined &src); /** * @brief Move assigns src to this combined signal. * @details The combiner is being moved, for * other members, signal_base move * semantics are applied. * @param src The other combined signal to move * assign from. */ combined& operator=(combined &&src); /** * @brief Returns the combiner object used by * the combined signal. * @return The internal combiner. */ Combiner_type& getCombiner(); /** * @brief Sets the combiner used by the * combined signal. * @param combiner The combiner to set. */ void setCombiner(const Combiner_type &combiner); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The combined result of the return values * of slot activations. */ Return_type emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in reverse order * of they were connected to the signal. * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The combined result of the return values * of slot activations. */ Return_type emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); /** * @brief Emits the signal by activating all of the * connected slot's callback functions. * @details The slots are activated in the exact same * order they were connected to the signal. * This is a convenience function, which * calls emit(). * @param arg1 The first argument. * @param arg2 The second argument. * @param arg3 The third argument. * @param arg4 The fourth argument. * @return The combined result of the return values * of slot activations. */ Return_type operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4); protected: /**< The combiner used by the signal */ HYDROSIG_SHARED_PTR_TYPE<Combiner_type> m_combiner; }; /** * Member definitions: * ------------------- */ HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>::signal_4_base() : signal_base() { ; } HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>::signal_4_base( const signal_4_base& /*src*/) : signal_base() { // Do not copy the list of slots } HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>::signal_4_base( signal_4_base&& src) : signal_base() { // Move the list of slots HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN m_slots = std::move(src.m_slots); m_blocked = src.m_blocked; HYDROSIG_REMOTE_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>& signal_4_base<HYDROSIG_4_ARG>::operator=( const signal_4_base& /*src*/) { // Do not copy the list of slots m_blocked = false; return *this; } HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>& signal_4_base<HYDROSIG_4_ARG>::operator=( signal_4_base&& src) { if(this == &src) return *this; HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN HYDROSIG_PROTECTED_BLOCK_BEGIN // Move the list of slots m_slots = std::move(src.m_slots); // Copy the blocking state m_blocked = src.m_blocked; HYDROSIG_PROTECTED_BLOCK_END HYDROSIG_REMOTE_PROTECTED_BLOCK_END return *this; } HYDROSIG_TEMPLATE_4_ARG signal_4_base<HYDROSIG_4_ARG>::~signal_4_base() { ; } HYDROSIG_TEMPLATE_4_ARG unsigned int signal_4_base<HYDROSIG_4_ARG>::size() const { return m_slots.size(); } HYDROSIG_TEMPLATE_4_ARG bool signal_4_base<HYDROSIG_4_ARG>::empty() const { return m_slots.empty(); } HYDROSIG_TEMPLATE_4_ARG void signal_4_base<HYDROSIG_4_ARG>::clear() { HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.clear(); HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG typename signal_4_base<HYDROSIG_4_ARG>::connection_type signal_4_base<HYDROSIG_4_ARG>::connect( Return_type(*function)(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(function), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4)) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); object->addValidator(validator); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { object->removeValidator(validator); throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); object->addValidator(validator); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { object->removeValidator(validator); throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); object->addValidator(validator); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { object->removeValidator(validator); throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_UNTRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_CONNECT_ENABLER_TRACKABLE_IMPL_4 signal_4_base<HYDROSIG_4_ARG>::connect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun(object, function), validator)); object->addValidator(validator); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { object->removeValidator(validator); throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG template<class Callable_type> typename signal_4_base<HYDROSIG_4_ARG>::connection_type signal_4_base<HYDROSIG_4_ARG>::connect(Callable_type callable) { HYDROSIG_SHARED_PTR_TYPE<connection_validator> validator; try { validator = std::make_shared<connection_validator>(); HYDROSIG_SHARED_PTR_TYPE<slot_type> newSlot( new slot_type(make_fun<HYDROSIG_CALLABLE_4_ARG> (callable), validator)); HYDROSIG_PROTECTED_BLOCK_BEGIN m_slots.push_back(newSlot); HYDROSIG_PROTECTED_BLOCK_END return connection_type(newSlot,this,validator); } catch(...) { throw connection_failure(); } } HYDROSIG_TEMPLATE_4_ARG void signal_4_base<HYDROSIG_4_ARG>::disconnect(Return_type(*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_free_4<HYDROSIG_4_ARG> supplied(function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_TRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4), bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { object->removeValidator((*itBegin)->getValidator()); itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_const_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_TRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_const_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { object->removeValidator((*itBegin)->getValidator()); itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_TRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) volatile, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { object->removeValidator((*itBegin)->getValidator()); itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_UNTRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_const_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_DISCONNECT_ENABLER_TRACKABLE signal_4_base<HYDROSIG_4_ARG>::disconnect(Object_type* object, Return_type(Object_type::*function)( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) const volatile, bool disconnectAll) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { // Functor from the callable functor_to_member_const_volatile_4<Object_type, HYDROSIG_4_ARG> supplied(object,function); // Comparing functors if(comp_fun(&supplied,(*itBegin)->get_functor())) { object->removeValidator((*itBegin)->getValidator()); itBegin = m_slots.erase(itBegin); if(!disconnectAll) { return; } } else { itBegin++; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG void signal_4_base<HYDROSIG_4_ARG>::disconnect( const HYDROSIG_SHARED_PTR_TYPE<slot_type> slot_ptr) { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { if(*itBegin == slot_ptr) { m_slots.erase(itBegin); return; } } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG void signal_4_base<HYDROSIG_4_ARG>::removeInvalidated() { HYDROSIG_PROTECTED_BLOCK_BEGIN typename slot_list::iterator itBegin(m_slots.begin()); typename slot_list::iterator itEnd(m_slots.end()); while(itBegin != itEnd) { if(!(*itBegin)->isValid()) { itBegin = m_slots.erase(itBegin); continue; } itBegin++; } HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG void signal_4<HYDROSIG_4_ARG>::emit(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { if(this->isBlocked()) return; this->removeInvalidated(); HYDROSIG_PROTECTED_BLOCK_BEGIN slot_list copy = this->m_slots; typename slot_list::iterator itBegin(copy.begin()); typename slot_list::iterator itEnd(copy.end()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { (*itBegin)->activate(arg1,arg2,arg3, arg4); itBegin++; } catch(...) { throw; } } } HYDROSIG_TEMPLATE_4_ARG void signal_4<HYDROSIG_4_ARG>::emit_reverse(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { if(this->isBlocked()) return; this->removeInvalidated(); HYDROSIG_PROTECTED_BLOCK_BEGIN slot_list copy = this->m_slots; typename slot_list::reverse_iterator itBegin(copy.rbegin()); typename slot_list::reverse_iterator itEnd(copy.rend()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { (*itBegin)->activate(arg1,arg2,arg3, arg4); itBegin++; } catch(...) { throw; } } } HYDROSIG_TEMPLATE_4_ARG void signal_4<HYDROSIG_4_ARG>::operator()(Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { try { emit(arg1,arg2,arg3,arg4); } catch(...) { throw; } } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::emit( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { HYDROSIG_LIST_TYPE<Return_type> resultList; this->removeInvalidated(); if(this->isBlocked()) return resultList; HYDROSIG_PROTECTED_BLOCK_BEGIN slot_list copy = this->m_slots; typename slot_list::iterator itBegin(copy.begin()); typename slot_list::iterator itEnd(copy.end()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { resultList.push_back((*itBegin)->activate(arg1,arg2,arg3, arg4)); itBegin++; } catch(...) { throw; } } return resultList; } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::emit_reverse( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { HYDROSIG_LIST_TYPE<Return_type> resultList; this->removeInvalidated(); if(this->isBlocked()) return resultList; HYDROSIG_PROTECTED_BLOCK_BEGIN slot_list copy = this->m_slots; typename slot_list::reverse_iterator itBegin(copy.rbegin()); typename slot_list::reverse_iterator itEnd(copy.rend()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { resultList.push_back((*itBegin)->activate(arg1,arg2,arg3, arg4)); itBegin++; } catch(...) { throw; } } return resultList; } HYDROSIG_TEMPLATE_4_ARG HYDROSIG_LIST_TYPE<Return_type> signal_4<HYDROSIG_4_ARG>::collected::operator()( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { try { return emit(arg1,arg2,arg3, arg4); } catch(...) { throw; } } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined() : m_combiner(new Combiner_type()) { ; } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined( const Combiner_type &combiner) : m_combiner(new Combiner_type(combiner)) { ; } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined( const combined &src) : signal_4_base<HYDROSIG_4_ARG>(src) { HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>( new Combiner_type(*(src.m_combiner))); HYDROSIG_REMOTE_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::combined( combined &&src) : signal_4_base<HYDROSIG_4_ARG>( std::forward<signal_4_base<HYDROSIG_4_ARG>>(src)) { HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN m_combiner = std::move(src.m_combiner); HYDROSIG_REMOTE_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>& signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator=( const combined &src) { if(this == &src) return *this; signal_4_base<HYDROSIG_4_ARG>::operator =(src); HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN HYDROSIG_PROTECTED_BLOCK_BEGIN m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>( new Combiner_type(*(src.m_combiner))); HYDROSIG_PROTECTED_BLOCK_END HYDROSIG_REMOTE_PROTECTED_BLOCK_END return *this; } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>& signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator=( combined &&src) { if(this == &src) return *this; signal_4_base<HYDROSIG_4_ARG>::operator =( std::forward<signal_4_base<HYDROSIG_4_ARG>>(src)); HYDROSIG_REMOTE_PROTECTED_BLOCK_BEGIN HYDROSIG_PROTECTED_BLOCK_BEGIN m_combiner = std::move(src.m_combiner); HYDROSIG_PROTECTED_BLOCK_END HYDROSIG_REMOTE_PROTECTED_BLOCK_END return *this; } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> Combiner_type& signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::getCombiner() { return *m_combiner; } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> void signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::setCombiner( const Combiner_type &combiner) { HYDROSIG_PROTECTED_BLOCK_BEGIN m_combiner = HYDROSIG_SHARED_PTR_TYPE<Combiner_type>(combiner); HYDROSIG_PROTECTED_BLOCK_END } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::emit( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { if(this->isBlocked()) return m_combiner->value(); this->removeInvalidated(); HYDROSIG_PROTECTED_BLOCK_BEGIN HYDROSIG_SHARED_PTR_TYPE<Combiner_type> combiner(m_combiner); slot_list copy = this->m_slots; typename slot_list::iterator itBegin(copy.begin()); typename slot_list::iterator itEnd(copy.end()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { (*combiner)((*itBegin)->activate(arg1,arg2,arg3, arg4)); itBegin++; } catch(...) { throw; } } return combiner->value(); } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::emit_reverse( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { if(this->isBlocked()) return m_combiner->value(); this->removeInvalidated(); HYDROSIG_PROTECTED_BLOCK_BEGIN HYDROSIG_SHARED_PTR_TYPE<Combiner_type> combiner(m_combiner); slot_list copy = this->m_slots; typename slot_list::reverse_iterator itBegin(copy.rbegin()); typename slot_list::reverse_iterator itEnd(copy.rend()); HYDROSIG_PROTECTED_BLOCK_END while(itBegin != itEnd) { // Skip the slot if blocked or invalid if(!(*itBegin)->isValid() || (*itBegin)->isBlocked()) { itBegin++; continue; } // Activating the slot try { (*combiner)((*itBegin)->activate(arg1,arg2,arg3, arg4)); itBegin++; } catch(...) { throw; } } return combiner->value(); } HYDROSIG_TEMPLATE_4_ARG template<class Combiner_type> Return_type signal_4<HYDROSIG_4_ARG>::combined<Combiner_type>::operator()( Arg1_type arg1, Arg2_type arg2, Arg3_type arg3, Arg4_type arg4) { try { return emit(arg1,arg2,arg3, arg4); } catch(...) { throw; } } HYDROSIG_NAMESPACE_END #endif // HYDROSIG_SIGNAL_4_HPP_INCLUDED
30.496042
98
0.608514
Peterskhan
3ec7e3e0ddb3a3b21ce09317ba4f6932b8fc5271
453
cpp
C++
FangameReader/GlFont.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
3
2019-04-02T19:23:35.000Z
2021-04-30T03:57:15.000Z
FangameReader/GlFont.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
1
2018-07-10T22:34:41.000Z
2018-07-10T22:52:43.000Z
FangameReader/GlFont.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
3
2020-12-28T19:06:07.000Z
2021-01-30T10:09:56.000Z
#include <common.h> #pragma hdrstop #include <GlFont.h> namespace Fangame { ////////////////////////////////////////////////////////////////////////// CGlFont::CGlFont( CUnicodeView fontName, int fontSize ) : font( fontName ), renderer( CreateOwner<CFreeTypeGlyphProvider>( font, fontSize ) ) { renderer.LoadBasicCharSet(); } ////////////////////////////////////////////////////////////////////////// } // namespace Fangame.
22.65
75
0.456954
TheBiob
3ec8a6c5ac9c61483b1d7c98c26ecfba15563680
1,804
cc
C++
midlib/trunk/buffer.cc
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
4
2015-07-27T04:05:50.000Z
2021-01-28T21:56:09.000Z
midlib/trunk/buffer.cc
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
null
null
null
midlib/trunk/buffer.cc
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
null
null
null
#include "buffer.h" #include <iostream> #include <string.h> #include <strings.h> using namespace std; namespace midi { Buffer::Buffer(const char* data, unsigned long len) : data_(data), len_(len), pos_(0) { } Buffer::~Buffer() { } bool Buffer::Read(char* c) { return Read(c, 1); } bool Buffer::Read(unsigned char* c) { return Read((char*)c, 1); } bool Buffer::Read(char* buf, unsigned long count) { if (pos_ + count > len_) { cerr << "Read past end of buffer! (" << pos_ + count << " > " << len_ << ")" << endl; return false; } bcopy(&data_[pos_], buf, count); pos_ += count; return true; } bool Buffer::Read(unsigned short* value) { if (pos_ + sizeof(unsigned short) > len_) { cerr << "Read past end of buffer!" << endl; return false; } bcopy(&data_[pos_], value, sizeof(unsigned short)); pos_ += sizeof(unsigned short); return true; } bool Buffer::Read(unsigned long* value) { if (pos_ + sizeof(unsigned long) > len_) { cerr << "Read past end of buffer!" << endl; return false; } bcopy(&data_[pos_], value, sizeof(unsigned long)); pos_ += sizeof(unsigned long); return true; } bool Buffer::ReadVar(unsigned int* value) { unsigned int v = 0; int numcount = 0; *value = 0; while (numcount <= 4) { unsigned char c = 0; if (!Read((char*)&c)) { return false; } if ((c & 0x80) == 0x80) { v = (v<<7) + c - 0x80; } else { v = (v<<7) + c; break; } numcount++; } *value = v; return true; } bool Buffer::Seek(unsigned long offset) { if (offset > len_) { cerr << "Read past end of buffer!" << endl; return false; } pos_ = offset; return true; } bool Buffer::SeekRelative(unsigned long offset) { return Seek(pos_ + offset); } } // namespace midi
19.824176
65
0.588137
allenporter
3eca1e161cd1853477bd14ad924017aaec6d3d43
739
cpp
C++
tests/test_trivial.cpp
mit-gfx/recfilter
0489a3f5d262c84b78dce15b56c0aef0f8df83e9
[ "MIT" ]
13
2016-06-03T16:49:52.000Z
2022-01-07T10:21:03.000Z
tests/test_trivial.cpp
mit-gfx/recfilter
0489a3f5d262c84b78dce15b56c0aef0f8df83e9
[ "MIT" ]
1
2020-02-24T03:28:19.000Z
2020-03-10T23:49:49.000Z
tests/test_trivial.cpp
mit-gfx/recfilter
0489a3f5d262c84b78dce15b56c0aef0f8df83e9
[ "MIT" ]
null
null
null
#include <iostream> #include <Halide.h> #include <recfilter.h> using namespace Halide; int main(int argc, char **argv) { int width = 20; int height = 20; int tile = 4; Image<float> image = generate_random_image<float>(width,height); RecFilterDim x("x", width), y("y", height); RecFilter filter; filter(x,y) = image(x,y); filter.add_filter(+x, {1.0, 1.0}); filter.add_filter(+y, {1.0, 1.0}); filter.split(x, tile, y, tile); //filter.intra_schedule().compute_globally(); //filter.inter_schedule().compute_globally(); std::cerr << filter << std::endl; Realization out = filter.realize(); Image<float> hl_out(out); std::cerr << hl_out << std::endl; return 0; }
21.114286
68
0.614344
mit-gfx
3eca661c6f612772afd46a8fd5461d585c427bfc
254
cpp
C++
resources/minimal-example.cpp
hasahmed/shape_game_cpp
1f14ba1d3f6dc31723de827c21714bdc7bc3acaa
[ "MIT" ]
null
null
null
resources/minimal-example.cpp
hasahmed/shape_game_cpp
1f14ba1d3f6dc31723de827c21714bdc7bc3acaa
[ "MIT" ]
null
null
null
resources/minimal-example.cpp
hasahmed/shape_game_cpp
1f14ba1d3f6dc31723de827c21714bdc7bc3acaa
[ "MIT" ]
null
null
null
#include "shapegame.hpp" using namespace shapegame; int main() { Game game(400, 400, "My New Game"); game.scene->setBackgroundColor(Color::BLUE); game.scene->addChild(new TriangleIsosceles(100, 100, Position(100, 100), Color::BLACK)); game.run(); }
25.4
89
0.716535
hasahmed
3ecc6ba4f19740f0e490edf7bb76c3be07c09aef
3,397
hpp
C++
http_server/include/op.hpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
http_server/include/op.hpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
http_server/include/op.hpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
#pragma once // // Copyright (c) 2015, J2 Innovations // Copyright (c) 2012 Brian Frank // Licensed under the Academic Free License version 3.0 // History: // 08 Sep 2014 Radu Racariu<radur@2inn.com> Ported to C++ // 06 Jun 2011 Brian Frank Creation // #include "headers.hpp" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "grid.hpp" #include "ref.hpp" using Poco::Net::HTTPServerRequest; using Poco::Net::HTTPServerResponse; namespace haystack { class Server; class Uri; class Ref; class Val; /** Op is the base class for server side operations exposed by the REST API. All methods on Op must be thread safe. @see <a href = 'http://project-haystack.org/doc/Ops'>Project Haystack< / a> */ class Op : boost::noncopyable { public: Op() {} /** Programatic name of the operation. */ virtual const std::string name() const = 0; /** Short one line summary of what the operation does. */ virtual const std::string summary() const = 0; /** Service the request and return response. This method routes to "on_service(Server& db, const Grid& req)" */ void on_service(Server& db, HTTPServerRequest& req, HTTPServerResponse& res); /** Service the request and return response. */ virtual Grid::auto_ptr_t on_service(Server& db, const Grid& req); protected: typedef boost::ptr_vector<Ref> refs_t; refs_t grid_to_ids(const Server& db, const Grid& grid) const; Val::auto_ptr_t val_to_id(const Server& db, const Val& val) const; private: // Map the GET query parameters to grid with one row Grid::auto_ptr_t get_to_grid(HTTPServerRequest& req); // Map the POST body to grid Grid::auto_ptr_t post_to_grid(HTTPServerRequest& req, HTTPServerResponse& res); }; class StdOps { public: /** List the registered operations. */ static const Op& about; /** List the registered operations. */ static const Op& ops; /** List the registered grid formats. */ static const Op& formats; /** Read entity records in database. */ static const Op& read; /** Navigate tree structure of database. */ static const Op& nav; /** Watch subscription. */ static const Op& watch_sub; /** Watch unsubscription. */ static const Op& watch_unsub; /** Watch poll cov or refresh. */ static const Op& watch_poll; /** List all Watches. */ static const Op& watch_list; /** Read/write writable point priority array. */ static const Op& point_write; /** Read time series history data. */ static const Op& his_read; /** Write time series history data. */ static const Op& his_write; /** Invoke action. */ static const Op& invoke_action; typedef std::map<std::string, const Op* const> ops_map_t; static const ops_map_t& ops_map(); private: static ops_map_t* m_ops_map; }; }
25.734848
87
0.574919
kushaldalsania
3ecef9f340aa1eec159ea6ca6c738500fd62513d
17,991
cpp
C++
BezierWeights.cpp
sereslorant/gb_patch_gpu
cb7d47c28acd11925ead7d0916de44ba051a5b10
[ "MIT" ]
null
null
null
BezierWeights.cpp
sereslorant/gb_patch_gpu
cb7d47c28acd11925ead7d0916de44ba051a5b10
[ "MIT" ]
null
null
null
BezierWeights.cpp
sereslorant/gb_patch_gpu
cb7d47c28acd11925ead7d0916de44ba051a5b10
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <string> #include <cstring> PFNGLGENBUFFERSPROC glGenBuffers; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLBINDBUFFERRANGEPROC glBindBufferRange; PFNGLBUFFERDATAPROC glBufferData; PFNGLMAPBUFFERPROC glMapBuffer; PFNGLUNMAPBUFFERPROC glUnmapBuffer; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; PFNGLBINDVERTEXARRAYPROC glBindVertexArray; PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; PFNGLCREATESHADERPROC glCreateShader; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLDELETESHADERPROC glDeleteShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLATTACHSHADERPROC glAttachShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLDETACHSHADERPROC glDetachShader; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLPATCHPARAMETERIPROC glPatchParameteri; void GLLoadExtensions() { glGenBuffers = (PFNGLGENBUFFERSPROC)SDL_GL_GetProcAddress("glGenBuffers"); glBindBuffer = (PFNGLBINDBUFFERPROC)SDL_GL_GetProcAddress("glBindBuffer"); glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)SDL_GL_GetProcAddress("glBindBufferRange"); glBufferData = (PFNGLBUFFERDATAPROC)SDL_GL_GetProcAddress("glBufferData"); glMapBuffer = (PFNGLMAPBUFFERPROC)SDL_GL_GetProcAddress("glMapBuffer"); glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)SDL_GL_GetProcAddress("glUnmapBuffer"); glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)SDL_GL_GetProcAddress("glDeleteBuffers"); glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glGenVertexArrays"); glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)SDL_GL_GetProcAddress("glBindVertexArray"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glDeleteVertexArrays"); glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray"); glVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)SDL_GL_GetProcAddress("glVertexAttribFormat"); glVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)SDL_GL_GetProcAddress("glVertexAttribBinding"); glBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)SDL_GL_GetProcAddress("glBindVertexBuffer"); glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)SDL_GL_GetProcAddress("glDrawElementsBaseVertex"); glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader"); glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource"); glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader"); glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader"); glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram"); glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram"); glDetachShader = (PFNGLDETACHSHADERPROC)SDL_GL_GetProcAddress("glDetachShader"); glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)SDL_GL_GetProcAddress("glDeleteProgram"); glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)SDL_GL_GetProcAddress("glPatchParameteri"); } PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB; PFNGLGETINFOLOGARBPROC glGetInfoLogARB; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; void GLDbgLoadExtensions() { glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB"); glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB"); glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv"); glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog"); } #include <iostream> void lGLDbgPrintShaderCompileError(GLuint shader) { GLint compiled; glGetObjectParameterivARB(shader,GL_COMPILE_STATUS,&compiled); if(!compiled) { GLint ret_size; char log[256]; glGetInfoLogARB(shader,sizeof(log),&ret_size,log); std::cerr << log << std::endl; } } void lGLDbgPrintProgramLinkError(GLuint program) { GLint linked; glGetProgramiv(program,GL_LINK_STATUS,&linked); if(!linked) { GLint ret_size; char log[256]; glGetProgramInfoLog(program,sizeof(log),&ret_size,log); std::cerr << log << std::endl; } } std::string VertexShaderSrc = R"( #version 400 void main() { } )"; std::string TcShaderSrc = R"( #version 400 layout(vertices = 3) out; void main() { gl_TessLevelOuter[0] = 16.0; gl_TessLevelOuter[1] = 16.0; gl_TessLevelOuter[2] = 16.0; gl_TessLevelInner[0] = 16.0; } )"; std::string TeShaderSrc = R"( #version 400 layout(triangles,equal_spacing,ccw) in; const uint MAX_SIDE_COUNT = 5; out vec3 OutColor; float BinomialCoefficient(uint k,uint n) { float Accumulator = 1.0; for(uint i=1;i <= k;i++) { Accumulator *= (n + 1.0 - i)/i; } return Accumulator; } void main() { const uint SIDE_COUNT = 5; const uint DEGREE = 5; const uint LAYERS = (DEGREE + 1) / 2; const float PI = 3.14159265359; const float EPSILON = 1e-2; uint VertexId0 = (gl_PrimitiveID % SIDE_COUNT); uint VertexId1 = ((gl_PrimitiveID + 1) % SIDE_COUNT); vec3 Vertices[MAX_SIDE_COUNT]; for(uint i=0;i < SIDE_COUNT;i++) { float SinParam = float(i)/ SIDE_COUNT; Vertices[i] = vec3(cos(SinParam * 2.0 * PI),sin(SinParam * 2.0 * PI),0.0); } vec3 UvCoord = gl_TessCoord.y * Vertices[VertexId0] + gl_TessCoord.z * Vertices[VertexId1]; float SumBaryCoords = 0.0; float BaryCoords[MAX_SIDE_COUNT]; for(uint i=0;i < SIDE_COUNT;i++) { uint Prev = (i-1); uint Curr = i; uint Next = (i+1) % SIDE_COUNT; if(i == 0) {Prev = SIDE_COUNT - 1;} float A1 = length(cross(Vertices[Curr] - UvCoord,Vertices[Prev] - UvCoord))/2.0; float A2 = length(cross(Vertices[Curr] - UvCoord,Vertices[Next] - UvCoord))/2.0; float C = length(cross(Vertices[Prev] - Vertices[Curr],Vertices[Next] - Vertices[Curr]))/2.0; BaryCoords[i] = C/(A1*A2); SumBaryCoords += BaryCoords[i]; } for(uint i=0;i < SIDE_COUNT;i++) { if(gl_TessCoord.x > EPSILON) {BaryCoords[i] /= SumBaryCoords;} else {BaryCoords[i] = 0.0;} } if(gl_TessCoord.x < EPSILON) { BaryCoords[VertexId0] = gl_TessCoord.y; BaryCoords[VertexId1] = gl_TessCoord.z; } vec2 SideCoords[MAX_SIDE_COUNT]; for(uint i=0;i < SIDE_COUNT;i++) { SideCoords[i] = vec2(0.0,0.0); uint Prev = (i-1); uint Curr = i; if(i == 0) {Prev = SIDE_COUNT - 1;} float Denominator = BaryCoords[Prev] + BaryCoords[Curr]; SideCoords[i].x = BaryCoords[Curr] / Denominator; if(Denominator < EPSILON) {SideCoords[i].x = 0.0;} SideCoords[i].y = 1.0 - BaryCoords[Prev] - BaryCoords[Curr]; } float CentralCoeff = 1.0; float BezierRibbonContrib[MAX_SIDE_COUNT]; for(uint i=0;i < SIDE_COUNT;i++) { BezierRibbonContrib[i] = 0.0; uint Prev = (i-1); uint Curr = i; uint Next = (i+1) % SIDE_COUNT; if(i == 0) {Prev = SIDE_COUNT - 1;} for(uint j=0;j <= DEGREE;j++) { for(uint k=0;k < LAYERS;k++) { float Bernstein = BinomialCoefficient(j,DEGREE)*pow(1.0-SideCoords[i].x,DEGREE-j)*pow(SideCoords[i].x,j) * BinomialCoefficient(k,DEGREE)*pow(1.0-SideCoords[i].y,DEGREE-k)*pow(SideCoords[i].y,k); float Weight = 1.0; if(k < 2) { if(j < 2) { float Denominator = (SideCoords[Prev].y + SideCoords[Curr].y); if(Denominator < EPSILON) {Weight = 1.0;} else {Weight = (SideCoords[Prev].y)/Denominator;} } if(j > (DEGREE - 2)) { float Denominator = (SideCoords[Next].y + SideCoords[Curr].y); if(Denominator < EPSILON) {Weight = 0.0;} else {Weight = (SideCoords[Next].y)/Denominator;} } } else { if(j < LAYERS) { if(j < k) {Weight = 0.0;} else if(j == k) {Weight = 0.5;} } else { if(j > (DEGREE - k)) {Weight = 0.0;} else if(j == (DEGREE - k)) {Weight = 0.5;} } } float Coeff = Bernstein * Weight; BezierRibbonContrib[i] += Coeff; CentralCoeff -= Coeff; } } } float ColorY = 0.0;//SideCoords[SIDE_COUNT - 1].y; //float ColorZ = 0.0;//SideCoords[1].y; float ColorZ = CentralCoeff; OutColor = vec3(BezierRibbonContrib[0],BezierRibbonContrib[1],CentralCoeff); OutColor = vec3(BezierRibbonContrib[1],BezierRibbonContrib[2],CentralCoeff); OutColor = vec3(BezierRibbonContrib[2],BezierRibbonContrib[3],CentralCoeff); OutColor = vec3(BezierRibbonContrib[3],BezierRibbonContrib[4],CentralCoeff); OutColor = vec3(BezierRibbonContrib[4],BezierRibbonContrib[0],CentralCoeff); gl_Position = vec4(UvCoord,1.0); } )"; std::string FragmentShaderSrc = R"( #version 400 in vec3 OutColor; layout(location=0) out vec4 FragColor; void main() { FragColor = vec4(OutColor,1.0); } )"; class GLApp { private: GLuint VertexBuffer = 0; GLuint IndexBuffer = 0; GLuint VertexArrayObject = 0; GLuint ShaderProgram = 0; public: void Loop() { glClearColor(0.5,0.5,0.5,1.0); glClear(GL_COLOR_BUFFER_BIT); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); glUseProgram(ShaderProgram); glBindVertexArray(VertexArrayObject); glBindVertexBuffer(0,VertexBuffer,0,2*sizeof(float)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,IndexBuffer); glPatchParameteri(GL_PATCH_VERTICES,3); //glDrawElements(GL_PATCHES,9,GL_UNSIGNED_INT,0); //glDrawElements(GL_PATCHES,12,GL_UNSIGNED_INT,0); glDrawElements(GL_PATCHES,15,GL_UNSIGNED_INT,0); } GLApp() { std::cout << VertexShaderSrc << std::endl; std::cout << TcShaderSrc << std::endl; std::cout << TeShaderSrc << std::endl; std::cout << FragmentShaderSrc << std::endl; GLLoadExtensions(); GLDbgLoadExtensions(); { const char *ShaderSource = VertexShaderSrc.c_str(); GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShader,1,&ShaderSource,nullptr); glCompileShader(VertexShader); lGLDbgPrintShaderCompileError(VertexShader); ShaderSource = TcShaderSrc.c_str(); GLuint TcShader = glCreateShader(GL_TESS_CONTROL_SHADER); glShaderSource(TcShader,1,&ShaderSource,nullptr); glCompileShader(TcShader); lGLDbgPrintShaderCompileError(TcShader); ShaderSource = TeShaderSrc.c_str(); GLuint TeShader = glCreateShader(GL_TESS_EVALUATION_SHADER); glShaderSource(TeShader,1,&ShaderSource,nullptr); glCompileShader(TeShader); lGLDbgPrintShaderCompileError(TeShader); ShaderSource = FragmentShaderSrc.c_str(); GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShader,1,&ShaderSource,nullptr); glCompileShader(FragmentShader); lGLDbgPrintShaderCompileError(FragmentShader); ShaderProgram = glCreateProgram(); glAttachShader(ShaderProgram,VertexShader); glAttachShader(ShaderProgram,TcShader); glAttachShader(ShaderProgram,TeShader); glAttachShader(ShaderProgram,FragmentShader); glLinkProgram(ShaderProgram); glDetachShader(ShaderProgram,VertexShader); glAttachShader(ShaderProgram,TcShader); glAttachShader(ShaderProgram,TeShader); glDetachShader(ShaderProgram,FragmentShader); lGLDbgPrintProgramLinkError(ShaderProgram); glDeleteShader(VertexShader); glDeleteShader(TcShader); glDeleteShader(TeShader); glDeleteShader(FragmentShader); } { unsigned int NumVertices = 5; std::size_t VertexDataSize = NumVertices * 2 * sizeof(float); float VertexData[] = { -0.125,-0.125, 0.125,-0.125, 0.125, 0.125, -0.125, 0.125, 0.375, 0.125, }; unsigned int NumIndices = 18; std::size_t IndexDataSize = NumIndices * sizeof(std::uint32_t); std::uint32_t IndexData[] = { 0,1,2, 0,2,3, 1,2,4, 0,1,2, 0,2,3, 1,2,4, }; glGenBuffers(1,&VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer); glBufferData(GL_ARRAY_BUFFER,VertexDataSize,VertexData,GL_STATIC_DRAW); glGenBuffers(1,&IndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,IndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER,IndexDataSize,IndexData,GL_STATIC_DRAW); } glGenVertexArrays(1,&VertexArrayObject); glBindVertexArray(VertexArrayObject); glEnableVertexAttribArray(0); glVertexAttribFormat(0, 2, GL_FLOAT, GL_FALSE, 0 ); glVertexAttribBinding(0,0); } ~GLApp() { glDeleteBuffers(1,&VertexBuffer); glDeleteBuffers(1,&IndexBuffer); glDeleteVertexArrays(1,&VertexArrayObject); glDeleteProgram(ShaderProgram); } }; int main(int argc, char **argv) { SDL_Window *Window; SDL_GLContext GLContext; SDL_Init(SDL_INIT_EVERYTHING); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); Window = SDL_CreateWindow("GLRenderSample",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,600,600,SDL_WINDOW_OPENGL); GLContext = SDL_GL_CreateContext(Window); SDL_ShowWindow(Window); GLApp App; bool Running = true; while(Running) { int BeginTime = SDL_GetTicks(); SDL_Event Event; while(SDL_PollEvent(&Event)) { if(Event.type == SDL_QUIT) { Running = false; } } App.Loop(); SDL_GL_SwapWindow(Window); int EndTime = SDL_GetTicks(); std::cout << "Frame time: " << (EndTime-BeginTime) << "ms\nFps: " << 1000.0/(EndTime-BeginTime) << std::endl; } SDL_GL_DeleteContext(GLContext); SDL_DestroyWindow(Window); SDL_Quit(); return 0; }
32.950549
126
0.579901
sereslorant
3ecf7457bcdc4adfc815c79e6f95c8c509d9b8d3
1,146
cpp
C++
Algorithms/ReverseLL.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
98
2018-10-09T15:42:41.000Z
2021-10-04T15:25:44.000Z
Algorithms/ReverseLL.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
141
2018-10-06T16:55:20.000Z
2021-10-31T18:25:35.000Z
Algorithms/ReverseLL.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
885
2018-10-06T17:14:44.000Z
2022-01-29T03:16:21.000Z
/// Recursive approach //this code is used to reverse a linked list #include<iostream> using namespace std; class node{ public: int data; node * next; node(int data){ this->data=data; this->next=NULL; } }; node* takeinput(){ int data; cin>>data; node* head=NULL,*tail=NULL; while(data!=-1){ node *newnode=new node(data); if(head==NULL) { head=newnode; tail=newnode; } else{ tail->next=newnode; tail=newnode; } cin>>data; } return head; } void print(node *head) { node*temp=head; while(temp!=NULL) { cout<<temp->data<<" "; temp=temp->next; } cout<<endl; } node *reverse_linked_list_rec(node *head) { node*temp=head; if(head->next==NULL) { return head; } node *s=reverse_linked_list_rec(head->next); node* t=s; while(t->next!=NULL) { t=t->next; } t->next=temp; temp->next=NULL; return s; } int main(){ node* head=takeinput(); head=reverse_linked_list_rec(head); print(head); return 0; }
16.140845
46
0.534031
Praggya17
3ed0385635d5f4369955886cb903dff9e49a0d44
1,729
cpp
C++
src/10. MinPerimeterRectangle.cpp
zooyouny/codility
260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7
[ "Unlicense" ]
null
null
null
src/10. MinPerimeterRectangle.cpp
zooyouny/codility
260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7
[ "Unlicense" ]
null
null
null
src/10. MinPerimeterRectangle.cpp
zooyouny/codility
260ecc4045f8c28d3b65e9ffe56ef50f3098f7e7
[ "Unlicense" ]
null
null
null
#include "gtest/gtest.h" /* 정수 N이 주어졌을 때 최소 둘레(perimeter)를 찾는 문제. 여기서 N은 사각형의 넓이. 예) N = 30 이라면 다음과 같은 조합이 있을 수 있음 (1, 30), with a perimeter of 62, (2, 15), with a perimeter of 34, (3, 10), with a perimeter of 26, (5, 6), with a perimeter of 22. 여기서 최소 넓이는 22 이므로 22를 리턴하면 된다. 힌트 : * 한 변의 길이가 정해지면 다른 한변의 길이는 자동으로 결정 된다. (w, h = 넓이 / w) * 모든 w 에 대해 perimeter를 구해보고 최소값을 찾아 리턴하면 된다. * w 의 범위는 [1, sqrt(넓이)] 로 한정할 수 있다. * w 가 sqrt(넓이)에 가까울 수록 perimeter는 작아지므로 sqrt(넓이)에서 부터 1의 방향으로 순회하면 좀 더 빨리 찾을 수 있다. ** 그렇다 하더라도 O(sqrt(N)) 는 동일 주의 : * 최소값(1), 최대값(1,000,000,000), 소수(982,451,653)와 같은 최악의 경우에 대해 테스트가 필요하다. */ #include <iostream> #include <random> #include <vector> #include <algorithm> #include <unordered_map> #include <map> #include <ctime> #include <stack> using namespace std; int perimeter(int w, int h) { return 2 * (w + h); } int solution(int N) { // 1 ~ 1,000,000,000 int sol = perimeter(1, N); int rootN = static_cast<int>(sqrt(N)); for (int i = rootN; i >= 1; i--) { if (N % i == 0) { auto ret = perimeter(i, N / i); return ret; } } return sol; } TEST(MinPerimeterRectangle, SimpleTest) { EXPECT_EQ(22, solution(30)); EXPECT_EQ(4, solution(1)); EXPECT_EQ(24, solution(36)); EXPECT_EQ(28, solution(48)); EXPECT_EQ(204, solution(101)); EXPECT_EQ(1238, solution(1234)); } TEST(MinPerimeterRectangle, ExtremeTest) { EXPECT_EQ(27116, solution(45664320)); EXPECT_EQ(30972904, solution(15486451)); EXPECT_EQ(40000, solution(100000000)); EXPECT_EQ(1964903308, solution(982451653)); EXPECT_EQ(126500, solution(1000000000)); }
24.352113
83
0.59919
zooyouny
a79205d8c479bc8ef26150762193843d5e6a486e
26,700
inl
C++
Extras/RigidBodyGpuPipeline/dynamics/basic_demo/Stubs/SolverHost.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
2
2015-02-28T15:50:06.000Z
2016-04-12T18:03:10.000Z
Extras/RigidBodyGpuPipeline/dynamics/basic_demo/Stubs/SolverHost.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
Extras/RigidBodyGpuPipeline/dynamics/basic_demo/Stubs/SolverHost.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
/* Copyright (c) 2012 Advanced Micro Devices, Inc. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //Originally written by Takahiro Harada class SolverInl { public: typedef SolverBase::ConstraintData ConstraintData; static __forceinline void setLinearAndAngular(const MYF4& n, const MYF4& r0, const MYF4& r1, MYF4& linear, MYF4& angular0, MYF4& angular1) { linear = -n; angular0 = -cross3(r0, n); angular1 = cross3(r1, n); } static __forceinline float calcJacCoeff(const MYF4& linear0, const MYF4& linear1, const MYF4& angular0, const MYF4& angular1, float invMass0, const Matrix3x3& invInertia0, float invMass1, const Matrix3x3& invInertia1) { // linear0,1 are normlized float jmj0 = invMass0;//dot3F4(linear0, linear0)*invMass0; float jmj1 = dot3F4(mtMul3(angular0,invInertia0), angular0); float jmj2 = invMass1;//dot3F4(linear1, linear1)*invMass1; float jmj3 = dot3F4(mtMul3(angular1,invInertia1), angular1); return -1.f/(jmj0+jmj1+jmj2+jmj3); } static __forceinline float calcRelVel(const MYF4& l0, const MYF4& l1, const MYF4& a0, const MYF4& a1, const MYF4& linVel0, const MYF4& angVel0, const MYF4& linVel1, const MYF4& angVel1) { return dot3F4(l0, linVel0) + dot3F4(a0, angVel0) + dot3F4(l1, linVel1) + dot3F4(a1, angVel1); } static __forceinline void setConstraint4( const MYF4& posA, const MYF4& linVelA, const MYF4& angVelA, float invMassA, const Matrix3x3& invInertiaA, const MYF4& posB, const MYF4& linVelB, const MYF4& angVelB, float invMassB, const Matrix3x3& invInertiaB, const Contact4& src, const SolverBase::ConstraintCfg& cfg, Constraint4& dstC ) { dstC.m_bodyA = (u32)src.m_bodyAPtr; dstC.m_bodyB = (u32)src.m_bodyBPtr; float dtInv = 1.f/cfg.m_dt; for(int ic=0; ic<4; ic++) { dstC.m_appliedRambdaDt[ic] = 0.f; } dstC.m_fJacCoeffInv[0] = dstC.m_fJacCoeffInv[1] = 0.f; const MYF4& n = src.m_worldNormal; dstC.m_linear = -n; dstC.setFrictionCoeff( src.getFrictionCoeff() ); for(int ic=0; ic<4; ic++) { MYF4 r0 = src.m_worldPos[ic] - posA; MYF4 r1 = src.m_worldPos[ic] - posB; if( ic >= src.getNPoints() ) { dstC.m_jacCoeffInv[ic] = 0.f; continue; } float relVelN; { MYF4 linear, angular0, angular1; setLinearAndAngular(n, r0, r1, linear, angular0, angular1); dstC.m_jacCoeffInv[ic] = calcJacCoeff(linear, -linear, angular0, angular1, invMassA, invInertiaA, invMassB, invInertiaB ); relVelN = calcRelVel(linear, -linear, angular0, angular1, linVelA, angVelA, linVelB, angVelB); float e = src.getRestituitionCoeff(); if( relVelN*relVelN < 0.004f ) e = 0.f; dstC.m_b[ic] = e*relVelN; dstC.m_b[ic] += (src.getPenetration(ic) + cfg.m_positionDrift)*cfg.m_positionConstraintCoeff*dtInv; dstC.m_appliedRambdaDt[ic] = 0.f; } } if( src.getNPoints() > 1 ) { // prepare friction MYF4 center = MAKE_MYF4(0.f); for(int i=0; i<src.getNPoints(); i++) center += src.m_worldPos[i]; center /= (float)src.getNPoints(); MYF4 tangent[2]; tangent[0] = cross3( src.m_worldNormal, src.m_worldPos[0]-center ); tangent[1] = cross3( tangent[0], src.m_worldNormal ); tangent[0] = normalize3( tangent[0] ); tangent[1] = normalize3( tangent[1] ); MYF4 r[2]; r[0] = center - posA; r[1] = center - posB; for(int i=0; i<2; i++) { MYF4 linear, angular0, angular1; setLinearAndAngular(tangent[i], r[0], r[1], linear, angular0, angular1); dstC.m_fJacCoeffInv[i] = calcJacCoeff(linear, -linear, angular0, angular1, invMassA, invInertiaA, invMassB, invInertiaB ); dstC.m_fAppliedRambdaDt[i] = 0.f; } dstC.m_center = center; } else { // single point constraint } for(int i=0; i<4; i++) { if( i<src.getNPoints() ) { dstC.m_worldPos[i] = src.m_worldPos[i]; } else { dstC.m_worldPos[i] = MAKE_MYF4(0.f); } } } /* struct Constraint4 { float4 m_linear; X float4 m_angular0[4]; X float4 m_angular1[4]; center float m_jacCoeffInv[4]; [0,1] float m_b[4]; X float m_appliedRambdaDt[4]; [0,1] void* m_bodyAPtr; X void* m_bodyBPtr; X }; */ static __inline void solveFriction(Constraint4& cs, const MYF4& posA, MYF4& linVelA, MYF4& angVelA, float invMassA, const Matrix3x3& invInertiaA, const MYF4& posB, MYF4& linVelB, MYF4& angVelB, float invMassB, const Matrix3x3& invInertiaB, float maxRambdaDt[4], float minRambdaDt[4]) { if( cs.m_fJacCoeffInv[0] == 0 && cs.m_fJacCoeffInv[0] == 0 ) return; const MYF4& center = cs.m_center; MYF4 n = -cs.m_linear; MYF4 tangent[2]; tangent[0] = cross3( n, cs.m_worldPos[0]-center ); tangent[1] = cross3( tangent[0], n ); tangent[0] = normalize3( tangent[0] ); tangent[1] = normalize3( tangent[1] ); MYF4 angular0, angular1, linear; MYF4 r0 = center - posA; MYF4 r1 = center - posB; for(int i=0; i<2; i++) { setLinearAndAngular( tangent[i], r0, r1, linear, angular0, angular1 ); float rambdaDt = calcRelVel(linear, -linear, angular0, angular1, linVelA, angVelA, linVelB, angVelB ); rambdaDt *= cs.m_fJacCoeffInv[i]; { float prevSum = cs.m_fAppliedRambdaDt[i]; float updated = prevSum; updated += rambdaDt; updated = max2( updated, minRambdaDt[i] ); updated = min2( updated, maxRambdaDt[i] ); rambdaDt = updated - prevSum; cs.m_fAppliedRambdaDt[i] = updated; } MYF4 linImp0 = invMassA*linear*rambdaDt; MYF4 linImp1 = invMassB*(-linear)*rambdaDt; MYF4 angImp0 = mtMul1(invInertiaA, angular0)*rambdaDt; MYF4 angImp1 = mtMul1(invInertiaB, angular1)*rambdaDt; linVelA += linImp0; angVelA += angImp0; linVelB += linImp1; angVelB += angImp1; } { // angular damping for point constraint MYF4 ab = normalize3( posB - posA ); MYF4 ac = normalize3( center - posA ); if( dot3F4( ab, ac ) > 0.95f || (invMassA == 0.f || invMassB == 0.f)) { float angNA = dot3F4( n, angVelA ); float angNB = dot3F4( n, angVelB ); angVelA -= (angNA*0.1f)*n; angVelB -= (angNB*0.1f)*n; } } } template<bool JACOBI> static __inline void solveContact(Constraint4& cs, const MYF4& posA, MYF4& linVelA, MYF4& angVelA, float invMassA, const Matrix3x3& invInertiaA, const MYF4& posB, MYF4& linVelB, MYF4& angVelB, float invMassB, const Matrix3x3& invInertiaB, float maxRambdaDt[4], float minRambdaDt[4]) { MYF4 dLinVelA = MAKE_MYF4(0.f); MYF4 dAngVelA = MAKE_MYF4(0.f); MYF4 dLinVelB = MAKE_MYF4(0.f); MYF4 dAngVelB = MAKE_MYF4(0.f); for(int ic=0; ic<4; ic++) { // dont necessary because this makes change to 0 if( cs.m_jacCoeffInv[ic] == 0.f ) continue; { MYF4 angular0, angular1, linear; MYF4 r0 = cs.m_worldPos[ic] - posA; MYF4 r1 = cs.m_worldPos[ic] - posB; setLinearAndAngular( -cs.m_linear, r0, r1, linear, angular0, angular1 ); float rambdaDt = calcRelVel(cs.m_linear, -cs.m_linear, angular0, angular1, linVelA, angVelA, linVelB, angVelB ) + cs.m_b[ic]; rambdaDt *= cs.m_jacCoeffInv[ic]; { float prevSum = cs.m_appliedRambdaDt[ic]; float updated = prevSum; updated += rambdaDt; updated = max2( updated, minRambdaDt[ic] ); updated = min2( updated, maxRambdaDt[ic] ); rambdaDt = updated - prevSum; cs.m_appliedRambdaDt[ic] = updated; } MYF4 linImp0 = invMassA*linear*rambdaDt; MYF4 linImp1 = invMassB*(-linear)*rambdaDt; MYF4 angImp0 = mtMul1(invInertiaA, angular0)*rambdaDt; MYF4 angImp1 = mtMul1(invInertiaB, angular1)*rambdaDt; if( JACOBI ) { dLinVelA += linImp0; dAngVelA += angImp0; dLinVelB += linImp1; dAngVelB += angImp1; } else { linVelA += linImp0; angVelA += angImp0; linVelB += linImp1; angVelB += angImp1; } } } if( JACOBI ) { linVelA += dLinVelA; angVelA += dAngVelA; linVelB += dLinVelB; angVelB += dAngVelB; } } enum { N_SPLIT = SolverBase::N_SPLIT, }; // for parallel solve struct ParallelSolveData { u32 m_n[N_SPLIT*N_SPLIT]; u32 m_offset[N_SPLIT*N_SPLIT]; }; static __inline int sortConstraintByBatch(Contact4* cs, int n, int ignoreIdx, int simdWidth = -1) { SortData* sortData; { BT_PROFILE("new"); sortData = new SortData[n]; } u32* idxBuffer = new u32[n]; u32* idxSrc = idxBuffer; u32* idxDst = idxBuffer; int nIdxSrc, nIdxDst; const int N_FLG = 256; const int FLG_MASK = N_FLG-1; u32 flg[N_FLG/32]; #if defined(_DEBUG) for(int i=0; i<n; i++) cs[i].getBatchIdx() = -1; #endif for(int i=0; i<n; i++) idxSrc[i] = i; nIdxSrc = n; int batchIdx = 0; { BT_PROFILE("batching"); while( nIdxSrc ) { nIdxDst = 0; int nCurrentBatch = 0; // clear flag for(int i=0; i<N_FLG/32; i++) flg[i] = 0; for(int i=0; i<nIdxSrc; i++) { int idx = idxSrc[i]; ADLASSERT( idx < n ); // check if it can go int aIdx = cs[idx].m_bodyAPtr & FLG_MASK; int bIdx = cs[idx].m_bodyBPtr & FLG_MASK; u32 aUnavailable = flg[ aIdx/32 ] & (1<<(aIdx&31)); u32 bUnavailable = flg[ bIdx/32 ] & (1<<(bIdx&31)); aUnavailable = (ignoreIdx==cs[idx].m_bodyAPtr)? 0:aUnavailable; bUnavailable = (ignoreIdx==cs[idx].m_bodyBPtr)? 0:bUnavailable; if( aUnavailable==0 && bUnavailable==0 ) // ok { flg[ aIdx/32 ] |= (1<<(aIdx&31)); flg[ bIdx/32 ] |= (1<<(bIdx&31)); cs[idx].getBatchIdx() = batchIdx; sortData[idx].m_key = batchIdx; sortData[idx].m_value = idx; { nCurrentBatch++; if( nCurrentBatch == simdWidth ) { nCurrentBatch = 0; for(int i=0; i<N_FLG/32; i++) flg[i] = 0; } } } else { idxDst[nIdxDst++] = idx; } } swap2( idxSrc, idxDst ); swap2( nIdxSrc, nIdxDst ); batchIdx ++; } } { BT_PROFILE("radix sort data"); // sort SortData Device::Config cfg; Device* deviceHost = DeviceUtils::allocate( TYPE_HOST, cfg ); { Buffer<SortData> sortBuffer; sortBuffer.setRawPtr( deviceHost, sortData, n ); RadixSort<TYPE_HOST>::Data* sort = RadixSort<TYPE_HOST>::allocate( deviceHost, n ); RadixSort<TYPE_HOST>::execute( sort, sortBuffer, n ); RadixSort<TYPE_HOST>::deallocate( sort ); } DeviceUtils::deallocate( deviceHost ); } { BT_PROFILE("reorder"); // reorder Contact4* old = new Contact4[n]; memcpy( old, cs, sizeof(Contact4)*n); for(int i=0; i<n; i++) { int idx = sortData[i].m_value; cs[i] = old[idx]; } delete [] old; } { BT_PROFILE("delete"); delete [] idxBuffer; delete [] sortData; } #if defined(_DEBUG) // debugPrintf( "nBatches: %d\n", batchIdx ); for(int i=0; i<n; i++) ADLASSERT( cs[i].getBatchIdx() != -1 ); #endif return batchIdx; } }; enum { // N_SPLIT = SOLVER_N_SPLIT, // MAX_TASKS_PER_BATCH = N_SPLIT*N_SPLIT/4, }; struct SolveTask// : public ThreadPool::Task { SolveTask(const Buffer<RigidBodyBase::Body>* bodies, const Buffer<RigidBodyBase::Inertia>* shapes, const Buffer<Constraint4>* constraints, int start, int nConstraints) : m_bodies( bodies ), m_shapes( shapes ), m_constraints( constraints ), m_start( start ), m_nConstraints( nConstraints ), m_solveFriction( true ){} u16 getType(){ return 0; } void run(int tIdx) { HostBuffer<RigidBodyBase::Body>& hBody = *(HostBuffer<RigidBodyBase::Body>*)m_bodies; HostBuffer<RigidBodyBase::Inertia>& hShape = *(HostBuffer<RigidBodyBase::Inertia>*)m_shapes; HostBuffer<Constraint4>& hc = *(HostBuffer<Constraint4>*)m_constraints; for(int ic=0; ic<m_nConstraints; ic++) { int i = m_start + ic; float frictionCoeff = hc[i].getFrictionCoeff(); int aIdx = (int)hc[i].m_bodyA; int bIdx = (int)hc[i].m_bodyB; RigidBodyBase::Body& bodyA = hBody[aIdx]; RigidBodyBase::Body& bodyB = hBody[bIdx]; if( !m_solveFriction ) { float maxRambdaDt[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; float minRambdaDt[4] = {0.f,0.f,0.f,0.f}; SolverInl::solveContact<false>( hc[i], bodyA.m_pos, (MYF4&)bodyA.m_linVel, (MYF4&)bodyA.m_angVel, bodyA.m_invMass, hShape[aIdx].m_invInertia, bodyB.m_pos, (MYF4&)bodyB.m_linVel, (MYF4&)bodyB.m_angVel, bodyB.m_invMass, hShape[bIdx].m_invInertia, maxRambdaDt, minRambdaDt ); } else { float maxRambdaDt[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; float minRambdaDt[4] = {0.f,0.f,0.f,0.f}; float sum = 0; for(int j=0; j<4; j++) { sum +=hc[i].m_appliedRambdaDt[j]; } frictionCoeff = 0.7f; for(int j=0; j<4; j++) { maxRambdaDt[j] = frictionCoeff*sum; minRambdaDt[j] = -maxRambdaDt[j]; } SolverInl::solveFriction( hc[i], bodyA.m_pos, (MYF4&)bodyA.m_linVel, (MYF4&)bodyA.m_angVel, bodyA.m_invMass, hShape[aIdx].m_invInertia, bodyB.m_pos, (MYF4&)bodyB.m_linVel, (MYF4&)bodyB.m_angVel, bodyB.m_invMass, hShape[bIdx].m_invInertia, maxRambdaDt, minRambdaDt ); } } } const Buffer<RigidBodyBase::Body>* m_bodies; const Buffer<RigidBodyBase::Inertia>* m_shapes; const Buffer<Constraint4>* m_constraints; int m_start; int m_nConstraints; bool m_solveFriction; }; template<> static Solver<adl::TYPE_HOST>::Data* Solver<adl::TYPE_HOST>::allocate( const Device* device, int pairCapacity ) { Solver<adl::TYPE_HOST>::Data* data = new Data; data->m_device = device; data->m_parallelSolveData = 0; return data; } template<> static void Solver<adl::TYPE_HOST>::deallocate( Solver<TYPE_HOST>::Data* data ) { if( data->m_parallelSolveData ) delete (SolverInl::ParallelSolveData*)data->m_parallelSolveData; delete data; } void sortContacts2( Solver<TYPE_HOST>::Data* data, const Buffer<RigidBodyBase::Body>* bodyBuf, Buffer<Contact4>* contactsIn, void* additionalData, int nContacts, const Solver<TYPE_HOST>::ConstraintCfg& cfg ) { ADLASSERT( data->m_device->m_type == TYPE_HOST ); HostBuffer<RigidBodyBase::Body>* bodyNative = (HostBuffer<RigidBodyBase::Body>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, bodyBuf ); HostBuffer<Contact4>* contactNative = (HostBuffer<Contact4>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, contactsIn); if( cfg.m_enableParallelSolve ) { ADLASSERT( data->m_parallelSolveData == 0 ); data->m_parallelSolveData = new SolverInl::ParallelSolveData; SolverInl::ParallelSolveData* solveData = (SolverInl::ParallelSolveData*)data->m_parallelSolveData; HostBuffer<SortData> sortData( data->m_device, nContacts ); { // 2. set cell idx float spacing = adl::SolverBase::N_OBJ_PER_SPLIT*cfg.m_averageExtent; float xScale = 1.f/spacing; for(int i=0; i<nContacts; i++) { int idx = ((*contactNative)[i].m_bodyAPtr==cfg.m_staticIdx)? (*contactNative)[i].m_bodyBPtr:(*contactNative)[i].m_bodyAPtr; float4& p = (*bodyNative)[idx].m_pos; int xIdx = (int)((p.x-((p.x<0.f)?1.f:0.f))*xScale)&(adl::SolverBase::N_SPLIT-1); int zIdx = (int)((p.z-((p.z<0.f)?1.f:0.f))*xScale)&(adl::SolverBase::N_SPLIT-1); ADLASSERT( xIdx >= 0 && xIdx < adl::SolverBase::N_SPLIT ); ADLASSERT( zIdx >= 0 && zIdx < adl::SolverBase::N_SPLIT ); sortData[i].m_key = (xIdx+zIdx*adl::SolverBase::N_SPLIT); sortData[i].m_value = i; } } { // 3. sort by cell idx RadixSort<TYPE_HOST>::Data* sData = RadixSort<TYPE_HOST>::allocate( data->m_device, nContacts ); RadixSort<TYPE_HOST>::execute( sData, sortData, nContacts ); RadixSort<TYPE_HOST>::deallocate( sData ); } { // 4. find entries HostBuffer<u32> counts; counts.setRawPtr( data->m_device, solveData->m_n, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); HostBuffer<u32> offsets; offsets.setRawPtr( data->m_device, solveData->m_offset, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); { BoundSearch<TYPE_HOST>::Data* sData = BoundSearch<TYPE_HOST>::allocate( data->m_device ); PrefixScan<TYPE_HOST>::Data* pData = PrefixScan<TYPE_HOST>::allocate( data->m_device, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); BoundSearch<TYPE_HOST>::execute( sData, sortData, nContacts, counts, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT, BoundSearchBase::COUNT ); PrefixScan<TYPE_HOST>::execute( pData, counts, offsets, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); BoundSearch<TYPE_HOST>::deallocate( sData ); PrefixScan<TYPE_HOST>::deallocate( pData ); } #if defined(_DEBUG) { HostBuffer<u32> n0( data->m_device, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); HostBuffer<u32> offset0( data->m_device, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); for(int i=0; i<adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT; i++) { n0[i] = 0; offset0[i] = 0; } for(int i=0; i<nContacts; i++) { int idx = sortData[i].m_key; n0[idx]++; } // scan int sum = 0; for(int i=0; i<adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT; i++) { offset0[i] = sum; sum += n0[i]; } for(int i=0; i<adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT; i++) { ADLASSERT( n0[i] == counts[i] ); ADLASSERT( offset0[i] == offsets[i] ); } } #endif } { // 5. sort constraints by cellIdx Contact4* old = new Contact4[nContacts]; memcpy( old, contactNative->m_ptr, sizeof(Contact4)*nContacts ); for(int i=0; i<nContacts; i++) { int srcIdx = sortData[i].m_value; (*contactNative)[i] = old[srcIdx]; } delete [] old; } } BufferUtils::unmap<false>( bodyNative, bodyBuf ); BufferUtils::unmap<true>( contactNative, contactsIn ); } static void reorderConvertToConstraints2( Solver<TYPE_HOST>::Data* data, const Buffer<RigidBodyBase::Body>* bodyBuf, const Buffer<RigidBodyBase::Inertia>* shapeBuf, adl::Buffer<Contact4>* contactsIn, SolverData contactCOut, void* additionalData, int nContacts, const Solver<TYPE_HOST>::ConstraintCfg& cfg ) { sortContacts2( data, bodyBuf, contactsIn, additionalData, nContacts, cfg ); { SolverInl::ParallelSolveData* solveData = (SolverInl::ParallelSolveData*)data->m_parallelSolveData; Buffer<u32> n; n.setRawPtr( data->m_device, solveData->m_n, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); Buffer<u32> offsets; offsets.setRawPtr( data->m_device, solveData->m_offset, adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT ); Solver<TYPE_HOST>::batchContacts( data, contactsIn, nContacts, &n, &offsets, cfg.m_staticIdx ); printf("hello\n"); } Solver<TYPE_HOST>::convertToConstraints( data, bodyBuf, shapeBuf, contactsIn, contactCOut, additionalData, nContacts, cfg ); } template<DeviceType TYPE> static void solveContactConstraint( Solver<TYPE_HOST>::Data* data, const Buffer<RigidBodyBase::Body>* bodyBuf, const Buffer<RigidBodyBase::Inertia>* shapeBuf, SolverData constraint, void* additionalData, int n ) { Buffer<RigidBodyBase::Body>* bodyNative = BufferUtils::map<TYPE_HOST, true>( data->m_device, bodyBuf ); Buffer<RigidBodyBase::Inertia>* shapeNative = BufferUtils::map<TYPE_HOST, true>( data->m_device, shapeBuf ); Buffer<Constraint4>* constraintNative = BufferUtils::map<TYPE_HOST, true>( data->m_device, (const Buffer<Constraint4>*)constraint ); for(int iter=0; iter<data->m_nIterations; iter++) { SolveTask task( bodyNative, shapeNative, constraintNative, 0, n ); task.m_solveFriction = false; task.run(0); } for(int iter=0; iter<data->m_nIterations; iter++) { SolveTask task( bodyNative, shapeNative, constraintNative, 0, n ); task.m_solveFriction = true; task.run(0); } BufferUtils::unmap<true>( bodyNative, bodyBuf ); BufferUtils::unmap<false>( shapeNative, shapeBuf ); BufferUtils::unmap<false>( constraintNative, (const Buffer<Constraint4>*)constraint ); } #if 0 static int createSolveTasks( int batchIdx, Data* data, const Buffer<RigidBodyBase::Body>* bodyBuf, const Buffer<RigidBodyBase::Inertia>* shapeBuf, SolverData constraint, int n, ThreadPool::Task* tasksOut[], int taskCapacity ) { /* ADLASSERT( (N_SPLIT&1) == 0 ); ADLASSERT( batchIdx < N_BATCHES ); ADLASSERT( data->m_device->m_type == TYPE_HOST ); ADLASSERT( data->m_parallelSolveData ); SolverInl::ParallelSolveData* solveData = (SolverInl::ParallelSolveData*)data->m_parallelSolveData; data->m_batchIdx = 0; const int nx = N_SPLIT/2; int nTasksCreated = 0; // for(int ii=0; ii<2; ii++) for(batchIdx=0; batchIdx<4; batchIdx++) { int2 offset = make_int2( batchIdx&1, batchIdx>>1 ); for(int ix=0; ix<nx; ix++) for(int iy=0; iy<nx; iy++) { int xIdx = ix*2 + offset.x; int yIdx = iy*2 + offset.y; int cellIdx = xIdx+yIdx*N_SPLIT; int n = solveData->m_n[cellIdx]; int start = solveData->m_offset[cellIdx]; if( n == 0 ) continue; SolveTask* task = new SolveTask( bodyBuf, shapeBuf, (const Buffer<Constraint4>*)constraint, start, n ); // task->m_solveFriction = (ii==0)? false:true; tasksOut[nTasksCreated++] = task; } } return nTasksCreated; */ ADLASSERT(0); return 0; } #endif static void convertToConstraints2( Solver<TYPE_HOST>::Data* data, const Buffer<RigidBodyBase::Body>* bodyBuf, const Buffer<RigidBodyBase::Inertia>* shapeBuf, Buffer<Contact4>* contactsIn, SolverData contactCOut, void* additionalData, int nContacts, const Solver<TYPE_HOST>::ConstraintCfg& cfg ) { ADLASSERT( data->m_device->m_type == TYPE_HOST ); HostBuffer<RigidBodyBase::Body>* bodyNative = (HostBuffer<RigidBodyBase::Body>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, bodyBuf ); HostBuffer<RigidBodyBase::Inertia>* shapeNative = (HostBuffer<RigidBodyBase::Inertia>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, shapeBuf ); HostBuffer<Contact4>* contactNative = (HostBuffer<Contact4>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, contactsIn ); HostBuffer<Constraint4>* constraintNative = (HostBuffer<Constraint4>*)BufferUtils::map<TYPE_HOST, false>( data->m_device, (Buffer<Constraint4>*)contactCOut ); { #if !defined(_DEBUG) #pragma omp parallel for #endif for(int i=0; i<nContacts; i++) { // new (constraintNative+i)Constraint4; Contact4& contact = (*contactNative)[i]; if( contact.isInvalid() ) continue; int aIdx = (int)contact.m_bodyAPtr; int bIdx = (int)contact.m_bodyBPtr; { const RigidBodyBase::Body& bodyA = (*bodyNative)[aIdx]; const RigidBodyBase::Body& bodyB = (*bodyNative)[bIdx]; MYF4 posA( bodyA.m_pos ); MYF4 linVelA( bodyA.m_linVel ); MYF4 angVelA( bodyA.m_angVel ); MYF4 posB( bodyB.m_pos ); MYF4 linVelB( bodyB.m_linVel ); MYF4 angVelB( bodyB.m_angVel ); bool aIsInactive = ( isZero( linVelA ) && isZero( angVelA ) ); bool bIsInactive = ( isZero( linVelB ) && isZero( angVelB ) ); SolverInl::setConstraint4( posA, linVelA, angVelA, //(*bodyNative)[aIdx].m_invMass, (*shapeNative)[aIdx].m_invInertia, (aIsInactive)? 0.f : (*bodyNative)[aIdx].m_invMass, (aIsInactive)? mtZero() : (*shapeNative)[aIdx].m_invInertia, posB, linVelB, angVelB, //(*bodyNative)[bIdx].m_invMass, (*shapeNative)[bIdx].m_invInertia, (bIsInactive)? 0.f : (*bodyNative)[bIdx].m_invMass, (bIsInactive)? mtZero() : (*shapeNative)[bIdx].m_invInertia, contact, cfg, (*constraintNative)[i] ); (*constraintNative)[i].m_batchIdx = contact.getBatchIdx(); } } } BufferUtils::unmap<false>( bodyNative, bodyBuf ); BufferUtils::unmap<false>( shapeNative, shapeBuf ); BufferUtils::unmap<false>( contactNative, contactsIn ); BufferUtils::unmap<true>( constraintNative, (Buffer<Constraint4>*)contactCOut ); } static void batchContacts2( Solver<TYPE_HOST>::Data* data, Buffer<Contact4>* contacts, int nContacts, Buffer<u32>* n, Buffer<u32>* offsets, int staticIdx ) { ADLASSERT( data->m_device->m_type == TYPE_HOST ); HostBuffer<Contact4>* contactNative =0; HostBuffer<u32>* nNative =0; HostBuffer<u32>* offsetsNative =0; int sz = sizeof(Contact4); int sz2 = sizeof(int2); { BT_PROFILE("BufferUtils::map"); contactNative = (HostBuffer<Contact4>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, contacts, nContacts ); } { BT_PROFILE("BufferUtils::map2"); nNative = (HostBuffer<u32>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, n ); offsetsNative= (HostBuffer<u32>*)BufferUtils::map<TYPE_HOST, true>( data->m_device, offsets ); } { BT_PROFILE("sortConstraintByBatch"); int numNonzeroGrid=0; int maxNumBatches = 0; for(int i=0; i<adl::SolverBase::N_SPLIT*adl::SolverBase::N_SPLIT; i++) { int n = (*nNative)[i]; int offset = (*offsetsNative)[i]; if( n ) { numNonzeroGrid++; int numBatches = SolverInl::sortConstraintByBatch( contactNative->m_ptr+offset, n, staticIdx,-1 ); // on GPU maxNumBatches = max(numBatches,maxNumBatches); // SolverInl::sortConstraintByBatch( contactNative->m_ptr+offset, n, staticIdx ); // on CPU } } printf("maxNumBatches = %d\n", maxNumBatches); } { BT_PROFILE("BufferUtils::unmap"); BufferUtils::unmap<true>( contactNative, contacts, nContacts ); } { BT_PROFILE("BufferUtils::unmap2"); BufferUtils::unmap<false>( nNative, n ); BufferUtils::unmap<false>( offsetsNative, offsets ); } }
31.448763
244
0.652172
tizenorg
a7926411ae96cb4329ea491c1cf85e6d85f5b13c
2,649
hpp
C++
pwm/libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp
1162431386/RT-Thread
55223abcf9559baf7d77faddcbcde0c99b6c880b
[ "Apache-2.0" ]
8
2020-12-15T13:40:34.000Z
2021-11-28T14:49:37.000Z
libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp
apeng2012/RT-Thread-tmc5160-demo
2634ec85f7a050ef188ede1b23e73d0dfdce6c3e
[ "MIT" ]
null
null
null
libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/PixelDataWidget.hpp
apeng2012/RT-Thread-tmc5160-demo
2634ec85f7a050ef188ede1b23e73d0dfdce6c3e
[ "MIT" ]
4
2020-12-15T14:01:36.000Z
2022-01-25T00:17:14.000Z
/** ****************************************************************************** * This file is part of the TouchGFX 4.15.0 distribution. * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /** * @file touchgfx/widgets/PixelDataWidget.hpp * * Declares the touchgfx::PixelDataWidget class. */ #ifndef PIXELDATAWIDGET_HPP #define PIXELDATAWIDGET_HPP #include <touchgfx/Bitmap.hpp> #include <touchgfx/hal/Types.hpp> #include <touchgfx/widgets/Widget.hpp> namespace touchgfx { /** * A widget for displaying a buffer of pixel data. This can also be though of as a dynamic * bitmap where the dimensions of the bitmap is the same as the dimensions of the widget * and the actual bitmap data can be set and updated dynamically. The size of the buffer * must match the number of bytes required for the widget calculated as WIDTH x HEIGHT x * BYTES_PER_PIXEL. If the LCD is 16 bit per pixel the buffer must hold 2 bytes for each * pixel. If the LCD is 24 bit the buffer must hold 3 bytes for each pixel. */ class PixelDataWidget : public Widget { public: PixelDataWidget(); virtual void draw(const Rect& invalidatedArea) const; virtual Rect getSolidRect() const; /** * Set the pixel data to display. The given pointer must contain WIDTH x HEIGHT x * BYTES_PER_PIXEL bytes of addressable image data. * * @param [in] data Image data. * * @see setBitmapFormat */ void setPixelData(uint8_t* const data); /** * Set the format of the pixel data. The supported formats depend on the display type. * For example grayscale displays do not support color images. * * @param format Describes the format to use when reading the pixel data. */ void setBitmapFormat(Bitmap::BitmapFormat format); /** * @copydoc Image::setAlpha */ void setAlpha(uint8_t newAlpha); /** * @copydoc Image::getAlpha */ uint8_t getAlpha() const; protected: uint8_t* buffer; ///< The buffer where the pixels are copied from Bitmap::BitmapFormat format; ///< The pixel format for the data. uint8_t alpha; ///< The Alpha for this widget. }; } // namespace touchgfx #endif // PIXELDATAWIDGET_HPP
31.535714
90
0.640997
1162431386
a79467fa5283cbdd72196600acf6725810830811
9,654
inl
C++
stdx/stdx-Enum.inl
cornell-brg/xloops-bmarks
2f91a5aad168882672a8f150fc59158575ae5923
[ "BSD-3-Clause" ]
3
2017-09-26T16:03:28.000Z
2021-01-16T03:29:50.000Z
stdx/stdx-Enum.inl
cornell-brg/xloops-bmarks
2f91a5aad168882672a8f150fc59158575ae5923
[ "BSD-3-Clause" ]
null
null
null
stdx/stdx-Enum.inl
cornell-brg/xloops-bmarks
2f91a5aad168882672a8f150fc59158575ae5923
[ "BSD-3-Clause" ]
1
2017-10-13T22:03:22.000Z
2017-10-13T22:03:22.000Z
//======================================================================== // stdx-Enum.inl //======================================================================== // The implementation of enumerations is a little intricate to give us // the performance and syntax we desire while still guaranteeing that we // never use an uninitialized enumeration during the static // initialization phase. One solution to the static initialization // problem is to use static member functions which return a reference to // a _local_ static object (initialized within the member function) as // opposed to directly exposing the static member as done above. See // Item 47 in Scott Meyer's "Effective C++" for more information on this // approach. // // Unforunately, there are two issues with this approach. First, it // means every reference to an enumeration item requires a function call // and second, the syntax for using an enumeration item looks like a // function call instead of like a name. So for enumerations we use a // different approach. // // During the static initialization phase a user should always // initialize a specific enumeration item with the static_init function // and should always access that enumeration item with the static_access // function. The basic syntax for static_init is as follows: // // const Fruit Fruit::apple = Fruit::static_init(Fruit::apple,"apple"); // // We can ignore the name string for now. The static_init function is a // static member of stdx::Enum<Fruit> and it accesses some static data // in this base class. Since the base class is templated (by the // enumeration type) the static data is _unique_ for each enumeration // type. The static data includes an "inits" vector and a counter. The // inits vector contains pairs of addresses and enumeration instances. // Here is the interesting part. Each address is the address of one of // the static const enumeration items (eg. Fruit::apple). So what // static_init does is first take the address of the static const // enumeration item which is passed in as a parameter (Fruit::apple) and // look through the table to see if it finds an entry with the same // address. If it doesn't exist then we create a new entry in the table // with the address of Fruit::apple and a brand new enumeration // instance. We make sure that the new enumeration instance has a unique // id by using the static counter. Then we return a reference to the // brand new enumeration instance. The assignment operator copies the // brand new enumeration instance into the static constant Fruit::apple // during the static initialization phase. If the address already exists // in the table, then all we need to do is return a reference to the // associated enumeration instance. How could this ever happen, you // might ask? How could an entry already be in the table? The only way // that could happen is if someone else already called static_init ... // or if they called static_access! // // The static_access method is basically how other code can access the // static variable during the static initialization phase. It is works // the same as static_init except that there is no name string. So they // key point is that it doesn't matter what order static_init and // static_access are called during the static initialization phase since // both functions check to see if they are the first to be called and if // so create a new entry in the inits table otherwise they just return // the already exisiting item in the table. // // The name string just gives us a way to convert enumerations to and // from strings. We keep a static vector of name strings (in // stdx::Enum<Fruit>) and use the unique id number to index into this // table whenever we need to do the conversion. #include "stdx-ReflectionUtils.h" #include <cassert> #include <iostream> namespace stdx { //---------------------------------------------------------------------- // Static member accessor methods //---------------------------------------------------------------------- template < typename T > std::string& Enum<T>::s_prefix() { static std::string s_prefix = stdx::demangle_type<T>(); return s_prefix; } template < typename T > std::vector<std::string>& Enum<T>::s_names() { static std::vector<std::string> s_names; return s_names; } template < typename T > std::vector<std::pair<const T*,T> >& Enum<T>::s_inits() { static std::vector< std::pair<const T*,T> > s_inits; return s_inits; } template < typename T > int& Enum<T>::s_counter() { static int s_counter = -1; return s_counter; } //---------------------------------------------------------------------- // get_items() //---------------------------------------------------------------------- template < typename T > std::vector<T> Enum<T>::get_items() { std::vector<T> items(s_inits().size()); for ( int idx = 0; idx < static_cast<int>(s_inits().size()); ++idx ) items.at(idx) = s_inits().at(idx).second; return items; } template < typename T > void Enum<T>::set_prefix( const std::string& prefix ) { s_prefix() = prefix; } template < typename T > std::string Enum<T>::get_prefix() { return s_prefix(); } //---------------------------------------------------------------------- // Static access/init methods for enum items //---------------------------------------------------------------------- template < typename T > const T& Enum<T>::static_access( const T& t ) { // See if we have already initialized the given enumeration item // and if so just return a reference to the correct item typedef typename std::vector<std::pair<const T*,T> >::iterator ITR; for ( ITR itr = s_inits().begin(); itr != s_inits().end(); ++itr ) { if ( &t == itr->first ) return itr->second; } // If we haven't already initialized the enumeration item then do so // and return a reference to the newly created item s_inits().push_back( std::make_pair( &t, mk_item(++s_counter()) ) ); return s_inits().back().second; } template < typename T > const T& Enum<T>::static_init( const T& t, const std::string& name ) { // Make sure the item is already initialized const T& item = static_access(t); // Add the name to the static names vector if ( item.m_id+1 > static_cast<int>(s_names().size()) ) s_names().resize(item.m_id+1); s_names().at(item.m_id) = name; return item; } //---------------------------------------------------------------------- // Constructors & Destructors //---------------------------------------------------------------------- template < typename T > Enum<T>::Enum() : m_id(-1) { } //---------------------------------------------------------------------- // Make enumeration item from id //---------------------------------------------------------------------- template < typename T > T Enum<T>::mk_item( int id ) { T item; item.m_id = id; return item; } //---------------------------------------------------------------------- // operator << //---------------------------------------------------------------------- template < typename T > std::ostream& operator<<( std::ostream& os, const Enum<T>& rhs ) { // Currently we always output the short form (ie no prefix). // Eventually we should add support to choose whether or not to // include the prefix in the output. if ( rhs.m_id == -1 ) os << "UNDEFINED"; else os << Enum<T>::s_names().at(rhs.m_id); return os; } //---------------------------------------------------------------------- // operator >> //---------------------------------------------------------------------- template < typename T > std::istream& operator>>( std::istream& is, Enum<T>& rhs ) { std::string name; is >> name; // See if the name has the correct prefix and if so strip it off std::string prefix = Enum<T>::s_prefix()+"::"; if ( ( name.length() > prefix.length() ) && ( name.substr(0,prefix.length()) == prefix ) ) { name = name.substr( prefix.length() ); } // Find the name in the names vector and extract corresponding item std::vector<std::string>& names = Enum<T>::s_names(); for ( int idx = 0; idx < static_cast<int>(names.size()); idx++ ) { if ( name == names[idx] ) { rhs = Enum<T>::mk_item(idx); return is; } } // If we couldn't find the name then signal an error is.clear( std::ios_base::badbit ); return is; } //---------------------------------------------------------------------- // operator == //---------------------------------------------------------------------- template < typename T > inline bool operator==( const Enum<T>& lhs, const Enum<T>& rhs ) { return ( lhs.get_id() == rhs.get_id() ); } //---------------------------------------------------------------------- // operator != //---------------------------------------------------------------------- template < typename T > inline bool operator!=( const Enum<T>& lhs, const Enum<T>& rhs ) { return ( lhs.get_id() != rhs.get_id() ); } } //------------------------------------------------------------------------ // STDX_ENUM_ITEM //------------------------------------------------------------------------ #define STDX_ENUM_ITEM_( enum_, item_ ) \ const enum_ enum_::item_ \ = enum_::static_init( enum_::item_, #item_ ); \
36.430189
74
0.553967
cornell-brg
a794bcf13250204383df4cb226dcf0ea1d027586
26,790
cpp
C++
src/token.cpp
tnash9/chief
d633be42b6531890f5e810e0d1af06d70f106830
[ "MIT" ]
null
null
null
src/token.cpp
tnash9/chief
d633be42b6531890f5e810e0d1af06d70f106830
[ "MIT" ]
null
null
null
src/token.cpp
tnash9/chief
d633be42b6531890f5e810e0d1af06d70f106830
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <iostream> #include <cctype> #include <fstream> #include <list> #include "main.h" #include "arch.h" #include "diagnostics.h" #include "reference.h" #include "operation.h" // --------------------------------------------------------------------------------------------------------------------- // TODO: // 1. Match boolean tokens in any case (i.e. TRUE, FaLsE) void SkipWhiteSpace(const std::string& line, size_t& position) { for(; position < line.size() && line.at(position) == ' '; position++); } bool IsInteger(const std::string& tokenString) { for(size_t i=0; i<tokenString.size(); i++) { if(!std::isdigit(tokenString.at(i))) return false; } return true; } bool IsDecimal(const std::string& tokenString) { bool foundDecimalPointAlready = false; for(size_t i=0; i<tokenString.size(); i++) { if(!std::isdigit(tokenString.at(i))) { if(tokenString.at(i) == '.') { if(foundDecimalPointAlready) return false; foundDecimalPointAlready = true; } else { return false; } } } return true; } bool IsString(const std::string& tokenString) { return tokenString.at(0) == '"' && tokenString.at(tokenString.size()-1) == '"'; } std::string ToLowerCase(const std::string& str) { std::string lowerCaseStr = ""; for(size_t i=0; i<str.size(); i++) { lowerCaseStr += std::tolower(str.at(i)); } return lowerCaseStr; } bool IsBoolean(const std::string& tokenString) { return ToLowerCase(tokenString) == "true" || ToLowerCase(tokenString) == "false"; } bool IsReference(const std::string& tokenString) { return (tokenString.at(0) >= 65 && tokenString.at(0) <= 90); } TokenType TypeOfTokenString(const std::string& tokenString) { if(IsInteger(tokenString)) { return TokenType::Integer; } else if(IsDecimal(tokenString)) { return TokenType::Decimal; } else if(IsString(tokenString)) { return TokenType::String; } else if(IsBoolean(tokenString)) { return TokenType::Boolean; } else if(IsReference(tokenString)) { return TokenType::Reference; } else { return TokenType::Simple; } } const String StringStartChars = "\"'"; const char DecimalPoint = '.'; const String SingletonChars = "!@#$%^*()-+=[]{}\\:;<>,./?~`&|"; const String DoubledChars = "&&||==!="; bool IsSingleTonChar(char c) { for(size_t i=0; i<SingletonChars.size(); i++) if(c == SingletonChars.at(i)) return true; return false; } Token* GetSingletonCharToken(const String& line, size_t& position, int tokenNumber) { String tokenString = ""; tokenString += line.at(position++); return new Token { TokenType::Simple, tokenString, tokenNumber }; } bool IsDoubleCharToken(size_t& position, const String& line) { if(position + 1 >= line.size()) return false; for(size_t i=0; i<DoubledChars.size(); i+=2) { if(line.at(position) == DoubledChars.at(i) && line.at(position+1) == DoubledChars.at(i+1)) return true; } return false; } Token* GetDoubleCharToken(const String& line, size_t& position, int tokenNumber) { String tokenString = ""; tokenString += line.at(position); tokenString += line.at(position+1); position += 2; return new Token { TokenType::Simple, tokenString, tokenNumber }; } bool IsStringStartChar(char c) { return c == '"'; } Token* GetStringToken(const String& line, size_t& position, int tokenNumber) { String tokenString; while(++position < line.size() && line.at(position) != '"') { tokenString += line.at(position); } position++; // get rid of end quote return new Token { TokenType::String, tokenString, tokenNumber }; } bool IsNumericChar(char c) { return 48 <= static_cast<int>(c) && 57 >= static_cast<int>(c); } bool IsActuallyDecimalPoint(const size_t& position, const String& line) { return (position > 0 && IsNumericChar(line.at(position-1))) && (position + 1 < line.size() && IsNumericChar(line.at(position+1))); } Token* GetToken(const std::string& line, size_t& position, int tokenNumber) { SkipWhiteSpace(line, position); if(position >= line.size()) return nullptr; // special case for string if(IsStringStartChar(line.at(position))) { return GetStringToken(line, position, tokenNumber); } else if(IsDoubleCharToken(position, line)) { return GetDoubleCharToken(line, position, tokenNumber); } else if(IsSingleTonChar(line.at(position))) { return GetSingletonCharToken(line, position, tokenNumber); } Token* token; std::string tokenString = ""; for(; position < line.size() && line.at(position) != ' '; position++) { if(line.at(position) != DecimalPoint && IsSingleTonChar(line.at(position))) break; else if(line.at(position) == DecimalPoint) { if(!IsActuallyDecimalPoint(position, line)) break; } tokenString += line.at(position); } if(tokenString == "") return nullptr; token = new Token { TypeOfTokenString(tokenString), tokenString, tokenNumber }; return token; } TokenList LexLine(const std::string& line) { TokenList tokens; size_t linePosition = 0; int tokenNumber = 0; while(linePosition < line.size()) { Token* t = GetToken(line, linePosition, tokenNumber); if(t == nullptr) continue; tokens.push_back(t); tokenNumber++; } return tokens; } std::string GetStringTokenType(TokenType type) { std::string typeString; switch(type) { case TokenType::Boolean: typeString = "boolean "; break; case TokenType::Decimal: typeString = "decimal "; break; case TokenType::Integer: typeString = "integer "; break; case TokenType::Reference: typeString = "reference"; break; case TokenType::Simple: typeString = "simple "; break; case TokenType::String: typeString = "string "; break; default: typeString = "unknown "; break; } return typeString; } bool SameLetterOrChar(char c1, char c2) { return std::toupper(c1) == std::toupper(c2); } bool StringCaseInsensitiveEquals(const std::string& str1, const std::string& str2) { if(str1.size() != str2.size()) return false; for(size_t pos=0; pos<str1.size(); pos++) { if(!SameLetterOrChar(str1.at(pos), str2.at(pos))) return false; } return true; } Token* FindToken(const TokenList& tokens, std::string str) { for(Token* t: tokens) { if(StringCaseInsensitiveEquals(str, t->Content)) return t; } return nullptr; } void RenumberTokenList(TokenList& tokens) { for(int i=0; static_cast<size_t>(i)<tokens.size(); i++) { tokens.at(i)->Position = i; } } TokenList RightOfToken(const TokenList& tokens, Token* pivotToken) { TokenList rightList; rightList.reserve(tokens.size()); for(int i=pivotToken->Position + 1; static_cast<size_t>(i)<tokens.size(); i++) rightList.push_back(tokens.at(i)); RenumberTokenList(rightList); return rightList; } TokenList LeftOfToken(const TokenList& tokens, Token* pivotToken) { TokenList leftList; leftList.reserve(tokens.size()); for(int i=0; i<pivotToken->Position; i++) leftList.push_back(tokens.at(i)); RenumberTokenList(leftList); return leftList; } bool TokenMatchesType(Token* token, std::vector<TokenType> types) { for(TokenType type: types) { if(type == token->Type) return true; } return false; } bool TokenMatchesType(Token* token, TokenType type) { std::vector<TokenType> types = { type }; return TokenMatchesType(token, types); } bool TokenMatchesContent(Token* token, std::vector<String> contents) { for(String content: contents) { if(content == token->Content) return true; } return false; } bool TokenMatchesContent(Token* token, String content) { std::vector<String> contents = { content }; return TokenMatchesContent(token, contents); } Token* NextTokenMatching(const TokenList& tokens, std::vector<TokenType> types, int& pos) { for(; static_cast<size_t>(pos)<tokens.size(); pos++) { if(TokenMatchesType(tokens.at(pos), types)) return tokens.at(pos++); } pos = -1; return nullptr; } Token* NextTokenMatching(const TokenList& tokens, TokenType type, int& pos) { std::vector<TokenType> types = { type }; return NextTokenMatching(tokens, types, pos); } Token* NextTokenMatching(const TokenList& tokens, TokenType type) { int i = 0; return NextTokenMatching(tokens, type, i); } Token* NextTokenMatching(const TokenList& tokens, std::vector<TokenType> types) { int i = 0; return NextTokenMatching(tokens, types, i); } Token* NextTokenMatching(const TokenList& tokens, std::vector<String> contents, int& pos) { for(; static_cast<size_t>(pos)<tokens.size(); pos++) { if(TokenMatchesContent(tokens.at(pos), contents)) return tokens.at(pos++); } pos = -1; return nullptr; } Token* NextTokenMatching(const TokenList& tokens, std::vector<String> contents) { int pos = 0; return NextTokenMatching(tokens, contents, pos); } Token* NextTokenMatching(const TokenList& tokens, String content, int& pos) { std::vector<String> contents = { content }; return NextTokenMatching(tokens, contents, pos); } Token* NextTokenMatching(const TokenList& tokens, String content) { int pos = 0; return NextTokenMatching(tokens, content, pos); } bool TokenListContainsContent(const TokenList& tokenList, std::vector<String> contents) { for(Token* t: tokenList) { if(TokenMatchesContent(t, contents)) return true; } return false; } // --------------------------------------------------------------------------------------------------------------------- // Formal grammar parser parser (experimental) struct CFGRule { String Name; String Symbol; int Precedence; OperationType OpType; std::vector<String> IntoPattern; String FromProduction; String ParseOperation; }; struct PrecedenceClass { std::vector<String> Members; }; OperationType StringNameToOperationType(String Name) { if(Name=="Add") return OperationType::Add; else if(Name=="Subtract") return OperationType::Subtract; else if(Name=="Multiply") return OperationType::Multiply; else if(Name=="Divide") return OperationType::Divide; else if(Name=="And") return OperationType::And; else if(Name=="Or") return OperationType::Or; else if(Name=="Not") return OperationType::Not; else if(Name=="IsEqual") return OperationType::IsEqual; else if(Name=="IsGreaterThan") return OperationType::IsGreaterThan; else if(Name=="IsLessThan") return OperationType::IsLessThan; else if(Name=="Evaluate") return OperationType::Evaluate; else if(Name=="If") return OperationType::If; else if(Name=="DefineMethod") return OperationType::DefineMethod; else if(Name=="Assign") return OperationType::Assign; else if(Name=="Define") return OperationType::Define; else if(Name=="Tuple") return OperationType::Tuple; else if(Name=="Print") return OperationType::Print; else if(Name=="Return") return OperationType::Return; else return OperationType::Ref; } std::vector<CFGRule*> Grammar; std::list<PrecedenceClass> PrecedenceRules; std::vector<String> ProductionVariables = { "Ref" }; void AddProductionVariable(String newProductionVar) { for(auto productionVar: ProductionVariables) { if(productionVar == newProductionVar) return; } ProductionVariables.push_back(newProductionVar); } // TODO: move to diagnostics void PrintPrecedenceRules() { std::cout << "PRINTING\n"; for(auto rule: PrecedenceRules) { for(auto s: rule.Members) { std::cout << s << " "; } std::cout << "\n"; } } int PrecedenceOf(String opSymbol) { int i=1; for(auto rule: PrecedenceRules) { for(auto str: rule.Members) { if(str == opSymbol) { return i; } } i++; } LogIt(Sev3_Critical, "PrecedenceOf", Msg("unknown operation symbol %s", opSymbol)); return 0; } int PrecedenceOf(Token* lookaheadToken) { if(lookaheadToken == nullptr) return 0; return PrecedenceOf(lookaheadToken->Content); } void AssignRulePrecedences() { for(auto rule: Grammar) { rule->Precedence = PrecedenceOf(rule->Symbol); } } void AddPrecedenceClass(TokenList& tokens) { PrecedenceClass precdence; for(Token* t: tokens) { precdence.Members.push_back(t->Content); } PrecedenceRules.push_front(precdence); } void AddGrammarRule(TokenList& tokens, CFGRule** rule) { if(tokens.at(0)->Content == "@") { *rule = new CFGRule; (*rule)->Name = tokens.at(1)->Content; (*rule)->Symbol = tokens.at(2)->Content; (*rule)->ParseOperation = tokens.at(3)->Content; (*rule)->OpType = StringNameToOperationType((*rule)->Name); } else if(tokens.at(0)->Type == TokenType::Reference) { (*rule)->FromProduction = tokens.at(0)->Content; AddProductionVariable((*rule)->FromProduction); for(size_t i=3; i<tokens.size(); i++) { (*rule)->IntoPattern.push_back(tokens.at(i)->Content); } Grammar.push_back((*rule)); } } void CompileGrammar() { std::fstream file; file.open(".\\assets\\grammar.txt", std::ios::in); CFGRule* rule = nullptr; // state: +1 upon every occurance of '###' // 0: skip all lines // 1: read grammar rules // 2: read precedences // other: skip all lines int state = 0; String line; while(std::getline(file, line)) { TokenList tokens = LexLine(line); if(tokens.empty()) continue; if(tokens.at(0)->Content == "#") { state++; continue; } switch(state) { case 1: AddGrammarRule(tokens, &rule); continue; case 2: AddPrecedenceClass(tokens); break; default: continue; } } AssignRulePrecedences(); } // --------------------------------------------------------------------------------------------------------------------- // Formal grammar parser (experimental) struct ParseToken { String TokenType; Operation* Value; ParseToken* Next = nullptr; ParseToken* Prev = nullptr; }; /// add a [newToken] to an existing [listTail] void AddToList(ParseToken** listHead, ParseToken** listTail, ParseToken* newToken) { if(*listHead == nullptr) { *listHead = newToken; *listTail = newToken; return; } else { (*listTail)->Next = newToken; newToken->Prev = *listTail; *listTail = newToken; } } ParseToken* ParseTokenConstructor(String tokenType) { ParseToken* gt = new ParseToken; gt->Next = nullptr; gt->Prev = nullptr; gt->TokenType = tokenType; gt->Value = nullptr; return gt; } /// constructs a operation of type OperationType::Ref with either a primitive value or a named Reference stub Operation* RefOperation(Token* refToken) { Reference* ref = ReferenceForPrimitive(refToken, c_operationReferenceName); if(ref == nullptr) { ref = ReferenceStub(refToken->Content); } Operation* op = OperationConstructor(OperationType::Ref, ref); return op; } CFGRule* MatchGrammarPatterns(ParseToken* listHead, ParseToken* listTail) { for(CFGRule* rule: Grammar) { bool isMatchForRule = true; ParseToken* listItr = listTail; for(int i=rule->IntoPattern.size()-1; i>=0; i--, listItr = listItr->Prev) { // false if rule is longer than the list if(listItr == nullptr) { isMatchForRule = false; break; } if(listItr->TokenType != rule->IntoPattern.at(i)) { isMatchForRule = false; break; } } if(isMatchForRule) return rule; } return nullptr; } void DestroyList(ParseToken* listHead) { ParseToken* prevToken; while(listHead != nullptr) { prevToken = listHead; listHead = listHead->Next; delete prevToken; } } bool ParseTokenTypeMatches(String TokenType, std::vector<String> matchTypes) { for(auto str: matchTypes) { if(TokenType == str) return true; } return false; } /// pushes listTail back to before the [rule] pattern and sets listSnipHead to be the head (start) of [rule] in the ParseStack void PointToHeadOfRuleAndSnip(ParseToken** listHead, ParseToken** listTail, ParseToken** listSnipHead, CFGRule* rule) { int backtrackAmount = rule->IntoPattern.size()-1; for(int i=0; i<backtrackAmount; i++, *listSnipHead = (*listSnipHead)->Prev); *listTail = (*listSnipHead)->Prev; if(*listTail != nullptr) { (*listTail)->Next = nullptr; } else { // if the remaining list is empty *listHead = nullptr; } } /// assumes that the list matches [rule] and removes the rule OperationsList GetOperandsAndRemoveRule(ParseToken** listHead, ParseToken** listTail, CFGRule* rule) { OperationsList operands = {}; ParseToken* listSnipHead = *listTail; PointToHeadOfRuleAndSnip(listHead, listTail, &listSnipHead, rule); // gets the operands for(ParseToken* listSnipItr = listSnipHead; listSnipItr != nullptr; listSnipItr = listSnipItr->Next) { if(ParseTokenTypeMatches(listSnipItr->TokenType, ProductionVariables)) { operands.push_back(listSnipItr->Value); } } DestroyList(listSnipHead); return operands; } /// collapse a rule by adding each component as the operand of a new operation Operation* CollapseByReduce(CFGRule* rule, OperationsList& components) { return OperationConstructor(rule->OpType, components); } /// collapse a rule by merging all components into the first component's operand list Operation* CollapseByMerge(CFGRule* rule, OperationsList& components) { OperationsList& oplist = components.at(0)->Operands; for(size_t i=1; i< components.size(); i++) { oplist.push_back(components.at(i)); } return components.at(0); // for(auto op: components) // { // // direcly merge ::Ref type operations into the new operandsList // if(op->Type == OperationType::Ref) // mergedOperands.push_back(op); // // for all other operation types, port the operands directly into the new operandsList // else // { // for(auto opOperand: op->Operands) // mergedOperands.push_back(opOperand); // } // } // return OperationConstructor(rule->OpType, mergedOperands); } /// collapse a rule corresponding to defining a method Operation* CollapseAsDefineMethod(CFGRule* rule, OperationsList& components) { LogItDebug("Custom type", "CollapseListByRule"); auto methodName = components.at(0)->Value->Name; Method* m = MethodConstructor(CurrentScope()); EnterScope(m->Parameters); { if(components.size() > 1) { if(components.at(1)->Type == OperationType::Tuple) { for(auto op: components.at(1)->Operands) { NullReference(op->Value->Name); } } else { NullReference(components.at(1)->Value->Name); } // // if the operand is already a return operation // if(components.at(1)->Type == OperationType::Ref) // NullReference(components.at(1)->Value->Name); // // if the operand is a list of parameters // else // for(size_t i=0; i<components.at(1)->Operands.size(); i++) // NullReference(components.at(1)->Operands.at(i)->Value->Name); } } ExitScope(); Reference* ref = ReferenceFor(methodName, m); return OperationConstructor(OperationType::DefineMethod, { OperationConstructor(OperationType::Ref, ref) } ); } Operation* CollapseRuleInternal(CFGRule* rule, OperationsList& components) { if(rule->ParseOperation == "Reduce") { return CollapseByReduce(rule, components); } else if(rule->ParseOperation == "Retain") { return components.at(0); } else if(rule->ParseOperation == "Merge") { return CollapseByMerge(rule, components); } else if(rule->ParseOperation == "Custom") { return CollapseAsDefineMethod(rule, components); } else { LogIt(LogSeverityType::Sev1_Notify, "CollapseRule", "unknown collapsing procedure"); return nullptr; } } /// reverses a rule in the ParseStack void CollapseListByRule(ParseToken** listHead, ParseToken** listTail, CFGRule* rule) { OperationsList operands = GetOperandsAndRemoveRule(listHead, listTail, rule); Operation* op = CollapseRuleInternal(rule, operands); ParseToken* t = ParseTokenConstructor(rule->FromProduction); t->Value = op; AddToList(listHead, listTail, t); } /// if [op] is assigning to an undefined reference, define it void DefineNewReferenceIfNecessary(Operation* op) { if(op->Type == OperationType::Assign) { Reference* stub = op->Operands.at(0)->Value; auto assignToRef = ReferenceFor(stub->Name); // creates define operation if(assignToRef == nullptr) { Operation* newRefReturn = OperationConstructor(OperationType::Ref, NullReference(stub->Name)); Operation* defRef = OperationConstructor(OperationType::Define, { newRefReturn }); op->Operands[0] = defRef; delete stub; } } } void ResolveRefOperation(Operation* refOp) { Reference* stub = refOp->Value; // verify that Reference is in fact a stub if(IsReferenceStub(stub)) { // get the reference by name which should be defined auto resolvedRef = ReferenceFor(stub->Name); if(resolvedRef == nullptr) { ReportCompileMsg(SystemMessageType::Exception, Msg("cannot resolve reference %s. make sure it has been defined", stub->Name)); resolvedRef = NullReference(stub->Name); } refOp->Value = resolvedRef; } } /// recursively resolves all reference stubs in [op] void ResolveReferences(Operation* op) { // breaks recursion. these types are handled in the parent if(op->Type == OperationType::Ref) return; if(op->Type == OperationType::DefineMethod) return; DefineNewReferenceIfNecessary(op); for(auto operand: op->Operands) { if(operand->Type == OperationType::Ref) { ResolveRefOperation(operand); } else { ResolveReferences(operand); } } } void LogParseStack(ParseToken* listHead) { String Line; for(ParseToken* t = listHead; t != nullptr; t = t->Next) { Line += t->TokenType; Line += " "; } LogItDebug(Line, "LogParseStack"); } /// add a new token for a Ref (object) to the ParseList void AddRefToken(ParseToken** listHead, ParseToken** listTail, Token* token) { ParseToken* t = ParseTokenConstructor("Ref"); t->Value = RefOperation(token); AddToList(listHead, listTail, t); } /// add a new token for a simple keyword/operation to the ParseList void AddSimpleToken(ParseToken** listHead, ParseToken** listTail, Token* token) { ParseToken* t = ParseTokenConstructor(token->Content); AddToList(listHead, listTail, t); } /// if a grammar rule matches, and the lookahead is of less precedence, then reverse the rule and update /// the list. continue doing so until no rules match void TryMatchingGrammarRules(ParseToken** listHead, ParseToken** listTail, Token* lookaheadToken) { CFGRule* match = MatchGrammarPatterns(*listHead, *listTail); while(match != nullptr) { if(match != nullptr){ int currentRulePrecedence = match->Precedence; int lookaheadPrecedence = PrecedenceOf(lookaheadToken); if(currentRulePrecedence >= lookaheadPrecedence) { CollapseListByRule(listHead, listTail, match); match = MatchGrammarPatterns(*listHead, *listTail); } else { break; } } LogParseStack(*listHead); } } Operation* ExpressionParser(TokenList& line) { ParseToken* listHead = nullptr; ParseToken* listTail = nullptr; int pos = 0; while(static_cast<size_t>(pos) < line.size()) { Token* currentToken = line.at(pos); if(TokenMatchesType(line.at(pos), ObjectTokenTypes)) { AddRefToken(&listHead, &listTail, currentToken); } else { AddSimpleToken(&listHead, &listTail, currentToken); } LogParseStack(listHead); Token* lookaheadToken = nullptr; if(static_cast<size_t>(pos+1) < line.size()) lookaheadToken = line.at(pos+1); TryMatchingGrammarRules(&listHead, &listTail, lookaheadToken); pos++; } // if the line could not be parsed if(listHead != listTail) { ReportCompileMsg(SystemMessageType::Exception, "bad format"); } ResolveReferences(listHead->Value); LogItDebug("end reached", "ExpressionParser"); return listHead->Value; }
24.92093
138
0.600261
tnash9
a7965c840339caaf98d370b6ef4abb88fdf7b186
17,925
cpp
C++
Sources/Internal/Render/Image/ImageConvert.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-11-14T10:18:24.000Z
2020-11-14T10:18:24.000Z
Sources/Internal/Render/Image/ImageConvert.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Render/Image/ImageConvert.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-09-05T21:16:17.000Z
2020-09-05T21:16:17.000Z
#include "Render/Image/ImageConvert.h" #include "Render/Image/LibDdsHelper.h" #include "Render/Image/LibPVRHelper.h" #include "Render/Image/Image.h" #include "Functional/Function.h" namespace DAVA { uint32 ChannelFloatToInt(float32 ch) { return static_cast<uint32>(Min(ch, 1.0f) * std::numeric_limits<uint8>::max()); } float32 ChannelIntToFloat(uint32 ch) { return (static_cast<float32>(ch) / std::numeric_limits<uint8>::max()); } namespace ImageConvert { bool Normalize(PixelFormat format, const void* inData, uint32 width, uint32 height, uint32 pitch, void* outData) { if (format == FORMAT_RGBA8888) { ConvertDirect<uint32, uint32, NormalizeRGBA8888> convert; convert(inData, width, height, pitch, outData, width, height, pitch); return true; } Logger::Error("Normalize function not implemented for %s", PixelFormatDescriptor::GetPixelFormatString(format)); return false; } bool ConvertImage(const Image* srcImage, Image* dstImage) { DVASSERT(srcImage); DVASSERT(dstImage); DVASSERT(srcImage->format != dstImage->format); DVASSERT(srcImage->width == dstImage->width); DVASSERT(srcImage->height == dstImage->height); PixelFormat srcFormat = srcImage->format; PixelFormat dstFormat = dstImage->format; Function<bool(const Image*, Image*)> decompressFn = nullptr; if (LibDdsHelper::CanDecompressFrom(srcFormat)) { decompressFn = &LibDdsHelper::DecompressToRGBA; } else if (LibPVRHelper::CanDecompressFrom(srcFormat)) { decompressFn = &LibPVRHelper::DecompressToRGBA; } Function<bool(const Image*, Image*)> compressFn = nullptr; if (LibDdsHelper::CanCompressTo(dstFormat)) { compressFn = &LibDdsHelper::CompressFromRGBA; } else if (LibPVRHelper::CanCompressTo(dstFormat)) { compressFn = &LibPVRHelper::CompressFromRGBA; } if (decompressFn == nullptr && compressFn == nullptr) { return ConvertImageDirect(srcImage, dstImage); } else if (decompressFn != nullptr && compressFn != nullptr) { ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888)); return (decompressFn(srcImage, rgba) && compressFn(rgba, dstImage)); } else if (decompressFn != nullptr) { if (dstFormat == FORMAT_RGBA8888) { return decompressFn(srcImage, dstImage); } else { ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888)); return (decompressFn(srcImage, rgba) && ConvertImageDirect(rgba, dstImage)); } } else { if (srcFormat == FORMAT_RGBA8888) { return compressFn(srcImage, dstImage); } else { ScopedPtr<Image> rgba(Image::Create(srcImage->width, srcImage->height, FORMAT_RGBA8888)); return (ConvertImageDirect(srcImage, rgba) && compressFn(rgba, dstImage)); } } } bool ConvertImageDirect(const Image* srcImage, Image* dstImage) { return ConvertImageDirect(srcImage->format, dstImage->format, srcImage->data, srcImage->width, srcImage->height, ImageUtils::GetPitchInBytes(srcImage->width, srcImage->format), dstImage->data, dstImage->width, dstImage->height, ImageUtils::GetPitchInBytes(dstImage->width, dstImage->format)); } bool ConvertImageDirect(PixelFormat inFormat, PixelFormat outFormat, const void* inData, uint32 inWidth, uint32 inHeight, uint32 inPitch, void* outData, uint32 outWidth, uint32 outHeight, uint32 outPitch) { if (inFormat == FORMAT_RGBA5551 && outFormat == FORMAT_RGBA8888) { ConvertDirect<uint16, uint32, ConvertRGBA5551toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA4444 && outFormat == FORMAT_RGBA8888) { ConvertDirect<uint16, uint32, ConvertRGBA4444toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGB888 && outFormat == FORMAT_RGBA8888) { ConvertDirect<RGB888, uint32, ConvertRGB888toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGB565 && outFormat == FORMAT_RGBA8888) { ConvertDirect<uint16, uint32, ConvertRGB565toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_A8 && outFormat == FORMAT_RGBA8888) { ConvertDirect<uint8, uint32, ConvertA8toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_A16 && outFormat == FORMAT_RGBA8888) { ConvertDirect<uint16, uint32, ConvertA16toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_BGR888 && outFormat == FORMAT_RGB888) { ConvertDirect<BGR888, RGB888, ConvertBGR888toRGB888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_BGR888 && outFormat == FORMAT_RGBA8888) { ConvertDirect<BGR888, uint32, ConvertBGR888toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_BGRA8888 && outFormat == FORMAT_RGBA8888) { ConvertDirect<BGRA8888, RGBA8888, ConvertBGRA8888toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGB888) { ConvertDirect<uint32, RGB888, ConvertRGBA8888toRGB888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA16161616 && outFormat == FORMAT_RGBA8888) { ConvertDirect<RGBA16161616, uint32, ConvertRGBA16161616toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA32323232 && outFormat == FORMAT_RGBA8888) { ConvertDirect<RGBA32323232, uint32, ConvertRGBA32323232toRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA16F && outFormat == FORMAT_RGBA8888) { ConvertDirect<RGBA16F, uint32, ConvertRGBA16FtoRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA32F && outFormat == FORMAT_RGBA8888) { ConvertDirect<RGBA32F, uint32, ConvertRGBA32FtoRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGBA16F) { ConvertDirect<uint32, RGBA16F, ConvertRGBA8888toRGBA16F> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else if (inFormat == FORMAT_RGBA8888 && outFormat == FORMAT_RGBA32F) { ConvertDirect<uint32, RGBA32F, ConvertRGBA8888toRGBA32F> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); return true; } else { Logger::FrameworkDebug("Unsupported image conversion from format %d to %d", inFormat, outFormat); return false; } } bool CanConvertDirect(PixelFormat inFormat, PixelFormat outFormat) { return ConvertImageDirect(inFormat, outFormat, nullptr, 0, 0, 0, nullptr, 0, 0, 0); } bool CanConvertFromTo(PixelFormat inFormat, PixelFormat outFormat) { bool inCompressed = LibDdsHelper::CanDecompressFrom(inFormat) || LibPVRHelper::CanDecompressFrom(inFormat); bool outCompressed = LibDdsHelper::CanCompressTo(outFormat) || LibPVRHelper::CanCompressTo(outFormat); if (!inCompressed && !outCompressed) { return CanConvertDirect(inFormat, outFormat); } else if (inCompressed && outCompressed) { return true; } else if (inCompressed) { return (outFormat == FORMAT_RGBA8888 ? true : CanConvertDirect(FORMAT_RGBA8888, outFormat)); } else { return (inFormat == FORMAT_RGBA8888 ? true : CanConvertDirect(outFormat, FORMAT_RGBA8888)); } } void SwapRedBlueChannels(const Image* srcImage, const Image* dstImage /* = nullptr*/) { DVASSERT(srcImage); if (dstImage) { DVASSERT(PixelFormatDescriptor::GetPixelFormatSizeInBits(dstImage->format) == PixelFormatDescriptor::GetPixelFormatSizeInBits(srcImage->format)); DVASSERT(srcImage->width == dstImage->width); DVASSERT(srcImage->height == dstImage->height); } SwapRedBlueChannels(srcImage->format, srcImage->data, srcImage->width, srcImage->height, ImageUtils::GetPitchInBytes(srcImage->width, srcImage->format), dstImage ? dstImage->data : nullptr); } void SwapRedBlueChannels(PixelFormat format, void* srcData, uint32 width, uint32 height, uint32 pitch, void* dstData /* = nullptr*/) { if (!dstData) dstData = srcData; switch (format) { case FORMAT_RGB888: { ConvertDirect<BGR888, RGB888, ConvertBGR888toRGB888> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_RGBA8888: { ConvertDirect<BGRA8888, RGBA8888, ConvertBGRA8888toRGBA8888> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_RGBA4444: { ConvertDirect<uint16, uint16, ConvertBGRA4444toRGBA4444> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_RGB565: { ConvertDirect<uint16, uint16, ConvertBGR565toRGB565> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_RGBA16161616: { ConvertDirect<RGBA16161616, RGBA16161616, ConvertBGRA16161616toRGBA16161616> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_RGBA32323232: { ConvertDirect<RGBA32323232, RGBA32323232, ConvertBGRA32323232toRGBA32323232> swap; swap(srcData, width, height, pitch, dstData); return; } case FORMAT_A8: case FORMAT_A16: { // do nothing for grayscale images return; } default: { Logger::Error("Image color exchanging is not supported for format %d", format); return; } } } bool DownscaleTwiceBillinear(PixelFormat inFormat, PixelFormat outFormat, const void* inData, uint32 inWidth, uint32 inHeight, uint32 inPitch, void* outData, uint32 outWidth, uint32 outHeight, uint32 outPitch, bool normalize) { if ((inFormat == FORMAT_RGBA8888) && (outFormat == FORMAT_RGBA8888)) { if (normalize) { ConvertDownscaleTwiceBillinear<uint32, uint32, uint32, UnpackRGBA8888, PackNormalizedRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else { ConvertDownscaleTwiceBillinear<uint32, uint32, uint32, UnpackRGBA8888, PackRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } } else if ((inFormat == FORMAT_RGBA8888) && (outFormat == FORMAT_RGBA4444)) { ConvertDownscaleTwiceBillinear<uint32, uint16, uint32, UnpackRGBA8888, PackRGBA4444> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA4444) && (outFormat == FORMAT_RGBA8888)) { ConvertDownscaleTwiceBillinear<uint16, uint32, uint32, UnpackRGBA4444, PackRGBA8888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_A8) && (outFormat == FORMAT_A8)) { ConvertDownscaleTwiceBillinear<uint8, uint8, uint32, UnpackA8, PackA8> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGB888) && (outFormat == FORMAT_RGB888)) { ConvertDownscaleTwiceBillinear<RGB888, RGB888, uint32, UnpackRGB888, PackRGB888> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA5551) && (outFormat == FORMAT_RGBA5551)) { ConvertDownscaleTwiceBillinear<uint16, uint16, uint32, UnpackRGBA5551, PackRGBA5551> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA16161616) && (outFormat == FORMAT_RGBA16161616)) { ConvertDownscaleTwiceBillinear<RGBA16161616, RGBA16161616, uint32, UnpackRGBA16161616, PackRGBA16161616> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA32323232) && (outFormat == FORMAT_RGBA32323232)) { ConvertDownscaleTwiceBillinear<RGBA32323232, RGBA32323232, uint64, UnpackRGBA32323232, PackRGBA32323232> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA16F) && (outFormat == FORMAT_RGBA16F)) { ConvertDownscaleTwiceBillinear<RGBA16F, RGBA16F, float32, UnpackRGBA16F, PackRGBA16F> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else if ((inFormat == FORMAT_RGBA32F) && (outFormat == FORMAT_RGBA32F)) { ConvertDownscaleTwiceBillinear<RGBA32F, RGBA32F, float32, UnpackRGBA32F, PackRGBA32F> convert; convert(inData, inWidth, inHeight, inPitch, outData, outWidth, outHeight, outPitch); } else { Logger::Error("Downscale from %s to %s is not implemented", PixelFormatDescriptor::GetPixelFormatString(inFormat), PixelFormatDescriptor::GetPixelFormatString(outFormat)); return false; } return true; } Image* DownscaleTwiceBillinear(const Image* source, bool isNormalMap /*= false*/) { DVASSERT(source != nullptr); PixelFormat pixelFormat = source->GetPixelFormat(); uint32 sWidth = source->GetWidth(); uint32 sHeigth = source->GetHeight(); uint32 dWidth = sWidth >> 1; uint32 dHeigth = sHeigth >> 1; Image* destination = Image::Create(dWidth, dHeigth, pixelFormat); if (destination != nullptr) { uint32 pitchMultiplier = PixelFormatDescriptor::GetPixelFormatSizeInBits(pixelFormat); bool downscaled = DownscaleTwiceBillinear(pixelFormat, pixelFormat, source->GetData(), sWidth, sHeigth, sWidth * pitchMultiplier / 8, destination->GetData(), dWidth, dHeigth, dWidth * pitchMultiplier / 8, isNormalMap); if (downscaled == false) { SafeRelease(destination); } } return destination; } void ResizeRGBA8Billinear(const uint32* inPixels, uint32 w, uint32 h, uint32* outPixels, uint32 w2, uint32 h2) { int32 a, b, c, d, x, y, index; float32 x_ratio = (static_cast<float32>(w - 1)) / w2; float32 y_ratio = (static_cast<float32>(h - 1)) / h2; float32 x_diff, y_diff, blue, red, green, alpha; uint32 offset = 0; for (uint32 i = 0; i < h2; i++) { for (uint32 j = 0; j < w2; j++) { x = static_cast<int32>(x_ratio * j); y = static_cast<int32>(y_ratio * i); x_diff = (x_ratio * j) - x; y_diff = (y_ratio * i) - y; index = (y * w + x); a = inPixels[index]; b = inPixels[index + 1]; c = inPixels[index + w]; d = inPixels[index + w + 1]; blue = (a & 0xff) * (1 - x_diff) * (1 - y_diff) + (b & 0xff) * (x_diff) * (1 - y_diff) + (c & 0xff) * (y_diff) * (1 - x_diff) + (d & 0xff) * (x_diff * y_diff); green = ((a >> 8) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 8) & 0xff) * (x_diff) * (1 - y_diff) + ((c >> 8) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 8) & 0xff) * (x_diff * y_diff); red = ((a >> 16) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 16) & 0xff) * (x_diff) * (1 - y_diff) + ((c >> 16) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 16) & 0xff) * (x_diff * y_diff); alpha = ((a >> 24) & 0xff) * (1 - x_diff) * (1 - y_diff) + ((b >> 24) & 0xff) * (x_diff) * (1 - y_diff) + ((c >> 24) & 0xff) * (y_diff) * (1 - x_diff) + ((d >> 24) & 0xff) * (x_diff * y_diff); outPixels[offset++] = (((static_cast<uint32>(alpha)) << 24) & 0xff000000) | (((static_cast<uint32>(red)) << 16) & 0xff0000) | (((static_cast<uint32>(green)) << 8) & 0xff00) | (static_cast<uint32>(blue)); } } } } // namespace ImageConvert } // namespace DAVA
39.137555
226
0.64781
Serviak
a7968cd873c8fa79160cff2125ba098cb90144dc
1,939
cxx
C++
osf-to-esf/dbnl/algo/dbnl_solve_trigonometric_equation.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
1
2022-01-01T20:43:47.000Z
2022-01-01T20:43:47.000Z
osf-to-esf/dbnl/dbnl_solve_trigonometric_equation.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
null
null
null
osf-to-esf/dbnl/dbnl_solve_trigonometric_equation.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
null
null
null
// This is basic/dbnl/dbnl_solve_trigonometric_equation.cxx //: // \file #include "dbnl_solve_trigonometric_equation.h" #include <vnl/vnl_math.h> #include <vcl_cmath.h> const double dbnl_solve_trigonometry_eps = 1e-12; //: Solve trigonometry equation a sin(x) + b cos(x) + c = 0 // returned roots have format: root(cos(x), sin(x)) void dbnl_solve_1st_order_trig_equation(double a, double b, double c, vcl_vector<double >& sin_x, vcl_vector<double >& cos_x) { // sanitize storage variables cos_x.clear(); sin_x.clear(); // DEGENERATE CASES // no root because a^2 + b^2 = 0 and c != 0 if (a==0 && b==0 && c != 0) return; // infinitely many roots. Return 3 roots if (a==0 && b==0 && c == 0) { // root1 cos_x.push_back(1); sin_x.push_back(0); // root2 cos_x.push_back(0); sin_x.push_back(1); // root3 cos_x.push_back(-1); sin_x.push_back(0); return; } // no root because c > a^2 + b^2 double sin_t = -c / vcl_sqrt(a*a+b*b); if (vnl_math_abs(sin_t) > 1) { return; } double cos_alpha = a/vcl_sqrt(a*a+b*b); double sin_alpha = b/vcl_sqrt(a*a+b*b); // one root if (vnl_math_abs(sin_t) == 1) { cos_x.push_back(sin_t * sin_alpha); sin_x.push_back(sin_t * cos_alpha); return; } // REGULAR CASES - 2 roots double cos_x_plus_alpha[2]; double sin_x_plus_alpha[2]; cos_x_plus_alpha[0] = vcl_sqrt(1-sin_t*sin_t); sin_x_plus_alpha[0] = sin_t; cos_x_plus_alpha[1] = -vcl_sqrt(1-sin_t*sin_t); sin_x_plus_alpha[1] = sin_t; for (int i=0; i<2; ++i) { // dot and cross product of alpha and x_plus_alpha double dot = cos_alpha * cos_x_plus_alpha[i] + sin_alpha * sin_x_plus_alpha[i]; double cross = cos_alpha * sin_x_plus_alpha[i] - sin_alpha * cos_x_plus_alpha[i]; cos_x.push_back(dot); sin_x.push_back(cross); } return; }
22.287356
85
0.620423
wenhanshi
a797c912d75622ed895e3000d010ba3b7de561dc
3,607
cpp
C++
src/libraries/core/db/IOstreams/Sstreams/state.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/IOstreams/Sstreams/state.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/IOstreams/Sstreams/state.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2015 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Description Implementation of parser: test the state of either an istream or an ostream. Report an error if there is one. \*---------------------------------------------------------------------------*/ #include "error.hpp" #include "token.hpp" #include "int.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Print state of ostream. void CML::state(ostream& to, const string& s) { state_value osState = state_value(to.rdstate()); switch (osState) { case _good: // Do not anything 'unusual'. break; case _eof: Info << "Output stream: premature end of stream", s << endl; break; case _fail: SeriousErrorInFunction << "Output stream failure (bad format?)", s << endl; break; case (_fail + _eof) : SeriousErrorInFunction << "Output stream failure and end of stream", s << endl; break; case _bad: SeriousErrorInFunction << "Serious output stream failure", s << endl; break; default: SeriousErrorInFunction << "Output stream failure of unknown type", s << endl << "Stream state value = ", osState << endl; break; } return; } // Print state of istream. void CML::state(istream& from, const string& s) { state_value isState = state_value(from.rdstate()); switch (isState) { case _good: // Do not anything 'unusual'. break; case _eof: Info << "Input stream: premature end of stream", s << endl; Info<< "If all else well, possibly a quote mark missing" << endl; break; case _fail: SeriousErrorInFunction << "Input stream failure (bad format?)", s << endl; Info<< "If all else well, possibly a quote mark missing" << endl; break; case (_fail + _eof) : SeriousErrorInFunction << "Input stream failure and end of stream", s << endl; Info<< "If all else well, possibly a quote mark missing" << endl; break; case _bad: SeriousErrorInFunction << "Serious input stream failure", s << endl; break; default: SeriousErrorInFunction << "Input stream failure of unknown type", s << endl; SeriousErrorInFunction << "Stream state value = ", isState << endl; break; } return; } // ************************************************************************* //
30.310924
79
0.513446
MrAwesomeRocks
a7989f7e4ece026bbdc262e3111af38ca068f156
2,945
cpp
C++
samples/hwdrivers_capture_video_opencv/test.cpp
wstnturner/mrpt
b0be3557a4cded6bafff03feb28f7fa1f75762a3
[ "BSD-3-Clause" ]
38
2015-01-04T05:24:26.000Z
2015-07-17T00:30:02.000Z
samples/hwdrivers_capture_video_opencv/test.cpp
wstnturner/mrpt
b0be3557a4cded6bafff03feb28f7fa1f75762a3
[ "BSD-3-Clause" ]
40
2015-01-03T22:43:00.000Z
2015-07-17T18:52:59.000Z
samples/hwdrivers_capture_video_opencv/test.cpp
wstnturner/mrpt
b0be3557a4cded6bafff03feb28f7fa1f75762a3
[ "BSD-3-Clause" ]
41
2015-01-06T12:32:19.000Z
2017-05-30T15:50:13.000Z
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <mrpt/gui/CDisplayWindow.h> #include <mrpt/hwdrivers/CImageGrabber_OpenCV.h> #include <mrpt/io/CFileGZOutputStream.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/system/CTicTac.h> #include <iostream> using namespace mrpt::hwdrivers; using namespace mrpt::gui; using namespace mrpt::obs; using namespace mrpt::system; using namespace mrpt::io; using namespace mrpt::serialization; using namespace std; // ------------------------------------------------------ // TestCaptureOpenCV // ------------------------------------------------------ bool LIVE_CAM = true; int N_CAM_TO_OPEN = 0; std::string AVI_TO_OPEN; void TestCapture_OpenCV() { CImageGrabber_OpenCV* capture = nullptr; if (LIVE_CAM) { #if 0 // test: Select the desired resolution mrpt::vision::TCaptureCVOptions opts; opts.frame_width = 320; opts.frame_height = 240; capture = new CImageGrabber_OpenCV( 0, CAMERA_CV_AUTODETECT, opts ); #else capture = new CImageGrabber_OpenCV(N_CAM_TO_OPEN, CAMERA_CV_AUTODETECT); #endif } else { capture = new CImageGrabber_OpenCV(AVI_TO_OPEN); } CTicTac tictac; cout << "Press any key to stop capture to 'capture.rawlog'..." << endl; CFileGZOutputStream fil("./capture.rawlog"); CDisplayWindow win("Capturing..."); int cnt = 0; while (!mrpt::system::os::kbhit()) { if ((cnt++ % 20) == 0) { if (cnt > 0) { double t = tictac.Tac(); double FPS = 20 / t; printf("\n %f FPS\n", FPS); } tictac.Tic(); } CObservationImage::Ptr obs = CObservationImage::Create(); // Memory will be // freed by // SF destructor in each // loop. if (!capture->getObservation(*obs)) { cerr << "Error retrieving images!" << endl; break; } archiveFrom(fil) << obs; cout << "."; cout.flush(); if (win.isOpen()) win.showImage(obs->image); } delete capture; } int main(int argc, char** argv) { try { if (argc > 1) { if (!strstr(argv[1], ".avi")) { LIVE_CAM = true; N_CAM_TO_OPEN = atoi(argv[1]); } else { LIVE_CAM = false; AVI_TO_OPEN = argv[1]; } } TestCapture_OpenCV(); return 0; } catch (const std::exception& e) { std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << std::endl; return -1; } catch (...) { printf("Another exception!!"); return -1; } }
22.653846
80
0.551104
wstnturner
a798ce7c24d72630cb5e2dbc35c2c576b50d7142
4,063
hh
C++
be/src/formats/orc/apache-orc/c++/src/sargs/PredicateLeaf.hh
zxyboy/starrocks
6de5d7412bb654fa667b78ad9ee66b99c8c63e50
[ "BSD-3-Clause-Clear", "Zlib", "PSF-2.0", "Apache-2.0" ]
1
2021-10-12T09:57:10.000Z
2021-10-12T09:57:10.000Z
be/src/formats/orc/apache-orc/c++/src/sargs/PredicateLeaf.hh
zxyboy/starrocks
6de5d7412bb654fa667b78ad9ee66b99c8c63e50
[ "BSD-3-Clause-Clear", "Zlib", "PSF-2.0", "Apache-2.0" ]
1
2022-03-31T06:44:29.000Z
2022-03-31T06:44:29.000Z
be/src/formats/orc/apache-orc/c++/src/sargs/PredicateLeaf.hh
rickif/starrocks
94af746ec83cc1260e15dc1f5295e7b014c96598
[ "BSD-3-Clause-Clear", "Zlib", "PSF-2.0", "Apache-2.0" ]
1
2021-10-19T13:13:16.000Z
2021-10-19T13:13:16.000Z
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/orc/tree/main/c++/src/sargs/PredicateLeaf.hh /** * 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. */ #ifndef ORC_PREDICATELEAF_HH #define ORC_PREDICATELEAF_HH #include <string> #include <vector> #include "orc/Common.hh" #include "orc/sargs/Literal.hh" #include "orc/sargs/TruthValue.hh" #include "wrap/orc-proto-wrapper.hh" namespace orc { static constexpr uint64_t INVALID_COLUMN_ID = std::numeric_limits<uint64_t>::max(); class BloomFilter; /** * The primitive predicates that form a SearchArgument. */ class PredicateLeaf { public: /** * The possible operators for predicates. To get the opposites, construct * an expression with a not operator. */ enum class Operator { EQUALS = 0, NULL_SAFE_EQUALS, LESS_THAN, LESS_THAN_EQUALS, IN, BETWEEN, IS_NULL }; // The possible types for sargs. enum class Type { LONG = 0, // all of the integer types FLOAT, // float and double STRING, // string, char, varchar DATE, DECIMAL, TIMESTAMP, BOOLEAN }; PredicateLeaf() = default; PredicateLeaf(Operator op, PredicateDataType type, std::string colName, const Literal& literal); PredicateLeaf(Operator op, PredicateDataType type, std::string colName, const std::initializer_list<Literal>& literalList); PredicateLeaf(Operator op, PredicateDataType type, std::string colName, const std::vector<Literal>& literalList); /** * Get the operator for the leaf. */ Operator getOperator() const; /** * Get the type of the column and literal by the file format. */ PredicateDataType getType() const; /** * Get the simple column name. */ const std::string& getColumnName() const; /** * Get the literal half of the predicate leaf. */ Literal getLiteral() const; /** * For operators with multiple literals (IN and BETWEEN), get the literals. */ const std::vector<Literal>& getLiteralList() const; /** * Evaluate current PredicateLeaf based on ColumnStatistics and BloomFilter */ TruthValue evaluate(const WriterVersion writerVersion, const proto::ColumnStatistics& colStats, const BloomFilter* bloomFilter) const; std::string toString() const; bool operator==(const PredicateLeaf& r) const; size_t getHashCode() const { return mHashCode; } private: size_t hashCode() const; void validate() const; TruthValue evaluatePredicateMinMax(const proto::ColumnStatistics& colStats) const; TruthValue evaluatePredicateBloomFiter(const BloomFilter* bloomFilter, bool hasNull) const; private: Operator mOperator; PredicateDataType mType; std::string mColumnName; uint64_t mColumnId; std::vector<Literal> mLiterals; size_t mHashCode; }; struct PredicateLeafHash { size_t operator()(const PredicateLeaf& leaf) const { return leaf.getHashCode(); } }; struct PredicateLeafComparator { bool operator()(const PredicateLeaf& lhs, const PredicateLeaf& rhs) const { return lhs == rhs; } }; } // namespace orc #endif //ORC_PREDICATELEAF_HH
29.656934
117
0.698991
zxyboy
a79aa1315719ce59f29cf99d5d635eb68d9833aa
7,803
cpp
C++
source/Lib/CommonLib/x86/InitX86.cpp
1div0/vvdec
fceca978976f7f7394df839fe31497d2299fde80
[ "BSD-3-Clause" ]
204
2020-09-08T01:46:07.000Z
2022-03-29T23:54:49.000Z
source/Lib/CommonLib/x86/InitX86.cpp
1div0/vvdec
fceca978976f7f7394df839fe31497d2299fde80
[ "BSD-3-Clause" ]
42
2020-09-09T04:40:13.000Z
2022-03-08T03:52:18.000Z
source/Lib/CommonLib/x86/InitX86.cpp
1div0/vvdec
fceca978976f7f7394df839fe31497d2299fde80
[ "BSD-3-Clause" ]
57
2020-09-08T01:46:09.000Z
2022-03-16T07:07:38.000Z
/* ----------------------------------------------------------------------------- The copyright in this software is being made available under the BSD License, included below. No patent rights, trademark rights and/or other Intellectual Property Rights other than the copyrights concerning the Software are granted under this license. For any license concerning other Intellectual Property rights than the software, especially patent licenses, a separate Agreement needs to be closed. For more information please contact: Fraunhofer Heinrich Hertz Institute Einsteinufer 37 10587 Berlin, Germany www.hhi.fraunhofer.de/vvc vvc@hhi.fraunhofer.de Copyright (c) 2018-2021, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Fraunhofer nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------------------- */ /* * \ingroup CommonLib * \file InitX86.cpp * \brief Initialize encoder SIMD functions. */ #include "CommonLib/CommonDef.h" #include "CommonLib/InterpolationFilter.h" #include "CommonLib/TrQuant.h" #include "CommonLib/RdCost.h" #include "CommonLib/Buffer.h" #include "CommonLib/TrQuant_EMT.h" #include "CommonLib/IntraPrediction.h" #include "CommonLib/LoopFilter.h" #include "CommonLib/Picture.h" #include "CommonLib/AdaptiveLoopFilter.h" #include "CommonLib/SampleAdaptiveOffset.h" namespace vvdec { #ifdef TARGET_SIMD_X86 #if ENABLE_SIMD_OPT_MCIF void InterpolationFilter::initInterpolationFilterX86( /*int iBitDepthY, int iBitDepthC*/ ) { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initInterpolationFilterX86<AVX2>(/*iBitDepthY, iBitDepthC*/); break; #endif // !TARGET_SIMD_WASM case AVX: _initInterpolationFilterX86<AVX>(/*iBitDepthY, iBitDepthC*/); break; case SSE42: case SSE41: _initInterpolationFilterX86<SSE41>(/*iBitDepthY, iBitDepthC*/); break; default: break; } } #endif #if ENABLE_SIMD_OPT_BUFFER void PelBufferOps::initPelBufOpsX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initPelBufOpsX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initPelBufOpsX86<AVX>(); break; case SSE42: case SSE41: _initPelBufOpsX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_DIST void RdCost::initRdCostX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initRdCostX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initRdCostX86<AVX>(); break; case SSE42: case SSE41: _initRdCostX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_ALF void AdaptiveLoopFilter::initAdaptiveLoopFilterX86() { auto vext = read_x86_extension_flags(); switch ( vext ) { case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initAdaptiveLoopFilterX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initAdaptiveLoopFilterX86<AVX>(); break; case SSE42: case SSE41: _initAdaptiveLoopFilterX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_DBLF void LoopFilter::initLoopFilterX86() { auto vext = read_x86_extension_flags(); switch ( vext ) { case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initLoopFilterX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initLoopFilterX86<AVX>(); break; case SSE42: case SSE41: _initLoopFilterX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_TCOEFF_OPS void TCoeffOps::initTCoeffOpsX86() { auto vext = read_x86_extension_flags(); switch( vext ) { case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initTCoeffOpsX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initTCoeffOpsX86<AVX>(); break; case SSE42: case SSE41: _initTCoeffOpsX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_INTRAPRED void IntraPrediction::initIntraPredictionX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initIntraPredictionX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initIntraPredictionX86<AVX>(); break; case SSE42: case SSE41: _initIntraPredictionX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_SAO void SampleAdaptiveOffset::initSampleAdaptiveOffsetX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initSampleAdaptiveOffsetX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initSampleAdaptiveOffsetX86<AVX>(); break; case SSE42: case SSE41: _initSampleAdaptiveOffsetX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_INTER void InterPrediction::initInterPredictionX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initInterPredictionX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initInterPredictionX86<AVX>(); break; case SSE42: case SSE41: _initInterPredictionX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_PICTURE void Picture::initPictureX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initPictureX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initPictureX86<AVX>(); break; case SSE42: case SSE41: _initPictureX86<SSE41>(); break; default: break; } } #endif #if ENABLE_SIMD_OPT_QUANT void Quant::initQuantX86() { auto vext = read_x86_extension_flags(); switch (vext){ case AVX512: case AVX2: #ifndef TARGET_SIMD_WASM _initQuantX86<AVX2>(); break; #endif // !TARGET_SIMD_WASM case AVX: _initQuantX86<AVX>(); break; case SSE42: case SSE41: _initQuantX86<SSE41>(); break; default: break; } } #endif #endif }
21.918539
94
0.695117
1div0
a79eec3054f3faaae30c43783dac2c20f6857966
521
cpp
C++
Structural/Bridge/src/main.cpp
craviee/design-patterns-modern-cpp
39896c8a2491c5599f79afa65a07deda2e4e7dd7
[ "Unlicense" ]
3
2019-11-15T01:38:31.000Z
2020-04-21T13:04:19.000Z
Structural/Bridge/src/main.cpp
craviee/design-patterns-modern-cpp
39896c8a2491c5599f79afa65a07deda2e4e7dd7
[ "Unlicense" ]
23
2019-11-29T09:13:42.000Z
2020-02-05T14:53:03.000Z
Structural/Bridge/src/main.cpp
craviee/design-patterns-modern-cpp
39896c8a2491c5599f79afa65a07deda2e4e7dd7
[ "Unlicense" ]
null
null
null
#include <iostream> #include <memory> #include "CompanyTraveler.hpp" #include "PlaneTravel.hpp" #include "TrainTravel.hpp" int main() { auto plane = std::make_shared<PlaneTravel>(); auto train = std::make_shared<TrainTravel>(); CompanyTraveler traveler{std::static_pointer_cast<TravelMethod>(plane)}; CompanyTraveler anotherTraveler{std::static_pointer_cast<TravelMethod>(train)}; traveler.doTravel(); plane->price = 400; traveler.doTravel(); anotherTraveler.doTravel(); return 0; }
26.05
83
0.721689
craviee
a79fb6fe444538eda1e8ce75a50b158177480294
15,180
cpp
C++
Source/Core/GeometryBackgroundBorder.cpp
aquawicket/RmlUi
d56f17e49ca2ee88aadeb304228cd1eae14e3f51
[ "MIT" ]
null
null
null
Source/Core/GeometryBackgroundBorder.cpp
aquawicket/RmlUi
d56f17e49ca2ee88aadeb304228cd1eae14e3f51
[ "MIT" ]
null
null
null
Source/Core/GeometryBackgroundBorder.cpp
aquawicket/RmlUi
d56f17e49ca2ee88aadeb304228cd1eae14e3f51
[ "MIT" ]
null
null
null
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * 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 "GeometryBackgroundBorder.h" #include "../../Include/RmlUi/Core/Box.h" #include "../../Include/RmlUi/Core/Math.h" #include <algorithm> #include <float.h> namespace Rml { GeometryBackgroundBorder::GeometryBackgroundBorder(Vector<Vertex>& vertices, Vector<int>& indices) : vertices(vertices), indices(indices) {} void GeometryBackgroundBorder::Draw(Vector<Vertex>& vertices, Vector<int>& indices, CornerSizes radii, const Box& box, const Vector2f offset, const Colourb background_color, const Colourb* border_colors) { using Edge = Box::Edge; EdgeSizes border_widths = { Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::TOP)), Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::RIGHT)), Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::BOTTOM)), Math::RoundFloat(box.GetEdge(Box::BORDER, Edge::LEFT)), }; int num_borders = 0; if (border_colors) { for (int i = 0; i < 4; i++) if (border_colors[i].alpha > 0 && border_widths[i] > 0) num_borders += 1; } const Vector2f padding_size = box.GetSize(Box::PADDING).Round(); const bool has_background = (background_color.alpha > 0 && padding_size.x > 0 && padding_size.y > 0); const bool has_border = (num_borders > 0); if (!has_background && !has_border) return; // -- Find the corner positions -- const Vector2f border_position = offset.Round(); const Vector2f padding_position = border_position + Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]); const Vector2f border_size = padding_size + Vector2f(border_widths[Edge::LEFT] + border_widths[Edge::RIGHT], border_widths[Edge::TOP] + border_widths[Edge::BOTTOM]); // Border edge positions CornerPositions positions_outer = { border_position, border_position + Vector2f(border_size.x, 0), border_position + border_size, border_position + Vector2f(0, border_size.y) }; // Padding edge positions CornerPositions positions_inner = { padding_position, padding_position + Vector2f(padding_size.x, 0), padding_position + padding_size, padding_position + Vector2f(0, padding_size.y) }; // -- For curved borders, find the positions to draw ellipses around, and the scaled outer and inner radii -- const float sum_radius = (radii[TOP_LEFT] + radii[TOP_RIGHT] + radii[BOTTOM_RIGHT] + radii[BOTTOM_LEFT]); const bool has_radius = (sum_radius > 1.f); // Curved borders are drawn as circles (outer border) and ellipses (inner border) around the centers. CornerPositions positions_circle_center; // Radii of the padding edges, 2-dimensional as these can be ellipses. // The inner radii is effectively the (signed) distance from the circle center to the padding edge. // They can also be zero or negative, in which case a sharp corner should be drawn instead of an arc. CornerSizes2 inner_radii; if (has_radius) { // Scale the radii such that we have no overlapping curves. float scale_factor = FLT_MAX; scale_factor = Math::Min(scale_factor, padding_size.x / (radii[TOP_LEFT] + radii[TOP_RIGHT])); // Top scale_factor = Math::Min(scale_factor, padding_size.y / (radii[TOP_RIGHT] + radii[BOTTOM_RIGHT])); // Right scale_factor = Math::Min(scale_factor, padding_size.x / (radii[BOTTOM_RIGHT] + radii[BOTTOM_LEFT])); // Bottom scale_factor = Math::Min(scale_factor, padding_size.y / (radii[BOTTOM_LEFT] + radii[TOP_LEFT])); // Left scale_factor = Math::Min(1.0f, scale_factor); for (float& radius : radii) radius = Math::RoundFloat(radius * scale_factor); // Place the circle/ellipse centers positions_circle_center = { positions_outer[TOP_LEFT] + Vector2f(1, 1) * radii[TOP_LEFT], positions_outer[TOP_RIGHT] + Vector2f(-1, 1) * radii[TOP_RIGHT], positions_outer[BOTTOM_RIGHT] + Vector2f(-1, -1) * radii[BOTTOM_RIGHT], positions_outer[BOTTOM_LEFT] + Vector2f(1, -1) * radii[BOTTOM_LEFT] }; inner_radii = { Vector2f(radii[TOP_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::TOP]), Vector2f(radii[TOP_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::TOP]), Vector2f(radii[BOTTOM_RIGHT]) - Vector2f(border_widths[Edge::RIGHT], border_widths[Edge::BOTTOM]), Vector2f(radii[BOTTOM_LEFT]) - Vector2f(border_widths[Edge::LEFT], border_widths[Edge::BOTTOM]) }; } // -- Generate the geometry -- GeometryBackgroundBorder geometry(vertices, indices); { // Reserve geometry. A conservative estimate, does not take border-radii into account and assumes same-colored borders. const int estimated_num_vertices = 4 * int(has_background) + 2 * num_borders; const int estimated_num_triangles = 2 * int(has_background) + 2 * num_borders; vertices.reserve((int)vertices.size() + estimated_num_vertices); indices.reserve((int)indices.size() + 3 * estimated_num_triangles); } // Draw the background if (has_background) { const int offset_vertices = (int)vertices.size(); for (int corner = 0; corner < 4; corner++) geometry.DrawBackgroundCorner(Corner(corner), positions_inner[corner], positions_circle_center[corner], radii[corner], inner_radii[corner], background_color); geometry.FillBackground(offset_vertices); } // Draw the border if (has_border) { using Edge = Box::Edge; const int offset_vertices = (int)vertices.size(); const bool draw_edge[4] = { border_widths[Edge::TOP] > 0 && border_colors[Edge::TOP].alpha > 0, border_widths[Edge::RIGHT] > 0 && border_colors[Edge::RIGHT].alpha > 0, border_widths[Edge::BOTTOM] > 0 && border_colors[Edge::BOTTOM].alpha > 0, border_widths[Edge::LEFT] > 0 && border_colors[Edge::LEFT].alpha > 0 }; const bool draw_corner[4] = { draw_edge[Edge::TOP] || draw_edge[Edge::LEFT], draw_edge[Edge::TOP] || draw_edge[Edge::RIGHT], draw_edge[Edge::BOTTOM] || draw_edge[Edge::RIGHT], draw_edge[Edge::BOTTOM] || draw_edge[Edge::LEFT] }; for (int corner = 0; corner < 4; corner++) { const Edge edge0 = Edge((corner + 3) % 4); const Edge edge1 = Edge(corner); if (draw_corner[corner]) geometry.DrawBorderCorner(Corner(corner), positions_outer[corner], positions_inner[corner], positions_circle_center[corner], radii[corner], inner_radii[corner], border_colors[edge0], border_colors[edge1]); if (draw_edge[edge1]) { RMLUI_ASSERTMSG(draw_corner[corner] && draw_corner[(corner + 1) % 4], "Border edges can only be drawn if both of its connected corners are drawn."); geometry.FillEdge(edge1 == Edge::LEFT ? offset_vertices : (int)vertices.size()); } } } #if 0 // Debug draw vertices if (has_radius) { const int num_vertices = vertices.size(); const int num_indices = indices.size(); vertices.resize(num_vertices + 4 * num_vertices); indices.resize(num_indices + 6 * num_indices); for (int i = 0; i < num_vertices; i++) { GeometryUtilities::GenerateQuad(vertices.data() + num_vertices + 4 * i, indices.data() + num_indices + 6 * i, vertices[i].position, Vector2f(3, 3), Colourb(255, 0, (i % 2) == 0 ? 0 : 255), num_vertices + 4 * i); } } #endif #ifdef RMLUI_DEBUG const int num_vertices = (int)vertices.size(); for (int index : indices) { RMLUI_ASSERT(index < num_vertices); } #endif } void GeometryBackgroundBorder::DrawBackgroundCorner(Corner corner, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color) { if (R == 0 || r.x <= 0 || r.y <= 0) { DrawPoint(pos_inner, color); } else if (r.x > 0 && r.y > 0) { const float a0 = float((int)corner + 2) * 0.5f * Math::RMLUI_PI; const float a1 = float((int)corner + 3) * 0.5f * Math::RMLUI_PI; const int num_points = GetNumPoints(R); DrawArc(pos_circle_center, r, a0, a1, color, color, num_points); } } void GeometryBackgroundBorder::DrawPoint(Vector2f pos, Colourb color) { const int offset_vertices = (int)vertices.size(); vertices.resize(offset_vertices + 1); vertices[offset_vertices].position = pos; vertices[offset_vertices].colour = color; } void GeometryBackgroundBorder::DrawArc(Vector2f pos_center, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points) { RMLUI_ASSERT(num_points >= 2 && r.x > 0 && r.y > 0); const int offset_vertices = (int)vertices.size(); vertices.resize(offset_vertices + num_points); for (int i = 0; i < num_points; i++) { const float t = float(i) / float(num_points - 1); const float a = Math::Lerp(t, a0, a1); const Vector2f unit_vector(Math::Cos(a), Math::Sin(a)); vertices[offset_vertices + i].position = unit_vector * r + pos_center; vertices[offset_vertices + i].colour = Math::RoundedLerp(t, color0, color1); } } void GeometryBackgroundBorder::FillBackground(int index_start) { const int num_added_vertices = (int)vertices.size() - index_start; const int offset_indices = (int)indices.size(); const int num_triangles = (num_added_vertices - 2); indices.resize(offset_indices + 3 * num_triangles); for (int i = 0; i < num_triangles; i++) { indices[offset_indices + 3 * i] = index_start; indices[offset_indices + 3 * i + 1] = index_start + i + 2; indices[offset_indices + 3 * i + 2] = index_start + i + 1; } } void GeometryBackgroundBorder::DrawBorderCorner(Corner corner, Vector2f pos_outer, Vector2f pos_inner, Vector2f pos_circle_center, float R, Vector2f r, Colourb color0, Colourb color1) { const float a0 = float((int)corner + 2) * 0.5f * Math::RMLUI_PI; const float a1 = float((int)corner + 3) * 0.5f * Math::RMLUI_PI; if (R == 0) { DrawPointPoint(pos_outer, pos_inner, color0, color1); } else if (r.x > 0 && r.y > 0) { DrawArcArc(pos_circle_center, R, r, a0, a1, color0, color1, GetNumPoints(R)); } else { DrawArcPoint(pos_circle_center, pos_inner, R, a0, a1, color0, color1, GetNumPoints(R)); } } void GeometryBackgroundBorder::DrawPointPoint(Vector2f pos_outer, Vector2f pos_inner, Colourb color0, Colourb color1) { const bool different_color = (color0 != color1); vertices.reserve((int)vertices.size() + (different_color ? 4 : 2)); DrawPoint(pos_inner, color0); DrawPoint(pos_outer, color0); if (different_color) { DrawPoint(pos_inner, color1); DrawPoint(pos_outer, color1); } } void GeometryBackgroundBorder::DrawArcArc(Vector2f pos_center, float R, Vector2f r, float a0, float a1, Colourb color0, Colourb color1, int num_points) { RMLUI_ASSERT(num_points >= 2 && R > 0 && r.x > 0 && r.y > 0); const int num_triangles = 2 * (num_points - 1); const int offset_vertices = (int)vertices.size(); const int offset_indices = (int)indices.size(); vertices.resize(offset_vertices + 2 * num_points); indices.resize(offset_indices + 3 * num_triangles); for (int i = 0; i < num_points; i++) { const float t = float(i) / float(num_points - 1); const float a = Math::Lerp(t, a0, a1); const Colourb color = Math::RoundedLerp(t, color0, color1); const Vector2f unit_vector(Math::Cos(a), Math::Sin(a)); vertices[offset_vertices + 2 * i].position = unit_vector * r + pos_center; vertices[offset_vertices + 2 * i].colour = color; vertices[offset_vertices + 2 * i + 1].position = unit_vector * R + pos_center; vertices[offset_vertices + 2 * i + 1].colour = color; } for (int i = 0; i < num_triangles; i += 2) { indices[offset_indices + 3 * i + 0] = offset_vertices + i + 0; indices[offset_indices + 3 * i + 1] = offset_vertices + i + 2; indices[offset_indices + 3 * i + 2] = offset_vertices + i + 1; indices[offset_indices + 3 * i + 3] = offset_vertices + i + 1; indices[offset_indices + 3 * i + 4] = offset_vertices + i + 2; indices[offset_indices + 3 * i + 5] = offset_vertices + i + 3; } } void GeometryBackgroundBorder::DrawArcPoint(Vector2f pos_center, Vector2f pos_inner, float R, float a0, float a1, Colourb color0, Colourb color1, int num_points) { RMLUI_ASSERT(R > 0 && num_points >= 2); const int offset_vertices = (int)vertices.size(); vertices.reserve(offset_vertices + num_points + 2); // Generate the vertices. We could also split the arc mid-way to create a sharp color transition. DrawPoint(pos_inner, color0); DrawArc(pos_center, Vector2f(R), a0, a1, color0, color1, num_points); DrawPoint(pos_inner, color1); RMLUI_ASSERT((int)vertices.size() - offset_vertices == num_points + 2); // Swap the last two vertices such that the outer edge vertex is last, see the comment for the border drawing functions. Their colors should already be the same. const int last_vertex = (int)vertices.size() - 1; std::swap(vertices[last_vertex - 1].position, vertices[last_vertex].position); // Generate the indices const int num_triangles = (num_points - 1); const int i_vertex_inner0 = offset_vertices; const int i_vertex_inner1 = last_vertex - 1; const int offset_indices = (int)indices.size(); indices.resize(offset_indices + 3 * num_triangles); for (int i = 0; i < num_triangles; i++) { indices[offset_indices + 3 * i + 0] = (i > num_triangles / 2 ? i_vertex_inner1 : i_vertex_inner0); indices[offset_indices + 3 * i + 1] = offset_vertices + i + 2; indices[offset_indices + 3 * i + 2] = offset_vertices + i + 1; } // Since we swapped the last two vertices we also need to change the last triangle. indices[offset_indices + 3 * (num_triangles - 1) + 1] = last_vertex; } void GeometryBackgroundBorder::FillEdge(int index_next_corner) { const int offset_indices = (int)indices.size(); const int num_vertices = (int)vertices.size(); RMLUI_ASSERT(num_vertices >= 2); indices.resize(offset_indices + 6); indices[offset_indices + 0] = num_vertices - 2; indices[offset_indices + 1] = index_next_corner; indices[offset_indices + 2] = num_vertices - 1; indices[offset_indices + 3] = num_vertices - 1; indices[offset_indices + 4] = index_next_corner; indices[offset_indices + 5] = index_next_corner + 1; } int GeometryBackgroundBorder::GetNumPoints(float R) const { return Math::Clamp(3 + Math::RoundToInteger(R / 6.f), 2, 100); } } // namespace Rml
36.142857
214
0.713439
aquawicket
a7a133e38e7f26144b668b432f88a35dc2e5d172
1,426
cpp
C++
src/engine/ModelLoader.cpp
eknah/Forradia
20ec33fd515e131cd1943e9684552961d2e1e0db
[ "MIT" ]
null
null
null
src/engine/ModelLoader.cpp
eknah/Forradia
20ec33fd515e131cd1943e9684552961d2e1e0db
[ "MIT" ]
null
null
null
src/engine/ModelLoader.cpp
eknah/Forradia
20ec33fd515e131cd1943e9684552961d2e1e0db
[ "MIT" ]
null
null
null
// Copyright (C) 2022 Andreas Åkerberg // This code is licensed under MIT license (see LICENSE for details) #include "ModelLoader.h" #include <filesystem> namespace Forradia { void ModelLoader::LoadModels() { models.clear(); modelNames.clear(); auto file_path = std::string(SDL_GetBasePath()); file_path.append(modelsPath); auto entries = std::filesystem::recursive_directory_iterator(file_path.c_str()); for (auto& file : entries) { auto full_filename = file.path().filename().string(); auto filename = full_filename.substr(0, full_filename.find(".")); auto image_name_hash = int(); if (file.is_directory() || modelNameExtension != full_filename.substr(full_filename.length() - modelNameExtension.length(), modelNameExtension.length())) continue; Forradia::Model3D loaded_model; loaded_model.LoadFile(file.path().string()); image_name_hash = GetId(filename); models[image_name_hash] = loaded_model; modelNames[image_name_hash] = filename; } } bool ModelLoader::ModelExists(std::string ModelName) const { auto result = modelNames.count(GetId(ModelName)) > 0; return result; } } // namespace Forradia
27.960784
77
0.592567
eknah
a7a1c8bead1ac0f903421739664b49597d79f6c8
2,375
hpp
C++
Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/relate/less.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2014. // Modifications copyright (c) 2014, Oracle and/or its affiliates. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/util/math.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { #ifndef DOXYGEN_NO_DISPATCH namespace detail_dispatch { namespace relate { // TODO: Integrate it with geometry::less? template <typename Point1, typename Point2, std::size_t I = 0, std::size_t D = geometry::dimension<Point1>::value> struct less { static inline bool apply(Point1 const& left, Point2 const& right) { typename geometry::coordinate_type<Point1>::type cleft = geometry::get<I>(left); typename geometry::coordinate_type<Point2>::type cright = geometry::get<I>(right); if ( geometry::math::equals(cleft, cright) ) { return less<Point1, Point2, I + 1, D>::apply(left, right); } else { return cleft < cright; } } }; template <typename Point1, typename Point2, std::size_t D> struct less<Point1, Point2, D, D> { static inline bool apply(Point1 const&, Point2 const&) { return false; } }; }} // namespace detail_dispatch::relate #endif #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace relate { struct less { template <typename Point1, typename Point2> inline bool operator()(Point1 const& point1, Point2 const& point2) const { return detail_dispatch::relate::less<Point1, Point2>::apply(point1, point2); } }; }} // namespace detail::relate #endif // DOXYGEN_NO_DETAIL }} // namespace geofeatures_boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_LESS_HPP
28.27381
116
0.703158
xarvey
a7a3d8700e1bce2f18c4bc9eca68d645ae447870
8,954
cc
C++
deps/lcb/src/operations/touch.cc
florinspataru1/couchnode
b6e8f7b835388d9d47b8fca0e1181e9e4267f89a
[ "Apache-2.0" ]
97
2017-01-02T20:05:10.000Z
2022-02-06T18:44:04.000Z
deps/lcb/src/operations/touch.cc
florinspataru1/couchnode
b6e8f7b835388d9d47b8fca0e1181e9e4267f89a
[ "Apache-2.0" ]
108
2017-01-27T15:00:32.000Z
2021-12-06T15:06:47.000Z
deps/lcb/src/operations/touch.cc
florinspataru1/couchnode
b6e8f7b835388d9d47b8fca0e1181e9e4267f89a
[ "Apache-2.0" ]
29
2017-01-31T21:11:51.000Z
2022-02-20T20:11:17.000Z
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010-2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "internal.h" #include "collections.h" #include "trace.h" #include "defer.h" #include "capi/cmd_touch.hh" LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_status(const lcb_RESPTOUCH *resp) { return resp->ctx.rc; } LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_error_context(const lcb_RESPTOUCH *resp, const lcb_KEY_VALUE_ERROR_CONTEXT **ctx) { *ctx = &resp->ctx; return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_cookie(const lcb_RESPTOUCH *resp, void **cookie) { *cookie = resp->cookie; return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_cas(const lcb_RESPTOUCH *resp, uint64_t *cas) { *cas = resp->ctx.cas; return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_key(const lcb_RESPTOUCH *resp, const char **key, size_t *key_len) { *key = resp->ctx.key.c_str(); *key_len = resp->ctx.key.size(); return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_resptouch_mutation_token(const lcb_RESPTOUCH *resp, lcb_MUTATION_TOKEN *token) { if (token) { *token = resp->mt; } return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_create(lcb_CMDTOUCH **cmd) { *cmd = new lcb_CMDTOUCH{}; return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_destroy(lcb_CMDTOUCH *cmd) { delete cmd; return LCB_SUCCESS; } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_timeout(lcb_CMDTOUCH *cmd, uint32_t timeout) { return cmd->timeout_in_microseconds(timeout); } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_parent_span(lcb_CMDTOUCH *cmd, lcbtrace_SPAN *span) { return cmd->parent_span(span); } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_collection(lcb_CMDTOUCH *cmd, const char *scope, size_t scope_len, const char *collection, size_t collection_len) { try { lcb::collection_qualifier qualifier(scope, scope_len, collection, collection_len); return cmd->collection(std::move(qualifier)); } catch (const std::invalid_argument &) { return LCB_ERR_INVALID_ARGUMENT; } } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_key(lcb_CMDTOUCH *cmd, const char *key, size_t key_len) { if (key == nullptr || key_len == 0) { return LCB_ERR_INVALID_ARGUMENT; } return cmd->key(std::string(key, key_len)); } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_expiry(lcb_CMDTOUCH *cmd, uint32_t expiration) { return cmd->expiry(expiration); } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_durability(lcb_CMDTOUCH * /* cmd */, lcb_DURABILITY_LEVEL /* level */) { return LCB_ERR_UNSUPPORTED_OPERATION; } LIBCOUCHBASE_API lcb_STATUS lcb_cmdtouch_on_behalf_of(lcb_CMDTOUCH *cmd, const char *data, size_t data_len) { return cmd->on_behalf_of(std::string(data, data_len)); } static lcb_STATUS touch_validate(lcb_INSTANCE *instance, const lcb_CMDTOUCH *cmd) { if (cmd->key().empty()) { return LCB_ERR_EMPTY_KEY; } if (!LCBT_SETTING(instance, use_collections) && !cmd->collection().is_default_collection()) { /* only allow default collection when collections disabled for the instance */ return LCB_ERR_SDK_FEATURE_UNAVAILABLE; } return LCB_SUCCESS; } static lcb_STATUS touch_schedule(lcb_INSTANCE *instance, std::shared_ptr<lcb_CMDTOUCH> cmd) { protocol_binary_request_header hdr{}; mc_PIPELINE *pl; mc_PACKET *pkt; lcb_STATUS err; std::vector<std::uint8_t> framing_extras; if (cmd->want_impersonation()) { err = lcb::flexible_framing_extras::encode_impersonate_user(cmd->impostor(), framing_extras); if (err != LCB_SUCCESS) { return err; } } hdr.request.magic = framing_extras.empty() ? PROTOCOL_BINARY_REQ : PROTOCOL_BINARY_AREQ; auto ffextlen = static_cast<std::uint8_t>(framing_extras.size()); lcb_KEYBUF keybuf{LCB_KV_COPY, {cmd->key().c_str(), cmd->key().size()}}; err = mcreq_basic_packet(&instance->cmdq, &keybuf, cmd->collection().collection_id(), &hdr, 4, ffextlen, &pkt, &pl, MCREQ_BASICPACKET_F_FALLBACKOK); if (err != LCB_SUCCESS) { return err; } hdr.request.opcode = PROTOCOL_BINARY_CMD_TOUCH; hdr.request.cas = 0; hdr.request.datatype = PROTOCOL_BINARY_RAW_BYTES; hdr.request.opaque = pkt->opaque; hdr.request.bodylen = htonl(hdr.request.extlen + ffextlen + mcreq_get_key_size(&hdr)); memcpy(SPAN_BUFFER(&pkt->kh_span), &hdr, sizeof(hdr)); std::size_t offset = sizeof(hdr); if (!framing_extras.empty()) { memcpy(SPAN_BUFFER(&pkt->kh_span) + offset, framing_extras.data(), framing_extras.size()); offset += framing_extras.size(); } std::uint32_t expiry = htonl(cmd->expiry()); memcpy(SPAN_BUFFER(&pkt->kh_span) + offset, &expiry, sizeof(expiry)); pkt->u_rdata.reqdata.cookie = cmd->cookie(); pkt->u_rdata.reqdata.start = cmd->start_time_or_default_in_nanoseconds(gethrtime()); pkt->u_rdata.reqdata.deadline = pkt->u_rdata.reqdata.start + cmd->timeout_or_default_in_nanoseconds(LCB_US2NS(LCBT_SETTING(instance, operation_timeout))); pkt->u_rdata.reqdata.span = lcb::trace::start_kv_span(instance->settings, pkt, cmd); LCB_SCHED_ADD(instance, pl, pkt); TRACE_TOUCH_BEGIN(instance, &hdr, cmd); return LCB_SUCCESS; } static lcb_STATUS touch_execute(lcb_INSTANCE *instance, std::shared_ptr<lcb_CMDTOUCH> cmd) { if (!LCBT_SETTING(instance, use_collections)) { /* fast path if collections are not enabled */ return touch_schedule(instance, cmd); } if (collcache_get(instance, cmd->collection()) == LCB_SUCCESS) { return touch_schedule(instance, cmd); } return collcache_resolve( instance, cmd, [instance](lcb_STATUS status, const lcb_RESPGETCID *resp, std::shared_ptr<lcb_CMDTOUCH> operation) { const auto callback_type = LCB_CALLBACK_TOUCH; lcb_RESPCALLBACK operation_callback = lcb_find_callback(instance, callback_type); lcb_RESPTOUCH response{}; if (resp != nullptr) { response.ctx = resp->ctx; } response.ctx.key = operation->key(); response.ctx.scope = operation->collection().scope(); response.ctx.collection = operation->collection().collection(); response.cookie = operation->cookie(); if (status == LCB_ERR_SHEDULE_FAILURE || resp == nullptr) { response.ctx.rc = LCB_ERR_TIMEOUT; operation_callback(instance, callback_type, &response); return; } if (resp->ctx.rc != LCB_SUCCESS) { operation_callback(instance, callback_type, &response); return; } response.ctx.rc = touch_schedule(instance, operation); if (response.ctx.rc != LCB_SUCCESS) { operation_callback(instance, callback_type, &response); } }); } LIBCOUCHBASE_API lcb_STATUS lcb_touch(lcb_INSTANCE *instance, void *cookie, const lcb_CMDTOUCH *command) { lcb_STATUS rc; rc = touch_validate(instance, command); if (rc != LCB_SUCCESS) { return rc; } auto cmd = std::make_shared<lcb_CMDTOUCH>(*command); cmd->cookie(cookie); if (instance->cmdq.config == nullptr) { cmd->start_time_in_nanoseconds(gethrtime()); return lcb::defer_operation(instance, [instance, cmd](lcb_STATUS status) { const auto callback_type = LCB_CALLBACK_TOUCH; lcb_RESPCALLBACK operation_callback = lcb_find_callback(instance, callback_type); lcb_RESPTOUCH response{}; response.ctx.key = cmd->key(); response.cookie = cmd->cookie(); if (status == LCB_ERR_REQUEST_CANCELED) { response.ctx.rc = status; operation_callback(instance, callback_type, &response); return; } response.ctx.rc = touch_execute(instance, cmd); if (response.ctx.rc != LCB_SUCCESS) { operation_callback(instance, callback_type, &response); } }); } return touch_execute(instance, cmd); }
34.840467
119
0.66931
florinspataru1
a7a4c1fb3c934cfdca240c5f94bac17dfc69a4cc
1,432
cpp
C++
jsUnits/jsAxialStiffness.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsAxialStiffness.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsAxialStiffness.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 DNV AS // // 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 #include <jsUnits/jsAxialStiffness.h> #include <jsUnits/jsUnitClass.h> #include <Units/AxialStiffness.h> #include "jsRotationalStiffnessPerUnitLength.h" #include "jsCoupledStiffness.h" #include "jsForce.h" using namespace DNVS::MoFa::Units; Runtime::DynamicPhenomenon jsAxialStiffness::GetPhenomenon() { return AxialStiffnessPhenomenon(); } void jsAxialStiffness::init(jsTypeLibrary& typeLibrary) { jsUnitClass<jsAxialStiffness, AxialStiffness> cls(typeLibrary); if (cls.reinit()) return; cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsRotationalStiffnessPerUnitLength>); cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsCoupledStiffness>); cls.ImplicitConstructorConversion(&jsUnitClass<jsAxialStiffness, AxialStiffness>::ConstructEquivalentQuantity<jsForce>); cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return RotationalStiffnessPerUnitLength(val); }); cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return CoupledStiffness(val); }); cls.ImplicitConstructorConversion([](const jsAxialStiffness& val) {return Force(val); }); }
42.117647
151
0.796788
dnv-opensource
a7a5eb60a38c574a2984a102cedb70ddd1f7d33a
19,537
cc
C++
src/nameserver/logdb.cc
spiritbrother1/bfs
f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c
[ "BSD-3-Clause" ]
null
null
null
src/nameserver/logdb.cc
spiritbrother1/bfs
f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c
[ "BSD-3-Clause" ]
null
null
null
src/nameserver/logdb.cc
spiritbrother1/bfs
f3bb0ea70e8e2bda99df742e4c0b768f6a96d57c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <common/logging.h> #include <common/string_util.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include "nameserver/logdb.h" namespace baidu { namespace bfs { LogDB::LogDB() : thread_pool_(NULL), next_index_(0), smallest_index_(-1), write_log_(NULL), write_index_(NULL), marker_log_(NULL) {} LogDB::~LogDB() { if (thread_pool_) { thread_pool_->Stop(true); } if (write_log_) fclose(write_log_); for (FileCache::iterator it = read_log_.begin(); it != read_log_.end(); ++it) { fclose((it->second).first); fclose((it->second).second); } if (write_index_) fclose(write_index_); if (marker_log_) fclose(marker_log_); } void LogDB::Open(const std::string& path, const DBOption& option, LogDB** dbptr) { *dbptr = NULL; LogDB* logdb = new LogDB(); logdb->dbpath_ = path + "/"; logdb->snapshot_interval_ = option.snapshot_interval * 1000; logdb->log_size_ = option.log_size << 20; mkdir(logdb->dbpath_.c_str(), 0755); if(!logdb->RecoverMarker()) { LOG(WARNING, "[LogDB] RecoverMarker failed reason: %s", strerror(errno)); delete logdb; return; } std::map<std::string, std::string>::iterator it = logdb->markers_.find(".smallest_index_"); if (it != logdb->markers_.end()) { logdb->smallest_index_ = boost::lexical_cast<int64_t>(it->second); } if (!logdb->BuildFileCache()) { LOG(WARNING, "[LogDB] BuildFileCache failed"); delete logdb; return; } logdb->thread_pool_ = new ThreadPool(10); logdb->WriteMarkerSnapshot(); *dbptr = logdb; return; } StatusCode LogDB::Write(int64_t index, const std::string& entry) { MutexLock lock(&mu_); if (index != next_index_ && smallest_index_ != -1) { LOG(INFO, "[LogDB] Write with invalid index = %ld smallest_index_ = %ld next_index_ = %ld ", index, smallest_index_, next_index_); return kBadParameter; } if (smallest_index_ == -1) { // empty db StatusCode s = WriteMarkerNoLock(".smallest_index_", common::NumToString(index)); if (s != kOK) { return s; } smallest_index_ = index; LOG(INFO, "[LogDB] Set smallest_index_ to %ld ", smallest_index_); } uint32_t len = entry.length(); std::string data; data.append(reinterpret_cast<char*>(&len), 4); data.append(entry); if (!write_log_) { if (!NewWriteLog(index)) { return kWriteError; } } int64_t offset = ftell(write_log_); if (offset > log_size_) { if (!NewWriteLog(index)) { return kWriteError; } offset = 0; } if (fwrite(data.c_str(), 1, data.length(), write_log_) != data.length() || fflush(write_log_) != 0) { LOG(WARNING, "[LogDB] Write log %ld failed", index); CloseCurrent(); return kWriteError; } if (fwrite(reinterpret_cast<char*>(&index), 1, 8, write_index_) != 8) { LOG(WARNING, "[LogDB] Write index %ld failed", index); CloseCurrent(); return kWriteError; } if (fwrite(reinterpret_cast<char*>(&offset), 1, 8, write_index_) != 8 || fflush(write_index_) != 0) { LOG(WARNING, "[LogDB] Write index %ld failed", index); CloseCurrent(); return kWriteError; } next_index_ = index + 1; return kOK; } StatusCode LogDB::Read(int64_t index, std::string* entry) { if (read_log_.empty() || index >= next_index_ || index < smallest_index_) { return kNsNotFound; } FileCache::iterator it = read_log_.lower_bound(index); if (it == read_log_.end() || (it != read_log_.begin() && index != it->first)) { --it; } if (index < it->first) { LOG(FATAL, "[LogDB] Read cannot find index file %ld ", index); } FILE* idx_fp = (it->second).first; FILE* log_fp = (it->second).second; // find entry offset int offset = 16 * (index - it->first); int64_t read_index = -1; int64_t entry_offset = -1; { MutexLock lock(&mu_); if (fseek(idx_fp, offset, SEEK_SET) != 0) { LOG(FATAL, "[LogDB] Read cannot find index file %ld ", index); } StatusCode s = ReadIndex(idx_fp, index, &read_index, &entry_offset); if (s != kOK) { return s; } } // read log entry { MutexLock lock(&mu_); if(fseek(log_fp, entry_offset, SEEK_SET) != 0) { LOG(WARNING, "[LogDB] Read %ld with invalid offset %ld ", index, entry_offset); return kReadError; } int ret = ReadOne(log_fp, entry); if (ret <= 0) { LOG(WARNING, "[LogDB] Read log error %ld ", index); return kReadError; } } return kOK; } StatusCode LogDB::WriteMarkerNoLock(const std::string& key, const std::string& value) { if (marker_log_ == NULL) { marker_log_ = fopen((dbpath_ + "marker.mak").c_str(), "a"); if (marker_log_ == NULL) { LOG(WARNING, "[LogDB] open marker.mak failed %s", strerror(errno)); return kWriteError; } } std::string data; uint32_t len = 4 + key.length() + 4 + value.length(); data.append(reinterpret_cast<char*>(&len), 4); EncodeMarker(MarkerEntry(key, value), &data); if (fwrite(data.c_str(), 1, data.length(), marker_log_) != data.length() || fflush(marker_log_) != 0) { LOG(WARNING, "[LogDB] WriteMarker failed key = %s value = %s", key.c_str(), value.c_str()); return kWriteError; } fflush(marker_log_); markers_[key] = value; return kOK; } StatusCode LogDB::WriteMarker(const std::string& key, const std::string& value) { MutexLock lock(&mu_); return WriteMarkerNoLock(key, value); } StatusCode LogDB::WriteMarker(const std::string& key, int64_t value) { return WriteMarker(key, std::string(reinterpret_cast<char*>(&value), 8)); } StatusCode LogDB::ReadMarker(const std::string& key, std::string* value) { MutexLock lock(&mu_); std::map<std::string, std::string>::iterator it = markers_.find(key); if (it == markers_.end()) { return kNsNotFound; } *value = it->second; return kOK; } StatusCode LogDB::ReadMarker(const std::string& key, int64_t* value) { std::string v; StatusCode status = ReadMarker(key, &v); if (status != kOK) { return status; } memcpy(value, &(v[0]), 8); return kOK; } StatusCode LogDB::GetLargestIdx(int64_t* value) { MutexLock lock(&mu_); if (smallest_index_ == next_index_) { *value = -1; return kNsNotFound; } *value = next_index_ - 1; return kOK; } StatusCode LogDB::DeleteUpTo(int64_t index) { if (index < smallest_index_) { return kOK; } if (index >= next_index_) { LOG(INFO, "[LogDB] DeleteUpTo over limit index = %ld next_index_ = %ld", index, next_index_); return kBadParameter; } MutexLock lock(&mu_); smallest_index_ = index + 1; WriteMarkerNoLock(".smallest_index_", common::NumToString(smallest_index_)); FileCache::reverse_iterator upto = read_log_.rbegin(); while (upto != read_log_.rend()) { if (upto->first <= index) break; ++upto; } if (upto == read_log_.rend()) { return kOK; } int64_t upto_index = upto->first; FileCache::iterator it = read_log_.begin(); while (it->first != upto_index) { fclose((it->second).first); fclose((it->second).second); std::string log_name, idx_name; FormLogName(it->first, &log_name, &idx_name); remove(log_name.c_str()); remove(idx_name.c_str()); read_log_.erase(it++); } LOG(INFO, "[LogDB] DeleteUpTo done smallest_index_ = %ld next_index_ = %ld", smallest_index_, next_index_); return kOK; } StatusCode LogDB::DeleteFrom(int64_t index) { if (index >= next_index_) { return kOK; } if (index < smallest_index_) { LOG(INFO, "[LogDB] DeleteUpTo over limit index = %ld smallest_index_ = %ld next_index_ = %ld", index, smallest_index_, next_index_); return kBadParameter; } MutexLock lock(&mu_); FileCache::iterator from = read_log_.lower_bound(index); bool need_truncate = index != from->first; for (FileCache::iterator it = from; it != read_log_.end(); ++it) { fclose((it->second).first); fclose((it->second).second); std::string log_name, idx_name; FormLogName(it->first, &log_name, &idx_name); remove(log_name.c_str()); remove(idx_name.c_str()); } CloseCurrent(); // truancate the last log and open it for read read_log_.erase(from, read_log_.end()); if (need_truncate && !read_log_.empty()) { FileCache::reverse_iterator it = read_log_.rbegin(); int offset = 16 * (index - it->first); fseek((it->second).first, offset, SEEK_SET); char buf[16]; int len = fread(buf, 1, 16, (it->second).first); assert(len == 16); int64_t tmp_offset; memcpy(&tmp_offset, buf + 8, 8); fclose((it->second).first); fclose((it->second).second); std::string log_name, idx_name; FormLogName(it->first, &log_name, &idx_name); truncate(log_name.c_str(), tmp_offset); truncate(idx_name.c_str(), offset); (it->second).first = fopen(idx_name.c_str(), "r"); (it->second).second = fopen(log_name.c_str(), "r"); } next_index_ = index; LOG(INFO, "[LogDB] DeleteFrom done smallest_index_ = %ld next_index_ = %ld", smallest_index_, next_index_); return kOK; } bool LogDB::BuildFileCache() { // build log file cache struct dirent *entry = NULL; DIR *dir_ptr = opendir(dbpath_.c_str()); if (dir_ptr == NULL) { LOG(WARNING, "[LogDB] open dir failed %s", dbpath_.c_str()); return false; } bool error = false; while ((entry = readdir(dir_ptr)) != NULL) { size_t idx = std::string(entry->d_name).find(".idx"); if (idx != std::string::npos) { std::string file_name = std::string(entry->d_name); int64_t index = boost::lexical_cast<int64_t>(file_name.substr(0, idx)); std::string log_name, idx_name; FormLogName(index, &log_name, &idx_name); FILE* idx_fp = fopen(idx_name.c_str(), "r"); if (idx_fp == NULL) { LOG(WARNING, "[LogDB] open index file failed %s", file_name.c_str()); error = true; break; } FILE* log_fp = fopen(log_name.c_str(), "r"); if (log_fp == NULL) { LOG(WARNING, "[LogDB] open log file failed %s", file_name.c_str()); fclose(idx_fp); error = true; break; } read_log_[index] = std::make_pair(idx_fp, log_fp); LOG(INFO, "[LogDB] Add file cache %ld to %s ", index, file_name.c_str()); } } closedir(dir_ptr); // check log & idx match, build largest index if (error || !CheckLogIdx()) { LOG(WARNING, "[LogDB] BuildFileCache failed error = %d", error); for (FileCache::iterator it = read_log_.begin(); it != read_log_.end(); ++it) { fclose((it->second).first); fclose((it->second).second); } read_log_.clear(); return false; } return true; } bool LogDB::CheckLogIdx() { if (read_log_.empty()) { if (smallest_index_ == -1) { next_index_ = 0; } else { next_index_ = smallest_index_; } LOG(INFO, "[LogDB] No previous log, next_index_ = %ld ", next_index_); return true; } FileCache::iterator it = read_log_.begin(); if (smallest_index_ < it->first) { LOG(WARNING, "[LogDB] log does not contain smallest_index_ %ld %ld", smallest_index_, it->first); return false; } next_index_ = it->first; bool error = false; for (; it != read_log_.end(); ++it) { if (it->first != next_index_) { LOG(WARNING, "[LogDB] log is not continous, current index %ld ", it->first); return false; } FILE* idx = (it->second).first; FILE* log = (it->second).second; fseek(idx, 0, SEEK_END); int idx_size = ftell(idx); if (idx_size < 16) { LOG(WARNING, "[LogDB] index file too small %ld ", it->first); error = true; break; } int reminder = idx_size % 16; if (reminder != 0) { LOG(INFO, "[LogDB] incomplete index file %ld.idx ", it->first); } fseek(idx, idx_size - 16 - reminder, SEEK_SET); int64_t expect_index = it->first + (idx_size / 16) - 1; int64_t read_index = -1; int64_t offset = -1; StatusCode s = ReadIndex(idx, expect_index, &read_index, &offset); if (s != kOK) { LOG(WARNING, "[LogDB] check index file failed %ld.idx %s", it->first, StatusCode_Name(s).c_str()); return false; } fseek(log, 0, SEEK_END); int log_size = ftell(log); fseek(log, offset, SEEK_SET); int len; int ret = fread(&len, 1, 4, log); if (ret < 4 || (offset + 4 + len > log_size)) { LOG(WARNING, "[LogDB] incomplete log %ld ", it->first); return false; } next_index_ = expect_index + 1; } if (error) { if (++it != read_log_.end()) { return false; } FileCache::reverse_iterator rit = read_log_.rbegin(); fclose((rit->second).first); fclose((rit->second).second); read_log_.erase(rit->first); } LOG(INFO, "[LogDB] Set next_index_ to %ld", next_index_); return true; } bool LogDB::RecoverMarker() { // recover markers FILE* fp = fopen((dbpath_ + "marker.mak").c_str(), "r"); if (fp == NULL) { if (errno == ENOENT) { fp = fopen((dbpath_ + "marker.tmp").c_str(), "r"); } } if (fp == NULL) { LOG(INFO, "[LogDB] No marker to recover"); return errno == ENOENT; } std::string data; while (true) { int ret = ReadOne(fp, &data); if (ret == 0) break; if (ret < 0) { LOG(WARNING, "[LogDB] RecoverMarker failed while reading"); fclose(fp); return false; } MarkerEntry mark; DecodeMarker(data, &mark); markers_[mark.key] = mark.value; } fclose(fp); LOG(INFO, "[LogDB] Recover markers done"); rename((dbpath_ + "marker.tmp").c_str(), (dbpath_ + "marker.mak").c_str()); return true; } void LogDB::WriteMarkerSnapshot() { MutexLock lock(&mu_); FILE* fp = fopen((dbpath_ + "marker.tmp").c_str(), "w"); if (fp == NULL) { LOG(WARNING, "[LogDB] open marker.tmp failed %s", strerror(errno)); return; } std::string data; for (std::map<std::string, std::string>::iterator it = markers_.begin(); it != markers_.end(); ++it) { MarkerEntry marker(it->first, it->second); uint32_t len = 4 + (it->first).length() + 4 + (it->second).length(); data.clear(); data.append(reinterpret_cast<char*>(&len), 4); EncodeMarker(marker, &data); if (fwrite(data.c_str(), 1, data.length(), fp) != data.length() || fflush(fp) != 0) { LOG(WARNING, "[LogDB] write marker.tmp failed %s", strerror(errno)); fclose(fp); return; } } fclose(fp); if (marker_log_) { fclose(marker_log_); marker_log_ = NULL; } rename((dbpath_ + "marker.tmp").c_str(), (dbpath_ + "marker.mak").c_str()); marker_log_ = fopen((dbpath_ + "marker.mak").c_str(), "a"); if (marker_log_ == NULL) { LOG(WARNING, "[LogDB] open marker.mak failed %s", strerror(errno)); return; } LOG(INFO, "[LogDB] WriteMarkerSnapshot done"); thread_pool_->DelayTask(snapshot_interval_, boost::bind(&LogDB::WriteMarkerSnapshot, this)); } void LogDB::CloseCurrent() { if (write_log_) { fclose(write_log_); write_log_ = NULL; } if (write_index_) { fclose(write_index_); write_index_ = NULL; } } int LogDB::ReadOne(FILE* fp, std::string* data) { int len; int ret = fread(&len, 1, 4, fp); if (ret == 0) { return 0; } if (ret != 4) return -1; char* buf = new char[len]; ret = fread(buf, 1, len, fp); if (ret != len) { LOG(WARNING, "Read(%d) return %d", len, ret); delete[] buf; return -1; } data->clear(); data->assign(buf, len); delete[] buf; return len; } StatusCode LogDB::ReadIndex(FILE* fp, int64_t expect_index, int64_t* index, int64_t* offset) { char buf[16]; int ret = fread(buf, 1, 16, fp); if (ret == 0) { return kNsNotFound; } else if (ret != 16) { LOG(WARNING, "[logdb] Read index file error %ld", expect_index); return kReadError; } memcpy(index, buf, 8); memcpy(offset, buf + 8, 8); if (expect_index != *index) { LOG(WARNING, "[LogDB] Index file mismatch %ld ", index); return kReadError; } return kOK; } void LogDB::EncodeMarker(const MarkerEntry& marker, std::string* data) { int klen = (marker.key).length(); int vlen = (marker.value).length(); data->append(reinterpret_cast<char*>(&klen), 4); data->append(marker.key); data->append(reinterpret_cast<char*>(&vlen), 4); data->append(marker.value); } void LogDB::DecodeMarker(const std::string& data, MarkerEntry* marker) { // data = klen + k + vlen + v int klen; memcpy(&klen, &(data[0]), 4); (marker->key).assign(data.substr(4, klen)); int vlen; memcpy(&vlen, &(data[4 + klen]), 4); (marker->value).assign(data.substr(4 + klen + 4, vlen)); } bool LogDB::NewWriteLog(int64_t index) { if (write_log_) fclose(write_log_); if (write_index_) fclose(write_index_); std::string log_name, idx_name; FormLogName(index, &log_name, &idx_name); write_log_ = fopen(log_name.c_str(), "w"); write_index_ = fopen(idx_name.c_str(), "w"); FILE* idx_fp = fopen(idx_name.c_str(), "r"); FILE* log_fp = fopen(log_name.c_str(), "r"); if (!(write_log_ && write_index_ && idx_fp && log_fp)) { if (write_log_) fclose(write_log_); if (write_index_) fclose(write_index_); if (idx_fp) fclose(idx_fp); if (log_fp) fclose(log_fp); LOG(WARNING, "[logdb] open log/idx file failed %ld %s", index, strerror(errno)); return false; } read_log_[index] = std::make_pair(idx_fp, log_fp); return true; } void LogDB::FormLogName(int64_t index, std::string* log_name, std::string* idx_name) { log_name->clear(); log_name->append(dbpath_); log_name->append(common::NumToString(index)); log_name->append(".log"); idx_name->clear(); idx_name->append(dbpath_); idx_name->append(common::NumToString(index)); idx_name->append(".idx"); } } // namespace bfs } // namespace baidu
33.282794
105
0.575472
spiritbrother1
a7a67c688924f90044804c0d16a399b57e7b7da3
2,870
cpp
C++
FdogClient/traywidget.cpp
FdogMain/FdogInstantMessaging
4d2e9a12d90dfc79a90d8367b373df8828578f06
[ "Apache-2.0" ]
35
2021-05-01T13:39:18.000Z
2021-07-19T12:33:51.000Z
FdogClient/traywidget.cpp
BearStar0914/FdogInstantMessaging
4d2e9a12d90dfc79a90d8367b373df8828578f06
[ "Apache-2.0" ]
2
2021-05-05T13:26:22.000Z
2021-07-16T01:39:03.000Z
FdogClient/traywidget.cpp
BearStar0914/FdogInstantMessaging
4d2e9a12d90dfc79a90d8367b373df8828578f06
[ "Apache-2.0" ]
8
2021-06-02T08:02:25.000Z
2021-07-19T06:59:04.000Z
#include "traywidget.h" #include "ui_traywidget.h" #include<QDebug> #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif Traywidget::Traywidget(QString name,QWidget *parent) : QWidget(parent), ui(new Ui::Traywidget) { qDebug()<<"创1"; ui->setupUi(this); this->setWindowFlags(Qt::SplashScreen|Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground); ui->listWidget->setFrameShape(QListWidget::NoFrame); ui->label->setText(name); qDebug()<<"创1"; } Traywidget::~Traywidget() { delete ui; } QString Traywidget::getName() const { return name; } void Traywidget::setName(const QString &value) { name = value; ui->label->setText(name); } void Traywidget::setTrayWidgetItem(QPixmap pixmap,const QString &str,const QString &account) { qDebug()<<"消息1"; QFont font; font.setFamily("Microsoft YaHei"); font.setPointSize(10); //font.setBold(true); font.setStyleStrategy(QFont::PreferAntialias); QHBoxLayout *horLayout = new QHBoxLayout();//水平布局 horLayout->setContentsMargins(0,0,0,0); horLayout->setSpacing(0); QPushButton * btn = new QPushButton(); btn->setIcon(pixmap); QSize btnsize(25,25); btn->setIconSize(btnsize); btn->setFixedSize(26,26); btn->setFlat(true); QLabel * la = new QLabel(" "+str); la->setFont(font); horLayout->addWidget(btn); horLayout->addWidget(la); QWidget * widget = new QWidget(this); widget->setObjectName(account); widget->setLayout(horLayout); QListWidgetItem * Listitem = new QListWidgetItem(ui->listWidget); Listitem->setSizeHint(QSize(270, 26)); //每次改变Item的高度 ui->listWidget->setItemWidget(Listitem,widget); ui->listWidget->setStyleSheet("QListWidget{color:gray;font-size:12px;background:#FAFAFD;}\ QScrollBar{width:0;height:0}"); //ui->listWidget->setFixedSize(270,26*(1)); //ui->listWidget->sortItems(); } void Traywidget::deleteItem() { ui->listWidget->clear(); } void Traywidget::paintEvent(QPaintEvent *e) { Q_UNUSED(e) QPainter painter(this); QPixmap pixmap(":/lib/background.png");//做好的图 qDrawBorderPixmap(&painter, this->rect(), QMargins(0, 0, 0, 0), pixmap); QRect rect(this->rect().x()+8, this->rect().y()+8, this->rect().width()-16, this->rect().height()-16); painter.fillRect(rect, QColor(255, 255, 255)); } void Traywidget::on_listWidget_itemDoubleClicked(QListWidgetItem *item) { //获得信息,包括头像,名字,账号,传给主界面 QWidget * widget = ui->listWidget->itemWidget(item); //从消息池找到正确的消息 emit senddata3(widget->objectName());//获取正确的消息 //删除选中消息 ui->listWidget->removeItemWidget(item); } void Traywidget::on_pushButton_2_clicked()//查看全部 { emit senddata(); } void Traywidget::on_pushButton_clicked()//忽略全部 { emit senddata2(); }
28.137255
110
0.673868
FdogMain
a7a6a89abceae5b06c3353dd51de6c2feaae471f
189
hpp
C++
DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp
99Angelrm/Webots
036ce182aa69f5fbecd358c179ac23fd9a1c91cd
[ "MIT" ]
null
null
null
DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp
99Angelrm/Webots
036ce182aa69f5fbecd358c179ac23fd9a1c91cd
[ "MIT" ]
null
null
null
DARwIn OP/Controllers/ZeroPlayer-Teleoperado/teleoperado.hpp
99Angelrm/Webots
036ce182aa69f5fbecd358c179ac23fd9a1c91cd
[ "MIT" ]
null
null
null
#ifndef TELEOPERADO_HPP #define TELEOPERADO_HPP #include <webots/Robot.hpp> #include "ZeroPlayer.hpp" #define NMOTORS 20 namespace webots { class Joystick; }; void teleoperado(); #endif
17.181818
27
0.772487
99Angelrm
a7a8d47d2a498de74055c2f748b17afe12ad34f7
2,202
cpp
C++
chrgfx/src/coldef.cpp
RyogaMasaki/chrgfx
f70d78b9742546d5f38246621e32c2c834cdaf0b
[ "MIT" ]
9
2019-03-25T19:28:24.000Z
2020-06-08T06:28:09.000Z
chrgfx/src/coldef.cpp
RyogaMasaki/gfx
f70d78b9742546d5f38246621e32c2c834cdaf0b
[ "MIT" ]
1
2019-11-18T12:35:58.000Z
2019-11-18T12:35:58.000Z
chrgfx/src/coldef.cpp
RyogaMasaki/gfx
f70d78b9742546d5f38246621e32c2c834cdaf0b
[ "MIT" ]
2
2019-10-12T08:22:18.000Z
2019-11-17T19:38:09.000Z
#include "coldef.hpp" #include <string> #include <vector> namespace chrgfx { using namespace std; using namespace png; coldef::coldef(string const & id, coldef_type type, bool const big_endian, string const & description) : gfxdef(id, description), m_type(type), m_big_endian(big_endian) { } refcoldef::refcoldef(string const & id, palette const & reftab, bool const big_endian, string const & description) : coldef(id, ref, big_endian, description), m_reftab(reftab) {}; color refcoldef::by_value(ushort index) const { return m_reftab[index]; }; ushort refcoldef::by_color(color rgb) const { size_t idx { 0 }; for(auto & this_color : m_reftab) { if(this_color.red == rgb.red && this_color.green == rgb.green && this_color.blue == rgb.blue) { return idx; } ++idx; } // this could certainly use some tuning, but it mostly works vector<pair<int, int>> distances; distances.reserve(this->m_reftab.size()); int pal_color_iter { 0 }; for(const auto & this_color : this->m_reftab) { int this_distance = (abs(this_color.red - rgb.red)) + (abs(this_color.green - rgb.green)) + (abs(this_color.blue - rgb.blue)); distances.push_back(pair<int, int>(pal_color_iter, this_distance)); ++pal_color_iter; } int dist_check { distances[0].second }; idx = 0; for(const auto & this_entry : distances) { if(get<1>(this_entry) < dist_check) { dist_check = this_entry.second; idx = this_entry.first; } } return idx; }; png::palette const & refcoldef::reftab() const { return m_reftab; } bool coldef::big_endian() const { return m_big_endian; }; coldef_type coldef::type() const { return m_type; } rgbcoldef::rgbcoldef(string const & id, ushort const bitdepth, vector<rgb_layout> const & layout, bool const big_endian, string const & description) : coldef(id, rgb, big_endian, description), m_bitdepth(bitdepth), m_layout(layout) {}; vector<rgb_layout> const & rgbcoldef::layout() const { return m_layout; }; rgb_layout const & rgbcoldef::rgb_pass(ushort pass) const { return m_layout[pass]; } ushort rgbcoldef::bitdepth() const { return m_bitdepth; }; } // namespace chrgfx
21.173077
74
0.686194
RyogaMasaki
a7a9aba9e9b818cd099105375a2fdeb4e198523d
271
cpp
C++
Project/PepEngine/BurgerTime/SprayLeftCommand.cpp
PepijnVerhaert/PepEngine
5a5dd4d78d8217d7109c2ea6990563ef583a0be4
[ "MIT" ]
null
null
null
Project/PepEngine/BurgerTime/SprayLeftCommand.cpp
PepijnVerhaert/PepEngine
5a5dd4d78d8217d7109c2ea6990563ef583a0be4
[ "MIT" ]
null
null
null
Project/PepEngine/BurgerTime/SprayLeftCommand.cpp
PepijnVerhaert/PepEngine
5a5dd4d78d8217d7109c2ea6990563ef583a0be4
[ "MIT" ]
null
null
null
#include "SprayLeftCommand.h" #include "Object.h" #include "SprayPepperComponent.h" SprayLeftCommand::SprayLeftCommand(pep::Object* pObject) :BaseCommand(pObject) { } void SprayLeftCommand::Execute() { GetActor()->GetComponent<SprayPepperComponent>()->SprayLeft(); }
19.357143
63
0.767528
PepijnVerhaert
a7aa64bbaaf81a50ce5187a54103f8fd0321ca40
10,319
cpp
C++
src/nyx/features/glszm.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
1
2021-09-09T18:57:23.000Z
2021-09-09T18:57:23.000Z
src/nyx/features/glszm.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
null
null
null
src/nyx/features/glszm.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
1
2021-09-17T14:51:21.000Z
2021-09-17T14:51:21.000Z
#include <algorithm> #include <iostream> #include <iomanip> #include <sstream> #include <unordered_set> #include "glszm.h" GLSZM_features::GLSZM_features (int minI, int maxI, const ImageMatrix& im) { //==== Check if the ROI is degenerate (equal intensity) if (minI == maxI) { bad_roi_data = true; return; } //==== Make a list of intensity clusters (zones) using ACluster = std::pair<PixIntens, int>; std::vector<ACluster> Z; //==== While scanning clusters, learn unique intensities std::unordered_set<PixIntens> U; int maxZoneArea = 0; // Copy the image matrix auto M = im; pixData& D = M.WriteablePixels(); //M.print("initial\n"); // Number of zones const int VISITED = -1; for (int row=0; row<M.height; row++) for (int col = 0; col < M.width; col++) { // Find a non-blank pixel auto pi = D(row, col); if (pi == 0 || int(pi)==VISITED) continue; // Found a gray pixel. Find same-intensity neighbourhood of it. std::vector<std::tuple<int, int>> history; int x = col, y = row; int zoneArea = 1; D(y,x) = VISITED; // for(;;) { if (D.safe(y,x+1) && D(y,x+1) == pi) { D(y,x+1) = VISITED; zoneArea++; //M.print("After x+1,y"); // Remember this pixel history.push_back({x,y}); // Advance x = x + 1; // Proceed continue; } if (D.safe(y + 1, x + 1) && D(y + 1, x+1) == pi) { D(y + 1, x+1) = VISITED; zoneArea++; //M.print("After x+1,y+1"); history.push_back({ x,y }); x = x + 1; y = y + 1; continue; } if (D.safe(y + 1, x) && D(y + 1, x) == pi) { D(y + 1, x) = VISITED; zoneArea++; //M.print("After x,y+1"); history.push_back({ x,y }); y = y + 1; continue; } if (D.safe(y + 1, x - 1) && D(y + 1, x-1) == pi) { D(y + 1, x-1) = VISITED; zoneArea++; //M.print("After x-1,y+1"); history.push_back({ x,y }); x = x - 1; y = y + 1; continue; } // Return from the branch if (history.size() > 0) { // Recollect the coordinate where we diverted from std::tuple<int, int> prev = history[history.size() - 1]; history.pop_back(); } // We are done exploring this cluster break; } // Done scanning a cluster. Perform 3 actions: // --1 U.insert(pi); // --2 maxZoneArea = std::max(maxZoneArea, zoneArea); //std::stringstream ss; //ss << "End of cluster " << x << "," << y; //M.print (ss.str()); // --3 ACluster clu = {pi, zoneArea}; Z.push_back (clu); } //M.print("finished"); //==== Fill the SZ-matrix Ng = (decltype(Ng)) U.size(); Ns = maxZoneArea; Nz = (decltype(Nz)) Z.size(); Np = 1; // --Set to vector to be able to know each intensity's index std::vector<PixIntens> I (U.begin(), U.end()); std::sort (I.begin(), I.end()); // Optional // --allocate the matrix P.allocate (Ns, Ng); // --iterate zones and fill the matrix for (auto& z : Z) { // row auto iter = std::find(I.begin(), I.end(), z.first); int row = int (iter - I.begin()); // col int col = z.second - 1; // 0-based => -1 auto & k = P(col, row); k++; } } // 1. Small Area Emphasis double GLSZM_features::calc_SAE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i=1; i<=Ng; i++) { for (int j = 1; j <= Ns; j++) { f += P.matlab(i,j) / (j * j); } } double retval = f / double(Nz); return retval; } // 2. Large Area Emphasis double GLSZM_features::calc_LAE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { f += P.matlab(i, j) * double (j * j); } } double retval = f / double(Nz); return retval; } // 3. Gray Level Non - Uniformity double GLSZM_features::calc_GLN() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { double sum = 0.0; for (int j = 1; j <= Ns; j++) { sum += P.matlab(i,j); } f += sum * sum; } double retval = f / double(Nz); return retval; } // 4. Gray Level Non - Uniformity Normalized double GLSZM_features::calc_GLNN() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { double sum = 0.0; for (int j = 1; j <= Ns; j++) { sum += P.matlab(i,j); } f += sum * sum; } double retval = f / double(Nz * Nz); return retval; } // 5. Size - Zone Non - Uniformity double GLSZM_features::calc_SZN() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ns; i++) { double sum = 0.0; for (int j = 1; j <= Ng; j++) { sum += P.matlab(j,i); } f += sum * sum; } double retval = f / double(Nz); return retval; } // 6. Size - Zone Non - Uniformity Normalized double GLSZM_features::calc_SZNN() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ns; i++) { double sum = 0.0; for (int j = 1; j <= Ng; j++) { sum += P.matlab(j,i); } f += sum * sum; } double retval = f / double(Nz * Nz); return retval; } // 7. Zone Percentage double GLSZM_features::calc_ZP() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double retval = double(Nz) / double(Np); return retval; } // 8. Gray Level Variance double GLSZM_features::calc_GLV() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double mu = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { mu += P.matlab(i, j) * i; } } double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { double mu2 = (i - mu) * (i - mu); f += P.matlab(i,j) * mu2; } } return f; } // 9. Zone Variance double GLSZM_features::calc_ZV() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double mu = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { mu += P.matlab(i,j) * double(j); } } double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { double mu2 = (j - mu) * (j - mu); f += P.matlab(i, j) * mu2; } } return f; } // 10. Zone Entropy double GLSZM_features::calc_ZE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { double entrTerm = log2(P.matlab(i,j) + EPS); f += P.matlab(i,j) * entrTerm; } } double retval = -f; return retval; } // 11. Low Gray Level Zone Emphasis double GLSZM_features::calc_LGLZE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { f += P.matlab(i,j) / double(i*i); } } double retval = f / double(Nz); return retval; } // 12. High Gray Level Zone Emphasis double GLSZM_features::calc_HGLZE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j <= Ns; j++) { f += P.matlab(i,j) * double(i*i); } } double retval = f / double(Nz); return retval; } // 13. Small Area Low Gray Level Emphasis double GLSZM_features::calc_SALGLE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i <= Ng; i++) { for (int j = 1; j < Ns; j++) { f += P.matlab(i,j) / double(i * i * j * j); } } double retval = f / double(Nz); return retval; } // 14. Small Area High Gray Level Emphasis double GLSZM_features::calc_SAHGLE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i < Ng; i++) { for (int j = 1; j < Ns; j++) { f += P.matlab(i,j) * double(i * i) / double(j * j); } } double retval = f / double(Nz); return retval; } // 15. Large Area Low Gray Level Emphasis double GLSZM_features::calc_LALGLE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i < Ng; i++) { for (int j = 1; j < Ns; j++) { f += P.matlab(i,j) * double(j * j) / double(i * i); } } double retval = f / double(Nz); return retval; } // 16. Large Area High Gray Level Emphasis double GLSZM_features::calc_LAHGLE() { // Prevent using bad data if (bad_roi_data) return BAD_ROI_FVAL; double f = 0.0; for (int i = 1; i < Ng; i++) { for (int j = 1; j < Ns; j++) { f += P.matlab(i,j) * double(i * i * j * j); } } double retval = f / double(Nz); return retval; } void GLSZM_features::reduce (size_t start, size_t end, std::vector<int>* ptrLabels, std::unordered_map <int, LR>* ptrLabelData) { for (auto i = start; i < end; i++) { int lab = (*ptrLabels)[i]; LR& r = (*ptrLabelData)[lab]; if (r.has_bad_data()) continue; GLSZM_features glszm ((int)r.fvals[MIN][0], (int)r.fvals[MAX][0], r.aux_image_matrix); r.fvals[GLSZM_SAE][0] = glszm.calc_SAE(); r.fvals[GLSZM_LAE][0] = glszm.calc_LAE(); r.fvals[GLSZM_GLN][0] = glszm.calc_GLN(); r.fvals[GLSZM_GLNN][0] = glszm.calc_GLNN(); r.fvals[GLSZM_SZN][0] = glszm.calc_SZN(); r.fvals[GLSZM_SZNN][0] = glszm.calc_SZNN(); r.fvals[GLSZM_ZP][0] = glszm.calc_ZP(); r.fvals[GLSZM_GLV][0] = glszm.calc_GLV(); r.fvals[GLSZM_ZV][0] = glszm.calc_ZV(); r.fvals[GLSZM_ZE][0] = glszm.calc_ZE(); r.fvals[GLSZM_LGLZE][0] = glszm.calc_LGLZE(); r.fvals[GLSZM_HGLZE][0] = glszm.calc_HGLZE(); r.fvals[GLSZM_SALGLE][0] = glszm.calc_SALGLE(); r.fvals[GLSZM_SAHGLE][0] = glszm.calc_SAHGLE(); r.fvals[GLSZM_LALGLE][0] = glszm.calc_LALGLE(); r.fvals[GLSZM_LAHGLE][0] = glszm.calc_LAHGLE(); } }
20.075875
128
0.538424
friskluft
a7aaf8cfe05a5bd0598bed7b56a8e10879f1d88a
1,718
cpp
C++
tests/gl.cpp
Toefinder/gepetto-viewer
5163a81991dafed7dda7a4268baa3512f2cedb78
[ "BSD-2-Clause" ]
18
2019-02-09T08:38:36.000Z
2022-02-19T13:22:04.000Z
tests/gl.cpp
Toefinder/gepetto-viewer
5163a81991dafed7dda7a4268baa3512f2cedb78
[ "BSD-2-Clause" ]
67
2018-10-12T13:52:04.000Z
2022-03-16T11:25:06.000Z
tests/gl.cpp
Toefinder/gepetto-viewer
5163a81991dafed7dda7a4268baa3512f2cedb78
[ "BSD-2-Clause" ]
8
2019-05-06T11:14:43.000Z
2022-02-07T15:32:28.000Z
#include <iostream> #include <stdio.h> #ifdef _WIN32 #include <Windows.h> #endif #include <osgViewer/Viewer> #include <osg/GLExtensions> const int OSG_WIDTH = 1024; const int OSG_HEIGHT = 960; class TestSupportOperation : public osg::GraphicsOperation { public: TestSupportOperation() : osg::Referenced(true) , osg::GraphicsOperation("TestSupportOperation", false) , m_supported(true) , m_errorMsg() , m_version(1.3) {} virtual void operator() (osg::GraphicsContext* gc) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(m_mutex); osg::GLExtensions* gl2ext = gc->getState()->get<osg::GLExtensions>(); if( gl2ext ){ if( !gl2ext->isGlslSupported ) { m_supported = false; m_errorMsg = "ERROR: GLSL not supported by OpenGL driver."; } else m_version = gl2ext->glVersion; } else{ m_supported = false; m_errorMsg = "ERROR: GLSL not supported."; } } OpenThreads::Mutex m_mutex; bool m_supported; std::string m_errorMsg; float m_version; }; int main(int, char**) { #ifdef _WIN32 ::SetProcessDPIAware(); #endif osgViewer::Viewer viewer; viewer.setUpViewInWindow(100,100,OSG_WIDTH, OSG_HEIGHT); // openGL version: osg::ref_ptr<TestSupportOperation> so = new TestSupportOperation; viewer.setRealizeOperation(so.get()); viewer.realize(); if (so->m_supported) std::cout << "GLVersion=" << so->m_version << std::endl; else std::cout << so->m_errorMsg << std::endl; return viewer.run(); }
23.534247
77
0.593714
Toefinder
a7ae15693e9bc0122946b48378b626aa7d294575
6,346
cpp
C++
src/slib/ui/ui_event_android.cpp
emarc99/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
146
2017-03-21T07:50:43.000Z
2022-03-19T03:32:22.000Z
src/slib/ui/ui_event_android.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
50
2017-03-22T04:08:15.000Z
2019-10-21T16:55:48.000Z
src/slib/ui/ui_event_android.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
55
2017-03-21T07:52:58.000Z
2021-12-27T13:02:08.000Z
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/core/definition.h" #if defined(SLIB_UI_IS_ANDROID) #include "slib/ui/event.h" #include "slib/ui/core.h" #include "slib/ui/platform.h" #include "slib/core/hash_table.h" #include "slib/core/safe_static.h" #include "slib/core/platform_android.h" namespace slib { namespace priv { namespace ui_event { class KeyMapper { private: HashTable<sl_uint32, sl_uint32> mapKeyToVK; HashTable<sl_uint32, sl_uint32> mapVKToKey; public: KeyMapper() { map(Keycode::Tab, 61); map(Keycode::Enter, 66); map(Keycode::Escape, 111); map(Keycode::Space, 62); map(Keycode::Grave, 68); map(Keycode::Equal, 70); map(Keycode::Semicolon, 74); map(Keycode::Backslash, 73); map(Keycode::LeftBaracket, 71); map(Keycode::RightBaracket, 72); map(Keycode::Quote, 75); map(Keycode::Comma, 55); map(Keycode::Minus, 69); map(Keycode::Period, 56); map(Keycode::Divide, 76); map(Keycode::Num0, 7); map(Keycode::Num1, 8); map(Keycode::Num2, 9); map(Keycode::Num3, 10); map(Keycode::Num4, 11); map(Keycode::Num5, 12); map(Keycode::Num6, 13); map(Keycode::Num7, 14); map(Keycode::Num8, 15); map(Keycode::Num9, 16); map(Keycode::A, 29); map(Keycode::B, 30); map(Keycode::C, 31); map(Keycode::D, 32); map(Keycode::E, 33); map(Keycode::F, 34); map(Keycode::G, 35); map(Keycode::H, 36); map(Keycode::I, 37); map(Keycode::J, 38); map(Keycode::K, 39); map(Keycode::L, 40); map(Keycode::M, 41); map(Keycode::N, 42); map(Keycode::O, 43); map(Keycode::P, 44); map(Keycode::Q, 45); map(Keycode::R, 46); map(Keycode::S, 47); map(Keycode::T, 48); map(Keycode::U, 49); map(Keycode::V, 50); map(Keycode::W, 51); map(Keycode::X, 52); map(Keycode::Y, 53); map(Keycode::Z, 54); map(Keycode::Numpad0, 144); map(Keycode::Numpad1, 145); map(Keycode::Numpad2, 146); map(Keycode::Numpad3, 147); map(Keycode::Numpad4, 148); map(Keycode::Numpad5, 149); map(Keycode::Numpad6, 150); map(Keycode::Numpad7, 151); map(Keycode::Numpad8, 152); map(Keycode::Numpad9, 153); map(Keycode::NumpadDivide, 154); map(Keycode::NumpadMultiply, 155); map(Keycode::NumpadMinus, 156); map(Keycode::NumpadPlus, 157); map(Keycode::NumpadEnter, 160); map(Keycode::NumpadDecimal, 158); map(Keycode::F1, 131); map(Keycode::F2, 132); map(Keycode::F3, 133); map(Keycode::F4, 134); map(Keycode::F5, 135); map(Keycode::F6, 136); map(Keycode::F7, 137); map(Keycode::F8, 138); map(Keycode::F9, 139); map(Keycode::F10, 140); map(Keycode::F11, 141); map(Keycode::F12, 142); map(Keycode::Backspace, 67); map(Keycode::PageUp, 92); map(Keycode::PageDown, 93); map(Keycode::Home, 122); map(Keycode::End, 123); map(Keycode::Left, 21); map(Keycode::Up, 19); map(Keycode::Right, 22); map(Keycode::Down, 20); map(Keycode::PrintScreen, 120); map(Keycode::Insert, 124); map(Keycode::Delete, 112); map(Keycode::Sleep, -1); map(Keycode::Pause, 121); map(Keycode::GoHome, -1); map(Keycode::GoMenu, 82); map(Keycode::GoBack, 4); map(Keycode::Camera, 27); map(Keycode::VolumeMute, 164); map(Keycode::VolumeDown, 25); map(Keycode::VolumeUp, 24); map(Keycode::MediaPrev, 88); map(Keycode::MediaNext, 87); map(Keycode::MediaPause, 85); map(Keycode::MediaStop, 86); map(Keycode::PhoneStar, 17); map(Keycode::PhonePound, 18); map(Keycode::LeftShift, 59); map(Keycode::RightShift, 60); map(Keycode::LeftControl, 113); map(Keycode::RightControl, 114); map(Keycode::LeftAlt, 57); map(Keycode::RightAlt, 58); map(Keycode::LeftWin, 117); map(Keycode::RightWin, 118); map(Keycode::CapsLock, 115); map(Keycode::ScrollLock, 116); map(Keycode::NumLock, 143); map(Keycode::ContextMenu, -1); } public: void map(Keycode key, sl_uint32 vk) { if (vk == -1) { return; } mapKeyToVK.put((int)key, vk); mapVKToKey.put(vk, (int)key); } Keycode vkToKey(sl_uint32 vk) { sl_uint32 ret; if (mapVKToKey.get(vk, &ret)) { return (Keycode)ret; } else { return Keycode::Unknown; } } sl_uint32 keyToVk(Keycode code) { sl_uint32 ret; if (mapKeyToVK.get((int)code, &ret)) { return ret; } else { return -1; } } }; SLIB_SAFE_STATIC_GETTER(KeyMapper, GetKeyMapper) } } using namespace priv::ui_event; sl_uint32 UIEvent::getSystemKeycode(Keycode key) { KeyMapper* mapper = GetKeyMapper(); if (mapper) { return mapper->keyToVk(key); } return 0; } Keycode UIEvent::getKeycodeFromSystemKeycode(sl_uint32 vkey) { KeyMapper* mapper = GetKeyMapper(); if (mapper) { return mapper->vkToKey(vkey); } return Keycode::Unknown; } } #endif
26.33195
82
0.611409
emarc99
a7af02e6b2cfe87ab1a312ae4641903284386902
14,084
hpp
C++
include/System/Runtime/Remoting/Lifetime/Lease.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/System/Runtime/Remoting/Lifetime/Lease.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/System/Runtime/Remoting/Lifetime/Lease.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.MarshalByRefObject #include "System/MarshalByRefObject.hpp" // Including type: System.Runtime.Remoting.Lifetime.ILease #include "System/Runtime/Remoting/Lifetime/ILease.hpp" // Including type: System.DateTime #include "System/DateTime.hpp" // Including type: System.Runtime.Remoting.Lifetime.LeaseState #include "System/Runtime/Remoting/Lifetime/LeaseState.hpp" // Including type: System.TimeSpan #include "System/TimeSpan.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Remoting::Lifetime namespace System::Runtime::Remoting::Lifetime { // Forward declaring type: ISponsor class ISponsor; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: ArrayList class ArrayList; // Forward declaring type: Queue class Queue; } // Completed forward declares // Type namespace: System.Runtime.Remoting.Lifetime namespace System::Runtime::Remoting::Lifetime { // Forward declaring type: Lease class Lease; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(System::Runtime::Remoting::Lifetime::Lease); DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Remoting::Lifetime::Lease*, "System.Runtime.Remoting.Lifetime", "Lease"); // Type namespace: System.Runtime.Remoting.Lifetime namespace System::Runtime::Remoting::Lifetime { // Size: 0x58 #pragma pack(push, 1) // Autogenerated type: System.Runtime.Remoting.Lifetime.Lease // [TokenAttribute] Offset: FFFFFFFF class Lease : public System::MarshalByRefObject/*, public System::Runtime::Remoting::Lifetime::ILease*/ { public: // Nested type: System::Runtime::Remoting::Lifetime::Lease::RenewalDelegate class RenewalDelegate; #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private System.DateTime _leaseExpireTime // Size: 0x8 // Offset: 0x18 System::DateTime leaseExpireTime; // Field size check static_assert(sizeof(System::DateTime) == 0x8); // private System.Runtime.Remoting.Lifetime.LeaseState _currentState // Size: 0x4 // Offset: 0x20 System::Runtime::Remoting::Lifetime::LeaseState currentState; // Field size check static_assert(sizeof(System::Runtime::Remoting::Lifetime::LeaseState) == 0x4); // Padding between fields: currentState and: initialLeaseTime char __padding1[0x4] = {}; // private System.TimeSpan _initialLeaseTime // Size: 0x8 // Offset: 0x28 System::TimeSpan initialLeaseTime; // Field size check static_assert(sizeof(System::TimeSpan) == 0x8); // private System.TimeSpan _renewOnCallTime // Size: 0x8 // Offset: 0x30 System::TimeSpan renewOnCallTime; // Field size check static_assert(sizeof(System::TimeSpan) == 0x8); // private System.TimeSpan _sponsorshipTimeout // Size: 0x8 // Offset: 0x38 System::TimeSpan sponsorshipTimeout; // Field size check static_assert(sizeof(System::TimeSpan) == 0x8); // private System.Collections.ArrayList _sponsors // Size: 0x8 // Offset: 0x40 System::Collections::ArrayList* sponsors; // Field size check static_assert(sizeof(System::Collections::ArrayList*) == 0x8); // private System.Collections.Queue _renewingSponsors // Size: 0x8 // Offset: 0x48 System::Collections::Queue* renewingSponsors; // Field size check static_assert(sizeof(System::Collections::Queue*) == 0x8); // private System.Runtime.Remoting.Lifetime.Lease/System.Runtime.Remoting.Lifetime.RenewalDelegate _renewalDelegate // Size: 0x8 // Offset: 0x50 System::Runtime::Remoting::Lifetime::Lease::RenewalDelegate* renewalDelegate; // Field size check static_assert(sizeof(System::Runtime::Remoting::Lifetime::Lease::RenewalDelegate*) == 0x8); public: // Creating interface conversion operator: operator System::Runtime::Remoting::Lifetime::ILease operator System::Runtime::Remoting::Lifetime::ILease() noexcept { return *reinterpret_cast<System::Runtime::Remoting::Lifetime::ILease*>(this); } // Deleting conversion operator: operator ::Il2CppObject* constexpr operator ::Il2CppObject*() const noexcept = delete; // Get instance field reference: private System.DateTime _leaseExpireTime System::DateTime& dyn__leaseExpireTime(); // Get instance field reference: private System.Runtime.Remoting.Lifetime.LeaseState _currentState System::Runtime::Remoting::Lifetime::LeaseState& dyn__currentState(); // Get instance field reference: private System.TimeSpan _initialLeaseTime System::TimeSpan& dyn__initialLeaseTime(); // Get instance field reference: private System.TimeSpan _renewOnCallTime System::TimeSpan& dyn__renewOnCallTime(); // Get instance field reference: private System.TimeSpan _sponsorshipTimeout System::TimeSpan& dyn__sponsorshipTimeout(); // Get instance field reference: private System.Collections.ArrayList _sponsors System::Collections::ArrayList*& dyn__sponsors(); // Get instance field reference: private System.Collections.Queue _renewingSponsors System::Collections::Queue*& dyn__renewingSponsors(); // Get instance field reference: private System.Runtime.Remoting.Lifetime.Lease/System.Runtime.Remoting.Lifetime.RenewalDelegate _renewalDelegate System::Runtime::Remoting::Lifetime::Lease::RenewalDelegate*& dyn__renewalDelegate(); // public System.TimeSpan get_CurrentLeaseTime() // Offset: 0x1BF3490 System::TimeSpan get_CurrentLeaseTime(); // public System.Runtime.Remoting.Lifetime.LeaseState get_CurrentState() // Offset: 0x1BF3508 System::Runtime::Remoting::Lifetime::LeaseState get_CurrentState(); // public System.TimeSpan get_RenewOnCallTime() // Offset: 0x1BF351C System::TimeSpan get_RenewOnCallTime(); // public System.Void Activate() // Offset: 0x1BF3510 void Activate(); // public System.TimeSpan Renew(System.TimeSpan renewalTime) // Offset: 0x1BF3524 System::TimeSpan Renew(System::TimeSpan renewalTime); // public System.Void Unregister(System.Runtime.Remoting.Lifetime.ISponsor obj) // Offset: 0x1BF35C0 void Unregister(System::Runtime::Remoting::Lifetime::ISponsor* obj); // System.Void UpdateState() // Offset: 0x1BF36D0 void UpdateState(); // private System.Void CheckNextSponsor() // Offset: 0x1BF381C void CheckNextSponsor(); // private System.Void ProcessSponsorResponse(System.Object state, System.Boolean timedOut) // Offset: 0x1BF3A80 void ProcessSponsorResponse(::Il2CppObject* state, bool timedOut); // public System.Void .ctor() // Offset: 0x1BF32F8 // Implemented from: System.MarshalByRefObject // Base method: System.Void MarshalByRefObject::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Lease* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::Remoting::Lifetime::Lease::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Lease*, creationType>())); } }; // System.Runtime.Remoting.Lifetime.Lease #pragma pack(pop) static check_size<sizeof(Lease), 80 + sizeof(System::Runtime::Remoting::Lifetime::Lease::RenewalDelegate*)> __System_Runtime_Remoting_Lifetime_LeaseSizeCheck; static_assert(sizeof(Lease) == 0x58); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::get_CurrentLeaseTime // Il2CppName: get_CurrentLeaseTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::TimeSpan (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::get_CurrentLeaseTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "get_CurrentLeaseTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::get_CurrentState // Il2CppName: get_CurrentState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Runtime::Remoting::Lifetime::LeaseState (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::get_CurrentState)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "get_CurrentState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::get_RenewOnCallTime // Il2CppName: get_RenewOnCallTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::TimeSpan (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::get_RenewOnCallTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "get_RenewOnCallTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::Activate // Il2CppName: Activate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::Activate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "Activate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::Renew // Il2CppName: Renew template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::TimeSpan (System::Runtime::Remoting::Lifetime::Lease::*)(System::TimeSpan)>(&System::Runtime::Remoting::Lifetime::Lease::Renew)> { static const MethodInfo* get() { static auto* renewalTime = &::il2cpp_utils::GetClassFromName("System", "TimeSpan")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "Renew", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{renewalTime}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::Unregister // Il2CppName: Unregister template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Lifetime::Lease::*)(System::Runtime::Remoting::Lifetime::ISponsor*)>(&System::Runtime::Remoting::Lifetime::Lease::Unregister)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System.Runtime.Remoting.Lifetime", "ISponsor")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "Unregister", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::UpdateState // Il2CppName: UpdateState template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::UpdateState)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "UpdateState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::CheckNextSponsor // Il2CppName: CheckNextSponsor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Lifetime::Lease::*)()>(&System::Runtime::Remoting::Lifetime::Lease::CheckNextSponsor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "CheckNextSponsor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::ProcessSponsorResponse // Il2CppName: ProcessSponsorResponse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Lifetime::Lease::*)(::Il2CppObject*, bool)>(&System::Runtime::Remoting::Lifetime::Lease::ProcessSponsorResponse)> { static const MethodInfo* get() { static auto* state = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* timedOut = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Lifetime::Lease*), "ProcessSponsorResponse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state, timedOut}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::Lifetime::Lease::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
55.015625
234
0.726356
sc2ad
a7b379cfc8620d65fdd839931aee24c75dbd2c9e
2,817
cpp
C++
test/selene/img/interop/ImageToDynImage.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
284
2017-11-20T08:23:54.000Z
2022-03-30T12:52:00.000Z
test/selene/img/interop/ImageToDynImage.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
9
2018-02-14T08:21:41.000Z
2021-07-27T19:52:12.000Z
test/selene/img/interop/ImageToDynImage.cpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
17
2018-03-10T00:01:36.000Z
2021-06-29T10:44:27.000Z
// This file is part of the `Selene` library. // Copyright 2017-2019 Michael Hofmann (https://github.com/kmhofmann). // Distributed under MIT license. See accompanying LICENSE file in the top-level directory. #include <catch2/catch.hpp> #include <selene/img/interop/ImageToDynImage.hpp> #include <selene/img/pixel/PixelTypeAliases.hpp> #include <selene/img/typed/ImageTypeAliases.hpp> using namespace sln::literals; namespace { template <typename PixelType> struct PixelProducer; template <typename T> struct PixelProducer<sln::Pixel<T, 1>> { static sln::Pixel<T, 1> get(sln::PixelIndex x, sln::PixelIndex y) { return sln::Pixel<T, 1>(x + y); } }; template <typename T> struct PixelProducer<sln::Pixel<T, 2>> { static sln::Pixel<T, 2> get(sln::PixelIndex x, sln::PixelIndex y) { return sln::Pixel<T, 2>(x + y, 2 * x + y); } }; template <typename T> struct PixelProducer<sln::Pixel<T, 3>> { static sln::Pixel<T, 3> get(sln::PixelIndex x, sln::PixelIndex y) { return sln::Pixel<T, 3>(x + y, 2 * x + y, x + 2 * y); } }; template <typename T> struct PixelProducer<sln::Pixel<T, 4>> { static sln::Pixel<T, 4> get(sln::PixelIndex x, sln::PixelIndex y) { return sln::Pixel<T, 4>(x + y, 2 * x + y, x + 2 * y, 2 * x + 2 * y); } }; template <typename PixelType> sln::Image<PixelType> create_test_image(sln::PixelLength width, sln::PixelLength height) { sln::Image<PixelType> img({width, height}); for (auto y = 0_idx; y < img.height(); ++y) { for (auto x = 0_idx; x < img.width(); ++x) { img(x, y) = PixelProducer<PixelType>::get(x, y); } } return img; } template <typename PixelType> void test_image(sln::PixelLength width, sln::PixelLength height) { auto img = create_test_image<PixelType>(width, height); auto img_data_view = sln::to_dyn_image_view(img, sln::PixelFormat::Unknown); REQUIRE(img_data_view.width() == width); REQUIRE(img_data_view.height() == height); REQUIRE(img_data_view.is_packed()); REQUIRE(img_data_view.is_valid()); // TODO: Content tests // ... auto img_data = sln::to_dyn_image(std::move(img), sln::PixelFormat::Unknown); REQUIRE(img_data.width() == width); REQUIRE(img_data.height() == height); REQUIRE(img_data.is_packed()); REQUIRE(img_data.is_valid()); // TODO: Content tests // ... } } // namespace TEST_CASE("Typed image to dynamic image", "[img]") { { sln::Image_8u1 img; sln::DynImage<> dyn_img; REQUIRE_THROWS(dyn_img = sln::to_dyn_image(std::move(img), sln::PixelFormat::Unknown)); } for (auto w = 1_px; w < 32_px; w += 1_px) { for (auto h = 1_px; h < 32_px; h += 1_px) { test_image<sln::Pixel_8u1>(w, h); test_image<sln::Pixel_8u2>(w, h); test_image<sln::Pixel_8u3>(w, h); test_image<sln::Pixel_8u4>(w, h); } } }
24.495652
91
0.652467
kmhofmann
a7b3a6eb2aa64050eedeabf66a27382e43ac24cc
28,004
cpp
C++
test/test.cpp
AmonShokhinAhmed/TattleTale
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
[ "MIT" ]
1
2022-03-22T16:17:45.000Z
2022-03-22T16:17:45.000Z
test/test.cpp
AmonShokhinAhmed/TattleTale
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
[ "MIT" ]
88
2022-01-31T09:16:19.000Z
2022-03-29T19:30:50.000Z
test/test.cpp
AmonShokhinAhmed/TattleTale
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <iostream> #include <vector> #include <list> #include <algorithm> #include <memory> #include "tale/tale.hpp" #include <time.h> #define GTEST_INFO std::cout << "[ INFO ] " using namespace tattletale; TEST(TaleKernels, IncreasingKernelId) { Random random; Chronicle chronicle(random); std::vector<Kernel *> no_reasons; size_t tick = 0; Setting setting; setting.actor_count = 0; setting.days_to_simulate = 0; School school(chronicle, random, setting); chronicle.Reset(); Actor *actor = chronicle.CreateActor(school, "John", "Doe"); Emotion *emotion = chronicle.CreateEmotion(EmotionType::kHappy, tick, actor, no_reasons, 1); Goal *goal = chronicle.CreateGoal(Goal::GetRandomGoalType(random), tick, actor, no_reasons); Relationship *relationship = chronicle.CreateRelationship(RelationshipType::kLove, tick, actor, actor, no_reasons, 1); Resource *wealth = chronicle.CreateResource("wealth", "wealthy", "poor", tick, actor, no_reasons, 1); EXPECT_EQ(0, emotion->id_); EXPECT_EQ(1, goal->id_); EXPECT_EQ(2, relationship->id_); EXPECT_EQ(3, wealth->id_); } class TaleCreateAndRunSchool : public ::testing::Test { protected: TaleCreateAndRunSchool() {} virtual ~TaleCreateAndRunSchool() {} void SetUp(const Setting &setting) { Random random; Chronicle chronicle(random); School school(chronicle, random, setting); for (size_t i = 0; i < setting.actor_count; ++i) { EXPECT_EQ(school.GetActor(i)->id_, i); } for (size_t i = 0; i < setting.course_count(); ++i) { EXPECT_EQ(school.GetCourse(i).id_, i); } school.SimulateDays(setting.days_to_simulate); } virtual void TearDown() {} }; TEST_F(TaleCreateAndRunSchool, CreateAndRunDefaultSchool) { Setting setting; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroActors) { Setting setting; setting.actor_count = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroActorsPerCourse) { Setting setting; setting.actors_per_course = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroCoursesPerDay) { Setting setting; setting.courses_per_day = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroSameCoursesPerWeek) { Setting setting; setting.same_course_per_week = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroFreetimeActorCount) { Setting setting; setting.freetime_actor_count = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithZeroInAllSettings) { Setting setting; setting.actor_count = 0; setting.actors_per_course = 0; setting.courses_per_day = 0; setting.same_course_per_week = 0; setting.freetime_actor_count = 0; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneActor) { Setting setting; setting.actor_count = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneActorPerCourse) { Setting setting; setting.actors_per_course = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneCoursePerDay) { Setting setting; setting.courses_per_day = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneFreetimeActorCount) { Setting setting; setting.freetime_actor_count = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneSameCoursePerWeek) { Setting setting; setting.same_course_per_week = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithOneInAllSettings) { Setting setting; setting.actor_count = 1; setting.actors_per_course = 1; setting.courses_per_day = 1; setting.same_course_per_week = 1; setting.freetime_actor_count = 1; SetUp(setting); } TEST_F(TaleCreateAndRunSchool, CreateAndRunSchoolWithRandomValuesInAllSettings) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); Setting setting; setting.actor_count = random.GetUInt(0, 1000); setting.actors_per_course = random.GetUInt(0, 50); setting.courses_per_day = random.GetUInt(0, 10); setting.same_course_per_week = random.GetUInt(0, 10); setting.days_to_simulate = random.GetUInt(0, 50); setting.freetime_actor_count = random.GetUInt(0, 30); GTEST_INFO << "Actor Count = " << setting.actor_count << std::endl; GTEST_INFO << "Actors per Course = " << setting.actors_per_course << std::endl; GTEST_INFO << "Courses per Day = " << setting.courses_per_day << std::endl; GTEST_INFO << "Same Course per Week = " << setting.same_course_per_week << std::endl; GTEST_INFO << "Days to Simulate = " << setting.days_to_simulate << std::endl; SetUp(setting); } TEST(TaleExtraSchoolTests, CorrectCurrentDayAfterSimulation) { Setting setting; setting.actor_count = 10; setting.days_to_simulate = 5; Random random; Chronicle chronicle(random); chronicle.Reset(); School school(chronicle, random, setting); school.SimulateDays(setting.days_to_simulate); EXPECT_EQ(school.GetCurrentDay(), 5); EXPECT_EQ(school.GetCurrentWeekday(), Weekday::Saturday); } TEST(TaleExtraSchoolTests, InitializedRelationshipsAtStart) { Setting setting; setting.actor_count = 100; setting.desired_min_start_relationships_count = 4; setting.desired_max_start_relationships_count = 12; Random random; Chronicle chronicle(random); chronicle.Reset(); School school(chronicle, random, setting); for (size_t i = 0; i < setting.actor_count; ++i) { auto a = school.GetActor(i); for (auto &b : a->GetAllKnownActors()) { EXPECT_NE(a->CalculateRelationshipStrength(b->id_), 0); EXPECT_NE(b->CalculateRelationshipStrength(a->id_), 0); } } } TEST(TaleInteractions, CreateRandomInteractionFromStore) { Random random; Setting setting; Chronicle chronicle(random); InteractionStore interaction_store(random); size_t interaction_index = interaction_store.GetRandomInteractionPrototypeIndex(); size_t participant_count = interaction_store.GetParticipantCount(interaction_index); chronicle.Reset(); setting.actor_count = participant_count; School school(chronicle, random, setting); std::vector<Actor *> participants; for (size_t i = 0; i < participant_count; ++i) { participants.push_back(school.GetActor(i)); } size_t tick = 0; std::vector<Kernel *> no_reasons; Interaction *interaction = interaction_store.CreateInteraction(chronicle, interaction_index, 1.0f, tick, no_reasons, participants); EXPECT_EQ(interaction->name_, interaction_store.GetInteractionName(interaction_index)); EXPECT_EQ(interaction->tick_, tick); EXPECT_EQ(interaction->GetAllParticipants().size(), participant_count); for (size_t i = 0; i < participant_count; ++i) { EXPECT_EQ(interaction->GetAllParticipants()[i], school.GetActor(i)); } for (size_t i = 0; i < interaction->GetPrototype()->wealth_effects.size(); ++i) { EXPECT_EQ(interaction->GetPrototype()->wealth_effects[i], interaction_store.GetWealthEffects(interaction_index)[i]); } for (size_t i = 0; i < interaction->GetPrototype()->emotion_effects.size(); ++i) { for (size_t j = 0; j < interaction->GetPrototype()->emotion_effects[i].size(); ++j) { EXPECT_EQ(interaction->GetPrototype()->emotion_effects[i][j], interaction_store.GetEmotionEffects(interaction_index)[i][j]); } } for (size_t i = 0; i < interaction->GetPrototype()->relationship_effects.size(); ++i) { for (auto &[participant, vector] : interaction->GetPrototype()->relationship_effects[i]) { for (size_t j = 0; j < vector.size(); ++j) { EXPECT_EQ(vector[j], interaction_store.GetRelationshipEffects(interaction_index)[i].at(participant)[j]); } } } } TEST(TaleInteractions, ApplyInteraction) { size_t tick = 0; std::vector<Kernel *> no_reasons; Random random; size_t participant_count = 2; Setting setting; setting.actor_count = participant_count; Chronicle chronicle(random); School school(chronicle, random, setting); std::vector<Actor *> participants; participants.push_back(school.GetActor(0)); participants.push_back(school.GetActor(1)); std::vector<float> wealth_effects; std::vector<std::vector<float>> emotion_effects; std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> relationship_effects; std::vector<float> expected_wealth_values; std::vector<std::vector<float>> expected_emotion_values; std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> expected_relationship_values; std::vector<float> signs = {1.0f, -1.0f}; for (size_t participant_index = 0; participant_index < 2; ++participant_index) { float sign = signs[participant_index]; wealth_effects.push_back(0.5f * sign); expected_wealth_values.push_back(0.5f * sign + school.GetActor(participant_index)->wealth_->GetValue()); std::vector<float> emotion_vector(static_cast<int>(EmotionType::kLast), 0.0f); std::vector<float> expected_emotion_values_vector(static_cast<int>(EmotionType::kLast), 0.0f); for (int type_index = 0; type_index < emotion_vector.size(); ++type_index) { emotion_vector[type_index] = type_index * 0.1f * sign; expected_emotion_values_vector[type_index] = type_index * 0.1f * sign + school.GetActor(participant_index)->emotions_[type_index]->GetValue(); } emotion_effects.push_back(emotion_vector); expected_emotion_values.push_back(expected_emotion_values_vector); std::vector<float> relationship_vector(static_cast<int>(RelationshipType::kLast), 0.0f); std::vector<float> expected_relationship_values_vector(static_cast<int>(RelationshipType::kLast), 0.0f); size_t other_participant = (participant_index == 0 ? 1 : 0); for (int type_index = 0; type_index < relationship_vector.size(); ++type_index) { relationship_vector[type_index] = type_index * 0.1f * sign; float existing_value = 0; Actor *actor = school.GetActor(participant_index); if (actor->relationships_.count(other_participant)) { std::vector<Relationship *> existing_map = actor->relationships_.at(other_participant); existing_value = existing_map[type_index]->GetValue(); } expected_relationship_values_vector[type_index] = existing_value + type_index * 0.1f * sign; } robin_hood::unordered_map<size_t, std::vector<float>> participant_relationship_map = {{other_participant, relationship_vector}}; robin_hood::unordered_map<size_t, std::vector<float>> expected_participant_relationship_map = {{other_participant, expected_relationship_values_vector}}; relationship_effects.push_back(participant_relationship_map); expected_relationship_values.push_back(expected_participant_relationship_map); } std::shared_ptr<InteractionPrototype> prototype(new InteractionPrototype()); prototype->name = "Test"; prototype->wealth_effects = wealth_effects; prototype->emotion_effects = emotion_effects; prototype->relationship_effects = relationship_effects; std::shared_ptr<InteractionRequirement> requirement(new InteractionRequirement()); std::shared_ptr<InteractionTendency> tendency(new InteractionTendency()); Interaction *interaction = chronicle.CreateInteraction(prototype, requirement, tendency, 1.0f, tick, no_reasons, participants); interaction->Apply(); for (size_t participant_index = 0; participant_index < participant_count; ++participant_index) { EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetValue(), std::clamp(expected_wealth_values[participant_index], -1.0f, 1.0f)); for (size_t type_index = 0; type_index < expected_emotion_values[participant_index].size(); ++type_index) { EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetValue(), std::clamp(expected_emotion_values[participant_index][type_index], -1.0f, 1.0f)); } for (auto &[other_participant_index, vector] : expected_relationship_values[participant_index]) { for (size_t type_index = 0; type_index < vector.size(); ++type_index) { EXPECT_EQ(school.GetActor(participant_index)->relationships_[other_participant_index][type_index]->GetValue(), std::clamp(vector[type_index], -1.0f, 1.0f)); } } } } TEST(TaleInteractions, InteractionBecomesReason) { size_t tick = 0; Random random; size_t participant_count = 2; Setting setting; setting.desired_min_start_relationships_count = 0; setting.desired_max_start_relationships_count = 0; setting.actor_count = participant_count; Chronicle chronicle(random); School school(chronicle, random, setting); std::vector<Actor *> participants; participants.push_back(school.GetActor(0)); participants.push_back(school.GetActor(1)); std::vector<float> wealth_effects; std::vector<std::vector<float>> emotion_effects; std::vector<robin_hood::unordered_map<size_t, std::vector<float>>> relationship_effects; for (size_t participant_index = 0; participant_index < participant_count; ++participant_index) { wealth_effects.push_back(0.1f); std::vector<float> emotion_vector(static_cast<int>(EmotionType::kLast), 0.1f); emotion_effects.push_back(emotion_vector); std::vector<float> relationship_vector(static_cast<int>(RelationshipType::kLast), 0.1f); size_t other_participant = (participant_index == 0 ? 1 : 0); robin_hood::unordered_map<size_t, std::vector<float>> participant_relationship_map = {{other_participant, relationship_vector}}; relationship_effects.push_back(participant_relationship_map); } std::shared_ptr<InteractionPrototype> prototype(new InteractionPrototype()); prototype->name = "InteractionBecomesReason"; prototype->wealth_effects = wealth_effects; prototype->emotion_effects = emotion_effects; prototype->relationship_effects = relationship_effects; prototype->description = "{} did test interaction with {}"; std::shared_ptr<InteractionRequirement> requirement(new InteractionRequirement()); requirement->SetParticipantCount(participant_count); std::shared_ptr<InteractionTendency> tendency(new InteractionTendency()); std::vector<Kernel *> no_reasons; Interaction *interaction = chronicle.CreateInteraction(prototype, requirement, tendency, 1.0f, tick, no_reasons, participants); interaction->Apply(); for (size_t participant_index = 0; participant_index < participant_count; ++participant_index) { EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetReasons()[0]->name_, prototype->name); EXPECT_EQ(school.GetActor(participant_index)->wealth_->GetReasons()[0]->id_, interaction->id_); for (int type_index = 0; type_index < static_cast<int>(EmotionType::kLast); ++type_index) { EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetReasons()[0]->name_, prototype->name); EXPECT_EQ(school.GetActor(participant_index)->emotions_[type_index]->GetReasons()[0]->id_, interaction->id_); } for (auto &[other_participant, vector] : school.GetActor(participant_index)->relationships_) { for (int type_index = 0; type_index < static_cast<int>(EmotionType::kLast); ++type_index) { EXPECT_EQ(vector[type_index]->GetReasons()[0]->name_, prototype->name); EXPECT_EQ(vector[type_index]->GetReasons()[0]->id_, interaction->id_); } } } } TEST(TaleCourse, CreateCourse) { Setting setting; Random random; Course course(random, setting, 0, "Test"); EXPECT_EQ(course.GetSlotCount(), setting.slot_count_per_week()); } TEST(TaleCourse, AddGroupsToSlot) { Setting setting; Random random; Course course(random, setting, 0, "Test"); setting.actor_count = 0; Chronicle chronicle(random); School school(chronicle, random, setting); std::vector<Actor *> actors; for (size_t slot = 0; slot < course.GetSlotCount(); ++slot) { std::list<Actor *> course_group; Actor *actor = chronicle.CreateActor(school, "John", "Doe"); actors.push_back(actor); course_group.push_back(actor); course.AddToSlot(course_group, slot); EXPECT_EQ((*course.GetCourseGroupForSlot(slot).begin())->id_, slot); } for (size_t slot = 0; slot < course.GetSlotCount(); ++slot) { EXPECT_EQ((*course.GetCourseGroupForSlot(slot).begin())->id_, slot); } } TEST(TaleCourse, AreAllSlotsFilled) { Setting setting; Random random; Course course(random, setting, 0, "Test"); setting.actor_count = 0; Chronicle chronicle(random); School school(chronicle, random, setting); EXPECT_FALSE(course.AllSlotsFilled()); for (size_t slot = 0; slot < setting.slot_count_per_week() - 1; ++slot) { std::list<Actor *> course_group; for (size_t actor_index = 0; actor_index < setting.actors_per_course; ++actor_index) { Actor *actor = chronicle.CreateActor(school, "John", "Doe"); course_group.push_back(actor); } course.AddToSlot(course_group, slot); EXPECT_FALSE(course.AllSlotsFilled()); } std::list<Actor *> course_group; for (size_t actor_index = 0; actor_index < setting.actors_per_course; ++actor_index) { Actor *actor = chronicle.CreateActor(school, "John", "Doe"); course_group.push_back(actor); } course.AddToSlot(course_group, setting.slot_count_per_week() - 1); EXPECT_TRUE(course.AllSlotsFilled()); } TEST(TaleCourse, GetRandomCourseSlot) { Setting setting; uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); setting.actor_count = 300; setting.actors_per_course = 30; setting.courses_per_day = 6; setting.same_course_per_week = 4; Course course(random, setting, 0, "Test"); setting.actor_count = 0; Chronicle chronicle(random); School school(chronicle, random, setting); std::vector<uint32_t> random_filled_slots; for (size_t i = 0; i < setting.slot_count_per_week() / 2; ++i) { uint32_t random_slot = random.GetUInt(0, static_cast<uint32_t>(setting.slot_count_per_week() - 1)); while (std::count(random_filled_slots.begin(), random_filled_slots.end(), random_slot)) { ++random_slot; random_slot %= setting.slot_count_per_week(); } random_filled_slots.push_back(random_slot); } for (size_t i = 0; i < random_filled_slots.size(); ++i) { std::list<Actor *> course_group; Actor *actor = chronicle.CreateActor(school, "John", "Doe"); course_group.push_back(actor); course.AddToSlot(course_group, random_filled_slots[i]); } size_t tries = 10000; for (size_t i = 0; i < tries; ++i) { uint32_t random_empty_slot = course.GetRandomEmptySlot(); for (size_t j = 0; j < random_filled_slots.size(); ++j) { EXPECT_NE(random_empty_slot, random_filled_slots[j]); } } } class TaleActor : public ::testing::Test { protected: std::string actor_first_name_ = "John"; std::string actor_last_name_ = "Doe"; uint32_t desired_min_start_relationships_count_ = 1; uint32_t desired_max_start_relationships_count_ = 8; Actor *actor_; Setting setting_; School *school_; Random random_; Chronicle chronicle_; TaleActor() : random_(), chronicle_(random_) { setting_.actor_count = 10; setting_.desired_min_start_relationships_count = desired_min_start_relationships_count_; setting_.desired_max_start_relationships_count = desired_max_start_relationships_count_; school_ = new School(chronicle_, random_, setting_); actor_ = chronicle_.CreateActor(*school_, actor_first_name_, actor_last_name_); actor_->SetupRandomValues(0); } virtual ~TaleActor() {} void SetUp() {} virtual void TearDown() {} }; TEST_F(TaleActor, CreateActor) { EXPECT_EQ(actor_->first_name_, actor_first_name_); EXPECT_EQ(actor_->last_name_, actor_last_name_); EXPECT_EQ(actor_->id_, setting_.actor_count); } TEST_F(TaleActor, ActorHasInitializedStartingValues) { EXPECT_TRUE(actor_->wealth_); EXPECT_NE(actor_->emotions_.size(), 0); GTEST_INFO << "Relationship Size: " << actor_->relationships_.size() << "\n"; EXPECT_LE(actor_->relationships_.size(), setting_.max_start_relationships_count()); } TEST_F(TaleActor, AddActorToCourse) { size_t course_id = 5; Course course(school_->GetRandom(), setting_, course_id, "Test"); std::list<Actor *> course_group; std::vector<uint32_t> slots_to_check; course_group.push_back(actor_); EXPECT_FALSE(actor_->IsEnrolledInCourse(course_id)); EXPECT_EQ(actor_->GetFilledSlotsCount(), 0); for (uint32_t i = 0; i < setting_.slot_count_per_week(); ++i) { slots_to_check.push_back(i); EXPECT_TRUE(actor_->SlotsEmpty(slots_to_check)); } for (size_t i = 0; i < setting_.slot_count_per_week(); ++i) { EXPECT_FALSE(actor_->AllSlotsFilled()); course.AddToSlot(course_group, i); EXPECT_EQ(actor_->GetFilledSlotsCount(), i + 1); EXPECT_TRUE(actor_->IsEnrolledInCourse(course_id)); EXPECT_FALSE(actor_->SlotsEmpty(slots_to_check)); } EXPECT_TRUE(actor_->AllSlotsFilled()); } TEST_F(TaleActor, DefaultTendencyChanceCalculation) { InteractionTendency tendency; ContextType context = ContextType::kLast; Kernel *reason; float chance = actor_->CalculateInteractionChance(tendency, context, reason); EXPECT_FLOAT_EQ(chance, 0.5f); } TEST_F(TaleActor, MaxTendencyChanceCalculation) { InteractionTendency tendency; tendency.contexts[static_cast<int>(ContextType::kCourse)] = 1.0f; tendency.contexts[static_cast<int>(ContextType::kFreetime)] = -1.0f; tendency.wealth = 1.0f; for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index) { tendency.emotions[type_index] = 1.0f; } std::vector<Kernel *> no_reasons; actor_->wealth_ = chronicle_.CreateResource("wealth", "wealthy", "poor", 0, actor_, no_reasons, 1.0f); for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index) { actor_->emotions_[type_index] = chronicle_.CreateEmotion(static_cast<EmotionType>(type_index), 0, actor_, no_reasons, 1.0f); } ContextType context = ContextType::kCourse; Kernel *reason; float chance = actor_->CalculateInteractionChance(tendency, context, reason); EXPECT_FLOAT_EQ(chance, 1.0f); } TEST_F(TaleActor, RandomTendencyChanceCalculation) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); InteractionTendency tendency; uint32_t tries = 1000; for (uint32_t i = 0; i < tries; ++i) { tendency.contexts[static_cast<int>(ContextType::kCourse)] = random.GetFloat(-1.0f, 1.0f); tendency.contexts[static_cast<int>(ContextType::kFreetime)] = random.GetFloat(-1.0f, 1.0f); tendency.wealth = random.GetFloat(-1.0f, 1.0f); for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index) { tendency.emotions[type_index] = random.GetFloat(-1.0f, 1.0f); } std::vector<Kernel *> no_reasons; actor_->wealth_ = chronicle_.CreateResource("wealth", "wealthy", "poor", 0, actor_, no_reasons, random.GetFloat(-1.0f, 1.0f)); for (size_t type_index = 0; type_index < tendency.emotions.size(); ++type_index) { actor_->emotions_[type_index] = chronicle_.CreateEmotion(static_cast<EmotionType>(type_index), 0, actor_, no_reasons, random.GetFloat(-1.0f, 1.0f)); } ContextType context = (random.GetFloat(-1.0f, 1.0f) <= 0 ? ContextType::kCourse : ContextType::kFreetime); Kernel *reason; float chance = actor_->CalculateInteractionChance(tendency, context, reason); EXPECT_GE(chance, 0.0f); EXPECT_LE(chance, 1.0f); } } TEST(TaleRandom, PickIndexWithHundredPercentChance) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); uint32_t tries = 1000; for (uint32_t i = 0; i < tries; ++i) { uint32_t random_index = random.GetUInt(0, tries - 1); std::vector<float> distribution; distribution.reserve(tries); for (size_t j = 0; j < tries; ++j) { distribution.push_back((j == random_index ? 1.0f : 0.0f)); } EXPECT_EQ(random.PickIndex(distribution), random_index); } } TEST(TaleRandom, PickBetweenFullRangeWithHundredPercentChance) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); uint32_t tries = 1000; for (uint32_t i = 0; i < tries; ++i) { uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2); uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1); std::vector<float> distribution(tries, 1.0f); EXPECT_GE(random.PickIndex(distribution), 0); EXPECT_LT(random.PickIndex(distribution), tries); } } TEST(TaleRandom, PickBetweenFullRangeWithZeroPercentChance) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); uint32_t tries = 1000; for (uint32_t i = 0; i < tries; ++i) { uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2); uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1); std::vector<float> distribution(tries, 0.0f); EXPECT_GE(random.PickIndex(distribution, true), 0); EXPECT_LT(random.PickIndex(distribution, true), tries); } } TEST(TaleRandom, PickBetweenRandomRange) { uint32_t seconds = static_cast<uint32_t>(time(NULL)); Random random(seconds); uint32_t tries = 1000; for (uint32_t i = 0; i < tries; ++i) { uint32_t random_index_bottom = random.GetUInt(0, (tries - 1) / 2); uint32_t random_index_top = random.GetUInt(random_index_bottom, tries - 1); std::vector<float> distribution; distribution.reserve(tries); for (uint32_t j = 0; j < tries; ++j) { distribution.push_back(((j >= random_index_bottom && j <= random_index_top) ? 1.0f : 0.0f)); } EXPECT_GE(random.PickIndex(distribution, true), random_index_bottom); EXPECT_LE(random.PickIndex(distribution, true), random_index_top); } }
39.891738
175
0.673082
AmonShokhinAhmed
a7b7214dcad5af84c017b9bca86f4c7d35942a42
968
cpp
C++
problems/atcoder/abc218/d---rectangles/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/atcoder/abc218/d---rectangles/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/atcoder/abc218/d---rectangles/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; static_assert(sizeof(int) == 4 && sizeof(long) == 8); using P = array<int, 2>; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int N; cin >> N; vector<P> pts(N); for (auto& [x, y] : pts) { cin >> x >> y; } sort(begin(pts), end(pts)); auto contains = [&](int x, int y) { auto it = lower_bound(begin(pts), end(pts), P{x, y}); return it != end(pts) && *it == P{x, y}; }; int ans = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { auto [x0, y0] = pts[i]; auto [x1, y1] = pts[j]; if (x0 != x1 && y0 != y1) { if (contains(x0, y1) && contains(x1, y0)) { ans++; } } } } ans /= 2; cout << ans << '\n'; return 0; }
23.047619
61
0.436983
brunodccarvalho
a7b90ebefe5ef12f8c6f78917eaee4dd17b73171
603
cpp
C++
external/cryptopp/gf256.cpp
netmebtc/NibbleClassic-Core-CLI_blid
a65a596aa12a2790ed43304cce0cbe2868cee601
[ "BSD-3-Clause" ]
245
2018-06-08T16:07:44.000Z
2022-03-31T16:36:50.000Z
external/cryptopp/gf256.cpp
netmebtc/NibbleClassic-Core-CLI_blid
a65a596aa12a2790ed43304cce0cbe2868cee601
[ "BSD-3-Clause" ]
22
2019-05-08T01:47:10.000Z
2021-11-29T08:38:27.000Z
external/cryptopp/gf256.cpp
netmebtc/NibbleClassic-Core-CLI_blid
a65a596aa12a2790ed43304cce0cbe2868cee601
[ "BSD-3-Clause" ]
84
2018-05-22T06:00:07.000Z
2022-02-07T09:57:44.000Z
// gf256.cpp - originally written and placed in the public domain by Wei Dai #include "pch.h" #include "gf256.h" NAMESPACE_BEGIN(CryptoPP) GF256::Element GF256::Multiply(Element a, Element b) const { word result = 0, t = b; for (unsigned int i=0; i<8; i++) { result <<= 1; if (result & 0x100) result ^= m_modulus; t <<= 1; if (t & 0x100) result ^= a; } return (GF256::Element) result; } GF256::Element GF256::MultiplicativeInverse(Element a) const { Element result = a; for (int i=1; i<7; i++) result = Multiply(Square(result), a); return Square(result); } NAMESPACE_END
17.228571
76
0.6534
netmebtc
a7bc12e08c641cea6a2a0d2a43ad1ce6b7ee5afd
3,822
cpp
C++
Engine/Source/ThirdParty/PhysX/NvCloth/test/src/tests/Range.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/ThirdParty/PhysX/NvCloth/test/src/tests/Range.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/ThirdParty/PhysX/NvCloth/test/src/tests/Range.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
#include "utilities/Utilities.h" #include <NvCloth/Range.h> TEST_LEAK_FIXTURE(Range) TEST_F(Range, Constructor) { nv::cloth::Range<char> char_range; EXPECT_EQ(char_range.size(), 0); EXPECT_NULLPTR(char_range.begin()); EXPECT_NULLPTR(char_range.end()); nv::cloth::Range<char> a((char*)0x123, (char*)0x456); nv::cloth::Range<char> b(a); EXPECT_EQ(b.begin(), a.begin()); EXPECT_EQ(b.end(), a.end()); } TEST_F(Range, Size) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(char_array.size(), char_range.size()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(float_array.size(), float_range.size()); } TEST_F(Range, Empty) { { nv::cloth::Range<char> char_range; EXPECT_TRUE(char_range.empty()); nv::cloth::Range<float> float_range; EXPECT_TRUE(float_range.empty()); } { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range = CreateRange(char_array); EXPECT_FALSE(char_range.empty()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range = CreateRange(float_array); EXPECT_FALSE(float_range.empty()); } } TEST_F(Range, Pop) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array.front(), &char_range.front()); EXPECT_EQ(&char_array.back(), &char_range.back()); char_range.popBack(); EXPECT_EQ(&char_array.back() - 1, &char_range.back()); char_range.popFront(); EXPECT_EQ(&char_array.front() + 1, &char_range.front()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array.front(), &float_range.front()); EXPECT_EQ(&float_array.back(), &float_range.back()); float_range.popBack(); EXPECT_EQ(&float_array.back() - 1, &float_range.back()); float_range.popFront(); EXPECT_EQ(&float_array.front() + 1, &float_range.front()); } TEST_F(Range, BeginEnd) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0]+char_array.size()); EXPECT_EQ(&char_array[0], char_range.begin()); EXPECT_EQ(&char_array[0] + char_array.size(), char_range.end()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array[0], float_range.begin()); EXPECT_EQ(&float_array[0] + float_array.size(), float_range.end()); } TEST_F(Range, FrontBack) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array.front(), &char_range.front()); EXPECT_EQ(&char_array.back(), &char_range.back()); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array.front(), &float_range.front()); EXPECT_EQ(&float_array.back(), &float_range.back()); } TEST_F(Range, ArrayOperator) { std::vector<char> char_array; char_array.resize(100); nv::cloth::Range<char> char_range(&char_array[0], &char_array[0] + char_array.size()); EXPECT_EQ(&char_array[0], &char_range[0]); EXPECT_EQ(&char_array[99], &char_range[99]); std::vector<float> float_array; float_array.resize(100); nv::cloth::Range<float> float_range(&float_array[0], &float_array[0] + float_array.size()); EXPECT_EQ(&float_array[0], &float_range[0]); EXPECT_EQ(&float_array[99], &float_range[99]); }
31.586777
92
0.717425
windystrife
a7bd47760454d46cfb69247601d88f658fbe03a5
1,478
cpp
C++
QFtpServerLib/ftpretrcommand.cpp
spygg/QFtpServer
28410fd296795d49f17d4310c992dc6e6b0c26f8
[ "MIT" ]
null
null
null
QFtpServerLib/ftpretrcommand.cpp
spygg/QFtpServer
28410fd296795d49f17d4310c992dc6e6b0c26f8
[ "MIT" ]
null
null
null
QFtpServerLib/ftpretrcommand.cpp
spygg/QFtpServer
28410fd296795d49f17d4310c992dc6e6b0c26f8
[ "MIT" ]
null
null
null
#include "ftpretrcommand.h" #include <QFile> #include <QSslSocket> FtpRetrCommand::FtpRetrCommand(QObject *parent, const QString &fileName, qint64 seekTo) : FtpCommand(parent) { this->fileName = fileName; this->seekTo = seekTo; file = 0; } FtpRetrCommand::~FtpRetrCommand() { if (m_started) { if (file && file->isOpen() && file->atEnd()) { emit reply("226 Closing data connection."); } else { emit reply("550 Requested action not taken; file unavailable."); } } } void FtpRetrCommand::startImplementation() { file = new QFile(fileName, this); if (!file->open(QIODevice::ReadOnly)) { deleteLater(); return; } emit reply("150 File status okay; about to open data connection."); if (seekTo) { file->seek(seekTo); } // For encryted SSL sockets, we need to use the encryptedBytesWritten() // signal, see the QSslSocket documentation to for reasons why. if (m_socket->isEncrypted()) { connect(m_socket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64))); } else { connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64))); } refillSocketBuffer(128*1024); } void FtpRetrCommand::refillSocketBuffer(qint64 bytes) { if (!file->atEnd()) { m_socket->write(file->read(bytes)); } else { m_socket->disconnectFromHost(); } }
25.482759
105
0.629905
spygg
a7be1b315b8c3828fc0f69564f11dbfb8f31648d
2,292
cpp
C++
Net/testsuite/src/MailStreamTest.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
2
2021-04-11T20:16:11.000Z
2021-11-17T11:28:59.000Z
Net/testsuite/src/MailStreamTest.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
1
2016-03-31T10:04:18.000Z
2016-03-31T10:04:43.000Z
Net/testsuite/src/MailStreamTest.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
1
2022-03-09T08:11:03.000Z
2022-03-09T08:11:03.000Z
// // MailStreamTest.cpp // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "MailStreamTest.h" #include "Poco/CppUnit/TestCaller.h" #include "Poco/CppUnit/TestSuite.h" #include "Poco/Net/MailStream.h" #include "Poco/StreamCopier.h" #include <sstream> using Poco::Net::MailInputStream; using Poco::Net::MailOutputStream; using Poco::StreamCopier; MailStreamTest::MailStreamTest(const std::string& name): CppUnit::TestCase(name) { } MailStreamTest::~MailStreamTest() { } void MailStreamTest::testMailInputStream() { std::istringstream istr( "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" "..and this one too\r\n" "..\r\n" ".\r\n" ); MailInputStream mis(istr); std::ostringstream ostr; StreamCopier::copyStream(mis, ostr); std::string s(ostr.str()); assertTrue (s == "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" ".and this one too\r\n" ".\r\n" ); } void MailStreamTest::testMailOutputStream() { std::string msg( "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" ".This line starts with a period.\r\n" "\r\n" ".and this one too\r\n" ".\r\n" ); std::ostringstream ostr; MailOutputStream mos(ostr); mos << msg; mos.close(); std::string s(ostr.str()); assertTrue (s == "From: john.doe@no.domain\r\n" "To: jane.doe@no.domain\r\n" "Subject: test\r\n" "\r\n" "This is a test.\r\n" "\rThis.is.\ngarbage\r.\r\n" "..This line starts with a period.\r\n" "\r\n" "..and this one too\r\n" "..\r\n" ".\r\n" ); } void MailStreamTest::setUp() { } void MailStreamTest::tearDown() { } CppUnit::Test* MailStreamTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailStreamTest"); CppUnit_addTest(pSuite, MailStreamTest, testMailInputStream); CppUnit_addTest(pSuite, MailStreamTest, testMailOutputStream); return pSuite; }
18.786885
80
0.655323
astlin
a7be6335e39fb8d1fb62ee82cb793236df2b1d0a
2,335
cc
C++
onnxruntime/test/perftest/main.cc
KsenijaS/onnxruntime
5086e55a35f83e3137bdb34b6d7210c97a512e6a
[ "MIT" ]
2
2021-07-24T01:13:36.000Z
2021-11-17T11:03:52.000Z
onnxruntime/test/perftest/main.cc
KsenijaS/onnxruntime
5086e55a35f83e3137bdb34b6d7210c97a512e6a
[ "MIT" ]
4
2020-12-04T21:00:38.000Z
2022-01-22T12:49:30.000Z
onnxruntime/test/perftest/main.cc
KsenijaS/onnxruntime
5086e55a35f83e3137bdb34b6d7210c97a512e6a
[ "MIT" ]
1
2020-07-30T12:50:02.000Z
2020-07-30T12:50:02.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // onnxruntime dependencies #include <core/session/onnxruntime_c_api.h> #include <random> #include "command_args_parser.h" #include "performance_runner.h" #include <google/protobuf/stubs/common.h> using namespace onnxruntime; const OrtApi* g_ort = NULL; #ifdef _WIN32 int real_main(int argc, wchar_t* argv[]) { #else int real_main(int argc, char* argv[]) { #endif g_ort = OrtGetApiBase()->GetApi(ORT_API_VERSION); perftest::PerformanceTestConfig test_config; if (!perftest::CommandLineParser::ParseArguments(test_config, argc, argv)) { perftest::CommandLineParser::ShowUsage(); return -1; } Ort::Env env{nullptr}; try { OrtLoggingLevel logging_level = test_config.run_config.f_verbose ? ORT_LOGGING_LEVEL_VERBOSE : ORT_LOGGING_LEVEL_WARNING; env = Ort::Env(logging_level, "Default"); } catch (const Ort::Exception& e) { fprintf(stderr, "Error creating environment: %s \n", e.what()); return -1; } if(test_config.machine_config.provider_type_name == onnxruntime::kOpenVINOExecutionProvider){ if(test_config.run_config.concurrent_session_runs != 1){ fprintf(stderr, "OpenVINO doesn't support more than 1 session running simultaneously default value of 1 will be set \n"); test_config.run_config.concurrent_session_runs = 1; } if(test_config.run_config.execution_mode == ExecutionMode::ORT_PARALLEL){ fprintf(stderr, "OpenVINO doesn't support parallel executor using sequential executor\n"); test_config.run_config.execution_mode = ExecutionMode::ORT_SEQUENTIAL; } } std::random_device rd; perftest::PerformanceRunner perf_runner(env, test_config, rd); auto status = perf_runner.Run(); if (!status.IsOK()) { printf("Run failed:%s\n", status.ErrorMessage().c_str()); return -1; } perf_runner.SerializeResult(); return 0; } #ifdef _WIN32 int wmain(int argc, wchar_t* argv[]) { #else int main(int argc, char* argv[]) { #endif int retval = -1; try { retval = real_main(argc, argv); } catch (std::exception& ex) { fprintf(stderr, "%s\n", ex.what()); retval = -1; } ::google::protobuf::ShutdownProtobufLibrary(); return retval; }
31.133333
127
0.692505
KsenijaS
a7c5144e2f50813d84e2f23d99206b08a7e1da7e
17,985
cpp
C++
src/generator/protobufclassgenerator.cpp
R0ll1ngSt0ne/qtprotobuf
ce6f09ffa77fecd35fff84deb798720d870ab3e7
[ "MIT" ]
null
null
null
src/generator/protobufclassgenerator.cpp
R0ll1ngSt0ne/qtprotobuf
ce6f09ffa77fecd35fff84deb798720d870ab3e7
[ "MIT" ]
null
null
null
src/generator/protobufclassgenerator.cpp
R0ll1ngSt0ne/qtprotobuf
ce6f09ffa77fecd35fff84deb798720d870ab3e7
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Tatyana Borisova <tanusshhka@mail.ru> * * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf * * 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 "protobufclassgenerator.h" #include "utils.h" #include <iostream> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/zero_copy_stream.h> using namespace ::QtProtobuf::generator; using namespace ::google::protobuf; using namespace ::google::protobuf::io; using namespace ::google::protobuf::compiler; ProtobufClassGenerator::ProtobufClassGenerator(const Descriptor *message, std::unique_ptr<::google::protobuf::io::ZeroCopyOutputStream> out) : ClassGeneratorBase(message->full_name(), std::move(out)) , mMessage(message) { } void ProtobufClassGenerator::printCopyFunctionality() { assert(mMessage != nullptr); mPrinter.Print({{"classname", mClassName}}, Templates::CopyConstructorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::CopyFieldTemplate); } Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"classname", mClassName}}, Templates::AssignmentOperatorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::CopyFieldTemplate); } mPrinter.Print(Templates::AssignmentOperatorReturnTemplate); Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); } void ProtobufClassGenerator::printMoveSemantic() { assert(mMessage != nullptr); mPrinter.Print({{"classname", mClassName}}, Templates::MoveConstructorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (isComplexType(field) || field->is_repeated()) { printField(field, Templates::MoveComplexFieldTemplate); } else { if (field->type() != FieldDescriptor::TYPE_ENUM) { printField(field, Templates::MoveFieldTemplate); } else { printField(field, Templates::EnumMoveFieldTemplate); } } } Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"classname", mClassName}}, Templates::MoveAssignmentOperatorTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (isComplexType(field) || field->is_repeated()) { printField(field, Templates::MoveComplexFieldTemplate); } else { if (field->type() != FieldDescriptor::TYPE_ENUM) { printField(field, Templates::MoveFieldTemplate); } else { printField(field, Templates::EnumMoveFieldTemplate); } } } mPrinter.Print(Templates::AssignmentOperatorReturnTemplate); Outdent(); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); } void ProtobufClassGenerator::printComparisonOperators() { assert(mMessage != nullptr); bool isFirst = true; PropertyMap properties; mPrinter.Print({{"type", mClassName}}, Templates::EqualOperatorTemplate); if (mMessage->field_count() <= 0) { mPrinter.Print("true"); } for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (producePropertyMap(field, properties)) { if (!isFirst) { mPrinter.Print("\n&& "); } else { Indent(); Indent(); isFirst = false; } mPrinter.Print(properties, Templates::EqualOperatorPropertyTemplate); } } //Only if at least one field "copied" if (!isFirst) { Outdent(); Outdent(); } mPrinter.Print(";\n"); mPrinter.Print(Templates::SimpleBlockEnclosureTemplate); mPrinter.Print({{"type", mClassName}}, Templates::NotEqualOperatorTemplate); } void ProtobufClassGenerator::printIncludes() { assert(mMessage != nullptr); mPrinter.Print(Templates::DefaultProtobufIncludesTemplate); std::set<std::string> existingIncludes; for (int i = 0; i < mMessage->field_count(); i++) { printInclude(mMessage->field(i), existingIncludes); } } void ProtobufClassGenerator::printInclude(const FieldDescriptor *field, std::set<std::string> &existingIncludes) { assert(field != nullptr); std::string newInclude; const char *includeTemplate; switch (field->type()) { case FieldDescriptor::TYPE_MESSAGE: if ( field->is_map() ) { newInclude = "QMap"; assert(field->message_type() != nullptr); assert(field->message_type()->field_count() == 2); printInclude(field->message_type()->field(0), existingIncludes); printInclude(field->message_type()->field(1), existingIncludes); includeTemplate = Templates::ExternalIncludeTemplate; } else { std::string typeName = field->message_type()->name(); utils::tolower(typeName); newInclude = typeName; includeTemplate = Templates::InternalIncludeTemplate; } break; case FieldDescriptor::TYPE_BYTES: newInclude = "QByteArray"; includeTemplate = Templates::ExternalIncludeTemplate; break; case FieldDescriptor::TYPE_STRING: newInclude = "QString"; includeTemplate = Templates::ExternalIncludeTemplate; break; case FieldDescriptor::TYPE_ENUM: { EnumVisibility enumVisibily = getEnumVisibility(field, mMessage); if (enumVisibily == GLOBAL_ENUM) { includeTemplate = Templates::GlobalEnumIncludeTemplate; } else if (enumVisibily == NEIGHBOUR_ENUM) { includeTemplate = Templates::InternalIncludeTemplate; std::string fullEnumName = field->enum_type()->full_name(); std::vector<std::string> fullEnumNameParts; utils::split(fullEnumName, fullEnumNameParts, '.'); std::string enumTypeOwner = fullEnumNameParts.at(fullEnumNameParts.size() - 2); utils::tolower(enumTypeOwner); newInclude = enumTypeOwner; } else { return; } } break; default: return; } if (existingIncludes.find(newInclude) == std::end(existingIncludes)) { mPrinter.Print({{"include", newInclude}}, includeTemplate); existingIncludes.insert(newInclude); } } void ProtobufClassGenerator::printField(const FieldDescriptor *field, const char *fieldTemplate) { assert(field != nullptr); std::map<std::string, std::string> propertyMap; if (producePropertyMap(field, propertyMap)) { mPrinter.Print(propertyMap, fieldTemplate); } } bool ProtobufClassGenerator::producePropertyMap(const FieldDescriptor *field, PropertyMap &propertyMap) { assert(field != nullptr); std::string typeName = getTypeName(field, mMessage); if (typeName.size() <= 0) { std::cerr << "Type " << field->type_name() << " is not supported by Qt Generator" " please look at https://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html" " for details" << std::endl; return false; } std::string typeNameLower(typeName); utils::tolower(typeNameLower); std::string capProperty = field->camelcase_name(); capProperty[0] = static_cast<char>(::toupper(capProperty[0])); std::string typeNameNoList = typeName; if (field->is_repeated() && !field->is_map()) { if(field->type() == FieldDescriptor::TYPE_MESSAGE || field->type() == FieldDescriptor::TYPE_ENUM) { typeNameNoList.resize(typeNameNoList.size() - strlen(Templates::ListSuffix)); } else { typeNameNoList.resize(typeNameNoList.size() - strlen("List")); } } propertyMap = {{"type", typeName}, {"type_lower", typeNameLower}, {"property_name", field->camelcase_name()}, {"property_name_cap", capProperty}, {"type_nolist", typeNameNoList} }; return true; } bool ProtobufClassGenerator::isListType(const FieldDescriptor *field) { assert(field != nullptr); return field && field->is_repeated() && field->type() == FieldDescriptor::TYPE_MESSAGE; } bool ProtobufClassGenerator::isComplexType(const FieldDescriptor *field) { assert(field != nullptr); return field->type() == FieldDescriptor::TYPE_MESSAGE || field->type() == FieldDescriptor::TYPE_STRING || field->type() == FieldDescriptor::TYPE_BYTES; } void ProtobufClassGenerator::printConstructor() { std::string parameterList; for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); std::string fieldTypeName = getTypeName(field, mMessage); std::string fieldName = field->camelcase_name(); fieldName[0] = static_cast<char>(::tolower(fieldName[0])); if (field->is_repeated() || field->is_map()) { parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}"; } else { switch (field->type()) { case FieldDescriptor::TYPE_DOUBLE: case FieldDescriptor::TYPE_FLOAT: parameterList += fieldTypeName + " " + fieldName + " = " + "0.0"; break; case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_UINT64: parameterList += fieldTypeName + " " + fieldName + " = " + "0"; break; case FieldDescriptor::TYPE_BOOL: parameterList += fieldTypeName + " " + fieldName + " = " + "false"; break; case FieldDescriptor::TYPE_BYTES: case FieldDescriptor::TYPE_STRING: case FieldDescriptor::TYPE_MESSAGE: parameterList += "const " + fieldTypeName + " &" + fieldName + " = {}"; break; default: parameterList += fieldTypeName + " " + fieldName + " = " + "{}"; break; } } parameterList += ", "; } mPrinter.Print({{"classname", mClassName}, {"parameter_list", parameterList}}, Templates::ProtoConstructorTemplate); } void ProtobufClassGenerator::printMaps() { Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_map()) { std::string keyType = getTypeName(field->message_type()->field(0), mMessage); std::string valueType = getTypeName(field->message_type()->field(1), mMessage); const char *mapTemplate = Templates::MapTypeUsingTemplate; if (field->message_type()->field(1)->type() == FieldDescriptor::TYPE_MESSAGE) { mapTemplate = Templates::MessageMapTypeUsingTemplate; } mPrinter.Print({{"classname",field->message_type()->name()}, {"key", keyType}, {"value", valueType}}, mapTemplate); } } Outdent(); } void ProtobufClassGenerator::printLocalEmumsMetaTypesDeclaration() { for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field == nullptr || field->enum_type() == nullptr) continue; if (field->type() == FieldDescriptor::TYPE_ENUM && isLocalMessageEnum(mMessage, field)) { mPrinter.Print({{"classname", mClassName + "::" + field->enum_type()->name() + Templates::ListSuffix}, {"namespaces", mNamespacesColonDelimited}}, Templates::DeclareMetaTypeTemplate); } } } void ProtobufClassGenerator::printMapsMetaTypesDeclaration() { for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_map()) { mPrinter.Print({{"classname", field->message_type()->name()}, {"namespaces", mNamespacesColonDelimited + "::" + mClassName}}, Templates::DeclareMetaTypeTemplate); } } } void ProtobufClassGenerator::printProperties() { assert(mMessage != nullptr); //private section Indent(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); const char *propertyTemplate = Templates::PropertyTemplate; if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map() && !field->is_repeated()) { propertyTemplate = Templates::MessagePropertyTemplate; } printField(field, propertyTemplate); } //Generate extra QmlListProperty that is mapped to list for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->type() == FieldDescriptor::TYPE_MESSAGE && field->is_repeated() && !field->is_map()) { printField(field, Templates::QmlListPropertyTemplate); } } Outdent(); printQEnums(mMessage); //public section printPublic(); printMaps(); //Body Indent(); printConstructor(); printCopyFunctionality(); printMoveSemantic(); printComparisonOperators(); for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->type() == FieldDescriptor::TYPE_MESSAGE) { if (!field->is_map() && !field->is_repeated()) { printField(field, Templates::GetterMessageTemplate); } } printField(field, Templates::GetterTemplate); if (field->is_repeated()) { printField(field, Templates::GetterContainerExtraTemplate); if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_map()) { printField(field, Templates::QmlListGetterTemplate); } } } for (int i = 0; i < mMessage->field_count(); i++) { auto field = mMessage->field(i); switch (field->type()) { case FieldDescriptor::TYPE_MESSAGE: if (!field->is_map() && !field->is_repeated()) { printField(field, Templates::SetterTemplateMessageType); } printField(field, Templates::SetterTemplateComplexType); break; case FieldDescriptor::FieldDescriptor::TYPE_STRING: case FieldDescriptor::FieldDescriptor::TYPE_BYTES: printField(field, Templates::SetterTemplateComplexType); break; default: printField(field, Templates::SetterTemplateSimpleType); break; } } Outdent(); mPrinter.Print(Templates::SignalsBlockTemplate); Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::SignalTemplate); } Outdent(); } void ProtobufClassGenerator::printListType() { mPrinter.Print({{"classname", mClassName}}, Templates::ComplexListTypeUsingTemplate); } void ProtobufClassGenerator::printClassMembers() { Indent(); for (int i = 0; i < mMessage->field_count(); i++) { printField(mMessage->field(i), Templates::MemberTemplate); } Outdent(); } std::set<std::string> ProtobufClassGenerator::extractModels() const { std::set<std::string> extractedModels; for (int i = 0; i < mMessage->field_count(); i++) { const FieldDescriptor *field = mMessage->field(i); if (field->is_repeated() && field->type() == FieldDescriptor::TYPE_MESSAGE) { std::string typeName = field->message_type()->name(); extractedModels.insert(typeName); } } return extractedModels; } void ProtobufClassGenerator::run() { printPreamble(); printIncludes(); printNamespaces(); printClassDeclaration(); printProperties(); printPrivate(); printClassMembers(); encloseClass(); printListType(); encloseNamespaces(); printMetaTypeDeclaration(); printMapsMetaTypesDeclaration(); printLocalEmumsMetaTypesDeclaration(); }
35.826693
140
0.619127
R0ll1ngSt0ne
a7c6a53c147194bd18746ddc3b384784cae07a4a
5,302
cpp
C++
modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/arm_converter/arm_converter_one_hot.cpp
IvanNovoselov/openvino_contrib
5fe8fd389d57972bd470b447c606138679ab5d49
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <details/ie_exception.hpp> #include "arm_converter/arm_converter.hpp" #include <ngraph/runtime/reference/one_hot.hpp> namespace ArmPlugin { template <typename Indices, typename OutputType> void wrap_one_hot(const Indices* arg, OutputType* out, const ngraph::Shape& in_shape, const ngraph::Shape& out_shape, size_t one_hot_axis, const OutputType* on_values, const OutputType* off_values) { ngraph::runtime::reference::one_hot(arg, out, in_shape, out_shape, one_hot_axis, on_values[0], off_values[0]); } template<> Converter::Conversion::Ptr Converter::Convert(const opset::OneHot& node) { auto make = [&] (auto refFunction) { return MakeConversion(refFunction, node.input(0), node.output(0), node.get_input_shape(0), node.get_output_shape(0), static_cast<size_t>(node.get_axis()), node.input(2), node.input(3)); }; ngraph::element::Type_t outType = node.get_output_element_type(0); switch (node.get_input_element_type(0)) { case ngraph::element::Type_t::u8 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint8_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint8_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint8_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint8_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint8_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::i16 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int16_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int16_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int16_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int16_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int16_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::u16 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint16_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint16_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint16_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint16_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint16_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::u32 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::uint32_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::uint32_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::uint32_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::uint32_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::uint32_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } case ngraph::element::Type_t::i32 : switch (outType) { case ngraph::element::Type_t::u8 : return make(wrap_one_hot<std::int32_t, std::uint8_t>); case ngraph::element::Type_t::i16 : return make(wrap_one_hot<std::int32_t, std::int16_t>); case ngraph::element::Type_t::u16 : return make(wrap_one_hot<std::int32_t, std::uint16_t>); case ngraph::element::Type_t::i32 : return make(wrap_one_hot<std::int32_t, std::int32_t>); case ngraph::element::Type_t::f32 : return make(wrap_one_hot<std::int32_t, float>); default: THROW_IE_EXCEPTION << "Unsupported Type: " << outType; return {}; } default: THROW_IE_EXCEPTION << "Unsupported Type: " << node.get_input_element_type(0); return {}; } } } // namespace ArmPlugin
58.911111
108
0.570351
IvanNovoselov
a7c756bd055afbcfc273cc9586846f802c14e5e9
2,326
cpp
C++
media/extractors/mpeg2/ExtractorBundle.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/extractors/mpeg2/ExtractorBundle.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/extractors/mpeg2/ExtractorBundle.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "MPEG2ExtractorBundle" #include <utils/Log.h> #include <media/MediaExtractorPluginHelper.h> #include <media/stagefright/MediaDefs.h> #include "MPEG2PSExtractor.h" #include "MPEG2TSExtractor.h" namespace android { struct CDataSource; static const char *extensions[] = { "m2p", "m2ts", "mts", "ts", NULL }; extern "C" { // This is the only symbol that needs to be exported __attribute__ ((visibility ("default"))) ExtractorDef GETEXTRACTORDEF() { return { EXTRACTORDEF_VERSION, UUID("3d1dcfeb-e40a-436d-a574-c2438a555e5f"), 1, "MPEG2-PS/TS Extractor", { .v3 = { []( CDataSource *source, float *confidence, void **, FreeMetaFunc *) -> CreatorFunc { DataSourceHelper helper(source); if (SniffMPEG2TS(&helper, confidence)) { return []( CDataSource *source, void *) -> CMediaExtractor* { return wrap(new MPEG2TSExtractor(new DataSourceHelper(source)));}; } else if (SniffMPEG2PS(&helper, confidence)) { return []( CDataSource *source, void *) -> CMediaExtractor* { return wrap(new MPEG2PSExtractor(new DataSourceHelper(source)));}; } return NULL; }, extensions } }, }; } } // extern "C" } // namespace android
30.207792
94
0.5546
Dreadwyrm
a7c761c18ab7051ec25627e38782b52942f3409a
2,220
cpp
C++
Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/Licensing/EvaluationDateTimeLimitations.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "EvaluationDateTimeLimitations.h" #include <Tsk.h> #include <TaskCollection.h> #include <Task.h> #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <system/date_time.h> #include <saving/Enums/SaveFileFormat.h> #include <Project.h> #include <Key.h> #include <enums/TaskKey.h> #include "RunExamples.h" using namespace Aspose::Tasks::Saving; namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace Licensing { RTTI_INFO_IMPL_HASH(2704315891u, ::Aspose::Tasks::Examples::CPP::Licensing::EvaluationDateTimeLimitations, ThisTypeBaseTypesInfo); void EvaluationDateTimeLimitations::Run() { System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:DateTimeLimitations // Create a prject instance System::SharedPtr<Project> project1 = System::MakeObject<Project>(); // Define Tasks System::SharedPtr<Task> task1 = project1->get_RootTask()->get_Children()->Add(u"Task1"); task1->Set(Tsk::ActualStart(), System::DateTime::Parse(u"06-Apr-2010")); System::SharedPtr<Task> task2 = project1->get_RootTask()->get_Children()->Add(u"Task2"); task2->Set(Tsk::ActualStart(), System::DateTime::Parse(u"10-Apr-2010")); // Save the Project as XML project1->Save(u"EvalProject_out.xml", Aspose::Tasks::Saving::SaveFileFormat::XML); // ExEnd:DateTimeLimitations } } // namespace Licensing } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
34.153846
164
0.743243
aspose-tasks
a7c8ddbe8b0e3c05222f891e457df5b0f4a44241
1,797
cpp
C++
encoder/vaapiencoder_vp8_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
89
2015-01-09T10:31:13.000Z
2018-01-18T12:48:21.000Z
encoder/vaapiencoder_vp8_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
626
2015-01-12T00:01:26.000Z
2018-01-23T18:58:58.000Z
encoder/vaapiencoder_vp8_unittest.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
104
2015-01-12T04:02:09.000Z
2017-12-28T08:27:42.000Z
/* * Copyright 2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // // The unittest header must be included before va_x11.h (which might be included // indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers // define 'Bool' and 'None' preprocessor types. Gtest uses the same names // to define some struct placeholders. Thus, this creates a compile conflict // if X defines them before gtest. Hence, the include order requirement here // is the only fix for this right now. // // See bug filed on gtest at https://github.com/google/googletest/issues/371 // for more details. // #include "common/factory_unittest.h" // primary header #include "vaapiencoder_vp8.h" namespace YamiMediaCodec { class VaapiEncoderVP8Test : public FactoryTest<IVideoEncoder, VaapiEncoderVP8> { protected: /* invoked by gtest before the test */ virtual void SetUp() { return; } /* invoked by gtest after the test */ virtual void TearDown() { return; } }; #define VAAPIENCODER_VP8_TEST(name) \ TEST_F(VaapiEncoderVP8Test, name) VAAPIENCODER_VP8_TEST(Factory) { FactoryKeys mimeTypes; mimeTypes.push_back(YAMI_MIME_VP8); doFactoryTest(mimeTypes); } }
28.078125
80
0.725097
genisysram
a7c974e4a298f7c669de3f5dcc90e888d6a23a1b
462
hxx
C++
src/engine/Component.hxx
broken-bytes/Cyanite
0392e3114c946e41b7352afd4b8eceb6f03939da
[ "MIT" ]
1
2021-11-11T02:56:56.000Z
2021-11-11T02:56:56.000Z
src/engine/Component.hxx
broken-bytes/Cyanite
0392e3114c946e41b7352afd4b8eceb6f03939da
[ "MIT" ]
null
null
null
src/engine/Component.hxx
broken-bytes/Cyanite
0392e3114c946e41b7352afd4b8eceb6f03939da
[ "MIT" ]
null
null
null
#pragma once #include "EntityRegistry.hxx" #include "EntitySet.hxx" namespace BrokenBytes::Cyanite::Engine { struct Component { Component(std::string name) { this->_name = name; } protected: std::string _name; private: friend class EntityRegistry; friend struct EntitySet; friend struct Entity; auto Name() const->std::string { return this->_name; } }; }
20.086957
40
0.577922
broken-bytes
a7cb1c42b24ebbefc330279f4b3ea6c016ef40dd
7,739
cpp
C++
src/b.cpp
oniani/b
19d4ecff7c7d3f99c3e70b99871224ad2110e61c
[ "MIT" ]
1
2020-09-28T14:02:59.000Z
2020-09-28T14:02:59.000Z
src/b.cpp
oniani/b
19d4ecff7c7d3f99c3e70b99871224ad2110e61c
[ "MIT" ]
null
null
null
src/b.cpp
oniani/b
19d4ecff7c7d3f99c3e70b99871224ad2110e61c
[ "MIT" ]
null
null
null
#include "b.hpp" CommandVertex::CommandVertex(std::string specifier, std::string exec, std::vector<std::string> dependencies) : specifier(specifier) , exec(exec) , dependencies(dependencies) {}; void CommandVertex::run() { // Takes a C string as a formal parameter system(this->exec.c_str()); } bool proper(std::string line) { if (line.empty() || line[0] == '#') { return false; } for (int i = 1; i < line.size(); i++) { if (line[i] != ' ') { if (line[i] == '#' || line[i] == '\t') { return false; } else if (isalpha(line[i])) { return true; } } } return false; } std::vector<std::string> get_proper_lines(std::string filepath) { std::vector<std::string> lines; std::ifstream file(filepath); std::string line; if (!file.is_open()) { std::runtime_error("Error while opening the file"); } // Get only if not a comment while (std::getline(file, line)) { if (proper(line)) { lines.push_back(line); } } if (file.bad()) { std::runtime_error("Error while reading the file"); } return lines; } std::vector<std::string> split(std::string str, char delimiter) { std::vector<std::string> internal; // Turn the string into a stream std::stringstream ss(str); std::string token; while(getline(ss, token, delimiter)) { std::string_view ref = token; ref.remove_prefix(std::min(ref.find_first_not_of(" "), ref.size())); ref.remove_suffix(std::min(ref.find_first_not_of(" "), ref.size())); internal.push_back(std::string(ref)); } return internal; } Graph build_graph(std::vector<std::string> lines, char delimiter) { Graph cmds; for (int i = 0; i < lines.size(); i++) { if (lines[i].find(DELIMITER) != std::string::npos) { std::vector<std::string> all = split(lines[i], delimiter); // std::string std::string specifier = all[0]; // Exec std::string_view sv = lines[i + 1]; sv.remove_prefix(std::min(sv.find_first_not_of(" "), sv.size())); std::string exec = std::string(sv); // Dependencies std::vector<std::string> dependencies; for (std::string item : split(all[1], ' ')) { std::string ref = item; dependencies.push_back(ref); } // Create the command and push it onto the cmds CommandVertex cmd = CommandVertex(specifier, exec, dependencies); cmd.indegree = dependencies.size(); cmds.push_back(cmd); } else { continue; } } return cmds; } CommandVertex get_vertex(Graph g, std::string specifier) { for (int i = 0; i < g.size(); i++) { if (g[i].specifier == specifier) { return g[i]; } } throw("The vertex does not exist in the graph"); } std::vector<std::string> get_all_dependencies(Graph g, std::string specifier) { std::vector<std::string> subgraph; std::set<std::string> visited; std::vector<std::string> vertices; vertices.push_back(specifier); while (vertices.size() != 0) { std::string vertex = vertices.back(); vertices.pop_back(); if (visited.find(vertex) == visited.end()) { visited.insert(vertex); subgraph.push_back(vertex); // TODO: Should be optimized, `std::map`? // NOTE: Though, `std::map` uses the built-in hasher that has // a bad performance due to backward compatibility std::vector<std::string> deps = get_vertex(g, vertex).dependencies; for (std::string dep_name : deps) { vertices.push_back(dep_name); } } } return subgraph; } std::vector<CommandVertex> topological_sort(Graph g) { std::vector<CommandVertex> no_incoming; // Keep track of the vertices with no incoming edges for (CommandVertex vertex : g) { if (vertex.indegree == 0) { no_incoming.push_back(vertex); } } // Define a topological ordering std::vector<CommandVertex> tlogical_ordering; // As long as there exists a vertex with no incoming edges while (no_incoming.size() > 0) { // Add the vertex to the ordering and remove it from the vector CommandVertex vertex = no_incoming.back(); no_incoming.pop_back(); tlogical_ordering.push_back(vertex); // Decrement the indegree of the neighbors of the removed vertex for (int i = 0; i < g.size(); i++) { // Get all dependencies std::vector<std::string> deps = g[i].dependencies; // `std::find` is more efficient than `std::count` since it stops // the search once the element is found if (std::find(deps.begin(), deps.end(), vertex.specifier) != deps.end()) { g[i].indegree -= 1; if (g[i].indegree == 0) { no_incoming.push_back(g[i]); } } } } // If we have all vertices, we are done if (tlogical_ordering.size() == g.size()) { return tlogical_ordering; } // Otherwise, we have a cycle throw std::logic_error("Circular dependencies"); } int main(int argc, char **argv) { // The system looks for the file `b.txt` std::vector<std::string> lines = get_proper_lines("b.txt"); // Build a dependency graph Graph dependency_graph = build_graph(lines, DELIMITER); // Validate the command line arguments if (argc == 1) { return 0; } if (argc != 2) { throw std::invalid_argument("Redundant arguments"); } // Get the specifier std::string specifier = argv[1]; // Make sure the command exists // If it does, construct the subgraph, construct the topological ordering, // and execute the commands bool exists = false; for (int i = 0; i < dependency_graph.size(); i++) { if (dependency_graph[i].specifier == std::string(specifier)) { // It exists exists = true; // If there are no dependencies, the associated command // gets executed if (dependency_graph[i].dependencies.empty()) { dependency_graph[i].run(); } else { // If there are some dependencies, a subgraph gets constructed // and the topological ordering is created // Finally, we iterate over all dependencies and run them std::vector<std::string> dependencies = get_all_dependencies(dependency_graph, specifier); // Create a subgraph of the command and all associated // dependencies Graph subgraph; for (std::string dep : dependencies) { subgraph.push_back(get_vertex(dependency_graph, dep)); } // Return the topological ordering of the graph subgraph = topological_sort(subgraph); subgraph.pop_back(); // Run the commands in a topological order for (CommandVertex vertex : subgraph) { std::cout << vertex.specifier << std::endl; vertex.run(); } } } } if (!exists) { throw std::invalid_argument("The specifier does not exist"); } }
29.538168
79
0.549683
oniani
a7d21becff72ba015465e94f6fbe8dd17adfe203
8,312
cc
C++
chill/omega/omega_lib/src/omega_core/oc_util.cc
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
5
2019-05-20T03:35:41.000Z
2021-09-16T22:22:13.000Z
chill/omega/omega_lib/src/omega_core/oc_util.cc
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
chill/omega/omega_lib/src/omega_core/oc_util.cc
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
/***************************************************************************** Copyright (C) 1994-2000 the Omega Project Team Copyright (C) 2005-2011 Chun Chen All Rights Reserved. Purpose: Notes: History: *****************************************************************************/ #include <omega/omega_core/oc_i.h> #include <algorithm> namespace omega { void Problem:: problem_merge(Problem &p2) { int newLocation[maxVars]; int i,e2; resurrectSubs(); p2.resurrectSubs(); setExternals(); p2.setExternals(); assert(safeVars == p2.safeVars); if(DBUG) { fprintf(outputFile,"Merging:\n"); printProblem(); fprintf(outputFile,"and\n"); p2.printProblem(); } for(i=1; i<= p2.safeVars; i++) { assert(p2.var[i] > 0) ; newLocation[i] = forwardingAddress[p2.var[i]]; } for(; i<= p2.nVars; i++) { int j = ++(nVars); newLocation[i] = j; zeroVariable(j); var[j] = -1; } newLocation[0] = 0; for (e2 = p2.nEQs - 1; e2 >= 0; e2--) { int e1 = newEQ(); eqnnzero(&(EQs[e1]), nVars); for(i=0;i<=p2.nVars;i++) EQs[e1].coef[newLocation[i]] = p2.EQs[e2].coef[i]; } for (e2 = p2.nGEQs - 1; e2 >= 0; e2--) { int e1 = newGEQ(); eqnnzero(&(GEQs[e1]), nVars); GEQs[e1].touched = 1; for(i=0;i<=p2.nVars;i++) GEQs[e1].coef[newLocation[i]] = p2.GEQs[e2].coef[i]; } int w = -1; for (i = 1; i <= nVars; i++) if (var[i] < 0) var[i] = w--; if(DBUG) { fprintf(outputFile,"to get:\n"); printProblem(); } } void Problem::chainUnprotect() { int i, e; int unprotect[maxVars]; int any = 0; for (i = 1; i <= safeVars; i++) { unprotect[i] = (var[i] < 0); for (e = nSUBs - 1; e >= 0; e--) if (SUBs[e].coef[i]) unprotect[i] = 0; } for (i = 1; i <= safeVars; i++) if (unprotect[i]) any=1; if (!any) return; if (DBUG) { fprintf(outputFile, "Doing chain reaction unprotection\n"); printProblem(); for (i = 1; i <= safeVars; i++) if (unprotect[i]) fprintf(outputFile, "unprotecting %s\n", variable(i)); } for (i = 1; i <= safeVars; i++) if (unprotect[i]) { /* wild card */ if (i < safeVars) { int j = safeVars; std::swap(var[i], var[j]); for (e = nGEQs - 1; e >= 0; e--) { GEQs[e].touched = 1; std::swap(GEQs[e].coef[i], GEQs[e].coef[j]); } for (e = nEQs - 1; e >= 0; e--) std::swap(EQs[e].coef[i], EQs[e].coef[j]); for (e = nSUBs - 1; e >= 0; e--) std::swap(SUBs[e].coef[i], SUBs[e].coef[j]); std::swap(unprotect[i], unprotect[j]); i--; } safeVars--; } if (DBUG) { fprintf(outputFile, "After chain reactions\n"); printProblem(); } } void Problem::resurrectSubs() { if (nSUBs > 0 && !pleaseNoEqualitiesInSimplifiedProblems) { int i, e, n, m,mbr; mbr = 0; for (e = nGEQs - 1; e >= 0; e--) if (GEQs[e].color) mbr=1; for (e = nEQs - 1; e >= 0; e--) if (EQs[e].color) mbr=1; if (nMemories) mbr = 1; assert(!mbr || mayBeRed); if (DBUG) { fprintf(outputFile, "problem reduced, bringing variables back to life\n"); if(mbr && !mayBeRed) fprintf(outputFile, "Red equations we don't expect\n"); printProblem(); } if (DBUG && nEQs > 0) fprintf(outputFile,"This is wierd: problem has equalities\n"); for (i = 1; i <= safeVars; i++) if (var[i] < 0) { /* wild card */ if (i < safeVars) { int j = safeVars; std::swap(var[i], var[j]); for (e = nGEQs - 1; e >= 0; e--) { GEQs[e].touched = 1; std::swap(GEQs[e].coef[i], GEQs[e].coef[j]); } for (e = nEQs - 1; e >= 0; e--) std::swap(EQs[e].coef[i], EQs[e].coef[j]); for (e = nSUBs - 1; e >= 0; e--) std::swap(SUBs[e].coef[i], SUBs[e].coef[j]); i--; } safeVars--; } m = nSUBs; n = nVars; if (n < safeVars + m) n = safeVars + m; for (e = nGEQs - 1; e >= 0; e--) { if (singleVarGEQ(&GEQs[e])) { i = abs(GEQs[e].key); if (i >= safeVars + 1) GEQs[e].key += (GEQs[e].key > 0 ? m : -m); } else { GEQs[e].touched = true; GEQs[e].key = 0; } } for (i = nVars; i >= safeVars + 1; i--) { var[i + m] = var[i]; for (e = nGEQs - 1; e >= 0; e--) GEQs[e].coef[i + m] = GEQs[e].coef[i]; for (e = nEQs - 1; e >= 0; e--) EQs[e].coef[i + m] = EQs[e].coef[i]; for (e = nSUBs - 1; e >= 0; e--) SUBs[e].coef[i + m] = SUBs[e].coef[i]; } for (i = safeVars + m; i >= safeVars + 1; i--) { for (e = nGEQs - 1; e >= 0; e--) GEQs[e].coef[i] = 0; for (e = nEQs - 1; e >= 0; e--) EQs[e].coef[i] = 0; for (e = nSUBs - 1; e >= 0; e--) SUBs[e].coef[i] = 0; } nVars += m; safeVars += m; for (e = nSUBs - 1; e >= 0; e--) var[safeVars -m + 1 + e] = SUBs[e].key; for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; if (DBUG) { fprintf(outputFile,"Ready to wake substitutions\n"); printProblem(); } for (e = nSUBs - 1; e >= 0; e--) { int neweq = newEQ(); eqnncpy(&(EQs[neweq]), &(SUBs[e]), nVars); EQs[neweq].coef[safeVars -m + 1 + e] = -1; EQs[neweq].color = EQ_BLACK; if (DBUG) { fprintf(outputFile, "brought back: "); printEQ(&EQs[neweq]); fprintf(outputFile, "\n"); } } nSUBs = 0; if (DBUG) { fprintf(outputFile, "variables brought back to life\n"); printProblem(); } } coalesce(); recallRedMemories(); cleanoutWildcards(); } void Problem::reverseProtectedVariables() { int v1,v2,e,i; coef_t t; for (v1 = 1; v1 <= safeVars; v1++) { v2 = safeVars+1-v1; if (v2>=v1) break; for(e=0;e<nEQs;e++) { t = EQs[e].coef[v1]; EQs[e].coef[v1] = EQs[e].coef[v2]; EQs[e].coef[v2] = t; } for(e=0;e<nGEQs;e++) { t = GEQs[e].coef[v1]; GEQs[e].coef[v1] = GEQs[e].coef[v2]; GEQs[e].coef[v2] = t; GEQs[e].touched = 1; } for(e=0;e<nSUBs;e++) { t = SUBs[e].coef[v1]; SUBs[e].coef[v1] = SUBs[e].coef[v2]; SUBs[e].coef[v2] = t; } } for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; for (i = 0; i < nSUBs; i++) forwardingAddress[SUBs[i].key] = -i - 1; } void Problem::ordered_elimination(int symbolic) { int i,j,e; int isDead[maxmaxGEQs]; for(e=0;e<nEQs;e++) isDead[e] = 0; if (!variablesInitialized) { initializeVariables(); } for(i=nVars;i>symbolic;i--) for(e=0;e<nEQs;e++) if (EQs[e].coef[i] == 1 || EQs[e].coef[i] == -1) { for(j=nVars;j>i;j--) if (EQs[e].coef[j]) break; if (i==j) { doElimination(e, i); isDead[e] = 1; break; } } for(e=nEQs-1;e>=0;e--) if (isDead[e]) { nEQs--; if (e < nEQs) eqnncpy(&EQs[e], &EQs[nEQs], nVars); } for (i = 1; i <= safeVars; i++) forwardingAddress[var[i]] = i; for (i = 0; i < nSUBs; i++) forwardingAddress[SUBs[i].key] = -i - 1; } coef_t Problem::checkSum() const { coef_t cs; int e; cs = 0; for(e=0;e<nGEQs;e++) { coef_t c = GEQs[e].coef[0]; cs += c*c*c; } return cs; } void Problem::coalesce() { int e, e2, colors; int isDead[maxmaxGEQs]; int foundSomething = 0; colors = 0; for (e = 0; e < nGEQs; e++) if (GEQs[e].color) colors++; if (colors < 2) return; for (e = 0; e < nGEQs; e++) isDead[e] = 0; for (e = 0; e < nGEQs; e++) if (!GEQs[e].touched) for (e2 = e + 1; e2 < nGEQs; e2++) if (!GEQs[e2].touched && GEQs[e].key == -GEQs[e2].key && GEQs[e].coef[0] == -GEQs[e2].coef[0]) { int neweq = newEQ(); eqnncpy(&EQs[neweq], &GEQs[e], nVars); EQs[neweq].color = GEQs[e].color || GEQs[e2].color; foundSomething++; isDead[e] = 1; isDead[e2] = 1; } for (e = nGEQs - 1; e >= 0; e--) if (isDead[e]) { deleteGEQ(e); } if (DEBUG && foundSomething) { fprintf(outputFile, "Coalesced GEQs into %d EQ's:\n", foundSomething); printProblem(); } } } // namespace
25.341463
82
0.479548
CompOpt4Apps
a7d315127779f62fffee62610b0b2e9776a01bb4
7,698
cpp
C++
ciphers/lowmc/tfhe/lowmc_tfhe.cpp
IAIK/hybrid-HE-framework
7b1116a1a449c27e96b6017db216f988c186da54
[ "MIT" ]
12
2020-11-11T10:31:36.000Z
2021-12-23T03:04:58.000Z
ciphers/lowmc/tfhe/lowmc_tfhe.cpp
IAIK/hybrid-HE-framework
7b1116a1a449c27e96b6017db216f988c186da54
[ "MIT" ]
null
null
null
ciphers/lowmc/tfhe/lowmc_tfhe.cpp
IAIK/hybrid-HE-framework
7b1116a1a449c27e96b6017db216f988c186da54
[ "MIT" ]
1
2021-11-01T15:50:21.000Z
2021-11-01T15:50:21.000Z
#include "lowmc_tfhe.h" #include <iostream> namespace LOWMC { void LOWMC_256_128_63_14_TFHE::encrypt_key() { secret_key_encrypted.init(params.key_size_bits, context); for (size_t i = 0; i < params.key_size_bits; i++) { uint8_t bit = (secret_key[i / 8] >> (7 - i % 8)) & 1; bootsSymEncrypt(&secret_key_encrypted[i], bit, he_sk); } } TFHECiphertextVec LOWMC_256_128_63_14_TFHE::HE_decrypt( std::vector<uint8_t>& ciphertexts, size_t bits) { size_t num_block = ceil((double)bits / params.cipher_size_bits); LowMC lowmc(use_m4ri); block iv = 0; TFHECiphertextVec result(bits, context); for (size_t i = 0; i < num_block; i++) { std::cout << "round 0" << std::endl; TFHECiphertextVec state; if (use_m4ri) { state = secret_key_encrypted; MultiplyWithGF2Matrix(lowmc.m4ri_KeyMatrices[0], state); } else state = MultiplyWithGF2Matrix(lowmc.KeyMatrices[0], secret_key_encrypted); addConstant(state, ctr(iv, i + 1)); for (unsigned r = 1; r <= rounds; ++r) { std::cout << "round " << r << std::endl; sboxlayer(state); if (use_m4ri) { MultiplyWithGF2Matrix(lowmc.m4ri_LinMatrices[r - 1], state); MultiplyWithGF2MatrixAndAdd(lowmc.m4ri_KeyMatrices[r], secret_key_encrypted, state); } else { MultiplyWithGF2Matrix(lowmc.LinMatrices[r - 1], state); MultiplyWithGF2MatrixAndAdd(lowmc.KeyMatrices[r], secret_key_encrypted, state); } addConstant(state, lowmc.roundconstants[r - 1]); } // add cipher for (size_t k = 0; k < blocksize && i * blocksize + k < bits; k++) { size_t ind = i * blocksize + k; int32_t bit = (ciphertexts[ind / 8] >> (7 - ind % 8)) & 1; if (!bit) lweCopy(&result[ind], &state[k], he_pk->params->in_out_params); else bootsNOT(&result[ind], &state[k], he_pk); } } return result; } std::vector<uint8_t> LOWMC_256_128_63_14_TFHE::decrypt_result( TFHECiphertextVec& ciphertexts) { size_t size = ceil((double)ciphertexts.size() / 8); std::vector<uint8_t> res(size, 0); for (size_t i = 0; i < ciphertexts.size(); i++) { uint8_t bit = bootsSymDecrypt(&ciphertexts[i], he_sk) & 0xFF; res[i / 8] |= (bit << (7 - i % 8)); } return res; } TFHECiphertextVec LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix( const std::vector<keyblock>& matrix, const TFHECiphertextVec& key) { TFHECiphertextVec out(params.cipher_size_bits, context); for (unsigned i = 0; i < params.cipher_size_bits; ++i) { bool init = false; for (unsigned j = 0; j < params.key_size_bits; ++j) { if (!matrix[i][j]) continue; if (!init) { lweCopy(&out[i], &key[j], he_pk->params->in_out_params); init = true; } else bootsXOR(&out[i], &out[i], &key[j], he_pk); } } return out; } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2MatrixAndAdd( const std::vector<keyblock>& matrix, const TFHECiphertextVec& key, TFHECiphertextVec& state) { for (unsigned i = 0; i < params.cipher_size_bits; ++i) { for (unsigned j = 0; j < params.key_size_bits; ++j) { if (!matrix[i][j]) continue; bootsXOR(&state[i], &state[i], &key[j], he_pk); } } } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix( const std::vector<block>& matrix, TFHECiphertextVec& state) { TFHECiphertextVec out(params.cipher_size_bits, context); for (unsigned i = 0; i < params.cipher_size_bits; ++i) { bool init = false; for (unsigned j = 0; j < params.cipher_size_bits; ++j) { if (!matrix[i][j]) continue; if (!init) { lweCopy(&out[i], &state[j], he_pk->params->in_out_params); init = true; } else bootsXOR(&out[i], &out[i], &state[j], he_pk); } } state = out; } void LOWMC_256_128_63_14_TFHE::addConstant(TFHECiphertextVec& state, const block& constant) { for (size_t i = 0; i < params.cipher_size_bits; i++) { if (!constant[i]) continue; bootsNOT(&state[i], &state[i], he_pk); } } void LOWMC_256_128_63_14_TFHE::sboxlayer(TFHECiphertextVec& state) { for (unsigned i = 0; i < numofboxes; i++) { // invSbox(state[i * 3], state[i* 3 + 1], state[i * 3 + 2]); Sbox(state[i * 3], state[i * 3 + 1], state[i * 3 + 2]); } } void LOWMC_256_128_63_14_TFHE::Sbox(LweSample& a, LweSample& b, LweSample& c) { TFHECiphertext r_a(context); bootsAND(r_a, &b, &c, he_pk); bootsXOR(r_a, r_a, &a, he_pk); bootsXOR(r_a, r_a, &b, he_pk); bootsXOR(r_a, r_a, &c, he_pk); TFHECiphertext r_b(context); bootsAND(r_b, &a, &c, he_pk); bootsXOR(r_b, r_b, &b, he_pk); bootsXOR(r_b, r_b, &c, he_pk); TFHECiphertext r_c(context); bootsAND(r_c, &a, &b, he_pk); bootsXOR(r_c, r_c, &c, he_pk); lweCopy(&a, r_a, he_pk->params->in_out_params); lweCopy(&b, r_b, he_pk->params->in_out_params); lweCopy(&c, r_c, he_pk->params->in_out_params); } void LOWMC_256_128_63_14_TFHE::invSbox(LweSample& a, LweSample& b, LweSample& c) { TFHECiphertext r_a(context); bootsAND(r_a, &b, &c, he_pk); bootsXOR(r_a, r_a, &b, he_pk); bootsXOR(r_a, r_a, &c, he_pk); bootsXOR(r_a, r_a, &a, he_pk); TFHECiphertext r_b(context); bootsAND(r_b, &a, &c, he_pk); bootsXOR(r_b, r_b, &b, he_pk); TFHECiphertext r_c(context); bootsAND(r_c, &a, &b, he_pk); bootsXOR(r_c, r_c, &b, he_pk); bootsXOR(r_c, r_c, &c, he_pk); lweCopy(&a, r_a, he_pk->params->in_out_params); lweCopy(&b, r_b, he_pk->params->in_out_params); lweCopy(&c, r_c, he_pk->params->in_out_params); } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2MatrixAndAdd( const mzd_t* matrix, const TFHECiphertextVec& key, TFHECiphertextVec& state) { rci_t k = floor(log2(matrix->ncols)) - 2; if (k < 1) k = 1; std::vector<rci_t> L(1 << k); TFHECiphertextVec T(1 << k, context); L[0] = 0; for (rci_t i = 0; i < matrix->ncols; i += k) { if (i + k > matrix->ncols) k = matrix->ncols - i; for (rci_t j = 1; j < 1 << k; j++) { rci_t rowneeded = i + m4ri_codebook[k]->inc[j - 1]; L[m4ri_codebook[k]->ord[j]] = j; if (j == 1) lweCopy(&T[j], &key[rowneeded], he_pk->params->in_out_params); else bootsXOR(&T[j], &T[j - 1], &key[rowneeded], he_pk); } for (rci_t j = 0; j < matrix->nrows; j++) { rci_t x = L[mzd_read_bits_int(matrix, j, i, k)]; if (!x) continue; bootsXOR(&state[j], &state[j], &T[x], he_pk); } } } void LOWMC_256_128_63_14_TFHE::MultiplyWithGF2Matrix(const mzd_t* matrix, TFHECiphertextVec& state) { TFHECiphertextVec out(params.cipher_size_bits, context); rci_t k = floor(log2(matrix->ncols)) - 2; if (k < 1) k = 1; block init = 0; std::vector<rci_t> L(1 << k); TFHECiphertextVec T(1 << k, context); L[0] = 0; for (rci_t i = 0; i < matrix->ncols; i += k) { if (i + k > matrix->ncols) k = matrix->ncols - i; for (rci_t j = 1; j < 1 << k; j++) { rci_t rowneeded = i + m4ri_codebook[k]->inc[j - 1]; L[m4ri_codebook[k]->ord[j]] = j; if (j == 1) lweCopy(&T[j], &state[rowneeded], he_pk->params->in_out_params); else bootsXOR(&T[j], &T[j - 1], &state[rowneeded], he_pk); } for (rci_t j = 0; j < matrix->nrows; j++) { rci_t x = L[mzd_read_bits_int(matrix, j, i, k)]; if (!x) continue; if (init[j] == 0) { lweCopy(&out[j], &T[x], he_pk->params->in_out_params); init[j] = 1; } else bootsXOR(&out[j], &out[j], &T[x], he_pk); } } state = out; } } // namespace LOWMC
31.679012
80
0.599636
IAIK
a7d3a9eaeb55658b5a88017c289927a46866f4b9
2,238
cpp
C++
PLATFORM/Linux/SceneManager.cpp
Parseus/pixfight
b1f134b5e969e2da9ae66653f9e29da77bb6f28f
[ "MIT" ]
30
2018-04-19T10:01:03.000Z
2019-08-26T10:44:12.000Z
PLATFORM/Linux/SceneManager.cpp
Parseus/pixfight
b1f134b5e969e2da9ae66653f9e29da77bb6f28f
[ "MIT" ]
2
2018-07-09T04:35:50.000Z
2018-07-23T09:52:15.000Z
PLATFORM/Linux/SceneManager.cpp
Parseus/pixfight
b1f134b5e969e2da9ae66653f9e29da77bb6f28f
[ "MIT" ]
6
2018-05-24T17:55:17.000Z
2019-03-13T09:55:18.000Z
#include "SceneManager.hpp" #include "MenuScene.hpp" #include "NewGameScene.hpp" #include "LoadGameScene.hpp" #include "SettingsScene.hpp" #include "RenderScene.hpp" #ifndef __EMSCRIPTEN__ #include "MultiplayerScene.hpp" #include "MakeRoomScene.hpp" #include "JoinRoomScene.hpp" #endif SceneManager::SceneManager(struct nk_context *ctx, const std::string path) : _currentScene(nullptr) { auto menuScene = new MenuScene("menu", path, ctx); auto newGameScene = new NewGameScene("newgame", path, ctx); auto loadGameScene = new LoadGameScene("loadgame", path, ctx); auto settingsScene = new SettingsScene("settings", path, ctx); auto renderScene = new RenderScene("render", path, ctx); #ifndef __EMSCRIPTEN__ auto multiScene = new MultiplayerScene("multi", path, ctx); auto makeRoomScene = new MakeRoomScene("makeroom", path, ctx); auto joinRoomScene = new JoinRoomScene("joinroom", path, ctx); #endif _sceneDB[menuScene->getName()] = menuScene; _sceneDB[newGameScene->getName()] = newGameScene; _sceneDB[loadGameScene->getName()] = loadGameScene; _sceneDB[settingsScene->getName()] = settingsScene; _sceneDB[renderScene->getName()] = renderScene; #ifndef __EMSCRIPTEN__ _sceneDB[multiScene->getName()] = multiScene; _sceneDB[makeRoomScene->getName()] = makeRoomScene; _sceneDB[joinRoomScene->getName()] = joinRoomScene; #endif this->setCurrent("menu"); } SceneManager::~SceneManager() noexcept { for (auto it = _sceneDB.begin(); it != _sceneDB.end(); it++) { if ((*it).second != nullptr) { (*it).second->Destroy(); delete (*it).second; } (*it).second = nullptr; } _sceneDB.clear(); } SceneType SceneManager::Render(struct nk_font *smallfont, struct nk_font *normal) { return _currentScene->Render(smallfont, normal); } bool SceneManager::setCurrent(const std::string & name) { auto it = _sceneDB.find(name); if (it == _sceneDB.end()) { return false; } if (_currentScene != it->second) { _currentScene = it->second; } return true; } BaseScene* SceneManager::getScenePointer(const std::string & name) { auto it = _sceneDB.find(name); if (it == _sceneDB.end()) { return nullptr; } return it->second; }
24.064516
83
0.696604
Parseus
a7d449ff1d722a52d43480dffbe82ddc3253a869
14,209
cpp
C++
src/kfilter.cpp
Jamieryan/carma_pack
347ea78818cc808e53e4a46d341829f787198df5
[ "MIT" ]
39
2015-01-25T19:24:09.000Z
2022-02-28T11:55:28.000Z
src/kfilter.cpp
Jamieryan/carma_pack
347ea78818cc808e53e4a46d341829f787198df5
[ "MIT" ]
13
2015-04-29T12:37:45.000Z
2021-11-28T23:31:29.000Z
src/kfilter.cpp
Jamieryan/carma_pack
347ea78818cc808e53e4a46d341829f787198df5
[ "MIT" ]
19
2015-09-15T00:41:28.000Z
2021-07-28T07:28:47.000Z
// // kfilter.cpp // carma_pack // // Created by Brandon Kelly on 6/27/13. // Copyright (c) 2013 Brandon Kelly. All rights reserved. // #include <random.hpp> #include "include/kfilter.hpp" // Global random number generator object, instantiated in random.cpp extern boost::random::mt19937 rng; // Object containing some common random number generators. extern RandomGenerator RandGen; // Reset the Kalman Filter for a CAR(1) process void KalmanFilter1::Reset() { mean(0) = 0.0; var(0) = sigsqr_ / (2.0 * omega_) + yerr_(0) * yerr_(0); yconst_ = 0.0; yslope_ = 0.0; current_index_ = 1; } // Perform one iteration of the Kalman Filter for a CAR(1) process to update it void KalmanFilter1::Update() { double rho, var_ratio, previous_var; rho = exp(-1.0 * omega_ * dt_(current_index_-1)); previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1); var_ratio = previous_var / var(current_index_-1); // Update the Kalman filter mean mean(current_index_) = rho * mean(current_index_-1) + rho * var_ratio * (y_(current_index_-1) - mean(current_index_-1)); // Update the Kalman filter variance var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio); // add in contribution to variance from measurement errors var(current_index_) += yerr_(current_index_) * yerr_(current_index_); current_index_++; } // Initialize the coefficients used for interpolation and backcasting assuming a CAR(1) process void KalmanFilter1::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) { yconst_ = 0.0; yslope_ = exp(-std::abs(time_(itime) - time) * omega_); var[itime] = sigsqr_ / (2.0 * omega_) * (1.0 - yslope_ * yslope_) + yerr_(itime) * yerr_(itime); current_index_ = itime + 1; } // Update the coefficients used for interpolation and backcasting, assuming a CAR(1) process void KalmanFilter1::UpdateCoefs() { double rho = exp(-1.0 * dt_(current_index_-1) * omega_); double previous_var = var(current_index_-1) - yerr_(current_index_-1) * yerr_(current_index_-1); double var_ratio = previous_var / var(current_index_-1); yslope_ *= rho * (1.0 - var_ratio); yconst_ = yconst_ * rho * (1.0 - var_ratio) + rho * var_ratio * y_[current_index_-1]; var(current_index_) = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio) + yerr_(current_index_) * yerr_(current_index_); current_index_++; } // Return the predicted value and its variance at time assuming a CAR(1) process std::pair<double, double> KalmanFilter1::Predict(double time) { double rho, var_ratio, previous_var; double ypredict_mean, ypredict_var, yprecision; unsigned int ipredict = 0; while (time > time_(ipredict)) { // find the index where time_ > time for the first time ipredict++; if (ipredict == time_.n_elem) { // time is greater than last element of time_, so do forecasting break; } } // Run the Kalman filter up to the point time_[ipredict-1] Reset(); for (int i=1; i<ipredict; i++) { Update(); } if (ipredict == 0) { // backcasting, so initialize the conditional mean and variance to the stationary values ypredict_mean = 0.0; ypredict_var = sigsqr_ / (2.0 * omega_); } else { // predict the value of the time series at time, given the earlier values double dt = time - time_[ipredict-1]; rho = exp(-dt * omega_); previous_var = var(ipredict-1) - yerr_(ipredict-1) * yerr_(ipredict-1); var_ratio = previous_var / var(ipredict-1); // initialize the conditional mean and variance ypredict_mean = rho * mean(ipredict-1) + rho * var_ratio * (y_(ipredict-1) - mean(ipredict-1)); ypredict_var = sigsqr_ / (2.0 * omega_) * (1.0 - rho * rho) + rho * rho * previous_var * (1.0 - var_ratio); } if (ipredict == time_.n_elem) { // Forecasting, so we're done: no need to run interpolation steps std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } yprecision = 1.0 / ypredict_var; ypredict_mean *= yprecision; // Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of // the predicted time series value, then update the running conditional mean and variance of the predicted // time series value InitializeCoefs(time, ipredict, 0.0, 0.0); yprecision += yslope_ * yslope_ / var(ipredict); ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict); for (int i=ipredict+1; i<time_.n_elem; i++) { UpdateCoefs(); yprecision += yslope_ * yslope_ / var(i); ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i); } ypredict_var = 1.0 / yprecision; ypredict_mean *= ypredict_var; std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } // Reset the Kalman Filter for a CARMA(p,q) process void KalmanFilterp::Reset() { // Initialize the matrix of Eigenvectors. We will work with the state vector // in the space spanned by the Eigenvectors because in this space the state // transition matrix is diagonal, so the calculation of the matrix exponential // is fast. arma::cx_mat EigenMat(p_,p_); EigenMat.row(0) = arma::ones<arma::cx_rowvec>(p_); EigenMat.row(1) = omega_.st(); for (int i=2; i<p_; i++) { EigenMat.row(i) = strans(arma::pow(omega_, i)); } // Input vector under original state space representation arma::cx_vec Rvector = arma::zeros<arma::cx_vec>(p_); Rvector(p_-1) = 1.0; // Transform the input vector to the rotated state space representation. // The notation R and J comes from Belcher et al. (1994). arma::cx_vec Jvector(p_); Jvector = arma::solve(EigenMat, Rvector); // Transform the moving average coefficients to the space spanned by EigenMat. rotated_ma_coefs_ = ma_coefs_ * EigenMat; // Calculate the stationary covariance matrix of the state vector. for (int i=0; i<p_; i++) { for (int j=i; j<p_; j++) { // Only fill in upper triangle of StateVar because of symmetry StateVar_(i,j) = -sigsqr_ * Jvector(i) * std::conj(Jvector(j)) / (omega_(i) + std::conj(omega_(j))); } } StateVar_ = arma::symmatu(StateVar_); // StateVar is symmetric PredictionVar_ = StateVar_; // One-step state prediction error state_vector_.zeros(); // Initial state is set to zero // Initialize the Kalman mean and variance. These are the forecasted value // for the measured time series values and its variance, conditional on the // previous measurements mean(0) = 0.0; var(0) = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) ); var(0) += yerr_(0) * yerr_(0); // Add in measurement error contribution innovation_ = y_(0); // The innovation current_index_ = 1; } // Perform one iteration of the Kalman Filter for a CARMA(p,q) process to update it void KalmanFilterp::Update() { // First compute the Kalman Gain kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1); // Now update the state vector state_vector_ += kalman_gain_ * innovation_; // Update the state one-step prediction error variance PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t()); // Predict the next state rho_ = arma::exp(omega_ * dt_(current_index_-1)); state_vector_ = rho_ % state_vector_; // Update the predicted state variance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // Now predict the observation and its variance. mean(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) ); var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ); var(current_index_) += yerr_(current_index_) * yerr_(current_index_); // Add in measurement error contribution // Finally, update the innovation innovation_ = y_(current_index_) - mean(current_index_); current_index_++; } // Predict the time series at the input time given the measured time series, assuming a CARMA(p,q) process std::pair<double, double> KalmanFilterp::Predict(double time) { unsigned int ipredict = 0; while (time > time_(ipredict)) { // find the index where time_ > time for the first time ipredict++; if (ipredict == time_.n_elem) { // time is greater than last element of time_, so do forecasting break; } } // Run the Kalman filter up to the point time_[ipredict-1] Reset(); for (int i=1; i<ipredict; i++) { Update(); } double ypredict_mean, ypredict_var, yprecision; if (ipredict == 0) { // backcasting, so initialize the conditional mean and variance to the stationary values ypredict_mean = 0.0; ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * StateVar_ * rotated_ma_coefs_.t()) ); } else { // predict the value of the time series at time, given the earlier values kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(ipredict-1); state_vector_ += kalman_gain_ * innovation_; PredictionVar_ -= var(ipredict-1) * (kalman_gain_ * kalman_gain_.t()); double dt = std::abs(time - time_(ipredict-1)); rho_ = arma::exp(omega_ * dt); state_vector_ = rho_ % state_vector_; PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // initialize the conditional mean and variance ypredict_mean = std::real( arma::as_scalar(rotated_ma_coefs_ * state_vector_) ); ypredict_var = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ); } if (ipredict == time_.n_elem) { // Forecasting, so we're done: no need to run interpolation steps std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } yprecision = 1.0 / ypredict_var; ypredict_mean *= yprecision; // Either backcasting or interpolating, so need to calculate coefficients of linear filter as a function of // the predicted time series value, then update the running conditional mean and variance of the predicted // time series value InitializeCoefs(time, ipredict, ypredict_mean / yprecision, ypredict_var); yprecision += yslope_ * yslope_ / var(ipredict); ypredict_mean += yslope_ * (y_(ipredict) - yconst_) / var(ipredict); for (int i=ipredict+1; i<time_.n_elem; i++) { UpdateCoefs(); yprecision += yslope_ * yslope_ / var(i); ypredict_mean += yslope_ * (y_(i) - yconst_) / var(i); } ypredict_var = 1.0 / yprecision; ypredict_mean *= ypredict_var; std::pair<double, double> ypredict(ypredict_mean, ypredict_var); return ypredict; } // Initialize the coefficients needed for computing the Kalman Filter at future times as a function of // the time series at time, where time_(itime-1) < time < time_(itime) void KalmanFilterp::InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) { kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / yvar; // initialize the coefficients for predicting the state vector at coefs(time_predict|time_predict) state_const_ = state_vector_ - kalman_gain_ * ymean; state_slope_ = kalman_gain_; // update the state one-step prediction error variance PredictionVar_ -= yvar * (kalman_gain_ * kalman_gain_.t()); // coefs(time_predict|time_predict) --> coefs(time[i+1]|time_predict) double dt = std::abs(time_(itime) - time); rho_ = arma::exp(omega_ * dt); state_const_ = rho_ % state_const_; state_slope_ = rho_ % state_slope_; // update the predicted state covariance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted // y[ipredict] yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) ); yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) ); var(itime) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ) + yerr_(itime) * yerr_(itime); current_index_ = itime + 1; } // Update the coefficients need for computing the Kalman Filter at future times as a function of the // time series value at some earlier time void KalmanFilterp::UpdateCoefs() { kalman_gain_ = PredictionVar_ * rotated_ma_coefs_.t() / var(current_index_-1); // update the coefficients for predicting the state vector at coefs(i|i-1) --> coefs(i|i) state_const_ += kalman_gain_ * (y_(current_index_-1) - yconst_); state_slope_ -= kalman_gain_ * yslope_; // update the state one-step prediction error variance PredictionVar_ -= var(current_index_-1) * (kalman_gain_ * kalman_gain_.t()); // compute the one-step state prediction coefficients: coefs(i|i) --> coefs(i+1|i) rho_ = arma::exp(omega_ * dt_(current_index_-1)); state_const_ = rho_ % state_const_; state_slope_ = rho_ % state_slope_; // update the predicted state covariance matrix PredictionVar_ = (rho_ * rho_.t()) % (PredictionVar_ - StateVar_) + StateVar_; // compute the coefficients for the linear filter at time[ipredict], and compute the variance in the predicted // y[ipredict] yconst_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_const_) ); yslope_ = std::real( arma::as_scalar(rotated_ma_coefs_ * state_slope_) ); var(current_index_) = std::real( arma::as_scalar(rotated_ma_coefs_ * PredictionVar_ * rotated_ma_coefs_.t()) ) + yerr_(current_index_) * yerr_(current_index_); current_index_++; }
42.038462
115
0.671265
Jamieryan
a7d8c4e42f5e8b0f14bec65e1b38b18bc0593325
4,071
cpp
C++
src/Dicom_util.cpp
Swassie/dcmedit
ffa3052386679ac60d5373f0b33bc767aa57de04
[ "BSD-3-Clause" ]
null
null
null
src/Dicom_util.cpp
Swassie/dcmedit
ffa3052386679ac60d5373f0b33bc767aa57de04
[ "BSD-3-Clause" ]
null
null
null
src/Dicom_util.cpp
Swassie/dcmedit
ffa3052386679ac60d5373f0b33bc767aa57de04
[ "BSD-3-Clause" ]
1
2021-05-10T08:54:39.000Z
2021-05-10T08:54:39.000Z
#include "Dicom_util.h" #include "logging/Log.h" #include <dcmtk/dcmdata/dcelem.h> #include <dcmtk/dcmdata/dcitem.h> #include <dcmtk/dcmdata/dcpath.h> #include <dcmtk/dcmdata/dcsequen.h> #include <stdexcept> static DcmObject* get_object(DcmPath* path) { DcmPathNode* last_element = path->back(); if(last_element == nullptr) { throw std::runtime_error("Invalid tag path."); } DcmObject* object = last_element->m_obj; if(object == nullptr) { throw std::runtime_error("Invalid tag path."); } return object; } static void set_element_value(const OFList<DcmPath*>& paths, const std::string& value) { bool error = false; for(DcmPath* path : paths) { DcmPathNode* last_element = path->back(); if(last_element == nullptr) { error = true; continue; } auto element = dynamic_cast<DcmElement*>(last_element->m_obj); if(element == nullptr) { error = true; continue; } OFCondition status = element->putString(value.c_str()); if(status.bad()) { Log::error(std::string("Failed to set element value. Reason: ") + status.text()); error = true; continue; } } if(error) { throw std::runtime_error("At least one error occurred, check log for details."); } } void Dicom_util::set_element(const std::string& tag_path, const std::string& value, DcmDataset& dataset) { DcmPathProcessor path_proc; OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), true); if(status.bad()) { throw std::runtime_error(status.text()); } OFList<DcmPath*> foundPaths; auto resultCount = path_proc.getResults(foundPaths); if(resultCount == 0) { throw std::runtime_error("Tag path not found."); } DcmObject* object = get_object(foundPaths.front()); if(!object->isLeaf()) { if(!value.empty()) { throw std::runtime_error("Can't set value for non-leaf element."); } return; } set_element_value(foundPaths, value); } void Dicom_util::edit_element(const std::string& tag_path, const std::string& value, DcmDataset& dataset) { DcmPathProcessor path_proc; OFCondition status = path_proc.findOrCreatePath(&dataset, tag_path.c_str(), false); if(status.bad()) { throw std::runtime_error(status.text()); } OFList<DcmPath*> foundPaths; auto resultCount = path_proc.getResults(foundPaths); if(resultCount == 0) { throw std::runtime_error("Tag path not found."); } DcmObject* object = get_object(foundPaths.front()); if(!object->isLeaf()) { throw std::runtime_error("Can't edit non-leaf element."); } set_element_value(foundPaths, value); } void Dicom_util::delete_element(const std::string& tag_path, DcmDataset& dataset) { DcmPathProcessor path_proc; unsigned int resultCount = 0; OFCondition status = path_proc.findOrDeletePath(&dataset, tag_path.c_str(), resultCount); if(status.bad()) { throw std::runtime_error(status.text()); } } int Dicom_util::get_index_nr(DcmObject& object) { DcmObject* parent = object.getParent(); if(!parent) { return 0; } const DcmEVR vr = parent->ident(); if(vr == EVR_item || vr == EVR_dataset) { auto item = static_cast<DcmItem*>(parent); auto elementCount = item->getNumberOfValues(); for(auto i = 0u; i < elementCount; ++i) { if(item->getElement(i) == &object) { return i; } } } else if(vr == EVR_SQ) { auto sq = static_cast<DcmSequenceOfItems*>(parent); auto itemCount = sq->getNumberOfValues(); for(auto i = 0u; i < itemCount; ++i) { if(sq->getItem(i) == &object) { return i; } } } Log::error("Could not get index of object. Parent VR: " + std::to_string(vr)); return -1; }
30.380597
93
0.603537
Swassie
a7d8e221b08ecf295bde87bf34c1691c55495dd3
15,082
cpp
C++
underworld/libUnderworld/gLucifer/DrawingObjects/src/SwarmViewer.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
underworld/libUnderworld/gLucifer/DrawingObjects/src/SwarmViewer.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
underworld/libUnderworld/gLucifer/DrawingObjects/src/SwarmViewer.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <petsc.h> #include <Underworld/Function/src/FunctionIO.hpp> #include <Underworld/Function/src/ParticleCoordinate.hpp> #include <Underworld/Function/src/Function.hpp> extern "C" { #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> #include <gLucifer/Base/src/Base.h> #include "types.h" #include <gLucifer/Base/src/DrawingObject.h> } #include "SwarmViewer.h" /* Textual name of this class - This is a global pointer which is used for times when you need to refer to class and not a particular instance of a class */ const Type lucSwarmViewer_Type = (char*) "lucSwarmViewer"; void _lucSwarmViewer_SetFn( void* _self, Fn::Function* fn_colour, Fn::Function* fn_mask, Fn::Function* fn_size, Fn::Function* fn_opacity ){ lucSwarmViewer* self = (lucSwarmViewer*)_self; lucSwarmViewer_cppdata* cppdata = (lucSwarmViewer_cppdata*) self->cppdata; // setup fn input. first make particle coordinate std::shared_ptr<ParticleCoordinate> particleCoord = std::make_shared<ParticleCoordinate>( self->swarm->particleCoordVariable ); // grab first particle for sample data particleCoord->index() = 0; // record fns, and also throw in a min/max guy where required if (fn_colour) { Fn::Function::func func = fn_colour->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_colour = std::make_shared<Fn::MinMax>(fn_colour); cppdata->func_colour = cppdata->fn_colour->getFunction(particleCoord.get()); } if (fn_mask) { cppdata->fn_mask = fn_mask; cppdata->func_mask = cppdata->fn_mask->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(cppdata->func_mask(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); } if (fn_size) { Fn::Function::func func = fn_size->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_size = std::make_shared<Fn::MinMax>(fn_size); cppdata->func_size = cppdata->fn_size->getFunction(particleCoord.get()); } if (fn_opacity) { Fn::Function::func func = fn_opacity->getFunction(particleCoord.get()); const FunctionIO* io = dynamic_cast<const FunctionIO*>(func(particleCoord.get())); if( !io ) throw std::invalid_argument("Provided function does not appear to return a valid result."); if( io->size() != 1 ) throw std::invalid_argument("Provided function must return a scalar result."); // ok we've made it this far, switch out for MinMax version cppdata->fn_opacity = std::make_shared<Fn::MinMax>(fn_opacity); cppdata->func_opacity = cppdata->fn_opacity->getFunction(particleCoord.get()); } } /* Private Constructor: This will accept all the virtual functions for this class as arguments. */ lucSwarmViewer* _lucSwarmViewer_New( LUCSWARMVIEWER_DEFARGS ) { lucSwarmViewer* self; /* Call private constructor of parent - this will set virtual functions of parent and continue up the hierarchy tree. At the beginning of the tree it will allocate memory of the size of object and initialise all the memory to zero. */ assert( _sizeOfSelf >= sizeof(lucSwarmViewer) ); self = (lucSwarmViewer*) _lucDrawingObject_New( LUCDRAWINGOBJECT_PASSARGS ); self->_plotParticle = _plotParticle; self->_setParticleColour = _setParticleColour; self->cppdata = (void*) new lucSwarmViewer_cppdata; return self; } void _lucSwarmViewer_Init( lucSwarmViewer* self, GeneralSwarm* swarm, lucColourMap* opacityColourMap) { self->swarm = swarm; /* Create a default colour component mapping, full range black->white */ self->opacityColourMap = opacityColourMap; self->geomType = lucPointType; /* Draws points by default */ } void _lucSwarmViewer_Delete( void* drawingObject ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; if (self->cppdata) delete (lucSwarmViewer_cppdata*)self->cppdata; _lucDrawingObject_Delete( self ); } void _lucSwarmViewer_Print( void* drawingObject, Stream* stream ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; _lucDrawingObject_Print( self, stream ); } void* _lucSwarmViewer_Copy( void* drawingObject, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; lucSwarmViewer* newDrawingObject; newDrawingObject = (lucSwarmViewer*) _lucDrawingObject_Copy( self, dest, deep, nameExt, ptrMap ); /* TODO */ abort(); return (void*) newDrawingObject; } void* _lucSwarmViewer_DefaultNew( Name name ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(lucSwarmViewer); Type type = lucSwarmViewer_Type; Stg_Class_DeleteFunction* _delete = _lucSwarmViewer_Delete; Stg_Class_PrintFunction* _print = _lucSwarmViewer_Print; Stg_Class_CopyFunction* _copy = NULL; Stg_Component_DefaultConstructorFunction* _defaultConstructor = _lucSwarmViewer_DefaultNew; Stg_Component_ConstructFunction* _construct = _lucSwarmViewer_AssignFromXML; Stg_Component_BuildFunction* _build = _lucSwarmViewer_Build; Stg_Component_InitialiseFunction* _initialise = _lucSwarmViewer_Initialise; Stg_Component_ExecuteFunction* _execute = _lucSwarmViewer_Execute; Stg_Component_DestroyFunction* _destroy = _lucSwarmViewer_Destroy; lucDrawingObject_SetupFunction* _setup = _lucSwarmViewer_Setup; lucDrawingObject_DrawFunction* _draw = _lucSwarmViewer_Draw; lucDrawingObject_CleanUpFunction* _cleanUp = lucDrawingObject_CleanUp; lucSwarmViewer_PlotParticleFunction* _plotParticle = _lucSwarmViewer_PlotParticle; lucSwarmViewer_SetParticleColourFunction* _setParticleColour = _lucSwarmViewer_SetParticleColour; /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */ AllocationType nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */; return (void*) _lucSwarmViewer_New( LUCSWARMVIEWER_PASSARGS ); } void _lucSwarmViewer_AssignFromXML( void* drawingObject, Stg_ComponentFactory* cf, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; GeneralSwarm* swarm; /* Construct Parent */ _lucDrawingObject_AssignFromXML( self, cf, data ); swarm = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"Swarm", GeneralSwarm, True, data ) ; _lucSwarmViewer_Init( self, swarm, Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"OpacityColourMap", lucColourMap, False, data) ); } void _lucSwarmViewer_Build( void* drawingObject, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; _lucDrawingObject_Build( self, data ); } void _lucSwarmViewer_Initialise( void* drawingObject, void* data ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; /* Initialise Parent */ _lucDrawingObject_Initialise( self, data ); } void _lucSwarmViewer_Execute( void* drawingObject, void* data ) {} void _lucSwarmViewer_Destroy( void* drawingObject, void* data ) {} void _lucSwarmViewer_Setup( void* drawingObject, lucDatabase* database, void* _context ) {} void _lucSwarmViewer_Draw( void* drawingObject, lucDatabase* database, void* _context ) { lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; GeneralSwarm* swarm = self->swarm; Particle_Index particleLocalCount = swarm->particleLocalCount; Particle_Index lParticle_I; lucSwarmViewer_cppdata* cppdata = (lucSwarmViewer_cppdata*) self->cppdata; /* reset the min/max values */ if (cppdata->fn_colour) cppdata->fn_colour->reset(); if (cppdata->fn_size) cppdata->fn_size->reset(); if (cppdata->fn_opacity) cppdata->fn_opacity->reset(); // setup fn_io. std::shared_ptr<ParticleCoordinate> particleCoord = std::make_shared<ParticleCoordinate>( self->swarm->particleCoordVariable ); for ( lParticle_I = 0 ; lParticle_I < particleLocalCount ; lParticle_I++) { particleCoord->index() = lParticle_I; /* note we need to cast object to const version to ensure it selects const data() method */ const double* coord = const_cast<const ParticleCoordinate*>(particleCoord.get())->data(); /* Test to see if this particle should be drawn */ if ( cppdata->fn_mask && !cppdata->func_mask(particleCoord.get())->at<bool>()) continue; /* Export particle position */ float coordf[3] = {(float)coord[0],(float) coord[1], swarm->dim == 3 ? (float)coord[2] : 0.0f}; lucDatabase_AddVertices(database, 1, self->geomType, coordf); if (cppdata->fn_colour) { /* evaluate function */ float valuef = cppdata->func_colour(particleCoord.get())->at<float>(); lucDatabase_AddValues(database, 1, self->geomType, lucColourValueData, NULL, &valuef); } if (cppdata->fn_size) { /* evaluate function */ float valuef = cppdata->func_size(particleCoord.get())->at<float>(); lucDatabase_AddValues(database, 1, self->geomType, lucSizeData, NULL, &valuef); } } /* Set the value range */ if (cppdata->fn_colour) lucGeometryData_Setup(database->data[self->geomType][lucColourValueData], cppdata->fn_colour->getMinGlobal(), cppdata->fn_colour->getMaxGlobal()); /* Dynamic Scale Colour Maps */ if ( self->colourMap && self->colourMap->minimum == self->colourMap->maximum && cppdata->fn_colour ) lucColourMap_SetMinMax( self->colourMap, self->colourMap->minimum, self->colourMap->maximum ); } void lucSwarmViewer_SetColourComponent(void* object, lucDatabase* database, SwarmVariable* var, Particle_Index lParticle_I, lucGeometryDataType type, lucColourMap* colourMap) { #if 0 lucSwarmViewer* self = (lucSwarmViewer*)object; if (var && colourMap) { double value; lucColour colour; SwarmVariable_ValueAt( var, lParticle_I, &value ); //lucColourMap_GetColourFromValue( colourMap, value, &colour, self->opacity ); /* Extract and overwrite component value */ if (type == lucRedValueData) self->colour.red = colour.red; if (type == lucGreenValueData) self->colour.green = colour.green; if (type == lucBlueValueData) self->colour.blue = colour.blue; if (type == lucOpacityValueData) self->colour.opacity = colour.opacity; /* Export particle value */ float valuef = value; lucDatabase_AddValues(database, 1, self->geomType, type, colourMap, &valuef); } #endif } /* Default Swarm Viewer Implementation */ void _lucSwarmViewer_SetParticleColour( void* drawingObject, lucDatabase* database, Particle_Index lParticle_I ) { // lucSwarmViewer* self = (lucSwarmViewer*) drawingObject; // SwarmVariable* colourVariable = self->colourVariable; // SwarmVariable* opacityVariable = self->opacityVariable; // lucColourMap* colourMap = self->colourMap; // double colourValue; // // /* Get colour value if there is a colourVariable and a colourMap */ // if ( colourVariable && colourMap ) // { // SwarmVariable_ValueAt( colourVariable, lParticle_I, &colourValue ); // lucColourMap_GetColourFromValue( colourMap, colourValue, &self->colour, self->opacity ); // /* Export particle colour value */ // float valuef = colourValue; // if (database) lucDatabase_AddValues(database, 1, self->geomType, lucColourValueData, colourMap, &valuef); // } // // /* Get Opacity Value */ // lucSwarmViewer_SetColourComponent(self, database, opacityVariable, lParticle_I, lucOpacityValueData, self->opacityColourMap); // // lucColour_SetColour( &self->colour, self->opacity ); } void _lucSwarmViewer_PlotParticle( void* drawingObject, lucDatabase* database, Particle_Index lParticle_I ) { // lucSwarmViewer* self = (lucSwarmViewer*)drawingObject; // float size = 1.0; //= self->pointSize; // if (self->sizeVariable) // { // size = lucSwarmViewer_GetScalar(self->sizeVariable, lParticle_I, size); // lucDatabase_AddValues(database, 1, self->geomType, lucSizeData, NULL, &size); // } } float lucSwarmViewer_GetScalar( SwarmVariable* variable, Particle_Index lParticle_I, float defaultVal ){ abort(); } SwarmVariable* lucSwarmViewer_InitialiseVariable(void* object, Name variableName, Bool scalarRequired, void* data ){ abort(); } void lucSwarmViewer_UpdateVariables( void *drawingObject ){ abort(); } ;
43.970845
237
0.657671
rbeucher
a7d96fd91a8175ef20c22e2aaf1d3c40d7aa2122
21,644
cpp
C++
core/src/glam/jit/math_compiler.cpp
glammath/glam
2eca0625c95ecf4ea0592f06101e13a92926c5cf
[ "Apache-2.0" ]
3
2021-08-01T16:00:11.000Z
2021-08-13T20:51:47.000Z
core/src/glam/jit/math_compiler.cpp
glammath/glam
2eca0625c95ecf4ea0592f06101e13a92926c5cf
[ "Apache-2.0" ]
null
null
null
core/src/glam/jit/math_compiler.cpp
glammath/glam
2eca0625c95ecf4ea0592f06101e13a92926c5cf
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Kioshi Morosin <glam@hex.lc> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "math_compiler.h" #include <wasm-stack.h> #include <binaryen-c.h> #include "globals.h" #define GLAM_COMPILER_TRACE(msg) GLAM_TRACE("[compiler] " << msg) void module_visitor::visit_module() { GLAM_COMPILER_TRACE("visit_module"); this->module = BinaryenModuleCreate(); // we import memory and table from the core module so we can indirect-call functions BinaryenAddMemoryImport(module, "memory", "env", "memory", 0); BinaryenAddTableImport(module, "table", "env", "table"); } void module_visitor::visit_export(const std::string &inner_name, const std::string &outer_name) { GLAM_COMPILER_TRACE("visit_export " << inner_name << " -> " << outer_name); auto exp = new wasm::Export; exp->name = outer_name; exp->value = inner_name; exp->kind = wasm::ExternalKind::Function; module->addExport(exp); } function_visitor *module_visitor::visit_function(const std::string &name, wasm::Signature sig) { GLAM_COMPILER_TRACE("visit_function " << name); auto fv = new function_visitor(this); this->children.push_back(fv); fv->parent = this; fv->func->name = name; fv->func->type = sig; return fv; } template <typename T> compiled_fxn<T> module_visitor::visit_end() { GLAM_COMPILER_TRACE("visit_end module"); uint32_t globalFlags = 0; uint32_t totalArenaSize = 0; std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { globalFlags |= fv->flags; totalArenaSize += fv->arena_size; }); // add fake function imports so binaryen is aware of the function types. increases binary size but i'm not sure // of a better way to do this (using stack IR). if (globalFlags & function_visitor::USES_MPCx1) { GLAM_COMPILER_TRACE("uses mpcx1"); BinaryenType ii[2] = { BinaryenTypeInt32(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ii, 2); BinaryenAddFunctionImport(module, "_operator_nop1", "env", "_operator_nop1", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_MPCx2) { GLAM_COMPILER_TRACE("uses mpcx2"); BinaryenType iii[3] = { BinaryenTypeInt32(), BinaryenTypeInt32(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(iii, 3); BinaryenAddFunctionImport(module, "_operator_nop2", "env", "_operator_nop2", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_F64x2) { GLAM_COMPILER_TRACE("uses f64x2"); BinaryenType ddi[3] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ddi, 3); BinaryenAddFunctionImport(module, "_operator_nop2d", "env", "_operator_nop2", fakeType, BinaryenTypeInt32()); } if (globalFlags & function_visitor::USES_F64x4) { GLAM_COMPILER_TRACE("uses f64x4"); BinaryenType ddddi[5] = { BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeFloat64(), BinaryenTypeInt32() }; auto fakeType = BinaryenTypeCreate(ddddi, 5); BinaryenAddFunctionImport(module, "_operator_nop4", "env", "_operator_nop4", fakeType, BinaryenTypeInt32()); } if (globalFlags & (function_visitor::USES_F64x2 | function_visitor::USES_F64x4 | function_visitor::USES_MPCx1 | function_visitor::USES_MPCx2)) { GLAM_COMPILER_TRACE("uses arena"); BinaryenAddGlobalImport(module, "_arena", "env", "_arena", wasm::Type::i32, false); } auto result = BinaryenModuleAllocateAndWrite(module, nullptr); compiled_fxn<T> fxn(entry_point, fxn_name, parameter_name, result.binary, result.binaryBytes, totalArenaSize); BinaryenModuleDispose(module); std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { delete fv; }); fxn.install(result.binary, result.binaryBytes); free(result.binary); GLAM_COMPILER_TRACE("compilation complete"); return fxn; } void module_visitor::abort() { GLAM_COMPILER_TRACE("mv: aborting early"); std::for_each(children.begin(), children.end(), [&](function_visitor *fv) { delete fv; }); BinaryenModuleDispose(module); } function_visitor::function_visitor(module_visitor *_parent): parent(_parent) { this->func = new wasm::Function; auto nop = parent->module->allocator.alloc<wasm::Nop>(); nop->type = wasm::Type::none; this->func->body = nop; this->func->stackIR = std::make_unique<wasm::StackIR>(); } void function_visitor::visit_entry_point() { GLAM_COMPILER_TRACE("visit_entry_point " << func->name.str); parent->entry_point = func->name.str; } void function_visitor::visit_float(double d) { GLAM_COMPILER_TRACE("visit_float " << d); auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::f64; c->value = wasm::Literal(d); visit_basic(c); } void function_visitor::visit_complex(std::complex<double> z) { visit_float(z.real()); visit_float(z.imag()); } void function_visitor::visit_basic(wasm::Expression *inst) { inst->finalize(); auto si = parent->module->allocator.alloc<wasm::StackInst>(); si->op = wasm::StackInst::Basic; si->type = inst->type; si->origin = inst; func->stackIR->push_back(si); } void function_visitor::visit_complex(const mp_complex &z) { auto ptr = std::find(local_consts.begin(), local_consts.end(), z); if (ptr == local_consts.end()) { local_consts.push_back(z); } visit_global_get("_complex_" + std::to_string(ptr - local_consts.begin())); } template <typename T> void function_visitor::visit_ptr(T *ptr) { auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::i32; c->value = wasm::Literal(static_cast<int32_t>(reinterpret_cast<uintptr_t>(ptr))); visit_basic(c); } void function_visitor::visit_global_get(const std::string &name) { auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = name; } void function_visitor::visit_mpcx2(morpheme_mpcx2 *morph) { GLAM_COMPILER_TRACE("visit_mpcx2"); arena_size += 2; flags |= USES_MPCx2; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = "_arena"; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (iii)->i callIndirect->table = "table"; callIndirect->isReturn = false; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); } void function_visitor::visit_mpcx1(morpheme_mpcx1 *morph) { GLAM_COMPILER_TRACE("visit_mpcx1"); arena_size++; flags |= USES_MPCx1; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->type = wasm::Type::i32; globalGet->name = "_arena"; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::i32, wasm::Type::i32 }), wasm::Type::i32); // (ii)->i callIndirect->table = "table"; callIndirect->isReturn = false; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); } bool function_visitor::visit_variable_mp(const std::string &name) { GLAM_COMPILER_TRACE("visit_variable_mp " << name); if (name == parent->parameter_name) { auto localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::i32; localGet->index = 0; visit_basic(localGet); return true; } else { auto ptr = globals::consts_mp.find(name); if (ptr == globals::consts_mp.end()) { return false; } else { visit_ptr(ptr->second); return true; } } } void function_visitor::visit_binary_splat(wasm::BinaryOp op) { auto localSetD = parent->module->allocator.alloc<wasm::LocalSet>(); localSetD->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetD); auto localSetC = parent->module->allocator.alloc<wasm::LocalSet>(); localSetC->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetC); auto localSetB = parent->module->allocator.alloc<wasm::LocalSet>(); localSetB->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSetB); auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>(); localGetC->index = localSetC->index; localGetC->type = wasm::Type::f64; visit_basic(localGetC); auto inst = parent->module->allocator.alloc<wasm::Binary>(); inst->type = wasm::Type::f64; inst->op = op; visit_basic(inst); auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>(); localGetB->index = localSetB->index; localGetB->type = wasm::Type::f64; visit_basic(localGetB); auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>(); localGetD->index = localSetD->index; localGetD->type = wasm::Type::f64; visit_basic(localGetD); visit_basic(inst); } void function_visitor::visit_add() { GLAM_COMPILER_TRACE("visit_add (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); visit_binary_splat(wasm::AddFloat64); } } void function_visitor::visit_sub() { GLAM_COMPILER_TRACE("visit_sub (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); visit_binary_splat(wasm::SubFloat64); } } void function_visitor::visit_mul() { GLAM_COMPILER_TRACE("visit_mul (dp)"); if (flags & GEN_SIMD) { } else { visit_unwrap(); wasm::Index i = visit_binary(); auto localGetC = parent->module->allocator.alloc<wasm::LocalGet>(); localGetC->index = i + 1; localGetC->type = wasm::Type::f64; auto mul = parent->module->allocator.alloc<wasm::Binary>(); mul->type = wasm::Type::f64; mul->op = wasm::MulFloat64; auto localGetB = parent->module->allocator.alloc<wasm::LocalGet>(); localGetB->index = i + 2; localGetB->type = wasm::Type::f64; auto localGetA = parent->module->allocator.alloc<wasm::LocalGet>(); localGetA->index = i + 3; localGetA->type = wasm::Type::f64; auto localGetD = parent->module->allocator.alloc<wasm::LocalGet>(); localGetD->index = i; localGetD->type = wasm::Type::f64; auto add = parent->module->allocator.alloc<wasm::Binary>(); add->type = wasm::Type::f64; add->op = wasm::AddFloat64; auto sub = parent->module->allocator.alloc<wasm::Binary>(); sub->type = wasm::Type::f64; sub->op = wasm::SubFloat64; visit_basic(localGetC); visit_basic(mul); visit_basic(localGetB); visit_basic(localGetD); visit_basic(mul); visit_basic(sub); visit_basic(localGetA); visit_basic(localGetD); visit_basic(mul); visit_basic(localGetB); visit_basic(localGetC); visit_basic(mul); visit_basic(add); } } void function_visitor::visit_div() { GLAM_COMPILER_TRACE("visit_div (dp)"); if (flags & GEN_SIMD) { } else { // we use a morpheme here because division is hard visit_f64x4(&_fmorpheme_div); } } void function_visitor::visit_f64x2(morpheme_f64x2 *morph) { GLAM_COMPILER_TRACE("visit_f64x2"); visit_unwrap(); arena_size++; flags |= USES_F64x2; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->name = "_arena"; globalGet->type = wasm::Type::i32; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->type = wasm::Type::i32; callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }), wasm::Type::i32); // (ddi)->i callIndirect->table = "table"; callIndirect->isReturn = false; visit_basic(callIndirect); needs_unwrap = true; } wasm::Index function_visitor::visit_binary() { flags |= USES_BINARY; // (a, b) (c, d) wasm::Index var = wasm::Builder::addVar(func, wasm::Type::f64); auto localSet1 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet1->index = var; visit_basic(localSet1); auto localSet2 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet2->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet2); auto localSet3 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet3->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet3); auto localSet4 = parent->module->allocator.alloc<wasm::LocalSet>(); localSet4->index = wasm::Builder::addVar(func, wasm::Type::f64); localSet4->type = wasm::Type::f64; visit_basic(localSet4); return var; } void function_visitor::visit_unwrap() { if (needs_unwrap) { GLAM_COMPILER_TRACE("visit_unwrap"); this->flags |= USES_UNWRAP; visit_dupi32(); auto loadIm = parent->module->allocator.alloc<wasm::Load>(); loadIm->type = wasm::Type::f64; loadIm->offset = 8; // get the imaginary part first loadIm->bytes = 8; loadIm->isAtomic = false; visit_basic(loadIm); auto localSet = parent->module->allocator.alloc<wasm::LocalSet>(); localSet->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localSet); auto loadRe = parent->module->allocator.alloc<wasm::Load>(); loadRe->type = wasm::Type::f64; loadRe->offset = 0; loadRe->bytes = 8; loadRe->isAtomic = false; visit_basic(loadRe); auto localGet1 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet1->index = localSet->index; localGet1->type = wasm::Type::f64; visit_basic(localGet1); needs_unwrap = false; } } void function_visitor::visit_f64x4(morpheme_f64x4 *morph) { GLAM_COMPILER_TRACE("visit_f64x4"); visit_unwrap(); arena_size++; flags |= USES_F64x4; auto globalGet = parent->module->allocator.alloc<wasm::GlobalGet>(); globalGet->name = "_arena"; globalGet->type = wasm::Type::i32; visit_basic(globalGet); visit_ptr(morph); auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->type = wasm::Type::i32; callIndirect->sig = wasm::Signature(wasm::Type({ wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::f64, wasm::Type::i32 }), wasm::Type::i32); // (ddddi)->i callIndirect->table = "table"; callIndirect->isReturn = false; visit_basic(callIndirect); needs_unwrap = true; } void function_visitor::visit_fxncall(const std::string &name) { uintptr_t ptr = globals::fxn_table[name]; assert(ptr); // should never fail, the parser checks first GLAM_COMPILER_TRACE("visit_fxncall " << name << " @ " << ptr); auto c = parent->module->allocator.alloc<wasm::Const>(); c->type = wasm::Type::i32; c->value = wasm::Literal(static_cast<uint32_t>(ptr)); visit_basic(c); // todo for now we assume that it's also a double-precision fxn, i.e. it is (f64, f64)->i32 auto callIndirect = parent->module->allocator.alloc<wasm::CallIndirect>(); callIndirect->isReturn = false; callIndirect->sig = wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32); callIndirect->table = "table"; callIndirect->type = wasm::Type::i32; visit_basic(callIndirect); needs_unwrap = true; } bool function_visitor::visit_variable_dp(const std::string &name) { GLAM_COMPILER_TRACE("visit_variable_dp " << name); visit_unwrap(); if (name == parent->parameter_name) { auto localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::f64; localGet->index = 0; visit_basic(localGet); localGet = parent->module->allocator.alloc<wasm::LocalGet>(); localGet->type = wasm::Type::f64; localGet->index = 1; visit_basic(localGet); return true; } else { auto z = globals::consts_dp.find(name); if (z == globals::consts_dp.end()) { return false; } else { visit_complex(z->second); return true; } } } void function_visitor::visit_dupi32() { // wasm doesn't have a dup opcode so this is what we have to do auto localTee = parent->module->allocator.alloc<wasm::LocalSet>(); localTee->type = wasm::Type::i32; localTee->index = wasm::Builder::addVar(func, wasm::Type::i32); visit_basic(localTee); auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet0->type = wasm::Type::i32; localGet0->index = localTee->index; visit_basic(localGet0); } void function_visitor::visit_dupf64() { flags |= USES_DUPF64; auto localTee = parent->module->allocator.alloc<wasm::LocalSet>(); localTee->type = wasm::Type::f64; localTee->index = wasm::Builder::addVar(func, wasm::Type::f64); visit_basic(localTee); auto localGet0 = parent->module->allocator.alloc<wasm::LocalGet>(); localGet0->type = wasm::Type::f64; localGet0->index = localTee->index; visit_basic(localGet0); } function_visitor::~function_visitor() noexcept { delete this->func; } std::string function_visitor::visit_end() { GLAM_COMPILER_TRACE("visit_end function"); if (!needs_unwrap) { // now we actually need to wrap GLAM_COMPILER_TRACE("wrapping complex"); visit_f64x2(&_fmorpheme_wrap); } auto ret = parent->module->allocator.alloc<wasm::Return>(); visit_basic(ret); parent->module->addFunction(func); return func->name.c_str(); } std::map<std::string, morpheme_f64x2 *> math_compiler_dp::unary_morphemes = { std::make_pair("sin", &_fmorpheme_sin), std::make_pair("cos", &_fmorpheme_cos), std::make_pair("tan", &_fmorpheme_tan), std::make_pair("sinh", &_fmorpheme_sinh), std::make_pair("cosh", &_fmorpheme_cosh), std::make_pair("tanh", &_fmorpheme_tanh) }; std::map<std::string, morpheme_f64x4 *> math_compiler_dp::binary_morphemes = { std::make_pair("^", &_fmorpheme_exp) }; void math_compiler_dp::visit_operator(function_visitor *fv, const std::string &op) { GLAM_COMPILER_TRACE("compiling operator " << op); if (op == "+") { fv->visit_add(); return; } else if (op == "-") { fv->visit_sub(); return; } else if (op == "*") { fv->visit_mul(); return; } else if (op == "/") { fv->visit_div(); return; } else { auto iter1 = unary_morphemes.find(op); if (iter1 != unary_morphemes.end()) { fv->visit_f64x2(*iter1->second); return; } else { auto iter2 = binary_morphemes.find(op); if (iter2 != binary_morphemes.end()) { fv->visit_f64x4(*iter2->second); return; } } } GLAM_COMPILER_TRACE("unrecognized operator"); abort(); } fxn<std::complex<double>, compiled_fxn<std::complex<double>>> math_compiler_dp::compile(const emscripten::val &stack) { module_visitor mv(fxn_name, parameter_name); mv.visit_module(); auto fv = mv.visit_function(name, wasm::Signature({ wasm::Type::f64, wasm::Type::f64 }, wasm::Type::i32)); const auto len = stack["length"].as<size_t>(); assert(len > 0); for (size_t i = 0; i < len; i++) { emscripten::val stackObj = stack[i]; auto type = stackObj["type"].as<int32_t>(); auto value = stackObj["value"].as<std::string>(); switch (type) { case 0: // NUMBER // we take advantage of boost's parsing even if we don't want a multiprecision complex number fv->visit_complex(mp_complex(value).convert_to<std::complex<double>>()); break; case 1: // IDENTIFIER if (!fv->visit_variable_dp(value)) { mv.abort(); abort(); } break; case 2: // OPERATOR visit_operator(fv, value); break; case 3: // FXNCALL fv->visit_fxncall(value); break; default: GLAM_COMPILER_TRACE("unrecognized stack object " << type); mv.abort(); abort(); } } fv->visit_entry_point(); auto f_name = fv->visit_end(); mv.visit_export(f_name, name); return mv.visit_end<std::complex<double>>(); }
35.022654
140
0.640362
glammath
a7dad1058da0ab8e4d01ee5c7c23121560b4d0da
13,357
cpp
C++
modules/base/processors/meshcreator.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
modules/base/processors/meshcreator.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
modules/base/processors/meshcreator.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/base/processors/meshcreator.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <inviwo/core/datastructures/geometry/simplemeshcreator.h> #include <inviwo/core/interaction/events/pickingevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/interaction/events/touchevent.h> #include <inviwo/core/interaction/events/wheelevent.h> namespace inviwo { const ProcessorInfo MeshCreator::processorInfo_{ "org.inviwo.MeshCreator", // Class identifier "Mesh Creator", // Display name "Mesh Creation", // Category CodeState::Stable, // Code state Tags::CPU, // Tags }; const ProcessorInfo MeshCreator::getProcessorInfo() const { return processorInfo_; } MeshCreator::MeshCreator() : Processor() , outport_("outport") , position1_("position1", "Start Position", vec3(0.0f, 0.0f, 0.0f), vec3(-50.0f), vec3(50.0f)) , position2_("position2", "Stop Position", vec3(1.0f, 0.0f, 0.0f), vec3(-50.0f), vec3(50.0f)) , basis_("Basis", "Basis and offset") , normal_("normal", "Normal", vec3(0.0f, 0.0f, 1.0f), vec3(-50.0f), vec3(50.0f)) , color_("color", "Color", vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color) , torusRadius1_("torusRadius1_", "Torus Radius 1", 1.0f) , torusRadius2_("torusRadius2_", "Torus Radius 2", 0.3f) , meshScale_("scale", "Size scaling", 1.f, 0.01f, 10.f) , meshRes_("res", "Mesh resolution", vec2(16), vec2(1), vec2(1024)) , meshType_("meshType", "Mesh Type") , enablePicking_("enablePicking", "Enable Picking", false) , picking_(this, 1, [&](PickingEvent* p) { if (enablePicking_) handlePicking(p); }) , camera_("camera", "Camera") , pickingUpdate_{[](PickingEvent*){}} { addPort(outport_); meshType_.addOption("sphere", "Sphere", MeshType::Sphere); meshType_.addOption("colorsphere", "Color Sphere", MeshType::ColorSphere); meshType_.addOption("cube_basic_mesh", "Cube (Basic Mesh)", MeshType::CubeBasicMesh); meshType_.addOption("cube", "Cube (Simple Mesh)", MeshType::CubeSimpleMesh); meshType_.addOption("linecube", "Line cube", MeshType::LineCube); meshType_.addOption("linecubeadjacency", "Line cube adjacency", MeshType::LineCubeAdjacency); meshType_.addOption("plane", "Plane", MeshType::Plane); meshType_.addOption("disk", "Disk", MeshType::Disk); meshType_.addOption("cone", "Cone", MeshType::Cone); meshType_.addOption("cylinder", "Cylinder", MeshType::Cylinder); meshType_.addOption("arrow", "Arrow", MeshType::Arrow); meshType_.addOption("coordaxes", "Coordinate Indicator", MeshType::CoordAxes); meshType_.addOption("torus", "Torus", MeshType::Torus); meshType_.addOption("sphereopt", "Sphere with Position", MeshType::SphereOpt); util::hide(position1_, position2_, normal_, basis_, color_ , torusRadius1_ , torusRadius2_); util::show(meshScale_, meshRes_); meshType_.set(MeshType::Sphere); meshType_.setCurrentStateAsDefault(); meshType_.onChange([this]() { auto updateNone = [](PickingEvent*) {}; auto getDelta = [this](PickingEvent* p) { auto currNDC = p->getNDC(); auto prevNDC = p->getPreviousNDC(); // Use depth of initial press as reference to move in the image plane. auto refDepth = p->getPressedDepth(); currNDC.z = refDepth; prevNDC.z = refDepth; auto corrWorld = camera_.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC)); auto prevWorld = camera_.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC)); return (corrWorld - prevWorld); }; auto updatePosition1 = [this, getDelta](PickingEvent* p) { position1_.set(position1_.get() + getDelta(p)); }; auto updatePosition1and2 = [this, getDelta](PickingEvent* p) { auto delta = getDelta(p); position1_.set(position1_.get() + delta); position2_.set(position2_.get() + delta); }; auto updateBasis = [this, getDelta](PickingEvent* p) { basis_.offset_.set(basis_.offset_.get() + getDelta(p)); }; util::hide(position1_, position2_, normal_, basis_, meshScale_, meshRes_, color_, torusRadius1_, torusRadius2_); switch (meshType_.get()) { case MeshType::Sphere: { pickingUpdate_ = updateNone; util::show(meshScale_, meshRes_); break; } case MeshType::ColorSphere: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_); break; } case MeshType::CubeBasicMesh: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, color_); break; } case MeshType::CubeSimpleMesh: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_); break; } case MeshType::LineCube: { pickingUpdate_ = updateBasis; util::show(basis_, color_); break; } case MeshType::LineCubeAdjacency: { pickingUpdate_ = updateBasis; util::show(basis_, color_); break; } case MeshType::Plane: { pickingUpdate_ = updatePosition1; util::show(position1_, normal_, meshScale_, meshRes_, color_); break; } case MeshType::Disk: { pickingUpdate_ = updatePosition1; util::show(position1_, normal_, meshScale_, meshRes_, color_); break; } case MeshType::Cone: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::Cylinder: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::Arrow: { pickingUpdate_ = updatePosition1and2; util::show(position1_, position2_, meshScale_, meshRes_, color_); break; } case MeshType::CoordAxes: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_); break; } case MeshType::Torus: { pickingUpdate_ = updatePosition1; util::show(position1_,torusRadius1_, torusRadius2_,meshRes_,color_); break; } case MeshType::SphereOpt: { pickingUpdate_ = updatePosition1; util::show(position1_, meshScale_, color_); break; } default: { pickingUpdate_ = updateNone; util::show(meshScale_, meshRes_); break; } } }); addProperty(meshType_); addProperty(position1_); addProperty(position2_); addProperty(normal_); addProperty(basis_); addProperty(torusRadius1_); addProperty(torusRadius2_); addProperty(color_); addProperty(meshScale_); addProperty(meshRes_); addProperty(enablePicking_); addProperty(camera_); camera_.setInvalidationLevel(InvalidationLevel::Valid); camera_.setCollapsed(true); } MeshCreator::~MeshCreator() {} std::shared_ptr<Mesh> MeshCreator::createMesh() { switch (meshType_.get()) { case MeshType::Sphere: return SimpleMeshCreator::sphere(0.5f * meshScale_.get(), meshRes_.get().y, meshRes_.get().x); case MeshType::ColorSphere: return BasicMesh::colorsphere(position1_, meshScale_.get()); case MeshType::CubeBasicMesh: { vec3 posLLF = position1_; vec3 posURB = position2_; mat4 m = glm::translate(mat4(1.0f), posLLF); m = glm::scale(m, posURB - posLLF); return BasicMesh::cube(m, color_.get()); } case MeshType::CubeSimpleMesh: { vec3 posLLF = position1_; vec3 posURB = position2_; return SimpleMeshCreator::rectangularPrism(posLLF, posURB, posLLF, posURB, vec4(posLLF, 1.f), vec4(posURB, 1.f)); } case MeshType::LineCube: return BasicMesh::boundingbox(basis_.getBasisAndOffset(), color_); case MeshType::LineCubeAdjacency: return BasicMesh::boundingBoxAdjacency(basis_.getBasisAndOffset(), color_); case MeshType::Plane: { return BasicMesh::square(position1_, normal_, vec2(1.0f, 1.0f) * meshScale_.get(), color_, meshRes_.get()); } case MeshType::Disk: return BasicMesh::disk(position1_, normal_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Cone: return BasicMesh::cone(position1_, position2_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Cylinder: return BasicMesh::cylinder(position1_, position2_, color_, meshScale_.get(), meshRes_.get().x); case MeshType::Arrow: return BasicMesh::arrow(position1_, position2_, color_, meshScale_.get(), 0.15f, meshScale_.get() * 2, meshRes_.get().x); case MeshType::CoordAxes: return BasicMesh::coordindicator(position1_, meshScale_.get()); case MeshType::Torus: return BasicMesh::torus(position1_, vec3(0, 0, 1), torusRadius1_, torusRadius2_, meshRes_, color_); case MeshType::SphereOpt: return BasicMesh::sphere(position1_, meshScale_, color_); default: return SimpleMeshCreator::sphere(0.1f, meshRes_.get().x, meshRes_.get().y); } } void MeshCreator::handlePicking(PickingEvent* p) { if (p->getState() == PickingState::Updated && p->getEvent()->hash() == MouseEvent::chash()) { auto me = p->getEventAs<MouseEvent>(); if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) { pickingUpdate_(p); p->markAsUsed(); } } else if (p->getState() == PickingState::Updated && p->getEvent()->hash() == TouchEvent::chash()) { auto te = p->getEventAs<TouchEvent>(); if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) { pickingUpdate_(p); p->markAsUsed(); } } } void MeshCreator::process() { auto mesh = createMesh(); if (enablePicking_) { // Add picking ids auto bufferRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(mesh->getBuffer(0)->getSize()); auto pickBuffer = std::make_shared<Buffer<uint32_t>>(bufferRAM); auto& data = bufferRAM->getDataContainer(); std::fill(data.begin(), data.end(), static_cast<uint32_t>(picking_.getPickingId(0))); mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4), pickBuffer); } outport_.setData(mesh); } } // namespace
41.740625
104
0.596242
victorca25
a7dec0fd98ba900c1a7008a69f24db37baf08b54
4,543
cpp
C++
src/Core/src/simple_face.cpp
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
6
2016-11-01T11:09:00.000Z
2022-02-15T06:31:58.000Z
src/Core/src/simple_face.cpp
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
null
null
null
src/Core/src/simple_face.cpp
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
null
null
null
#include "precompiled.h" #include "cleanup_loop.h" #include "equality_context.h" #include "exceptions.h" #include "sbt-core.h" #include "stringification.h" #include "simple_face.h" namespace { typedef std::vector<point_3> loop; loop create_loop(const polyloop & p, equality_context * c) { std::vector<ipoint_3> pts; for (size_t i = 0; i < p.vertex_count; ++i) { pts.push_back(ipoint_3(p.vertices[i].x, p.vertices[i].y, p.vertices[i].z)); } loop res; if (geometry_common::cleanup_loop(&pts, c->height_epsilon())) { boost::transform(pts, std::back_inserter(res), [c](const ipoint_3 & p) { return c->request_point(p.x(), p.y(), p.z()); }); } return res; } } // namespace simple_face::simple_face( const face & f, bool force_planar, equality_context * c) { using boost::transform; using geometry_common::calculate_plane_and_average_point; using geometry_common::share_sense; auto raw_loop = create_loop(f.outer_boundary, c); if (raw_loop.size() < 3) { throw invalid_face_exception(); } plane_3 raw_pl; std::tie(raw_pl, m_average_point) = calculate_plane_and_average_point(raw_loop, *c); if (raw_pl.is_degenerate()) { throw invalid_face_exception(); } auto snapped_dir = c->snap(raw_pl.orthogonal_direction()); m_plane = plane_3(m_average_point, snapped_dir); auto project = [this](const point_3 & p) { return m_plane.projection(p); }; if (force_planar) { transform(raw_loop, std::back_inserter(m_outer), project); } else { m_outer = raw_loop; } for (size_t i = 0; i < f.void_count; ++i) { auto inner = create_loop(f.voids[i], c); auto inner_pl = std::get<0>(calculate_plane_and_average_point(inner, *c)); auto inner_dir = inner_pl.orthogonal_direction(); if (!share_sense(m_plane.orthogonal_direction(), inner_dir)) { boost::reverse(inner); } if (force_planar) { m_inners.push_back(loop()); transform(inner, std::back_inserter(m_inners.back()), project); } else { m_inners.push_back(inner); } } #ifndef NDEBUG direction_3 normal = m_plane.orthogonal_direction(); debug_dx = CGAL::to_double(normal.dx()); debug_dy = CGAL::to_double(normal.dy()); debug_dz = CGAL::to_double(normal.dz()); #endif } simple_face & simple_face::operator = (simple_face && src) { if (&src != this) { m_outer = std::move(src.m_outer); m_inners = std::move(src.m_inners); m_plane = std::move(src.m_plane); m_average_point = std::move(src.m_average_point); } return *this; } bool simple_face::is_planar() const { for (auto p = m_outer.begin(); p != m_outer.end(); ++p) { if (!m_plane.has_on(*p)) { return false; } } for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) { for (auto p = hole->begin(); p != hole->end(); ++p) { if (!m_plane.has_on(*p)) { return false; } } } return true; } std::string simple_face::to_string() const { std::stringstream ss; ss << "Outer:\n"; for (auto p = m_outer.begin(); p != m_outer.end(); ++p) { ss << reporting::to_string(*p) << std::endl; } for (auto hole = m_inners.begin(); hole != m_inners.end(); ++hole) { ss << "Hole:\n"; for (auto p = hole->begin(); p != hole->end(); ++p) { ss << reporting::to_string(*p) << std::endl; } } return ss.str(); } simple_face simple_face::reversed() const { typedef std::vector<point_3> loop; std::vector<loop> inners; boost::transform( m_inners, std::back_inserter(inners), [](const loop & inner) { return loop(inner.rbegin(), inner.rend()); }); return simple_face( m_outer | boost::adaptors::reversed, inners, m_plane.opposite(), m_average_point); } std::vector<segment_3> simple_face::all_edges_voids_reversed() const { std::vector<segment_3> res; for (size_t i = 0; i < m_outer.size(); ++i) { res.push_back(segment_3(m_outer[i], m_outer[(i+1) % m_outer.size()])); } res.push_back(segment_3(m_outer.back(), m_outer.front())); boost::for_each(m_inners, [&res](const std::vector<point_3> & inner) { for (size_t i = 0; i < inner.size(); ++i) { res.push_back(segment_3(inner[(i+1) % inner.size()], inner[i])); } res.push_back(segment_3(inner.front(), inner.back())); }); return res; } simple_face simple_face::transformed(const transformation_3 & t) const { loop new_outer; boost::transform(m_outer, std::back_inserter(new_outer), t); std::vector<loop> new_inners; for (auto h = m_inners.begin(); h != m_inners.end(); ++h) { new_inners.push_back(loop()); boost::transform(*h, std::back_inserter(new_inners.back()), t); } return simple_face(new_outer, new_inners, t(m_plane), t(m_average_point)); }
28.572327
124
0.673784
rosecodym
a7df04203507436d4a61eb1502cf5807768cf9bf
1,408
cpp
C++
thrift/lib/cpp2/test/PathsTest.cpp
tahmidbintaslim/fbthrift
1492869dbd748295a2262ad76a19623c90e47b95
[ "Apache-2.0" ]
null
null
null
thrift/lib/cpp2/test/PathsTest.cpp
tahmidbintaslim/fbthrift
1492869dbd748295a2262ad76a19623c90e47b95
[ "Apache-2.0" ]
null
null
null
thrift/lib/cpp2/test/PathsTest.cpp
tahmidbintaslim/fbthrift
1492869dbd748295a2262ad76a19623c90e47b95
[ "Apache-2.0" ]
1
2020-02-13T10:42:16.000Z
2020-02-13T10:42:16.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <cmath> #include <iostream> #include <string> #include <folly/portability/GTest.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/test/gen-cpp2/Paths_types.h> using namespace apache::thrift; using namespace apache::thrift::test; TEST(PathsDemo, example) { Path1 p1; // list of pairs, 5005 bytes Path2 p2; // pair of lists, 2009 bytes for (int i = 0; i < 1000; ++i) { int x = 60 * std::cos(i * 0.01); int y = 60 * std::sin(i * 0.01); Point p; p.x = x; p.y = y; p1.points.push_back(p); p2.xs.push_back(x); p2.ys.push_back(y); } auto s1 = CompactSerializer::serialize<std::string>(p1); auto s2 = CompactSerializer::serialize<std::string>(p2); EXPECT_EQ(5005, s1.size()); EXPECT_EQ(2009, s2.size()); }
28.16
75
0.683239
tahmidbintaslim
a7dffd0919a0fea4d1d18d9f854a2712191faf87
11,425
cpp
C++
src/mongocxx/test/sdam-monitoring.cpp
lzlzymy/mongo-cxx-driver
bcdeb3ad9412f6b7b87a45dc3384ad18759ac572
[ "Apache-2.0" ]
null
null
null
src/mongocxx/test/sdam-monitoring.cpp
lzlzymy/mongo-cxx-driver
bcdeb3ad9412f6b7b87a45dc3384ad18759ac572
[ "Apache-2.0" ]
null
null
null
src/mongocxx/test/sdam-monitoring.cpp
lzlzymy/mongo-cxx-driver
bcdeb3ad9412f6b7b87a45dc3384ad18759ac572
[ "Apache-2.0" ]
null
null
null
// Copyright 2018-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <set> #include <bsoncxx/stdx/optional.hpp> #include <bsoncxx/string/to_string.hpp> #include <bsoncxx/test_util/catch.hh> #include <mongocxx/client.hpp> #include <mongocxx/exception/exception.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/test/spec/operation.hh> #include <mongocxx/test_util/client_helpers.hh> // Don't use SDAM Monitoring spec tests, we'd need libmongoc internals to send hello replies. namespace { using namespace mongocxx; using bsoncxx::oid; using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using bsoncxx::string::to_string; void open_and_close_client(const uri& test_uri, const options::apm& apm_opts) { // Apply listeners and trigger connection. options::client client_opts; client_opts.apm_opts(apm_opts); client client{test_uri, test_util::add_test_server_api(client_opts)}; client["admin"].run_command(make_document(kvp("ping", 1))); } TEST_CASE("SDAM Monitoring", "[sdam_monitoring]") { instance::current(); std::string rs_name; uri test_uri; client discoverer{uri{}, test_util::add_test_server_api()}; auto topology_type = test_util::get_topology(discoverer); if (topology_type == "replicaset") { rs_name = test_util::replica_set_name(discoverer); test_uri = uri{"mongodb://localhost/?replicaSet=" + rs_name}; } options::apm apm_opts; stdx::optional<oid> topology_id; SECTION("Server Events") { int server_opening_events = 0; int server_changed_events = 0; /////////////////////////////////////////////////////////////////////// // Begin server description listener lambdas /////////////////////////////////////////////////////////////////////// // ServerOpeningEvent apm_opts.on_server_opening([&](const events::server_opening_event& event) { server_opening_events++; if (topology_id) { // A previous server was opened first. REQUIRE(topology_id.value() == event.topology_id()); } topology_id = event.topology_id(); }); // ServerDescriptionChanged apm_opts.on_server_changed([&](const events::server_changed_event& event) { server_changed_events++; // A server_opening_event should have set topology_id. REQUIRE(topology_id); REQUIRE(topology_id.value() == event.topology_id()); auto old_sd = event.previous_description(); auto new_sd = event.new_description(); auto new_type = to_string(new_sd.type()); REQUIRE(old_sd.hello().empty()); REQUIRE(to_string(old_sd.host()) == to_string(event.host())); REQUIRE(old_sd.port() == event.port()); REQUIRE(old_sd.round_trip_time() == -1); REQUIRE(to_string(old_sd.type()) == "Unknown"); REQUIRE(to_string(new_sd.host()) == to_string(event.host())); REQUIRE_FALSE(new_sd.hello().empty()); REQUIRE(new_sd.port() == event.port()); REQUIRE(new_sd.round_trip_time() >= 0); if (topology_type == "single") { REQUIRE(new_type == "Standalone"); } else if (topology_type == "replicaset") { // RSPrimary, RSSecondary, etc. REQUIRE(new_type.substr(0, 2) == "RS"); } else { REQUIRE(topology_type == "sharded"); REQUIRE(new_type == "Mongos"); } REQUIRE(old_sd.id() == new_sd.id()); }); // We don't expect a ServerClosedEvent unless a replica set member is removed. /////////////////////////////////////////////////////////////////////// // End server description listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(server_opening_events > 0); REQUIRE(server_changed_events > 0); } SECTION("Topology Events") { int topology_opening_events = 0; int topology_changed_events = 0; int topology_closed_events = 0; bool found_servers = false; /////////////////////////////////////////////////////////////////////// // Begin topology description listener lambdas /////////////////////////////////////////////////////////////////////// // TopologyOpeningEvent apm_opts.on_topology_opening([&](const events::topology_opening_event& event) { topology_opening_events++; if (topology_id) { // A previous server was opened first. REQUIRE(topology_id.value() == event.topology_id()); } topology_id = event.topology_id(); }); // TopologyDescriptionChanged apm_opts.on_topology_changed([&](const events::topology_changed_event& event) { topology_changed_events++; // A topology_opening_event should have set topology_id. REQUIRE(topology_id); REQUIRE(topology_id.value() == event.topology_id()); auto old_td = event.previous_description(); auto new_td = event.new_description(); auto new_type = to_string(new_td.type()); auto new_servers = new_td.servers(); if (topology_changed_events == 1) { // First event, nothing discovered yet. REQUIRE(old_td.servers().size() == 0); REQUIRE_FALSE(old_td.has_readable_server(read_preference{})); REQUIRE_FALSE(old_td.has_writable_server()); } if (topology_type == "replicaset") { if (new_td.has_writable_server()) { REQUIRE(new_type == "ReplicaSetWithPrimary"); } else { REQUIRE(new_type == "ReplicaSetNoPrimary"); } } else { REQUIRE(new_type == "Single"); } for (auto&& new_sd : new_servers) { found_servers = true; auto new_sd_type = to_string(new_sd.type()); REQUIRE(new_sd.host().length()); REQUIRE_FALSE(new_sd.hello().empty()); REQUIRE(new_sd.port() > 0); REQUIRE(new_sd.round_trip_time() >= 0); if (topology_type == "single") { REQUIRE(new_sd_type == "Standalone"); } else if (topology_type == "replicaset") { // RSPrimary, RSSecondary, etc. REQUIRE(new_sd_type.substr(0, 2) == "RS"); } else { REQUIRE(topology_type == "sharded"); REQUIRE(new_sd_type == "Mongos"); } } }); // TopologyClosedEvent apm_opts.on_topology_closed([&](const events::topology_closed_event& event) { topology_closed_events++; REQUIRE(topology_id.value() == event.topology_id()); }); /////////////////////////////////////////////////////////////////////// // End topology description listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(topology_opening_events > 0); REQUIRE(topology_changed_events > 0); REQUIRE(topology_closed_events > 0); REQUIRE(found_servers); } SECTION("Heartbeat Events") { int heartbeat_started_events = 0; int heartbeat_succeeded_events = 0; auto mock_started_awaited = libmongoc::apm_server_heartbeat_started_get_awaited.create_instance(); auto mock_succeeded_awaited = libmongoc::apm_server_heartbeat_succeeded_get_awaited.create_instance(); bool started_awaited_called = false; bool succeeded_awaited_called = false; mock_started_awaited->visit( [&](const mongoc_apm_server_heartbeat_started_t*) { started_awaited_called = true; }); mock_succeeded_awaited->visit([&](const mongoc_apm_server_heartbeat_succeeded_t*) { succeeded_awaited_called = true; }); /////////////////////////////////////////////////////////////////////// // Begin heartbeat listener lambdas /////////////////////////////////////////////////////////////////////// // ServerHeartbeatStartedEvent apm_opts.on_heartbeat_started([&](const events::heartbeat_started_event& event) { heartbeat_started_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE(event.port() != 0); // Client is single-threaded, and will never perform an awaitable hello. REQUIRE(!event.awaited()); }); // ServerHeartbeatSucceededEvent apm_opts.on_heartbeat_succeeded([&](const events::heartbeat_succeeded_event& event) { heartbeat_succeeded_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE(event.port() != 0); REQUIRE_FALSE(event.reply().empty()); // Client is single-threaded, and will never perform an awaitable hello. REQUIRE(!event.awaited()); }); // Don't expect a ServerHeartbeatFailedEvent here, see the test below. /////////////////////////////////////////////////////////////////////// // End heartbeat listener lambdas /////////////////////////////////////////////////////////////////////// open_and_close_client(test_uri, apm_opts); REQUIRE(heartbeat_started_events > 0); REQUIRE(heartbeat_succeeded_events > 0); REQUIRE(started_awaited_called); REQUIRE(succeeded_awaited_called); } } TEST_CASE("Heartbeat failed event", "[sdam_monitoring]") { instance::current(); options::apm apm_opts; bool failed_awaited_called = false; auto mock_failed_awaited = libmongoc::apm_server_heartbeat_failed_get_awaited.create_instance(); mock_failed_awaited->visit( [&](const mongoc_apm_server_heartbeat_failed_t*) { failed_awaited_called = true; }); int heartbeat_failed_events = 0; // ServerHeartbeatFailedEvent apm_opts.on_heartbeat_failed([&](const events::heartbeat_failed_event& event) { heartbeat_failed_events++; REQUIRE_FALSE(event.host().empty()); REQUIRE_FALSE(event.message().empty()); REQUIRE(event.port() != 0); REQUIRE(!event.awaited()); }); REQUIRE_THROWS_AS( open_and_close_client(uri{"mongodb://bad-host/?connectTimeoutMS=1"}, apm_opts), mongocxx::exception); REQUIRE(heartbeat_failed_events > 0); REQUIRE(failed_awaited_called); } } // namespace
39.396552
100
0.569278
lzlzymy
a7e1429e15be464fa4e2a5469cf160ad9145f864
1,009
cpp
C++
src/Kernel/VideoDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Kernel/VideoDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Kernel/VideoDecoder.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "VideoDecoder.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/AssertionType.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// VideoDecoder::VideoDecoder() { } ////////////////////////////////////////////////////////////////////////// VideoDecoder::~VideoDecoder() { } ////////////////////////////////////////////////////////////////////////// void VideoDecoder::setCodecDataInfo( const CodecDataInfo * _dataInfo ) { MENGINE_ASSERTION_MEMORY_PANIC( _dataInfo ); MENGINE_ASSERTION_TYPE( _dataInfo, const VideoCodecDataInfo * ); m_dataInfo = *static_cast<const VideoCodecDataInfo *>(_dataInfo); } ////////////////////////////////////////////////////////////////////////// const VideoCodecDataInfo * VideoDecoder::getCodecDataInfo() const { return &m_dataInfo; } ////////////////////////////////////////////////////////////////////////// }
32.548387
78
0.418236
irov
a7e395319bfdef5c234886d2b136295a3be6f8e6
23,974
hpp
C++
src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
src/AFQMC/HamiltonianOperations/Real3IndexFactorization.hpp
kayahans/qmcpack
c25d77702e36363ff7368ded783bf31c1b1c5f17
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source // License. See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // Miguel A. Morales, moralessilva2@llnl.gov // Lawrence Livermore National Laboratory // // File created by: // Miguel A. Morales, moralessilva2@llnl.gov // Lawrence Livermore National Laboratory //////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP #define QMCPLUSPLUS_AFQMC_HAMILTONIANOPERATIONS_REAL3INDEXFACTORIZATION_HPP #include <vector> #include <type_traits> #include <random> #include "Configuration.h" #include "AFQMC/config.h" #include "mpi3/shared_communicator.hpp" #include "multi/array.hpp" #include "multi/array_ref.hpp" #include "AFQMC/Numerics/ma_operations.hpp" #include "AFQMC/Utilities/type_conversion.hpp" #include "AFQMC/Utilities/taskgroup.h" namespace qmcplusplus { namespace afqmc { // MAM: to make the working precision of this class a template parameter, // sed away SPComplexType by another type ( which is then defined through a template parameter) // This should be enough, since some parts are kept at ComplexType precision // defined through the cmake // Custom implementation for real build class Real3IndexFactorization { using sp_pointer = SPComplexType*; using const_sp_pointer = SPComplexType const*; using IVector = boost::multi::array<int,1>; using CVector = boost::multi::array<ComplexType,1>; using SpVector = boost::multi::array<SPComplexType,1>; using CMatrix = boost::multi::array<ComplexType,2>; using CMatrix_cref = boost::multi::array_cref<ComplexType,2>; using CMatrix_ref = boost::multi::array_ref<ComplexType,2>; using CVector_ref = boost::multi::array_ref<ComplexType,1>; using RMatrix = boost::multi::array<RealType,2>; using RMatrix_cref = boost::multi::array_cref<RealType,2>; using RMatrix_ref = boost::multi::array_ref<RealType,2>; using RVector_ref = boost::multi::array_ref<RealType,1>; using SpCMatrix = boost::multi::array<SPComplexType,2>; using SpCMatrix_cref = boost::multi::array_cref<SPComplexType,2>; using SpCVector_ref = boost::multi::array_ref<SPComplexType,1>; using SpCMatrix_ref = boost::multi::array_ref<SPComplexType,2>; using SpRMatrix = boost::multi::array<SPRealType,2>; using SpRMatrix_cref = boost::multi::array_cref<SPRealType,2>; using SpRVector_ref = boost::multi::array_ref<SPRealType,1>; using SpRMatrix_ref = boost::multi::array_ref<SPRealType,2>; using C3Tensor = boost::multi::array<ComplexType,3>; using SpC3Tensor = boost::multi::array<SPComplexType,3>; using SpC3Tensor_ref = boost::multi::array_ref<SPComplexType,3>; using SpC4Tensor_ref = boost::multi::array_ref<SPComplexType,4>; using shmCVector = boost::multi::array<ComplexType,1,shared_allocator<ComplexType>>; using shmRMatrix = boost::multi::array<RealType,2,shared_allocator<RealType>>; using shmCMatrix = boost::multi::array<ComplexType,2,shared_allocator<ComplexType>>; using shmC3Tensor = boost::multi::array<ComplexType,3,shared_allocator<ComplexType>>; using shmSpRVector = boost::multi::array<SPRealType,1,shared_allocator<SPRealType>>; using shmSpRMatrix = boost::multi::array<SPRealType,2,shared_allocator<SPRealType>>; using shmSpCMatrix = boost::multi::array<SPComplexType,2,shared_allocator<SPComplexType>>; using shmSpC3Tensor = boost::multi::array<SPComplexType,3,shared_allocator<SPComplexType>>; using this_t = Real3IndexFactorization; public: static const HamiltonianTypes HamOpType = RealDenseFactorized; HamiltonianTypes getHamType() const { return HamOpType; } Real3IndexFactorization(afqmc::TaskGroup_& tg_, WALKER_TYPES type, shmRMatrix&& hij_, shmCMatrix&& haj_, shmSpRMatrix&& vik, shmSpCMatrix&& vak, std::vector<shmSpC3Tensor>&& vank, shmCMatrix&& vn0_, ValueType e0_, int cv0, int gncv): TG(tg_), walker_type(type), global_origin(cv0), global_nCV(gncv), local_nCV(0), E0(e0_), hij(std::move(hij_)), haj(std::move(haj_)), Likn(std::move(vik)), Lank(std::move(vank)), Lakn(std::move(vak)), vn0(std::move(vn0_)), SM_TMats({1,1},shared_allocator<SPComplexType>{TG.TG_local()}) { local_nCV=Likn.size(1); TG.Node().barrier(); } ~Real3IndexFactorization() {} Real3IndexFactorization(const Real3IndexFactorization& other) = delete; Real3IndexFactorization& operator=(const Real3IndexFactorization& other) = delete; Real3IndexFactorization(Real3IndexFactorization&& other) = default; Real3IndexFactorization& operator=(Real3IndexFactorization&& other) = delete; CMatrix getOneBodyPropagatorMatrix(TaskGroup_& TG, boost::multi::array<ComplexType,1> const& vMF) { int NMO = hij.size(0); // in non-collinear case with SO, keep SO matrix here and add it // for now, stay collinear CMatrix H1({NMO,NMO}); // add sum_n vMF*Spvn, vMF has local contribution only! boost::multi::array_ref<ComplexType,1> H1D(H1.origin(),{NMO*NMO}); std::fill_n(H1D.origin(),H1D.num_elements(),ComplexType(0)); vHS(vMF, H1D); TG.TG().all_reduce_in_place_n(H1D.origin(),H1D.num_elements(),std::plus<>()); // add hij + vn0 and symmetrize using ma::conj; for(int i=0; i<NMO; i++) { H1[i][i] += hij[i][i] + vn0[i][i]; for(int j=i+1; j<NMO; j++) { H1[i][j] += hij[i][j] + vn0[i][j]; H1[j][i] += hij[j][i] + vn0[j][i]; // This is really cutoff dependent!!! if( std::abs( H1[i][j] - ma::conj(H1[j][i]) ) > 1e-6 ) { app_error()<<" WARNING in getOneBodyPropagatorMatrix. H1 is not hermitian. \n"; app_error()<<i <<" " <<j <<" " <<H1[i][j] <<" " <<H1[j][i] <<" " <<hij[i][j] <<" " <<hij[j][i] <<" " <<vn0[i][j] <<" " <<vn0[j][i] <<std::endl; //APP_ABORT("Error in getOneBodyPropagatorMatrix. H1 is not hermitian. \n"); } H1[i][j] = 0.5*(H1[i][j]+ma::conj(H1[j][i])); H1[j][i] = ma::conj(H1[i][j]); } } return H1; } template<class Mat, class MatB> void energy(Mat&& E, MatB const& G, int k, bool addH1=true, bool addEJ=true, bool addEXX=true) { MatB* Kr(nullptr); MatB* Kl(nullptr); energy(E,G,k,Kl,Kr,addH1,addEJ,addEXX); } // KEleft and KEright must be in shared memory for this to work correctly template<class Mat, class MatB, class MatC, class MatD> void energy(Mat&& E, MatB const& Gc, int nd, MatC* KEleft, MatD* KEright, bool addH1=true, bool addEJ=true, bool addEXX=true) { assert(E.size(1)>=3); assert(nd >= 0); assert(nd < haj.size()); if(walker_type==COLLINEAR) assert(2*nd+1 < Lank.size()); else assert(nd < Lank.size()); int nwalk = Gc.size(0); int nspin = (walker_type==COLLINEAR?2:1); int NMO = hij.size(0); int nel[2]; nel[0] = Lank[nspin*nd].size(0); nel[1] = ((nspin==2)?Lank[nspin*nd+1].size(0):0); assert(Lank[nspin*nd].size(1) == local_nCV); assert(Lank[nspin*nd].size(2) == NMO); if(nspin==2) { assert(Lank[nspin*nd+1].size(1) == local_nCV); assert(Lank[nspin*nd+1].size(2) == NMO); } assert(Gc.num_elements() == nwalk*(nel[0]+nel[1])*NMO); int getKr = KEright!=nullptr; int getKl = KEleft!=nullptr; if(E.size(0) != nwalk || E.size(1) < 3) APP_ABORT(" Error in AFQMC/HamiltonianOperations/Real3IndexFactorization::energy(...). Incorrect matrix dimensions \n"); // T[nwalk][nup][nup][local_nCV] + D[nwalk][nwalk][local_nCV] size_t mem_needs(0); size_t cnt(0); if(addEJ) { #if MIXED_PRECISION mem_needs += nwalk*local_nCV; #else if(not getKl) mem_needs += nwalk*local_nCV; #endif } if(addEXX) { mem_needs += nwalk*nel[0]*nel[0]*local_nCV; #if MIXED_PRECISION mem_needs += nwalk*nel[0]*NMO; #else if(nspin == 2) mem_needs += nwalk*nel[0]*NMO; #endif } set_shm_buffer(mem_needs); // messy SPComplexType *Klptr(nullptr); long Knr=0, Knc=0; if(addEJ) { Knr=nwalk; Knc=local_nCV; if(getKr) { assert(KEright->size(0) == nwalk && KEright->size(1) == local_nCV); assert(KEright->stride(0) == KEright->size(1)); } #if MIXED_PRECISION if(getKl) { assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV); assert(KEleft->stride(0) == KEleft->size(1)); } #else if(getKl) { assert(KEleft->size(0) == nwalk && KEleft->size(1) == local_nCV); assert(KEleft->stride(0) == KEleft->size(1)); Klptr = to_address(KEleft->origin()); } else #endif { Klptr = to_address(SM_TMats.origin())+cnt; cnt += Knr*Knc; } if(TG.TG_local().root()) std::fill_n(Klptr,Knr*Knc,SPComplexType(0.0)); } else if(getKr or getKl) { APP_ABORT(" Error: Kr and/or Kl can only be calculated with addEJ=true.\n"); } SpCMatrix_ref Kl(Klptr,{long(Knr),long(Knc)}); for(int n=0; n<nwalk; n++) std::fill_n(E[n].origin(),3,ComplexType(0.)); // one-body contribution // haj[ndet][nocc*nmo] // not parallelized for now, since it would require customization of Wfn if(addH1) { boost::multi::array_cref<ComplexType,1> haj_ref(to_address(haj[nd].origin()), iextensions<1u>{haj[nd].num_elements()}); ma::product(ComplexType(1.),Gc,haj_ref,ComplexType(1.),E(E.extension(0),0)); for(int i=0; i<nwalk; i++) E[i][0] += E0; } // move calculation of H1 here // NOTE: For CLOSED/NONCOLLINEAR, can do all walkers simultaneously to improve perf. of GEMM // Not sure how to do it for COLLINEAR. if(addEXX) { SPRealType scl = (walker_type==CLOSED?2.0:1.0); for(int ispin=0, is0=0; ispin<nspin; ispin++) { size_t cnt_(cnt); SPComplexType *ptr(nullptr); #if MIXED_PRECISION ptr = to_address(SM_TMats.origin())+cnt_; cnt_ += nwalk*nel[ispin]*NMO; for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; copy_n_cast(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO); } TG.TG_local().barrier(); #else if(nspin==1) { ptr = to_address(Gc.origin()); } else { ptr = to_address(SM_TMats.origin())+cnt_; cnt_ += nwalk*nel[ispin]*NMO; for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; std::copy_n(to_address(Gc[n].origin())+is0,nel[ispin]*NMO,ptr+n*nel[ispin]*NMO); } TG.TG_local().barrier(); } #endif SpCMatrix_ref GF(ptr,{nwalk*nel[ispin],NMO}); SpCMatrix_ref Lan(to_address(Lank[nd*nspin + ispin].origin()), {nel[ispin]*local_nCV,NMO}); SpCMatrix_ref Twban(to_address(SM_TMats.origin())+cnt_,{nwalk*nel[ispin],nel[ispin]*local_nCV}); SpC4Tensor_ref T4Dwban(Twban.origin(),{nwalk,nel[ispin],nel[ispin],local_nCV}); long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(nel[ispin]*local_nCV), long(TG.TG_local().size())); ma::product(GF,ma::T(Lan.sliced(i0,iN)),Twban(Twban.extension(0),{i0,iN})); TG.TG_local().barrier(); for(int n=0, an=0; n<nwalk; ++n) { ComplexType E_(0.0); for(int a=0; a<nel[ispin]; ++a, an++) { if( an%TG.TG_local().size() != TG.TG_local().rank() ) continue; for(int b=0; b<nel[ispin]; ++b) E_ += static_cast<ComplexType>(ma::dot(T4Dwban[n][a][b],T4Dwban[n][b][a])); } E[n][1] -= 0.5*scl*E_; } if(addEJ) { for(int n=0; n<nwalk; ++n) { if( n%TG.TG_local().size() != TG.TG_local().rank() ) continue; for(int a=0; a<nel[ispin]; ++a) ma::axpy(SPComplexType(1.0),T4Dwban[n][a][a],Kl[n]); } } is0 += nel[ispin]*NMO; } // if } TG.TG_local().barrier(); if(addEJ) { if(not addEXX) { // calculate Kr APP_ABORT(" Error: Finish addEJ and not addEXX"); } TG.TG_local().barrier(); SPRealType scl = (walker_type==CLOSED?2.0:1.0); for(int n=0; n<nwalk; ++n) { if(n%TG.TG_local().size() == TG.TG_local().rank()) E[n][2] += 0.5*static_cast<ComplexType>(scl*scl*ma::dot(Kl[n],Kl[n])); } #if MIXED_PRECISION if(getKl) { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEleft->num_elements()), long(TG.TG_local().size())); copy_n_cast(Klptr+i0,iN-i0,to_address(KEleft->origin())+i0); } #endif if(getKr) { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()),long(KEright->num_elements()), long(TG.TG_local().size())); copy_n_cast(Klptr+i0,iN-i0,to_address(KEright->origin())+i0); } TG.TG_local().barrier(); } } template<class... Args> void fast_energy(Args&&... args) { APP_ABORT(" Error: fast_energy not implemented in Real3IndexFactorization. \n"); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>, typename = void > void vHS(MatA& X, MatB&& v, double a=1., double c=0.) { using BType = typename std::decay<MatB>::type::element ; using AType = typename std::decay<MatA>::type::element ; boost::multi::array_ref<BType,2> v_(to_address(v.origin()), {v.size(0),1}); boost::multi::array_ref<const AType,2> X_(to_address(X.origin()), {X.size(0),1}); return vHS(X_,v_,a,c); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)> > void vHS(MatA& X, MatB&& v, double a=1., double c=0.) { using XType = typename std::decay_t<typename MatA::element>; using vType = typename std::decay<MatB>::type::element ; assert( Likn.size(1) == X.size(0) ); assert( Likn.size(0) == v.size(0) ); assert( X.size(1) == v.size(1) ); long ik0, ikN; std::tie(ik0,ikN) = FairDivideBoundary(long(TG.TG_local().rank()),long(Likn.size(0)),long(TG.TG_local().size())); // setup buffer space if changing precision in X or v size_t vmem(0),Xmem(0); if(not std::is_same<XType,SPComplexType>::value) Xmem = X.num_elements(); if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements(); set_shm_buffer(vmem+Xmem); sp_pointer vptr(nullptr); const_sp_pointer Xptr(nullptr); // setup origin of Xsp and copy_n_cast if necessary if(std::is_same<XType,SPComplexType>::value) { Xptr = reinterpret_cast<const_sp_pointer>(to_address(X.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(X.num_elements()),long(TG.TG_local().size())); copy_n_cast(to_address(X.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0); Xptr = to_address(SM_TMats.origin()); } // setup origin of vsp and copy_n_cast if necessary if(std::is_same<vType,SPComplexType>::value) { vptr = reinterpret_cast<sp_pointer>(to_address(v.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(v.num_elements()),long(TG.TG_local().size())); vptr = to_address(SM_TMats.origin())+Xmem; if( std::abs(c) > 1e-12 ) copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0); } // setup array references boost::multi::array_cref<SPComplexType const,2> Xsp(Xptr, X.extensions()); boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions()); TG.TG_local().barrier(); ma::product(SPValueType(a),Likn.sliced(ik0,ikN),Xsp, SPValueType(c),vsp.sliced(ik0,ikN)); if(not std::is_same<vType,SPComplexType>::value) { copy_n_cast(to_address(vsp[ik0].origin()),vsp.size(1)*(ikN-ik0), to_address(v[ik0].origin())); } TG.TG_local().barrier(); } template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==1)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==1)>, typename = void > void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) { using BType = typename std::decay<MatB>::type::element ; using AType = typename std::decay<MatA>::type::element ; boost::multi::array_ref<BType,2> v_(to_address(v.origin()), {v.size(0),1}); if(haj.size(0) == 1) { boost::multi::array_cref<AType,2> G_(to_address(G.origin()), {1,G.size(0)}); return vbias(G_,v_,a,c,k); } else { boost::multi::array_cref<AType,2> G_(to_address(G.origin()), {G.size(0),1}); return vbias(G_,v_,a,c,k); } } // v(n,w) = sum_ak L(ak,n) G(w,ak) template<class MatA, class MatB, typename = typename std::enable_if_t<(std::decay<MatA>::type::dimensionality==2)>, typename = typename std::enable_if_t<(std::decay<MatB>::type::dimensionality==2)> > void vbias(const MatA& G, MatB&& v, double a=1., double c=0., int k=0) { using GType = typename std::decay_t<typename MatA::element>; using vType = typename std::decay<MatB>::type::element ; long ic0, icN; // setup buffer space if changing precision in G or v size_t vmem(0),Gmem(0); if(not std::is_same<GType,SPComplexType>::value) Gmem = G.num_elements(); if(not std::is_same<vType,SPComplexType>::value) vmem = v.num_elements(); set_shm_buffer(vmem+Gmem); const_sp_pointer Gptr(nullptr); sp_pointer vptr(nullptr); // setup origin of Gsp and copy_n_cast if necessary if(std::is_same<GType,SPComplexType>::value) { Gptr = reinterpret_cast<const_sp_pointer>(to_address(G.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(G.num_elements()),long(TG.TG_local().size())); copy_n_cast(to_address(G.origin())+i0,iN-i0,to_address(SM_TMats.origin())+i0); Gptr = to_address(SM_TMats.origin()); } // setup origin of vsp and copy_n_cast if necessary if(std::is_same<vType,SPComplexType>::value) { vptr = reinterpret_cast<sp_pointer>(to_address(v.origin())); } else { long i0, iN; std::tie(i0,iN) = FairDivideBoundary(long(TG.TG_local().rank()), long(v.num_elements()),long(TG.TG_local().size())); vptr = to_address(SM_TMats.origin())+Gmem; if( std::abs(c) > 1e-12 ) copy_n_cast(to_address(v.origin())+i0,iN-i0,vptr+i0); } // setup array references boost::multi::array_cref<SPComplexType const,2> Gsp(Gptr, G.extensions()); boost::multi::array_ref<SPComplexType,2> vsp(vptr, v.extensions()); TG.TG_local().barrier(); if(haj.size(0) == 1) { assert( Lakn.size(0) == G.size(1) ); assert( Lakn.size(1) == v.size(0) ); assert( G.size(0) == v.size(1) ); std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()), long(Lakn.size(1)),long(TG.TG_local().size())); if(walker_type==CLOSED) a*=2.0; ma::product(SPValueType(a),ma::T(Lakn(Lakn.extension(0),{ic0,icN})),ma::T(Gsp), SPValueType(c),vsp.sliced(ic0,icN)); } else { // multideterminant is not half-rotated, so use Likn assert( Likn.size(0) == G.size(0) ); assert( Likn.size(1) == v.size(0) ); assert( G.size(1) == v.size(1) ); std::tie(ic0,icN) = FairDivideBoundary(long(TG.TG_local().rank()), long(Likn.size(1)),long(TG.TG_local().size())); if(walker_type==CLOSED) a*=2.0; ma::product(SPValueType(a),ma::T(Likn(Likn.extension(0),{ic0,icN})),Gsp, SPValueType(c),vsp.sliced(ic0,icN)); } // copy data back if changing precision if(not std::is_same<vType,SPComplexType>::value) { copy_n_cast(to_address(vsp[ic0].origin()),vsp.size(1)*(icN-ic0), to_address(v[ic0].origin())); } TG.TG_local().barrier(); } template<class Mat, class MatB> void generalizedFockMatrix(Mat&& G, MatB&& Fp, MatB&& Fm) { APP_ABORT(" Error: generalizedFockMatrix not implemented for this hamiltonian.\n"); } bool distribution_over_cholesky_vectors() const{ return true; } int number_of_ke_vectors() const{ return local_nCV; } int local_number_of_cholesky_vectors() const{ return local_nCV; } int global_number_of_cholesky_vectors() const{ return global_nCV; } int global_origin_cholesky_vector() const{ return global_origin; } // transpose=true means G[nwalk][ik], false means G[ik][nwalk] bool transposed_G_for_vbias() const{ return (haj.size(0) == 1); } bool transposed_G_for_E() const{return true;} // transpose=true means vHS[nwalk][ik], false means vHS[ik][nwalk] bool transposed_vHS() const{return false;} bool fast_ph_energy() const { return false; } boost::multi::array<ComplexType,2> getHSPotentials() { return boost::multi::array<ComplexType,2>{}; } private: afqmc::TaskGroup_& TG; WALKER_TYPES walker_type; int global_origin; int global_nCV; int local_nCV; ValueType E0; // bare one body hamiltonian shmRMatrix hij; // (potentially half rotated) one body hamiltonian shmCMatrix haj; //Cholesky Tensor Lik[i][k][n] shmSpRMatrix Likn; // permuted half-tranformed Cholesky tensor // Lank[ 2*idet + ispin ] std::vector<shmSpC3Tensor> Lank; // half-tranformed Cholesky tensor // only used in single determinant case, haj.size(0)==1. shmSpCMatrix Lakn; // one-body piece of Hamiltonian factorization shmCMatrix vn0; // shared buffer space // using matrix since there are issues with vectors shmSpCMatrix SM_TMats; myTimer Timer; void set_shm_buffer(size_t N) { if(SM_TMats.num_elements() < N) SM_TMats.reextent({N,1}); } }; } } #endif
38.918831
131
0.588888
kayahans
a7e41efd5bcc11619c12c326053dcccdc2c3d109
157
hxx
C++
src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/AbstractIndicationSubscription/UNIX_AbstractIndicationSubscription_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H #define __UNIX_ABSTRACTINDICATIONSUBSCRIPTION_PRIVATE_H #endif #endif
13.083333
55
0.878981
brunolauze
a7e53e2e17e6741f7355ed71f56800248291a4b6
1,032
cpp
C++
binary-tree-zigzag-level-order-traversal.cpp
mittalnaman2706/LeetCode
ba7e1602fb70ca0063c3e5573ea0661cc5ae9856
[ "Apache-2.0" ]
2
2019-01-10T17:50:26.000Z
2019-05-23T14:31:58.000Z
binary-tree-zigzag-level-order-traversal.cpp
mittalnaman2706/LeetCode
ba7e1602fb70ca0063c3e5573ea0661cc5ae9856
[ "Apache-2.0" ]
null
null
null
binary-tree-zigzag-level-order-traversal.cpp
mittalnaman2706/LeetCode
ba7e1602fb70ca0063c3e5573ea0661cc5ae9856
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>>q; int i,j,k,l; TreeNode* z; TreeNode* x; queue<TreeNode* >a; if(root==NULL) return q; a.push(root); while(a.size()) { vector<int >w; k=a.size(); while(k--) { z=a.front(); if(z->left) a.push(z->left); if(z->right) a.push(z->right); w.push_back(z->val); a.pop(); } q.push_back(w); } for(i=1;i<q.size();i+=2) { reverse(q[i].begin(),q[i].end()); } return q; } };
21.5
59
0.379845
mittalnaman2706
a7e7b02880ca8c7110af6dd292b5a8cda5fece1b
9,084
cpp
C++
ArrhythmiaStudio/src/engine/rendering/Renderer.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
6
2021-10-04T03:06:12.000Z
2022-02-14T09:32:59.000Z
ArrhythmiaStudio/src/engine/rendering/Renderer.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
null
null
null
ArrhythmiaStudio/src/engine/rendering/Renderer.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
1
2021-12-04T17:59:22.000Z
2021-12-04T17:59:22.000Z
#include "Renderer.h" #include "post_processing/Bloom.h" #include "GlobalConstants.h" #include "../../MainWindow.h" #include "drawers/BatchedDrawer.h" #include "glad/glad.h" Renderer* Renderer::inst; Renderer::Renderer(GLFWwindow* window) { if (inst) { return; } inst = this; const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* vendor = glGetString(GL_VENDOR); const GLubyte* version = glGetString(GL_VERSION); const GLubyte* langVer = glGetString(GL_SHADING_LANGUAGE_VERSION); LOG4CXX_INFO(logger, "Renderer: " << (const char*)renderer); LOG4CXX_INFO(logger, "Vendor: " << (const char*)vendor); LOG4CXX_INFO(logger, "OpenGL Version: " << (const char*)version); LOG4CXX_INFO(logger, "GLSL Version: " << (const char*)langVer); viewportWidth = RENDERER_INITIAL_WIDTH; viewportHeight = RENDERER_INITIAL_HEIGHT; lastViewportWidth = viewportWidth; lastViewportHeight = viewportHeight; // Generate render texture glGenTextures(1, &renderTexture); glBindTexture(GL_TEXTURE_2D, renderTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, viewportWidth, viewportHeight, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Initialize framebuffer to copy from multisample framebuffer glGenFramebuffers(1, &finalFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, finalFramebuffer); // Attach generated resources to framebuffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Generate multisample color texture glGenTextures(1, &multisampleTexture); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, MSAA_SAMPLES, GL_RGBA16F, viewportWidth, viewportHeight, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); // Generate render texture glGenRenderbuffers(1, &depthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, MSAA_SAMPLES, GL_DEPTH_COMPONENT, viewportWidth, viewportHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Initialize framebuffer to render into glGenFramebuffers(1, &multisampleFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer); // Attach generated resources to framebuffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); mainWindow = window; camera = new Camera(); imGuiController = new ImGuiController(window, "Assets/Fonts/Inconsolata-Regular.ttf"); bloom = new Bloom(); // tonemapping = new Tonemapping(); } void Renderer::update() { imGuiController->update(); resizeViewport(); } void Renderer::resizeViewport() { if (viewportWidth != lastViewportWidth || viewportHeight != lastViewportHeight) { // Resize all framebuffer attachments glBindTexture(GL_TEXTURE_2D, renderTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, viewportWidth, viewportHeight, 0, GL_RGB, GL_FLOAT, nullptr); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, multisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, MSAA_SAMPLES, GL_RGBA16F, viewportWidth, viewportHeight, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, MSAA_SAMPLES, GL_DEPTH_COMPONENT, viewportWidth, viewportHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); lastViewportWidth = viewportWidth; lastViewportHeight = viewportHeight; } } void Renderer::render() { renderViewport(); // Render ImGui last imGuiController->renderImGui(); } void Renderer::renderViewport() { float aspect = viewportWidth / (float)viewportHeight; glm::mat4 view, projection; camera->calculateViewProjection(aspect, &view, &projection); glm::mat4 viewProjection = projection * view; recursivelyRenderNodes(Scene::inst->rootNode, glm::mat4(1.0f)); prepareDrawers(); FramebufferStack::push(multisampleFramebuffer); glViewport(0, 0, viewportWidth, viewportHeight); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); // Opaque shits are drawn here for (Drawer* drawer : queuedOpaqueDrawers) { drawer->draw(viewProjection); delete drawer; } glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Transparent shits are drawn here for (Drawer* drawer : queuedTransparentDrawers) { drawer->draw(viewProjection); delete drawer; } glDepthMask(GL_TRUE); FramebufferStack::pop(); glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampleFramebuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, finalFramebuffer); glBlitFramebuffer(0, 0, viewportWidth, viewportHeight, 0, 0, viewportWidth, viewportHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); bloom->processImage(renderTexture, viewportWidth, viewportHeight); // tonemapping->processImage(renderTexture, viewportWidth, viewportHeight); // Clean up queuedOpaqueDrawers.clear(); queuedTransparentDrawers.clear(); BatchedDrawer::clearBatches(); glBindVertexArray(0); glUseProgram(0); } uint32_t Renderer::getRenderTexture() const { return renderTexture; } void Renderer::recursivelyRenderNodes(SceneNode* node, glm::mat4 parentTransform) { if (!node->getActive()) { return; } const glm::mat4 nodeTransform = node->transform.getLocalMatrix(); const glm::mat4 globalTransform = parentTransform * nodeTransform; if (node->renderer) { RenderCommand* cmd; if (node->renderer->tryRender(globalTransform, &cmd)) { if (cmd->drawDepth.has_value()) { queuedCommandTransparent.push_back(cmd); } else { queuedCommandOpaque.push_back(cmd); } } } for (SceneNode* child : node->activeChildren) { recursivelyRenderNodes(child, globalTransform); } } void Renderer::prepareDrawers() { // Sort draw commands // We sort opaque commands by type to maximize batching efficiency std::sort(queuedCommandOpaque.begin(), queuedCommandOpaque.end(), [](RenderCommand* a, RenderCommand* b) { return a->drawData->getType() < b->drawData->getType(); }); // For transparent commands, we sort by depth, then by type std::sort(queuedCommandTransparent.begin(), queuedCommandTransparent.end(), [](RenderCommand* a, RenderCommand* b) { assert(a->drawDepth.has_value()); assert(b->drawDepth.has_value()); const float depthA = a->drawDepth.value(); const float depthB = b->drawDepth.value(); if (depthA != depthB) { return depthA < depthB; } return a->drawData->getType() < b->drawData->getType(); }); // Batching and queuing other stuff // Batching opaque objects { BatchedDrawer* currentOpaqueDrawer = nullptr; for (RenderCommand* cmd : queuedCommandOpaque) { if (cmd->drawData->getType() == DrawDataType_Batched) { if (!currentOpaqueDrawer) { currentOpaqueDrawer = new BatchedDrawer(); } BatchedDrawData* drawData = (BatchedDrawData*)cmd->drawData; currentOpaqueDrawer->appendMesh(drawData->mesh, drawData->transform, drawData->color); } else { if (currentOpaqueDrawer) { queuedOpaqueDrawers.push_back(currentOpaqueDrawer); currentOpaqueDrawer = nullptr; } queuedOpaqueDrawers.push_back(cmd->drawData->getDrawer()); } delete cmd; } // We check if there is any unqueued opaque drawer at the end and if there is, queue it if (currentOpaqueDrawer) { queuedOpaqueDrawers.push_back(currentOpaqueDrawer); currentOpaqueDrawer = nullptr; } } // Batching transparent objects { BatchedDrawer* currentTransparentDrawer = nullptr; for (RenderCommand* cmd : queuedCommandTransparent) { if (cmd->drawData->getType() == DrawDataType_Batched) { if (!currentTransparentDrawer) { currentTransparentDrawer = new BatchedDrawer(); } BatchedDrawData* drawData = (BatchedDrawData*)cmd->drawData; currentTransparentDrawer->appendMesh(drawData->mesh, drawData->transform, drawData->color); } else { if (currentTransparentDrawer) { queuedTransparentDrawers.push_back(currentTransparentDrawer); currentTransparentDrawer = nullptr; } queuedTransparentDrawers.push_back(cmd->drawData->getDrawer()); } delete cmd; } // We check if there is any unqueued transparent drawer at the end and if there is, queue it if (currentTransparentDrawer) { queuedTransparentDrawers.push_back(currentTransparentDrawer); currentTransparentDrawer = nullptr; } } queuedCommandTransparent.clear(); queuedCommandOpaque.clear(); }
27.865031
126
0.760128
Reimnop
a7e7f19abe028c6cb3e170a2a1ee32cb9a326059
14,996
cpp
C++
Source/UnrealEnginePython/Private/UEPySubclassing.cpp
recogni/UnrealEnginePython
57310d0881a408d9392188aa8f6aeb4443e17c96
[ "MIT" ]
null
null
null
Source/UnrealEnginePython/Private/UEPySubclassing.cpp
recogni/UnrealEnginePython
57310d0881a408d9392188aa8f6aeb4443e17c96
[ "MIT" ]
null
null
null
Source/UnrealEnginePython/Private/UEPySubclassing.cpp
recogni/UnrealEnginePython
57310d0881a408d9392188aa8f6aeb4443e17c96
[ "MIT" ]
null
null
null
#include "UnrealEnginePythonPrivatePCH.h" int unreal_engine_py_init(ue_PyUObject *self, PyObject *args, PyObject *kwds) { // is it subclassing ? if (PyTuple_Size(args) == 3) { // TODO make it smarter on error checking UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 0))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 1))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(PyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 2))))); PyObject *parents = PyTuple_GetItem(args, 1); ue_PyUObject *parent = (ue_PyUObject *)PyTuple_GetItem(parents, 0); PyObject *class_attributes = PyTuple_GetItem(args, 2); PyObject *class_name = PyDict_GetItemString(class_attributes, (char *)"__qualname__"); char *name = PyUnicode_AsUTF8(class_name); // check if parent is a uclass UClass *new_class = unreal_engine_new_uclass(name, (UClass *)parent->ue_object); if (!new_class) return -1; // map the class to the python object self->ue_object = new_class; self->py_proxy = nullptr; self->auto_rooted = 0; self->py_dict = PyDict_New(); FUnrealEnginePythonHouseKeeper::Get()->RegisterPyUObject(new_class, self); PyObject *py_additional_properties = PyDict_New(); PyObject *class_attributes_keys = PyObject_GetIter(class_attributes); for (;;) { PyObject *key = PyIter_Next(class_attributes_keys); if (!key) { if (PyErr_Occurred()) return -1; break; } if (!PyUnicodeOrString_Check(key)) continue; char *class_key = PyUnicode_AsUTF8(key); PyObject *value = PyDict_GetItem(class_attributes, key); if (strlen(class_key) > 2 && class_key[0] == '_' && class_key[1] == '_') { continue; } bool prop_added = false; if (UProperty *u_property = new_class->FindPropertyByName(FName(UTF8_TO_TCHAR(class_key)))) { UE_LOG(LogPython, Warning, TEXT("Found UProperty %s"), UTF8_TO_TCHAR(class_key)); PyDict_SetItem(py_additional_properties, key, value); prop_added = true; } // add simple property else if (ue_is_pyuobject(value)) { ue_PyUObject *py_obj = (ue_PyUObject *)value; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } // add array property else if (PyList_Check(value)) { if (PyList_Size(value) == 1) { PyObject *first_item = PyList_GetItem(value, 0); if (ue_is_pyuobject(first_item)) { ue_PyUObject *py_obj = (ue_PyUObject *)first_item; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } } #if ENGINE_MINOR_VERSION >= 15 else if (PyDict_Check(value)) { if (PyDict_Size(value) == 1) { PyObject *py_key = nullptr; PyObject *py_value = nullptr; Py_ssize_t pos = 0; PyDict_Next(value, &pos, &py_key, &py_value); if (ue_is_pyuobject(py_key) && ue_is_pyuobject(py_value)) { PyObject *first_item = nullptr; PyObject *second_item = nullptr; ue_PyUObject *py_obj = (ue_PyUObject *)py_key; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { first_item = py_key; } else { first_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { first_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } ue_PyUObject *py_obj2 = (ue_PyUObject *)py_value; if (py_obj2->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj2->ue_object; if (p_class->IsChildOf<UProperty>()) { second_item = py_value; } else { second_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj2->ue_object->IsA<UScriptStruct>()) { second_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } if (!py_ue_add_property(self, Py_BuildValue("([OO]sOO)", first_item, second_item, class_key, py_key, py_value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } #endif // function ? else if (PyCallable_Check(value) && class_key[0] >= 'A' && class_key[0] <= 'Z') { uint32 func_flags = FUNC_Native | FUNC_BlueprintCallable | FUNC_Public; PyObject *is_event = PyObject_GetAttrString(value, (char *)"event"); if (is_event && PyObject_IsTrue(is_event)) { func_flags |= FUNC_Event | FUNC_BlueprintEvent; } else if (!is_event) PyErr_Clear(); PyObject *is_multicast = PyObject_GetAttrString(value, (char *)"multicast"); if (is_multicast && PyObject_IsTrue(is_multicast)) { func_flags |= FUNC_NetMulticast; } else if (!is_multicast) PyErr_Clear(); PyObject *is_server = PyObject_GetAttrString(value, (char *)"server"); if (is_server && PyObject_IsTrue(is_server)) { func_flags |= FUNC_NetServer; } else if (!is_server) PyErr_Clear(); PyObject *is_client = PyObject_GetAttrString(value, (char *)"client"); if (is_client && PyObject_IsTrue(is_client)) { func_flags |= FUNC_NetClient; } else if (!is_client) PyErr_Clear(); PyObject *is_reliable = PyObject_GetAttrString(value, (char *)"reliable"); if (is_reliable && PyObject_IsTrue(is_reliable)) { func_flags |= FUNC_NetReliable; } else if (!is_reliable) PyErr_Clear(); PyObject *is_pure = PyObject_GetAttrString(value, (char *)"pure"); if (is_pure && PyObject_IsTrue(is_pure)) { func_flags |= FUNC_BlueprintPure; } else if (!is_pure) PyErr_Clear(); PyObject *is_static = PyObject_GetAttrString(value, (char *)"static"); if (is_static && PyObject_IsTrue(is_static)) { func_flags |= FUNC_Static; } else if (!is_static) PyErr_Clear(); PyObject *override_name = PyObject_GetAttrString(value, (char *)"override"); if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = PyUnicode_AsUTF8(override_name); } else if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = PyUnicode_AsUTF8(override_name); } else if (!override_name) PyErr_Clear(); if (!unreal_engine_add_function(new_class, class_key, value, func_flags)) { UE_LOG(LogPython, Error, TEXT("unable to add function %s"), UTF8_TO_TCHAR(class_key)); return -1; } prop_added = true; } if (!prop_added) { UE_LOG(LogPython, Warning, TEXT("Adding %s as attr"), UTF8_TO_TCHAR(class_key)); PyObject_SetAttr((PyObject *)self, key, value); } } if (PyDict_Size(py_additional_properties) > 0) { PyObject_SetAttrString((PyObject *)self, (char*)"__additional_uproperties__", py_additional_properties); } UPythonClass *new_u_py_class = (UPythonClass *)new_class; // TODO: check if we can use this to decref the ue_PyUbject mapped to the class new_u_py_class->py_uobject = self; new_u_py_class->ClassConstructor = [](const FObjectInitializer &ObjectInitializer) { FScopePythonGIL gil; UClass *u_class = ue_py_class_constructor_placeholder ? ue_py_class_constructor_placeholder : ObjectInitializer.GetClass(); ue_py_class_constructor_placeholder = nullptr; UEPyClassConstructor(u_class->GetSuperClass(), ObjectInitializer); if (UPythonClass *u_py_class_casted = Cast<UPythonClass>(u_class)) { ue_PyUObject *new_self = ue_get_python_uobject(ObjectInitializer.GetObj()); if (!new_self) { unreal_engine_py_log_error(); return; } // fill __dict__ from class if (u_py_class_casted->py_uobject && u_py_class_casted->py_uobject->py_dict) { PyObject *found_additional_props = PyDict_GetItemString(u_py_class_casted->py_uobject->py_dict, (char *)"__additional_uproperties__"); // manage UProperties (and automatically maps multicast properties) if (found_additional_props) { PyObject *keys = PyDict_Keys(found_additional_props); Py_ssize_t items_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < items_len; i++) { PyObject *mc_key = PyList_GetItem(keys, i); PyObject *mc_value = PyDict_GetItem(found_additional_props, mc_key); char *mc_name = PyUnicode_AsUTF8(mc_key); UProperty *u_property = ObjectInitializer.GetObj()->GetClass()->FindPropertyByName(FName(UTF8_TO_TCHAR(mc_name))); if (u_property) { if (auto casted_prop = Cast<UMulticastDelegateProperty>(u_property)) { FMulticastScriptDelegate multiscript_delegate = casted_prop->GetPropertyValue_InContainer(ObjectInitializer.GetObj()); FScriptDelegate script_delegate; UPythonDelegate *py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewDelegate(ObjectInitializer.GetObj(), mc_value, casted_prop->SignatureFunction); // fake UFUNCTION for bypassing checks script_delegate.BindUFunction(py_delegate, FName("PyFakeCallable")); // add the new delegate multiscript_delegate.Add(script_delegate); // re-assign multicast delegate casted_prop->SetPropertyValue_InContainer(ObjectInitializer.GetObj(), multiscript_delegate); } else { PyObject_SetAttr((PyObject *)new_self, mc_key, mc_value); } } } Py_DECREF(keys); } else { PyErr_Clear(); } PyObject *keys = PyDict_Keys(u_py_class_casted->py_uobject->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(u_py_class_casted->py_uobject->py_dict, key); if (PyUnicode_Check(key)) { char *key_name = PyUnicode_AsUTF8(key); if (!strcmp(key_name, (char *)"__additional_uproperties__")) continue; } // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_self, key, value); } } Py_DECREF(keys); } // call __init__ u_py_class_casted->CallPyConstructor(new_self); } }; if (self->py_dict) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set dict on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(self->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(self->py_dict, key); // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_default_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_default_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_default_self, key, value); } } Py_DECREF(keys); } // add default uproperties values if (py_additional_properties) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set properties on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(py_additional_properties); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(py_additional_properties, key); PyObject_SetAttr((PyObject *)new_default_self, key, value); } Py_DECREF(keys); } // add custom constructor (__init__) PyObject *py_init = PyDict_GetItemString(class_attributes, (char *)"__init__"); if (py_init && PyCallable_Check(py_init)) { // fake initializer FObjectInitializer initializer(new_u_py_class->ClassDefaultObject, nullptr, false, true); new_u_py_class->SetPyConstructor(py_init); ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to call __init__ on new ClassDefaultObject")); return -1; } new_u_py_class->CallPyConstructor(new_default_self); } } return 0; }
30.983471
161
0.658442
recogni
a7ea2b322fecaa7b4a02e2d96db789062e02bf4c
1,156
hpp
C++
include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/anim/AnimNode_AimConstraint_ObjectUp.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/generated/Vector3.hpp> #include <RED4ext/Types/generated/anim/AnimNode_OnePoseInput.hpp> #include <RED4ext/Types/generated/anim/ConstraintWeightMode.hpp> #include <RED4ext/Types/generated/anim/NamedTrackIndex.hpp> #include <RED4ext/Types/generated/anim/TransformIndex.hpp> namespace RED4ext { namespace anim { struct AnimNode_AimConstraint_ObjectUp : anim::AnimNode_OnePoseInput { static constexpr const char* NAME = "animAnimNode_AimConstraint_ObjectUp"; static constexpr const char* ALIAS = NAME; anim::TransformIndex targetTransform; // 60 anim::TransformIndex upTransform; // 78 Vector3 forwardAxisLS; // 90 Vector3 upAxisLS; // 9C anim::TransformIndex transformIndex; // A8 anim::ConstraintWeightMode weightMode; // C0 float weight; // C4 anim::NamedTrackIndex weightFloatTrack; // C8 uint8_t unkE0[0x108 - 0xE0]; // E0 }; RED4EXT_ASSERT_SIZE(AnimNode_AimConstraint_ObjectUp, 0x108); } // namespace anim } // namespace RED4ext
33.028571
78
0.763841
Cyberpunk-Extended-Development-Team
a7ec028f47d869af8d9e35e4cdcedf47560f0fe0
11,677
cpp
C++
tests/test_code/test_modbus.cpp
yisea123/modbus-tcp-server-1
0d9f697059b2034dfae2d45115c0f4897de87977
[ "MIT" ]
1
2019-12-11T05:24:14.000Z
2019-12-11T05:24:14.000Z
tests/test_code/test_modbus.cpp
yisea123/modbus-tcp-server-1
0d9f697059b2034dfae2d45115c0f4897de87977
[ "MIT" ]
null
null
null
tests/test_code/test_modbus.cpp
yisea123/modbus-tcp-server-1
0d9f697059b2034dfae2d45115c0f4897de87977
[ "MIT" ]
null
null
null
#include "CppUTest/TestHarness.h" #include <string.h> #include <stdio.h> #define NO_OF_INPUT_REGS 10 #define INPUT_REG_START_ADDRESS 0 extern "C" { #include "mbap_conf.h" #include "mbap.h" } #define QUERY_SIZE_IN_BYTES (255u) #define RESPONSE_SIZE_IN_BYTES (255u) #define INPUT_REGISTER_START_ADDRESS (0u) #define MAX_INPUT_REGISTERS (15u) #define HOLDING_REGISTER_START_ADDRESS (0u) #define MAX_HOLDING_REGISTERS (15u) #define DISCRETE_INPUTS_START_ADDRESS (0u) #define MAX_DISCRETE_INPUTS (3u) #define COILS_START_ADDRESS (0u) #define MAX_COILS (3u) #define MBT_EXCEPTION_PACKET_LEN (9u) #define QUERY_LEN (12u) #define NO_OF_DATA_OFFSET (10u) #define DATA_START_ADDRESS_OFFSET (8u) #define REGISTER_VALUE_OFFSET (10u) //PDU Offset in response #define MBT_BYTE_COUNT_OFFSET (8u) #define MBT_DATA_VALUES_OFFSET (9u) #define MBAP_HEADER_LEN (7u) #define DISCRETE_INPUT_BUF_SIZE (MAX_DISCRETE_INPUTS / 8u + 1u) #define COILS_BUF_SIZE (MAX_COILS / 8u + 1u) int16_t g_sInputRegsBuf[MAX_INPUT_REGISTERS] = {1, 2, 3}; int16_t g_sHoldingRegsBuf[MAX_HOLDING_REGISTERS] = {5, 6, 7}; uint8_t g_ucDiscreteInputsBuf[DISCRETE_INPUT_BUF_SIZE] = {0xef}; uint8_t g_ucCoilsBuf[COILS_BUF_SIZE] = {5}; int16_t g_sHoldingRegsLowerLimitBuf[MAX_HOLDING_REGISTERS] = {0, 0, 0}; int16_t g_sHoldingRegsHigherLimitBuf[MAX_HOLDING_REGISTERS] = {200, 200, 200}; TEST_GROUP(Module) { uint8_t *pucQuery = NULL; uint8_t *pucResponse = NULL; int16_t *psInputRegisters = NULL; int16_t *psHoldingRegisters = NULL; ModbusData_t *pModbusData = NULL; void setup() { pucQuery = (uint8_t*)calloc(QUERY_SIZE_IN_BYTES, sizeof(uint8_t)); pucResponse = (uint8_t*)calloc(RESPONSE_SIZE_IN_BYTES, sizeof(uint8_t)); pModbusData = (ModbusData_t*)calloc(1, sizeof(ModbusData_t)); pModbusData->psInputRegisters = g_sInputRegsBuf; pModbusData->usInputRegisterStartAddress = INPUT_REGISTER_START_ADDRESS; pModbusData->usMaxInputRegisters = MAX_INPUT_REGISTERS; pModbusData->psHoldingRegisters = g_sHoldingRegsBuf; pModbusData->usHoldingRegisterStartAddress = HOLDING_REGISTER_START_ADDRESS; pModbusData->usMaxHoldingRegisters = MAX_HOLDING_REGISTERS; pModbusData->psHoldingRegisterLowerLimit = g_sHoldingRegsLowerLimitBuf; pModbusData->psHoldingRegisterHigherLimit = g_sHoldingRegsHigherLimitBuf; pModbusData->pucDiscreteInputs = g_ucDiscreteInputsBuf; pModbusData->usDiscreteInputStartAddress = DISCRETE_INPUTS_START_ADDRESS; pModbusData->usMaxDiscreteInputs = MAX_DISCRETE_INPUTS; pModbusData->pucCoils = g_ucCoilsBuf; pModbusData->usCoilsStartAddress = COILS_START_ADDRESS; pModbusData->usMaxCoils = MAX_COILS; mbap_DataInit(pModbusData); } void teardown() { free(pucQuery); free(pucResponse); free(pModbusData); } }; TEST(Module, read_input_registers) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 5, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; uint16_t usStartAddress = 0; usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8); usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]); usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2; ucByteCount = usNumOfData * 2; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++) { int16_t sReceivedValue = 0; sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8); sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]); CHECK_EQUAL(g_sInputRegsBuf[ucCount + usStartAddress], sReceivedValue); } } TEST(Module, illegal_input_registers_address) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 4, 0, 0, 0, 16}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, read_holding_registers) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 5, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; uint16_t usStartAddress = 0; usStartAddress = (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET] << 8); usStartAddress |= (uint16_t)(ucQueryBuf[DATA_START_ADDRESS_OFFSET + 1]); usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData * 2) + 2; ucByteCount = usNumOfData * 2; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < usNumOfData; ucCount++) { int16_t sReceivedValue = 0; sReceivedValue = (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2)] << 8); sReceivedValue |= (int16_t)(pucResponse[MBT_DATA_VALUES_OFFSET + (ucCount * 2) + 1]); CHECK_EQUAL(g_sHoldingRegsBuf[ucCount + usStartAddress], sReceivedValue); } } TEST(Module, illegal_holding_registers_address) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 3, 0, 0, 0, 16}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_ADDRESS, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, illegal_function_code) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 10, 0, 0, 0, 11}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_FUNCTION_CODE, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, write_single_holding_register) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 200}; uint8_t ucResponseLen = 0; int16_t sReceivedValue = 0; int16_t sSentValue = 0; ucResponseLen = MBAP_HEADER_LEN + 5; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); sReceivedValue = (int16_t)(pucResponse[REGISTER_VALUE_OFFSET] << 8); sReceivedValue |= (int16_t)(pucResponse[REGISTER_VALUE_OFFSET + 1]); sSentValue = (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET] << 8); sSentValue |= (int16_t)(ucQueryBuf[REGISTER_VALUE_OFFSET + 1]); CHECK_EQUAL(sSentValue, sReceivedValue); } TEST(Module, illega_data_value) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 6, 0, 1, 0, 201}; uint8_t ucResponseLen = 0; ucResponseLen = MBT_EXCEPTION_PACKET_LEN; memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ILLEGAL_DATA_VALUE, pucResponse[MBT_BYTE_COUNT_OFFSET] ); } TEST(Module, read_discrete_inputs) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 2, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_DISCRETE_INPUTS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usDiscreteBit = 0; usByteOffset = ucCount / 8 ; usDiscreteBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucDiscreteInputsBuf[usByteOffset] & (1 << usDiscreteBit) , ucReceivedValue & (1 << usDiscreteBit)); } } TEST(Module, read_coils) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usCoilsBit = 0; usByteOffset = ucCount / 8 ; usCoilsBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit)); } } TEST(Module, write_coil) { uint8_t ucQueryBuf[QUERY_LEN] = {0, 0, 0, 0, 0, 6, 1, 1, 0, 0, 0, 3}; uint8_t ucResponseLen = 0; uint8_t ucByteCount = 0; uint16_t usNumOfData = 0; usNumOfData = (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET] << 8); usNumOfData |= (uint16_t)(ucQueryBuf[NO_OF_DATA_OFFSET + 1]); ucResponseLen = MBAP_HEADER_LEN + (usNumOfData / 8) + 2; ucByteCount = usNumOfData / 8; if (0 != ucQueryBuf[11]) { ucResponseLen = ucResponseLen + 1; ucByteCount = ucByteCount + 1; } memcpy(pucQuery, ucQueryBuf, QUERY_LEN); CHECK_EQUAL(ucResponseLen, mbap_ProcessRequest(pucQuery, QUERY_LEN, pucResponse)); CHECK_EQUAL(ucByteCount, pucResponse[MBT_BYTE_COUNT_OFFSET]); for (uint8_t ucCount = 0; ucCount < MAX_COILS; ucCount++) { uint8_t ucReceivedValue = 0; uint16_t usByteOffset = 0; uint16_t usCoilsBit = 0; usByteOffset = ucCount / 8 ; usCoilsBit = ucCount - usByteOffset * 8; ucReceivedValue = (uint8_t)(pucResponse[MBT_DATA_VALUES_OFFSET + usByteOffset]); CHECK_EQUAL(g_ucCoilsBuf[usByteOffset] & (1 << usCoilsBit) , ucReceivedValue & (1 << usCoilsBit)); } }
35.066066
119
0.684936
yisea123
a7ed46564aa28c4496c89aac6c47e69f72c87805
2,034
cpp
C++
DataPackets/main.cpp
culaja/CppDsp
70163cf51291692bb72a165fc0216ae087b75292
[ "MIT" ]
null
null
null
DataPackets/main.cpp
culaja/CppDsp
70163cf51291692bb72a165fc0216ae087b75292
[ "MIT" ]
null
null
null
DataPackets/main.cpp
culaja/CppDsp
70163cf51291692bb72a165fc0216ae087b75292
[ "MIT" ]
null
null
null
#include <iostream> #include <cpptest.h> #include "MainTestHarness.h" #include "UnitTests/PacketQueueTests.h" #define RUN_MAIN_TEST_HARNESS // Comment this line if you want to run unit tests, otherwise this will trigger MainTestHarness to execute using namespace std; enum OutputType { Compiler, Html, TextTerse, TextVerbose }; static void usage() { cout << "usage: mytest [MODE]\n" << "where MODE may be one of:\n" << " --compiler\n" << " --html\n" << " --text-terse (default)\n" << " --text-verbose\n"; exit(0); } static auto_ptr<Test::Output> cmdline(int argc, char* argv[]) { if (argc > 2) usage(); // will not return Test::Output* output = 0; if (argc == 1) output = new Test::TextOutput(Test::TextOutput::Verbose); else { const char* arg = argv[1]; if (strcmp(arg, "--compiler") == 0) output = new Test::CompilerOutput; else if (strcmp(arg, "--html") == 0) output = new Test::HtmlOutput; else if (strcmp(arg, "--text-terse") == 0) output = new Test::TextOutput(Test::TextOutput::Terse); else if (strcmp(arg, "--text-verbose") == 0) output = new Test::TextOutput(Test::TextOutput::Verbose); else { cout << "invalid commandline argument: " << arg << endl; usage(); // will not return } } return auto_ptr<Test::Output>(output); } int run_tests(int argc, char* argv[]) { try { // Demonstrates the ability to use multiple test suites // Test::Suite ts; ts.add(auto_ptr<Test::Suite>(new PacketQueueTests)); // Run the tests // auto_ptr<Test::Output> output(cmdline(argc, argv)); ts.run(*output, true); Test::HtmlOutput* const html = dynamic_cast<Test::HtmlOutput*>(output.get()); if (html) html->generate(cout, true, "MyTest"); } catch (...) { cout << "unexpected exception encountered\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Main test program // int main(int argc, char* argv[]) { #ifdef RUN_MAIN_TEST_HARNESS MainTestHarness test; return test.Run(argc, argv); #else return run_tests(argc, argv); #endif }
20.755102
136
0.656342
culaja
a7ee53eed9f898947d3f9cdf8453e33c43f2abf2
12,845
cpp
C++
tests/Widget.cpp
cyanskies/TGUI
9d84916313aacdfc33dc9a8b9e60609449fddce7
[ "Zlib" ]
null
null
null
tests/Widget.cpp
cyanskies/TGUI
9d84916313aacdfc33dc9a8b9e60609449fddce7
[ "Zlib" ]
null
null
null
tests/Widget.cpp
cyanskies/TGUI
9d84916313aacdfc33dc9a8b9e60609449fddce7
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "Tests.hpp" #include <TGUI/TGUI.hpp> TEST_CASE("[Widget]") { tgui::Widget::Ptr widget = std::make_shared<tgui::Button>(); SECTION("Visibile") { REQUIRE(widget->isVisible()); widget->hide(); REQUIRE(!widget->isVisible()); widget->show(); REQUIRE(widget->isVisible()); } SECTION("Enabled") { REQUIRE(widget->isEnabled()); widget->disable(); REQUIRE(!widget->isEnabled()); widget->enable(); REQUIRE(widget->isEnabled()); } SECTION("Parent") { tgui::Panel::Ptr panel1 = std::make_shared<tgui::Panel>(); tgui::Panel::Ptr panel2 = std::make_shared<tgui::Panel>(); tgui::Panel::Ptr panel3 = std::make_shared<tgui::Panel>(); REQUIRE(widget->getParent() == nullptr); panel1->add(widget); REQUIRE(widget->getParent() == panel1.get()); panel1->remove(widget); REQUIRE(widget->getParent() == nullptr); panel2->add(widget); REQUIRE(widget->getParent() == panel2.get()); widget->setParent(panel3.get()); REQUIRE(widget->getParent() == panel3.get()); widget->setParent(nullptr); REQUIRE(widget->getParent() == nullptr); } SECTION("Opacity") { REQUIRE(widget->getOpacity() == 1.f); widget->setOpacity(0.5f); REQUIRE(widget->getOpacity() == 0.5f); widget->setOpacity(2.f); REQUIRE(widget->getOpacity() == 1.f); widget->setOpacity(-2.f); REQUIRE(widget->getOpacity() == 0.f); } SECTION("Tooltip") { auto tooltip1 = std::make_shared<tgui::Label>(); tooltip1->setText("some text"); widget->setToolTip(tooltip1); REQUIRE(widget->getToolTip() == tooltip1); // ToolTip does not has to be a label auto tooltip2 = std::make_shared<tgui::Panel>(); widget->setToolTip(tooltip2); REQUIRE(widget->getToolTip() == tooltip2); // ToolTip can be removed widget->setToolTip(nullptr); REQUIRE(widget->getToolTip() == nullptr); } SECTION("Font") { widget = std::make_shared<tgui::Button>(); REQUIRE(widget->getFont() == nullptr); widget->setFont("resources/DroidSansArmenian.ttf"); REQUIRE(widget->getFont() != nullptr); widget->setFont(nullptr); REQUIRE(widget->getFont() == nullptr); tgui::Gui gui; gui.add(widget); REQUIRE(widget->getFont() != nullptr); } SECTION("Move to front/back") { auto container = std::make_shared<tgui::Panel>(); auto widget1 = std::make_shared<tgui::Button>(); auto widget2 = std::make_shared<tgui::Button>(); auto widget3 = std::make_shared<tgui::Button>(); container->add(widget1); container->add(widget2); container->add(widget3); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget1); REQUIRE(container->getWidgets()[1] == widget2); REQUIRE(container->getWidgets()[2] == widget3); widget1->moveToFront(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget3); REQUIRE(container->getWidgets()[2] == widget1); widget3->moveToFront(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget1); REQUIRE(container->getWidgets()[2] == widget3); widget1->moveToBack(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget1); REQUIRE(container->getWidgets()[1] == widget2); REQUIRE(container->getWidgets()[2] == widget3); widget2->moveToBack(); REQUIRE(container->getWidgets().size() == 3); REQUIRE(container->getWidgets()[0] == widget2); REQUIRE(container->getWidgets()[1] == widget1); REQUIRE(container->getWidgets()[2] == widget3); } SECTION("Layouts") { auto container = std::make_shared<tgui::Panel>(); auto widget2 = std::make_shared<tgui::Button>(); container->add(widget); container->add(widget2, "w2"); widget2->setPosition(100, 50); widget2->setSize(600, 150); widget->setPosition(20, 10); widget->setSize(100, 30); SECTION("Position") { REQUIRE(widget->getPosition() == sf::Vector2f(20, 10)); widget->setPosition(tgui::bindLeft(widget2), {"w2.y"}); REQUIRE(widget->getPosition() == sf::Vector2f(100, 50)); widget2->setPosition(50, 30); REQUIRE(widget->getPosition() == sf::Vector2f(50, 30)); // String layout only works after adding widget to parent auto widget3 = widget->clone(); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 0)); container->add(widget3); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 30)); // Layout can only be copied when it is a string widget2->setPosition(20, 40); REQUIRE(widget3->getPosition() == sf::Vector2f(50, 40)); // String is re-evaluated and new widgets are bound after copying widget->setPosition({"{width, height}"}); REQUIRE(widget->getPosition() == sf::Vector2f(100, 30)); auto widget4 = widget->clone(); widget->setSize(40, 50); REQUIRE(widget4->getPosition() == sf::Vector2f(100, 30)); widget4->setSize(60, 70); REQUIRE(widget4->getPosition() == sf::Vector2f(60, 70)); } SECTION("Size") { REQUIRE(widget->getSize() == sf::Vector2f(100, 30)); widget->setSize({"w2.width"}, tgui::bindHeight(widget2)); REQUIRE(widget->getSize() == sf::Vector2f(600, 150)); widget2->setSize(50, 30); REQUIRE(widget->getSize() == sf::Vector2f(50, 30)); // String layout only works after adding widget to parent auto widget3 = widget->clone(); REQUIRE(widget3->getSize() == sf::Vector2f(0, 30)); container->add(widget3); REQUIRE(widget3->getSize() == sf::Vector2f(50, 30)); // Layout can only be copied when it is a string widget2->setSize(20, 40); REQUIRE(widget3->getSize() == sf::Vector2f(20, 30)); // String is re-evaluated and new widgets are bound after copying widget->setSize({"position"}); REQUIRE(widget->getSize() == sf::Vector2f(20, 10)); auto widget4 = widget->clone(); widget->setPosition(40, 50); REQUIRE(widget4->getSize() == sf::Vector2f(20, 10)); widget4->setPosition(60, 70); REQUIRE(widget4->getSize() == sf::Vector2f(60, 70)); } } SECTION("Saving and loading widget with layouts from file") { auto parent = std::make_shared<tgui::Panel>(); parent->add(widget, "Widget Name.With:Special{Chars}"); SECTION("Bind 2d non-string") { widget->setPosition(tgui::bindPosition(parent)); widget->setSize(tgui::bindSize(parent)); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); // Non-string layouts cannot be saved yet! parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(50, 50)); REQUIRE(widget->getSize() == sf::Vector2f(400, 300)); } SECTION("Bind 1d non-strings and string combination") { widget->setPosition(tgui::bindLeft(parent), {"parent.top"}); widget->setSize({"parent.width"}, tgui::bindHeight(parent)); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); // Non-string layout cannot be saved yet, string layout will have been saved correctly! parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(50, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 300)); } SECTION("Bind 1d strings") { widget->setPosition({"&.x"}, {"&.y"}); widget->setSize({"&.w"}, {"&.h"}); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(100, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 600)); } SECTION("Bind 2d strings") { widget->setPosition({"{&.x, &.y}"}); widget->setSize({"parent.size"}); parent->setSize(400, 300); parent->setPosition(50, 50); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileWidget1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileWidget2.txt")); REQUIRE(compareFiles("WidgetFileWidget1.txt", "WidgetFileWidget2.txt")); widget = parent->get("Widget Name.With:Special{Chars}"); parent->setPosition(100, 100); parent->setSize(800, 600); REQUIRE(widget->getPosition() == sf::Vector2f(100, 100)); REQUIRE(widget->getSize() == sf::Vector2f(800, 600)); } } SECTION("Bug Fixes") { SECTION("Disabled widgets should not be focusable (https://forum.tgui.eu/index.php?topic=384)") { tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>(); tgui::EditBox::Ptr editBox = std::make_shared<tgui::EditBox>(); editBox->setFont("resources/DroidSansArmenian.ttf"); panel->add(editBox); editBox->focus(); REQUIRE(editBox->isFocused()); editBox->disable(); REQUIRE(!editBox->isFocused()); editBox->focus(); REQUIRE(!editBox->isFocused()); } } }
39.645062
129
0.576645
cyanskies
a7ef33772188da38d9a71d4c5a812edf7feb3ea2
2,052
cpp
C++
src/Node.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
1
2018-05-29T03:08:54.000Z
2018-05-29T03:08:54.000Z
src/Node.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
null
null
null
src/Node.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
1
2017-07-24T11:58:52.000Z
2017-07-24T11:58:52.000Z
#include <torch/Node.h> #include <algorithm> #include <torch/Context.h> #include <torch/Link.h> #include <torch/Object.h> namespace torch { Node::Node(std::shared_ptr<Context> context) : Object(context) { } size_t Node::GetChildCount() const { return m_children.size(); } std::shared_ptr<Node> Node::GetChild(size_t index) const { return m_children[index]; } bool Node::HasChild(std::shared_ptr<const Node> child) const { auto iter = std::find(m_children.begin(), m_children.end(), child); return iter != m_children.end(); } void Node::AddChild(std::shared_ptr<Node> child) { if (CanAddChild(child)) { m_children.push_back(child); m_context->MarkDirty(); } } void Node::RemoveChild(std::shared_ptr<const Node> child) { auto iter = std::find(m_children.begin(), m_children.end(), child); if (iter != m_children.end()) { m_children.erase(iter); m_context->MarkDirty(); } } void Node::RemoveChildren() { if (!m_children.empty()) { m_children.clear(); m_context->MarkDirty(); } } void Node::PreBuildScene() { } void Node::BuildScene(Link& link) { BuildChildScene(link); } void Node::PostBuildScene() { } void Node::BuildScene(optix::Variable variable) { Link link(m_context); BuildScene(link); link.Write(variable); } BoundingBox Node::GetBounds(const Transform& transform) { return GetChildBounds(transform); } BoundingBox Node::GetChildBounds(const Transform& transform) { BoundingBox bounds; const Transform childTransform = transform * m_transform; for (std::shared_ptr<Node> child : m_children) { bounds.Union(child->GetBounds(childTransform)); } return bounds; } void Node::BuildChildScene(Link& link) { Link childLink = link.Branch(m_transform); for (std::shared_ptr<Node> child : m_children) { child->BuildScene(childLink); } } bool Node::CanAddChild(std::shared_ptr<const Node> child) const { return child && child.get() != this && !HasChild(child); } void Node::UpdateTransform() { m_context->MarkDirty(); } } // namespace torch
17.389831
69
0.693957
arpg
a7f0ac58a4c9789743746dd14e1fd24a1d034a4f
6,545
cc
C++
src/json_serializer.cc
prestolabs/treelite
10878afbe4823dc30ff4b1a3ed2a156012e2539a
[ "Apache-2.0" ]
585
2017-09-12T20:13:47.000Z
2022-03-30T06:18:36.000Z
src/json_serializer.cc
prestolabs/treelite
10878afbe4823dc30ff4b1a3ed2a156012e2539a
[ "Apache-2.0" ]
325
2017-09-14T21:45:46.000Z
2022-03-28T11:27:58.000Z
src/json_serializer.cc
prestolabs/treelite
10878afbe4823dc30ff4b1a3ed2a156012e2539a
[ "Apache-2.0" ]
88
2017-09-16T01:02:29.000Z
2022-03-29T22:50:17.000Z
/*! * Copyright (c) 2020-2021 by Contributors * \file json_serializer.cc * \brief Reference serializer implementation, which serializes to JSON. This is useful for testing * correctness of the binary serializer * \author Hyunsu Cho */ #include <treelite/tree.h> #include <treelite/logging.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/writer.h> #include <rapidjson/prettywriter.h> #include <ostream> #include <type_traits> #include <cstdint> #include <cstddef> namespace { template <typename WriterType, typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true> void WriteElement(WriterType& writer, T e) { writer.Uint64(static_cast<uint64_t>(e)); } template <typename WriterType, typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true> void WriteElement(WriterType& writer, T e) { writer.Double(static_cast<double>(e)); } template <typename WriterType> void WriteString(WriterType& writer, const std::string& str) { writer.String(str.data(), str.size()); } template <typename WriterType, typename ThresholdType, typename LeafOutputType> void WriteNode(WriterType& writer, const treelite::Tree<ThresholdType, LeafOutputType>& tree, int node_id) { writer.StartObject(); writer.Key("node_id"); writer.Int(node_id); if (tree.IsLeaf(node_id)) { writer.Key("leaf_value"); if (tree.HasLeafVector(node_id)) { writer.StartArray(); for (LeafOutputType e : tree.LeafVector(node_id)) { WriteElement(writer, e); } writer.EndArray(); } else { WriteElement(writer, tree.LeafValue(node_id)); } } else { writer.Key("split_feature_id"); writer.Uint(tree.SplitIndex(node_id)); writer.Key("default_left"); writer.Bool(tree.DefaultLeft(node_id)); writer.Key("split_type"); auto split_type = tree.SplitType(node_id); WriteString(writer, treelite::SplitFeatureTypeName(split_type)); if (split_type == treelite::SplitFeatureType::kNumerical) { writer.Key("comparison_op"); WriteString(writer, treelite::OpName(tree.ComparisonOp(node_id))); writer.Key("threshold"); writer.Double(tree.Threshold(node_id)); } else if (split_type == treelite::SplitFeatureType::kCategorical) { writer.Key("categories_list_right_child"); writer.Bool(tree.CategoriesListRightChild(node_id)); writer.Key("matching_categories"); writer.StartArray(); for (uint32_t e : tree.MatchingCategories(node_id)) { writer.Uint(e); } writer.EndArray(); } writer.Key("left_child"); writer.Int(tree.LeftChild(node_id)); writer.Key("right_child"); writer.Int(tree.RightChild(node_id)); } if (tree.HasDataCount(node_id)) { writer.Key("data_count"); writer.Uint64(tree.DataCount(node_id)); } if (tree.HasSumHess(node_id)) { writer.Key("sum_hess"); writer.Double(tree.SumHess(node_id)); } if (tree.HasGain(node_id)) { writer.Key("gain"); writer.Double(tree.Gain(node_id)); } writer.EndObject(); } template <typename WriterType> void SerializeTaskParamToJSON(WriterType& writer, treelite::TaskParam task_param) { writer.StartObject(); writer.Key("output_type"); WriteString(writer, treelite::OutputTypeToString(task_param.output_type)); writer.Key("grove_per_class"); writer.Bool(task_param.grove_per_class); writer.Key("num_class"); writer.Uint(task_param.num_class); writer.Key("leaf_vector_size"); writer.Uint(task_param.leaf_vector_size); writer.EndObject(); } template <typename WriterType> void SerializeModelParamToJSON(WriterType& writer, treelite::ModelParam model_param) { writer.StartObject(); writer.Key("pred_transform"); WriteString(writer, std::string(model_param.pred_transform)); writer.Key("sigmoid_alpha"); writer.Double(model_param.sigmoid_alpha); writer.Key("global_bias"); writer.Double(model_param.global_bias); writer.EndObject(); } } // anonymous namespace namespace treelite { template <typename WriterType, typename ThresholdType, typename LeafOutputType> void DumpTreeAsJSON(WriterType& writer, const Tree<ThresholdType, LeafOutputType>& tree) { writer.StartObject(); writer.Key("num_nodes"); writer.Int(tree.num_nodes); writer.Key("nodes"); writer.StartArray(); for (std::size_t i = 0; i < tree.nodes_.Size(); ++i) { WriteNode<WriterType, ThresholdType, LeafOutputType>(writer, tree, i); } writer.EndArray(); writer.EndObject(); // Basic checks TREELITE_CHECK_EQ(tree.nodes_.Size(), tree.num_nodes); TREELITE_CHECK_EQ(tree.nodes_.Size() + 1, tree.matching_categories_offset_.Size()); TREELITE_CHECK_EQ(tree.matching_categories_offset_.Back(), tree.matching_categories_.Size()); } template <typename WriterType, typename ThresholdType, typename LeafOutputType> void DumpModelAsJSON(WriterType& writer, const ModelImpl<ThresholdType, LeafOutputType>& model) { writer.StartObject(); writer.Key("num_feature"); writer.Int(model.num_feature); writer.Key("task_type"); WriteString(writer, TaskTypeToString(model.task_type)); writer.Key("average_tree_output"); writer.Bool(model.average_tree_output); writer.Key("task_param"); SerializeTaskParamToJSON(writer, model.task_param); writer.Key("model_param"); SerializeModelParamToJSON(writer, model.param); writer.Key("trees"); writer.StartArray(); for (const Tree<ThresholdType, LeafOutputType>& tree : model.trees) { DumpTreeAsJSON(writer, tree); } writer.EndArray(); writer.EndObject(); } template <typename ThresholdType, typename LeafOutputType> void ModelImpl<ThresholdType, LeafOutputType>::DumpAsJSON(std::ostream& fo, bool pretty_print) const { rapidjson::OStreamWrapper os(fo); if (pretty_print) { rapidjson::PrettyWriter<rapidjson::OStreamWrapper> writer(os); writer.SetFormatOptions(rapidjson::PrettyFormatOptions::kFormatSingleLineArray); DumpModelAsJSON(writer, *this); } else { rapidjson::Writer<rapidjson::OStreamWrapper> writer(os); DumpModelAsJSON(writer, *this); } } template void ModelImpl<float, uint32_t>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<float, float>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<double, uint32_t>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; template void ModelImpl<double, double>::DumpAsJSON(std::ostream& fo, bool pretty_print) const; } // namespace treelite
32.562189
99
0.724523
prestolabs
a7f12eab1ab20b7e9afc6219b69cff28f070d373
1,801
cc
C++
tensorflow/lite/experimental/micro/examples/micro_speech/disco_f746ng/command_responder.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tensorflow/lite/experimental/micro/examples/micro_speech/disco_f746ng/command_responder.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tensorflow/lite/experimental/micro/examples/micro_speech/disco_f746ng/command_responder.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/experimental/micro/examples/micro_speech/command_responder.h" #include "LCD_DISCO_F746NG.h" LCD_DISCO_F746NG lcd; // When a command is detected, write it to the display and log it to the // serial port. void RespondToCommand(tflite::ErrorReporter *error_reporter, int32_t current_time, const char *found_command, uint8_t score, bool is_new_command) { if (is_new_command) { error_reporter->Report("Heard %s (%d) @%dms", found_command, score, current_time); if (*found_command == 'y') { lcd.Clear(0xFF0F9D58); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard yes!", CENTER_MODE); } else if (*found_command == 'n') { lcd.Clear(0xFFDB4437); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard no :(", CENTER_MODE); } else if (*found_command == 'u') { lcd.Clear(0xFFF4B400); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard unknown", CENTER_MODE); } else { lcd.Clear(0xFF4285F4); lcd.DisplayStringAt(0, LINE(5), (uint8_t *)"Heard silence", CENTER_MODE); } } }
40.022222
87
0.659634
abhaikollara
a7f1bb691a74cb7a47e0e0fe8076658cdb0b8887
40,903
cpp
C++
toonz/sources/tnztools/plastictool_meshedit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
3,710
2016-03-26T00:40:48.000Z
2022-03-31T21:35:12.000Z
toonz/sources/tnztools/plastictool_meshedit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
4,246
2016-03-26T01:21:45.000Z
2022-03-31T23:10:47.000Z
toonz/sources/tnztools/plastictool_meshedit.cpp
wofogen/tahoma2d
ce5a89a7b1027b2c1769accb91184a2ee6442b4d
[ "BSD-3-Clause" ]
633
2016-03-26T00:42:25.000Z
2022-03-17T02:55:13.000Z
// TnzCore includes #include "tmeshimage.h" #include "tgl.h" #include "tundo.h" // TnzExt includes #include "ext/plasticdeformerstorage.h" // tcg includes #include "tcg/tcg_macros.h" #include "tcg/tcg_point_ops.h" #include <unordered_set> #include <unordered_map> using namespace tcg::bgl; #include <boost/graph/breadth_first_search.hpp> // STD includes #include <stack> #include "plastictool.h" using namespace PlasticToolLocals; //**************************************************************************************** // Local namespace stuff //**************************************************************************************** namespace { typedef PlasticTool::MeshIndex MeshIndex; typedef TTextureMesh::vertex_type vertex_type; typedef TTextureMesh::edge_type edge_type; typedef TTextureMesh::face_type face_type; //------------------------------------------------------------------------ bool borderEdge(const TTextureMesh &mesh, int e) { return (mesh.edge(e).facesCount() < 2); } bool borderVertex(const TTextureMesh &mesh, int v) { const TTextureVertex &vx = mesh.vertex(v); tcg::vertex_traits<TTextureVertex>::edges_const_iterator et, eEnd(vx.edgesEnd()); for (et = vx.edgesBegin(); et != eEnd; ++et) { if (borderEdge(mesh, *et)) return true; } return false; } //============================================================================ bool testSwapEdge(const TTextureMesh &mesh, int e) { return (mesh.edge(e).facesCount() == 2); } //------------------------------------------------------------------------ bool testCollapseEdge(const TTextureMesh &mesh, int e) { struct Locals { const TTextureMesh &m_mesh; int m_e; const TTextureMesh::edge_type &m_ed; bool testTrianglesCount() { // There must be at least one remanining triangle return (m_mesh.facesCount() > m_ed.facesCount()); } bool testBoundary() { // Must not join two non-adjacent boundary vertices return (!borderVertex(m_mesh, m_ed.vertex(0)) || !borderVertex(m_mesh, m_ed.vertex(1)) || borderEdge(m_mesh, m_e)); } bool testAdjacency() { // See TriMesh<>::collapseEdge() // Retrieve allowed adjacent vertices int f, fCount = m_ed.facesCount(); int allowedV[6], *avt, *avEnd = allowedV + 3 * fCount; for (f = 0, avt = allowedV; f != fCount; ++f, avt += 3) m_mesh.faceVertices(m_ed.face(f), avt[0], avt[1], avt[2]); // Test adjacent vertices int v0 = m_ed.vertex(0), v1 = m_ed.vertex(1); const vertex_type &vx0 = m_mesh.vertex(v0); tcg::vertex_traits<vertex_type>::edges_const_iterator et, eEnd = vx0.edgesEnd(); for (et = vx0.edgesBegin(); et != eEnd; ++et) { int otherV = m_mesh.edge(*et).otherVertex(v0); if (m_mesh.edgeInciding(v1, otherV) >= 0) { // Adjacent vertex - must be found in the allowed list if (std::find(allowedV, avEnd, otherV) == avEnd) return false; } } return true; } } locals = {mesh, e, mesh.edge(e)}; return (locals.testTrianglesCount() && locals.testBoundary() && locals.testAdjacency()); } } // namespace //**************************************************************************************** // PlasticToolLocals stuff //**************************************************************************************** namespace PlasticToolLocals { struct Closer { const TTextureMesh &m_mesh; TPointD m_pos; double dist2(const TTextureMesh::vertex_type &a) { return tcg::point_ops::dist2<TPointD>(a.P(), m_pos); } double dist2(const TTextureMesh::edge_type &a) { const TTextureMesh::vertex_type &avx0 = m_mesh.vertex(a.vertex(0)), &avx1 = m_mesh.vertex(a.vertex(1)); return sq(tcg::point_ops::segDist<TPointD>(avx0.P(), avx1.P(), m_pos)); } bool operator()(const TTextureMesh::vertex_type &a, const TTextureMesh::vertex_type &b) { return (dist2(a) < dist2(b)); } bool operator()(const TTextureMesh::edge_type &a, const TTextureMesh::edge_type &b) { return (dist2(a) < dist2(b)); } }; //============================================================================== static std::pair<double, int> closestVertex(const TTextureMesh &mesh, const TPointD &pos) { Closer closer = {mesh, pos}; int vIdx = int( std::min_element(mesh.vertices().begin(), mesh.vertices().end(), closer) .index()); return std::make_pair(closer.dist2(mesh.vertex(vIdx)), vIdx); } //------------------------------------------------------------------------ static std::pair<double, int> closestEdge(const TTextureMesh &mesh, const TPointD &pos) { Closer closer = {mesh, pos}; int eIdx = int(std::min_element(mesh.edges().begin(), mesh.edges().end(), closer) .index()); return std::make_pair(closer.dist2(mesh.edge(eIdx)), eIdx); } //------------------------------------------------------------------------ std::pair<double, MeshIndex> closestVertex(const TMeshImage &mi, const TPointD &pos) { std::pair<double, MeshIndex> closest((std::numeric_limits<double>::max)(), MeshIndex()); const TMeshImage::meshes_container &meshes = mi.meshes(); TMeshImage::meshes_container::const_iterator mt, mEnd = meshes.end(); for (mt = meshes.begin(); mt != mEnd; ++mt) { const std::pair<double, int> &candidateIdx = closestVertex(**mt, pos); std::pair<double, MeshIndex> candidate( candidateIdx.first, MeshIndex(mt - meshes.begin(), candidateIdx.second)); if (candidate < closest) closest = candidate; } return closest; } //------------------------------------------------------------------------ std::pair<double, MeshIndex> closestEdge(const TMeshImage &mi, const TPointD &pos) { std::pair<double, MeshIndex> closest((std::numeric_limits<double>::max)(), MeshIndex()); const TMeshImage::meshes_container &meshes = mi.meshes(); TMeshImage::meshes_container::const_iterator mt, mEnd = meshes.end(); for (mt = meshes.begin(); mt != mEnd; ++mt) { const std::pair<double, int> &candidateIdx = closestEdge(**mt, pos); std::pair<double, MeshIndex> candidate( candidateIdx.first, MeshIndex(mt - meshes.begin(), candidateIdx.second)); if (candidate < closest) closest = candidate; } return closest; } } // namespace //**************************************************************************************** // Cut Mesh operation //**************************************************************************************** namespace { struct EdgeCut { int m_vIdx; //!< Vertex index to cut from. int m_eIdx; //!< Edge index to cut. EdgeCut(int vIdx, int eIdx) : m_vIdx(vIdx), m_eIdx(eIdx) {} }; struct VertexOccurrence { int m_count; //!< Number of times a vertex occurs. int m_adjacentEdgeIdx[2]; //!< Edge indexes of which a vertex is endpoint. }; //============================================================================ bool buildEdgeCuts(const TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection, int &meshIdx, std::vector<EdgeCut> &edgeCuts) { typedef PlasticTool::MeshSelection::objects_container edges_container; typedef PlasticTool::MeshIndex MeshIndex; typedef std::unordered_map<int, VertexOccurrence> VertexOccurrencesMap; struct locals { static bool differentMesh(const MeshIndex &a, const MeshIndex &b) { return (a.m_meshIdx != b.m_meshIdx); } static int testSingleMesh(const edges_container &edges) { assert(!edges.empty()); return (std::find_if(edges.begin(), edges.end(), [&edges](const MeshIndex &x) { return differentMesh(x, edges.front()); }) == edges.end()) ? edges.front().m_meshIdx : -1; } static bool testNoBoundaryEdge(const TTextureMesh &mesh, const edges_container &edges) { edges_container::const_iterator et, eEnd = edges.end(); for (et = edges.begin(); et != eEnd; ++et) if (::borderEdge(mesh, et->m_idx)) return false; return true; } static bool buildVertexOccurrences( const TTextureMesh &mesh, const edges_container &edges, VertexOccurrencesMap &vertexOccurrences) { // Calculate vertex occurrences as edge endpoints edges_container::const_iterator et, eEnd = edges.end(); for (et = edges.begin(); et != eEnd; ++et) { const edge_type &ed = mesh.edge(et->m_idx); int v0 = ed.vertex(0), v1 = ed.vertex(1); VertexOccurrence &vo0 = vertexOccurrences[v0], &vo1 = vertexOccurrences[v1]; if (vo0.m_count > 1 || vo1.m_count > 1) return false; vo0.m_adjacentEdgeIdx[vo0.m_count++] = vo1.m_adjacentEdgeIdx[vo1.m_count++] = et->m_idx; } return true; } static bool buildEdgeCuts(const TTextureMesh &mesh, const edges_container &edges, std::vector<EdgeCut> &edgeCuts) { VertexOccurrencesMap vertexOccurrences; if (!buildVertexOccurrences(mesh, edges, vertexOccurrences)) return false; // Build endpoints (exactly 2) int endPoints[2]; int epCount = 0; VertexOccurrencesMap::iterator ot, oEnd = vertexOccurrences.end(); for (ot = vertexOccurrences.begin(); ot != oEnd; ++ot) { if (ot->second.m_count == 1) { if (epCount > 1) return false; endPoints[epCount++] = ot->first; } } if (epCount != 2) return false; // Pick the first endpoint on the boundary, if any (otherwise, just pick // one) int *ept, *epEnd = endPoints + 2; ept = std::find_if(endPoints, epEnd, [&mesh](int v) { return borderVertex(mesh, v); }); if (ept == epEnd) { // There is no boundary endpoint if (edges.size() < 2) // We should not cut the mesh on a return false; // single edge - no vertex to duplicate! ept = endPoints; } // Build the edge cuts list, expanding the edges selection from // the chosen endpoint edgeCuts.push_back(EdgeCut( // Build the first EdgeCut separately *ept, vertexOccurrences[*ept].m_adjacentEdgeIdx[0])); int e, eCount = int(edges.size()); // Build the remaining ones for (e = 1; e != eCount; ++e) { const EdgeCut &lastCut = edgeCuts.back(); int vIdx = mesh.edge(lastCut.m_eIdx).otherVertex(lastCut.m_vIdx); const int(&adjEdges)[2] = vertexOccurrences[vIdx].m_adjacentEdgeIdx; int eIdx = (adjEdges[0] == lastCut.m_eIdx) ? adjEdges[1] : adjEdges[0]; edgeCuts.push_back(EdgeCut(vIdx, eIdx)); } return true; } }; const edges_container &edges = edgesSelection.objects(); // Trivial early bailouts if (edges.empty()) return false; // Selected edges must lie on the same mesh meshIdx = locals::testSingleMesh(edges); if (meshIdx < 0) return false; const TTextureMesh &mesh = *mi.meshes()[meshIdx]; // No selected edge must be on the boundary return (locals::testNoBoundaryEdge(mesh, edges) && locals::buildEdgeCuts(mesh, edges, edgeCuts)); } //------------------------------------------------------------------------ inline bool testCutMesh(const TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection) { std::vector<EdgeCut> edgeCuts; int meshIdx; return buildEdgeCuts(mi, edgesSelection, meshIdx, edgeCuts); } //------------------------------------------------------------------------ void slitMesh(TTextureMesh &mesh, int e) //! Opens a slit along the specified edge index. { TTextureMesh::edge_type &ed = mesh.edge(e); assert(ed.facesCount() == 2); // Duplicate the edge and pass one face to the duplicate TTextureMesh::edge_type edDup(ed.vertex(0), ed.vertex(1)); int f = ed.face(1); edDup.addFace(f); ed.eraseFace(ed.facesBegin() + 1); int eDup = mesh.addEdge(edDup); // Alter the face to host the duplicate TTextureMesh::face_type &fc = mesh.face(f); (fc.edge(0) == e) ? fc.setEdge(0, eDup) : (fc.edge(1) == e) ? fc.setEdge(1, eDup) : fc.setEdge(2, eDup); } //------------------------------------------------------------------------ /*! \brief Duplicates a mesh edge-vertex pair (the 'cut') and separates their connections to adjacent mesh primitives. \remark The starting vertex is supposed to be on the mesh boundary. \remark Edges with a single neighbouring face can be duplicated, too. */ void cutEdge(TTextureMesh &mesh, const EdgeCut &edgeCut) { struct locals { static void transferEdge(TTextureMesh &mesh, int e, int vFrom, int vTo) { edge_type &ed = mesh.edge(e); vertex_type &vxFrom = mesh.vertex(vFrom), &vxTo = mesh.vertex(vTo); (ed.vertex(0) == vFrom) ? ed.setVertex(0, vTo) : ed.setVertex(1, vTo); vxTo.addEdge(e); vxFrom.eraseEdge( std::find(vxFrom.edges().begin(), vxFrom.edges().end(), e)); } static void transferFace(TTextureMesh &mesh, int eFrom, int eTo) { edge_type &edFrom = mesh.edge(eFrom), &edTo = mesh.edge(eTo); int f = mesh.edge(eFrom).face(1); { face_type &fc = mesh.face(f); (fc.edge(0) == eFrom) ? fc.setEdge(0, eTo) : (fc.edge(1) == eFrom) ? fc.setEdge(1, eTo) : fc.setEdge(2, eTo); edTo.addFace(f); edFrom.eraseFace(edFrom.facesBegin() + 1); } } }; // locals int vOrig = edgeCut.m_vIdx, eOrig = edgeCut.m_eIdx; // Create a new vertex at the same position of the original int vDup = mesh.addVertex(vertex_type(mesh.vertex(vOrig).P())); int e = eOrig; if (mesh.edge(e).facesCount() == 2) { // Duplicate the cut edge e = mesh.addEdge(edge_type(vDup, mesh.edge(eOrig).otherVertex(vOrig))); // Transfer one face from the original to the duplicate locals::transferFace(mesh, eOrig, e); } else { // Transfer the original edge to the duplicate vertex locals::transferEdge(mesh, eOrig, vOrig, vDup); } // Edges adjacent to the original vertex that are also adjacent // to the transferred face above must be transferred too int f = mesh.edge(e).face(0); while (f >= 0) { // Retrieve the next edge to transfer int otherE = mesh.otherFaceEdge(f, mesh.edge(e).otherVertex(vDup)); // NOTE: Not "mesh.edgeInciding(vOrig, mesh.otherFaceVertex(f, e))" in the // calculation // of otherE. This is required since by transferring each edge at a // time, // we're 'breaking' faces up - f is adjacent to both vOrig AND vDup! // // The chosen calculation, instead, just asks for the one edge which // does // not have a specific vertex in common to the 2 other edges in the // face. locals::transferEdge(mesh, otherE, vOrig, vDup); // Update e and f e = otherE; f = mesh.edge(otherE).otherFace(f); } } //------------------------------------------------------------------------ } namespace locals_ { // Need to use a named namespace due to // a known gcc 4.2 bug with compiler-generated struct VertexesRecorder // copy constructors. { std::unordered_set<int> &m_examinedVertexes; public: typedef boost::on_examine_vertex event_filter; public: VertexesRecorder(std::unordered_set<int> &examinedVertexes) : m_examinedVertexes(examinedVertexes) {} void operator()(int v, const TTextureMesh &) { m_examinedVertexes.insert(v); } }; } namespace { // void splitUnconnectedMesh(TMeshImage &mi, int meshIdx) { struct locals { static void buildConnectedComponent(const TTextureMesh &mesh, std::unordered_set<int> &vertexes) { // Prepare BFS algorithm std::unique_ptr<UCHAR[]> colorMapP(new UCHAR[mesh.vertices().nodesCount()]()); locals_::VertexesRecorder vertexesRecorder(vertexes); std::stack<int> verticesQueue; // Launch it boost::breadth_first_visit( mesh, int(mesh.vertices().begin().index()), verticesQueue, boost::make_bfs_visitor(vertexesRecorder), colorMapP.get()); } }; // locals // Retrieve the list of vertexes in the first connected component TTextureMesh &origMesh = *mi.meshes()[meshIdx]; std::unordered_set<int> firstComponent; locals::buildConnectedComponent(origMesh, firstComponent); if (firstComponent.size() == origMesh.verticesCount()) return; // There are (exactly) 2 connected components. Just duplicate the mesh // and keep/delete found vertexes. TTextureMeshP dupMeshPtr(new TTextureMesh(origMesh)); TTextureMesh &dupMesh = *dupMeshPtr; TTextureMesh::vertices_container &vertices = origMesh.vertices(); TTextureMesh::vertices_container::iterator vt, vEnd = vertices.end(); for (vt = vertices.begin(); vt != vEnd;) { int v = int(vt.index()); ++vt; if (firstComponent.count(v)) dupMesh.removeVertex(v); else origMesh.removeVertex(v); } dupMesh.squeeze(); origMesh.squeeze(); mi.meshes().push_back(dupMeshPtr); } //------------------------------------------------------------------------ void splitMesh(TMeshImage &mi, int meshIdx, int lastBoundaryVertex) { // Retrieve a cutting edge with a single adjacent face - cutting that // will just duplicate the vertex and separate the mesh in 2 connected // components TTextureMesh &mesh = *mi.meshes()[meshIdx]; int e; { const vertex_type &lbVx = mesh.vertex(lastBoundaryVertex); vertex_type::edges_const_iterator et = std::find_if(lbVx.edgesBegin(), lbVx.edgesEnd(), [&mesh](int e) { return borderEdge(mesh, e); }); assert(et != lbVx.edgesEnd()); e = *et; } cutEdge(mesh, EdgeCut(lastBoundaryVertex, e)); // At this point, separate the 2 resulting connected components // in 2 separate meshes (if necessary) splitUnconnectedMesh(mi, meshIdx); } //------------------------------------------------------------------------ bool cutMesh(TMeshImage &mi, const PlasticTool::MeshSelection &edgesSelection) { struct locals { static int lastVertex(const TTextureMesh &mesh, const std::vector<EdgeCut> &edgeCuts) { return mesh.edge(edgeCuts.back().m_eIdx) .otherVertex(edgeCuts.back().m_vIdx); } static int lastBoundaryVertex(const TTextureMesh &mesh, const std::vector<EdgeCut> &edgeCuts) { int v = lastVertex(mesh, edgeCuts); return ::borderVertex(mesh, v) ? v : -1; } }; // locals std::vector<EdgeCut> edgeCuts; int meshIdx; if (!::buildEdgeCuts(mi, edgesSelection, meshIdx, edgeCuts)) return false; TTextureMesh &mesh = *mi.meshes()[meshIdx]; int lastBoundaryVertex = locals::lastBoundaryVertex(mesh, edgeCuts); // Slit the mesh on the first edge, in case the cuts do not start // on the mesh boundary std::vector<EdgeCut>::iterator ecBegin = edgeCuts.begin(); if (!::borderVertex(mesh, ecBegin->m_vIdx)) { ::slitMesh(mesh, ecBegin->m_eIdx); ++ecBegin; } // Cut edges, in the order specified by edgeCuts std::for_each(ecBegin, edgeCuts.end(), [&mesh](const EdgeCut &edgeCut) { return cutEdge(mesh, edgeCut); }); // Finally, the mesh could have been split in 2 - we need to separate // the pieces if needed if (lastBoundaryVertex >= 0) splitMesh(mi, meshIdx, lastBoundaryVertex); return true; } } // namespace //**************************************************************************************** // Undo definitions //**************************************************************************************** namespace { class MoveVertexUndo_Mesh final : public TUndo { int m_row, m_col; //!< Xsheet coordinates std::vector<MeshIndex> m_vIdxs; //!< Moved vertices std::vector<TPointD> m_origVxsPos; //!< Original vertex positions TPointD m_posShift; //!< Vertex positions shift public: MoveVertexUndo_Mesh(const std::vector<MeshIndex> &vIdxs, const std::vector<TPointD> &origVxsPos, const TPointD &posShift) : m_row(::row()) , m_col(::column()) , m_vIdxs(vIdxs) , m_origVxsPos(origVxsPos) , m_posShift(posShift) { assert(m_vIdxs.size() == m_origVxsPos.size()); } int getSize() const override { return int(sizeof(*this) + m_vIdxs.size() * (sizeof(int) + 2 * sizeof(TPointD))); } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); l_plasticTool.setMeshVertexesSelection(m_vIdxs); l_plasticTool.moveVertex_mesh(m_origVxsPos, m_posShift); l_plasticTool.invalidate(); l_plasticTool .notifyImageChanged(); // IMPORTANT: In particular, sets the level's } // dirty flag, so Toonz knows it has // to be saved! void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); l_plasticTool.setMeshVertexesSelection(m_vIdxs); l_plasticTool.moveVertex_mesh(m_origVxsPos, TPointD()); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class SwapEdgeUndo final : public TUndo { int m_row, m_col; //!< Xsheet coordinates mutable MeshIndex m_edgeIdx; //!< Edge index public: SwapEdgeUndo(const MeshIndex &edgeIdx) : m_row(::row()), m_col(::column()), m_edgeIdx(edgeIdx) {} int getSize() const override { return sizeof(*this); } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = TMeshImageP(TTool::getImage(true)); assert(mi); // Perform swap TTextureMesh &mesh = *mi->meshes()[m_edgeIdx.m_meshIdx]; m_edgeIdx.m_idx = mesh.swapEdge(m_edgeIdx.m_idx); assert(m_edgeIdx.m_idx >= 0); // Invalidate any deformer associated with mi PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Update tool selection l_plasticTool.setMeshEdgesSelection(m_edgeIdx); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { redo(); } // Operation is idempotent (indices // are perfectly restored, too) }; //============================================================================== class TTextureMeshUndo : public TUndo { protected: int m_row, m_col; //!< Xsheet coordinates int m_meshIdx; //!< Mesh index in the image at stored xsheet coords mutable TTextureMesh m_origMesh; //!< Copy of the original mesh public: TTextureMeshUndo(int meshIdx) : m_row(::row()), m_col(::column()), m_meshIdx(meshIdx) {} // Let's say 1MB each - storing the mesh is costly int getSize() const override { return 1 << 20; } TMeshImageP getMeshImage() const { const TMeshImageP &mi = TMeshImageP(TTool::getImage(true)); assert(mi); return mi; } }; //============================================================================== class CollapseEdgeUndo final : public TTextureMeshUndo { int m_eIdx; //!< Collapsed edge index public: CollapseEdgeUndo(const MeshIndex &edgeIdx) : TTextureMeshUndo(edgeIdx.m_meshIdx), m_eIdx(edgeIdx.m_idx) {} void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Store the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; m_origMesh = mesh; // Collapse mesh.collapseEdge(m_eIdx); mesh.squeeze(); // Invalidate any cached deformer associated with the modified mesh image PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Refresh the tool l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Restore the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; mesh = m_origMesh; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(MeshIndex(m_meshIdx, m_eIdx)); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class SplitEdgeUndo final : public TTextureMeshUndo { int m_eIdx; //!< Split edge index public: SplitEdgeUndo(const MeshIndex &edgeIdx) : TTextureMeshUndo(edgeIdx.m_meshIdx), m_eIdx(edgeIdx.m_idx) {} void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Store the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; m_origMesh = mesh; // Split mesh.splitEdge(m_eIdx); // mesh.squeeze(); // // There should be no need to squeeze assert(mesh.vertices().size() == mesh.vertices().nodesCount()); // assert(mesh.edges().size() == mesh.edges().nodesCount()); // assert(mesh.faces().size() == mesh.faces().nodesCount()); // PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); const TMeshImageP &mi = getMeshImage(); // Restore the original mesh TTextureMesh &mesh = *mi->meshes()[m_meshIdx]; mesh = m_origMesh; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(MeshIndex(m_meshIdx, m_eIdx)); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; //============================================================================== class CutEdgesUndo final : public TUndo { int m_row, m_col; //!< Xsheet coordinates TMeshImageP m_origImage; //!< Clone of the original image PlasticTool::MeshSelection m_edgesSelection; //!< Selection to operate on public: CutEdgesUndo(const PlasticTool::MeshSelection &edgesSelection) : m_row(::row()) , m_col(::column()) , m_origImage(TTool::getImage(false)->cloneImage()) , m_edgesSelection(edgesSelection) {} int getSize() const override { return 1 << 20; } bool do_() const { TMeshImageP mi = TTool::getImage(true); if (::cutMesh(*mi, m_edgesSelection)) { PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); l_plasticTool.clearMeshSelections(); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); return true; } return false; } void redo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); bool ret = do_(); (void)ret; assert(ret); } void undo() const override { PlasticTool::TemporaryActivation tempActivate(m_row, m_col); TMeshImageP mi = TTool::getImage(true); // Restore the original image *mi = *m_origImage; PlasticDeformerStorage::instance()->releaseMeshData(mi.getPointer()); // Restore selection l_plasticTool.setMeshEdgesSelection(m_edgesSelection); l_plasticTool.invalidate(); l_plasticTool.notifyImageChanged(); } }; } // namespace //**************************************************************************************** // PlasticTool functions //**************************************************************************************** void PlasticTool::storeMeshImage() { TMeshImageP mi = getImage(false); if (mi != m_mi) { m_mi = mi; clearMeshSelections(); } } //------------------------------------------------------------------------ void PlasticTool::setMeshSelection(MeshSelection &target, const MeshSelection &newSel) { if (newSel.isEmpty()) { target.selectNone(); target.makeNotCurrent(); return; } target.setObjects(newSel.objects()); target.notifyView(); target.makeCurrent(); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshSelection(MeshSelection &target, const MeshSelection &addition) { typedef MeshSelection::objects_container objects_container; const objects_container &storedIdxs = target.objects(); const objects_container &addedIdxs = addition.objects(); // Build new selection objects_container selectedIdxs; if (target.contains(addition)) { std::set_difference(storedIdxs.begin(), storedIdxs.end(), addedIdxs.begin(), addedIdxs.end(), std::back_inserter(selectedIdxs)); } else { std::set_union(storedIdxs.begin(), storedIdxs.end(), addedIdxs.begin(), addedIdxs.end(), std::back_inserter(selectedIdxs)); } setMeshSelection(target, selectedIdxs); } //------------------------------------------------------------------------ void PlasticTool::clearMeshSelections() { m_mvHigh = m_meHigh = MeshIndex(); m_mvSel.selectNone(); m_mvSel.makeNotCurrent(); m_meSel.selectNone(); m_meSel.makeNotCurrent(); } //------------------------------------------------------------------------ void PlasticTool::setMeshVertexesSelection(const MeshSelection &vSel) { setMeshSelection(m_meSel, MeshSelection()), setMeshSelection(m_mvSel, vSel); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshVertexesSelection(const MeshSelection &vSel) { setMeshSelection(m_meSel, MeshSelection()), toggleMeshSelection(m_mvSel, vSel); } //------------------------------------------------------------------------ void PlasticTool::setMeshEdgesSelection(const MeshSelection &eSel) { setMeshSelection(m_meSel, eSel), setMeshSelection(m_mvSel, MeshSelection()); } //------------------------------------------------------------------------ void PlasticTool::toggleMeshEdgesSelection(const MeshSelection &eSel) { toggleMeshSelection(m_meSel, eSel), setMeshSelection(m_mvSel, MeshSelection()); } //------------------------------------------------------------------------ void PlasticTool::mouseMove_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; // Needs to be done now - ensures m_pos is valid m_mvHigh = MeshIndex(); // Reset highlighted primitives if (m_mi) { // Look for nearest primitive std::pair<double, MeshIndex> closestVertex = ::closestVertex(*m_mi, pos), closestEdge = ::closestEdge(*m_mi, pos); // Discriminate on fixed metric const double hDistSq = sq(getPixelSize() * MESH_HIGHLIGHT_DISTANCE); m_mvHigh = m_meHigh = MeshIndex(); if (closestEdge.first < hDistSq) m_meHigh = closestEdge.second; if (closestVertex.first < hDistSq) m_mvHigh = closestVertex.second, m_meHigh = MeshIndex(); } assert(!(m_mvHigh && m_meHigh)); // Vertex and edge highlights are mutually exclusive invalidate(); } //------------------------------------------------------------------------ void PlasticTool::leftButtonDown_mesh(const TPointD &pos, const TMouseEvent &me) { struct Locals { PlasticTool *m_this; void updateSelection(MeshSelection &sel, const MeshIndex &idx, const TMouseEvent &me) { if (idx) { MeshSelection newSel(idx); if (me.isCtrlPressed()) m_this->toggleMeshSelection(sel, newSel); else if (!sel.contains(newSel)) m_this->setMeshSelection(sel, newSel); } else m_this->setMeshSelection(sel, MeshSelection()); } } locals = {this}; // Track mouse position m_pressedPos = m_pos = pos; // Update selection locals.updateSelection(m_mvSel, m_mvHigh, me); locals.updateSelection(m_meSel, m_meHigh, me); // Store original vertex positions if (!m_mvSel.isEmpty()) { std::vector<TPointD> v; for (auto const &e : m_mvSel.objects()) { v.push_back(m_mi->meshes()[e.m_meshIdx]->vertex(e.m_idx).P()); } m_pressedVxsPos = std::move(v); } // Redraw selections invalidate(); } //------------------------------------------------------------------------ void PlasticTool::leftButtonDrag_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; if (!m_mvSel.isEmpty()) { moveVertex_mesh(m_pressedVxsPos, pos - m_pressedPos); invalidate(); } } //------------------------------------------------------------------------ void PlasticTool::leftButtonUp_mesh(const TPointD &pos, const TMouseEvent &me) { // Track mouse position m_pos = pos; if (m_dragged && !m_mvSel.isEmpty()) { TUndoManager::manager()->add(new MoveVertexUndo_Mesh( m_mvSel.objects(), m_pressedVxsPos, pos - m_pressedPos)); invalidate(); notifyImageChanged(); // Sets the level's dirty flag -.-' } } //------------------------------------------------------------------------ void PlasticTool::addContextMenuActions_mesh(QMenu *menu) { bool ret = true; if (!m_meSel.isEmpty()) { if (m_meSel.hasSingleObject()) { const MeshIndex &mIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[mIdx.m_meshIdx]; if (::testSwapEdge(mesh, mIdx.m_idx)) { QAction *swapEdge = menu->addAction(tr("Swap Edge")); ret = ret && connect(swapEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(swapEdge_mesh_undo())); } if (::testCollapseEdge(mesh, mIdx.m_idx)) { QAction *collapseEdge = menu->addAction(tr("Collapse Edge")); ret = ret && connect(collapseEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(collapseEdge_mesh_undo())); } QAction *splitEdge = menu->addAction(tr("Split Edge")); ret = ret && connect(splitEdge, SIGNAL(triggered()), &l_plasticTool, SLOT(splitEdge_mesh_undo())); } if (::testCutMesh(*m_mi, m_meSel)) { QAction *cutEdges = menu->addAction(tr("Cut Mesh")); ret = ret && connect(cutEdges, SIGNAL(triggered()), &l_plasticTool, SLOT(cutEdges_mesh_undo())); } menu->addSeparator(); } assert(ret); } //------------------------------------------------------------------------ void PlasticTool::moveVertex_mesh(const std::vector<TPointD> &origVxsPos, const TPointD &posShift) { if (m_mvSel.isEmpty() || !m_mi) return; assert(origVxsPos.size() == m_mvSel.objects().size()); // Move selected vertices TMeshImageP mi = getImage(true); assert(m_mi == mi); int v, vCount = int(m_mvSel.objects().size()); for (v = 0; v != vCount; ++v) { const MeshIndex &meshIndex = m_mvSel.objects()[v]; TTextureMesh &mesh = *mi->meshes()[meshIndex.m_meshIdx]; mesh.vertex(meshIndex.m_idx).P() = origVxsPos[v] + posShift; } // Mesh must be recompiled PlasticDeformerStorage::instance()->invalidateMeshImage( mi.getPointer(), PlasticDeformerStorage::MESH); } //------------------------------------------------------------------------ void PlasticTool::swapEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; // Test current edge swapability { const MeshIndex &eIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[eIdx.m_meshIdx]; if (!::testSwapEdge(mesh, eIdx.m_idx)) return; } // Perform operation std::unique_ptr<TUndo> undo(new SwapEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::collapseEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; // Test collapsibility of current edge { const MeshIndex &eIdx = m_meSel.objects().front(); const TTextureMesh &mesh = *m_mi->meshes()[eIdx.m_meshIdx]; if (!::testCollapseEdge(mesh, eIdx.m_idx)) return; } // Perform operation std::unique_ptr<TUndo> undo(new CollapseEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::splitEdge_mesh_undo() { if (!(m_mi && m_meSel.hasSingleObject())) return; std::unique_ptr<TUndo> undo(new SplitEdgeUndo(m_meSel.objects().front())); undo->redo(); TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::cutEdges_mesh_undo() { if (!m_mi) return; std::unique_ptr<CutEdgesUndo> undo(new CutEdgesUndo(m_meSel.objects())); if (undo->do_()) TUndoManager::manager()->add(undo.release()); } //------------------------------------------------------------------------ void PlasticTool::draw_mesh() { struct Locals { PlasticTool *m_this; double m_pixelSize; void drawLine(const TPointD &a, const TPointD &b) { glVertex2d(a.x, a.y); glVertex2d(b.x, b.y); } void drawVertexSelections() { typedef MeshSelection::objects_container objects_container; const objects_container &objects = m_this->m_mvSel.objects(); glColor3ub(255, 0, 0); // Red glLineWidth(1.0f); const double hSize = MESH_SELECTED_HANDLE_SIZE * m_pixelSize; objects_container::const_iterator vt, vEnd = objects.end(); for (vt = objects.begin(); vt != vEnd; ++vt) { const TTextureVertex &vx = m_this->m_mi->meshes()[vt->m_meshIdx]->vertex(vt->m_idx); ::drawFullSquare(vx.P(), hSize); } } void drawEdgeSelections() { typedef MeshSelection::objects_container objects_container; const objects_container &objects = m_this->m_meSel.objects(); glColor3ub(0, 0, 255); // Blue glLineWidth(2.0f); glBegin(GL_LINES); objects_container::const_iterator et, eEnd = objects.end(); for (et = objects.begin(); et != eEnd; ++et) { const TTextureVertex &vx0 = m_this->m_mi->meshes()[et->m_meshIdx]->edgeVertex(et->m_idx, 0), &vx1 = m_this->m_mi->meshes()[et->m_meshIdx]->edgeVertex(et->m_idx, 1); drawLine(vx0.P(), vx1.P()); } glEnd(); } void drawVertexHighlights() { if (m_this->m_mvHigh) { const MeshIndex &vHigh = m_this->m_mvHigh; const TTextureMesh::vertex_type &vx = m_this->m_mi->meshes()[vHigh.m_meshIdx]->vertex(vHigh.m_idx); glColor3ub(255, 0, 0); // Red glLineWidth(1.0f); const double hSize = MESH_HIGHLIGHTED_HANDLE_SIZE * m_pixelSize; ::drawSquare(vx.P(), hSize); } } void drawEdgeHighlights() { if (m_this->m_meHigh) { const MeshIndex &eHigh = m_this->m_meHigh; const TTextureMesh::vertex_type &vx0 = m_this->m_mi->meshes()[eHigh.m_meshIdx]->edgeVertex( eHigh.m_idx, 0), &vx1 = m_this->m_mi->meshes()[eHigh.m_meshIdx]->edgeVertex( eHigh.m_idx, 1); { glPushAttrib(GL_LINE_BIT); glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0xCCCC); glColor3ub(0, 0, 255); // Blue glLineWidth(1.0f); glBegin(GL_LINES); drawLine(vx0.P(), vx1.P()); glEnd(); glPopAttrib(); } } } } locals = {this, getPixelSize()}; // The selected mesh image is already drawn by the stage // Draw additional overlays if (m_mi) { locals.drawVertexSelections(); locals.drawEdgeSelections(); locals.drawVertexHighlights(); locals.drawEdgeHighlights(); } }
30.479136
90
0.580202
wofogen
a7f58765e36f8a66ee7e1ab398b4ff4afda0fade
8,194
cpp
C++
test/coders/base64_coder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
12
2020-12-26T04:40:48.000Z
2022-02-12T17:58:33.000Z
test/coders/base64_coder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
308
2017-09-20T22:19:57.000Z
2022-02-26T00:16:11.000Z
test/coders/base64_coder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
2
2020-12-26T04:41:02.000Z
2021-06-17T18:24:03.000Z
#include "fly/coders/base64/base64_coder.hpp" #include "test/util/path_util.hpp" #include "catch2/catch_test_macros.hpp" #include <cctype> #include <filesystem> namespace { // This must match the size of fly::coders::Base64Coder::m_encoded constexpr const std::size_t s_large_string_size = 256 << 10; } // namespace CATCH_TEST_CASE("Base64", "[coders]") { fly::coders::Base64Coder coder; CATCH_SECTION("Encode and decode empty stream") { const std::string raw; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc.empty()); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream without padding") { const std::string raw = "Man"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TWFu"); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream with one padding symbol") { const std::string raw = "Ma"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TWE="); CATCH_CHECK(raw == dec); } CATCH_SECTION("Encode and decode a stream with two padding symbols") { const std::string raw = "M"; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); CATCH_CHECK(enc == "TQ=="); CATCH_CHECK(raw == dec); } CATCH_SECTION("Cannot decode streams with invalid symbols") { std::string dec; for (char ch = 0x00; ch >= 0x00; ++ch) { if ((ch == '+') || (ch == '/') || (ch == '=') || std::isalnum(ch)) { continue; } const std::string test(1, ch); const std::string fill("a"); CATCH_CHECK_FALSE(coder.decode_string(test + test + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + test + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(test + fill + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + fill + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + test + fill + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + test + test, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + test + fill, dec)); CATCH_CHECK_FALSE(coder.decode_string(fill + fill + fill + test, dec)); } // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("abc^" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Cannot decode streams with invalid chunk sizes") { std::string dec; CATCH_CHECK_FALSE(coder.decode_string("a", dec)); CATCH_CHECK_FALSE(coder.decode_string("ab", dec)); CATCH_CHECK_FALSE(coder.decode_string("abc", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcde", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcdef", dec)); CATCH_CHECK_FALSE(coder.decode_string("abcdefg", dec)); // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("abc" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Cannot decode streams with padding in invalid position") { std::string dec; CATCH_CHECK_FALSE(coder.decode_string("=abc", dec)); CATCH_CHECK_FALSE(coder.decode_string("a=bc", dec)); CATCH_CHECK_FALSE(coder.decode_string("ab=c", dec)); // Also ensure the failure is handled in a multi-chunk sized input stream. CATCH_CHECK_FALSE(coder.decode_string("ab=c" + std::string(s_large_string_size, 'a'), dec)); } CATCH_SECTION("Example from Wikipedia: https://en.wikipedia.org/wiki/Base64#Examples") { const std::string raw = "Man is distinguished, not only by his reason, but by this singular passion from other " "animals, which is a lust of the mind, that by a perseverance of delight in the " "continued and indefatigable generation of knowledge, exceeds the short vehemence of " "any carnal pleasure."; std::string enc, dec; CATCH_REQUIRE(coder.encode_string(raw, enc)); CATCH_REQUIRE(coder.decode_string(enc, dec)); const std::string expected = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bG" "FyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQg" "YnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIG" "dlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5h" "bCBwbGVhc3VyZS4="; CATCH_CHECK(enc == expected); CATCH_CHECK(raw == dec); } CATCH_SECTION("File tests") { fly::test::PathUtil::ScopedTempDirectory path; std::filesystem::path encoded_file = path.file(); std::filesystem::path decoded_file = path.file(); CATCH_SECTION("Encode and decode a large file containing only ASCII symbols") { // Generated with: // tr -dc '[:graph:]' </dev/urandom | head -c 4194304 > test.txt const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.txt"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.txt > test.txt.base64 const auto expected = here / "data" / "test.txt.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } CATCH_SECTION("Encode and decode a PNG image file") { const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.png"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.png > test.png.base64 const auto expected = here / "data" / "test.png.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } CATCH_SECTION("Encode and decode a GIF image file") { const auto here = std::filesystem::path(__FILE__).parent_path(); const auto raw = here / "data" / "test.gif"; CATCH_REQUIRE(coder.encode_file(raw, encoded_file)); CATCH_REQUIRE(coder.decode_file(encoded_file, decoded_file)); // Generated with: // base64 -w0 test.gif > test.gif.base64 const auto expected = here / "data" / "test.gif.base64"; CATCH_CHECK(fly::test::PathUtil::compare_files(encoded_file, expected)); CATCH_CHECK(fly::test::PathUtil::compare_files(raw, decoded_file)); } } }
38.650943
100
0.629729
ExternalRepositories
a7f5a1b80e20229c0c6a09679b7234563cbbed84
2,483
cc
C++
src/main/cc/wfa/virtual_people/common/field_filter/gt_filter.cc
world-federation-of-advertisers/virtual_people_common
ed17b00b7fe7a2c5646479e42dc3bb32b2f5c80f
[ "Apache-2.0" ]
4
2021-04-09T07:43:57.000Z
2021-04-27T17:21:26.000Z
src/main/cc/wfa/virtual_people/common/field_filter/gt_filter.cc
world-federation-of-advertisers/virtual_people_common
ed17b00b7fe7a2c5646479e42dc3bb32b2f5c80f
[ "Apache-2.0" ]
8
2021-03-30T23:03:35.000Z
2022-02-19T23:04:12.000Z
src/main/cc/wfa/virtual_people/common/field_filter/gt_filter.cc
world-federation-of-advertisers/virtual_people_common
ed17b00b7fe7a2c5646479e42dc3bb32b2f5c80f
[ "Apache-2.0" ]
1
2022-02-10T00:02:31.000Z
2022-02-10T00:02:31.000Z
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "wfa/virtual_people/common/field_filter/gt_filter.h" #include <memory> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common_cpp/macros/macros.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "wfa/virtual_people/common/field_filter.pb.h" #include "wfa/virtual_people/common/field_filter/field_filter.h" #include "wfa/virtual_people/common/field_filter/utils/field_util.h" #include "wfa/virtual_people/common/field_filter/utils/integer_comparator.h" namespace wfa_virtual_people { absl::StatusOr<std::unique_ptr<GtFilter>> GtFilter::New( const google::protobuf::Descriptor* descriptor, const FieldFilterProto& config) { if (config.op() != FieldFilterProto::GT) { return absl::InvalidArgumentError(absl::StrCat( "Op must be GT. Input FieldFilterProto: ", config.DebugString())); } if (!config.has_name()) { return absl::InvalidArgumentError(absl::StrCat( "Name must be set. Input FieldFilterProto: ", config.DebugString())); } if (!config.has_value()) { return absl::InvalidArgumentError(absl::StrCat( "Value must be set. Input FieldFilterProto: ", config.DebugString())); } ASSIGN_OR_RETURN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(descriptor, config.name())); ASSIGN_OR_RETURN( std::unique_ptr<IntegerComparator> comparator, IntegerComparator::New(std::move(field_descriptors), config.value())); return absl::make_unique<GtFilter>(std::move(comparator)); } bool GtFilter::IsMatch(const google::protobuf::Message& message) const { return comparator_->Compare(message) == IntegerCompareResult::GREATER_THAN; } } // namespace wfa_virtual_people
38.796875
78
0.746275
world-federation-of-advertisers
a7f5e74f62b595a3ed13b0256616a38454fd4e68
2,497
cpp
C++
STL Transformations/numword.cpp
sidrockzz/STL-C-
71a9cd36e0f86fe8e4316092497a4afb13dc00e3
[ "MIT" ]
null
null
null
STL Transformations/numword.cpp
sidrockzz/STL-C-
71a9cd36e0f86fe8e4316092497a4afb13dc00e3
[ "MIT" ]
null
null
null
STL Transformations/numword.cpp
sidrockzz/STL-C-
71a9cd36e0f86fe8e4316092497a4afb13dc00e3
[ "MIT" ]
null
null
null
#include "numword.h" using namespace bw; // destructor numword::~numword() { clearbuf(); } // assignment operator numnum numword::operator = ( const numnum num ) { setnum(num); return getnum(); } const char * numword::words() { return words(_num); } // convert to words const char * numword::words( const numnum num ) { if (num > _maxnum) { return errnum; } initbuf(); numnum n = num; if (n == 0) { appendbuf(_singles[n]); return _buf; } // powers of 1000 if (n >= 1000) { for(int i = 5; i > 0; --i) { numnum power = (numnum) pow(1000.0, i); numnum _n = ( n - ( n % power ) ) / power; if (_n) { int index = i; numword _nw(_n); appendspace(); appendbuf(_nw.words()); appendspace(); appendbuf(_powers[index]); n -= _n * power; } } } // hundreds if (n >= 100 && n < 1000) { numnum _n = ( n - ( n % 100 ) ) / 100; numword _nw(_n); appendspace(); appendbuf(_nw.words()); appendspace(); appendbuf(_hundred); n -= _n * 100; } // tens if (n >= 20 && n < 100) { numnum _n = ( n - ( n % 10 ) ) / 10; appendspace(); appendbuf(_tens[_n]); n -= _n * 10; hyphen_flag = true; } // teens if (n >= 10 && n < 20) { appendspace(); appendbuf(_teens[n - 10]); n = 0; } // singles if (n > 0 && n < 10) { appendspace(); appendbuf(_singles[n]); } return _buf; } // -- private methods -- // reset the buffer void numword::clearbuf() { if (_buf != nullptr) { free(_buf); _buf = nullptr; } _buflen = 0; } // initialize the buffer void numword::initbuf() { clearbuf(); _buf = (char *) malloc(_maxstr); *_buf = 0; hyphen_flag = false; } // append space (or hyphen) void numword::appendspace() { if (_buflen) { appendbuf( hyphen_flag ? _hyphen : _space); hyphen_flag = false; } } // append text to the string buffer void numword::appendbuf(const char * s) { if(!s) return; size_t slen = strnlen(s, _maxstr); if (slen < 1) { return; } if ((slen + _buflen + 1) >= _maxstr) { return; } memcpy(_buf + _buflen, s, slen); _buflen += slen; _buf[_buflen] = 0; }
20.983193
54
0.477773
sidrockzz
a7f63d2eddc1be3db436f5e6531bdba7685de98d
355
cpp
C++
src/ui/repo-item.cpp
movicha/wingufile-client
29485539c054d9b0567cd3b86d650aa7bf64bc5f
[ "Apache-2.0" ]
null
null
null
src/ui/repo-item.cpp
movicha/wingufile-client
29485539c054d9b0567cd3b86d650aa7bf64bc5f
[ "Apache-2.0" ]
null
null
null
src/ui/repo-item.cpp
movicha/wingufile-client
29485539c054d9b0567cd3b86d650aa7bf64bc5f
[ "Apache-2.0" ]
null
null
null
#include <QtGui> #include "rpc/local-repo.h" #include "repo-item.h" RepoItem::RepoItem(const LocalRepo& repo, QWidget *parent) : QWidget(parent), repo_(repo) { setupUi(this); refresh(); setFixedHeight(70); } void RepoItem::refresh() { mRepoName->setText(repo_.name); mRepoIcon->setPixmap(QPixmap(":/images/repo.png")); }
16.904762
58
0.656338
movicha
a7f814f7ebc4bed353133b5972952fb54527b965
886
cpp
C++
test/tests/SimpleHashTesterOneI1.cpp
asidorov95/momo
ebede4ba210ac1fa614bb2571a526e7591a92b56
[ "MIT" ]
null
null
null
test/tests/SimpleHashTesterOneI1.cpp
asidorov95/momo
ebede4ba210ac1fa614bb2571a526e7591a92b56
[ "MIT" ]
null
null
null
test/tests/SimpleHashTesterOneI1.cpp
asidorov95/momo
ebede4ba210ac1fa614bb2571a526e7591a92b56
[ "MIT" ]
null
null
null
/**********************************************************\ This file is distributed under the MIT License. See https://github.com/morzhovets/momo/blob/master/LICENSE for details. tests/SimpleHashTesterOneI1.cpp \**********************************************************/ #include "pch.h" #include "TestSettings.h" #ifdef TEST_SIMPLE_HASH #ifdef TEST_OLD_HASH_BUCKETS #undef NDEBUG #include "SimpleHashTester.h" #include "../../momo/details/HashBucketOneI1.h" static int testSimpleHash = [] { SimpleHashTester::TestStrHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); SimpleHashTester::TestTemplHashSet<momo::HashBucketOneI1, 1, 1>("momo::HashBucketOneI1"); SimpleHashTester::TestTemplHashSet<momo::HashBucketOneI1, 4, 2>("momo::HashBucketOneI1"); return 0; }(); #endif // TEST_OLD_HASH_BUCKETS #endif // TEST_SIMPLE_HASH
25.314286
91
0.630926
asidorov95
a7f965c884f9128c82b4a7ae6c6cb4f2e574a753
819
hpp
C++
fileid/document/excel/structures/formulas/PtgRange.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
13
2016-03-13T17:57:46.000Z
2021-12-21T12:11:41.000Z
fileid/document/excel/structures/formulas/PtgRange.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
9
2016-04-07T13:07:58.000Z
2020-05-30T13:31:59.000Z
fileid/document/excel/structures/formulas/PtgRange.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
5
2017-04-20T14:47:55.000Z
2021-03-08T03:27:17.000Z
#pragma once #include "../../../../common.hpp" #include "../../MSExcel.common.hpp" #include "../../IParsable.hpp" #include "Ptg.hpp" namespace oless { namespace excel { namespace structures { namespace formulas { // see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/f5ef334a-bc47-41ce-ba5d-096373423fab // ptg=0x11 // The PtgRange structure specifies the range operation, where the minimum bounding rectangle of the first expression and the second expression is generated. class PtgRange : public PtgBasic { private: public: PtgRange(unsigned char* buffer, size_t max, unsigned int offset):PtgBasic() { this->Parse(buffer, max, offset); } std::string to_string() const override { return "PtgRange"; } }; } } } }
25.59375
161
0.665446
DBHeise
a7f98fccc20b4653c7ece5a6a83abcc8f605d9b6
1,173
cpp
C++
procrender/src/GeneticAlgoScene.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
18
2017-04-26T13:53:43.000Z
2021-05-29T03:55:27.000Z
procrender/src/GeneticAlgoScene.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
null
null
null
procrender/src/GeneticAlgoScene.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
2
2017-10-17T10:32:01.000Z
2019-11-11T07:23:54.000Z
/* * GeneticAlgoScene.cpp * * Created on: Nov 2, 2015 * Author: Karl Haubenwallner */ #include "GeneticAlgoScene.h" GeneticAlgoScene::GeneticAlgoScene(const std::string& filename): seed(217197128u), genetic_algo(PGA::ProceduralAlgorithm_impl::createFromConfig(filename)), _current_generation(0) { } double GeneticAlgoScene::recombine(bool restart) { //genetic_algo->reset(); //genetic_algo->doOneGeneration(); genetic_algo->run(); _current_generation ++; return 0.0f; } double GeneticAlgoScene::generate() { auto t0 = std::chrono::high_resolution_clock::now(); genetic_algo->generateGeometry(); auto t1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0); return time_span.count(); } void GeneticAlgoScene::getVoxels(std::vector<math::float4>& centers) { genetic_algo->getVoxels(centers); } void GeneticAlgoScene::getGeometry(std::vector<PGA::GeneratedVertex>& geometry, std::vector<unsigned>& indices) { } PGA::GeometryBufferInstanced& GeneticAlgoScene::getGeometryBuffer() { return genetic_algo->getGeometryBufferInstanced(); }
20.946429
111
0.746803
crest01
a7fcbc13f768c0c5354f6726fd7981b1a478f5b7
3,691
cpp
C++
src/projects/base/sequential/test_BASE_assembly.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
1
2020-03-05T13:00:41.000Z
2020-03-05T13:00:41.000Z
src/projects/base/sequential/test_BASE_assembly.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
null
null
null
src/projects/base/sequential/test_BASE_assembly.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
1
2022-03-27T15:12:24.000Z
2022-03-27T15:12:24.000Z
/// shaft, connected to the bround by revolute joint at the point <100, 0, 0> /// initial linear speed is (0, 0, 300.); /// initial angular speed angularVelAbs = (0, 3., 0); #include <cmath> #include "chrono/physics/ChSystemNSC.h" #include "chrono/solver/ChIterativeSolverLS.h" #include "chrono/solver/ChDirectSolverLS.h" #include "chrono_irrlicht/ChIrrApp.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; ChVector<> getLinearAccelAbs(std::shared_ptr<ChBody> body) { auto& bodyFrame = body->GetFrame_REF_to_abs(); ChVector<> linearAccAbs = body->GetFrame_REF_to_abs().GetPos_dtdt(); return linearAccAbs; } int main(int argc, char* argv[]) { ChSystemNSC m_System; m_System.Set_G_acc(ChVector<>(0, 0, 0)); // Create the ground (fixed) body // ------------------------------ auto ground = chrono_types::make_shared<ChBody>(); m_System.AddBody(ground); ground->SetIdentifier(-1); ground->SetBodyFixed(true); ground->SetCollide(false); auto m_Body = chrono_types::make_shared<ChBody>(); m_System.AddBody(m_Body); m_Body->SetIdentifier(1); m_Body->SetBodyFixed(false); m_Body->SetCollide(false); m_Body->SetMass(1); m_Body->SetInertiaXX(ChVector<>(1, 1, 1)); m_Body->SetPos(ChVector<>(0, 0, 0)); m_Body->SetRot(ChQuaternion<>(1, 0, 0, 0)); auto cyl = chrono_types::make_shared<ChCylinderShape>(); cyl->GetCylinderGeometry().p1 = ChVector<>(-100, 0, 0); cyl->GetCylinderGeometry().p2 = ChVector<>(100, 0, 0); cyl->GetCylinderGeometry().rad = 2; m_Body->AddAsset(cyl); auto col = chrono_types::make_shared<ChColorAsset>(0.6f, 0.0f, 0.0f); m_Body->AddAsset(col); ChVector<> linearVelAbs(0, 0, 300.); m_Body->SetPos_dt(linearVelAbs); ChVector<> angularVelAbs(0, 3, 0); //// RADU: changed this!!! m_Body->SetWvel_par(angularVelAbs); m_Body->SetPos_dt(linearVelAbs); ChVector<> translation(100, 0, 0); ChVector<> orientationRad = CH_C_DEG_TO_RAD * 90.; ChQuaternion<> quat; quat.Q_from_AngX(orientationRad[0]); Coordsys absCoor{translation, quat}; auto markerBodyLink = std::make_shared<ChMarker>("MarkerBodyLink", m_Body.get(), ChCoordsys<>(), ChCoordsys<>(), ChCoordsys<>()); m_Body->AddMarker(markerBodyLink); markerBodyLink->Impose_Abs_Coord(absCoor); auto markerGroundLink = std::make_shared<ChMarker>("MarkerGroundLink", ground.get(), ChCoordsys<>(), ChCoordsys<>(), ChCoordsys<>()); ground->AddMarker(markerGroundLink); markerGroundLink->Impose_Abs_Coord(absCoor); auto m_Link = std::shared_ptr<chrono::ChLinkMarkers>(new ChLinkLockRevolute()); m_Link->Initialize(markerGroundLink, markerBodyLink); m_System.AddLink(m_Link); auto solver = chrono_types::make_shared<ChSolverSparseQR>(); solver->SetVerbose(false); m_System.SetSolver(solver); m_System.SetSolverForceTolerance(1e-12); m_System.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_PROJECTED); m_System.SetStep(1e-10); ChIrrApp application(&m_System, L"ChBodyAuxRef demo", core::dimension2d<u32>(800, 600), false, true); application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(0, 20, 150)); application.AssetBindAll(); application.AssetUpdateAll(); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); ////m_System.DoStepDynamics(1e-4); application.EndScene(); } m_System.DoFullAssembly(); auto linearAccelInit = getLinearAccelAbs(m_Body); }
31.016807
117
0.68518
rserban
a7fd1450863825a11a3c7bcf2dfbedd72780e8e1
2,735
cpp
C++
src/main/cpp/autonomous/AutoRightSideShootSix.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
10
2020-02-07T04:13:15.000Z
2022-02-26T00:13:39.000Z
src/main/cpp/autonomous/AutoRightSideShootSix.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
82
2020-02-12T03:05:15.000Z
2022-02-18T02:14:38.000Z
src/main/cpp/autonomous/AutoRightSideShootSix.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
5
2020-02-14T16:24:01.000Z
2022-03-31T09:10:01.000Z
// Copyright (c) 2020-2021 FRC Team 3512. All Rights Reserved. #include <frc/trajectory/constraint/MaxVelocityConstraint.h> #include <frc/trajectory/constraint/RectangularRegionConstraint.h> #include <wpi/numbers> #include "Robot.hpp" namespace frc3512 { void Robot::AutoRightSideShootSix() { // Initial Pose - Right in line with the three balls in the Trench Run const frc::Pose2d kInitialPose{12_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; // Mid Pose - Drive forward slightly const frc::Pose2d kMidPose{12_m - 1.5 * Drivetrain::kLength, 1.05_m, units::radian_t{wpi::numbers::pi}}; // End Pose - Third/Farthest ball in the Trench Run const frc::Pose2d kEndPose{7.95_m, 1.05_m, units::radian_t{wpi::numbers::pi}}; drivetrain.Reset(kInitialPose); // Move back to shoot three comfortably drivetrain.AddTrajectory(kInitialPose, {}, kMidPose); intake.Deploy(); if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } if constexpr (IsSimulation()) { for (int i = 0; i < 3; ++i) { intakeSim.AddBall(); } } Shoot(3); if (!m_autonChooser.Suspend([=] { return !IsShooting(); })) { return; } // Add a constraint to slow down the drivetrain while it's // approaching the balls frc::RectangularRegionConstraint regionConstraint{ frc::Translation2d{kEndPose.X(), kEndPose.Y() - 0.5 * Drivetrain::kLength}, // X: First/Closest ball in the trench run frc::Translation2d{9.82_m + 0.5 * Drivetrain::kLength, kInitialPose.Y() + 0.5 * Drivetrain::kLength}, frc::MaxVelocityConstraint{1.6_mps}}; { auto config = Drivetrain::MakeTrajectoryConfig(); config.AddConstraint(regionConstraint); drivetrain.AddTrajectory(kMidPose, {}, kEndPose, config); } // Intake Balls x3 intake.Start(); if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } // Drive back { auto config = Drivetrain::MakeTrajectoryConfig(); config.SetReversed(true); drivetrain.AddTrajectory({kEndPose, kMidPose}, config); } if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) { return; } if constexpr (IsSimulation()) { for (int i = 0; i < 3; ++i) { intakeSim.AddBall(); } } Shoot(3); if (!m_autonChooser.Suspend([=] { return !IsShooting(); })) { return; } intake.Stop(); EXPECT_TRUE(turret.AtGoal()); } } // namespace frc3512
28.789474
74
0.590859
frc3512
a7ff750ea073d777aa1f32b668ddda5dd46057c6
185
hpp
C++
server/api/include/rsPhyPathReg.hpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
333
2015-01-15T15:42:29.000Z
2022-03-19T19:16:15.000Z
server/api/include/rsPhyPathReg.hpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
3,551
2015-01-02T19:55:40.000Z
2022-03-31T21:24:56.000Z
server/api/include/rsPhyPathReg.hpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
148
2015-01-31T16:13:46.000Z
2022-03-23T20:23:43.000Z
#ifndef RS_PHY_PATH_REG_HPP #define RS_PHY_PATH_REG_HPP #include "rodsConnect.h" #include "dataObjInpOut.h" int rsPhyPathReg( rsComm_t *rsComm, dataObjInp_t *phyPathRegInp ); #endif
18.5
66
0.805405
JustinKyleJames
a7ffcf1d625f2bd097e16e8ac254b19a867464ef
813
cpp
C++
3rdparty/pytorch/aten/src/ATen/detail/ComplexHooksInterface.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
1
2019-07-23T11:20:58.000Z
2019-07-23T11:20:58.000Z
3rdparty/pytorch/aten/src/ATen/detail/ComplexHooksInterface.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/aten/src/ATen/detail/ComplexHooksInterface.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
#include <ATen/detail/ComplexHooksInterface.h> namespace at { namespace detail { const ComplexHooksInterface& getComplexHooks() { static std::unique_ptr<ComplexHooksInterface> complex_hooks; // NB: The once_flag here implies that if you try to call any Complex // functionality before you load the complex library, you're toast. // Same restriction as in getCUDAHooks() static std::once_flag once; std::call_once(once, [] { complex_hooks = ComplexHooksRegistry()->Create("ComplexHooks", ComplexHooksArgs{}); if (!complex_hooks) { complex_hooks = std::unique_ptr<ComplexHooksInterface>(new ComplexHooksInterface()); } }); return *complex_hooks; } } // namespace detail C10_DEFINE_REGISTRY( ComplexHooksRegistry, ComplexHooksInterface, ComplexHooksArgs) }
29.035714
87
0.734317
WoodoLee
c501489c7a798216d51283dbb79d1fb6e7d56421
524
cpp
C++
code/misc/knapsack_bounded_cost.cpp
VerasThiago/icpc-notebook
e09e4f1cb34a21ae52a246c463f2130ee83c87d6
[ "MIT" ]
13
2019-04-28T14:18:10.000Z
2021-08-19T12:13:26.000Z
code/misc/knapsack_bounded_cost.cpp
raphasramos/competitive-programming
749b6726bd9d517d9143af7e9236d3e5e8cef49b
[ "MIT" ]
null
null
null
code/misc/knapsack_bounded_cost.cpp
raphasramos/competitive-programming
749b6726bd9d517d9143af7e9236d3e5e8cef49b
[ "MIT" ]
6
2019-07-31T02:47:36.000Z
2020-10-12T01:46:23.000Z
// menor custo para conseguir peso ate M usando N tipos diferentes de elementos, sendo que o i-esimo elemento pode ser usado b[i] vezes, tem peso w[i] e custo c[i] // O(N * M) int b[N], w[N], c[N]; MinQueue Q[M] int d[M] //d[i] = custo minimo para conseguir peso i for(int i = 0; i <= M; i++) d[i] = i ? oo : 0; for(int i = 0; i < N; i++){ for(int j = 0; j < w[i]; j++) Q[j].clear(); for(int j = 0; j <= M; j++){ q = Q[j % w[i]]; if(q.size() >= q) q.pop(); q.add(c[i]); q.push(d[j]); d[j] = q.getmin(); } }
26.2
163
0.530534
VerasThiago
c501712bd7c5583ec2f2e726243a37943ddcaf3b
41,303
cpp
C++
admin/admt/workobj/usercopy.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/admt/workobj/usercopy.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/admt/workobj/usercopy.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//#pragma title("usercopy- copies user accounts") /* ================================================================================ (c) Copyright 1995-1998, Mission Critical Software, Inc., All Rights Reserved Proprietary and confidential to Mission Critical Software, Inc. Program - usercopy Class - LAN Manager Utilities Author - Tom Bernhardt Created - 05/08/91 Description- Merges the NetUser information from the specified source server with the target system (or the current system if no target is specified). Group information is also merged if the /g option is given. Existing entries on the target system are not overwritten unless the /r option is used. Syntax - USERCOPY source [target] [/u] [/l] [/g] [/r] where: source source server target destination server /g copies global group information /l copies local group information /u copies user information /r replaces existing target entries with source entries /AddTo:x Adds all newly created users (/u) to group "x" Updates - 91/06/17 TPB General code cleanup and change so that all stdout i/o lines up nicely on-screen for reporting. 93/06/12 TPB Port to Win32 96/06/21 TPB Support for local groups 97/09/20 CAB Added subset of accounts option for GUI 98/06 TPB/CAB Support for computer accounts 99/01 COM-ization of DCT. ================================================================================ */ #include "StdAfx.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <ntdsapi.h> #include <lm.h> #include <iads.h> #include "TxtSid.h" #define INCL_NETUSER #define INCL_NETGROUP #define INCL_NETERRORS #include <lm.h> #include "Common.hpp" #include "UString.hpp" #include "WorkObj.h" //#include "Usercopy.hpp" //#included by ARUtil.hpp below #include "ARUtil.hpp" #include "BkupRstr.hpp" #include "DCTStat.h" #include "ErrDct.hpp" #include "RegTrans.h" #include "TEvent.hpp" #include "LSAUtils.h" #include "GetDcName.h" #include <sddl.h> //#import "\bin\NetEnum.tlb" no_namespace //#import "\bin\DBManager.tlb" no_namespace, named_guids #import "NetEnum.tlb" no_namespace //#import "DBMgr.tlb" no_namespace, named_guids //already #imported via ARUtil.hpp #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern TErrorDct err; extern TErrorDct & errC; bool abortall; extern bool g_bAddSidWorks = false; // global counts of accounts processed AccountStats warnings = { 0,0,0,0 }; AccountStats errors = { 0,0,0,0 }; AccountStats created = { 0,0,0,0 }; AccountStats replaced = { 0,0,0,0 }; AccountStats processed = { 0,0,0,0 }; BOOL machineAcctsCreated = FALSE; BOOL otherAcctsCreated = FALSE; PSID srcSid = NULL; // SID for source domain typedef UINT (CALLBACK* DSBINDFUNC)(TCHAR*, TCHAR*, HANDLE*); typedef UINT (CALLBACK* DSADDSIDHISTORY)(HANDLE, DWORD, LPCTSTR, LPCTSTR, LPCTSTR, RPC_AUTH_IDENTITY_HANDLE,LPCTSTR,LPCTSTR); #ifndef IADsPtr _COM_SMARTPTR_TYPEDEF(IADs, IID_IADs); #endif int TNodeCompareSourceName(TNode const * t1,TNode const * t2) { TAcctReplNode const * n1 = (TAcctReplNode *)t1; TAcctReplNode const * n2 = (TAcctReplNode *)t2; return UStrICmp(n1->GetName(),n2->GetName()); } int TNodeCompareSourceNameValue(TNode const * t1, void const * v) { TAcctReplNode const * n1 = (TAcctReplNode *)t1; WCHAR const * name = (WCHAR const *)v; return UStrICmp(n1->GetName(),name); } bool BindToDS(Options* pOpt) { // Get the handle to the Directory service. DSBINDFUNC DsBind; HINSTANCE hInst = LoadLibrary(L"NTDSAPI.DLL"); if ( hInst ) { DsBind = (DSBINDFUNC) GetProcAddress(hInst, "DsBindW"); if (DsBind) { // // If source domain controllers are running W2K or later then specify // DNS name of target domain controller otherwise must specify flat // (NetBIOS) name of target domain controller. // // Note that this is a requirement of the DsAddSidHistory implementation // when the source domain is NT4 and explicit source domain credentials // are not supplied. As ADMT does not supply explicit credentials this // will always be the case when the source domain is NT4. // PWSTR strDestDC = (pOpt->srcDomainVer > 4) ? pOpt->tgtCompDns : pOpt->tgtCompFlat; DWORD rc = DsBind(strDestDC, NULL, &pOpt->dsBindHandle); if ( rc != 0 ) { err.SysMsgWrite( ErrE, rc, DCT_MSG_DSBIND_FAILED_S, strDestDC); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_GET_PROC_ADDRESS_FAILED_SSD,L"NTDSAPI.DLL",L"DsBindW",GetLastError()); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { err.SysMsgWrite(ErrW,GetLastError(),DCT_MSG_LOAD_LIBRARY_FAILED_SD,L"NTDSAPI.DLL",GetLastError()); Mark(L"warnings", L"generic"); return false; } FreeLibrary(hInst); return true; } // The following function is used to get the actual account name from the source domain // instead of account that contains the SID in its SID history. DWORD GetName(PSID pObjectSID, WCHAR * sNameAccount, WCHAR * sDomain) { DWORD cb = 255; DWORD cbDomain = 255; DWORD tempVal; PDWORD psubAuth; PUCHAR pVal; SID_NAME_USE sid_Use; _bstr_t sDC; DWORD rc = 0; if ((pObjectSID == NULL) || !IsValidSid(pObjectSID)) { return ERROR_INVALID_PARAMETER; } // Copy the Sid to a temp SID DWORD sidLen = GetLengthSid(pObjectSID); PSID pObjectSID1 = new BYTE[sidLen]; if (!pObjectSID1) return ERROR_NOT_ENOUGH_MEMORY; if (!CopySid(sidLen, pObjectSID1, pObjectSID)) { delete pObjectSID1; return GetLastError(); } if (!IsValidSid(pObjectSID1)) { rc = GetLastError(); err.SysMsgWrite(ErrE, rc,DCT_MSG_DOMAIN_LOOKUP_FAILED_D,rc); try { Mark(L"errors", L"generic"); } catch (...) { } delete pObjectSID1; return rc; } // Get the RID out of the SID and get the domain SID pVal = GetSidSubAuthorityCount(pObjectSID1); (*pVal)--; psubAuth = GetSidSubAuthority(pObjectSID1, *pVal); tempVal = *psubAuth; *psubAuth = -1; //Lookup the domain from the SID if (!LookupAccountSid(NULL, pObjectSID1, sNameAccount, &cb, sDomain, &cbDomain, &sid_Use)) { rc = GetLastError(); err.SysMsgWrite(ErrE, rc,DCT_MSG_DOMAIN_LOOKUP_FAILED_D,rc); Mark(L"errors", L"generic"); delete pObjectSID1; return rc; } // Get a DC for the domain rc = GetAnyDcName4(sDomain, sDC); if ( rc ) { err.SysMsgWrite(ErrE,rc,DCT_MSG_GET_DCNAME_FAILED_SD,sDomain,rc); Mark(L"errors", L"generic"); delete pObjectSID1; return rc; } // Reset the sizes cb = 255; cbDomain = 255; // Lookup the account on the PDC that we found above. if ( LookupAccountSid(sDC, pObjectSID, sNameAccount, &cb, sDomain, &cbDomain, &sid_Use) == 0) { delete pObjectSID1; return GetLastError(); } delete pObjectSID1; return 0; } /* This is a list of specific error codes that can be returned by DsAddSidHistory. This was obtained from Microsoft via email > ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED > The operation requires that destination domain auditing be enabled for > Success and Failure auditing of account management operations. > > ERROR_DS_UNWILLING_TO_PERFORM > It may be that the user account is not one of UF_NORMAL_ACCOUNT, > UF_WORKSTATION_TRUST_ACCOUNT, or UF_SERVER_TRUST_ACCOUNT. > > It may be that the source principal is a built in account. > > It may be that the source principal is a well known RID being added > to a destination principal that is a different RID. In other words, > Administrators of the source domain can only be assigned to > Administrators of the destination domain. > > ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER > The source object must be a group or user. > > ERROR_DS_SRC_SID_EXISTS_IN_FOREST > The source object's SID already exists in destination forest. > > ERROR_DS_INTERNAL_FAILURE; > The directory service encountered an internal failure. Shouldn't > happen. > > ERROR_DS_MUST_BE_RUN_ON_DST_DC > For security reasons, the operation must be run on the destination DC. > Specifically, the connection between the client and server > (destination > DC) requires 128-bit encryption when credentials for the source domain > are supplied. > > ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION > The connection between client and server requires packet privacy or > better. > > ERROR_DS_SOURCE_DOMAIN_IN_FOREST > The source domain may not be in the same forest as destination. > > ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST > The destination domain must be in the forest. > > ERROR_DS_MASTERDSA_REQUIRED > The operation must be performed at a master DSA (writable DC). > > ERROR_DS_INSUFF_ACCESS_RIGHTS > Insufficient access rights to perform the operation. Most likely > the caller is not a member of domain admins for the dst domain. > > ERROR_DS_DST_DOMAIN_NOT_NATIVE > Destination domain must be in native mode. > > ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN > The operation couldn't locate a DC for the source domain. > > ERROR_DS_OBJ_NOT_FOUND > Directory object not found. Most likely the FQDN of the > destination principal could not be found in the destination > domain. > > ERROR_DS_NAME_ERROR_NOT_UNIQUE > Name translation: Input name mapped to more than one > output name. Most likely the destination principal mapped > to more than one FQDN in the destination domain. > > ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH > The source and destination object must be of the same type. > > ERROR_DS_OBJ_CLASS_VIOLATION > The requested operation did not satisfy one or more constraints > associated with the class of the object. Most likely because the > destination principal is not a user or group. > > ERROR_DS_UNAVAILABLE > The directory service is unavailable. Most likely the > ldap_initW() to the NT5 src DC failed. > > ERROR_DS_INAPPROPRIATE_AUTH > Inappropriate authentication. Most likely the ldap_bind_sW() to > the NT5 src dc failed. > > ERROR_DS_SOURCE_AUDITING_NOT_ENABLED > The operation requires that source domain auditing be enabled for > Success and Failure auditing of account management operations. > > ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER > For security reasons, the source DC must be Service Pack 4 or greater. > */ HRESULT CopySidHistoryProperty( Options * pOptions, TAcctReplNode * pNode, IStatusObj * pStatus ) { HRESULT hr = S_OK; IADs * pAds = NULL; _variant_t var; // long ub = 0, lb = 0; // fetch the SIDHistory property for the source account // for each entry in the source's SIDHistory, call DsAddSidHistory // Get the IADs pointer to the object and get the SIDHistory attribute. hr = ADsGetObject(const_cast<WCHAR*>(pNode->GetSourcePath()), IID_IADs, (void**)&pAds); if ( SUCCEEDED(hr) ) { hr = pAds->Get(L"sIDHistory", &var); } if ( SUCCEEDED(hr) ) { // This is a multivalued property so we need to get all the values // for each one get the name and the domain of the object and then call the // add sid history function to add the SID to the target objects SIDHistory. _variant_t var; DWORD rc = pAds->GetEx(L"sIDHistory", &var); if ( !rc ) { if ( V_VT(&var) == (VT_ARRAY | VT_VARIANT) ) { // This is the array type that we were looking for. void HUGEP *pArray; VARIANT var2; ULONG dwSLBound = -1; ULONG dwSUBound = -1; hr = SafeArrayGetLBound( V_ARRAY(&var), 1, (long FAR *) &dwSLBound ); hr = SafeArrayGetUBound( V_ARRAY(&var), 1, (long FAR *) &dwSUBound ); if (SUCCEEDED(hr)) { // Each element in this array is a SID in form of a VARIANT hr = SafeArrayAccessData( V_ARRAY(&var), &pArray ); for ( long x = (long)dwSLBound; x <= (long)dwSUBound; x++) { hr = SafeArrayGetElement(V_ARRAY(&var), &x, &var2); // Get the SID from the Variant in a ARRAY form hr = SafeArrayAccessData( V_ARRAY(&var2), &pArray ); PSID pObjectSID = (PSID)pArray; //Convert SID to string. if (pObjectSID) { WCHAR sNameAccount[255]; WCHAR sDomain[255]; WCHAR sNetBIOS[255]; DWORD rc = 0; rc = GetName(pObjectSID, sNameAccount, sDomain); if (!rc) { WCHAR sTemp[LEN_Path]; WCHAR sSourceDNS[LEN_Path]; // We are going to temporarily change the Domain DNS to the domain of the SID we are adding wcscpy(sTemp, pOptions->srcDomainDns); if ( GetDnsAndNetbiosFromName(sDomain, sNetBIOS, sSourceDNS) ) { wcscpy(pOptions->srcDomainDns, sSourceDNS); AddSidHistory(pOptions, sNameAccount, pNode->GetTargetSam(), NULL, FALSE); // Replace the original domain dns. wcscpy(pOptions->srcDomainDns, sTemp); } else { err.SysMsgWrite(ErrE, GetLastError(),DCT_MSG_DOMAIN_DNS_LOOKUP_FAILED_SD, sDomain,GetLastError()); Mark(L"errors", pNode->GetType()); } } else { // Get name failed we need to log a message. WCHAR sSid[LEN_Path]; DWORD len = LEN_Path; GetTextualSid(pObjectSID, sSid, &len); err.SysMsgWrite(ErrE,rc,DCT_MSG_ERROR_CONVERTING_SID_SSD, pNode->GetTargetName(), sSid, rc); Mark(L"errors", pNode->GetType()); } } SafeArrayUnaccessData(V_ARRAY(&var2)); } SafeArrayUnaccessData(V_ARRAY(&var)); } } } else { // No SID History to copy. } } return hr; } bool AddSidHistory( const Options * pOptions, const WCHAR * strSrcPrincipal, const WCHAR * strDestPrincipal, IStatusObj * pStatus, BOOL isFatal) { //Add the sid to the history // Authentication Structure SEC_WINNT_AUTH_IDENTITY auth; DWORD rc = 0; WCHAR szPassword[LEN_Password]; auth.Domain = const_cast<WCHAR*>(pOptions->authDomain); auth.DomainLength = wcslen(pOptions->authDomain); auth.User = const_cast<WCHAR*>(pOptions->authUser); auth.UserLength = wcslen(pOptions->authUser); // // If credentials were supplied then retrieve password. // if ((auth.DomainLength > 0) && (auth.UserLength > 0)) { DWORD dwError = RetrievePassword(pOptions->authPassword, szPassword, sizeof(szPassword) / sizeof(szPassword[0])); if (dwError == ERROR_SUCCESS) { auth.Password = szPassword; auth.PasswordLength = wcslen(szPassword); } else { err.SysMsgWrite(ErrE, dwError, DCT_MSG_UNABLE_TO_RETRIEVE_PASSWORD); g_bAddSidWorks = FALSE; // log a message indicating that SIDHistory will not be tried for the rest of the accounts err.MsgWrite(ErrW,DCT_MSG_SIDHISTORY_FATAL_ERROR); Mark(L"warnings", L"generic"); // we are going to set the status to abort so that we don't try to migrate anymore. if ( pStatus ) { pStatus->put_Status(DCT_STATUS_ABORTING); } return false; } } else { auth.Password = NULL; auth.PasswordLength = 0; } auth.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; // Auth Identity handle // if source domain credentials supplied use them // otherwise credentials of caller will be used RPC_AUTH_IDENTITY_HANDLE pHandle = ((auth.DomainLength > 0) && (auth.UserLength > 0)) ? &auth : NULL; DSADDSIDHISTORY DsAddSidHistory; HINSTANCE hInst = LoadLibrary(L"NTDSAPI.DLL"); if ( hInst ) { DsAddSidHistory = (DSADDSIDHISTORY) GetProcAddress(hInst, "DsAddSidHistoryW"); if (DsAddSidHistory) { if ( !pOptions->nochange ) { int loopCount = 0; rc = RPC_S_SERVER_UNAVAILABLE; // If we get the RPC server errors we need to retry 5 times. while ( (((rc == RPC_S_SERVER_UNAVAILABLE) || (rc == RPC_S_CALL_FAILED) || (rc == RPC_S_CALL_FAILED_DNE)) && loopCount < 5) || ( (rc == ERROR_INVALID_HANDLE) && loopCount < 3 ) ) // In case of invalid handle we try it 3 times now. { // Make the API call to add Sid to the history rc = DsAddSidHistory( pOptions->dsBindHandle, //DS Handle NULL, // flags pOptions->srcDomain, // Source domain strSrcPrincipal, // Source Account name NULL, // Source Domain Controller pHandle, // RPC_AUTH_IDENTITY_HANDLE pOptions->tgtDomainDns, // Target domain strDestPrincipal); // Target Account name if ( loopCount > 0 ) Sleep(500); loopCount++; } } SecureZeroMemory(szPassword, sizeof(szPassword)); if ( rc != 0 ) { switch ( rc ) { // these are the error codes caused by permissions or configuration problems case ERROR_NONE_MAPPED: err.MsgWrite(ErrE, DCT_MSG_ADDSIDHISTORY_FAIL_BUILTIN_SSD,strSrcPrincipal, strDestPrincipal, rc); break; case ERROR_DS_UNWILLING_TO_PERFORM: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DS_UNWILLING_TO_PERFORM_SSSSD,strDestPrincipal,pOptions->srcDomain, strSrcPrincipal, pOptions->tgtDomain,rc); break; case ERROR_DS_INSUFF_ACCESS_RIGHTS: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF_ACCESS_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_INVALID_HANDLE: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INVALID_HANDLE_SSD,pOptions->srcDomainDns,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOAUDIT_SSD,strDestPrincipal,pOptions->tgtDomainDns,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_MUST_BE_RUN_ON_DST_DC: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DST_DC_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_PKT_PRIVACY_SD,strDestPrincipal,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_SOURCE_DOMAIN_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_SOURCE_IN_FOREST_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DEST_WRONG_FOREST_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_DS_MASTERDSA_REQUIRED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NO_MASTERDSA_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_ACCESS_DENIED: g_bAddSidWorks = FALSE; if (pHandle) { err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF2_SSS,strDestPrincipal,pOptions->authDomain,pOptions->authUser); } else { err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_INSUFF2_S,strDestPrincipal); } break; case ERROR_DS_DST_DOMAIN_NOT_NATIVE: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOT_NATIVE_S,strDestPrincipal); break; case ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NO_SOURCE_DC_S,strDestPrincipal); break; // case ERROR_DS_INAPPROPRIATE_AUTH: case ERROR_DS_UNAVAILABLE: g_bAddSidWorks = FALSE; err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_DS_UNAVAILABLE_S,strDestPrincipal); break; case ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_NOAUDIT_SSD,strDestPrincipal,pOptions->srcDomain,rc); g_bAddSidWorks = FALSE; break; case ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_SOURCE_NOT_SP4_S,strDestPrincipal); g_bAddSidWorks = FALSE; break; case ERROR_SESSION_CREDENTIAL_CONFLICT: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_CREDENTIALS_CONFLICT_SSSS,strDestPrincipal,pOptions->srcDomain,pOptions->authDomain,pOptions->authUser); g_bAddSidWorks = FALSE; break; // these are error codes that only affect this particular account case ERROR_SUCCESS: g_bAddSidWorks = TRUE; // no error message needed for success case! break; case ERROR_DS_SRC_SID_EXISTS_IN_FOREST: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_IN_FOREST_SD,strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; case ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: err.MsgWrite(ErrE,DCT_MSG_SID_HISTORY_WRONGTYPE_SD,strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; case ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: err.MsgWrite(ErrE, DCT_MSG_SID_HISTORY_CLASS_MISMATCH_SSD, strDestPrincipal, strSrcPrincipal, rc); g_bAddSidWorks = TRUE; break; default: err.MsgWrite(ErrE,DCT_MSG_ADDSID_FAILED_SSD,strSrcPrincipal, strDestPrincipal,rc); g_bAddSidWorks = TRUE; break; } Mark(L"errors", L"generic"); // This may or may not be a fatal error depending on weather we are Adding // sid history or copying sid history g_bAddSidWorks |= !(isFatal); if (! g_bAddSidWorks ) { // log a message indicating that SIDHistory will not be tried for the rest of the accounts err.MsgWrite(ErrW,DCT_MSG_SIDHISTORY_FATAL_ERROR); Mark(L"warnings", L"generic"); // we are going to set the status to abort so that we don't try to migrate anymore. if ( pStatus ) { pStatus->put_Status(DCT_STATUS_ABORTING); } } FreeLibrary(hInst); return false; } else { err.MsgWrite(0, DCT_MSG_ADD_SID_SUCCESS_SSSS, pOptions->srcDomainFlat, strSrcPrincipal, pOptions->tgtDomainFlat, strDestPrincipal); FreeLibrary(hInst); return true; } } else { SecureZeroMemory(szPassword, sizeof(szPassword)); err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_NO_ADDSIDHISTORY_FUNCTION); Mark(L"errors", L"generic"); FreeLibrary(hInst); return false; } } else { SecureZeroMemory(szPassword, sizeof(szPassword)); err.SysMsgWrite(ErrE,GetLastError(),DCT_MSG_NO_NTDSAPI_DLL); Mark(L"errors", L"generic"); return false; } } //-------------------------------------------------------------------------- // FillupNamingContext : This function fills in the target Naming context // for NT5 domain. //-------------------------------------------------------------------------- void FillupNamingContext( Options * options //in,out- Options to fill up ) { WCHAR sPath[LEN_Path]; IADs * pAds; _variant_t var; HRESULT hr; wsprintf(sPath, L"LDAP://%s/rootDSE", options->tgtDomain); hr = ADsGetObject(sPath, IID_IADs, (void**)&pAds); if ( FAILED(hr) ) { wcscpy(options->tgtNamingContext, L""); return; } hr = pAds->Get(L"defaultNamingContext", &var); if ( FAILED(hr) ) { wcscpy(options->tgtNamingContext, L""); return; } pAds->Release(); wcscpy(options->tgtNamingContext, (WCHAR*) V_BSTR(&var)); } //-------------------------------------------------------------------------- // MakeFullyQualifiedAdsPath : Makes a LDAP sub path into a fully qualified // LDAP path name. //-------------------------------------------------------------------------- void MakeFullyQualifiedAdsPath( WCHAR * sPath, //out- Fully qulified LDAP path to the object DWORD nPathLen, //in - MAX size, in characters, of the sPath buffer WCHAR * sSubPath, //in- LDAP subpath of the object WCHAR * tgtDomain, //in- Domain name where object exists. WCHAR * sDN //in- Default naming context for the Domain ) { if ((!sPath) || (!sSubPath) || (!tgtDomain) || (!sDN)) return; _bstr_t sTempPath; if (wcsncmp(sSubPath, L"LDAP://", 7) == 0) { //it is already a fully qualified LDAP path so lets copy it and return it wcsncpy(sPath, sSubPath, nPathLen-1); sPath[nPathLen - 1] = L'\0'; return; } //We need to build this path so lets get to work if ( wcslen(sDN) ) { sTempPath = L"LDAP://"; sTempPath += tgtDomain; sTempPath += L"/"; sTempPath += sSubPath; sTempPath += L","; sTempPath += sDN; } else { sTempPath = L"LDAP://"; sTempPath += tgtDomain; sTempPath += L"/"; sTempPath += sSubPath; } if (sTempPath.length() > 0) { wcsncpy(sPath, sTempPath, nPathLen - 1); sPath[nPathLen - 1] = L'\0'; } else { *sPath = L'\0'; } } //-------------------------------------------------------------------------- // IsAccountMigrated : Function checks if the account has been migrated in // the past. If it has it returns true filling in the // name of the target object in case it was renamed. // Otherwise it returns FALSE and Empty string for the // target name. //-------------------------------------------------------------------------- bool IsAccountMigrated( TAcctReplNode * pNode, //in -Account node that contains the Account info Options * pOptions, //in -Options as specified by the user. IIManageDBPtr pDb, //in -Pointer to DB manager. We dont want to create this object for every account we process WCHAR * sTgtSam //in,out - Name of the target object that was copied if any. ) { IVarSetPtr pVs(__uuidof(VarSet)); IUnknown * pUnk; pVs->QueryInterface(IID_IUnknown, (void**) &pUnk); HRESULT hrFind = pDb->raw_GetAMigratedObject(const_cast<WCHAR*>(pNode->GetSourceSam()), pOptions->srcDomain, pOptions->tgtDomain, &pUnk); pUnk->Release(); if ( hrFind != S_OK ) { wcscpy(sTgtSam,L""); return false; } else { _bstr_t sText; sText = pVs->get(L"MigratedObjects.TargetSamName"); if (!(WCHAR*)sText) { wcscpy(sTgtSam,L""); return false; } wcscpy(sTgtSam, (WCHAR*) sText); return true; } } bool CheckifAccountExists( Options const * options, //in-Options as set by the user WCHAR * acctName //in-Name of the account to look for ) { USER_INFO_0 * buf; long rc = 0; if ( (rc = NetUserGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } if ( (rc = NetGroupGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } if ( (rc = NetLocalGroupGetInfo(const_cast<WCHAR*>(options->tgtComp), acctName, 0, (LPBYTE *) &buf)) == NERR_Success ) { NetApiBufferFree(buf); return true; } return false; } //-------------------------------------------------------------------------- // Mark : Increments appropriate counters depending on the arguments. //-------------------------------------------------------------------------- void Mark( _bstr_t sMark, //in- Represents the type of marking { processed, errors, replaced, created } _bstr_t sObj //in- Type of object being marked { user, group, computer } ) { if (!UStrICmp(sMark,L"processed")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) processed.users++; else if ( !UStrICmp(sObj,L"group")) processed.globals++; else if ( !UStrICmp(sObj,L"computer")) processed.computers++; else if ( !UStrICmp(sObj,L"generic")) processed.generic++; } else if (!UStrICmp(sMark,L"errors")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) errors.users++; else if ( !UStrICmp(sObj,L"group")) errors.globals++; else if ( !UStrICmp(sObj,L"computer")) errors.computers++; else if ( !UStrICmp(sObj,L"generic")) errors.generic++; } else if (!UStrICmp(sMark,L"warnings")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) warnings.users++; else if ( !UStrICmp(sObj,L"group")) warnings.globals++; else if ( !UStrICmp(sObj,L"computer")) warnings.computers++; else if ( !UStrICmp(sObj,L"generic")) warnings.generic++; } else if (!UStrICmp(sMark,L"replaced")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) replaced.users++; else if ( !UStrICmp(sObj,L"group")) replaced.globals++; else if ( !UStrICmp(sObj,L"computer")) replaced.computers++; else if ( !UStrICmp(sObj,L"generic")) replaced.generic++; } else if (!UStrICmp(sMark,L"created")) { if ( !UStrICmp(sObj,L"user") || !UStrICmp(sObj,L"inetOrgPerson") ) created.users++; else if ( !UStrICmp(sObj,L"group")) created.globals++; else if ( !UStrICmp(sObj,L"computer")) created.computers++; else if ( !UStrICmp(sObj,L"generic")) created.generic++; } } // // This function batch-marks one category of AccountStats based on an EAMAccountStatItem struct. // statItem: the EAMAccountStatItem struct // aStat: the AccountStats struct; should be one of errors, warnings, replaced, created, processed // static void BatchMarkCategory(const EAMAccountStatItem& statItem, AccountStats& aStat) { aStat.locals += statItem.locals; aStat.users += statItem.users; aStat.globals += statItem.globals; aStat.computers += statItem.computers; aStat.generic += statItem.generic; } // // This function batch-marks all categories of AccountStats based on an EAMAccountStats struct. // stats: the EAMAccountStats struct // void BatchMark(const EAMAccountStats& stats) { BatchMarkCategory(stats.errors, errors); BatchMarkCategory(stats.warnings, warnings); BatchMarkCategory(stats.replaced, replaced); BatchMarkCategory(stats.created, created); BatchMarkCategory(stats.processed, processed); } HRESULT __stdcall GetRidPoolAllocator(Options* pOptions) { WCHAR szADsPath[LEN_Path]; // // Bind to source Domain object and retrieve distinguished name of RID Manager object. // IADsPtr spDomain; _bstr_t strRIDManagerReference; szADsPath[countof(szADsPath) - 1] = L'\0'; int cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, pOptions->srcNamingContext ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; HRESULT hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spDomain); if (FAILED(hr)) { return hr; } VARIANT varRIDManagerReference; VariantInit(&varRIDManagerReference); hr = spDomain->Get(L"rIDManagerReference", &varRIDManagerReference); if (FAILED(hr)) { return hr; } strRIDManagerReference = _variant_t(varRIDManagerReference, false); // // Bind to RID Manager object and retrieve distinguished name of the FSMO Role Owner. // IADsPtr spRIDManager; _bstr_t strFSMORoleOwner; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strRIDManagerReference ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spRIDManager); if (FAILED(hr)) { return hr; } VARIANT varFSMORoleOwner; VariantInit(&varFSMORoleOwner); hr = spRIDManager->Get(L"fSMORoleOwner", &varFSMORoleOwner); if (FAILED(hr)) { return hr; } strFSMORoleOwner = _variant_t(varFSMORoleOwner, false); // // Bind to NTDS-DSA object and retrieve ADsPath of parent Server object. // IADsPtr spNTDSDSA; _bstr_t strServer; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strFSMORoleOwner ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spNTDSDSA); if (FAILED(hr)) { return hr; } BSTR bstrServer; hr = spNTDSDSA->get_Parent(&bstrServer); if (FAILED(hr)) { return hr; } strServer = _bstr_t(bstrServer, false); // // Bind to Server object and retrieve distinguished name of Computer object. // IADsPtr spServer; _bstr_t strServerReference; hr = ADsGetObject(strServer, IID_IADs, (VOID**)&spServer); if (FAILED(hr)) { return hr; } VARIANT varServerReference; VariantInit(&varServerReference); hr = spServer->Get(L"serverReference", &varServerReference); if (FAILED(hr)) { return hr; } strServerReference = _variant_t(varServerReference, false); // // Bind to Computer object and retrieve DNS host name and SAM account name. // IADsPtr spComputer; _bstr_t strDNSHostName; _bstr_t strSAMAccountName; szADsPath[countof(szADsPath) - 1] = L'\0'; cch = _snwprintf( szADsPath, countof(szADsPath), L"LDAP://%s/%s", pOptions->srcComp + 2, (PCWSTR)strServerReference ); if ((cch < 0) || (szADsPath[countof(szADsPath) - 1] != L'\0')) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } szADsPath[countof(szADsPath) - 1] = L'\0'; hr = ADsGetObject(szADsPath, IID_IADs, (VOID**)&spComputer); if (FAILED(hr)) { return hr; } VARIANT varDNSHostName; VariantInit(&varDNSHostName); hr = spComputer->Get(L"dNSHostName", &varDNSHostName); if (FAILED(hr)) { return hr; } strDNSHostName = _variant_t(varDNSHostName, false); VARIANT varSAMAccountName; VariantInit(&varSAMAccountName); hr = spComputer->Get(L"SAMAccountName", &varSAMAccountName); if (FAILED(hr)) { return hr; } strSAMAccountName = _variant_t(varSAMAccountName, false); if ((strDNSHostName.length() == 0) || (strSAMAccountName.length() == 0)) { return E_OUTOFMEMORY; } // // Update source domain controller names. // if ((2 + strDNSHostName.length() >= countof(pOptions->srcComp)) || (2 + strDNSHostName.length() >= countof(pOptions->srcCompDns)) || (2 + strSAMAccountName.length() >= countof(pOptions->srcCompFlat))) { return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } wcscpy(pOptions->srcComp, L"\\\\"); wcscat(pOptions->srcComp, strDNSHostName); wcscpy(pOptions->srcCompDns, pOptions->srcComp); wcscpy(pOptions->srcCompFlat, L"\\\\"); wcscat(pOptions->srcCompFlat, strSAMAccountName); // Remove trailing $ character. pOptions->srcCompFlat[wcslen(pOptions->srcCompFlat) - 1] = L'\0'; return S_OK; }
34.913779
168
0.559451
npocmaka
c502952e8ad6370cd472f841ccb12d33af00855b
2,093
cpp
C++
exec/brownian/advance.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
exec/brownian/advance.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
exec/brownian/advance.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "hydro_functions.H" #include "hydro_functions_F.H" #include "common_functions.H" #include "common_functions_F.H" #include "common_namespace.H" #include "gmres_functions.H" #include "gmres_functions_F.H" #include "gmres_namespace.H" #include <AMReX_ParallelDescriptor.H> #include <AMReX_MultiFabUtil.H> using namespace amrex; using namespace common; using namespace gmres; // argv contains the name of the inputs file entered at the command line void advance( std::array< MultiFab, AMREX_SPACEDIM >& umac, MultiFab& pres, const std::array< MultiFab, AMREX_SPACEDIM >& stochMfluxdiv, const std::array< MultiFab, AMREX_SPACEDIM >& sourceTerms, std::array< MultiFab, AMREX_SPACEDIM >& alpha_fc, MultiFab& beta, MultiFab& gamma, std::array< MultiFab, NUM_EDGE >& beta_ed, const Geometry geom, const Real& dt) { BL_PROFILE_VAR("advance()",advance); Real theta_alpha = 0.; Real norm_pre_rhs; const BoxArray& ba = beta.boxArray(); const DistributionMapping& dmap = beta.DistributionMap(); // rhs_p GMRES solve MultiFab gmres_rhs_p(ba, dmap, 1, 0); gmres_rhs_p.setVal(0.); // rhs_u GMRES solve std::array< MultiFab, AMREX_SPACEDIM > gmres_rhs_u; for (int d=0; d<AMREX_SPACEDIM; ++d) { gmres_rhs_u[d].define(convert(ba,nodal_flag_dir[d]), dmap, 1, 0); gmres_rhs_u[d].setVal(0.); } ////////////////////////////////////////////////// // ADVANCE velocity field ////////////////////////////////////////////////// // add stochastic forcing to gmres_rhs_u for (int d=0; d<AMREX_SPACEDIM; ++d) { MultiFab::Add(gmres_rhs_u[d], stochMfluxdiv[d], 0, 0, 1, 0); MultiFab::Add(gmres_rhs_u[d], sourceTerms[d], 0, 0, 1, 0); } // HERE is where you would add the particle forcing to gmres_rhs_u // // // // call GMRES GMRES(gmres_rhs_u,gmres_rhs_p,umac,pres,alpha_fc,beta,beta_ed,gamma,theta_alpha,geom,norm_pre_rhs); // fill periodic ghost cells for (int d=0; d<AMREX_SPACEDIM; ++d) { umac[d].FillBoundary(geom.periodicity()); } }
27.539474
101
0.651218
ckim103
c5045369a7cc0f610029dabf89d0154c75b1da93
3,782
cpp
C++
Phase 3/main.cpp
HxnDev/Parallel-15-Puzzle-Solver-Using-Multi-Threading
d03d4f03988e22db4038912a402271439c5ed4d8
[ "MIT" ]
4
2021-07-06T04:35:39.000Z
2021-07-27T08:52:37.000Z
Phase 3/main.cpp
HxnDev/Parallel-15-Puzzle-Solver-Using-Multi-Threading
d03d4f03988e22db4038912a402271439c5ed4d8
[ "MIT" ]
null
null
null
Phase 3/main.cpp
HxnDev/Parallel-15-Puzzle-Solver-Using-Multi-Threading
d03d4f03988e22db4038912a402271439c5ed4d8
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------------------------------------------------- // Hassan Shahzad // 18i-0441 // OS-Project // FAST NUCES // main.cpp //-------------------------------------------------------------------------------------------------------------------------------- //================================================================================================================================ // 1: This file needs to be run inorder to ecexute the whole program successfully. //================================================================================================================================ #include <iostream> #include <vector> #include <unordered_set> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <chrono> using namespace std::chrono; using namespace std; #include "board.cpp" State* start; State* goal; vector<State*> path; int numThreads = 0; int queuesPerThread = -1 ; #include "queues.cpp" #include "multithreading.cpp" int main(int argc, char *argv[]) { int size = 4; int moves = -1; int choice; string inputFile; cout<<"Do you want to test from file ?\n1: Yes\n2: No\nYour Choice = "; cin>>choice; if (choice == 1) { cout<<"Enter the name of the file = "; cin>>inputFile; } else { inputFile = ""; } cout<<"Enter the number of queues you want per thread = "; cin>> queuesPerThread; if (argc > 1) //Number of arguments must be greater than 1 numThreads = atoi(argv[1]); if (argc <=1 ) cout<<"Invalid number of threads"<<endl; cout << "Number of threads = " << numThreads << endl; cout << "Size = " << size << endl; cout << "Moves = " << moves << endl; if (inputFile.empty()) //If choice 2 is selected { if (moves >= 0) { start = (State*)(new Board(size, moves)); } else { start = (State*)(new Board(size)); } } else { start = (State*)(new Board(inputFile)); } cout << "Start board:" << endl; //Displaying the initial board cout << start->toString() << endl; if (numThreads != 0) { cout << "Running parallel version with " << numThreads << " threads..." << endl; //Displaying number of threads } if (queuesPerThread != -1) { int totalQueues = queuesPerThread * numThreads; //Storing the total number of queues cout << "Using " << totalQueues << " number of queues..." << endl; cout<<"Each thread will have "<<queuesPerThread << " queues to work with ...."<<endl; } goal = (State*)(new Board(size, 0)); auto start = high_resolution_clock::now(); //Calculating execution time if (numThreads == 0) { cout<<"Invalid number of threads entered.\nThe program will now exit........"<<endl; exit(0); } else { parallel(numThreads); } auto stop = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>(stop - start); cout << "Optimal solution found!" << endl << endl; int length = path.size(); for (int i = 0; i < length; i++) //Dispalying steps { cout << "Step " << i << ":" << endl; cout << path[i]->toString() << endl; } cout << "Length of path: " << length-1 << endl; //Displaying total number of steps cout << "Total time: " << duration.count() << " ms" << endl; //Displaying execution time return 0; }
28.43609
130
0.459545
HxnDev