hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses 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 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92ece188879a4cb37fad47d6afdc92ee51859ebb | 4,009 | cpp | C++ | Code/System/Animation/AnimationSkeleton.cpp | JuanluMorales/KRG | f3a11de469586a4ef0db835af4bc4589e6b70779 | [
"MIT"
] | 419 | 2022-01-27T19:37:43.000Z | 2022-03-31T06:14:22.000Z | Code/System/Animation/AnimationSkeleton.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-01-28T20:35:33.000Z | 2022-03-13T17:42:52.000Z | Code/System/Animation/AnimationSkeleton.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 20 | 2022-01-27T20:41:02.000Z | 2022-03-26T16:16:57.000Z | #include "AnimationSkeleton.h"
#include "System/Core/Drawing/DebugDrawing.h"
//-------------------------------------------------------------------------
namespace KRG::Animation
{
bool Skeleton::IsValid() const
{
return !m_boneIDs.empty() && ( m_boneIDs.size() == m_parentIndices.size() ) && ( m_boneIDs.size() == m_localReferencePose.size() );
}
Transform Skeleton::GetBoneGlobalTransform( int32 idx ) const
{
KRG_ASSERT( idx >= 0 && idx < m_localReferencePose.size() );
Transform boneGlobalTransform = m_localReferencePose[idx];
int32 parentIdx = GetParentBoneIndex( idx );
while ( parentIdx != InvalidIndex )
{
boneGlobalTransform = boneGlobalTransform * m_localReferencePose[parentIdx];
parentIdx = GetParentBoneIndex( parentIdx );
}
return boneGlobalTransform;
}
int32 Skeleton::GetFirstChildBoneIndex( int32 boneIdx ) const
{
int32 const numBones = GetNumBones();
KRG_ASSERT( IsValidBoneIndex( boneIdx ) );
int32 childIdx = InvalidIndex;
for ( auto i = boneIdx + 1; i < numBones; i++ )
{
if ( m_parentIndices[i] == boneIdx )
{
childIdx = i;
break;
}
}
return childIdx;
}
bool Skeleton::IsChildBoneOf( int32 parentBoneIdx, int32 childBoneIdx ) const
{
KRG_ASSERT( IsValidBoneIndex( parentBoneIdx ) );
KRG_ASSERT( IsValidBoneIndex( childBoneIdx ) );
bool isChild = false;
int32 actualParentBoneIdx = GetParentBoneIndex( childBoneIdx );
while ( actualParentBoneIdx != InvalidIndex )
{
if ( actualParentBoneIdx == parentBoneIdx )
{
isChild = true;
break;
}
actualParentBoneIdx = GetParentBoneIndex( actualParentBoneIdx );
}
return isChild;
}
//-------------------------------------------------------------------------
#if KRG_DEVELOPMENT_TOOLS
void Skeleton::DrawDebug( Drawing::DrawContext& ctx, Transform const& worldTransform ) const
{
auto const numBones = m_localReferencePose.size();
if ( numBones > 0 )
{
TInlineVector<Transform, 256> globalTransforms;
globalTransforms.resize( numBones );
globalTransforms[0] = m_localReferencePose[0] * worldTransform;
for ( auto i = 1; i < numBones; i++ )
{
auto const& parentIdx = m_parentIndices[i];
auto const& parentTransform = globalTransforms[parentIdx];
globalTransforms[i] = m_localReferencePose[i] * parentTransform;
}
//-------------------------------------------------------------------------
DrawRootBone( ctx, globalTransforms[0] );
for ( auto boneIdx = 1; boneIdx < numBones; boneIdx++ )
{
auto const& parentIdx = m_parentIndices[boneIdx];
auto const& parentTransform = globalTransforms[parentIdx];
auto const& boneTransform = globalTransforms[boneIdx];
ctx.DrawLine( boneTransform.GetTranslation().ToFloat3(), parentTransform.GetTranslation().ToFloat3(), Colors::HotPink, 2.0f );
ctx.DrawAxis( boneTransform, 0.03f, 2.0f );
}
}
}
void DrawRootBone( Drawing::DrawContext& ctx, Transform const& worldTransform )
{
constexpr static float const gizmoRadius = 0.045f;
constexpr static float const arrowLength = 0.1f;
Vector const fwdDir = worldTransform.GetAxisY().GetNegated();
Vector const arrowStartPos = Vector::MultiplyAdd( fwdDir, Vector( gizmoRadius ), worldTransform.GetTranslation() );
ctx.DrawDisc( worldTransform.GetTranslation(), gizmoRadius, Colors::Red );
ctx.DrawArrow( arrowStartPos, fwdDir, arrowLength, Colors::Lime, 8 );
}
#endif
} | 34.560345 | 142 | 0.568222 | JuanluMorales |
92eee549a041c35cb1e6f2f411ddf0b9b51527e8 | 1,453 | hpp | C++ | src/Core/Algorithm/ScalarField/ScalarField.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Core/Algorithm/ScalarField/ScalarField.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Core/Algorithm/ScalarField/ScalarField.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | #ifndef SCALAR_FIELD_OPERATION
#define SCALAR_FIELD_OPERATION
#include <Core/Containers/VectorArray.hpp>
#include <Core/Math/LinearAlgebra.hpp>
#include <Core/Mesh/MeshTypes.hpp>
namespace Ra {
namespace Core {
namespace Algorithm {
// Defining a ScalarField over the mesh vertices
typedef Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > ScalarField;
// Defining the Gradient, over the faces of a mesh, of a ScalarField
typedef VectorArray< Vector3 > Gradient;
// Defining the Divergence, expressend on the vertices, of a Gradient field, expressed on the faces
typedef Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > Divergence;
/*
* Return the Gradient field computed from the ScalarField S defined on the surface of a mesh.
*
* The definition was taken from:
* "Geodesics in Heat: A New Approach to Computing Distance Based on Heat Flow"
* [Keenan Crane, Clarisse Weischedel, Max Wardetzky ]
* TOG 2013
*/
Gradient gradientOfFieldS( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, const ScalarField& S );
/*
* Return the Divergence of the Gradient field defined on the surface of a mesh
*
* The definition was taken from:
* "Geodesics in Heat: A New Approach to Computing Distance Based on Heat Flow"
* [Keenan Crane, Clarisse Weischedel, Max Wardetzky ]
* TOG 2013
*/
Divergence divergenceOfFieldX( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, const Gradient& X );
}
}
}
#endif //SCALAR_FIELD_OPERATION
| 27.415094 | 118 | 0.759119 | nmellado |
92f4a5da6bd6a63349d2096e0e6c5f60b3637c9c | 12,310 | cpp | C++ | ledger-core-bitcoin/test/fixtures/Fixtures.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | ledger-core-bitcoin/test/fixtures/Fixtures.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | ledger-core-bitcoin/test/fixtures/Fixtures.cpp | phaazon/lib-ledger-core | 726009203f9b298e70b65c679ca92e99705dfc8c | [
"MIT"
] | null | null | null | #include <core/utils/Hex.hpp>
#include <bitcoin/transactions/BitcoinLikeTransactionParser.hpp>
#include "Fixtures.hpp"
namespace ledger {
namespace testing {
core::api::ExtendedKeyAccountCreationInfo P2PKH_MEDIUM_XPUB_INFO(
0, {"main"}, {"44'/0'/0'"}, {"xpub6D4waFVPfPCpRvPkQd9A6n65z3hTp6TvkjnBHG5j2MCKytMuadKgfTUHqwRH77GQqCKTTsUXSZzGYxMGpWpJBdYAYVH75x7yMnwJvra1BUJ"}
);
core::api::ExtendedKeyAccountCreationInfo P2WPKH_MEDIUM_XPUB_INFO(
0, {"main"}, {"84'/0'/0'"}, {"xpub6CMeLkY9TzXyLYXPWMXB5LWtprVABb6HwPEPXnEgESMNrSUBsvhXNsA7zKS1ZRKhUyQG4HjZysEP8v7gDNU4J6PvN5yLx4meEm3mpEapLMN"}
);
core::api::AccountCreationInfo P2PKH_MEDIUM_KEYS_INFO(
0, {"main", "main"}, {"44'/0'/0'", "44'/0'"},
{core::hex::toByteArray("0437bc83a377ea025e53eafcd18f299268d1cecae89b4f15401926a0f8b006c0f7ee1b995047b3e15959c5d10dd1563e22a2e6e4be9572aa7078e32f317677a901"), core::hex::toByteArray("04fb60043afe80ee1aeb0160e2aafc94690fb4427343e8d4bf410105b1121f7a44a311668fa80a7a341554a4ef5262bc6ebd8cc981b8b600dafd40f7682edb5b3b")},
{core::hex::toByteArray("d1bb833ecd3beed6ec5f6aa79d3a424d53f5b99147b21dbc00456b05bc978a71"), core::hex::toByteArray("88c2281acd51737c912af74cc1d1a8ba564eb7925e0d58a5500b004ba76099cb")}
);
core::api::ExtendedKeyAccountCreationInfo P2PKH_BIG_XPUB_INFO(
0, {"main"}, {"44'/0'/0'"}, {"xpub6CThYZbX4PTeA7KRYZ8YXP3F6HwT2eVKPQap3Avieds3p1eos35UzSsJtTbJ3vQ8d3fjRwk4bCEz4m4H6mkFW49q29ZZ6gS8tvahs4WCZ9X"}
);
core::api::ExtendedKeyAccountCreationInfo P2SH_XPUB_INFO(
0, {"main"}, {"49'/0'/0'"}, {"tpubDCcvqEHx7prGddpWTfEviiew5YLMrrKy4oJbt14teJZenSi6AYMAs2SNXwYXFzkrNYwECSmobwxESxMCrpfqw4gsUt88bcr8iMrJmbb8P2q"}
);
std::string TX_1 = "{\"hash\":\"666613fd82459f94c74211974e74ffcb4a4b96b62980a6ecaee16af7702bbbe5\",\"received_at\":\"2015-06-22T13:31:27Z\",\"lock_time\":0,\"block\":{\"hash\":\"00000000000000000b2df329293632a46c6b6a6c066fe5a617b264ff6edfa6a4\",\"height\":362035,\"time\":\"2015-06-22T13:31:27Z\"},\"inputs\":[{\"input_index\":0,\"output_hash\":\"e4486c80c17f41ff16b607044a1bf8a4d4aa3985156396b040290812575e71e1\",\"output_index\":0,\"value\":890000,\"address\":\"1KMbwcH1sGpHetLwwQVNMt4cEZB5u8Uk4b\",\"script_signature\":\"473044022009b9163abea9783d2ed1f9d4f9d0c16d624f5bba013728a1551877b9f934e5ad02201b5803ab33d7f19fa8d71106242467b21be592b24f1397569b970ceacf62e8870121020a90429f7e8964be1595789f7cedcb80b850405993e59c7ff244d83a7ec4ac4a\"},{\"input_index\":1,\"output_hash\":\"1565ad6bccb0c9d6c4771d8df49a2b6c5022b6f9dcd307582c7e2fe37e8b4f48\",\"output_index\":0,\"value\":13970000,\"address\":\"15zxN5EuryNJRpgo6rBRvgiYiDYix6EiHK\",\"script_signature\":\"483045022100ec78b471f6760c429044c76d34a084417967e090fada2cc797ef03bf0144a034022072b9e31f69b4a2a37e9d7c02a2e08d8a8195d6fd6da17ef8e2392c8c786015a30121021775300e7f3ba1c538349eb35f24a47314b53e6cc57e7ed154a073fabb00f3d7\"},{\"input_index\":2,\"output_hash\":\"e4486c80c17f41ff16b607044a1bf8a4d4aa3985156396b040290812575e71e1\",\"output_index\":1,\"value\":100000,\"address\":\"12BSjgZhjNi5JVh418h88nVkEBph9tn9JH\",\"script_signature\":\"483045022100ce0fe58a1297c6c96a3059ec11be82351046bbe977f4f5780a6b9710e871069f0220677bbd8364dbf8ef4b9817b404668c26fc6ae98141fbfa5b5c2e60b814e5e6da012102647367b0928f40d80ccec71104692e34f9e2abd4a0e6b7cad6faa1c9e51f3292\"},{\"input_index\":3,\"output_hash\":\"2f7e07679ea5babfe105c1a7c202efa8791819ef59e57ead25911f147dd90eaf\",\"output_index\":1,\"value\":23990000,\"address\":\"1PMiVc1UXestrbbaMqSwDuUrRRhTfy1UZc\",\"script_signature\":\"47304402201047d9e4eb4ce52377ec54a2e75fa0e6ecae6dc349f8a252f5eda4ea2bc8603c022002c016500d49a896aa79a8fb0235b0de27dd32a52feb7ab71c6a67bd44ddfa3501210249511220e84a3b3172895a000a012429c67a78fb33207a2650ec7e69fee21709\"},{\"input_index\":4,\"output_hash\":\"b9325a52d3373f725e8d39d04ff67531490af2221fd94bd3973ffc1b8208053b\",\"output_index\":1,\"value\":37019500,\"address\":\"13XU2CS1YgkDu7N1Xv7zoyypX1B7t4XHWS\",\"script_signature\":\"483045022100c37b6d5f22d6ba176ee0d06be46bcc86a7bd7ef6301bf7983e5f3fcac95ad414022029537ecc338f9a50316d287411bb69362539122b78ff121ecaa5c5ae79796dd70121025df76c1fc25d3d839a27a9b1f1b7051f612b929de2d19b48cbeade18d6439730\"},{\"input_index\":5,\"output_hash\":\"2f7e07679ea5babfe105c1a7c202efa8791819ef59e57ead25911f147dd90eaf\",\"output_index\":0,\"value\":1000000,\"address\":\"1PA2cZx9wZDo3xnd1HpRiLwTAtrpUFgPMw\",\"script_signature\":\"483045022100b257fb66f2ab29e80a4c6cfd4a07fcbb3aafedd02cb0ad76fdd455c34cf94c4502202dbf2392b466b6fe6e9bd4f1fc85077a639a07f3ec956fc45deefc6a5bdf5e26012103d766a986dbeab84e8827d6997e1e7630b909c8f6d16455485df2070ae21ebfe6\"},{\"input_index\":6,\"output_hash\":\"f5a1c29cbce3f0b99a38f46989bda4365a1f32941c8dcf415d76e35cbd0b1cbb\",\"output_index\":0,\"value\":10000,\"address\":\"14nMrPfMVLtXK3csgphyGZPsBPaPzNqtnQ\",\"script_signature\":\"483045022100ff1efd876eaf5813c9d8df381cc46f5b0d283e9b560461988a26465da1fb9fff0220567adc5ab53667e8864cba76a4540b2b5a6e8600495e7117d11e1747f458cdc801210319e6c9ac4a6f0d99d7dc2311dc177506ae3ad251b92a7345beb4add203cc342d\"},{\"input_index\":7,\"output_hash\":\"f871f48ddcf9ae17e5f0ff00121b36bfe54d329a9cbc38afa77db7c4540af7a4\",\"output_index\":1,\"value\":60000,\"address\":\"1EYLmfsvCVGsBmmiUmgJzoQG3MCou2Mh7J\",\"script_signature\":\"47304402202765acf7ea410e5712d5c5adacad0bcb0d71ef1b22b30860a42e851f745338e8022001de1738785ca43291b50e51281d20ecc4f451df9797e5c95641136f267cd4fe01210297af3c6d7e5f0c96a3ac24d059f838d20792362fbf945a10aa3cddeeacdb3cc4\"},{\"input_index\":8,\"output_hash\":\"2adc12ff62c58b56bb9fd5bf6cb702d2d07f39e7fd06b44ed69181c202f1ac2b\",\"output_index\":0,\"value\":9630000,\"address\":\"1Bmpme646SNGa1jjjYAfuijdyBNJXLGEh\",\"script_signature\":\"47304402201a44458da76e5359a904e40c6318e3930d5951a6649df9a846807c5107652d2b0220112e5d86a87e5f54d2d58b234392cf39cd7e9e3313a2f6850f89a9c60fc95d250121037b9922b3bea53333486d9b068ffafba088e4730e4b4081d6a71063b9aefda8ca\"},{\"input_index\":9,\"output_hash\":\"2217f57871f2a973e1544828b3fafe79d7bc8168e875ae50ed2304d7abd5be3a\",\"output_index\":1,\"value\":5000000,\"address\":\"1PhMRy1tEDiPYLxLGGXqVUSYr2qQ5NL8fm\",\"script_signature\":\"47304402200bf3579d28b96dd59a466ad5ae89ca4aef3ca5a473683f27a63d71cb7e90203702206900566e2f84abf4839e87b1bd52969e81c9629e728be9249f2be9e8c4e60bed01210325d655fc73c30551f6cf5a80bd224ccf676d51431d58e3e39fb0ca8ddbf4d891\"},{\"input_index\":10,\"output_hash\":\"7fa17586ffb7775bd19be72f568cba521c6e97eb166c9702096daf4856a2a4d3\",\"output_index\":0,\"value\":2000000,\"address\":\"1JpVd5LgkDw9o43bFsT9kMSMtqEKuYY69m\",\"script_signature\":\"473044022072655d94fef5fcecaa6153ef89a8ed93361665392d222b275072578af623f01a0220232f49fe3ad36eeca863884ac70a5800964239a6851e25f12cba1ebd97c4cdc301210357885d4578594861cdc10e1fbe9456a1df2461038936a8b913f7c727d1becb1b\"},{\"input_index\":11,\"output_hash\":\"8ff2a1c170a728fbd0ceb2947b120f8f1d0d08a52567b05882c02b41b866e357\",\"output_index\":1,\"value\":540000,\"address\":\"12YvvHBzc4r9bS5EaEs27AgqYTjX1guUer\",\"script_signature\":\"4730440220485e6884a4490a318bc8e8d04d93f283819ece82dfed6bf0434e3aadf8f8855d02202c46fa38e627beae7accd47adcb0ac3d75eaa05f9e962967ecedd1ca5870405c012102fc03f7162b34700e03a2da4bcbf9799eb6eec61ae01548e79db50765fb943932\"},{\"input_index\":12,\"output_hash\":\"7b7bb35e059cfabe79ea3b72caaa866fbf624d645768e198c5d021622262be80\",\"output_index\":0,\"value\":20000000,\"address\":\"12LVnPYsDzZKN3F4gdFaBJ1WSkkSxje6AS\",\"script_signature\":\"483045022100e7539137c60e00b5320ff1f7f4a0e1539a538c87fb133731dba7c8bc22fcfc7402200c4a2db4b203c6a84e7d41446d4ebc3c66ac203cf0ce93285887d8c7e23bb7680121030f25559e42584669dc19661b398a60660258e0bd3edfc16f3f38d1171c59c1fc\"},{\"input_index\":13,\"output_hash\":\"904fb0ba6c126a5fc50507c0f953e8e48363eb34798e82945971fc3634e2b305\",\"output_index\":0,\"value\":68384000,\"address\":\"1PKsemsjKHX8r2AWNHWTXhDq4waRMQpFEA\",\"script_signature\":\"47304402202013318f36716b9405627529a42d76901256798f5c8ac3a248b4b17f97e3640e02205cf81ccf9f0827679d462b6b20d954e0556f50cd52861eb50494841e9240aea40121034bd0aa6737a5d7b1571a3ac24afafd9225109feb0b79f57c1cf2271cfb6d2f59\"},{\"input_index\":14,\"output_hash\":\"a7e29eb70660fb23d0f6ecededf91519d9d17fa2ed2624a44f80f39e7f1cc634\",\"output_index\":1,\"value\":10000,\"address\":\"16VLgkWhKRSgLhW8sCra88qRuWXjpaZRtM\",\"script_signature\":\"47304402200b78257a162efa7410dc74cd6b29a8a80677a38f8ff2a3632fb472e59296d321022038de9ebe64e2a96454c4ddadb75f32d9b7f7026e2c3fefb66ebe60106569a5c30121025748f109aa23987b80a4ac8a681881e0b5532387ac0db5226ec1931bad68ebc0\"}],\"outputs\":[{\"output_index\":0,\"value\":182593500,\"address\":\"1DDBzjLyAmDr4qLRC2T2WJ831cxBM5v7G7\",\"script_hex\":\"76a91485efaded203a798edc46cd458f0714136f6d0acb88ac\"}],\"fees\":10000,\"amount\":182593500,\"confirmations\":110220}";
std::string TX_2 = "{\"hash\":\"a5fb8b23c1131850569874b8d8592800211b3d0392753b84d2d5f9f53b7e09fc\",\"received_at\":\"2015-06-22T15:58:30Z\",\"lock_time\":0,\"block\":{\"hash\":\"00000000000000000198e024d936c87807b4198f9de7105015036ce785fa2bdc\",\"height\":362055,\"time\":\"2015-06-22T15:58:30Z\"},\"inputs\":[{\"input_index\":0,\"output_hash\":\"666613fd82459f94c74211974e74ffcb4a4b96b62980a6ecaee16af7702bbbe5\",\"output_index\":0,\"value\":182593500,\"address\":\"1DDBzjLyAmDr4qLRC2T2WJ831cxBM5v7G7\",\"script_signature\":\"473044022018ac8a44412d66f489138c3e8f9196b60dba1c24fb715dd8c3d66921bcc13f4702201f222fd3e25fe8f3807347650ae7b41451c078c9a8fc2e5b7d82d6a928a8c363012103da611b1fcacc0056ceb5489ee951b523e52de7ff1902fd1c6f9c212a542da297\"}],\"outputs\":[{\"output_index\":0,\"value\":182483500,\"address\":\"18BkSm7P2wQJfQhV7B5st14t13mzHRJ2o1\",\"script_hex\":\"76a9144ed14e321713e1c97056643a233b968d34b2231188ac\"},{\"output_index\":1,\"value\":100000,\"address\":\"1NMfmPC9yHBe5US2CUwWARPRM6cDP6N86m\",\"script_hex\":\"76a914ea4351fd2a0a2cd62ab264d9f0b1997696a632f488ac\"}],\"fees\":10000,\"amount\":182583500,\"confirmations\":110200}";
std::string TX_3 = "{\"hash\":\"a5fb8b23c1131850569874b8d8592800211b3d0392753b84d2d5f9f53b7e09fc\",\"received_at\":\"2015-06-22T15:58:30Z\",\"lock_time\":0,\"block\":{\"hash\":\"00000000000000000198e024d936c87807b4198f9de7105015036ce785fa2bdc\",\"height\":362055,\"time\":\"2015-06-22T15:58:30Z\"},\"inputs\":[{\"input_index\":0,\"output_hash\":\"666613fd82459f94c74211974e74ffcb4a4b96b62980a6ecaee16af7702bbbe5\",\"output_index\":0,\"value\":182593500,\"address\":\"1DDBzjLyAmDr4qLRC2T2WJ831cxBM5v7G7\",\"script_signature\":\"473044022018ac8a44412d66f489138c3e8f9196b60dba1c24fb715dd8c3d66921bcc13f4702201f222fd3e25fe8f3807347650ae7b41451c078c9a8fc2e5b7d82d6a928a8c363012103da611b1fcacc0056ceb5489ee951b523e52de7ff1902fd1c6f9c212a542da297\"}],\"outputs\":[{\"output_index\":0,\"value\":182483500,\"address\":\"18BkSm7P2wQJfQhV7B5st14t13mzHRJ2o1\",\"script_hex\":\"76a9144ed14e321713e1c97056643a233b968d34b2231188ac\"},{\"output_index\":1,\"value\":100000,\"address\":\"1NMfmPC9yHBe5US2CUwWARPRM6cDP6N86m\",\"script_hex\":\"76a914ea4351fd2a0a2cd62ab264d9f0b1997696a632f488ac\"}],\"fees\":10000,\"amount\":182583500,\"confirmations\":110200}";
std::string TX_4 = "{\"hash\":\"4450e70656888bd7f5240a9b532eac54db7d72f3b48bfef09fb45a185bb9c570\",\"received_at\":\"2015-06-22T16:19:26Z\",\"lock_time\":0,\"block\":{\"hash\":\"0000000000000000037e0f13d498d13a0b08e7ecc069ed497d665b6927b4724d\",\"height\":362058,\"time\":\"2015-06-22T16:19:26Z\"},\"inputs\":[{\"input_index\":0,\"output_hash\":\"a5fb8b23c1131850569874b8d8592800211b3d0392753b84d2d5f9f53b7e09fc\",\"output_index\":0,\"value\":182483500,\"address\":\"18BkSm7P2wQJfQhV7B5st14t13mzHRJ2o1\",\"script_signature\":\"483045022100bb268c100d815e49db33b14426b894639e62f6ac6cabbe1ded0af045ed7b5ca502200e9828576212c5003058ff9e2a6ac507d956fbe9c2ee24687f12ed43902a77410121029a8a38f29bfadfd6b9fe2a41f0f079b8c0a39f7e9c0479c3ac49a091d2e9d550\"}],\"outputs\":[{\"output_index\":0,\"value\":182373500,\"address\":\"139dJmHhFuuhrgbNAPehpokjYHNEtvkxot\",\"script_hex\":\"76a9141791e2de9302ecc21f60ac0cd417538c49cb5c6b88ac\"},{\"output_index\":1,\"value\":100000,\"address\":\"16cqCPDSoBYkaKUkYw94k3CeoNcMDcTLYN\",\"script_hex\":\"76a9143d9f6b778193e20365b2e8a493f33c35886d630688ac\"}],\"fees\":10000,\"amount\":182473500,\"confirmations\":110197}";
}
}
| 332.702703 | 7,035 | 0.831763 | phaazon |
92f5811a90b75bf13db2eb7ba698f51fb03b3157 | 2,727 | cpp | C++ | UiComponents/TextInput/TextInput.cpp | cross-platform/DSPatcher | 80a14439eb9f93a2788711d6e5d898796c1b385e | [
"BSD-2-Clause"
] | 27 | 2019-01-26T15:13:44.000Z | 2021-11-17T04:00:08.000Z | UiComponents/TextInput/TextInput.cpp | cross-platform/DSPatcher | 80a14439eb9f93a2788711d6e5d898796c1b385e | [
"BSD-2-Clause"
] | 1 | 2018-01-09T19:52:58.000Z | 2018-10-26T15:32:31.000Z | UiComponents/TextInput/TextInput.cpp | cross-platform/DSPatcher | 80a14439eb9f93a2788711d6e5d898796c1b385e | [
"BSD-2-Clause"
] | 9 | 2019-08-14T06:24:32.000Z | 2021-11-17T04:00:09.000Z | /******************************************************************************
DSPatcher - Cross-Platform Graphical Tool for DSPatch
Copyright (c) 2021, Marcus Tomlinson
BSD 2-Clause License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <TextInput.h>
#include <QHBoxLayout>
#include <QLineEdit>
using namespace DSPatch;
using namespace DSPatcher;
namespace DSPatch
{
namespace DSPatcher
{
namespace internal
{
class TextInput
{
public:
TextInput()
{
widget = new QWidget();
textEdit = new QLineEdit( widget );
textEdit->connect( textEdit, &QLineEdit::textChanged, [this]( const QString& value ) { currentValue = value.toStdString(); } );
QHBoxLayout* layout = new QHBoxLayout( widget );
layout->addWidget( textEdit );
layout->setContentsMargins( 15, 15, 15, 15 );
widget->resize( layout->sizeHint() );
}
~TextInput()
{
textEdit->disconnect();
widget->deleteLater();
}
QLineEdit* textEdit;
QWidget* widget;
std::string currentValue;
};
} // namespace internal
} // namespace DSPatcher
} // namespace DSPatch
TextInput::TextInput()
: UiComponent( ProcessOrder::OutOfOrder )
, p( new internal::TextInput() )
{
SetOutputCount_( 1 );
}
QWidget* TextInput::widget()
{
return p->widget;
}
void TextInput::Process_( SignalBus const&, SignalBus& outputs )
{
outputs.SetValue( 0, p->currentValue );
}
| 29.641304 | 135 | 0.689036 | cross-platform |
92f77bc3df14e93ec50cea31df57f1704ac6a66a | 3,675 | hpp | C++ | engine/subsystems/vulkan/se_vulkan_render_subsystem_framebuffer.hpp | grobermoldavan/SabrinaEngine | 9a6f983500deb2d03cc2dcb5710407d01a62b2fd | [
"MIT"
] | null | null | null | engine/subsystems/vulkan/se_vulkan_render_subsystem_framebuffer.hpp | grobermoldavan/SabrinaEngine | 9a6f983500deb2d03cc2dcb5710407d01a62b2fd | [
"MIT"
] | null | null | null | engine/subsystems/vulkan/se_vulkan_render_subsystem_framebuffer.hpp | grobermoldavan/SabrinaEngine | 9a6f983500deb2d03cc2dcb5710407d01a62b2fd | [
"MIT"
] | null | null | null | #ifndef _SE_VULKAN_RENDER_SUBSYSTEM_FRAMEBUFFER_H_
#define _SE_VULKAN_RENDER_SUBSYSTEM_FRAMEBUFFER_H_
#include "se_vulkan_render_subsystem_base.hpp"
#include "se_vulkan_render_subsystem_render_pass.hpp"
#include "se_vulkan_render_subsystem_texture.hpp"
#include "engine/containers.hpp"
#define SE_VK_FRAMEBUFFER_MAX_TEXTURES 8
struct SeVkFramebufferInfo
{
struct SeVkDevice* device;
ObjectPoolEntryRef<SeVkRenderPass> pass;
ObjectPoolEntryRef<SeVkTexture> textures[SE_VK_FRAMEBUFFER_MAX_TEXTURES];
uint32_t numTextures;
};
struct SeVkFramebuffer
{
SeVkObject object;
struct SeVkDevice* device;
ObjectPoolEntryRef<SeVkRenderPass> pass;
ObjectPoolEntryRef<SeVkTexture> textures[SE_VK_FRAMEBUFFER_MAX_TEXTURES];
uint32_t numTextures;
VkFramebuffer handle;
VkExtent2D extent;
};
void se_vk_framebuffer_construct(SeVkFramebuffer* framebuffer, SeVkFramebufferInfo* info);
void se_vk_framebuffer_destroy(SeVkFramebuffer* framebuffer);
template<>
void se_vk_destroy<SeVkFramebuffer>(SeVkFramebuffer* res)
{
se_vk_framebuffer_destroy(res);
}
namespace hash_value
{
namespace builder
{
template<>
void absorb<SeVkFramebufferInfo>(HashValueBuilder& builder, const SeVkFramebufferInfo& value)
{
hash_value::builder::absorb(builder, value.pass);
hash_value::builder::absorb(builder, value.numTextures);
for (size_t it = 0; it < value.numTextures; it++) hash_value::builder::absorb(builder, value.textures[it]);
}
}
template<>
HashValue generate<SeVkFramebufferInfo>(const SeVkFramebufferInfo& value)
{
HashValueBuilder builder = hash_value::builder::create();
hash_value::builder::absorb(builder, value);
return hash_value::builder::end(builder);
}
}
namespace string
{
template<>
SeString cast<SeVkFramebufferInfo>(const SeVkFramebufferInfo& value, SeStringLifetime lifetime)
{
SeStringBuilder builder = string_builder::begin(lifetime);
string_builder::append(builder, "[Framebuffer info. ");
string_builder::append(builder, "Pass id: [");
string_builder::append(builder, string::cast(value.pass.generation));
string_builder::append(builder, ", ");
string_builder::append(builder, string::cast(value.pass.index));
string_builder::append(builder, "]. Textures: [num: ");
string_builder::append(builder, string::cast(value.numTextures));
string_builder::append(builder, ", ");
for (size_t it = 0; it < value.numTextures; it++)
{
string_builder::append(builder, "[");
string_builder::append(builder, string::cast(value.textures[it].generation));
string_builder::append(builder, ", ");
string_builder::append(builder, string::cast(value.textures[it].index));
string_builder::append(builder, "], ");
}
string_builder::append(builder, "]]");
return string_builder::end(builder);
}
template<>
SeString cast<SeVkFramebuffer>(const SeVkFramebuffer& value, SeStringLifetime lifetime)
{
SeStringBuilder builder = string_builder::begin(lifetime);
string_builder::append(builder, "Framebuffer. ");
string_builder::append(builder, "id: [");
string_builder::append(builder, string::cast(value.object.uniqueIndex));
string_builder::append(builder, "]");
return string_builder::end(builder);
}
}
#endif
| 36.75 | 119 | 0.670476 | grobermoldavan |
92f858b66625e0932e05fbf71d279d907ddc4808 | 3,928 | cpp | C++ | Source/Scripting/bsfScript/Generated/BsScriptGUISkin.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 1,745 | 2018-03-16T02:10:28.000Z | 2022-03-26T17:34:21.000Z | Source/Scripting/bsfScript/Generated/BsScriptGUISkin.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 395 | 2018-03-16T10:18:20.000Z | 2021-08-04T16:52:08.000Z | Source/Scripting/bsfScript/Generated/BsScriptGUISkin.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 267 | 2018-03-17T19:32:54.000Z | 2022-02-17T16:55:50.000Z | //********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "BsScriptGUISkin.generated.h"
#include "BsMonoMethod.h"
#include "BsMonoClass.h"
#include "BsMonoUtil.h"
#include "../../../Foundation/bsfEngine/GUI/BsGUISkin.h"
#include "BsScriptResourceManager.h"
#include "Wrappers/BsScriptRRefBase.h"
#include "BsScriptGUIElementStyle.generated.h"
#include "../../../Foundation/bsfEngine/GUI/BsGUISkin.h"
namespace bs
{
ScriptGUISkin::ScriptGUISkin(MonoObject* managedInstance, const ResourceHandle<GUISkin>& value)
:TScriptResource(managedInstance, value)
{
}
void ScriptGUISkin::initRuntimeData()
{
metaData.scriptClass->addInternalCall("Internal_GetRef", (void*)&ScriptGUISkin::Internal_getRef);
metaData.scriptClass->addInternalCall("Internal_hasStyle", (void*)&ScriptGUISkin::Internal_hasStyle);
metaData.scriptClass->addInternalCall("Internal_getStyle", (void*)&ScriptGUISkin::Internal_getStyle);
metaData.scriptClass->addInternalCall("Internal_setStyle", (void*)&ScriptGUISkin::Internal_setStyle);
metaData.scriptClass->addInternalCall("Internal_removeStyle", (void*)&ScriptGUISkin::Internal_removeStyle);
metaData.scriptClass->addInternalCall("Internal_getStyleNames", (void*)&ScriptGUISkin::Internal_getStyleNames);
metaData.scriptClass->addInternalCall("Internal_create", (void*)&ScriptGUISkin::Internal_create);
}
MonoObject*ScriptGUISkin::createInstance()
{
bool dummy = false;
void* ctorParams[1] = { &dummy };
return metaData.scriptClass->createInstance("bool", ctorParams);
}
MonoObject* ScriptGUISkin::Internal_getRef(ScriptGUISkin* thisPtr)
{
return thisPtr->getRRef();
}
bool ScriptGUISkin::Internal_hasStyle(ScriptGUISkin* thisPtr, MonoString* name)
{
bool tmp__output;
String tmpname;
tmpname = MonoUtil::monoToString(name);
tmp__output = thisPtr->getHandle()->hasStyle(tmpname);
bool __output;
__output = tmp__output;
return __output;
}
MonoObject* ScriptGUISkin::Internal_getStyle(ScriptGUISkin* thisPtr, MonoString* guiElemType)
{
SPtr<GUIElementStyle> tmp__output = bs_shared_ptr_new<GUIElementStyle>();
String tmpguiElemType;
tmpguiElemType = MonoUtil::monoToString(guiElemType);
*tmp__output = *thisPtr->getHandle()->getStyle(tmpguiElemType);
MonoObject* __output;
__output = ScriptGUIElementStyle::create(tmp__output);
return __output;
}
void ScriptGUISkin::Internal_setStyle(ScriptGUISkin* thisPtr, MonoString* guiElemType, MonoObject* style)
{
String tmpguiElemType;
tmpguiElemType = MonoUtil::monoToString(guiElemType);
SPtr<GUIElementStyle> tmpstyle;
ScriptGUIElementStyle* scriptstyle;
scriptstyle = ScriptGUIElementStyle::toNative(style);
if(scriptstyle != nullptr)
tmpstyle = scriptstyle->getInternal();
thisPtr->getHandle()->setStyle(tmpguiElemType, *tmpstyle);
}
void ScriptGUISkin::Internal_removeStyle(ScriptGUISkin* thisPtr, MonoString* guiElemType)
{
String tmpguiElemType;
tmpguiElemType = MonoUtil::monoToString(guiElemType);
thisPtr->getHandle()->removeStyle(tmpguiElemType);
}
MonoArray* ScriptGUISkin::Internal_getStyleNames(ScriptGUISkin* thisPtr)
{
Vector<String> vec__output;
vec__output = thisPtr->getHandle()->getStyleNames();
MonoArray* __output;
int arraySize__output = (int)vec__output.size();
ScriptArray array__output = ScriptArray::create<String>(arraySize__output);
for(int i = 0; i < arraySize__output; i++)
{
array__output.set(i, vec__output[i]);
}
__output = array__output.getInternal();
return __output;
}
void ScriptGUISkin::Internal_create(MonoObject* managedInstance)
{
ResourceHandle<GUISkin> instance = GUISkin::create();
ScriptResourceManager::instance().createBuiltinScriptResource(instance, managedInstance);
}
}
| 35.071429 | 124 | 0.754837 | bsf2dev |
92fa3674ee2f7fea341c55d1c902b53c12b307d0 | 605 | cpp | C++ | 11743 Credit Check.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 11743 Credit Check.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 11743 Credit Check.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int sum = 0;
for (int i = 0; i < 4; ++i)
{
int num;
cin >> num;
for (int j = 0; j < 2; ++j)
{
sum += num % 10;
num /= 10;
sum += num * 2 % 10;
sum += (num % 10 * 2 / 10);
num /= 10;
}
}
if (sum % 10)
cout << "Invalid\n";
else
cout << "Valid\n";
}
} | 16.805556 | 43 | 0.272727 | zihadboss |
92fa589eb087550944646b0a23ec5f65031f0372 | 5,628 | cpp | C++ | source/main_NG_MPI.cpp | jfbucas/PION | e0a66aa301e4d94d581ba4df078f1a3b82faab99 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T11:31:22.000Z | 2020-12-05T13:30:03.000Z | source/main_NG_MPI.cpp | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | null | null | null | source/main_NG_MPI.cpp | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T14:33:19.000Z | 2022-03-07T10:29:34.000Z | /// \file main_NG_MPI.cpp
/// \brief Main program which sets up a NG grid and runs a MCMD sim.
/// \author Jonathan Mackey
///
///
/// Arguments: \<pion_NG_mpi\> \<icfile\> [override options]\n
/// Parameters:
/// - \<icfile\> Can be an ASCII text parameter-file for 1D and 2D shocktube
/// test problems; otherwise should be an initial-condition file or a
/// restartfile in fits/silo format.
/// - [override options] are optional and of the format \<name\>=\<value\> with no spaces.
/// - redirect=PATH: Path to redirect stdout/stderr to, (with trailing forward slash).
/// - opfreq=N : modify output frequency to every Nth timestep.
/// - optype=N : modify type of output file, 1=TXT,2=FITS,3=FitsTable,4=TXT+FITS.
/// - outfile=NAME : Replacement output filename, with path.
/// - ooa=N : modify order of accuracy.
/// - eqntype=N : modify type of equations, 1=Euler, 2=idealMHD, 3=glmMHD
/// [- artvisc=D : modify artificial viscosity, =0 none, Otherwise AVFalle with eta=D,]
/// - AVtype=N : modify type of AV: 0=none, 1=FKJ98, 2=CW84
/// - EtaVisc=D : modify viscosity parameter to double precision value.
/// - noise=D : add noise to icfile if desired, at fractional level of D
/// - finishtime=D : set time to finish simulation, in code time units.
/// - coordsys=NAME : set coordinate system to [cartesian,cylindrical]. DANGEROUS TO OVERRIDE!
/// - cfl=D : change the CFL no. for the simulation, in range (0,1).
/// - cooling=N : cooling=0 for no cooling, 1 for Sutherland&Dopita1993.
///
/// Modifications:
/// - 2018.08.30 JM: wrote code.
#include <iostream>
#include <sstream>
using namespace std;
#include "defines/functionality_flags.h"
#include "defines/testing_flags.h"
#include "sim_constants.h"
#include "tools/reporting.h"
#include "grid/grid_base_class.h"
#include "sim_control/sim_control_NG_MPI.h"
int main(int argc, char **argv)
{
int err = COMM->init(&argc,&argv);
//cout <<"argc="<<argc<<"\n";
int myrank = -1, nproc = -1;
COMM->get_rank_nproc(&myrank, &nproc);
//
// Set up simulation controller class.
//
class sim_control_NG_MPI *sim_control = 0;
sim_control = new class sim_control_NG_MPI();
if (!sim_control)
rep.error("(pion) Couldn't initialise sim_control", sim_control);
//
// Check that command-line arguments are sufficient.
//
if (argc<2) {
sim_control->print_command_line_options(argc,argv);
rep.error("Bad arguments",argc);
}
string *args=0;
args = new string [argc];
for (int i=0;i<argc;i++) args[i] = argv[i];
// Set up reporting class.
for (int i=0;i<argc; i++) {
if (args[i].find("redirect=") != string::npos) {
string outpath = (args[i].substr(9));
ostringstream path; path << outpath <<"_"<<myrank<<"_";
outpath = path.str();
if (myrank==0) {
cout <<"\tRedirecting stdout to "<<outpath<<"info.txt"<<"\n";
}
// Redirects cout and cerr to text files in the directory specified.
rep.redirect(outpath);
}
}
#ifdef REPORT_RANK0
rep.kill_stdout_from_other_procs(0);
#endif
cout <<"-------------------------------------------------------\n";
cout <<"--------- pion NG MPI v2.0 running ----------------\n";
cout <<"-------------------------------------------------------\n";
//
// Reset max. walltime to run the simulation for, if needed.
// Input should be in hours.
//
for (int i=0;i<argc; i++) {
if (args[i].find("maxwalltime=") != string::npos) {
double tmp = atof((args[i].substr(12)).c_str());
if (isnan(tmp) || isinf(tmp) || tmp<0.0)
rep.error("Don't recognise max walltime as a valid runtime!",tmp);
sim_control->set_max_walltime(tmp*3600.0);
if (myrank==0) {
cout <<"\tResetting MAXWALLTIME to ";
cout <<sim_control->get_max_walltime()<<" seconds, or ";
cout <<sim_control->get_max_walltime()/3600.0<<" hours.\n";
}
}
}
// Set what type of file to open: 1=parameterfile, 2/5=restartfile.
int ft;
if (args[1].find(".silo") != string::npos) {
cout <<"(pion) reading ICs from SILO IC file "<<args[1]<<"\n";
ft=5;
}
else if (args[1].find(".fits") != string::npos) {
cout <<"(pion) reading ICs from Fits ICfile "<<args[1]<<"\n";
ft=2;
}
else {
cout <<"(pion) IC file not fits/silo: assuming parameter file";
cout <<args[1]<<"\n";
ft=1;
}
//
// set up vector of grids.
//
vector<class GridBaseClass *> grid;
//
// Initialise the grid.
// inputs are infile_name, infile_type, nargs, *args[]
//
err = sim_control->Init(args[1], ft, argc, args, grid);
if (err!=0){
cerr<<"(*pion*) err!=0 from Init"<<"\n";
delete sim_control;
return 1;
}
//
// Integrate forward in time until the end of the calculation.
//
err+= sim_control->Time_Int(grid);
if (err!=0){
cerr<<"(*pion*) err!=0 from Time_Int"<<"\n";
delete sim_control;
//delete grid;
return 1;
}
//
// Finalise and exit.
//
err+= sim_control->Finalise(grid);
if (err!=0){
cerr<<"(*pion*) err!=0 from Finalise"<<"\n";
delete sim_control;
return 1;
}
delete sim_control; sim_control=0;
for (unsigned int v=0; v<grid.size(); v++) {
delete grid[v];
}
delete [] args; args=0;
COMM->finalise();
cout << "rank: " << myrank << " nproc: " << nproc << "\n";
delete COMM; COMM=0;
cout <<"-------------------------------------------------------\n";
cout <<"--------- pion NG MPI v2.0 finished ----------------\n";
cout <<"-------------------------------------------------------\n";
return 0;
}
| 30.586957 | 97 | 0.585821 | jfbucas |
92fc02a7f0ae016a38896b845ca1e8995a093ae3 | 609 | cpp | C++ | solutions/ugly-number/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/ugly-number/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/ugly-number/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-08-30T06:53:23.000Z | 2019-08-30T06:53:23.000Z | #include <iostream>
#include <limits>
using namespace std;
class Solution {
public:
bool isUgly(int num) {
if (num <= 0)
return false;
while (num % 2 == 0)
num /= 2;
while (num % 3 == 0)
num /= 3;
while (num % 5 == 0)
num /= 5;
return num == 1;
}
};
int main()
{
int input[] = {
numeric_limits<int>::min(),
-100, -60, -55, 0, 1, 2, 3, 4, 5, 7,
10, 14, 20, 32, 47, 48, 55, 125, 375,
numeric_limits<int>::max(),
};
Solution solution;
for (int num: input) {
cout << num << " is ";
if (!solution.isUgly(num))
cout << "not ";
cout << "ugly" << endl;
}
return 0;
}
| 16.026316 | 39 | 0.528736 | locker |
92fcb5a33460a600221ccf5d59d48e463312e6fc | 74,164 | cpp | C++ | all/native/packagemanager/PackageManager.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/packagemanager/PackageManager.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/packagemanager/PackageManager.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | #ifdef _CARTO_PACKAGEMANAGER_SUPPORT
#include "PackageManager.h"
#include "core/BinaryData.h"
#include "components/Exceptions.h"
#include "projections/Projection.h"
#include "projections/EPSG3857.h"
#include "packagemanager/handlers/PackageHandler.h"
#include "packagemanager/handlers/PackageHandlerFactory.h"
#include "utils/URLFileLoader.h"
#include "utils/GeneralUtils.h"
#include "utils/Log.h"
#include <cstdint>
#include <memory>
#include <utility>
#include <algorithm>
#include <limits>
#include <time.h>
#include <boost/lexical_cast.hpp>
#include <stdext/utf8_filesystem.h>
#include <stdext/zlib.h>
#include <sqlite3pp.h>
#include <sqlite3ppext.h>
#include <rapidjson/rapidjson.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/document.h>
#include <rc5.h>
#include <sha.h>
#include <modes.h>
#include <filters.h>
#include <hex.h>
namespace {
std::shared_ptr<carto::PackageMetaInfo> createPackageMetaInfo(const rapidjson::Value& value) {
rapidjson::StringBuffer metaInfo;
rapidjson::Writer<rapidjson::StringBuffer> writer(metaInfo);
value.Accept(writer);
carto::Variant var = carto::Variant::FromString(metaInfo.GetString());
return std::make_shared<carto::PackageMetaInfo>(var);
}
}
namespace carto {
PackageManager::PackageManager(const std::string& packageListURL, const std::string& dataFolder, const std::string& serverEncKey, const std::string& localEncKey) :
_packageListURL(packageListURL),
_packageListFileName("serverpackages.json"),
_dataFolder(dataFolder),
_serverEncKey(serverEncKey),
_localEncKey(localEncKey),
_localPackages(),
_localDb(),
_taskQueue(),
_taskQueueCondition(),
_packageManagerThread(),
_onChangeListeners(),
_stopped(true),
_prevTaskId(-1),
_prevAction(PackageAction::PACKAGE_ACTION_WAITING),
_prevRoundedProgress(0),
_packageManagerListener(),
_serverPackageCache(),
_packageHandlerCache(),
_mutex()
{
std::string taskDbFileName = "tasks_v1.sqlite";
try {
_taskQueue = std::make_shared<PersistentTaskQueue>(createLocalFilePath(taskDbFileName));
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager: Error while constructing PackageManager::PersistentTaskQueue: %s, trying to remove...", ex.what());
_taskQueue.reset();
utf8_filesystem::unlink(taskDbFileName.c_str());
try {
_taskQueue = std::make_shared<PersistentTaskQueue>(createLocalFilePath(taskDbFileName));
}
catch (const std::exception& ex) {
throw FileException("Failed to create/open package manager task queue database", taskDbFileName);
}
}
std::string packageDbFileName = "packages_v1.sqlite";
try {
_localDb = std::make_shared<sqlite3pp::database>(createLocalFilePath(packageDbFileName).c_str());
InitializeDb(*_localDb, _serverEncKey + _localEncKey);
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager: Error while constructing PackageManager: %s, trying to remove", ex.what());
_localDb.reset();
utf8_filesystem::unlink(packageDbFileName.c_str());
try {
_localDb = std::make_shared<sqlite3pp::database>(createLocalFilePath(packageDbFileName).c_str());
InitializeDb(*_localDb, _serverEncKey + _localEncKey);
}
catch (const std::exception& ex) {
throw FileException("Failed to create/open package manager database", packageDbFileName);
}
}
syncLocalPackages();
}
PackageManager::~PackageManager() {
stop(true);
}
std::shared_ptr<PackageManagerListener> PackageManager::getPackageManagerListener() const {
return _packageManagerListener.get();
}
void PackageManager::setPackageManagerListener(const std::shared_ptr<PackageManagerListener>& listener) {
_packageManagerListener.set(listener);
}
void PackageManager::registerOnChangeListener(const std::shared_ptr<OnChangeListener>& listener) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_onChangeListeners.push_back(listener);
}
void PackageManager::unregisterOnChangeListener(const std::shared_ptr<OnChangeListener>& listener) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_onChangeListeners.erase(std::remove(_onChangeListeners.begin(), _onChangeListeners.end(), listener), _onChangeListeners.end());
}
bool PackageManager::start() {
if (!_localDb) {
return false;
}
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_stopped && _packageManagerThread) {
return true;
}
}
stop(true);
std::lock_guard<std::recursive_mutex> lock(_mutex);
_stopped = false;
_packageManagerThread = std::make_shared<std::thread>(std::bind(&PackageManager::run, this));
Log::Info("PackageManager: Package manager started");
return true;
}
void PackageManager::stop(bool wait) {
if (!_localDb) {
return;
}
std::shared_ptr<std::thread> packageManagerThread;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_stopped) {
_stopped = true;
_taskQueueCondition.notify_all();
Log::Info("PackageManager: Stopping package manager");
}
packageManagerThread = _packageManagerThread;
}
if (packageManagerThread && wait) {
packageManagerThread->join();
std::lock_guard<std::recursive_mutex> lock(_mutex);
_packageManagerThread.reset();
Log::Info("PackageManager: Package manager stopped");
}
}
std::string PackageManager::getSchema() const {
if (!_localDb) {
return std::string();
}
try {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT value FROM metadata WHERE name='schema'");
for (auto qit = query.begin(); qit != query.end(); qit++) {
return qit->get<const char*>(0);
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::getSchema: %s", ex.what());
}
return std::string();
}
std::vector<std::shared_ptr<PackageInfo> > PackageManager::getServerPackages() const {
try {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_serverPackageCache) {
_serverPackageCache = std::make_shared<std::vector<std::shared_ptr<PackageInfo> > >();
// Load package list and parse
std::string packageListJson = loadPackageListJson(_packageListFileName);
if (packageListJson.empty()) {
return std::vector<std::shared_ptr<PackageInfo> >();
}
rapidjson::Document packageListDoc;
if (packageListDoc.Parse<rapidjson::kParseDefaultFlags>(packageListJson.c_str()).HasParseError()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Error while parsing package list");
}
// Create packages
for (rapidjson::Value::ValueIterator jit = packageListDoc["packages"].Begin(); jit != packageListDoc["packages"].End(); jit++) {
rapidjson::Value& jsonPackageInfo = *jit;
std::string packageId = jsonPackageInfo["id"].GetString();
std::string packageURL = jsonPackageInfo["url"].GetString();
PackageType::PackageType packageType = PackageHandlerFactory::DetectPackageType(packageURL);
std::shared_ptr<PackageMetaInfo> metaInfo;
if (jsonPackageInfo.HasMember("metainfo")) {
metaInfo = createPackageMetaInfo(jsonPackageInfo["metainfo"]);
}
std::shared_ptr<PackageTileMask> tileMask;
if (jsonPackageInfo.HasMember("tile_mask")) {
tileMask = DecodeTileMask(jsonPackageInfo["tile_mask"].GetString());
}
auto packageInfo = std::make_shared<PackageInfo>(
packageId,
packageType,
jsonPackageInfo["version"].IsString() ? boost::lexical_cast<int>(jsonPackageInfo["version"].GetString()) : jsonPackageInfo["version"].GetInt(),
jsonPackageInfo["size"].IsString() ? boost::lexical_cast<std::uint64_t>(jsonPackageInfo["size"].GetString()) : jsonPackageInfo["size"].GetInt64(),
packageURL,
tileMask,
metaInfo
);
_serverPackageCache->push_back(packageInfo);
}
}
return *_serverPackageCache;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::getServerPackages: %s", ex.what());
}
return std::vector<std::shared_ptr<PackageInfo> >();
}
std::vector<std::shared_ptr<PackageInfo> > PackageManager::getLocalPackages() const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _localPackages;
}
std::shared_ptr<PackageMetaInfo> PackageManager::getServerPackageListMetaInfo() const {
try {
// Parse package list file, load meta info
std::string packageListJson = loadPackageListJson(_packageListFileName);
if (packageListJson.empty()) {
return std::shared_ptr<PackageMetaInfo>();
}
rapidjson::Document packageListDoc;
if (packageListDoc.Parse<rapidjson::kParseDefaultFlags>(packageListJson.c_str()).HasParseError()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Error while parsing package list");
}
if (packageListDoc.HasMember("metainfo")) {
return createPackageMetaInfo(packageListDoc["metainfo"]);
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::getServerPackageListMetaInfo: %s", ex.what());
}
return std::shared_ptr<PackageMetaInfo>();
}
int PackageManager::getServerPackageListAge() const {
// Use last modification time of package list file
std::lock_guard<std::recursive_mutex> lock(_mutex);
utf8_filesystem::stat st;
memset(&st, 0, sizeof(st));
if (utf8_filesystem::fstat(createLocalFilePath(_packageListFileName).c_str(), &st) == 0) {
return static_cast<int>(time(NULL) - st.st_mtime);
}
return std::numeric_limits<int>::max();
}
std::shared_ptr<PackageInfo> PackageManager::getServerPackage(const std::string& packageId) const {
std::vector<std::shared_ptr<PackageInfo> > packages = getServerPackages();
auto it = std::find_if(packages.begin(), packages.end(), [&packageId](const std::shared_ptr<PackageInfo>& packageInfo) {
return packageInfo->getPackageId() == packageId;
});
if (it == packages.end()) {
return std::shared_ptr<PackageInfo>();
}
return *it;
}
std::shared_ptr<PackageInfo> PackageManager::getLocalPackage(const std::string& packageId) const {
std::vector<std::shared_ptr<PackageInfo> > packages = getLocalPackages();
auto it = std::find_if(packages.begin(), packages.end(), [&packageId](const std::shared_ptr<PackageInfo>& packageInfo) {
return packageInfo->getPackageId() == packageId;
});
if (it == packages.end()) {
return std::shared_ptr<PackageInfo>();
}
return *it;
}
std::shared_ptr<PackageStatus> PackageManager::getLocalPackageStatus(const std::string& packageId, int version) const {
if (!_localDb) {
return std::shared_ptr<PackageStatus>();
}
try {
std::lock_guard<std::recursive_mutex> lock(_mutex);
// Check task queue first for the package
for (int taskId : _taskQueue->getTaskIds()) {
Task task = _taskQueue->getTask(taskId);
if (task.packageId == packageId && (version == -1 || task.packageVersion == version)) {
return std::make_shared<PackageStatus>(task.action, isTaskPaused(taskId), static_cast<float>(task.progress));
}
}
// Check if the package is ready
for (const std::shared_ptr<PackageInfo>& localPackage : getLocalPackages()) {
if (localPackage->getPackageId() == packageId && (version == -1 || localPackage->getVersion() == version)) {
return std::make_shared<PackageStatus>(PackageAction::PACKAGE_ACTION_READY, false, 100.0f);
}
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::getLocalPackageStatus: %s", ex.what());
}
// No local package, no task => no status
return std::shared_ptr<PackageStatus>();
}
void PackageManager::accessLocalPackages(const std::function<void(const std::map<std::shared_ptr<PackageInfo>, std::shared_ptr<PackageHandler> >&)>& callback) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
// Create instances to all open files
std::map<std::shared_ptr<PackageInfo>, std::shared_ptr<PackageHandler> > packageHandlerMap;
for (const std::shared_ptr<PackageInfo>& packageInfo : _localPackages) {
auto it = _packageHandlerCache.find(packageInfo);
if (it == _packageHandlerCache.end()) {
std::string fileName = createLocalFilePath(createPackageFileName(packageInfo->getPackageId(), packageInfo->getPackageType(), packageInfo->getVersion()));
auto handler = PackageHandlerFactory(_serverEncKey, _localEncKey).createPackageHandler(packageInfo->getPackageType(), fileName);
if (!handler) {
continue;
}
it = _packageHandlerCache.insert(std::make_pair(packageInfo, handler)).first;
}
packageHandlerMap[packageInfo] = it->second;
}
// Use the callback
callback(packageHandlerMap);
}
std::vector<std::shared_ptr<PackageInfo> > PackageManager::suggestPackages(const MapPos& mapPos, const std::shared_ptr<Projection>& projection) const {
if (!_localDb) {
return std::vector<std::shared_ptr<PackageInfo> >();
}
if (!projection) {
throw NullArgumentException("Null projection");
}
// Detect zoom level from tile masks
int zoom = 0;
for (const std::shared_ptr<PackageInfo>& packageInfo : getServerPackages()) {
zoom = std::max(zoom, packageInfo->getTileMask()->getMaxZoomLevel());
}
// Calculate map tile from the map position
MapTile mapTile = CalculateMapTile(mapPos, zoom, projection);
// Find tile statuses from all packages. Keep only packages where the tile exists
std::vector<std::pair<std::shared_ptr<PackageInfo>, PackageTileStatus::PackageTileStatus> > packageTileStatuses;
while (true) {
for (const std::shared_ptr<PackageInfo>& packageInfo : getServerPackages()) {
PackageTileStatus::PackageTileStatus status = packageInfo->getTileMask()->getTileStatus(mapTile);
if (status != PackageTileStatus::PACKAGE_TILE_STATUS_MISSING) {
packageTileStatuses.emplace_back(packageInfo, packageInfo->getTileMask()->getTileStatus(mapTile));
}
}
if (!packageTileStatuses.empty() || mapTile.getZoom() == 0) {
break;
}
mapTile = mapTile.getParent();
}
// Sort packages based on tile status and package size
std::sort(packageTileStatuses.begin(), packageTileStatuses.end(), [](const std::pair<std::shared_ptr<PackageInfo>, PackageTileStatus::PackageTileStatus>& package1, const std::pair<std::shared_ptr<PackageInfo>, PackageTileStatus::PackageTileStatus>& package2) {
if (package1.second != package2.second) {
return package1.second == PackageTileStatus::PACKAGE_TILE_STATUS_FULL;
}
return package1.first->getSize() < package2.first->getSize();
});
// Return the packages
std::vector<std::shared_ptr<PackageInfo> > packageInfos;
std::transform(packageTileStatuses.begin(), packageTileStatuses.end(), std::back_inserter(packageInfos), [](const std::pair<std::shared_ptr<PackageInfo>, PackageTileStatus::PackageTileStatus>& package) {
return package.first;
});
return packageInfos;
}
bool PackageManager::isAreaDownloaded(const MapBounds& mapBounds, int zoom, const std::shared_ptr<Projection>& projection) const {
if (!_localDb) {
return false;
}
if (!projection) {
throw NullArgumentException("Null projection");
}
// Get local packages
std::vector<std::shared_ptr<PackageInfo> > localPackages = getLocalPackages();
// Calculate tile extents
MapTile mapTile1 = CalculateMapTile(mapBounds.getMin(), zoom, projection);
MapTile mapTile2 = CalculateMapTile(mapBounds.getMax(), zoom, projection);
for (int y = std::min(mapTile1.getY(), mapTile2.getY()); y <= std::max(mapTile1.getY(), mapTile2.getY()); y++) {
for (int x = std::min(mapTile1.getX(), mapTile2.getX()); x <= std::max(mapTile1.getX(), mapTile2.getX()); x++) {
bool found = false;
for (std::size_t i = 0; i < localPackages.size(); i++) {
if (localPackages[i]->getTileMask()->getTileStatus(MapTile(x, y, zoom, 0)) == PackageTileStatus::PACKAGE_TILE_STATUS_FULL) {
std::rotate(localPackages.begin(), localPackages.begin() + i, localPackages.begin() + i + 1);
found = true;
break;
}
}
if (!found) {
return false;
}
}
}
return true;
}
bool PackageManager::startPackageListDownload() {
if (!_localDb) {
return false;
}
try {
Task downloadTask;
downloadTask.command = Task::DOWNLOAD_PACKAGE_LIST;
int taskId = _taskQueue->scheduleTask(downloadTask);
_taskQueue->setTaskPriority(taskId, std::numeric_limits<int>::max());
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_WAITING, 0);
_taskQueueCondition.notify_one();
return true;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::startPackageListDownload: %s", ex.what());
}
return false;
}
bool PackageManager::startPackageImport(const std::string& packageId, int version, const std::string& packageFileName) {
if (!_localDb) {
return false;
}
try {
Task importTask;
importTask.command = Task::IMPORT_PACKAGE;
importTask.packageId = packageId;
importTask.packageType = PackageHandlerFactory::DetectPackageType(packageFileName);
importTask.packageVersion = version;
importTask.packageLocation = packageFileName;
int taskId = _taskQueue->scheduleTask(importTask);
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_WAITING, 0);
_taskQueueCondition.notify_one();
return true;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::startPackageImport: %s", ex.what());
}
return false;
}
bool PackageManager::startPackageDownload(const std::string& packageId) {
if (!_localDb) {
return false;
}
try {
// Find server package
std::shared_ptr<PackageInfo> package;
for (const std::shared_ptr<PackageInfo>& serverPackage : getServerPackages()) {
if (serverPackage->getPackageId() == packageId) {
package = serverPackage;
}
}
if (!package) {
int currentVersion = 0;
std::shared_ptr<PackageInfo> localPackage = getLocalPackage(packageId);
if (localPackage) {
currentVersion = localPackage->getVersion();
}
package = getCustomPackage(packageId, currentVersion + 1);
if (!package) {
return false;
}
}
// Create download task
Task downloadTask;
downloadTask.command = Task::DOWNLOAD_PACKAGE;
downloadTask.packageId = package->getPackageId();
downloadTask.packageType = package->getPackageType();
downloadTask.packageVersion = package->getVersion();
downloadTask.packageLocation = package->getServerURL();
int taskId = _taskQueue->scheduleTask(downloadTask);
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_WAITING, 0);
_taskQueueCondition.notify_one();
return true;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::startPackageDownload: %s", ex.what());
}
return false;
}
void PackageManager::cancelPackageTasks(const std::string& packageId) {
if (!_localDb) {
return;
}
try {
for (int taskId : _taskQueue->getTaskIds()) {
Task task = _taskQueue->getTask(taskId);
if (task.packageId == packageId) {
_taskQueue->cancelTask(taskId);
updateTaskStatus(taskId, task.action, task.progress / 100.0f);
_taskQueueCondition.notify_one();
}
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::cancelPackageTasks: %s", ex.what());
}
}
bool PackageManager::startPackageRemove(const std::string& packageId) {
if (!_localDb) {
return false;
}
try {
// Find local package
std::shared_ptr<PackageInfo> package;
for (const std::shared_ptr<PackageInfo>& localPackage : getLocalPackages()) {
if (localPackage->getPackageId() == packageId) {
package = localPackage;
}
}
if (!package) {
return false;
}
// Cancel all previous tasks, as their results will be erased anyway
for (int taskId : _taskQueue->getTaskIds()) {
Task task = _taskQueue->getTask(taskId);
if (task.packageId == packageId) {
_taskQueue->cancelTask(taskId);
updateTaskStatus(taskId, task.action, task.progress / 100.0f);
}
}
// Add remove task
Task removeTask;
removeTask.command = Task::REMOVE_PACKAGE;
removeTask.packageId = package->getPackageId();
removeTask.packageType = package->getPackageType();
removeTask.packageVersion = package->getVersion();
int taskId = _taskQueue->scheduleTask(removeTask);
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_WAITING, 0);
_taskQueueCondition.notify_one();
return true;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::startPackageRemove: %s", ex.what());
}
return false;
}
void PackageManager::setPackagePriority(const std::string& packageId, int priority) {
if (!_localDb) {
return;
}
try {
for (int taskId : _taskQueue->getTaskIds()) {
Task task = _taskQueue->getTask(taskId);
if (task.packageId == packageId) {
_taskQueue->setTaskPriority(taskId, priority);
updateTaskStatus(taskId, task.action, task.progress / 100.0f);
_taskQueueCondition.notify_one();
}
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::setPackagePriority: %s", ex.what());
}
}
bool PackageManager::startStyleDownload(const std::string& styleName) {
if (!_localDb) {
return false;
}
try {
Task downloadTask;
downloadTask.command = Task::DOWNLOAD_STYLE;
downloadTask.packageId = styleName;
int taskId = _taskQueue->scheduleTask(downloadTask);
_taskQueue->setTaskPriority(taskId, std::numeric_limits<int>::max());
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_WAITING, 0);
_taskQueueCondition.notify_one();
return true;
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::startStyleDownload: %s", ex.what());
}
return false;
}
void PackageManager::run() {
try {
while (true) {
int taskId = -1;
{
std::unique_lock<std::recursive_mutex> lock(_mutex);
if (_stopped) {
break;
}
taskId = _taskQueue->getActiveTaskId();
if (taskId == -1) {
_taskQueueCondition.wait(lock);
continue;
}
}
try {
Task::Command command = _taskQueue->getTask(taskId).command;
bool success = false;
switch (command) {
case Task::NOP:
success = true;
break;
case Task::DOWNLOAD_PACKAGE_LIST:
success = downloadPackageList(taskId);
break;
case Task::DOWNLOAD_PACKAGE:
success = downloadPackage(taskId);
break;
case Task::IMPORT_PACKAGE:
success = importPackage(taskId);
break;
case Task::REMOVE_PACKAGE:
success = removePackage(taskId);
break;
case Task::DOWNLOAD_STYLE:
success = downloadStyle(taskId);
break;
}
if (success) {
setTaskFinished(taskId);
}
else {
setTaskFailed(taskId, PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM);
}
}
catch (const PauseException&) {
setTaskPaused(taskId);
Log::Info("PackageManager: Paused task");
}
catch (const CancelException&) {
setTaskCancelled(taskId);
Log::Info("PackageManager: Cancelled task");
}
catch (const PackageException& ex) {
setTaskFailed(taskId, ex.getErrorType());
Log::Errorf("PackageManager: Exception while executing task: %s", ex.what());
}
catch (const std::exception& ex) {
setTaskFailed(taskId, PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM);
Log::Errorf("PackageManager: Exception while executing task: %s", ex.what());
}
}
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager: Unexpected exception while handling tasks, shutting down: %s", ex.what());
}
}
bool PackageManager::downloadPackageList(int taskId) {
// Download package list data
std::vector<unsigned char> packageListData;
for (int retry = 0; true; retry++) {
if (retry > 0) {
packageListData.clear();
Log::Info("PackageManager: Retrying package list download");
}
int errorCode = DownloadFile(createPackageListURL(_packageListURL), [this, &packageListData, taskId](std::uint64_t offset, std::uint64_t length, const unsigned char* buf, std::size_t size) {
if (isTaskCancelled(taskId)) {
return false;
}
if (isTaskPaused(taskId)) {
return false;
}
if (packageListData.size() != offset) {
packageListData.resize(static_cast<size_t>(offset));
}
packageListData.insert(packageListData.end(), buf, buf + size);
return true;
});
if (errorCode == 0) {
break;
}
if (isTaskCancelled(taskId)) {
throw CancelException();
}
if (isTaskPaused(taskId)) {
throw PauseException();
}
if (retry > 0) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_CONNECTION, "Failed to download package list");
}
}
// Test if the data is gzipped, in that case inflate
std::vector<unsigned char> packageListDataTemp;
if (zlib::inflate_gzip(packageListData.data(), packageListData.size(), packageListDataTemp)) {
std::swap(packageListData, packageListDataTemp);
}
// Create JSON string
std::string packageListJson;
if (!packageListData.empty()) {
packageListJson.assign(reinterpret_cast<const char*>(&packageListData[0]), reinterpret_cast<const char*>(&packageListData[0] + packageListData.size()));
}
// Parse JSON, check that it is valid
rapidjson::Document packageListDoc;
if (packageListDoc.Parse<rapidjson::kParseDefaultFlags>(packageListJson.c_str()).HasParseError()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Error while parsing package list");
}
if (!packageListDoc.HasMember("packages")) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Package list does not contain package definitions");
}
// Check optional schema value. Always keep the schema up-to-date
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command delCmd(*_localDb, "DELETE FROM metadata WHERE name='schema'");
delCmd.execute();
if (packageListDoc.HasMember("schema")) {
sqlite3pp::command insCmd(*_localDb, "INSERT INTO metadata(name, value) VALUES('schema', :schema)");
insCmd.bind(":schema", packageListDoc["schema"].GetString());
insCmd.execute();
}
}
// Update package list file
savePackageListJson(_packageListFileName, packageListJson);
Log::Info("PackageManager: Package list updated");
return true;
}
bool PackageManager::importPackage(int taskId) {
Task task = _taskQueue->getTask(taskId);
// Check if the package is already imported
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT id FROM packages WHERE package_id=:package_id AND version=:version AND valid=1");
query.bind(":package_id", task.packageId.c_str());
query.bind(":version", task.packageVersion);
for (auto qit = query.begin(); qit != query.end(); qit++) {
Log::Infof("PackageManager: Package %s already imported", task.packageId.c_str());
return true;
}
}
std::string packageFileName = createLocalFilePath(createPackageFileName(task.packageId, task.packageType, task.packageVersion));
try {
// Determine file size, copy file
std::uint64_t fileSize = 0;
{
FILE* fpDestRaw = utf8_filesystem::fopen(packageFileName.c_str(), "wb");
if (!fpDestRaw) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not create file ") + packageFileName);
}
std::shared_ptr<FILE> fpDest(fpDestRaw, fclose);
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_COPYING, 0.0f);
std::string sourceURL = task.packageLocation;
if (sourceURL.find("://") == std::string::npos) {
sourceURL = "file://" + sourceURL;
}
URLFileLoader loader;
loader.setLocalFiles(true);
bool result = loader.stream(sourceURL, [&](std::uint64_t length, const unsigned char* buf, std::size_t size) {
if (isTaskCancelled(taskId)) {
return false;
}
if (fwrite(buf, sizeof(unsigned char), size, fpDest.get()) != size) {
Log::Errorf("PackageManager: Storage full? Could not write to package file %s", packageFileName.c_str());
return false;
}
fileSize += size;
if (length > 0) {
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_COPYING, static_cast<float>(fileSize) / static_cast<float>(length));
}
return true;
});
if (isTaskCancelled(taskId)) {
throw CancelException();
}
if (!result) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Failed to import package " + task.packageId);
}
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_COPYING, 1.0f);
}
// Find package tiles and calculate tile mask
std::string tileMaskValue;
if (auto handler = PackageHandlerFactory(_serverEncKey, _localEncKey).createPackageHandler(task.packageType, packageFileName)) {
tileMaskValue = EncodeTileMask(handler->calculateTileMask());
}
// Get package id
int id = -1;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query1(*_localDb, "SELECT id FROM packages WHERE package_id=:package_id AND version=:version");
query1.bind(":package_id", task.packageId.c_str());
query1.bind(":version", task.packageVersion);
for (auto qit = query1.begin(); qit != query1.end(); qit++) {
id = qit->get<int>(0);
}
if (id == -1) {
sqlite3pp::command command(*_localDb, "INSERT INTO packages(package_id, package_type, version, size, server_url, tile_mask, metainfo, valid) VALUES(:package_id, :package_type, :version, :size, '', :tile_mask, '', 0)");
command.bind(":package_id", task.packageId.c_str());
command.bind(":package_type", static_cast<int>(task.packageType));
command.bind(":version", task.packageVersion);
command.bind(":size", fileSize);
command.bind(":tile_mask", tileMaskValue.c_str());
command.execute();
id = static_cast<int>(_localDb->last_insert_rowid());
}
}
// Import package
importLocalPackage(id, taskId, task.packageId, task.packageType, packageFileName);
}
catch (...) {
utf8_filesystem::unlink(packageFileName.c_str());
throw;
}
Log::Infof("PackageManager: Package %s imported", task.packageId.c_str());
return true;
}
bool PackageManager::downloadPackage(int taskId) {
Task task = _taskQueue->getTask(taskId);
// Find the package info
std::shared_ptr<PackageInfo> package;
for (const std::shared_ptr<PackageInfo>& serverPackage : getServerPackages()) {
if (serverPackage->getPackageId() == task.packageId && serverPackage->getVersion() == task.packageVersion) {
package = serverPackage;
break;
}
}
if (!package) {
package = getCustomPackage(task.packageId, task.packageVersion);
if (!package) {
Log::Errorf("PackageManager: Failed to find package %s to download", task.packageId.c_str());
return false;
}
}
// Check if the package is already downloaded
bool downloaded = false;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT version FROM packages WHERE package_id=:package_id AND valid=1");
query.bind(":package_id", task.packageId.c_str());
for (auto qit = query.begin(); qit != query.end(); qit++) {
if (qit->get<int>(0) == task.packageVersion && task.packageVersion != -1) {
Log::Infof("PackageManager: Package %s already downloaded", task.packageId.c_str());
return true;
}
downloaded = true;
}
}
// Create new package file or reuse partly downloaded file
bool packageSizeIndeterminate = package->getSize() == 0;
std::string packageFileName = createLocalFilePath(createPackageFileName(task.packageId, task.packageType, task.packageVersion));
try {
// Try to download the package
for (int retry = 0; true; retry++) {
if (retry > 0) {
utf8_filesystem::unlink(packageFileName.c_str());
Log::Infof("PackageManager: Retrying package %s download", task.packageId.c_str());
}
FILE* fpRaw = utf8_filesystem::fopen(packageFileName.c_str(), "ab");
if (!fpRaw) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not create download package file ") + packageFileName);
}
std::shared_ptr<FILE> fp(fpRaw, fclose);
utf8_filesystem::fseek64(fp.get(), 0, SEEK_END);
std::uint64_t fileOffset = utf8_filesystem::ftell64(fp.get());
std::uint64_t fileSize = package->getSize();
if (!packageSizeIndeterminate && fileOffset == fileSize) {
break;
}
if (fileSize > 0) {
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_DOWNLOADING, static_cast<float>(fileOffset) / static_cast<float>(fileSize));
}
std::string packageURL = createPackageURL(task.packageId, task.packageVersion, task.packageLocation, downloaded);
if (packageURL.empty()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_NO_OFFLINE_PLAN, "Offline packages not available");
}
int errorCode = DownloadFile(packageURL, [this, fp, taskId, packageFileName, &fileOffset, fileSize](std::uint64_t offset, std::uint64_t length, const unsigned char* buf, std::size_t size) {
if (isTaskCancelled(taskId)) {
return false;
}
if (isTaskPaused(taskId)) {
return false;
}
if (offset != fileOffset) {
Log::Infof("PackageManager: Truncating file");
utf8_filesystem::fseek64(fp.get(), offset, SEEK_SET);
utf8_filesystem::ftruncate64(fp.get(), offset);
}
if (fwrite(buf, sizeof(unsigned char), size, fp.get()) != size) {
Log::Errorf("PackageManager: Storage full? Could not write to package file %s", packageFileName.c_str());
return false;
}
fileOffset = offset + size;
std::uint64_t realSize = fileSize;
if (fileSize == 0 && length != std::numeric_limits<std::uint64_t>::max()) {
realSize = length;
}
if (realSize > 0) {
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_DOWNLOADING, static_cast<float>(fileOffset) / static_cast<float>(realSize));
}
return true;
}, fileOffset);
if (errorCode == 0) {
if (packageSizeIndeterminate || fileOffset == fileSize) {
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_DOWNLOADING, 1.0f);
break;
}
Log::Errorf("PackageManager: File size mismatch for package %s (expected %lld, actual %lld)", task.packageId.c_str(), static_cast<long long>(fileSize), static_cast<long long>(fileOffset));
}
if (isTaskCancelled(taskId)) {
throw CancelException();
}
if (isTaskPaused(taskId)) {
throw PauseException();
}
if (retry > 0) {
switch (errorCode) {
case 402: // Payment required
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_DOWNLOAD_LIMIT_EXCEEDED, "Subscription limit exceeded while downloading: " + task.packageId);
case 403: // Forbidden
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_NO_OFFLINE_PLAN, "Offline packages not available");
break;
case 406: // Not acceptable
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_PACKAGE_TOO_BIG, "Package contains too many tiles: " + task.packageId);
break;
default:
throw PackageException(errorCode < 0 ? PackageErrorType::PACKAGE_ERROR_TYPE_CONNECTION : PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Failed to download package " + task.packageId);
}
}
}
// Get package id, create package record
int id = -1;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT id FROM packages WHERE package_id=:package_id AND version=:version");
query.bind(":package_id", task.packageId.c_str());
query.bind(":version", task.packageVersion);
for (auto qit = query.begin(); qit != query.end(); qit++) {
id = qit->get<int>(0);
}
if (id == -1) {
std::string metaInfo;
if (package->getMetaInfo()) {
metaInfo = package->getMetaInfo()->getVariant().toString();
}
std::string tileMaskValue;
if (package->getTileMask()) {
tileMaskValue = EncodeTileMask(package->getTileMask());
}
else if (auto handler = PackageHandlerFactory(_serverEncKey, _localEncKey).createPackageHandler(task.packageType, packageFileName)) {
tileMaskValue = EncodeTileMask(handler->calculateTileMask());
}
std::uint64_t fileSize = package->getSize();
if (packageSizeIndeterminate) {
FILE* fpRaw = utf8_filesystem::fopen(packageFileName.c_str(), "rb");
if (fpRaw) {
std::shared_ptr<FILE> fp(fpRaw, fclose);
utf8_filesystem::fseek64(fp.get(), 0, SEEK_END);
fileSize = utf8_filesystem::ftell64(fp.get());
}
}
sqlite3pp::command command(*_localDb, "INSERT INTO packages(package_id, package_type, version, size, server_url, tile_mask, metainfo, valid) VALUES(:package_id, :package_type, :version, :size, :server_url, :tile_mask, :metainfo, 0)");
command.bind(":package_id", package->getPackageId().c_str());
command.bind(":package_type", static_cast<int>(package->getPackageType()));
command.bind(":version", package->getVersion());
command.bind(":size", fileSize);
command.bind(":server_url", package->getServerURL().c_str());
command.bind(":tile_mask", tileMaskValue.c_str());
command.bind(":metainfo", metaInfo.c_str());
command.execute();
id = static_cast<int>(_localDb->last_insert_rowid());
}
}
// Import download package
importLocalPackage(id, taskId, task.packageId, task.packageType, packageFileName);
}
catch (const PauseException&) {
throw;
}
catch (const CancelException&) {
utf8_filesystem::unlink(packageFileName.c_str());
throw;
}
catch (...) {
utf8_filesystem::unlink(packageFileName.c_str());
throw;
}
Log::Infof("PackageManager: Package %s downloaded", task.packageId.c_str());
return true;
}
bool PackageManager::removePackage(int taskId) {
Task task = _taskQueue->getTask(taskId);
if (_taskQueue->isTaskCancelled(taskId)) {
throw CancelException();
}
// Find package id
int id = -1;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT id FROM packages WHERE package_id=:package_id AND version=:version");
query.bind(":package_id", task.packageId.c_str());
query.bind(":version", task.packageVersion);
for (auto qit = query.begin(); qit != query.end(); qit++) {
id = qit->get<int>(0);
}
}
if (id == -1) {
Log::Error("PackageManager: Failed to find package to remove");
return false;
}
// Delete package
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_REMOVING, 0);
deleteLocalPackage(id);
updateTaskStatus(taskId, PackageAction::PACKAGE_ACTION_REMOVING, 100);
Log::Infof("PackageManager: Package %s removed", task.packageId.c_str());
return true;
}
bool PackageManager::downloadStyle(int taskId) {
Task task = _taskQueue->getTask(taskId);
if (_taskQueue->isTaskCancelled(taskId)) {
throw CancelException();
}
if (updateStyle(task.packageId)) {
notifyStylesChanged();
}
return true;
}
void PackageManager::syncLocalPackages() {
if (!_localDb) {
return;
}
try {
std::lock_guard<std::recursive_mutex> lock(_mutex);
// Find all valid packages
std::vector<std::shared_ptr<PackageInfo> > packages;
sqlite3pp::query query(*_localDb, "SELECT package_id, package_type, version, size, server_url, tile_mask, metainfo FROM packages WHERE valid=1 ORDER BY id ASC");
for (auto qit = query.begin(); qit != query.end(); qit++) {
std::shared_ptr<PackageTileMask> tileMask;
if (strlen(qit->get<const char*>(5)) != 0) {
tileMask = DecodeTileMask(qit->get<const char*>(5));
}
std::shared_ptr<PackageMetaInfo> metaInfo;
if (strlen(qit->get<const char*>(6)) != 0) {
rapidjson::Document metaInfoDoc;
if (metaInfoDoc.Parse<rapidjson::kParseDefaultFlags>(qit->get<const char*>(6)).HasParseError()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Error while parsing meta info");
}
metaInfo = createPackageMetaInfo(metaInfoDoc);
}
auto packageInfo = std::make_shared<PackageInfo>(
qit->get<const char*>(0),
static_cast<PackageType::PackageType>(qit->get<int>(1)),
qit->get<int>(2),
qit->get<std::uint64_t>(3),
qit->get<const char*>(4),
tileMask,
metaInfo
);
packages.push_back(packageInfo);
}
// Update packages, sync caches
std::swap(_localPackages, packages);
_packageHandlerCache.clear();
}
catch (const std::exception& ex) {
Log::Errorf("PackageManager::syncLocalPackages: %s", ex.what());
}
}
void PackageManager::importLocalPackage(int id, int taskId, const std::string& packageId, PackageType::PackageType packageType, const std::string& packageFileName) {
// Invoke handler callback
if (auto handler = PackageHandlerFactory(_serverEncKey, _localEncKey).createPackageHandler(packageType, packageFileName)) {
handler->onImportPackage();
}
// Mark downloaded package as valid and older packages as invalid.
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command2(*_localDb, "UPDATE packages SET valid=(id=:id) WHERE package_id=:package_id");
command2.bind(":id", id);
command2.bind(":package_id", packageId.c_str());
command2.execute();
// Delete older invalid packages
sqlite3pp::query query(*_localDb, "SELECT id FROM packages WHERE package_id=:package_id AND valid=0");
query.bind(":package_id", packageId.c_str());
for (auto qit = query.begin(); qit != query.end(); qit++) {
int otherId = qit->get<int>(0);
deleteLocalPackage(otherId);
}
}
// Sync
syncLocalPackages();
notifyPackagesChanged();
}
void PackageManager::deleteLocalPackage(int id) {
std::string packageFileName;
PackageType::PackageType packageType = PackageType::PACKAGE_TYPE_MAP;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
// Get package file name
sqlite3pp::query query(*_localDb, "SELECT package_id, package_type, version FROM packages WHERE id=:id");
query.bind(":id", id);
for (auto qit = query.begin(); qit != query.end(); qit++) {
std::string packageId = qit->get<const char*>(0);
packageType = static_cast<PackageType::PackageType>(qit->get<int>(1));
int version = qit->get<int>(2);
packageFileName = createLocalFilePath(createPackageFileName(packageId, packageType, version));
}
if (packageFileName.empty()) {
return;
}
// Delete package from package list
sqlite3pp::command command(*_localDb, "DELETE FROM packages WHERE id=:id");
command.bind(":id", id);
command.execute();
}
// Sync
syncLocalPackages();
notifyPackagesChanged();
// Invoke handler callback
if (auto handler = PackageHandlerFactory(_serverEncKey, _localEncKey).createPackageHandler(packageType, packageFileName)) {
handler->onDeletePackage();
}
// Delete file
utf8_filesystem::unlink(packageFileName.c_str());
}
bool PackageManager::isTaskCancelled(int taskId) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _taskQueue->isTaskCancelled(taskId);
}
bool PackageManager::isTaskPaused(int taskId) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (_stopped) {
return true;
}
return _taskQueue->getActiveTaskId(taskId) != taskId;
}
void PackageManager::updateTaskStatus(int taskId, PackageAction::PackageAction action, float progress) {
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
int roundedProgress = std::min(100, std::max(0, static_cast<int>(progress * 100.0f)));
if (taskId == _prevTaskId && action == _prevAction && roundedProgress == _prevRoundedProgress) {
return;
}
_taskQueue->updateTaskStatus(taskId, action, progress);
_prevTaskId = taskId;
_prevAction = action;
_prevRoundedProgress = roundedProgress;
}
DirectorPtr<PackageManagerListener> packageManagerListener = _packageManagerListener;
if (packageManagerListener) {
Task task = _taskQueue->getTask(taskId);
switch (task.command) {
case Task::Command::DOWNLOAD_PACKAGE:
case Task::Command::IMPORT_PACKAGE:
if (std::shared_ptr<PackageStatus> status = getLocalPackageStatus(task.packageId, task.packageVersion)) {
packageManagerListener->onPackageStatusChanged(task.packageId, task.packageVersion, status);
}
break;
default:
break;
}
}
}
void PackageManager::setTaskFinished(int taskId) {
Task task = _taskQueue->getTask(taskId);
_taskQueue->deleteTask(taskId);
DirectorPtr<PackageManagerListener> packageManagerListener = _packageManagerListener;
if (packageManagerListener) {
switch (task.command) {
case Task::Command::DOWNLOAD_PACKAGE_LIST:
packageManagerListener->onPackageListUpdated();
break;
case Task::Command::DOWNLOAD_PACKAGE:
case Task::Command::IMPORT_PACKAGE:
case Task::Command::REMOVE_PACKAGE:
packageManagerListener->onPackageUpdated(task.packageId, task.packageVersion);
break;
case Task::Command::DOWNLOAD_STYLE:
packageManagerListener->onStyleUpdated(task.packageId);
break;
default:
break;
}
}
}
void PackageManager::setTaskPaused(int taskId) {
Task task = _taskQueue->getTask(taskId);
DirectorPtr<PackageManagerListener> packageManagerListener = _packageManagerListener;
if (packageManagerListener) {
switch (task.command) {
case Task::Command::DOWNLOAD_PACKAGE:
case Task::Command::IMPORT_PACKAGE:
case Task::Command::REMOVE_PACKAGE:
if (std::shared_ptr<PackageStatus> status = getLocalPackageStatus(task.packageId, task.packageVersion)) {
packageManagerListener->onPackageStatusChanged(task.packageId, task.packageVersion, status);
}
break;
default:
break;
}
}
}
void PackageManager::setTaskCancelled(int taskId) {
Task task = _taskQueue->getTask(taskId);
_taskQueue->deleteTask(taskId);
DirectorPtr<PackageManagerListener> packageManagerListener = _packageManagerListener;
if (packageManagerListener) {
switch (task.command) {
case Task::Command::DOWNLOAD_PACKAGE:
case Task::Command::IMPORT_PACKAGE:
case Task::Command::REMOVE_PACKAGE:
packageManagerListener->onPackageCancelled(task.packageId, task.packageVersion);
break;
default:
break;
}
}
}
void PackageManager::setTaskFailed(int taskId, PackageErrorType::PackageErrorType errorType) {
Task task = _taskQueue->getTask(taskId);
_taskQueue->deleteTask(taskId);
DirectorPtr<PackageManagerListener> packageManagerListener = _packageManagerListener;
if (packageManagerListener) {
switch (task.command) {
case Task::Command::DOWNLOAD_PACKAGE_LIST:
packageManagerListener->onPackageListFailed();
break;
case Task::Command::DOWNLOAD_PACKAGE:
case Task::Command::IMPORT_PACKAGE:
case Task::Command::REMOVE_PACKAGE:
packageManagerListener->onPackageFailed(task.packageId, task.packageVersion, errorType);
break;
case Task::Command::DOWNLOAD_STYLE:
packageManagerListener->onStyleFailed(task.packageId);
break;
default:
break;
}
}
}
std::string PackageManager::createLocalFilePath(const std::string& name) const {
std::string fileName = _dataFolder;
if (!fileName.empty()) {
char c = fileName[fileName.size() - 1];
if (c != '/' && c != '\\') {
fileName.append("/");
}
}
fileName.append("__Nuti_pkgmgr_" + name);
return fileName;
}
std::string PackageManager::createPackageFileName(const std::string& packageId, PackageType::PackageType packageType, int version) const {
return packageId + "." + boost::lexical_cast<std::string>(version) + PackageHandlerFactory::GetPackageTypeExtension(packageType);
}
std::string PackageManager::createPackageListURL(const std::string& baseURL) const {
return baseURL;
}
std::string PackageManager::createPackageURL(const std::string& packageId, int version, const std::string& baseURL, bool downloaded) const {
return baseURL;
}
std::shared_ptr<PackageInfo> PackageManager::getCustomPackage(const std::string& packageId, int version) const {
return std::shared_ptr<PackageInfo>();
}
bool PackageManager::updateStyle(const std::string& styleName) {
return false;
}
void PackageManager::notifyPackagesChanged() {
std::vector<std::shared_ptr<OnChangeListener> > onChangeListeners;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
onChangeListeners = _onChangeListeners;
}
for (const std::shared_ptr<OnChangeListener>& onChangeListener : onChangeListeners) {
onChangeListener->onPackagesChanged();
}
}
void PackageManager::notifyStylesChanged() {
std::vector<std::shared_ptr<OnChangeListener> > onChangeListeners;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
onChangeListeners = _onChangeListeners;
}
for (const std::shared_ptr<OnChangeListener>& onChangeListener : onChangeListeners) {
onChangeListener->onStylesChanged();
}
}
std::string PackageManager::loadPackageListJson(const std::string& jsonFileName) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
std::string packageListFileName = createLocalFilePath(jsonFileName);
FILE* fpRaw = utf8_filesystem::fopen(packageListFileName.c_str(), "rb");
if (!fpRaw) {
return std::string();
}
std::shared_ptr<FILE> fp(fpRaw, fclose);
std::string json;
while (!feof(fp.get())) {
char buf[4096];
std::size_t n = fread(buf, sizeof(char), sizeof(buf) / sizeof(char), fp.get());
if (n == 0) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not open read package list file ") + packageListFileName);
}
json.append(buf, n);
}
return json;
}
void PackageManager::savePackageListJson(const std::string& jsonFileName, const std::string& json) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
std::string packageListFileName = createLocalFilePath(jsonFileName);
std::string tempPackageListFileName = createLocalFilePath(jsonFileName + ".tmp");
FILE* fpRaw = utf8_filesystem::fopen(tempPackageListFileName.c_str(), "wb");
if (!fpRaw) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not create package list file ") + tempPackageListFileName);
}
std::shared_ptr<FILE> fp(fpRaw, fclose);
if (fwrite(json.data(), sizeof(char), json.size(), fp.get()) != json.size()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not write to package list file ") + tempPackageListFileName);
}
fp.reset();
utf8_filesystem::unlink(packageListFileName.c_str());
if (utf8_filesystem::rename(tempPackageListFileName.c_str(), packageListFileName.c_str()) != 0) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, std::string("Could not rename package list file ") + tempPackageListFileName);
}
_serverPackageCache.reset();
}
void PackageManager::InitializeDb(sqlite3pp::database& db, const std::string& encKey) {
db.execute("PRAGMA encoding='UTF-8'");
db.execute(R"SQL(
CREATE TABLE IF NOT EXISTS packages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
package_id TEXT NOT NULL,
package_type INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL,
size INTEGER NOT NULL,
server_url TEXT NOT NULL,
tile_mask TEXT NOT NULL,
metainfo TEXT NOT NULL,
valid INTEGER NOT NULL DEFAULT 0
))SQL");
db.execute(R"SQL(
CREATE TABLE IF NOT EXISTS metadata(
name TEXT,
value TEXT
))SQL");
db.execute("CREATE INDEX IF NOT EXISTS packages_package_id ON packages(package_id)");
std::string dbHash;
sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='nutikeysha1'");
for (auto qit = query.begin(); qit != query.end(); qit++) {
dbHash = qit->get<const char*>(0);
}
if (dbHash.empty()) {
if (!encKey.empty()) {
std::string sha1 = CalculateKeyHash(encKey);
sqlite3pp::command command(db, "INSERT INTO metadata(name, value) VALUES('nutikeysha1', :hash)");
command.bind(":hash", sha1.c_str());
command.execute();
}
}
else {
CheckDbEncryption(db, encKey);
}
}
bool PackageManager::CheckDbEncryption(sqlite3pp::database& db, const std::string& encKey) {
sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='nutikeysha1'");
for (auto qit = query.begin(); qit != query.end(); qit++) {
if (encKey.empty()) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Package database is encrypted and needs encryption key");
}
std::string sha1 = qit->get<const char*>(0);
if (sha1 != CalculateKeyHash(encKey)) {
throw PackageException(PackageErrorType::PACKAGE_ERROR_TYPE_SYSTEM, "Package encryption keys do not match");
}
return true;
}
return false;
}
std::string PackageManager::CalculateKeyHash(const std::string& encKey) {
CryptoPP::SHA1 hash;
unsigned char digest[CryptoPP::SHA1::DIGESTSIZE];
hash.CalculateDigest(digest, reinterpret_cast<const unsigned char*>(encKey.c_str()), encKey.size());
std::string sha1;
CryptoPP::HexEncoder encoder;
encoder.Attach(new CryptoPP::StringSink(sha1));
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
return sha1;
}
MapTile PackageManager::CalculateMapTile(const MapPos& mapPos, int zoom, const std::shared_ptr<Projection>& proj) {
EPSG3857 epsg3857;
double tileWidth = epsg3857.getBounds().getDelta().getX() / (1 << zoom);
double tileHeight = epsg3857.getBounds().getDelta().getY() / (1 << zoom);
MapVec mapVec = epsg3857.fromWgs84(proj->toWgs84(mapPos)) - epsg3857.getBounds().getMin();
int x = static_cast<int>(std::floor(mapVec.getX() / tileWidth));
int y = static_cast<int>(std::floor(mapVec.getY() / tileHeight));
return MapTile(x, y, zoom, 0);
}
std::shared_ptr<PackageTileMask> PackageManager::DecodeTileMask(const std::string& tileMaskStr) {
std::vector<std::string> parts = GeneralUtils::Split(tileMaskStr, ':');
if (parts.empty()) {
return std::shared_ptr<PackageTileMask>();
}
int zoomLevel = DEFAULT_TILEMASK_ZOOMLEVEL;
if (parts.size() > 1) {
zoomLevel = boost::lexical_cast<int>(parts[1]);
}
return std::make_shared<PackageTileMask>(parts[0], zoomLevel);
}
std::string PackageManager::EncodeTileMask(const std::shared_ptr<PackageTileMask>& tileMask) {
if (!tileMask) {
return std::string();
}
return tileMask->getStringValue() + ":" + boost::lexical_cast<std::string>(tileMask->getMaxZoomLevel());
}
int PackageManager::DownloadFile(const std::string& url, NetworkUtils::HandlerFunc handler, std::uint64_t offset) {
Log::Debugf("PackageManager::DownloadFile: %s", url.c_str());
std::map<std::string, std::string> requestHeaders = NetworkUtils::CreateAppRefererHeader();
std::map<std::string, std::string> responseHeaders;
return NetworkUtils::StreamHTTPResponse("GET", url, requestHeaders, responseHeaders, handler, offset, Log::IsShowDebug());
}
PackageManager::PersistentTaskQueue::PersistentTaskQueue(const std::string& dbFileName) {
_localDb = std::make_shared<sqlite3pp::database>(dbFileName.c_str());
_localDb->execute("PRAGMA encoding='UTF-8'");
_localDb->execute(R"SQL(
CREATE TABLE IF NOT EXISTS manager_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
command INTEGER NOT NULL,
priority INTEGER NOT NULL DEFAULT 0,
cancelled INTEGER NOT NULL DEFAULT 0,
action INTEGER NOT NULL DEFAULT 0,
progress INTEGER NOT NULL DEFAULT 0,
package_id TEXT,
package_version INTEGER,
package_type INTEGER DEFAULT 0,
package_location TEXT
))SQL");
_localDb->execute("CREATE INDEX IF NOT EXISTS manager_tasks_package_id ON manager_tasks(package_id)");
}
int PackageManager::PersistentTaskQueue::getActiveTaskId(int currentActiveTaskId) const {
// Find task with highest priority. Do not process paused tasks (priority < 0) unless they are cancelled. Cancelled tasks should be always processed.
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT id, package_id, (CASE WHEN id=:active_id THEN -1 ELSE id END) as ordering FROM manager_tasks WHERE priority>=0 OR cancelled=1 ORDER BY priority DESC, ordering ASC LIMIT 1");
query.bind(":active_id", currentActiveTaskId);
for (auto qit = query.begin(); qit != query.end(); qit++) {
int taskId = qit->get<int>(0);
const char* packageId = qit->get<const char*>(1);
if (!packageId) {
return taskId;
}
// This is a package task - package tasks have to be processed in-order, so take the first task with the same package (even if it is paused).
sqlite3pp::query query2(*_localDb, "SELECT id FROM manager_tasks WHERE package_id=:package_id ORDER BY id ASC LIMIT 1");
query2.bind(":package_id", packageId);
for (auto qit2 = query2.begin(); qit2 != query2.end(); qit2++) {
return qit2->get<int>(0);
}
}
return -1;
}
std::vector<int> PackageManager::PersistentTaskQueue::getTaskIds() const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT id FROM manager_tasks");
std::vector<int> taskIds;
for (auto qit = query.begin(); qit != query.end(); qit++) {
taskIds.push_back(qit->get<int>(0));
}
return taskIds;
}
PackageManager::Task PackageManager::PersistentTaskQueue::getTask(int taskId) const {
Task task;
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT command, priority, action, progress, package_id, package_type, package_version, package_location FROM manager_tasks WHERE id=:task_id");
query.bind(":task_id", taskId);
for (auto qit = query.begin(); qit != query.end(); qit++) {
task.command = static_cast<Task::Command>(qit->get<int>(0));
task.priority = qit->get<int>(1);
task.action = static_cast<PackageAction::PackageAction>(qit->get<int>(2));
task.progress = qit->get<int>(3);
task.packageId = qit->get<const char*>(4);
task.packageType = static_cast<PackageType::PackageType>(qit->get<int>(5));
task.packageVersion = qit->get<int>(6);
task.packageLocation = qit->get<const char*>(7);
}
return task;
}
int PackageManager::PersistentTaskQueue::scheduleTask(const Task& task) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command(*_localDb, "INSERT INTO manager_tasks(command, action, progress, package_id, package_type, package_version, package_location) VALUES(:command, :action, :progress, :package_id, :package_type, :package_version, :package_location)");
command.bind(":command", static_cast<int>(task.command));
command.bind(":action", static_cast<int>(task.action));
command.bind(":progress", task.progress);
command.bind(":package_id", task.packageId.c_str());
command.bind(":package_type", static_cast<int>(task.packageType));
command.bind(":package_version", task.packageVersion);
command.bind(":package_location", task.packageLocation.c_str());
command.execute();
int taskId = static_cast<int>(_localDb->last_insert_rowid());
return taskId;
}
bool PackageManager::PersistentTaskQueue::isTaskCancelled(int taskId) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::query query(*_localDb, "SELECT cancelled FROM manager_tasks WHERE id=:task_id");
query.bind(":task_id", taskId);
for (auto qit = query.begin(); qit != query.end(); qit++) {
return qit->get<bool>(0);
}
return true;
}
void PackageManager::PersistentTaskQueue::cancelTask(int taskId) {
// NOTE: cancelled tasks still need to be processed, do not delete them
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command(*_localDb, "UPDATE manager_tasks SET cancelled=1, priority=1000000 WHERE id=:task_id");
command.bind(":task_id", taskId);
command.execute();
}
void PackageManager::PersistentTaskQueue::setTaskPriority(int taskId, int priority) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command(*_localDb, "UPDATE manager_tasks SET priority=:priority WHERE id=:task_id");
command.bind(":task_id", taskId);
command.bind(":priority", priority);
command.execute();
}
void PackageManager::PersistentTaskQueue::updateTaskStatus(int taskId, PackageAction::PackageAction action, float progress) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command(*_localDb, "UPDATE manager_tasks SET action=:action, progress=:progress WHERE id=:task_id");
command.bind(":task_id", taskId);
command.bind(":action", static_cast<int>(action));
command.bind(":progress", std::min(100, std::max(0, static_cast<int>(progress * 100.0f))));
command.execute();
}
void PackageManager::PersistentTaskQueue::deleteTask(int taskId) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
sqlite3pp::command command(*_localDb, "DELETE FROM manager_tasks WHERE id=:task_id");
command.bind(":task_id", taskId);
command.execute();
}
const int PackageManager::DEFAULT_TILEMASK_ZOOMLEVEL = 14;
}
#endif
| 44.066548 | 268 | 0.581846 | mostafa-j13 |
13041ee6b66fcc3f18590ff0753acb866e4b78cc | 1,453 | cpp | C++ | higan/fc/cartridge/board/konami-vrc4.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 3 | 2016-03-23T01:17:36.000Z | 2019-10-25T06:41:09.000Z | higan/fc/cartridge/board/konami-vrc4.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | higan/fc/cartridge/board/konami-vrc4.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | struct KonamiVRC4 : Board {
KonamiVRC4(Markup::Node& document) : Board(document), vrc4(*this) {
settings.pinout.a0 = 1 << document["board/chip/pinout/a0"].natural();
settings.pinout.a1 = 1 << document["board/chip/pinout/a1"].natural();
}
auto main() -> void {
return vrc4.main();
}
auto prg_read(uint addr) -> uint8 {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return prgram.read(addr);
return prgrom.read(vrc4.prg_addr(addr));
}
auto prg_write(uint addr, uint8 data) -> void {
if(addr < 0x6000) return;
if(addr < 0x8000) return prgram.write(addr, data);
bool a0 = (addr & settings.pinout.a0);
bool a1 = (addr & settings.pinout.a1);
addr &= 0xfff0;
addr |= (a1 << 1) | (a0 << 0);
return vrc4.reg_write(addr, data);
}
auto chr_read(uint addr) -> uint8 {
if(addr & 0x2000) return ppu.ciram_read(vrc4.ciram_addr(addr));
return Board::chr_read(vrc4.chr_addr(addr));
}
auto chr_write(uint addr, uint8 data) -> void {
if(addr & 0x2000) return ppu.ciram_write(vrc4.ciram_addr(addr), data);
return Board::chr_write(vrc4.chr_addr(addr), data);
}
auto power() -> void {
vrc4.power();
}
auto reset() -> void {
vrc4.reset();
}
auto serialize(serializer& s) -> void {
Board::serialize(s);
vrc4.serialize(s);
}
struct Settings {
struct Pinout {
uint a0;
uint a1;
} pinout;
} settings;
VRC4 vrc4;
};
| 24.216667 | 74 | 0.614591 | ameer-bauer |
13043340800ae1244402952870fed76f1fbbb04c | 37,924 | cpp | C++ | cavelock/Hap/HapHttp.cpp | cavecafe/cavelock | 5b015ecaa738ab782f7bef99fdb1c24a6cabf0bd | [
"MIT"
] | null | null | null | cavelock/Hap/HapHttp.cpp | cavecafe/cavelock | 5b015ecaa738ab782f7bef99fdb1c24a6cabf0bd | [
"MIT"
] | null | null | null | cavelock/Hap/HapHttp.cpp | cavecafe/cavelock | 5b015ecaa738ab782f7bef99fdb1c24a6cabf0bd | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2019 Gera Kazakov
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 "Hap.h"
namespace Hap
{
namespace Http
{
const char* ContentTypeJson = "application/hap+json";
const char* ContentTypeTlv8 = "application/pairing+tlv8";
const char* Username = "Pair-Setup";
// current pairing session - only one simultaneous pairing is allowed
Srp::Verifier ver; // SRP verifier //TODO: pre-calculate and store in config data
Srp::Host srp(ver); // .active()=true - pairing in progress, only one pairing at a time
uint8_t srp_auth_count = 0; // auth attempts counter
// Open
// returns new session ID, 0..sid_max, or sid_invalid
sid_t Server::Open()
{
for (sid_t sid = 0; sid < sizeofarr(_sess); sid++)
{
if (_sess[sid].isOpen())
continue;
// open session - use same buffers for all sessions
_sess[sid].Open(sid, &_buf);
// open database
_db.Open(sid);
return sid;
}
return sid_invalid;
}
// Close
// returns true if opened session was closed
bool Server::Close(sid_t sid)
{
if (sid > sid_max)
return false;
if (!_sess[sid].isOpen())
return false;
_db.Close(sid);
_sess[sid].Close();
// cancel current pairing if any
if (srp.active(sid))
srp.close(sid);
return true;
}
bool Server::Process(sid_t sid, Recv recv, Send send)
{
if (sid > MaxHttpSessions) // invalid sid
return false;
Session* sess = &_sess[sid];
bool secured = sess->secured;
Log::Msg("Http::Process Ses %d secured %d %s\n", sid, sess->secured, sess->ios ? (sess->ios->perm == Hap::Controller::Admin ? "admin" : "user") : "?");
if (sid == MaxHttpSessions) // too many sessions
{
// TODO: read request, create error response
send(sid, sess->rsp.buf(), sess->rsp.len());
return false;
}
// prepare for request parsing
sess->Init();
// read and parse the HTTP request
uint16_t len = 0; // total len of valid data received so far
uint16_t http_len = 0; // current length of http request
while (true)
{
uint8_t* req = sess->data() + len;
uint16_t req_len = sess->sizeofdata() - len;
// read next portion of the request
int l = recv(sid, (char*)req, req_len);
if (l < 0) // read error
{
Log::Err("Http: Read Error %d\n", l);
return false;
}
if (l == 0)
{
Log::Msg("Http: Read EOF\n");
return false;
}
len += l;
if (sess->secured)
{
// it session is secured, decrypt the block - when the whole block is received
// max length of http data that can be processed is defined by MaxHttpFrame/MaxHttpBlock
if (len < 2) // wait fot at least two bytes of data length
continue;
uint8_t *p = sess->data();
uint16_t aad = p[0] + ((uint16_t)(p[1]) << 8); // data length, also serves as AAD for decryption
if (aad > MaxHttpBlock)
{
Log::Err("Http: encrypted block size is too big: %d\n", aad);
return false;
}
if (len < 2 + aad + 16) // wait for complete encrypted block
continue;
// ensure the new portion of data fits into the request buffer
if (http_len + aad > sess->req.size() - 16) // leave room for 16-bit tag
{
Log::Err("Http: encrypted request is too big: %d + %d = %d\n", http_len, aad, http_len + aad);
return false;
}
// make 96-bit nonce from receive sequential number
uint8_t nonce[12];
memset(nonce, 0, sizeof(nonce));
memcpy(nonce + 4, &sess->recvSeq, 8);
// decrypt into request buffer
uint8_t* b = (uint8_t*)sess->req.buf() + http_len;
Crypto::Aead aead(Crypto::Aead::Decrypt,
b, b + aad, // output data and tag positions
sess->ControllerToAccessoryKey, // decryption key
nonce,
p + 2, aad, // encrypted data
p, 2 // aad
);
sess->recvSeq++;
// compare passed in and calculated tags
if (memcmp(b + aad, p + 2 + aad, 16) != 0)
{
Log::Err("Http: decrypt error\n");
return false;
}
http_len += aad;
// if there is more data after encypted block
// move it to block start
if (len > 2 + aad + 16)
{
len -= 2 + aad + 16;
b = (uint8_t*)sess->req.buf();
memmove(b, b + 2 + aad + 16, len);
}
}
else // unsequred session
{
// ensure the new portion of data fits into the request buffer
if (http_len + len > sess->req.size())
{
Log::Err("Http: request is too big: %d + %d = %d\n", http_len, len, http_len + len);
return false;
}
// copy received data into request buffer as is
memcpy(sess->req.buf() + http_len, sess->data(), len);
http_len += len;
len = 0;
}
// try parsing HTTP request
auto status = sess->req.parse(http_len);
if (status == sess->req.Error) // parser error
{
// send response 'Internal server error'
sess->rsp.start(HTTP_500);
sess->rsp.end();
send(sid, sess->rsp.buf(), sess->rsp.len());
return false;
}
if (status == sess->req.Success)
// request parsed, stop reading
break;
// status = Incomplete -> read more data
}
auto m = sess->req.method();
Log::Msg("Method: '%.*s'\n", m.l(), m.p());
auto p = sess->req.path();
Log::Msg("Path: '%.*s'\n", p.l(), p.p());
auto d = sess->req.data();
for (uint32_t i = 0; i < sess->req.hdr_count(); i++)
{
auto n = sess->req.hdr_name(i);
auto v = sess->req.hdr_value(i);
Log::Msg("%.*s: '%.*s'\n", n.l(), n.p(), v.l(), v.p());
}
if (m.l() == 4 && strncmp(m.p(), "POST", 4) == 0)
{
// POST
// /identify
// /pair-setup
// /pair-verify
// /pairings
if (p.l() == 9 && strncmp(p.p(), "/identify", 9) == 0)
{
if (_pairings.Count() == 0)
{
Log::Msg("Http: Exec unpaired identify\n");
sess->rsp.start(HTTP_204);
sess->rsp.end();
}
else
{
Log::Msg("Http: Unpaired identify prohibited when paired\n");
sess->rsp.start(HTTP_400);
sess->rsp.add(ContentType, ContentTypeJson);
sess->rsp.end("{\"status\":-70401}");
}
}
else if (p.l() == 11 && strncmp(p.p(), "/pair-setup", 11) == 0)
{
int len;
if (!sess->req.hdr(ContentType, ContentTypeTlv8))
{
Log::Msg("Http: Unknown or missing ContentType\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentLength, len))
{
Log::Err("Http: Unknown or missing ContentLength\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
sess->tlvi.parse(d.p(), d.l());
Log::Msg("PairSetup: TLV item count %d\n", sess->tlvi.count());
Tlv::State state;
if (!sess->tlvi.get(Tlv::Type::State, state))
{
Log::Msg("PairSetup: State not found\n");
}
else
{
switch (state)
{
case Tlv::State::M1:
_pairSetup1(sess);
break;
case Tlv::State::M3:
_pairSetup3(sess);
break;
case Tlv::State::M5:
_pairSetup5(sess);
break;
default:
Log::Err("PairSetup: Unknown state %d\n", (int)state);
}
}
}
}
else if (p.l() == 12 && strncmp(p.p(), "/pair-verify", 12) == 0)
{
int len;
if (!sess->req.hdr(ContentType, ContentTypeTlv8))
{
Log::Err("Http: Unknown or missing ContentType\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentLength, len))
{
Log::Err("Http: Unknown or missing ContentLength\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
sess->tlvi.parse(d.p(), d.l());
Log::Msg("PairVerify: TLV item count %d\n", sess->tlvi.count());
Tlv::State state;
if (!sess->tlvi.get(Tlv::Type::State, state))
{
Log::Err("PairVerify: State not found\n");
}
else
{
switch (state)
{
case Tlv::State::M1:
_pairVerify1(sess);
break;
case Tlv::State::M3:
_pairVerify3(sess);
secured = sess->ios != nullptr;
break;
default:
Log::Err("PairVerify: Unknown state %d\n", (int)state);
}
}
}
}
else if (p.l() == 9 && strncmp(p.p(), "/pairings", 9) == 0)
{
int len;
if (!sess->secured)
{
Log::Err("Http: Authorization required\n");
sess->rsp.start(HTTP_470);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentType, ContentTypeTlv8))
{
Log::Err("Http: Unknown or missing ContentType\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentLength, len))
{
Log::Err("Http: Unknown or missing ContentLength\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
sess->tlvi.parse(d.p(), d.l());
Log::Msg("Pairings: TLV item count %d\n", sess->tlvi.count());
Tlv::State state;
if (!sess->tlvi.get(Tlv::Type::State, state))
{
Log::Err("Pairings: State not found\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
if(state != Tlv::State::M1)
{
Log::Err("Pairings: Invalid State\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
Tlv::Method method;
if (!sess->tlvi.get(Tlv::Type::Method, method))
{
Log::Err("Pairings: Method not found\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
switch (method)
{
case Tlv::Method::AddPairing:
_pairingAdd(sess);
break;
case Tlv::Method::RemovePairing:
_pairingRemove(sess);
break;
case Tlv::Method::ListPairing:
_pairingList(sess);
break;
default:
Log::Err("Pairings: Unknown method\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
}
}
}
}
}
else
{
Log::Err("Http: Unknown path %.*s\n", p.l(), p.p());
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
}
else if (m.l() == 3 && strncmp(m.p(), "GET", 3) == 0)
{
// GET
// /accessories
// /characteristics
if (!sess->secured)
{
Log::Err("Http: Authorization required\n");
sess->rsp.start(HTTP_470);
sess->rsp.end();
}
else if (p.l() == 12 && strncmp(p.p(), "/accessories", 12) == 0)
{
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeJson);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
int len = _db.getDb(sess->Sid(), sess->rsp.data(), sess->rsp.size());
Log::Dbg("Db: '%.*s'\n", len, sess->rsp.data());
sess->rsp.setContentLength(len);
}
else if(strncmp(p.p(), "/characteristics?", 17) == 0)
{
int len = sess->sizeofdata();
auto status = _db.Read(sess->Sid(), p.p() + 17, p.l() - 17, (char*)sess->data(), len);
Log::Msg("Read: Status %d '%.*s'\n", status, len, sess->data());
sess->rsp.start(status);
if (len > 0)
{
sess->rsp.add(ContentType, ContentTypeJson);
sess->rsp.end((const char*)sess->data(), len);
}
else
{
sess->rsp.end();
}
}
else
{
Log::Err("Http: Unknown path %.*s\n", p.l(), p.p());
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
}
else if (m.l() == 3 && strncmp(m.p(), "PUT", 3) == 0)
{
// PUT
// /characteristics
if (p.l() == 16 && strncmp(p.p(), "/characteristics", 16) == 0)
{
int len;
if (!sess->secured)
{
Log::Err("Http: Authorization required\n");
sess->rsp.start(HTTP_470);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentType, ContentTypeJson))
{
Log::Err("Http: Unknown or missing ContentType\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else if (!sess->req.hdr(ContentLength, len))
{
Log::Err("Http: Unknown or missing ContentLength\n");
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
else
{
Log::Msg("Http: %.*s\n", d.l(), d.p());
int len = sess->sizeofdata();
auto status = _db.Write(sess->Sid(), (const char*)d.p(), d.l(), (char*)sess->data(), len);
Log::Msg("Write: Status %d '%.*s'\n", status, len, sess->data());
sess->rsp.start(status);
if (len > 0)
{
sess->rsp.add(ContentType, ContentTypeJson);
sess->rsp.end((const char*)sess->data(), len);
}
else
{
sess->rsp.end();
}
}
}
else
{
Log::Err("Http: Unknown path %.*s\n", p.l(), p.p());
sess->rsp.start(HTTP_400);
sess->rsp.end();
}
}
if (!_send(sess, send))
return false;
sess->secured = secured;
Log::Msg("Http::Process exit Ses %d secured %d\n", sid, sess->secured);
return true;
}
void Server::Poll(sid_t sid, Send send)
{
Session* sess = &_sess[sid];
if (!sess->secured)
return;
int len = sess->sizeofdata();
auto status = _db.getEvents(sid, (char*)sess->data(), len);
if (status != Http::Status::HTTP_200)
return;
if (len == 0)
return;
Log::Msg("Events: sid %d '%.*s'\n", sid, len, sess->data());
sess->rsp.event(status);
sess->rsp.add(ContentType, ContentTypeJson);
sess->rsp.end((const char*)sess->data(), len);
_send(sess, send);
}
bool Server::_send(Session* sess, Send& send)
{
if (sess->secured)
{
// session secured - encrypt data
const uint8_t *p = (uint8_t*)sess->rsp.buf();
uint16_t len = sess->rsp.len(); // data length
while (len > 0)
{
uint16_t aad = len; // block length, and AAD for encryption
if (aad > MaxHttpBlock)
aad = MaxHttpBlock;
// make 96-bit nonce from send sequential number
uint8_t nonce[12];
memset(nonce, 0, sizeof(nonce));
memcpy(nonce + 4, &sess->sendSeq, 8);
// encrypt into sess->data buffer which must be >= MaxHttpFrame
uint8_t* b = sess->data();
// copy data length into output buffer
b[0] = aad & 0xFF;
b[1] = (aad >> 8) & 0xFF;
Crypto::Aead aead(Crypto::Aead::Encrypt,
b + 2, b + 2 + aad, // output data and tag positions
sess->AccessoryToControllerKey, // encryption key
nonce,
p, aad, // data to encrypt
b, 2 // aad
);
sess->sendSeq++;
// send encrypted block
send(sess->Sid(), (char*)b, 2 + aad + 16);
len -= aad;
p += aad;
}
}
else
{
//send response as is
send(sess->Sid(), sess->rsp.buf(), sess->rsp.len());
}
return true;
}
void Server::_pairSetup1(Session* sess)
{
Log::Msg("PairSetupM1\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M2);
// verify that valid Method is present in input TLV
Tlv::Method method;
if (!sess->tlvi.get(Tlv::Type::Method, method))
{
Log::Err("PairSetupM1: Method not found\n");
goto RetErr;
}
if (method != Tlv::Method::PairSetupNonMfi)
{
Log::Err("PairSetupM1: Invalid Method\n");
goto RetErr;
}
// if the accessory is already paired it must respond Error_Unavailable
if (_pairings.Count() != 0)
{
Log::Err("PairSetupM1: Already paired, return Error_Unavailable\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unavailable);
goto Ret;
}
// if accessory received more than 100 unsuccessfull auth attempts, respond Error_MaxTries
if (srp_auth_count > 100)
{
Log::Err("PairSetupM1: Too many auth attempts, return Error_MaxTries\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::MaxTries);
goto Ret;
}
// if accessory is currently performing PairSetup with different controller, respond Error_Busy
if (srp.active())
{
Log::Err("PairSetupM1: Already pairing, return Error_Busy\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Busy);
goto Ret;
}
// create new pairing session
if (!srp.open(sess->Sid()))
{
Log::Err("PairSetupM1: srp open error\n");
goto RetErr;
}
srp_auth_count++;
// init new verifier // TODO: store salt and verifier in config data
ver.init(Username, Hap::cfg->setupCode);
Log::Hex("Srp.I", ver.I, (uint32_t)strlen(ver.I));
Log::Hex("Srp.p", ver.p, (uint32_t)strlen(ver.p));
Log::Hex("Srp.s", ver.s, Srp::SRP_SALT_BYTES);
srp.init();
Log::Hex("Srp.B", srp.getB(), Srp::SRP_PUBLIC_BYTES);
sess->tlvo.add(Hap::Tlv::Type::PublicKey, srp.getB(), Srp::SRP_PUBLIC_BYTES);
sess->tlvo.add(Hap::Tlv::Type::Salt, ver.s, Srp::SRP_SALT_BYTES);
goto Ret;
RetErr:
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairSetup3(Session* sess)
{
uint8_t* iosKey = sess->data();
uint16_t iosKey_size = Srp::SRP_PUBLIC_BYTES;
uint8_t* iosProof = iosKey + Srp::SRP_PUBLIC_BYTES;
uint16_t iosProof_size = Srp::SRP_PROOF_BYTES;
Log::Msg("PairSetupM3\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M4);
// verify that pairing is in progress on current session
if (!srp.active(sess->Sid()))
{
Log::Err("PairSetupM3: No active pairing\n");
goto RetErr;
}
// verify that required items are present in input TLV
if (!sess->tlvi.get(Tlv::Type::PublicKey, iosKey, iosKey_size))
{
Log::Err("PairSetupM3: PublicKey not found\n");
goto RetErr;
}
Log::Hex("iosKey", iosKey, iosKey_size);
if (!sess->tlvi.get(Tlv::Type::Proof, iosProof, iosProof_size))
{
Log::Err("PairSetupM3: Proof not found\n");
goto RetErr;
}
Log::Hex("iosProof", iosProof, iosProof_size);
srp.setA(iosKey);
Crypto::HkdfSha512(
(const uint8_t*)"Pair-Setup-Encrypt-Salt", sizeof("Pair-Setup-Encrypt-Salt") - 1,
srp.getK(), Srp::SRP_KEY_BYTES,
(const uint8_t*)"Pair-Setup-Encrypt-Info", sizeof("Pair-Setup-Encrypt-Info") - 1,
sess->key, sizeof(sess->key)
);
Log::Hex("SessKey", sess->key, sizeof(sess->key));
if (!srp.verify(iosProof, iosProof_size))
{
Log::Err("PairSetupM3: SRP verify error\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
uint8_t V[Srp::SRP_PROOF_BYTES];
srp.getV(V);
Log::Hex("Response", V, sizeof(V));
sess->tlvo.add(Hap::Tlv::Type::Proof, V, Srp::SRP_PROOF_BYTES);
goto Ret;
RetErr: // error, cancel current pairing, if this session owns it
if (srp.active(sess->Sid()))
srp.close(sess->Sid());
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairSetup5(Session* sess)
{
uint8_t* iosEncrypted; // encrypted tata from iOS with tag attached
uint8_t* iosTag; // pointer to iOS tag
uint8_t* iosTlv; // decrypted TLV
uint8_t* srvTag; // calculated tag
uint16_t iosTlv_size;
Log::Msg("PairSetupM5\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M6);
// verify that pairing is in progress on current session
if (!srp.active(sess->Sid()))
{
Log::Err("PairSetupM5: No active pairing\n");
goto RetErr;
}
// extract encrypted data into sess->data buffer
iosEncrypted = sess->data();
iosTlv_size = sess->sizeofdata();
if (!sess->tlvi.get(Tlv::Type::EncryptedData, iosEncrypted, iosTlv_size))
{
Log::Err("PairSetupM5: EncryptedData not found\n");
goto RetErr;
}
else
{
Hap::Tlv::Item id;
Hap::Tlv::Item ltpk;
Hap::Tlv::Item sign;
// format sess->data buffer
iosTlv = iosEncrypted + iosTlv_size; // decrypted TLV
iosTlv_size -= 16; // strip off tag
iosTag = iosEncrypted + iosTlv_size; // iOS tag location
srvTag = iosTlv + iosTlv_size; // place for our tag
// decrypt iOS data using session key
Crypto::Aead aead(Crypto::Aead::Decrypt, iosTlv, srvTag,
sess->key, (const uint8_t *)"\x00\x00\x00\x00PS-Msg05",
iosEncrypted, iosTlv_size);
Log::Hex("iosTlv", iosTlv, iosTlv_size);
Log::Hex("iosTag", iosTag, 16);
Log::Hex("srvTlv", srvTag, 16);
// compare calculated tag with passed in one
if (memcmp(iosTag, srvTag, 16) != 0)
{
Log::Err("PairSetupM5: authTag does not match\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
// parse decrypted TLV - 3 items expected
Hap::Tlv::Parse<3> tlv(iosTlv, iosTlv_size);
Log::Err("PairSetupM5: TLV item count %d\n", tlv.count());
// extract TLV items
if (!tlv.get(Hap::Tlv::Type::Identifier, id))
{
Log::Err("PairSetupM5: Identifier not found\n");
goto RetErr;
}
Log::Hex("iosPairingId:", id.p(), id.l());
if (!tlv.get(Hap::Tlv::Type::PublicKey, ltpk))
{
Log::Err("PairSetupM5: PublicKey not found\n");
goto RetErr;
}
Log::Hex("iosLTPK:", ltpk.p(), ltpk.l());
if (!tlv.get(Hap::Tlv::Type::Signature, sign))
{
Log::Err("PairSetupM5: Signature not found\n");
goto RetErr;
}
Log::Hex("iosSignature:", sign.p(), sign.l());
// TODO: build iOSDeviceInfo and verify iOS device signature
// add pairing info to pairig database
if (!_pairings.Add(id, ltpk, Controller::Admin))
{
Log::Err("PairSetupM5: cannot add Pairing record\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::MaxPeers);
goto Ret;
}
// buid Accessory Info and sign it
uint8_t* AccesoryInfo = sess->data(); // re-use sess->data buffer
uint8_t* p = AccesoryInfo;
int l = sess->sizeofdata();
// add AccessoryX
Crypto::HkdfSha512(
(const uint8_t*)"Pair-Setup-Accessory-Sign-Salt", sizeof("Pair-Setup-Accessory-Sign-Salt") - 1,
srp.getK(), Srp::SRP_KEY_BYTES,
(const uint8_t*)"Pair-Setup-Accessory-Sign-Info", sizeof("Pair-Setup-Accessory-Sign-Info") - 1,
p, 32);
p += 32;
l -= 32;
// add Accessory PairingId
memcpy(p, cfg->deviceId, strlen(cfg->deviceId));
p += (uint32_t)strlen(cfg->deviceId);
l -= (uint32_t)strlen(cfg->deviceId);
// add Accessory LTPK
memcpy(p, _keys.pubKey(), _keys.PUBKEY_SIZE_BYTES);
p += _keys.PUBKEY_SIZE_BYTES;
l -= _keys.PUBKEY_SIZE_BYTES;
// sign the info
_keys.sign(p, AccesoryInfo, (uint16_t)(p - AccesoryInfo));
p += _keys.SIGN_SIZE_BYTES;
l -= _keys.SIGN_SIZE_BYTES;
// construct the sub-TLV
Hap::Tlv::Create subTlv;
subTlv.create(p, l);
subTlv.add(Hap::Tlv::Type::Identifier, (const uint8_t*)cfg->deviceId, (uint16_t)strlen(cfg->deviceId));
subTlv.add(Hap::Tlv::Type::PublicKey, _keys.pubKey(), _keys.PUBKEY_SIZE_BYTES);
subTlv.add(Hap::Tlv::Type::Signature, p - _keys.SIGN_SIZE_BYTES, _keys.SIGN_SIZE_BYTES);
p += subTlv.length();
l -= subTlv.length();
// enrypt AccessoryInfo using session key
Crypto::Aead(Crypto::Aead::Encrypt,
p, // output encrypted TLV
p + subTlv.length(), // output tag follows the encrypted TLV
sess->key,
(const uint8_t *)"\x00\x00\x00\x00PS-Msg06",
p - subTlv.length(), // input TLV
subTlv.length() // TLV length
);
l -= subTlv.length() + 16;
Log::Msg("PairSetupM5: sess->data unused: %d\n", l);
// add encryped info and tag to output TLV
sess->tlvo.add(Hap::Tlv::Type::EncryptedData, p, subTlv.length() + 16);
Hap::cfg->Update();
goto RetDone; // pairing complete
}
RetErr: // error, cancel current pairing, if this session owns it
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
RetDone:
if (srp.active(sess->Sid()))
srp.close(sess->Sid());
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairVerify1(Session* sess)
{
Hap::Tlv::Item iosKey;
const uint8_t* sharedSecret;
uint8_t* p;
int l;
Log::Msg("PairVerifyM1\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M2);
// verify that PublicKey is present in input TLV
if (!sess->tlvi.get(Tlv::Type::PublicKey, iosKey))
{
Log::Err("PairVerifyM1: PublicKey not found\n");
goto RetErr;
}
// create new Curve25519 key pair
sess->curve.init();
// generate shared secret
sharedSecret = sess->curve.sharedSecret(iosKey.p());
// create session key from shared secret
Crypto::HkdfSha512(
(const uint8_t*)"Pair-Verify-Encrypt-Salt", sizeof("Pair-Verify-Encrypt-Salt") - 1,
sharedSecret, sess->curve.KEY_SIZE_BYTES,
(const uint8_t*)"Pair-Verify-Encrypt-Info", sizeof("Pair-Verify-Encrypt-Info") - 1,
sess->key, sizeof(sess->key));
// construct AccessoryInfo
p = sess->data();
l = sess->sizeofdata();
// add Curve25519 public key
memcpy(p, sess->curve.pubKey(), sess->curve.KEY_SIZE_BYTES);
p += sess->curve.KEY_SIZE_BYTES;
l -= sess->curve.KEY_SIZE_BYTES;
// add Accessory PairingId
memcpy(p, cfg->deviceId, strlen(cfg->deviceId));
p += strlen(cfg->deviceId);
l -= strlen(cfg->deviceId);
// add iOS device public key
memcpy(p, iosKey.p(), iosKey.l());
p += iosKey.l();
l -= iosKey.l();
// sign the AccessoryInfo
_keys.sign(p, sess->data(), p - sess->data());
p += _keys.SIGN_SIZE_BYTES;
l -= _keys.SIGN_SIZE_BYTES;
// make sub-TLV
Hap::Tlv::Create subTlv;
subTlv.create(p, l);
subTlv.add(Hap::Tlv::Type::Identifier, (const uint8_t*)cfg->deviceId, (uint16_t)strlen(cfg->deviceId));
subTlv.add(Hap::Tlv::Type::Signature, p - _keys.SIGN_SIZE_BYTES, _keys.SIGN_SIZE_BYTES);
p += subTlv.length();
l -= subTlv.length();
// encrypt sub-TLV using session key
Crypto::Aead(Crypto::Aead::Encrypt,
p, // output encrypted TLV
p + subTlv.length(), // output tag follows the encrypted TLV
sess->key,
(const uint8_t *)"\x00\x00\x00\x00PV-Msg02",
p - subTlv.length(), // input TLV
subTlv.length() // TLV length
);
l -= subTlv.length() + 16;
Log::Msg("PairVerifyM1: sess->data unused: %d\n", l);
// add Accessory public key to output TLV
sess->tlvo.add(Hap::Tlv::Type::PublicKey, sess->curve.pubKey(), sess->curve.KEY_SIZE_BYTES);
// add encryped info and tag to output TLV
sess->tlvo.add(Hap::Tlv::Type::EncryptedData, p, subTlv.length() + 16);
goto Ret;
RetErr: // error
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairVerify3(Session* sess)
{
uint8_t* iosEncrypted; // encrypted tata from iOS with tag attached
uint8_t* iosTag; // pointer to iOS tag
uint8_t* iosTlv; // decrypted TLV
uint8_t* srvTag; // calculated tag
uint16_t iosTlv_size;
Log::Msg("PairVerifyM3\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M4);
// extract encrypted data into sess->data buffer
iosEncrypted = sess->data();
iosTlv_size = sess->sizeofdata();
if (!sess->tlvi.get(Tlv::Type::EncryptedData, iosEncrypted, iosTlv_size))
{
Log::Err("PairVerifyM3: EncryptedData not found\n");
goto RetErr;
}
else
{
Hap::Tlv::Item id;
Hap::Tlv::Item sign;
// format sess->data buffer
iosTlv = iosEncrypted + iosTlv_size; // decrypted TLV
iosTlv_size -= 16; // strip off tag
iosTag = iosEncrypted + iosTlv_size; // iOS tag location
srvTag = iosTlv + iosTlv_size; // place for our tag
// decrypt iOS data using session key
Crypto::Aead(Crypto::Aead::Decrypt, iosTlv, srvTag,
sess->key, (const uint8_t *)"\x00\x00\x00\x00PV-Msg03",
iosEncrypted, iosTlv_size);
Log::Hex("iosTlv", iosTlv, iosTlv_size);
Log::Hex("iosTag", iosTag, 16);
Log::Hex("srvTlv", srvTag, 16);
// compare calculated tag with passed in one
if (memcmp(iosTag, srvTag, 16) != 0)
{
Log::Err("PairVerifyM3: authTag does not match\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
// parse decrypted TLV - 2 items expected
Hap::Tlv::Parse<2> tlv(iosTlv, iosTlv_size);
Log::Msg("PairVerifyM3: TLV item count %d\n", tlv.count());
// extract TLV items
if (!tlv.get(Hap::Tlv::Type::Identifier, id))
{
Log::Err("PairVerifyM3: Identifier not found\n");
goto RetErr;
}
Log::Hex("iosPairingId:", id.p(), id.l());
if (!tlv.get(Hap::Tlv::Type::Signature, sign))
{
Log::Err("PairVerifyM3: Signature not found\n");
goto RetErr;
}
Log::Hex("iosSignature:", sign.p(), sign.l());
// lookup iOS id in pairing database
auto ios = _pairings.Get(id);
if (ios == nullptr)
{
Log::Err("PairVerifyM3: iOS device ID not found\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
// TODO: construct iOSDeviceInfo and verify signature
// create session encryption keys
Crypto::HkdfSha512(
(const uint8_t*)"Control-Salt", sizeof("Control-Salt") - 1,
sess->curve.sharedSecret(), sess->curve.KEY_SIZE_BYTES,
(const uint8_t*)"Control-Read-Encryption-Key", sizeof("Control-Read-Encryption-Key") - 1,
sess->AccessoryToControllerKey, sizeof(sess->AccessoryToControllerKey));
Crypto::HkdfSha512(
(const uint8_t*)"Control-Salt", sizeof("Control-Salt") - 1,
sess->curve.sharedSecret(), sess->curve.KEY_SIZE_BYTES,
(const uint8_t*)"Control-Write-Encryption-Key", sizeof("Control-Write-Encryption-Key") - 1,
sess->ControllerToAccessoryKey, sizeof(sess->ControllerToAccessoryKey));
// mark session as secured after response is sent
sess->ios = ios;
goto Ret;
}
RetErr: // error
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairingAdd(Session* sess)
{
Tlv::Item id;
Tlv::Item key;
Controller::Perm perm;
const Controller* ios;
Log::Msg("PairingAdd\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M2);
// verify that controller has admin permissions
if (sess->ios->perm != Controller::Admin)
{
Log::Err("PairingAdd: No Admin permissions\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
// extract required items from input TLV
if (!sess->tlvi.get(Tlv::Type::Identifier, id))
{
Log::Err("PairingAdd: Identifier not found\n");
goto RetErr;
}
Log::Hex("PairingAdd: Identifier", id.p(), id.l());
if (!sess->tlvi.get(Tlv::Type::PublicKey, key))
{
Log::Err("PairingAdd: PublicKey not found\n");
goto RetErr;
}
Log::Hex("PairingAdd: PublicKey", key.p(), key.l());
if (!sess->tlvi.get(Tlv::Type::Permissions, perm))
{
Log::Err("PairingAdd: Permissions not found\n");
goto RetErr;
}
Log::Msg("PairingAdd: Permissions 0x%X\n", perm);
// locate new controller in pairing db
ios = _pairings.Get(id);
if (ios != nullptr)
{
// compare controller LTPK with stored one
if (key.l() != Controller::KeyLen || memcmp(key.p(), ios->key, Controller::KeyLen) != 0)
{
Log::Err("PairingAdd: mismatch\n");
goto RetErr;
}
_pairings.Update(id, perm);
}
else if (!_pairings.Add(id, key, perm))
{
Log::Err("PairingAdd: Unable to add\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::MaxPeers);
goto Ret;
}
Hap::cfg->Update();
goto Ret;
RetErr: // error
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairingRemove(Session* sess)
{
Tlv::Item id;
Log::Msg("PairingRemove\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M2);
// verify that controller has admin permissions
if (sess->ios->perm != Controller::Admin)
{
Log::Err("PairingRemove: No Admin permissions\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
// extract required items from input TLV
if (!sess->tlvi.get(Tlv::Type::Identifier, id))
{
Log::Err("PairingRemove: Identifier not found\n");
goto RetErr;
}
Log::Hex("PairingRemove: Identifier", id.p(), id.l());
if (!_pairings.Remove(id))
{
Log::Err("PairingRemove: Remove error\n");
goto RetErr;
}
Hap::cfg->Update();
// TODO: close all sessions to removed controller
goto Ret;
RetErr: // error
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
void Server::_pairingList(Session* sess)
{
bool first = true;
bool rc;
Log::Msg("PairingList\n");
// prepare response without data
sess->rsp.start(HTTP_200);
sess->rsp.add(ContentType, ContentTypeTlv8);
sess->rsp.add(ContentLength, 0);
sess->rsp.end();
// create response TLV in the response buffer right after HTTP headers
sess->tlvo.create((uint8_t*)sess->rsp.data(), sess->rsp.size());
sess->tlvo.add(Hap::Tlv::Type::State, Hap::Tlv::State::M2);
// verify that controller has admin permissions
if (sess->ios->perm != Controller::Admin)
{
Log::Err("PairingList: No Admin permissions\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Authentication);
goto Ret;
}
rc = _pairings.forEach([sess, &first](const Controller* ios) -> bool {
if (!first)
{
if (!sess->tlvo.add(Hap::Tlv::Type::Separator))
return false;
}
if (!sess->tlvo.add(Hap::Tlv::Type::Identifier, ios->id, ios->IdLen)) // TODO: store real ID length (or zero-terminate?)
return false;
if (!sess->tlvo.add(Hap::Tlv::Type::PublicKey, ios->key, ios->KeyLen))
return false;
if (!sess->tlvo.add(Hap::Tlv::Type::Permissions, ios->perm))
return false;
first = false;
return true;
});
if(rc)
goto Ret;
//RetErr: // error
Log::Err("PairingList: TLV overflow\n");
sess->tlvo.add(Hap::Tlv::Type::Error, Hap::Tlv::Error::Unknown);
Ret:
// adjust content length in response
sess->rsp.setContentLength(sess->tlvo.length());
}
}
}
| 27.864805 | 156 | 0.601888 | cavecafe |
130494807ab2c4967617e3fb1aa05fbd274b5f97 | 1,442 | cpp | C++ | server/Common/Packets/GWAskChangeScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Common/Packets/GWAskChangeScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Common/Packets/GWAskChangeScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
#include "GWAskChangeScene.h"
BOOL GWAskChangeScene::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_Status), sizeof(BYTE) ) ;
iStream.Read( (CHAR*)(&m_PlayerID), sizeof(PlayerID_t) ) ;
iStream.Read( (CHAR*)(&m_GUID), sizeof(GUID_t) ) ;
iStream.Read( (CHAR*)(&m_SourSceneID), sizeof(SceneID_t) ) ;
iStream.Read( (CHAR*)(&m_DestSceneID), sizeof(SceneID_t) ) ;
if( m_Status==CSS_DIFFSERVER )
iStream.Read( (CHAR*)(&m_UserData), sizeof(FULLUSERDATA) ) ;
iStream.Read( (CHAR*)(&m_uKey), sizeof(UINT) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GWAskChangeScene::Write( SocketOutputStream& oStream ) const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_Status), sizeof(BYTE) ) ;
oStream.Write( (CHAR*)(&m_PlayerID), sizeof(PlayerID_t) ) ;
oStream.Write( (CHAR*)(&m_GUID), sizeof(GUID_t) ) ;
oStream.Write( (CHAR*)(&m_SourSceneID), sizeof(SceneID_t) ) ;
oStream.Write( (CHAR*)(&m_DestSceneID), sizeof(SceneID_t) ) ;
if( m_Status==CSS_DIFFSERVER )
oStream.Write( (CHAR*)(&m_UserData), sizeof(FULLUSERDATA) ) ;
oStream.Write( (CHAR*)(&m_uKey), sizeof(UINT) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GWAskChangeScene::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GWAskChangeSceneHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 24.033333 | 69 | 0.669903 | viticm |
13054dee50887543d8d0d1f6e7e8efb2cb457bf1 | 282 | cpp | C++ | src/lib/zap/zap/toolchains/clang.cpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | src/lib/zap/zap/toolchains/clang.cpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | src/lib/zap/zap/toolchains/clang.cpp | chybz/zap | ccc67d85def09faa962e44b9e36ca414207d4ec3 | [
"MIT"
] | null | null | null | #include <zap/toolchains/clang.hpp>
namespace zap::toolchains {
clang::clang(
const zap::env_paths& ep,
zap::toolchain_info&& ti,
zap::executor& exec
)
: gcc(ep, std::forward<zap::toolchain_info>(ti), exec)
{
scanner_.push_args({ "-w" });
}
clang::~clang()
{}
}
| 14.842105 | 54 | 0.634752 | chybz |
130814635baaca6cbd79f9e45dd8ceea564e80ec | 5,653 | cpp | C++ | examples/advection/parallel/main.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | examples/advection/parallel/main.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | examples/advection/parallel/main.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | /*
Parallel program solving advection equation in a prescribed velocity field.
Copyright 2014, 2015, 2016 Ilja Honkonen
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 copyright holders nor the names of their 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.
*/
//! see ../serial.cpp and ../game_of_life/parallel/* for basics
#include "array"
#include "boost/lexical_cast.hpp"
#include "cmath"
#include "cstdlib"
#include "iostream"
#include "mpi.h"
#include "dccrg.hpp"
#include "dccrg_cartesian_geometry.hpp"
#include "gensimcell.hpp"
#include "advection_initialize.hpp"
#include "advection_save.hpp"
#include "advection_solve.hpp"
#include "advection_variables.hpp"
int main(int argc, char* argv[])
{
// the cell type used by this program
using Cell = advection::Cell;
/*
Set up MPI
*/
if (MPI_Init(&argc, &argv) != MPI_SUCCESS) {
std::cerr << "Coudln't initialize MPI." << std::endl;
abort();
}
MPI_Comm comm = MPI_COMM_WORLD;
int rank = 0, comm_size = 0;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &comm_size);
// intialize Zoltan
float zoltan_version;
if (Zoltan_Initialize(argc, argv, &zoltan_version) != ZOLTAN_OK) {
std::cerr << "Zoltan_Initialize failed." << std::endl;
abort();
}
/*
Set up the grid in which the simulation will run
*/
dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry> grid;
// initialize the grid
std::array<uint64_t, 3> grid_length = {{20, 20, 1}};
const unsigned int neighborhood_size = 1;
if (not grid.initialize(
grid_length,
comm,
"RANDOM",
neighborhood_size,
0,
false, false, false
)) {
std::cerr << __FILE__ << ":" << __LINE__
<< ": Couldn't initialize grid."
<< std::endl;
abort();
}
// set the grid's geometry
dccrg::Cartesian_Geometry::Parameters geom_params;
geom_params.start[0] =
geom_params.start[1] = -1;
geom_params.start[2] = -1.0 / grid_length[0];
geom_params.level_0_cell_length[0] =
geom_params.level_0_cell_length[1] =
geom_params.level_0_cell_length[2] = 2.0 / grid_length[0];
if (not grid.set_geometry(geom_params)) {
std::cerr << __FILE__ << ":" << __LINE__
<< ": Couldn't set grid geometry."
<< std::endl;
abort();
}
grid.balance_load();
/*
Simulate
*/
advection::initialize<
Cell,
advection::Density,
advection::Density_Flux,
advection::Velocity
>(grid);
const std::vector<uint64_t>
inner_cells = grid.get_local_cells_not_on_process_boundary(),
outer_cells = grid.get_local_cells_on_process_boundary();
const double advection_save_interval = 0.1;
double advection_next_save = 0;
double
simulation_time = 0,
time_step = 0;
while (simulation_time <= M_PI) {
double next_time_step = std::numeric_limits<double>::max();
/*
Save simulation to disk
*/
Cell::set_transfer_all(
false,
advection::Density(),
advection::Density_Flux(),
advection::Velocity()
);
if (advection_next_save <= simulation_time) {
advection_next_save += advection_save_interval;
advection::save<
Cell,
advection::Density,
advection::Velocity
>(grid, simulation_time);
}
if (simulation_time >= M_PI) {
break;
}
/*
Solve
*/
Cell::set_transfer_all(
true,
advection::Density(),
advection::Velocity()
);
grid.start_remote_neighbor_copy_updates();
next_time_step
= std::min(
next_time_step,
advection::solve<
Cell,
advection::Density,
advection::Density_Flux,
advection::Velocity
>(time_step, inner_cells, grid)
);
grid.wait_remote_neighbor_copy_update_receives();
next_time_step
= std::min(
next_time_step,
advection::solve<
Cell,
advection::Density,
advection::Density_Flux,
advection::Velocity
>(time_step, outer_cells, grid)
);
/*
Apply solution
*/
advection::apply_solution<
Cell,
advection::Density,
advection::Density_Flux
>(inner_cells, grid);
grid.wait_remote_neighbor_copy_update_sends();
Cell::set_transfer_all(
false,
advection::Density(),
advection::Velocity()
);
advection::apply_solution<
Cell,
advection::Density,
advection::Density_Flux
>(outer_cells, grid);
simulation_time += time_step;
MPI_Allreduce(&next_time_step, &time_step, 1, MPI_DOUBLE, MPI_MIN, comm);
const double CFL = 0.5;
time_step *= CFL;
}
MPI_Finalize();
return EXIT_SUCCESS;
}
| 23.95339 | 80 | 0.718203 | nasailja |
130883db75cc7039b1094d9d29bc2f37e78f876c | 628 | hpp | C++ | include/zax/fs.hpp | fcharlie/zax | 041ad510635df85e5842036cd0319ea92f7f56ba | [
"MIT"
] | null | null | null | include/zax/fs.hpp | fcharlie/zax | 041ad510635df85e5842036cd0319ea92f7f56ba | [
"MIT"
] | null | null | null | include/zax/fs.hpp | fcharlie/zax | 041ad510635df85e5842036cd0319ea92f7f56ba | [
"MIT"
] | null | null | null | //
#ifndef ZAX_FS_HPP
#define ZAX_FS_HPP
#ifdef _WIN32
#include <windows.h>
#endif
#include "zax.hpp"
namespace zax::fs {
#ifdef _WIN32
using native_handle = HANDLE;
#define closedfd INVALID_HANDLE_VALUE
#else
using native_handle = int;
constexpr auto closedfd = -1;
#endif
class File {
public:
File() = default;
File(const File &) = delete;
File &operator=(const File &) = delete;
~File();
ssize_t Write(const uint8_t *data, size_t len);
ssize_t Read(uint8_t *buffer, size_t bufsz);
int Close();
native_handle FD() const { return fd; }
private:
native_handle fd{closedfd};
};
} // namespace zax::fs
#endif | 18.470588 | 49 | 0.707006 | fcharlie |
13092d2198b0661dd944ce4cbb8f0edabf280965 | 2,217 | cpp | C++ | atspoles_algoritms.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | atspoles_algoritms.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | atspoles_algoritms.cpp | IvarsSaudinis/alkoritmi-un-datu-strukturas | d3856b1428894843f2c80f27661ca6fb86ded878 | [
"MIT"
] | null | null | null | /*
* Using Shuttle Sort algorithm, sort in ascending sort the list of random numbers stored in doubly linked list
* --
* build with CLion/ch-0/183.5429.37/bin/cmake/linux/bin/cmake and little miracle
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Saraksts // classic
{
int Dati;
Saraksts *Cits, *Iepr;
};
void ironiski_nosutit_final_psd_maketu_uz_izdruku(struct Saraksts *p )
{
while(p != NULL)
{
cout << p->Dati << " ";
p = p->Cits;
}
cout << endl;
}
int main (){
srand(time(0)); // "random" sēkliņas izmešana
Saraksts *H, *p;
cout << "Original: " << endl;
H = new Saraksts; // tiek izveidots saraksta 1. ieraksts, kas arī tiek automātiski atzīmēts par ierakstu saraksta pirmo punktu
H->Iepr = NULL; // atsauce uz iepriekšejo ierakstu ir NULL par cik iepriekšējais nav nemaz iespējams
H->Dati = rand() % 99 + 1; // aizpildam ar random vērtību 1..99
p = H; // atgriež atsauci sākumpunktā
for(int i=0; i<19; i++) // cikls izpildīsies 0,1,2 ... 18,19 reizes. Kopā 20 reizes
{
p->Cits = new Saraksts; // Mainīgā (operanda, šķiet) sadaļā `Cits` piešķiram jauno mainīgo
p->Cits->Iepr = p; // šī mainīgā Cits vērtības Iepr piešķiršana
p = p->Cits;
p->Dati = rand() % 99 + 1; // vērtības piešķiršana
}
p->Cits = NULL; // kā arī definējam ieraksta pēdējo vērtību
p = H; // Atgriežam atsauci sākotnējā punktā
ironiski_nosutit_final_psd_maketu_uz_izdruku(p); // izdruka ekrānā, loooģiski
p = H; // Atgriežam atsauci sākotnējā punktā
do
{
while(p->Dati > p->Cits->Dati )
{
swap(p->Cits->Dati , p->Dati);
if(p->Iepr != NULL )
p = p->Iepr; // atsauci atmetam uz iepriekšējo vērtību, ja nav NULL
else break; // ja iepriekš ir break, tad jau laužam ciklu
}
p = p->Cits; // skatāmies nākošo vērtību
}
while(p->Cits!=NULL); // nodarbinām kamēr nākošā vērtībā nav NULL
cout << "Sorted:" << endl;
p = H;
ironiski_nosutit_final_psd_maketu_uz_izdruku(p); // izvade
return 0;
}
| 31.225352 | 140 | 0.602165 | IvarsSaudinis |
131899825c29a437322bf6e08b25c3bb9a558987 | 738 | cpp | C++ | simplefvm/src/MeshLoader/MeshContainer/CellsSizeDefiner.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | 4 | 2022-01-03T08:45:55.000Z | 2022-01-06T19:57:11.000Z | simplefvm/src/MeshLoader/MeshContainer/CellsSizeDefiner.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | null | null | null | simplefvm/src/MeshLoader/MeshContainer/CellsSizeDefiner.cpp | artvns/SimpleFvm | 5a8eca332d6780e738c0bc6c8c2b787b47b5b20d | [
"MIT"
] | null | null | null | #include "CellsSizeDefiner.h"
namespace meshloader {
CellsSizeDefiner::CellsSizeDefiner() {
}
void CellsSizeDefiner::setCellsSize(Mesh& meshContainer,
const double dx, const double dy) {
for (size_t i = 0; i < meshContainer.getCellsAmount(); ++i) {
meshContainer.getCellByIndex(i)->getCellU().set_dX(dx);
meshContainer.getCellByIndex(i)->getCellV().set_dX(dx);
meshContainer.getCellByIndex(i)->getCellP().set_dX(dx);
meshContainer.getCellByIndex(i)->getCellU().set_dY(dy);
meshContainer.getCellByIndex(i)->getCellV().set_dY(dy);
meshContainer.getCellByIndex(i)->getCellP().set_dY(dy);
}
}
} | 32.086957 | 75 | 0.615176 | artvns |
131a53b9b5074e797947857ceef8798f660bc81a | 2,961 | hpp | C++ | sparta/cache/DefaultAddrDecoder.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/cache/DefaultAddrDecoder.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/cache/DefaultAddrDecoder.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null |
#ifndef _SPA_CACHE_DEFAULT_ADDR_DECODER_IF_H__
#define _SPA_CACHE_DEFAULT_ADDR_DECODER_IF_H__
#include "cassert"
#include "sparta/utils/MathUtils.hpp"
#include "cache/AddrDecoderIF.hpp"
namespace sparta
{
namespace cache
{
/* DefaultAddrDecoder: decodes a 64-bit address.
*
* Assuming line_size==stride, the address is decoded as below
* +--------------------------+------+------+
* |tag |idx |offset|
* *--------------------------+------+------+
*/
class DefaultAddrDecoder: public AddrDecoderIF
{
public:
DefaultAddrDecoder(uint64_t sz, // cache size, in KB or bytes
uint64_t line_sz, // line size, in bytes
uint64_t stride, // stride, in bytes
uint32_t num_ways, // num ways
bool cache_sz_unit_is_kb = true) // choose between KB or B
{
assert( utils::is_power_of_2(line_sz) );
assert( utils::is_power_of_2(stride) );
line_size_ = line_sz;
const uint64_t sz_bytes = (cache_sz_unit_is_kb) ? (sz*1024) : (sz);
const uint32_t num_sets = (sz_bytes)/ (line_sz * num_ways);
//MRVN-464: implement 3-bank SL3, so the total # sets are no longer power of 2.
//assert( utils::is_power_of_2(num_sets) );
blk_offset_mask_ = line_sz - 1;
blk_addr_mask_ = ~uint64_t(blk_offset_mask_);
index_mask_ = num_sets - 1;
index_shift_ = utils::floor_log2(stride);
tag_shift_ = utils::floor_log2(num_sets * stride);
}
virtual uint64_t calcTag(uint64_t addr) const { return (addr >> tag_shift_); }
virtual uint32_t calcIdx(uint64_t addr) const { return (addr >> index_shift_) & index_mask_; }
virtual uint64_t calcBlockAddr(uint64_t addr) const { return (addr & blk_addr_mask_); }
virtual uint64_t calcBlockOffset(uint64_t addr) const { return (addr & blk_offset_mask_); }
uint64_t getIndexMask() { return index_mask_;}
uint64_t getIndexShift() { return index_shift_;}
uint64_t getBlockOffsetMask() {return blk_offset_mask_;}
private:
uint64_t line_size_;
uint64_t blk_addr_mask_; //
uint64_t blk_offset_mask_; //
uint32_t index_shift_; // Amount to shift right for index
uint32_t index_mask_; // Mask to apply after index shift
uint32_t tag_shift_; // Amount to shift right for tag
}; // class AddrDecoderIF
}; // namespace cache
}; // namespace sparta
#endif // _SPA_CACHE_DEFAULT_ADDR_DECODER_IF_H__
| 42.913043 | 106 | 0.544748 | knute-sifive |
131dcba6ae1a31cca5f4c1cdd9b0a2130593cd07 | 1,109 | hpp | C++ | big-finish-downloader-gtk/include/libbf/gui/alert_box.hpp | Emersont1/big-finish-downloader | c6c754e65a827a500dad3c9d847fd723ce3e2fb4 | [
"MIT"
] | 1 | 2021-01-11T20:03:25.000Z | 2021-01-11T20:03:25.000Z | big-finish-downloader-gtk/include/libbf/gui/alert_box.hpp | Emersont1/big-finish-downloader | c6c754e65a827a500dad3c9d847fd723ce3e2fb4 | [
"MIT"
] | 16 | 2021-01-08T23:22:02.000Z | 2021-01-27T10:10:05.000Z | big-finish-downloader-gtk/include/libbf/gui/alert_box.hpp | Emersont1/big-finish-downloader | c6c754e65a827a500dad3c9d847fd723ce3e2fb4 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <gtk/gtk.h>
//~~shamelessly stolen~~ adapted from aaronmjacobs/Boxer
namespace libbf::gui::alert {
/*!
* Options for styles to apply to a message box
*/
enum class Style {
Info = GTK_MESSAGE_INFO,
Warning = GTK_MESSAGE_WARNING,
Error = GTK_MESSAGE_ERROR,
Question = GTK_MESSAGE_QUESTION
};
/*!
* Options for buttons to provide on a message box
*/
enum class Buttons {
OK = GTK_BUTTONS_OK,
OKCancel = GTK_BUTTONS_OK_CANCEL,
YesNo = GTK_BUTTONS_YES_NO,
Quit = GTK_BUTTONS_CLOSE
};
/*!
* Possible responses from a message box. 'None' signifies that no option was
* chosen, and 'Error' signifies that an error was encountered while creating
* the message box.
*/
enum class Selection {
OK = GTK_RESPONSE_OK,
Cancel = GTK_RESPONSE_CANCEL,
Yes = GTK_RESPONSE_YES,
No = GTK_RESPONSE_NO,
Quit = GTK_RESPONSE_CLOSE,
None = -1,
Error = -2
};
Selection show(std::string message, std::string title, Style style = Style::Info,
Buttons buttons = Buttons::OK);
} // namespace libbf::gui::alert | 23.104167 | 81 | 0.688909 | Emersont1 |
131e6b976ac90637b41ff52a96f02ffca4b2052f | 5,003 | hh | C++ | lua/inc/com/centreon/broker/lua/luabinding.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 40 | 2015-03-10T07:55:39.000Z | 2021-06-11T10:13:56.000Z | lua/inc/com/centreon/broker/lua/luabinding.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 297 | 2015-04-30T10:02:04.000Z | 2022-03-09T13:31:54.000Z | lua/inc/com/centreon/broker/lua/luabinding.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 29 | 2015-08-03T10:04:15.000Z | 2021-11-25T12:21:00.000Z | /*
** Copyright 2018 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_LUA_LUABINDING_HH
#define CCB_LUA_LUABINDING_HH
#include <map>
#include "com/centreon/broker/lua/macro_cache.hh"
#include "com/centreon/broker/misc/variant.hh"
extern "C" {
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
}
CCB_BEGIN()
namespace lua {
/**
* @class luabinding luabinding.hh
* "com/centreon/broker/luabinding/luabinding.hh"
* @brief Class managing exchange with the the lua interpreter.
*
* Here is the class used to send broker data to the Lua interpreter. We are
* compatible with Lua 5.1, 5.2, 5.3 and 5.4.
*
* This class constructor needs three parameters that are:
* * the script to load (just its file name).
* * the configuration parameters given as a map.
* * a macro_cache object (used to store the cache...).
*
* At the construction, the script is read. We check also that it contains:
* * a global function init(conf) : this one is mandatory. conf is a Lua table
* containing the configuration set in the web configuration of broker.
* * a global function write(d) : this one is mandatory. if the v1 api is used,
* d is a Lua table that reprensents a transformed Broker event. In case of
* v2 api, d is a Lua userdata containing directly the Broker event. The api
* allows the user to use this event as if it was a Lua table. To choose what
* api to use, the script has to contain the definition of a variable named
* broker_version_api, that should contain 1 or 2. The write function returns
* true to allow broker to acknowledge all the last received events and false
* otherwise.
* * a global filter(c, v) : this one is not mandatory. This function improves
* Broker performance particularly in the case of the v1 api, because
* transforming an event into Lua table is expensive for the CPU. Using it
* may be dangerous, events retained by the filter are not automatically
* acknowledged because broker can only acknowledge events from the beginning
* of its queue and the acknowledged block must not contain hole, they must
* be contiguous. So filtered events are acknowledged only when not filtered
* events among them are also acknowledged.
* If the beginning of the queue is as follows (N not filtered, F for
* filtered), The first one is given to the write function but often not
* acknowledged immediatly. Then, the three next events are not given to
* write() but cannot be acknowledged since the first one is still waiting.
* And so only when the first one will be acknowledged, those ones will:
*
* NFFFNFFNNN.....
*
* * a global flush() : this one is not mandatory but may be should. The good
* practice is to have a write function that keeps a queue of received
* events. When this queue reaches the a max size, it is sent to a peer using
* the flush() function. If this flush() function successes, it returns true.
*
* And in case of retention, broker does not call anymore the write()
* function, but directly calls flush(). If present, this will clear the
* queue and events are acknowledged so it will be possible again to call the
* write() function.
*
*/
class luabinding {
// The Lua state machine.
lua_State* _L;
// True if there is a filter() function in the Lua script.
bool _filter;
// True if there is a flush() function in the Lua script.
bool _flush;
// The cache.
macro_cache& _cache;
// Count on events
int32_t _total;
// Api version among (1, 2)
uint32_t _broker_api_version;
lua_State* _load_interpreter();
void _load_script(const std::string& lua_script);
void _init_script(std::map<std::string, misc::variant> const& conf_params);
void _update_lua_path(std::string const& path);
public:
luabinding(std::string const& lua_script,
std::map<std::string, misc::variant> const& conf_params,
macro_cache& cache);
luabinding(luabinding const&) = delete;
luabinding& operator=(luabinding const&) = delete;
~luabinding();
bool has_filter() const noexcept;
int32_t write(std::shared_ptr<io::data> const& data) noexcept;
bool has_flush() const noexcept;
int32_t flush() noexcept;
};
// Event conversion to Lua table.
void push_event_as_table(lua_State* L, io::data const& d);
} // namespace lua
CCB_END()
#endif // !CCB_LUA_LUA_HH
| 37.901515 | 80 | 0.714171 | centreon-lab |
132098f1eb86814e03959b0f09210899844749ca | 21,530 | cpp | C++ | winSys/edit.cpp | alec101/Ix | 84143d737bdc4beabb3ff46e5c3bc98579f4e90a | [
"BSD-3-Clause"
] | null | null | null | winSys/edit.cpp | alec101/Ix | 84143d737bdc4beabb3ff46e5c3bc98579f4e90a | [
"BSD-3-Clause"
] | null | null | null | winSys/edit.cpp | alec101/Ix | 84143d737bdc4beabb3ff46e5c3bc98579f4e90a | [
"BSD-3-Clause"
] | null | null | null | #include "ix/ix.h"
#include "ix/winSys/_privateDef.h"
/*
WHEN A CHAR IS DELETED, ALL IT'S DIECRITICALS MUST BE DELETED!!!
TODO:
-left->right right->left top->bottom, all should be basically done
-bottom to top writing i don't think exists, but you never know...
IDEEAS:
-sound for keys? another sound for when a char cannot be typed
*/
using namespace Str;
static int32 _ixEditClickDelta= 7; // (default: 7x7 box) any mouse up that moved outisde this box is considered a drag instead
void ixEdit::_setClickLimits(int32 in_delta) {
_ixEditClickDelta= in_delta;
}
ixEdit::ixEdit(): usage(this), text(this), ixBaseWindow(&is, &usage) {
_type= ixeWinType::edit;
enterPressed= false;
//text._parent= this;
}
ixEdit::~ixEdit() {
delData();
}
void ixEdit::delData() {
text.delData();
//text.font= null;
enterPressed= false;
text.cur.line= text.cur.pos= 0; text.cur.pLine= (ixTxtData::Line *)text.lines.first;
text.sel.delData();
ixBaseWindow::delData();
}
// funcs
// sets the editor in a special one-line, fixed buffer mode. the buffer is UTF-32 format (int32 per unicode value)
bool ixEdit::Usage::setOneLineFixed(int32 in_size) {
if(in_size<= 0) return false;
if(((ixEdit *)_win)->text.nrUnicodes) ((ixEdit *)_win)->delData();
/// set the vars
oneLine= 1;
fixedBuffer= 1;
limitUnicodes= in_size;
((ixEdit *)_win)->text._fixedBuffer= (char32 *)new uint32[limitUnicodes+ 1];
// create the line in the text data
ixTxtData::Line *p= new ixTxtData::Line;
p->text.wrap(((ixEdit *)_win)->text._fixedBuffer, limitUnicodes+ 1);
((ixEdit *)_win)->text.lines.add(p);
((ixEdit *)_win)->text._updateWrapList();
((ixEdit *)_win)->text.cur.updateWline();
((ixEdit *)_win)->text.findTextDy();
return true;
}
// whiteLists an unicode or a sequence of unicodes
void ixEdit::Usage::whiteList(int32 in_from, int32 in_to) {
/// search if this sequence is already whitelisted
_List *p= (_List *)_whiteList.first;
for(; p; p= (_List *)p->next)
if((p->from== in_from) && (p->to== in_to)) {
error.console("IGNORING: unicode sequence already whitelisted [ixEdit::whiteList()]");
return;
}
if(in_from< 0) { error.console("IGNORING: unicode sequence starts with negative number [ixEdit::whiteList()]"); return; }
// add the unicode sequence
p= new _List;
p->from= in_from;
p->to= (in_to< 0? in_from: in_to);
_whiteList.add(p);
}
// removes the whole list if no params are passed, or searches for the unicode or unicodes to remove from the list
void ixEdit::Usage::whiteListDel(int32 in_from, int32 in_to) {
/// delete whole list, case in_from is negative
if(in_from< 0) {
_whiteList.delData();
return;
}
_List *p= (_List *)_whiteList.first;
for(; p; p= (_List *)p->next)
if((p->from== in_from) && (p->to== (in_to< 0? in_from: in_to))) {
_whiteList.del(p);
return;
}
error.console("IGNORING: unicode sequence to delete not found [ixEdit::whiteListDel()]");
}
// blackLists an unicode or a sequence of unicodes
void ixEdit::Usage::blackList(int32 in_from, int32 in_to) {
/// search if this sequence is already whitelisted
_List *p= (_List *)_blackList.first;
for(; p; p= (_List *)p->next)
if((p->from== in_from) && (p->to== in_to)) {
error.console("IGNORING: unicode sequence already whitelisted [ixEdit::blackList()]");
return;
}
if(in_from< 0) { error.console("IGNORING: unicode sequence starts with negative number [ixEdit::blackList()]"); return; }
// add the unicode sequence
p= new _List;
p->from= in_from;
p->to= (in_to< 0? in_from: in_to);
_blackList.add(p);
}
// removes the whole list if no params are passed, or searches for the unicode or unicodes to remove from the list
void ixEdit::Usage::blackListDel(int32 in_from, int32 in_to) {
/// delete whole list, case in_from is negative
if(in_from< 0) {
_blackList.delData();
return;
}
_List *p= (_List *)_blackList.first;
for(; p; p= (_List *)p->next)
if((p->from== in_from) && (p->to== (in_to< 0? in_from: in_to))) {
_blackList.del(p);
return;
}
error.console("IGNORING: unicode sequence to delete not found [ixEdit::whiteListDel()]");
}
// if using the special fixed buffer, returns a pointer to it to be easily accessed
//char32 *ixEdit::Usage::getOneLineFixedBuffer() {
// return _parent->text._fixedBuffer;
//}
// PRIVATE FUNCS
/*
void ixEdit::_paste(str32 *in_str) {
if(!in_str) return;
_delSelection();
for(uint32 *p= (uint32 *)in_str->d; *p; p++) { /// loop thru all unicodes in paste string
// insert only if passes the _checkLimits() func
if(_checkLimits(*p)) {
text.cur.pLine->text.insert(*p, text.cur.pos);
text.nrUnicodes++;
ixPrint::getCharDy(text.font);
// THIS IS NOT WORKING WITH A FIXED BUFFER
// add a line
if(*p== '\n') { /// this won't be a case when the editor is on oneline, it simply wont come up to this point
ixLineData *p= new ixLineData;
p->text= text.cur.pLine->text.d+ text.cur.pos+ 1; /// +1 due current \n char
p->dx= ixPrint::getTextDx32(p->text, text.font);
p->dy= ixPrint::getCharDy(text.font);
text.lines.addAfter(p, text.cur.pLine);
text.cur.pLine->text.del(text.cur.pLine->text.nrUnicodes- text.cur.pos- 1, text.cur.pos+ 1);
text.cur.pLine->dx= ixPrint::getTextDx32(text.cur.pLine->text, text.font);
text.cur.pos= 0;
text.cur.line++;
text.cur.pLine= p;
}
text.cur.pos++;
} /// add a line
} /// loop thru all unicodes in paste string
text.cur.pLine->dx= ixPrint::getTextDx32(text.cur.pLine->text, text.font); /// linesize in pixels
text.findTextDx();
text.findTextDy();
}
*/
bool ixEdit::_checkLimits(char32 unicode) {
if(!usage.acceptCombs) if(isComb(unicode)) return false;
if(usage.limitUnicodes) if(text.nrUnicodes>= usage.limitUnicodes) return false;
if(usage.oneLine) if(unicode== '\n') return false;
if(usage.onlyNumbers) if(!(unicode>= '0' && unicode<= '9')) return false;
if(usage._whiteList.nrNodes) {
bool found= false;
for(Usage::_List *p= (Usage::_List *)usage._whiteList.first; p; p= (Usage::_List *)p->next)
if((unicode>= p->from) && (unicode <= p->to)) {
found= true; break;
}
if(!found) return false;
}
if(usage._blackList.nrNodes)
for(Usage::_List *p= (Usage::_List *)usage._blackList.first; p; p= (Usage::_List *)p->next)
if((unicode>= p->from) && (unicode <= p->to))
return false;
return true;
// REMOVED
//if(usage.limitLines) if(text.lines.nrNodes>= usage.limitLines) return false;
//if(usage.limitUnicodesPerLine) if(text.cur.pLine->text.nrUnicodes>= usage.limitUnicodesPerLine) return false;
//if(usage.limitCharsPerLine) { if(!isComb(unicode)) if(text.cur.pLine->text.nrChars()>= usage.limitCharsPerLine) return false; }
}
/*
maybe a "check n unicodes that can be inserted"
still... when pasting happens... it's very hard not to check char by char...
well... a trimming of bad chars can happen before paste, so only insert line by line happens
*/
// ## ## ###### ###### #### ######## ########
// ## ## ## ## ## ## ## ## ## ##
// ## ## ###### ## ## ## ## ## ###### func
// ## ## ## ## ## ######## ## ##
// #### ## ###### ## ## ## ########
bool ixEdit::_update(bool in_mIn, bool updateChildren) {
if(!is.visible) return false;
recti r; getVDcoordsRecti(&r);
bool sendMIn= (in_mIn? r.inside(in.m.x, in.m.y): false);
/// update it's children first
if(updateChildren)
if(_updateChildren(sendMIn))
return true;
// A THING TO CONSIDER: ret (return value), as it is now, is true either any command is procesed or not, when osi.in is processed
// problem is, if the manip/char is not part of this, it should be put in osi again? cuz in.getManip() will erase it
// think on the keyboard focus. an esc press would mean lost keyboard focus?
// _view and cursor MUST WORK LIKE CLOCKWORK
bool ret= false; /// this will return true if any action to this window happened
enterPressed= false; /// reset it from last time
//uint32 c;
ret= text._update(sendMIn);
// THE MOVEMENT IN txtShared.cpp OF THIS WHOLE MECHANISM IS NOT TESTED <<<<<<<<<<<<<<<<<<<<<<<
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// static seems ok, if edit works too, this whole code can just go away
/*
// process all chars - can be unicodes, or special str manipulation codes
if(Ix::wsys().focus== this)
while((c= in.k.getChar())) {
/// shortcuts
str32 *s= &text.cur.pLine->text; // AFTER A _delSelection() OR SIMILAR, THIS POINTER WILL BE BAD, CAREFUL TO UPDATE
int32 *cpos= &text.cur.pos;
// new line
if(c== Kch_enter) {
if(usage.oneLine) {
enterPressed= true;
} else {
if(!_checkLimits('\n')) continue;
/// if the cursor is in the middle of diacriticals, move it back, so the whole char is moved to the next line
while(*cpos> 0) {
if(!Str::isComb(s->d[*cpos- 1]))
break;
(*cpos)--;
}
s->insert('\n', *cpos);
text.nrUnicodes++;
int32 ipos= (*cpos)+ 1;
ixTxtData::Line *p= new ixTxtData::Line;
text.lines.addAfter(p, text.cur.pLine);
/// everything after the cursor is inserted in next line
p->text= s->d+ ipos;
/// everything after cursor is deleted from current line
s->del(s->nrUnicodes- ipos, ipos);
text._updateWrapList(text.cur.pLine);
text._updateWrapList(p);
/// cursor update, move to next line
text.cur.increaseUnicode();
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
}
// backspace
} else if(c== Kch_backSpace) {
if(text.sel) {
_delSelection();
} else if(*cpos> 0) {
/// all diacriticals will be erased, if a char is deleted, not a diacritical
bool wipeCombs= false;
if(isComb(s->d[*cpos- 1]))
wipeCombs= true;
s->del(1, (*cpos)- 1);
text.cur.decreaseUnicode();
text.nrUnicodes--;
if(wipeCombs && *cpos)
while(isComb(s->d[*cpos- 1])) {
s->del(1, (*cpos)- 1);
text.cur.decreaseUnicode();
text.nrUnicodes--;
if(!*cpos) { error.simple("ixEdit::update() - cursor position reached 0, shouldn't have"); break; }
}
text._updateWrapList(text.cur.pLine);
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
/// delete a \n
} else if((*cpos== 0) && (text.cur.line> 0)) {
text.cur.decreaseUnicode();
text.cur.makeSureVisible(); /// asures _view is not on the deleted line
ixTxtData::Line *p1= (ixTxtData::Line *)text.cur.pLine;
ixTxtData::Line *p2= (ixTxtData::Line *)text.cur.pLine->next;
text._delWrapForLine(p2);
// delete '\n' if there is one
if(p1->text.nrUnicodes)
if(p1->text.d[p1->text.nrUnicodes- 1]== '\n') {
//text.cur.decreaseUnicode(); first decrease unicode already does this
p1->text.del();
text.nrUnicodes--;
}
// copy line 2 to line 1's end
p1->text+= p2->text;
text.lines.del(p2); /// delete the second line
text._updateWrapList(p1);
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
}
} else if(c== Kch_delete) {
if(text.sel)
_delSelection();
else if(s->d[*cpos]== '\n') {
ixTxtData::Line *p1= text.cur.pLine;
ixTxtData::Line *p2= (ixTxtData::Line *)p1->next;
s->del(1, *cpos);
text.nrUnicodes--;
if(p2) {
text.cur.makeSureInBounds();
text.cur.makeSureVisible(); /// asure _view is not on the deleted line
text._delWrapForLine(p2);
p1->text+= p2->text;
text.lines.del(p2);
}
text._updateWrapList(p1);
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
} else if(s->d[*cpos]!= 0) {
/// check if to wipe diacriticals. when deleting a char, all it's diacriticals are deleted
bool wipeCombs= false;
if(!isComb(s->d[*cpos]))
wipeCombs= true;
s->del(1, *cpos);
text.nrUnicodes--;
if(wipeCombs)
if(*cpos> 0)
while(isComb(s->d[(*cpos)- 1])) {
s->del(1, (*cpos)- 1);
text.nrUnicodes--;
text.cur.decreaseUnicode();
if(*cpos== 0) break;
}
text._updateWrapList(text.cur.pLine);
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
}
} else if(c== Kch_cut) {
if(text.sel) {
str32 s;
_copy(&s);
osi.setClipboard(s.convert8());
_delSelection();
}
} else if(c== Kch_copy) {
if(text.sel) {
str32 s;
_copy(&s);
osi.setClipboard(s.convert8());
}
} else if(c== Kch_paste) {
str8 s;
osi.getClipboard(&s.d);
s.updateLen();
str32 s32(s);
_paste(&s32);
text.cur.makeSureVisible();
} else if(c== Kch_left) {
text.sel.delData();
text.cur.left();
text.cur.makeSureVisible();
} else if(c== Kch_right) {
text.sel.delData();
text.cur.right();
text.cur.makeSureVisible();
} else if(c== Kch_up) {
text.sel.delData();
text.cur.up();
text.cur.makeSureVisible();
} else if(c== Kch_down) {
text.sel.delData();
text.cur.down();
text.cur.makeSureVisible();
} else if(c== Kch_home) {
text.sel.delData();
text.cur.home();
text.cur.makeSureVisible();
} else if(c== Kch_end) {
text.sel.delData();
text.cur.end();
text.cur.makeSureVisible();
} else if(c== Kch_pgUp) {
text.sel.delData();
text.cur.pgUp();
text.cur.makeSureVisible();
} else if(c== Kch_pgDown) {
text.sel.delData();
text.cur.pgDown();
text.cur.makeSureVisible();
} else if(c== Kch_selLeft) {
text.sel.addLeft();
text.cur.makeSureVisible();
} else if(c== Kch_selRight) {
text.sel.addRight();
text.cur.makeSureVisible();
} else if(c== Kch_selUp) {
text.sel.addUp();
text.cur.makeSureVisible();
} else if(c== Kch_selDown) {
text.sel.addDown();
text.cur.makeSureVisible();
} else if(c== Kch_selHome) {
text.sel.addHome();
text.cur.makeSureVisible();
} else if(c== Kch_selEnd) {
text.sel.addEnd();
text.cur.makeSureVisible();
} else if(c== Kch_selPgUp) {
text.sel.addPgUp();
text.cur.makeSureVisible();
} else if(c== Kch_selPgDown) {
text.sel.addPgDown();
text.cur.makeSureVisible();
// unicode character
} else {
// ONELINES MUST BE FAST, A SPECIAL BRANCH SHOULD BE DONE FOR THEM
if(text.sel) {
_delSelection();
s= &text.cur.pLine->text;
}
if(_checkLimits(c)) {
s->insert(c, *cpos);
text.nrUnicodes++;
text._updateWrapList(text.cur.pLine);
text.cur.increaseUnicode();
text.cur.makeSureInBounds();
text.cur.makeSureVisible();
}
}
if(c!= 0) {
Ix::wsys().flags.setUp((uint32)ixeWSflags::keyboardUsed);
ret= true;
}
} /// process all manip chars
// MOUSE events
//static int32 imx, imy; /// these will hold where the initial click happened
//static int32 iUnicode, iLine; /// the line and unicode when the mouse was initially clicked
// no event currently happening
if(!Ix::wsys()._op.win && in_mIn) {
/// a r-click event starts - can be a SELECTION DRAG or a CURSOR POS CHANGE
if(in.m.but[0].down && r.inside(in.m.x, in.m.y)) {
Ix::wsys()._op.win= this;
Ix::wsys()._op.mRclick= true;
text.sel.delData();
Ix::wsys().bringToFront(this);
Ix::wsys().focus= this;
Ix::wsys().flags.setUp((uint32)ixeWSflags::mouseUsed);
return true;
}
}
// if there are problems with small fonts, and selecting while you don't want selecting,
// selection could happen only if mouse is being hold more than 1 second for example
/// an event is happening with this window involved
if(Ix::wsys()._op.win== this) {
// R-Click event
if(Ix::wsys()._op.mRclick) {
static int32 lx= -1, ly= -1;
// R-Click is being hold down - update cursor & selection
if(in.m.but[0].down) {
/// mouse moved while clicked
if(in.m.x!= lx || in.m.y!= ly) {
/// text coord y is from top to bottom, like a page of text
//text.cur._setLineAndPosInPixels(in.m.x- (r.x0+ _viewArea.x0)+ hscroll->position, (r.y0+ _viewArea.ye)- in.m.y+ vscroll->position);
text.cur._setLineAndPosInPixels(in.m.x- (r.x0+ _viewArea.x0)+ hscroll->position, in.m.y- (r.y0+ _viewArea.y0)+ vscroll->position);
if(!text.sel)
text.sel._startSelection();
text.sel._updateEndFromCursor();
lx= in.m.x, ly= in.m.y;
}
Ix::wsys().flags.setUp((uint32)ixeWSflags::mouseUsed);
return true;
// R-Click end - final cursor and selection positions
} else if(!in.m.but[0].down) { /// mouse r-button released
/// text coord y is from top to bottom, like a page of text
//text.cur._setLineAndPosInPixels(imx- (r.x0+ _viewArea.x0), (r.y0+ _viewArea.ye)- imy);
//text.cur._setLineAndPosInPixels(in.m.x- (r.x0+ _viewArea.x0)+ hscroll->position, (r.y0+ _viewArea.ye)- in.m.y+ vscroll->position);
text.cur._setLineAndPosInPixels(in.m.x- (r.x0+ _viewArea.x0)+ hscroll->position, in.m.y- (r.y0+ _viewArea.y0)+ vscroll->position);
if(text.sel.start== text.sel.end && text.sel.startLine== text.sel.endLine)
text.sel.delData();
Ix::wsys()._op.delData();
lx= ly= -1;
Ix::wsys().flags.setUp((uint32)ixeWSflags::mouseUsed);
return true;
}
} /// r-click event
} /// an event happening with this window
*/
if(ret)
return ret;
// base window update, at this point - no childrens tho, those were updated first
return ixBaseWindow::_update(in_mIn, false);
}
void ixEdit::resize(int32 dx,int32 dy) {
// identic func with ixStatic
// any change here, must happen to the other one too
ixBaseWindow::resize(dx, dy);
text._computeWrapLen();
text._updateWrapList(); // <<< _VIEW AND CUR WILL BE PLACED AT START. THAT IS NOT GOOD
}
void ixEdit::resizeDelta(int32 dx,int32 dy) {
// identic func with ixStatic
// any change here, must happen to the other one too
ixBaseWindow::resizeDelta(dx, dy);
text._computeWrapLen();
text._updateWrapList();
}
void ixEdit::setPos(int32 x0,int32 y0,int32 dx,int32 dy) {
// identic func with ixStatic
// any change here, must happen to the other one too
ixBaseWindow::setPos(x0, y0, dx, dy);
text._computeWrapLen();
text._updateWrapList();
}
void ixEdit::_computeChildArea() {
// identic func with ixStatic
// any change here, must happen to the other one too
ixBaseWindow::_computeChildArea();
if(_childArea.xe< text.textDx)
_childArea.xe= text.textDx;
if(_childArea.ye< text.textDy)
_childArea.ye= text.textDy;
_childArea.compDeltas();
}
// DDDDDD RRRRRR AAAA WW WW
// DD DD RR RR AA AA WW WW
// DD DD RRRRRR AA AA WW WW WW func
// DD DD RR RR AAAAAAAA WW WW WW
// DDDDDD RR RR AA AA WW WW
#ifdef IX_USE_OPENGL
void ixEdit::_glDraw(Ix *in_ix, ixWSsubStyleBase *in_style) {
ixBaseWindow::_glDraw(in_ix, in_style);
/// vars init
recti r;
_getVDviewArea(&r);
vec3i scr;
scr.x= (hscroll? hscroll->position: 0);
scr.y= (vscroll? vscroll->position: 0);
scr.z= 0;
text._glDraw(in_ix, r, scr);
/// scrollbars draw
if(usage.scrollbars || usage.autoScrollbars) {
if(hscroll) hscroll->_glDraw(in_ix);
if(vscroll) vscroll->_glDraw(in_ix);
}
/// childrens draw
for(ixBaseWindow *p= (ixBaseWindow *)childrens.last; p; p= (ixBaseWindow *)p->prev)
if(p!= hscroll && p!= vscroll)
p->_glDraw(in_ix);
}
#endif /// IX_USE_OPENGL
#ifdef IX_USE_VULKAN
void ixEdit::_vkDraw(VkCommandBuffer in_cmd, Ix *in_ix, ixWSsubStyleBase *in_style) {
ixBaseWindow::_vkDraw(in_cmd, in_ix, in_style);
if(!_clip.exists()) return;
if(!is.visible) return;
/// vars init
recti r;
_getVDviewArea(&r);
vec3i scr;
scr.x= (hscroll? hscroll->position: 0);
scr.y= (vscroll? vscroll->position: 0);
scr.z= 0;
text._vkDraw(in_cmd, in_ix, r, scr);
/// scrollbars draw
if(usage._scrollbars || usage._autoScrollbars) {
if(hscroll) hscroll->_vkDraw(in_cmd, in_ix);
if(vscroll) vscroll->_vkDraw(in_cmd, in_ix);
}
/// childrens draw
for(ixBaseWindow *p= (ixBaseWindow *)childrens.last; p; p= (ixBaseWindow *)p->prev)
if(p!= hscroll && p!= vscroll)
p->_vkDraw(in_cmd, in_ix);
}
#endif
| 27.357052 | 142 | 0.594984 | alec101 |
1322c10c45ae0ce1149eff5f930ca22d3ee7e8d2 | 1,452 | cpp | C++ | codes/CodeForces/Round #333/cf601D.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #333/cf601D.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #333/cf601D.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 300005;
const int SIGMA_SIZE = 26;
typedef long long ll;
int SZ = 0;
struct Node {
int sz, ch[SIGMA_SIZE];
Node () { memset(ch, 0, sizeof(ch)); }
}nd[maxn<<1];
int newNode () {
++SZ;
memset(nd[SZ].ch, 0, sizeof(nd[SZ].ch));
return SZ;
}
void maintain(int u) {
nd[u].sz = 1;
for (int i = 0; i < SIGMA_SIZE; i++) if (nd[u].ch[i])
nd[u].sz += nd[nd[u].ch[i]].sz;
}
void merge(int &a, int b) {
if (a == 0) {
a = b;
} else {
for (int i = 0; i < SIGMA_SIZE; i++) {
if (nd[b].ch[i])
merge(nd[a].ch[i], nd[b].ch[i]);
}
}
maintain(a);
}
int N;
ll C[maxn];
char S[maxn];
vector<int> G[maxn];
void init () {
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
G[i].clear();
scanf("%lld", &C[i]);
}
scanf("%s", S + 1);
int u, v;
for (int i = 1; i < N; i++) {
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
}
int dfs(int u, int f) {
int p = newNode();
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == f) continue;
merge(p, dfs(v, u));
}
maintain(p);
int r = newNode();
nd[r].ch[S[u] - 'a'] = p;
maintain(r);
C[u] += nd[r].sz - 1;
return r;
}
int main () {
init();
dfs(1, 0);
ll ans = 0, cnt;
for (int i = 1; i <= N; i++) {
if (C[i] > ans) { ans = C[i]; cnt = 0; }
if (C[i] == ans) { cnt++; }
}
printf("%lld\n%lld\n", ans, cnt);
return 0;
}
| 15.956044 | 54 | 0.500689 | JeraKrs |
132ff24748536db4ced4e3f630155c72286908d3 | 2,683 | cpp | C++ | c++/learncpp/7.x/main.cpp | jleopold28/snippets-and-notes | 0a032ee6ecc31c1e626305464f6ca59bfec90275 | [
"MIT"
] | null | null | null | c++/learncpp/7.x/main.cpp | jleopold28/snippets-and-notes | 0a032ee6ecc31c1e626305464f6ca59bfec90275 | [
"MIT"
] | null | null | null | c++/learncpp/7.x/main.cpp | jleopold28/snippets-and-notes | 0a032ee6ecc31c1e626305464f6ca59bfec90275 | [
"MIT"
] | null | null | null | #include <iostream>
// array is the array to search over.
// target is the value we're trying to determine exists or not.
// min is the index of the lower bounds of the array we're searching.
// max is the index of the upper bounds of the array we're searching.
// binarySearch() should return the index of the target element if the target is found, -1 otherwise
int iterBinarySearch(int *array, int target, int min, int max) {
while(min <= max) {
auto midNum = (min + max) / 2;
auto midValue = array[midNum];
if (target < midValue)
max = midNum - 1;
else if (target > midValue)
min = midNum + 1;
else if (target == midValue)
return midNum;
}
return -1;
}
int recurBinarySearch(int *array, int target, int min, int max) {
if (min > max)
return -1;
auto midNum = (min + max) / 2;
auto midValue = array[midNum];
if (target < midValue)
recurBinarySearch(array, target, min, midNum - 1);
else if (target > midValue)
recurBinarySearch(array, target, midNum + 1, max);
else if (target == midValue)
return midNum;
}
int main(int argc, char *argv[]) {
int array[] = { 3, 6, 8, 12, 14, 17, 20, 21, 26, 32, 36, 37, 42, 44, 48 };
// We're going to test a bunch of values to see if they produce the expected results
const auto numTestValues = 9;
// Here are the test values
int testValues[numTestValues] = { 0, 3, 12, 13, 22, 26, 43, 44, 49 };
// And here are the expected results for each value
int expectedValues[numTestValues] = { -1, 0, 3, -1, -1, 8, -1, 13, -1 };
// Loop through all of the test values
for (auto count=0; count < numTestValues; ++count)
{
// See if our test value is in the array
auto index = iterBinarySearch(array, testValues[count], 0, 14);
// If it matches our expected value, then great!
if (index == expectedValues[count])
std::cout << "test value " << testValues[count] << " passed!\n";
else // otherwise, our binarySearch() function must be broken
std::cout << "test value " << testValues[count] << " failed. There's something wrong with your code!\n";
}
// Loop through all of the test values
for (auto count=0; count < numTestValues; ++count)
{
// See if our test value is in the array
auto index = recurBinarySearch(array, testValues[count], 0, 14);
// If it matches our expected value, then great!
if (index == expectedValues[count])
std::cout << "test value " << testValues[count] << " passed!\n";
else // otherwise, our binarySearch() function must be broken
std::cout << "test value " << testValues[count] << " failed. There's something wrong with your code!\n";
}
return 0;
}
| 35.773333 | 111 | 0.644428 | jleopold28 |
1344a29fb06dbef9a35685f5542a4face8c8c2d3 | 369 | cpp | C++ | elastic-circuits/examples/order_test_1.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 46 | 2019-11-16T13:44:07.000Z | 2022-03-12T14:28:44.000Z | elastic-circuits/examples/order_test_1.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 11 | 2020-05-12T17:20:51.000Z | 2022-02-04T10:04:59.000Z | elastic-circuits/examples/order_test_1.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 22 | 2020-02-21T21:33:40.000Z | 2022-02-24T06:50:41.000Z | //------------------------------------------------------------------------
// FIR
//------------------------------------------------------------------------
void order_test(int Out[10]) {
int i, j;
int tmp = 0;
for (i = 0; i < 10; i++) {
tmp = 0;
for (j = 0; j < 10; j++) {
tmp *= tmp;
}
Out[i] = tmp;
}
}
| 20.5 | 74 | 0.195122 | minseongg |
13484b2d65807de00c93eae4e737217de43f0961 | 382 | hpp | C++ | networklib/include/networklib/https_read.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | networklib/include/networklib/https_read.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | networklib/include/networklib/https_read.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | #ifndef NETWORKLIB_HTTPS_READ_HPP
#define NETWORKLIB_HTTPS_READ_HPP
#include <networklib/response.hpp>
#include <networklib/socket.hpp>
namespace network {
/// Reads a Reponse from \p socket.
/** \p socket should come from a call to `https_write(Request)`. */
[[nodiscard]] auto https_read(Socket socket) -> Response;
} // namespace network
#endif // NETWORKLIB_HTTPS_READ_HPP
| 27.285714 | 67 | 0.76178 | zina1995 |
134956da110729d74ea82ff7f0c5b09ddf58556f | 5,374 | cc | C++ | shared_vs_unique_ptr/benchmark.cc | xysperi/benchmark | a1fd0bb10842329e1c17a25768d23e3d725f60ef | [
"MIT"
] | null | null | null | shared_vs_unique_ptr/benchmark.cc | xysperi/benchmark | a1fd0bb10842329e1c17a25768d23e3d725f60ef | [
"MIT"
] | null | null | null | shared_vs_unique_ptr/benchmark.cc | xysperi/benchmark | a1fd0bb10842329e1c17a25768d23e3d725f60ef | [
"MIT"
] | null | null | null | #include <benchmark/benchmark.h>
#include <memory>
#include <atomic>
#include <boost/smart_ptr/intrusive_ptr.hpp>
struct X {
std::atomic<size_t> ref_cnt{0};
};
inline void intrusive_ptr_add_ref(X* x){
x->ref_cnt.fetch_add(1, std::memory_order_relaxed);
}
inline void intrusive_ptr_release(X* x){
if (x->ref_cnt.fetch_sub(1, std::memory_order_release) == 1) {
x->ref_cnt.load(std::memory_order_acquire);
delete x;
}
}
static void BM_construct_and_destruct_shared_ptr(benchmark::State& state) {
for (auto _ : state) {
auto p = std::make_shared<X>();
benchmark::DoNotOptimize(p);
}
}
BENCHMARK(BM_construct_and_destruct_shared_ptr);
static void BM_construct_and_destruct_intrusive_ptr(benchmark::State& state) {
for (auto _ : state) {
boost::intrusive_ptr p(new X());
benchmark::DoNotOptimize(p);
}
}
BENCHMARK(BM_construct_and_destruct_intrusive_ptr);
static void BM_construct_and_destruct_unique_ptr(benchmark::State& state) {
for (auto _ : state) {
auto p = std::make_unique<X>();
benchmark::DoNotOptimize(p);
}
}
BENCHMARK(BM_construct_and_destruct_unique_ptr);
static void BM_construct_and_destruct_raw_ptr(benchmark::State& state) {
for (auto _ : state) {
auto p = new X();
benchmark::DoNotOptimize(p);
delete p;
}
}
BENCHMARK(BM_construct_and_destruct_raw_ptr);
static void BM_copy_shared_ptr(benchmark::State& state) {
auto p = std::make_shared<X>();
for (auto _ : state) {
// two copies (back and forth)
auto q = p;
p = q;
benchmark::DoNotOptimize(p);
benchmark::DoNotOptimize(q);
}
}
BENCHMARK(BM_copy_shared_ptr);
static void BM_copy_intrusive_ptr(benchmark::State& state) {
boost::intrusive_ptr<X> p(new X());
for (auto _ : state) {
// two copies (back and forth)
auto q = p;
p = q;
benchmark::DoNotOptimize(p);
benchmark::DoNotOptimize(q);
}
}
BENCHMARK(BM_copy_intrusive_ptr);
static void BM_move_unique_ptr(benchmark::State& state) {
auto p = std::make_unique<X>();
for (auto _ : state) {
// two moves (back and forth)
auto q = std::move(p);
p = std::move(q);
benchmark::DoNotOptimize(p);
benchmark::DoNotOptimize(q);
}
}
BENCHMARK(BM_move_unique_ptr);
static void BM_copy_raw_ptr(benchmark::State& state) {
auto p = new X();
for (auto _ : state) {
// two copies (back and forth)
auto q = p;
p = q;
benchmark::DoNotOptimize(p);
benchmark::DoNotOptimize(q);
}
delete p;
}
BENCHMARK(BM_copy_raw_ptr);
struct workload {
char buffer_[4096];
void copy_string_len(char const *b, size_t const len) {
memcpy(buffer_, b, len); buffer_[len] = '\0';
}
};
struct workload_with_user_defined_ref_count : public workload {
std::atomic<size_t> ref_cnt{0};
};
inline void intrusive_ptr_add_ref(workload_with_user_defined_ref_count* x){
x->ref_cnt.fetch_add(1, std::memory_order_relaxed);
}
inline void intrusive_ptr_release(workload_with_user_defined_ref_count* x){
if (x->ref_cnt.fetch_sub(1, std::memory_order_release) == 1) {
x->ref_cnt.load(std::memory_order_acquire);
delete x;
}
}
constexpr size_t iterations = 1000;
static void BM_shared_ptr_with_workload(benchmark::State& state) {
for (auto _ : state) {
for (size_t i = 0; i < iterations; ++i) {
auto p = std::make_shared<workload>();
p->copy_string_len("testing", 7);
benchmark::DoNotOptimize(p);
}
}
}
BENCHMARK(BM_shared_ptr_with_workload);
static void BM_intrusive_ptr_with_workload(benchmark::State& state) {
for (auto _ : state) {
for (size_t i = 0; i < iterations; ++i) {
boost::intrusive_ptr<workload_with_user_defined_ref_count> p(new workload_with_user_defined_ref_count());
p->copy_string_len("testing", 7);
benchmark::DoNotOptimize(p);
}
}
}
BENCHMARK(BM_intrusive_ptr_with_workload);
static void BM_raw_ptr_with_workload(benchmark::State& state) {
for (auto _ : state) {
for (size_t i = 0; i < iterations; ++i) {
auto p = new workload();
p->copy_string_len("testing", 7);
benchmark::DoNotOptimize(p);
delete p;
}
}
}
BENCHMARK(BM_raw_ptr_with_workload);
static void BM_unique_ptr_with_workload(benchmark::State& state) {
for (auto _ : state) {
for (size_t i = 0; i < iterations; ++i) {
auto p = std::make_unique<workload>();
p->copy_string_len("testing", 7);
benchmark::DoNotOptimize(p);
}
}
}
BENCHMARK(BM_unique_ptr_with_workload);
BENCHMARK_MAIN();
/* sample numbers
Run on (8 X 2800 MHz CPU s)
CPU Caches:
L1 Data 32K (x4)
L1 Instruction 32K (x4)
L2 Unified 262K (x4)
L3 Unified 6291K (x1)
Load Average: 2.25, 2.31, 2.34
-------------------------------------------------------------------------------
Benchmark Time CPU Iterations
-------------------------------------------------------------------------------
BM_construct_and_destruct_raw_ptr 68.5 ns 68.5 ns 10028079
BM_construct_and_destruct_shared_ptr 81.3 ns 81.2 ns 8493084
BM_construct_and_destruct_unique_ptr 70.3 ns 70.2 ns 9864991
BM_copy_shared_ptr 22.3 ns 22.2 ns 30460740
BM_move_unique_ptr 1.38 ns 1.37 ns 514433535
BM_copy_raw_ptr 0.272 ns 0.271 ns 1000000000
*/
| 27.558974 | 111 | 0.648493 | xysperi |
134b9f74de8ef7b16e053a9826450f320637db63 | 1,037 | cpp | C++ | GLFX/GLEffects/GUIManager.cpp | luca1337/GLFX | b6e6e18228d76d82d5080a4eb55434a4b7fec18d | [
"MIT"
] | null | null | null | GLFX/GLEffects/GUIManager.cpp | luca1337/GLFX | b6e6e18228d76d82d5080a4eb55434a4b7fec18d | [
"MIT"
] | null | null | null | GLFX/GLEffects/GUIManager.cpp | luca1337/GLFX | b6e6e18228d76d82d5080a4eb55434a4b7fec18d | [
"MIT"
] | null | null | null | #include "GUIManager.h"
#include "GObjectHierarchy.h"
#include "GToolBar.h"
#include "GUIUtils.h"
#include <GLFW/glfw3.h>
namespace glfx::gui
{
auto GUIManager::Init(GLFWwindow* window) -> void
{
IMGUI_CHECKVERSION();
// todo: handle errors properly
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init();
ImGui::StyleColorsDark();
m_hierarchy = std::make_shared<GObjectHierarchy>();
m_tool_bar = std::make_shared<GToolBar>();
}
auto GUIManager::RenderAll(const double delta_time) -> void
{
// just call it here 1 time
BEGIN_FRAME();
m_tool_bar->Render(delta_time);
m_hierarchy->Render(delta_time);
}
auto GUIManager::SubmitAll() -> void
{
END_FRAME();
}
auto GUIManager::CleanUp() -> void
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
} | 23.044444 | 63 | 0.614272 | luca1337 |
134cb153ed03a668f491f0588b78fef18ce44daf | 2,794 | cpp | C++ | ops/FrictionResponse.cpp | parduino/MDOF | c4272ce52309383bd29c941e5e760ce441a8dae3 | [
"BSD-2-Clause"
] | 8 | 2019-03-05T16:25:10.000Z | 2020-04-17T14:12:03.000Z | ops/FrictionResponse.cpp | parduino/MDOF | c4272ce52309383bd29c941e5e760ce441a8dae3 | [
"BSD-2-Clause"
] | 6 | 2017-05-16T22:08:40.000Z | 2018-09-24T05:52:00.000Z | ops/FrictionResponse.cpp | parduino/MDOF | c4272ce52309383bd29c941e5e760ce441a8dae3 | [
"BSD-2-Clause"
] | 20 | 2017-03-21T17:31:32.000Z | 2021-12-19T15:45:23.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 4952 $
// $Date: 2012-08-08 22:56:05 -0700 (Wed, 08 Aug 2012) $
// $URL: svn://opensees.berkeley.edu/usr/local/svn/OpenSees/trunk/SRC/element/frictionBearing/frictionModel/FrictionResponse.cpp $
// Written: Andreas Schellenberg (andreas.schellenberg@gmail.com)
// Created: 02/06
// Revision: A
//
// Description: This file contains the FrictionResponse class implementation
#include <FrictionResponse.h>
#include <FrictionModel.h>
FrictionResponse::FrictionResponse(FrictionModel *frn, int id)
: Response(), theFriction(frn), responseID(id)
{
}
FrictionResponse::FrictionResponse(FrictionModel *frn, int id, int val)
: Response(val), theFriction(frn), responseID(id)
{
}
FrictionResponse::FrictionResponse(FrictionModel *frn, int id, double val)
: Response(val), theFriction(frn), responseID(id)
{
}
FrictionResponse::FrictionResponse(FrictionModel *frn, int id, const ID &val)
: Response(val), theFriction(frn), responseID(id)
{
}
FrictionResponse::FrictionResponse(FrictionModel *frn, int id, const Vector &val)
: Response(val), theFriction(frn), responseID(id)
{
}
FrictionResponse::FrictionResponse(FrictionModel *frn, int id, const Matrix &val)
: Response(val), theFriction(frn), responseID(id)
{
}
FrictionResponse::~FrictionResponse()
{
}
int FrictionResponse::getResponse()
{
return theFriction->getResponse(responseID, myInfo);
}
| 32.114943 | 130 | 0.540802 | parduino |
134ff642c03252d0c72f0abcc6983c4568ce2fe3 | 626 | hpp | C++ | bnb_sdk_manager/src/GlfwWindow.hpp | vadimVoloshanov/quickstart-desktop-cpp | a73dafce9668f57cc64d94411e68603f1d5a2a7a | [
"MIT"
] | null | null | null | bnb_sdk_manager/src/GlfwWindow.hpp | vadimVoloshanov/quickstart-desktop-cpp | a73dafce9668f57cc64d94411e68603f1d5a2a7a | [
"MIT"
] | null | null | null | bnb_sdk_manager/src/GlfwWindow.hpp | vadimVoloshanov/quickstart-desktop-cpp | a73dafce9668f57cc64d94411e68603f1d5a2a7a | [
"MIT"
] | null | null | null | #pragma once
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <string>
#include <async++.h>
class GlfwWindow
{
public:
explicit GlfwWindow(const std::string& title);
~GlfwWindow();
void show(uint32_t width_hint, uint32_t height_hint);
void run_main_loop();
[[nodiscard]] GLFWwindow* get_window() const
{
return m_window;
}
private:
// To execute scheduled tasks wake up main loop (glfwPostEmptyEvent)
async::fifo_scheduler m_scheduler;
GLFWwindow* m_window{};
void init();
void create_window(const std::string& title);
void load_glad_functions();
}; | 20.193548 | 72 | 0.688498 | vadimVoloshanov |
1350f5e0768a4df235ccb1d5902d5c199ecdbc1a | 187 | cpp | C++ | OpenTESArena/src/World/MapInstance.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/MapInstance.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/MapInstance.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | #include "MapInstance.h"
void MapInstance::init(int levelCount)
{
this->levels.init(levelCount);
}
LevelInstance &MapInstance::getLevel(int index)
{
return this->levels.get(index);
}
| 15.583333 | 47 | 0.743316 | Digital-Monk |
135200e5f1410044cd6f6f2eba3dca7b441ab846 | 1,548 | hpp | C++ | include/nbdl/detail/promise_join.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 47 | 2016-06-20T01:41:24.000Z | 2021-11-16T10:53:27.000Z | include/nbdl/detail/promise_join.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 21 | 2015-11-12T23:05:47.000Z | 2019-07-17T19:01:40.000Z | include/nbdl/detail/promise_join.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 6 | 2015-11-12T21:23:29.000Z | 2019-05-09T17:54:25.000Z | //
// Copyright Jason Rice 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_DETAIL_PROMISE_JOIN_HPP
#define NBDL_DETAIL_PROMISE_JOIN_HPP
#include <nbdl/detail/wrap_promise.hpp>
#include <nbdl/fwd/detail/promise_join.hpp>
#include <nbdl/fwd/hold_lazy.hpp>
#include <boost/hana/concept/foldable.hpp>
#include <boost/hana/core/is_a.hpp>
#include <boost/hana/fold_right.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/type.hpp>
#include <utility>
namespace nbdl::detail
{
template <typename Current, typename Next>
auto promise_join_fn::operator()(Current&& current, Next&& next) const
{
if constexpr(hana::Foldable<Current>::value)
{
return hana::fold_right(
std::forward<Current>(current)
, std::forward<Next>(next)
, detail::promise_join_fn{}
);
}
else if constexpr(decltype(hana::is_a<make_lazy_holder_tag, Current>)::value)
{
using Promise = decltype(current(hana::typeid_(next)));
return promise_join_t<Promise, std::decay_t<Next>>(
std::forward<Current>(current)(hana::typeid_(next))
, std::forward<Next>(next)
);
}
else
{
using WrappedPromise = decltype(wrap_promise(std::forward<Current>(current)));
return promise_join_t<WrappedPromise, std::decay_t<Next>>(
wrap_promise(std::forward<Current>(current))
, std::forward<Next>(next)
);
}
}
}
#endif
| 27.642857 | 84 | 0.689276 | ricejasonf |
1352162527facd7fa0a1f86f9a3b862d632d9037 | 10,971 | hpp | C++ | examples/implicit/coupled.hpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 7 | 2018-01-19T00:19:19.000Z | 2021-06-22T00:53:00.000Z | examples/implicit/coupled.hpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 66 | 2021-06-22T22:44:21.000Z | 2022-03-16T15:18:00.000Z | examples/implicit/coupled.hpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 6 | 2017-04-13T19:42:27.000Z | 2022-03-26T18:46:24.000Z | // SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com>
// SPDX-License-Identifier: MIT
#ifndef IMPLICIT_COUPLED_HPP
#define IMPLICIT_COUPLED_HPP
#include "ads/executor/galois.hpp"
#include "ads/lin/dense_matrix.hpp"
#include "ads/lin/dense_solve.hpp"
#include "ads/output_manager.hpp"
#include "ads/simulation.hpp"
namespace ads {
class coupled : public simulation_2d {
private:
using Base = simulation_2d;
using vector_view = lin::tensor_view<double, 2>;
std::vector<double> sol, buf; // Buffers for keeping the combined RHS vectors
// Two sets of vectors for two coupled equations
vector_type u, u_prev;
vector_type u2, u2_prev;
output_manager<2> output;
galois_executor executor{4};
// Large matrices - dense matrices + data for solver
lin::dense_matrix Ax, Ay;
lin::solver_ctx Ax_ctx, Ay_ctx;
// NEW: Mass matrices for the periodic basis
lin::dense_matrix Mx, My;
lin::solver_ctx Mx_ctx, My_ctx;
double s = 40;
public:
explicit coupled(const config_2d& config)
: Base{config}
, sol(2 * (x.dofs() - 1) * (y.dofs() - 1))
, buf(2 * (x.dofs() - 1) * (y.dofs() - 1))
, u{shape()}
, u_prev{shape()}
, u2{shape()}
, u2_prev{shape()}
, output{x.B, y.B, 200}
, Ax{2 * (x.dofs() - 1), 2 * (x.dofs() - 1)} // 2x2 matrix for x direction
, Ay{2 * (y.dofs() - 1), 2 * (y.dofs() - 1)} // 2x2 matrix for y direction
, Ax_ctx{Ax}
, Ay_ctx{Ay}
, Mx{x.dofs() - 1, x.dofs() - 1} // NEW: initialization of mass matrices
, My{y.dofs() - 1, y.dofs() - 1}
, Mx_ctx{Mx}
, My_ctx{My} {
// Fill the large matrices
matrix(Ax, x.basis, steps.dt);
matrix(Ay, y.basis, steps.dt);
// NEW: Fill the mass matrices
mass_matrix(Mx, x.basis, steps.dt);
mass_matrix(My, y.basis, steps.dt);
}
double init_state(double x, double y) {
double dx = x - 0.5;
double dy = y - 0.5;
double r2 = std::min(20 * (dx * dx + dy * dy), 1.0);
return (r2 - 1) * (r2 - 1) * (r2 + 1) * (r2 + 1);
}
private:
// NEW: Mass matrix no longer diagonal
void mass_matrix(lin::dense_matrix& M, const basis_data& d, double /*h*/) {
auto N = d.basis.dofs() - 1;
for (element_id e = 0; e < d.elements; ++e) {
for (int q = 0; q < d.quad_order; ++q) {
int first = d.first_dof(e);
int last = d.last_dof(e);
for (int a = 0; a + first <= last; ++a) {
for (int b = 0; b + first <= last; ++b) {
int ia = a + first;
int ib = b + first;
auto va = d.b[e][q][0][a];
auto vb = d.b[e][q][0][b];
M(ia % N, ib % N) += va * vb * d.w[q] * d.J[e]; // upper left
}
}
}
}
}
void matrix(lin::dense_matrix& K, const basis_data& d, double h) const {
auto N = d.basis.dofs() - 1;
for (element_id e = 0; e < d.elements; ++e) {
for (int q = 0; q < d.quad_order; ++q) {
int first = d.first_dof(e);
int last = d.last_dof(e);
for (int a = 0; a + first <= last; ++a) {
for (int b = 0; b + first <= last; ++b) {
int ia = a + first;
int ib = b + first;
auto va = d.b[e][q][0][a];
auto vb = d.b[e][q][0][b];
auto da = d.b[e][q][1][a];
auto db = d.b[e][q][1][b];
auto val = va * vb + 0.5 * h * da * db - 0.5 * h * s * va * db;
K(ia % N, ib % N) += val * d.w[q] * d.J[e]; // upper left
K(N + ia % N, N + ib % N) += val * d.w[q] * d.J[e]; // lower right
// Mass-Mass-Stiffness matrix (what you need if I recall correctly):
// K(ia, ib) += va * vb * d.w[q] * d.J[e]; // upper left
// K(N + ia, N + ib) += va * vb * d.w[q] * d.J[e]; // lower right
// K(N + ia, ib) += da * db * d.w[q] * d.J[e]; // lower left
}
}
}
}
}
void prepare_matrices() {
Base::prepare_matrices();
// Dense factorization (overloaded function)
lin::factorize(Ax, Ax_ctx);
lin::factorize(Ay, Ay_ctx);
// NEW: factorize mass matrices
lin::factorize(Mx, Mx_ctx);
lin::factorize(My, My_ctx);
}
void before() override {
prepare_matrices();
auto init = [this](double x, double y) { return init_state(2 * x - 1, y); };
projection(u, init);
solve(u);
output.to_file(u, "out1_0.data");
auto init2 = [this](double x, double y) { return init_state(x, y - 0.3); };
projection(u2, init2);
solve(u2);
output.to_file(u2, "out2_0.data");
}
void before_step(int /*iter*/, double /*t*/) override {
using std::swap;
swap(u, u_prev);
swap(u2, u2_prev);
}
void step(int /*iter*/, double /*t*/) override {
compute_rhs_1();
// NEW: different size and indices are taken mod Nx, Ny to ensure periodic BC
int Nx = x.dofs() - 1;
int Ny = y.dofs() - 1;
// Copy data from separate RHS vectors to the combined one
std::fill(begin(sol), end(sol), 0);
vector_view view_x{sol.data(), {2 * Nx, Ny}};
for (auto i = 0; i < x.dofs(); ++i) {
for (auto j = 0; j < y.dofs(); ++j) {
view_x(i % Nx, j % Ny) += u(i, j);
view_x(Nx + i % Nx, j % Ny) += u2(i, j);
}
}
// ads_solve(u, buffer, dim_data{Kx, x.ctx}, y.data());
// ads_solve(u2, buffer, dim_data{Kx, x.ctx}, y.data());
// Expanded ADS call:
lin::solve_with_factorized(Ax, view_x, Ax_ctx);
auto F = lin::cyclic_transpose(view_x, buf.data());
// NEW: periodic mass matrix instead of a standard one
// lin::solve_with_factorized(y.data().M, F, y.data().ctx);
lin::solve_with_factorized(My, F, My_ctx);
lin::cyclic_transpose(F, view_x);
// ... and copy the solutions back to the separate vectors
for (auto i = 0; i < x.dofs(); ++i) {
for (auto j = 0; j < y.dofs(); ++j) {
u(i, j) = view_x(i % Nx, j % Ny);
u2(i, j) = view_x(Nx + i % Nx, j % Ny);
}
}
using std::swap;
swap(u, u_prev);
swap(u2, u2_prev);
compute_rhs_2();
// Copy data from separate RHS vectors to the combined one
std::fill(begin(sol), end(sol), 0);
vector_view view_y{sol.data(), {Nx, 2 * Ny}};
for (auto i = 0; i < x.dofs(); ++i) {
for (auto j = 0; j < y.dofs(); ++j) {
view_y(i % Nx, j % Ny) += u(i, j);
view_y(i % Nx, Ny + j % Ny) += u2(i, j);
}
}
// ads_solve(u, buffer, x.data(), dim_data{Ky, y.ctx});
// ads_solve(u2, buffer, x.data(), dim_data{Ky, y.ctx});
// Expanded ADS call:
// NEW: periodic mass matrix instead of a standard one
// lin::solve_with_factorized(x.data().M, view_y, x.data().ctx);
lin::solve_with_factorized(Mx, view_y, Mx_ctx);
auto F2 = lin::cyclic_transpose(view_y, buf.data());
lin::solve_with_factorized(Ay, F2, Ay_ctx);
lin::cyclic_transpose(F2, view_y);
// ... and copy the solutions back to the separate vectors
for (auto i = 0; i < x.dofs(); ++i) {
for (auto j = 0; j < y.dofs(); ++j) {
u(i, j) = view_y(i % Nx, j % Ny);
u2(i, j) = view_y(i % Nx, Ny + j % Ny);
}
}
}
void after_step(int iter, double /*t*/) override {
if ((iter + 1) % 1 == 0) {
std::cout << "Iter " << iter << std::endl;
output.to_file(u, "out1_%d.data", iter + 1);
output.to_file(u2, "out2_%d.data", iter + 1);
}
}
void compute_rhs_1() {
auto& rhs = u;
auto& rhs2 = u2;
zero(rhs);
zero(rhs2);
executor.for_each(elements(), [&](index_type e) {
auto U = element_rhs();
auto U2 = element_rhs();
double J = jacobian(e);
for (auto q : quad_points()) {
double w = weight(q);
for (auto a : dofs_on_element(e)) {
auto aa = dof_global_to_local(e, a);
value_type v = eval_basis(e, q, a);
value_type u = eval_fun(u_prev, e, q);
value_type u2 = eval_fun(u2_prev, e, q);
double gradient_prod = u.dy * v.dy;
double val = u.val * v.val - 0.5 * steps.dt * gradient_prod
+ 0.5 * steps.dt * s * u.dy * v.val;
U(aa[0], aa[1]) += val * w * J;
gradient_prod = u2.dy * v.dy;
val = u2.val * v.val - 0.5 * steps.dt * gradient_prod
+ 0.5 * steps.dt * s * u2.dy * v.val;
U2(aa[0], aa[1]) += val * w * J;
}
}
executor.synchronized([&]() {
update_global_rhs(rhs, U, e);
update_global_rhs(rhs2, U2, e);
});
});
}
void compute_rhs_2() {
auto& rhs = u;
auto& rhs2 = u2;
zero(rhs);
zero(rhs2);
executor.for_each(elements(), [&](index_type e) {
auto U = element_rhs();
auto U2 = element_rhs();
double J = jacobian(e);
for (auto q : quad_points()) {
double w = weight(q);
for (auto a : dofs_on_element(e)) {
auto aa = dof_global_to_local(e, a);
value_type v = eval_basis(e, q, a);
value_type u = eval_fun(u_prev, e, q);
value_type u2 = eval_fun(u2_prev, e, q);
double gradient_prod = u.dx * v.dx;
double val = u.val * v.val - 0.5 * steps.dt * gradient_prod
+ 0.5 * steps.dt * s * u.dx * v.val;
U(aa[0], aa[1]) += val * w * J;
gradient_prod = u2.dx * v.dx;
val = u2.val * v.val - 0.5 * steps.dt * gradient_prod
+ 0.5 * steps.dt * s * u2.dx * v.val;
U2(aa[0], aa[1]) += val * w * J;
}
}
executor.synchronized([&]() {
update_global_rhs(rhs, U, e);
update_global_rhs(rhs2, U2, e);
});
});
}
};
} // namespace ads
#endif // IMPLICIT_COUPLED_HPP
| 35.163462 | 92 | 0.461763 | Pan-Maciek |
1353f08f993e62878458ac7d25b14b033bd00dbd | 2,910 | cpp | C++ | libs/bimap/example/mi_to_b_path/hashed_indices.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/bimap/example/mi_to_b_path/hashed_indices.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/bimap/example/mi_to_b_path/hashed_indices.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Boost.Bimap Example
//-----------------------------------------------------------------------------
// Hashed indices can be used as an alternative to ordered indices when fast
// lookup is needed and sorting information is of no interest. The example
// features a word counter where duplicate entries are checked by means of a
// hashed index.
#include <boost/config.hpp>
//[ code_mi_to_b_path_hashed_indices
#include <iostream>
#include <iomanip>
#include <boost/tokenizer.hpp>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap/support/lambda.hpp>
using namespace boost::bimaps;
struct word {};
struct occurrences {};
typedef bimap
<
multiset_of< tagged<unsigned int,occurrences>, std::greater<unsigned int> >,
unordered_set_of< tagged< std::string, word> >
> word_counter;
typedef boost::tokenizer<boost::char_separator<char> > text_tokenizer;
int main()
{
std::string text=
"Relations between data in the STL are represented with maps."
"A map is a directed relation, by using it you are representing "
"a mapping. In this directed relation, the first type is related to "
"the second type but it is not true that the inverse relationship "
"holds. This is useful in a lot of situations, but there are some "
"relationships that are bidirectional by nature.";
// feed the text into the container
word_counter wc;
text_tokenizer tok(text,boost::char_separator<char>(" \t\n.,;:!?'\"-"));
unsigned int total_occurrences = 0;
for( text_tokenizer::const_iterator it = tok.begin(), it_end = tok.end();
it != it_end ; ++it )
{
++total_occurrences;
word_counter::map_by<occurrences>::iterator wit =
wc.by<occurrences>().insert(
word_counter::map_by<occurrences>::value_type(0,*it)
).first;
wc.by<occurrences>().modify_key( wit, ++_key);
}
// list words by frequency of appearance
std::cout << std::fixed << std::setprecision(2);
for( word_counter::map_by<occurrences>::const_iterator
wit = wc.by<occurrences>().begin(),
wit_end = wc.by<occurrences>().end();
wit != wit_end; ++wit )
{
std::cout << std::setw(15) << wit->get<word>() << ": "
<< std::setw(5)
<< 100.0 * wit->get<occurrences>() / total_occurrences << "%"
<< std::endl;
}
return 0;
}
//]
| 30.631579 | 83 | 0.597595 | zyiacas |
135c78cda460225b910f634dce0ebd4504307064 | 17,423 | cc | C++ | psdaq/psdaq/eb/EbLfLink.cc | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/eb/EbLfLink.cc | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/eb/EbLfLink.cc | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "EbLfLink.hh"
#include "Endpoint.hh"
#include "psdaq/service/fast_monotonic_clock.hh"
#include <chrono>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace Pds;
using namespace Pds::Fabrics;
using namespace Pds::Eb;
using ms_t = std::chrono::milliseconds;
static int checkMr(Fabric* fabric,
void* region,
size_t size,
MemoryRegion* mr,
const unsigned& verbose)
{
//printf("*** PE::checkMr: mr %p, start %p, region %p, len %zu, size %zu\n",
// mr, mr->start(), region, mr->length(), size);
if ((region == mr->start()) && (size <= mr->length()))
{
if (verbose)
{
printf("Reusing MR: %10p : %10p, size 0x%08zx = %zu\n",
mr->start(), (char*)(mr->start()) + mr->length(),
mr->length(), mr->length());
}
return 0;
}
if (!fabric->deregister_memory(mr))
{
fprintf(stderr, "%s:\n Failed to deregister MR %p (%p, %zu)\n",
__PRETTY_FUNCTION__, mr, mr->start(), mr->length());
}
if (verbose > 1)
{
printf("Freed MR: %10p : %10p, size 0x%08zx = %zu\n",
mr->start(), (char*)(mr->start()) + mr->length(),
mr->length(), mr->length());
}
return 1;
}
int Pds::Eb::setupMr(Fabric* fabric,
void* region,
size_t size,
MemoryRegion** memReg,
const unsigned& verbose)
{
//printf("*** PE::setupMr: memReg %p, *memReg %p, region %p, size %zu\n",
// memReg, memReg ? *memReg : 0, region, size);
// If *memReg describes a region, check that its size is appropriate
if (memReg && *memReg && !checkMr(fabric, region, size, *memReg, verbose))
{
return 0;
}
// If there's a MR for the region, check that its size is appropriate
MemoryRegion* mr = fabric->lookup_memory(region, sizeof(uint8_t));
//printf("*** PE::setupMr: mr lkup %p, region %p, size %zu\n", mr, region, size);
if (mr && !checkMr(fabric, region, size, mr, verbose))
{
if (memReg) *memReg = mr;
return 0;
}
mr = fabric->register_memory(region, size);
//printf("*** PE::setupMr: mr new %p, region %p, size %zu\n", mr, region, size);
if (memReg) *memReg = mr; // Even on error, set *memReg
if (!mr)
{
fprintf(stderr, "%s:\n Failed to register MR @ %p, size %zu: %s\n",
__PRETTY_FUNCTION__, region, size, fabric->error());
return fabric->error_num();
}
if (verbose)
{
printf("Registered MR: %10p : %10p, size 0x%08zx = %zu\n",
mr->start(), (char*)(mr->start()) + mr->length(),
mr->length(), mr->length());
}
return 0;
}
// ---
EbLfLink::EbLfLink(Endpoint* ep,
int depth,
const unsigned& verbose) :
_id (-1),
_ep (ep),
_mr (nullptr),
_verbose (verbose),
_timedOut(0ull),
_depth (depth)
{
postCompRecv(depth);
}
int EbLfLink::recvU32(uint32_t* u32,
const char* peer,
const char* name)
{
ssize_t rc;
uint64_t data;
if ((rc = poll(&data, 7000)))
{
const char* errMsg = rc == -FI_EAGAIN ? "Timed out" : _ep->error();
fprintf(stderr, "%s:\n Failed to receive %s from %s: %s\n",
__PRETTY_FUNCTION__, name, peer, errMsg);
return rc;
}
*u32 = data;
if (_verbose > 1) printf("Received %s's %s: 0x%08x = %d\n",
peer, name, *u32, *u32);
return 0;
}
int EbLfLink::sendU32(uint32_t u32,
const char* peer,
const char* name)
{
ssize_t rc;
uint64_t imm = u32;
if ((rc = post(imm)))
{
const char* errMsg = rc == -FI_ETIMEDOUT ? "Timed out" : _ep->error();
fprintf(stderr, "%s:\n Failed to send %s to %s: %s\n",
__PRETTY_FUNCTION__, name, peer, errMsg);
return rc;
}
if (_verbose > 1) printf("Sent %s %s 0x%08x = %d\n",
peer, name, u32, u32);
return 0;
}
int EbLfLink::recvMr(RemoteAddress& ra,
const char* peer)
{
ssize_t rc;
unsigned* ptr = reinterpret_cast<unsigned*>(&ra);
for (unsigned i = 0; i < sizeof(ra)/sizeof(*ptr); ++i)
{
uint64_t imm;
if ((rc = poll(&imm, 7000)))
{
const char* errMsg = rc == -FI_EAGAIN ? "Timed out" : _ep->error();
fprintf(stderr, "%s:\n Failed to receive %s from %s ID %d: %s\n",
__PRETTY_FUNCTION__, "remote region specs", peer, _id, errMsg);
return rc;
}
*ptr++ = imm & 0x00000000ffffffffull;
}
if (_verbose > 1)
{
printf("Received %s's MR: %10p : %10p, size 0x%08zx = %zu\n", peer,
(void*)ra.addr, (void*)(ra.addr + ra.extent), ra.extent, ra.extent);
}
return 0;
}
int EbLfLink::sendMr(MemoryRegion* mr,
const char* peer)
{
ssize_t rc;
RemoteAddress ra(mr->rkey(), (uint64_t)mr->start(), mr->length());
unsigned* ptr = reinterpret_cast<unsigned*>(&ra);
for (unsigned i = 0; i < sizeof(ra)/sizeof(*ptr); ++i)
{
uint64_t imm = *ptr++;
if ((rc = post(imm)) < 0)
{
const char* errMsg = rc == -FI_ETIMEDOUT ? "Timed out" : _ep->error();
fprintf(stderr, "%s:\n Failed to send %s to %s ID %d: %s\n",
__PRETTY_FUNCTION__, "local memory specs", peer, _id, errMsg);
return rc;
}
}
if (_verbose > 1)
{
printf("Sent %s MR: %10p : %10p, size 0x%08zx = %zu\n", peer,
(void*)ra.addr, (void*)(ra.addr + ra.extent), ra.extent, ra.extent);
}
return 0;
}
// ---
EbLfSvrLink::EbLfSvrLink(Endpoint* ep,
int depth,
const unsigned& verbose) :
EbLfLink(ep, depth, verbose)
{
}
int EbLfSvrLink::_synchronizeBegin()
{
int rc;
// Send a synchronization message to _one_ client
uint64_t imm = _BegSync; // Use a different value from Clients
if ( (rc = EbLfLink::post(imm)) ) return rc;
// Drain any stale transmissions that are stuck in the pipe
while ((rc = EbLfLink::poll(&imm, 60000)) == 0)
{
if (imm == _EndSync) break; // Break on synchronization message
fprintf(stderr, "%s: Got junk from id %d: imm %08lx != %08x\n",
__PRETTY_FUNCTION__, _id, imm, _EndSync);
}
if (rc == -FI_EAGAIN)
fprintf(stderr, "\n%s: Timed out\n\n", __PRETTY_FUNCTION__);
return rc;
}
int EbLfSvrLink::_synchronizeEnd()
{
int rc;
uint64_t imm = _SvrSync;
if ( (rc = EbLfLink::post(imm)) ) return rc;
// Drain any stale transmissions that are stuck in the pipe
while ((rc = EbLfLink::poll(&imm, 7000)) == 0)
{
if (imm == _CltSync) break;
fprintf(stderr, "%s: Got junk from id %d: imm %08lx != %08x\n",
__PRETTY_FUNCTION__, _id, imm, _CltSync);
//return 1;
}
if (rc == -FI_EAGAIN)
fprintf(stderr, "\n%s: Timed out\n\n", __PRETTY_FUNCTION__);
return rc;
}
int EbLfSvrLink::prepare(unsigned id,
const char* peer)
{
int rc;
// Wait for synchronization to complete successfully prior to any sends/recvs
if ( (rc = _synchronizeBegin()) )
{
fprintf(stderr, "%s:\n Failed synchronize Begin with %s: rc %d\n",
__PRETTY_FUNCTION__, peer, rc);
return rc;
}
// Exchange IDs and get MR size
if ( (rc = recvU32(&_id, peer, "ID")) ) return rc;
if ( (rc = sendU32( id, peer, "ID")) ) return rc;
// Verify the exchanges are complete
if ( (rc = _synchronizeEnd()) )
{
fprintf(stderr, "%s:\n Failed synchronize End with %s: rc %d\n",
__PRETTY_FUNCTION__, peer, rc);
return rc;
}
return 0;
}
int EbLfSvrLink::prepare(unsigned id,
size_t* size,
const char* peer)
{
int rc;
uint32_t rs;
// Wait for synchronization to complete successfully prior to any sends/recvs
if ( (rc = _synchronizeBegin()) )
{
fprintf(stderr, "%s:\n Failed synchronize Begin with %s: rc %d\n",
__PRETTY_FUNCTION__, peer, rc);
return rc;
}
// Exchange IDs and get MR size
if ( (rc = recvU32(&_id, peer, "ID")) ) return rc;
if ( (rc = sendU32( id, peer, "ID")) ) return rc;
if ( (rc = recvU32( &rs, peer, "MR size")) ) return rc;
if (size) *size = rs;
// This method requires a call to setupMr(region, size) below
// to complete the protocol, which involves a call to sendMr()
return 0;
}
int EbLfSvrLink::setupMr(void* region,
size_t size,
const char* peer)
{
int rc;
// Set up the MR and provide its specs to the other side
if ( (rc = Pds::Eb::setupMr(_ep->fabric(), region, size, &_mr, _verbose)) ) return rc;
if ( (rc = sendMr(_mr, peer)) ) return rc;
// Verify the exchanges are complete
if ( (rc = _synchronizeEnd()) )
{
fprintf(stderr, "%s:\n Failed synchronize End with %s: rc %d\n",
__PRETTY_FUNCTION__, peer, rc);
return rc;
}
return rc;
}
// ---
EbLfCltLink::EbLfCltLink(Endpoint* ep,
int depth,
const unsigned& verbose,
volatile uint64_t& pending) :
EbLfLink(ep, depth, verbose),
_pending(pending)
{
}
int EbLfCltLink::setupMr(void* region, size_t size)
{
if (_ep)
return Pds::Eb::setupMr(_ep->fabric(), region, size, nullptr, _verbose);
else
return -1;
}
int EbLfCltLink::_synchronizeBegin()
{
int rc;
// NB: Clients can't send anything to a server before receiving the
// synchronization message or the Server will get confused
// Drain any stale transmissions that are stuck in the pipe
uint64_t imm;
while ((rc = EbLfLink::poll(&imm, 60000)) == 0)
{
if (imm == _BegSync) break; // Break on synchronization message
fprintf(stderr, "%s: Got junk from id %d: imm %08lx != %08x\n",
__PRETTY_FUNCTION__, _id, imm, _BegSync);
}
if (rc == -FI_EAGAIN)
fprintf(stderr, "\n%s: Timed out\n\n", __PRETTY_FUNCTION__);
if (rc == 0)
{
// Send a synchronization message to the server
imm = _EndSync; // Use a different value from Servers
if ( (rc = EbLfLink::post(imm)) ) return rc;
}
return rc;
}
int EbLfCltLink::_synchronizeEnd()
{
int rc;
uint64_t imm = _CltSync;
if ( (rc = EbLfLink::post(imm)) ) return rc;
// Drain any stale transmissions that are stuck in the pipe
while ((rc = EbLfLink::poll(&imm, 7000)) == 0)
{
if (imm == _SvrSync) break;
fprintf(stderr, "%s: Got junk from id %d: imm %08lx != %08x\n",
__PRETTY_FUNCTION__, _id, imm, _SvrSync);
//return 1;
}
if (rc == -FI_EAGAIN)
fprintf(stderr, "\n%s: Timed out\n\n", __PRETTY_FUNCTION__);
return rc;
}
int EbLfCltLink::prepare(unsigned id,
const char* peer)
{
return prepare(id, nullptr, 0, 0, peer);
}
int EbLfCltLink::prepare(unsigned id,
void* region,
size_t size,
const char* peer)
{
return prepare(id, region, size, size, peer);
}
// Buffers to be posted using the post(buf, len, offset, immData, ctx) method,
// below, must be covered by a memory region set up using this method.
int EbLfCltLink::prepare(unsigned id,
void* region,
size_t lclSize,
size_t rmtSize,
const char* peer)
{
int rc;
// Wait for synchronization to complete successfully prior to any sends/recvs
if ( (rc = _synchronizeBegin()) )
{
fprintf(stderr, "%s:\n Failed synchronize Begin with %s: rc %d\n",
__PRETTY_FUNCTION__, peer, rc);
return rc;
}
// Exchange IDs and get MR size
if ( (rc = sendU32( id, peer, "ID")) ) return rc;
if ( (rc = recvU32(&_id, peer, "ID")) ) return rc;
// Revisit: Would like to make it const, but has issues in Endpoint.cc
if (region)
{
if ( (rc = sendU32(rmtSize, peer, "MR size")) ) return rc;
// Set up the MR and provide its specs to the other side
if ( (rc = Pds::Eb::setupMr(_ep->fabric(), region, lclSize, &_mr, _verbose)) ) return rc;
if ( (rc = recvMr (_ra, peer)) ) return rc;
}
// Verify the exchanges are complete
if ( (rc = _synchronizeEnd()) )
{
fprintf(stderr, "%s:\n Failed synchronize End with peer: rc %d\n",
__PRETTY_FUNCTION__, rc);
return rc;
}
return 0;
}
// This method requires that the buffers to be posted are covered by a memory
// region set up using the prepare(region, size) method above.
int EbLfCltLink::post(const void* buf,
size_t len,
uint64_t offset,
uint64_t immData,
void* ctx)
{
RemoteAddress ra{_ra.rkey, _ra.addr + offset, len};
auto t0{fast_monotonic_clock::now()};
ssize_t rc;
_pending |= 1 << _id;
while (true)
{
// writedata() will do (the equivalent of) inject_writedata() if the size
// is less than the inject_size, so there is no need to duplicate that here
if ( !(rc = _ep->writedata(buf, len, &ra, ctx, immData, _mr)) ) break;
if (rc != -FI_EAGAIN)
{
fprintf(stderr, "%s:\n writedata to ID %d failed: %s\n",
__PRETTY_FUNCTION__, _id, _ep->error());
break;
}
// With FI_SELECTIVE_COMPLETION, fabtests seems to indicate there is no need
// to check the Tx completion queue as nothing will ever appear in it
//fi_cq_data_entry cqEntry;
//rc = _ep->txcq()->comp(&cqEntry, 1);
//if ((rc < 0) && (rc != -FI_EAGAIN)) // EAGAIN means no completions available
//{
// fprintf(stderr, "%s:\n Error reading Tx CQ: %s\n",
// __PRETTY_FUNCTION__, _ep->txcq()->error());
// break;
//}
const ms_t tmo{7000};
auto t1 {fast_monotonic_clock::now()};
if (t1 - t0 > tmo)
{
++_timedOut;
rc = -FI_ETIMEDOUT;
break;
}
usleep(100); // Don't retry too quickly
// Maybe check if an EQ event indicates the link is shut down?
}
_pending &= ~(1 << _id);
return rc;
}
// This method requires that a memory region has been registered that covers the
// buffer specified by buf, len. This can be done using the prepare(size)
// method above. If these are NULL, no memory region is needed.
int EbLfLink::post(const void* buf,
size_t len,
uint64_t immData)
{
ssize_t rc;
if ( (rc = _ep->injectdata(buf, len, immData)) )
{
fprintf(stderr, "%s:\n injectdata() to ID %d failed: %s\n",
__PRETTY_FUNCTION__, _id, _ep->error());
}
return rc;
}
int EbLfLink::post(uint64_t immData)
{
auto rc = post(nullptr, 0, immData);
//printf("%s: To ID %d, sent imm %08lx: rc %zd\n",
// __PRETTY_FUNCTION__, _id, immData, rc);
return rc;
}
int EbLfLink::poll(uint64_t* data) // Sample only, don't wait
{
int rc;
fi_cq_data_entry cqEntry;
const unsigned nEntries = 1;
rc = _ep->rxcq()->comp(&cqEntry, nEntries);
if (rc > 0)
{
if (postCompRecv(nEntries))
{
fprintf(stderr, "%s:\n Failed to post %d CQ buffers\n",
__PRETTY_FUNCTION__, nEntries);
}
*data = cqEntry.data;
//printf("%s: From ID %d, received imm %08lx, rc %d\n",
// __PRETTY_FUNCTION__, _id, cqEntry.data, rc);
return 0;
}
if (rc == -FI_EAGAIN)
++_timedOut;
else
fprintf(stderr, "%s:\n No CQ entries for ID %d: rc %d: %s\n",
__PRETTY_FUNCTION__, _id, rc, _ep->rxcq()->error());
return rc;
}
int EbLfLink::poll(uint64_t* data, int msTmo) // Wait until timed out
{
int rc;
auto cq = _ep->rxcq();
auto t0{fast_monotonic_clock::now()};
do
{
fi_cq_data_entry cqEntry;
const unsigned nEntries = 1;
rc = cq->comp_wait(&cqEntry, nEntries, msTmo);
if (rc > 0)
{
if (postCompRecv(nEntries))
{
fprintf(stderr, "%s:\n Failed to post %d CQ buffers\n",
__PRETTY_FUNCTION__, nEntries);
}
*data = cqEntry.data;
//printf("%s: From ID %d, received imm %08lx, rc %d\n",
// __PRETTY_FUNCTION__, _id, cqEntry.data, rc);
return 0;
}
if (rc == -FI_EAGAIN)
{
const ms_t tmo{msTmo};
auto t1 {fast_monotonic_clock::now()};
if (t1 - t0 > tmo)
{
++_timedOut;
return rc;
}
}
}
while ((rc == -FI_EAGAIN) || (rc == 0));
fprintf(stderr, "%s:\n No CQ entries for ID %d: rc %d: %s\n",
__PRETTY_FUNCTION__, _id, rc, cq->error());
return rc;
}
// postCompRecv() is meant to be called after an immediate data message has been
// received (via EbLfServer::pend(), poll(), etc., or EbLfLink::poll()) to
// replenish the completion receive buffers
ssize_t EbLfLink::postCompRecv()
{
ssize_t rc = 0;
if ((rc = _ep->recv_comp_data(this)) < 0)
{
if (rc != -FI_EAGAIN)
fprintf(stderr, "%s:\n Link ID %d failed to post a CQ buffer: %s\n",
__PRETTY_FUNCTION__, _id, _ep->error());
else
rc = 0;
}
return rc;
}
| 27.138629 | 94 | 0.557826 | slac-lcls |
135dbdadde91af3c2ebac66852267c7726a371b0 | 347 | cpp | C++ | competitive-programming/leetcode/Number-theory/add_digits.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | competitive-programming/leetcode/Number-theory/add_digits.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | competitive-programming/leetcode/Number-theory/add_digits.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int digitSum(int n){
int sum = 0;
while(n >= 10){
sum += (n % 10);
n /= 10;
}
return sum+n;
}
int addDigits(int n){
int res = n;
while(res >= 10){
res = digitSum(res);
}
return res;
}
int main(){
int n = 38;
cout<<addDigits(n);
return 0;
} | 13.88 | 28 | 0.495677 | dushimsam |
135f3f0aa8b3948fa1c92ebfe3d776d9a9d1ebfb | 1,718 | cpp | C++ | 24.swap-nodes-in-pairs.cpp | meyash/LeetCode-Solutions | a9e064af64436e5a24bc3a2c93bd15d3c43f2391 | [
"MIT"
] | 1 | 2022-01-08T14:26:11.000Z | 2022-01-08T14:26:11.000Z | 24.swap-nodes-in-pairs.cpp | meyash/LeetCode-Solutions | a9e064af64436e5a24bc3a2c93bd15d3c43f2391 | [
"MIT"
] | null | null | null | 24.swap-nodes-in-pairs.cpp | meyash/LeetCode-Solutions | a9e064af64436e5a24bc3a2c93bd15d3c43f2391 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=24 lang=cpp
*
* [24] Swap Nodes in Pairs
*
* https://leetcode.com/problems/swap-nodes-in-pairs/description/
*
* algorithms
* Medium (52.34%)
* Likes: 3141
* Dislikes: 199
* Total Accepted: 555K
* Total Submissions: 1.1M
* Testcase Example: '[1,2,3,4]'
*
* Given a linked list, swap every two adjacent nodes and return its head.
*
*
* Example 1:
*
*
* Input: head = [1,2,3,4]
* Output: [2,1,4,3]
*
*
* Example 2:
*
*
* Input: head = []
* Output: []
*
*
* Example 3:
*
*
* Input: head = [1]
* Output: [1]
*
*
*
* Constraints:
*
*
* The number of nodes in the list is in the range [0, 100].
* 0 <= Node.val <= 100
*
*
*
* Follow up: Can you solve the problem without modifying the values in the
* list's nodes? (i.e., Only nodes themselves may be changed.)
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *bakup=head;
while(head!=NULL){
if(head->next!=NULL){
// swap
int temp=head->val;
head->val=head->next->val;
head->next->val=temp;
// move head 2 forward
head=head->next->next;
}else{
head=head->next;
}
}
return bakup;
}
};
// @lc code=end
| 19.088889 | 75 | 0.528522 | meyash |
1361a37f4b1da97bb92190c9e2e46117ec901d0b | 26,700 | hh | C++ | Kaskade/timestepping/limexWithoutJensHierarchicEst.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 3 | 2019-07-03T14:03:31.000Z | 2021-12-19T10:18:49.000Z | Kaskade/timestepping/limexWithoutJensHierarchicEst.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 6 | 2020-02-17T12:01:30.000Z | 2021-12-09T22:02:33.000Z | Kaskade/timestepping/limexWithoutJensHierarchicEst.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 2 | 2020-12-03T04:41:18.000Z | 2021-01-11T21:44:42.000Z | #ifndef LIMEX_HH
#define LIMEX_HH
#include <fstream>
#include <iostream>
#include <boost/timer/timer.hpp>
#include "dune/istl/solvers.hh"
#include "fem/embedded_errorest.hh"
#include "fem/iterate_grid.hh"
#include "fem/hierarchicErrorEstimator.hh"
#include "fem/hierarchicspace.hh"
#include "fem/istlinterface.hh"
#include "dune/istl/solvers.hh"
#include "dune/istl/preconditioners.hh"
#include "timestepping/extrapolation.hh"
#include "timestepping/semieuler.hh"
#include "linalg/factorization.hh"
#include "linalg/umfpack_solve.hh"
// #include "linalg/mumps_solve.hh"
// #include "linalg/superlu_solve.hh"
#include "linalg/trivialpreconditioner.hh"
#include "linalg/direct.hh"
#include "linalg/triplet.hh"
#include "linalg/iluprecond.hh"
#include "linalg/additiveschwarz.hh"
// #include "linalg/hyprecond.hh"
#include "linalg/jacobiPreconditioner.hh"
#include "utilities/enums.hh"
#include "io/vtk.hh"
bool fabscompare( double a, double b ) { return fabs( a ) < fabs( b ) ; }
DirectType xyz = DirectType::UMFPACK;
namespace Kaskade
{
template <class Functional>
struct CardioD2
{
template <int row, int col>
class D2: public Functional::template D2<row,col>
{
typedef typename Functional::template D2<row,col> d2;
public:
static bool const present = d2::present && (row==0) && (col==0);
static bool const lumped = true;
};
};
/**
* \ingroup timestepping
* \brief Extrapolated linearly implicit Euler method.
*
* This class implements the extrapolated linearly implicit Euler
* method for integrating time-dependent evolution problems. The
* implementation follows Deuflhard/Bornemann Chapter 6.4.3.
*/
template <class Eq>
class Limex
{
public:
typedef Eq EvolutionEquation;
typedef typename EvolutionEquation::AnsatzVars::VariableSet State;
private:
typedef SemiLinearizationAt<SemiImplicitEulerStep<EvolutionEquation> > Linearization;
typedef VariationalFunctionalAssembler<Linearization> Assembler;
// for hierarchic error estimator
typedef FEFunctionSpace<ContinuousHierarchicExtensionMapper<double,typename Eq::AnsatzVars::Grid::LeafGridView> > SpaceEx;
typedef boost::fusion::vector< typename SpaceType<typename Eq::AnsatzVars::Spaces,0>::type const*, SpaceEx const*> ExSpaces;
// two components, 1 space -- how to generalize?
// typedef boost::fusion::vector<VariableDescription<1,1,0>, VariableDescription<1,1,1> > ExVariableDescriptions;
// 1 component, 1 space -- how to generalize?
typedef boost::fusion::vector<VariableDescription<1,1,0> > ExVariableDescriptions;
typedef VariableSetDescription<ExSpaces,ExVariableDescriptions> ExVariableSet;
typedef HierarchicErrorEstimator<Linearization,ExVariableSet,ExVariableSet,CardioD2<Linearization> > ErrorEstimator;
typedef VariationalFunctionalAssembler<ErrorEstimator> EstimatorAssembler;
// typedef typename EstimatorAssembler::template AnsatzVariableRepresentation<> Ansatz;
// typedef typename EstimatorAssembler::template TestVariableRepresentation<> Test;
/* typedef typename ExVariableSet::template CoefficientVectorRepresentation<0,1>::type ExCoefficientVectors;*/
typedef typename Eq::AnsatzVars::Grid::Traits::LeafIndexSet IS ;
public:
/**
* Constructs an ODE integrator. The arguments eq and ansatzVars
* have to exist during the lifetime of the integrator.
*/
Limex(GridManager<typename EvolutionEquation::AnsatzVars::Grid>& gridManager_,
EvolutionEquation& eq_, typename EvolutionEquation::AnsatzVars const& ansatzVars_, DirectType st=DirectType::UMFPACK):
gridManager(gridManager_), ansatzVars(ansatzVars_), eq(&eq_,0),
assembler(gridManager,ansatzVars.spaces),
iteSteps(10000), iteEps(1e-6), extrap(0),
rhsAssemblyTime(0.0), matrixAssemblyTime(0.0), factorizationTime(0.0), solutionTime(0.0), adaptivityTime(0.0),
solverType(st)
{}
/**
* In order to maintain compatibility with existing code,
* this overload is needed, as non const reference parameters (refinements) can not
* have default values. All ist does is call the original method with a temporary
* parameter.
*/
State const& step(State const& x, double dt, int order,
std::vector<std::pair<double,double> > const& tolX)
{
std::vector<std::vector<bool> > tmp ;
return step(x,dt,order,tolX,tmp);
}
/**
* Computes a state increment that advances the given state in
* time. The time in the given evolution equation is increased by
* dt.
*
* \param x the initial state to be evolved
* \param dt the time step
* \param order the extrapolation order >= 0 (0 corresponds to the linearly implicit Euler)
* \param tolX
* \param refinements keep track of the cells marked for refinement
* \return the state increment (references an internal variable that will be
* invalidated by a subsequent call of step)
*
* \todo (i) check for B constant, do not reassemble matrix in this case
* (ii) implement fixed point iteration instead of new factorization
* in case B is not constant
*/
State const& step(State const& x, double dt, int order,
std::vector<std::pair<double,double> > const& tolX,
std::vector< std::vector<bool> > &refinements )
{
boost::timer::cpu_timer timer;
std::vector<double> stepFractions(order+1);
for (int i=0; i<=order; ++i) stepFractions[i] = 1.0/(i+1); // harmonic sequence
extrap.clear();
typedef typename EvolutionEquation::AnsatzVars::Grid Grid;
int const dim = EvolutionEquation::AnsatzVars::Grid::dimension;
int const nvars = EvolutionEquation::AnsatzVars::noOfVariables;
int const neq = EvolutionEquation::TestVars::noOfVariables;
size_t nnz = assembler.nnz(0,neq,0,nvars,false);
size_t size = ansatzVars.degreesOfFreedom(0,nvars);
std::vector<double> rhs(size), sol(size);
State dx(x), dxsum(x), tmp(x);
double const t = eq.time();
double estTime = 0 ;
eq.temporalEvaluationRange(t,t+dt);
typedef AssembledGalerkinOperator<Assembler,0,neq,0,neq> Op;
bool iterative = true ;
int fill_lev = /*0*/ /*1*/2;
typedef typename EvolutionEquation::AnsatzVars::template CoefficientVectorRepresentation<0,neq>::type
CoefficientVectors;
typedef typename EvolutionEquation::TestVars::template CoefficientVectorRepresentation<0,neq>::type
LinearSpaceX;
for (int i=0; i<=order; ++i) {
double const tau = stepFractions[i]*dt;
eq.setTau(tau);
eq.time(t);
// mesh adaptation loop. Just once if i>0.
bool accurate = true;
int refinement_count = 0 ;
do {
// Evaluate and factorize matrix B(t)-tau*J
dx/* * */= 0;
timer.start();
// assembler.assemble(Linearization(eq,x,x,dx)/*,(Assembler::VALUE|Assembler::RHS|Assembler::MATRIX),4*/);
// #ifndef KASKADE_SEQUENTIAL
// gridManager.enforceConcurrentReads(std::is_same<Grid,Dune::UGGrid<dim> >::value);
// assembler.setNSimultaneousBlocks(40);
// assembler.setRowBlockFactor(2.0);
// #endif
// std::cout << "assemble linear system ..." ; std::cout.flush();
assembler.assemble(Linearization(eq,x,x,dx)/*,(Assembler::VALUE|Assembler::RHS|Assembler::MATRIX),4*/);
// std::cout << " done\n"; std::cout.flush();
matrixAssemblyTime += (double)(timer.elapsed().user)/1e9;
Op A(assembler);
// std::cout << "solve linear system\n"; std::cout.flush();
if (iterative)
{
timer.start();
CoefficientVectors solution(EvolutionEquation::AnsatzVars::template CoefficientVectorRepresentation<0,neq>::init(ansatzVars.spaces)
);
solution = 0;
CoefficientVectors rhs(assembler.rhs());
ILUKPreconditioner<Op> p(A,fill_lev,0);
// ILUTPreconditioner<Op> p(A,240,1e-2,0);
// JacobiPreconditioner<Op> p(A,1.0);
Dune::BiCGSTABSolver<LinearSpaceX> cg(A,p,1e-7,2000,0); //verbosity: 0-1-2 (nothing-start/final-every it.)
Dune::InverseOperatorResult res;
cg.apply(solution,rhs,res);
if ( !(res.converged) || (res.iterations == 2001) ) {
std::cout << " no of iterations in cg = " << res.iterations << std::endl;
std::cout << " convergence status of cg = " << res.converged << std::endl;
assert(0);
}
dx.data = solution.data;
solutionTime += (double)(timer.elapsed().user)/1e9;
}
else
{
// direct solution
timer.start();
// assembler.toTriplet(0,neq,0,nvars,ridx.begin(),cidx.begin(),data.begin(),false);
MatrixAsTriplet<double> triplet = A.template get<MatrixAsTriplet<double> >();
Factorization<double> *matrix = 0;
switch (solverType) {
case DirectType::UMFPACK:
matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
break;
case DirectType::UMFPACK3264:
matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
break;
// case MUMPS:
// matrix = new MUMPSFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
// break;
// case SUPERLU:
// matrix = new SUPERLUFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
// break;
default:
throw -321;
break;
}
factorizationTime += (double)(timer.elapsed().user)/1e9;
// First right hand side (j=0) has been assembled together with matrix.
timer.start();
A.getAssembler().toSequence(0,neq,rhs.begin());
for (int k=0; k<rhs.size(); ++k) assert(std::isfinite(rhs[k]));
matrix->solve(rhs,sol);
delete matrix;
for (int k=0; k<sol.size(); ++k) assert(std::isfinite(sol[k]));
dx.read(sol.begin());
solutionTime += (double)(timer.elapsed().user)/1e9;
// Factorization<double> *matrix = 0;
// switch (solverType)
// {
// case UMFPACK:
// matrix = new UMFFactorization<double>(size,0,ridx,cidx,data);
// break;
// case UMFPACK3264:
// matrix = new UMFFactorization<double>(size,0,ridx,cidx,data);
// break;
// case MUMPS:
// matrix = new MUMPSFactorization<double>(size,0,ridx,cidx,data);
// break;
// case SUPERLU:
// matrix = new SUPERLUFactorization<double>(size,0,ridx,cidx,data);
// break;
// default:
// throw -321;
// break;
// }
// factorizationTime += (double)(timer.elapsed().user)/1e9;
//
// // First right hand side (j=0) has been assembled together with matrix.
// timer.start();
// assembler.toSequence(0,neq,rhs.begin());
// for (size_t k=0; k<rhs.size(); ++k) assert(finite(rhs[k]));
// matrix->solve(rhs,sol);
// delete matrix;
// for (size_t k=0; k<sol.size(); ++k) assert(finite(sol[k]));
// dx.read(sol.begin());
// solutionTime += (double)(timer.elapsed().user)/1e9;
//end: direct solution
}
// Mesh adaptation only if requested and only for the full
// implicit Euler step (first stage).
typedef typename EvolutionEquation::AnsatzVars::GridView::template Codim<0>::Iterator CellIterator ;
accurate = true ;
timer.start();
IS const& is = gridManager.grid().leafIndexSet();
std::vector<double> errorDistribution(is.size(0),0.0);
double maxErr = 0.0, errNorm = 0.0 ;
if (!tolX.empty() && i==0) {
// embeddedErrorEstimator can not be used for linear finite elements
// use HierarchicErrorEstimator instead
// preparation for HierarchicErrorEstimator
if(true) // to avoid mesh adaptation for exVariables
{
//TODO: this should be using the gridviews/index sets of the original space, not the leaf!
SpaceEx spaceEx(gridManager,gridManager.grid().leafGridView(), boost::fusion::at_c<0>(ansatzVars.spaces)->mapper().getOrder()+1);
typename SpaceType<typename Eq::AnsatzVars::Spaces,0>::type spaceH1 = *(boost::fusion::at_c<0>(ansatzVars.spaces)) ;
ExSpaces exSpaces(&spaceH1,&spaceEx);
std::string exVarNames[2] = { "ev", "ew" };
ExVariableSet exVariableSet(exSpaces, exVarNames);
EstimatorAssembler estAssembler(gridManager,exSpaces);
tmp/* * */= 0 ;
// estAssembler.assemble(ErrorEstimator(Linearization(eq,x,x,tmp/*dx*/),dx));
estAssembler.assemble(ErrorEstimator(semiLinearization(eq,x,x,/*dx*/tmp),dx));
int const estNvars = ErrorEstimator::AnsatzVars::noOfVariables;
// std::cout << "estimator: nvars = " << estNvars << "\n";
int const estNeq = ErrorEstimator::TestVars::noOfVariables;
// std::cout << "estimator: neq = " << estNeq << "\n";
size_t estNnz = estAssembler.nnz(0,estNeq,0,estNvars,false);
size_t estSize = exVariableSet.degreesOfFreedom(0,estNvars);
std::vector<int> estRidx(estNnz), estCidx(estNnz);
std::vector<double> estData(estNnz), estRhs(estSize), estSolVec(estSize);
estAssembler.toSequence(0,estNeq,estRhs.begin());
typedef typename ExVariableSet::template CoefficientVectorRepresentation<0,estNeq>::type ExCoefficientVectors;
// iterative solution of error estimator
// timer.start();
// AssembledGalerkinOperator<EstimatorAssembler> E(estAssembler);
// typename Dune::InverseOperatorResult estRes;
// typename Test::type estRhside( Test::rhs(estAssembler) ) ;
// typename Ansatz::type estSol( Ansatz::init(estAssembler) ) ;
// estSol = 1.0 ;
// JacobiPreconditioner<EstimatorAssembler> jprec(estAssembler, 1.0);
// jprec.apply(estSol,estRhside); //single Jacobi iteration
// estTime += (double)(timer.elapsed().user)/1e9;
// estSol.write(estSolVec.begin());
typedef AssembledGalerkinOperator<EstimatorAssembler> AssEstOperator;
AssEstOperator agro(estAssembler);
Dune::InverseOperatorResult estRes;
ExCoefficientVectors estRhside(estAssembler.rhs());
ExCoefficientVectors estSol(ExVariableSet::template CoefficientVectorRepresentation<0,estNeq>::init(exVariableSet.spaces));
estSol = 1.0 ;
JacobiPreconditioner<AssEstOperator> jprec(agro, 1.0);
jprec.apply(estSol,estRhside); //single Jacobi iteration
// estTime += (double)(timer.elapsed().user)/1e9;
estSol.write(estSolVec.begin());
//--
// Transfer error indicators to cells.
CellIterator ciEnd = ansatzVars.gridView.template end<0>() ;
for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ciEnd; ++ci) {
typedef typename SpaceEx::Mapper::GlobalIndexRange GIR;
double err = 0.0;
GIR gix = spaceEx.mapper().globalIndices(*ci);
for (typename GIR::iterator j=gix.begin(); j!=gix.end(); ++j)
err += fabs(boost::fusion::at_c<0>(estSol.data)[*j]);
// only for 1st component -- second in monodomain is ODE
errorDistribution[is.index(*ci)] = err;
if (fabs(err)>maxErr) maxErr = fabs(err);
}
// std::cout << "maxErr: " << maxErr << "\n";
// for( size_t cno = 0 ; cno < is.size(0); cno++ )
// std::cout << cno << "\t\t" << errorDistribution[cno] << "\n";
// std::cout.flush();
//TODO: estimate only error in PDE, not ODE!
// what about relative accuracy?
for (size_t k = 0; k < estRhs.size() ; k++ ) errNorm += fabs( estRhs[k] * estSolVec[k] );
// this is for all variables?!
// errNorm = tau/*dt*/*sqrt(errNorm);
std::cout << "errNorm = " << errNorm << std::endl ;
std::cout.flush();
}
double overallTol = tolX[0].first ;
// for( int i = 0 ; i < 1 /*nvars*/ ; i++ )
// overallTol += tolX[i].first*tolX[i].first ;
// overallTol = sqrt(overallTol);
// std::cout << "overallTol = " << overallTol << std::endl ;
// alpha = 0 ; // for uniform refinement
int nRefMax = /*10*/7 ;/*7*//*5*//*3*//*15*/ /*4*/ /*5*/ /*10*/
double fractionOfCells = 0.05; /*0.1,0.2*/
unsigned long noToRefine = 0, noToCoarsen = 0;
double alpha = 1.0; /*0.5; //test april 13*/
double errLevel = 0.5*maxErr ; //0.75
// double minRefine = 0.05;
// if (minRefine>0.0)
// {
// std::vector<double> eSort(errorDistribution);
// std::sort(eSort.begin(),eSort.end(),fabscompare);
// int minRefineIndex = minRefine*(eSort.size()-1);
// double minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;
// if (minErrLevel<errLevel)
// errLevel = minErrLevel;
// }
// double minRefine = fractionOfCells; //* gridManager.grid().size(0);
// if (minRefine >0.0)
// {
// std::vector<double> eSort(errorDistribution);
// std::sort(eSort.begin(),eSort.end(),fabscompare);
// int minRefineIndex = minRefine*(eSort.size()-1);
// double minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;
// if (minErrLevel<errLevel)
// errLevel = minErrLevel;
// }
size_t maxNoOfVertices =/* 500000*/ /*2000000*//*12000*/30000;
size_t maxNoOfElements = 2000000;
int maxLevel = /*20*/6 /*25*/ /*18*/; // additional refinement levels
if( errNorm > overallTol && refinement_count < nRefMax
&& gridManager.grid().size(/*dim*/0) < /*maxNoOfVertices*/maxNoOfElements )
//current setup: for 2D BFGS; for 3D fibrillation: use maxNoOfElements
{
// accurate = false;
// std::vector<bool> toRefine( is.size(0), false ) ;
// size_t noCells = gridManager.grid().size(0);
// // std::cout << is.size(0) << " " << noCells << "\n"; std::cout.flush();
// for( size_t cno = 0 ; cno < noCells ; cno++ )
// {
// if (fabs(errorDistribution[cno]) >= alpha*errLevel)
// {
// noToRefine++;
// toRefine[cno] = true ;
// }
// }
std::vector<bool> toRefine( is.size(0), false ) ; //for adaptivity in compression
accurate = false ;
size_t noCells = gridManager.grid().size(0);
// // Nagaiah paper:
// unsigned minLevel = 10 ; // do not coarsen below that level
// CellIterator ciEnd = ansatzVars.gridView.template end<0>() ;
// for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ciEnd; ++ci)
// {
// double vol = sqrt( ci->geometry().volume() );
// if (fabs(errorDistribution[is.index(*ci)])/vol >= 0.2 /*0.1*/ )
// {
// if( ci->level() < maxLevel && gridManager.grid().size(dim) < maxNoOfVertices )
// {
// gridManager.mark(1,*ci);
// noToRefine++;
// }
// }
// else if (fabs(errorDistribution[is.index(*ci)])/vol < 0.1 /* /2 */ && ci->level() > minLevel )
// {
// gridManager.mark(-1,*ci);
// noToCoarsen++;
// }
// }
// std::cout << "refine: " << noToRefine << " coarsen: " << noToCoarsen << "\n";
// gridManager.countMarked();
// last implementation was the following:
unsigned long noToRefineOld = 0;
do{
noToRefineOld = noToRefine;
for( size_t cno = 0 ; cno < noCells ; cno++ )
{
if (fabs(errorDistribution[cno]) >= alpha*errLevel)
{ // TODO: check and bugfix this!
if( !toRefine[cno] ) noToRefine++;
toRefine[cno] = true ;
}
}
// std::cout << "alpha: " << alpha << "\trefine: " << noToRefine << "\n";
// std::cout.flush();
alpha *= 0.75; // refine more aggressively: reduce alpha by larger amount
} while ( noToRefine < fractionOfCells * noCells && (!noToRefineOld == noToRefine) ) ;
// std::cout << "to refine: " << noToRefine << "\n";
std::cout.flush();
// alpha = 0.5; //50
// do {
// for( size_t cno = 0 ; cno < noCells ; cno++ )
// if (fabs(errorDistribution[cno]) > alpha*maxErr/*overallTol/noCells*/) {
// /*if( !toRefine[cno] )*/ noToRefine++;
// toRefine[cno] = true;
// }
//
// alpha *=0.9;
// } while (noToRefine < fractionOfCells * noCells);
// long int nRefined = (long int) std::count( toRefine.begin(), toRefine.end(), true );
// std::cout << " noToRefine = " << nRefined << std::endl;
// refinements.push_back(toRefine);
for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ansatzVars.gridView.template end<0>(); ++ci)
if( toRefine[is.index(*ci)] && ci->level() < maxLevel ) gridManager.mark(1,*ci);
bool refok = gridManager.adaptAtOnce(); // something has been refined?
if( !refok )
{
// nothing has been refined
std::cout << "nothing has been refined (probably due to maxLevel constraint), stopping\n";
accurate = true ;
}
if (!accurate) {
refinement_count++ ;
nnz = assembler.nnz(0,neq,0,nvars,false);
size = ansatzVars.degreesOfFreedom(0,nvars);
rhs.resize(size);
sol.resize(size);
}
}
else
{
if( errNorm > overallTol && refinement_count > nRefMax )
std::cout << "max no of refinements exceeded\n";
// if( errNorm > overallTol && gridManager.grid().size(2) > maxNoOfVertices )
// std::cout << "max no of nodes exceeded\n";
accurate = true ;
}
}
} while (!accurate);
adaptivityTime += (double)(timer.elapsed().user)/1e9;
// std::cout << gridManager.grid().size(dim) << " nodes on " << gridManager.grid().maxLevel() << "levels\n";
dxsum = dx;
// propagate by linearly implicit Euler
for (int j=1; j<=i; ++j) {
// Assemble new right hand side tau*f(x_j)
eq.time(eq.time()+tau);
tmp = x; tmp += dxsum;
State zero(x); zero /* * */= 0;
timer.start();
// gridManager.enforceConcurrentReads(true);
// assembler.setNSimultaneousBlocks(40);
// assembler.setRowBlockFactor(2.0);
assembler.assemble(Linearization(eq,tmp,x,zero),Assembler::RHS|Assembler::MATRIX,4);
rhsAssemblyTime += (double)(timer.elapsed().user)/1e9;
Op A(assembler);
if( !iterative )
{
timer.start();
//direct solution
A.getAssembler().toSequence(0,neq,rhs.begin());
MatrixAsTriplet<double> triplet = A.template get<MatrixAsTriplet<double> >();
Factorization<double> *matrix = 0;
switch (solverType) {
case DirectType::UMFPACK:
matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
break;
case DirectType::UMFPACK3264:
matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
break;
// case MUMPS:
// matrix = new MUMPSFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
// break;
// case SUPERLU:
// matrix = new SUPERLUFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);
// break;
default:
throw -321;
break;
}
factorizationTime += (double)(timer.elapsed().user)/1e9;
timer.start();
matrix->solve(rhs,sol);
delete matrix;
for (int k=0; k<rhs.size(); ++k) assert(std::isfinite(rhs[k]));
for (int k=0; k<sol.size(); ++k) assert(std::isfinite(sol[k]));
dx.read(sol.begin());
solutionTime += (double)(timer.elapsed().user)/1e9;
}
else
{
timer.start();
CoefficientVectors solution(EvolutionEquation::AnsatzVars::template
CoefficientVectorRepresentation<0,neq>::init(ansatzVars.spaces) );
solution = 0;
// assembler.assemble(linearization(F,x));
CoefficientVectors rhs(assembler.rhs());
ILUKPreconditioner<Op> p(A,fill_lev,0);
// ILUTPreconditioner<Op> p(A,240,1e-2,0);
// JacobiPreconditioner<Op> p(A,1.0);
Dune::BiCGSTABSolver<LinearSpaceX> cg(A,p,1e-7,2000,0); //verbosity: 0-1-2 (nothing-start/final-every it.)
Dune::InverseOperatorResult res;
cg.apply(solution,rhs,res);
if ( !(res.converged) || (res.iterations == 2001) ) {
std::cout << " no of iterations in cg = " << res.iterations << std::endl;
std::cout << " convergence status of cg = " << res.converged << std::endl;
assert(0);
}
dx.data = solution.data;
// // iterative solution
// timer.start();
// typedef typename Assembler::template TestVariableRepresentation<>::type Rhs;
// typedef typename Assembler::template AnsatzVariableRepresentation<>::type Sol;
// Sol solution(Assembler::template AnsatzVariableRepresentation<>::init(assembler));
// Rhs rhside(Assembler::template TestVariableRepresentation<>::rhs(assembler));
// AssembledGalerkinOperator<Assembler,0,1,0,1> A(assembler, false);
// typename AssembledGalerkinOperator<Assembler,0,1,0,1>::matrix_type tri(A.getmat());
//
//
// typedef typename Assembler::template TestVariableRepresentation<>::type LinearSpace;
// Dune::InverseOperatorResult res;
// solution = 1.0;
// JacobiPreconditioner<Assembler,0,1,0> p(assembler,1.0);
// // TrivialPreconditioner<LinearSpace> trivial;
// Dune::CGSolver<LinearSpace> cg(A,/*trivial*/p,iteEps,iteSteps,0);
// cg.apply(solution,rhside,res);
// A.applyscaleadd(-1.0,rhside,solution);
// double slntime = (double)(timer.elapsed().user)/1e9;
// solutionTime += slntime ;
// dx.data = solution.data ;
// // end: iterative solution
}
dxsum += dx;
solutionTime += (double)(timer.elapsed().user)/1e9;
}
// insert into extrapolation tableau
extrap.push_back(dxsum,stepFractions[i]);
// restore initial time
eq.time(t);
}
return extrap.back();
}
/**
* Estimates the time discretization error of the previously
* computed step by taking the difference between the diagonal and
* subdiagonal extrapolation values of maximal order. This requires
* that order>1 has been given for the last step.
*/
std::vector<std::pair<double,double> > estimateError(State const& x,int i, int j) const
{
assert(extrap.size()>1);
std::vector<std::pair<double,double> > e(ansatzVars.noOfVariables);
relativeError(typename EvolutionEquation::AnsatzVars::Variables(),extrap[i].data,
extrap[j].data,x.data,
ansatzVars.spaces,eq.scaling(),e.begin());
return e;
}
template <class OutStream>
void reportTime(OutStream& out) const {
out << "Limex time: " << matrixAssemblyTime << "s matrix assembly\n"
<< " " << rhsAssemblyTime << "s rhs assembly\n"
<< " " << factorizationTime << "s factorization\n"
<< " " << solutionTime << "s solution\n"
<< " " << adaptivityTime << "s adaptivity\n";
}
void advanceTime(double dt) { eq.time(eq.time()+dt); }
private:
GridManager<typename EvolutionEquation::AnsatzVars::Grid>& gridManager;
typename EvolutionEquation::AnsatzVars const& ansatzVars;
SemiImplicitEulerStep<EvolutionEquation> eq;
Assembler assembler;
int iteSteps ;
double iteEps ;
public:
ExtrapolationTableau<State> extrap;
double rhsAssemblyTime, matrixAssemblyTime, factorizationTime, solutionTime, adaptivityTime;
DirectType solverType;
};
} //namespace Kaskade
#endif
| 36.827586 | 135 | 0.648315 | chenzongxiong |
1366afee72885e9cf2725973a9d8813df5c6595e | 195,357 | cpp | C++ | p2cog.cpp | pullmoll/p2 | ef205195c26a291fb91fda6639351a33e95d1c29 | [
"BSD-3-Clause"
] | 1 | 2019-12-17T16:20:50.000Z | 2019-12-17T16:20:50.000Z | p2cog.cpp | pullmoll/p2emu | ef205195c26a291fb91fda6639351a33e95d1c29 | [
"BSD-3-Clause"
] | null | null | null | p2cog.cpp | pullmoll/p2emu | ef205195c26a291fb91fda6639351a33e95d1c29 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
*
* P2 emulator Cog implementation
*
* Function bodies and comments generated from ":/P2 instruction set.csv"
*
* Copyright (C) 2019 Jürgen Buchmüller <pullmoll@t-online.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****************************************************************************/
#include "p2cog.h"
#include "p2util.h"
P2Cog::P2Cog(int cog_id, P2Hub* hub, QObject* parent)
: QObject(parent)
, HUB(hub)
, ID(static_cast<p2_LONG>(cog_id))
, PC(0xfc000)
, WAIT()
, FLAGS()
, CT1(0)
, CT2(0)
, CT3(0)
, PAT()
, PIN()
, INT()
, IR()
, D(0)
, S(0)
, Q(0)
, C(0)
, Z(0)
, FIFO()
, K(0)
, STACK()
, S_next()
, S_aug()
, D_aug()
, R_aug()
, IR_aug()
, REP_instr()
, REP_offset(0)
, REP_times(0)
, SKIP(0)
, SKIPF(0)
, PTRA0(0)
, PTRB0(0)
, HUBOP(0)
, CORDIC_count(0)
, QX_posted(false)
, QY_posted(false)
, RW_repeat(false)
, RDL_mask(0)
, RDL_flags0(0)
, RDL_flags1(0)
, WRL_mask(0)
, WRL_flags0(0)
, WRL_flags1(0)
, COG()
, LUT()
, MEM(hub->mem())
, MEMSIZE(hub->memsize())
{
}
p2_LONG P2Cog::rd_cog(p2_LONG addr) const
{
return COG.RAM[addr & COG_MASK];
}
void P2Cog::wr_cog(p2_LONG addr, p2_LONG val)
{
COG.RAM[addr & COG_MASK] = val;
}
p2_LONG P2Cog::rd_lut(p2_LONG addr) const
{
return LUT.RAM[addr & LUT_MASK];
}
void P2Cog::wr_lut(p2_LONG addr, p2_LONG val)
{
LUT.RAM[addr & LUT_MASK] = val;
}
p2_LONG P2Cog::rd_mem(p2_LONG addr) const
{
p2_LONG result = 0;
switch (addr & 0xfff800) {
case 0x000000:
result = rd_cog(addr/4);
break;
case 0x000800:
result = rd_lut(addr/4);
break;
default:
Q_ASSERT(HUB);
result = HUB->rd_LONG(addr);
}
return result;
}
void P2Cog::wr_mem(p2_LONG addr, p2_LONG val)
{
switch (addr & 0xfff800) {
case 0x000000:
wr_cog(addr/4, val);
break;
case 0x000800:
wr_lut(addr/4, val);
break;
default:
Q_ASSERT(HUB);
HUB->wr_LONG(addr, val);
}
}
/**
* @brief Write PC address
* @param addr address to jump to
*/
void P2Cog::wr_PC(p2_LONG addr)
{
PC = addr & A20MASK;
if (PC >= HUB_ADDR0)
PC &= ~3u;
}
/**
* @brief Write PTRA address
* @param addr address to store in PTRA
*/
void P2Cog::wr_PTRA(p2_LONG addr)
{
COG.REG.PTRA = addr & A20MASK;
}
/**
* @brief Write PTRB address
* @param addr address to store in PTRB
*/
void P2Cog::wr_PTRB(p2_LONG addr)
{
COG.REG.PTRB = addr & A20MASK;
}
/**
* @brief Update C if the WC flag bit is set
* @param c new C flag
*/
void P2Cog::updateC(bool c) {
if (IR.op7.wc)
C = c & 1u;
}
/**
* @brief Update Z if the WZ flag bit is set
* @param z new Z flag
*/
void P2Cog::updateZ(bool z) {
if (IR.op7.wz)
C = z & 1u;
}
/**
* @brief Update D, i.e. write result to COG result register R
* @param d new value for D
*/
void P2Cog::updateD(p2_LONG d)
{
COG.RAM[R] = d;
}
/**
* @brief Update Q
* @param d new value for Q
*/
void P2Cog::updateQ(p2_LONG q)
{
Q = q;
}
/**
* @brief Update PC (program counter)
* @param pc new program counter
*/
void P2Cog::updatePC(p2_LONG pc)
{
// TODO: handle switch between COG, LUT, and HUB ?
PC = pc;
// Stop REP, if any
REP_instr.clear();
}
/**
* @brief Write long %d to the LUT at address %addr
* @param addr address (9 bit)
* @param d data to write
*/
void P2Cog::updateLUT(p2_LONG addr, p2_LONG d)
{
LUT.RAM[addr & 0x1ff] = d;
}
/**
* @brief Update the SKIP flag word
* @param d new value for SKIP flag
*/
void P2Cog::updateSKIP(p2_LONG d)
{
SKIP = d;
}
/**
* @brief Update the SKIPF flag word
* @param d new value for SKIPF flag
*/
void P2Cog::updateSKIPF(p2_LONG d)
{
SKIPF = d;
}
/**
* @brief Push value %val to the 8 level stack
* @param val value to push
*/
void P2Cog::pushK(p2_LONG val)
{
K = (K - 1) & 7;
STACK[K] = val;
}
/**
* @brief Pop value %val from the 8 level stack
* @return
*/
p2_LONG P2Cog::popK()
{
p2_LONG val = STACK[K];
K = (K + 1) & 7;
return val;
}
/**
* @brief Push value %val to PA
* @param val value to push
*/
void P2Cog::pushPA(p2_LONG val)
{
COG.REG.PA = val;
}
/**
* @brief Push value %val to PA
* @param val value to push
*/
void P2Cog::pushPB(p2_LONG val)
{
COG.REG.PB = val;
}
/**
* @brief Push value %val to HUB memory at PTRA++
* @param val value to push
*/
void P2Cog::pushPTRA(p2_LONG val)
{
HUB->wr_LONG(COG.REG.PTRA, val);
COG.REG.PTRA = (COG.REG.PTRA + 4) & A20MASK;
}
/**
* @brief Pop value %val from HUB memory at --PTRA
* @return value from HUB memory
*/
p2_LONG P2Cog::popPTRA()
{
COG.REG.PTRA = (COG.REG.PTRA - 4) & A20MASK;
p2_LONG val = HUB->rd_LONG(COG.REG.PTRA);
return val;
}
/**
* @brief Push value %val to HUB memory at PTRB++
* @param val value to push
*/
void P2Cog::pushPTRB(p2_LONG val)
{
HUB->wr_LONG(COG.REG.PTRB, val);
COG.REG.PTRB = (COG.REG.PTRB + 4) & A20MASK;
}
/**
* @brief Pop value %val from HUB memory at --PTRB
* @return value from HUB memory
*/
p2_LONG P2Cog::popPTRB()
{
COG.REG.PTRA = (COG.REG.PTRB - 4) & A20MASK;
p2_LONG val = HUB->rd_LONG(COG.REG.PTRB);
return val;
}
/**
* @brief Augment #S or use #S, if the flag bit is set, then possibly set S from next_S
* @param f true if immediate mode
*/
void P2Cog::augmentS(bool f)
{
if (f) {
if (S_aug.isValid()) {
S = S_aug.toUInt() | IR.op7.src;
S_aug.clear();
} else {
S = IR.op7.src;
}
}
if (S_next.isValid()) {
// set S to next_S
S = S_next.toUInt();
S_next.clear();
}
}
/**
* @brief Augment #D or use #D, if the flag bit is set
* @param f true if immediate mode
*/
void P2Cog::augmentD(bool f)
{
if (f) {
if (D_aug.isValid()) {
D = D_aug.toUInt() | IR.op7.dst;
D_aug.clear();
} else {
D = IR.op7.dst;
}
}
}
/**
* @brief Update PA, i.e. write result to port A
* @param d value to write
*/
void P2Cog::updatePA(p2_LONG d)
{
Q_ASSERT(HUB);
COG.REG.PA = d;
HUB->wr_PA(COG.REG.PA);
}
/**
* @brief Update PB, i.e. write result to port B
* @param d value to write
*/
void P2Cog::updatePB(p2_LONG d)
{
Q_ASSERT(HUB);
COG.REG.PB = d;
HUB->wr_PB(COG.REG.PB);
}
/**
* @brief Update PTRA
* @param d value to write
*/
void P2Cog::updatePTRA(p2_LONG d)
{
COG.REG.PTRA = d;
}
/**
* @brief Update PTRB
* @param d value to write
*/
void P2Cog::updatePTRB(p2_LONG d)
{
COG.REG.PTRB = d;
}
/**
* @brief Update DIR bit
* @param pin pin number to set direction for
* @param io direction input (true), or output (false)
*/
void P2Cog::updateDIR(p2_LONG pin, bool io)
{
HUB->wr_DIR(pin, static_cast<p2_LONG>(io) & 1);
}
/**
* @brief Update OUT bit
* @param pin pin number to set output for
* @param io output value hi (true), or low (false)
*/
void P2Cog::updateOUT(p2_LONG pin, bool io)
{
HUB->wr_OUT(pin, static_cast<p2_LONG>(io) & 1);
}
/**
* @brief Setup COG to repeat a number instructions a number of times
* @param instr number of instructions to repeat
* @param times number of times to repeat (0 forever)
*/
void P2Cog::updateREP(p2_LONG instr, p2_LONG times)
{
REP_times = times;
REP_offset = 0;
if (!instr) {
REP_instr.clear();
} else {
REP_instr = instr;
}
}
/**
* @brief return conditional execution status for condition %cond
* @param cond condition
* @return true if met, false otherwise
*/
bool P2Cog::conditional(p2_Cond_e cond)
{
switch (cond) {
case cc__ret_: // execute always
return true;
case cc_nc_and_nz: // execute if C = 0 and Z = 0
return C == 0 && Z == 0;
case cc_nc_and_z: // execute if C = 0 and Z = 1
return C == 0 && Z == 1;
case cc_nc: // execute if C = 0
return C == 0;
case cc_c_and_nz: // execute if C = 1 and Z = 0
return C == 1 && Z == 0;
case cc_nz: // execute if Z = 0
return Z == 0;
case cc_c_ne_z: // execute if C != Z
return C != Z;
case cc_nc_or_nz: // execute if C = 0 or Z = 0
return C == 0 || Z == 0;
case cc_c_and_z: // execute if C = 1 and Z = 1
return C == 1 && Z == 1;
case cc_c_eq_z: // execute if C = Z
return C == Z;
case cc_z: // execute if Z = 1
return Z == 1;
case cc_nc_or_z: // execute if C = 0 or Z = 1
return C == 0 || Z == 1;
case cc_c: // execute if C = 1
return C == 1;
case cc_c_or_nz: // execute if C = 1 or Z = 0
return C == 1 || Z == 0;
case cc_c_or_z: // execute if C = 1 or Z = 1
return C == 1 || Z == 1;
case cc_always:
return true;
}
return false;
}
/**
* @brief Alias for conditional() with an unsigned parameter
* @param cond condition (0 … 15)
* @return true if met, false otherwise
*/
bool P2Cog::conditional(unsigned cond)
{
return conditional(static_cast<p2_Cond_e>(cond));
}
/**
* @brief Return the current FIFO level
* @return FIFO level 0 … 15
*/
p2_LONG P2Cog::fifo_level()
{
return (FIFO.windex - FIFO.rindex) & 15;
}
void P2Cog::check_interrupt_flags()
{
p2_LONG count = U32L(HUB->count());
// Update counter flags
if (count == CT1)
FLAGS.f_CT1 = true;
if (count == CT2)
FLAGS.f_CT2 = true;
if (count == CT3)
FLAGS.f_CT3 = true;
// Update pattern match/mismatch flag
switch (PAT.mode) {
case p2_PAT_PA_EQ: // (PA & mask) == match
if (PAT.match == (HUB->rd_PA() & PAT.mask)) {
PAT.mode = p2_PAT_NONE;
FLAGS.f_PAT = true;
}
break;
case p2_PAT_PA_NE: // (PA & mask) != match
if (PAT.match != (HUB->rd_PA() & PAT.mask)) {
PAT.mode = p2_PAT_NONE;
FLAGS.f_PAT = true;
}
break;
case p2_PAT_PB_EQ: // (PB & mask) == match
if (PAT.match == (HUB->rd_PB() & PAT.mask)) {
PAT.mode = p2_PAT_NONE;
FLAGS.f_PAT = true;
}
break;
case p2_PAT_PB_NE: // (PB & mask) != match
if (PAT.match != (HUB->rd_PB() & PAT.mask)) {
PAT.mode = p2_PAT_NONE;
FLAGS.f_PAT = true;
}
break;
default:
PAT.mode = p2_PAT_NONE;
}
// Update PIN edge detection
if (PIN.edge & 0xc0) {
bool prev = ((PIN.edge >> 8) & 1) ? true : false;
if (prev != HUB->rd_PIN(PIN.edge)) {
switch (PIN.mode) {
case p2_PIN_CHANGED_LO:
if (prev)
INT.flags.PIN_active = true;
break;
case p2_PIN_CHANGED_HI:
if (!prev)
INT.flags.PIN_active = true;
break;
case p2_PIN_CHANGED:
INT.flags.PIN_active = true;
break;
default:
INT.flags.PIN_active = false;
}
PIN.edge ^= 0x100;
}
}
// Update RDLONG state
if (RDL_mask & RDL_flags1) {
INT.flags.RDL_active = true;
}
// Update WRLONG state
if (WRL_mask & WRL_flags1) {
INT.flags.WRL_active = true;
}
// Update LOCK edge state
if (LOCK.edge & 0x30) {
if (LOCK.prev != HUB->lockstate(LOCK.num)) {
switch (LOCK.mode) {
case p2_LOCK_NONE:
INT.flags.LOCK_active = false;
break;
case p2_LOCK_CHANGED_LO:
if (LOCK.prev)
INT.flags.LOCK_active = true;
break;
case p2_LOCK_CHANGED_HI:
if (!LOCK.prev)
INT.flags.LOCK_active = true;
break;
case p2_LOCK_CHANGED:
INT.flags.LOCK_active = true;
break;
}
}
LOCK.prev = !LOCK.prev;
}
}
/**
* @brief Check and update the interrupt state
*/
void P2Cog::check_wait_int_state()
{
// Check if interrupts disabled or INT1 active
if (INT.flags.disabled || INT.flags.INT1_active)
return;
// Check INT1
if (INT.flags.INT1_source) {
p2_LONG bitmask = 1u << INT.flags.INT1_source;
if (INT.bits & bitmask) {
INT.flags.disabled = true;
return;
}
}
// Check if interrupts disabled or INT1 or INT2 active
if (INT.flags.disabled || INT.flags.INT1_active || INT.flags.INT2_active)
return;
// Check INT2
if (INT.flags.INT2_source) {
p2_LONG bitmask = 1u << INT.flags.INT2_source;
if (INT.bits & bitmask) {
INT.flags.disabled = true;
return;
}
}
// Check if interrupts disabled or INT1 or INT2 or INT3 active
if (INT.flags.disabled || INT.flags.INT1_active || INT.flags.INT2_active || INT.flags.INT3_active)
return;
// Check INT3
if (INT.flags.INT3_source) {
p2_LONG bitmask = 1u << INT.flags.INT3_source;
if (INT.bits & bitmask) {
INT.flags.disabled = true;
return;
}
}
}
/**
* @brief Check and update the WAIT flags
* @param IR instruction register
* @param value1 1st value (D)
* @param value2 2nd value (S)
* @param streamflag true, if streaming is active
* @return
*/
p2_LONG P2Cog::check_wait_flag(p2_opcode_u IR, p2_LONG value1, p2_LONG value2, bool streamflag)
{
p2_LONG hubcycles;
const p2_INSTX1_e inst1 = static_cast<p2_INSTX1_e>(IR.opcode & p2_INSTR_MASK1);
const p2_INSTX2_e inst2 = static_cast<p2_INSTX2_e>(IR.opcode & p2_INSTR_MASK2);
const p2_OPCODE_e opcode = static_cast<p2_OPCODE_e>(IR.op7.inst);
if (WAIT.flag) {
switch (WAIT.mode) {
case p2_WAIT_CACHE:
Q_ASSERT(false && "We should not be here!");
break;
case p2_WAIT_CORDIC:
switch (inst1) {
case p2_INSTR_GETQX:
if (QX_posted)
WAIT.flag = 0;
break;
case p2_INSTR_GETQY:
if (QY_posted)
WAIT.flag = 0;
break;
default:
Q_ASSERT(false && "We should not be here!");
}
if (0 == WAIT.flag)
WAIT.mode = p2_WAIT_NONE;
return WAIT.flag;
case p2_WAIT_FLAG:
break;
default:
WAIT.flag--;
if (0 == WAIT.flag) {
if (WAIT.mode == p2_WAIT_HUB && streamflag)
WAIT.flag = 16;
else {
WAIT.mode = p2_WAIT_NONE;
}
}
return WAIT.flag;
}
}
if (RW_repeat) {
if (!streamflag)
return 0;
WAIT.flag = 16;
WAIT.mode = p2_WAIT_HUB;
return WAIT.flag;
}
if (0 == HUB->hubslots())
hubcycles = 0;
else
hubcycles = ((ID + (value2 >> 2)) - HUB->cogindex()) & 15u;
if (p2_INSTR_GETQX == inst1) {
if (!QX_posted && CORDIC_count > 0) {
WAIT.flag = 1;
WAIT.mode = p2_WAIT_CORDIC;
}
} else if (p2_INSTR_GETQY == inst1) {
if (!QY_posted && CORDIC_count > 0) {
WAIT.flag = 1;
WAIT.mode = p2_WAIT_CORDIC;
}
} else if (p2_INSTR_WAITXXX == inst2) {
if (0x02024 == (IR.opcode & 0x3ffff))
check_wait_int_state();
switch (IR.op7.dst) {
case 0x10:
WAIT.flag = FLAGS.f_INT ? 0 : 1;
WAIT.mode = FLAGS.f_INT ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x11:
WAIT.flag = FLAGS.f_CT1 ? 0 : 1;
WAIT.mode = FLAGS.f_CT1 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x12:
WAIT.flag = FLAGS.f_CT2 ? 0 : 1;
WAIT.mode = FLAGS.f_CT2 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x13:
WAIT.flag = FLAGS.f_CT3 ? 0 : 1;
WAIT.mode = FLAGS.f_CT3 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x14:
WAIT.flag = FLAGS.f_SE1 ? 0 : 1;
WAIT.mode = FLAGS.f_SE1 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x15:
WAIT.flag = FLAGS.f_SE2 ? 0 : 1;
WAIT.mode = FLAGS.f_SE2 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x16:
WAIT.flag = FLAGS.f_SE3 ? 0 : 1;
WAIT.mode = FLAGS.f_SE3 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x17:
WAIT.flag = FLAGS.f_SE4 ? 0 : 1;
WAIT.mode = FLAGS.f_SE4 ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x18:
WAIT.flag = FLAGS.f_PAT ? 0 : 1;
WAIT.mode = FLAGS.f_PAT ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x19:
WAIT.flag = FLAGS.f_FBW ? 0 : 1;
WAIT.mode = FLAGS.f_FBW ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x1a:
WAIT.flag = FLAGS.f_XMT ? 0 : 1;
WAIT.mode = FLAGS.f_XMT ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x1b:
WAIT.flag = FLAGS.f_XFI ? 0 : 1;
WAIT.mode = FLAGS.f_XFI ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x1c:
WAIT.flag = FLAGS.f_XRO ? 0 : 1;
WAIT.mode = FLAGS.f_XRO ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x1d:
WAIT.flag = FLAGS.f_XRL ? 0 : 1;
WAIT.mode = FLAGS.f_XRL ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
case 0x1e:
WAIT.flag = FLAGS.f_ATN ? 0 : 1;
WAIT.mode = FLAGS.f_ATN ? p2_WAIT_NONE : p2_WAIT_FLAG;
break;
}
} else if (p2_INSTR_WAITX == inst1) {
WAIT.flag = value1;
WAIT.mode = p2_WAIT_CNT;
} else if (opcode >= p2_OPCODE_RDBYTE && opcode <= p2_OPCODE_RDLONG) {
HUBOP = 1;
WAIT.flag = hubcycles + 2;
WAIT.mode = p2_WAIT_HUB;
} else if ((opcode == p2_OPCODE_WRBYTE) ||
(opcode == p2_OPCODE_WRLONG && IR.op7.wc) ||
(opcode == p2_OPCODE_WMLONG && IR.op7.wc && IR.op7.wz)) {
HUBOP = 1;
WAIT.flag = hubcycles + 2;
WAIT.mode = p2_WAIT_HUB;
} else if ((opcode >= p2_OPCODE_QMUL && opcode <= p2_OPCODE_QVECTOR) ||
(inst1 == p2_INSTR_QLOG) || (inst1 == p2_INSTR_QEXP))
{
HUBOP = 1;
WAIT.flag = ((ID - HUB->cogindex()) & 15) + 1;
WAIT.mode = p2_WAIT_HUB;
} else if (inst1 >= p2_INSTR_LOCKNEW && inst1 <= p2_INSTR_LOCKSET) {
HUBOP = 1;
WAIT.flag = ((ID - HUB->cogindex()) & 15) + 1;
WAIT.mode = p2_WAIT_HUB;
} else if (inst1 >= p2_INSTR_RFBYTE && inst1 <= p2_INSTR_RFLONG) {
if (fifo_level() < 2) {
WAIT.flag = 1;
WAIT.mode = p2_WAIT_CACHE;
} else {
WAIT.flag = 0;
}
} else if (inst1 >= p2_INSTR_WFBYTE && inst1 <= p2_INSTR_WFLONG) {
if (fifo_level() >= 15) {
WAIT.flag = 1;
WAIT.mode = p2_WAIT_CACHE;
} else {
WAIT.flag = 0;
}
} else {
WAIT.flag = 0;
}
return HUBOP;
}
/**
* @brief Compute the hub RAM address from the pointer instruction
* @param inst instruction field (1SUPIIIII)
* @param size size of instruction (0 = byte, 1 = word, 2 = long)
* @return computed 20 bit RAM address
*/
p2_LONG P2Cog::get_pointer(p2_LONG inst, p2_LONG size)
{
p2_LONG address = 0;
p2_LONG offset = static_cast<p2_LONG>((static_cast<qint32>(inst) << 27) >> (27 - size));
switch ((inst >> 5) & 7) {
case 0: // PTRA[offset]
address = COG.REG.PTRA + offset;
break;
case 1: // PTRA
address = COG.REG.PTRA;
break;
case 2: // PTRA[++offset]
address = COG.REG.PTRA + offset;
PTRA0 = address;
break;
case 3: // PTRA[offset++]
address = COG.REG.PTRA;
PTRA0 = COG.REG.PTRA + offset;
break;
case 4: // PTRB[offset]
address = COG.REG.PTRB + offset;
break;
case 5: // PTRB
address = COG.REG.PTRB;
break;
case 6: // PTRB[++offset]
address = COG.REG.PTRB + offset;
PTRB0 = address;
break;
case 7: // PTRB[offset++]
address = COG.REG.PTRB;
PTRB0 = COG.REG.PTRB + offset;
break;
}
return address & A20MASK;
}
/**
* @brief Save pointer registers PTRA/PTRB
*/
void P2Cog::save_regs()
{
PTRA0 = COG.REG.PTRA;
PTRB0 = COG.REG.PTRB;
}
/**
* @brief Update pointer registers PTRA/PTRB
*/
void P2Cog::update_regs()
{
COG.REG.PTRA = PTRA0;
COG.REG.PTRB = PTRB0;
}
/**
* @brief Read the next I register; preset D and S registers
*
* If the SKIPF LSB is set, skip the instruction
*
* @return number of cycles
*/
int P2Cog::gox()
{
while (SKIPF & 1) {
PC += 4; // increment PC
SKIPF >>= 1;
}
PC &= A20MASK;
// rdRAM Ib
switch (PC & 0xfff800) {
case 0x00000: // COG exec
IR.opcode = COG.RAM[(PC/sz_LONG) & COG_MASK];
break;
case 0x00800: // LUT exec
IR.opcode = LUT.RAM[(PC/sz_LONG) & LUT_MASK];
break;
default: // hubexec
IR.opcode = HUB->rd_LONG(PC);
}
PC += 4; // increment PC
S = IR.op7.src; // latch Sb
D = IR.op7.dst; // latch Db
R = IR.op7.dst; // preset R = Db
return 1;
}
int P2Cog::get()
{
int cycles = 1;
check_interrupt_flags();
S = COG.RAM[S]; // rdRAM Sb
D = COG.RAM[D]; // rdRAM Db
if (SKIP & 1) {
// cancel this instruction
SKIP >>= 1;
return cycles;
}
if (SKIP)
SKIP >>= 1;
// check for the condition
if (!conditional(IR.op7.cond))
return cycles;
// Dispatch to op_xxx() functions
switch (IR.op7.inst) {
case p2_ROR:
cycles = op_ROR();
break;
case p2_ROL:
cycles = op_ROL();
break;
case p2_SHR:
cycles = op_SHR();
break;
case p2_SHL:
cycles = op_SHL();
break;
case p2_RCR:
cycles = op_RCR();
break;
case p2_RCL:
cycles = op_RCL();
break;
case p2_SAR:
cycles = op_SAR();
break;
case p2_SAL:
cycles = op_SAL();
break;
case p2_ADD:
cycles = op_ADD();
break;
case p2_ADDX:
cycles = op_ADDX();
break;
case p2_ADDS:
cycles = op_ADDS();
break;
case p2_ADDSX:
cycles = op_ADDSX();
break;
case p2_SUB:
cycles = op_SUB();
break;
case p2_SUBX:
cycles = op_SUBX();
break;
case p2_SUBS:
cycles = op_SUBS();
break;
case p2_SUBSX:
cycles = op_SUBSX();
break;
case p2_CMP:
cycles = op_CMP();
break;
case p2_CMPX:
cycles = op_CMPX();
break;
case p2_CMPS:
cycles = op_CMPS();
break;
case p2_CMPSX:
cycles = op_CMPSX();
break;
case p2_CMPR:
cycles = op_CMPR();
break;
case p2_CMPM:
cycles = op_CMPM();
break;
case p2_SUBR:
cycles = op_SUBR();
break;
case p2_CMPSUB:
cycles = op_CMPSUB();
break;
case p2_FGE:
cycles = op_FGE();
break;
case p2_FLE:
cycles = op_FLE();
break;
case p2_FGES:
cycles = op_FGES();
break;
case p2_FLES:
cycles = op_FLES();
break;
case p2_SUMC:
cycles = op_SUMC();
break;
case p2_SUMNC:
cycles = op_SUMNC();
break;
case p2_SUMZ:
cycles = op_SUMZ();
break;
case p2_SUMNZ:
cycles = op_SUMNZ();
break;
case p2_TESTB_W_BITL:
switch (IR.op9.inst) {
case p2_TESTB_WC:
case p2_TESTB_WZ:
cycles = op_TESTB_W();
break;
case p2_BITL:
case p2_BITL_WCZ:
cycles = op_BITL();
break;
default:
Q_ASSERT_X(false, "TESTB WC|WZ, BITL {WCZ}", "inst9 error");
}
break;
case p2_TESTBN_W_BITH:
switch (IR.op9.inst) {
case p2_TESTBN_WZ:
case p2_TESTBN_WC:
cycles = op_TESTBN_W();
break;
case p2_BITH:
case p2_BITH_WCZ:
cycles = op_BITH();
break;
default:
Q_ASSERT_X(false, "TESTBN WC|WZ, BITH {WCZ}", "inst9 error");
}
break;
case p2_TESTB_AND_BITC:
switch (IR.op9.inst) {
case p2_TESTB_ANDZ:
case p2_TESTB_ANDC:
cycles = op_TESTB_AND();
break;
case p2_BITC:
case p2_BITC_WCZ:
cycles = op_BITC();
break;
default:
Q_ASSERT_X(false, "TESTB ANDC|ANDZ, BITC {WCZ}", "inst9 error");
}
break;
case p2_TESTBN_AND_BITNC:
switch (IR.op9.inst) {
case p2_TESTBN_ANDZ:
case p2_TESTBN_ANDC:
cycles = op_TESTBN_AND();
break;
case p2_BITNC:
case p2_BITNC_WCZ:
cycles = op_BITNC();
break;
default:
Q_ASSERT_X(false, "TESTBN ANDC|ANDZ, BITNC {WCZ}", "inst9 error");
}
break;
case p2_TESTB_OR_BITZ:
switch (IR.op9.inst) {
case p2_TESTB_ORC:
case p2_TESTB_ORZ:
cycles = op_TESTB_OR();
break;
case p2_BITZ:
case p2_BITZ_WCZ:
cycles = op_BITZ();
break;
default:
Q_ASSERT_X(false, "TESTB ORC|ORZ, BITZ {WCZ}", "inst9 error");
}
break;
case p2_TESTBN_OR_BITNZ:
switch (IR.op9.inst) {
case p2_TESTBN_ORC:
case p2_TESTBN_ORZ:
cycles = op_TESTBN_OR();
break;
case p2_BITNZ:
case p2_BITNZ_WCZ:
cycles = op_BITNZ();
break;
default:
Q_ASSERT_X(false, "TESTBN ORC|ORZ, BITNZ {WCZ}", "inst9 error");
}
break;
case p2_TESTB_XOR_BITRND:
switch (IR.op9.inst) {
case p2_TESTB_XORC:
case p2_TESTB_XORZ:
cycles = op_TESTB_XOR();
break;
case p2_BITRND:
case p2_BITRND_WCZ:
cycles = op_BITRND();
break;
default:
Q_ASSERT_X(false, "TESTB XORC|XORZ, BITRND {WCZ}", "inst9 error");
}
break;
case p2_TESTBN_XOR_BITNOT:
switch (IR.op9.inst) {
case p2_TESTBN_XORC:
case p2_TESTBN_XORZ:
cycles = op_TESTBN_XOR();
break;
case p2_BITNOT:
case p2_BITNOT_WCZ:
cycles = op_BITNOT();
break;
default:
Q_ASSERT_X(false, "TESTBN XORC|XORZ, BITNOT {WCZ}", "inst9 error");
}
break;
case p2_AND:
cycles = op_AND();
break;
case p2_ANDN:
cycles = op_ANDN();
break;
case p2_OR:
cycles = op_OR();
break;
case p2_XOR:
cycles = op_XOR();
break;
case p2_MUXC:
cycles = op_MUXC();
break;
case p2_MUXNC:
cycles = op_MUXNC();
break;
case p2_MUXZ:
cycles = op_MUXZ();
break;
case p2_MUXNZ:
cycles = op_MUXNZ();
break;
case p2_MOV:
cycles = op_MOV();
break;
case p2_NOT:
cycles = op_NOT();
break;
case p2_ABS:
cycles = op_ABS();
break;
case p2_NEG:
cycles = op_NEG();
break;
case p2_NEGC:
cycles = op_NEGC();
break;
case p2_NEGNC:
cycles = op_NEGNC();
break;
case p2_NEGZ:
cycles = op_NEGZ();
break;
case p2_NEGNZ:
cycles = op_NEGNZ();
break;
case p2_INCMOD:
cycles = op_INCMOD();
break;
case p2_DECMOD:
cycles = op_DECMOD();
break;
case p2_ZEROX:
cycles = op_ZEROX();
break;
case p2_SIGNX:
cycles = op_SIGNX();
break;
case p2_ENCOD:
cycles = op_ENCOD();
break;
case p2_ONES:
cycles = op_ONES();
break;
case p2_TEST:
cycles = op_TEST();
break;
case p2_TESTN:
cycles = op_TESTN();
break;
case p2_SETNIB_0_3:
case p2_SETNIB_4_7:
cycles = op_SETNIB();
break;
case p2_GETNIB_0_3:
case p2_GETNIB_4_7:
cycles = op_GETNIB();
break;
case p2_ROLNIB_0_3:
case p2_ROLNIB_4_7:
cycles = op_ROLNIB();
break;
case p2_SETBYTE_0_3:
cycles = op_SETBYTE();
break;
case p2_GETBYTE_0_3:
cycles = op_GETBYTE();
break;
case p2_ROLBYTE_0_3:
cycles = op_ROLBYTE();
break;
case p2_SETWORD_GETWORD:
switch (IR.op9.inst) {
case p2_SETWORD_ALTSW:
cycles = op_SETWORD_ALTSW();
break;
case p2_SETWORD:
cycles = op_SETWORD();
break;
case p2_GETWORD_ALTGW:
cycles = op_GETWORD_ALTGW();
break;
case p2_GETWORD:
cycles = op_GETWORD();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "SETWORD/GETWORD");
}
break;
case p2_ROLWORD_ALTSN_ALTGN:
switch (IR.op9.inst) {
case p2_ROLWORD_ALTGW:
if (0 == IR.op7.src) {
cycles = op_ROLWORD_ALTGW();
break;
}
break;
case p2_ROLWORD:
cycles = op_ROLWORD();
break;
case p2_ALTSN:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTSN_D();
break;
}
cycles = op_ALTSN();
break;
case p2_ALTGN:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTGN_D();
break;
}
cycles = op_ALTGN();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ROLWORD/ALTSN/ALTGN");
}
break;
case p2_ALTSB_ALTGB_ALTSW_ALTGW:
switch (IR.op9.inst) {
case p2_ALTSB:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTSB_D();
break;
}
cycles = op_ALTSB();
break;
case p2_ALTGB:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTGB_D();
break;
}
cycles = op_ALTGB();
break;
case p2_ALTSW:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTSW_D();
break;
}
cycles = op_ALTSW();
break;
case p2_ALTGW:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTGW_D();
break;
}
cycles = op_ALTGW();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ALTSB/ALTGB/ALTSW/ALTGW");
}
break;
case p2_ALTR_ALTD_ALTS_ALTB:
switch (IR.op9.inst) {
case p2_ALTR:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTR_D();
break;
}
cycles = op_ALTR();
break;
case p2_ALTD:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTD_D();
break;
}
cycles = op_ALTD();
break;
case p2_ALTS:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTS_D();
break;
}
cycles = op_ALTS();
break;
case p2_ALTB:
if (0 == IR.op7.src && true == IR.op7.im) {
cycles = op_ALTB_D();
break;
}
cycles = op_ALTB();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ALTR/ALTD/ALTS/ALTB");
}
break;
case p2_ALTI_SETR_SETD_SETS:
switch (IR.op9.inst) {
case p2_ALTI:
if (true == IR.op7.im && 0x164 == IR.op7.src /* 101100100 */) {
cycles = op_ALTI_D();
break;
}
cycles = op_ALTI();
break;
case p2_SETR:
cycles = op_SETR();
break;
case p2_SETD:
cycles = op_SETD();
break;
case p2_SETS:
cycles = op_SETS();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ALTI/SETR/SETD/SETS");
}
break;
case p2_DECOD_BMASK_CRCBIT_CRCNIB:
switch (IR.op9.inst) {
case p2_DECOD:
if (false == IR.op7.im && IR.op7.src == IR.op7.dst) {
cycles = op_DECOD_D();
break;
}
cycles = op_DECOD();
break;
case p2_BMASK:
if (false == IR.op7.im && IR.op7.src == IR.op7.dst) {
cycles = op_BMASK_D();
break;
}
cycles = op_BMASK();
break;
case p2_CRCBIT:
cycles = op_CRCBIT();
break;
case p2_CRCNIB:
cycles = op_CRCNIB();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "DECOD/BMASK/CRCBIT/CRCNIB");
}
break;
case p2_MUX_NITS_NIBS_Q_MOVBYTS:
switch (IR.op9.inst) {
case p2_MUXNITS:
cycles = op_MUXNITS();
break;
case p2_MUXNIBS:
cycles = op_MUXNIBS();
break;
case p2_MUXQ:
cycles = op_MUXQ();
break;
case p2_MOVBYTS:
cycles = op_MOVBYTS();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "MUXNITS/MUXNIBS/MUXQ/MOVBYTS");
}
break;
case p2_MUL_MULS:
switch (IR.op8.inst) {
case p2_MUL:
cycles = op_MUL();
break;
case p2_MULS:
cycles = op_MULS();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "MUL/MULS");
}
break;
case p2_SCA_SCAS:
switch (IR.op8.inst) {
case p2_SCA:
cycles = op_SCA();
break;
case p2_SCAS:
cycles = op_SCAS();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "SCA/SCAS");
}
break;
case p2_XXXPIX:
switch (IR.op9.inst) {
case p2_ADDPIX:
cycles = op_ADDPIX();
break;
case p2_MULPIX:
cycles = op_MULPIX();
break;
case p2_BLNPIX:
cycles = op_BLNPIX();
break;
case p2_MIXPIX:
cycles = op_MIXPIX();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ADDPIX/MULPIX/BLNPIX/MIXPIX");
}
break;
case p2_WMLONG_ADDCTx:
switch (IR.op9.inst) {
case p2_ADDCT1:
cycles = op_ADDCT1();
break;
case p2_ADDCT2:
cycles = op_ADDCT2();
break;
case p2_ADDCT3:
cycles = op_ADDCT3();
break;
case p2_WMLONG:
cycles = op_WMLONG();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "ADDCT1/ADDCT2/ADDCT3/WMLONG");
}
break;
case p2_RQPIN_RDPIN:
switch (IR.op8.inst) {
case p2_RQPIN:
cycles = op_RQPIN();
break;
case p2_RDPIN:
cycles = op_RDPIN();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "RQPIN/RDPIN");
}
break;
case p2_RDLUT:
cycles = op_RDLUT();
break;
case p2_RDBYTE:
cycles = op_RDBYTE();
break;
case p2_RDWORD:
cycles = op_RDWORD();
break;
case p2_RDLONG:
cycles = op_RDLONG();
break;
case p2_CALLD:
cycles = op_CALLD();
break;
case p2_CALLPA_CALLPB:
switch (IR.op8.inst) {
case p2_CALLPA:
cycles = op_CALLPA();
break;
case p2_CALLPB:
cycles = op_CALLPB();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "CALLPA/CALLPB");
}
break;
case p2_DJZ_DJNZ_DJF_DJNF:
switch (IR.op9.inst) {
case p2_DJZ:
cycles = op_DJZ();
break;
case p2_DJNZ:
cycles = op_DJNZ();
break;
case p2_DJF:
cycles = op_DJF();
break;
case p2_DJNF:
cycles = op_DJNF();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "DJZ/DJNZ/DJF/DJNF");
}
break;
case p2_IJZ_IJNZ_TJZ_TJNZ:
switch (IR.op9.inst) {
case p2_IJZ:
cycles = op_IJZ();
break;
case p2_IJNZ:
cycles = op_IJNZ();
break;
case p2_TJZ:
cycles = op_TJZ();
break;
case p2_TJNZ:
cycles = op_TJNZ();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "IJZ/IJNZ/TJZ/TJNZ");
}
break;
case p2_TJF_TJNF_TJS_TJNS:
switch (IR.op9.inst) {
case p2_TJF:
cycles = op_TJF();
break;
case p2_TJNF:
cycles = op_TJNF();
break;
case p2_TJS:
cycles = op_TJS();
break;
case p2_TJNS:
cycles = op_TJNS();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "TJF/TJNF/TJS/TJNS");
}
break;
case p2_TJV_OPDST_empty:
if (false == IR.op7.wc) {
if (false == IR.op7.wz) {
cycles = op_TJV();
} else {
switch (IR.op7.dst) {
case p2_OPDST_JINT:
cycles = op_JINT();
break;
case p2_OPDST_JCT1:
cycles = op_JCT1();
break;
case p2_OPDST_JCT2:
cycles = op_JCT2();
break;
case p2_OPDST_JCT3:
cycles = op_JCT3();
break;
case p2_OPDST_JSE1:
cycles = op_JSE1();
break;
case p2_OPDST_JSE2:
cycles = op_JSE2();
break;
case p2_OPDST_JSE3:
cycles = op_JSE3();
break;
case p2_OPDST_JSE4:
cycles = op_JSE4();
break;
case p2_OPDST_JPAT:
cycles = op_JPAT();
break;
case p2_OPDST_JFBW:
cycles = op_JFBW();
break;
case p2_OPDST_JXMT:
cycles = op_JXMT();
break;
case p2_OPDST_JXFI:
cycles = op_JXFI();
break;
case p2_OPDST_JXRO:
cycles = op_JXRO();
break;
case p2_OPDST_JXRL:
cycles = op_JXRL();
break;
case p2_OPDST_JATN:
cycles = op_JATN();
break;
case p2_OPDST_JQMT:
cycles = op_JQMT();
break;
case p2_OPDST_JNINT:
cycles = op_JNINT();
break;
case p2_OPDST_JNCT1:
cycles = op_JNCT1();
break;
case p2_OPDST_JNCT2:
cycles = op_JNCT2();
break;
case p2_OPDST_JNCT3:
cycles = op_JNCT3();
break;
case p2_OPDST_JNSE1:
cycles = op_JNSE1();
break;
case p2_OPDST_JNSE2:
cycles = op_JNSE2();
break;
case p2_OPDST_JNSE3:
cycles = op_JNSE3();
break;
case p2_OPDST_JNSE4:
cycles = op_JNSE4();
break;
case p2_OPDST_JNPAT:
cycles = op_JNPAT();
break;
case p2_OPDST_JNFBW:
cycles = op_JNFBW();
break;
case p2_OPDST_JNXMT:
cycles = op_JNXMT();
break;
case p2_OPDST_JNXFI:
cycles = op_JNXFI();
break;
case p2_OPDST_JNXRO:
cycles = op_JNXRO();
break;
case p2_OPDST_JNXRL:
cycles = op_JNXRL();
break;
case p2_OPDST_JNATN:
cycles = op_JNATN();
break;
case p2_OPDST_JNQMT:
cycles = op_JNQMT();
break;
default:
// TODO: invalid D value
Q_ASSERT_X(false, "p2_opdst_e", "missing enum value");
break;
}
}
} else {
cycles = op_1011110_1();
}
break;
case p2_empty_SETPAT:
switch (IR.op8.inst) {
case p2_1011111_0:
cycles = op_1011111_0();
break;
case p2_SETPAT:
cycles = op_SETPAT();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "1011111_0/SETPAT");
}
break;
case p2_WRPIN_AKPIN_WXPIN:
switch (IR.op8.inst) {
case p2_WRPIN:
if (IR.op7.wz == 1 && IR.op7.dst == 1) {
cycles = op_AKPIN();
break;
}
cycles = op_WRPIN();
break;
case p2_WXPIN:
cycles = op_WXPIN();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "WRPIN/AKPIN/WXPIN");
}
break;
case p2_WYPIN_WRLUT:
switch (IR.op8.inst) {
case p2_WYPIN:
cycles = op_WYPIN();
break;
case p2_WRLUT:
cycles = op_WRLUT();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "WYPIN/WRLUT");
}
break;
case p2_WRBYTE_WRWORD:
switch (IR.op8.inst) {
case p2_WRBYTE:
cycles = op_WRBYTE();
break;
case p2_WRWORD:
cycles = op_WRWORD();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "WRBYTE/WRWORD");
}
break;
case p2_WRLONG_RDFAST:
switch (IR.op8.inst) {
case p2_WRLONG:
cycles = op_WRLONG();
break;
case p2_RDFAST:
cycles = op_RDFAST();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "WRLONG/RDFAST");
}
break;
case p2_WRFAST_FBLOCK:
switch (IR.op8.inst) {
case p2_WRFAST:
cycles = op_WRFAST();
break;
case p2_FBLOCK:
cycles = op_FBLOCK();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "WRFAST/FBLOCK");
}
break;
case p2_XINIT_XSTOP_XZERO:
switch (IR.op8.inst) {
case p2_XINIT:
if (IR.op7.wz == 1 && true == IR.op7.im && 0 == IR.op7.src && 0 == IR.op7.dst) {
cycles = op_XSTOP();
break;
}
cycles = op_XINIT();
break;
case p2_XZERO:
cycles = op_XZERO();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "XINIT/XSTOP/XZERO");
}
break;
case p2_XCONT_REP:
switch (IR.op8.inst) {
case p2_XCONT:
cycles = op_XCONT();
break;
case p2_REP:
cycles = op_REP();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "XCONT/REP");
}
break;
case p2_COGINIT:
cycles = op_COGINIT();
break;
case p2_QMUL_QDIV:
switch (IR.op8.inst) {
case p2_QMUL:
cycles = op_QMUL();
break;
case p2_QDIV:
cycles = op_QDIV();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "QMUL/QDIV");
}
break;
case p2_QFRAC_QSQRT:
switch (IR.op8.inst) {
case p2_QFRAC:
cycles = op_QFRAC();
break;
case p2_QSQRT:
cycles = op_QSQRT();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "QFRAC/QSQRT");
}
break;
case p2_QROTATE_QVECTOR:
switch (IR.op8.inst) {
case p2_QROTATE:
cycles = op_QROTATE();
break;
case p2_QVECTOR:
cycles = op_QVECTOR();
break;
default:
Q_ASSERT_X(false, "p2_inst8_e", "QROTATE/QVECTOR");
}
break;
case p2_OPSRC:
switch (IR.op7.src) {
case p2_OPSRC_HUBSET:
cycles = op_HUBSET();
break;
case p2_OPSRC_COGID:
cycles = op_COGID();
break;
case p2_OPSRC_COGSTOP:
cycles = op_COGSTOP();
break;
case p2_OPSRC_LOCKNEW:
cycles = op_LOCKNEW();
break;
case p2_OPSRC_LOCKRET:
cycles = op_LOCKRET();
break;
case p2_OPSRC_LOCKTRY:
cycles = op_LOCKTRY();
break;
case p2_OPSRC_LOCKREL:
cycles = op_LOCKREL();
break;
case p2_OPSRC_QLOG:
cycles = op_QLOG();
break;
case p2_OPSRC_QEXP:
cycles = op_QEXP();
break;
case p2_OPSRC_RFBYTE:
cycles = op_RFBYTE();
break;
case p2_OPSRC_RFWORD:
cycles = op_RFWORD();
break;
case p2_OPSRC_RFLONG:
cycles = op_RFLONG();
break;
case p2_OPSRC_RFVAR:
cycles = op_RFVAR();
break;
case p2_OPSRC_RFVARS:
cycles = op_RFVARS();
break;
case p2_OPSRC_WFBYTE:
cycles = op_WFBYTE();
break;
case p2_OPSRC_WFWORD:
cycles = op_WFWORD();
break;
case p2_OPSRC_WFLONG:
cycles = op_WFLONG();
break;
case p2_OPSRC_GETQX:
cycles = op_GETQX();
break;
case p2_OPSRC_GETQY:
cycles = op_GETQY();
break;
case p2_OPSRC_GETCT:
cycles = op_GETCT();
break;
case p2_OPSRC_GETRND:
if (0 == IR.op7.dst) {
cycles = op_GETRND_CZ();
break;
}
cycles = op_GETRND();
break;
case p2_OPSRC_SETDACS:
cycles = op_SETDACS();
break;
case p2_OPSRC_SETXFRQ:
cycles = op_SETXFRQ();
break;
case p2_OPSRC_GETXACC:
cycles = op_GETACC();
break;
case p2_OPSRC_WAITX:
cycles = op_WAITX();
break;
case p2_OPSRC_SETSE1:
cycles = op_SETSE1();
break;
case p2_OPSRC_SETSE2:
cycles = op_SETSE2();
break;
case p2_OPSRC_SETSE3:
cycles = op_SETSE3();
break;
case p2_OPSRC_SETSE4:
cycles = op_SETSE4();
break;
case p2_OPSRC_X24:
switch (IR.op7.dst) {
case p2_OPX24_POLLINT:
cycles = op_POLLINT();
break;
case p2_OPX24_POLLCT1:
cycles = op_POLLCT1();
break;
case p2_OPX24_POLLCT2:
cycles = op_POLLCT2();
break;
case p2_OPX24_POLLCT3:
cycles = op_POLLCT3();
break;
case p2_OPX24_POLLSE1:
cycles = op_POLLSE1();
break;
case p2_OPX24_POLLSE2:
cycles = op_POLLSE2();
break;
case p2_OPX24_POLLSE3:
cycles = op_POLLSE3();
break;
case p2_OPX24_POLLSE4:
cycles = op_POLLSE4();
break;
case p2_OPX24_POLLPAT:
cycles = op_POLLPAT();
break;
case p2_OPX24_POLLFBW:
cycles = op_POLLFBW();
break;
case p2_OPX24_POLLXMT:
cycles = op_POLLXMT();
break;
case p2_OPX24_POLLXFI:
cycles = op_POLLXFI();
break;
case p2_OPX24_POLLXRO:
cycles = op_POLLXRO();
break;
case p2_OPX24_POLLXRL:
cycles = op_POLLXRL();
break;
case p2_OPX24_POLLATN:
cycles = op_POLLATN();
break;
case p2_OPX24_POLLQMT:
cycles = op_POLLQMT();
break;
case p2_OPX24_WAITINT:
cycles = op_WAITINT();
break;
case p2_OPX24_WAITCT1:
cycles = op_WAITCT1();
break;
case p2_OPX24_WAITCT2:
cycles = op_WAITCT2();
break;
case p2_OPX24_WAITCT3:
cycles = op_WAITCT3();
break;
case p2_OPX24_WAITSE1:
cycles = op_WAITSE1();
break;
case p2_OPX24_WAITSE2:
cycles = op_WAITSE2();
break;
case p2_OPX24_WAITSE3:
cycles = op_WAITSE3();
break;
case p2_OPX24_WAITSE4:
cycles = op_WAITSE4();
break;
case p2_OPX24_WAITPAT:
cycles = op_WAITPAT();
break;
case p2_OPX24_WAITFBW:
cycles = op_WAITFBW();
break;
case p2_OPX24_WAITXMT:
cycles = op_WAITXMT();
break;
case p2_OPX24_WAITXFI:
cycles = op_WAITXFI();
break;
case p2_OPX24_WAITXRO:
cycles = op_WAITXRO();
break;
case p2_OPX24_WAITXRL:
cycles = op_WAITXRL();
break;
case p2_OPX24_WAITATN:
cycles = op_WAITATN();
break;
case p2_OPX24_ALLOWI:
cycles = op_ALLOWI();
break;
case p2_OPX24_STALLI:
cycles = op_STALLI();
break;
case p2_OPX24_TRGINT1:
cycles = op_TRGINT1();
break;
case p2_OPX24_TRGINT2:
cycles = op_TRGINT2();
break;
case p2_OPX24_TRGINT3:
cycles = op_TRGINT3();
break;
case p2_OPX24_NIXINT1:
cycles = op_NIXINT1();
break;
case p2_OPX24_NIXINT2:
cycles = op_NIXINT2();
break;
case p2_OPX24_NIXINT3:
cycles = op_NIXINT3();
break;
}
break;
case p2_OPSRC_SETINT1:
cycles = op_SETINT1();
break;
case p2_OPSRC_SETINT2:
cycles = op_SETINT2();
break;
case p2_OPSRC_SETINT3:
cycles = op_SETINT3();
break;
case p2_OPSRC_SETQ:
cycles = op_SETQ();
break;
case p2_OPSRC_SETQ2:
cycles = op_SETQ2();
break;
case p2_OPSRC_PUSH:
cycles = op_PUSH();
break;
case p2_OPSRC_POP:
cycles = op_POP();
break;
case p2_OPSRC_JMP:
cycles = op_JMP();
break;
case p2_OPSRC_CALL_RET:
if (false == IR.op7.im) {
cycles = op_CALL();
break;
}
cycles = op_RET();
break;
case p2_OPSRC_CALLA_RETA:
if (false == IR.op7.im) {
cycles = op_CALLA();
break;
}
cycles = op_RETA();
break;
case p2_OPSRC_CALLB_RETB:
if (false == IR.op7.im) {
cycles = op_CALLB();
break;
}
cycles = op_RETB();
break;
case p2_OPSRC_JMPREL:
cycles = op_JMPREL();
break;
case p2_OPSRC_SKIP:
cycles = op_SKIP();
break;
case p2_OPSRC_SKIPF:
cycles = op_SKIPF();
break;
case p2_OPSRC_EXECF:
cycles = op_EXECF();
break;
case p2_OPSRC_GETPTR:
cycles = op_GETPTR();
break;
case p2_OPSRC_COGBRK:
switch (IR.op9.inst) {
case p2_COGBRK:
cycles = op_COGBRK();
break;
case p2_GETBRK_WZ:
case p2_GETBRK_WC:
case p2_GETBRK_WCZ:
cycles = op_GETBRK();
break;
default:
Q_ASSERT_X(false, "p2_inst9_e", "COGBRK/GETBRK {WZ,WC,WCZ}");
}
break;
case p2_OPSRC_BRK:
cycles = op_BRK();
break;
case p2_OPSRC_SETLUTS:
cycles = op_SETLUTS();
break;
case p2_OPSRC_SETCY:
cycles = op_SETCY();
break;
case p2_OPSRC_SETCI:
cycles = op_SETCI();
break;
case p2_OPSRC_SETCQ:
cycles = op_SETCQ();
break;
case p2_OPSRC_SETCFRQ:
cycles = op_SETCFRQ();
break;
case p2_OPSRC_SETCMOD:
cycles = op_SETCMOD();
break;
case p2_OPSRC_SETPIV:
cycles = op_SETPIV();
break;
case p2_OPSRC_SETPIX:
cycles = op_SETPIX();
break;
case p2_OPSRC_COGATN:
cycles = op_COGATN();
break;
case p2_OPSRC_TESTP_W_DIRL:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTP_W()
: op_DIRL();
break;
case p2_OPSRC_TESTPN_W_DIRH:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTPN_W()
: op_DIRH();
break;
case p2_OPSRC_TESTP_AND_DIRC:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTP_AND()
: op_DIRC();
break;
case p2_OPSRC_TESTPN_AND_DIRNC:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTPN_AND()
: op_DIRNC();
break;
case p2_OPSRC_TESTP_OR_DIRZ:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTP_OR()
: op_DIRZ();
break;
case p2_OPSRC_TESTPN_OR_DIRNZ:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTPN_OR()
: op_DIRNZ();
break;
case p2_OPSRC_TESTP_XOR_DIRRND:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTP_XOR()
: op_DIRRND();
break;
case p2_OPSRC_TESTPN_XOR_DIRNOT:
cycles = (IR.op7.wc != IR.op7.wz) ? op_TESTPN_XOR()
: op_DIRNOT();
break;
case p2_OPSRC_OUTL:
cycles = op_OUTL();
break;
case p2_OPSRC_OUTH:
cycles = op_OUTH();
break;
case p2_OPSRC_OUTC:
cycles = op_OUTC();
break;
case p2_OPSRC_OUTNC:
cycles = op_OUTNC();
break;
case p2_OPSRC_OUTZ:
cycles = op_OUTZ();
break;
case p2_OPSRC_OUTNZ:
cycles = op_OUTNZ();
break;
case p2_OPSRC_OUTRND:
cycles = op_OUTRND();
break;
case p2_OPSRC_OUTNOT:
cycles = op_OUTNOT();
break;
case p2_OPSRC_FLTL:
cycles = op_FLTL();
break;
case p2_OPSRC_FLTH:
cycles = op_FLTH();
break;
case p2_OPSRC_FLTC:
cycles = op_FLTC();
break;
case p2_OPSRC_FLTNC:
cycles = op_FLTNC();
break;
case p2_OPSRC_FLTZ:
cycles = op_FLTZ();
break;
case p2_OPSRC_FLTNZ:
cycles = op_FLTNZ();
break;
case p2_OPSRC_FLTRND:
cycles = op_FLTRND();
break;
case p2_OPSRC_FLTNOT:
cycles = op_FLTNOT();
break;
case p2_OPSRC_DRVL:
cycles = op_DRVL();
break;
case p2_OPSRC_DRVH:
cycles = op_DRVH();
break;
case p2_OPSRC_DRVC:
cycles = op_DRVC();
break;
case p2_OPSRC_DRVNC:
cycles = op_DRVNC();
break;
case p2_OPSRC_DRVZ:
cycles = op_DRVZ();
break;
case p2_OPSRC_DRVNZ:
cycles = op_DRVNZ();
break;
case p2_OPSRC_DRVRND:
cycles = op_DRVRND();
break;
case p2_OPSRC_DRVNOT:
cycles = op_DRVNOT();
break;
case p2_OPSRC_SPLITB:
cycles = op_SPLITB();
break;
case p2_OPSRC_MERGEB:
cycles = op_MERGEB();
break;
case p2_OPSRC_SPLITW:
cycles = op_SPLITW();
break;
case p2_OPSRC_MERGEW:
cycles = op_MERGEW();
break;
case p2_OPSRC_SEUSSF:
cycles = op_SEUSSF();
break;
case p2_OPSRC_SEUSSR:
cycles = op_SEUSSR();
break;
case p2_OPSRC_RGBSQZ:
cycles = op_RGBSQZ();
break;
case p2_OPSRC_RGBEXP:
cycles = op_RGBEXP();
break;
case p2_OPSRC_XORO32:
cycles = op_XORO32();
break;
case p2_OPSRC_REV:
cycles = op_REV();
break;
case p2_OPSRC_RCZR:
cycles = op_RCZR();
break;
case p2_OPSRC_RCZL:
cycles = op_RCZL();
break;
case p2_OPSRC_WRC:
cycles = op_WRC();
break;
case p2_OPSRC_WRNC:
cycles = op_WRNC();
break;
case p2_OPSRC_WRZ:
cycles = op_WRZ();
break;
case p2_OPSRC_WRNZ_MODCZ:
cycles = (IR.op7.wc || IR.op7.wz) ? op_MODCZ()
: op_WRNZ();
break;
case p2_OPSRC_SETSCP:
cycles = op_SETSCP();
break;
case p2_OPSRC_GETSCP:
cycles = op_GETSCP();
break;
}
break;
case p2_JMP_ABS:
cycles = op_JMP_ABS();
break;
case p2_CALL_ABS:
cycles = op_CALL_ABS();
break;
case p2_CALLA_ABS:
cycles = op_CALLA_ABS();
break;
case p2_CALLB_ABS:
cycles = op_CALLB_ABS();
break;
case p2_CALLD_ABS_PA:
cycles = op_CALLD_ABS_PA();
break;
case p2_CALLD_ABS_PB:
cycles = op_CALLD_ABS_PB();
break;
case p2_CALLD_ABS_PTRA:
cycles = op_CALLD_ABS_PTRA();
break;
case p2_CALLD_ABS_PTRB:
cycles = op_CALLD_ABS_PTRB();
break;
case p2_LOC_PA:
cycles = op_LOC_PA();
break;
case p2_LOC_PB:
cycles = op_LOC_PB();
break;
case p2_LOC_PTRA:
cycles = op_LOC_PTRA();
break;
case p2_LOC_PTRB:
cycles = op_LOC_PTRB();
break;
case p2_AUGS_00:
case p2_AUGS_01:
case p2_AUGS_10:
case p2_AUGS_11:
cycles = op_AUGS();
break;
case p2_AUGD_00:
case p2_AUGD_01:
case p2_AUGD_10:
case p2_AUGD_11:
cycles = op_AUGD();
break;
}
// Handle REP instructions
if (IR.op8.inst != p2_REP && REP_instr.isValid()) {
p2_LONG instr = REP_instr.toUInt();
// qDebug("%s: repeat %u instructions %u times", __func__, instr, REP_times);
if (++REP_offset == instr) {
if (REP_times == 0 || --REP_times > 0) {
PC = PC - (PC < 0x400 ? instr : 4 * instr);
REP_offset = 0;
}
}
}
return cycles;
}
/**
* @brief No operation.
*<pre>
* 0000 0000000 000 000000000 000000000
*
* NOP
*</pre>
*/
int P2Cog::op_NOP()
{
return 1;
}
/**
* @brief Rotate right.
*<pre>
* EEEE 0000000 CZI DDDDDDDDD SSSSSSSSS
*
* ROR D,{#}S {WC/WZ/WCZ}
*
* D = [31:0] of ({D[31:0], D[31:0]} >> S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[0].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ROR()
{
if (0 == IR.opcode)
return op_NOP();
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) << 32 | U64(D);
const p2_LONG result = U32L(accu >> shift);
updateC((D & (LSB << shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Rotate left.
*<pre>
* EEEE 0000001 CZI DDDDDDDDD SSSSSSSSS
*
* ROL D,{#}S {WC/WZ/WCZ}
*
* D = [63:32] of ({D[31:0], D[31:0]} << S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ROL()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) << 32 | U64(D);
const p2_LONG result = U32H(accu << shift);
updateC((D & (MSB >> shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Shift right.
*<pre>
* EEEE 0000010 CZI DDDDDDDDD SSSSSSSSS
*
* SHR D,{#}S {WC/WZ/WCZ}
*
* D = [31:0] of ({32'b0, D[31:0]} >> S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[0].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SHR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D);
const p2_LONG result = U32L(accu >> shift);
updateC((D & (LSB << shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Shift left.
*<pre>
* EEEE 0000011 CZI DDDDDDDDD SSSSSSSSS
*
* SHL D,{#}S {WC/WZ/WCZ}
*
* D = [63:32] of ({D[31:0], 32'b0} << S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SHL()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) << 32;
const p2_LONG result = U32H(accu << shift);
updateC((D & (MSB >> shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Rotate carry right.
*<pre>
* EEEE 0000100 CZI DDDDDDDDD SSSSSSSSS
*
* RCR D,{#}S {WC/WZ/WCZ}
*
* D = [31:0] of ({{32{C}}, D[31:0]} >> S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[0].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RCR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) | C ? HMAX : 0;
const p2_LONG result = U32L(accu >> shift);
updateC((D & (LSB << shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Rotate carry left.
*<pre>
* EEEE 0000101 CZI DDDDDDDDD SSSSSSSSS
*
* RCL D,{#}S {WC/WZ/WCZ}
*
* D = [63:32] of ({D[31:0], {32{C}}} << S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RCL()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) << 32 | C ? LMAX : 0;
const p2_LONG result = U32H(accu << shift);
updateC((D & (MSB >> shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Shift arithmetic right.
*<pre>
* EEEE 0000110 CZI DDDDDDDDD SSSSSSSSS
*
* SAR D,{#}S {WC/WZ/WCZ}
*
* D = [31:0] of ({{32{D[31]}}, D[31:0]} >> S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[0].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SAR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) | (D & MSB) ? HMAX : 0;
const p2_LONG result = U32L(accu >> shift);
updateC((D & (LSB << shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Shift arithmetic left.
*<pre>
* EEEE 0000111 CZI DDDDDDDDD SSSSSSSSS
*
* SAL D,{#}S {WC/WZ/WCZ}
*
* D = [63:32] of ({D[31:0], {32{D[0]}}} << S[4:0]).
* C = last bit shifted out if S[4:0] > 0, else D[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SAL()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_QUAD accu = U64(D) << 32 | (D & LSB) ? LMAX : 0;
const p2_LONG result = U32H(accu << shift);
updateC((D & (MSB >> shift)) != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Add S into D.
*<pre>
* EEEE 0001000 CZI DDDDDDDDD SSSSSSSSS
*
* ADD D,{#}S {WC/WZ/WCZ}
*
* D = D + S.
* C = carry of (D + S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ADD()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) + U64(S);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Add (S + C) into D, extended.
*<pre>
* EEEE 0001001 CZI DDDDDDDDD SSSSSSSSS
*
* ADDX D,{#}S {WC/WZ/WCZ}
*
* D = D + S + C.
* C = carry of (D + S + C).
* Z = Z AND (result == 0).
*</pre>
*/
int P2Cog::op_ADDX()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) + U64(S) + C;
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(Z & (result == 0));
updateD(result);
return 1;
}
/**
* @brief Add S into D, signed.
*<pre>
* EEEE 0001010 CZI DDDDDDDDD SSSSSSSSS
*
* ADDS D,{#}S {WC/WZ/WCZ}
*
* D = D + S.
* C = correct sign of (D + S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ADDS()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const qint64 accu = SX64(D) + SX64(S);
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Add (S + C) into D, signed and extended.
*<pre>
* EEEE 0001011 CZI DDDDDDDDD SSSSSSSSS
*
* ADDSX D,{#}S {WC/WZ/WCZ}
*
* D = D + S + C.
* C = correct sign of (D + S + C).
* Z = Z AND (result == 0).
*</pre>
*/
int P2Cog::op_ADDSX()
{
augmentS(IR.op7.im);
const uchar sign = (D ^ (S + C)) >> 31;
const qint64 accu = SX64(D) + SX64(S) + C;
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(Z & (result == 0));
updateD(result);
return 1;
}
/**
* @brief Subtract S from D.
*<pre>
* EEEE 0001100 CZI DDDDDDDDD SSSSSSSSS
*
* SUB D,{#}S {WC/WZ/WCZ}
*
* D = D - S.
* C = borrow of (D - S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUB()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) - U64(S);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Subtract (S + C) from D, extended.
*<pre>
* EEEE 0001101 CZI DDDDDDDDD SSSSSSSSS
*
* SUBX D,{#}S {WC/WZ/WCZ}
*
* D = D - (S + C).
* C = borrow of (D - (S + C)).
* Z = Z AND (result == 0).
*</pre>
*/
int P2Cog::op_SUBX()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) - (U64(S) + C);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(Z & (result == 0));
updateD(result);
return 1;
}
/**
* @brief Subtract S from D, signed.
*<pre>
* EEEE 0001110 CZI DDDDDDDDD SSSSSSSSS
*
* SUBS D,{#}S {WC/WZ/WCZ}
*
* D = D - S.
* C = correct sign of (D - S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUBS()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const qint64 accu = SX64(D) - SX64(S);
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Subtract (S + C) from D, signed and extended.
*<pre>
* EEEE 0001111 CZI DDDDDDDDD SSSSSSSSS
*
* SUBSX D,{#}S {WC/WZ/WCZ}
*
* D = D - (S + C).
* C = correct sign of (D - (S + C)).
* Z = Z AND (result == 0).
*</pre>
*/
int P2Cog::op_SUBSX()
{
augmentS(IR.op7.im);
const uchar sign = (D ^ (S + C)) >> 31;
const qint64 accu = SX64(D) - (SX64(S) + C);
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(Z & (result == 0));
updateD(result);
return 1;
}
/**
* @brief Compare D to S.
*<pre>
* EEEE 0010000 CZI DDDDDDDDD SSSSSSSSS
*
* CMP D,{#}S {WC/WZ/WCZ}
*
* C = borrow of (D - S).
* Z = (D == S).
*</pre>
*/
int P2Cog::op_CMP()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) - U64(S);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(0 == result);
return 1;
}
/**
* @brief Compare D to (S + C), extended.
*<pre>
* EEEE 0010001 CZI DDDDDDDDD SSSSSSSSS
*
* CMPX D,{#}S {WC/WZ/WCZ}
*
* C = borrow of (D - (S + C)).
* Z = Z AND (D == S + C).
*</pre>
*/
int P2Cog::op_CMPX()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) - (U64(S) + C);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(Z & (result == 0));
return 1;
}
/**
* @brief Compare D to S, signed.
*<pre>
* EEEE 0010010 CZI DDDDDDDDD SSSSSSSSS
*
* CMPS D,{#}S {WC/WZ/WCZ}
*
* C = correct sign of (D - S).
* Z = (D == S).
*</pre>
*/
int P2Cog::op_CMPS()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const qint64 accu = SX64(D) - SX64(S);
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(0 == result);
return 1;
}
/**
* @brief Compare D to (S + C), signed and extended.
*<pre>
* EEEE 0010011 CZI DDDDDDDDD SSSSSSSSS
*
* CMPSX D,{#}S {WC/WZ/WCZ}
*
* C = correct sign of (D - (S + C)).
* Z = Z AND (D == S + C).
*</pre>
*/
int P2Cog::op_CMPSX()
{
augmentS(IR.op7.im);
const uchar sign = (D ^ (S + C)) >> 31;
const qint64 accu = SX64(D) - (SX64(S) + C);
const p2_LONG result = U32L(accu);
updateC((accu < 0) ^ sign);
updateZ(Z & (result == 0));
return 1;
}
/**
* @brief Compare S to D (reverse).
*<pre>
* EEEE 0010100 CZI DDDDDDDDD SSSSSSSSS
*
* CMPR D,{#}S {WC/WZ/WCZ}
*
* C = borrow of (S - D).
* Z = (D == S).
*</pre>
*/
int P2Cog::op_CMPR()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(S) - U64(D);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(0 == result);
return 1;
}
/**
* @brief Compare D to S, get MSB of difference into C.
*<pre>
* EEEE 0010101 CZI DDDDDDDDD SSSSSSSSS
*
* CMPM D,{#}S {WC/WZ/WCZ}
*
* C = MSB of (D - S).
* Z = (D == S).
*</pre>
*/
int P2Cog::op_CMPM()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(D) - U64(S);
const p2_LONG result = U32L(accu);
updateC((accu >> 31) & 1);
updateZ(0 == result);
return 1;
}
/**
* @brief Subtract D from S (reverse).
*<pre>
* EEEE 0010110 CZI DDDDDDDDD SSSSSSSSS
*
* SUBR D,{#}S {WC/WZ/WCZ}
*
* D = S - D.
* C = borrow of (S - D).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUBR()
{
augmentS(IR.op7.im);
const p2_QUAD accu = U64(S) - U64(D);
const p2_LONG result = U32L(accu);
updateC((accu >> 32) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Compare and subtract S from D if D >= S.
*<pre>
* EEEE 0010111 CZI DDDDDDDDD SSSSSSSSS
*
* CMPSUB D,{#}S {WC/WZ/WCZ}
*
* If D => S then D = D - S and C = 1, else D same and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_CMPSUB()
{
augmentS(IR.op7.im);
if (D < S) {
// Do not change D
const p2_LONG result = D;
updateC(0);
updateZ(0 == result);
} else {
// Do the subtract and set C = 1, if WC is set
const p2_QUAD accu = U64(D) - U64(S);
const p2_LONG result = U32L(accu);
updateC(1);
updateZ(0 == result);
updateD(result);
}
return 1;
}
/**
* @brief Force D >= S.
*<pre>
* EEEE 0011000 CZI DDDDDDDDD SSSSSSSSS
*
* FGE D,{#}S {WC/WZ/WCZ}
*
* If D < S then D = S and C = 1, else D same and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_FGE()
{
augmentS(IR.op7.im);
if (D < S) {
const p2_LONG result = S;
updateC(1);
updateZ(0 == result);
updateD(result);
} else {
const p2_LONG result = D;
updateC(0);
updateZ(0 == result);
}
return 1;
}
/**
* @brief Force D <= S.
*<pre>
* EEEE 0011001 CZI DDDDDDDDD SSSSSSSSS
*
* FLE D,{#}S {WC/WZ/WCZ}
*
* If D > S then D = S and C = 1, else D same and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_FLE()
{
augmentS(IR.op7.im);
if (D > S) {
const p2_LONG result = S;
updateC(1);
updateZ(0 == result);
updateD(result);
} else {
const p2_LONG result = D;
updateC(0);
updateZ(0 == result);
}
return 1;
}
/**
* @brief Force D >= S, signed.
*<pre>
* EEEE 0011010 CZI DDDDDDDDD SSSSSSSSS
*
* FGES D,{#}S {WC/WZ/WCZ}
*
* If D < S then D = S and C = 1, else D same and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_FGES()
{
augmentS(IR.op7.im);
if (S32(D) < S32(S)) {
const p2_LONG result = S;
updateC(1);
updateZ(0 == result);
updateD(result);
} else {
const p2_LONG result = D;
updateC(0);
updateZ(0 == result);
}
return 1;
}
/**
* @brief Force D <= S, signed.
*<pre>
* EEEE 0011011 CZI DDDDDDDDD SSSSSSSSS
*
* FLES D,{#}S {WC/WZ/WCZ}
*
* If D > S then D = S and C = 1, else D same and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_FLES()
{
augmentS(IR.op7.im);
if (S32(D) > S32(S)) {
const p2_LONG result = S;
updateC(1);
updateZ(0 == result);
updateD(result);
} else {
const p2_LONG result = D;
updateC(0);
updateZ(0 == result);
}
return 1;
}
/**
* @brief Sum +/-S into D by C.
*<pre>
* EEEE 0011100 CZI DDDDDDDDD SSSSSSSSS
*
* SUMC D,{#}S {WC/WZ/WCZ}
*
* If C = 1 then D = D - S, else D = D + S.
* C = correct sign of (D +/- S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUMC()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const p2_QUAD accu = C ? U64(D) - U64(S) : U64(D) + U64(S);
const p2_LONG result = U32L(accu);
updateC(((accu >> 32) & 1) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Sum +/-S into D by !C.
*<pre>
* EEEE 0011101 CZI DDDDDDDDD SSSSSSSSS
*
* SUMNC D,{#}S {WC/WZ/WCZ}
*
* If C = 0 then D = D - S, else D = D + S.
* C = correct sign of (D +/- S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUMNC()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const p2_QUAD accu = !C ? U64(D) - U64(S) : U64(D) + U64(S);
const p2_LONG result = U32L(accu);
updateC(((accu >> 32) & 1) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Sum +/-S into D by Z.
*<pre>
* EEEE 0011110 CZI DDDDDDDDD SSSSSSSSS
*
* SUMZ D,{#}S {WC/WZ/WCZ}
*
* If Z = 1 then D = D - S, else D = D + S.
* C = correct sign of (D +/- S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUMZ()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const p2_QUAD accu = Z ? U64(D) - U64(S) : U64(D) + U64(S);
const p2_LONG result = U32L(accu);
updateC(((accu >> 32) & 1) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Sum +/-S into D by !Z.
*<pre>
* EEEE 0011111 CZI DDDDDDDDD SSSSSSSSS
*
* SUMNZ D,{#}S {WC/WZ/WCZ}
*
* If Z = 0 then D = D - S, else D = D + S.
* C = correct sign of (D +/- S).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SUMNZ()
{
augmentS(IR.op7.im);
const bool sign = (S32(D) ^ S32(S)) < 0;
const p2_QUAD accu = !Z ? U64(D) - U64(S) : U64(D) + U64(S);
const p2_LONG result = U32L(accu);
updateC(((accu >> 32) & 1) ^ sign);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Test bit S[4:0] of D, write to C/Z.
*<pre>
* EEEE 0100000 CZI DDDDDDDDD SSSSSSSSS
*
* TESTB D,{#}S WC/WZ
*
* C/Z = D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTB_W()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (D >> shift) & 1;
updateC(bit);
updateZ(bit);
return 1;
}
/**
* @brief Test bit S[4:0] of !D, write to C/Z.
*<pre>
* EEEE 0100001 CZI DDDDDDDDD SSSSSSSSS
*
* TESTBN D,{#}S WC/WZ
*
* C/Z = !D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTBN_W()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (~D >> shift) & 1;
updateC(bit);
updateZ(bit);
return 1;
}
/**
* @brief Test bit S[4:0] of D, AND into C/Z.
*<pre>
* EEEE 0100010 CZI DDDDDDDDD SSSSSSSSS
*
* TESTB D,{#}S ANDC/ANDZ
*
* C/Z = C/Z AND D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTB_AND()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (D >> shift) & 1;
updateC(C & bit);
updateZ(Z & bit);
return 1;
}
/**
* @brief Test bit S[4:0] of !D, AND into C/Z.
*<pre>
* EEEE 0100011 CZI DDDDDDDDD SSSSSSSSS
*
* TESTBN D,{#}S ANDC/ANDZ
*
* C/Z = C/Z AND !D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTBN_AND()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (~D >> shift) & 1;
updateC(C & bit);
updateZ(Z & bit);
return 1;
}
/**
* @brief Test bit S[4:0] of D, OR into C/Z.
*<pre>
* EEEE 0100100 CZI DDDDDDDDD SSSSSSSSS
*
* TESTB D,{#}S ORC/ORZ
*
* C/Z = C/Z OR D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTB_OR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (D >> shift) & 1;
updateC(C | bit);
updateZ(Z | bit);
return 1;
}
/**
* @brief Test bit S[4:0] of !D, OR into C/Z.
*<pre>
* EEEE 0100101 CZI DDDDDDDDD SSSSSSSSS
*
* TESTBN D,{#}S ORC/ORZ
*
* C/Z = C/Z OR !D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTBN_OR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (~D >> shift) & 1;
updateC(C | bit);
updateZ(Z | bit);
return 1;
}
/**
* @brief Test bit S[4:0] of D, XOR into C/Z.
*<pre>
* EEEE 0100110 CZI DDDDDDDDD SSSSSSSSS
*
* TESTB D,{#}S XORC/XORZ
*
* C/Z = C/Z XOR D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTB_XOR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (D >> shift) & 1;
updateC(C ^ bit);
updateZ(Z ^ bit);
return 1;
}
/**
* @brief Test bit S[4:0] of !D, XOR into C/Z.
*<pre>
* EEEE 0100111 CZI DDDDDDDDD SSSSSSSSS
*
* TESTBN D,{#}S XORC/XORZ
*
* C/Z = C/Z XOR !D[S[4:0]].
*</pre>
*/
int P2Cog::op_TESTBN_XOR()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const uchar bit = (~D >> shift) & 1;
updateC(C ^ bit);
updateZ(Z ^ bit);
return 1;
}
/**
* @brief Bit S[4:0] of D = 0, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100000 CZI DDDDDDDDD SSSSSSSSS
*
* BITL D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITL()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = 1, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100001 CZI DDDDDDDDD SSSSSSSSS
*
* BITH D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITH()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = D | bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = C, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100010 CZI DDDDDDDDD SSSSSSSSS
*
* BITC D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITC()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = C ? D | bit : D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = !C, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100011 CZI DDDDDDDDD SSSSSSSSS
*
* BITNC D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITNC()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = !C ? D | bit : D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = Z, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100100 CZI DDDDDDDDD SSSSSSSSS
*
* BITZ D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITZ()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = Z ? D | bit : D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = !Z, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100101 CZI DDDDDDDDD SSSSSSSSS
*
* BITNZ D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITNZ()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = !Z ? D | bit : D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = RND, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100110 CZI DDDDDDDDD SSSSSSSSS
*
* BITRND D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITRND()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = (HUB->random(shift) & 1) ? D | bit : D & ~bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief Bit S[4:0] of D = !bit, C,Z = D[S[4:0]].
*<pre>
* EEEE 0100111 CZI DDDDDDDDD SSSSSSSSS
*
* BITNOT D,{#}S {WCZ}
*</pre>
*/
int P2Cog::op_BITNOT()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG bit = LSB << shift;
const p2_LONG result = D ^ bit;
updateC((result >> shift) & 1);
updateZ((result >> shift) & 1);
return 1;
}
/**
* @brief AND S into D.
*<pre>
* EEEE 0101000 CZI DDDDDDDDD SSSSSSSSS
*
* AND D,{#}S {WC/WZ/WCZ}
*
* D = D & S.
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_AND()
{
augmentS(IR.op7.im);
const p2_LONG result = D & S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief AND !S into D.
*<pre>
* EEEE 0101001 CZI DDDDDDDDD SSSSSSSSS
*
* ANDN D,{#}S {WC/WZ/WCZ}
*
* D = D & !S.
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ANDN()
{
augmentS(IR.op7.im);
const p2_LONG result = D & ~S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief OR S into D.
*<pre>
* EEEE 0101010 CZI DDDDDDDDD SSSSSSSSS
*
* OR D,{#}S {WC/WZ/WCZ}
*
* D = D | S.
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_OR()
{
augmentS(IR.op7.im);
const p2_LONG result = D | S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief XOR S into D.
*<pre>
* EEEE 0101011 CZI DDDDDDDDD SSSSSSSSS
*
* XOR D,{#}S {WC/WZ/WCZ}
*
* D = D ^ S.
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_XOR()
{
augmentS(IR.op7.im);
const p2_LONG result = D ^ S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Mux C into each D bit that is '1' in S.
*<pre>
* EEEE 0101100 CZI DDDDDDDDD SSSSSSSSS
*
* MUXC D,{#}S {WC/WZ/WCZ}
*
* D = (!S & D ) | (S & {32{ C}}).
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_MUXC()
{
augmentS(IR.op7.im);
const p2_LONG result = (D & ~S) | (C ? S : 0);
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Mux !C into each D bit that is '1' in S.
*<pre>
* EEEE 0101101 CZI DDDDDDDDD SSSSSSSSS
*
* MUXNC D,{#}S {WC/WZ/WCZ}
*
* D = (!S & D ) | (S & {32{!C}}).
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_MUXNC()
{
augmentS(IR.op7.im);
const p2_LONG result = (D & ~S) | (!C ? S : 0);
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Mux Z into each D bit that is '1' in S.
*<pre>
* EEEE 0101110 CZI DDDDDDDDD SSSSSSSSS
*
* MUXZ D,{#}S {WC/WZ/WCZ}
*
* D = (!S & D ) | (S & {32{ Z}}).
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_MUXZ()
{
augmentS(IR.op7.im);
const p2_LONG result = (D & ~S) | (Z ? S : 0);
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Mux !Z into each D bit that is '1' in S.
*<pre>
* EEEE 0101111 CZI DDDDDDDDD SSSSSSSSS
*
* MUXNZ D,{#}S {WC/WZ/WCZ}
*
* D = (!S & D ) | (S & {32{!Z}}).
* C = parity of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_MUXNZ()
{
augmentS(IR.op7.im);
const p2_LONG result = (D & ~S) | (!Z ? S : 0);
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Move S into D.
*<pre>
* EEEE 0110000 CZI DDDDDDDDD SSSSSSSSS
*
* MOV D,{#}S {WC/WZ/WCZ}
*
* D = S.
* C = S[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_MOV()
{
augmentS(IR.op7.im);
const p2_LONG result = S;
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Get !S into D.
*<pre>
* EEEE 0110001 CZI DDDDDDDDD SSSSSSSSS
*
* NOT D,{#}S {WC/WZ/WCZ}
*
* D = !S.
* C = !S[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NOT()
{
augmentS(IR.op7.im);
const p2_LONG result = ~S;
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Get absolute value of S into D.
*<pre>
* EEEE 0110010 CZI DDDDDDDDD SSSSSSSSS
*
* ABS D,{#}S {WC/WZ/WCZ}
*
* D = ABS(S).
* C = S[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ABS()
{
augmentS(IR.op7.im);
const qint32 result = qAbs(S32(S));
updateC(S >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Negate S into D.
*<pre>
* EEEE 0110011 CZI DDDDDDDDD SSSSSSSSS
*
* NEG D,{#}S {WC/WZ/WCZ}
*
* D = -S.
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NEG()
{
augmentS(IR.op7.im);
const qint32 result = 0 - S32(S);
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Negate S by C into D.
*<pre>
* EEEE 0110100 CZI DDDDDDDDD SSSSSSSSS
*
* NEGC D,{#}S {WC/WZ/WCZ}
*
* If C = 1 then D = -S, else D = S.
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NEGC()
{
augmentS(IR.op7.im);
const qint32 result = C ? 0 - S32(S) : S32(32);
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Negate S by !C into D.
*<pre>
* EEEE 0110101 CZI DDDDDDDDD SSSSSSSSS
*
* NEGNC D,{#}S {WC/WZ/WCZ}
*
* If C = 0 then D = -S, else D = S.
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NEGNC()
{
augmentS(IR.op7.im);
const qint32 result = !C ? 0 - S32(S) : S32(32);
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Negate S by Z into D.
*<pre>
* EEEE 0110110 CZI DDDDDDDDD SSSSSSSSS
*
* NEGZ D,{#}S {WC/WZ/WCZ}
*
* If Z = 1 then D = -S, else D = S.
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NEGZ()
{
augmentS(IR.op7.im);
const qint32 result = Z ? 0 - S32(S) : S32(32);
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Negate S by !Z into D.
*<pre>
* EEEE 0110111 CZI DDDDDDDDD SSSSSSSSS
*
* NEGNZ D,{#}S {WC/WZ/WCZ}
*
* If Z = 0 then D = -S, else D = S.
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_NEGNZ()
{
augmentS(IR.op7.im);
const qint32 result = !Z ? 0 - S32(S) : S32(32);
updateC(result >> 31);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Increment with modulus.
*<pre>
* EEEE 0111000 CZI DDDDDDDDD SSSSSSSSS
*
* INCMOD D,{#}S {WC/WZ/WCZ}
*
* If D = S then D = 0 and C = 1, else D = D + 1 and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_INCMOD()
{
augmentS(IR.op7.im);
const p2_LONG result = (D == S) ? 0 : D + 1;
updateC(result == 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Decrement with modulus.
*<pre>
* EEEE 0111001 CZI DDDDDDDDD SSSSSSSSS
*
* DECMOD D,{#}S {WC/WZ/WCZ}
*
* If D = 0 then D = S and C = 1, else D = D - 1 and C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_DECMOD()
{
augmentS(IR.op7.im);
const p2_LONG result = (D == 0) ? S : D - 1;
updateC(result == S);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Zero-extend D above bit S[4:0].
*<pre>
* EEEE 0111010 CZI DDDDDDDDD SSSSSSSSS
*
* ZEROX D,{#}S {WC/WZ/WCZ}
*
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ZEROX()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG msb = (D >> (shift - 1)) & 1;
const p2_LONG mask = 0xffffffffu << shift;
const p2_LONG result = D & ~mask;
updateC(msb);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Sign-extend D from bit S[4:0].
*<pre>
* EEEE 0111011 CZI DDDDDDDDD SSSSSSSSS
*
* SIGNX D,{#}S {WC/WZ/WCZ}
*
* C = MSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SIGNX()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG msb = (D >> (shift - 1)) & 1;
const p2_LONG mask = FULL << shift;
const p2_LONG result = msb ? D | mask : D & ~mask;
updateC(msb);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Get bit position of top-most '1' in S into D.
*<pre>
* EEEE 0111100 CZI DDDDDDDDD SSSSSSSSS
*
* ENCOD D,{#}S {WC/WZ/WCZ}
*
* D = position of top '1' in S (0 … 31).
* C = (S != 0).
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ENCOD()
{
augmentS(IR.op7.im);
const p2_LONG result = static_cast<p2_LONG>(P2Util::encode(S));
updateC(S != 0);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Get number of '1's in S into D.
*<pre>
* EEEE 0111101 CZI DDDDDDDDD SSSSSSSSS
*
* ONES D,{#}S {WC/WZ/WCZ}
*
* D = number of '1's in S (0 … 32).
* C = LSB of result.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_ONES()
{
augmentS(IR.op7.im);
const p2_LONG result = P2Util::ones(S);
updateC(result & 1);
updateZ(0 == result);
return 1;
}
/**
* @brief Test D with S.
*<pre>
* EEEE 0111110 CZI DDDDDDDDD SSSSSSSSS
*
* TEST D,{#}S {WC/WZ/WCZ}
*
* C = parity of (D & S).
* Z = ((D & S) == 0).
*</pre>
*/
int P2Cog::op_TEST()
{
augmentS(IR.op7.im);
const p2_LONG result = D & S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Test D with !S.
*<pre>
* EEEE 0111111 CZI DDDDDDDDD SSSSSSSSS
*
* TESTN D,{#}S {WC/WZ/WCZ}
*
* C = parity of (D & !S).
* Z = ((D & !S) == 0).
*</pre>
*/
int P2Cog::op_TESTN()
{
augmentS(IR.op7.im);
const p2_LONG result = D & ~S;
updateC(P2Util::parity(result));
updateZ(0 == result);
return 1;
}
/**
* @brief Set S[3:0] into nibble N in D, keeping rest of D same.
*<pre>
* EEEE 100000N NNI DDDDDDDDD SSSSSSSSS
*
* SETNIB D,{#}S,#N
*</pre>
*/
int P2Cog::op_SETNIB()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 7) * 4;
const p2_LONG mask = LNIBBLE << shift;
const p2_LONG result = (D & ~mask) | ((S << shift) & mask);
updateD(result);
return 1;
}
/**
* @brief Set S[3:0] into nibble established by prior ALTSN instruction.
*<pre>
* EEEE 1000000 00I 000000000 SSSSSSSSS
*
* SETNIB {#}S
*</pre>
*/
int P2Cog::op_SETNIB_ALTSN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Get nibble N of S into D.
*<pre>
* EEEE 100001N NNI DDDDDDDDD SSSSSSSSS
*
* GETNIB D,{#}S,#N
*
* D = {28'b0, S.NIBBLE[N]).
*</pre>
*/
int P2Cog::op_GETNIB()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 7) * 4;
const p2_LONG result = (S >> shift) & LNIBBLE;
updateD(result);
return 1;
}
/**
* @brief Get nibble established by prior ALTGN instruction into D.
*<pre>
* EEEE 1000010 000 DDDDDDDDD 000000000
*
* GETNIB D
*</pre>
*/
int P2Cog::op_GETNIB_ALTGN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Rotate-left nibble N of S into D.
*<pre>
* EEEE 100010N NNI DDDDDDDDD SSSSSSSSS
*
* ROLNIB D,{#}S,#N
*
* D = {D[27:0], S.NIBBLE[N]).
*</pre>
*/
int P2Cog::op_ROLNIB()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 7) * 4;
const p2_LONG result = (D << 4) | ((S >> shift) & LNIBBLE);
updateD(result);
return 1;
}
/**
* @brief Rotate-left nibble established by prior ALTGN instruction into D.
*<pre>
* EEEE 1000100 000 DDDDDDDDD 000000000
*
* ROLNIB D
*</pre>
*/
int P2Cog::op_ROLNIB_ALTGN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set S[7:0] into byte N in D, keeping rest of D same.
*<pre>
* EEEE 1000110 NNI DDDDDDDDD SSSSSSSSS
*
* SETBYTE D,{#}S,#N
*</pre>
*/
int P2Cog::op_SETBYTE()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 3) * 8;
const p2_LONG mask = LBYTE << shift;
const p2_LONG result = (D & ~mask) | ((S << shift) & mask);
updateD(result);
return 1;
}
/**
* @brief Set S[7:0] into byte established by prior ALTSB instruction.
*<pre>
* EEEE 1000110 00I 000000000 SSSSSSSSS
*
* SETBYTE {#}S
*</pre>
*/
int P2Cog::op_SETBYTE_ALTSB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Get byte N of S into D.
*<pre>
* EEEE 1000111 NNI DDDDDDDDD SSSSSSSSS
*
* GETBYTE D,{#}S,#N
*
* D = {24'b0, S.BYTE[N]).
*</pre>
*/
int P2Cog::op_GETBYTE()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 3) * 8;
const p2_LONG result = (S >> shift) & LBYTE;
updateD(result);
return 1;
}
/**
* @brief Get byte established by prior ALTGB instruction into D.
*<pre>
* EEEE 1000111 000 DDDDDDDDD 000000000
*
* GETBYTE D
*</pre>
*/
int P2Cog::op_GETBYTE_ALTGB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Rotate-left byte N of S into D.
*<pre>
* EEEE 1001000 NNI DDDDDDDDD SSSSSSSSS
*
* ROLBYTE D,{#}S,#N
*
* D = {D[23:0], S.BYTE[N]).
*</pre>
*/
int P2Cog::op_ROLBYTE()
{
augmentS(IR.op7.im);
const uchar shift = static_cast<uchar>((IR.opcode >> 19) & 3) * 8;
const p2_LONG result = (D << 8) | ((S >> shift) & LBYTE);
updateD(result);
return 1;
}
/**
* @brief Rotate-left byte established by prior ALTGB instruction into D.
*<pre>
* EEEE 1001000 000 DDDDDDDDD 000000000
*
* ROLBYTE D
*</pre>
*/
int P2Cog::op_ROLBYTE_ALTGB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set S[15:0] into word N in D, keeping rest of D same.
*<pre>
* EEEE 1001001 0NI DDDDDDDDD SSSSSSSSS
*
* SETWORD D,{#}S,#N
*</pre>
*/
int P2Cog::op_SETWORD()
{
augmentS(IR.op7.im);
const uchar shift = IR.op7.wz ? 16 : 0;
const p2_LONG mask = LWORD << shift;
const p2_LONG result = (D & ~mask) | ((S >> shift) & mask);
updateD(result);
return 1;
}
/**
* @brief Set S[15:0] into word established by prior ALTSW instruction.
*<pre>
* EEEE 1001001 00I 000000000 SSSSSSSSS
*
* SETWORD {#}S
*</pre>
*/
int P2Cog::op_SETWORD_ALTSW()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Get word N of S into D.
*<pre>
* EEEE 1001001 1NI DDDDDDDDD SSSSSSSSS
*
* GETWORD D,{#}S,#N
*
* D = {16'b0, S.WORD[N]).
*</pre>
*/
int P2Cog::op_GETWORD()
{
augmentS(IR.op7.im);
const uchar shift = IR.op7.wz * 16;
const p2_LONG result = (S >> shift) & LWORD;
updateD(result);
return 1;
}
/**
* @brief Get word established by prior ALTGW instruction into D.
*<pre>
* EEEE 1001001 100 DDDDDDDDD 000000000
*
* GETWORD D
*</pre>
*/
int P2Cog::op_GETWORD_ALTGW()
{
return 1;
}
/**
* @brief Rotate-left word N of S into D.
*<pre>
* EEEE 1001010 0NI DDDDDDDDD SSSSSSSSS
*
* ROLWORD D,{#}S,#N
*
* D = {D[15:0], S.WORD[N]).
*</pre>
*/
int P2Cog::op_ROLWORD()
{
augmentS(IR.op7.im);
const uchar shift = IR.op7.wz * 16;
const p2_LONG result = (D << 16) & ((S >> shift) & LWORD);
updateD(result);
return 1;
}
/**
* @brief Rotate-left word established by prior ALTGW instruction into D.
*<pre>
* EEEE 1001010 000 DDDDDDDDD 000000000
*
* ROLWORD D
*</pre>
*/
int P2Cog::op_ROLWORD_ALTGW()
{
return 1;
}
/**
* @brief Alter subsequent SETNIB instruction.
*<pre>
* EEEE 1001010 10I DDDDDDDDD SSSSSSSSS
*
* ALTSN D,{#}S
*
* Next D field = (D[11:3] + S) & $1FF, N field = D[2:0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTSN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent SETNIB instruction.
*<pre>
* EEEE 1001010 101 DDDDDDDDD 000000000
*
* ALTSN D
*
* Next D field = D[11:3], N field = D[2:0].
*</pre>
*/
int P2Cog::op_ALTSN_D()
{
return 1;
}
/**
* @brief Alter subsequent GETNIB/ROLNIB instruction.
*<pre>
* EEEE 1001010 11I DDDDDDDDD SSSSSSSSS
*
* ALTGN D,{#}S
*
* Next S field = (D[11:3] + S) & $1FF, N field = D[2:0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTGN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent GETNIB/ROLNIB instruction.
*<pre>
* EEEE 1001010 111 DDDDDDDDD 000000000
*
* ALTGN D
*
* Next S field = D[11:3], N field = D[2:0].
*</pre>
*/
int P2Cog::op_ALTGN_D()
{
return 1;
}
/**
* @brief Alter subsequent SETBYTE instruction.
*<pre>
* EEEE 1001011 00I DDDDDDDDD SSSSSSSSS
*
* ALTSB D,{#}S
*
* Next D field = (D[10:2] + S) & $1FF, N field = D[1:0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTSB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent SETBYTE instruction.
*<pre>
* EEEE 1001011 001 DDDDDDDDD 000000000
*
* ALTSB D
*
* Next D field = D[10:2], N field = D[1:0].
*</pre>
*/
int P2Cog::op_ALTSB_D()
{
return 1;
}
/**
* @brief Alter subsequent GETBYTE/ROLBYTE instruction.
*<pre>
* EEEE 1001011 01I DDDDDDDDD SSSSSSSSS
*
* ALTGB D,{#}S
*
* Next S field = (D[10:2] + S) & $1FF, N field = D[1:0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTGB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent GETBYTE/ROLBYTE instruction.
*<pre>
* EEEE 1001011 011 DDDDDDDDD 000000000
*
* ALTGB D
*
* Next S field = D[10:2], N field = D[1:0].
*</pre>
*/
int P2Cog::op_ALTGB_D()
{
return 1;
}
/**
* @brief Alter subsequent SETWORD instruction.
*<pre>
* EEEE 1001011 10I DDDDDDDDD SSSSSSSSS
*
* ALTSW D,{#}S
*
* Next D field = (D[9:1] + S) & $1FF, N field = D[0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTSW()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent SETWORD instruction.
*<pre>
* EEEE 1001011 101 DDDDDDDDD 000000000
*
* ALTSW D
*
* Next D field = D[9:1], N field = D[0].
*</pre>
*/
int P2Cog::op_ALTSW_D()
{
return 1;
}
/**
* @brief Alter subsequent GETWORD/ROLWORD instruction.
*<pre>
* EEEE 1001011 11I DDDDDDDDD SSSSSSSSS
*
* ALTGW D,{#}S
*
* Next S field = ((D[9:1] + S) & $1FF), N field = D[0].
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTGW()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter subsequent GETWORD/ROLWORD instruction.
*<pre>
* EEEE 1001011 111 DDDDDDDDD 000000000
*
* ALTGW D
*
* Next S field = D[9:1], N field = D[0].
*</pre>
*/
int P2Cog::op_ALTGW_D()
{
return 1;
}
/**
* @brief Alter result register address (normally D field) of next instruction to (D + S) & $1FF.
*<pre>
* EEEE 1001100 00I DDDDDDDDD SSSSSSSSS
*
* ALTR D,{#}S
*
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTR()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter result register address (normally D field) of next instruction to D[8:0].
*<pre>
* EEEE 1001100 001 DDDDDDDDD 000000000
*
* ALTR D
*</pre>
*/
int P2Cog::op_ALTR_D()
{
return 1;
}
/**
* @brief Alter D field of next instruction to (D + S) & $1FF.
*<pre>
* EEEE 1001100 01I DDDDDDDDD SSSSSSSSS
*
* ALTD D,{#}S
*
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTD()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter D field of next instruction to D[8:0].
*<pre>
* EEEE 1001100 011 DDDDDDDDD 000000000
*
* ALTD D
*</pre>
*/
int P2Cog::op_ALTD_D()
{
return 1;
}
/**
* @brief Alter S field of next instruction to (D + S) & $1FF.
*<pre>
* EEEE 1001100 10I DDDDDDDDD SSSSSSSSS
*
* ALTS D,{#}S
*
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTS()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter S field of next instruction to D[8:0].
*<pre>
* EEEE 1001100 101 DDDDDDDDD 000000000
*
* ALTS D
*</pre>
*/
int P2Cog::op_ALTS_D()
{
return 1;
}
/**
* @brief Alter D field of next instruction to (D[13:5] + S) & $1FF.
*<pre>
* EEEE 1001100 11I DDDDDDDDD SSSSSSSSS
*
* ALTB D,{#}S
*
* D += sign-extended S[17:9].
*</pre>
*/
int P2Cog::op_ALTB()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alter D field of next instruction to D[13:5].
*<pre>
* EEEE 1001100 111 DDDDDDDDD 000000000
*
* ALTB D
*</pre>
*/
int P2Cog::op_ALTB_D()
{
return 1;
}
/**
* @brief Substitute next instruction's I/R/D/S fields with fields from D, per S.
*<pre>
* EEEE 1001101 00I DDDDDDDDD SSSSSSSSS
*
* ALTI D,{#}S
*
* Modify D per S.
*</pre>
*/
int P2Cog::op_ALTI()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Execute D in place of next instruction.
*<pre>
* EEEE 1001101 001 DDDDDDDDD 101100100
*
* ALTI D
*
* D stays same.
*</pre>
*/
int P2Cog::op_ALTI_D()
{
return 1;
}
/**
* @brief Set R field of D to S[8:0].
*<pre>
* EEEE 1001101 01I DDDDDDDDD SSSSSSSSS
*
* SETR D,{#}S
*
* D = {D[31:28], S[8:0], D[18:0]}.
*</pre>
*/
int P2Cog::op_SETR()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set D field of D to S[8:0].
*<pre>
* EEEE 1001101 10I DDDDDDDDD SSSSSSSSS
*
* SETD D,{#}S
*
* D = {D[31:18], S[8:0], D[8:0]}.
*</pre>
*/
int P2Cog::op_SETD()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set S field of D to S[8:0].
*<pre>
* EEEE 1001101 11I DDDDDDDDD SSSSSSSSS
*
* SETS D,{#}S
*
* D = {D[31:9], S[8:0]}.
*</pre>
*/
int P2Cog::op_SETS()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Decode S[4:0] into D.
*<pre>
* EEEE 1001110 00I DDDDDDDDD SSSSSSSSS
*
* DECOD D,{#}S
*
* D = 1 << S[4:0].
*</pre>
*/
int P2Cog::op_DECOD()
{
augmentS(IR.op7.im);
const uchar shift = S & 31;
const p2_LONG result = LSB << shift;
updateD(result);
return 1;
}
/**
* @brief Decode D[4:0] into D.
*<pre>
* EEEE 1001110 000 DDDDDDDDD DDDDDDDDD
*
* DECOD D
*
* D = 1 << D[4:0].
*</pre>
*/
int P2Cog::op_DECOD_D()
{
return 1;
}
/**
* @brief Get LSB-justified bit mask of size (S[4:0] + 1) into D.
*<pre>
* EEEE 1001110 01I DDDDDDDDD SSSSSSSSS
*
* BMASK D,{#}S
*
* D = ($0000_0002 << S[4:0]) - 1.
*</pre>
*/
int P2Cog::op_BMASK()
{
const uchar shift = S & 31;
const p2_LONG result = U32L((Q_UINT64_C(2) << shift) - 1);
updateD(result);
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Get LSB-justified bit mask of size (D[4:0] + 1) into D.
*<pre>
* EEEE 1001110 010 DDDDDDDDD DDDDDDDDD
*
* BMASK D
*
* D = ($0000_0002 << D[4:0]) - 1.
*</pre>
*/
int P2Cog::op_BMASK_D()
{
const uchar shift = D & 31;
const p2_LONG result = U32L((Q_UINT64_C(2) << shift) - 1);
updateD(result);
return 1;
}
/**
* @brief Iterate CRC value in D using C and polynomial in S.
*<pre>
* EEEE 1001110 10I DDDDDDDDD SSSSSSSSS
*
* CRCBIT D,{#}S
*
* If (C XOR D[0]) then D = (D >> 1) XOR S, else D = (D >> 1).
*</pre>
*/
int P2Cog::op_CRCBIT()
{
augmentS(IR.op7.im);
const p2_LONG result = (D >> 1) ^ (S & SXn<p2_LONG,1>(C ^ D));
updateC(D & 1);
updateD(result);
return 1;
}
/**
* @brief Iterate CRC value in D using Q[31:28] and polynomial in S.
*<pre>
* EEEE 1001110 11I DDDDDDDDD SSSSSSSSS
*
* CRCNIB D,{#}S
*
* Like CRCBIT, but 4x.
* Q = Q << 4.
* Use SETQ+CRCNIB+CRCNIB+CRCNIB.
*</pre>
*/
int P2Cog::op_CRCNIB()
{
augmentS(IR.op7.im);
const p2_LONG q0 = Q >> 28;
const p2_LONG c0 = C;
const p2_LONG q1 = (q0 >> 1) ^ (S & SXn<p2_LONG,1>(c0 ^ q0));
const p2_LONG c1 = q0 & 1;
const p2_LONG q2 = (q1 >> 1) ^ (S & SXn<p2_LONG,1>(c1 ^ q1));
const p2_LONG c2 = q1 & 1;
const p2_LONG q3 = (q2 >> 1) ^ (S & SXn<p2_LONG,1>(c2 ^ q2));
const p2_LONG c3 = q1 & 1;
const p2_LONG q4 = (q3 >> 1) ^ (S & SXn<p2_LONG,1>(c3 ^ q3));
updateQ(Q << 4);
updateD(D ^ q4);
updateC(c3);
return 1;
}
/**
* @brief For each non-zero bit pair in S, copy that bit pair into the corresponding D bits, else leave that D bit pair the same.
*<pre>
* EEEE 1001111 00I DDDDDDDDD SSSSSSSSS
*
* MUXNITS D,{#}S
*</pre>
*/
int P2Cog::op_MUXNITS()
{
augmentS(IR.op7.im);
const p2_LONG mask = S | ((S & 0xaaaaaaaa) >> 1) | ((S & 0x55555555) << 1);
const p2_LONG result = (D & ~mask) | (S & mask);
updateD(result);
return 1;
}
/**
* @brief For each non-zero nibble in S, copy that nibble into the corresponding D nibble, else leave that D nibble the same.
*<pre>
* EEEE 1001111 01I DDDDDDDDD SSSSSSSSS
*
* MUXNIBS D,{#}S
*</pre>
*/
int P2Cog::op_MUXNIBS()
{
augmentS(IR.op7.im);
const p2_LONG mask0 = S | ((S & 0xaaaaaaaa) >> 1) | ((S & 0x55555555) << 1);
const p2_LONG mask1 = ((mask0 & 0xcccccccc) >> 2) | ((mask0 & 0x33333333) << 2);
const p2_LONG result = (D & ~mask1) | (S & mask1);
updateD(result);
return 1;
}
/**
* @brief Used after SETQ.
*<pre>
* EEEE 1001111 10I DDDDDDDDD SSSSSSSSS
*
* MUXQ D,{#}S
*
* For each '1' bit in Q, copy the corresponding bit in S into D.
* D = (D & !Q) | (S & Q).
*</pre>
*/
int P2Cog::op_MUXQ()
{
augmentS(IR.op7.im);
const p2_LONG result = (D & ~Q) | (S & Q);
updateD(result);
return 1;
}
/**
* @brief Move bytes within D, per S.
*<pre>
* EEEE 1001111 11I DDDDDDDDD SSSSSSSSS
*
* MOVBYTS D,{#}S
*
* D = {D.BYTE[S[7:6]], D.BYTE[S[5:4]], D.BYTE[S[3:2]], D.BYTE[S[1:0]]}.
*</pre>
*/
int P2Cog::op_MOVBYTS()
{
augmentS(IR.op7.im);
union {
p2_LONG l;
p2_BYTE b[4];
} src, dst;
src.l = D;
dst.b[0] = src.b[(S >> 0) & 3];
dst.b[1] = src.b[(S >> 2) & 3];
dst.b[2] = src.b[(S >> 4) & 3];
dst.b[3] = src.b[(S >> 6) & 3];
updateD(dst.l);
return 1;
}
/**
* @brief D = unsigned (D[15:0] * S[15:0]).
*<pre>
* EEEE 1010000 0ZI DDDDDDDDD SSSSSSSSS
*
* MUL D,{#}S {WZ}
*
* Z = (S == 0) | (D == 0).
*</pre>
*/
int P2Cog::op_MUL()
{
augmentS(IR.op7.im);
const p2_LONG result = U16(D) * U16(S);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief D = signed (D[15:0] * S[15:0]).
*<pre>
* EEEE 1010000 1ZI DDDDDDDDD SSSSSSSSS
*
* MULS D,{#}S {WZ}
*
* Z = (S == 0) | (D == 0).
*</pre>
*/
int P2Cog::op_MULS()
{
augmentS(IR.op7.im);
const p2_LONG result = static_cast<p2_LONG>(S16(D) * S16(S));
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Next instruction's S value = unsigned (D[15:0] * S[15:0]) >> 16.
*<pre>
* EEEE 1010001 0ZI DDDDDDDDD SSSSSSSSS
*
* SCA D,{#}S {WZ}
*
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SCA()
{
augmentS(IR.op7.im);
const p2_LONG result = (U16(D) * U16(S)) >> 16;
updateZ(0 == result);
S_next = result;
return 1;
}
/**
* @brief Next instruction's S value = signed (D[15:0] * S[15:0]) >> 14.
*<pre>
* EEEE 1010001 1ZI DDDDDDDDD SSSSSSSSS
*
* SCAS D,{#}S {WZ}
*
* In this scheme, $4000 = 1.0 and $C000 = -1.0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_SCAS()
{
augmentS(IR.op7.im);
const p2_LONG result = static_cast<p2_LONG>((S16(D) * S16(S)) >> 14);
updateZ(0 == result);
S_next = result;
return 1;
}
/**
* @brief Add bytes of S into bytes of D, with $FF saturation.
*<pre>
* EEEE 1010010 00I DDDDDDDDD SSSSSSSSS
*
* ADDPIX D,{#}S
*</pre>
*/
int P2Cog::op_ADDPIX()
{
augmentS(IR.op7.im);
union {
p2_LONG l;
p2_BYTE b[4];
} dst, src;
dst.l = D;
src.l = S;
dst.b[0] = qMin<p2_BYTE>(dst.b[0] + src.b[0], 0xff);
dst.b[1] = qMin<p2_BYTE>(dst.b[1] + src.b[1], 0xff);
dst.b[2] = qMin<p2_BYTE>(dst.b[2] + src.b[2], 0xff);
dst.b[3] = qMin<p2_BYTE>(dst.b[3] + src.b[3], 0xff);
updateD(dst.l);
return 1;
}
/**
* @brief Multiply bytes of S into bytes of D, where $FF = 1.
*<pre>
* EEEE 1010010 01I DDDDDDDDD SSSSSSSSS
*
* MULPIX D,{#}S
*</pre>
*/
int P2Cog::op_MULPIX()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Alpha-blend bytes of S into bytes of D, using SETPIV value.
*<pre>
* EEEE 1010010 10I DDDDDDDDD SSSSSSSSS
*
* BLNPIX D,{#}S
*</pre>
*/
int P2Cog::op_BLNPIX()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Mix bytes of S into bytes of D, using SETPIX and SETPIV values.
*<pre>
* EEEE 1010010 11I DDDDDDDDD SSSSSSSSS
*
* MIXPIX D,{#}S
*</pre>
*/
int P2Cog::op_MIXPIX()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set CT1 event to trigger on CT = D + S.
*<pre>
* EEEE 1010011 00I DDDDDDDDD SSSSSSSSS
*
* ADDCT1 D,{#}S
*
* Adds S into D.
*</pre>
*/
int P2Cog::op_ADDCT1()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set CT2 event to trigger on CT = D + S.
*<pre>
* EEEE 1010011 01I DDDDDDDDD SSSSSSSSS
*
* ADDCT2 D,{#}S
*
* Adds S into D.
*</pre>
*/
int P2Cog::op_ADDCT2()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Set CT3 event to trigger on CT = D + S.
*<pre>
* EEEE 1010011 10I DDDDDDDDD SSSSSSSSS
*
* ADDCT3 D,{#}S
*
* Adds S into D.
*</pre>
*/
int P2Cog::op_ADDCT3()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Write only non-$00 bytes in D[31:0] to hub address {#}S/PTRx.
*<pre>
* EEEE 1010011 11I DDDDDDDDD SSSSSSSSS
*
* WMLONG D,{#}S/P
*
* Prior SETQ/SETQ2 invokes cog/LUT block transfer.
*</pre>
*/
int P2Cog::op_WMLONG()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Read smart pin S[5:0] result "Z" into D, don't acknowledge smart pin ("Q" in RQPIN means "quiet").
*<pre>
* EEEE 1010100 C0I DDDDDDDDD SSSSSSSSS
*
* RQPIN D,{#}S {WC}
*
* C = modal result.
*</pre>
*/
int P2Cog::op_RQPIN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Read smart pin S[5:0] result "Z" into D, acknowledge smart pin.
*<pre>
* EEEE 1010100 C1I DDDDDDDDD SSSSSSSSS
*
* RDPIN D,{#}S {WC}
*
* C = modal result.
*</pre>
*/
int P2Cog::op_RDPIN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Read LUT data from address S[8:0] into D.
*<pre>
* EEEE 1010101 CZI DDDDDDDDD SSSSSSSSS
*
* RDLUT D,{#}S/P {WC/WZ/WCZ}
*
* C = MSB of data.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RDLUT()
{
augmentS(IR.op7.im);
p2_LONG result;
if (S == offs_PTRA) {
result = HUB->rd_LONG(COG.REG.PTRA);
} else if (S == offs_PTRB) {
result = HUB->rd_LONG(COG.REG.PTRB);
} else {
result = LUT.RAM[S & 0x1ff];
}
updateC((result >> 31) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Read zero-extended byte from hub address {#}S/PTRx into D.
*<pre>
* EEEE 1010110 CZI DDDDDDDDD SSSSSSSSS
*
* RDBYTE D,{#}S/P {WC/WZ/WCZ}
*
* C = MSB of byte.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RDBYTE()
{
augmentS(IR.op7.im);
p2_BYTE result;
if (S == offs_PTRA) {
result = HUB->rd_BYTE(COG.REG.PTRA);
} else if (S == offs_PTRB) {
result = HUB->rd_BYTE(COG.REG.PTRB);
} else {
result = HUB->rd_BYTE(S);
}
updateC((result >> 7) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Read zero-extended word from hub address {#}S/PTRx into D.
*<pre>
* EEEE 1010111 CZI DDDDDDDDD SSSSSSSSS
*
* RDWORD D,{#}S/P {WC/WZ/WCZ}
*
* C = MSB of word.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RDWORD()
{
augmentS(IR.op7.im);
p2_WORD result;
if (S == offs_PTRA) {
result = HUB->rd_WORD(COG.REG.PTRA);
} else if (S == offs_PTRB) {
result = HUB->rd_WORD(COG.REG.PTRB);
} else {
result = HUB->rd_WORD(S);
}
updateC((result >> 15) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Read long from hub address {#}S/PTRx into D.
*<pre>
* EEEE 1011000 CZI DDDDDDDDD SSSSSSSSS
*
* RDLONG D,{#}S/P {WC/WZ/WCZ}
*
* C = MSB of long.
* rior SETQ/SETQ2 invokes cog/LUT block transfer.
*</pre>
*/
int P2Cog::op_RDLONG()
{
augmentS(IR.op7.im);
p2_LONG result;
if (S == offs_PTRA) {
result = HUB->rd_LONG(COG.REG.PTRA);
} else if (S == offs_PTRB) {
result = HUB->rd_LONG(COG.REG.PTRB);
} else {
result = HUB->rd_LONG(S);
}
updateC((result >> 15) & 1);
updateZ(0 == result);
updateD(result);
return 1;
}
/**
* @brief Read long from hub address --PTRA into D.
*<pre>
* EEEE 1011000 CZ1 DDDDDDDDD 101011111
*
* POPA D {WC/WZ/WCZ}
*
* C = MSB of long.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_POPA()
{
return 1;
}
/**
* @brief Read long from hub address --PTRB into D.
*<pre>
* EEEE 1011000 CZ1 DDDDDDDDD 111011111
*
* POPB D {WC/WZ/WCZ}
*
* C = MSB of long.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_POPB()
{
return 1;
}
/**
* @brief Call to S** by writing {C, Z, 10'b0, PC[19:0]} to D.
*<pre>
* EEEE 1011001 CZI DDDDDDDDD SSSSSSSSS
*
* CALLD D,{#}S {WC/WZ/WCZ}
*
* C = S[31], Z = S[30].
*</pre>
*/
int P2Cog::op_CALLD()
{
augmentS(IR.op7.im);
if (IR.op7.wc && IR.op7.wz) {
if (IR.op7.dst == offs_IJMP3 && IR.op7.src == offs_IRET3)
return op_RESI3();
if (IR.op7.dst == offs_IJMP2 && IR.op7.src == offs_IRET2)
return op_RESI2();
if (IR.op7.dst == offs_IJMP1 && IR.op7.src == offs_IRET1)
return op_RESI1();
if (IR.op7.dst == offs_INA && IR.op7.src == offs_INB)
return op_RESI0();
if (IR.op7.dst == offs_INB && IR.op7.src == offs_IRET3)
return op_RETI3();
if (IR.op7.dst == offs_INB && IR.op7.src == offs_IRET2)
return op_RETI2();
if (IR.op7.dst == offs_INB && IR.op7.src == offs_IRET1)
return op_RETI1();
if (IR.op7.dst == offs_INB && IR.op7.src == offs_INB)
return op_RETI0();
}
const p2_LONG result = (U32(C) << 31) | (U32(Z) << 30) | PC;
updateC((S >> 31) & 1);
updateZ((S >> 30) & 1);
updateD(result);
updatePC(S & A20MASK);
return 1;
}
/**
* @brief Resume from INT3.
*<pre>
* EEEE 1011001 110 111110000 111110001
*
* RESI3
*
* (CALLD $1F0,$1F1 WC,WZ).
*</pre>
*/
int P2Cog::op_RESI3()
{
return 1;
}
/**
* @brief Resume from INT2.
*<pre>
* EEEE 1011001 110 111110010 111110011
*
* RESI2
*
* (CALLD $1F2,$1F3 WC,WZ).
*</pre>
*/
int P2Cog::op_RESI2()
{
return 1;
}
/**
* @brief Resume from INT1.
*<pre>
* EEEE 1011001 110 111110100 111110101
*
* RESI1
*
* (CALLD $1F4,$1F5 WC,WZ).
*</pre>
*/
int P2Cog::op_RESI1()
{
return 1;
}
/**
* @brief Resume from INT0.
*<pre>
* EEEE 1011001 110 111111110 111111111
*
* RESI0
*
* (CALLD $1FE,$1FF WC,WZ).
*</pre>
*/
int P2Cog::op_RESI0()
{
return 1;
}
/**
* @brief Return from INT3.
*<pre>
* EEEE 1011001 110 111111111 111110001
*
* RETI3
*
* (CALLD $1FF,$1F1 WC,WZ).
*</pre>
*/
int P2Cog::op_RETI3()
{
return 1;
}
/**
* @brief Return from INT2.
*<pre>
* EEEE 1011001 110 111111111 111110011
*
* RETI2
*
* (CALLD $1FF,$1F3 WC,WZ).
*</pre>
*/
int P2Cog::op_RETI2()
{
return 1;
}
/**
* @brief Return from INT1.
*<pre>
* EEEE 1011001 110 111111111 111110101
*
* RETI1
*
* (CALLD $1FF,$1F5 WC,WZ).
*</pre>
*/
int P2Cog::op_RETI1()
{
return 1;
}
/**
* @brief Return from INT0.
*<pre>
* EEEE 1011001 110 111111111 111111111
*
* RETI0
*
* (CALLD $1FF,$1FF WC,WZ).
*</pre>
*/
int P2Cog::op_RETI0()
{
return 1;
}
/**
* @brief Call to S** by pushing {C, Z, 10'b0, PC[19:0]} onto stack, copy D to PA.
*<pre>
* EEEE 1011010 0LI DDDDDDDDD SSSSSSSSS
*
* CALLPA {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_CALLPA()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG address = S;
const p2_LONG result = D;
pushK(stack);
updatePA(result);
updatePC(address);
return 1;
}
/**
* @brief Call to S** by pushing {C, Z, 10'b0, PC[19:0]} onto stack, copy D to PB.
*<pre>
* EEEE 1011010 1LI DDDDDDDDD SSSSSSSSS
*
* CALLPB {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_CALLPB()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG address = S;
const p2_LONG result = D;
pushK(stack);
updatePB(result);
updatePC(address);
return 1;
}
/**
* @brief Decrement D and jump to S** if result is zero.
*<pre>
* EEEE 1011011 00I DDDDDDDDD SSSSSSSSS
*
* DJZ D,{#}S
*
*</pre>
*/
int P2Cog::op_DJZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D - 1;
const p2_LONG address = S;
if (result == ZERO)
updatePC(address);
return 1;
}
/**
* @brief Decrement D and jump to S** if result is not zero.
*<pre>
* EEEE 1011011 01I DDDDDDDDD SSSSSSSSS
*
* DJNZ D,{#}S
*
*</pre>
*/
int P2Cog::op_DJNZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D - 1;
const p2_LONG address = S;
if (result != ZERO)
updatePC(address);
return 1;
}
/**
* @brief Decrement D and jump to S** if result is $FFFF_FFFF.
*<pre>
* EEEE 1011011 10I DDDDDDDDD SSSSSSSSS
*
* DJF D,{#}S
*
*</pre>
*/
int P2Cog::op_DJF()
{
augmentS(IR.op7.im);
const p2_LONG result = D - 1;
const p2_LONG address = S;
if (result == FULL)
updatePC(address);
return 1;
}
/**
* @brief Decrement D and jump to S** if result is not $FFFF_FFFF.
*<pre>
* EEEE 1011011 11I DDDDDDDDD SSSSSSSSS
*
* DJNF D,{#}S
*
*</pre>
*/
int P2Cog::op_DJNF()
{
augmentS(IR.op7.im);
const p2_LONG result = D - 1;
const p2_LONG address = S;
if (result != FULL)
updatePC(address);
return 1;
}
/**
* @brief Increment D and jump to S** if result is zero.
*<pre>
* EEEE 1011100 00I DDDDDDDDD SSSSSSSSS
*
* IJZ D,{#}S
*
*</pre>
*/
int P2Cog::op_IJZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D + 1;
const p2_LONG address = S;
if (result == ZERO)
updatePC(address);
return 1;
}
/**
* @brief Increment D and jump to S** if result is not zero.
*<pre>
* EEEE 1011100 01I DDDDDDDDD SSSSSSSSS
*
* IJNZ D,{#}S
*
*</pre>
*/
int P2Cog::op_IJNZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D + 1;
const p2_LONG address = S;
if (result != ZERO)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is zero.
*<pre>
* EEEE 1011100 10I DDDDDDDDD SSSSSSSSS
*
* TJZ D,{#}S
*
*</pre>
*/
int P2Cog::op_TJZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D;
const p2_LONG address = S;
if (result == ZERO)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is not zero.
*<pre>
* EEEE 1011100 11I DDDDDDDDD SSSSSSSSS
*
* TJNZ D,{#}S
*
*</pre>
*/
int P2Cog::op_TJNZ()
{
augmentS(IR.op7.im);
const p2_LONG result = D;
const p2_LONG address = S;
if (result != ZERO)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is full (D = $FFFF_FFFF).
*<pre>
* EEEE 1011101 00I DDDDDDDDD SSSSSSSSS
*
* TJF D,{#}S
*
*</pre>
*/
int P2Cog::op_TJF()
{
augmentS(IR.op7.im);
const p2_LONG result = D;
const p2_LONG address = S;
if (result == FULL)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is not full (D != $FFFF_FFFF).
*<pre>
* EEEE 1011101 01I DDDDDDDDD SSSSSSSSS
*
* TJNF D,{#}S
*
*</pre>
*/
int P2Cog::op_TJNF()
{
augmentS(IR.op7.im);
const p2_LONG result = D;
const p2_LONG address = S;
if (result != FULL)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is signed (D[31] = 1).
*<pre>
* EEEE 1011101 10I DDDDDDDDD SSSSSSSSS
*
* TJS D,{#}S
*
*</pre>
*/
int P2Cog::op_TJS()
{
augmentS(IR.op7.im);
const p2_LONG result = D & MSB;
const p2_LONG address = S;
if (result)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D is not signed (D[31] = 0).
*<pre>
* EEEE 1011101 11I DDDDDDDDD SSSSSSSSS
*
* TJNS D,{#}S
*
*</pre>
*/
int P2Cog::op_TJNS()
{
augmentS(IR.op7.im);
const p2_LONG result = D & MSB;
const p2_LONG address = S;
if (!result)
updatePC(address);
return 1;
}
/**
* @brief Test D and jump to S** if D overflowed (D[31] != C, C = 'correct sign' from last addition/subtraction).
*<pre>
* EEEE 1011110 00I DDDDDDDDD SSSSSSSSS
*
* TJV D,{#}S
*
*</pre>
*/
int P2Cog::op_TJV()
{
augmentS(IR.op7.im);
const p2_LONG result = (D >> 31) ^ C;
const p2_LONG address = S;
if (result)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if INT event flag is set.
*<pre>
* EEEE 1011110 01I 000000000 SSSSSSSSS
*
* JINT {#}S
*
*</pre>
*/
int P2Cog::op_JINT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_INT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT1 event flag is set.
*<pre>
* EEEE 1011110 01I 000000001 SSSSSSSSS
*
* JCT1 {#}S
*
*</pre>
*/
int P2Cog::op_JCT1()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_CT1)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT2 event flag is set.
*<pre>
* EEEE 1011110 01I 000000010 SSSSSSSSS
*
* JCT2 {#}S
*
*</pre>
*/
int P2Cog::op_JCT2()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_CT2)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT3 event flag is set.
*<pre>
* EEEE 1011110 01I 000000011 SSSSSSSSS
*
* JCT3 {#}S
*
*</pre>
*/
int P2Cog::op_JCT3()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_CT3)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE1 event flag is set.
*<pre>
* EEEE 1011110 01I 000000100 SSSSSSSSS
*
* JSE1 {#}S
*
*</pre>
*/
int P2Cog::op_JSE1()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_SE1)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE2 event flag is set.
*<pre>
* EEEE 1011110 01I 000000101 SSSSSSSSS
*
* JSE2 {#}S
*
*</pre>
*/
int P2Cog::op_JSE2()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_SE2)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE3 event flag is set.
*<pre>
* EEEE 1011110 01I 000000110 SSSSSSSSS
*
* JSE3 {#}S
*
*</pre>
*/
int P2Cog::op_JSE3()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_SE3)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE4 event flag is set.
*<pre>
* EEEE 1011110 01I 000000111 SSSSSSSSS
*
* JSE4 {#}S
*
*</pre>
*/
int P2Cog::op_JSE4()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_SE4)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if PAT event flag is set.
*<pre>
* EEEE 1011110 01I 000001000 SSSSSSSSS
*
* JPAT {#}S
*
*</pre>
*/
int P2Cog::op_JPAT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_PAT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if FBW event flag is set.
*<pre>
* EEEE 1011110 01I 000001001 SSSSSSSSS
*
* JFBW {#}S
*
*</pre>
*/
int P2Cog::op_JFBW()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_FBW)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XMT event flag is set.
*<pre>
* EEEE 1011110 01I 000001010 SSSSSSSSS
*
* JXMT {#}S
*
*</pre>
*/
int P2Cog::op_JXMT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_XMT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XFI event flag is set.
*<pre>
* EEEE 1011110 01I 000001011 SSSSSSSSS
*
* JXFI {#}S
*
*</pre>
*/
int P2Cog::op_JXFI()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_XFI)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XRO event flag is set.
*<pre>
* EEEE 1011110 01I 000001100 SSSSSSSSS
*
* JXRO {#}S
*
*</pre>
*/
int P2Cog::op_JXRO()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_XRO)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XRL event flag is set.
*<pre>
* EEEE 1011110 01I 000001101 SSSSSSSSS
*
* JXRL {#}S
*
*</pre>
*/
int P2Cog::op_JXRL()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_XRL)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if ATN event flag is set.
*<pre>
* EEEE 1011110 01I 000001110 SSSSSSSSS
*
* JATN {#}S
*
*</pre>
*/
int P2Cog::op_JATN()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_ATN)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if QMT event flag is set.
*<pre>
* EEEE 1011110 01I 000001111 SSSSSSSSS
*
* JQMT {#}S
*
*</pre>
*/
int P2Cog::op_JQMT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (FLAGS.f_QMT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if INT event flag is clear.
*<pre>
* EEEE 1011110 01I 000010000 SSSSSSSSS
*
* JNINT {#}S
*
*</pre>
*/
int P2Cog::op_JNINT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_INT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT1 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010001 SSSSSSSSS
*
* JNCT1 {#}S
*
*</pre>
*/
int P2Cog::op_JNCT1()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_CT1)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT2 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010010 SSSSSSSSS
*
* JNCT2 {#}S
*
*</pre>
*/
int P2Cog::op_JNCT2()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_CT2)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if CT3 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010011 SSSSSSSSS
*
* JNCT3 {#}S
*
*</pre>
*/
int P2Cog::op_JNCT3()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_CT3)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE1 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010100 SSSSSSSSS
*
* JNSE1 {#}S
*
*</pre>
*/
int P2Cog::op_JNSE1()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_SE1)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE2 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010101 SSSSSSSSS
*
* JNSE2 {#}S
*
*</pre>
*/
int P2Cog::op_JNSE2()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_SE2)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE3 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010110 SSSSSSSSS
*
* JNSE3 {#}S
*
*</pre>
*/
int P2Cog::op_JNSE3()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_SE3)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if SE4 event flag is clear.
*<pre>
* EEEE 1011110 01I 000010111 SSSSSSSSS
*
* JNSE4 {#}S
*
*</pre>
*/
int P2Cog::op_JNSE4()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_SE4)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if PAT event flag is clear.
*<pre>
* EEEE 1011110 01I 000011000 SSSSSSSSS
*
* JNPAT {#}S
*
*</pre>
*/
int P2Cog::op_JNPAT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_PAT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if FBW event flag is clear.
*<pre>
* EEEE 1011110 01I 000011001 SSSSSSSSS
*
* JNFBW {#}S
*
*</pre>
*/
int P2Cog::op_JNFBW()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_FBW)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XMT event flag is clear.
*<pre>
* EEEE 1011110 01I 000011010 SSSSSSSSS
*
* JNXMT {#}S
*
*</pre>
*/
int P2Cog::op_JNXMT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_XMT)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XFI event flag is clear.
*<pre>
* EEEE 1011110 01I 000011011 SSSSSSSSS
*
* JNXFI {#}S
*
*</pre>
*/
int P2Cog::op_JNXFI()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_XFI)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XRO event flag is clear.
*<pre>
* EEEE 1011110 01I 000011100 SSSSSSSSS
*
* JNXRO {#}S
*
*</pre>
*/
int P2Cog::op_JNXRO()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_XRO)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if XRL event flag is clear.
*<pre>
* EEEE 1011110 01I 000011101 SSSSSSSSS
*
* JNXRL {#}S
*
*</pre>
*/
int P2Cog::op_JNXRL()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_XRL)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if ATN event flag is clear.
*<pre>
* EEEE 1011110 01I 000011110 SSSSSSSSS
*
* JNATN {#}S
*
*</pre>
*/
int P2Cog::op_JNATN()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_ATN)
updatePC(address);
return 1;
}
/**
* @brief Jump to S** if QMT event flag is clear.
*<pre>
* EEEE 1011110 01I 000011111 SSSSSSSSS
*
* JNQMT {#}S
*
*</pre>
*/
int P2Cog::op_JNQMT()
{
augmentS(IR.op7.im);
const p2_LONG address = S;
if (!FLAGS.f_QMT)
updatePC(address);
return 1;
}
/**
* @brief <empty>.
*<pre>
* EEEE 1011110 1LI DDDDDDDDD SSSSSSSSS
*
* <empty> {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_1011110_1()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief <empty>.
*<pre>
* EEEE 1011111 0LI DDDDDDDDD SSSSSSSSS
*
* <empty> {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_1011111_0()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Set pin pattern for PAT event.
*<pre>
* EEEE 1011111 BEI DDDDDDDDD SSSSSSSSS
*
* SETPAT {#}D,{#}S
*
* C selects INA/INB, Z selects =/!=, D provides mask value, S provides match value.
*</pre>
*/
int P2Cog::op_SETPAT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.im);
PAT.mode = IR.op7.wc ? (IR.op7.wz ? p2_PAT_PB_EQ : p2_PAT_PB_NE)
: (IR.op7.wz ? p2_PAT_PA_EQ : p2_PAT_PA_NE);
PAT.mask = D;
PAT.match = S;
return 1;
}
/**
* @brief Write D to mode register of smart pin S[5:0], acknowledge smart pin.
*<pre>
* EEEE 1100000 0LI DDDDDDDDD SSSSSSSSS
*
* WRPIN {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_WRPIN()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Acknowledge smart pin S[5:0].
*<pre>
* EEEE 1100000 01I 000000001 SSSSSSSSS
*
* AKPIN {#}S
*
*</pre>
*/
int P2Cog::op_AKPIN()
{
augmentS(IR.op7.im);
return 1;
}
/**
* @brief Write D to parameter "X" of smart pin S[5:0], acknowledge smart pin.
*<pre>
* EEEE 1100000 1LI DDDDDDDDD SSSSSSSSS
*
* WXPIN {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_WXPIN()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Write D to parameter "Y" of smart pin S[5:0], acknowledge smart pin.
*<pre>
* EEEE 1100001 0LI DDDDDDDDD SSSSSSSSS
*
* WYPIN {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_WYPIN()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Write D to LUT address S[8:0].
*<pre>
* EEEE 1100001 1LI DDDDDDDDD SSSSSSSSS
*
* WRLUT {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_WRLUT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
const p2_LONG address = D;
const p2_LONG result = S;
updateLUT(address, result);
return 1;
}
/**
* @brief Write byte in D[7:0] to hub address {#}S/PTRx.
*<pre>
* EEEE 1100010 0LI DDDDDDDDD SSSSSSSSS
*
* WRBYTE {#}D,{#}S/P
*
*</pre>
*/
int P2Cog::op_WRBYTE()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
p2_LONG address = get_pointer(S, 2);
p2_BYTE result = static_cast<p2_BYTE>(D);
HUB->wr_BYTE(address, result);
return 1;
}
/**
* @brief Write word in D[15:0] to hub address {#}S/PTRx.
*<pre>
* EEEE 1100010 1LI DDDDDDDDD SSSSSSSSS
*
* WRWORD {#}D,{#}S/P
*
*</pre>
*/
int P2Cog::op_WRWORD()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
p2_LONG address = get_pointer(S, 1);
p2_WORD result = static_cast<p2_WORD>(D);
HUB->wr_WORD(address, result);
return 1;
}
/**
* @brief Write long in D[31:0] to hub address {#}S/PTRx.
*<pre>
* EEEE 1100011 0LI DDDDDDDDD SSSSSSSSS
*
* WRLONG {#}D,{#}S/P
*
* Prior SETQ/SETQ2 invokes cog/LUT block transfer.
*</pre>
*/
int P2Cog::op_WRLONG()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
p2_LONG address = get_pointer(S, 0);
p2_LONG result = D;
HUB->wr_BYTE(address, result);
return 1;
}
/**
* @brief Write long in D[31:0] to hub address PTRA++.
*<pre>
* EEEE 1100011 0L1 DDDDDDDDD 101100001
*
* PUSHA {#}D
*
*</pre>
*/
int P2Cog::op_PUSHA()
{
augmentD(IR.op7.wz);
p2_LONG result = D;
pushPTRA(result);
return 1;
}
/**
* @brief Write long in D[31:0] to hub address PTRB++.
*<pre>
* EEEE 1100011 0L1 DDDDDDDDD 111100001
*
* PUSHB {#}D
*
*</pre>
*/
int P2Cog::op_PUSHB()
{
augmentD(IR.op7.wz);
p2_LONG result = D;
pushPTRB(result);
return 1;
}
/**
* @brief Begin new fast hub read via FIFO.
*<pre>
* EEEE 1100011 1LI DDDDDDDDD SSSSSSSSS
*
* RDFAST {#}D,{#}S
*
* D[31] = no wait, D[13:0] = block size in 64-byte units (0 = max), S[19:0] = block start address.
*</pre>
*/
int P2Cog::op_RDFAST()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin new fast hub write via FIFO.
*<pre>
* EEEE 1100100 0LI DDDDDDDDD SSSSSSSSS
*
* WRFAST {#}D,{#}S
*
* D[31] = no wait, D[13:0] = block size in 64-byte units (0 = max), S[19:0] = block start address.
*</pre>
*/
int P2Cog::op_WRFAST()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Set next block for when block wraps.
*<pre>
* EEEE 1100100 1LI DDDDDDDDD SSSSSSSSS
*
* FBLOCK {#}D,{#}S
*
* D[13:0] = block size in 64-byte units (0 = max), S[19:0] = block start address.
*</pre>
*/
int P2Cog::op_FBLOCK()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Issue streamer command immediately, zeroing phase.
*<pre>
* EEEE 1100101 0LI DDDDDDDDD SSSSSSSSS
*
* XINIT {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_XINIT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Stop streamer immediately.
*<pre>
* EEEE 1100101 011 000000000 000000000
*
* XSTOP
*
*</pre>
*/
int P2Cog::op_XSTOP()
{
return 1;
}
/**
* @brief Buffer new streamer command to be issued on final NCO rollover of current command, zeroing phase.
*<pre>
* EEEE 1100101 1LI DDDDDDDDD SSSSSSSSS
*
* XZERO {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_XZERO()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Buffer new streamer command to be issued on final NCO rollover of current command, continuing phase.
*<pre>
* EEEE 1100110 0LI DDDDDDDDD SSSSSSSSS
*
* XCONT {#}D,{#}S
*
*</pre>
*/
int P2Cog::op_XCONT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Execute next D[8:0] instructions S times.
*<pre>
* EEEE 1100110 1LI DDDDDDDDD SSSSSSSSS
*
* REP {#}D,{#}S
*
* If S = 0, repeat infinitely.
* If D[8:0] = 0, nothing repeats.
*</pre>
*/
int P2Cog::op_REP()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
updateREP(D, S);
return 1;
}
/**
* @brief Start cog selected by D.
*<pre>
* EEEE 1100111 CLI DDDDDDDDD SSSSSSSSS
*
* COGINIT {#}D,{#}S {WC}
*
* S[19:0] sets hub startup address and PTRB of cog.
* Prior SETQ sets PTRA of cog.
*</pre>
*/
int P2Cog::op_COGINIT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
Q_ASSERT(HUB);
HUB->coginit(D, S, Q);
return 1;
}
/**
* @brief Begin CORDIC unsigned multiplication of D * S.
*<pre>
* EEEE 1101000 0LI DDDDDDDDD SSSSSSSSS
*
* QMUL {#}D,{#}S
*
* GETQX/GETQY retrieves lower/upper product.
*</pre>
*/
int P2Cog::op_QMUL()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin CORDIC unsigned division of {SETQ value or 32'b0, D} / S.
*<pre>
* EEEE 1101000 1LI DDDDDDDDD SSSSSSSSS
*
* QDIV {#}D,{#}S
*
* GETQX/GETQY retrieves quotient/remainder.
*</pre>
*/
int P2Cog::op_QDIV()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin CORDIC unsigned division of {D, SETQ value or 32'b0} / S.
*<pre>
* EEEE 1101001 0LI DDDDDDDDD SSSSSSSSS
*
* QFRAC {#}D,{#}S
*
* GETQX/GETQY retrieves quotient/remainder.
*</pre>
*/
int P2Cog::op_QFRAC()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin CORDIC square root of {S, D}.
*<pre>
* EEEE 1101001 1LI DDDDDDDDD SSSSSSSSS
*
* QSQRT {#}D,{#}S
*
* GETQX retrieves root.
*</pre>
*/
int P2Cog::op_QSQRT()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin CORDIC rotation of point (D, SETQ value or 32'b0) by angle S.
*<pre>
* EEEE 1101010 0LI DDDDDDDDD SSSSSSSSS
*
* QROTATE {#}D,{#}S
*
* GETQX/GETQY retrieves X/Y.
*</pre>
*/
int P2Cog::op_QROTATE()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Begin CORDIC vectoring of point (D, S).
*<pre>
* EEEE 1101010 1LI DDDDDDDDD SSSSSSSSS
*
* QVECTOR {#}D,{#}S
*
* GETQX/GETQY retrieves length/angle.
*</pre>
*/
int P2Cog::op_QVECTOR()
{
augmentS(IR.op7.im);
augmentD(IR.op7.wz);
return 1;
}
/**
* @brief Set hub configuration to D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000000000
*
* HUBSET {#}D
*
*</pre>
*/
int P2Cog::op_HUBSET()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief If D is register and no WC, get cog ID (0 to 15) into D.
*<pre>
* EEEE 1101011 C0L DDDDDDDDD 000000001
*
* COGID {#}D {WC}
*
* If WC, check status of cog D[3:0], C = 1 if on.
*</pre>
*/
int P2Cog::op_COGID()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Stop cog D[3:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000000011
*
* COGSTOP {#}D
*
*</pre>
*/
int P2Cog::op_COGSTOP()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Request a LOCK.
*<pre>
* EEEE 1101011 C00 DDDDDDDDD 000000100
*
* LOCKNEW D {WC}
*
* D will be written with the LOCK number (0 to 15).
* C = 1 if no LOCK available.
*</pre>
*/
int P2Cog::op_LOCKNEW()
{
return 1;
}
/**
* @brief Return LOCK D[3:0] for reallocation.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000000101
*
* LOCKRET {#}D
*
*</pre>
*/
int P2Cog::op_LOCKRET()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Try to get LOCK D[3:0].
*<pre>
* EEEE 1101011 C0L DDDDDDDDD 000000110
*
* LOCKTRY {#}D {WC}
*
* C = 1 if got LOCK.
* LOCKREL releases LOCK.
* LOCK is also released if owner cog stops or restarts.
*</pre>
*/
int P2Cog::op_LOCKTRY()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Release LOCK D[3:0].
*<pre>
* EEEE 1101011 C0L DDDDDDDDD 000000111
*
* LOCKREL {#}D {WC}
*
* If D is a register and WC, get current/last cog id of LOCK owner into D and LOCK status into C.
*</pre>
*/
int P2Cog::op_LOCKREL()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Begin CORDIC number-to-logarithm conversion of D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000001110
*
* QLOG {#}D
*
* GETQX retrieves log {5'whole_exponent, 27'fractional_exponent}.
*</pre>
*/
int P2Cog::op_QLOG()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Begin CORDIC logarithm-to-number conversion of D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000001111
*
* QEXP {#}D
*
* GETQX retrieves number.
*</pre>
*/
int P2Cog::op_QEXP()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Read zero-extended byte from FIFO into D. Used after RDFAST.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000010000
*
* RFBYTE D {WC/WZ/WCZ}
*
* C = MSB of byte.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RFBYTE()
{
return 1;
}
/**
* @brief Read zero-extended word from FIFO into D. Used after RDFAST.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000010001
*
* RFWORD D {WC/WZ/WCZ}
*
* C = MSB of word.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RFWORD()
{
return 1;
}
/**
* @brief Read long from FIFO into D. Used after RDFAST.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000010010
*
* RFLONG D {WC/WZ/WCZ}
*
* C = MSB of long.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RFLONG()
{
return 1;
}
/**
* @brief Read zero-extended 1 … 4-byte value from FIFO into D. Used after RDFAST.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000010011
*
* RFVAR D {WC/WZ/WCZ}
*
* C = 0.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RFVAR()
{
return 1;
}
/**
* @brief Read sign-extended 1 … 4-byte value from FIFO into D. Used after RDFAST.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000010100
*
* RFVARS D {WC/WZ/WCZ}
*
* C = MSB of value.
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_RFVARS()
{
return 1;
}
/**
* @brief Write byte in D[7:0] into FIFO. Used after WRFAST.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000010101
*
* WFBYTE {#}D
*
*</pre>
*/
int P2Cog::op_WFBYTE()
{
return 1;
}
/**
* @brief Write word in D[15:0] into FIFO. Used after WRFAST.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000010110
*
* WFWORD {#}D
*
*</pre>
*/
int P2Cog::op_WFWORD()
{
return 1;
}
/**
* @brief Write long in D[31:0] into FIFO. Used after WRFAST.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000010111
*
* WFLONG {#}D
*
*</pre>
*/
int P2Cog::op_WFLONG()
{
return 1;
}
/**
* @brief Retrieve CORDIC result X into D.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000011000
*
* GETQX D {WC/WZ/WCZ}
*
* Waits, in case result:
op_not ready.();
return;
* C = X[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_GETQX()
{
return 1;
}
/**
* @brief Retrieve CORDIC result Y into D.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000011001
*
* GETQY D {WC/WZ/WCZ}
*
* Waits, in case result:
op_not ready.();
return;
* C = Y[31].
* Z = (result == 0).
*</pre>
*/
int P2Cog::op_GETQY()
{
return 1;
}
/**
* @brief Get CT into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 000011010
*
* GETCT D
*
* CT is the free-running 32-bit system counter that increments on every clock.
*</pre>
*/
int P2Cog::op_GETCT()
{
return 1;
}
/**
* @brief Get RND into D/C/Z.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000011011
*
* GETRND D {WC/WZ/WCZ}
*
* RND is the PRNG that updates on every clock.
* D = RND[31:0], C = RND[31], Z = RND[30], unique per cog.
*</pre>
*/
int P2Cog::op_GETRND()
{
p2_LONG result = HUB->random(2*ID);
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updateD(result);
return 1;
}
/**
* @brief Get RND into C/Z.
*<pre>
* EEEE 1101011 CZ1 000000000 000011011
*
* GETRND WC/WZ/WCZ
*
* C = RND[31], Z = RND[30], unique per cog.
*</pre>
*/
int P2Cog::op_GETRND_CZ()
{
p2_LONG result = HUB->random(2*ID);
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
return 1;
}
/**
* @brief DAC3 = D[31:24], DAC2 = D[23:16], DAC1 = D[15:8], DAC0 = D[7:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000011100
*
* SETDACS {#}D
*
*</pre>
*/
int P2Cog::op_SETDACS()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set streamer NCO frequency to D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000011101
*
* SETXFRQ {#}D
*
*</pre>
*/
int P2Cog::op_SETXFRQ()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Get the streamer's Goertzel X accumulator into D and the Y accumulator into the next instruction's S, clear accumulators.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 000011110
*
* GETXACC D
*
*</pre>
*/
int P2Cog::op_GETACC()
{
return 1;
}
/**
* @brief Wait 2 + D clocks if no WC/WZ/WCZ.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000011111
*
* WAITX {#}D {WC/WZ/WCZ}
*
* If WC/WZ/WCZ, wait 2 + (D & RND) clocks.
* C/Z = 0.
*</pre>
*/
int P2Cog::op_WAITX()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set SE1 event configuration to D[8:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100000
*
* SETSE1 {#}D
*
*</pre>
*/
int P2Cog::op_SETSE1()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set SE2 event configuration to D[8:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100001
*
* SETSE2 {#}D
*
*</pre>
*/
int P2Cog::op_SETSE2()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set SE3 event configuration to D[8:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100010
*
* SETSE3 {#}D
*
*</pre>
*/
int P2Cog::op_SETSE3()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set SE4 event configuration to D[8:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100011
*
* SETSE4 {#}D
*
*</pre>
*/
int P2Cog::op_SETSE4()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Get INT event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000000 000100100
*
* POLLINT {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLINT()
{
return 1;
}
/**
* @brief Get CT1 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000001 000100100
*
* POLLCT1 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLCT1()
{
return 1;
}
/**
* @brief Get CT2 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000010 000100100
*
* POLLCT2 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLCT2()
{
return 1;
}
/**
* @brief Get CT3 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000011 000100100
*
* POLLCT3 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLCT3()
{
return 1;
}
/**
* @brief Get SE1 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000100 000100100
*
* POLLSE1 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLSE1()
{
return 1;
}
/**
* @brief Get SE2 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000101 000100100
*
* POLLSE2 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLSE2()
{
return 1;
}
/**
* @brief Get SE3 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000110 000100100
*
* POLLSE3 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLSE3()
{
return 1;
}
/**
* @brief Get SE4 event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000000111 000100100
*
* POLLSE4 {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLSE4()
{
return 1;
}
/**
* @brief Get PAT event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001000 000100100
*
* POLLPAT {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLPAT()
{
return 1;
}
/**
* @brief Get FBW event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001001 000100100
*
* POLLFBW {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLFBW()
{
return 1;
}
/**
* @brief Get XMT event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001010 000100100
*
* POLLXMT {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLXMT()
{
return 1;
}
/**
* @brief Get XFI event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001011 000100100
*
* POLLXFI {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLXFI()
{
return 1;
}
/**
* @brief Get XRO event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001100 000100100
*
* POLLXRO {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLXRO()
{
return 1;
}
/**
* @brief Get XRL event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001101 000100100
*
* POLLXRL {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLXRL()
{
return 1;
}
/**
* @brief Get ATN event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001110 000100100
*
* POLLATN {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLATN()
{
return 1;
}
/**
* @brief Get QMT event flag into C/Z, then clear it.
*<pre>
* EEEE 1101011 CZ0 000001111 000100100
*
* POLLQMT {WC/WZ/WCZ}
*
*</pre>
*/
int P2Cog::op_POLLQMT()
{
return 1;
}
/**
* @brief Wait for INT event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010000 000100100
*
* WAITINT {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITINT()
{
return 1;
}
/**
* @brief Wait for CT1 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010001 000100100
*
* WAITCT1 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITCT1()
{
return 1;
}
/**
* @brief Wait for CT2 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010010 000100100
*
* WAITCT2 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITCT2()
{
return 1;
}
/**
* @brief Wait for CT3 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010011 000100100
*
* WAITCT3 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITCT3()
{
return 1;
}
/**
* @brief Wait for SE1 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010100 000100100
*
* WAITSE1 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITSE1()
{
return 1;
}
/**
* @brief Wait for SE2 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010101 000100100
*
* WAITSE2 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITSE2()
{
return 1;
}
/**
* @brief Wait for SE3 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010110 000100100
*
* WAITSE3 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITSE3()
{
return 1;
}
/**
* @brief Wait for SE4 event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000010111 000100100
*
* WAITSE4 {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITSE4()
{
return 1;
}
/**
* @brief Wait for PAT event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011000 000100100
*
* WAITPAT {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITPAT()
{
return 1;
}
/**
* @brief Wait for FBW event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011001 000100100
*
* WAITFBW {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITFBW()
{
return 1;
}
/**
* @brief Wait for XMT event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011010 000100100
*
* WAITXMT {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITXMT()
{
return 1;
}
/**
* @brief Wait for XFI event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011011 000100100
*
* WAITXFI {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITXFI()
{
return 1;
}
/**
* @brief Wait for XRO event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011100 000100100
*
* WAITXRO {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITXRO()
{
return 1;
}
/**
* @brief Wait for XRL event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011101 000100100
*
* WAITXRL {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITXRL()
{
return 1;
}
/**
* @brief Wait for ATN event flag, then clear it.
*<pre>
* EEEE 1101011 CZ0 000011110 000100100
*
* WAITATN {WC/WZ/WCZ}
*
* Prior SETQ sets optional CT timeout value.
* C/Z = timeout.
*</pre>
*/
int P2Cog::op_WAITATN()
{
return 1;
}
/**
* @brief Allow interrupts (default).
*<pre>
* EEEE 1101011 000 000100000 000100100
*
* ALLOWI
*
*</pre>
*/
int P2Cog::op_ALLOWI()
{
return 1;
}
/**
* @brief Stall Interrupts.
*<pre>
* EEEE 1101011 000 000100001 000100100
*
* STALLI
*
*</pre>
*/
int P2Cog::op_STALLI()
{
return 1;
}
/**
* @brief Trigger INT1, regardless of STALLI mode.
*<pre>
* EEEE 1101011 000 000100010 000100100
*
* TRGINT1
*
*</pre>
*/
int P2Cog::op_TRGINT1()
{
return 1;
}
/**
* @brief Trigger INT2, regardless of STALLI mode.
*<pre>
* EEEE 1101011 000 000100011 000100100
*
* TRGINT2
*
*</pre>
*/
int P2Cog::op_TRGINT2()
{
return 1;
}
/**
* @brief Trigger INT3, regardless of STALLI mode.
*<pre>
* EEEE 1101011 000 000100100 000100100
*
* TRGINT3
*
*</pre>
*/
int P2Cog::op_TRGINT3()
{
return 1;
}
/**
* @brief Cancel INT1.
*<pre>
* EEEE 1101011 000 000100101 000100100
*
* NIXINT1
*
*</pre>
*/
int P2Cog::op_NIXINT1()
{
return 1;
}
/**
* @brief Cancel INT2.
*<pre>
* EEEE 1101011 000 000100110 000100100
*
* NIXINT2
*
*</pre>
*/
int P2Cog::op_NIXINT2()
{
return 1;
}
/**
* @brief Cancel INT3.
*<pre>
* EEEE 1101011 000 000100111 000100100
*
* NIXINT3
*
*</pre>
*/
int P2Cog::op_NIXINT3()
{
return 1;
}
/**
* @brief Set INT1 source to D[3:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100101
*
* SETINT1 {#}D
*
*</pre>
*/
int P2Cog::op_SETINT1()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set INT2 source to D[3:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100110
*
* SETINT2 {#}D
*
*</pre>
*/
int P2Cog::op_SETINT2()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set INT3 source to D[3:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000100111
*
* SETINT3 {#}D
*
*</pre>
*/
int P2Cog::op_SETINT3()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set Q to D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000101000
*
* SETQ {#}D
*
* Use before RDLONG/WRLONG/WMLONG to set block transfer.
* Also used before MUXQ/COGINIT/QDIV/QFRAC/QROTATE/WAITxxx.
*</pre>
*/
int P2Cog::op_SETQ()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set Q to D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000101001
*
* SETQ2 {#}D
*
* Use before RDLONG/WRLONG/WMLONG to set LUT block transfer.
*</pre>
*/
int P2Cog::op_SETQ2()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Push D onto stack.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000101010
*
* PUSH {#}D
*
*</pre>
*/
int P2Cog::op_PUSH()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Pop stack (K).
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000101011
*
* POP D {WC/WZ/WCZ}
*
* C = K[31], Z = K[30], D = K.
*</pre>
*/
int P2Cog::op_POP()
{
return 1;
}
/**
* @brief Jump to D.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000101100
*
* JMP D {WC/WZ/WCZ}
*
* C = D[31], Z = D[30], PC = D[19:0].
*</pre>
*/
int P2Cog::op_JMP()
{
updateC((D >> 31) & 1);
updateZ((D >> 30) & 1);
updatePC(D);
return 1;
}
/**
* @brief Call to D by pushing {C, Z, 10'b0, PC[19:0]} onto stack.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000101101
*
* CALL D {WC/WZ/WCZ}
*
* C = D[31], Z = D[30], PC = D[19:0].
*</pre>
*/
int P2Cog::op_CALL()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = D;
pushK(stack);
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Return by popping stack (K).
*<pre>
* EEEE 1101011 CZ1 000000000 000101101
*
* RET {WC/WZ/WCZ}
*
* C = K[31], Z = K[30], PC = K[19:0].
*</pre>
*/
int P2Cog::op_RET()
{
p2_LONG result = popK();
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Call to D by writing {C, Z, 10'b0, PC[19:0]} to hub long at PTRA++.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000101110
*
* CALLA D {WC/WZ/WCZ}
*
* C = D[31], Z = D[30], PC = D[19:0].
*</pre>
*/
int P2Cog::op_CALLA()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = D;
pushPTRA(stack);
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Return by reading hub long (L) at --PTRA.
*<pre>
* EEEE 1101011 CZ1 000000000 000101110
*
* RETA {WC/WZ/WCZ}
*
* C = L[31], Z = L[30], PC = L[19:0].
*</pre>
*/
int P2Cog::op_RETA()
{
p2_LONG result = popPTRA();
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Call to D by writing {C, Z, 10'b0, PC[19:0]} to hub long at PTRB++.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000101111
*
* CALLB D {WC/WZ/WCZ}
*
* C = D[31], Z = D[30], PC = D[19:0].
*</pre>
*/
int P2Cog::op_CALLB()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = D;
pushPTRB(stack);
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Return by reading hub long (L) at --PTRB.
*<pre>
* EEEE 1101011 CZ1 000000000 000101111
*
* RETB {WC/WZ/WCZ}
*
* C = L[31], Z = L[30], PC = L[19:0].
*</pre>
*/
int P2Cog::op_RETB()
{
p2_LONG result = popPTRB();
updateC((result >> 31) & 1);
updateZ((result >> 30) & 1);
updatePC(result);
return 1;
}
/**
* @brief Jump ahead/back by D instructions.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110000
*
* JMPREL {#}D
*
* For cogex, PC += D[19:0].
* For hubex, PC += D[17:0] << 2.
*</pre>
*/
int P2Cog::op_JMPREL()
{
augmentD(IR.op7.im);
const p2_LONG result = PC < 0x400 ? PC + D : PC + D * 4;
updatePC(result);
return 1;
}
/**
* @brief Skip instructions per D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110001
*
* SKIP {#}D
*
* Subsequent instructions 0 … 31 get cancelled for each '1' bit in D[0] … D[31].
*</pre>
*/
int P2Cog::op_SKIP()
{
augmentD(IR.op7.im);
const p2_LONG result = D;
updateSKIP(result);
return 1;
}
/**
* @brief Skip cog/LUT instructions fast per D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110010
*
* SKIPF {#}D
*
* Like SKIP, but instead of cancelling instructions, the PC leaps over them.
*</pre>
*/
int P2Cog::op_SKIPF()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Jump to D[9:0] in cog/LUT and set SKIPF pattern to D[31:10].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110011
*
* EXECF {#}D
*
* PC = {10'b0, D[9:0]}.
*</pre>
*/
int P2Cog::op_EXECF()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Get current FIFO hub pointer into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 000110100
*
* GETPTR D
*
*</pre>
*/
int P2Cog::op_GETPTR()
{
const p2_LONG result = FIFO.head_addr;
updateD(result);
return 1;
}
/**
* @brief Get breakpoint status into D according to WC/WZ/WCZ.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 000110101
*
* GETBRK D WC/WZ/WCZ
*
* C = 0.
* Z = 0.
*</pre>
*/
int P2Cog::op_GETBRK()
{
return 1;
}
/**
* @brief If in debug ISR, trigger asynchronous breakpoint in cog D[3:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110101
*
* COGBRK {#}D
*
* Cog D[3:0] must have asynchronous breakpoint enabled.
*</pre>
*/
int P2Cog::op_COGBRK()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief If in debug ISR, set next break condition to D.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110110
*
* BRK {#}D
*
* Else, trigger break if enabled, conditionally write break code to D[7:0].
*</pre>
*/
int P2Cog::op_BRK()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief If D[0] = 1 then enable LUT sharing, where LUT writes within the adjacent odd/even companion cog are copied to this LUT.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000110111
*
* SETLUTS {#}D
*
*</pre>
*/
int P2Cog::op_SETLUTS()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set the colorspace converter "CY" parameter to D[31:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111000
*
* SETCY {#}D
*
*</pre>
*/
int P2Cog::op_SETCY()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set the colorspace converter "CI" parameter to D[31:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111001
*
* SETCI {#}D
*
*</pre>
*/
int P2Cog::op_SETCI()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set the colorspace converter "CQ" parameter to D[31:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111010
*
* SETCQ {#}D
*
*</pre>
*/
int P2Cog::op_SETCQ()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set the colorspace converter "CFRQ" parameter to D[31:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111011
*
* SETCFRQ {#}D
*
*</pre>
*/
int P2Cog::op_SETCFRQ()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set the colorspace converter "CMOD" parameter to D[6:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111100
*
* SETCMOD {#}D
*
*</pre>
*/
int P2Cog::op_SETCMOD()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set BLNPIX/MIXPIX blend factor to D[7:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111101
*
* SETPIV {#}D
*
*</pre>
*/
int P2Cog::op_SETPIV()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Set MIXPIX mode to D[5:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111110
*
* SETPIX {#}D
*
*</pre>
*/
int P2Cog::op_SETPIX()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Strobe "attention" of all cogs whose corresponging bits are high in D[15:0].
*<pre>
* EEEE 1101011 00L DDDDDDDDD 000111111
*
* COGATN {#}D
*
*</pre>
*/
int P2Cog::op_COGATN()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test IN bit of pin D[5:0], write to C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000000
*
* TESTP {#}D WC/WZ
*
* C/Z = IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTP_W()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test !IN bit of pin D[5:0], write to C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000001
*
* TESTPN {#}D WC/WZ
*
* C/Z = !IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTPN_W()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test IN bit of pin D[5:0], AND into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000010
*
* TESTP {#}D ANDC/ANDZ
*
* C/Z = C/Z AND IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTP_AND()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test !IN bit of pin D[5:0], AND into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000011
*
* TESTPN {#}D ANDC/ANDZ
*
* C/Z = C/Z AND !IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTPN_AND()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test IN bit of pin D[5:0], OR into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000100
*
* TESTP {#}D ORC/ORZ
*
* C/Z = C/Z OR IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTP_OR()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test !IN bit of pin D[5:0], OR into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000101
*
* TESTPN {#}D ORC/ORZ
*
* C/Z = C/Z OR !IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTPN_OR()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test IN bit of pin D[5:0], XOR into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000110
*
* TESTP {#}D XORC/XORZ
*
* C/Z = C/Z XOR IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTP_XOR()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief Test !IN bit of pin D[5:0], XOR into C/Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000111
*
* TESTPN {#}D XORC/XORZ
*
* C/Z = C/Z XOR !IN[D[5:0]].
*</pre>
*/
int P2Cog::op_TESTPN_XOR()
{
augmentD(IR.op7.im);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = 0.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000000
*
* DIRL {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRL()
{
augmentD(IR.op7.im);
const p2_LONG result = 0;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = 1.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000001
*
* DIRH {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRH()
{
augmentD(IR.op7.im);
const p2_LONG result = 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000010
*
* DIRC {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRC()
{
augmentD(IR.op7.im);
const p2_LONG result = C;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = !C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000011
*
* DIRNC {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRNC()
{
augmentD(IR.op7.im);
const p2_LONG result = C ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000100
*
* DIRZ {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = !Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000101
*
* DIRNZ {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRNZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = RND.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000110
*
* DIRRND {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRRND()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->random(2*ID) & 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief DIR bit of pin D[5:0] = !bit.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001000111
*
* DIRNOT {#}D {WCZ}
*
* C,Z = DIR bit.
*</pre>
*/
int P2Cog::op_DIRNOT()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->rd_DIR(D) ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 0.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001000
*
* OUTL {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTL()
{
augmentD(IR.op7.im);
const p2_LONG result = 0;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 1.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001001
*
* OUTH {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTH()
{
augmentD(IR.op7.im);
const p2_LONG result = 1;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001010
*
* OUTC {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTC()
{
augmentD(IR.op7.im);
const p2_LONG result = C;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001011
*
* OUTNC {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTNC()
{
augmentD(IR.op7.im);
const p2_LONG result = C ^ 1;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001100
*
* OUTZ {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001101
*
* OUTNZ {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTNZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z ^ 1;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = RND.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001110
*
* OUTRND {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTRND()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->random(2*ID) & 1;
updateC(result);
updateZ(result);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !bit.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001001111
*
* OUTNOT {#}D {WCZ}
*
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_OUTNOT()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->rd_OUT(D) ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 0.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010000
*
* FLTL {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTL()
{
augmentD(IR.op7.im);
const p2_LONG result = 0;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 1.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010001
*
* FLTH {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTH()
{
augmentD(IR.op7.im);
const p2_LONG result = 1;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010010
*
* FLTC {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTC()
{
augmentD(IR.op7.im);
const p2_LONG result = C;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010011
*
* FLTNC {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTNC()
{
augmentD(IR.op7.im);
const p2_LONG result = C ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010100
*
* FLTZ {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010101
*
* FLTNZ {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTNZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = RND.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010110
*
* FLTRND {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTRND()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->random(2*ID) & 1;
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !bit.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001010111
*
* FLTNOT {#}D {WCZ}
*
* DIR bit = 0.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_FLTNOT()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->rd_OUT(D);
updateC(result);
updateZ(result);
updateDIR(D, 0);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 0.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011000
*
* DRVL {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVL()
{
augmentD(IR.op7.im);
const p2_LONG result = 0;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = 1.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011001
*
* DRVH {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVH()
{
augmentD(IR.op7.im);
const p2_LONG result = 1;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011010
*
* DRVC {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVC()
{
augmentD(IR.op7.im);
const p2_LONG result = C;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !C.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011011
*
* DRVNC {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVNC()
{
augmentD(IR.op7.im);
const p2_LONG result = C ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011100
*
* DRVZ {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !Z.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011101
*
* DRVNZ {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVNZ()
{
augmentD(IR.op7.im);
const p2_LONG result = Z ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = RND.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011110
*
* DRVRND {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVRND()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->random(2*ID) & 1;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief OUT bit of pin D[5:0] = !bit.
*<pre>
* EEEE 1101011 CZL DDDDDDDDD 001011111
*
* DRVNOT {#}D {WCZ}
*
* DIR bit = 1.
* C,Z = OUT bit.
*</pre>
*/
int P2Cog::op_DRVNOT()
{
augmentD(IR.op7.im);
const p2_LONG result = HUB->rd_OUT(D) ^ 1;
updateC(result);
updateZ(result);
updateDIR(D, 1);
updateOUT(D, result);
return 1;
}
/**
* @brief Split every 4th bit of S into bytes of D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100000
*
* SPLITB D
*
* D = {S[31], S[27], S[23], S[19], … S[12], S[8], S[4], S[0]}.
*</pre>
*/
int P2Cog::op_SPLITB()
{
const quint32 result =
(((S >> 31) & 1) << 31) | (((S >> 27) & 1) << 30) | (((S >> 23) & 1) << 29) | (((S >> 19) & 1) << 28) |
(((S >> 15) & 1) << 27) | (((S >> 11) & 1) << 26) | (((S >> 7) & 1) << 25) | (((S >> 3) & 1) << 24) |
(((S >> 30) & 1) << 23) | (((S >> 26) & 1) << 22) | (((S >> 22) & 1) << 21) | (((S >> 18) & 1) << 20) |
(((S >> 14) & 1) << 19) | (((S >> 10) & 1) << 18) | (((S >> 6) & 1) << 17) | (((S >> 2) & 1) << 16) |
(((S >> 29) & 1) << 15) | (((S >> 25) & 1) << 14) | (((S >> 21) & 1) << 13) | (((S >> 17) & 1) << 12) |
(((S >> 13) & 1) << 11) | (((S >> 9) & 1) << 10) | (((S >> 5) & 1) << 9) | (((S >> 1) & 1) << 8) |
(((S >> 28) & 1) << 7) | (((S >> 24) & 1) << 6) | (((S >> 20) & 1) << 5) | (((S >> 16) & 1) << 4) |
(((S >> 12) & 1) << 3) | (((S >> 8) & 1) << 2) | (((S >> 4) & 1) << 1) | (((S >> 0) & 1) << 0);
updateD(result);
return 1;
}
/**
* @brief Merge bits of bytes in S into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100001
*
* MERGEB D
*
* D = {S[31], S[23], S[15], S[7], … S[24], S[16], S[8], S[0]}.
*</pre>
*/
int P2Cog::op_MERGEB()
{
const quint32 result =
(((S >> 31) & 1) << 31) | (((S >> 23) & 1) << 30) | (((S >> 15) & 1) << 29) | (((S >> 7) & 1) << 28) |
(((S >> 30) & 1) << 27) | (((S >> 22) & 1) << 26) | (((S >> 14) & 1) << 25) | (((S >> 6) & 1) << 24) |
(((S >> 29) & 1) << 23) | (((S >> 21) & 1) << 22) | (((S >> 13) & 1) << 21) | (((S >> 5) & 1) << 20) |
(((S >> 28) & 1) << 19) | (((S >> 20) & 1) << 18) | (((S >> 12) & 1) << 17) | (((S >> 4) & 1) << 16) |
(((S >> 27) & 1) << 15) | (((S >> 19) & 1) << 14) | (((S >> 11) & 1) << 13) | (((S >> 3) & 1) << 12) |
(((S >> 26) & 1) << 11) | (((S >> 18) & 1) << 10) | (((S >> 10) & 1) << 9) | (((S >> 2) & 1) << 8) |
(((S >> 25) & 1) << 7) | (((S >> 17) & 1) << 6) | (((S >> 9) & 1) << 5) | (((S >> 1) & 1) << 4) |
(((S >> 24) & 1) << 3) | (((S >> 16) & 1) << 2) | (((S >> 8) & 1) << 1) | (((S >> 0) & 1) << 0);
updateD(result);
return 1;
}
/**
* @brief Split bits of S into words of D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100010
*
* SPLITW D
*
* D = {S[31], S[29], S[27], S[25], … S[6], S[4], S[2], S[0]}.
*</pre>
*/
int P2Cog::op_SPLITW()
{
const quint32 result =
(((S >> 31) & 1) << 31) | (((S >> 29) & 1) << 30) | (((S >> 27) & 1) << 29) | (((S >> 25) & 1) << 28) |
(((S >> 23) & 1) << 27) | (((S >> 21) & 1) << 26) | (((S >> 19) & 1) << 25) | (((S >> 17) & 1) << 24) |
(((S >> 15) & 1) << 23) | (((S >> 13) & 1) << 22) | (((S >> 11) & 1) << 21) | (((S >> 9) & 1) << 20) |
(((S >> 7) & 1) << 19) | (((S >> 5) & 1) << 18) | (((S >> 3) & 1) << 17) | (((S >> 1) & 1) << 16) |
(((S >> 30) & 1) << 15) | (((S >> 28) & 1) << 14) | (((S >> 26) & 1) << 13) | (((S >> 24) & 1) << 12) |
(((S >> 22) & 1) << 11) | (((S >> 20) & 1) << 10) | (((S >> 18) & 1) << 9) | (((S >> 16) & 1) << 8) |
(((S >> 14) & 1) << 7) | (((S >> 12) & 1) << 6) | (((S >> 10) & 1) << 5) | (((S >> 8) & 1) << 4) |
(((S >> 6) & 1) << 3) | (((S >> 4) & 1) << 2) | (((S >> 2) & 1) << 1) | (((S >> 0) & 1) << 0);
updateD(result);
return 1;
}
/**
* @brief Merge bits of words in S into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100011
*
* MERGEW D
*
* D = {S[31], S[15], S[30], S[14], … S[17], S[1], S[16], S[0]}.
*</pre>
*/
int P2Cog::op_MERGEW()
{
const quint32 result =
(((S >> 31) & 1) << 31) | (((S >> 15) & 1) << 30) |
(((S >> 30) & 1) << 29) | (((S >> 14) & 1) << 28) |
(((S >> 29) & 1) << 27) | (((S >> 13) & 1) << 26) |
(((S >> 28) & 1) << 25) | (((S >> 12) & 1) << 24) |
(((S >> 27) & 1) << 23) | (((S >> 11) & 1) << 22) |
(((S >> 26) & 1) << 21) | (((S >> 10) & 1) << 20) |
(((S >> 25) & 1) << 19) | (((S >> 9) & 1) << 18) |
(((S >> 24) & 1) << 17) | (((S >> 8) & 1) << 16) |
(((S >> 23) & 1) << 15) | (((S >> 7) & 1) << 14) |
(((S >> 22) & 1) << 13) | (((S >> 6) & 1) << 12) |
(((S >> 21) & 1) << 11) | (((S >> 5) & 1) << 10) |
(((S >> 20) & 1) << 9) | (((S >> 4) & 1) << 8) |
(((S >> 19) & 1) << 7) | (((S >> 3) & 1) << 6) |
(((S >> 18) & 1) << 5) | (((S >> 2) & 1) << 4) |
(((S >> 17) & 1) << 3) | (((S >> 1) & 1) << 2) |
(((S >> 16) & 1) << 1) | (((S >> 0) & 1) << 0);
updateD(result);
return 1;
}
/**
* @brief Relocate and periodically invert bits from S into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100100
*
* SEUSSF D
*
* Returns to original value on 32nd iteration.
* Forward pattern.
*</pre>
*/
int P2Cog::op_SEUSSF()
{
const p2_LONG result = P2Util::seuss(S, true);
updateD(result);
return 1;
}
/**
* @brief Relocate and periodically invert bits from S into D.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100101
*
* SEUSSR D
*
* Returns to original value on 32nd iteration.
* Reverse pattern.
*</pre>
*/
int P2Cog::op_SEUSSR()
{
const p2_LONG result = P2Util::seuss(S, false);
updateD(result);
return 1;
}
/**
* @brief Squeeze 8:8:8 RGB value in S[31:8] into 5:6:5 value in D[15:0].
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100110
*
* RGBSQZ D
*
* D = {15'b0, S[31:27], S[23:18], S[15:11]}.
*</pre>
*/
int P2Cog::op_RGBSQZ()
{
const p2_LONG result =
(((S >> 27) & 0x1f) << 11) |
(((S >> 18) & 0x3f) << 5) |
(((S >> 11) & 0x1f) << 0);
updateD(result);
return 1;
}
/**
* @brief Expand 5:6:5 RGB value in S[15:0] into 8:8:8 value in D[31:8].
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001100111
*
* RGBEXP D
*
* D = {S[15:11,15:13], S[10:5,10:9], S[4:0,4:2], 8'b0}.
*</pre>
*/
int P2Cog::op_RGBEXP()
{
const p2_LONG result =
(((S >> 11) & 0x1f) << 27) |
(((S >> 13) & 0x07) << 24) |
(((S >> 5) & 0x3f) << 18) |
(((S >> 9) & 0x03) << 16) |
(((S >> 0) & 0x1f) << 11) |
(((S >> 2) & 0x07) << 8);
updateD(result);
return 1;
}
/**
* @brief Iterate D with xoroshiro32+ PRNG algorithm and put PRNG result into next instruction's S.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101000
*
* XORO32 D
*
*</pre>
*/
int P2Cog::op_XORO32()
{
return 1;
}
/**
* @brief Reverse D bits.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101001
*
* REV D
*
* D = D[0:31].
*</pre>
*/
int P2Cog::op_REV()
{
p2_LONG result = P2Util::reverse(D);
updateD(result);
return 1;
}
/**
* @brief Rotate C,Z right through D.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 001101010
*
* RCZR D {WC/WZ/WCZ}
*
* D = {C, Z, D[31:2]}.
* C = D[1], Z = D[0].
*</pre>
*/
int P2Cog::op_RCZR()
{
const p2_LONG result = (C << 31) | (Z << 30) | (D >> 2);
updateC((D >> 1) & 1);
updateZ((D >> 0) & 1);
updateD(result);
return 1;
}
/**
* @brief Rotate C,Z left through D.
*<pre>
* EEEE 1101011 CZ0 DDDDDDDDD 001101011
*
* RCZL D {WC/WZ/WCZ}
*
* D = {D[29:0], C, Z}.
* C = D[31], Z = D[30].
*</pre>
*/
int P2Cog::op_RCZL()
{
const p2_LONG result = (D << 2) | (C << 1) | (Z << 0);
updateC((D >> 31) & 1);
updateZ((D >> 30) & 1);
updateD(result);
return 1;
}
/**
* @brief Write 0 or 1 to D, according to C.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101100
*
* WRC D
*
* D = {31'b0, C).
*</pre>
*/
int P2Cog::op_WRC()
{
const p2_LONG result = C;
updateD(result);
return 1;
}
/**
* @brief Write 0 or 1 to D, according to !C.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101101
*
* WRNC D
*
* D = {31'b0, !C).
*</pre>
*/
int P2Cog::op_WRNC()
{
const p2_LONG result = C ^ 1;
updateD(result);
return 1;
}
/**
* @brief Write 0 or 1 to D, according to Z.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101110
*
* WRZ D
*
* D = {31'b0, Z).
*</pre>
*/
int P2Cog::op_WRZ()
{
const p2_LONG result = Z;
updateD(result);
return 1;
}
/**
* @brief Write 0 or 1 to D, according to !Z.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001101111
*
* WRNZ D
*
* D = {31'b0, !Z).
*</pre>
*/
int P2Cog::op_WRNZ()
{
const p2_LONG result = Z ^ 1;
updateD(result);
return 1;
}
/**
* @brief Modify C and Z according to cccc and zzzz.
*<pre>
* EEEE 1101011 CZ1 0cccczzzz 001101111
*
* MODCZ c,z {WC/WZ/WCZ}
*
* C = cccc[{C,Z}], Z = zzzz[{C,Z}].
*</pre>
*/
int P2Cog::op_MODCZ()
{
const p2_Cond_e cccc = static_cast<p2_Cond_e>((IR.op7.dst >> 4) & 15);
const p2_Cond_e zzzz = static_cast<p2_Cond_e>((IR.op7.dst >> 0) & 15);
updateC(conditional(cccc));
updateZ(conditional(zzzz));
return 1;
}
/**
* @brief Set scope mode.
*<pre>
* EEEE 1101011 00L DDDDDDDDD 001110000
*
* SETSCP {#}D
*
*
* SETSCP points the scope mux to a set of four pins starting
* at (D[5:0] AND $3C), with D[6]=1 to enable scope operation.
*
* Set pins D[5:2] (0, 4, 8, 12, …, 60)
* Enable if D[6]=1.
*</pre>
*/
int P2Cog::op_SETSCP()
{
augmentD(IR.op7.im);
HUB->wr_SCP(D);
return 1;
}
/**
* @brief Get scope values.
*<pre>
* EEEE 1101011 000 DDDDDDDDD 001110001
*
* Any time GETSCP is executed, the lower bytes of those four pins' RDPIN values are returned in D.
*
* GETSCP D
*
* Pins D[5:2].
*</pre>
*/
int P2Cog::op_GETSCP()
{
const p2_LONG result = HUB->rd_SCP();
updateD(result);
return 1;
}
/**
* @brief Jump to A.
*<pre>
* EEEE 1101100 RAA AAAAAAAAA AAAAAAAAA
*
* JMP #A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_JMP_ABS()
{
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
updatePC(result);
return 1;
}
/**
* @brief Call to A by pushing {C, Z, 10'b0, PC[19:0]} onto stack.
*<pre>
* EEEE 1101101 RAA AAAAAAAAA AAAAAAAAA
*
* CALL #A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALL_ABS()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushK(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to hub long at PTRA++.
*<pre>
* EEEE 1101110 RAA AAAAAAAAA AAAAAAAAA
*
* CALLA #A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLA_ABS()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPTRA(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to hub long at PTRB++.
*<pre>
* EEEE 1101111 RAA AAAAAAAAA AAAAAAAAA
*
* CALLB #A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLB_ABS()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPTRB(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to PA (per W).
*<pre>
* EEEE 1110000 RAA AAAAAAAAA AAAAAAAAA
*
* CALLD PA,#A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLD_ABS_PA()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPA(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to PB (per W).
*<pre>
* EEEE 1110001 RAA AAAAAAAAA AAAAAAAAA
*
* CALLD PB,#A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLD_ABS_PB()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPB(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to PTRA (per W).
*<pre>
* EEEE 1110010 RAA AAAAAAAAA AAAAAAAAA
*
* CALLD PTRA,#A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLD_ABS_PTRA()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPTRA(stack);
updatePC(result);
return 1;
}
/**
* @brief Call to A by writing {C, Z, 10'b0, PC[19:0]} to PTRB (per W).
*<pre>
* EEEE 1110011 RAA AAAAAAAAA AAAAAAAAA
*
* CALLD PTRB,#A
*
* If R = 1, PC += A, else PC = A.
*</pre>
*/
int P2Cog::op_CALLD_ABS_PTRB()
{
const p2_LONG stack = (C << 31) | (Z << 30) | PC;
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
pushPTRB(stack);
updatePC(result);
return 1;
}
/**
* @brief Get {12'b0, address[19:0]} into PA/PB/PTRA/PTRB (per W).
*<pre>
* EEEE 11101WW RAA AAAAAAAAA AAAAAAAAA
*
* LOC PA/PB/PTRA/PTRB,#A
*
* If R = 1, address = PC + A, else address = A.
*</pre>
*/
int P2Cog::op_LOC_PA()
{
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
updatePA(result);
return 1;
}
/**
* @brief Get {12'b0, address[19:0]} into PA/PB/PTRA/PTRB (per W).
*<pre>
* EEEE 11101WW RAA AAAAAAAAA AAAAAAAAA
*
* LOC PA/PB/PTRA/PTRB,#A
*
* If R = 1, address = PC + A, else address = A.
*</pre>
*/
int P2Cog::op_LOC_PB()
{
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
updatePB(result);
return 1;
}
/**
* @brief Get {12'b0, address[19:0]} into PA/PB/PTRA/PTRB (per W).
*<pre>
* EEEE 11101WW RAA AAAAAAAAA AAAAAAAAA
*
* LOC PA/PB/PTRA/PTRB,#A
*
* If R = 1, address = PC + A, else address = A.
*</pre>
*/
int P2Cog::op_LOC_PTRA()
{
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
updatePTRA(result);
return 1;
}
/**
* @brief Get {12'b0, address[19:0]} into PA/PB/PTRA/PTRB (per W).
*<pre>
* EEEE 11101WW RAA AAAAAAAAA AAAAAAAAA
*
* LOC PA/PB/PTRA/PTRB,#A
*
* If R = 1, address = PC + A, else address = A.
*</pre>
*/
int P2Cog::op_LOC_PTRB()
{
const p2_LONG result = (IR.op5.address + (PC & SXn<p2_LONG,1>(IR.op5.rel))) & A20MASK;
updatePTRB(result);
return 1;
}
/**
* @brief Queue #N[31:9] to be used as upper 23 bits for next #S occurrence, so that the next 9-bit #S will be augmented to 32 bits.
*<pre>
* EEEE 11110NN NNN NNNNNNNNN NNNNNNNNN
*
* AUGS #N
*
*</pre>
*/
int P2Cog::op_AUGS()
{
S_aug = (IR.opcode << AUG_SHIFT) & AUG_MASK;
return 1;
}
/**
* @brief Queue #N[31:9] to be used as upper 23 bits for next #D occurrence, so that the next 9-bit #D will be augmented to 32 bits.
*<pre>
* EEEE 11111NN NNN NNNNNNNNN NNNNNNNNN
*
* AUGD #N
*
*</pre>
*/
int P2Cog::op_AUGD()
{
D_aug = (IR.opcode << AUG_SHIFT) & AUG_MASK;
return 1;
}
| 19.715107 | 132 | 0.523206 | pullmoll |
13677a90830216fa92966aa76e8d06cd51f35f15 | 2,579 | cpp | C++ | leetcode/problems/medium/662-maximum-width-of-binary-tree.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/medium/662-maximum-width-of-binary-tree.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/medium/662-maximum-width-of-binary-tree.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Maximum Width of Binary Tree
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
Example 1:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:
Input:
1
/
3
/ \
5 3
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:
Input:
1
/ \
3 2
/
5
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:
Input:
1
/ \
3 2
/ \
5 9
/ \
6 7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
Note: Answer will in the range of 32-bit signed integer.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
vector<unsigned long long> s;
// approach: dfs. don't need to care about the value
dfs(root,0,1LL,s);
return ans;
}
private:
long long ans=1;
// use unsigned long long to avoid overflow
void dfs(TreeNode* root, unsigned long long lv, unsigned long long idx, vector<unsigned long long>& s){
if(!root) return;
if(s.size()==lv) s.emplace_back(idx); // storing the leftmost node idx
else if(idx-s[lv]+1>ans) ans=idx-s[lv]+1; //
dfs(root->left,lv+1,idx*2,s); // the next left node would be idx*2
dfs(root->right,lv+1,idx*2+1,s); // the next left node would be idx*2+1
}
};
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7 | 26.864583 | 227 | 0.570376 | wingkwong |
136ae6eb4cdb6c096f8edfeab8336e76d31aa048 | 176 | hpp | C++ | Structural/Bridge/include/TrainTravel.hpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | 3 | 2019-11-15T01:38:31.000Z | 2020-04-21T13:04:19.000Z | Structural/Bridge/include/TrainTravel.hpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | 23 | 2019-11-29T09:13:42.000Z | 2020-02-05T14:53:03.000Z | Structural/Bridge/include/TrainTravel.hpp | craviee/design-patterns-modern-cpp | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | [
"Unlicense"
] | null | null | null | #pragma once
#include "TravelMethod.hpp"
#include <iostream>
class TrainTravel : public TravelMethod {
public:
TrainTravel() { price = 50; };
void startTravel();
}; | 14.666667 | 41 | 0.681818 | craviee |
136d2bad571633e9960bd3268798748c94c0d4cc | 792 | hpp | C++ | OpenS4/Renderer/TransformationPipeline.hpp | MadShadow-/OpenS4 | 1b2f69d617406a2a49ed0511d93771d978b6bfc3 | [
"MIT"
] | 3 | 2020-08-05T19:54:08.000Z | 2021-06-11T12:21:51.000Z | OpenS4/Renderer/TransformationPipeline.hpp | MadShadow-/OpenS4 | 1b2f69d617406a2a49ed0511d93771d978b6bfc3 | [
"MIT"
] | null | null | null | OpenS4/Renderer/TransformationPipeline.hpp | MadShadow-/OpenS4 | 1b2f69d617406a2a49ed0511d93771d978b6bfc3 | [
"MIT"
] | 4 | 2020-07-20T13:25:13.000Z | 2021-08-06T12:44:14.000Z | #pragma once
#include "MatrixStack.hpp"
namespace OpenS4::Renderer {
class TransformationPipeline {
OpenS4::Renderer::MatrixStack m_modelView;
OpenS4::Renderer::MatrixStack m_projection;
glm::mat4x4 m_mvp;
public:
OpenS4::Renderer::MatrixStack* getModelViewStack() { return &m_modelView; }
OpenS4::Renderer::MatrixStack* getProjectionStack() {
return &m_projection;
}
const glm::mat4x4& getProjectionMatrix() const {
return m_projection.getMatrix();
}
const glm::mat4x4& getModelViewMatrix() const {
return m_modelView.getMatrix();
}
const glm::mat4x4& getModelViewProjectionMatrix() {
m_mvp = getProjectionMatrix() * getModelViewMatrix();
return m_mvp;
}
};
} // namespace OpenS4::Renderer
| 23.294118 | 79 | 0.681818 | MadShadow- |
136ecd7cc9bb9b563fbfa5bdba36746079b3c3fe | 1,986 | hpp | C++ | higan/ws/system/system.hpp | libretro-mirrors/higan | 8617711ea2c201a33442266945dc7ed186e9d695 | [
"Intel",
"ISC"
] | 2 | 2018-09-13T15:43:23.000Z | 2020-07-15T01:59:04.000Z | higan/ws/system/system.hpp | libretro-mirrors/higan | 8617711ea2c201a33442266945dc7ed186e9d695 | [
"Intel",
"ISC"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | higan/ws/system/system.hpp | libretro-mirrors/higan | 8617711ea2c201a33442266945dc7ed186e9d695 | [
"Intel",
"ISC"
] | null | null | null | struct System : IO {
enum class Model : uint { WonderSwan, WonderSwanColor, SwanCrystal, PocketChallengeV2 };
auto loaded() const -> bool { return _loaded; }
auto model() const -> Model { return _model; }
auto color() const -> bool { return r.color; }
auto planar() const -> bool { return r.format == 0; }
auto packed() const -> bool { return r.format == 1; }
auto depth() const -> bool { return r.color && r.depth == 1; }
auto init() -> void;
auto term() -> void;
auto load(Emulator::Interface*, Model) -> bool;
auto save() -> void;
auto unload() -> void;
auto power() -> void;
auto run() -> void;
auto runToSave() -> void;
auto pollKeypad() -> void;
//io.cpp
auto portRead(uint16 addr) -> uint8 override;
auto portWrite(uint16 addr, uint8 data) -> void override;
//video.cpp
auto configureVideoPalette() -> void;
auto configureVideoEffects() -> void;
//serialization.cpp
auto serializeInit() -> void;
auto serialize() -> serializer;
auto unserialize(serializer&) -> bool;
auto serializeAll(serializer&) -> void;
auto serialize(serializer&) -> void;
struct Information {
string manifest;
} information;
EEPROM eeprom;
struct Keypad {
bool y1, y2, y3, y4;
bool x1, x2, x3, x4;
bool b, a, start;
bool rotate;
} keypad;
private:
Emulator::Interface* interface = nullptr;
struct Registers {
//$0060 DISP_MODE
uint5 unknown;
uint1 format;
uint1 depth;
uint1 color;
} r;
bool _loaded = false;
Model _model = Model::WonderSwan;
uint _serializeSize = 0;
};
extern System system;
auto Model::WonderSwan() -> bool { return system.model() == System::Model::WonderSwan; }
auto Model::WonderSwanColor() -> bool { return system.model() == System::Model::WonderSwanColor; }
auto Model::SwanCrystal() -> bool { return system.model() == System::Model::SwanCrystal; }
auto Model::PocketChallengeV2() -> bool { return system.model() == System::Model::PocketChallengeV2; }
| 27.971831 | 102 | 0.653575 | libretro-mirrors |
136f22c19a7bea3cfa5b49f5ed831f5f77602776 | 57,555 | cpp | C++ | bfcp/server/conference.cpp | Issic47/bfcp | b0e78534f58820610df6133dc4043f902c001173 | [
"BSD-3-Clause"
] | 10 | 2015-08-05T06:07:41.000Z | 2020-12-17T04:28:48.000Z | bfcp/server/conference.cpp | Issic47/bfcp | b0e78534f58820610df6133dc4043f902c001173 | [
"BSD-3-Clause"
] | null | null | null | bfcp/server/conference.cpp | Issic47/bfcp | b0e78534f58820610df6133dc4043f902c001173 | [
"BSD-3-Clause"
] | 8 | 2015-11-27T13:22:30.000Z | 2021-01-28T07:20:50.000Z | #include <bfcp/server/conference.h>
#include <boost/bind.hpp>
#include <muduo/base/Logging.h>
#include <tinyxml2.h>
#include <bfcp/common/bfcp_conn.h>
#include <bfcp/server/floor.h>
#include <bfcp/server/user.h>
#include <bfcp/server/floor_request_node.h>
namespace bfcp
{
namespace detail
{
class FloorRequestCmp
{
public:
FloorRequestCmp(uint16_t floorRequestID)
: floorRequestID_(floorRequestID)
{}
bool operator()(const FloorRequestNodePtr &floorRequest)
{
return floorRequest->getFloorRequestID() == floorRequestID_;
}
private:
uint16_t floorRequestID_;
};
const bfcp_prim SUPPORTED_PRIMS[] =
{
BFCP_FLOOR_REQUEST,
BFCP_FLOOR_RELEASE,
BFCP_FLOOR_REQUEST_QUERY,
BFCP_FLOOR_REQUEST_STATUS,
BFCP_USER_QUERY,
BFCP_USER_STATUS,
BFCP_FLOOR_QUERY,
BFCP_FLOOR_STATUS ,
BFCP_CHAIR_ACTION,
BFCP_CHAIR_ACTION_ACK,
BFCP_HELLO,
BFCP_HELLO_ACK,
BFCP_ERROR,
BFCP_FLOOR_REQ_STATUS_ACK,
BFCP_FLOOR_STATUS_ACK,
BFCP_GOODBYE,
BFCP_GOODBYE_ACK,
};
const bfcp_attrib SUPPORTED_ATTRS[] =
{
BFCP_BENEFICIARY_ID,
BFCP_FLOOR_ID,
BFCP_FLOOR_REQUEST_ID,
BFCP_PRIORITY,
BFCP_REQUEST_STATUS,
BFCP_ERROR_CODE,
BFCP_ERROR_INFO,
BFCP_PART_PROV_INFO,
BFCP_STATUS_INFO,
BFCP_SUPPORTED_ATTRS,
BFCP_SUPPORTED_PRIMS,
BFCP_USER_DISP_NAME,
BFCP_USER_URI,
/* grouped: */
BFCP_BENEFICIARY_INFO,
BFCP_FLOOR_REQ_INFO,
BFCP_REQUESTED_BY_INFO,
BFCP_FLOOR_REQ_STATUS,
BFCP_OVERALL_REQ_STATUS,
};
} // namespace detail
const char * toString( AcceptPolicy policy )
{
switch (policy)
{
case AcceptPolicy::kAutoAccept:
return "AutoAccept";
case AcceptPolicy::kAutoDeny:
return "AutoDeny";
default:
return "???";
}
}
Conference::Conference(muduo::net::EventLoop *loop,
const BfcpConnectionPtr &connection,
uint32_t conferenceID,
const ConferenceConfig &config)
: loop_(CHECK_NOTNULL(loop)),
connection_(connection),
conferenceID_(conferenceID),
nextFloorRequestID_(0),
maxFloorRequest_(config.maxFloorRequest),
timeForChairAction_(config.timeForChairAction),
acceptPolicy_(config.acceptPolicy),
userObsoletedTime_(config.userObsoletedTime)
{
LOG_TRACE << "Conference::Conference [" << conferenceID << "] constructing";
assert(connection_);
initRequestHandlers();
}
void Conference::initRequestHandlers()
{
requestHandler_.insert(std::make_pair(
BFCP_FLOOR_REQUEST,
boost::bind(&Conference::handleFloorRequest, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_FLOOR_RELEASE,
boost::bind(&Conference::handleFloorRelease, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_FLOOR_REQUEST_QUERY,
boost::bind(&Conference::handleFloorRequestQuery, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_USER_QUERY,
boost::bind(&Conference::handleUserQuery, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_FLOOR_QUERY,
boost::bind(&Conference::handleFloorQuery, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_CHAIR_ACTION,
boost::bind(&Conference::handleChairAction, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_HELLO,
boost::bind(&Conference::handleHello, this, _1)));
requestHandler_.insert(std::make_pair(
BFCP_GOODBYE,
boost::bind(&Conference::handleGoodbye, this, _1)));
}
Conference::~Conference()
{
LOG_TRACE << "Conference::~Conference [" << conferenceID_ << "] destructing";
}
bfcp::ControlError Conference::set(const ConferenceConfig &config)
{
LOG_TRACE << "{conferencID:" << conferenceID_
<< ", config: {maxFloorRequest: " << config.maxFloorRequest
<< ", acceptPolicy: " << toString(config.acceptPolicy)
<< ", timeForChairAction: " << config.timeForChairAction << "}}";
maxFloorRequest_ = config.maxFloorRequest;
acceptPolicy_ = config.acceptPolicy;
timeForChairAction_ = config.timeForChairAction;
return ControlError::kNoError;
}
ControlError Conference::setMaxFloorRequest( uint16_t maxFloorRequest )
{
LOG_TRACE << "Set max floor request " << maxFloorRequest
<< " in Conference " << conferenceID_;
maxFloorRequest_ = maxFloorRequest;
return ControlError::kNoError;
}
ControlError Conference::modifyFloor(
uint16_t floorID, const FloorConfig &config)
{
LOG_TRACE << "{conferencID:" << conferenceID_
<< ", floorID:" << floorID
<< ", config:{maxGrantedNum:" << config.maxGrantedNum
<< ", maxHoldingTime:" << config.maxHoldingTime << "}}";
auto floor = findFloor(floorID);
if (!floor)
{
LOG_ERROR << "Floor " << floorID
<< " not exist in Conference " << conferenceID_;
return ControlError::kFloorNotExist;
}
floor->setMaxGrantedCount(config.maxGrantedNum);
floor->setMaxHoldingTime(config.maxHoldingTime);
return ControlError::kNoError;
}
ControlError Conference::setAcceptPolicy(
AcceptPolicy policy, double timeForChairAction)
{
LOG_TRACE << "Set accept policy " << toString(policy)
<< " and chair action time to " << timeForChairAction
<< "s in Conference " << conferenceID_;
timeForChairAction_ = timeForChairAction;
acceptPolicy_ = policy;
return ControlError::kNoError;
}
ControlError Conference::addUser(const UserInfoParam &user)
{
LOG_TRACE << "Add User " << user.id << " to Conference " << conferenceID_;
ControlError err = ControlError::kNoError;
auto lb = users_.lower_bound(user.id);
if (lb != users_.end() && !users_.key_comp()(user.id, (*lb).first))
{
LOG_ERROR << "User " << user.id
<< " already exist in Conference " << conferenceID_;
err = ControlError::kUserAlreadyExist;
}
else
{
auto res = users_.emplace_hint(
lb,
user.id,
boost::make_shared<User>(user.id, user.username, user.useruri));
// FIXME: check if insert success
(void)(res);
}
return err;
}
ControlError Conference::removeUser( uint16_t userID )
{
LOG_TRACE << "Remove User " << userID
<< " from Conference " << conferenceID_;
auto user = findUser(userID);
if (!user)
{
LOG_ERROR << "User " << userID
<< " not exist in Conference " << conferenceID_;
return ControlError::kUserNotExist;
}
// remove floor query
for (auto floor : floors_)
{
floor.second->removeQueryUser(userID);
}
// checks if the user is chair of any floors
for (auto floor : floors_)
{
if (floor.second->isAssigned() && floor.second->getChairID() == userID)
{
removeChair(floor.first);
}
}
cancelFloorRequestsFromPendingByUserID(userID);
cancelFloorRequestsFromAcceptedByUserID(userID);
releaseFloorRequestsFromGrantedByUserID(userID);
users_.erase(userID);
tryToGrantFloorRequestsWithAllFloors();
return ControlError::kNoError;
}
void Conference::cancelFloorRequestsFromPendingByUserID(uint16_t userID)
{
for (auto it = pending_.begin(); it != pending_.end();)
{
auto floorRequest = *it;
if (floorRequest->getUserID() == userID ||
(floorRequest->hasBeneficiary() &&
floorRequest->getBeneficiaryID() == userID))
{
LOG_INFO << "Cancel FloorRequest " << floorRequest->getFloorRequestID()
<< " from Pending Queue in Conference " << conferenceID_;
it = pending_.erase(it);
loop_->cancel(floorRequest->getExpiredTimer()); // cancel the chair action timer
floorRequest->setOverallStatus(BFCP_CANCELLED);
floorRequest->removeQueryUser(userID);
revokeFloorsFromFloorRequest(floorRequest);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
void Conference::cancelFloorRequestsFromAcceptedByUserID( uint16_t userID )
{
for (auto it = accepted_.begin(); it != accepted_.end();)
{
auto floorRequest = *it;
if (floorRequest->getUserID() == userID ||
(floorRequest->hasBeneficiary() &&
floorRequest->getBeneficiaryID() == userID))
{
LOG_INFO << "Cancel FloorRequest " << floorRequest->getFloorRequestID()
<< " from Accepted Queue in Conference " << conferenceID_;
it = accepted_.erase(it);
floorRequest->setOverallStatus(BFCP_CANCELLED);
floorRequest->removeQueryUser(userID);
floorRequest->setQueuePosition(0);
revokeFloorsFromFloorRequest(floorRequest);
updateQueuePosition(accepted_);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
void Conference::releaseFloorRequestsFromGrantedByUserID( uint16_t userID )
{
for (auto it = granted_.begin(); it != granted_.end();)
{
auto floorRequest = *it;
if (floorRequest->getUserID() == userID ||
(floorRequest->hasBeneficiary() &&
floorRequest->getBeneficiaryID() == userID))
{
LOG_INFO << "Release FloorRequest " << floorRequest->getFloorRequestID()
<< " from Granted Queue in Conference " << conferenceID_;
it = granted_.erase(it);
loop_->cancel(floorRequest->getExpiredTimer()); // cancel the holding timer
floorRequest->setOverallStatus(BFCP_RELEASED);
floorRequest->removeQueryUser(userID);
revokeFloorsFromFloorRequest(floorRequest);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
ControlError Conference::addFloor(uint16_t floorID, const FloorConfig &config)
{
LOG_TRACE << "Add Floor " << floorID << " to Conference " << conferenceID_;
ControlError err = ControlError::kNoError;
auto lb = floors_.lower_bound(floorID);
if (lb != floors_.end() && !floors_.key_comp()(floorID, (*lb).first))
{ // This floor already exists
LOG_ERROR << "Floor " << floorID
<< " already exist in Conference " << conferenceID_;
err = ControlError::kFloorAlreadyExist;
}
else
{
auto res = floors_.emplace_hint(
lb,
floorID,
boost::make_shared<Floor>(floorID, config.maxGrantedNum, config.maxHoldingTime));
// FIXME: check if insert success
(void)(res);
}
return err;
}
ControlError Conference::removeFloor( uint16_t floorID )
{
LOG_TRACE << "Remove Floor " << floorID
<< " from Conference " << conferenceID_;
auto floor = findFloor(floorID);
if (!floor)
{
LOG_ERROR << "Floor " << floorID
<< " not exist in Conference " << conferenceID_;
return ControlError::kFloorNotExist;
}
cancelFloorRequestsFromPendingByFloorID(floorID);
cancelFloorRequestsFromAcceptedByFloorID(floorID);
releaseFloorRequestsFromGrantedByFloorID(floorID);
floors_.erase(floorID);
tryToGrantFloorRequestsWithAllFloors();
return ControlError::kNoError;
}
void Conference::cancelFloorRequestsFromPendingByFloorID(uint16_t floorID)
{
for (auto it = pending_.begin(); it != pending_.end();)
{
if ((*it)->findFloor(floorID))
{
LOG_INFO << "Cancel FloorRequest " << (*it)->getFloorRequestID()
<< " from Pending Queue in Conference " << conferenceID_;
auto floorRequest = *it;
loop_->cancel(floorRequest->getExpiredTimer()); // cancel the chair action timer
floorRequest->setOverallStatus(BFCP_CANCELLED);
it = pending_.erase(it);
revokeFloorsFromFloorRequest(floorRequest);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
void Conference::cancelFloorRequestsFromAcceptedByFloorID(uint16_t floorID)
{
for (auto it = accepted_.begin(); it != accepted_.end();)
{
if ((*it)->findFloor(floorID))
{
LOG_INFO << "Cancel FloorRequest " << (*it)->getFloorRequestID()
<< " from Accepted Queue in Conference " << conferenceID_;
auto floorRequest = *it;
floorRequest->setOverallStatus(BFCP_CANCELLED);
it = accepted_.erase(it);
revokeFloorsFromFloorRequest(floorRequest);
updateQueuePosition(accepted_);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
void Conference::releaseFloorRequestsFromGrantedByFloorID(uint16_t floorID)
{
for (auto it = granted_.begin(); it != granted_.end();)
{
if ((*it)->findFloor(floorID))
{
LOG_INFO << "Release FloorRequest " << (*it)->getFloorRequestID()
<< " from Granted Queue in Conference " << conferenceID_;
auto floorRequest = *it;
floorRequest->setOverallStatus(BFCP_RELEASED);
it = granted_.erase(it);
revokeFloorsFromFloorRequest(floorRequest);
notifyFloorAndRequestInfo(floorRequest);
continue;
}
++it;
}
}
ControlError Conference::setChair( uint16_t floorID, uint16_t userID )
{
LOG_TRACE << "Set Chair " << userID << " of Floor " << floorID
<< " in Conference " << conferenceID_;
ControlError err = ControlError::kNoError;
do
{
auto user = findUser(userID);
if (!user)
{
LOG_ERROR << "User " << userID
<< " not exist in Conference " << conferenceID_;
err = ControlError::kUserNotExist;
break;
}
auto floor = findFloor(floorID);
if (!floor)
{
LOG_ERROR << "Floor " << floorID
<< " not exist in Conference " << conferenceID_;
err = ControlError::kFloorNotExist;
break;
}
floor->unassigned();
floor->assignedToChair(userID);
} while (false);
return err;
}
UserPtr Conference::findUser( uint16_t userID )
{
auto it = users_.find(userID);
return it != users_.end() ? (*it).second : nullptr;
}
bfcp::FloorPtr Conference::findFloor( uint16_t floorID )
{
auto it = floors_.find(floorID);
return it != floors_.end() ? (*it).second : nullptr;
}
ControlError Conference::removeChair( uint16_t floorID )
{
LOG_TRACE << "Remove Chair of Floor " << floorID
<< " in Conference " << conferenceID_;
ControlError err = ControlError::kNoError;
do
{
auto floor = findFloor(floorID);
if (!floor)
{
LOG_ERROR << "Floor " << floorID
<< " not exist in Conference " << conferenceID_;
err = ControlError::kFloorNotExist;
break;
}
if (!floor->isAssigned())
{
err = ControlError::kChairNotExist;
break;
}
assert(findUser(floor->getChairID()));
if (acceptPolicy_ == AcceptPolicy::kAutoDeny)
{
cancelFloorRequestsFromPendingByFloorID(floorID);
}
else if (acceptPolicy_ == AcceptPolicy::kAutoAccept)
{
if (tryToAcceptFloorRequestsWithFloor(floor))
{
tryToGrantFloorRequestsWithFloor(floor);
}
}
floor->unassigned();
} while (false);
return err;
}
bool Conference::tryToAcceptFloorRequestsWithFloor(FloorPtr &floor)
{
if (!floor) return false;
uint16_t floorID = floor->getFloorID();
bool hasAcceptFloor = false;
for (auto it = pending_.begin(); it != pending_.end();)
{
auto floorRequest = *it;
auto floorNode = floorRequest->findFloor(floorID);
if (floorNode && floorNode->getStatus() != BFCP_ACCEPTED)
{
floorNode->setStatus(BFCP_ACCEPTED);
floorNode->setStatusInfo(nullptr);
hasAcceptFloor = true;
if (!floorRequest->isAllFloorStatus(BFCP_ACCEPTED))
{
notifyWithFloorRequestStatus(floorRequest);
}
else // all floor status in the floor request is accepted
{
// remove the floor request from pending queue
it = pending_.erase(it);
loop_->cancel(floorRequest->getExpiredTimer()); // cancel the chair action timer
insertFloorRequestToAcceptedQueue(floorRequest);
continue;
}
}
++it;
}
return hasAcceptFloor;
}
void Conference::insertFloorRequestToPendingQueue(
FloorRequestNodePtr &floorRequest)
{
LOG_INFO << "Insert FloorRequest " << floorRequest->getFloorRequestID()
<< " to Pending Queue in Conference " << conferenceID_;
assert(floorRequest->isAnyFloorStatus(BFCP_PENDING));
floorRequest->setOverallStatus(BFCP_PENDING);
floorRequest->setQueuePosition(0);
insertFloorRequestToQueue(pending_, floorRequest);
notifyFloorAndRequestInfo(floorRequest);
}
void Conference::insertFloorRequestToAcceptedQueue(
FloorRequestNodePtr &floorRequest)
{
LOG_INFO << "Insert FloorRequest " << floorRequest->getFloorRequestID()
<< "to Accepted Queue in Conference " << conferenceID_;
assert(floorRequest->isAllFloorStatus(BFCP_ACCEPTED));
floorRequest->setOverallStatus(BFCP_ACCEPTED);
floorRequest->setPrioriy(BFCP_PRIO_LOWEST);
insertFloorRequestToQueue(accepted_, floorRequest);
updateQueuePosition(accepted_);
notifyFloorAndRequestInfo(floorRequest);
}
void Conference::insertFloorRequestToGrantedQueue(
FloorRequestNodePtr &floorRequest)
{
LOG_INFO << "Insert FloorRequest " << floorRequest->getFloorRequestID()
<< " to Granted Queue in Conference " << conferenceID_;
assert(floorRequest->isAllFloorStatus(BFCP_GRANTED));
floorRequest->setOverallStatus(BFCP_GRANTED);
floorRequest->setQueuePosition(0);
floorRequest->setPrioriy(BFCP_PRIO_LOWEST);
insertFloorRequestToQueue(granted_, floorRequest);
notifyFloorAndRequestInfo(floorRequest);
// set holding timer
double minHoldingTime = -1.0;
for (auto &floorNode : floorRequest->getFloorNodeList())
{
auto floor = findFloor(floorNode.getFloorID());
assert(floor);
if (floor->getMaxHoldingTime() > 0.0)
{
double holdingTime = floor->getMaxHoldingTime();
minHoldingTime = minHoldingTime < 0.0 ?
holdingTime : (std::min)(minHoldingTime, holdingTime);
}
}
if (minHoldingTime > 0.0)
{
setFloorRequestExpired(
floorRequest, minHoldingTime, holdingTimeoutCallback_);
}
}
void Conference::insertFloorRequestToQueue(
FloorRequestQueue &queue, FloorRequestNodePtr &floorRequest)
{
// NOTE: The queue stores floor requests from low priority to high priority
// If queue position is not 0, we set the one the chair stated
auto it = queue.begin();
if (floorRequest->getQueuePosition() != 0 && it != queue.end())
{
int pos = 1;
auto rit = queue.rbegin();
while (pos < floorRequest->getQueuePosition() &&
rit != queue.rend())
{
++pos;
++rit;
}
if (pos == floorRequest->getQueuePosition())
{
it = rit.base();
}
else
{
it = queue.begin();
}
floorRequest->setPrioriy(BFCP_PRIO_LOWEST);
}
floorRequest->setQueuePosition(0);
while (it != queue.end() && (*it)->getPriority() < floorRequest->getPriority()) {
++it;
}
queue.insert(it, floorRequest);
}
void Conference::updateQueuePosition( FloorRequestQueue &queue )
{
// NOTE: queue position starts from 1
uint8_t qpos = 1;
for (auto it = queue.rbegin(); it != queue.rend(); ++it)
{
(*it)->setQueuePosition(qpos++);
}
}
void Conference::onTimeoutForHoldingFloors( uint16_t floorRequestID )
{
LOG_TRACE << "FloorRequest " << floorRequestID
<< " is expired in Conference " << conferenceID_;
auto floorRequest = findFloorRequest(granted_, floorRequestID);
if (!floorRequest) return;
LOG_INFO << "Revoke FloorRequest " << floorRequestID
<< " from Granted Queue in Conference " << conferenceID_;
granted_.remove(floorRequest);
revokeFloorsFromFloorRequest(floorRequest);
for (auto &floorNode : floorRequest->getFloorNodeList())
{
floorNode.setStatus(BFCP_REVOKED);
}
floorRequest->setStatusInfo("Timeout for holding floor(s).");
floorRequest->setOverallStatus(BFCP_REVOKED);
notifyFloorAndRequestInfo(floorRequest);
tryToGrantFloorRequestsWithAllFloors();
}
bool Conference::tryToGrantFloorRequestsWithAllFloors()
{
bool hasGrantFloor = false;
for (auto &floor : floors_)
{
if (tryToGrantFloorRequestsWithFloor(floor.second))
{
hasGrantFloor = true;
}
}
return hasGrantFloor;
}
bool Conference::tryToGrantFloorRequestsWithFloor( FloorPtr &floor )
{
if (!floor) return false;
bool hasGrantFloor = false;
// NOTE: floor request store floor requests from low priority to high priority
for (auto it = accepted_.rbegin(); it != accepted_.rend();)
{
if (!floor->isFreeToGrant()) break;
if (tryToGrantFloor(*it, floor))
{
hasGrantFloor = true;
if ((*it)->isAllFloorStatus(BFCP_GRANTED))
{
auto floorRequest = *it;
// remove the floor request from accepted queue
it = FloorRequestQueue::reverse_iterator(
accepted_.erase(std::next(it).base()));
// move the floor request to granted queue
insertFloorRequestToGrantedQueue(floorRequest);
continue;
}
}
++it;
}
return hasGrantFloor;
}
bool Conference::tryToGrantFloor(FloorRequestNodePtr &floorRequest,
FloorPtr &floor)
{
if (floor && floor->isFreeToGrant())
{
uint16_t floorID = floor->getFloorID();
auto floorNode = floorRequest->findFloor(floorID);
if (floorNode && floorNode->getStatus() != BFCP_GRANTED)
{
bool res = floor->tryToGrant();
(void)(res);
assert(res);
floorNode->setStatus(BFCP_GRANTED);
floorNode->setStatusInfo(nullptr);
return true;
}
}
return false;
}
void Conference::notifyFloorAndRequestInfo(
const FloorRequestNodePtr &floorRequest)
{
for (auto &floorNode : floorRequest->getFloorNodeList())
{
notifyWithFloorStatus(floorNode.getFloorID());
}
notifyWithFloorRequestStatus(floorRequest);
}
void Conference::notifyWithFloorStatus( uint16_t floorID )
{
auto floor = findFloor(floorID);
if (!floor) return;
BasicRequestParam basicParam;
basicParam.conferenceID = conferenceID_;
auto floorStatusParam = getFloorStatusParam(floorID);
// make the chair of the floor to be notified
if (floor->isAssigned())
{
floor->addQueryUser(floor->getChairID());
}
// notify all query users about the floor status
for (auto userID : floor->getQueryUsers())
{
auto user = findUser(userID);
if (user && isUserAvailable(user))
{
basicParam.userID = userID;
basicParam.dst = user->getAddr();
assert(clientReponseCallback_);
basicParam.cb = boost::bind(clientReponseCallback_,
conferenceID_, BFCP_FLOOR_STATUS_ACK, userID, _1, _2);
user->runSendMessageTask(
boost::bind(&BfcpConnection::notifyFloorStatus,
connection_, basicParam, floorStatusParam));
}
}
}
void Conference::notifyWithFloorRequestStatus(
const FloorRequestNodePtr &floorRequest)
{
const auto &queryUsers = floorRequest->getFloorRequestQueryUsers();
BasicRequestParam param;
param.conferenceID = conferenceID_;
auto frqInfo = floorRequest->toFloorRequestInfoParam(users_);
for (auto userID : queryUsers)
{
auto user = findUser(userID);
if (user && isUserAvailable(user))
{
param.userID = userID;
param.dst = user->getAddr();
assert(clientReponseCallback_);
param.cb = boost::bind(clientReponseCallback_,
conferenceID_, BFCP_FLOOR_REQ_STATUS_ACK, userID, _1, _2);
user->runSendMessageTask(
boost::bind(&BfcpConnection::notifyFloorRequestStatus,
connection_, param, frqInfo));
}
}
}
void Conference::onNewRequest( const BfcpMsgPtr &msg )
{
LOG_TRACE << "Conference received new request " << msg->toString();
assert(msg->valid());
assert(!msg->isResponse());
assert(msg->getConferenceID() == conferenceID_);
if (checkUnknownAttrs(msg) && checkUserID(msg, msg->getUserID()))
{
auto user = findUser(msg->getUserID());
assert(user);
if (!isUserAvailable(user))
{
user->setAvailable(true);
user->setAddr(msg->getSrc());
}
user->setActiveTime(msg->getReceivedTime());
bfcp_prim prim = msg->primitive();
auto it = requestHandler_.find(prim);
if (it != requestHandler_.end())
{
(*it).second(msg);
}
else
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"Unknown primitive %s(%i) as request", bfcp_prim_name(prim), prim);
replyWithError(msg, BFCP_UNKNOWN_PRIM, errorInfo);
}
}
}
bool Conference::isUserAvailable( const UserPtr &user ) const
{
if (!user->isAvailable()) return false;
if (userObsoletedTime_ > 0.0)
{
muduo::Timestamp now = muduo::Timestamp::now();
double livingTime = muduo::timeDifference(now, user->getActiveTime());
return livingTime < userObsoletedTime_;
}
return true;
}
bool Conference::checkUnknownAttrs( const BfcpMsgPtr &msg )
{
auto &unknownAttrs = msg->getUnknownAttrs();
if (unknownAttrs.typec > 0)
{
bfcp_errcode_t errcode;
errcode.code = BFCP_UNKNOWN_MAND_ATTR;
errcode.details = const_cast<uint8_t*>(unknownAttrs.typev);
errcode.len = unknownAttrs.typec;
ErrorParam param;
param.setErrorCode(errcode);
connection_->replyWithError(msg, param);
return false;
}
return true;
}
bool Conference::checkUserID( const BfcpMsgPtr &msg, uint16_t userID )
{
if (!findUser(userID))
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"User %hu does not exist in Conference %u",
userID, msg->getConferenceID());
replyWithError(msg, BFCP_USER_NOT_EXIST, errorInfo);
return false;
}
return true;
}
void Conference::replyWithError(const BfcpMsgPtr &msg,
bfcp_err err,
const char *errInfo)
{
ErrorParam param;
param.errorCode.code = err;
param.setErrorInfo(errInfo);
connection_->replyWithError(msg, param);
}
void Conference::handleHello( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_HELLO);
HelloAckParam param;
// set supported primitives
const size_t primCount =
sizeof(detail::SUPPORTED_PRIMS) / sizeof(detail::SUPPORTED_PRIMS[0]);
param.primitives.reserve(primCount);
param.primitives.assign(
detail::SUPPORTED_PRIMS, detail::SUPPORTED_PRIMS + primCount);
// set supported attributes
const size_t attrCount =
sizeof(detail::SUPPORTED_ATTRS) / sizeof(detail::SUPPORTED_ATTRS[0]);
param.attributes.reserve(attrCount);
param.attributes.assign(
detail::SUPPORTED_ATTRS, detail::SUPPORTED_ATTRS + attrCount);
connection_->replyWithHelloAck(msg, param);
}
void Conference::handleGoodbye( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_GOODBYE);
connection_->replyWithGoodbyeAck(msg);
auto user = findUser(msg->getUserID());
assert(user);
user->setAvailable(false);
user->clearAllSendMessageTasks();
}
void Conference::handleFloorRequest( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_FLOOR_REQUEST);
FloorRequestParam param;
if (!parseFloorRequestParam(param, msg)) return;
auto user = findUser(msg->getUserID());
assert(user);
auto beneficiaryUser = user;
if (param.hasBeneficiaryID)
{
if (!checkUserID(msg, param.beneficiaryID)) return;
beneficiaryUser = findUser(param.beneficiaryID);
assert(beneficiaryUser);
}
if (!checkFloorIDs(msg, param.floorIDs)) return;
FloorRequestNodePtr newFloorRequest =
boost::make_shared<FloorRequestNode>(
nextFloorRequestID_++, msg->getUserID(), param);
for (auto &floorNode : newFloorRequest->getFloorNodeList())
{
uint16_t floorID = floorNode.getFloorID();
auto floor = findFloor(floorID);
assert(floor);
if (!floor->isAssigned() && acceptPolicy_ == AcceptPolicy::kAutoDeny)
{
floorNode.setStatus(BFCP_DENIED);
newFloorRequest->setOverallStatus(BFCP_DENIED);
replyWithFloorRequestStatus(msg, newFloorRequest);
return;
}
// NOTE: must check all request counts before adding request of floors
uint16_t requestCount = beneficiaryUser->getRequestCountOfFloor(floorID);
if (maxFloorRequest_ <= requestCount)
{
char errorInfo[200];
snprintf(errorInfo, sizeof errorInfo,
"User %hu has already reached "
"the maximum allowed number of requests (%hu)"
"for the same floor in Conference %u",
beneficiaryUser->getUserID(),
requestCount,
conferenceID_);
replyWithError(msg, BFCP_MAX_FLOOR_REQ_REACHED, errorInfo);
return;
}
}
// add request of floors
for (auto &floorNode : newFloorRequest->getFloorNodeList())
{
beneficiaryUser->addOneRequestOfFloor(floorNode.getFloorID());
}
// insert to the pending queue
insertFloorRequestToPendingQueue(newFloorRequest);
replyWithFloorRequestStatus(msg, newFloorRequest);
newFloorRequest->addQueryUser(msg->getUserID());
// handle chair part
bool needChairAction = false;
for (auto &floorNode : newFloorRequest->getFloorNodeList())
{
auto floor = findFloor(floorNode.getFloorID());
assert(floor);
if (!floor->isAssigned())
{
assert(acceptPolicy_ == AcceptPolicy::kAutoAccept);
floorNode.setStatus(BFCP_ACCEPTED);
}
else
{
uint16_t chairID = floor->getChairID();
assert(findUser(chairID));
(void)(chairID);
needChairAction = true;
}
}
if (needChairAction)
{
// start timer for chair action
if (timeForChairAction_ > 0.0)
{
setFloorRequestExpired(
newFloorRequest, timeForChairAction_, chairActionTimeoutCallback_);
}
}
// check if the floor request is accepted
if (newFloorRequest->isAllFloorStatus(BFCP_ACCEPTED))
{
// put the floor request to the accepted queue
pending_.remove(newFloorRequest);
insertFloorRequestToAcceptedQueue(newFloorRequest);
tryToGrantFloorRequestWithAllFloors(newFloorRequest);
}
}
bool Conference::parseFloorRequestParam(FloorRequestParam ¶m, const BfcpMsgPtr &msg)
{
param.floorIDs = msg->getFloorIDs();
if (param.floorIDs.empty())
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing FLOOR-ID attribute");
return false;
}
auto attr = msg->findAttribute(BFCP_BENEFICIARY_ID);
if (attr)
{
BfcpAttr beneficiaryIDAttr(*attr);
param.hasBeneficiaryID = true;
param.beneficiaryID = beneficiaryIDAttr.getBeneficiaryID();
}
attr = msg->findAttribute(BFCP_PART_PROV_INFO);
if (attr)
{
BfcpAttr partProvInfo(*attr);
detail::setString(param.pInfo, partProvInfo.getParticipantProvidedInfo());
}
attr = msg->findAttribute(BFCP_PRIORITY);
if (attr)
{
BfcpAttr priorityAttr(*attr);
param.priority = priorityAttr.getPriority();
}
return true;
}
bool Conference::isChair( uint16_t userID ) const
{
for (auto floor : floors_)
{
if (floor.second->isAssigned() &&
floor.second->getChairID() == userID)
{
return true;
}
}
return false;
}
bool Conference::checkFloorIDs( const BfcpMsgPtr &msg, const bfcp_floor_id_list &floorIDs )
{
for (auto floorID : floorIDs)
{
if (!checkFloorID(msg, floorID))
{
return false;
}
}
return true;
}
bool Conference::checkFloorID( const BfcpMsgPtr &msg, uint16_t floorID )
{
if (!findFloor(floorID))
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"Floor %hu does not exist in Conference %u",
floorID, conferenceID_);
replyWithError(msg, BFCP_INVALID_FLOOR_ID, errorInfo);
return false;
}
return true;
}
void Conference::replyWithFloorRequestStatus(
const BfcpMsgPtr &msg, FloorRequestNodePtr &floorRequest)
{
FloorRequestInfoParam param =
floorRequest->toFloorRequestInfoParam(users_);
connection_->replyWithFloorRequestStatus(msg, param);
}
void Conference::setFloorRequestExpired(FloorRequestNodePtr &floorRequest,
double expiredTime,
const FloorRequestExpiredCallback &cb)
{
assert(cb);
assert(expiredTime > 0.0);
uint16_t floorRequestID = floorRequest->getFloorRequestID();
muduo::net::TimerId timerId = loop_->runAfter(
expiredTime,
boost::bind(cb, conferenceID_, floorRequestID));
floorRequest->setExpiredTimer(timerId);
}
bool Conference::tryToGrantFloorRequestWithAllFloors(
FloorRequestNodePtr &floorRequest)
{
assert(!floorRequest->isAllFloorStatus(BFCP_GRANTED));
bool hasGrantedFloor = false;
for (auto &floorNode : floorRequest->getFloorNodeList())
{
auto floor = findFloor(floorNode.getFloorID());
if (floorNode.getStatus() != BFCP_GRANTED && floor->isFreeToGrant())
{
bool res = floor->tryToGrant();
(void)(res);
assert(res);
floorNode.setStatus(BFCP_GRANTED);
floorNode.setStatusInfo(nullptr);
hasGrantedFloor = true;
}
}
if (hasGrantedFloor && floorRequest->isAllFloorStatus(BFCP_GRANTED))
{
accepted_.remove(floorRequest);
updateQueuePosition(accepted_);
insertFloorRequestToGrantedQueue(floorRequest);
return true;
}
return false;
}
void Conference::onTimeoutForChairAction( uint16_t floorRequestID )
{
LOG_TRACE << "FloorRequest " << floorRequestID
<< " is expired in Conference " << conferenceID_;
auto floorRequest = findFloorRequest(pending_, floorRequestID);
if (!floorRequest) return;
for (auto &floorNode : floorRequest->getFloorNodeList())
{
if (floorNode.getStatus() == BFCP_PENDING)
floorNode.setStatus(BFCP_CANCELLED);
}
LOG_INFO << "Cancel FloorRequest " << floorRequestID
<< " from Pending Queue in Conference " << conferenceID_;
pending_.remove(floorRequest);
revokeFloorsFromFloorRequest(floorRequest);
floorRequest->setOverallStatus(BFCP_CANCELLED);
notifyFloorAndRequestInfo(floorRequest);
}
void Conference::handleFloorRelease( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_FLOOR_RELEASE);
auto attr = msg->findAttribute(BFCP_FLOOR_REQUEST_ID);
if (!attr)
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing FLOOR-REQUEST-ID attribute");
return;
}
uint16_t floorRequestID;
{
BfcpAttr floorRequestIDAttr(*attr);
floorRequestID = floorRequestIDAttr.getFloorRequestID();
}
// FIXME: reply with error BFCP_UNAUTH_OPERATION if user ID not matched?
FloorRequestNodePtr floorRequest =
removeFloorRequest(floorRequestID, msg->getUserID());
if (!floorRequest)
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"FloorRequest %hu does not exist in Conference %u",
floorRequestID, conferenceID_);
replyWithError(msg, BFCP_FLOOR_REQ_ID_NOT_EXIST, errorInfo);
return;
}
// reply the releaser about the floor request status of the release request
replyWithFloorRequestStatus(msg, floorRequest);
floorRequest->removeQueryUser(msg->getUserID());
// notify the interested users
notifyWithFloorRequestStatus(floorRequest);
if (revokeFloorsFromFloorRequest(floorRequest))
{
tryToGrantFloorRequestsWithAllFloors();
}
}
FloorRequestNodePtr Conference::removeFloorRequest(
uint16_t floorRequestID, uint16_t userID)
{
// check the pending queue
auto floorRequest =
extractFloorRequestFromQueue(pending_, floorRequestID, userID);
if (floorRequest)
{
LOG_INFO << "Cancel FloorRequest " << floorRequestID
<< " from Pending Queue in Conference " << conferenceID_;
floorRequest->setOverallStatus(BFCP_CANCELLED);
// cancel the chair action timer
loop_->cancel(floorRequest->getExpiredTimer());
return floorRequest;
}
// check the accepted queue
floorRequest =
extractFloorRequestFromQueue(accepted_, floorRequestID, userID);
if (floorRequest)
{
LOG_INFO << "Cancel FloorRequest " << floorRequestID
<< " from Accepted Queue in Conference " << conferenceID_;
floorRequest->setOverallStatus(BFCP_CANCELLED);
floorRequest->setQueuePosition(0);
updateQueuePosition(accepted_);
return floorRequest;
}
// check the granted queue
floorRequest =
extractFloorRequestFromQueue(granted_, floorRequestID, userID);
if (floorRequest)
{
LOG_INFO << "Release FloorRequest " << floorRequestID
<< " from Granted Queue in Conference " << conferenceID_;
floorRequest->setOverallStatus(BFCP_RELEASED);
// cancel the holding timer
loop_->cancel(floorRequest->getExpiredTimer());
return floorRequest;
}
return nullptr;
}
FloorRequestNodePtr Conference::extractFloorRequestFromQueue(
FloorRequestQueue &queue, uint16_t floorRequestID, uint16_t userID)
{
auto it = std::find_if(queue.begin(), queue.end(),
detail::FloorRequestCmp(floorRequestID));
if (it != queue.end() && (*it)->getUserID() == userID)
{
auto floorRequest = *it;
queue.erase(it);
return floorRequest;
}
return nullptr;
}
bool Conference::revokeFloorsFromFloorRequest(FloorRequestNodePtr &floorRequest)
{
UserPtr beneficiaryUser = floorRequest->hasBeneficiary() ?
findUser(floorRequest->getBeneficiaryID()) :
findUser(floorRequest->getUserID());
assert(beneficiaryUser);
bool hasRevokeFloor = false;
for (auto &floorNode : floorRequest->getFloorNodeList())
{
auto floor = findFloor(floorNode.getFloorID());
assert(floor);
beneficiaryUser->removeOneRequestOfFloor(floor->getFloorID());
if (floorNode.getStatus() == BFCP_GRANTED)
{
floor->revoke();
hasRevokeFloor = true;
}
}
return hasRevokeFloor;
}
void Conference::handleChairAction( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_CHAIR_ACTION);
auto attr = msg->findAttribute(BFCP_FLOOR_REQ_INFO);
if (!attr)
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing FLOOR-REQUEST-INFORMATION attribute");
return;
}
BfcpAttr floorReqInfoAttr(*attr);
auto info = floorReqInfoAttr.getFloorRequestInfo();
if (!checkFloorRequestInfo(msg, info)) return;
assert(info.oRS.requestStatus);
bfcp_reqstat status = info.oRS.requestStatus->status;
switch (status)
{
case BFCP_ACCEPTED:
acceptFloorRequest(msg, info); break;
case BFCP_DENIED:
denyFloorRequest(msg, info); break;
case BFCP_REVOKED:
revokeFloorRequest(msg, info); break;
default:
replyWithError(msg, BFCP_PARSE_ERROR,
"Only accepted, denied and revoked statuses allowed in ChairAction");
break;
}
}
bool Conference::checkFloorRequestInfo(
const BfcpMsgPtr &msg, const bfcp_floor_request_info &info)
{
if (info.fRS.empty())
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing FLOOR-REQUEST-STATUS attribute");
return false;
}
// FIXME: should have OVERALL-REQUEST-STATUS attribute
// it's easier to have OVERALL-REQUEST-STATUS to handle chair action
if (!(info.valueType & kHasOverallRequestStatus))
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing OVERALL-REQUEST-STATUS attribute");
return false;
}
if (info.oRS.floorRequestID != info.floorRequestID)
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Floor request ID in OVERALL-REQUEST-STATUS is different from "
"the one in FLOOR-REQUEST-INFORMATION");
return false;
}
if (!info.oRS.requestStatus)
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing REQUEST-STATUS in OVERALL-REQUEST-STATUS attribute");
return false;
}
// check if all the floors exist in the conference
// check if the user is allowed to do this operation
for (auto &floorReqStatus : info.fRS)
{
if (!(checkFloorID(msg, floorReqStatus.floorID) &&
checkFloorChair(msg, floorReqStatus.floorID, msg->getUserID())))
{
return false;
}
}
return true;
}
bool Conference::checkFloorChair(
const BfcpMsgPtr &msg, uint16_t floorID, uint16_t userID)
{
auto floor = findFloor(floorID);
assert(floor);
if (!floor->isAssigned() || floor->getChairID() != userID)
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"User %hu is not chair of Floor %hu in Conference %u",
userID, floorID, conferenceID_);
replyWithError(msg, BFCP_UNAUTH_OPERATION, errorInfo);
return false;
}
return true;
}
void Conference::acceptFloorRequest(
const BfcpMsgPtr &msg, const bfcp_floor_request_info &info)
{
assert(info.oRS.requestStatus);
assert(info.oRS.requestStatus->status == BFCP_ACCEPTED);
auto floorRequest = checkFloorRequestInPendingQueue(msg, info.floorRequestID);
if (!floorRequest) return;
// FIXME: check if all floors in chair action are requested by the floor request
if (!checkFloorsInFloorRequest(msg, floorRequest, info.fRS))
return;
// reply chair action ack
connection_->replyWithChairActionAck(msg);
for (auto &floorReqStatus : info.fRS)
{
FloorNode *floorNode = floorRequest->findFloor(floorReqStatus.floorID);
assert(floorNode);
// FIXME: currently ignore the REQUEST-STATUS in FLOOR-REQUEST-STATUS
floorNode->setStatus(BFCP_ACCEPTED);
floorNode->setStatusInfo(floorReqStatus.statusInfo);
}
assert(info.oRS.requestStatus);
floorRequest->setQueuePosition(info.oRS.requestStatus->qpos);
if (floorRequest->isAllFloorStatus(BFCP_ACCEPTED))
{
pending_.remove(floorRequest);
// cancel the chair action timer
loop_->cancel(floorRequest->getExpiredTimer());
insertFloorRequestToAcceptedQueue(floorRequest);
tryToGrantFloorRequestWithAllFloors(floorRequest);
}
}
void Conference::denyFloorRequest(
const BfcpMsgPtr &msg, const bfcp_floor_request_info &info)
{
assert(info.oRS.requestStatus);
assert(info.oRS.requestStatus->status == BFCP_DENIED);
auto floorRequest = checkFloorRequestInPendingQueue(msg, info.floorRequestID);
if (!floorRequest) return;
// FIXME: check if all floors in chair action are requested by the floor request
if (!checkFloorsInFloorRequest(msg, floorRequest, info.fRS))
return;
// reply chair action ack
connection_->replyWithChairActionAck(msg);
// cancel the chair action timer
loop_->cancel(floorRequest->getExpiredTimer());
pending_.remove(floorRequest);
revokeFloorsFromFloorRequest(floorRequest);
for (auto &floorReqStatus : info.fRS)
{
auto floorNode = floorRequest->findFloor(floorReqStatus.floorID);
assert(floorNode);
floorNode->setStatus(BFCP_DENIED);
floorNode->setStatusInfo(floorReqStatus.statusInfo);
}
floorRequest->setStatusInfo(info.oRS.statusInfo);
floorRequest->setOverallStatus(BFCP_DENIED);
notifyFloorAndRequestInfo(floorRequest);
}
FloorRequestNodePtr Conference::checkFloorRequestInPendingQueue(
const BfcpMsgPtr &msg, uint16_t floorRequestID)
{
auto floorRequest = findFloorRequest(pending_, floorRequestID);
if (!floorRequest)
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"Pending FloorRequest %hu does not exist in Conference %u",
floorRequestID, conferenceID_);
replyWithError(msg, BFCP_FLOOR_REQ_ID_NOT_EXIST, errorInfo);
return nullptr;
}
return floorRequest;
}
FloorRequestNodePtr Conference::findFloorRequest(
FloorRequestQueue &queue, uint16_t floorRequestID)
{
auto it = std::find_if(queue.begin(), queue.end(),
detail::FloorRequestCmp(floorRequestID));
return it != queue.end() ? *it : nullptr;
}
bool Conference::checkFloorsInFloorRequest(
const BfcpMsgPtr &msg,
FloorRequestNodePtr &floorRequest,
const bfcp_floor_request_status_list &fRS)
{
for (auto &floorReqStatus : fRS)
{
if (!floorRequest->findFloor(floorReqStatus.floorID))
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"FloorRequest %hu does not request Floor %hu",
floorRequest->getFloorRequestID(), floorReqStatus.floorID);
replyWithError(msg, BFCP_INVALID_FLOOR_ID, errorInfo);
return false;
}
}
return true;
}
void Conference::revokeFloorRequest(
const BfcpMsgPtr &msg, const bfcp_floor_request_info &info)
{
assert(info.oRS.requestStatus);
assert(info.oRS.requestStatus->status == BFCP_REVOKED);
auto floorRequest = checkFloorRequestInGrantedQueue(msg, info.floorRequestID);
if (!floorRequest) return;
// FIXME: check if all floors in chair action are requested by the floor request
if (!checkFloorsInFloorRequest(msg, floorRequest, info.fRS))
return;
// reply chair action ack
connection_->replyWithChairActionAck(msg);
granted_.remove(floorRequest);
revokeFloorsFromFloorRequest(floorRequest);
for (auto &floorReqStatus : info.fRS)
{
auto floorNode = floorRequest->findFloor(floorReqStatus.floorID);
assert(floorNode);
floorNode->setStatus(BFCP_REVOKED);
floorNode->setStatusInfo(floorReqStatus.statusInfo);
}
floorRequest->setStatusInfo(info.oRS.statusInfo);
floorRequest->setOverallStatus(BFCP_REVOKED);
notifyFloorAndRequestInfo(floorRequest);
tryToGrantFloorRequestsWithAllFloors();
}
FloorRequestNodePtr Conference::checkFloorRequestInGrantedQueue(
const BfcpMsgPtr &msg, uint16_t floorRequestID)
{
auto floorRequest = findFloorRequest(granted_, floorRequestID);
if (!floorRequest)
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"Granted FloorRequest %hu does not exist in Conference %u",
floorRequestID, conferenceID_);
replyWithError(msg, BFCP_FLOOR_REQ_ID_NOT_EXIST, errorInfo);
return nullptr;
}
return floorRequest;
}
void Conference::handleFloorRequestQuery( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_FLOOR_REQUEST_QUERY);
auto attr = msg->findAttribute(BFCP_FLOOR_REQUEST_ID);
if (!attr)
{
replyWithError(msg, BFCP_PARSE_ERROR,
"Missing FLOOR-REQUEST-ID attribute");
return;
}
BfcpAttr floorRequestIDAttr(*attr);
uint16_t floorRequestID = floorRequestIDAttr.getFloorRequestID();
// find floor request in pending, accepted and granted queue
auto floorRequest = findFloorRequest(pending_, floorRequestID);
if (!floorRequest)
{
floorRequest = findFloorRequest(accepted_, floorRequestID);
}
if (!floorRequest)
{
floorRequest = findFloorRequest(granted_, floorRequestID);
}
if (!floorRequest) // floor request not found
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"FloorRequest %hu does not exist in Conference %u",
floorRequestID, conferenceID_);
replyWithError(msg, BFCP_FLOOR_REQ_ID_NOT_EXIST, errorInfo);
return;
}
replyWithFloorRequestStatus(msg, floorRequest);
LOG_INFO << "Add Query User " << msg->getUserID()
<< " to FloorRequest " << floorRequestID
<< " in Conference " << conferenceID_;
floorRequest->addQueryUser(msg->getUserID());
}
void Conference::handleUserQuery( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_USER_QUERY);
UserStatusParam param;
UserPtr user;
auto attr = msg->findAttribute(BFCP_BENEFICIARY_ID);
if (!attr)
{
user = findUser(msg->getUserID());
}
else
{
BfcpAttr beneficiaryIDAttr(*attr);
user = findUser(beneficiaryIDAttr.getBeneficiaryID());
if (!user) // beneficiary user not found
{
char errorInfo[200];
snprintf(errorInfo, sizeof errorInfo,
"User %hu (beneficiary of the query) does not exist in Conference %u",
beneficiaryIDAttr.getBeneficiaryID(),
conferenceID_);
replyWithError(msg, BFCP_USER_NOT_EXIST, errorInfo);
return;
}
param.hasBeneficiary = true;
param.beneficiary = user->toUserInfoParam();
}
assert(user);
uint16_t userID = user->getUserID();
getFloorRequestInfoParamsByUserID(param.frqInfoList, userID, granted_);
getFloorRequestInfoParamsByUserID(param.frqInfoList, userID, accepted_);
getFloorRequestInfoParamsByUserID(param.frqInfoList, userID, pending_);
connection_->replyWithUserStatus(msg, param);
}
void Conference::getFloorRequestInfoParamsByUserID(
FloorRequestInfoParamList &frqInfoList,
uint16_t userID,
const FloorRequestQueue &queue) const
{
for (auto it = queue.rbegin(); it != queue.rend(); ++it)
{
if ((*it)->getUserID() == userID ||
((*it)->hasBeneficiary() && (*it)->getBeneficiaryID() == userID))
{
frqInfoList.push_back((*it)->toFloorRequestInfoParam(users_));
}
}
}
void Conference::handleFloorQuery( const BfcpMsgPtr &msg )
{
assert(msg->primitive() == BFCP_FLOOR_QUERY);
uint16_t userID = msg->getUserID();
auto floorIDs = msg->getFloorIDs();
// first clear the floor query of the user
for (auto floor : floors_)
{
floor.second->removeQueryUser(userID);
}
// set the new floor query of the user
uint16_t invalidFloorID = 0;
bool hasInvalidFloor = false;
for (auto floorID : floorIDs)
{
auto floor = findFloor(floorID);
if (floor)
{
LOG_INFO << "Add Query User " << msg->getUserID()
<< " to Floor " << floorID
<< " in Conference " << conferenceID_;
floor->addQueryUser(userID);
}
else
{
hasInvalidFloor = true;
invalidFloorID = floorID;
}
}
if (hasInvalidFloor)
{
char errorInfo[128];
snprintf(errorInfo, sizeof errorInfo,
"Floor %hu does not exist in Conference %u",
invalidFloorID, conferenceID_);
replyWithError(msg, BFCP_INVALID_FLOOR_ID, errorInfo);
return;
}
if (floorIDs.empty())
{
replyWithFloorStatus(msg, nullptr);
}
else
{
auto it = floorIDs.begin();
replyWithFloorStatus(msg, &(*it));
++it;
for (; it != floorIDs.end(); ++it)
{
notifyWithFloorStatus(userID, *it);
}
}
}
void Conference::replyWithFloorStatus(const BfcpMsgPtr &msg, const uint16_t *floorID)
{
FloorStatusParam param;
if (floorID)
{
param = getFloorStatusParam(*floorID);
}
connection_->replyWithFloorStatus(msg, param);
}
void Conference::notifyWithFloorStatus(uint16_t userID, uint16_t floorID)
{
auto user = findUser(userID);
if (user && isUserAvailable(user))
{
BasicRequestParam basicParam;
basicParam.conferenceID = conferenceID_;
basicParam.userID = user->getUserID();
basicParam.dst = user->getAddr();
assert(clientReponseCallback_);
basicParam.cb = boost::bind(clientReponseCallback_,
conferenceID_, BFCP_FLOOR_STATUS_ACK, user->getUserID(), _1, _2);
user->runSendMessageTask(boost::bind(&BfcpConnection::notifyFloorStatus,
connection_, basicParam, getFloorStatusParam(floorID)));
}
}
FloorStatusParam Conference::getFloorStatusParam( uint16_t floorID ) const
{
FloorStatusParam param;
param.setFloorID(floorID);
getFloorRequestInfoParamsByFloorID(param.frqInfoList, floorID, granted_);
getFloorRequestInfoParamsByFloorID(param.frqInfoList, floorID, accepted_);
getFloorRequestInfoParamsByFloorID(param.frqInfoList, floorID, pending_);
return param;
}
void Conference::getFloorRequestInfoParamsByFloorID(
FloorRequestInfoParamList &frqInfoList,
uint16_t floorID,
const FloorRequestQueue &queue) const
{
for (auto it = queue.rbegin(); it != queue.rend(); ++it)
{
if ((*it)->findFloor(floorID))
{
frqInfoList.push_back((*it)->toFloorRequestInfoParam(users_));
}
}
}
void Conference::onResponse(bfcp_prim expectedPrimitive,
uint16_t userID,
ResponseError err,
const BfcpMsgPtr &msg)
{
auto user = findUser(userID);
if (!user)
{
LOG_WARN << "Conference::onReponse: User " << userID
<< " doesn't exist in Conference " << conferenceID_;
return;
}
if (err != ResponseError::kNoError)
{
LOG_TRACE << "Conference received response with error "
<< response_error_name(err);
LOG_INFO << "Set User " << userID << " in Conference " << conferenceID_
<<" to unavailable";
user->setAvailable(false);
user->clearAllSendMessageTasks();
}
else
{
assert(msg->valid());
assert(msg->getUserID() == userID);
// FIXME: currently treat unexpected primitive as ACK
if (msg->primitive() != expectedPrimitive)
{
LOG_ERROR << "Expected BFCP " << bfcp_prim_name(expectedPrimitive)
<< " but get " << bfcp_prim_name(msg->primitive());
}
user->setActiveTime(msg->getReceivedTime());
if (isUserAvailable(user))
{
user->runNextSendMessageTask();
}
}
}
string Conference::getConferenceInfo() const
{
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement *conferenceElement = doc.NewElement("conference");
doc.InsertEndChild(conferenceElement);
// add conference info
conferenceElement->SetAttribute("id", conferenceID_);
conferenceElement->SetAttribute("maxFloorRequest", maxFloorRequest_);
conferenceElement->SetAttribute("timeForChairAction", timeForChairAction_);
conferenceElement->SetAttribute("acceptPolicy", toString(acceptPolicy_));
conferenceElement->SetAttribute("userObsoletedTime", userObsoletedTime_);
addUserInfoToXMLNode(&doc, conferenceElement);
addFloorInfoToXMLNode(&doc, conferenceElement);
addQueueInfoToXMLNode(&doc, conferenceElement, pending_, "pendingQueue");
addQueueInfoToXMLNode(&doc, conferenceElement, accepted_, "acceptedQueue");
addQueueInfoToXMLNode(&doc, conferenceElement, granted_, "grantedQueue");
tinyxml2::XMLPrinter printer;
doc.Print(&printer);
return printer.CStr();
}
void Conference::addUserInfoToXMLNode(tinyxml2::XMLDocument *doc,
tinyxml2::XMLNode *node) const
{
tinyxml2::XMLNode *userListNode = node->InsertEndChild(doc->NewElement("users"));
for (const auto &user : users_)
{
tinyxml2::XMLElement *userNode = doc->NewElement("user");
userNode->SetAttribute("id", user.second->getUserID());
if (!user.second->getDisplayName().empty())
{
userNode->SetAttribute("displayName", user.second->getDisplayName().c_str());
}
if (!user.second->getURI().empty())
{
userNode->SetAttribute("uri", user.second->getURI().c_str());
}
userNode->SetAttribute("isAvailable", isUserAvailable(user.second));
userListNode->InsertEndChild(userNode);
}
}
void Conference::addFloorInfoToXMLNode(tinyxml2::XMLDocument *doc,
tinyxml2::XMLNode *node) const
{
tinyxml2::XMLNode *floorsListNode = node->InsertEndChild(doc->NewElement("floors"));
for (const auto &floor : floors_)
{
tinyxml2::XMLElement *floorNode = doc->NewElement("floor");
floorNode->SetAttribute("id", floor.second->getFloorID());
floorNode->SetAttribute("isAssigned", floor.second->isAssigned());
if (floor.second->isAssigned())
{
floorNode->SetAttribute("chairID", floor.second->getChairID());
}
floorNode->SetAttribute("maxGrantedCount", floor.second->getMaxGrantedCount());
floorNode->SetAttribute("currentGrantedCount", floor.second->getGrantedCount());
// add query users
tinyxml2::XMLNode *queryUsersListNode =
floorNode->InsertEndChild(doc->NewElement("queryUsers"));
for (auto userID : floor.second->getQueryUsers())
{
tinyxml2::XMLElement *queryUserNode = doc->NewElement("user");
queryUserNode->SetAttribute("id", userID);
queryUsersListNode->InsertEndChild(queryUserNode);
}
floorsListNode->InsertEndChild(floorNode);
}
}
void Conference::addQueueInfoToXMLNode(tinyxml2::XMLDocument *doc,
tinyxml2::XMLNode *node,
const FloorRequestQueue &queue,
const string &queueName) const
{
tinyxml2::XMLNode *queueNode = node->InsertEndChild(doc->NewElement(queueName.c_str()));
for (const auto &floorRequest : queue)
{
addFloorRequestInfoToXMLNode(doc, queueNode, floorRequest);
}
}
void Conference::addFloorRequestInfoToXMLNode(tinyxml2::XMLDocument *doc,
tinyxml2::XMLNode *node,
const FloorRequestNodePtr &floorRequest) const
{
tinyxml2::XMLElement *requestNode = doc->NewElement("floorRequest");
requestNode->SetAttribute("id", floorRequest->getFloorRequestID());
requestNode->SetAttribute("userID", floorRequest->getUserID());
requestNode->SetAttribute("hasBeneficiaryID", floorRequest->hasBeneficiary());
if (floorRequest->hasBeneficiary())
{
requestNode->SetAttribute("beneficiaryID", floorRequest->getBeneficiaryID());
}
requestNode->SetAttribute("priority", floorRequest->getPriority());
if (!floorRequest->getParticipantInfo().empty())
{
requestNode->SetAttribute("participantInfo", floorRequest->getParticipantInfo().c_str());
}
requestNode->SetAttribute(
"overallStatus",
bfcp_reqstatus_name(floorRequest->getOverallStatus()));
requestNode->SetAttribute("queuePosition", floorRequest->getQueuePosition());
if (!floorRequest->getStatusInfo().empty())
{
requestNode->SetAttribute("statusInfo", floorRequest->getStatusInfo().c_str());
}
// add floors
tinyxml2::XMLNode *floorsListNode =
requestNode->InsertEndChild(doc->NewElement("floors"));
for (const auto &floor : floorRequest->getFloorNodeList())
{
tinyxml2::XMLElement *floorNode = doc->NewElement("floor");
floorNode->SetAttribute("id", floor.getFloorID());
floorNode->SetAttribute("status", bfcp_reqstatus_name(floor.getStatus()));
if (!floor.getStatusInfo().empty())
{
floorNode->SetAttribute("statusInfo", floor.getStatusInfo().c_str());
}
floorsListNode->InsertEndChild(floorNode);
}
// add query user
tinyxml2::XMLNode *queryUsersListNode =
requestNode->InsertEndChild(doc->NewElement("queryUsers"));
for (auto userID : floorRequest->getFloorRequestQueryUsers())
{
tinyxml2::XMLElement *queryUserNode = doc->NewElement("user");
queryUserNode->SetAttribute("id", userID);
queryUsersListNode->InsertEndChild(queryUserNode);
}
node->InsertEndChild(requestNode);
}
} // namespace bfcp
| 29.698142 | 93 | 0.692086 | Issic47 |
137081ba4854c7315c8985ba7f8652a95ff39bd7 | 2,023 | cpp | C++ | src/dsp/PulseShaper.cpp | Chowdhury-DSP/ChowKick | 632c6ee3ae9d43cbbc21e5d2e372ceee1f7d8cfb | [
"BSD-3-Clause"
] | 92 | 2021-05-17T13:53:35.000Z | 2022-03-30T00:57:53.000Z | src/dsp/PulseShaper.cpp | Chowdhury-DSP/ChowKick | 632c6ee3ae9d43cbbc21e5d2e372ceee1f7d8cfb | [
"BSD-3-Clause"
] | 19 | 2021-05-16T02:03:57.000Z | 2021-11-17T09:40:42.000Z | src/dsp/PulseShaper.cpp | Chowdhury-DSP/ChowKick | 632c6ee3ae9d43cbbc21e5d2e372ceee1f7d8cfb | [
"BSD-3-Clause"
] | 10 | 2021-05-17T02:27:18.000Z | 2022-03-30T00:57:51.000Z | #include "PulseShaper.h"
using namespace ShaperTags;
PulseShaper::PulseShaper (AudioProcessorValueTreeState& vts, double sampleRate) : c40 (0.015e-6f, (float) sampleRate, 0.029f)
{
decayParam = vts.getRawParameterValue (decayTag);
sustainParam = vts.getRawParameterValue (sustainTag);
}
void PulseShaper::addParameters (Parameters& params)
{
using namespace chowdsp::ParamUtils;
params.push_back (std::make_unique<VTSParam> (sustainTag,
"Sustain",
String(),
NormalisableRange<float> { 0.0f, 1.0f },
0.5f,
&percentValToString,
&stringToPercentVal));
params.push_back (std::make_unique<VTSParam> (decayTag,
"Decay",
String(),
NormalisableRange<float> { 0.0f, 1.0f },
0.5f,
&percentValToString,
&stringToPercentVal));
}
void PulseShaper::processBlock (dsp::AudioBlock<Vec>& block, const int numSamples)
{
constexpr float r1Off = 5000.0f;
constexpr float r1Scale = 500000.0f;
auto sustainVal = 1.0f - std::pow (sustainParam->load(), 0.05f);
auto r1Val = r1Off + (sustainVal * (r1Scale - r1Off));
r163.setResistanceValue (r1Val);
constexpr float r2Off = 500.0f;
constexpr float r2Scale = 100000.0f;
auto decayVal = std::pow (decayParam->load(), 2.0f);
auto r2Val = r2Off + (decayVal * (r2Scale - r2Off));
r162.setResistanceValue (r2Val);
auto* x = block.getChannelPointer (0);
for (int n = 0; n < numSamples; ++n)
x[n] = processSample (x[n]);
}
| 41.285714 | 125 | 0.490855 | Chowdhury-DSP |
13720b8a66bcf90a8925539c1c915c1265ae5a92 | 8,685 | cpp | C++ | samplevenmanager/samplevenmanager/VENImpl.cpp | AnalyticsFire/OpenADR-VEN-Library | 621e410370c3b3b91a5973d1fc19094278eeff75 | [
"Apache-2.0"
] | null | null | null | samplevenmanager/samplevenmanager/VENImpl.cpp | AnalyticsFire/OpenADR-VEN-Library | 621e410370c3b3b91a5973d1fc19094278eeff75 | [
"Apache-2.0"
] | 3 | 2021-01-20T13:02:54.000Z | 2021-02-19T14:05:34.000Z | samplevenmanager/samplevenmanager/VENImpl.cpp | AnalyticsFire/OpenADR-VEN-Library | 621e410370c3b3b91a5973d1fc19094278eeff75 | [
"Apache-2.0"
] | null | null | null | /*
* VENImpl.cpp
*
* Created on: Jul 8, 2015
* Author: dupes
*/
#include "VENImpl.h"
#include <iostream>
#include <oadr/request/report/ReportHelper.h>
#include <stdlib.h>
using namespace std;
namespace samplevenmanager
{
VENImpl::VENImpl(string venName, bool logToStdout)
{
el::Configurations conf;
conf.setGlobally(el::ConfigurationType::ToStandardOutput, (logToStdout ? "true" : "false"));
conf.setGlobally(el::ConfigurationType::ToFile, "true");
conf.setGlobally(el::ConfigurationType::Filename, "logs/" + venName + ".log");
el::Loggers::reconfigureLogger("default", conf);
}
/********************************************************************************/
VENImpl::~VENImpl()
{
}
/********************************************************************************/
void VENImpl::OnPeriodicReportStart(const oadrReportRequestType& reportRequest)
{
LOG(INFO) << " periodic report start";
}
/********************************************************************************/
void VENImpl::OnPeriodicReportComplete(
const oadrReportRequestType& reportRequest)
{
LOG(INFO) << " periodic report complete";
}
/********************************************************************************/
void VENImpl::OnGenerateOneshotReport(
const oadrReportRequestType& reportRequest,
oadrUpdateReportType::oadrReport_sequence &sequence)
{
LOG(INFO) << " generate oneshot report";
}
/********************************************************************************/
void VENImpl::OnGeneratePeriodicReport(
const oadrReportRequestType& reportRequest,
oadrUpdateReportType::oadrReport_sequence &sequence, time_t dtstart,
unsigned int durationInSeconds)
{
LOG(INFO) << "generate periodic report: " << reportRequest.reportRequestID();
time_t dtend = dtstart - durationInSeconds;
intervals::interval_sequence intervals;
// find the nearest time_t that ends on the minute
dtend = dtend + (60 - (dtend % 60));
while (dtend <= dtstart)
{
IntervalType intervalType = ReportHelper::generateInterval(dtend, 1, &DurationModifier::MINUTES);
// for each rid, add a payload to IntervalType
for (auto &specifier : reportRequest.reportSpecifier().specifierPayload())
{
string rid = specifier.rID();
float value = (float)(rand() % 10);
oadrReportPayloadType payload = ReportHelper::generateOadrReportPayloadFloat(rid, value,
oadr2b::oadr::oadrDataQualityType::Quality_Good___Non_Specific,
1, 1);
intervalType.streamPayloadBase().push_back(payload);
}
intervals.push_back(intervalType);
// increment to the next minute
dtend += 60;
}
if (intervals.size() > 0)
{
time_t now = time(NULL);
oadrReportType report = ReportHelper::generateReport(&ReportName::TELEMETRY_USAGE, reportRequest.reportSpecifier().reportSpecifierID(),
reportRequest.reportRequestID(), now, intervals);
sequence.push_back(report);
}
}
/********************************************************************************/
void VENImpl::OnGenerateHistoricalReport(
const oadrReportRequestType& reportRequest,
oadrUpdateReportType::oadrReport_sequence &sequence, time_t dtstart,
unsigned int durationInSeconds)
{
LOG(INFO) << "generate historical report";
}
/********************************************************************************/
void VENImpl::OnGenerateRegisterReport(oadrRegisterReportType::oadrReport_sequence &sequence)
{
LOG(INFO) << "register report";
oadrReportType::oadrReportDescription_sequence description;
// 1 minute energy interval
oadrReportDescriptionType energy = ReportHelper::generateDescriptionEnergyItem("rid_energy_4184bb93", "DEVICE1", ReportEnumeratedType::reading,
ReadingTypeEnumeratedType::Direct_Read, "", 1, 1, false, &DurationModifier::MINUTES,
ReportHelper::eEnergyReal, "Wh", SiScaleCodeType::none);
// 1 minute power interval
oadrReportDescriptionType power = ReportHelper::generateDescriptionPowerItem("rid_power_4184bb93", "DEVICE1", ReportEnumeratedType::reading,
ReadingTypeEnumeratedType::Direct_Read, "", 1, 1, false, &DurationModifier::MINUTES,
ReportHelper::ePowerReal, "W", SiScaleCodeType::none, 60.0, 120, true);
// ...
// Create additional oadrReportDescriptionType objects...
// ...
// put each oadrReportDescriptionType into the description container
description.push_back(energy);
description.push_back(power);
// create a report with the descriptions
// there are two main report types: TELEMETRY_USAGE and HISTORY_USAGE
// the structure of these report types is identical. the only difference is how the reports can be used
oadrReportType telemetryUsage = ReportHelper::generateReportDescription(&ReportName::TELEMETRY_USAGE, 120, &DurationModifier::MINUTES,
"DEMO_TELEMETRY_USAGE", 0, description);
// push the telemtry usage report onto the container
// if there are additional reports (such as a history usage report), push those
// reports as well.
sequence.push_back(telemetryUsage);
}
/********************************************************************************/
void VENImpl::OnEventStart(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event, unsigned int remainingDurationInSeconds)
{
LOG(INFO) << "event start: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventComplete(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event)
{
LOG(INFO) << "event complete: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventIntervalStart(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event,
const oadr2b::ei::eiEventSignalType* eventSignal, std::string uid,
float payload, time_t dtstart, unsigned int remainingDurationInSeconds)
{
LOG(INFO) << "event interval start: " << eventID << payload << " " << remainingDurationInSeconds;
}
/********************************************************************************/
void VENImpl::OnEventNew(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event, oadr2b::ei::OptTypeType::value &optType)
{
LOG(INFO) << "new event received: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventNew(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event)
{
LOG(INFO) << "new event received: " << eventID << " (no response expected)";
}
/********************************************************************************/
void VENImpl::OnEventModify(const std::string& eventID,
const oadr2b::oadr::oadrEvent* newEvent,
const oadr2b::oadr::oadrEvent* oldEvent, oadr2b::ei::OptTypeType::value &optType)
{
LOG(INFO) << "event modified: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventModify(const std::string& eventID,
const oadr2b::oadr::oadrEvent* newEvent,
const oadr2b::oadr::oadrEvent* oldEvent)
{
LOG(INFO) << "event modified: " << eventID << " (no response expected)";
}
/********************************************************************************/
void VENImpl::OnEventCancel(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event, oadr2b::ei::OptTypeType::value &optType)
{
LOG(INFO) << "event cancelled: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventCancel(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event)
{
LOG(INFO) << "event cancelled: " << eventID;
}
/********************************************************************************/
void VENImpl::OnEventImplicitCancel(const std::string& eventID,
const oadr2b::oadr::oadrEvent* event)
{
LOG(INFO) << "event imiplicitly cancelled: " << eventID;
}
/********************************************************************************/
void VENImpl::OnOadrMessageReceived(std::string &message)
{
LOG(INFO) << "\nVEN <--- VTN\n" << message << "\n=================================\n";
}
/********************************************************************************/
void VENImpl::OnOadrMessageSent(std::string &message)
{
LOG(INFO) << "\nVEN ---> VTN\n" << message << "\n=================================\n";
}
/********************************************************************************/
void VENImpl::OnCurlException(CurlException &ex)
{
LOG(ERROR) << "curl exception : " << ex.what();
}
/********************************************************************************/
void VENImpl::VENImpl::OnException(std::exception &ex)
{
LOG(ERROR) << "std exception : " << ex.what();
}
} /* namespace samplevenmanager */
| 31.467391 | 144 | 0.581577 | AnalyticsFire |
1373eff35dc1bb4a577ca1979c6d056c070a3100 | 3,716 | cpp | C++ | SerialPrograms/Source/CommonFramework/ImageMatch/ImageDiff.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/CommonFramework/ImageMatch/ImageDiff.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/CommonFramework/ImageMatch/ImageDiff.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | /* Image Diff
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <cmath>
#include <smmintrin.h>
#include "Common/Compiler.h"
#include "Common/Cpp/Exceptions.h"
#include "Common/Cpp/SIMDDebuggers.h"
#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h"
#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h"
#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h"
#include "ImageDiff.h"
#include <iostream>
using std::cout;
using std::endl;
namespace PokemonAutomation{
namespace ImageMatch{
FloatPixel pixel_average(const QImage& image, const QImage& alpha_mask){
if (!image.size().isValid()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions");
}
if (image.size() != alpha_mask.size()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions");
}
Kernels::PixelSums sums;
Kernels::pixel_sum_sqr(
sums, image.width(), image.height(),
(const uint32_t*)image.bits(), image.bytesPerLine(),
(const uint32_t*)alpha_mask.bits(), alpha_mask.bytesPerLine()
);
FloatPixel sum(sums.sumR, sums.sumG, sums.sumB);
sum /= sums.count;
return sum;
}
void scale_brightness(QImage& image, const FloatPixel& multiplier){
Kernels::scale_brightness(
image.width(), image.height(),
(uint32_t*)image.bits(), image.bytesPerLine(),
(float)multiplier.r, (float)multiplier.g, (float)multiplier.b
);
}
double pixel_RMSD(const QImage& reference, const QImage& image){
if (!image.size().isValid()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions");
}
if (reference.size() != image.size()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions");
}
uint64_t count = 0;
uint64_t sumsqrs = 0;
Kernels::sum_sqr_deviation(
count, sumsqrs,
reference.width(), reference.height(),
(const uint32_t*)reference.bits(), reference.bytesPerLine(),
(const uint32_t*)image.bits(), image.bytesPerLine()
);
return std::sqrt((double)sumsqrs / (double)count);
}
double pixel_RMSD(const QImage& reference, const QImage& image, QRgb background){
if (!image.size().isValid()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions");
}
if (reference.size() != image.size()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions");
}
uint64_t count = 0;
uint64_t sumsqrs = 0;
Kernels::sum_sqr_deviation(
count, sumsqrs,
reference.width(), reference.height(),
(const uint32_t*)reference.bits(), reference.bytesPerLine(),
(const uint32_t*)image.bits(), image.bytesPerLine(),
background
);
return std::sqrt((double)sumsqrs / (double)count);
}
double pixel_RMSD_masked(const QImage& reference, const QImage& image){
if (!image.size().isValid()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions");
}
if (reference.size() != image.size()){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions");
}
uint64_t count = 0;
uint64_t sumsqrs = 0;
Kernels::sum_sqr_deviation_masked(
count, sumsqrs,
reference.width(), reference.height(),
(const uint32_t*)reference.bits(), reference.bytesPerLine(),
(const uint32_t*)image.bits(), image.bytesPerLine()
);
return std::sqrt((double)sumsqrs / (double)count);
}
}
}
| 32.884956 | 92 | 0.662002 | BlizzardHero |
13746480cc2d4e0c0edc506092a0b5a3f40a53ba | 1,604 | cpp | C++ | maratona_1/data_structure.cpp | eder-matheus/programming_marathons | 93e5e8bd21402a59b6d8e4cdfee2f8f3f7c96ecd | [
"MIT"
] | null | null | null | maratona_1/data_structure.cpp | eder-matheus/programming_marathons | 93e5e8bd21402a59b6d8e4cdfee2f8f3f7c96ecd | [
"MIT"
] | null | null | null | maratona_1/data_structure.cpp | eder-matheus/programming_marathons | 93e5e8bd21402a59b6d8e4cdfee2f8f3f7c96ecd | [
"MIT"
] | 1 | 2021-09-01T13:30:19.000Z | 2021-09-01T13:30:19.000Z | // data structure - uri 1340
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#define ADD_ELEMENT 1
#define REMOVE_ELEMENT 2
int main() {
int cmd_count;
int cmd, param;
while (std::cin >> cmd_count) {
bool is_stack = true;
bool is_queue = true;
bool is_prior_queue = true;
std::stack<int> stack;
std::queue<int> queue;
std::priority_queue<int> priority_queue;
for (int i = 0; i < cmd_count; i++) {
std::cin >> cmd >> param;
if (cmd == ADD_ELEMENT) {
stack.push(param);
queue.push(param);
priority_queue.push(param);
} else if (cmd == REMOVE_ELEMENT) {
if (stack.top() != param) {
is_stack = false;
}
stack.pop();
if (queue.front() != param) {
is_queue = false;
}
queue.pop();
if (priority_queue.top() != param) {
is_prior_queue = false;
}
priority_queue.pop();
} else {
std::cout << "[ERROR] Invalid command\n";
exit(1);
}
}
int possible_structs = 0;
std::string data_struct;
if (is_stack) {
data_struct = "stack";
possible_structs++;
}
if (is_queue) {
data_struct = "queue";
possible_structs++;
}
if (is_prior_queue) {
data_struct = "priority queue";
possible_structs++;
}
if (possible_structs == 1) {
std::cout << data_struct << "\n";
} else if (possible_structs > 1) {
std::cout << "not sure\n";
} else {
std::cout << "impossible\n";
}
}
return 0;
}
| 20.564103 | 49 | 0.535536 | eder-matheus |
137bec91d6c492eca71c6cc67b450771d8edf9fd | 213 | cpp | C++ | src/autonet/test/AutoNetTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | src/autonet/test/AutoNetTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | src/autonet/test/AutoNetTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autotesting/gtest-all-guard.hpp>
int main(int argc, const char* argv []) {
return autotesting_main(argc, argv);
}
| 26.625 | 65 | 0.71831 | CaseyCarter |
137c675b8a13eb396aed09c648230d3aabe5851d | 2,857 | cpp | C++ | Chapter 06/18.cpp | jesushilarioh/Starting-Out-With-C-Programming-Challenges | 34fd6ac3d95c4da934a739f8aeac9b3e078ef898 | [
"MIT"
] | 7 | 2019-08-03T10:36:55.000Z | 2022-03-01T09:31:14.000Z | Chapter 06/18.cpp | jesushilarioh/Starting-Out-With-C-Programming-Challenges | 34fd6ac3d95c4da934a739f8aeac9b3e078ef898 | [
"MIT"
] | null | null | null | Chapter 06/18.cpp | jesushilarioh/Starting-Out-With-C-Programming-Challenges | 34fd6ac3d95c4da934a739f8aeac9b3e078ef898 | [
"MIT"
] | 6 | 2019-07-04T05:59:19.000Z | 2022-01-26T03:33:03.000Z | #include <iostream>
using namespace std;
double inputValidate(double, double);
void getInfo(double &, double &, double &);
void calcAndDisplay(double, double, double);
int main()
{
const double CHARGE_PER_HOUR = 25.00;
double num_of_rooms,
price_per_gal,
sqft_to_paint = 0;
getInfo(num_of_rooms, price_per_gal, sqft_to_paint);
calcAndDisplay(num_of_rooms, price_per_gal, sqft_to_paint);
return 0;
} // END int main()
void getInfo(double &num_of_rooms,
double &price_per_gal,
double &sqft_to_paint)
{
// Get number of rooms to be painted
cout << "Number of rooms to be painted: ";
num_of_rooms = inputValidate(num_of_rooms, 1);
for (int i = 0; i < num_of_rooms; i++)
{
// Get sqft of wall space per room
cout << "Sq. Ft. of wall space to be painted "
<< "in room " << (i + 1) << ": ";
sqft_to_paint += inputValidate(sqft_to_paint, 0);
}
// Get price of paint per gallon
cout << "Price of paint per gallon: $";
price_per_gal = inputValidate(price_per_gal, 10.00);
}
double inputValidate(double number, double limit_number)
{
while(!(cin >> number) || number < limit_number)
{
cout << "Error. Number must not be "
<< " " << limit_number << " or greater:";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return number;
}
void calcAndDisplay(double num_of_rooms,
double price_per_gal,
double sqft_to_paint)
{
double gals_of_paint_req,
labor_required,
cost_of_paint,
labor_charges,
total_cost;
// Calculate:
gals_of_paint_req = sqft_to_paint / 110.0;
labor_required = gals_of_paint_req * 8.0;
cost_of_paint = price_per_gal * gals_of_paint_req;
labor_charges = labor_required * 25.00;
total_cost = labor_charges + cost_of_paint;
// Display:
cout << "Total SqFt to paint : "
<< sqft_to_paint
<< endl;
cout << "Price per gallon : "
<< price_per_gal
<< endl;
// • The number of gallons of paint required
cout << "Gallons required : "
<< gals_of_paint_req
<< endl;
// • The hours of labor required
cout << "Hours required : "
<< labor_required
<< endl;
// • The cost of the paint
cout << "Cost of paint :$"
<< cost_of_paint
<< endl;
// • The labor charges
cout << "Labor charges :$"
<< labor_charges
<< endl;
// • The total cost of the paint job
cout << "Total cost of job :$"
<< total_cost
<< endl;
} | 26.453704 | 63 | 0.553378 | jesushilarioh |
13829a09e7ed67423342e00b45f1b9f38f7a8aa1 | 3,003 | hpp | C++ | openstudiocore/src/cli/EmbeddedHelp.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-11-12T02:07:03.000Z | 2019-11-12T02:07:03.000Z | openstudiocore/src/cli/EmbeddedHelp.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-02-04T23:30:45.000Z | 2019-02-04T23:30:45.000Z | openstudiocore/src/cli/EmbeddedHelp.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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.
***********************************************************************************************************************/
#ifndef CLI_EMBEDDEDHELP_HPP
#define CLI_EMBEDDEDHELP_HPP
#include <iostream>
#if defined __APPLE__
#include <mach-o/dyld.h> /* _NSGetExecutablePath */
#include <limits.h> /* PATH_MAX */
#elif defined _WIN32
#include <windows.h>
#endif
namespace embedded_help {
inline std::string applicationFilePath() {
#ifdef __APPLE__
char path[PATH_MAX + 1];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0) {
return std::string(path);
}
#elif defined _WIN32
TCHAR szPath[MAX_PATH];
if( !GetModuleFileName( nullptr, szPath, MAX_PATH ) ) {
return std::string(szPath);
}
#endif
return std::string();
}
}
#endif // CLI_EMBEDDEDHELP_HPP | 50.05 | 125 | 0.698302 | hellok-coder |
1387eab01b3800d188276007b4a92b463e91e631 | 162 | hpp | C++ | Algorithms/tree_t(G)/Correctness/randomTreeGenerator.hpp | lucaskeiler/AlgoritmosTCC | eccf14c2c872acb9e0728eb8948eee121b274f2e | [
"MIT"
] | null | null | null | Algorithms/tree_t(G)/Correctness/randomTreeGenerator.hpp | lucaskeiler/AlgoritmosTCC | eccf14c2c872acb9e0728eb8948eee121b274f2e | [
"MIT"
] | null | null | null | Algorithms/tree_t(G)/Correctness/randomTreeGenerator.hpp | lucaskeiler/AlgoritmosTCC | eccf14c2c872acb9e0728eb8948eee121b274f2e | [
"MIT"
] | null | null | null | #ifndef TREE_GENERATOR_HPP
#define TREE_GENERATOR_HPP
#include "tree.hpp"
Graph* generate_random_tree(int n);
void randomizePercolationLimit(Graph* g);
#endif | 16.2 | 41 | 0.808642 | lucaskeiler |
138b9304f6ab196ecd0861d5e30311e58c74eddf | 5,271 | hpp | C++ | tpm_module/libhis_getpubkey.hpp | iadgovuser26/HIRS | 4b461ebbabac5cd8ef54e562f597d65346c3c863 | [
"Apache-2.0"
] | 127 | 2018-09-07T15:45:45.000Z | 2022-02-10T11:13:51.000Z | tpm_module/libhis_getpubkey.hpp | iadgovuser26/HIRS | 4b461ebbabac5cd8ef54e562f597d65346c3c863 | [
"Apache-2.0"
] | 260 | 2018-09-07T19:08:25.000Z | 2022-03-31T15:28:24.000Z | tpm_module/libhis_getpubkey.hpp | iadgovuser26/HIRS | 4b461ebbabac5cd8ef54e562f597d65346c3c863 | [
"Apache-2.0"
] | 48 | 2018-09-23T09:13:20.000Z | 2022-03-06T20:17:09.000Z | #ifndef libhis_getpubkey_hpp
#define libhis_getpubkey_hpp
#ifdef WINDOWS
#include "tspi.h"
#include "tss_error.h"
#include "tss_defines.h"
#endif
#ifdef LINUX
#include <tss/tspi.h>
#include <tss/tss_error.h>
#include <tss/tss_defines.h>
#endif
#include "libhis_exception.hpp"
class libhis_getpubkey
{
public:
libhis_getpubkey()
{
//create a context object
result = Tspi_Context_Create(&hcontext);
if(result != TSS_SUCCESS) throw libhis_exception("Create Conntext", result);
//create EK object
result = Tspi_Context_CreateObject(hcontext, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &hkey_ek);
if(result != TSS_SUCCESS) throw libhis_exception("Create EK", result);
//Create TPM policy
result = Tspi_Context_CreateObject(hcontext, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &hpolicy_tpm);
if(result != TSS_SUCCESS) throw libhis_exception("Create TPM Policy", result);
}
void getpubek(
unsigned char *auth_tpm_value,
unsigned long auth_tpm_size,
bool auth_tpm_sha1,
unsigned char *nonce,
unsigned char *&output_value,
unsigned long &output_size)
{
//establish a session
result = Tspi_Context_Connect(hcontext, 0);
if(result != TSS_SUCCESS) throw libhis_exception("Connect Context", result);
//get the TPM object
result = Tspi_Context_GetTpmObject(hcontext, &htpm);
if(result != TSS_SUCCESS) throw libhis_exception("Get TPM Object", result);
//set up TPM auth
if(auth_tpm_sha1)
{
result = Tspi_Policy_SetSecret(hpolicy_tpm, TSS_SECRET_MODE_SHA1, auth_tpm_size, auth_tpm_value);
if(result != TSS_SUCCESS) throw libhis_exception("Set TPM Secret SHA1", result);
}
else
{
result = Tspi_Policy_SetSecret(hpolicy_tpm, TSS_SECRET_MODE_PLAIN, auth_tpm_size, auth_tpm_value);
if(result != TSS_SUCCESS) throw libhis_exception("Set TPM Secret Plain", result);
}
//assign the TPM auth to the TPM
result = Tspi_Policy_AssignToObject(hpolicy_tpm, htpm);
if(result != TSS_SUCCESS) throw libhis_exception("Assign TPM Secret to TPM", result);
//assign the TPM auth to the EK
result = Tspi_Policy_AssignToObject(hpolicy_tpm, hkey_ek);
if(result != TSS_SUCCESS) throw libhis_exception("Assign TPM Secret to EK", result);
//set up nonce
validation.ulExternalDataLength = 20;
validation.rgbExternalData = nonce;
try
{
//get the public EK
result = Tspi_TPM_GetPubEndorsementKey(htpm, true, &validation, &hkey_ek);
if(result != TSS_SUCCESS) throw libhis_exception("Get Public EK", result);
}
catch(libhis_exception &e)
{
//get the public EK the Atmel TPM in an Ultrabook way
result = Tspi_TPM_GetPubEndorsementKey(htpm, false, &validation, &hkey_ek);
if(result != TSS_SUCCESS) throw libhis_exception("Get Public EK", result);
//let a second exception make its way upward (should be same error code)
}
//get the modulus
UINT32 mod_size;
BYTE *mod_value;
result = Tspi_GetAttribData(hkey_ek, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_value);
if(result != TSS_SUCCESS) throw libhis_exception("Get EK Blob", result);
//copy out the EK modulus
output_size = mod_size;
output_value = new unsigned char[mod_size];
for(unsigned long i = 0; i < mod_size; i++)
output_value[i] = mod_value[i];
//clean up ek modulus
result = Tspi_Context_FreeMemory(hcontext, mod_value);
if(result != TSS_SUCCESS) throw libhis_exception("Clean up modulus data", result);
}
void getpubsrk(
unsigned char *auth_tpm_value,
unsigned long auth_tpm_size,
bool auth_tpm_sha1,
unsigned char *&output_value,
unsigned long &output_size)
{
//establish a session
result = Tspi_Context_Connect(hcontext, 0);
if(result != TSS_SUCCESS) throw libhis_exception("Connect Context", result);
//get the TPM object
result = Tspi_Context_GetTpmObject(hcontext, &htpm);
if(result != TSS_SUCCESS) throw libhis_exception("Get TPM Object", result);
//set up TPM auth
if(auth_tpm_sha1)
{
result = Tspi_Policy_SetSecret(hpolicy_tpm, TSS_SECRET_MODE_SHA1, auth_tpm_size, auth_tpm_value);
if(result != TSS_SUCCESS) throw libhis_exception("Set TPM Secret SHA1", result);
}
else
{
result = Tspi_Policy_SetSecret(hpolicy_tpm, TSS_SECRET_MODE_PLAIN, auth_tpm_size, auth_tpm_value);
if(result != TSS_SUCCESS) throw libhis_exception("Set TPM Secret Plain", result);
}
//assign the TPM auth to the TPM
result = Tspi_Policy_AssignToObject(hpolicy_tpm, htpm);
if(result != TSS_SUCCESS) throw libhis_exception("Assign TPM Secret to TPM", result);
//set up key container
UINT32 mod_size;
BYTE *mod_value;
//get the public EK
result = Tspi_TPM_OwnerGetSRKPubKey(htpm, &mod_size, &mod_value);
if(result != TSS_SUCCESS) throw libhis_exception("Get Public SRK", result);
//copy out the SRK modulus
output_size = mod_size;
output_value = new unsigned char[mod_size];
for(unsigned long i = 0; i < mod_size; i++)
output_value[i] = mod_value[i];
//clean up SRK modulus
result = Tspi_Context_FreeMemory(hcontext, mod_value);
if(result != TSS_SUCCESS) throw libhis_exception("Clean up modulus data", result);
}
private:
TSS_RESULT result;
TSS_HCONTEXT hcontext;
TSS_HTPM htpm;
TSS_HKEY hkey_ek;
TSS_HPOLICY hpolicy_tpm;
TSS_VALIDATION validation;
};
#endif
| 31.562874 | 124 | 0.743502 | iadgovuser26 |
139069153eadeaafb5672cd87154d1c6af74317e | 4,593 | cpp | C++ | cpp/oneapi/dal/table/common.cpp | mchernov-intel/daal | 3342c0e2812e48d612da7ccfa845bd0168145fb7 | [
"Apache-2.0"
] | null | null | null | cpp/oneapi/dal/table/common.cpp | mchernov-intel/daal | 3342c0e2812e48d612da7ccfa845bd0168145fb7 | [
"Apache-2.0"
] | 4 | 2020-08-05T06:29:01.000Z | 2020-08-18T16:28:04.000Z | cpp/oneapi/dal/table/common.cpp | mchernov-intel/daal | 3342c0e2812e48d612da7ccfa845bd0168145fb7 | [
"Apache-2.0"
] | 2 | 2020-08-05T05:53:41.000Z | 2020-08-05T06:00:33.000Z | /*******************************************************************************
* Copyright 2020-2021 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.
*******************************************************************************/
#include "oneapi/dal/table/common.hpp"
#include "oneapi/dal/exceptions.hpp"
#include "oneapi/dal/table/backend/empty_table_impl.hpp"
using std::int64_t;
namespace oneapi::dal {
class detail::v1::table_metadata_impl {
public:
virtual ~table_metadata_impl() {}
virtual int64_t get_feature_count() const = 0;
virtual const feature_type& get_feature_type(int64_t index) const = 0;
virtual const data_type& get_data_type(int64_t index) const = 0;
};
namespace v1 {
class empty_metadata_impl : public detail::table_metadata_impl {
public:
int64_t get_feature_count() const override {
return 0;
}
const feature_type& get_feature_type(int64_t) const override {
throw domain_error(
dal::detail::error_messages::cannot_get_feature_type_from_empty_metadata());
}
const data_type& get_data_type(int64_t) const override {
throw domain_error(dal::detail::error_messages::cannot_get_data_type_from_empty_metadata());
}
};
class simple_metadata_impl : public detail::table_metadata_impl {
public:
simple_metadata_impl(const array<data_type>& dtypes, const array<feature_type>& ftypes)
: dtypes_(dtypes),
ftypes_(ftypes) {
if (dtypes_.get_count() != ftypes_.get_count()) {
throw out_of_range(
dal::detail::error_messages::
element_count_in_data_type_and_feature_type_arrays_does_not_match());
}
}
int64_t get_feature_count() const override {
return dtypes_.get_count();
}
const feature_type& get_feature_type(int64_t i) const override {
if (!is_in_range(i)) {
throw out_of_range(dal::detail::error_messages::feature_index_is_out_of_range());
}
return ftypes_[i];
}
const data_type& get_data_type(int64_t i) const override {
if (!is_in_range(i)) {
throw out_of_range(dal::detail::error_messages::feature_index_is_out_of_range());
}
return dtypes_[i];
}
private:
bool is_in_range(int64_t i) const {
return i >= 0 && i < dtypes_.get_count();
}
private:
array<data_type> dtypes_;
array<feature_type> ftypes_;
};
table_metadata::table_metadata() : impl_(new empty_metadata_impl()) {}
table_metadata::table_metadata(const array<data_type>& dtypes, const array<feature_type>& ftypes)
: impl_(new simple_metadata_impl(dtypes, ftypes)) {}
int64_t table_metadata::get_feature_count() const {
return impl_->get_feature_count();
}
const feature_type& table_metadata::get_feature_type(int64_t feature_index) const {
return impl_->get_feature_type(feature_index);
}
const data_type& table_metadata::get_data_type(int64_t feature_index) const {
return impl_->get_data_type(feature_index);
}
table::table() : table(backend::empty_table_impl{}) {}
table::table(table&& t) : impl_(std::move(t.impl_)) {
using wrapper = detail::table_impl_wrapper<backend::empty_table_impl>;
using wrapper_ptr = detail::shared<wrapper>;
t.impl_ = wrapper_ptr(new wrapper(backend::empty_table_impl{}));
}
table& table::operator=(table&& t) {
this->impl_.swap(t.impl_);
return *this;
}
bool table::has_data() const noexcept {
return impl_->get_column_count() > 0 && impl_->get_row_count() > 0;
}
int64_t table::get_column_count() const {
return impl_->get_column_count();
}
int64_t table::get_row_count() const {
return impl_->get_row_count();
}
const table_metadata& table::get_metadata() const {
return impl_->get_metadata();
}
int64_t table::get_kind() const {
return impl_->get_kind();
}
data_layout table::get_data_layout() const {
return impl_->get_data_layout();
}
void table::init_impl(detail::table_impl_iface* impl) {
impl_ = pimpl{ impl };
}
} // namespace v1
} // namespace oneapi::dal
| 30.019608 | 100 | 0.680165 | mchernov-intel |
ca5ed5c99de5ffacee1fda856d91607064bc8d85 | 3,127 | cpp | C++ | Source/Shared/service_call_routed_handler.cpp | natiskan/xbox-live-api | 9e7e51e0863b5983c2aa334a7b0db579b3bdf1de | [
"MIT"
] | 118 | 2019-05-13T22:56:02.000Z | 2022-03-16T06:12:39.000Z | Source/Shared/service_call_routed_handler.cpp | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 31 | 2019-05-07T13:09:28.000Z | 2022-01-26T10:02:59.000Z | Source/Shared/service_call_routed_handler.cpp | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 48 | 2019-05-28T23:55:31.000Z | 2021-12-22T03:47:56.000Z | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "service_call_routed_handler.h"
#include "http_call_request_message_internal.h"
#include "xsapi_utils.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN
ServiceCallRoutedHandler::ServiceCallRoutedHandler(
_In_ XblCallRoutedHandler handler,
_In_opt_ void* context
) noexcept :
m_clientHandler{ handler },
m_clientContext{ context }
{
m_hcToken = HCAddCallRoutedHandler(HCCallRoutedHandler, this);
}
ServiceCallRoutedHandler::~ServiceCallRoutedHandler() noexcept
{
HCRemoveCallRoutedHandler(m_hcToken);
}
void ServiceCallRoutedHandler::HCCallRoutedHandler(
_In_ HCCallHandle call,
_In_ void* context
)
{
auto pThis{ static_cast<ServiceCallRoutedHandler*>(context) };
String formattedResponse{ pThis->GetFormattedResponse(call) };
XblServiceCallRoutedArgs args
{
call,
s_nextResponseNumber++,
formattedResponse.data()
};
pThis->m_clientHandler(args, pThis->m_clientContext);
}
String ServiceCallRoutedHandler::GetFormattedResponse(
HCCallHandle call
) const noexcept
{
Stringstream response;
response << "== [XBOX SERVICE CALL] #";
response << s_nextResponseNumber;
response << "\r\n";
const char* uri{ nullptr };
HCHttpCallGetRequestUrl(call, &uri);
response << "\r\n[URI]: ";
response << uri;
const char* token{ nullptr };
HCHttpCallResponseGetHeader(call, AUTH_HEADER, &token);
if (token)
{
response << "\r\n[Authorization Header]: ";
response << token;
}
const char* signature{ nullptr };
HCHttpCallResponseGetHeader(call, SIG_HEADER, &signature);
if (signature)
{
response << "\r\n[Signature Header]: ";
response << signature;
}
uint32_t httpStatus{ 0 };
HCHttpCallResponseGetStatusCode(call, &httpStatus);
response << "\r\n[HTTP Status]: ";
response << httpStatus;
#if HC_PLATFORM_IS_MICROSOFT
HRESULT hr = utils::convert_http_status_to_hresult(httpStatus);
response << " [";
response << utils::convert_hresult_to_error_name(hr);
response << "] ";
#endif
uint32_t numHeaders{ 0 };
HCHttpCallResponseGetNumHeaders(call, &numHeaders);
if (numHeaders > 0)
{
response << "\r\n[Response Headers]: ";
const char* headerName{ nullptr };
const char* headerValue{ nullptr };
for (uint32_t i = 0; i < numHeaders; ++i)
{
HCHttpCallResponseGetHeaderAtIndex(call, i, &headerName, &headerValue);
response << headerName << " : " << headerValue << "; ";
}
}
const char* responseBody{ nullptr };
HCHttpCallResponseGetResponseString(call, &responseBody);
if (responseBody)
{
response << "\r\n[Response Body]: ";
response << responseBody;
}
response << "\r\n";
return response.str();
}
std::atomic<uint64_t> ServiceCallRoutedHandler::s_nextResponseNumber{ 0 };
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END | 26.5 | 101 | 0.676687 | natiskan |
ca5fad25cc1536cedb365efd03779db308de02a3 | 2,678 | cpp | C++ | Engine/GUI/gkGUIManager.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | 1 | 2017-01-16T11:53:44.000Z | 2017-01-16T11:53:44.000Z | Engine/GUI/gkGUIManager.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | null | null | null | Engine/GUI/gkGUIManager.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | null | null | null | /*
-------------------------------------------------------------------------------
This file is part of gkGUIManager.
http://gamekit.googlecode.com/
Copyright (c) 2012 Alberto Torres Ruiz
Contributor(s): none yet.
-------------------------------------------------------------------------------
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 "gkGUIManager.h"
#include <gkFont.h>
#include <gkFontManager.h>
#include <Rocket/Core.h>
#include <Rocket/Controls.h>
#include <Rocket/Debugger.h>
#include "rocket/SystemInterfaceOgre3D.h"
#include "rocket/FileInterfaceOgre3D.h"
UT_IMPLEMENT_SINGLETON(gkGUIManager)
gkGUIManager::gkGUIManager()
{
// Rocket initialisation.
Ogre::ResourceGroupManager::getSingleton().createResourceGroup(DEFAULT_ROCKET_RESOURCE_GROUP);
m_rkOgreSystem = new SystemInterfaceOgre3D();
Rocket::Core::SetSystemInterface(m_rkOgreSystem);
Rocket::Core::Initialise();
Rocket::Controls::Initialise();
m_rkFileInterface = new FileInterfaceOgre3D();
Rocket::Core::SetFileInterface(m_rkFileInterface);
}
gkGUIManager::~gkGUIManager()
{
Rocket::Core::Shutdown();
delete m_rkOgreSystem;
delete m_rkFileInterface;
Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup(DEFAULT_ROCKET_RESOURCE_GROUP);
}
void gkGUIManager::loadFont(const gkString& name)
{
gkFont *fnt = gkFontManager::getSingleton().getByName<gkFont>(name);
if (fnt)
{
Rocket::Core::FontDatabase::LoadFontFace((const unsigned char*)fnt->getData(), fnt->getSize());
}
else
{
Rocket::Core::FontDatabase::LoadFontFace(name.c_str());
}
}
void gkGUIManager::setDebug(gkGUI* gui)
{
if (gui)
{
if (!Rocket::Debugger::SetContext(gui->getContext()))
Rocket::Debugger::Initialise(gui->getContext());
}
else
Rocket::Debugger::SetContext(NULL);
}
| 28.489362 | 97 | 0.686706 | slagusev |
ca604a483b4c5f814e1012c44343a765d91447f4 | 1,460 | cpp | C++ | logfiletest/tests/KnownPlayersTest.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | 2 | 2016-08-19T19:28:04.000Z | 2021-04-18T04:48:44.000Z | logfiletest/tests/KnownPlayersTest.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | null | null | null | logfiletest/tests/KnownPlayersTest.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | null | null | null | #include "../model/KnownPlayers.h"
#include "gtest/gtest.h"
TEST(KnownPlayers, addPlayer1){
KnownPlayers players;
EXPECT_FALSE(players.isPlayer("PublicLightBus"));
players.addPlayer("PublicLightBus");
EXPECT_TRUE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("", players.getPlayerClass("PublicLightBus"));
players.setPlayerClass("PublicLightBus", "MA");
EXPECT_TRUE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("MA", players.getPlayerClass("PublicLightBus"));
}
TEST(KnownPlayers, playerCannotBeDetermined){
KnownPlayers players;
players.setPlayerClass("PublicLightBus", "pcnpc");
EXPECT_FALSE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("", players.getPlayerClass("PublicLightBus"));
}
TEST(KnownPlayers, playerButClassNotKnown){
KnownPlayers players;
players.setPlayerClass("PublicLightBus", "multi");
EXPECT_TRUE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("", players.getPlayerClass("PublicLightBus"));
}
TEST(KnownPlayers, setPlayerSubclass){
KnownPlayers players;
players.setPlayerClass("PublicLightBus", "WI");
EXPECT_TRUE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("WI", players.getPlayerClass("PublicLightBus"));
players.setPlayerClass("PublicLightBus", "MA");
EXPECT_TRUE(players.isPlayer("PublicLightBus"));
EXPECT_EQ("WI", players.getPlayerClass("PublicLightBus"));
}
TEST(KnownPlayers, notAPlayer){
KnownPlayers players;
EXPECT_EQ("", players.getPlayerClass("Talon Laborer"));
}
| 25.614035 | 59 | 0.764384 | maxperiod |
ca67ea5da51db24ed967d5f77e4d7709dfa85d35 | 1,621 | cc | C++ | src/load_balancer/lb_entry.cc | cuisonghui/tera | 99a3f16de13dd454a64d64e938fcfeb030674d5f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2,003 | 2015-07-13T08:36:45.000Z | 2022-03-26T02:10:07.000Z | src/load_balancer/lb_entry.cc | a1e2w3/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | [
"Apache-2.0",
"BSD-3-Clause"
] | 981 | 2015-07-14T00:03:24.000Z | 2021-05-10T09:50:01.000Z | src/load_balancer/lb_entry.cc | a1e2w3/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | [
"Apache-2.0",
"BSD-3-Clause"
] | 461 | 2015-07-14T02:53:35.000Z | 2022-03-10T10:31:49.000Z | // Copyright (c) 2015, 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 "load_balancer/lb_entry.h"
#include <string>
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "common/net/ip_address.h"
#include "common/this_thread.h"
#include "load_balancer/lb_impl.h"
#include "load_balancer/lb_service_impl.h"
DECLARE_string(tera_lb_server_addr);
DECLARE_string(tera_lb_server_port);
std::string GetTeraEntryName() { return "lb"; }
tera::TeraEntry* GetTeraEntry() { return new tera::load_balancer::LBEntry(); }
namespace tera {
namespace load_balancer {
LBEntry::LBEntry() : rpc_server_(nullptr), lb_service_impl_(nullptr), lb_impl_(nullptr) {
sofa::pbrpc::RpcServerOptions rpc_options;
rpc_server_.reset(new sofa::pbrpc::RpcServer(rpc_options));
}
LBEntry::~LBEntry() {}
bool LBEntry::StartServer() {
IpAddress lb_addr(FLAGS_tera_lb_server_addr, FLAGS_tera_lb_server_port);
LOG(INFO) << "Start load balancer RPC server at: " << lb_addr.ToString();
lb_impl_.reset(new LBImpl());
lb_service_impl_ = new LBServiceImpl(lb_impl_);
if (!lb_impl_->Init()) {
return false;
}
rpc_server_->RegisterService(lb_service_impl_);
if (!rpc_server_->Start(lb_addr.ToString())) {
LOG(ERROR) << "start RPC server error";
return false;
}
LOG(INFO) << "finish starting load balancer server";
return true;
}
bool LBEntry::Run() {
ThisThread::Sleep(1000);
return true;
}
void LBEntry::ShutdownServer() { rpc_server_->Stop(); }
} // namespace load_balancer
} // namespace tera
| 25.328125 | 89 | 0.728563 | cuisonghui |
ca69449fec6c183ef4191b4396ea1d7790c69444 | 7,832 | cpp | C++ | sys_opt/multiple_process/src/host.cpp | zohourih/Vitis_Accel_Examples | faf1e3f9288ba40047acb7cb4747e8cb4a2f2eb2 | [
"BSD-3-Clause"
] | null | null | null | sys_opt/multiple_process/src/host.cpp | zohourih/Vitis_Accel_Examples | faf1e3f9288ba40047acb7cb4747e8cb4a2f2eb2 | [
"BSD-3-Clause"
] | null | null | null | sys_opt/multiple_process/src/host.cpp | zohourih/Vitis_Accel_Examples | faf1e3f9288ba40047acb7cb4747e8cb4a2f2eb2 | [
"BSD-3-Clause"
] | null | null | null | /**********
Copyright (c) 2019, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********/
/*******************************************************************************
Description:
This is a simple to demonstrate Multi Process Support(MPS) using HLS kernels.
Limitation:
Debug and Profile will not function correctly when multiprocess has been
enabled.
Emulation flow does not have support for multiprocess.
*******************************************************************************/
#include "multi_krnl.h"
#include "xcl2.hpp"
#include <algorithm>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
bool run_kernel(std::string &binaryFile, int krnl_id) {
cl_int err;
const char *krnl_names[] = {"krnl_vadd", "krnl_vsub", "krnl_vmul"};
int pid = getpid();
printf("\n[PID: %d] Start Vector Operation (PARENT PPID: %d)\n",
pid,
getppid());
size_t vector_size_bytes = sizeof(int) * LENGTH;
std::vector<int, aligned_allocator<int>> source_a(LENGTH);
std::vector<int, aligned_allocator<int>> source_b(LENGTH);
std::vector<int, aligned_allocator<int>> result_sw(LENGTH);
std::vector<int, aligned_allocator<int>> result_hw(LENGTH);
/* Create the test data and run the vector addition locally */
std::generate(source_a.begin(), source_a.end(), std::rand);
std::generate(source_b.begin(), source_b.end(), std::rand);
for (int i = 0; i < LENGTH; i++) {
result_hw[i] = 0;
switch (krnl_id) {
case 0:
result_sw[i] = source_a[i] + source_b[i];
break;
case 1:
result_sw[i] = source_a[i] - source_b[i];
break;
case 2:
result_sw[i] = source_a[i] * source_b[i];
break;
default:
std::cout << "Kernel ID is unknown!!" << std::endl;
}
}
// OPENCL HOST CODE AREA START
auto devices = xcl::get_xil_devices();
auto device = devices[0];
OCL_CHECK(err, cl::Context context(device, NULL, NULL, NULL, &err));
OCL_CHECK(
err,
cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE, &err));
std::string device_name = device.getInfo<CL_DEVICE_NAME>();
printf("\n[PID: %d] Read XCLBIN file\n", pid);
auto fileBuf = xcl::read_binary_file(binaryFile);
cl::Program::Binaries bins{{fileBuf.data(), fileBuf.size()}};
devices.resize(1);
printf("[PID: %d] Create a Program and a [ %s ] Kernel\n",
pid,
krnl_names[krnl_id]);
OCL_CHECK(err, cl::Program program(context, devices, bins, NULL, &err));
OCL_CHECK(err, cl::Kernel krnl(program, krnl_names[krnl_id], &err));
OCL_CHECK(err,
cl::Buffer buffer_a(context,
CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
vector_size_bytes,
source_a.data(),
&err));
OCL_CHECK(err,
cl::Buffer buffer_b(context,
CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
vector_size_bytes,
source_b.data(),
&err));
OCL_CHECK(err,
cl::Buffer buffer_c(context,
CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
vector_size_bytes,
result_hw.data(),
&err));
/* Set the kernel arguments */
int vector_length = LENGTH;
OCL_CHECK(err, err = krnl.setArg(0, buffer_a));
OCL_CHECK(err, err = krnl.setArg(1, buffer_b));
OCL_CHECK(err, err = krnl.setArg(2, buffer_c));
OCL_CHECK(err, err = krnl.setArg(3, vector_length));
/* Copy input vectors to memory */
printf("\n[PID: %d] Transfer the Input Data to Device\n", pid);
OCL_CHECK(err,
err = q.enqueueMigrateMemObjects({buffer_a, buffer_b},
0 /* 0 means from host*/));
/* Launch the kernel */
printf("[PID: %d] Launch Kernel\n", pid);
OCL_CHECK(err, err = q.enqueueTask(krnl));
/* Copy result to local buffer */
printf("[PID: %d] Transfer the Output Data from Device\n", pid);
OCL_CHECK(err,
err = q.enqueueMigrateMemObjects({buffer_c},
CL_MIGRATE_MEM_OBJECT_HOST));
q.finish();
// OPENCL HOST CODE AREA END
/* Compare the results of the kernel to the simulation */
bool krnl_match = true;
printf("\n[PID: %d] Checking the Output Data with Golden Results...\n",
pid);
for (int i = 0; i < LENGTH; i++) {
if (result_sw[i] != result_hw[i]) {
printf("Error: i = %d CPU result = %d FPGA Result = %d\n",
i,
result_sw[i],
result_hw[i]);
krnl_match = false;
break;
}
}
return krnl_match;
}
int main(int argc, char *argv[]) {
int iter = 3;
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <XCLBIN File> " << std::endl;
return EXIT_FAILURE;
}
std::string binaryFile = argv[1];
//Setting XCL_MULTIPROCESS_MODE
std::cout << "Set the env variable for Multi Process Support (MPS)"
<< std::endl;
char mps_env[] = "XCL_MULTIPROCESS_MODE=1";
if (putenv(mps_env) != 0) {
std::cout << "putenv failed" << std::endl;
} else
std::cout << "Env variable: XCL_MULTIPROCESS_MODE: "
<< getenv("XCL_MULTIPROCESS_MODE") << std::endl;
bool result = true;
std::cout << "Now create (" << iter << ") CHILD processes" << std::endl;
for (int i = 0; i < iter; i++) {
if (fork() == 0) {
printf(
"[CHILD] PID %d from [PARENT] PPID %d\n", getpid(), getppid());
result = run_kernel(binaryFile, i);
exit(!(result));
}
}
// Need to wait for all child process to complete
for (int i = 0; i < iter; i++)
wait(NULL);
std::cout << "\n[PID: " << getpid() << "] PARENT WAITS CHILD TO FINISH.\n\n"
<< std::endl;
std::cout << "TEST " << ((result) ? "PASSED" : "FAILED") << std::endl;
return ((result) ? EXIT_SUCCESS : EXIT_FAILURE);
}
| 36.427907 | 101 | 0.580567 | zohourih |
ca69464a9aba7930efa09a2802a96b680b239b76 | 191 | hpp | C++ | include/utils.hpp | stereolabs/zed-tracking-viewer | 7b634de51d68a5a46a8156c16a259586a8e6c46c | [
"MIT"
] | 18 | 2016-09-29T16:05:26.000Z | 2020-01-30T09:23:45.000Z | include/utils.hpp | stereolabs/zed-tracking-viewer | 7b634de51d68a5a46a8156c16a259586a8e6c46c | [
"MIT"
] | 10 | 2016-07-05T18:22:58.000Z | 2017-07-28T21:40:26.000Z | include/utils.hpp | stereolabs/zed-tracking-viewer | 7b634de51d68a5a46a8156c16a259586a8e6c46c | [
"MIT"
] | 10 | 2016-08-29T05:59:30.000Z | 2021-02-25T16:30:55.000Z | #ifndef __UTILS_HPP__
#define __UTILS_HPP__
#include <GL/glew.h>
#include "GL/glut.h" /* OpenGL Utility Toolkit header */
#ifndef M_PI
#define M_PI 3.141592653
#endif
#endif
| 15.916667 | 60 | 0.691099 | stereolabs |
ca69e30937a9173f2083f55e5290ec93628ccf73 | 4,996 | cc | C++ | src/test/outmdsd/testbuflog.cc | panaji/fluentd-plugin-mdsd | 6e7680b2e60afd9a5f33f477a7eb50fdea224ee8 | [
"MIT"
] | 20 | 2017-03-24T21:53:16.000Z | 2021-12-22T22:19:42.000Z | src/test/outmdsd/testbuflog.cc | panaji/fluentd-plugin-mdsd | 6e7680b2e60afd9a5f33f477a7eb50fdea224ee8 | [
"MIT"
] | 61 | 2017-01-12T21:22:11.000Z | 2021-07-27T08:22:11.000Z | src/test/outmdsd/testbuflog.cc | panaji/fluentd-plugin-mdsd | 6e7680b2e60afd9a5f33f477a7eb50fdea224ee8 | [
"MIT"
] | 17 | 2017-03-17T22:48:14.000Z | 2021-07-27T04:08:32.000Z | #include <boost/test/unit_test.hpp>
#include "BufferedLogger.h"
#include "DjsonLogItem.h"
#include "testutil.h"
#include "MockServer.h"
using namespace EndpointLog;
BOOST_AUTO_TEST_SUITE(testbuflog)
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_Cstor_cache)
{
try {
BufferedLogger b("/tmp/nosuchfile", 1, 1, 1, 1);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_Cstor_nocache)
{
try {
BufferedLogger b("/tmp/nosuchfile", 0, 1, 1, 1);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_AddData_Null)
{
try {
BufferedLogger b("/tmp/nosuchfile", 1, 1, 1, 1);
BOOST_CHECK_THROW(b.AddData(nullptr), std::invalid_argument);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
// Validate BufferedLogger when socket server is down
static void
TestWhenSockServerIsDown(
size_t nitems
)
{
int connRetryTimeoutMS = 1;
BufferedLogger b("/tmp/nosuchfile", 100000, 100, connRetryTimeoutMS, nitems*10);
for (size_t i = 0; i < nitems; i++) {
LogItemPtr item(new DjsonLogItem("testsource", "testvalue-" + std::to_string(i+1)));
b.AddData(item);
}
// wait timeout depends on nitems and connection retry, plus some runtime
BOOST_CHECK(b.WaitUntilAllSend((connRetryTimeoutMS+10)*nitems+100));
BOOST_CHECK_EQUAL(0, b.GetNumTagsRead());
BOOST_CHECK_EQUAL(0, b.GetTotalSendSuccess());
BOOST_CHECK_EQUAL(0, b.GetTotalResend());
BOOST_CHECK_EQUAL(nitems, b.GetTotalSend());
BOOST_CHECK_EQUAL(nitems, b.GetNumItemsInCache());
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_ServerFailure_1)
{
try {
TestWhenSockServerIsDown(1);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_ServerFailure_100)
{
try {
TestWhenSockServerIsDown(100);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
// Wait until client has nothing in cache to resend.
// Return true if success, false if timeout.
bool
WaitForClientCacheEmpty(
BufferedLogger& bLogger,
int timeoutMS
)
{
for (int i = 0; i < timeoutMS; i++) {
if (0 == bLogger.GetNumItemsInCache()) {
return true;
}
usleep(1000);
}
return false;
}
// Validate that server receives total nitems.
// And each msg is formated like CreateMsg(i)
static void
ValidateServerResults(
const std::unordered_set<std::string>& serverDataSet,
size_t nitems
)
{
BOOST_CHECK_EQUAL(1, serverDataSet.count(TestUtil::EndOfTest()));
BOOST_CHECK_EQUAL(nitems+1, serverDataSet.size()); // end of test is an extra
if (nitems+1 == serverDataSet.size()) {
for (size_t i = 0; i < nitems; i++) {
auto item = TestUtil::CreateMsg(i);
BOOST_CHECK_MESSAGE(1 == serverDataSet.count(item), "Not found '" << item << "'");
}
}
}
static void
RunE2ETest(size_t nitems)
{
const std::string sockfile = TestUtil::GetCurrDir() + "/buflog-e2e";
auto mockServer = std::make_shared<TestUtil::MockServer>(sockfile, true);
mockServer->Init();
auto serverTask = std::async(std::launch::async, [mockServer]() { mockServer->Run(); });
BufferedLogger bLogger(sockfile, 1000000, 100, 100, nitems*2);
size_t totalSend = 0;
for (size_t i = 0; i < nitems; i++) {
auto testdata = TestUtil::CreateMsg(i);
LogItemPtr item(new DjsonLogItem("testsource", testdata));
bLogger.AddData(item);
totalSend += testdata.size();
}
LogItemPtr eot(new DjsonLogItem("testsource", TestUtil::EndOfTest()));
bLogger.AddData(eot);
totalSend += TestUtil::EndOfTest().size();
BOOST_CHECK(bLogger.WaitUntilAllSend(1000));
BOOST_CHECK(mockServer->WaitForTestsDone(1000));
BOOST_CHECK(WaitForClientCacheEmpty(bLogger, 1000));
mockServer->Stop();
serverTask.get();
ValidateServerResults(mockServer->GetUniqDataRead(), nitems);
BOOST_CHECK_LT(0, mockServer->GetTotalTags());
BOOST_CHECK_GT(mockServer->GetTotalBytesRead(), totalSend);
BOOST_CHECK_LE(nitems+1, bLogger.GetNumTagsRead());
BOOST_CHECK_EQUAL(nitems+1, bLogger.GetTotalSendSuccess());
BOOST_CHECK_LE(nitems+1, bLogger.GetTotalSend());
BOOST_CHECK_EQUAL(0, bLogger.GetNumItemsInCache());
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_E2E_1)
{
try {
RunE2ETest(1);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
BOOST_AUTO_TEST_CASE(Test_BufferedLogger_E2E_1000)
{
try {
RunE2ETest(1000);
}
catch(const std::exception & ex) {
BOOST_FAIL("Test exception " << ex.what());
}
}
BOOST_AUTO_TEST_SUITE_END()
| 26.716578 | 94 | 0.66293 | panaji |
ca6a882fad6f92e0978e7daf3a16622a7a1cb67a | 25,924 | cpp | C++ | Source/Anggur/Renderer/Renderer.cpp | NoorWachid/Anggur | 73b14abb238f90d964b9764aa259d8483a5dc593 | [
"MIT"
] | 1 | 2021-06-07T06:29:43.000Z | 2021-06-07T06:29:43.000Z | Source/Anggur/Renderer/Renderer.cpp | NoorWachid/Anggur | 73b14abb238f90d964b9764aa259d8483a5dc593 | [
"MIT"
] | null | null | null | Source/Anggur/Renderer/Renderer.cpp | NoorWachid/Anggur | 73b14abb238f90d964b9764aa259d8483a5dc593 | [
"MIT"
] | null | null | null | #include "Renderer.h"
#include <Anggur/Helper/Log.h>
#include <glad/glad.h>
#define ANGGUR_DEBUG_TEXT_RECTS 1
namespace Anggur
{
struct Vertex
{
float position[2];
float color[4];
float texCoord[2];
float texIndex;
static const size_t length = 9;
};
Shader Renderer::batchShader;
float* Renderer::vertexData;
uint* Renderer::indexData;
size_t Renderer::vertexCounter;
size_t Renderer::indexCounter;
size_t Renderer::maxQuad = 2048;
size_t Renderer::circleSegment = 32;
size_t Renderer::maxVertices;
size_t Renderer::maxIndices;
size_t Renderer::maxTextureUnits;
size_t Renderer::textureCounter;
float Renderer::textureIndex;
int* Renderer::textureIndices;
Texture* Renderer::textureData;
Matrix Renderer::viewProjection;
VertexArray Renderer::vertexArray;
VertexBuffer Renderer::vertexBuffer;
IndexBuffer Renderer::indexBuffer;
Shader& Renderer::GetBatchShader()
{
return batchShader;
}
void Renderer::CreateBatchShader()
{
batchShader.SetVertexSource(R"(
#version 330 core
layout (location = 0) in vec2 aPosition;
layout (location = 1) in vec4 aColor;
layout (location = 2) in vec2 aTexCoord;
layout (location = 3) in float aTexIndex;
out vec4 vColor;
out vec2 vTexCoord;
out float vTexIndex;
uniform mat3 uViewProjection;
void main()
{
gl_Position = vec4(uViewProjection * vec3(aPosition.x, aPosition.y, 1.0f), 1.0f);
vColor = aColor;
vTexCoord = aTexCoord;
vTexIndex = aTexIndex;
}
)");
string fragmentSource = R"(
#version 330 core
layout (location = 0) out vec4 aColor;
in vec4 vColor;
in vec2 vTexCoord;
in float vTexIndex;
uniform sampler2D uTex[16];
void main()
{
int index = int(vTexIndex);
switch (index)
{
// MULTI CHANNELS TEXTURE
case -1:
aColor = vColor;
break;
)";
int maxUnit;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxUnit);
maxTextureUnits = maxUnit;
textureData = new Texture[maxTextureUnits];
textureIndices = new int[maxTextureUnits];
for (size_t i = 0; i < maxTextureUnits; ++i)
{
textureIndices[i] = i;
fragmentSource += "case " + std::to_string(i) + ":\n";
fragmentSource += "aColor = texture(uTex[" + std::to_string(i) + "], vTexCoord) * vColor;\n";
fragmentSource += "break;\n";
fragmentSource += "case " + std::to_string(i + maxTextureUnits) + ":\n";
fragmentSource += "aColor = vec4(1.f, 1.f, 1.f, texture(uTex[" + std::to_string(i) + "], vTexCoord)) * vColor;\n";
fragmentSource += "break;\n";
}
fragmentSource += R"(
}
}
)";
batchShader.SetFragmentSource(fragmentSource);
batchShader.Compile();
}
void Renderer::Initialize()
{
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
CreateBatchShader();
maxVertices = maxQuad * 4;
maxIndices = maxQuad * 6;
vertexArray.Create();
vertexArray.Bind();
vertexData = new float[maxVertices * Vertex::length];
indexData = new uint[maxIndices];
vertexBuffer.Create();
vertexBuffer.Bind();
vertexBuffer.SetCapacity(sizeof(float) * maxVertices * Vertex::length);
vertexArray.SetAttributePtr(0, 2, sizeof(Vertex), (void*)offsetof(Vertex, position));
vertexArray.SetAttributePtr(1, 4, sizeof(Vertex), (void*)offsetof(Vertex, color));
vertexArray.SetAttributePtr(2, 2, sizeof(Vertex), (void*)offsetof(Vertex, texCoord));
vertexArray.SetAttributePtr(3, 1, sizeof(Vertex), (void*)offsetof(Vertex, texIndex));
indexBuffer.Create();
indexBuffer.Bind();
indexBuffer.SetCapacity(sizeof(uint) * maxIndices);
viewProjection = Matrix::identity;
ClearData();
}
void Renderer::Terminate()
{
delete[] vertexData;
delete[] indexData;
delete[] textureData;
delete[] textureIndices;
vertexData = nullptr;
indexData = nullptr;
textureData = nullptr;
textureIndices = nullptr;
indexBuffer.Destroy();
vertexBuffer.Destroy();
vertexArray.Destroy();
batchShader.Destroy();
}
void Renderer::SetDrawMode(DrawMode mode)
{
glPolygonMode(GL_FRONT_AND_BACK, static_cast<int>(mode));
}
void Renderer::SetMaxQuad(size_t max)
{
if (max < circleSegment)
max = circleSegment;
maxQuad = max;
}
void Renderer::SetCircleSegment(size_t segment)
{
if (segment < 3)
segment = 3;
if (maxQuad < segment)
maxQuad = segment;
circleSegment = segment;
}
void Renderer::SetViewport(Vector size)
{
glViewport(0, 0, size.x, size.y);
}
void Renderer::SetViewProjection(const Matrix& vp)
{
viewProjection = vp;
}
void Renderer::ClearBackground(const Color& color)
{
glClearColor(color.r, color.g, color.b, color.a);
glClear(GL_COLOR_BUFFER_BIT);
}
void Renderer::CheckLimit(size_t vertexOffset, size_t indexOffset, size_t textureOffset)
{
if (vertexCounter + vertexOffset > maxVertices)
return Render();
if (indexCounter + indexOffset > maxIndices)
return Render();
if (textureCounter + textureOffset > maxTextureUnits)
return Render();
}
void Renderer::AddData(const float* vetices, size_t vertexLength, const uint* indices, size_t indexLength)
{
size_t vertexOffset = vertexCounter * Vertex::length;
size_t vertexSize = vertexLength * Vertex::length;
for (size_t i = 0; i < vertexSize; ++i)
vertexData[vertexOffset + i] = vetices[i];
for (size_t i = 0; i < indexLength; ++i)
indexData[indexCounter + i] = vertexCounter + indices[i];
vertexCounter += vertexLength;
indexCounter += indexLength;
}
void Renderer::AddTextureData(const Texture& texture)
{
for (size_t i = 0; i < textureCounter; ++i)
{
if (textureData[i].GetID() == texture.GetID())
{
textureIndex = i;
return;
}
}
textureData[textureCounter] = texture;
textureIndex = textureCounter;
textureCounter++;
}
void Renderer::ClearData()
{
vertexCounter = 0;
indexCounter = 0;
textureCounter = 0;
}
void Renderer::Render()
{
if (vertexCounter == 0)
return;
batchShader.Bind();
batchShader.SetMatrix("uViewProjection", viewProjection);
batchShader.SetInt("uTex", maxTextureUnits, textureIndices);
for (size_t i = 0; i < textureCounter; ++i)
textureData[i].Bind(i);
vertexBuffer.Bind();
vertexBuffer.SetData(sizeof(float) * maxVertices * Vertex::length, vertexData);
indexBuffer.Bind();
indexBuffer.SetData(sizeof(uint) * maxIndices, indexData);
vertexArray.Bind();
glDrawElements(GL_TRIANGLES, indexCounter, GL_UNSIGNED_INT, nullptr);
ClearData();
}
// Primitive geometries
void Renderer::AddTriangle(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, const Color& c)
{
CheckLimit(3, 3);
Vector l0 = p0 * transform;
Vector l1 = p1 * transform;
Vector l2 = p2 * transform;
float vertices[] = {
l0.x, l0.y, c.r, c.g, c.b, c.a, 0.f, 0.f, -1,
l1.x, l1.y, c.r, c.g, c.b, c.a, 0.f, 0.f, -1,
l2.x, l2.y, c.r, c.g, c.b, c.a, 0.f, 0.f, -1,
};
uint indices[] = {0, 1, 2};
AddData(vertices, 3, indices, 3);
}
void Renderer::AddQuad(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, const Vector& p3, const Color& c)
{
CheckLimit(4, 6);
Vector l0 = p0 * transform;
Vector l1 = p1 * transform;
Vector l2 = p2 * transform;
Vector l3 = p3 * transform;
float vertices[] = {
l0.x,
l0.y,
c.r,
c.g,
c.b,
c.a,
0.f,
0.f,
-1,
l1.x,
l1.y,
c.r,
c.g,
c.b,
c.a,
0.f,
0.f,
-1,
l2.x,
l2.y,
c.r,
c.g,
c.b,
c.a,
0.f,
0.f,
-1,
l3.x,
l3.y,
c.r,
c.g,
c.b,
c.a,
0.f,
0.f,
-1,
};
uint indices[] = {
0, 1, 2,
2, 3, 0};
AddData(vertices, 4, indices, 6);
}
void Renderer::AddRect(const Matrix& transform, const Vector& p0, const Vector& p1, const Color& color)
{
AddQuad(transform, p0 * transform, Vector(p0.x, p1.y) * transform, p1 * transform, Vector(p1.x, p0.y) * transform, color);
}
void Renderer::AddPolygon(const Matrix& transform, const Vector& p0, float r, size_t segments, const Color& c)
{
if (segments < 3)
segments = 3;
size_t triangles = segments - 2;
CheckLimit(segments, triangles * 3);
float theta = Math::twoPi / segments;
float tangetialFactor = Math::Tan(theta);
float radialFactor = Math::Cos(theta);
float x = r;
float y = 0;
float vertices[segments * Vertex::length];
uint indices[triangles * 3];
for (size_t i = 0, offset = 0; i < segments; i++)
{
Vector point = Vector(p0.x + x, p0.y + y) * transform;
vertices[offset + 0] = x + point.x;
vertices[offset + 1] = y + point.y;
vertices[offset + 2] = c.r;
vertices[offset + 3] = c.g;
vertices[offset + 4] = c.b;
vertices[offset + 5] = c.a;
vertices[offset + 6] = 0;
vertices[offset + 7] = 0;
vertices[offset + 8] = -1;
float tx = -y;
float ty = x;
x += tx * tangetialFactor;
y += ty * tangetialFactor;
x *= radialFactor;
y *= radialFactor;
offset += Vertex::length;
}
for (size_t i = 0, offset = 0; i < triangles; ++i)
{
indices[offset + 0] = 0;
indices[offset + 1] = i + 1;
indices[offset + 2] = i + 2;
offset += 3;
}
AddData(vertices, segments, indices, triangles * 3);
}
void Renderer::AddCircle(const Matrix& transform, const Vector& p0, float r, const Color& c)
{
AddPolygon(transform, p0, r, circleSegment, c);
}
// Complex geometries
void Renderer::AddTerminator(const Matrix& transform, const Vector& p0, const Vector& p1, float weight, const Color& c)
{
Vector p3 = (p0 - p1).Normalize() * weight;
Vector t0 = (p1 - p0).GetPerpen().Normalize() * weight;
AddQuad(transform, p1 + t0, p3 + p0 + t0, p3 + p0 - t0, p1 - t0, c);
}
void Renderer::AddAnchor(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, float w0, const Color& c)
{
Vector i0 = Vector::zero * transform;
Vector l0 = p0 * transform;
Vector l1 = p1 * transform;
Vector l2 = p2 * transform;
Vector t0 = (l1 - l0).GetPerpen();
Vector t2 = (l2 - l1).GetPerpen();
if (0 < ((l1.x - l0.x) * (l2.y - l0.y) - (l2.x - l0.x) * (l1.y - l0.y)))
{
t0 = -t0;
t2 = -t2;
}
t0.SetLength(w0);
t2.SetLength(w0);
Vector u0 = (l0 + t0);
Vector u1 = (l2 + t2);
Vector n0 = (l0 - t0);
Vector n1 = (l2 - t2);
Vector c0 = (l1 + t0);
Vector c1 = (l1 + t2);
Vector d0 = (l1 - t0);
Vector d1 = (l1 - t2);
Vector e0 = ((l1 - l0).SetLength(w0 * 2) + c0);
Vector e1 = ((l1 - l2).SetLength(w0 * 2) + c1);
auto areLinesIntersected = [](
const Vector& p0,
const Vector& p1,
const Vector& p2,
const Vector& p3,
Vector& p4) -> bool
{
float denom = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y);
float numea = (p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x);
float numeb = (p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x);
float denomAbs = Math::Abs(denom);
float numeaAbs = Math::Abs(numea);
float numebAbs = Math::Abs(numeb);
if (numeaAbs < Math::epsilon && numebAbs < Math::epsilon && denomAbs < Math::epsilon)
{
p4 = Vector::Lerp(p0, p1, 0.5);
return true;
}
if (denomAbs < Math::epsilon)
return false;
float mua = numea / denom;
float mub = numeb / denom;
if (mua < 0 || mua > 1 || mub < 0 || mub > 1)
{
return false;
}
float muax = numea / denom;
p4 = (p1 - p0) * muax;
p4 += p0;
return true;
};
bool intersected = areLinesIntersected(c0, e0, c1, e1, i0);
#ifdef ANGGUR_DEBUG_ANCHOR_POINTS
AddCircle(Matrix(), e0, 0.01, Color::red);
AddCircle(Matrix(), e1, 0.01, Color::red);
AddCircle(Matrix(), u0, 0.01, Color::blue);
AddCircle(Matrix(), u1, 0.01, Color::blue);
AddCircle(Matrix(), n0, 0.01, Color::green);
AddCircle(Matrix(), n1, 0.01, Color::green);
AddCircle(Matrix(), c0, 0.01, Color::yellow);
AddCircle(Matrix(), c1, 0.01, Color::yellow);
AddCircle(Matrix(), d0, 0.01, Color::pink);
AddCircle(Matrix(), d1, 0.01, Color::pink);
AddCircle(Matrix(), i0, 0.01, Color::cyan);
AddCircle(Matrix(), l1, 0.01, Color::purple);
return;
#endif
float vertices[] = {
e0.x, e0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 0
e1.x, e1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 1
u0.x, u0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 2
u1.x, u1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 3
n0.x, n0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 4
n1.x, n1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 5
c0.x, c0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 6
c1.x, c1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 7
d0.x, d0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 8
d1.x, d1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 9
i0.x, i0.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 10
l1.x, l1.y, c.r, c.g, c.b, c.a, 0, 0, -1, // 11
};
uint indexLength = 21;
uint indices[] = {
2,
6,
8,
8,
4,
2,
7,
3,
5,
5,
9,
7,
6,
7,
11, // mid
6,
0,
1,
1,
7,
6,
};
if (intersected)
{
indexLength = 18;
indices[15] = 6;
indices[16] = 10;
indices[17] = 7;
}
AddData(vertices, 12, indices, indexLength);
}
void Renderer::AddLine(const Matrix& transform, const Vector& p0, const Vector& p1, float weight, const Color& c)
{
Vector m0 = Vector::Lerp(p0, p1, 0.5);
AddTerminator(transform, p0, m0, weight, c);
AddTerminator(transform, p1, m0, weight, c);
}
void Renderer::AddPolyline(const Matrix& transform, const std::vector<Vector>& ps, float w, const Color& c)
{
if (ps.size() > 1)
{
std::vector<Vector> ms;
for (size_t i = 0; i < ps.size() - 1; ++i)
ms.push_back(Vector::Lerp(ps[i], ps[i + 1], 0.5));
for (size_t i = 1; i < ms.size(); ++i)
AddAnchor(transform, ms[i - 1], ps[i], ms[i], w, c);
AddTerminator(transform, ps.front(), ms.front(), w, c);
AddTerminator(transform, ps.back(), ms.back(), w, c);
}
}
void Renderer::AddPolyring(const Matrix& transform, const std::vector<Vector>& ps, float w, const Color& c)
{
if (ps.size() > 1)
{
std::vector<Vector> ms;
for (size_t i = 0; i < ps.size() - 1; ++i)
ms.push_back(Vector::Lerp(ps[i], ps[i + 1], 0.5));
for (size_t i = 1; i < ms.size(); ++i)
AddAnchor(transform, ms[i - 1], ps[i], ms[i], w, c);
Vector m = Vector::Lerp(ps.front(), ps.back(), 0.5);
AddAnchor(transform, m, ps.front(), ms.front(), w, c);
AddAnchor(transform, ms.back(), ps.back(), m, w, c);
}
}
void Renderer::AddQuadraticBz(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, float w, const Color& c)
{
auto GetLerped = [](const Vector& p0, const Vector& p1, const Vector& p2, float t)
{
Vector pt;
float t2 = t * 2;
float tq = t * t;
float ti = 1.f - t;
float tiq = ti * ti;
pt.x = tiq * p0.x +
ti * t2 * p1.x +
tq * p2.x;
pt.y = tiq * p0.y +
ti * t2 * p1.y +
tq * p2.y;
return pt;
};
std::vector<Vector> points;
for (int i = 0; i <= 10; ++i)
points.push_back(GetLerped(p0, p1, p2, i / 10.f));
AddPolyline(transform, points, w, c);
}
void Renderer::AddQuadraticBzi(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, float w, const Color& c)
{
Vector px = p1 * 2 - (p0 + p2) / 2;
AddQuadraticBz(transform, p0, px, p2, w, c);
}
void Renderer::AddQubicBz(const Matrix& transform, const Vector& p0, const Vector& p1, const Vector& p2, const Vector& p3, float w, const Color& c)
{
auto GetLerped = [](const Vector& p0, const Vector& p1, const Vector& p2, const Vector& p3, float t)
{
Vector pt;
float t3 = t * 3;
float tc = t * t * t;
float ti = 1.f - t;
float tiq = ti * ti;
float tic = ti * ti * ti;
pt.x = tic * p0.x +
tiq * t3 * p1.x +
ti * t3 * t * p2.x +
tc * p3.x;
pt.y = tic * p0.y +
tiq * t3 * p1.y +
ti * t3 * t * p2.y +
tc * p3.y;
return pt;
};
std::vector<Vector> points;
for (int i = 0; i <= 10; ++i)
points.push_back(GetLerped(p0, p1, p2, p3, i / 10.f));
AddPolyline(transform, points, w, c);
}
// Natural geometries
void Renderer::AddConvex(const Matrix& transform, const std::vector<Vector>& ps, const Color& c)
{
size_t triangles = ps.size() - 2;
uint indices[triangles * 3];
float vertices[ps.size() * Vertex::length];
for (size_t i = 0, offset = 0; i < ps.size(); ++i)
{
vertices[offset + 0] = ps[i].x;
vertices[offset + 1] = ps[i].y;
vertices[offset + 2] = c.r;
vertices[offset + 3] = c.g;
vertices[offset + 4] = c.b;
vertices[offset + 5] = c.a;
vertices[offset + 6] = 0;
vertices[offset + 7] = 0;
vertices[offset + 8] = -1;
offset += Vertex::length;
}
for (size_t i = 0, offset = 0; i < triangles; ++i)
{
indices[offset + 0] = 0;
indices[offset + 1] = i + 1;
indices[offset + 2] = i + 2;
offset += 3;
}
AddData(vertices, ps.size(), indices, triangles * 3);
}
// Text
void Renderer::AddText(const Matrix& transform, const Vector& p0, const Vector& p1, const std::string& textBuffer, const TextOption& textOption, Font& textFont, const Color& color)
{
Vector offset = p0;
Vector containerArea = p1 - p0;
Vector occupiedArea;
Vector lineArea;
Vector wordOffset;
Vector wordArea;
occupiedArea.y = -textFont.GetLineHeight() * textOption.size * textOption.lineHeight;
lineArea.y = occupiedArea.y;
wordArea.y = occupiedArea.y - textOption.size * 0.3;
AddRect(transform, p0, p1, Color(0, 0, 1, 0.4));
bool isFit = true;
float wordSpace = textOption.size * textOption.wordSpace;
float letterSpace = textOption.size * textOption.letterSpace;
Vector ellipsisArea;
std::vector<CodepointContainer> ellipsisCcs;
for (size_t i = 0; i < textOption.ellipsis.size(); ++i)
{
int codepoint = textOption.ellipsis[i];
CodepointContainer cc;
cc.glyph = textFont.glyphs[codepoint];
cc.offset.x = ellipsisArea.x;
cc.offset.y = textOption.size * cc.glyph.ascent;
cc.area.x = textOption.size * cc.glyph.size.x;
cc.area.y = textOption.size * cc.glyph.size.y;
ellipsisCcs.push_back(cc);
ellipsisArea.x += cc.area.x + letterSpace;
}
ellipsisArea.x -= letterSpace;
std::vector<CodepointContainer> ccs;
auto CreateNewWord = [&]()
{
wordOffset.x += wordSpace;
lineArea.x += wordArea.x;
lineArea.x += wordSpace;
wordArea.x -= letterSpace;
#ifdef ANGGUR_DEBUG_TEXT_RECTS
AddRect(transform, offset, offset + wordArea, Color(1, 1, 1, 0.33));
#endif
AddTextChunk(transform, offset, ccs, textFont, color);
offset.x += wordOffset.x;
wordOffset.Set(0, 0);
wordArea.x = 0;
ccs.clear();
};
auto CreateNewLine = [&]()
{
offset.x = p0.x;
lineArea.x -= wordSpace;
lineArea.x -= letterSpace;
occupiedArea.x = Math::Max(occupiedArea.x, lineArea.x);
occupiedArea.y += lineArea.y;
#ifdef ANGGUR_DEBUG_TEXT_RECTS
AddRect(transform, offset, offset + lineArea, Color(1, 1, 1, 0.33));
#endif
lineArea.x = 0;
offset.y += lineArea.y;
};
for (size_t i = 0; i < textBuffer.size(); ++i)
{
int codepoint = textBuffer[i];
CodepointContainer cc;
cc.glyph = textFont.glyphs[codepoint];
cc.offset.x = wordOffset.x;
cc.offset.y = textOption.size * cc.glyph.ascent;
cc.area.x = textOption.size * cc.glyph.size.x;
cc.area.y = textOption.size * cc.glyph.size.y;
ccs.push_back(cc);
if (codepoint == '\n')
{
CreateNewWord();
CreateNewLine();
}
else if (codepoint == ' ')
{
if (lineArea.x + wordArea.x > containerArea.x)
{
if (occupiedArea.y + lineArea.y > containerArea.y)
{
occupiedArea.x = Math::Max(occupiedArea.x, lineArea.x);
#ifdef ANGGUR_DEBUG_TEXT_RECTS
AddCircle(transform, p0 + Vector(occupiedArea.x, occupiedArea.y + lineArea.y), 0.1, Color(1, 1, 0, 0.5));
#endif
isFit = false;
AddTextChunk(transform, offset, ellipsisCcs, textFont, color);
break;
}
else
{
CreateNewLine();
CreateNewWord();
}
}
else
CreateNewWord();
}
else
{
// TODO: Split the word if longer than the container area
float x = letterSpace + cc.area.x + textFont.GetKerning(codepoint, textBuffer[i + 1]) * textOption.size;
wordOffset.x += x;
wordArea.x += x;
}
}
if (isFit)
{
CreateNewLine();
CreateNewWord();
}
offset.x = p0.x;
#ifdef ANGGUR_DEBUG_TEXT_RECTS
AddRect(transform, offset, offset + lineArea, Color(1, 1, 1, 0.33));
AddRect(transform, p0, p0 + occupiedArea, Color(1, 1, 1, 0.33));
AddCircle(transform, p0 + containerArea, 0.1, Color::green);
#endif
}
void Renderer::AddTextChunk(const Matrix& transform, const Vector& p0, const std::vector<CodepointContainer>& ccs, Font& textFont, const Color& color)
{
for (const CodepointContainer& cc: ccs)
{
#ifdef ANGGUR_DEBUG_TEXT_RECTS
AddRect(transform, p0 + cc.offset, p0 + cc.offset + cc.area, Color(1, 1, 1, 0.33));
#endif
AddQuadx(
Vector(p0.x + cc.offset.x, p0.y + cc.offset.y) * transform,
Vector(p0.x + cc.offset.x + cc.area.x, p0.y + cc.offset.y) * transform,
Vector(p0.x + cc.offset.x + cc.area.x, p0.y + cc.offset.y + cc.area.y) * transform,
Vector(p0.x + cc.offset.x, p0.y + cc.offset.y + cc.area.y) * transform,
Vector(cc.glyph.x, cc.glyph.y),
Vector(cc.glyph.x + cc.glyph.w, cc.glyph.y),
Vector(cc.glyph.x + cc.glyph.w, cc.glyph.y + cc.glyph.h),
Vector(cc.glyph.x, cc.glyph.y + cc.glyph.h),
textFont.GetTexture(),
color);
}
}
// Textured geometries
void Renderer::AddQuadx(const Vector& p0, const Vector& p1, const Vector& p2, const Vector& p3, const Vector& t0, const Vector& t1, const Vector& t2, const Vector& t3, const Texture& t, const Color& c)
{
CheckLimit(4, 6, 1);
AddTextureData(t);
float ti = textureIndex;
if (t.GetChannels() == 1)
ti += maxTextureUnits;
float vertices[] = {
p0.x,
p0.y,
c.r,
c.g,
c.b,
c.a,
t0.x,
t0.y,
ti,
p1.x,
p1.y,
c.r,
c.g,
c.b,
c.a,
t1.x,
t1.y,
ti,
p2.x,
p2.y,
c.r,
c.g,
c.b,
c.a,
t2.x,
t2.y,
ti,
p3.x,
p3.y,
c.r,
c.g,
c.b,
c.a,
t3.x,
t3.y,
ti,
};
uint indices[] = {
0,
1,
2,
2,
3,
0,
};
AddData(vertices, 4, indices, 6);
}
void Renderer::Addx(const Vector& p0, const Texture& t, const Color& c)
{
float w = t.GetWidth();
float h = t.GetHeight();
AddQuadx(
p0,
{p0.x + w, p0.y},
{p0.x + w, p0.y + h},
{p0.x, p0.y + h},
{0.f, 0.f},
{1.f, 0.f},
{1.f, 1.f},
{0.f, 1.f},
t,
c);
}
void Renderer::AddRectx(const Vector& p0, float w, float h, const Texture& t, const Color& c)
{
AddQuadx(
p0,
{p0.x + w, p0.y},
{p0.x + w, p0.y + h},
{p0.x, p0.y + h},
{0, 0},
{1, 0},
{1, 1},
{0, 1},
t,
c);
}
void Renderer::AddBoxx(const Vector& position, const Vector& radii, const Texture& t, const Color& c)
{
AddQuadx(
{position.x - radii.x, position.y - radii.y},
{position.x + radii.x, position.y - radii.y},
{position.x + radii.x, position.y + radii.y},
{position.x - radii.x, position.y + radii.y},
{0, 0},
{1, 0},
{1, 1},
{0, 1},
t,
c);
}
} // namespace Anggur
| 25.846461 | 201 | 0.543126 | NoorWachid |
ca7cf8f7f94ccb57322f9fa7393614ff7a6131bf | 899 | cpp | C++ | libs/core/input/samples/mouse/sample_input_mouse_main.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/input/samples/mouse/sample_input_mouse_main.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/input/samples/mouse/sample_input_mouse_main.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file sample_input_mouse_main.cpp
*
* @brief マウス入力のサンプル
*
* @author myoukaku
*/
#include <bksge/core/input.hpp>
#include <bksge/core/math.hpp>
#include <iostream>
int main()
{
bksge::MouseManager mouse;
for (;;)
{
mouse.Update();
auto const& state = mouse.state(0);
if (state.pressed(bksge::MouseButton::kLeft))
{
std::cout << "Press: Left" << std::endl;
}
if (state.pressed(bksge::MouseButton::kRight))
{
std::cout << "Press: Right" << std::endl;
}
if (state.pressed(bksge::MouseButton::kMiddle))
{
std::cout << "Press: Middle" << std::endl;
}
bksge::Vector3f const vel(
state.velocity(bksge::MouseAxis::kX),
state.velocity(bksge::MouseAxis::kY),
state.velocity(bksge::MouseAxis::kWheel));
if (vel != bksge::Vector3f::Zero())
{
std::cout << vel << std::endl;
}
}
return 0;
}
| 18.729167 | 50 | 0.586207 | myoukaku |
ca7d4a3a1c5391b14b40a27a73a855398a2fe8b7 | 1,065 | cpp | C++ | binary_search/binary_search/153_find_minimum_in_rotated_sorted_array.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:19.000Z | 2020-10-12T19:18:19.000Z | binary_search/binary_search/153_find_minimum_in_rotated_sorted_array.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | null | null | null | binary_search/binary_search/153_find_minimum_in_rotated_sorted_array.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:04.000Z | 2020-10-12T19:18:04.000Z | //
// 153_find_minimum_in_rotated_sorted_array.cpp
// binary_search
//
// Created by Hadley on 08.08.20.
// Copyright © 2020 Hadley. All rights reserved.
//
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stack>
#include <cstring>
#include <queue>
#include <functional>
#include <numeric>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.size()==1||nums[0]<nums[nums.size()-1])return nums[0];
int l=0;
auto n=nums.size();
int r=n-1;
while(l<=r){
int mid=l+(r-l)/2;
if(nums[mid]<nums[r]){
if(mid==0||nums[mid]<nums[mid-1]){
return nums[mid];
}else{
r=mid-1;
}
}else{
if(nums[mid]>nums[mid+1]){
return nums[mid+1];
}else{
l=mid+1;
}
}
}
return 0;
}
};
| 22.1875 | 70 | 0.490141 | Hadleyhzy |
ca7fe8faab4db6a745ca19bd210755ff85062973 | 4,314 | cpp | C++ | plugins/core/qAnimation/src/ViewInterpolate.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | plugins/core/qAnimation/src/ViewInterpolate.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | plugins/core/qAnimation/src/ViewInterpolate.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | 1 | 2019-02-03T12:19:42.000Z | 2019-02-03T12:19:42.000Z | //##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: qAnimation #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: Ryan Wicks, 2G Robotics Inc., 2015 #
//# #
//##########################################################################
#include "ViewInterpolate.h"
ViewInterpolate::ViewInterpolate()
: m_view1 ( NULL )
, m_view2 ( NULL )
, m_totalSteps ( 0 )
, m_currentStep ( 0 )
{
}
ViewInterpolate::ViewInterpolate(cc2DViewportObject * viewParams1, cc2DViewportObject * viewParams2, unsigned int stepCount )
: m_view1 ( viewParams1 )
, m_view2 ( viewParams2 )
, m_totalSteps ( stepCount )
, m_currentStep ( 0 )
{
}
//helper function for interpolating between simple numerical types
template <class T> T InterpolateNumber( T start, T end, double interpolationFraction )
{
return static_cast < T > ( static_cast<double>(start) + (static_cast<double>(end) - static_cast<double>(start)) * interpolationFraction );
}
bool ViewInterpolate::nextView ( cc2DViewportObject& outViewport )
{
if ( m_currentStep >= m_totalSteps
|| m_view1 == NULL
|| m_view2 == NULL )
{
return false;
}
//initial and final views
const ccViewportParameters& viewParams1 = m_view1->getParameters();
const ccViewportParameters& viewParams2 = m_view2->getParameters();
ccViewportParameters interpView = m_view1->getParameters();
//interpolation fraction
double interpolate_fraction = static_cast <double>(m_currentStep) / m_totalSteps;
interpView.pixelSize = InterpolateNumber ( viewParams1.pixelSize, viewParams2.pixelSize, interpolate_fraction );
interpView.zoom = InterpolateNumber ( viewParams1.zoom, viewParams2.zoom, interpolate_fraction );
interpView.defaultPointSize = InterpolateNumber ( viewParams1.defaultPointSize, viewParams2.defaultPointSize, interpolate_fraction );
interpView.defaultLineWidth = InterpolateNumber ( viewParams1.defaultLineWidth, viewParams2.defaultLineWidth, interpolate_fraction );
interpView.zNearCoef = InterpolateNumber ( viewParams1.zNearCoef, viewParams2.zNearCoef, interpolate_fraction );
interpView.zNear = InterpolateNumber ( viewParams1.zNear, viewParams2.zNear, interpolate_fraction );
interpView.zFar = InterpolateNumber ( viewParams1.zFar, viewParams2.zFar, interpolate_fraction );
interpView.fov = InterpolateNumber ( viewParams1.fov, viewParams2.fov, interpolate_fraction );
interpView.perspectiveAspectRatio = InterpolateNumber ( viewParams1.perspectiveAspectRatio, viewParams2.perspectiveAspectRatio, interpolate_fraction );
interpView.orthoAspectRatio = InterpolateNumber ( viewParams1.orthoAspectRatio, viewParams2.orthoAspectRatio, interpolate_fraction );
interpView.viewMat = ccGLMatrixd::Interpolate(interpolate_fraction, viewParams1.viewMat, viewParams2.viewMat);
interpView.pivotPoint = viewParams1.pivotPoint + (viewParams2.pivotPoint - viewParams1.pivotPoint) * interpolate_fraction;
interpView.cameraCenter = viewParams1.cameraCenter + (viewParams2.cameraCenter - viewParams1.cameraCenter) * interpolate_fraction;
outViewport.setParameters( interpView );
++m_currentStep;
return true;
}
| 53.925 | 155 | 0.621929 | ohanlonl |
ca7ffcf02d80854f65a95f7ca88413fe1d1d33f8 | 1,264 | hpp | C++ | sprig/serialization/sprig/utility.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | 2 | 2017-10-24T13:56:24.000Z | 2018-09-28T13:21:22.000Z | sprig/serialization/sprig/utility.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | null | null | null | sprig/serialization/sprig/utility.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | 2 | 2016-04-12T03:26:06.000Z | 2018-09-28T13:21:22.000Z | /*=============================================================================
Copyright (c) 2010-2016 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprig
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPRIG_SERIALIZATION_SPRIG_UTILITY_HPP
#define SPRIG_SERIALIZATION_SPRIG_UTILITY_HPP
#include <sprig/config/config.hpp>
#ifdef SPRIG_USING_PRAGMA_ONCE
# pragma once
#endif // #ifdef SPRIG_USING_PRAGMA_ONCE
#include <boost/serialization/nvp.hpp>
#include <sprig/utility/serialization.hpp>
#include <sprig/utility/utility.hpp>
SPRIG_SERIALIZATION_NAMESPACE_BEGIN
template<typename Archive>
SPRIG_INLINE void serialize(
Archive&,
sprig::empty_class&,
unsigned int const
)
{}
template<typename Archive, typename T>
SPRIG_INLINE void serialize(
Archive&,
sprig::empty_class_type_to<T>&,
unsigned int const
)
{}
template<typename Archive, int N>
SPRIG_INLINE void serialize(
Archive&,
sprig::empty_class_enum<N>&,
unsigned int const
)
{}
SPRIG_SERIALIZATION_NAMESPACE_END
#endif // #ifndef SPRIG_SERIALIZATION_SPRIG_UTILITY_HPP
| 27.478261 | 79 | 0.685918 | bolero-MURAKAMI |
ca803721a17b979fcb480f1e41eb285ddb9e9234 | 6,759 | cpp | C++ | bbruntime_dll/bbruntime_dll.cpp | cooljith91112/blitz3d_msvc2017 | 6c8e0f570bea314837cf71bc9ef016255c1d56b3 | [
"Zlib"
] | 169 | 2015-01-01T21:51:22.000Z | 2022-03-31T04:43:37.000Z | bbruntime_dll/bbruntime_dll.cpp | quartexNOR/blitz3d | 647f304ef81387d8235b084bb1d9cb7ba5ff139e | [
"Zlib"
] | 2 | 2019-03-01T20:18:14.000Z | 2022-01-01T17:50:00.000Z | bbruntime_dll/bbruntime_dll.cpp | quartexNOR/blitz3d | 647f304ef81387d8235b084bb1d9cb7ba5ff139e | [
"Zlib"
] | 83 | 2015-01-11T04:26:37.000Z | 2022-03-21T07:38:25.000Z |
#pragma warning( disable:4786 )
#include "bbruntime_dll.h"
#include "../debugger/debugger.h"
#ifdef PRODEMO
#include "../shareprot/shareprot.h"
#endif
using namespace std;
#include <map>
#include <eh.h>
#include <float.h>
#include "../bbruntime/bbruntime.h"
class DummyDebugger : public Debugger{
public:
virtual void debugRun(){}
virtual void debugStop(){}// bbruntime_panic(0); }
virtual void debugStmt( int srcpos,const char *file ){}
virtual void debugEnter( void *frame,void *env,const char *func ){}
virtual void debugLeave(){}
virtual void debugLog( const char *msg ){}
virtual void debugMsg( const char *e,bool serious ){
if( serious ) MessageBox( 0,e,"Error!",MB_OK|MB_TOPMOST|MB_SETFOREGROUND );
}
virtual void debugSys( void *msg ){}
};
static HINSTANCE hinst;
static map<const char*,void*> syms;
map<const char*,void*>::iterator sym_it;
static gxRuntime *gx_runtime;
static void rtSym( const char *sym,void *pc ){
syms[sym]=pc;
}
#ifdef PRODEMO
static void killer(){
ExitProcess( -1 );
}
#endif
static void _cdecl seTranslator( unsigned int u,EXCEPTION_POINTERS* pExp ){
switch( u ){
case EXCEPTION_INT_DIVIDE_BY_ZERO:
bbruntime_panic( "Integer divide by zero" );
case EXCEPTION_ACCESS_VIOLATION:
bbruntime_panic( "Memory access violation" );
case EXCEPTION_ILLEGAL_INSTRUCTION:
bbruntime_panic( "Illegal instruction" );
case EXCEPTION_STACK_OVERFLOW:
bbruntime_panic( "Stack overflow!" );
}
bbruntime_panic( "Unknown runtime exception" );
}
int Runtime::version(){
return VERSION;
}
const char *Runtime::nextSym(){
if( !syms.size() ){
bbruntime_link( rtSym );
sym_it=syms.begin();
}
if( sym_it==syms.end() ){
syms.clear();return 0;
}
return (sym_it++)->first;
}
int Runtime::symValue( const char *sym ){
map<const char*,void*>::iterator it=syms.find( sym );
if( it!=syms.end() ) return (int)it->second;
return -1;
}
void Runtime::startup( HINSTANCE h ){
hinst=h;
}
void Runtime::shutdown(){
trackmem( false );
syms.clear();
}
void Runtime::execute( void (*pc)(),const char *args,Debugger *dbg ){
bool debug=!!dbg;
static DummyDebugger dummydebug;
if( !dbg ) dbg=&dummydebug;
trackmem( true );
_se_translator_function old_trans=_set_se_translator( seTranslator );
_control87( _RC_NEAR|_PC_24|_EM_INVALID|_EM_ZERODIVIDE|_EM_OVERFLOW|_EM_UNDERFLOW|_EM_INEXACT|_EM_DENORMAL,0xfffff );
//strip spaces from ends of args...
string params=args;
while( params.size() && params[0]==' ' ) params=params.substr( 1 );
while( params.size() && params[params.size()-1]==' ' ) params=params.substr( 0,params.size()-1 );
if( gx_runtime=gxRuntime::openRuntime( hinst,params,dbg ) ){
#ifdef PRODEMO
shareProtCheck( killer );
#endif
bbruntime_run( gx_runtime,pc,debug );
gxRuntime *t=gx_runtime;
gx_runtime=0;
gxRuntime::closeRuntime( t );
}
_control87( _CW_DEFAULT,0xfffff );
_set_se_translator( old_trans );
}
void Runtime::asyncStop(){
if( gx_runtime ) gx_runtime->asyncStop();
}
void Runtime::asyncRun(){
if( gx_runtime ) gx_runtime->asyncRun();
}
void Runtime::asyncEnd(){
if( gx_runtime ) gx_runtime->asyncEnd();
}
void Runtime::checkmem( streambuf *buf ){
ostream out( buf );
::checkmem( out );
}
Runtime *_cdecl runtimeGetRuntime(){
static Runtime runtime;
return &runtime;
}
/********************** BUTT UGLY DLL->EXE HOOK! *************************/
static void *module_pc;
static map<string,int> module_syms;
static map<string,int> runtime_syms;
static Runtime *runtime;
static void fail(){
MessageBox( 0,"Unable to run Blitz Basic module",0,0 );
ExitProcess(-1);
}
struct Sym{
string name;
int value;
};
static Sym getSym( void **p ){
Sym sym;
char *t=(char*)*p;
while( char c=*t++ ) sym.name+=c;
sym.value=*(int*)t+(int)module_pc;
*p=t+4;return sym;
}
static int findSym( const string &t ){
map<string,int>::iterator it;
it=module_syms.find( t );
if( it!=module_syms.end() ) return it->second;
it=runtime_syms.find( t );
if( it!=runtime_syms.end() ) return it->second;
string err="Can't find symbol: "+t;
MessageBox( 0,err.c_str(),0,0 );
ExitProcess(0);
return 0;
}
static void link(){
while( const char *sc=runtime->nextSym() ){
string t(sc);
if( t[0]=='_' ){
runtime_syms["_"+t]=runtime->symValue(sc);
continue;
}
if( t[0]=='!' ) t=t.substr(1);
if( !isalnum(t[0]) ) t=t.substr(1);
for( int k=0;k<t.size();++k ){
if( isalnum(t[k]) || t[k]=='_' ) continue;
t=t.substr( 0,k );break;
}
runtime_syms["_f"+tolower(t)]=runtime->symValue(sc);
}
HRSRC hres=FindResource( 0,MAKEINTRESOURCE(1111),RT_RCDATA );if( !hres ) fail();
HGLOBAL hglo=LoadResource( 0,hres );if( !hglo ) fail();
void *p=LockResource( hglo );if( !p ) fail();
int sz=*(int*)p;p=(int*)p+1;
//replace malloc for service pack 2 Data Execution Prevention (DEP).
module_pc=VirtualAlloc( 0,sz,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE );
memcpy( module_pc,p,sz );
p=(char*)p+sz;
int k,cnt;
cnt=*(int*)p;p=(int*)p+1;
for( k=0;k<cnt;++k ){
Sym sym=getSym( &p );
if( sym.value<(int)module_pc || sym.value>=(int)module_pc+sz ) fail();
module_syms[sym.name]=sym.value;
}
cnt=*(int*)p;p=(int*)p+1;
for( k=0;k<cnt;++k ){
Sym sym=getSym( &p );
int *pp=(int*)sym.value;
int dest=findSym( sym.name );
*pp+=dest-(int)pp;
}
cnt=*(int*)p;p=(int*)p+1;
for( k=0;k<cnt;++k ){
Sym sym=getSym( &p );
int *pp=(int*)sym.value;
int dest=findSym( sym.name );
*pp+=dest;
}
runtime_syms.clear();
module_syms.clear();
}
extern "C" _declspec(dllexport) int _stdcall bbWinMain();
extern "C" BOOL _stdcall _DllMainCRTStartup( HANDLE,DWORD,LPVOID );
bool WINAPI DllMain( HANDLE module,DWORD reason,void *reserved ){
return TRUE;
}
int __stdcall bbWinMain(){
HINSTANCE inst=GetModuleHandle( 0 );
_DllMainCRTStartup( inst,DLL_PROCESS_ATTACH,0 );
#ifdef BETA
int ver=VERSION & 0x7fff;
string t="Created with Blitz3D Beta V"+itoa( ver/100 )+"."+itoa( ver%100 );
MessageBox( GetDesktopWindow(),t.c_str(),"Blitz3D Message",MB_OK );
#endif
#ifdef SCHOOLS
MessageBox( GetDesktopWindow(),"Created with the schools version of Blitz Basic","Blitz Basic Message",MB_OK );
#endif
runtime=runtimeGetRuntime();
runtime->startup( inst );
link();
//get cmd_line and params
string cmd=GetCommandLine(),params;
while( cmd.size() && cmd[0]==' ' ) cmd=cmd.substr( 1 );
if( cmd.find( '\"' )==0 ){
int n=cmd.find( '\"',1 );
if( n!=string::npos ){
params=cmd.substr( n+1 );
cmd=cmd.substr( 1,n-1 );
}
}else{
int n=cmd.find( ' ' );
if( n!=string::npos ){
params=cmd.substr( n+1 );
cmd=cmd.substr( 0,n );
}
}
runtime->execute( (void(*)())module_pc,params.c_str(),0 );
runtime->shutdown();
_DllMainCRTStartup( inst,DLL_PROCESS_DETACH,0 );
ExitProcess(0);
return 0;
}
| 22.160656 | 118 | 0.67007 | cooljith91112 |
ca869b636ec9246c44585f420672f45664ac0b5a | 7,061 | hpp | C++ | control/velocity_controller_holonomic.hpp | jlecoeur/MAVRIC_Library | 56281851da7541d5c1199490a8621d7f18482be1 | [
"BSD-3-Clause"
] | 12 | 2016-07-12T10:26:47.000Z | 2021-12-14T10:03:11.000Z | control/velocity_controller_holonomic.hpp | jlecoeur/MAVRIC_Library | 56281851da7541d5c1199490a8621d7f18482be1 | [
"BSD-3-Clause"
] | 183 | 2015-01-22T12:35:18.000Z | 2017-06-09T10:11:26.000Z | control/velocity_controller_holonomic.hpp | jlecoeur/MAVRIC_Library | 56281851da7541d5c1199490a8621d7f18482be1 | [
"BSD-3-Clause"
] | 25 | 2015-02-03T15:15:48.000Z | 2021-12-14T08:55:04.000Z | /*******************************************************************************
* Copyright (c) 2009-2016, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* \file velocity_controller_holonomic.hpp
*
* \author MAV'RIC Team
* \author Julien Lecoeur
*
* \brief A velocity controller for holonomic hovering platform capable of generating 3D thrust
*
* \details It takes a velocity command as input and computes an attitude
* command and thrust command as output.
*
******************************************************************************/
#ifndef VELOCITY_CONTROLLER_HOLONOMIC_HPP_
#define VELOCITY_CONTROLLER_HOLONOMIC_HPP_
#include "control/velocity_controller_copter.hpp"
/**
* \brief Velocity controller for hovering platforms
*/
class Velocity_controller_holonomic : public Velocity_controller_copter
{
public:
/**
* \brief Velocity controller configuration
*/
struct conf_t: public Velocity_controller_copter::conf_t
{
pid_controller_conf_t attitude_offset_config[2];
};
/**
* \brief Default Configuration
*
* /return config
*/
static inline conf_t default_config(void);
/**
* \brief Constructor
*
* \param ahrs Reference to estimated attitude
* \param ins Reference to estimated speed and position
* \param config Configuration
*/
Velocity_controller_holonomic(const args_t& args, const conf_t& config = default_config());
protected:
/**
* \brief Computes attitude and thrust command based on desired acceleration. Depends on robot dynamics
*
* \param accel_vector Desired acceleration vectors (input)
* \param attitude_command Attitude command (output)
* \param thrust_command Thrust command (output)
*
* \return success
*/
virtual bool compute_attitude_and_thrust_from_desired_accel(const std::array<float,3>& accel_command,
attitude_command_t& attitude_command,
thrust_command_t& thrust_command);
public:
uint32_t use_3d_thrust_; ///< Boolean indicating if 3D thrust is generated instead of banking
uint32_t use_3d_thrust_threshold_; ///< Boolean indicating if 3D thrust is generated instead of banking only for low desired accel_vector
float accel_threshold_3d_thrust_; ///< Maximum accel command bellow which 3d thrust will be used if *use_3d_thrust_threshold_* is set to true
pid_controller_t attitude_offset_pid_[2]; ///< Attitude offset
};
Velocity_controller_holonomic::conf_t Velocity_controller_holonomic::default_config(void)
{
conf_t conf;
(*(Velocity_controller_copter::conf_t*)&conf) = Velocity_controller_copter::default_config();
// Do control in semilocal frame
conf.control_frame = SEMILOCAL_FRAME;
// -----------------------------------------------------------------
// ------ ROLL OFFSET ----------------------------------------------
// -----------------------------------------------------------------
conf.attitude_offset_config[X] = {};
conf.attitude_offset_config[X].p_gain = 0.0f;
conf.attitude_offset_config[X].clip_min = -0.5f;
conf.attitude_offset_config[X].clip_max = 0.5f;
conf.attitude_offset_config[X].integrator = {};
conf.attitude_offset_config[X].integrator.gain = 0.001f;
conf.attitude_offset_config[X].integrator.clip_pre = 0.1f;
conf.attitude_offset_config[X].integrator.accumulator = 0.0f;
conf.attitude_offset_config[X].integrator.clip = 0.5f;
conf.attitude_offset_config[X].differentiator = {};
conf.attitude_offset_config[X].differentiator.gain = 0.0f;
conf.attitude_offset_config[X].differentiator.previous = 0.0f;
conf.attitude_offset_config[X].differentiator.clip = 0.0f;
conf.attitude_offset_config[X].soft_zone_width = 0.0f;
// -----------------------------------------------------------------
// ------ PITCH OFFSET ---------------------------------------------
// -----------------------------------------------------------------
conf.attitude_offset_config[Y] = {};
conf.attitude_offset_config[Y].p_gain = 0.0f;
conf.attitude_offset_config[Y].clip_min = -0.5f;
conf.attitude_offset_config[Y].clip_max = 0.5f;
conf.attitude_offset_config[Y].integrator = {};
conf.attitude_offset_config[Y].integrator.gain = 0.001f;
conf.attitude_offset_config[Y].integrator.clip_pre = 0.1f;
conf.attitude_offset_config[Y].integrator.accumulator = 0.0f;
conf.attitude_offset_config[Y].integrator.clip = 0.5f;
conf.attitude_offset_config[Y].differentiator = {};
conf.attitude_offset_config[Y].differentiator.gain = 0.0f;
conf.attitude_offset_config[Y].differentiator.previous = 0.0f;
conf.attitude_offset_config[Y].differentiator.clip = 0.0f;
conf.attitude_offset_config[Y].soft_zone_width = 0.0f;
return conf;
}
#endif /* VELOCITY_CONTROLLER_HOLONOMIC_HPP_ */
| 45.554839 | 159 | 0.615635 | jlecoeur |
ca8738af26b4b76ac7b3ca0adbcd6774bb95e168 | 17,300 | cc | C++ | src/api/assets/audio.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/assets/audio.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/assets/audio.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | #include "audio.hh"
#include <ogg/ogg.h>
#include <vorbis/codec.h>
#include <commons/dataBuffer.hh>
#include <commons/fileio.hh>
#include <cstring>
#include <cmath>
float dBToVolume(float dB)
{
return powf(10.0f, 0.05f * dB);
}
float volumeTodB(float vol)
{
return 20.0f * log10f(vol);
}
AudioInfo decodeAudio(FILE *input, std::string const &filePath)
{
AudioInfo out{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
out = fromWAV(input, filePath);
if(out.format == AudioFormat::NONE || out.bitsPerSample == 0 || out.numChannels == 0 || out.sampleRate == 0 || out.samples.empty())
{
out = fromOGG(input, filePath);
}
/*if(out.format == AudioFormat::NONE || out.bitsPerSample == 0 || out.numChannels == 0 || out.sampleRate == 0 || out.samples.empty())
{
out = fromOpus(input, filePath);
}*/
if(out.format == AudioFormat::NONE || out.bitsPerSample == 0 || out.numChannels == 0 || out.sampleRate == 0 || out.samples.empty())
{
printf("Failed to decode file %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
return out;
}
AudioInfo decodeAudio(std::vector<uint8_t> const &input, std::string const &fileName)
{
AudioInfo out{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
out = fromOGG(input, fileName);
if(out.format == AudioFormat::NONE || out.bitsPerSample == 0 || out.numChannels == 0 || out.sampleRate == 0 || out.samples.empty())
{
out = fromWAV(input, fileName);
}
if(out.format == AudioFormat::NONE || out.bitsPerSample == 0 || out.numChannels == 0 || out.sampleRate == 0 || out.samples.empty())
{
printf("Failed to decode file %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
return out;
}
AudioInfo fromWAV(FILE *input, std::string const &filePath)
{
//http://soundfile.sapp.org/doc/WaveFormat/
std::vector<int16_t> output;
char chunkID[4], waveFormat[4], subchunk1Id[4], subchunk2Id[4];
int subchunk1Size = 0, audioFormat = 0;
size_t dataSize = 0;
int16_t numChannels = 0, bitsPerSample = 0;
int32_t sampleRate = 0;
readFile(input, chunkID, 4);
if(memcmp("RIFF", chunkID, 4) != 0)
{
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
fseek(input, 4, SEEK_CUR); //Skips ChunkSize
readFile(input, waveFormat, 4);
if(memcmp("WAVE", waveFormat, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing format in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
readFile(input, subchunk1Id, 4);
if(memcmp("fmt ", subchunk1Id, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing subchunk 1 ID in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
readFile(input, reinterpret_cast<uint8_t *>(&subchunk1Size), 4);
if(16 != subchunk1Size)
{
printf("WAV Decoder: Malformed wave file, wrong subchunk 1 size in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
readFile(input, reinterpret_cast<uint8_t *>(&audioFormat), 2);
if(1 != audioFormat)
{
printf("WAV Decoder: Compression is unsupported, offending file is: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
readFile(input, reinterpret_cast<uint8_t *>(&numChannels), 2);
readFile(input, reinterpret_cast<uint8_t *>(&sampleRate), 4);
fseek(input, 6, SEEK_CUR); //Skips ByteRate and BlockAlign
readFile(input, reinterpret_cast<uint8_t *>(&bitsPerSample), 2);
readFile(input, subchunk2Id, 4);
if(memcmp("data", subchunk2Id, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing subchunk 2 ID in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
readFile(input, reinterpret_cast<char *>(&dataSize), 4);
output.resize(dataSize);
readFile(input, output.data(), dataSize);
closeFile(input);
return AudioInfo{output, numChannels, bitsPerSample, sampleRate, AudioFormat::WAVE};
}
AudioInfo fromOGG(FILE *input, std::string const &filePath)
{
std::vector<int16_t> output;
ogg_int16_t convbuffer[4096];
int convsize = 4096;
int16_t numChannels = 0, bitsPerSample = 0;
int32_t sampleRate = 0;
ogg_sync_state syncState;
ogg_stream_state streamState;
ogg_page page;
ogg_packet packet;
vorbis_info vorbisInfo;
vorbis_comment comment;
vorbis_dsp_state dspState;
vorbis_block block;
size_t bytesRen = 0;
char *buffer;
ogg_sync_init(&syncState);
while(true)
{
int eos = 0;
buffer = ogg_sync_buffer(&syncState, 4096);
bytesRen = readFile(input, buffer, 4096);
ogg_sync_wrote(&syncState, (long)bytesRen);
if(ogg_sync_pageout(&syncState, &page) != 1) if(bytesRen < 4096) break;
ogg_stream_init(&streamState, ogg_page_serialno(&page));
vorbis_info_init(&vorbisInfo);
vorbis_comment_init(&comment);
if(ogg_stream_pagein(&streamState, &page) < 0)
{
printf("OGG Decoder: Error reading first page of OGG bitstream in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
if(ogg_stream_packetout(&streamState, &packet) != 1)
{
printf("OGG Decoder: Error reading initial header in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
if(vorbis_synthesis_headerin(&vorbisInfo, &comment, &packet) < 0)
{
printf("OGG Decoder: File does not contain Vorbis audio: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
int i = 0;
while(i < 2)
{
while(i < 2)
{
int result = ogg_sync_pageout(&syncState, &page);
if(result == 0) break;
if(result == 1)
{
ogg_stream_pagein(&streamState, &page);
while(i < 2)
{
result = ogg_stream_packetout(&streamState, &packet);
if(result == 0) break;
if(result < 0)
{
printf("OGG Decoder: Corrupted secondary header in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
result = vorbis_synthesis_headerin(&vorbisInfo, &comment, &packet);
if(result < 0)
{
printf("OGG Decoder: Corrupted secondary header in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
i++;
}
}
}
buffer = ogg_sync_buffer(&syncState, 4096);
readFile(input, buffer, 4096);
if(bytesRen == 0 && i < 2)
{
printf("OGG Decoder: End of file reached before finding all Vorbis headers in: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
ogg_sync_wrote(&syncState, (long)bytesRen);
}
convsize /= vorbisInfo.channels;
if(vorbis_synthesis_init(&dspState, &vorbisInfo) == 0)
{
vorbis_block_init(&dspState, &block);
while(!eos)
{
while(!eos)
{
int result = ogg_sync_pageout(&syncState, &page);
if(result == 0) break;
if(result >= 0)
{
ogg_stream_pagein(&streamState, &page);
while(true)
{
result = ogg_stream_packetout(&streamState, &packet);
if(result == 0) break;
if(result >= 0)
{
float **pcm;
int samples;
if(vorbis_synthesis(&block, &packet) == 0) vorbis_synthesis_blockin(&dspState, &block);
while((samples = vorbis_synthesis_pcmout(&dspState, &pcm)) > 0)
{
int j;
int bout = (samples < convsize ? samples : convsize);
for(i = 0; i < vorbisInfo.channels; i++)
{
ogg_int16_t *ptr = convbuffer + i;
float *mono = pcm[i];
for(j = 0; j < bout; j++)
{
int val = (int)(floor(mono[j] * 32767.0 + 0.5));
*ptr = (ogg_int16_t)val;
ptr += vorbisInfo.channels;
}
}
output.insert(output.end(), reinterpret_cast<uint8_t *>(convbuffer), reinterpret_cast<uint8_t *>(convbuffer) + (bout * vorbisInfo.channels * 2));
vorbis_synthesis_read(&dspState, bout);
}
}
}
if(ogg_page_eos(&page)) eos = 1;
}
}
if(!eos)
{
buffer = ogg_sync_buffer(&syncState, 4096);
readFile(input, buffer, 4096);
ogg_sync_wrote(&syncState, (long)bytesRen);
if(bytesRen == 0) eos = 1;
}
}
vorbis_block_clear(&block);
vorbis_dsp_clear(&dspState);
}
else
{
printf("OGG Decoder: Corrupt header during init in: %s\n", filePath.data());
}
bitsPerSample = 16;
numChannels = (int16_t)vorbisInfo.channels;
sampleRate = (int32_t)vorbisInfo.rate;
ogg_stream_clear(&streamState);
vorbis_comment_clear(&comment);
vorbis_info_clear(&vorbisInfo);
}
ogg_sync_clear(&syncState);
if(bitsPerSample == 0 || numChannels == 0 || sampleRate == 0)
{
printf("OGG Decoder: An error occured while reading Vorbis file: %s\n", filePath.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
fclose(input);
return AudioInfo{output, numChannels, bitsPerSample, sampleRate, AudioFormat::OGG};
}
/*AudioInfo fromOpus(FILE *input, std::string const &filePath)
{
AudioInfo out{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
int32_t err = 0;
OggOpusFile *opFile = op_open_file(input.data(), &err);
int64_t streamSize = op_pcm_total(opFile, -1), bytesRead = 0;
out.numChannels = (int16_t)op_channel_count(opFile, -1);
while(bytesRead <= streamSize)
{
int16_t pcm[5760];
int32_t read = op_read(opFile, pcm, 5760, nullptr);
if(read == 0) break;
bytesRead += read;
out.samples.resize((size_t)read);
memcpy(&out.samples[out.samples.size() - read], pcm, (size_t)read);
}
op_free(opFile);
if(out.samples.size() != (size_t)streamSize)
{
printf("Opus Decoder: Didn't receive the expected amount of data%s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
out.format = AudioFormat::OPUS;
out.bitsPerSample = 16;
out.sampleRate = 48000;
return out;
}*/
AudioInfo fromWAV(std::vector<uint8_t> const &input, std::string const &fileName)
{
//http://soundfile.sapp.org/doc/WaveFormat/
DataBuffer<uint8_t> buf(input);
std::vector<int16_t> output;
char chunkID[4], waveFormat[4]{}, subchunk1Id[4]{}, subchunk2Id[4]{};
int32_t subchunk1Size = 0, audioFormat = 0;
size_t dataSize = 0;
int16_t numChannels = 0, bitsPerSample = 0;
int32_t sampleRate = 0;
buf.read(chunkID, 4);
if(memcmp("RIFF", chunkID, 4) != 0)
{
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.seek(4, SeekPos::CUR); //Skips ChunkSize
buf.read(waveFormat, 4);
if(memcmp("WAVE", waveFormat, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing format\n");
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.read(subchunk1Id, 4);
if(memcmp("fmt ", subchunk1Id, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing subchunk 1 ID\n");
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.read(&subchunk1Size, 4);
if(16 != subchunk1Size)
{
printf("WAV Decoder: Malformed wave file, wrong subchunk 1 size\n");
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.read(&audioFormat, 2);
if(1 != audioFormat)
{
printf("WAV Decoder: Compression is unsupported, offending file\n");
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.read(&numChannels, 2);
buf.read(&sampleRate, 4);
buf.seek(6, SeekPos::CUR); //Skips ByteRate and BlockAlign
buf.read(&bitsPerSample, 2);
buf.read(subchunk2Id, 4);
if(memcmp("data", subchunk2Id, 4) != 0)
{
printf("WAV Decoder: Malformed wave file, missing subchunk 2 ID\n");
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
buf.read(&dataSize, 4);
output.resize(dataSize);
buf.read(output.data(), dataSize);
int16_t const *tmp = reinterpret_cast<int16_t const *>(output.data());
return AudioInfo{std::vector<int16_t>(tmp, tmp + (output.size() / 2)), numChannels, bitsPerSample, sampleRate, AudioFormat::WAVE};
}
AudioInfo fromOGG(std::vector<uint8_t> const &input, std::string const &fileName)
{
std::vector<uint8_t> output;
DataBuffer buf(input);
ogg_int16_t convbuffer[4096];
int convsize = 4096;
int32_t sampleRate = 0;
int16_t numChannels = 0, bitsPerSample = 0;
size_t bytesRen = 0;
ogg_sync_state syncState;
ogg_stream_state streamState;
ogg_page page;
ogg_packet packet;
vorbis_info vorbisInfo;
vorbis_comment comment;
vorbis_dsp_state dspState;
vorbis_block block;
char *buffer;
ogg_sync_init(&syncState);
while(true)
{
int eos = 0;
buffer = ogg_sync_buffer(&syncState, 4096);
bytesRen = buf.read(buffer, 4096);
ogg_sync_wrote(&syncState, (long)bytesRen);
if(ogg_sync_pageout(&syncState, &page) != 1) if(bytesRen < 4096) break;
ogg_stream_init(&streamState, ogg_page_serialno(&page));
vorbis_info_init(&vorbisInfo);
vorbis_comment_init(&comment);
if(ogg_stream_pagein(&streamState, &page) < 0)
{
//printf("OGG Decoder: Error reading first page of OGG bitstream: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
if(ogg_stream_packetout(&streamState, &packet) != 1)
{
//printf("OGG Decoder: Error reading initial header: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
if(vorbis_synthesis_headerin(&vorbisInfo, &comment, &packet) < 0)
{
//printf("OGG Decoder: File does not contain Vorbis audio: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
int i = 0;
while(i < 2)
{
while(i < 2)
{
int result = ogg_sync_pageout(&syncState, &page);
if(result == 0) break;
if(result == 1)
{
ogg_stream_pagein(&streamState, &page);
while(i < 2)
{
result = ogg_stream_packetout(&streamState, &packet);
if(result == 0) break;
if(result < 0)
{
printf("OGG Decoder: Corrupted secondary header: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
result = vorbis_synthesis_headerin(&vorbisInfo, &comment, &packet);
if(result < 0)
{
printf("OGG Decoder: Corrupted secondary header: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
i++;
}
}
}
buffer = ogg_sync_buffer(&syncState, 4096);
bytesRen = buf.read(buffer, 4096);
if(bytesRen == 0 && i < 2)
{
printf("OGG Decoder: End of file reached before finding all Vorbis headers: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
ogg_sync_wrote(&syncState, (long)bytesRen);
}
convsize /= vorbisInfo.channels;
if(vorbis_synthesis_init(&dspState, &vorbisInfo) == 0)
{
vorbis_block_init(&dspState, &block);
while(!eos)
{
while(!eos)
{
int result = ogg_sync_pageout(&syncState, &page);
if(result == 0) break;
if(result >= 0)
{
ogg_stream_pagein(&streamState, &page);
while(true)
{
result = ogg_stream_packetout(&streamState, &packet);
if(result == 0) break;
if(result >= 0)
{
float **pcm;
int samples;
if(vorbis_synthesis(&block, &packet) == 0) vorbis_synthesis_blockin(&dspState, &block);
while((samples = vorbis_synthesis_pcmout(&dspState, &pcm)) > 0)
{
int j;
int bout = (samples < convsize ? samples : convsize);
for(i = 0; i < vorbisInfo.channels; i++)
{
ogg_int16_t *ptr = convbuffer + i;
float *mono = pcm[i];
for(j = 0; j < bout; j++)
{
int val = (int)(floor(mono[j] * 32767.0 + 0.5));
*ptr = (ogg_int16_t)val;
ptr += vorbisInfo.channels;
}
}
output.insert(output.end(), reinterpret_cast<uint8_t *>(convbuffer), reinterpret_cast<uint8_t *>(convbuffer) + (bout * vorbisInfo.channels * 2));
vorbis_synthesis_read(&dspState, bout);
}
}
}
if(ogg_page_eos(&page)) eos = 1;
}
}
if(!eos)
{
buffer = ogg_sync_buffer(&syncState, 4096);
bytesRen = buf.read(buffer, 4096);
ogg_sync_wrote(&syncState, (long)bytesRen);
if(bytesRen == 0) eos = 1;
}
}
vorbis_block_clear(&block);
vorbis_dsp_clear(&dspState);
}
else
{
printf("OGG Decoder: Corrupt header during init: %s\n", fileName.data());
}
bitsPerSample = 16;
numChannels = (int16_t)vorbisInfo.channels;
sampleRate = (int32_t)vorbisInfo.rate;
ogg_stream_clear(&streamState);
vorbis_comment_clear(&comment);
vorbis_info_clear(&vorbisInfo);
}
ogg_sync_clear(&syncState);
if(bitsPerSample == 0 || numChannels == 0 || sampleRate == 0)
{
printf("OGG Decoder: An error occured while reading Vorbis file: %s\n", fileName.data());
return AudioInfo{std::vector<int16_t>{}, 0, 0, 0, AudioFormat::NONE};
}
auto tmp = reinterpret_cast<int16_t *>(output.data());
return AudioInfo{std::vector<int16_t>{tmp, tmp + (output.size() / 2)}, numChannels, bitsPerSample, sampleRate, AudioFormat::OGG};
}
| 31.627057 | 154 | 0.649653 | izzyaxel |
ca875961a51e9992462872ebf8581cc5c07c1141 | 3,655 | cpp | C++ | src/app/plugin/binding-chip/chip.cpp | balducci-apple/connectedhomeip | d5cbe865ee53557330941a3c4c243f40c3c7b400 | [
"Apache-2.0"
] | 1 | 2022-01-17T09:09:44.000Z | 2022-01-17T09:09:44.000Z | src/app/plugin/binding-chip/chip.cpp | balducci-apple/connectedhomeip | d5cbe865ee53557330941a3c4c243f40c3c7b400 | [
"Apache-2.0"
] | 1 | 2020-07-27T16:12:51.000Z | 2020-07-27T18:57:48.000Z | src/app/plugin/binding-chip/chip.cpp | balducci-apple/connectedhomeip | d5cbe865ee53557330941a3c4c243f40c3c7b400 | [
"Apache-2.0"
] | 2 | 2020-07-27T15:54:52.000Z | 2021-05-25T16:13:07.000Z | /**
*
* Copyright (c) 2020 Project CHIP 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.
*/
/**
* @file
* This file provides the CHIP implementation of functions required
* by the CHIP ZCL Application Layer
*
*/
#include "chip-zcl.h"
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>
#include <stdarg.h>
void chipZclCorePrintln(const char * formatString, ...)
{
va_list args;
va_start(args, formatString);
chip::Logging::LogV(chip::Logging::kLogModule_Zcl, chip::Logging::kLogCategory_Detail, formatString, args);
va_end(args);
}
// Default Response Stubs
ChipZclStatus_t chipZclSendDefaultResponse(const ChipZclCommandContext_t * context, ChipZclStatus_t status)
{
return CHIP_ZCL_STATUS_SUCCESS;
}
// Reporting Configuration Stubs
void chipZclReportingConfigurationsFactoryReset(ChipZclEndpointId_t endpointId)
{
return;
}
// Endpoint Management Stubs
ChipZclEndpointId_t chipZclEndpointIndexToId(ChipZclEndpointIndex_t index, const ChipZclClusterSpec_t * clusterSpec)
{
return CHIP_ZCL_ENDPOINT_NULL;
}
// Attribute Management Stubs
void chipZclResetAttributes(ChipZclEndpointId_t endpointId)
{
return;
}
// Event Management Stubs
EventQueue emAppEventQueue;
Event * chipZclEventFind(EventQueue * queue, EventActions * actions, EventPredicate predicate, void * data, bool all)
{
return 0;
}
void chEventControlSetDelayMS(ChipZclEventControl * event, uint32_t delay)
{
return;
}
void chipZclEventSetDelayMs(Event * event, uint32_t delay)
{
return;
}
int32_t chipZclCompareClusterSpec(const ChipZclClusterSpec_t * s1, const ChipZclClusterSpec_t * s2)
{
return 0;
}
bool chipZclAreClusterSpecsEqual(const ChipZclClusterSpec_t * s1, const ChipZclClusterSpec_t * s2)
{
return 0;
}
void chipZclReverseClusterSpec(const ChipZclClusterSpec_t * s1, ChipZclClusterSpec_t * s2)
{
return;
}
/**
* ChipZclBuffer_t is merely a type alias
*/
struct ChipZclBuffer_t : public chip::System::PacketBuffer
{
};
/**
* Function that allocates a buffer.
*/
ChipZclBuffer_t * chipZclBufferAlloc(uint16_t allocatedLength)
{
return static_cast<ChipZclBuffer_t *>(chip::System::PacketBuffer::NewWithAvailableSize(allocatedLength));
}
/**
* Function that frees a buffer and its storage.
*/
void chipZclBufferFree(ChipZclBuffer_t * buffer)
{
chip::System::PacketBuffer::Free(buffer);
}
/**
* Function that returns a pointer to the raw buffer.
*/
uint8_t * chipZclBufferPointer(ChipZclBuffer_t * buffer)
{
return buffer->Start();
}
/**
* Function that returns the size of the used portion of the buffer.
*/
uint16_t chipZclBufferDataLength(ChipZclBuffer_t * buffer)
{
return buffer->DataLength();
}
/**
* returns space available for writing after any data already in the buffer
*/
uint16_t chipZclBufferAvailableLength(ChipZclBuffer_t * buffer)
{
return buffer->AvailableDataLength();
}
/**
* sets data length for a buffer that's being written to
*/
void chipZclBufferSetDataLength(ChipZclBuffer_t * buffer, uint16_t newLength)
{
buffer->SetDataLength(newLength);
}
| 24.205298 | 117 | 0.746101 | balducci-apple |
ca88a4a87ee5efe553b0d9c38e76a232adcfd35a | 24,274 | hpp | C++ | libraries/chain/include/betterchain/chain/apply_context.hpp | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | 3 | 2018-01-18T07:12:34.000Z | 2018-01-22T10:00:29.000Z | libraries/chain/include/betterchain/chain/apply_context.hpp | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | null | null | null | libraries/chain/include/betterchain/chain/apply_context.hpp | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | 2 | 2018-01-30T01:03:10.000Z | 2019-02-28T09:04:06.000Z | /**
* @file
* @copyright defined in BetterChain/LICENSE.txt
*/
#pragma once
#include <betterchain/chain/block.hpp>
#include <betterchain/chain/transaction.hpp>
#include <betterchain/chain/transaction_metadata.hpp>
#include <betterchain/chain/contracts/contract_table_objects.hpp>
#include <fc/utility.hpp>
#include <sstream>
namespace chainbase { class database; }
namespace betterchain { namespace chain {
class chain_controller;
class apply_context {
public:
apply_context(chain_controller& con, chainbase::database& db, const action& a, const transaction_metadata& trx_meta)
:controller(con), db(db), act(a), mutable_controller(con),
mutable_db(db), used_authorizations(act.authorization.size(), false),
trx_meta(trx_meta) {}
void exec();
void execute_inline( action &&a );
void execute_deferred( deferred_transaction &&trx );
void cancel_deferred( uint32_t sender_id );
using table_id_object = contracts::table_id_object;
const table_id_object* find_table( name scope, name code, name table );
const table_id_object& find_or_create_table( name scope, name code, name table );
template <typename ObjectType>
int32_t store_record( const table_id_object& t_id, const typename ObjectType::key_type* keys, const char* value, size_t valuelen );
template <typename ObjectType>
int32_t update_record( const table_id_object& t_id, const typename ObjectType::key_type* keys, const char* value, size_t valuelen );
template <typename ObjectType>
int32_t remove_record( const table_id_object& t_id, const typename ObjectType::key_type* keys );
template <typename IndexType, typename Scope>
int32_t load_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t front_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t back_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys,
char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t next_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t previous_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t lower_bound_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
template <typename IndexType, typename Scope>
int32_t upper_bound_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen );
/**
* @brief Require @ref account to have approved of this message
* @param account The account whose approval is required
*
* This method will check that @ref account is listed in the message's declared authorizations, and marks the
* authorization as used. Note that all authorizations on a message must be used, or the message is invalid.
*
* @throws tx_missing_auth If no sufficient permission was found
*/
void require_authorization(const account_name& account)const;
void require_authorization(const account_name& account, const permission_name& permission)const;
void require_write_lock(const scope_name& scope);
void require_read_lock(const account_name& account, const scope_name& scope);
/**
* Requires that the current action be delivered to account
*/
void require_recipient(account_name account);
/**
* Return true if the current action has already been scheduled to be
* delivered to the specified account.
*/
bool has_recipient(account_name account)const;
bool all_authorizations_used()const;
vector<permission_level> unused_authorizations()const;
vector<account_name> get_active_producers() const;
const chain_controller& controller;
const chainbase::database& db; ///< database where state is stored
const action& act; ///< message being applied
account_name receiver; ///< the code that is currently running
chain_controller& mutable_controller;
chainbase::database& mutable_db;
///< Parallel to act.authorization; tracks which permissions have been used while processing the message
vector<bool> used_authorizations;
const transaction_metadata& trx_meta;
///< pending transaction construction
/*
typedef uint32_t pending_transaction_handle;
struct pending_transaction : public transaction {
typedef uint32_t handle_type;
pending_transaction(const handle_type& _handle, const apply_context& _context, const uint16_t& block_num, const uint32_t& block_ref, const time_point& expiration )
: transaction(block_num, block_ref, expiration, vector<account_name>(), vector<account_name>(), vector<action>())
, handle(_handle)
, context(_context) {}
handle_type handle;
const apply_context& context;
void check_size() const;
};
pending_transaction::handle_type next_pending_transaction_serial;
vector<pending_transaction> pending_transactions;
pending_transaction& get_pending_transaction(pending_transaction::handle_type handle);
pending_transaction& create_pending_transaction();
void release_pending_transaction(pending_transaction::handle_type handle);
///< pending message construction
typedef uint32_t pending_message_handle;
struct pending_message : public action {
typedef uint32_t handle_type;
pending_message(const handle_type& _handle, const account_name& code, const action_name& type, const vector<char>& data)
: action(code, type, vector<permission_level>(), data)
, handle(_handle) {}
handle_type handle;
};
pending_transaction::handle_type next_pending_message_serial;
vector<pending_message> pending_messages;
pending_message& get_pending_message(pending_message::handle_type handle);
pending_message& create_pending_message(const account_name& code, const action_name& type, const vector<char>& data);
void release_pending_message(pending_message::handle_type handle);
*/
struct apply_results {
vector<action_trace> applied_actions;
vector<deferred_transaction> generated_transactions;
vector<deferred_reference> canceled_deferred;
};
apply_results results;
template<typename T>
void console_append(T val) {
_pending_console_output << val;
}
template<typename T, typename ...Ts>
void console_append(T val, Ts ...rest) {
console_append(val);
console_append(rest...);
};
inline void console_append_formatted(const string& fmt, const variant_object& vo) {
console_append(fc::format_string(fmt, vo));
}
private:
void append_results(apply_results &&other) {
fc::move_append(results.applied_actions, move(other.applied_actions));
fc::move_append(results.generated_transactions, move(other.generated_transactions));
fc::move_append(results.canceled_deferred, move(other.canceled_deferred));
}
void exec_one();
vector<account_name> _notified; ///< keeps track of new accounts to be notifed of current message
vector<action> _inline_actions; ///< queued inline messages
std::ostringstream _pending_console_output;
vector<shard_lock> _read_locks;
vector<scope_name> _write_scopes;
};
using apply_handler = std::function<void(apply_context&)>;
namespace impl {
template<typename Scope>
struct scope_to_key_index;
template<>
struct scope_to_key_index<contracts::by_scope_primary> {
static constexpr int value = 0;
};
template<>
struct scope_to_key_index<contracts::by_scope_secondary> {
static constexpr int value = 1;
};
template<>
struct scope_to_key_index<contracts::by_scope_tertiary> {
static constexpr int value = 2;
};
template<typename Scope>
constexpr int scope_to_key_index_v = scope_to_key_index<Scope>::value;
template<int>
struct object_key_value;
template<>
struct object_key_value<0> {
template<typename ObjectType>
static const auto& get(const ObjectType& o) {
return o.primary_key;
}
template<typename ObjectType>
static auto& get(ObjectType& o) {
return o.primary_key;
}
};
template<>
struct object_key_value<1> {
template<typename ObjectType>
static const auto& get(const ObjectType& o) {
return o.secondary_key;
}
template<typename ObjectType>
static auto& get(ObjectType& o) {
return o.primary_key;
}
};
template<>
struct object_key_value<2> {
template<typename ObjectType>
static const auto& get(const ObjectType& o) {
return o.tertiary_key;
}
template<typename ObjectType>
static auto& get( ObjectType& o) {
return o.primary_key;
}
};
template<typename KeyType>
const KeyType& raw_key_value(const KeyType* keys, int index) {
return keys[index];
}
inline const char* raw_key_value(const std::string* keys, int index) {
return keys[index].data();
}
template<typename Type>
void set_key(Type& a, std::add_const_t<Type>& b) {
a = b;
}
inline void set_key(std::string& s, const shared_string& ss) {
s.assign(ss.data(), ss.size());
};
inline void set_key(shared_string& s, const std::string& ss) {
s.assign(ss.data(), ss.size());
};
template< typename ObjectType, int KeyIndex >
struct key_helper_impl {
using KeyType = typename ObjectType::key_type;
using KeyAccess = object_key_value<KeyIndex>;
using Next = key_helper_impl<ObjectType, KeyIndex - 1>;
static void set(ObjectType& o, const KeyType* keys) {
set_key(KeyAccess::get(o),*(keys + KeyIndex));
Next::set(o,keys);
}
static void get(KeyType* keys, const ObjectType& o) {
set_key(*(keys + KeyIndex),KeyAccess::get(o));
Next::get(keys, o);
}
static bool compare(const ObjectType& o, const KeyType* keys) {
return (KeyAccess::get(o) == raw_key_value(keys, KeyIndex)) && Next::compare(o, keys);
}
};
template< typename ObjectType >
struct key_helper_impl<ObjectType, -1> {
using KeyType = typename ObjectType::key_type;
static void set(ObjectType&, const KeyType*) {}
static void get(KeyType*, const ObjectType&) {}
static bool compare(const ObjectType&, const KeyType*) { return true; }
};
template< typename ObjectType >
using key_helper = key_helper_impl<ObjectType, ObjectType::number_of_keys - 1>;
/// find_tuple helper
template <typename KeyType, int KeyIndex, typename ...Args>
struct exact_tuple_impl {
static auto get(const contracts::table_id_object& tid, const KeyType* keys, Args... args ) {
return exact_tuple_impl<KeyType, KeyIndex - 1, const KeyType &, Args...>::get(tid, keys, raw_key_value(keys, KeyIndex), args...);
}
};
template <typename KeyType, typename ...Args>
struct exact_tuple_impl<KeyType, -1, Args...> {
static auto get(const contracts::table_id_object& tid, const KeyType*, Args... args) {
return boost::make_tuple(tid.id, args...);
}
};
template <typename ObjectType>
using exact_tuple = exact_tuple_impl<typename ObjectType::key_type, ObjectType::number_of_keys - 1>;
template< typename KeyType, int NullKeyCount, typename Scope, typename ... Args >
struct lower_bound_tuple_impl {
static auto get(const contracts::table_id_object& tid, const KeyType* keys, Args... args) {
return lower_bound_tuple_impl<KeyType, NullKeyCount - 1, Scope, KeyType, Args...>::get(tid, keys, KeyType(0), args...);
}
};
template< typename KeyType, typename Scope, typename ... Args >
struct lower_bound_tuple_impl<KeyType, 0, Scope, Args...> {
static auto get(const contracts::table_id_object& tid, const KeyType* keys, Args... args) {
return boost::make_tuple( tid.id, raw_key_value(keys, scope_to_key_index_v<Scope>), args...);
}
};
template< typename IndexType, typename Scope >
using lower_bound_tuple = lower_bound_tuple_impl<typename IndexType::value_type::key_type, IndexType::value_type::number_of_keys - scope_to_key_index_v<Scope> - 1, Scope>;
template< typename KeyType, int NullKeyCount, typename Scope, typename ... Args >
struct upper_bound_tuple_impl {
static auto get(const contracts::table_id_object& tid, const KeyType* keys, Args... args) {
return upper_bound_tuple_impl<KeyType, NullKeyCount - 1, Scope, KeyType, Args...>::get(tid, keys, KeyType(-1), args...);
}
};
template< typename KeyType, typename Scope, typename ... Args >
struct upper_bound_tuple_impl<KeyType, 0, Scope, Args...> {
static auto get(const contracts::table_id_object& tid, const KeyType* keys, Args... args) {
return boost::make_tuple( tid.id, raw_key_value(keys, scope_to_key_index_v<Scope>), args...);
}
};
template< typename IndexType, typename Scope >
using upper_bound_tuple = upper_bound_tuple_impl<typename IndexType::value_type::key_type, IndexType::value_type::number_of_keys - scope_to_key_index_v<Scope> - 1, Scope>;
template <typename IndexType, typename Scope>
struct record_scope_compare {
using ObjectType = typename IndexType::value_type;
using KeyType = typename ObjectType::key_type;
static constexpr int KeyIndex = scope_to_key_index_v<Scope>;
using KeyAccess = object_key_value<KeyIndex>;
static bool compare(const ObjectType& o, const KeyType* keys) {
return KeyAccess::get(o) == raw_key_value(keys, KeyIndex);
}
};
template < typename IndexType, typename Scope >
struct front_record_tuple {
static auto get( const contracts::table_id_object& tid ) {
return boost::make_tuple( tid.id );
}
};
}
template <typename ObjectType>
int32_t apply_context::store_record( const table_id_object& t_id, const typename ObjectType::key_type* keys, const char* value, size_t valuelen ) {
require_write_lock( t_id.scope );
auto tuple = impl::exact_tuple<ObjectType>::get(t_id, keys);
const auto* obj = db.find<ObjectType, contracts::by_scope_primary>(tuple);
if( obj ) {
mutable_db.modify( *obj, [&]( auto& o ) {
o.value.assign(value, valuelen);
});
return 0;
} else {
mutable_db.create<ObjectType>( [&](auto& o) {
o.t_id = t_id.id;
impl::key_helper<ObjectType>::set(o, keys);
o.value.insert( 0, value, valuelen );
});
return 1;
}
}
template <typename ObjectType>
int32_t apply_context::update_record( const table_id_object& t_id, const typename ObjectType::key_type* keys, const char* value, size_t valuelen ) {
require_write_lock( t_id.scope );
auto tuple = impl::exact_tuple<ObjectType>::get(t_id, keys);
const auto* obj = db.find<ObjectType, contracts::by_scope_primary>(tuple);
if( !obj ) {
return 0;
}
mutable_db.modify( *obj, [&]( auto& o ) {
if( valuelen > o.value.size() ) {
o.value.resize(valuelen);
}
memcpy(o.value.data(), value, valuelen);
});
return 1;
}
template <typename ObjectType>
int32_t apply_context::remove_record( const table_id_object& t_id, const typename ObjectType::key_type* keys ) {
require_write_lock( t_id.scope );
auto tuple = impl::exact_tuple<ObjectType>::get(t_id, keys);
const auto* obj = db.find<ObjectType, contracts::by_scope_primary>(tuple);
if( obj ) {
mutable_db.remove( *obj );
return 1;
}
return 0;
}
template <typename IndexType, typename Scope>
int32_t apply_context::load_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& idx = db.get_index<IndexType, Scope>();
auto tuple = impl::lower_bound_tuple<IndexType, Scope>::get(t_id, keys);
auto itr = idx.lower_bound(tuple);
if( itr == idx.end() ||
itr->t_id != t_id.id ||
!impl::record_scope_compare<IndexType, Scope>::compare(*itr, keys)) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::front_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& idx = db.get_index<IndexType, Scope>();
auto tuple = impl::front_record_tuple<IndexType, Scope>::get(t_id);
auto itr = idx.lower_bound( tuple );
if( itr == idx.end() ||
itr->t_id != t_id.id ) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::back_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& idx = db.get_index<IndexType, Scope>();
decltype(t_id.id) next_tid(t_id.id._id + 1);
auto tuple = boost::make_tuple( next_tid );
auto itr = idx.lower_bound(tuple);
if( std::distance(idx.begin(), itr) == 0 ) return -1;
--itr;
if( itr->t_id != t_id.id ) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::next_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& pidx = db.get_index<IndexType, contracts::by_scope_primary>();
auto tuple = impl::exact_tuple<typename IndexType::value_type>::get(t_id, keys);
auto pitr = pidx.find(tuple);
if(pitr == pidx.end())
return -1;
const auto& fidx = db.get_index<IndexType>();
auto itr = fidx.indicies().template project<Scope>(pitr);
const auto& idx = db.get_index<IndexType, Scope>();
if( itr == idx.end() ||
itr->t_id != t_id.id ||
!impl::key_helper<typename IndexType::value_type>::compare(*itr, keys) ) {
return -1;
}
++itr;
if( itr == idx.end() ||
itr->t_id != t_id.id ) {
return -1;
}
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::previous_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& pidx = db.get_index<IndexType, contracts::by_scope_primary>();
auto tuple = impl::exact_tuple<typename IndexType::value_type>::get(t_id, keys);
auto pitr = pidx.find(tuple);
if(pitr == pidx.end())
return -1;
const auto& fidx = db.get_index<IndexType>();
auto itr = fidx.indicies().template project<Scope>(pitr);
const auto& idx = db.get_index<IndexType, Scope>();
if( itr == idx.end() ||
itr == idx.begin() ||
itr->t_id != t_id.id ||
!impl::key_helper<typename IndexType::value_type>::compare(*itr, keys) ) return -1;
--itr;
if( itr->t_id != t_id.id ) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::lower_bound_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& idx = db.get_index<IndexType, Scope>();
auto tuple = impl::lower_bound_tuple<IndexType, Scope>::get(t_id, keys);
auto itr = idx.lower_bound(tuple);
if( itr == idx.end() ||
itr->t_id != t_id.id) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
template <typename IndexType, typename Scope>
int32_t apply_context::upper_bound_record( const table_id_object& t_id, typename IndexType::value_type::key_type* keys, char* value, size_t valuelen ) {
require_read_lock( t_id.code, t_id.scope );
const auto& idx = db.get_index<IndexType, Scope>();
auto tuple = impl::upper_bound_tuple<IndexType, Scope>::get(t_id, keys);
auto itr = idx.upper_bound(tuple);
if( itr == idx.end() ||
itr->t_id != t_id.id ) return -1;
impl::key_helper<typename IndexType::value_type>::get(keys, *itr);
if (valuelen) {
auto copylen = std::min<size_t>(itr->value.size(), valuelen);
if (copylen) {
itr->value.copy(value, copylen);
}
return copylen;
} else {
return itr->value.size();
}
}
} } // namespace betterchain::chain
FC_REFLECT(betterchain::chain::apply_context::apply_results, (applied_actions)(generated_transactions));
| 36.834598 | 177 | 0.64118 | betterchainio |
ca8d95e114761eac989d3bfcefe32bad6b3b09e4 | 685 | hpp | C++ | src/purple/view/scene/objects.hpp | snailbaron/purple | 1dc5ae84c7fd702d5aea27e33c557f48ac564e77 | [
"MIT"
] | null | null | null | src/purple/view/scene/objects.hpp | snailbaron/purple | 1dc5ae84c7fd702d5aea27e33c557f48ac564e77 | [
"MIT"
] | null | null | null | src/purple/view/scene/objects.hpp | snailbaron/purple | 1dc5ae84c7fd702d5aea27e33c557f48ac564e77 | [
"MIT"
] | null | null | null | #pragma once
#include "../renderer.hpp"
#include "../visual.hpp"
#include <purple/core/component.hpp>
class SceneObject {
public:
virtual void render(
Renderer& canvas, const WorldPoint& cameraPosition) const = 0;
virtual void update(double deltaSec) {}
};
class SceneGraphics : public SceneObject {
public:
SceneGraphics(
std::shared_ptr<PositionComponent> position,
std::unique_ptr<Visual>&& graphics);
void render(
Renderer& canvas, const WorldPoint& cameraPosition) const override;
void update(double deltaSec) override;
private:
std::shared_ptr<PositionComponent> _position;
std::unique_ptr<Visual> _graphics;
};
| 22.833333 | 75 | 0.705109 | snailbaron |
ca8fe46168ae8d6d7fc9f43078b3567da12f3814 | 627 | cpp | C++ | Info/Info/Items/AwardInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Info/Info/Items/AwardInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Info/Info/Items/AwardInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | #include "AwardInfo.h"
namespace Lunia {
namespace XRated {
namespace Database {
namespace Info {
AwardInfo::AwardInfo()
{
}
void AwardInfo::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AwardInfo");
out.Write(L"Items", Items);
out.Write(L"Title", Title);
out.Write(L"Text", Text);
out.Write(L"Sender", Sender);
}
void AwardInfo::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AwardInfo");
in.Read(L"Items", Items);
in.Read(L"Title", Title);
in.Read(L"Text", Text);
in.Read(L"Sender", Sender);
}
}
}
}
} | 21.62069 | 67 | 0.598086 | Teles1 |
ca90b12b174cbd40b679b1089b1a0640e129d182 | 30,810 | cpp | C++ | numerics/poisson_series_basis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | 565 | 2015-01-04T21:47:18.000Z | 2022-03-22T12:04:58.000Z | numerics/poisson_series_basis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | 1,019 | 2015-01-03T11:42:27.000Z | 2022-03-29T21:02:15.000Z | numerics/poisson_series_basis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | 92 | 2015-02-11T23:08:58.000Z | 2022-03-21T03:35:37.000Z |
#include "numerics/poisson_series_basis.hpp"
#include "geometry/frame.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/hilbert.hpp"
#include "geometry/named_quantities.hpp"
#include "gtest/gtest.h"
#include "numerics/poisson_series.hpp"
#include "numerics/polynomial_evaluators.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/numbers.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
namespace numerics {
using geometry::Frame;
using geometry::Handedness;
using geometry::Hilbert;
using geometry::Inertial;
using geometry::Instant;
using geometry::Vector;
using quantities::AngularFrequency;
using quantities::Length;
using quantities::Sqrt;
using quantities::si::Kelvin;
using quantities::si::Metre;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AlmostEquals;
class PoissonSeriesBasisTest : public ::testing::Test {
protected:
using World = Frame<serialization::Frame::TestTag,
Inertial,
Handedness::Right,
serialization::Frame::TEST>;
using V = Vector<double, World>;
using Series2 = PoissonSeries<double, 2, 2, HornerEvaluator>;
using Series3 = PoissonSeries<V, 3, 3, HornerEvaluator>;
Instant const t0_;
Instant const t1_ = t0_ - 2 * Second;
Instant const t2_ = t0_ + 2 * Second;
};
TEST_F(PoissonSeriesBasisTest, AperiodicScalar) {
auto const aperiodic =
PoissonSeriesBasisGenerator<Series2,
/*degree=*/2>::Basis(t1_, t2_);
EXPECT_EQ(3, aperiodic.size());
Instant const t1 = t0_ + 2 * Second;
EXPECT_EQ(1, aperiodic[0](t2_));
EXPECT_EQ(1, aperiodic[1](t2_));
EXPECT_EQ(1, aperiodic[2](t2_));
}
TEST_F(PoissonSeriesBasisTest, AperiodicVector) {
auto const aperiodic =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/3>::Basis(t1_, t2_);
auto const aperiodic_subspaces =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/3>::Subspaces();
EXPECT_EQ(12, aperiodic.size());
Instant const t1 = t0_ + 2 * Second;
// Degree 0.
EXPECT_EQ(V({1, 0, 0}), aperiodic[0](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[1](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[2](t2_));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[0]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[1]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[2]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[1]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[2]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[2]));
// Degree 1.
EXPECT_EQ(V({1, 0, 0}), aperiodic[3](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[4](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[5](t2_));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[5]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[5]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[5]));
// Degree 2.
EXPECT_EQ(V({1, 0, 0}), aperiodic[6](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[7](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[8](t2_));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[6]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[7]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[7],
aperiodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[7],
aperiodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[8],
aperiodic_subspaces[8]));
// Degree 3.
EXPECT_EQ(V({1, 0, 0}), aperiodic[9](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[10](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[11](t2_));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[0],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[1],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[2],
aperiodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[3],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[9]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[4],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[10]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[5],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[6],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[7],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[7],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[7],
aperiodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[8],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[8],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[8],
aperiodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[9],
aperiodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[9],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[9],
aperiodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[10],
aperiodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[10],
aperiodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(aperiodic_subspaces[11],
aperiodic_subspaces[11]));
}
TEST_F(PoissonSeriesBasisTest, PeriodicScalar) {
AngularFrequency const ω = π / 6 * Radian / Second;
auto const periodic =
PoissonSeriesBasisGenerator<Series2,
/*degree=*/2>::Basis(ω, t1_, t2_);
EXPECT_EQ(6, periodic.size());
Instant const t1 = t0_ + 2 * Second;
EXPECT_THAT(periodic[0](t2_), AlmostEquals(0.5, 1));
EXPECT_THAT(periodic[1](t2_), AlmostEquals(Sqrt(3) / 2, 0));
EXPECT_THAT(periodic[2](t2_), AlmostEquals(0.5, 1));
EXPECT_THAT(periodic[3](t2_), AlmostEquals(Sqrt(3) / 2, 0));
EXPECT_THAT(periodic[4](t2_), AlmostEquals(0.5, 1));
EXPECT_THAT(periodic[5](t2_), AlmostEquals(Sqrt(3) / 2, 0));
}
TEST_F(PoissonSeriesBasisTest, PeriodicVector) {
AngularFrequency const ω = π / 6 * Radian / Second;
auto const periodic =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/3>::Basis(ω, t1_, t2_);
auto const periodic_subspaces =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/3>::Subspaces(ω);
EXPECT_EQ(24, periodic.size());
Instant const t1 = t0_ + 2 * Second;
// Degree 0, Cos.
EXPECT_THAT(periodic[0](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[1](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[2](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[0]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[1]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[2]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[1]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[2]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[2]));
// Degree 0, Sin.
EXPECT_THAT(periodic[3](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[4](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[5](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[5]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[5]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[3]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[4]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[5]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[5]));
// Degree 1, Cos.
EXPECT_THAT(periodic[6](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[7](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[8](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[6]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[8]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[7]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[6]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[7],
periodic_subspaces[7]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[7],
periodic_subspaces[8]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[8],
periodic_subspaces[8]));
// Degree 1, Sin.
EXPECT_THAT(periodic[9](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[10](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[11](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[0],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[9]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[1],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[10]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[2],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[3],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[4],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[5],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[6],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[7],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[7],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[7],
periodic_subspaces[11]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[8],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[8],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[8],
periodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[9],
periodic_subspaces[9]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[9],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[9],
periodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[10],
periodic_subspaces[10]));
EXPECT_TRUE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[10],
periodic_subspaces[11]));
EXPECT_FALSE(PoissonSeriesSubspace::orthogonal(periodic_subspaces[11],
periodic_subspaces[11]));
// Degree 2, Cos.
EXPECT_THAT(periodic[12](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[13](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[14](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
// Degree 2, Sin.
EXPECT_THAT(periodic[15](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[16](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[17](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
// Degree 3, Cos.
EXPECT_THAT(periodic[18](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[19](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[20](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
// Degree 3, Sin.
EXPECT_THAT(periodic[21](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[22](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[23](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
}
TEST_F(PoissonSeriesBasisTest, ReducedDegree) {
auto const aperiodic =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/2>::Basis(t1_, t2_);
EXPECT_EQ(9, aperiodic.size());
AngularFrequency const ω = π / 6 * Radian / Second;
auto const periodic =
PoissonSeriesBasisGenerator<Series3,
/*degree=*/2>::Basis(ω, t1_, t2_);
EXPECT_EQ(18, periodic.size());
Instant const t1 = t0_ + 2 * Second;
EXPECT_EQ(V({1, 0, 0}), aperiodic[0](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[1](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[2](t2_));
EXPECT_EQ(V({1, 0, 0}), aperiodic[3](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[4](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[5](t2_));
EXPECT_EQ(V({1, 0, 0}), aperiodic[6](t2_));
EXPECT_EQ(V({0, 1, 0}), aperiodic[7](t2_));
EXPECT_EQ(V({0, 0, 1}), aperiodic[8](t2_));
EXPECT_THAT(periodic[0](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[1](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[2](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
EXPECT_THAT(periodic[3](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[4](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[5](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
EXPECT_THAT(periodic[6](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[7](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[8](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
EXPECT_THAT(periodic[9](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[10](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[11](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
EXPECT_THAT(periodic[12](t2_), AlmostEquals(V({0.5, 0, 0}), 1));
EXPECT_THAT(periodic[13](t2_), AlmostEquals(V({0, 0.5, 0}), 1));
EXPECT_THAT(periodic[14](t2_), AlmostEquals(V({0, 0, 0.5}), 1));
EXPECT_THAT(periodic[15](t2_), AlmostEquals(V({Sqrt(3) / 2, 0, 0}), 0));
EXPECT_THAT(periodic[16](t2_), AlmostEquals(V({0, Sqrt(3) / 2, 0}), 0));
EXPECT_THAT(periodic[17](t2_), AlmostEquals(V({0, 0, Sqrt(3) / 2}), 0));
}
} // namespace numerics
} // namespace principia
| 56.018182 | 75 | 0.576923 | erplsf |
ca959fc60fa922e237857429dcedc637321dc35a | 8,637 | cpp | C++ | src/MageFramework/SceneElements/model.cpp | AmanSachan1/ShaderPlayGround | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | 2 | 2019-12-04T17:06:44.000Z | 2019-12-24T16:33:37.000Z | src/MageFramework/SceneElements/model.cpp | AmanSachan1/GraphicsPlayground | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | null | null | null | src/MageFramework/SceneElements/model.cpp | AmanSachan1/GraphicsPlayground | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | null | null | null | #include "model.h"
Model::Model(std::shared_ptr<VulkanManager> vulkanManager, VkQueue& graphicsQueue, VkCommandPool& commandPool, unsigned int numSwapChainImages,
const JSONItem::Model& jsonModel, bool isMipMapped, RENDER_TYPE renderType)
: m_logicalDevice(vulkanManager->getLogicalDevice()), m_physicalDevice(vulkanManager->getPhysicalDevice()), m_numSwapChainImages(numSwapChainImages),
m_areTexturesMipMapped(isMipMapped), m_materialCount(0), m_primitiveCount(0), m_renderType(renderType)
{
m_updateUniforms.resize(m_numSwapChainImages, true);
LoadModel(jsonModel, graphicsQueue, commandPool);
};
Model::~Model()
{
vkDeviceWaitIdle(m_logicalDevice);
m_indices.indexBuffer.destroy(m_logicalDevice);
m_vertices.vertexBuffer.destroy(m_logicalDevice);
for (vkMaterial* material : m_materials)
{
delete material;
}
for (vkNode* node : m_linearNodes)
{
delete node;
}
}
void Model::updateUniformBuffer(uint32_t currentImageIndex)
{
if (m_updateUniforms[currentImageIndex])
{
for (vkNode* node : m_linearNodes)
{
if (node->mesh)
{
node->update(currentImageIndex);
}
}
m_updateUniforms[currentImageIndex] = false;
}
}
// Descriptor Setup
void Model::addToDescriptorPoolSize(std::vector<VkDescriptorPoolSize>& poolSizes)
{
// Model Uniforms + Material Uniforms
poolSizes.push_back({ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2 * m_primitiveCount * m_numSwapChainImages });
// (baseColor + metallicRoughness + normal + occlusion + emissive + specularGlossiness + diffuse) Texture Sampler
poolSizes.push_back({ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 7 * m_primitiveCount * m_numSwapChainImages });
}
void Model::createDescriptorSetLayout(VkDescriptorSetLayout& DSL_model)
{
//We pass in a descriptor Set layout because it will remain common to all models that we create. So no point keep multiple copies of it.
VkDescriptorSetLayoutBinding modelUniformLB = { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, nullptr };
VkDescriptorSetLayoutBinding materialUniformLB = { 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
VkDescriptorSetLayoutBinding baseColorTexSamplerLB = { 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
VkDescriptorSetLayoutBinding normalTexSamplerLB = { 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
VkDescriptorSetLayoutBinding metallicRoughnessTexSamplerLB = { 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
VkDescriptorSetLayoutBinding emissiveTexSamplerLB = { 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
VkDescriptorSetLayoutBinding occlusionTexSamplerLB = { 6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
//VkDescriptorSetLayoutBinding specularGlossinessTexSamplerLB = { 7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
//VkDescriptorSetLayoutBinding diffuseTexSamplerLB = { 8, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr };
std::vector<VkDescriptorSetLayoutBinding> modelPrimitiveBindings = {
modelUniformLB, materialUniformLB, baseColorTexSamplerLB, normalTexSamplerLB,
metallicRoughnessTexSamplerLB, emissiveTexSamplerLB, occlusionTexSamplerLB
// specularGlossinessTexSamplerLB, diffuseTexSamplerLB };
};
DescriptorUtil::createDescriptorSetLayout(m_logicalDevice, DSL_model, static_cast<uint32_t>(modelPrimitiveBindings.size()), modelPrimitiveBindings.data());
}
void Model::createDescriptorSets(VkDescriptorPool descriptorPool, VkDescriptorSetLayout& DSL_model, uint32_t index)
{
for (vkNode* node : m_linearNodes)
{
if (node->mesh)
{
for (auto primitive : node->mesh->primitives)
{
primitive->descriptorSets.resize(m_numSwapChainImages);
DescriptorUtil::createDescriptorSets(m_logicalDevice, descriptorPool, 1, &DSL_model, &primitive->descriptorSets[index]);
}
}
}
}
void Model::writeToAndUpdateDescriptorSets(uint32_t index)
{
// Loop over all materials and create the respective material descriptors
for (vkMaterial* material : m_materials)
{
material->uniformBlock.activeTextureFlags = material->activeTextures.to_ulong();
material->updateUniform();
material->materialUB.setDescriptorInfo();
material->baseColorTexture->setDescriptorInfo();
if (material->activeTextures[1]) { material->normalTexture->setDescriptorInfo(); }
if (material->activeTextures[2]) { material->metallicRoughnessTexture->setDescriptorInfo(); }
if (material->activeTextures[3]) { material->emissiveTexture->setDescriptorInfo(); }
if (material->activeTextures[4]) { material->occlusionTexture->setDescriptorInfo(); }
// if (material->activeTextures[5]) { material->specularGlossinessTexture->setDescriptorInfo(); }
// if (material->activeTextures[6]) { material->diffuseTexture->setDescriptorInfo(); }
}
for (vkNode* node : m_linearNodes)
{
if (node->mesh)
{
// Create the mesh descriptors
node->mesh->meshUniform[index].meshUB.setDescriptorInfo();
for (auto primitive : node->mesh->primitives)
{
primitive->writeToAndUpdateNodeDescriptorSet(node->mesh, index, m_logicalDevice);
}
}
}
}
void Model::recordDrawCmds( unsigned int frameIndex, const VkDescriptorSet& DS_camera,
const VkPipeline& rasterP, const VkPipelineLayout& rasterPL, VkCommandBuffer& graphicsCmdBuffer )
{
VkBuffer vertexBuffers[] = { m_vertices.vertexBuffer.buffer };
VkBuffer indexBuffer = m_indices.indexBuffer.buffer;
VkDeviceSize offsets[] = { 0 };
vkCmdBindPipeline(graphicsCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, rasterP);
vkCmdBindVertexBuffers(graphicsCmdBuffer, 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(graphicsCmdBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(graphicsCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, rasterPL, 0, 1, &DS_camera, 0, nullptr);
for (vkNode* node : m_linearNodes)
{
if (node->mesh)
{
for (vkPrimitive* primitive : node->mesh->primitives)
{
VkDescriptorSet DS_primitive = primitive->descriptorSets[frameIndex];
vkCmdBindDescriptorSets(graphicsCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, rasterPL, 1, 1, &DS_primitive, 0, nullptr);
vkCmdDrawIndexed(graphicsCmdBuffer, primitive->indexCount, 1, primitive->firstIndex, 0, 0);
}
}
}
}
bool Model::LoadModel(const JSONItem::Model& jsonModel, VkQueue& graphicsQueue, VkCommandPool& commandPool)
{
m_transform = jsonModel.transform;
if (jsonModel.filetype == FILE_TYPE::OBJ)
{
loadingUtil::loadObj(m_vertices.vertexArray, m_indices.indexArray, m_textures, jsonModel.meshPath, jsonModel.texturePaths,
m_areTexturesMipMapped, m_logicalDevice, m_physicalDevice, graphicsQueue, commandPool);
loadingUtil::convertObjToNodeStructure(m_vertices, m_indices, m_textures, m_materials, m_nodes, m_linearNodes,
jsonModel.name, m_transform, m_primitiveCount, m_materialCount, m_numSwapChainImages,
m_logicalDevice, m_physicalDevice, graphicsQueue, commandPool);
}
else if (jsonModel.filetype == FILE_TYPE::GLTF)
{
loadingUtil::loadGLTF(m_vertices.vertexArray, m_indices.indexArray, m_textures, m_materials,
m_nodes, m_linearNodes, jsonModel.meshPath, m_transform,
m_primitiveCount, m_materialCount, m_numSwapChainImages, m_logicalDevice, m_physicalDevice, graphicsQueue, commandPool);
}
else
{
throw std::runtime_error("Model not created because the filetype could not be identified");
}
m_vertices.numVertices = static_cast<uint32_t>(m_vertices.vertexArray.size());
m_vertices.vertexBuffer.bufferSize = m_vertices.numVertices * sizeof(Vertex);
m_indices.numIndices = static_cast<uint32_t>(m_indices.indexArray.size());
m_indices.indexBuffer.bufferSize = m_indices.numIndices * sizeof(uint32_t);
VkBufferUsageFlags allowedUsage = 0;
if (m_renderType == RENDER_TYPE::RAYTRACE)
{
allowedUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
}
BufferUtil::createMageVertexBuffer(m_logicalDevice, m_physicalDevice, graphicsQueue, commandPool,
m_vertices.vertexBuffer, m_vertices.vertexBuffer.bufferSize, m_vertices.vertexArray.data(), allowedUsage);
BufferUtil::createMageIndexBuffer(m_logicalDevice, m_physicalDevice, graphicsQueue, commandPool,
m_indices.indexBuffer, m_indices.indexBuffer.bufferSize, m_indices.indexArray.data(), allowedUsage);
if (m_renderType == RENDER_TYPE::RAYTRACE)
{
m_rayTracingGeom = vBLAS::createRayTraceGeometry(m_vertices, m_indices,
0, m_vertices.numVertices, 0, m_indices.numIndices, true);
}
return true;
} | 43.84264 | 156 | 0.794952 | AmanSachan1 |
ca96716cf7e6018c39d9f8260e46deb022cf9512 | 645 | cc | C++ | 04_Vector/VectorFirstExample.cc | jostue/UdemyCpp_Template | 1735036b1a19544518ce54e456d8451e45efa3cd | [
"MIT"
] | null | null | null | 04_Vector/VectorFirstExample.cc | jostue/UdemyCpp_Template | 1735036b1a19544518ce54e456d8451e45efa3cd | [
"MIT"
] | null | null | null | 04_Vector/VectorFirstExample.cc | jostue/UdemyCpp_Template | 1735036b1a19544518ce54e456d8451e45efa3cd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
template <class T>
void printVector(std::vector<T> &vec);
int main()
{
std::vector<int> myVector(2, 0);
printVector(myVector);
myVector[0] = 11;
myVector[0] = -42;
printVector(myVector);
myVector.push_back(7);
printVector(myVector);
myVector.pop_back();
printVector(myVector);
std::vector<double> myVector2(3, 2.5);
printVector(myVector2);
return 0;
}
template <class T>
void printVector(std::vector<T> &vec)
{
for (std::size_t i = 0; i < vec.size(); i++)
{
std::cout << vec[i] << std::endl;
}
std::cout << std::endl;
}
| 14.659091 | 48 | 0.592248 | jostue |
ca99455d8267de883ca141417b5e97189eb3b4d3 | 1,505 | hh | C++ | include/introvirt/windows/kernel/nt/types/objects/OBJECT.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 23 | 2021-02-17T16:58:52.000Z | 2022-02-12T17:01:06.000Z | include/introvirt/windows/kernel/nt/types/objects/OBJECT.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 1 | 2021-04-01T22:41:32.000Z | 2021-09-24T14:14:17.000Z | include/introvirt/windows/kernel/nt/types/objects/OBJECT.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 4 | 2021-02-17T16:53:18.000Z | 2021-04-13T16:51:10.000Z | /*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include <introvirt/fwd.hh>
#include <cstdint>
#include <memory>
namespace introvirt {
namespace windows {
namespace nt {
/**
* @brief Base class for all kernel objects
*/
class OBJECT {
public:
/**
* @brief Get the OBJECT_HEADER for this object
*/
virtual const OBJECT_HEADER& header() const = 0;
/**
* @returns The virtual address of this object
*/
virtual guest_ptr<void> ptr() const = 0;
static std::shared_ptr<OBJECT> make_shared(const NtKernel& kernel, const guest_ptr<void>& ptr);
static std::shared_ptr<OBJECT> make_shared(const NtKernel& kernel,
std::unique_ptr<OBJECT_HEADER>&& object_header);
/**
* @brief Destroy the instance
*/
virtual ~OBJECT() = default;
};
} /* namespace nt */
} /* namespace windows */
} /* namespace introvirt */
| 26.875 | 99 | 0.669767 | IntroVirt |
ca9ca4d889e41df4686eb56c0b7f6f31e980b0d9 | 2,426 | cpp | C++ | test/core/runtime/parachain_test.cpp | lamafab/kagome | 988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb | [
"Apache-2.0"
] | null | null | null | test/core/runtime/parachain_test.cpp | lamafab/kagome | 988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb | [
"Apache-2.0"
] | null | null | null | test/core/runtime/parachain_test.cpp | lamafab/kagome | 988bc6d93314ca58b320a9d83dcbc4cd3b87b7bb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "runtime/binaryen/runtime_api/parachain_host_impl.hpp"
#include <gtest/gtest.h>
#include "core/runtime/runtime_test.hpp"
#include "extensions/impl/extension_impl.hpp"
#include "runtime/binaryen/wasm_memory_impl.hpp"
#include "testutil/outcome.hpp"
using kagome::common::Buffer;
using kagome::extensions::ExtensionImpl;
using kagome::primitives::parachain::Chain;
using kagome::primitives::parachain::DutyRoster;
using kagome::primitives::parachain::Parachain;
using kagome::primitives::parachain::ParaId;
using kagome::primitives::parachain::Relay;
using kagome::primitives::parachain::ValidatorId;
using kagome::runtime::ParachainHost;
using kagome::runtime::binaryen::ParachainHostImpl;
using ::testing::_;
using ::testing::Return;
namespace fs = boost::filesystem;
class ParachainHostTest : public RuntimeTest {
public:
void SetUp() override {
RuntimeTest::SetUp();
api_ = std::make_shared<ParachainHostImpl>(runtime_manager_);
}
ParaId createParachainId() const {
return 1ul;
}
protected:
std::shared_ptr<ParachainHost> api_;
};
// TODO(yuraz): PRE-157 find out do we need to give block_id to api functions
/**
* @given initialized parachain host api
* @when dutyRoster() is invoked
* @then successful result is returned
*/
TEST_F(ParachainHostTest, DISABLED_DutyRosterTest) {
ASSERT_TRUE(api_->duty_roster());
}
/**
* @given initialized parachain host api
* @when activeParachains() is invoked
* @then successful result is returned
*/
TEST_F(ParachainHostTest, DISABLED_ActiveParachainsTest) {
ASSERT_TRUE(api_->active_parachains());
}
/**
* @given initialized parachain host api
* @when parachainHead() is invoked
* @then successful result is returned
*/
TEST_F(ParachainHostTest, DISABLED_ParachainHeadTest) {
auto id = createParachainId();
ASSERT_TRUE(api_->parachain_head(id));
}
/**
* @given initialized parachain host api
* @when parachain_code() is invoked
* @then successful result is returned
*/
TEST_F(ParachainHostTest, DISABLED_ParachainCodeTest) {
auto id = createParachainId();
ASSERT_TRUE(api_->parachain_code(id));
}
/**
* @given initialized parachain host api
* @when validators() is invoked
* @then successful result is returned
*/
TEST_F(ParachainHostTest, DISABLED_ValidatorsTest) {
ASSERT_TRUE(api_->validators());
}
| 25.808511 | 77 | 0.753092 | lamafab |
ca9ccbe1b913d020e6201cb018f995af32d79290 | 686 | hpp | C++ | frankr/include/waypoint.hpp | dkuss-tudresden/frankr | 9a48a24488bd6bae3777f89e3d8cefd40368aaa2 | [
"BSD-3-Clause"
] | 6 | 2020-12-02T16:51:34.000Z | 2021-03-20T10:29:42.000Z | frankr/include/waypoint.hpp | dkuss-tudresden/frankr | 9a48a24488bd6bae3777f89e3d8cefd40368aaa2 | [
"BSD-3-Clause"
] | 1 | 2021-01-22T02:38:28.000Z | 2021-01-22T19:13:42.000Z | frankr/include/waypoint.hpp | dkuss-tudresden/frankr | 9a48a24488bd6bae3777f89e3d8cefd40368aaa2 | [
"BSD-3-Clause"
] | 2 | 2021-02-02T15:22:20.000Z | 2021-07-14T08:25:39.000Z | /* Copyright (c) 2020, Danish Technological Institute.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Original author: Lars Berscheid <lars.berscheid@kit.edu>
*/
#pragma once
#include <geometry.hpp>
struct Waypoint {
enum class ReferenceType {
ABSOLUTE,
RELATIVE
};
Affine target_affine;
ReferenceType reference_type {ReferenceType::ABSOLUTE};
Waypoint(Affine target_affine): target_affine(target_affine) { }
Waypoint(Affine target_affine, ReferenceType reference_type): target_affine(target_affine), reference_type(reference_type) { }
};
| 24.5 | 128 | 0.750729 | dkuss-tudresden |
ca9f0f0c409880cbec6ef2b351016f46845084f3 | 1,027 | cpp | C++ | codeforces/B - Balanced Substring/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/B - Balanced Substring/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/B - Balanced Substring/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Oct/12/2017 20:21
* solution_verdict: Accepted language: GNU C++14
* run_time: 31 ms memory_used: 4200 KB
* problem: https://codeforces.com/contest/873/problem/B
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long n,qm,ans;
string s;
map<long,long>mp;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
cin>>s;
qm=0;
for(long i=1;i<=n;i++)
{
if(s[i-1]=='1')qm++;
else qm--;
if(qm==0)ans=max(ans,i);
else if(mp[qm]==0)mp[qm]=i;
else ans=max(ans,i-mp[qm]);
}
cout<<ans<<endl;
return 0;
} | 33.129032 | 111 | 0.365141 | kzvd4729 |
caa2c4fd2e85e9803b3342fe3f15708d1cf2fbf9 | 5,149 | hpp | C++ | benchmarks/solvers/gecode/include/gecode/kernel/gpi.hpp | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | benchmarks/solvers/gecode/include/gecode/kernel/gpi.hpp | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | benchmarks/solvers/gecode/include/gecode/kernel/gpi.hpp | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2009
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <cmath>
namespace Gecode { namespace Kernel {
/// Global propagator information
class GPI {
public:
/// Class for storing propagator information
class Info {
public:
/// Propagator identifier
unsigned int pid;
/// Group identifier
unsigned int gid;
/// The afc value
double afc;
/// Initialize
void init(unsigned int pid, unsigned int gid);
};
private:
/// Block of propagator information
class Block : public HeapAllocated {
public:
/// Number of propagator information entries in a block
static const int n_info = 8192;
/// Info entries
Info info[n_info];
/// Next block
Block* next;
/// Number of free blocks
int free;
/// Initialize
Block(void);
/// Rescale used afc values in entries
void rescale(void);
};
/// The current block
Block* b;
/// The inverse decay factor
double invd;
/// Next free propagator id
std::atomic<unsigned int> npid;
/// Whether to unshare
bool us;
/// The first block
Block fst;
/// Mutex to synchronize globally shared access
GECODE_KERNEL_EXPORT static Support::Mutex m;
public:
/// Initialize
GPI(void);
/// Set decay factor to \a d
void decay(double d);
/// Return decay factor
double decay(void) const;
/// Increment failure count
void fail(Info& c);
/// Allocate info for existing propagator with pid \a p
Info* allocate(unsigned int p, unsigned int gid);
/// Allocate new actor info
Info* allocate(unsigned int gid);
/// Return next free propagator id
unsigned int pid(void) const;
/// Provide access to unshare info and set to true
bool unshare(void);
/// Delete
~GPI(void);
};
forceinline void
GPI::Info::init(unsigned int pid0, unsigned int gid0) {
pid=pid0; gid=gid0; afc=1.0;
}
forceinline
GPI::Block::Block(void)
: next(nullptr), free(n_info) {}
forceinline void
GPI::Block::rescale(void) {
for (int i=free; i < n_info; i++)
info[i].afc *= Kernel::Config::rescale;
}
forceinline
GPI::GPI(void)
: b(&fst), invd(1.0), npid(0U), us(false) {}
forceinline void
GPI::fail(Info& c) {
m.acquire();
c.afc = invd * (c.afc + 1.0);
if (c.afc > Kernel::Config::rescale_limit)
for (Block* i = b; i != nullptr; i = i->next)
i->rescale();
m.release();
}
forceinline double
GPI::decay(void) const {
double d;
const_cast<GPI&>(*this).m.acquire();
d = 1.0 / invd;
const_cast<GPI&>(*this).m.release();
return d;
}
forceinline unsigned int
GPI::pid(void) const {
return npid.load(std::memory_order_acquire);
}
forceinline bool
GPI::unshare(void) {
bool u;
m.acquire();
u = us; us = true;
m.release();
return u;
}
forceinline void
GPI::decay(double d) {
m.acquire();
invd = 1.0 / d;
m.release();
}
forceinline GPI::Info*
GPI::allocate(unsigned int p, unsigned int gid) {
Info* c;
m.acquire();
if (b->free == 0) {
Block* n = new Block;
n->next = b; b = n;
}
c = &b->info[--b->free];
m.release();
c->init(p,gid);
return c;
}
forceinline GPI::Info*
GPI::allocate(unsigned int gid) {
Info* c;
m.acquire();
if (b->free == 0) {
Block* n = new Block;
n->next = b; b = n;
}
c = &b->info[--b->free];
m.release();
c->init(npid.fetch_add(std::memory_order::memory_order_seq_cst),gid);
return c;
}
forceinline
GPI::~GPI(void) {
Block* n = b;
while (n != &fst) {
Block* d = n;
n = n->next;
delete d;
}
}
}}
// STATISTICS: kernel-prop
| 24.995146 | 74 | 0.61643 | 95A31 |
caa5133660e6d29c668b4f0cf0cc30d2de035172 | 1,840 | cpp | C++ | Assignment4V1/ArrayLists.cpp | stephe00/DataStructs260 | 931fc728ba184c7f19548579ec8254e4ed507b3a | [
"CC0-1.0"
] | null | null | null | Assignment4V1/ArrayLists.cpp | stephe00/DataStructs260 | 931fc728ba184c7f19548579ec8254e4ed507b3a | [
"CC0-1.0"
] | null | null | null | Assignment4V1/ArrayLists.cpp | stephe00/DataStructs260 | 931fc728ba184c7f19548579ec8254e4ed507b3a | [
"CC0-1.0"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include "ArrayList.h"
using namespace std;
ArrayList::ArrayList() // Total: O(2n+1)
{
topIndex = -1; // O(1)
// Is this good practice?
for (int i = 0; i < 10; i++) // O(2n)
{
myList[i] = NULL; // O(n)
}
}
void ArrayList::addItem(int newValue) // Total (worst case): O(3)
{
if (topIndex < 9) // O(1)
{
topIndex++; // O(1)
myList[topIndex] = newValue; // O(1)
}
else
{
cout << "The list is full!" << endl; // O(1)
}
}
void ArrayList::insertItem(int data, int listIndex) // Total (worst case): O(2n+4)
{
if (listIndex > topIndex + 1) // O(1)
{
cout << "This insert is out of bounds!" << endl; // O(1)
return; // O(1)
}
else if (topIndex < 10) // O(1)
{
for (int i = topIndex; i > listIndex; i--) // O(2n)
{
myList[i] = myList[i-1]; // O(n)
}
topIndex++; // O(1)
myList[listIndex] = data; // O(1)
}
else
{
cout << "The list is full!" << endl; // O(1)
}
}
void ArrayList::deleteItem(int deleteData) // Total (worst case): O(6n+4)
{
int listIndex = topIndex; // O(1)
while (listIndex >= 0) // O(n)
{
if (myList[listIndex] != deleteData) // O(n)
{
listIndex--; // O(n)
}
else
{
// Again, Is this good practice?
myList[listIndex] = NULL; // O(1)
topIndex--; // O(1)
break; // O(1)
}
}
while (listIndex < topIndex) // O(n)
{
myList[listIndex] = myList[listIndex + 1]; // O(n)
listIndex++; // O(n)
}
}
void ArrayList::printList() // Total (worst case): O(2n)
{
for (int i = 0; i <= topIndex; i++) // O(n)
{
cout << myList[i] << endl; // O(n)
}
}
| 21.395349 | 82 | 0.464674 | stephe00 |
caa61d6ab60cc420fd63e5e070f874cb06126db7 | 3,634 | cpp | C++ | SteamMeUp.cpp | Wumpf/SteamMeUp | 61446352ad9843b5ce6815c44b0665cd1c88c0d9 | [
"MIT"
] | null | null | null | SteamMeUp.cpp | Wumpf/SteamMeUp | 61446352ad9843b5ce6815c44b0665cd1c88c0d9 | [
"MIT"
] | null | null | null | SteamMeUp.cpp | Wumpf/SteamMeUp | 61446352ad9843b5ce6815c44b0665cd1c88c0d9 | [
"MIT"
] | null | null | null | #include <windows.h>
#include <Xinput.h>
#include <thread>
#include <atomic>
#include "SteamMeUp.h"
#include "resource.h"
#include "Log.h"
// Undocumented button constants
#define XINPUT_GAMEPAD_GUIDE_BUTTON 0x0400
#define XINPUT_GAMEPAD_UNKNOWN 0x0800
typedef struct
{
unsigned long eventCount;
WORD wButtons;
BYTE bLeftTrigger;
BYTE bRightTrigger;
SHORT sThumbLX;
SHORT sThumbLY;
SHORT sThumbRX;
SHORT sThumbRY;
} XINPUT_STATE_EX;
int(__stdcall *XInputGetStateEx) (int, XINPUT_STATE_EX*);
wchar_t g_steamInstallationPath[MAX_PATH] = L"";
void StartSteam(bool bigPicture)
{
wchar_t steamStartupCommandLine[MAX_PATH * 2];
if (bigPicture)
wsprintf(steamStartupCommandLine, L"%s -bigpicture", g_steamInstallationPath);
else
lstrcpyW(steamStartupCommandLine, g_steamInstallationPath);
LOG(LogLevel::INFO, "Launching steam in big picture mode via \"" << steamStartupCommandLine << "\"...");
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (CreateProcess(NULL, steamStartupCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
LOG(LogLevel::INFO, "Started steam successfully.");
else
LOG(LogLevel::FAIL, "Failed to start steam: " << GetLastErrorAsString());
}
bool InitXInputAndFindSteam()
{
// Query steam installation location.
DWORD bufferSize = sizeof(g_steamInstallationPath);
if (RegGetValue(HKEY_CURRENT_USER,
L"Software\\Valve\\Steam",
L"SteamExe",
RRF_RT_REG_SZ,
NULL,
g_steamInstallationPath,
&bufferSize) == ERROR_SUCCESS)
{
LOG(LogLevel::INFO, "Found steam installation at: " << ToUtf8(g_steamInstallationPath));
}
else
{
LOG(LogLevel::FAIL, "Failed to find steam installation!");
return false;
}
// Query secret gamepad query function that allows to get the guide button.
// The default XInputGetState will never tell us about the guide button.
// https://forums.tigsource.com/index.php?topic=26792.msg847843#msg847843
wchar_t xinputDllPath[MAX_PATH];
GetSystemDirectory(xinputDllPath, sizeof(xinputDllPath));
wcscat_s(xinputDllPath, L"\\xinput1_4.dll");
HINSTANCE xinputDll = LoadLibrary(xinputDllPath);
if (!xinputDll)
{
LOG(LogLevel::FAIL, "Failed to load xinput dll at: " << ToUtf8(xinputDllPath));
return false;
}
XInputGetStateEx = (decltype(XInputGetStateEx))GetProcAddress(xinputDll, (LPCSTR)100);
// Deprecated.
//XInputEnable(TRUE);
return true;
}
void RunXInputMessageLoop(std::atomic<bool>& exited)
{
// Requires to press the button a bit longer but in return we keep the process more idle.
// General issue is that there seems to be no way to run XInput event based :(
const int updateFrequencyHz = 4;
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE);
XINPUT_STATE_EX oldState[XUSER_MAX_COUNT];
ZeroMemory(oldState, sizeof(oldState));
//HANDLE waitableTimer = CreateWaitableTimerW(nullptr, FALSE, nullptr);
while(!exited)
{
for (int i = 0; i < XUSER_MAX_COUNT; ++i)
{
XINPUT_STATE_EX newState;
auto result = XInputGetStateEx(i, &newState);
if (result)
{
ZeroMemory(&oldState[i], sizeof(oldState[i]));
continue;
}
// Released guide button - this way turning off doesn't trigger this.
if ((oldState[i].wButtons & XINPUT_GAMEPAD_GUIDE_BUTTON) != 0 &&
(newState.wButtons & XINPUT_GAMEPAD_GUIDE_BUTTON) == 0)
{
StartSteam(true);
}
oldState[i] = newState;
}
Sleep(1000 / updateFrequencyHz);
//WaitForSingleObject(waitableTimer, 1000 / updateFrequencyHz);
}
//CloseHandle(waitableTimer);
}
| 27.323308 | 105 | 0.720969 | Wumpf |
caa65a5b70668ba301c7760567199ae25a6ecf99 | 731 | cpp | C++ | src/macro/macro28.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null | src/macro/macro28.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null | src/macro/macro28.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null |
#include "Macro.h"
#include "DomainTree.h"
extern DomainTree domain;
int macro28(Macro ¯o)
{
if (!macro)
{
macro.name = "updt";
macro.type = "anly";
macro.what = "update domain for next time step";
macro.sensitivity[INTER] = true;
macro.sensitivity[BATCH] = true;
macro.db.selectDomain();
return 0;
}
//--------------------------------------------------------------------------------------------------
int type, id;
type = roundToInt(macro.p[0]);
id = roundToInt(macro.p[1]) - 1;
domain(type,id).timeUpdate();
//--------------------------------------------------------------------------------------------------
return 0;
}
| 19.236842 | 101 | 0.406293 | chennachaos |
caa69ca72b888cfbc93b9c50ba461bba4072199d | 432 | cpp | C++ | src/main.cpp | yicuiheng/phyicuiheng | af4fef18ad6540675b59bf94e9b1495649dc8bad | [
"MIT"
] | null | null | null | src/main.cpp | yicuiheng/phyicuiheng | af4fef18ad6540675b59bf94e9b1495649dc8bad | [
"MIT"
] | null | null | null | src/main.cpp | yicuiheng/phyicuiheng | af4fef18ad6540675b59bf94e9b1495649dc8bad | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include "model.hpp"
#include "window.hpp"
#include "GLFW/glfw3.h"
int main() {
auto window = std::make_unique<window_t>();
rigid_body_t rigid_body;
auto cloth = model_t::make_cloth(rigid_body);
while (true) {
rigid_body.update(0.1f);
window->update();
window->draw(cloth);
if (window->shouldClose())
break;
}
return 0;
} | 18.782609 | 49 | 0.599537 | yicuiheng |
caa7e99ade9cdafb107a3417b5c7475383c50411 | 916 | hpp | C++ | src/commonpp/thread/detail/Cores.hpp | deco016/commonpp | ad03dcb6f7dc67359d898016c37a848c855c515b | [
"BSD-2-Clause"
] | 32 | 2015-09-17T20:55:58.000Z | 2022-01-24T12:00:39.000Z | src/commonpp/thread/detail/Cores.hpp | deco016/commonpp | ad03dcb6f7dc67359d898016c37a848c855c515b | [
"BSD-2-Clause"
] | 7 | 2015-11-17T21:06:36.000Z | 2018-01-30T09:45:15.000Z | src/commonpp/thread/detail/Cores.hpp | deco016/commonpp | ad03dcb6f7dc67359d898016c37a848c855c515b | [
"BSD-2-Clause"
] | 11 | 2015-09-18T09:11:39.000Z | 2019-10-06T14:53:22.000Z | /*
* File: src/commonpp/thread/detail/Cores.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2016 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
#include <hwloc.h>
#include <vector>
#include "Core.hpp"
namespace commonpp
{
namespace thread
{
namespace detail
{
class Cores
{
public:
enum Options
{
ALL,
PHYSICAL,
};
Cores(Options options = PHYSICAL);
~Cores();
Cores(const Cores&);
Cores& operator=(const Cores&);
Cores(Cores&&) ;
Cores& operator=(Cores&&) ;
Core& operator[](int i);
size_t cores() const;
private:
void get_cores();
private:
Options opt_ = PHYSICAL;
hwloc_topology_t topology_ = nullptr;
size_t nb_cores_;
std::vector<Core> cores_;
};
} // namespace detail
} // namespace thread
} // namespace commonpp
| 15.266667 | 74 | 0.639738 | deco016 |
caa7f40acc86e80d227350c552d091af645a1fb2 | 552 | hpp | C++ | include/mk2/math/binomial_coefficient.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/binomial_coefficient.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/binomial_coefficient.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | //
// binomial_coefficient.hpp
//
//
// Created by Himatya on 2017/02/07.
// Copyright (c) 2017 Himatya. All rights reserved.
//
#pragma once
#include <type_traits>
#include <mk2/math/factorial.hpp>
namespace mk2{
namespace math{
template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type>
inline constexpr T binomial_coefficient(const std::size_t n, const std::size_t r){
return mk2::math::factorial<T>(n) * mk2::math::inverse_factorial<T>(r) * mk2::math::inverse_factorial<T>(n - r);
}
}
}
| 24 | 120 | 0.688406 | SachiSakurane |
caa81cbf972fb9d7b4ccd454151184349ea40120 | 34,958 | cpp | C++ | src/frameworks/av/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | src/frameworks/av/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | src/frameworks/av/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 12 | 2020-04-15T11:37:33.000Z | 2021-09-13T13:19:04.000Z | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.073
ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
Available from http://www.3gpp.org
(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
Filename: /audio/gsm_amr/c/src/q_plsf_5_tbl.c
------------------------------------------------------------------------------
REVISION HISTORY
Description: Created this file from the reference, q_plsf_5_tbl.tab
Description: Changed #defines of DICO_SIZE to DICO_5_SIZE, to avoid name
conflicts.
Description: Added #ifdef __cplusplus and removed "extern" from table
definition.
Description: Put "extern" back.
Who: Date:
Description:
------------------------------------------------------------------------------
MODULE DESCRIPTION
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "typedef.h"
#include "q_plsf_5_tbl.h"
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif
/*----------------------------------------------------------------------------
; MACROS
; [Define module specific macros here]
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; [Include all pre-processor statements here. Include conditional
; compile variables also.]
----------------------------------------------------------------------------*/
#define NB_QUA_PITCH 16
#define NB_QUA_CODE 32
#define DICO1_5_SIZE 128
#define DICO2_5_SIZE 256
#define DICO3_5_SIZE 256
#define DICO4_5_SIZE 256
#define DICO5_5_SIZE 64
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; [List function prototypes here]
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL VARIABLE DEFINITIONS
; [Variable declaration - defined here and used outside this module]
----------------------------------------------------------------------------*/
/* LSF means ->normalize frequency domain */
const Word16 mean_lsf_5[10] =
{
1384,
2077,
3420,
5108,
6742,
8122,
9863,
11092,
12714,
13701
};
const Word16 dico1_lsf_5[DICO1_5_SIZE * 4] =
{
-451, -1065, -529, -1305,
-450, -756, -497, -863,
-384, -619, -413, -669,
-317, -538, -331, -556,
-414, -508, -424, -378,
-274, -324, -434, -614,
-226, -500, -232, -514,
-263, -377, -298, -410,
-151, -710, -174, -818,
-149, -412, -156, -429,
-288, -462, -186, -203,
-170, -302, -191, -321,
-131, -147, -297, -395,
-228, -214, -245, -192,
-67, -316, -71, -327,
-104, -205, -94, -183,
-143, -38, -193, -95,
16, -76, -124, -248,
23, -237, 24, -244,
18, -136, 44, -111,
-33, -24, -25, 0,
149, 19, 23, -143,
158, -169, 174, -181,
133, -55, 165, -26,
111, 84, 98, 75,
87, 183, -115, -11,
-8, 130, 11, 170,
254, 77, 205, 17,
183, 112, 262, 194,
202, 287, 95, 189,
-42, -105, 234, 179,
39, 186, 163, 345,
332, 199, 299, 161,
-54, 285, -78, 281,
-133, 141, -182, 111,
249, 341, 271, 364,
93, 403, 75, 391,
92, 510, -138, 220,
-185, -29, -34, 361,
-115, 320, 3, 554,
99, 286, 218, 591,
-245, 406, -268, 453,
0, 580, 25, 606,
275, 532, 148, 450,
-73, 739, -285, 518,
-288, 94, -203, 674,
-140, -74, 205, 714,
-114, 299, 176, 923,
182, 557, 240, 705,
-16, 513, 485, 593,
293, 384, 451, 617,
-38, 50, 563, 529,
303, 209, 459, 363,
433, 452, 450, 454,
367, 606, 477, 741,
432, 353, 368, 267,
361, 716, 273, 583,
453, 166, 510, 172,
201, 629, 274, 191,
568, 639, 302, 298,
634, 387, 643, 350,
587, 560, 612, 565,
600, 788, 487, 672,
512, 1015, 321, 333,
357, 854, -125, 413,
474, 712, 17, -151,
564, 285, 270, -241,
971, 889, 489, 220,
510, 896, 549, 924,
327, 825, 290, 911,
540, 1108, 158, 805,
199, 957, 511, 730,
100, 874, 13, 791,
435, 632, 676, 972,
249, 900, 467, 1218,
781, 1074, 585, 785,
-23, 669, 267, 1043,
619, 1084, 615, 1145,
622, 905, 916, 1049,
80, 331, 584, 1075,
89, 639, 988, 961,
770, 720, 798, 699,
492, 447, 899, 627,
271, 1188, 725, 1333,
87, 603, 832, 1603,
616, 1127, 890, 1505,
1000, 1156, 866, 1009,
995, 827, 1149, 858,
817, 1450, 773, 1320,
500, 1389, 312, 1153,
-20, 1084, 64, 1283,
2, 1172, 399, 1869,
514, 1706, 502, 1636,
886, 1522, 416, 600,
1131, 1350, 1275, 1390,
889, 1795, 914, 1766,
227, 1183, 1250, 1826,
505, 1854, 919, 2353,
-199, 431, 152, 1735,
-213, -28, 392, 1334,
-153, -52, 978, 1151,
-323, -400, 813, 1703,
-136, 84, 1449, 2015,
-331, -143, -137, 1192,
-256, 534, -157, 1031,
-307, -439, 542, 731,
-329, -420, -97, 616,
-362, -168, -322, 366,
-247, -110, -211, 89,
-196, -309, 20, 59,
-364, -463, -286, 89,
-336, 175, -432, 141,
-379, -190, -434, -196,
-79, 150, -278, -227,
-280, 166, -555, -422,
-155, 541, -366, 54,
-29, -83, -301, -774,
186, 628, -397, -264,
242, 293, -197, -585,
124, 410, 53, -133,
10, 340, -570, -1065,
65, -446, 68, -493,
383, 937, -357, -711,
-359, -250, -677, -1068,
292, -26, 363, 6,
607, 1313, -127, -10,
1513, 1886, 713, 972,
1469, 2181, 1443, 2016
};
const Word16 dico2_lsf_5[DICO2_5_SIZE * 4] =
{
-1631, -1600, -1796, -2290,
-1027, -1770, -1100, -2025,
-1277, -1388, -1367, -1534,
-947, -1461, -972, -1524,
-999, -1222, -1020, -1172,
-815, -987, -992, -1371,
-1216, -1006, -1289, -1094,
-744, -1268, -755, -1293,
-862, -923, -905, -984,
-678, -1051, -685, -1050,
-1087, -985, -1062, -679,
-989, -641, -1127, -976,
-762, -654, -890, -806,
-833, -1091, -706, -629,
-621, -806, -640, -812,
-775, -634, -779, -543,
-996, -565, -1075, -580,
-546, -611, -572, -619,
-760, -290, -879, -526,
-823, -462, -795, -253,
-553, -415, -589, -439,
-533, -340, -692, -935,
-505, -772, -702, -1131,
-263, -306, -971, -483,
-445, -74, -555, -548,
-614, -129, -693, -234,
-396, -246, -475, -250,
-265, -404, -376, -514,
-417, -510, -300, -313,
-334, -664, -463, -814,
-386, -704, -337, -615,
-234, -201, -233, -239,
-167, -567, -203, -619,
-147, -415, -115, -352,
-166, -750, -171, -761,
-270, -879, -264, -903,
-367, -744, 43, -475,
14, -653, 43, -670,
11, -448, -59, -521,
-126, -119, -155, -613,
-42, -863, -27, -931,
136, -483, 183, -468,
55, -298, 55, -304,
313, -609, 313, -720,
322, -167, 100, -541,
-3, -119, -111, -187,
233, -236, 260, -234,
26, -165, 134, -45,
-40, -549, 360, -203,
378, -388, 450, -383,
275, 20, 182, -103,
246, -111, 431, 37,
462, -146, 487, -157,
-284, -59, 503, -184,
24, 53, -3, 54,
122, 259, 333, 66,
484, 104, 436, 68,
195, 116, 190, 206,
269, -9, 482, 352,
382, 285, 399, 277,
452, 256, 69, 186,
13, 297, -13, 259,
-95, 30, 56, 394,
196, 425, 205, 456,
281, 577, 15, 191,
375, 290, 407, 576,
-56, 227, 544, 405,
0, 549, -92, 528,
-229, 351, -245, 338,
-362, 435, 167, 527,
-75, 302, 91, 824,
129, 599, 496, 679,
186, 749, 153, 737,
-281, 600, -348, 615,
-236, 769, 41, 881,
38, 890, -220, 841,
-357, 883, -393, 903,
-634, 474, -444, 850,
-175, 678, -493, 242,
-519, 785, -714, 582,
-541, 366, -543, 434,
-597, 500, -765, 222,
-702, 917, -743, 962,
-869, 501, -899, 548,
-379, 200, -435, 157,
-819, 214, -861, 157,
-614, 40, -632, 94,
-883, -54, -741, 516,
-501, 298, -614, -171,
-870, -161, -865, -23,
-818, 93, -1015, -267,
-662, -359, -549, 2,
-442, -121, -377, 0,
-227, 33, -414, -126,
-129, 212, -934, 34,
-1082, -282, -1119, -268,
-710, -825, -420, -191,
-1076, -928, -917, -93,
-628, -358, 97, 7,
-206, -393, -101, 24,
-203, 38, -168, 83,
-599, -423, -279, 426,
-700, 118, -75, 206,
-981, -673, -680, 417,
-367, 37, -279, 474,
-129, -318, 319, 296,
-626, -39, 343, 602,
-696, -39, -303, 940,
104, 233, -380, 137,
-36, 269, -75, -214,
120, 43, -529, -477,
459, 164, -202, -229,
-49, -167, 609, 792,
98, -220, 915, 148,
293, 283, 869, 91,
575, 394, 326, -78,
717, 67, 365, -323,
616, -36, 731, 27,
619, 238, 632, 273,
448, 99, 801, 476,
869, 273, 685, 64,
789, 72, 1021, 217,
793, 459, 734, 360,
646, 480, 360, 322,
429, 464, 638, 430,
756, 363, 1000, 404,
683, 528, 602, 615,
655, 413, 946, 687,
937, 602, 904, 604,
555, 737, 786, 662,
467, 654, 362, 589,
929, 710, 498, 478,
415, 420, 693, 883,
813, 683, 781, 925,
913, 939, 726, 732,
491, 853, 531, 948,
734, 963, 315, 808,
761, 755, 1144, 760,
655, 1076, 826, 1057,
1091, 838, 1003, 808,
1047, 1133, 659, 1101,
992, 1050, 1074, 1075,
971, 694, 1226, 1054,
571, 841, 884, 1404,
1379, 1096, 1080, 861,
1231, 735, 1284, 760,
1272, 991, 1367, 1053,
1257, 700, 1050, 534,
988, 453, 1264, 599,
1140, 679, 1621, 815,
1384, 521, 1317, 393,
1564, 805, 1448, 686,
1068, 648, 875, 307,
1083, 361, 1047, 317,
1417, 964, 675, 571,
1152, 79, 1114, -47,
1530, 311, 1721, 314,
1166, 689, 514, -94,
349, 282, 1412, 328,
1025, 487, -65, 57,
805, 970, 36, 62,
769, -263, 791, -346,
637, 699, -137, 620,
534, 541, -735, 194,
711, 300, -268, -863,
926, 769, -708, -428,
506, 174, -892, -630,
435, 547, -1435, -258,
621, 471, -1018, -1368,
-393, 521, -920, -686,
-25, 20, -982, -1156,
340, 9, -1558, -1135,
-352, 48, -1579, -402,
-887, 6, -1156, -888,
-548, -352, -1643, -1168,
-159, 610, -2024, -963,
-225, 193, -1656, -1960,
-245, -493, -964, -1680,
-936, -635, -1299, -1744,
-1388, -604, -1540, -835,
-1397, -135, -1588, -290,
-1670, -712, -2011, -1632,
-1663, -27, -2258, -811,
-1157, 184, -1265, 189,
-1367, 586, -2011, 201,
-790, 712, -1210, 3,
-1033, 808, -1251, 830,
-111, 635, -1636, 447,
-463, -949, -445, -928,
-504, -1162, -501, -1211,
144, -351, -372, -1052,
-283, -1059, -279, -1123,
-575, -1438, -587, -1614,
-935, -984, 229, 690,
-921, -719, -403, 1362,
-685, -465, 874, 397,
-509, -46, 317, 1334,
-485, 456, 813, 439,
-411, 339, 898, 1067,
-425, 46, 1441, 497,
-909, -800, 1465, 1046,
-254, -321, 1430, 1165,
68, 350, 1034, 666,
370, 11, 1311, 790,
143, 232, 1041, 1562,
-114, 663, 1616, 1078,
454, 579, 1275, 1040,
-76, 909, 752, 1067,
153, 512, 348, 1214,
614, 385, 1843, 808,
269, 1034, 203, 1086,
652, 1017, 1783, 1130,
429, 1327, 387, 1384,
-49, 1183, -72, 1215,
-416, 1001, 544, 1749,
-352, 1223, -502, 1199,
-589, 569, -227, 1630,
-142, 1578, -230, 1715,
-714, 1288, -838, 1398,
1131, 1357, -208, 1232,
437, 965, -929, 818,
811, 1410, 859, 1507,
164, 1212, 1387, 1793,
484, 1874, 456, 2063,
996, 1170, 1326, 1402,
1316, 1360, 1135, 1262,
1234, 1618, 1361, 1768,
1421, 1227, 1584, 1347,
854, 672, 1685, 1566,
1139, 1270, 2016, 1825,
1773, 1581, 1532, 1460,
1487, 946, 1659, 1021,
1744, 1212, 1392, 977,
1772, 1161, 1826, 1164,
1718, 1429, 1973, 1591,
1185, 864, 2132, 1061,
1799, 814, 1838, 757,
2104, 1315, 2054, 1258,
2113, 915, 2331, 930,
1467, 1147, 2590, 1439,
2245, 1744, 2090, 1620,
2358, 1454, 2666, 1506,
1876, 1837, 2070, 1975,
1739, 1577, 682, 1289,
1584, 2045, 1454, 2098,
2498, 2004, 2711, 2066,
726, 1588, 2756, 2336,
228, 847, 2456, 1659,
36, 301, 1942, 1957,
-446, -96, 2154, 1396,
1533, 1101, 14, 608,
-923, -732, 1383, 1982,
1345, 952, -680, 321,
1281, 1268, -1594, 365,
941, 946, -1737, -822,
2374, 2787, 1821, 2788
};
const Word16 dico3_lsf_5[DICO3_5_SIZE * 4] =
{
-1812, -2275, -1879, -2537,
-1640, -1848, -1695, -2004,
-1220, -1912, -1221, -2106,
-1559, -1588, -1573, -1556,
-1195, -1615, -1224, -1727,
-1359, -1151, -1616, -1948,
-1274, -1391, -1305, -1403,
-1607, -1179, -1676, -1311,
-1443, -1478, -1367, -898,
-1256, -1059, -1331, -1134,
-982, -1133, -1149, -1504,
-1080, -1308, -1020, -1183,
-980, -1486, -967, -1495,
-988, -922, -1047, -1077,
-838, -1179, -858, -1222,
-1131, -1041, -1064, -767,
-872, -1157, -701, -880,
-706, -906, -774, -1016,
-578, -1080, -801, -1478,
-591, -1111, -592, -1146,
-713, -1388, -640, -1376,
-597, -1059, -416, -903,
-686, -832, -661, -708,
-444, -868, -490, -921,
-374, -776, -619, -1170,
-585, -549, -769, -795,
-435, -659, -530, -741,
-498, -837, -357, -597,
-279, -871, -243, -887,
-282, -665, -280, -667,
-165, -560, -394, -903,
-362, -410, -448, -583,
-409, -574, -313, -357,
-637, -548, -570, -436,
-896, -504, -382, -757,
-58, -481, -165, -618,
-191, -374, -234, -382,
-222, -683, -25, -480,
-418, -359, -730, -353,
-324, -157, -432, -322,
-394, -303, -284, -104,
-601, -289, -556, -196,
-588, -150, -659, -608,
-473, -24, -68, -448,
-474, -8, -506, -45,
-748, -184, -844, -252,
-901, -91, -584, -97,
-652, 138, -764, -131,
-678, -12, -670, 165,
-259, -3, -840, -107,
-909, 37, -992, 44,
-854, -415, -839, 13,
-1001, -271, -1026, -309,
-798, -478, -832, -488,
-943, 168, -1112, -387,
-1185, -101, -1183, -40,
-941, -316, -1030, -770,
-1044, -625, -1081, -538,
-1224, -299, -1312, -436,
-1197, -663, -1167, -161,
-1216, -690, -1237, -831,
-1432, -720, -1403, -493,
-898, -740, -922, -801,
-1102, -402, -1579, -964,
-1061, -638, -1269, -1438,
-1499, -934, -1502, -895,
-1598, -564, -1723, -717,
-606, -597, -1166, -1085,
-1369, -468, -1946, -1493,
-1838, -953, -1932, -931,
-1499, -188, -1635, -421,
-1457, -338, -1448, -22,
-1942, -422, -2006, -249,
-496, -114, -1910, -755,
-1289, 174, -1451, -109,
-482, -257, -1221, -508,
-1617, 151, -1694, 208,
-654, 107, -1651, 29,
-1141, 279, -1215, 306,
-1228, -506, -730, -175,
-1236, -101, -969, 551,
-870, 278, -823, 315,
-563, 376, -1051, 228,
-507, 280, -599, 281,
-758, 253, -305, 379,
-755, -134, -611, 660,
-824, 536, -817, 646,
-413, 49, -341, 177,
-453, 526, -482, 589,
-71, 339, -657, 264,
-244, 295, -237, 315,
-387, 569, -506, -9,
-377, 14, -160, 661,
-216, 40, -308, -46,
95, 214, -242, 167,
-86, 192, -56, 27,
-76, 31, 36, 309,
-106, -182, -113, 74,
-441, -22, 23, 139,
81, -11, 44, 15,
-87, -137, -118, -207,
-158, -58, 272, -92,
-156, -441, 8, -136,
128, -221, 101, -218,
40, -197, -76, -456,
9, -445, 33, -423,
226, 60, 73, -222,
156, -399, 280, -318,
245, -341, 166, -499,
339, -190, 327, -219,
325, -137, -89, -596,
100, -627, 144, -677,
487, 28, 252, -391,
214, -41, 282, -28,
99, -286, 331, 49,
459, -388, 565, -369,
436, 28, 336, -9,
397, -167, 618, 34,
596, -17, 561, -140,
299, 79, 522, 125,
203, 2, 244, 288,
255, 211, 175, 82,
596, 187, 517, 108,
381, 255, 365, 297,
497, 352, 327, -82,
25, 210, 371, 245,
261, 3, 545, 449,
140, 294, 44, 295,
212, 347, 244, 494,
331, 528, 201, 307,
349, 411, 613, 284,
614, 413, 464, 322,
624, 397, 97, 200,
-160, 384, 149, 362,
495, 525, 269, 585,
33, 491, -121, 433,
427, 611, 498, 516,
171, 443, 497, 666,
440, 275, 566, 575,
146, 639, 155, 670,
-33, 173, 212, 696,
-166, 601, -191, 695,
-489, 503, 175, 742,
214, 476, 372, 1083,
578, 530, 586, 777,
425, 874, 315, 841,
374, 848, -165, 565,
35, 991, -39, 1062,
329, 712, 786, 840,
645, 795, 661, 676,
571, 918, 632, 1079,
673, 817, 318, 388,
874, 1012, 564, 848,
880, 620, 557, 479,
671, 453, 692, 468,
840, 642, 844, 645,
506, 428, 897, 567,
837, 387, 962, 499,
691, 561, 939, 926,
783, 296, 790, 268,
1028, 530, 874, 329,
548, 143, 675, 291,
503, 66, 1041, 359,
786, 97, 805, 33,
837, 470, 511, 49,
1092, 327, 1174, 323,
3, 242, 872, 474,
689, 429, 1329, 678,
1042, 620, 1109, 664,
321, 193, 889, 950,
1153, 874, 893, 635,
877, 862, 948, 913,
1293, 665, 1320, 639,
997, 793, 1402, 1030,
1176, 1012, 1110, 959,
1410, 925, 1403, 915,
543, 862, 1116, 1222,
835, 1190, 835, 1190,
959, 1148, 1147, 1376,
1300, 1193, 1415, 1231,
1335, 1341, 746, 1092,
1711, 1283, 1389, 1073,
1334, 1566, 1153, 1475,
1645, 1137, 1825, 1220,
1056, 1382, 1521, 1730,
1632, 1545, 1620, 1542,
855, 1596, 865, 1667,
693, 885, 1716, 1519,
1167, 1296, 2209, 1760,
1952, 1493, 2020, 1482,
1534, 1866, 1694, 2008,
1566, 748, 1761, 825,
294, 1392, 1084, 2058,
621, 1315, 365, 1287,
198, 1028, 488, 1408,
249, 403, 1014, 1561,
324, 363, 1645, 1044,
193, 367, 2034, 1859,
-251, 579, 750, 994,
-243, 30, 1325, 879,
-28, -169, 624, 917,
-453, 159, 186, 1370,
-614, 6, 537, 392,
-94, -291, 781, 229,
-128, -298, 245, 491,
-701, -648, 972, 789,
-501, -640, 178, 255,
-365, -390, -255, 317,
-958, -294, -191, 228,
-775, -447, 157, -237,
-657, -720, -407, 92,
-117, -611, 334, -230,
-679, -1084, -144, -317,
-901, -861, -738, -360,
-85, -727, -90, -787,
100, -22, -391, -263,
-56, -73, -337, -754,
5, -189, -706, -624,
89, -344, -135, -1113,
-353, -237, -684, -1135,
-275, -1102, -269, -1203,
152, 145, -722, -1232,
49, 80, -1248, -776,
-248, 391, -732, -547,
469, 218, -255, -864,
69, 366, -166, -485,
-688, 191, -1212, -1196,
-170, -169, -1308, -1631,
321, 470, -1419, -1243,
-64, 272, -1361, -248,
492, 565, -721, -609,
195, 485, -573, -133,
427, 202, -171, -118,
199, 575, 2, -31,
694, 755, -1366, -39,
552, 557, -489, 271,
680, 537, 13, -453,
855, 954, -133, -52,
-81, 738, -1169, 637,
1055, 1059, -95, 676,
1259, 1081, 489, 305,
-449, 954, -534, 996,
-969, 866, -1058, 1059,
-1294, 618, -1416, 617,
-458, 1366, -159, 1821,
-774, -528, -14, 1110,
-1202, -901, -772, 433,
-1256, -1255, -1011, -302,
-602, -585, -759, -1618,
-760, -1549, -840, -1921,
-816, -539, -1769, -2235,
-227, -36, -2034, -1831,
-2107, -1126, -2471, -1816,
-1470, 252, -2701, -415,
-571, -467, 1509, 1554,
2180, 1975, 2326, 2020
};
const Word16 dico4_lsf_5[DICO4_5_SIZE * 4] =
{
-1857, -1681, -1857, -1755,
-2056, -1150, -2134, -1654,
-1619, -1099, -1704, -1131,
-1345, -1608, -1359, -1638,
-1338, -1293, -1325, -1265,
-1664, -1649, -1487, -851,
-1346, -1832, -1413, -2188,
-1282, -681, -1785, -1649,
-966, -1082, -1183, -1676,
-1054, -1073, -1142, -1158,
-1207, -744, -1274, -997,
-934, -1383, -927, -1416,
-1010, -1305, -783, -955,
-1049, -900, -993, -817,
-737, -823, -972, -1189,
-738, -1094, -738, -1154,
-784, -801, -810, -786,
-892, -520, -1000, -818,
-644, -965, -577, -882,
-541, -694, -671, -917,
-595, -642, -646, -615,
-956, -621, -925, -515,
-727, -483, -815, -485,
-840, -578, -440, -713,
-578, -325, -657, -670,
-386, -570, -441, -666,
-514, -787, -392, -529,
-522, -453, -487, -423,
-616, -585, -617, -157,
-662, -268, -680, -348,
-322, -323, -632, -444,
-304, -430, -332, -458,
-277, -468, -659, -793,
-319, -636, -227, -554,
-373, -347, -334, -210,
-456, -192, -530, -242,
-216, -198, -366, -370,
-338, -161, -409, -748,
-107, -380, -294, -643,
-223, -665, -234, -741,
-141, -496, -130, -510,
-139, -327, -172, -305,
-306, -580, -164, -263,
-262, -172, -67, -402,
31, -366, -10, -436,
-86, -527, 71, -377,
-22, -609, -12, -678,
-67, -319, 63, -191,
35, -181, -39, -242,
126, -167, -140, -544,
155, -297, 174, -297,
38, -8, 117, -380,
197, -452, 240, -522,
223, -103, 110, -187,
87, -155, 169, -47,
157, 26, -83, -100,
128, 80, 209, -62,
6, 7, 22, 5,
318, -20, 248, -45,
-200, -63, 156, -69,
250, -183, 369, -126,
-113, -76, -142, -122,
-64, -254, -31, 35,
-177, -71, -7, 171,
93, 27, 108, 212,
-330, -209, -123, -70,
-279, 95, -96, 20,
-188, -61, -314, 87,
-300, -78, -354, -134,
11, 122, -140, 122,
-275, 152, -293, 140,
-82, 138, -321, -111,
-480, -156, -359, 76,
-254, -40, -635, -96,
-522, 79, -507, 8,
-268, 303, -539, 68,
-446, 61, -522, 306,
111, 189, -435, 122,
-379, 166, -571, -398,
-632, -74, -747, -95,
-455, 194, -952, 83,
-798, 192, -755, 192,
-781, -162, -619, 234,
-663, -297, -488, -109,
-964, -132, -838, -68,
-843, 58, -1112, -86,
-805, -299, -944, -253,
-778, -50, -965, -549,
-352, -98, -992, -343,
-1117, -315, -1117, -307,
-1155, -374, -637, -230,
-1166, -43, -1299, -100,
-925, -393, -1274, -600,
-689, -130, -1479, -312,
-1321, -254, -1464, -442,
-1292, -613, -1261, -503,
-1501, -368, -1322, 26,
-1432, -66, -1743, -161,
-1644, -467, -1760, -548,
-1393, -568, -1556, -871,
-1495, -1034, -1387, -571,
-1917, -528, -1783, -123,
-1897, -231, -2054, -323,
-2052, -906, -1976, -567,
-1917, -620, -2047, -989,
-1077, -370, -2031, -704,
-2355, -749, -2740, -1089,
-1909, 159, -2012, 248,
-626, -123, -2339, -962,
-669, -408, -1379, -1174,
-452, -364, -1044, -735,
-132, 183, -1620, -752,
-547, -307, -777, -1261,
-98, 41, -880, -1091,
-257, 97, -1602, -1833,
31, -26, -644, -561,
-180, -546, -385, -1095,
-410, -802, -414, -827,
-457, -970, -490, -1109,
-215, -916, -144, -937,
-493, -1269, -517, -1507,
181, 101, -332, -889,
-836, -937, -559, -429,
-629, -547, -183, -337,
-545, -82, -250, -286,
5, -132, -348, -252,
-293, -472, -158, 100,
-29, 197, -236, -424,
-861, -213, -140, -7,
-427, -443, 187, -97,
-684, -736, -293, 258,
-368, -152, -150, 392,
-609, 175, -142, 299,
-138, 152, -119, 329,
-486, -52, 293, 198,
-183, 117, 175, 331,
-58, -274, 231, 300,
-288, 330, -305, 372,
-111, 409, -9, 423,
83, 256, 67, 367,
-19, 248, 91, 113,
-35, 406, -191, 154,
238, 296, 5, 197,
141, 221, 313, 198,
211, 421, 244, 334,
88, 426, -243, 454,
202, 552, -5, 403,
291, 185, 219, 301,
251, 138, 128, 69,
197, 288, -140, -61,
188, 361, 197, 598,
442, 273, 290, 143,
472, 482, 157, 370,
415, 321, 372, 385,
402, 552, 155, 24,
550, 263, -11, 21,
360, 227, 147, -254,
424, 97, 366, -13,
375, 141, 449, 232,
396, 507, 474, 272,
701, 324, 362, -47,
587, 148, 543, 69,
400, -51, 561, 59,
220, -10, 352, 147,
206, 211, 653, 185,
563, 297, 565, 284,
594, 121, 766, 192,
398, 118, 642, 434,
233, 264, 481, 467,
129, -165, 699, 239,
90, 26, 342, 474,
-55, 27, 388, 94,
-172, 0, 725, 379,
-60, 337, 370, 465,
95, 319, 806, 595,
78, 260, 497, 851,
210, 560, 458, 574,
-464, 202, 497, 625,
-202, 152, 48, 712,
-20, 566, 100, 715,
455, 468, 411, 605,
319, 646, 195, 615,
401, 538, 680, 739,
201, 667, 434, 954,
454, 425, 646, 491,
606, 681, 416, 508,
497, 822, 426, 815,
660, 647, 628, 716,
697, 466, 618, 457,
685, 460, 365, 309,
721, 567, 836, 601,
609, 300, 825, 459,
943, 687, 681, 533,
915, 598, 591, 243,
876, 451, 874, 420,
786, 317, 732, 220,
922, 317, 1108, 367,
531, 466, 1028, 649,
1053, 615, 1034, 553,
829, 602, 1021, 799,
927, 803, 878, 763,
799, 496, 1373, 773,
585, 770, 803, 930,
1099, 793, 1222, 862,
1209, 895, 1025, 727,
772, 845, 1172, 1115,
867, 1021, 830, 1013,
841, 910, 506, 703,
1239, 1077, 620, 819,
1196, 1083, 1155, 1081,
1142, 907, 1547, 1121,
1309, 648, 1343, 612,
1484, 988, 1479, 937,
985, 1328, 955, 1341,
429, 910, 841, 1338,
564, 1179, 412, 1156,
1427, 1320, 1434, 1330,
640, 760, 1726, 1410,
190, 555, 1073, 1005,
426, 257, 839, 980,
235, 231, 1520, 1167,
109, 293, 1014, 1569,
305, 142, 1148, 539,
-291, -108, 1213, 972,
22, -216, 667, 828,
-482, 438, 453, 1431,
-581, -422, 789, 387,
-358, -454, 174, 780,
-36, -372, 390, -134,
-629, 160, -306, 751,
-1258, -331, 177, 522,
-248, 574, -251, 639,
-531, 407, -596, 394,
-419, 789, -617, 801,
-986, 399, -857, 727,
-7, 518, -703, 310,
-1143, -24, -1002, 287,
-960, 363, -1299, 312,
-1534, 245, -1557, 305,
28, 153, -859, -175,
-33, 332, -1398, -154,
212, 410, -593, -197,
-1092, -704, -904, -65,
282, 367, -918, -686,
345, 93, -258, -357,
696, 644, -693, -28,
448, 493, -273, 193,
527, 546, -243, -513,
384, -136, 273, -353,
512, -142, 537, -198,
941, 750, 83, 248,
578, 861, -56, 592,
842, 44, 892, 24,
33, 890, -16, 982,
831, 1398, 1535, 1898,
1716, 1376, 1948, 1465
};
const Word16 dico5_lsf_5[DICO5_5_SIZE * 4] =
{
-1002, -929, -1096, -1203,
-641, -931, -604, -961,
-779, -673, -835, -788,
-416, -664, -458, -766,
-652, -521, -662, -495,
-1023, -509, -1023, -428,
-444, -552, -368, -449,
-479, -211, -1054, -903,
-316, -249, -569, -591,
-569, -275, -541, -191,
-716, -188, -842, -264,
-333, -248, -318, -228,
-275, 1, -567, -228,
-115, -221, -238, -374,
-197, -507, -222, -579,
-258, -432, -61, -244,
-345, 2, -338, 39,
-215, -169, -58, 0,
-56, -6, -203, -131,
1, -186, -5, -211,
6, -380, 11, -418,
-116, 131, -134, 113,
89, -4, 71, -2,
-19, -192, 262, 24,
189, 151, -133, -109,
186, -153, 166, -219,
37, 139, 193, 171,
337, 124, 158, -61,
141, 226, -13, 190,
231, 34, 354, 109,
316, 201, 244, 164,
330, -85, 390, -84,
254, 327, 257, 335,
491, 147, 476, 105,
54, 77, 437, 370,
421, 314, 449, 342,
329, 126, 673, 292,
571, 388, 243, 193,
653, 320, 621, 280,
194, 380, 517, 581,
45, 323, 111, 422,
489, 395, 734, 534,
622, 546, 486, 502,
318, 572, 189, 550,
385, 422, -157, 153,
-125, 382, -197, 386,
-263, 334, 228, 697,
-188, 1, 51, 297,
-507, 213, -376, 397,
-24, 255, -547, 89,
-502, -94, 387, 179,
-620, 68, -684, 112,
-642, -350, -260, 172,
-438, -324, 264, 648,
-964, -4, -1121, 7,
-134, 134, -1133, -306,
143, 96, -420, -497,
-1221, -350, -1527, -685,
-161, 72, 873, 691,
732, 283, 921, 353,
334, 475, 1095, 821,
864, 524, 843, 497,
714, 711, 788, 750,
1076, 714, 1204, 753
};
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
/*
------------------------------------------------------------------------------
FUNCTION NAME:
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
None
Outputs:
None
Returns:
None
Global Variables Used:
None
Local Variables Needed:
None
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
None
------------------------------------------------------------------------------
REQUIREMENTS
None
------------------------------------------------------------------------------
REFERENCES
[1] q_plsf_5.tab, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
RESOURCES USED [optional]
When the code is written for a specific target processor the
the resources used should be documented below.
HEAP MEMORY USED: x bytes
STACK MEMORY USED: x bytes
CLOCK CYCLES: (cycle count equation for this function) + (variable
used to represent cycle count for each subroutine
called)
where: (cycle count variable) = cycle count for [subroutine
name]
------------------------------------------------------------------------------
CAUTION [optional]
[State any special notes, constraints or cautions for users of this function]
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
| 30.006867 | 89 | 0.407003 | dAck2cC2 |
caacb89275df398ff97df1a966b033990b680277 | 2,491 | hpp | C++ | src/IO/Observer/Actions/RegisterWithObservers.hpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | null | null | null | src/IO/Observer/Actions/RegisterWithObservers.hpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | 1 | 2022-03-25T18:26:16.000Z | 2022-03-25T19:30:39.000Z | src/IO/Observer/Actions/RegisterWithObservers.hpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <type_traits>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "IO/Observer/Actions/ObserverRegistration.hpp"
#include "IO/Observer/ObservationId.hpp"
#include "IO/Observer/ObserverComponent.hpp"
#include "IO/Observer/TypeOfObservation.hpp"
#include "Parallel/ArrayIndex.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/Invoke.hpp"
/// \cond
template <class... Tags>
class TaggedTuple;
/// \endcond
namespace observers::Actions {
/*!
* \brief Register an observation ID with the observers.
*
* \warning If registering events, you should use RegisterEventsWithObservers
* instead. If your event is not compatible with RegisterEventsWithObservers,
* please make it so.
*
* The `RegisterHelper` passed as a template parameter must have a static
* `register_info` function that takes as its first template parameter the
* `ParallelComponent` and as function arguments a `db::DataBox` and the array
* component index. The function must return a
* `std::pair<observers::TypeOfObservation, observers::ObservationId>`
*/
template <typename RegisterHelper>
struct RegisterWithObservers {
template <typename DbTagList, typename... InboxTags, typename Metavariables,
typename ArrayIndex, typename ActionList,
typename ParallelComponent>
static std::tuple<db::DataBox<DbTagList>&&> apply(
db::DataBox<DbTagList>& box,
const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,
Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& array_index, const ActionList /*meta*/,
const ParallelComponent* const /*meta*/) noexcept {
auto& observer =
*Parallel::get_parallel_component<observers::Observer<Metavariables>>(
cache)
.ckLocalBranch();
const auto [type_of_observation, observation_id] =
RegisterHelper::template register_info<ParallelComponent>(box,
array_index);
Parallel::simple_action<
observers::Actions::RegisterContributorWithObserver>(
observer, observation_id,
observers::ArrayComponentId(
std::add_pointer_t<ParallelComponent>{nullptr},
Parallel::ArrayIndex<std::decay_t<ArrayIndex>>{array_index}),
type_of_observation);
return {std::move(box)};
}
};
} // namespace observers::Actions
| 36.632353 | 79 | 0.708551 | tomwlodarczyk |
caad0fcab8fff7de40dd1b8798e3ff63441a7d38 | 12,089 | cc | C++ | annotator/duration/duration.cc | yangzhigang1999/libtextclassifier | 4c965f1c12b3c7a37f6126cef737a8fe33f4677c | [
"Apache-2.0"
] | null | null | null | annotator/duration/duration.cc | yangzhigang1999/libtextclassifier | 4c965f1c12b3c7a37f6126cef737a8fe33f4677c | [
"Apache-2.0"
] | null | null | null | annotator/duration/duration.cc | yangzhigang1999/libtextclassifier | 4c965f1c12b3c7a37f6126cef737a8fe33f4677c | [
"Apache-2.0"
] | 1 | 2021-03-20T03:40:21.000Z | 2021-03-20T03:40:21.000Z | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "annotator/duration/duration.h"
#include <climits>
#include <cstdlib>
#include "annotator/collections.h"
#include "annotator/types.h"
#include "utils/base/logging.h"
#include "utils/base/macros.h"
#include "utils/strings/numbers.h"
#include "utils/utf8/unicodetext.h"
namespace libtextclassifier3 {
using DurationUnit = internal::DurationUnit;
namespace internal {
namespace {
std::string ToLowerString(const std::string& str, const UniLib* unilib) {
return unilib->ToLowerText(UTF8ToUnicodeText(str, /*do_copy=*/false))
.ToUTF8String();
}
void FillDurationUnitMap(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
expressions,
DurationUnit duration_unit,
std::unordered_map<std::string, DurationUnit>* target_map,
const UniLib* unilib) {
if (expressions == nullptr) {
return;
}
for (const flatbuffers::String* expression_string : *expressions) {
(*target_map)[ToLowerString(expression_string->c_str(), unilib)] =
duration_unit;
}
}
} // namespace
std::unordered_map<std::string, DurationUnit> BuildTokenToDurationUnitMapping(
const DurationAnnotatorOptions* options, const UniLib* unilib) {
std::unordered_map<std::string, DurationUnit> mapping;
FillDurationUnitMap(options->week_expressions(), DurationUnit::WEEK, &mapping,
unilib);
FillDurationUnitMap(options->day_expressions(), DurationUnit::DAY, &mapping,
unilib);
FillDurationUnitMap(options->hour_expressions(), DurationUnit::HOUR, &mapping,
unilib);
FillDurationUnitMap(options->minute_expressions(), DurationUnit::MINUTE,
&mapping, unilib);
FillDurationUnitMap(options->second_expressions(), DurationUnit::SECOND,
&mapping, unilib);
return mapping;
}
std::unordered_set<std::string> BuildStringSet(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
strings,
const UniLib* unilib) {
std::unordered_set<std::string> result;
if (strings == nullptr) {
return result;
}
for (const flatbuffers::String* string_value : *strings) {
result.insert(ToLowerString(string_value->c_str(), unilib));
}
return result;
}
std::unordered_set<int32> BuildInt32Set(
const flatbuffers::Vector<int32>* ints) {
std::unordered_set<int32> result;
if (ints == nullptr) {
return result;
}
for (const int32 int_value : *ints) {
result.insert(int_value);
}
return result;
}
// Get the dangling quantity unit e.g. for 2 hours 10, 10 would have the unit
// "minute".
DurationUnit GetDanglingQuantityUnit(const DurationUnit main_unit) {
switch (main_unit) {
case DurationUnit::HOUR:
return DurationUnit::MINUTE;
case DurationUnit::MINUTE:
return DurationUnit::SECOND;
case DurationUnit::UNKNOWN:
TC3_LOG(ERROR) << "Requesting parse of UNKNOWN duration duration_unit.";
TC3_FALLTHROUGH_INTENDED;
case DurationUnit::WEEK:
case DurationUnit::DAY:
case DurationUnit::SECOND:
// We only support dangling units for hours and minutes.
return DurationUnit::UNKNOWN;
}
}
} // namespace internal
bool DurationAnnotator::ClassifyText(
const UnicodeText& context, CodepointSpan selection_indices,
AnnotationUsecase annotation_usecase,
ClassificationResult* classification_result) const {
if (!options_->enabled() || ((options_->enabled_annotation_usecases() &
(1 << annotation_usecase))) == 0) {
return false;
}
const UnicodeText selection =
UnicodeText::Substring(context, selection_indices.first,
selection_indices.second, /*do_copy=*/false);
const std::vector<Token> tokens = feature_processor_->Tokenize(selection);
AnnotatedSpan annotated_span;
if (tokens.empty() ||
FindDurationStartingAt(context, tokens, 0, &annotated_span) !=
tokens.size()) {
return false;
}
TC3_DCHECK(!annotated_span.classification.empty());
*classification_result = annotated_span.classification[0];
return true;
}
bool DurationAnnotator::FindAll(const UnicodeText& context,
const std::vector<Token>& tokens,
AnnotationUsecase annotation_usecase,
std::vector<AnnotatedSpan>* results) const {
if (!options_->enabled() || ((options_->enabled_annotation_usecases() &
(1 << annotation_usecase))) == 0) {
return true;
}
for (int i = 0; i < tokens.size();) {
AnnotatedSpan span;
const int next_i = FindDurationStartingAt(context, tokens, i, &span);
if (next_i != i) {
results->push_back(span);
i = next_i;
} else {
i++;
}
}
return true;
}
int DurationAnnotator::FindDurationStartingAt(const UnicodeText& context,
const std::vector<Token>& tokens,
int start_token_index,
AnnotatedSpan* result) const {
CodepointIndex start_index = kInvalidIndex;
CodepointIndex end_index = kInvalidIndex;
bool has_quantity = false;
ParsedDurationAtom parsed_duration;
std::vector<ParsedDurationAtom> parsed_duration_atoms;
// This is the core algorithm for finding the duration expressions. It
// basically iterates over tokens and changes the state variables above as it
// goes.
int token_index;
int quantity_end_index;
for (token_index = start_token_index; token_index < tokens.size();
token_index++) {
const Token& token = tokens[token_index];
if (ParseQuantityToken(token, &parsed_duration)) {
has_quantity = true;
if (start_index == kInvalidIndex) {
start_index = token.start;
}
quantity_end_index = token.end;
} else if (((!options_->require_quantity() || has_quantity) &&
ParseDurationUnitToken(token, &parsed_duration.unit)) ||
ParseQuantityDurationUnitToken(token, &parsed_duration)) {
if (start_index == kInvalidIndex) {
start_index = token.start;
}
end_index = token.end;
parsed_duration_atoms.push_back(parsed_duration);
has_quantity = false;
parsed_duration = ParsedDurationAtom();
} else if (ParseFillerToken(token)) {
} else {
break;
}
}
if (parsed_duration_atoms.empty()) {
return start_token_index;
}
const bool parse_ended_without_unit_for_last_mentioned_quantity =
has_quantity;
if (parse_ended_without_unit_for_last_mentioned_quantity) {
const DurationUnit main_unit = parsed_duration_atoms.rbegin()->unit;
if (parsed_duration.plus_half) {
// Process "and half" suffix.
end_index = quantity_end_index;
ParsedDurationAtom atom = ParsedDurationAtom::Half();
atom.unit = main_unit;
parsed_duration_atoms.push_back(atom);
} else if (options_->enable_dangling_quantity_interpretation()) {
// Process dangling quantity.
ParsedDurationAtom atom;
atom.value = parsed_duration.value;
atom.unit = GetDanglingQuantityUnit(main_unit);
if (atom.unit != DurationUnit::UNKNOWN) {
end_index = quantity_end_index;
parsed_duration_atoms.push_back(atom);
}
}
}
ClassificationResult classification{Collections::Duration(),
options_->score()};
classification.priority_score = options_->priority_score();
classification.duration_ms =
ParsedDurationAtomsToMillis(parsed_duration_atoms);
result->span = feature_processor_->StripBoundaryCodepoints(
context, {start_index, end_index});
result->classification.push_back(classification);
result->source = AnnotatedSpan::Source::DURATION;
return token_index;
}
int64 DurationAnnotator::ParsedDurationAtomsToMillis(
const std::vector<ParsedDurationAtom>& atoms) const {
int64 result = 0;
for (auto atom : atoms) {
int multiplier;
switch (atom.unit) {
case DurationUnit::WEEK:
multiplier = 7 * 24 * 60 * 60 * 1000;
break;
case DurationUnit::DAY:
multiplier = 24 * 60 * 60 * 1000;
break;
case DurationUnit::HOUR:
multiplier = 60 * 60 * 1000;
break;
case DurationUnit::MINUTE:
multiplier = 60 * 1000;
break;
case DurationUnit::SECOND:
multiplier = 1000;
break;
case DurationUnit::UNKNOWN:
TC3_LOG(ERROR) << "Requesting parse of UNKNOWN duration duration_unit.";
return -1;
break;
}
double value = atom.value;
// This condition handles expressions like "an hour", where the quantity is
// not specified. In this case we assume quantity 1. Except for cases like
// "half hour".
if (value == 0 && !atom.plus_half) {
value = 1;
}
result += value * multiplier;
result += atom.plus_half * multiplier / 2;
}
return result;
}
bool DurationAnnotator::ParseQuantityToken(const Token& token,
ParsedDurationAtom* value) const {
if (token.value.empty()) {
return false;
}
std::string token_value_buffer;
const std::string& token_value = feature_processor_->StripBoundaryCodepoints(
token.value, &token_value_buffer);
const std::string& lowercase_token_value =
internal::ToLowerString(token_value, unilib_);
if (half_expressions_.find(lowercase_token_value) !=
half_expressions_.end()) {
value->plus_half = true;
return true;
}
double parsed_value;
if (ParseDouble(lowercase_token_value.c_str(), &parsed_value)) {
value->value = parsed_value;
return true;
}
return false;
}
bool DurationAnnotator::ParseDurationUnitToken(
const Token& token, DurationUnit* duration_unit) const {
std::string token_value_buffer;
const std::string& token_value = feature_processor_->StripBoundaryCodepoints(
token.value, &token_value_buffer);
const std::string& lowercase_token_value =
internal::ToLowerString(token_value, unilib_);
const auto it = token_value_to_duration_unit_.find(lowercase_token_value);
if (it == token_value_to_duration_unit_.end()) {
return false;
}
*duration_unit = it->second;
return true;
}
bool DurationAnnotator::ParseQuantityDurationUnitToken(
const Token& token, ParsedDurationAtom* value) const {
if (token.value.empty()) {
return false;
}
Token sub_token;
bool has_quantity = false;
for (const char c : token.value) {
if (sub_token_separator_codepoints_.find(c) !=
sub_token_separator_codepoints_.end()) {
if (has_quantity || !ParseQuantityToken(sub_token, value)) {
return false;
}
has_quantity = true;
sub_token = Token();
} else {
sub_token.value += c;
}
}
return (!options_->require_quantity() || has_quantity) &&
ParseDurationUnitToken(sub_token, &(value->unit));
}
bool DurationAnnotator::ParseFillerToken(const Token& token) const {
std::string token_value_buffer;
const std::string& token_value = feature_processor_->StripBoundaryCodepoints(
token.value, &token_value_buffer);
const std::string& lowercase_token_value =
internal::ToLowerString(token_value, unilib_);
if (filler_expressions_.find(lowercase_token_value) ==
filler_expressions_.end()) {
return false;
}
return true;
}
} // namespace libtextclassifier3
| 31.646597 | 80 | 0.674746 | yangzhigang1999 |
cab0a1f6540ef1de3d592383848171d34a4876a0 | 435 | cpp | C++ | 83.cpp | jonathanxqs/lintcode | 148435aff0a83ac5d77a7ccbd5d0caaea3140a62 | [
"MIT"
] | 1 | 2016-06-21T16:29:37.000Z | 2016-06-21T16:29:37.000Z | 83.cpp | jonathanxqs/lintcode | 148435aff0a83ac5d77a7ccbd5d0caaea3140a62 | [
"MIT"
] | null | null | null | 83.cpp | jonathanxqs/lintcode | 148435aff0a83ac5d77a7ccbd5d0caaea3140a62 | [
"MIT"
] | null | null | null | class Solution {
public:
/**
* @param A : An integer array
* @return : An integer
*/
int singleNumberII(vector<int> &A) {
// write your code here
int count[32] = {0};
int res = 0;
for (int i = 0; i < 32; i++) {
for (auto &v : A) {
count[i] += (v >> i) & 1;
}
res |= ((count[i] % 3) << i);
}
return res;
}
}; | 22.894737 | 41 | 0.381609 | jonathanxqs |
cab200e8d78e3f792e9d8addea4d8aec7e357ea2 | 6,021 | cc | C++ | Engine/graphicsystem/base/StreamBufferPool.cc | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 26 | 2015-01-15T12:57:40.000Z | 2022-02-16T10:07:12.000Z | Engine/graphicsystem/base/StreamBufferPool.cc | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | null | null | null | Engine/graphicsystem/base/StreamBufferPool.cc | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 17 | 2015-02-18T07:51:31.000Z | 2020-06-01T01:10:12.000Z | /****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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 "stdneb.h"
#include "StreamBufferPool.h"
#include "graphicsystem/GraphicSystem.h"
namespace Graphic
{
__ImplementClass(MemoryPool,'MMPL',Core::RefCounted)
MemoryPool::MemoryPool()
:mData(NULL)
,mSize(0)
{
}
MemoryPool::~MemoryPool()
{
n_assert(mBlocks.Count() == 0);
n_assert(NULL == mData);
n_assert(0 == mSize);
}
void MemoryPool::Setup(SizeT blockSize)
{
n_assert(mBlocks.Count() == 0);
n_assert(NULL == mData);
n_assert(0 == mSize);
alloc(blockSize);
}
void MemoryPool::Destroy()
{
free();
}
void MemoryPool::Clear()
{
mBlocks.Clear();
}
MemoryPool::pointer MemoryPool::_getPtr(int begin) const
{
n_assert(mSize > begin);
return mData + begin;
}
bool MemoryPool::GetBlock(SizeT size, MemoryBlock& out)
{
SizeT freeSize = getFreeSize();
if (freeSize < size)
{
return false;
}
blocks::ValueType& bl = mBlocks.PushBack();
bl.begin = mSize - freeSize;
bl.size = size;
out._set(this, bl.begin, bl.size);
return true;
}
bool MemoryPool::_checkBlcok(const MemoryBlock& check)
{
if (check.mParent)
{
const StreamBufferPool* sbp = GraphicSystem::Instance()->_GetPool();
if (sbp->_checkMemoryPool(check.mParent))
{
blocks::ConstIterator it = check.mParent->mBlocks.Begin();
blocks::ConstIterator end = check.mParent->mBlocks.End();
while(it != end)
{
if ((it->begin == check.mBegin) && (it->size == check.mSize))
{
return true;
}
++it;
}
}
}
return false;
}
SizeT MemoryPool::getFreeSize()
{
blocks::ConstIterator back = mBlocks.Back();
if (back)
{
return mSize - (back->begin + back->size);
}
else
{
return mSize;
}
}
void MemoryPool::alloc(SizeT size)
{
n_assert(0 == mSize);
n_assert(NULL == mData);
mData = n_new_array(buffer_type, size);
mSize = size;
}
void MemoryPool::free()
{
n_delete_array(mData);
mData = NULL;
mSize = 0;
mBlocks.Clear();
}
__ImplementClass(StreamBufferPool,'SBPL',Core::RefCounted)
StreamBufferPool::StreamBufferPool()
{
}
StreamBufferPool::~StreamBufferPool()
{
n_assert(!mDefualtPool.isvalid());
n_assert(mAditionPools.Size() == 0);
n_assert(mCustomPools.Size() == 0);
}
MemoryBlock StreamBufferPool::GetBlock(SizeT sizeInByte)
{
n_assert(mDefualtPool.isvalid());
n_assert(sizeInByte > 0);
MemoryBlock block;
if (!mDefualtPool->GetBlock(sizeInByte, block))
{
if (sizeInByte > mAditionSize)
{
if (0 == mCustomPools.Size())
{
MemoryPoolPtr custom = MemoryPool::Create();
custom->Setup(sizeInByte);
mCustomPools.Append(custom);
}
if (!mCustomPools[0]->GetBlock(sizeInByte, block))
{
mCustomPools[0]->Destroy();
mCustomPools[0]->Setup(sizeInByte);
if (!mCustomPools[0]->GetBlock(sizeInByte, block))
{
n_error("error: get buffer false");
}
}
}
else
{
bool result = false;
MemoryPools::Iterator it = mAditionPools.Begin();
MemoryPools::Iterator end = mAditionPools.End();
while(it != end)
{
result = (*it)->GetBlock(sizeInByte, block);
if (result)
{
break;
}
}
if (!result)
{
MemoryPoolPtr add = MemoryPool::Create();
add->Setup(mAditionSize);
mAditionPools.Append(add);
if (!add->GetBlock(sizeInByte, block))
{
n_error("error: get buffer false");
}
}
}
}
return block;
}
void StreamBufferPool::Setup(SizeT defaultSize, SizeT aditionSize)
{
n_assert(mAditionPools.Size() == 0);
n_assert(!mDefualtPool.isvalid());
n_assert(mCustomPools.Size() == 0);
mDefualtSize = defaultSize;
mAditionSize = aditionSize;
mDefualtPool = MemoryPool::Create();
mDefualtPool->Setup(defaultSize);
}
void StreamBufferPool::Destory()
{
mDefualtPool->Destroy();
mDefualtPool = NULL;
MemoryPools::Iterator it = mAditionPools.Begin();
MemoryPools::Iterator end = mAditionPools.End();
while(it != end)
{
(*it)->Destroy();
}
mAditionPools.Clear();
MemoryPools::Iterator it2 = mCustomPools.Begin();
MemoryPools::Iterator end2 = mCustomPools.End();
while(it2 != end2)
{
(*it2)->Destroy();
}
mCustomPools.Clear();
mDefualtSize = 0;
mAditionSize = 0;
}
bool StreamBufferPool::_checkMemoryPool(const MemoryPool* pool) const
{
if(mDefualtPool.get() == pool)
{
return true;
}
MemoryPools::Iterator it = mAditionPools.Begin();
MemoryPools::Iterator end = mAditionPools.End();
while(it != end)
{
if(it->get() == pool)
{
return true;
}
}
MemoryPools::Iterator it2 = mCustomPools.Begin();
MemoryPools::Iterator end2 = mCustomPools.End();
while(it2 != end2)
{
if(it2->get() == pool)
{
return true;
}
}
return false;
}
}
| 22.550562 | 77 | 0.650889 | BikkyS |
cab691fea264b4ce49fab17f5434a43ea327b2a4 | 1,267 | cpp | C++ | 000/50.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/50.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/50.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | // https://projecteuler.net/problem=50
// Consecutive prime sum
#include <iostream>
#include <string>
#include <algorithm>
#include "../Shared/primes.h"
using namespace std;
// Construct an array of sums of primes, ie
// v[0] = 0
// v[1] = 2
// v[2] = 2 + 3
// v[3] = 2 + 3 + 5
// ... etc
// A sum of consecutive primes can be represented as a difference in entries in
// this array. ex:
// sum of 2 ... 13 = v[6] - v[0]
// sum of 5 ... 23 = v[9] - v[2]
// Find the greatest D such that v[a + D] - v[D] is prime and < 1 million.
//
int main(int argc, char* argv[]) {
const unsigned int sumLimit = 1000000;
vector<unsigned long long> primeSum(1);
for (auto p : primes) {
primeSum.push_back(p + primeSum.back());
if (primeSum.back() > sumLimit)
break;
}
unsigned int maxSum = 0;
unsigned int maxDiff = 0;
for (int diff = 1; primeSum[diff] < sumLimit; diff++)
for (int i = diff; i < primeSum.size(); i++) {
if (primeSum[i] - primeSum[i-diff] > sumLimit)
break;
if (isPrime(primeSum[i] - primeSum[i-diff])) {
maxDiff = diff;
maxSum = primeSum[i] - primeSum[i-diff];
}
}
printf("%u consecutive primes sum to %u\n", maxDiff, maxSum);
getchar();
return 0;
}
| 23.036364 | 80 | 0.584846 | correipj |
caba704833c136a6ee88e318bd3cb79a9a355e2c | 2,784 | cpp | C++ | 3rdparty/libprocess/src/posix/subprocess.cpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 4,537 | 2015-01-01T03:26:40.000Z | 2022-03-31T03:07:00.000Z | 3rdparty/libprocess/src/posix/subprocess.cpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 227 | 2015-01-29T02:21:39.000Z | 2022-03-29T13:35:50.000Z | 3rdparty/libprocess/src/posix/subprocess.cpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 1,992 | 2015-01-05T12:29:19.000Z | 2022-03-31T03:07:07.000Z | // 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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <glog/logging.h>
#include <process/future.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#include <stout/error.hpp>
#include <stout/lambda.hpp>
#include <stout/foreach.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/os/pipe.hpp>
#include <stout/os/strerror.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
using std::array;
using std::map;
using std::string;
using std::vector;
namespace process {
using InputFileDescriptors = Subprocess::IO::InputFileDescriptors;
using OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;
Subprocess::IO Subprocess::PIPE()
{
return Subprocess::IO(
[]() -> Try<InputFileDescriptors> {
Try<array<int, 2>> pipefd = os::pipe();
if (pipefd.isError()) {
return Error(pipefd.error());
}
InputFileDescriptors fds;
fds.read = pipefd->at(0);
fds.write = pipefd->at(1);
return fds;
},
[]() -> Try<OutputFileDescriptors> {
Try<array<int, 2>> pipefd = os::pipe();
if (pipefd.isError()) {
return Error(pipefd.error());
}
OutputFileDescriptors fds;
fds.read = pipefd->at(0);
fds.write = pipefd->at(1);
return fds;
});
}
Subprocess::IO Subprocess::PATH(const string& path)
{
return Subprocess::IO(
[path]() -> Try<InputFileDescriptors> {
Try<int> open = os::open(path, O_RDONLY | O_CLOEXEC);
if (open.isError()) {
return Error("Failed to open '" + path + "': " + open.error());
}
InputFileDescriptors fds;
fds.read = open.get();
return fds;
},
[path]() -> Try<OutputFileDescriptors> {
Try<int> open = os::open(
path,
O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (open.isError()) {
return Error("Failed to open '" + path + "': " + open.error());
}
OutputFileDescriptors fds;
fds.write = open.get();
return fds;
});
}
} // namespace process {
| 26.514286 | 75 | 0.621408 | zagrev |
cabbaa88bea3cf8e2b055daca286037cc3a1df61 | 1,008 | cpp | C++ | luanics/logging/test/SimpleSourceTest.cpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | luanics/logging/test/SimpleSourceTest.cpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | luanics/logging/test/SimpleSourceTest.cpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | #include "luanics/logging/LevelFilter.hpp"
#include "luanics/logging/SimpleSink.hpp"
#include "luanics/logging/SimpleSource.hpp"
#include "luanics/logging/TupleRecord.hpp"
#include "luanics/testing/Unit.hpp"
#include <cstring>
#include <sstream>
using namespace luanics::logging;
BEGIN_TEST_SET(SimpleSource)
TEST(All) {
std::ostringstream out;
SimpleSource source;
source.setFilter(std::make_unique<LevelFilter>(Level::INFO));
source.setSink(std::make_unique<SimpleSink>(&out));
auto record1 = makeTupleRecord(Level::WARNING, "Source.cpp", 10, "data:", 42);
auto record2 = makeTupleRecord(Level::INFO, "File.cpp", 200, "stuff:", 101);
auto record3 = makeTupleRecord(Level::DEBUG, "File.cpp", 300, "stuff:", 201);
source.submit(std::move(record1));
source.submit(std::move(record2));
source.submit(std::move(record3));
std::string expected{
"[WARNING] Source.cpp:10 - data: 42 \n"
"[INFO ] File.cpp:200 - stuff: 101 \n"
};
EXPECT_EQ(expected, out.str());
}
END_TEST_SET(SimpleSource)
| 30.545455 | 79 | 0.729167 | luanics |
cabc8c6c4e730cb33cfe7ce4f3aa5d8df5be788f | 3,962 | cpp | C++ | pdbApp/qsrv.cpp | simon-ess/pva2pva | ad8b77e19f7e2ae50c48b5d871bdbe7b0ee23b61 | [
"MIT"
] | 3 | 2015-11-17T23:15:12.000Z | 2019-11-09T21:12:09.000Z | pdbApp/qsrv.cpp | simon-ess/pva2pva | ad8b77e19f7e2ae50c48b5d871bdbe7b0ee23b61 | [
"MIT"
] | 42 | 2017-10-04T10:21:29.000Z | 2021-10-19T18:19:50.000Z | pdbApp/qsrv.cpp | simon-ess/pva2pva | ad8b77e19f7e2ae50c48b5d871bdbe7b0ee23b61 | [
"MIT"
] | 8 | 2017-09-28T07:32:47.000Z | 2021-03-17T14:58:00.000Z |
#include <initHooks.h>
#include <epicsExit.h>
#include <epicsThread.h>
#include <epicsString.h>
#include <epicsStdio.h>
#include <dbAccess.h>
#include <dbChannel.h>
#include <dbStaticLib.h>
#include <dbLock.h>
#include <dbEvent.h>
#include <epicsVersion.h>
#include <dbNotify.h>
#include <pv/reftrack.h>
#include <pv/pvAccess.h>
#include <pv/serverContext.h>
#include <pv/iocshelper.h>
#include "pv/qsrv.h"
#include "pvahelper.h"
#include "pvif.h"
#include "pdb.h"
#include "pdbsingle.h"
#ifdef USE_MULTILOCK
# include "pdbgroup.h"
#endif
#include <epicsExport.h>
namespace pva = epics::pvAccess;
void QSRVRegistrar_counters()
{
epics::registerRefCounter("PDBSinglePV", &PDBSinglePV::num_instances);
epics::registerRefCounter("PDBSingleChannel", &PDBSingleChannel::num_instances);
epics::registerRefCounter("PDBSinglePut", &PDBSinglePut::num_instances);
epics::registerRefCounter("PDBSingleMonitor", &PDBSingleMonitor::num_instances);
#ifdef USE_MULTILOCK
epics::registerRefCounter("PDBGroupPV", &PDBGroupPV::num_instances);
epics::registerRefCounter("PDBGroupChannel", &PDBGroupChannel::num_instances);
epics::registerRefCounter("PDBGroupPut", &PDBGroupPut::num_instances);
epics::registerRefCounter("PDBGroupMonitor", &PDBGroupMonitor::num_instances);
#endif // USE_MULTILOCK
epics::registerRefCounter("PDBProvider", &PDBProvider::num_instances);
}
long dbLoadGroup(const char* fname)
{
try {
if(!fname) {
printf("dbLoadGroup(\"file.json\")\n"
"\n"
"Load additional DB group definitions from file.\n");
return 1;
}
#ifndef USE_MULTILOCK
static bool warned;
if(!warned) {
warned = true;
fprintf(stderr, "ignoring %s\n", fname);
}
#endif
if(fname[0]=='-') {
fname++;
if(fname[0]=='*' && fname[1]=='\0') {
PDBProvider::group_files.clear();
} else {
PDBProvider::group_files.remove(fname);
}
} else {
PDBProvider::group_files.remove(fname);
PDBProvider::group_files.push_back(fname);
}
return 0;
}catch(std::exception& e){
fprintf(stderr, "Error: %s\n", e.what());
return 1;
}
}
namespace {
void dbLoadGroupWrap(const char* fname)
{
(void)dbLoadGroup(fname);
}
void dbgl(int lvl, const char *pattern)
{
if(!pattern)
pattern = "";
try {
PDBProvider::shared_pointer prov(
std::tr1::dynamic_pointer_cast<PDBProvider>(
pva::ChannelProviderRegistry::servers()->getProvider("QSRV")));
if(!prov)
throw std::runtime_error("No Provider (PVA server not running?)");
PDBProvider::persist_pv_map_t pvs;
{
epicsGuard<epicsMutex> G(prov->transient_pv_map.mutex());
pvs = prov->persist_pv_map; // copy map
}
for(PDBProvider::persist_pv_map_t::const_iterator it(pvs.begin()), end(pvs.end());
it != end; ++it)
{
if(pattern[0] && epicsStrGlobMatch(it->first.c_str(), pattern)==0)
continue;
printf("%s\n", it->first.c_str());
if(lvl<=0)
continue;
it->second->show(lvl);
}
}catch(std::exception& e){
fprintf(stderr, "Error: %s\n", e.what());
}
}
void QSRVRegistrar()
{
QSRVRegistrar_counters();
pva::ChannelProviderRegistry::servers()->addSingleton<PDBProvider>("QSRV");
epics::iocshRegister<int, const char*, &dbgl>("dbgl", "level", "pattern");
epics::iocshRegister<const char*, &dbLoadGroupWrap>("dbLoadGroup", "jsonfile");
}
} // namespace
unsigned qsrvVersion(void)
{
return QSRV_VERSION_INT;
}
unsigned qsrvABIVersion(void)
{
return QSRV_ABI_VERSION_INT;
}
extern "C" {
epicsExportRegistrar(QSRVRegistrar);
}
| 26.413333 | 90 | 0.615851 | simon-ess |
cac1073b8f99c2f07fa8e082e88719a077f57e86 | 4,539 | cpp | C++ | simulation_intersection_scenario/costcriteria.cpp | SirTobias/DMPCRobotSimulation | e393538b37e5a63bfe4da94e9bd13feba45699db | [
"MIT"
] | 2 | 2021-12-06T08:05:12.000Z | 2022-03-22T13:56:38.000Z | simulation_intersection_scenario/costcriteria.cpp | SirTobias/DMPCRobotSimulation | e393538b37e5a63bfe4da94e9bd13feba45699db | [
"MIT"
] | null | null | null | simulation_intersection_scenario/costcriteria.cpp | SirTobias/DMPCRobotSimulation | e393538b37e5a63bfe4da94e9bd13feba45699db | [
"MIT"
] | 1 | 2022-03-29T12:46:37.000Z | 2022-03-29T12:46:37.000Z | #include "costcriteria.h"
#include "intersectionparameters.h"
#include <cmath>
/**
* @brief CostCriteria::CostCriteria
*/
CostCriteria::CostCriteria(const std::shared_ptr<SystemFunction>& sysFunc) {
m_globalLiveTime = sysFunc->getGlobalLiveTime();
m_globalWaitTime = sysFunc->getGlobalWaitTime();
m_reservationRequests = sysFunc->getReservationRequests();
m_waitTimeNextCell = sysFunc->getWaitTimeNextCell();
m_externalReservationRequests = sysFunc->getExternalReservationRequests();
}
CostCriteria::CostCriteria(const CarInformation& carInfo) {
m_globalLiveTime = carInfo.getGlobalLiveTime();
m_globalWaitTime = carInfo.getGlobalWaitTime();
m_reservationRequests = carInfo.getReservationRequests();
m_waitTimeNextCell = carInfo.getWaitTimeNextCell();
m_externalReservationRequests = carInfo.getExternalReservationRequests();
}
/**
* @brief CostCriteria::getGlobalLiveTime
* @return
*/
int64_t CostCriteria::getGlobalLiveTime() const {
return m_globalLiveTime;
}
/**
* @brief CostCriteria::setGlobalLiveTime
* @param t
*/
void CostCriteria::setGlobalLiveTime(const int64_t &t) {
m_globalLiveTime = t;
}
/**
* @brief CostCriteria::getGlobalWaitTime
* @return
*/
int64_t CostCriteria::getGlobalWaitTime() const {
return m_globalWaitTime;
}
/**
* @brief CostCriteria::setGlobalWaitTime
* @param t
*/
void CostCriteria::setGlobalWaitTime(const int64_t &t) {
m_globalWaitTime = t;
}
/**
* @brief CostCriteria::getReservationRequests
* @return
*/
int64_t CostCriteria::getReservationRequests() const {
return m_reservationRequests;
}
/**
* @brief CostCriteria::setReservationRequests
* @param r
*/
void CostCriteria::setReservationRequests(const int64_t &r) {
m_reservationRequests = r;
}
/**
* @brief CostCriteria::getWaitTimeNextCell
* @return
*/
int64_t CostCriteria::getWaitTimeNextCell() const {
return m_waitTimeNextCell;
}
/**
* @brief CostCriteria::setWaitTimeNextCell
* @param t
*/
void CostCriteria::setWaitTimeNextCell(const int64_t &t) {
m_waitTimeNextCell = t;
}
/**
* @brief CostCriteria::getExternalReservationRequests
* @return
*/
int64_t CostCriteria::getExternalReservationRequests() const {
return m_externalReservationRequests;
}
/**
* @brief CostCriteria::setExternalReservationRequests
* @param r
*/
void CostCriteria::setExternalReservationRequests(const int64_t &r) {
m_externalReservationRequests = r;
}
/**
* @brief CostCriteria::getCumulatedCosts sums up the weighted criteria and return the sum
* @return sum of weighted criteria
*/
double CostCriteria::getCumulatedCosts() const {
double costs = 0.0;
if (InterSectionParameters::directComm == 1) {
//global waitTime
costs += InterSectionParameters::weightGlobalWaitTime * (double)getGlobalLiveTime();
//global livetime
costs += InterSectionParameters::weightGlobalLiveTime * (double)getGlobalWaitTime();
//count reservation requests
costs += (double)InterSectionParameters::weightReservRequests * (double)getReservationRequests();
//wait time for certain next cell
costs += (double)InterSectionParameters::weightTimeNextCell * (double)getWaitTimeNextCell();
//amount of external reservation requests on current cell
costs += (double)InterSectionParameters::weightExternalReservRequests * (double)getExternalReservationRequests();
}
return costs;
}
/**
* @brief CostCriteria::getCumulatedQuadraticCosts squares the components, sums them up and returns the accumulated sum
* @return sum_of(criteria)^2
*/
double CostCriteria::getCumulatedQuadraticCosts() const {
double costs = 0.0;
if (InterSectionParameters::directComm == 1) {
//global waitTime
costs += std::pow(InterSectionParameters::weightGlobalWaitTime * (double)getGlobalLiveTime(),2);
//global livetime
costs += std::pow(InterSectionParameters::weightGlobalLiveTime * (double)getGlobalWaitTime(),2);
//count reservation requests
costs += std::pow((double)InterSectionParameters::weightReservRequests * (double)getReservationRequests(), 2);
//wait time for certain next cell
costs += std::pow((double)InterSectionParameters::weightTimeNextCell * (double)getWaitTimeNextCell(), 2);
//amount of external reservation requests on current cell
costs += std::pow((double)InterSectionParameters::weightExternalReservRequests * (double)getExternalReservationRequests(), 2);
}
return costs;
}
| 31.089041 | 134 | 0.735404 | SirTobias |
cac1a6e7742f933c8ac41471a8e342057b3b25b7 | 42,193 | cpp | C++ | draw_png.cpp | WRIM/mcmap | 86c67ff1482b5090d563a9dfc49f87832b1ffc2b | [
"BSD-2-Clause"
] | 19 | 2015-07-26T20:32:10.000Z | 2020-04-17T14:24:18.000Z | draw_png.cpp | WRIM/mcmap | 86c67ff1482b5090d563a9dfc49f87832b1ffc2b | [
"BSD-2-Clause"
] | null | null | null | draw_png.cpp | WRIM/mcmap | 86c67ff1482b5090d563a9dfc49f87832b1ffc2b | [
"BSD-2-Clause"
] | 10 | 2015-09-05T17:45:26.000Z | 2021-01-22T04:24:07.000Z | /**
* This file contains functions to create and draw to a png image
*/
#include "draw_png.h"
#include "helper.h"
#include "colors.h"
#include "globals.h"
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <png.h>
#include <list>
#include <ctime>
#ifndef _WIN32
#include <sys/stat.h>
#endif
#if defined(_WIN32) && !defined(__GNUC__)
# include <direct.h>
#endif
#ifndef Z_BEST_SPEED
# define Z_BEST_SPEED 6
#endif
#define PIXEL(x,y) (gImageBuffer[((x) + gOffsetX) * CHANSPERPIXEL + ((y) + gOffsetY) * gPngLocalLineWidthChans])
namespace
{
struct ImagePart {
int x, y, width, height;
char *filename;
FILE *pngFileHandle;
png_structp pngPtr;
png_infop pngInfo;
ImagePart(const char *_file, int _x, int _y, int _w, int _h) {
filename = strdup(_file);
x = _x;
y = _y;
width = _w;
height = _h;
pngPtr = NULL;
pngFileHandle = NULL;
pngInfo = NULL;
}
~ImagePart() {
free(filename);
}
};
struct ImageTile {
FILE *fileHandle;
png_structp pngPtr;
png_infop pngInfo;
};
typedef std::list<ImagePart *> imageList;
imageList partialImages;
uint8_t *gImageBuffer = NULL;
int gPngLocalLineWidthChans = 0, gPngLocalWidth = 0, gPngLocalHeight = 0;
int gPngLineWidthChans = 0, gPngWidth = 0, gPngHeight = 0;
int gOffsetX = 0, gOffsetY = 0;
uint64_t gPngSize = 0, gPngLocalSize = 0;
png_structp pngPtrMain = NULL; // Main image
png_infop pngInfoPtrMain = NULL;
png_structp pngPtrCurrent = NULL; // This will be either the same as above, or a temp image when using disk caching
FILE *gPngPartialFileHandle = NULL;
inline void blend(uint8_t * const destination, const uint8_t * const source);
inline void modColor(uint8_t * const color, const int mod);
inline void addColor(uint8_t * const color, const uint8_t * const add);
// Split them up so setPixel won't be one hell of a mess
void setSnow(const size_t x, const size_t y, const uint8_t * const color);
void setTorch(const size_t x, const size_t y, const uint8_t * const color);
void setFlower(const size_t x, const size_t y, const uint8_t * const color);
void setRedwire(const size_t x, const size_t y, const uint8_t * const color);
void setFire(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark);
void setGrass(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark, const int sub);
void setFence(const size_t x, const size_t y, const uint8_t * const color);
void setStep(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark);
void setUpStep(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark);
# define setRailroad setSnowBA
// Then make duplicate copies so it is one hell of a mess
// ..but hey, its for speeeeeeeeed!
void setSnowBA(const size_t x, const size_t y, const uint8_t * const color);
void setTorchBA(const size_t x, const size_t y, const uint8_t * const color);
void setFlowerBA(const size_t x, const size_t y, const uint8_t * const color);
void setGrassBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark, const int sub);
void setStepBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark);
void setUpStepBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark);
}
void createImageBuffer(const size_t width, const size_t height, const bool splitUp)
{
gPngLocalWidth = gPngWidth = (int)width;
gPngLocalHeight = gPngHeight = (int)height;
gPngLocalLineWidthChans = gPngLineWidthChans = gPngWidth * CHANSPERPIXEL;
gPngSize = gPngLocalSize = (uint64_t)gPngLineWidthChans * (uint64_t)gPngHeight;
printf("Image dimensions are %dx%d, 32bpp, %.2fMiB\n", gPngWidth, gPngHeight, float(gPngSize / float(1024 * 1024)));
if (!splitUp) {
gImageBuffer = new uint8_t[gPngSize];
memset(gImageBuffer, 0, (size_t)gPngSize);
}
}
bool createImage(FILE *fh, const size_t width, const size_t height, const bool splitUp)
{
gPngLocalWidth = gPngWidth = (int)width;
gPngLocalHeight = gPngHeight = (int)height;
gPngLocalLineWidthChans = gPngLineWidthChans = gPngWidth * 4;
gPngSize = gPngLocalSize = (uint64_t)gPngLineWidthChans * (uint64_t)gPngHeight;
printf("Image dimensions are %dx%d, 32bpp, %.2fMiB\n", gPngWidth, gPngHeight, float(gPngSize / float(1024 * 1024)));
if (!splitUp) {
gImageBuffer = new uint8_t[gPngSize];
memset(gImageBuffer, 0, (size_t)gPngSize);
}
fseek64(fh, 0, SEEK_SET);
// Write header
pngPtrMain = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (pngPtrMain == NULL) {
return false;
}
pngInfoPtrMain = png_create_info_struct(pngPtrMain);
if (pngInfoPtrMain == NULL) {
png_destroy_write_struct(&pngPtrMain, NULL);
return false;
}
if (setjmp(png_jmpbuf(pngPtrMain))) { // libpng will issue a longjmp on error, so code flow will end up
png_destroy_write_struct(&pngPtrMain, &pngInfoPtrMain); // here if something goes wrong in the code below
return false;
}
png_init_io(pngPtrMain, fh);
png_set_IHDR(pngPtrMain, pngInfoPtrMain, (uint32_t)width, (uint32_t)height,
8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_text title_text;
title_text.compression = PNG_TEXT_COMPRESSION_NONE;
title_text.key = (png_charp)"Software";
title_text.text = (png_charp)"mcmap";
png_set_text(pngPtrMain, pngInfoPtrMain, &title_text, 1);
png_write_info(pngPtrMain, pngInfoPtrMain);
if (!splitUp) {
pngPtrCurrent = pngPtrMain;
}
return true;
}
bool saveImage()
{
if (g_TilePath == NULL) {
// Normal single-file output
if (setjmp(png_jmpbuf(pngPtrMain))) { // libpng will issue a longjmp on error, so code flow will end up
png_destroy_write_struct(&pngPtrMain, &pngInfoPtrMain); // here if something goes wrong in the code below
return false;
}
uint8_t *srcLine = gImageBuffer;
printf("Writing to file...\n");
for (int y = 0; y < gPngHeight; ++y) {
if (y % 25 == 0) {
printProgress(size_t(y), size_t(gPngHeight));
}
png_write_row(pngPtrMain, (png_bytep)srcLine);
srcLine += gPngLineWidthChans;
}
printProgress(10, 10);
png_write_end(pngPtrMain, NULL);
png_destroy_write_struct(&pngPtrMain, &pngInfoPtrMain);
//
} else {
// Tiled output, suitable for google maps
printf("Writing to files...\n");
size_t tmpLen = strlen(g_TilePath) + 40;
char *tmpString = new char[tmpLen];
// Prepare a temporary buffer to copy the current line to, since we need the width to be a multiple of 4096
// and adjusting the whole image to that would be a waste of memory
const size_t tempWidth = ((gPngWidth - 5) / 4096 + 1) * 4096;
const size_t tempWidthChans = tempWidth * CHANSPERPIXEL;
#ifdef _DEBUG
printf("Temp width: %d, original width: %d\n", (int)tempWidthChans, (int)gPngLineWidthChans);
#endif
uint8_t *tempLine = new uint8_t[tempWidthChans];
memset(tempLine, 0, tempWidth * BYTESPERPIXEL);
// Source pointer
uint8_t *srcLine = gImageBuffer;
// Prepare an array of png structs that will output simultaneously to the various tiles
size_t sizeOffset[7], last = 0;
for (size_t i = 0; i < 7; ++i) {
sizeOffset[i] = last;
last += ((tempWidth - 1) / pow(2, 12 - i)) + 1;
}
ImageTile *tile = new ImageTile[sizeOffset[6]];
memset(tile, 0, sizeOffset[6] * sizeof(ImageTile));
for (int y = 0; y < gPngHeight; ++y) {
if (y % 25 == 0) {
printProgress(size_t(y), size_t(gPngHeight));
}
memcpy(tempLine, srcLine, gPngLineWidthChans);
srcLine += gPngLineWidthChans;
// Handle all png files
if (y % 128 == 0) {
size_t start;
if (y % 4096 == 0) start = 0;
else if (y % 2048 == 0) start = 1;
else if (y % 1024 == 0) start = 2;
else if (y % 512 == 0) start = 3;
else if (y % 256 == 0) start = 4;
else start = 5;
for (size_t tileSize = start; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
ImageTile &t = tile[tileIndex];
if (t.fileHandle != NULL) { // Unload/close first
//printf("Calling end with ptr == %p, y == %d, start == %d, tileSize == %d, tileIndex == %d, to == %d, numpng == %d\n",
//t.pngPtr, y, (int)start, (int)tileSize, (int)tileIndex, (int)sizeOffset[tileSize+1], (int)numpng);
png_write_end(t.pngPtr, NULL);
png_destroy_write_struct(&(t.pngPtr), &(t.pngInfo));
fclose(t.fileHandle);
t.fileHandle = NULL;
}
if (tileWidth * (tileIndex - sizeOffset[tileSize]) < size_t(gPngWidth)) {
// Open new tile file for a while
snprintf(tmpString, tmpLen, "%s/x%dy%dz%d.png", g_TilePath,
int(tileIndex - sizeOffset[tileSize]), int((y / pow(2, 12 - tileSize))), int(tileSize));
#ifdef _DEBUG
printf("Starting tile %s of size %d...\n", tmpString, (int)pow(2, 12 - tileSize));
#endif
t.fileHandle = fopen(tmpString, "wb");
if (t.fileHandle == NULL) {
printf("Error opening file!\n");
return false;
}
t.pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (t.pngPtr == NULL) {
printf("Error creating png write struct!\n");
return false;
}
if (setjmp(png_jmpbuf(t.pngPtr))) {
return false;
}
t.pngInfo = png_create_info_struct(t.pngPtr);
if (t.pngInfo == NULL) {
printf("Error creating png info struct!\n");
png_destroy_write_struct(&(t.pngPtr), NULL);
return false;
}
png_init_io(t.pngPtr, t.fileHandle);
png_set_IHDR(t.pngPtr, t.pngInfo,
uint32_t(pow(2, 12 - tileSize)), uint32_t(pow(2, 12 - tileSize)),
8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(t.pngPtr, t.pngInfo);
}
}
}
} // done preparing tiles
// Write data to all current tiles
for (size_t tileSize = 0; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
if (tile[tileIndex].fileHandle == NULL) continue;
png_write_row(tile[tileIndex].pngPtr, png_bytep(tempLine + tileWidth * (tileIndex - sizeOffset[tileSize]) * CHANSPERPIXEL));
}
} // done writing line
} // done with whole image
// Now the last set of tiles is not finished, so do that manually
memset(tempLine, 0, tempWidth * BYTESPERPIXEL);
for (size_t tileSize = 0; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
if (tile[tileIndex].fileHandle == NULL) continue;
const int imgEnd = (((gPngHeight - 1) / tileWidth) + 1) * tileWidth;
for (int i = gPngHeight; i < imgEnd; ++i) {
png_write_row(tile[tileIndex].pngPtr, png_bytep(tempLine));
}
png_write_end(tile[tileIndex].pngPtr, NULL);
png_destroy_write_struct(&(tile[tileIndex].pngPtr), &(tile[tileIndex].pngInfo));
fclose(tile[tileIndex].fileHandle);
}
}
printProgress(10, 10);
}
return true;
}
/**
* @return 0 = OK, -1 = Error, 1 = Zero/Negative size
*/
int loadImagePart(const int startx, const int starty, const int width, const int height)
{
// These are set to NULL in saveImahePartPng to make sure the two functions are called in turn
if (pngPtrCurrent != NULL || gPngPartialFileHandle != NULL) {
printf("Something wrong with disk caching.\n");
return -1;
}
// In case the image needs to be cropped the offsets will be negative
gOffsetX = MIN(startx, 0);
gOffsetY = MIN(starty, 0);
gPngLocalWidth = width;
gPngLocalHeight = height;
int localX = startx;
int localY = starty;
// Also modify gPngLocalWidth and gPngLocalHeight in these cases
if (localX < 0) {
gPngLocalWidth += localX;
localX = 0;
}
if (localY < 0) {
gPngLocalHeight += localY;
localY = 0;
}
if (localX + gPngLocalWidth > gPngWidth) {
gPngLocalWidth = gPngWidth - localX;
}
if (localY + gPngLocalHeight > gPngHeight) {
gPngLocalHeight = gPngHeight - localY;
}
if (gPngLocalWidth < 1 || gPngLocalHeight < 1) return 1;
char name[200];
snprintf(name, 200, "cache/%d.%d.%d.%d.%d.png", localX, localY, gPngLocalWidth, gPngLocalHeight, (int)time(NULL));
ImagePart *img = new ImagePart(name, localX, localY, gPngLocalWidth, gPngLocalHeight);
partialImages.push_back(img);
// alloc mem for image and open tempfile
gPngLocalLineWidthChans = gPngLocalWidth * CHANSPERPIXEL;
uint64_t size = (uint64_t)gPngLocalLineWidthChans * (uint64_t)gPngLocalHeight;
printf("Creating temporary image: %dx%d, 32bpp, %.2fMiB\n", gPngLocalWidth, gPngLocalHeight, float(size / float(1024 * 1024)));
if (gImageBuffer == NULL) {
gImageBuffer = new uint8_t[size];
gPngLocalSize = size;
} else if (size > gPngLocalSize) {
delete[] gImageBuffer;
gImageBuffer = new uint8_t[size];
gPngLocalSize = size;
}
memset(gImageBuffer, 0, (size_t)size);
// Create temp image
// This is done here to detect early if the target is not writable
#ifdef _WIN32
mkdir("cache");
#else
mkdir("cache", 0755);
#endif
gPngPartialFileHandle = fopen(name, "wb");
if (gPngPartialFileHandle == NULL) {
printf("Could not create temporary image at %s; check permissions in current dir.\n", name);
return -1;
}
return 0;
}
bool saveImagePart()
{
if (gPngPartialFileHandle == NULL || pngPtrCurrent != NULL) {
printf("saveImagePart() called in bad state.\n");
return false;
}
// Write header
png_infop info_ptr = NULL;
pngPtrCurrent = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (pngPtrCurrent == NULL) {
return false;
}
info_ptr = png_create_info_struct(pngPtrCurrent);
if (info_ptr == NULL) {
png_destroy_write_struct(&pngPtrCurrent, NULL);
return false;
}
if (setjmp(png_jmpbuf(pngPtrCurrent))) { // libpng will issue a longjmp on error, so code flow will end up
png_destroy_write_struct(&pngPtrCurrent, &info_ptr); // here if something goes wrong in the code below
return false;
}
png_init_io(pngPtrCurrent, gPngPartialFileHandle);
png_set_compression_level(pngPtrCurrent, Z_BEST_SPEED);
png_set_IHDR(pngPtrCurrent, info_ptr, (uint32_t)gPngLocalWidth, (uint32_t)gPngLocalHeight,
8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(pngPtrCurrent, info_ptr);
//
uint8_t *line = gImageBuffer;
for (int y = 0; y < gPngLocalHeight; ++y) {
png_write_row(pngPtrCurrent, (png_bytep)line);
line += gPngLocalLineWidthChans;
}
png_write_end(pngPtrCurrent, NULL);
png_destroy_write_struct(&pngPtrCurrent, &info_ptr);
pngPtrCurrent = NULL;
fclose(gPngPartialFileHandle);
gPngPartialFileHandle = NULL;
return true;
}
bool discardImagePart()
{
if (gPngPartialFileHandle == NULL || pngPtrCurrent != NULL) {
printf("discardImagePart() called in bad state.\n");
return false;
}
fclose(gPngPartialFileHandle);
gPngPartialFileHandle = NULL;
ImagePart *img = partialImages.back();
remove(img->filename);
delete img;
partialImages.pop_back();
return true;
}
bool composeFinalImage()
{
char *tmpString = NULL;
size_t tmpLen = 0;
if (g_TilePath == NULL) {
printf("Composing final png file...\n");
if (setjmp(png_jmpbuf(pngPtrMain))) {
png_destroy_write_struct(&pngPtrMain, NULL);
return false;
}
} else {
// Tiled output, suitable for google maps
printf("Composing final png files...\n");
tmpLen = strlen(g_TilePath) + 40;
tmpString = new char[tmpLen];
// Prepare a temporary buffer to copy the current line to, since we need the width to be a multiple of 4096
// and adjusting the whole image to that would be a waste of memory
}
const size_t tempWidth = (g_TilePath == NULL ? gPngLineWidthChans : ((gPngWidth - 5) / 4096 + 1) * 4096);
const size_t tempWidthChans = tempWidth * CHANSPERPIXEL;
uint8_t *lineWrite = new uint8_t[tempWidthChans];
uint8_t *lineRead = new uint8_t[gPngLineWidthChans];
// Prepare an array of png structs that will output simultaneously to the various tiles
size_t sizeOffset[7], last = 0;
ImageTile *tile = NULL;
if (g_TilePath != NULL) {
for (size_t i = 0; i < 7; ++i) {
sizeOffset[i] = last;
last += ((tempWidth - 1) / pow(2, 12 - i)) + 1;
}
tile = new ImageTile[sizeOffset[6]];
memset(tile, 0, sizeOffset[6] * sizeof(ImageTile));
}
for (int y = 0; y < gPngHeight; ++y) {
if (y % 100 == 0) {
printProgress(size_t(y), size_t(gPngHeight));
}
// paint each image on this one
memset(lineWrite, 0, tempWidthChans);
// the partial images are kept in this list. they're already in the correct order in which they have to me merged and blended
for (imageList::iterator it = partialImages.begin(); it != partialImages.end(); it++) {
ImagePart *img = *it;
// do we have to open this image?
if (img->y == y && img->pngPtr == NULL) {
img->pngFileHandle = fopen(img->filename, "rb");
if (img->pngFileHandle == NULL) {
printf("Error opening temporary image %s\n", img->filename);
return false;
}
img->pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (img->pngPtr == NULL) {
printf("Error creating read struct for temporary image %s\n", img->filename);
return false; // Not really cleaning up here, but program will terminate anyways, so why bother
}
img->pngInfo = png_create_info_struct(img->pngPtr);
if (img->pngInfo == NULL || setjmp(png_jmpbuf(img->pngPtr))) {
printf("Error reading data from temporary image %s\n", img->filename);
return false; // Same here
}
png_init_io(img->pngPtr, img->pngFileHandle);
png_read_info(img->pngPtr, img->pngInfo);
// Check if image dimensions match what is expected
int type, interlace, comp, filter, bitDepth;
png_uint_32 width, height;
png_uint_32 ret = png_get_IHDR(img->pngPtr, img->pngInfo, &width, &height, &bitDepth, &type, &interlace, &comp, &filter);
if (ret == 0 || width != (png_uint_32)img->width || height != (png_uint_32)img->height) {
printf("Temp image %s has wrong dimensions; expected %dx%d, got %dx%d\n", img->filename, img->width, img->height, (int)width, (int)height);
return false;
}
}
// Here, the image is either open and ready for reading another line, or its not open when it doesn't have to be copied/blended here, or is already finished
if (img->pngPtr == NULL) {
continue; // Not your turn, image!
}
// Read next line from current image chunk
png_read_row(img->pngPtr, (png_bytep)lineRead, NULL);
// Now this puts all the pixels in the right spot of the current line of the final image
const uint8_t *end = lineWrite + (img->x + img->width) * CHANSPERPIXEL;
uint8_t *read = lineRead;
for (uint8_t *write = lineWrite + (img->x * CHANSPERPIXEL); write < end; write += CHANSPERPIXEL) {
blend(write, read);
read += CHANSPERPIXEL;
}
// Now check if we're done with this image chunk
if (--(img->height) == 0) { // if so, close and discard
png_destroy_read_struct(&(img->pngPtr), &(img->pngInfo), NULL);
fclose(img->pngFileHandle);
img->pngFileHandle = NULL;
img->pngPtr = NULL;
remove(img->filename);
}
}
// Done composing this line, write to final image
if (g_TilePath == NULL) {
// Single file
png_write_row(pngPtrMain, (png_bytep)lineWrite);
} else {
// Tiled output
// Handle all png files
if (y % 128 == 0) {
size_t start;
if (y % 4096 == 0) start = 0;
else if (y % 2048 == 0) start = 1;
else if (y % 1024 == 0) start = 2;
else if (y % 512 == 0) start = 3;
else if (y % 256 == 0) start = 4;
else start = 5;
for (size_t tileSize = start; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
ImageTile &t = tile[tileIndex];
if (t.fileHandle != NULL) { // Unload/close first
//printf("Calling end with ptr == %p, y == %d, start == %d, tileSize == %d, tileIndex == %d, to == %d, numpng == %d\n",
//t.pngPtr, y, (int)start, (int)tileSize, (int)tileIndex, (int)sizeOffset[tileSize+1], (int)numpng);
png_write_end(t.pngPtr, NULL);
png_destroy_write_struct(&(t.pngPtr), &(t.pngInfo));
fclose(t.fileHandle);
t.fileHandle = NULL;
}
if (tileWidth * (tileIndex - sizeOffset[tileSize]) < size_t(gPngWidth)) {
// Open new tile file for a while
snprintf(tmpString, tmpLen, "%s/x%dy%dz%d.png", g_TilePath,
int(tileIndex - sizeOffset[tileSize]), int((y / pow(2, 12 - tileSize))), int(tileSize));
#ifdef _DEBUG
printf("Starting tile %s of size %d...\n", tmpString, (int)pow(2, 12 - tileSize));
#endif
t.fileHandle = fopen(tmpString, "wb");
if (t.fileHandle == NULL) {
printf("Error opening file!\n");
return false;
}
t.pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (t.pngPtr == NULL) {
printf("Error creating png write struct!\n");
return false;
}
if (setjmp(png_jmpbuf(t.pngPtr))) {
return false;
}
t.pngInfo = png_create_info_struct(t.pngPtr);
if (t.pngInfo == NULL) {
printf("Error creating png info struct!\n");
png_destroy_write_struct(&(t.pngPtr), NULL);
return false;
}
png_init_io(t.pngPtr, t.fileHandle);
png_set_IHDR(t.pngPtr, t.pngInfo,
uint32_t(pow(2, 12 - tileSize)), uint32_t(pow(2, 12 - tileSize)),
8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(t.pngPtr, t.pngInfo);
}
}
}
} // done preparing tiles
// Write data to all current tiles
for (size_t tileSize = 0; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
if (tile[tileIndex].fileHandle == NULL) continue;
png_write_row(tile[tileIndex].pngPtr, png_bytep(lineWrite + tileWidth * (tileIndex - sizeOffset[tileSize]) * CHANSPERPIXEL));
}
} // done writing line
//
}
// Y-Loop
}
if (g_TilePath == NULL) {
png_write_end(pngPtrMain, NULL);
png_destroy_write_struct(&pngPtrMain, &pngInfoPtrMain);
} else {
// Finish all current tiles
memset(lineWrite, 0, tempWidth * BYTESPERPIXEL);
for (size_t tileSize = 0; tileSize < 6; ++tileSize) {
const size_t tileWidth = pow(2, 12 - tileSize);
for (size_t tileIndex = sizeOffset[tileSize]; tileIndex < sizeOffset[tileSize+1]; ++tileIndex) {
if (tile[tileIndex].fileHandle == NULL) continue;
const int imgEnd = (((gPngHeight - 1) / tileWidth) + 1) * tileWidth;
for (int i = gPngHeight; i < imgEnd; ++i) {
png_write_row(tile[tileIndex].pngPtr, png_bytep(lineWrite));
}
png_write_end(tile[tileIndex].pngPtr, NULL);
png_destroy_write_struct(&(tile[tileIndex].pngPtr), &(tile[tileIndex].pngInfo));
fclose(tile[tileIndex].fileHandle);
}
}
}
printProgress(10, 10);
delete[] lineWrite;
delete[] lineRead;
return true;
}
uint64_t calcImageSize(const int mapChunksX, const int mapChunksZ, const size_t mapHeight, int &pixelsX, int &pixelsY, const bool tight)
{
pixelsX = (mapChunksX * CHUNKSIZE_X + mapChunksZ * CHUNKSIZE_Z) * 2 + (tight ? 3 : 10);
pixelsY = (mapChunksX * CHUNKSIZE_X + mapChunksZ * CHUNKSIZE_Z + int(mapHeight) * g_OffsetY) + (tight ? 3 : 10);
return uint64_t(pixelsX) * BYTESPERPIXEL * uint64_t(pixelsY);
}
void setPixel(const size_t x, const size_t y, const uint8_t color, const float fsub)
{
// Sets pixels around x,y where A is the anchor
// T = given color, D = darker, L = lighter
// A T T T
// D D L L
// D D L L
// D L
// First determine how much the color has to be lightened up or darkened
int sub = int(fsub * (float(colors[color][BRIGHTNESS]) / 323.0f + .21f)); // The brighter the color, the stronger the impact
uint8_t L[CHANSPERPIXEL], D[CHANSPERPIXEL], c[CHANSPERPIXEL];
// Now make a local copy of the color that we can modify just for this one block
memcpy(c, colors[color], BYTESPERPIXEL);
modColor(c, sub);
if (g_BlendAll) {
// Then check the block type, as some types will be drawn differently
if (color == SNOW || color == TRAPDOOR
|| color == 141 || color == 142 || color == 158 || color == 149
|| color == 131 || color == 132 || color == 150 || color == 147 || color == 148 || color == 68 || color == 69 || color == 70
|| color == 72 || color == 77 || color == 143 || color == 36) { //three lines of carpets ID's I can't do this other way
setSnowBA(x, y, c);
return;
}
if (color == TORCH || color == REDTORCH_ON || color == REDTORCH_OFF) {
setTorchBA(x, y, c);
return;
}
if (color == FLOWERR || color == FLOWERY || color == MUSHROOMB || color == MUSHROOMR || color == MELON_STEM || color == PUMPKIN_STEM || color == SHRUB || color == COBWEB || color == LILYPAD || color == NETHER_WART
|| color == 175 || color == BLUE_ORCHID || color == ALLIUM || color == AZURE_BLUET || color == RED_TULIP || color == ORANGE_TULIP || color == WHITE_TULIP || color == PINK_TULIP || color == OXEYE_DAISY || color == SUNFLOWER || color == LILAC || color == PEONY ) {
setFlowerBA(x, y, c);
return;
}
if (color == FENCE || color == FENCE_GATE || color == VINES || color == IRON_BARS || color == NETHER_BRICK_FENCE
|| color == 139) {
setFence(x, y, c);
return;
}
if (color == REDWIRE || color == TRIPWIRE) {
setRedwire(x, y, c);
return;
}
if (color == RAILROAD || color == POW_RAILROAD || color == DET_RAILROAD) {
setRailroad(x, y, c);
return;
}
// All the above blocks didn't need the shaded down versions of the color, so we only calc them here
// They are for the sides of blocks
memcpy(L, c, BYTESPERPIXEL);
memcpy(D, c, BYTESPERPIXEL);
modColor(L, -17);
modColor(D, -27);
// A few more blocks with special handling... Those need the two colors we just mixed
if (color == GRASS) {
setGrassBA(x, y, c, L, D, sub);
return;
}
if (color == FIRE || color == TALL_GRASS || color == COCOA_PLANT) {
setFire(x, y, c, L, D);
return;
}
if (color == STEP || color == CAKE || color == BED || color == SANDSTEP || color == WOODSTEP || color == COBBLESTEP || color == BRICKSTEP || color == STONEBRICKSTEP || color == PINESTEP || color == BIRCHSTEP || color == JUNGLESTEP
|| color == 151) {
setStepBA(x, y, c, L, D);
return;
}
if (color == UP_STEP || color == UP_SANDSTEP || color == UP_WOODSTEP || color == UP_COBBLESTEP || color == UP_BRICKSTEP || color == UP_STONEBRICKSTEP || color == UP_WOODSTEP2 || color == UP_PINESTEP || color == UP_BIRCHSTEP || color == UP_JUNGLESTEP) {
setUpStepBA(x, y, c, L, D);
return;
}
} else {
// Then check the block type, as some types will be drawn differently
if (color == SNOW || color == TRAPDOOR
|| color == 141 || color == 142 || color == 158 || color == 149
|| color == 131 || color == 132 || color == 150 || color == 147 || color == 148 || color == 68 || color == 69 || color == 70
|| color == 72 || color == 77 || color == 143 || color == 36) { //three lines of carpets ID's I can't do this other way
setSnow(x, y, c);
return;
}
if (color == TORCH || color == REDTORCH_ON || color == REDTORCH_OFF) {
setTorch(x, y, c);
return;
}
if (color == FLOWERR || color == FLOWERY || color == MUSHROOMB || color == MUSHROOMR || color == MELON_STEM || color == PUMPKIN_STEM || color == SHRUB || color == COBWEB || color == LILYPAD || color == NETHER_WART
|| color == 175 || color == BLUE_ORCHID || color == ALLIUM || color == AZURE_BLUET || color == RED_TULIP || color == ORANGE_TULIP || color == WHITE_TULIP || color == PINK_TULIP || color == OXEYE_DAISY || color == SUNFLOWER || color == LILAC || color == PEONY ) {
setFlower(x, y, c);
return;
}
if (color == FENCE || color == FENCE_GATE || color == VINES || color == IRON_BARS || color == NETHER_BRICK_FENCE) {
setFence(x, y, c);
return;
}
if (color == REDWIRE || color == TRIPWIRE) {
setRedwire(x, y, c);
return;
}
if (color == RAILROAD || color == POW_RAILROAD || color == DET_RAILROAD) {
setRailroad(x, y, c);
return;
}
// All the above blocks didn't need the shaded down versions of the color, so we only calc them here
// They are for the sides of blocks
memcpy(L, c, BYTESPERPIXEL);
memcpy(D, c, BYTESPERPIXEL);
modColor(L, -17);
modColor(D, -27);
// A few more blocks with special handling... Those need the two colors we just mixed
if (color == GRASS) {
setGrass(x, y, c, L, D, sub);
return;
}
if (color == FIRE || color == TALL_GRASS || color == COCOA_PLANT) {
setFire(x, y, c, L, D);
return;
}
if (color == STEP || color == CAKE || color == BED || color == SANDSTEP || color == WOODSTEP || color == COBBLESTEP || color == BRICKSTEP || color == STONEBRICKSTEP || color == PINESTEP || color == BIRCHSTEP || color == JUNGLESTEP
|| color == 151) {
setStep(x, y, c, L, D);
return;
}
if (color == UP_STEP || color == UP_SANDSTEP || color == UP_WOODSTEP || color == UP_COBBLESTEP || color == UP_BRICKSTEP || color == UP_STONEBRICKSTEP || color == UP_WOODSTEP2 || color == UP_PINESTEP || color == UP_BIRCHSTEP || color == UP_JUNGLESTEP) {
setUpStep(x, y, c, L, D);
return;
}
}
// In case the user wants noise, calc the strength now, depending on the desired intensity and the block's brightness
int noise = 0;
if (g_Noise && colors[color][NOISE]) {
noise = int(float(g_Noise * colors[color][NOISE]) * (float(GETBRIGHTNESS(c) + 10) / 2650.0f));
}
// Ordinary blocks are all rendered the same way
if (c[PALPHA] == 255) { // Fully opaque - faster
// Top row
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, c, BYTESPERPIXEL);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise);
}
}
// Second row
pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, (i < 2 ? D : L), BYTESPERPIXEL);
// The weird check here is to get the pattern right, as the noise should be stronger
// every other row, but take into account the isometric perspective
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 1 : 2));
}
}
// Third row
pos = &PIXEL(x, y+2);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, (i < 2 ? D : L), BYTESPERPIXEL);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 2 : 1));
}
}
// Last row
pos = &PIXEL(x, y+3);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, (i < 2 ? D : L), BYTESPERPIXEL);
// The weird check here is to get the pattern right, as the noise should be stronger
// every other row, but take into account the isometric perspective
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 1 : 2));
}
}
} else { // Not opaque, use slower blending code
// Top row
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, c);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise);
}
}
// Second row
pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, (i < 2 ? D : L));
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 1 : 2));
}
}
// Third row
pos = &PIXEL(x, y+2);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, (i < 2 ? D : L));
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 2 : 1));
}
}
// Last row
pos = &PIXEL(x, y+3);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, (i < 2 ? D : L));
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 1 : 2));
}
}
}
// The above two branches are almost the same, maybe one could just create a function pointer and...
}
void blendPixel(const size_t x, const size_t y, const uint8_t color, const float fsub)
{
// This one is used for cave overlay
// Sets pixels around x,y where A is the anchor
// T = given color, D = darker, L = lighter
// A T T T
// D D L L
// D D L L
// D L
uint8_t L[CHANSPERPIXEL], D[CHANSPERPIXEL], c[CHANSPERPIXEL];
// Now make a local copy of the color that we can modify just for this one block
memcpy(c, colors[color], BYTESPERPIXEL);
c[PALPHA] = clamp(int(float(c[PALPHA]) * fsub)); // The brighter the color, the stronger the impact
// They are for the sides of blocks
memcpy(L, c, BYTESPERPIXEL);
memcpy(D, c, BYTESPERPIXEL);
modColor(L, -17);
modColor(D, -27);
// In case the user wants noise, calc the strength now, depending on the desired intensity and the block's brightness
int noise = 0;
if (g_Noise && colors[color][NOISE]) {
noise = int(float(g_Noise * colors[color][NOISE]) * (float(GETBRIGHTNESS(c) + 10) / 2650.0f));
}
// Top row
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, c);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise);
}
}
// Second row
pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, (i < 2 ? D : L));
if (noise) {
modColor(pos, rand() % (noise * 2) - noise * (i == 0 || i == 3 ? 1 : 2));
}
}
}
namespace
{
inline void blend(uint8_t * const destination, const uint8_t * const source)
{
if (destination[PALPHA] == 0 || source[PALPHA] == 255) {
memcpy(destination, source, BYTESPERPIXEL);
return;
}
# define BLEND(ca,aa,cb) uint8_t(((size_t(ca) * size_t(aa)) + (size_t(255 - aa) * size_t(cb))) / 255)
destination[0] = BLEND(source[0], source[PALPHA], destination[0]);
destination[1] = BLEND(source[1], source[PALPHA], destination[1]);
destination[2] = BLEND(source[2], source[PALPHA], destination[2]);
destination[PALPHA] += (size_t(source[PALPHA]) * size_t(255 - destination[PALPHA])) / 255;
}
inline void modColor(uint8_t * const color, const int mod)
{
color[0] = clamp(color[0] + mod);
color[1] = clamp(color[1] + mod);
color[2] = clamp(color[2] + mod);
}
inline void addColor(uint8_t * const color, const uint8_t * const add)
{
const float v2 = (float(add[PALPHA]) / 255.0f);
const float v1 = (1.0f - (v2 * .2f));
color[0] = clamp(uint16_t(float(color[0]) * v1 + float(add[0]) * v2));
color[1] = clamp(uint16_t(float(color[1]) * v1 + float(add[1]) * v2));
color[2] = clamp(uint16_t(float(color[2]) * v1 + float(add[2]) * v2));
}
void setSnow(const size_t x, const size_t y, const uint8_t * const color)
{
// Top row (second row)
uint8_t *pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
}
}
void setTorch(const size_t x, const size_t y, const uint8_t * const color)
{
// Maybe the orientation should be considered when drawing, but it probably isn't worth the efford
uint8_t *pos = &PIXEL(x+2, y+1);
memcpy(pos, color, BYTESPERPIXEL);
pos = &PIXEL(x+2, y+2);
memcpy(pos, color, BYTESPERPIXEL);
}
void setFlower(const size_t x, const size_t y, const uint8_t * const color)
{
uint8_t *pos = &PIXEL(x, y+1);
memcpy(pos+(CHANSPERPIXEL), color, BYTESPERPIXEL);
memcpy(pos+(CHANSPERPIXEL*3), color, BYTESPERPIXEL);
pos = &PIXEL(x+2, y+2);
memcpy(pos, color, BYTESPERPIXEL);
pos = &PIXEL(x+1, y+3);
memcpy(pos, color, BYTESPERPIXEL);
}
void setFire(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark)
{
// This basically just leaves out a few pixels
// Top row
uint8_t *pos = &PIXEL(x, y);
blend(pos, light);
blend(pos + CHANSPERPIXEL*2, dark);
// Second and third row
for (size_t i = 1; i < 3; ++i) {
pos = &PIXEL(x, y+i);
blend(pos, dark);
blend(pos+(CHANSPERPIXEL*i), color);
blend(pos+(CHANSPERPIXEL*3), light);
}
// Last row
pos = &PIXEL(x, y+3);
blend(pos+(CHANSPERPIXEL*2), light);
}
void setGrass(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark, const int sub)
{
// this will make grass look like dirt from the side
uint8_t L[CHANSPERPIXEL], D[CHANSPERPIXEL];
memcpy(L, colors[DIRT], BYTESPERPIXEL);
memcpy(D, colors[DIRT], BYTESPERPIXEL);
modColor(L, sub - 15);
modColor(D, sub - 25);
// consider noise
int noise = 0;
if (g_Noise && colors[GRASS][NOISE]) {
noise = int(float(g_Noise * colors[GRASS][NOISE]) * (float(GETBRIGHTNESS(color) + 10) / 2650.0f));
}
// Top row
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise);
}
}
// Second row
pos = &PIXEL(x, y+1);
memcpy(pos, dark, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL, dark, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*2, light, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*3, light, BYTESPERPIXEL);
// Third row
pos = &PIXEL(x, y+2);
memcpy(pos, D, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL, D, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*2, L, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*3, L, BYTESPERPIXEL);
// Last row
pos = &PIXEL(x, y+3);
memcpy(pos, D, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL, D, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*2, L, BYTESPERPIXEL);
memcpy(pos+CHANSPERPIXEL*3, L, BYTESPERPIXEL);
}
void setFence(const size_t x, const size_t y, const uint8_t * const color)
{
// First row
uint8_t *pos = &PIXEL(x, y);
blend(pos+CHANSPERPIXEL, color);
blend(pos+CHANSPERPIXEL*2, color);
// Second row
pos = &PIXEL(x+1, y+1);
blend(pos, color);
// Third row
pos = &PIXEL(x, y+2);
blend(pos+CHANSPERPIXEL, color);
blend(pos+CHANSPERPIXEL*2, color);
}
void setStep(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark)
{
uint8_t *pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
}
pos = &PIXEL(x, y+2);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
}
}
void setUpStep(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark)
{
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
}
pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
memcpy(pos, color, BYTESPERPIXEL);
}
}
void setRedwire(const size_t x, const size_t y, const uint8_t * const color)
{
uint8_t *pos = &PIXEL(x+1, y+2);
blend(pos, color);
blend(pos+CHANSPERPIXEL, color);
}
// The g_BlendAll versions of the block set functions
//
void setSnowBA(const size_t x, const size_t y, const uint8_t * const color)
{
// Top row (second row)
uint8_t *pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
}
}
void setTorchBA(const size_t x, const size_t y, const uint8_t * const color)
{
// Maybe the orientation should be considered when drawing, but it probably isn't worth the effort
uint8_t *pos = &PIXEL(x+2, y+1);
blend(pos, color);
pos = &PIXEL(x+2, y+2);
blend(pos, color);
}
void setFlowerBA(const size_t x, const size_t y, const uint8_t * const color)
{
uint8_t *pos = &PIXEL(x, y+1);
blend(pos+CHANSPERPIXEL, color);
blend(pos+CHANSPERPIXEL*3, color);
pos = &PIXEL(x+2, y+2);
blend(pos, color);
pos = &PIXEL(x+1, y+3);
blend(pos, color);
}
void setGrassBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark, const int sub)
{
// this will make grass look like dirt from the side
uint8_t L[CHANSPERPIXEL], D[CHANSPERPIXEL];
memcpy(L, colors[DIRT], BYTESPERPIXEL);
memcpy(D, colors[DIRT], BYTESPERPIXEL);
modColor(L, sub - 15);
modColor(D, sub - 25);
// consider noise
int noise = 0;
if (g_Noise && colors[GRASS][NOISE]) {
noise = int(float(g_Noise * colors[GRASS][NOISE]) * (float(GETBRIGHTNESS(color) + 10) / 2650.0f));
}
// Top row
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 4; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
if (noise) {
modColor(pos, rand() % (noise * 2) - noise);
}
}
// Second row
pos = &PIXEL(x, y+1);
blend(pos, dark);
blend(pos+CHANSPERPIXEL, dark);
blend(pos+CHANSPERPIXEL*2, light);
blend(pos+CHANSPERPIXEL*3, light);
// Third row
pos = &PIXEL(x, y+2);
blend(pos, D);
blend(pos+CHANSPERPIXEL, D);
blend(pos+CHANSPERPIXEL*2, L);
blend(pos+CHANSPERPIXEL*3, L);
// Last row
pos = &PIXEL(x, y+3);
blend(pos, D);
blend(pos+CHANSPERPIXEL, D);
blend(pos+CHANSPERPIXEL*2, L);
blend(pos+CHANSPERPIXEL*3, L);
}
void setStepBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark)
{
uint8_t *pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 3; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
}
pos = &PIXEL(x, y+2);
for (size_t i = 0; i < 10; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
}
}
void setUpStepBA(const size_t x, const size_t y, const uint8_t * const color, const uint8_t * const light, const uint8_t * const dark)
{
uint8_t *pos = &PIXEL(x, y);
for (size_t i = 0; i < 3; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
}
pos = &PIXEL(x, y+1);
for (size_t i = 0; i < 10; ++i, pos += CHANSPERPIXEL) {
blend(pos, color);
}
}
}
| 37.207231 | 265 | 0.651151 | WRIM |
cac1e0aa4e0f2b08d8178a2e80b86d9af37d305e | 580 | hpp | C++ | TemplateRPG/World/places/place.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | 1 | 2015-11-29T04:47:29.000Z | 2015-11-29T04:47:29.000Z | TemplateRPG/World/places/place.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | null | null | null | TemplateRPG/World/places/place.hpp | davideberdin/Text-Turn-based-RPG-Template | 3b1e88b6498b7473b3928e7188157a7d7f1ba844 | [
"MIT"
] | null | null | null | //
// place.hpp
// TemplateRPG
//
// Created by Davide Berdin on 29/11/15.
// Copyright © 2015 Davide Berdin. All rights reserved.
//
#ifndef place_hpp
#define place_hpp
#include <stdio.h>
#include <string>
class Place
{
private:
std::string name = "";
public:
Place(std::string);
Place(const Place&);
~Place();
Place& operator=(const Place&);
friend bool operator!=(const Place&, const Place&);
friend bool operator==(const Place&, const Place&);
// methods
void SetName(std::string);
};
#endif /* place_hpp */ | 16.571429 | 56 | 0.613793 | davideberdin |
cacb1f6a87f50a69d042739b4e23815f7e938dae | 242 | cpp | C++ | workshop 2020/Variables and conditions/rowoftwo/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | workshop 2020/Variables and conditions/rowoftwo/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | workshop 2020/Variables and conditions/rowoftwo/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <deque>
#include <limits>
#define int long long
using namespace std;
signed main() {
int n;
cin >> n;
if(n%2==0){
cout << "L\n";
} else{
cout << "R\n";
}
} | 12.736842 | 22 | 0.520661 | wdjpng |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.