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
34c100713ae8964de2399b354af749dbc1f6ae78
4,315
cpp
C++
core/src/UniFlagStorage.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
core/src/UniFlagStorage.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
core/src/UniFlagStorage.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" #include "mmcore/UniFlagStorage.h" #include "mmcore/UniFlagCalls.h" using namespace megamol; using namespace megamol::core; UniFlagStorage::UniFlagStorage(void) : readFlagsSlot("readFlags", "Provides flag data to clients.") , writeFlagsSlot("writeFlags", "Accepts updated flag data from clients.") , readCPUFlagsSlot("readCPUFlags", "Provides flag data to clients.") , writeCPUFlagsSlot("writeCPUFlags", "Accepts updated flag data from clients.") { this->readFlagsSlot.SetCallback(FlagCallRead_GL::ClassName(), FlagCallRead_GL::FunctionName(FlagCallRead_GL::CallGetData), &UniFlagStorage::readDataCallback); this->readFlagsSlot.SetCallback(FlagCallRead_GL::ClassName(), FlagCallRead_GL::FunctionName(FlagCallRead_GL::CallGetMetaData), &UniFlagStorage::readMetaDataCallback); this->MakeSlotAvailable(&this->readFlagsSlot); this->writeFlagsSlot.SetCallback(FlagCallWrite_GL::ClassName(), FlagCallWrite_GL::FunctionName(FlagCallWrite_GL::CallGetData), &UniFlagStorage::writeDataCallback); this->writeFlagsSlot.SetCallback(FlagCallWrite_GL::ClassName(), FlagCallWrite_GL::FunctionName(FlagCallWrite_GL::CallGetMetaData), &UniFlagStorage::writeMetaDataCallback); this->MakeSlotAvailable(&this->writeFlagsSlot); this->readCPUFlagsSlot.SetCallback(FlagCallRead_CPU::ClassName(), FlagCallRead_CPU::FunctionName(FlagCallRead_CPU::CallGetData), &UniFlagStorage::readCPUDataCallback); this->readCPUFlagsSlot.SetCallback(FlagCallRead_CPU::ClassName(), FlagCallRead_CPU::FunctionName(FlagCallRead_CPU::CallGetMetaData), &UniFlagStorage::readMetaDataCallback); this->MakeSlotAvailable(&this->readCPUFlagsSlot); this->writeCPUFlagsSlot.SetCallback(FlagCallWrite_CPU::ClassName(), FlagCallWrite_CPU::FunctionName(FlagCallWrite_CPU::CallGetData), &UniFlagStorage::writeCPUDataCallback); this->writeCPUFlagsSlot.SetCallback(FlagCallWrite_CPU::ClassName(), FlagCallWrite_CPU::FunctionName(FlagCallWrite_CPU::CallGetMetaData), &UniFlagStorage::writeMetaDataCallback); this->MakeSlotAvailable(&this->writeCPUFlagsSlot); } UniFlagStorage::~UniFlagStorage(void) { this->Release(); }; bool UniFlagStorage::create(void) { this->theData = std::make_shared<FlagCollection_GL>(); const int num = 10; std::vector<uint32_t> temp_data(num, FlagStorage::ENABLED); this->theData->flags = std::make_shared<glowl::BufferObject>(GL_SHADER_STORAGE_BUFFER, temp_data.data(), num, GL_DYNAMIC_DRAW); this->theCPUData = std::make_shared<FlagCollection_CPU>(); this->theCPUData->flags = std::make_shared<FlagStorage::FlagVectorType>(num, FlagStorage::ENABLED); return true; } void UniFlagStorage::release(void) { // intentionally empty } bool UniFlagStorage::readDataCallback(core::Call& caller) { auto fc = dynamic_cast<FlagCallRead_GL*>(&caller); if (fc == nullptr) return false; fc->setData(this->theData, this->version); return true; } bool UniFlagStorage::writeDataCallback(core::Call& caller) { auto fc = dynamic_cast<FlagCallWrite_GL*>(&caller); if (fc == nullptr) return false; if (fc->version() > this->version) { this->theData = fc->getData(); this->version = fc->version(); GL2CPUCopy(); } return true; } bool UniFlagStorage::readCPUDataCallback(core::Call& caller) { auto fc = dynamic_cast<FlagCallRead_CPU*>(&caller); if (fc == nullptr) return false; fc->setData(this->theCPUData, this->version); return true; } bool UniFlagStorage::writeCPUDataCallback(core::Call& caller) { auto fc = dynamic_cast<FlagCallWrite_CPU*>(&caller); if (fc == nullptr) return false; if (fc->version() > this->version) { this->theCPUData = fc->getData(); this->version = fc->version(); CPU2GLCopy(); } return true; } bool UniFlagStorage::readMetaDataCallback(core::Call& caller) { // auto fc = dynamic_cast<FlagCallRead_GL*>(&caller); // if (fc == nullptr) return false; return true; } bool UniFlagStorage::writeMetaDataCallback(core::Call& caller) { // auto fc = dynamic_cast<FlagCallWrite_GL*>(&caller); // if (fc == nullptr) return false; return true; }
36.260504
117
0.716802
azuki-monster
34ccec0fbddb7bead1fba1b27d84b6ca1a3f46ea
1,160
hpp
C++
ufora/core/math/Smallest.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/core/math/Smallest.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/core/math/Smallest.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora 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 "Nullable.hpp" template<class T, class scalar = double> class Smallest { public: void observe(T value, scalar weight) { if (!mWeight || weight < *mWeight) { mWeight = weight; mValue = value; } } Nullable<T> smallest() const { return mValue; } Nullable<scalar> smallestWeight() const { return mWeight; } private: Nullable<T> mValue; Nullable<scalar> mWeight; };
24.680851
77
0.614655
ufora
34d12c5e7cdb2f53819bc022e22d53513e3f7e28
8,725
cc
C++
modules/external_packages/src/alien/kernels/petsc/linear_solver/field_split/PETScPrecConfigFieldSplitService.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
4
2021-12-02T09:06:38.000Z
2022-01-10T14:22:35.000Z
modules/external_packages/src/alien/kernels/petsc/linear_solver/field_split/PETScPrecConfigFieldSplitService.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
null
null
null
modules/external_packages/src/alien/kernels/petsc/linear_solver/field_split/PETScPrecConfigFieldSplitService.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
7
2021-11-23T14:50:58.000Z
2022-03-17T13:23:07.000Z
/* Author : gratienj * Preconditioner created by combining separate preconditioners for individual * fields or groups of fields. See the users manual section "Solving Block Matrices" * for more details in PETSc 3.3 documentation : * http://www.mcs.anl.gov/petsc/petsc-current/docs/manual.pdf */ #include <alien/kernels/petsc/linear_solver/field_split/PETScPrecConfigFieldSplitService.h> #include <ALIEN/axl/PETScPrecConfigFieldSplit_StrongOptions.h> #include <alien/core/utils/Partition.h> #include <arccore/message_passing/IMessagePassingMng.h> #include <map> #include <set> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Alien { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /** Constructeur de la classe */ #ifdef ALIEN_USE_ARCANE PETScPrecConfigFieldSplitService::PETScPrecConfigFieldSplitService( const Arcane::ServiceBuildInfo& sbi) : ArcanePETScPrecConfigFieldSplitObject(sbi) , PETScConfig(sbi.subDomain()->parallelMng()->isParallel()) { m_default_block_tag = "default"; } #endif PETScPrecConfigFieldSplitService::PETScPrecConfigFieldSplitService( Arccore::MessagePassing::IMessagePassingMng* parallel_mng, std::shared_ptr<IOptionsPETScPrecConfigFieldSplit> options) : ArcanePETScPrecConfigFieldSplitObject(options) , PETScConfig(parallel_mng->commSize() > 1) { m_default_block_tag = "default"; } //! Initialisation void PETScPrecConfigFieldSplitService::configure( PC& pc, const ISpace& space, const MatrixDistribution& distribution) { alien_debug([&] { cout() << "configure PETSc FlieldSplit preconditioner"; }); /*const Integer blocks_size = options()->block().size(); traceMng()->error() << "blocks_size 1 "<< blocks_size; IFieldSplitType* field_split_solver2 = options()->type(); if(field_split_solver2 == NULL) traceMng()->fatal() << "field split solver null";*/ /*if(options()->verbose()){ traceMng()->error() << "verbose"; } else{ traceMng()->error() << "no verbose"; }*/ /*Arcane::ConstArrayView<IOptionsPETScPrecConfigFieldSplit::IFieldSolver*> block = options()->block(); const Integer blocks_size2 = block.size(); traceMng()->error() << "blocks_size 2 "<< blocks_size2;*/ checkError("Set preconditioner", PCSetType(pc, PCFIELDSPLIT)); checkError("Build FieldSplit IndexSet", this->initializeFields(space, distribution)); const Arccore::Integer nbFields = m_field_petsc_indices.size(); ALIEN_ASSERT( (not m_field_petsc_indices.empty()), ("Unexpected empty PETSc IS for FieldSplit")); for (Arccore::Integer i = 0; i < nbFields; ++i) { #if ((PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR < 3) || (PETSC_VERSION_MAJOR < 3)) checkError("Set PetscIS", PCFieldSplitSetIS(pc, m_field_petsc_indices[i])); #else /* PETSC_VERSION */ checkError("Set PetscIS", PCFieldSplitSetIS(pc, m_field_tags[i].localstr(), m_field_petsc_indices[i])); #endif /* PETSC_VERSION */ } IFieldSplitType* field_split_solver = options()->type(); if (field_split_solver == NULL) alien_fatal([&] { cout() << "field split solver null"; }); // Configure type of FieldSplit decomposition checkError("Set FieldSplit type", field_split_solver->configure(pc, nbFields)); PCSetUp(pc); Arccore::Integer nbf; KSP* subksp; checkError("Get FieldSplit Sub KSP", PCFieldSplitGetSubKSP(pc, &nbf, &subksp)); if (nbf != nbFields) alien_fatal([&] { cout() << "Inconsistent number of split : user=" << nbFields << " PETSc=" << nbf; }); // a revoir pas naturel for (Arccore::Integer i = 0; i < nbFields; ++i) { if (m_field_tags[i] == m_default_block_tag) { IPETScKSP* sub_solver = options()->defaultBlock()[0]->solver(); sub_solver->configure(subksp[i], space, distribution); } else { // pas bon verifier manque indirection IPETScKSP* sub_solver = options()->block()[i]->solver(); sub_solver->configure(subksp[i], space, distribution); } } } Arccore::Integer PETScPrecConfigFieldSplitService::initializeFields( const ISpace& space, const MatrixDistribution& distribution) { const Arccore::String block_tag = options() ->blockTag(); // m_parent->getParams<std::string>()["fieldsplit-block-tag"]; // Verification des doublons de tags std::set<Arccore::String> tag_set; // const Integer block_size = m_parent->getParams<Integer>()["fieldsplit-block-size"]; const Arccore::Integer blocks_size = options()->block().size(); // traceMng()->error() << "blocks_size "<< blocks_size; m_field_tags.clear(); for (Arccore::Integer i = 0; i < blocks_size; ++i) { Arccore::String tag = options()->block()[i]->tag(); // traceMng()->error() << "tag "<< tag; if (tag == m_default_block_tag) alien_fatal([&] { cout() << "block-tag 'default' is a reserved keyword"; }); std::pair<std::set<Arccore::String>::const_iterator, bool> inserter = tag_set.insert(tag); if (inserter.second) { // traceMng()->error() << "add(m_field_tags,tag); "<< tag; m_field_tags.add(tag); } else alien_fatal([&] { cout() << "Duplicate block-tag found : " << tag; }); } // Partiton des indices Partition partition(space, distribution); partition.create(m_field_tags); bool has_untagged_part = partition.hasUntaggedPart(); // bool has_default_block = (options()->defaultBlock().size() > 0); // A t'on un defaut pour les partitions non taggés? if (has_untagged_part && (not has_default_block)) { alien_fatal( [&] { cout() << "Partition has untagged part and no default block is allowed"; }); return 1; } Arccore::Integer nbPart = partition.nbTaggedParts(); m_field_petsc_indices.clear(); m_field_petsc_indices.resize(nbPart + has_untagged_part); Arccore::Integer verbosity = options()->verbose(); Arccore::UniqueArray<Arccore::Integer> current_field_indices; Arccore::Integer nerror = 0; // Création de l'index set pour PETSc // Incrémentation de nerror si partition vide // Utilisation de current_field_indices comme buffer auto createIS = [&](Arccore::String tag, const Arccore::UniqueArray<Arccore::Integer>& indices, IS& petsc_is) { if (verbosity) alien_info( [&] { cout() << "Tag '" << tag << "' has " << indices.size() << " indices"; }); if (indices.size() == 0) { // Si partition vide, erreur alien_fatal([&] { cout() << "No entry found for block-tag '" << tag << "'"; }); ++nerror; } else { // copie et tri => peut être évité si besoin current_field_indices.resize(0); current_field_indices.copy(indices); std::sort(current_field_indices.begin(), current_field_indices.end()); // PETSc requires index ordering // Creation de l'index set pour PETSc #if ((PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR < 3) || (PETSC_VERSION_MAJOR < 3)) checkError("Create IndexSet", ISCreateGeneral(PETSC_COMM_WORLD, current_field_indices.size(), unguardedBasePointer(current_field_indices), &petsc_is)); #else /* PETSC_VERSION */ #ifndef WIN32 #warning "TODO OPTIM: using other copy mode may be more efficient" #endif checkError("Create IndexSet", ISCreateGeneral(PETSC_COMM_WORLD, current_field_indices.size(), current_field_indices.unguardedBasePointer(), PETSC_COPY_VALUES, &petsc_is)); #endif /* PETSC_VERSION */ } }; // Ajout des partitions taggées for (Arccore::Integer i = 0; i < partition.nbTaggedParts(); ++i) { createIS(m_field_tags[i], partition.taggedPart(i), m_field_petsc_indices[i]); } // Partition non taggée if (has_untagged_part) { m_field_tags.add(m_default_block_tag); createIS( m_field_tags[nbPart], partition.untaggedPart(), m_field_petsc_indices[nbPart]); } return nerror; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ // using namespace Arcane; ARCANE_REGISTER_SERVICE_PETSCPRECCONFIGFIELDSPLIT( FieldSplit, PETScPrecConfigFieldSplitService); } // namespace Alien REGISTER_STRONG_OPTIONS_PETSCPRECCONFIGFIELDSPLIT(); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
37.12766
91
0.626934
cedricga91
34d578e992a3519707dd652438e22bb310f749ff
409
hpp
C++
submodules/msgpack-c/include/msgpack/adaptor/complex.hpp
zhengwang/gaia-zbar-demo
8410dc3f12ffb4b1b1e79f66f376dd207b79e7b5
[ "MIT" ]
199
2017-12-29T13:36:53.000Z
2022-03-31T19:38:01.000Z
submodules/msgpack-c/include/msgpack/adaptor/complex.hpp
zhengwang/gaia-zbar-demo
8410dc3f12ffb4b1b1e79f66f376dd207b79e7b5
[ "MIT" ]
188
2017-11-03T18:22:46.000Z
2022-03-03T17:43:55.000Z
submodules/msgpack-c/include/msgpack/adaptor/complex.hpp
zhengwang/gaia-zbar-demo
8410dc3f12ffb4b1b1e79f66f376dd207b79e7b5
[ "MIT" ]
35
2017-11-02T19:18:34.000Z
2021-10-05T09:37:22.000Z
// // MessagePack for C++ static resolution routine // // Copyright (C) 2020 KONDO Takatoshi // // 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 MSGPACK_TYPE_COMPLEX_HPP #define MSGPACK_TYPE_COMPLEX_HPP #include "msgpack/v1/adaptor/complex.hpp" #endif // MSGPACK_TYPE_COMPLEX_HPP
25.5625
64
0.748166
zhengwang
34d5b46bf2d84f751764db1a2bd7ab092f9b9853
399
cc
C++
beautiful_matrix.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
beautiful_matrix.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
3
2021-01-04T18:33:39.000Z
2021-01-04T19:37:21.000Z
beautiful_matrix.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> //#include <utility> int main() { int x, y, v, x_c, y_c, ans = 0; for (y = 0; y < 5; ++y) { for (x = 0; x < 5; ++x) { std::cin >> v; if(v == 1) { x_c = x; y_c = y; } } } ans += abs(x_c - 2); ans += abs(y_c - 2); std::cout << ans; return 0; }
17.347826
35
0.340852
maximilianbrine
34d8d80e31c05a000c472c646582c4cb390c24ef
24,464
hpp
C++
integer.hpp
arbitrary-precision/ap
fc6dffabba8edcf09255c429ec81eed0b3fd63a8
[ "MIT" ]
11
2021-12-14T14:05:14.000Z
2022-01-09T20:24:56.000Z
integer.hpp
arbitrary-precision/ap
fc6dffabba8edcf09255c429ec81eed0b3fd63a8
[ "MIT" ]
null
null
null
integer.hpp
arbitrary-precision/ap
fc6dffabba8edcf09255c429ec81eed0b3fd63a8
[ "MIT" ]
1
2022-01-30T03:20:40.000Z
2022-01-30T03:20:40.000Z
#ifndef DEOHAYER_AP_INT_HPP #define DEOHAYER_AP_INT_HPP #include "integer_api.hpp" #include "integer_handle.hpp" #include <iostream> namespace ap { namespace library { #define AP_DEFAULT_STR_BASE 10 #define AP_DEFAULT_STR "0123456789ABCDEF" ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SFINAE template <typename _IntegerL, typename _IntegerR, bool _Left> struct wider_int; template <typename _IntegerL, typename _IntegerR> struct wider_int<_IntegerL, _IntegerR, true> { using type = _IntegerL; }; template <typename _IntegerL, typename _IntegerR> struct wider_int<_IntegerL, _IntegerR, false> { using type = _IntegerR; }; template <typename _Type1, typename _Type2> constexpr bool is_same_v() { return std::is_same<_Type1, _Type2>::value; } template <typename _IntegerL, typename _IntegerR> using wider_int_t = typename wider_int<_IntegerL, _IntegerR, (index_t(_IntegerL::valuewidth) >= index_t(_IntegerR::valuewidth))>::type; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // integer class, represents user-level API template <index_t _Bitwidth, bool _Signed> class integer { // Currently support for reverse narrowing is not available. static_assert(_Bitwidth > (sizeof(unsigned long long) * CHAR_BIT), "AP integer must be strictly greater than unsigned long long."); public: // Divided we fall. template <index_t _BitwidthO, bool _SignedO> friend class integer; private: // Holds actual data. using handle_t = integer_handle<_Bitwidth>; handle_t handle; private: // Handle situations that occured during operations. static void fregister_handler_none(fregister flags) { AP_UNUSED(flags); } static void fregister_handler_div(fregister flags) { if (flags.has_any(fregister::infinity)) { // Setting 0 / 0 explicitly may trigger compilation error. int a = 0; a = a / a; } } public: enum : index_t { is_signed = _Signed, bitwidth = handle_t::bitwidth, wordwidth = handle_t::wordwidth, valuewidth = bitwidth - is_signed }; public: ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ctor integer() = default; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // str integer& set(const char* str, index_t size = 0, index_t base = 0, const char* digits = AP_DEFAULT_STR) { fregister flags; size = ((size != 0) ? size : strlen(str)); if (this->is_signed) { flags = sinteger_fstr(this->handle.get_wregister(), str, size, base, digits); } else { flags = uinteger_fstr(this->handle.get_wregister(), str, size, base, digits); } return *this; } integer& set(const std::string& str, index_t base = 0, const char* digits = AP_DEFAULT_STR) { return this->set(str.c_str(), str.size(), base, digits); } explicit integer(const std::string& str, index_t base = 0, const char* digits = AP_DEFAULT_STR) : integer(str.c_str(), index_t(str.size()), base, digits) { } explicit integer(const char* str, index_t size = 0, index_t base = 0, const char* digits = AP_DEFAULT_STR) { this->set(str, size, base, digits); } integer& operator=(const std::string& str) { return this->set(str); } integer& operator=(const char* str) { return this->set(str); } std::string str(index_t base = AP_DEFAULT_STR_BASE, const char* digits = AP_DEFAULT_STR) const { std::string str; rregister r = this->handle.get_rregister(); if (this->is_signed) { sinteger_tstr(r, str, base, digits); } else { uinteger_tstr(r, str, base, digits); } return str; } explicit operator std::string() const { return this->str(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // basic template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> integer(T val) { wregister& reg = this->handle.get_wregister(); if (this->is_signed) { if (std::is_signed<T>::value) { sinteger_fbasic(reg, val); } else { uinteger_fbasic(reg, val); } } else { if (std::is_signed<T>::value) { sinteger_fbasic(reg, val); sinteger_tou(this->handle.get_rregister(), reg); } else { uinteger_fbasic(reg, val); } } } explicit operator bool() const { return this->handle.get_size(); } template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> explicit operator T() const { if (this->is_signed) { return static_cast<T>(sinteger_tbasic(this->handle.get_rregister())); } else { return static_cast<T>(uinteger_tbasic(this->handle.get_rregister())); } } template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> integer& operator=(T val) { *this = integer(val); return *this; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // move integer(integer&& other) = default; integer& operator=(integer&& other) = default; template <index_t _BitwidthO, bool _SignedO, typename std::enable_if<!((_Bitwidth - _Signed) < (_BitwidthO - _SignedO)), bool>::type = false> integer(integer<_BitwidthO, _SignedO>&& other) { this->handle = std::move(other.handle); if (this->handle.get_sign() && !this->is_signed) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } } template <index_t _BitwidthO, bool _SignedO, typename std::enable_if<((_Bitwidth - _Signed) < (_BitwidthO - _SignedO)), bool>::type = false> explicit integer(integer<_BitwidthO, _SignedO>&& other) { index_t other_size = other.handle.get_size(); this->handle = std::move(other.handle); if (this->is_signed) { if (((other_size > this->handle.get_capacity()) && this->handle.get_sign())) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } if (this->handle.get_rregister().has_msb()) { uinteger_tos(this->handle.get_rregister(), this->handle.get_wregister()); } } else { if (this->handle.get_sign() && !this->is_signed) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } } } template <index_t _BitwidthO, bool _SignedO> integer& operator=(integer<_BitwidthO, _SignedO>&& other) { *this = integer(std::move(other)); return *this; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // copy integer(const integer& other) = default; integer& operator=(const integer& other) = default; template <index_t _BitwidthO, bool _SignedO, typename std::enable_if<!((_Bitwidth - _Signed) < (_BitwidthO - _SignedO)), bool>::type = false> integer(const integer<_BitwidthO, _SignedO>& other) { this->handle = other.handle; if (this->handle.get_sign() && !this->is_signed) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } } template <index_t _BitwidthO, bool _SignedO, typename std::enable_if<((_Bitwidth - _Signed) < (_BitwidthO - _SignedO)), bool>::type = false> explicit integer(const integer<_BitwidthO, _SignedO>& other) { index_t other_size = other.handle.get_size(); this->handle = other.handle; if (this->is_signed) { if (((other_size > this->handle.get_capacity()) && this->handle.get_sign())) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } if (this->handle.get_rregister().has_msb()) { uinteger_tos(this->handle.get_rregister(), this->handle.get_wregister()); } } else { if (this->handle.get_sign() && !this->is_signed) { sinteger_tou(this->handle.get_rregister(), this->handle.get_wregister()); } } } template <index_t _BitwidthO, bool _SignedO> integer& operator=(const integer<_BitwidthO, _SignedO>& other) { *this = integer(other); return *this; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cmp template <typename T> bool operator<(const T& other) const { return this->cmp(other) == -1; } template <typename T> bool operator<=(const T& other) const { return this->cmp(other) != 1; } template <typename T> bool operator>(const T& other) const { return this->cmp(other) == 1; } template <typename T> bool operator>=(const T& other) const { return this->cmp(other) != -1; } template <typename T> bool operator==(const T& other) const { return this->cmp(other) == 0; } template <typename T> bool operator!=(const T& other) const { return this->cmp(other) != 0; } int cmp(const integer& other) const { if (this->is_signed) { return sinteger_cmp(this->handle.get_rregister(), other.handle.get_rregister()).result; } else { return uinteger_cmp(this->handle.get_rregister(), other.handle.get_rregister()).result; } } template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> int cmp(const T& other) const { if (other == 0) { if (this->handle.get_size() != 0) { return this->handle.get_size() > 0 ? 1 : -1; } else { return 0; } } return this->cmp(integer(other)); } template <typename T, typename std::enable_if<bool(T::valuewidth), bool>::type = false> int cmp(const T& other) const { if (_Signed != bool(other.is_signed)) { if (_Bitwidth > (other.valuewidth)) { return this->cmp(integer(other)); } else { return T(*this).cmp(other); } } else { if (this->is_signed) { return sinteger_cmp(this->handle.get_rregister(), other.handle.get_rregister()).result; } else { return uinteger_cmp(this->handle.get_rregister(), other.handle.get_rregister()).result; } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ordinary binary operators #define AP_BINARY_OPERATOR(name, op, fhandler) \ template <typename T, typename std::enable_if<bool(T::valuewidth), bool>::type = false> \ wider_int_t<integer<_Bitwidth, _Signed>, T> op(const T& other) const \ { \ wider_int_t<integer<_Bitwidth, _Signed>, T> result; \ this->dispatch_binary_operation<uinteger_##name, sinteger_##name, fhandler>(other, result); \ return result; \ } \ \ template <typename T, typename std::enable_if<bool(T::valuewidth), bool>::type = false> \ integer& op## = (const T& other) \ { \ this->dispatch_binary_operation<uinteger_##name, sinteger_##name, fhandler>(other, *this); \ return *this; \ } \ \ template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> \ integer op(const T& other) const \ { \ return this->op(integer(other)); \ } \ \ template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> \ integer& op## = (const T& other) \ { \ return this->op## = (integer(other)); \ } AP_BINARY_OPERATOR(add, operator+, fregister_handler_none) AP_BINARY_OPERATOR(sub, operator-, fregister_handler_none) AP_BINARY_OPERATOR(mul, operator*, fregister_handler_none) AP_BINARY_OPERATOR(quo, operator/, fregister_handler_div) AP_BINARY_OPERATOR(rem, operator%, fregister_handler_div) AP_BINARY_OPERATOR(and, operator&, fregister_handler_none) AP_BINARY_OPERATOR(or, operator|, fregister_handler_none) AP_BINARY_OPERATOR(xor, operator^, fregister_handler_none) integer operator~() const { integer result; if (_Signed) { sinteger_not(this->handle.get_rregister(), result.handle.get_wregister()); } else { uinteger_not(this->handle.get_rregister(), result.handle.get_wregister()); } return result; } integer operator++(int) { integer result = *this; *this += integer(1); return result; } integer& operator++() { return *this += integer(1); } integer operator--(int) { integer result = *this; *this -= integer(1); return result; } integer& operator--() { *this -= integer(1); return *this; } integer operator-() const { integer result = *this; if (this->handle.get_size() != 0) { wregister& reg = result.handle.get_wregister(); if (_Signed) { if (!reg.has_msb()) { reg.sign = !reg.sign; } } else { reg.sign = 1; sinteger_tou(rregister(reg), reg); } } return result; } integer operator+() const { return *this; } integer operator>>(unsigned long long int shift) const { integer result; if (_Signed) { sinteger_rsh(this->handle.get_rregister(), shift, result.handle.get_wregister()); } else { uinteger_rsh(this->handle.get_rregister(), shift, result.handle.get_wregister()); } return result; } integer& operator>>=(unsigned long long int shift) { if (_Signed) { sinteger_rsh(this->handle.get_rregister(), shift, this->handle.get_wregister()); } else { uinteger_rsh(this->handle.get_rregister(), shift, this->handle.get_wregister()); } return *this; } integer operator<<(unsigned long long int shift) const { integer result; if (_Signed) { sinteger_lsh(this->handle.get_rregister(), shift, result.handle.get_wregister()); } else { uinteger_lsh(this->handle.get_rregister(), shift, result.handle.get_wregister()); } return result; } integer& operator<<=(unsigned long long int shift) { (*this) = (*this) << shift; return *this; } private: using binary_operation = fregister (*)(rregister, rregister, wregister&); using fregister_handler = void (*)(fregister); template <binary_operation uop, binary_operation sop, fregister_handler h, index_t _BitwidthO, bool _SignedO, index_t _BitwidthR, bool _SignedR> void dispatch_binary_operation(const integer<_BitwidthO, _SignedO>& other, integer<_BitwidthR, _SignedR>& result) const { rregister left; rregister right; fregister flags; if (_SignedO == _Signed) { left = this->handle.get_rregister(); right = other.handle.get_rregister(); wregister& out = result.handle.get_wregister(); binary_operation op = (result.is_signed ? sop : uop); out.sign = 0; flags = op(left, right, out); } else { wregister& out = result.handle.get_wregister(); if ((_BitwidthO - _SignedO) > (_Bitwidth - _Signed)) { integer<_BitwidthO, _SignedO> nleft{*this}; left = nleft.handle.get_rregister(); right = other.handle.get_rregister(); binary_operation op = (_SignedO ? sop : uop); out.sign = 0; flags = op(left, right, out); if (result.is_signed != _SignedO) { if (_SignedO) { sinteger_tou(rregister(out), out); } else { uinteger_tos(rregister(out), out); } } } else { integer<_Bitwidth, _Signed> nright{other}; left = this->handle.get_rregister(); right = nright.handle.get_rregister(); binary_operation op = (_Signed ? sop : uop); out.sign = 0; flags = op(left, right, out); if (result.is_signed != _Signed) { if (_Signed) { sinteger_tou(rregister(out), out); } else { uinteger_tos(rregister(out), out); } } } } h(flags); } }; } // namespace library } // namespace ap template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator<(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) != -1; } template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator<=(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) != -1; } template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator>(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) != 1; } template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator>=(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) != 1; } template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator==(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) == 0; } template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> bool operator!=(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) { return right.cmp(left) != 0; } #define AP_BASIC_OPERATOR(op) \ template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> \ ap::library::integer<_Bitwidth, _Signed> operator op(const T& left, const ap::library::integer<_Bitwidth, _Signed>& right) \ { \ return ap::library::integer<_Bitwidth, _Signed>(left) op right; \ } \ \ template <typename T, ap::library::index_t _Bitwidth, bool _Signed, typename std::enable_if<std::is_integral<T>::value, bool>::type = false> \ T& operator op##=(T& left, const ap::library::integer<_Bitwidth, _Signed>& right) \ { \ left = static_cast<T>(ap::library::integer<_Bitwidth, _Signed>(left) op right); \ return left; \ } AP_BASIC_OPERATOR(+) AP_BASIC_OPERATOR(-) AP_BASIC_OPERATOR(*) AP_BASIC_OPERATOR(/) AP_BASIC_OPERATOR(%) AP_BASIC_OPERATOR(&) AP_BASIC_OPERATOR(^) AP_BASIC_OPERATOR(|) AP_BASIC_OPERATOR(<<) AP_BASIC_OPERATOR(>>) template <ap::library::index_t _Bitwidth, bool _Signed> std::ostream& operator<<(std::ostream& os, const ap::library::integer<_Bitwidth, _Signed>& val) { ap::library::index_t base = 10; if (os.flags() & std::ios_base::oct) { base = 8; } if (os.flags() & std::ios_base::hex) { base = 16; } os << val.str(base); return os; } template <ap::library::index_t _Bitwidth, bool _Signed> std::istream& operator>>(std::istream& is, ap::library::integer<_Bitwidth, _Signed>& val) { std::string str; is >> str; val = str; return is; } #undef AP_BASIC_OPERATOR #undef AP_BINARY_OPERATOR #undef AP_DEFAULT_STR #undef AP_DEFAULT_STR_BASE #endif
33.604396
146
0.485039
arbitrary-precision
34dd7abf37e1b8c2f160ba3f0f1f5a6dbb9d7da3
1,219
hpp
C++
include/lol/op/GetRsoAuthV1AuthorizationIdToken.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/op/GetRsoAuthV1AuthorizationIdToken.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/op/GetRsoAuthV1AuthorizationIdToken.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_op.hpp" #include <functional> #include "../def/RsoAuthIdToken.hpp" namespace lol { template<typename T> inline Result<RsoAuthIdToken> GetRsoAuthV1AuthorizationIdToken(T& _client) { try { return ToResult<RsoAuthIdToken>(_client.https.request("get", "/rso-auth/v1/authorization/id-token?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }))); } catch(const SimpleWeb::system_error &e) { return ToResult<RsoAuthIdToken>(e.code()); } } template<typename T> inline void GetRsoAuthV1AuthorizationIdToken(T& _client, std::function<void(T&, const Result<RsoAuthIdToken>&)> cb) { _client.httpsa.request("get", "/rso-auth/v1/authorization/id-token?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }),[cb,&_client](std::shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &e) { if(e) cb(_client, ToResult<RsoAuthIdToken>(e)); else cb(_client, ToResult<RsoAuthIdToken>(response)); }); } }
36.939394
141
0.635767
Maufeat
34df8aed70c93ced2056c7ae0483152508c930ff
56
hpp
C++
src/boost_compute_iterator_constant_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_compute_iterator_constant_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_compute_iterator_constant_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/compute/iterator/constant_iterator.hpp>
28
55
0.839286
miathedev
34e08cbd509422605d89e432daa71260e3448977
752
hpp
C++
src/tracer/camera.hpp
marovira/ctrt
86c59f398dd5c1ba800ab5e5b2909c990f3fd9c6
[ "BSD-3-Clause" ]
2
2021-03-15T19:29:23.000Z
2021-11-16T03:35:40.000Z
src/tracer/camera.hpp
marovira/ctrt
86c59f398dd5c1ba800ab5e5b2909c990f3fd9c6
[ "BSD-3-Clause" ]
null
null
null
src/tracer/camera.hpp
marovira/ctrt
86c59f398dd5c1ba800ab5e5b2909c990f3fd9c6
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "ray.hpp" class Camera { public: constexpr Camera() : m_distance{0.0f} {} constexpr Camera(Point const& eye, Vector const& look_at, Vector const& up, float distance) : m_eye{eye}, m_distance{distance} { m_w = normalise(eye - look_at); m_u = normalise(cross(up, m_w)); m_v = cross(m_w, m_u); } constexpr Vector get_ray_direction(Point const& p) const { auto dir = p.x() * m_u + p.y() * m_v - m_distance * m_w; return normalise(dir); } constexpr Point get_eye() const { return m_eye; } private: Point m_eye; Vector m_u, m_v, m_w; float m_distance; };
19.789474
64
0.537234
marovira
34e2b373272df2b8e92e33d97c71e1f1f52dc379
203
cpp
C++
Chapter01/in_out.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
207
2018-04-24T22:39:37.000Z
2022-03-28T12:16:16.000Z
Chapter01/in_out.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
1
2020-06-24T23:47:28.000Z
2020-07-17T12:56:41.000Z
Chapter01/in_out.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
98
2018-04-28T15:03:48.000Z
2022-01-03T12:16:07.000Z
// in_out.cpp #include <iostream> int main () { int i; std::cout << "Please enter an integer value: "; std::cin >> i; std::cout << "The value you entered is " << i; std::cout << "\n"; return 0; }
15.615385
48
0.576355
Vaibhav-Kashyap
34e4f806db8a642ebe01b1ce6aa1a24d17b8fa4e
1,412
cc
C++
algorithm_dbosch.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
6
2019-03-06T23:54:01.000Z
2020-08-24T09:18:33.000Z
algorithm_dbosch.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
6
2019-03-07T00:31:48.000Z
2021-01-10T13:28:41.000Z
algorithm_dbosch.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
8
2019-03-07T00:08:43.000Z
2021-05-13T12:14:08.000Z
#include "algorithm_dbosch.hpp" namespace prhlt { using namespace log4cxx;using namespace log4cxx::helpers; using namespace boost; using namespace Eigen; Algorithm_DBOSCH::Algorithm_DBOSCH(cv::Mat &ex_image):Algorithm_Distance_Map(ex_image){ } void Algorithm_DBOSCH::run(int ex_curvature_ratio, int ex_threshold,float ex_direct_constant, float ex_diagonal_constant){ this->direct_distance_constant = ex_direct_constant; this->diagonal_distance_constant = ex_diagonal_constant; Algorithm_Distance_Map::run(ex_curvature_ratio,ex_threshold); } void Algorithm_DBOSCH::run(int ex_curvature_ratio, cv::Mat frontier_points_mat,float ex_direct_constant, float ex_diagonal_constant){ this->direct_distance_constant = ex_direct_constant; this->diagonal_distance_constant = ex_diagonal_constant; Algorithm_Distance_Map::run(ex_curvature_ratio,frontier_points_mat); } float Algorithm_DBOSCH::calculate_neighbour_value(int r1,int c1, int r2, int c2){ LOG4CXX_DEBUG(this->logger,"<<WDTOCS: calculate grey gradient>>"); float gradient = 0.0; if(r1 != r2 and c1 != c2) gradient = 1.414213; else gradient = 1.0; return gradient+distance_matrix(r2,c2)+(float)((int)this->image.at<uchar>(r1,c1)/255.0); //return gradient+distance_matrix(r2,c2); } }
38.162162
137
0.711756
jkloe
34e73a26f3faaba69bd211507e911461a5b8c1e6
360
cpp
C++
origin_code/factorial.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/factorial.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/factorial.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// compute n! #include <iostream> using namespace std; int factorial(int n) {// Compute n! if (n <= 1) return 1; else return n * factorial(n - 1); } int main() {// test the function cout << "0! = " << factorial(0) << endl; cout << "1! = " << factorial(1) << endl; cout << "5! = " << factorial(5) << endl; return 0; }
17.142857
44
0.508333
vectordb-io
34e75b64636ca2e276112e5b6eb7bdedbcf8a0f1
175
cpp
C++
transitin-sqlite/validation.cpp
alairon/transitin-sqlite
6533b45ed2bc5da976ff86680e3a4aa9e40d874b
[ "MIT" ]
null
null
null
transitin-sqlite/validation.cpp
alairon/transitin-sqlite
6533b45ed2bc5da976ff86680e3a4aa9e40d874b
[ "MIT" ]
null
null
null
transitin-sqlite/validation.cpp
alairon/transitin-sqlite
6533b45ed2bc5da976ff86680e3a4aa9e40d874b
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "system.hpp" using namespace std; /*Checks if a file exists*/ bool fileExists(string file) { ifstream inFile(file); return (inFile.good()); }
15.909091
30
0.708571
alairon
34eb33e6701356fea57a57dbb655d34ab8559d7e
1,086
cpp
C++
oop_class_car.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
oop_class_car.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
oop_class_car.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
// Single-line comment /* * Multiple line comment */ #include <iostream> #include "oop_class_car.h" using namespace std; int Car::total_count {0}; Car::Car():Car(0) { cout << "Car()" << endl; } Car::Car(float amount):Car(amount, 0) { cout << "Car(float)" << endl; } Car::Car(float fuel, int passengers) { cout << "Car(float, int)" << endl; total_count++; this->fuel = fuel; this->passengers = passengers; this->speed = 0; } Car::~Car() { cout << "~Car()" << endl; total_count--; } void Car::fill_fuel(float amount) { fuel = amount; } void Car::accelerate() { speed++; fuel -= 0.5f; } void Car::breake() { speed = 0; } void foo(const Car &car) { } void Car::add_passengers(int passengers) { this->passengers = passengers; foo(*this); } void Car::show_count() { cout << "Total cars: " << total_count << endl; } void Car::dashboard() const { cout << "Fuel: " << fuel << endl; cout << "Speed: " << speed << endl; cout << "Passengers: " << passengers << endl; cout << "Array[2]: " << arr[2] << endl; cout << "Total count: " << total_count << endl; }
13.575
48
0.594843
rostislav-nikitin
34ed87a9d1efa199b206d61ed3f7d92013b33158
19,064
cpp
C++
src/main.cpp
7h3730B/SuperDuperLedAppESP
f73512bacba9ddb71b2ab23bfe4f82ddce3e9b2b
[ "MIT" ]
null
null
null
src/main.cpp
7h3730B/SuperDuperLedAppESP
f73512bacba9ddb71b2ab23bfe4f82ddce3e9b2b
[ "MIT" ]
null
null
null
src/main.cpp
7h3730B/SuperDuperLedAppESP
f73512bacba9ddb71b2ab23bfe4f82ddce3e9b2b
[ "MIT" ]
1
2019-11-16T16:31:35.000Z
2019-11-16T16:31:35.000Z
#include "Arduino.h" #include "Debug.h" #include "ESP8266WiFi.h" #include "ESP8266WebServer.h" #include "ArduinoJson.h" #include "FS.h" #include "FastLED.h" #include "WiFiUdp.h" #include <ESP8266HTTPUpdateServer.h> #include "effect.h" #include "effects/comet.cpp" #include "effects/rainbow.cpp" #include "effects/ripple.cpp" #include "effects/Konfetti.cpp" #include "effects/sinelon.cpp" #include "effects/juggle.cpp" #include "effects/theater.cpp" #include "effects/wave.cpp" #include "effects/pal.cpp" #include "effects/old.cpp" // Config stuff struct Config { char ssid[64]; char password[100]; char name[64]; int num_leds; }; // makegreater effect **effectarray = new effect *[9]; boolean bon = true; int currentEffect = 0; const char *filename = "config.json"; Config config; String led(config.num_leds); const char *type = "Led_1"; const char *version = "0.1.2"; const char *versionURL = "https://7h3730b.github.io/SuperDuperLedAppESP/versions.json"; // TODO: ADD INFO SITE // Server / UDP ESP8266WebServer server(80); ESP8266HTTPUpdateServer httpUpdater; WiFiUDP Udp; char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // Led #define DATA_PIN1 6 #define DATA_PIN2 5 #define MAX_NUM_LEDS 500 // TODO: Lower this if you need more DATA Space #define LED_TYPE WS2812B CRGB leds[MAX_NUM_LEDS]; void getAllFunctions(); void getsettingofFunction(); void set(); void seton(); void setoff(); void getbon(); void setWiFi(); void loadConfig(const char *filename, Config &config); void printFile(const char *filename); void saveConf(const char *filename, const Config &config); void getSettings(); void resetSettings(); void setSettings(); void v404(); void getversionURL(); void getversion(); void getStatus(); void restart(); void seteffectsetSetting(); void setup() { // AddtheFunction effectarray[0] = new ripple("Ripple"); effectarray[1] = new wave("Wave"); effectarray[2] = new pal("pal"); effectarray[3] = new old("old"); effectarray[4] = new juggle("Juggle"); effectarray[5] = new comet("Comet"); effectarray[6] = new Konfetti("Konfetti"); effectarray[7] = new sinelon("Sinelon"); effectarray[8] = new theater("theater"); effectarray[9] = new Rainbow("Rainbow"); #ifdef DEBUG Serial.begin(115200); #endif // init SPIFF and load config SPIFFS.begin(); printFile(filename); loadConfig(filename, config); // To allow for resets. WiFi.disconnect(); // LEDs FastLED.addLeds<LED_TYPE, DATA_PIN1, GRB>(leds, MAX_NUM_LEDS); FastLED.addLeds<LED_TYPE, DATA_PIN2, GRB>(leds, MAX_NUM_LEDS); // init WiFi WiFi.mode(WIFI_STA); WiFi.begin(config.ssid, config.password); static long last_check; static long last_check2; static boolean black; int c = 0; bool smartconfi = false; // WiFi check while (WiFi.status() != WL_CONNECTED) { delay(500); if (millis() - last_check > 1500) { delay(0); for (int i = 0; i < config.num_leds; i++) { if (i % 2 == 0) leds[i].setRGB(0, 255, 255); } FastLED.show(); last_check = millis(); ESP.wdtFeed(); last_check2 = millis(); black = true; } if (millis() - last_check2 > 500 && black) { fill_solid(leds, config.num_leds, CRGB::Black); FastLED.show(); last_check2 = millis(); black = false; } c++; // Falls nach 5 Sekunden kein WiFi => Smartconfig if (c >= 35) { smartconfi = true; break; } } if (smartconfi) { // Smartconfig beginnt WiFi.beginSmartConfig(); // Warten bis Smartconfig erhalten wird DEBUG_PRINTLN(F("Warten auf Smartconfig")); for (int i = 0; i < config.num_leds; i++) { if (i % 2 == 0) leds[i].setRGB(0, 255, 255); } FastLED.show(); while (!WiFi.smartConfigDone()) { delay(500); DEBUG_PRINT(F(".")); } // Falls fertig DEBUG_PRINTLN(F("SmartConfig erhalten.")); // Warten auf WiFi DEBUG_PRINTLN(F("Warten auf WiFi")); while (WiFi.status() != WL_CONNECTED) { delay(500); DEBUG_PRINT(F(".")); for (int i = 0; i < config.num_leds; i++) { if (i % 2 == 0) leds[i].setRGB(0, 255, 255); } FastLED.show(); fadeToBlackBy(leds, config.num_leds, 1); } } for (int i = 0; i < config.num_leds; i++) { if (i % 2 == 0) leds[i].setRGB(0, 255, 0); } FastLED.show(); DEBUG_PRINTLN(F("WiFi verbunden.")); server.on("/setWiFi", HTTP_POST, setWiFi); server.on("/set", HTTP_POST, set); server.on("/getallFunctions", HTTP_GET, getAllFunctions); server.on("/getsettingofFunction", HTTP_POST, getsettingofFunction); server.on("/seteffectset", HTTP_POST, seteffectsetSetting); server.on("/on", HTTP_GET, seton); server.on("/off", HTTP_GET, setoff); server.on("/getbon", HTTP_GET, getbon); server.on("/getSettings", HTTP_GET, getSettings); server.on("/setSettings", HTTP_POST, setSettings); server.on("/getStatus", HTTP_GET, getStatus); server.on("/getversion", HTTP_GET, getversion); server.on("/getversionURL", HTTP_GET, getversionURL); server.on("/restart", HTTP_GET, restart); server.on("/reset", HTTP_POST, resetSettings); server.onNotFound(v404); DEBUG_PRINT(F("IP Addresse: ")); DEBUG_PRINTLN(WiFi.localIP()); DEBUG_PRINTLN(WiFi.SSID()); httpUpdater.setup(&server); server.begin(); // INIT UDP SEARCH Udp.begin(8000); delay(500); fill_solid(leds, MAX_NUM_LEDS, CRGB::Black); FastLED.show(); } void loop() { if (bon) { effectarray[currentEffect]->loop(leds, config.num_leds); } else { for (int i = 0; i < config.num_leds; i++) { leds[i] = CRGB::Black; } } // Get the current time unsigned long continueTime = millis() + int(float(1000 / 50)); // Do our main loop functions, until we hit our wait time do { FastLED.show(); server.handleClient(); yield(); if (WiFi.status() != WL_CONNECTED) { DEBUG_PRINTLN(F("NO WIFI")); } // UDP SEARCH int packetSize = Udp.parsePacket(); if (packetSize) { String name(config.name); String typ(type); String ReplyBuffer = name + "|" + WiFi.macAddress() + "|" + typ; char cstr[ReplyBuffer.length() + 1]; strcpy(cstr, ReplyBuffer.c_str()); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(cstr); Udp.endPacket(); } } while (millis() < continueTime); } void seteffectsetSetting() { String data = server.arg("plain"); StaticJsonDocument<400> dataJson; DeserializationError error = deserializeJson(dataJson, data); if (error) { DEBUG_PRINTLN(F("deserializeJson() fehlgeschlagen: ")); DEBUG_PRINTLN(error.c_str()); return; } effectarray[dataJson["i"].as<int>()]->deserialize(dataJson); server.send(200, "application/json", "OK"); } void seton() { if (bon == false) bon = true; server.send(200, "application/plain", "OK"); } void setoff() { if (bon == true) bon = false; server.send(200, "application/plain", "OK"); } void getbon() { server.send(200, "application/plain", bon + ""); } void getAllFunctions() { // { // "e" : [ // { // "n" : "12345678912345678912", // "id" : "123" // }, // { // "n" : "12345678912345678912", // "id" : "123" // }, // ] // } int len = sizeof(effectarray) + 15; const size_t capacity = JSON_ARRAY_SIZE(len + 1) + JSON_OBJECT_SIZE(1) + (len + 1) * JSON_OBJECT_SIZE(2); DEBUG_PRINTLN(capacity); DynamicJsonDocument doc(capacity); JsonArray arra = doc.createNestedArray("e"); // getAllFunctionsGeneration JsonObject e_0 = arra.createNestedObject(); e_0["n"] = effectarray[0]->name; e_0["id"] = 0; JsonObject e_1 = arra.createNestedObject(); e_1["n"] = effectarray[1]->name; e_1["id"] = 1; JsonObject e_2 = arra.createNestedObject(); e_2["n"] = effectarray[2]->name; e_2["id"] = 2; JsonObject e_3 = arra.createNestedObject(); e_3["n"] = effectarray[3]->name; e_3["id"] = 3; JsonObject e_4 = arra.createNestedObject(); e_4["n"] = effectarray[4]->name; e_4["id"] = 4; JsonObject e_5 = arra.createNestedObject(); e_5["n"] = effectarray[5]->name; e_5["id"] = 5; JsonObject e_6 = arra.createNestedObject(); e_6["n"] = effectarray[6]->name; e_6["id"] = 6; JsonObject e_7 = arra.createNestedObject(); e_7["n"] = effectarray[7]->name; e_7["id"] = 7; JsonObject e_8 = arra.createNestedObject(); e_8["n"] = effectarray[8]->name; e_8["id"] = 8; JsonObject e_9 = arra.createNestedObject(); e_9["n"] = effectarray[9]->name; e_9["id"] = 9; server.send(200, "application/json", doc.as<String>()); } void getsettingofFunction() { // { // "e": [ // { // "n" : "Speed", // "t" : "i", // "mn": "1", // "mx": "15", // "v": "2", // "e" : "s" // }, // { // "n" : "Speed", // "t" : "i", // "mn": "1", // "mx": "15", // "v": "2", // "e" : "s" // }, // ] // } // { // "i": "0" // } String data = server.arg("plain"); StaticJsonDocument<30> dataJson; DeserializationError error = deserializeJson(dataJson, data); if (error) { DEBUG_PRINTLN(F("deserializeJson() fehlgeschlagen: ")); DEBUG_PRINTLN(error.c_str()); return; } const size_t capacity = JSON_ARRAY_SIZE(30) + JSON_OBJECT_SIZE(1) + (10) * JSON_OBJECT_SIZE(7); DynamicJsonDocument doc(capacity); JsonArray arra = doc.createNestedArray("e"); effectarray[dataJson["i"].as<int>()]->getData(arra); DEBUG_PRINTLN("Sending"); server.send(200, "application/json", doc.as<String>()); } void set() { String data = server.arg("plain"); StaticJsonDocument<30> dataJson; DeserializationError error = deserializeJson(dataJson, data); if (error) { DEBUG_PRINTLN(F("deserializeJson() fehlgeschlagen: ")); DEBUG_PRINTLN(error.c_str()); return; } currentEffect = dataJson["i"].as<int>(); effectarray[currentEffect]->begin(); server.send(200, "application/plain", "OK"); } void resetSettings() { SPIFFS.remove(filename); server.send(200, "application/plain", "OK"); delay(2000); ESP.restart(); } // TODO: ADD CHECKS EVERYWHERE void setSettings() { Config conf = Config(); String data = server.arg("plain"); StaticJsonDocument<500> doc; DeserializationError error = deserializeJson(doc, data); if (error) { DEBUG_PRINTLN(F("deserializeJson() fehlgeschlagen: ")); DEBUG_PRINTLN(error.c_str()); return; } strlcpy(conf.name, doc["n"] | config.name, sizeof(conf.name)); conf.num_leds = doc["l"] | config.num_leds; strlcpy(conf.password, config.password, sizeof(conf.password)); strlcpy(conf.ssid, config.ssid, sizeof(conf.ssid)); saveConf(filename, conf); server.send(200, F("text/plain"), F("f")); delay(2000); ESP.restart(); } void setWiFi() { Config conf = Config(); String data = server.arg("plain"); StaticJsonDocument<500> doc; DeserializationError error = deserializeJson(doc, data); if (error) { DEBUG_PRINTLN(F("deserializeJson() fehlgeschlagen: ")); DEBUG_PRINTLN(error.c_str()); return; } strlcpy(conf.name, type, sizeof(conf.name)); conf.num_leds = 30; strlcpy(conf.password, doc["p"] | config.password, sizeof(conf.password)); strlcpy(conf.ssid, doc["w"] | config.ssid, sizeof(conf.ssid)); saveConf(filename, conf); server.send(200, F("text/plain"), F("f")); delay(2000); ESP.restart(); } void saveConf(const char *filename, const Config &config) { SPIFFS.remove(filename); // Datei öffnen zum schreiben File file = SPIFFS.open(filename, "w"); if (!file) { DEBUG_PRINTLN(F("Failed to create file")); return; } StaticJsonDocument<500> doc; // Setze values des Dokuments doc["w"] = config.ssid; doc["p"] = config.password; doc["l"] = config.num_leds; doc["n"] = config.name; // Serialize JSON zu Datei if (serializeJson(doc, file) == 0) { DEBUG_PRINTLN(F("Failed to write to file")); } // Schließe die Datei file.close(); } void loadConfig(const char *filename, Config &config) { File file = SPIFFS.open(filename, "r"); StaticJsonDocument<500> doc; DeserializationError error = deserializeJson(doc, file); if (error) { DEBUG_PRINTLN(F("Datei lesen fehlgeschlagen, nutze Standart Configuration")); DEBUG_PRINTLN(error.c_str()); } config.num_leds = doc["l"] | 30; strlcpy(config.ssid, doc["w"] | "", sizeof(config.ssid)); strlcpy(config.password, doc["p"] | "", sizeof(config.password)); // TODO: Nutze ESP.getChipID strlcpy(config.name, doc["n"] | type, sizeof(config.name)); file.close(); } void printFile(const char *filename) { // Datei öffnen zum lesen File file = SPIFFS.open(filename, "r"); if (!file) { DEBUG_PRINTLN(F("Daten lesen fehlgeschlagen")); return; } // Schreibe jeden Charakter einzeln while (file.available()) { DEBUG_PRINT((char)file.read()); } DEBUG_PRINTLN(); // Schließe die Datei file.close(); } void getversionURL() { server.send(200, "application/plain", versionURL); } void getSettings() { // { // "e": [ // { // "t": "i", // "mn": "1", // "mx": "999", // "n": "Led Anzahl", // "e":"l" // }, // { // "t": "s", // "mn": "4", // "mx": "64", // "n": "Name", // "e":"n" // } // ] // } const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(1) + 2 * JSON_OBJECT_SIZE(5); DynamicJsonDocument doc(capacity); JsonArray e = doc.createNestedArray("e"); JsonObject e_0 = e.createNestedObject(); e_0["t"] = "i"; e_0["mn"] = "1"; e_0["mx"] = "999"; e_0["n"] = "Led Anzahl"; e_0["e"] = "l"; JsonObject e_1 = e.createNestedObject(); e_1["t"] = "s"; e_1["mn"] = "4"; e_1["mx"] = "64"; e_1["n"] = "Name"; e_1["e"] = "n"; server.send(200, "application/json", doc.as<String>()); } void getStatus() { const size_t bufferSize = JSON_OBJECT_SIZE(11) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(14) + JSON_ARRAY_SIZE(2); StaticJsonDocument<bufferSize> abra; // create JSON JsonObject root = abra.to<JsonObject>(); root["id"] = ESP.getChipId(); root["version"] = version; root["free_heap"] = ESP.getFreeHeap(); root["sdk_version"] = ESP.getSdkVersion(); root["boot_version"] = ESP.getBootVersion(); root["boot_mode"] = ESP.getBootMode(); root["vcc"] = ESP.getVcc() / 1024.00; root["cpu_freq"] = ESP.getCpuFreqMHz(); root["sketch_size"] = ESP.getSketchSize(); root["sketch_free_space"] = ESP.getFreeSketchSpace(); JsonObject flash_chip = root.createNestedObject("flash_chip"); flash_chip["id"] = ESP.getFlashChipId(); flash_chip["size"] = ESP.getFlashChipSize(); flash_chip["real_size"] = ESP.getFlashChipRealSize(); flash_chip["speed"] = ESP.getFlashChipSpeed(); FlashMode_t flashChipMode = ESP.getFlashChipMode(); if (flashChipMode == FM_QIO) flash_chip["mode"] = "qio"; else if (flashChipMode == FM_QOUT) flash_chip["mode"] = "qout"; else if (flashChipMode == FM_DIO) flash_chip["mode"] = "dio"; else if (flashChipMode == FM_DOUT) flash_chip["mode"] = "dout"; else if (flashChipMode == FM_UNKNOWN) flash_chip["mode"] = "unknown"; JsonObject wifi = root.createNestedObject("wifi"); wifi["mac"] = WiFi.macAddress(); wifi["ssid"] = WiFi.SSID(); wifi["bssid"] = WiFi.BSSIDstr(); wifi["rssi"] = WiFi.RSSI(); wifi["channel"] = WiFi.channel(); WiFiMode_t wifiMode = WiFi.getMode(); if (wifiMode == WIFI_OFF) wifi["mode"] = "off"; else if (wifiMode == WIFI_STA) wifi["mode"] = "sta"; else if (wifiMode == WIFI_AP) wifi["mode"] = "ap"; else if (wifiMode == WIFI_AP_STA) wifi["mode"] = "ap_sta"; WiFiPhyMode_t wifiPhyMode = WiFi.getPhyMode(); if (wifiPhyMode == WIFI_PHY_MODE_11B) wifi["phy_mode"] = "11b"; else if (wifiPhyMode == WIFI_PHY_MODE_11G) wifi["phy_mode"] = "11g"; else if (wifiPhyMode == WIFI_PHY_MODE_11N) wifi["phy_mode"] = "11n"; WiFiSleepType_t wifiSleepMode = WiFi.getSleepMode(); if (wifiSleepMode == WIFI_NONE_SLEEP) wifi["sleep_mode"] = "none"; else if (wifiSleepMode == WIFI_LIGHT_SLEEP) wifi["sleep_mode"] = "light"; else if (wifiSleepMode == WIFI_MODEM_SLEEP) wifi["sleep_mode"] = "modem"; wifi["persistent"] = WiFi.getPersistent(); wifi["ip"] = WiFi.localIP().toString(); wifi["hostname"] = WiFi.hostname(); wifi["subnet_mask"] = WiFi.subnetMask().toString(); wifi["gateway_ip"] = WiFi.gatewayIP().toString(); JsonArray dns = wifi.createNestedArray("dns"); dns.add(WiFi.dnsIP(0).toString()); dns.add(WiFi.dnsIP(1).toString()); // send response String response; response += abra.as<String>(); server.send(200, "application/json", response); } void getversion() { server.send(200, "application/plain", version); } void restart() { server.send(200, "application/plain", "OK"); delay(100); ESP.restart(); } void v404() { String message = "False URL\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); }
25.972752
117
0.570027
7h3730B
34f585b51562fd7b18ca96b9ac20b6bba8799f2c
1,570
hh
C++
mcg/src/external/BSR/include/concurrent/threads/synchronization/locks/auto_read_lock.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
392
2015-01-14T13:19:40.000Z
2022-02-12T08:47:33.000Z
mcg/src/external/BSR/include/concurrent/threads/synchronization/locks/auto_read_lock.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
45
2015-02-03T12:16:10.000Z
2022-03-07T00:25:09.000Z
mcg/src/external/BSR/include/concurrent/threads/synchronization/locks/auto_read_lock.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
168
2015-01-05T02:29:53.000Z
2022-02-22T04:32:04.000Z
/* * Auto read lock. * * An auto_read_lock takes a read lock on a synchronizable object when * constructed and releases the read lock when destructed. */ #ifndef CONCURRENT__THREADS__SYNCHRONIZATION__LOCKS__AUTO_READ_LOCK_HH #define CONCURRENT__THREADS__SYNCHRONIZATION__LOCKS__AUTO_READ_LOCK_HH namespace concurrent { namespace threads { namespace synchronization { namespace locks { /* * Auto read lock. */ template <typename Syn> class auto_read_lock { public: /* * Constructor. * Acquire read lock on the given object. */ explicit inline auto_read_lock(Syn&); /* * Copy constructor. * Copying an auto read lock invokes another read lock on the object. */ explicit inline auto_read_lock(const auto_read_lock&); /* * Destructor. * Release read lock. */ inline ~auto_read_lock(); protected: Syn& _s; /* synchronizable object */ }; /* * Constructor. * Acquire read lock on the given object. */ template <typename Syn> inline auto_read_lock<Syn>::auto_read_lock(Syn& s) : _s(s) { _s.read_lock(); } /* * Copy constructor. * Copying an auto read lock invokes another read lock on the object. */ template <typename Syn> inline auto_read_lock<Syn>::auto_read_lock(const auto_read_lock& l) : _s(l._s) { _s.read_lock(); } /* * Destructor. * Release read lock. */ template <typename Syn> inline auto_read_lock<Syn>::~auto_read_lock() { _s.read_unlock(); } } /* namespace locks */ } /* namespace synchronization */ } /* namespace threads */ } /* namespace concurrent */ #endif
19.625
72
0.699363
mouthwater
34f7d6ad3c594eb56a275d607fd7e21b5481a92f
45
cpp
C++
6.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
6.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
6.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
// // Created by sunguoyan on 2017/2/27. //
9
37
0.6
Sherryhaha
5a5568b8b9972a0e9d452be5e4276b692ba7d335
2,660
cpp
C++
render/Mesh.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
6
2019-01-25T08:41:14.000Z
2021-08-22T07:06:11.000Z
render/Mesh.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
null
null
null
render/Mesh.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
3
2019-01-25T08:41:16.000Z
2020-09-04T06:04:29.000Z
// // Created by huangkun on 04/04/2018. // #include "Mesh.h" using namespace std; Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, const std::vector<Texture> &textures) { _vertices = vertices; _indices = indices; _textures = textures; } Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, const std::vector<Texture2D *> &textures) { _vertices = vertices; _indices = indices; _texture2Ds = textures; } Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices) { _vertices = vertices; _indices = indices; } Mesh::Mesh(const std::vector<Vertex> &vertices) { _vertices = vertices; } void Mesh::setupMesh() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ARRAY_BUFFER, _vertices.size() * sizeof(Vertex), &_vertices[0], GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size() * sizeof(unsigned int), &_indices[0], GL_STATIC_DRAW); // vertex positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *) 0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *) offsetof( Vertex, normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *) offsetof( Vertex, texCoords)); glBindVertexArray(0); } void Mesh::draw(Shader &shader) { unsigned int diffuseNr = 1; unsigned int specularNr = 1; for (unsigned int i = 0; i < _textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // activate proper texture unit before binding // retrieve texture number (the N in diffuse_textureN) stringstream ss; string number; string name = _textures[i].type; if (name == "texture_diffuse") ss << diffuseNr++; // transfer unsigned int to stream else if (name == "texture_specular") ss << specularNr++; // transfer unsigned int to stream number = ss.str(); shader.setFloat(("material." + name + number).c_str(), i); glBindTexture(GL_TEXTURE_2D, _textures[i].id); } // draw mesh glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); } Mesh::~Mesh() { }
30.930233
112
0.659023
kunka
5a57ec1f0537267968c18b7300a5bb8d5f64792b
6,944
cpp
C++
examples/get-started/Vegg_BLE_DW/components/arduino/libraries/Painless_Mesh/src/painlessMeshAP.cpp
Techtesh/dwranging
3233947d7b91a8bf1b9d17417d0ae4e22689a865
[ "Apache-2.0" ]
null
null
null
examples/get-started/Vegg_BLE_DW/components/arduino/libraries/Painless_Mesh/src/painlessMeshAP.cpp
Techtesh/dwranging
3233947d7b91a8bf1b9d17417d0ae4e22689a865
[ "Apache-2.0" ]
null
null
null
examples/get-started/Vegg_BLE_DW/components/arduino/libraries/Painless_Mesh/src/painlessMeshAP.cpp
Techtesh/dwranging
3233947d7b91a8bf1b9d17417d0ae4e22689a865
[ "Apache-2.0" ]
null
null
null
// // painlessMeshAP.cpp // // // Created by Bill Gray on 7/26/16. // // #include <Arduino.h> #include "painlessMesh.h" extern "C" { #include <esp_wifi.h> } extern painlessMesh* staticThis; extern HardwareSerial Serial_log; extern HardwareSerial Serial_com; extern HardwareSerial BLE_log; // AP functions //*********************************************************************** void ICACHE_FLASH_ATTR painlessMesh::apInit(void) { if(!isRoot()) { _apIp = IPAddress(192,168,our_node.level,1); IPAddress new_ip(192,168,our_node.level,255); staticThis->loIp = new_ip; }else { _apIp = IPAddress(192,168,169,1); IPAddress new_ip(192,168,169,255); staticThis->loIp = new_ip; } IPAddress netmask(255,255,255,0); WiFi.softAPConfig(_apIp, _apIp, netmask); String new_wifi_ssid = _meshSSID; if(isRoot()) our_node.level = 0; if(staticThis->temporary_mode) new_wifi_ssid += "%"+String(100+staticThis->our_node.level); else new_wifi_ssid += "%"+String(staticThis->our_node.level); WiFi.softAP(new_wifi_ssid.c_str(), _meshPassword.c_str(), _meshChannel); // beginTalk(false); // delay(5); // beginTalk(true); // if(staticThis->_tcpListener == NULL) // tcpServerInit(); Serial_log.println("APINIT:::ADVT STARTED\n"+new_wifi_ssid); } IPAddress ICACHE_FLASH_ATTR painlessMesh::getAPIP() { return _apIp; } //*********************************************************************** void ICACHE_FLASH_ATTR painlessMesh::tcpServerInit() { // Serial_log.println("In here tcpServerInit"); // debugMsg(GENERAL, "tcpServerInit():\n"); // _tcpListener = new AsyncServer(_meshPort); // // _tcpListener->setNoDelay(true); // _tcpListener->onClient([](void * arg, AsyncClient *client){ // uint32_t nodeId_to_be; // bool is_founded = false; // staticThis->client123 = client; // staticThis->debugMsg(REMOTE, "New AP connection incoming\n"); // Serial_log.println("Ahiya pohchtu j nathi"); // wifi_sta_list_t sta_list; // esp_wifi_ap_get_sta_list(&sta_list); // tcpip_adapter_sta_list_t tcpip_sta_list; // ESP_ERROR_CHECK(tcpip_adapter_get_sta_list(&sta_list,&tcpip_sta_list)); // uint8_t final_d_level = 0; // for (int i = 0; i < tcpip_sta_list.num; i++) // { // if(IPAddress(tcpip_sta_list.sta[i].ip.addr) == client->remoteIP()) // { // // // Serial_log.print("IP ADDRESS ISS:::::"); // // // Serial_log.println(IPAddress(tcpip_sta_list.sta[i].ip.addr)); // // // Serial_log.print("SECOND IP ADDRESS ISS:::::"); // // // Serial_log.println(client->remoteIP()); // // nodeId_to_be = (staticThis->encodeNodeId(tcpip_sta_list.sta[i].mac))+1; // // is_founded = staticThis->sta_present(nodeId_to_be,client); // // staticThis->done_check(nodeId_to_be); // // if(!is_founded){ // // Serial_log.println("onClient():nodeId_to_be"+String(nodeId_to_be)); // // auto conn = std::make_shared<MeshConnection>(client, staticThis, false); // // conn->nodeId = nodeId_to_be; // // staticThis->_connections.push_back(conn); // // struct ap_sta_nodes new_node; // // new_node.nodeId = nodeId_to_be; // // new_node.d_level = staticThis->s_level+1; // s_level keeps tracking number of child node connected to us.. // // final_d_level = new_node.d_level; // // bool is_node_founded = false; // // for(auto && var:staticThis->ap_sta_nodes_list) // // { // // if(var.nodeId == nodeId_to_be) // // { // // is_node_founded = true; // // final_d_level = var.d_level; // jo koi child node pelethi connected hoi to enu s_level update karvani jarur nathi to je junu hatu e j java devanu // // staticThis->start_ap_timer_for_root(); // // staticThis->force_sta_check(); // // break; // // } // // } // // if(!is_node_founded) // // staticThis->ap_sta_nodes_list.push_back(new_node); // // } // // // Serial_log.println("pachi Ahiya pohchtu j nathi::"+String((uint32_t)(conn))); // // String new_node_json = "{\"t_m\":\""+String(staticThis->temporary_mode)+"\",\"pi\":"+String(staticThis->_nodeId)+",\"nid\":"+String(nodeId_to_be)+",\"le\":"+String((staticThis->our_node.level+1))+",\"s_l\":"+String((final_d_level))+",\"s\":"+String(staticThis->temporary_mode?staticThis->temporary_network_node_list.size():staticThis->network_node_list.size())+",\"data\":["; // // for(auto && var:staticThis->temporary_mode?staticThis->temporary_network_node_list:staticThis->network_node_list){ // // new_node_json += "{\"p\":"+String(var.parentId)+",\"l\":"+String(var.level)+",\"n\":"+String(var.nodeId)+",\"m\":\""+(var.mac)+"\",\"s_l\":\""+(var.s_level)+"\",\"st\":\""+(var.status)+"\"}"; // // new_node_json += ","; // // } // // if(staticThis->temporary_mode?staticThis->temporary_network_node_list.size()>0:staticThis->network_node_list.size()>0 ) // // new_node_json.remove(new_node_json.length()-1); // // new_node_json += "]}"; // // size_t buff_size = new_node_json.length()+1; // // char buff_char[buff_size]; // // new_node_json.toCharArray(buff_char,buff_size); // // Serial_log.print("In here node send list..."); // // Serial_log.println(buff_char); // // Serial_log.println(">>>>>>>>>>>>"); // // staticThis->sendSingleB(nodeId_to_be,NODE_LIST_ASSIGN,(uint8_t*)buff_char,buff_size); // // staticThis->sort_ap_sta_list(); // // Serial_log.println(">>>>>>"); // break; // } // // memcpy(tcpip_sta_list->sta[i].mac, wifi_sta_list->sta[i].mac, 6); // // dhcp_search_ip_on_mac(tcpip_sta_list->sta[i].mac, &tcpip_sta_list->sta[i].ip); // } // }, NULL); // _tcpListener->begin(); // debugMsg(STARTUP, "AP tcp server established on port %d\n", _meshPort); // return; } void ICACHE_FLASH_ATTR painlessMesh::stop_tcp_server(){ // if(_tcpListener!=NULL) // { // _tcpListener->end(); // _tcpListener = NULL; // } // getSum(); }
44.8
397
0.539747
Techtesh
5a586c0f37641816648c3e0a7e70ad8fdb728715
9,123
cpp
C++
msqlquery-demo/msqlquery/msqldatabase.cpp
Opostol/MSqlQuery
67cdfde4b1d94f1c5aff7fc6017e967d492fc3a2
[ "Unlicense" ]
6
2017-04-22T14:10:54.000Z
2021-11-02T20:24:02.000Z
msqlquery-demo/msqlquery/msqldatabase.cpp
Opostol/MSqlQuery
67cdfde4b1d94f1c5aff7fc6017e967d492fc3a2
[ "Unlicense" ]
1
2018-07-11T17:52:50.000Z
2018-08-22T18:44:35.000Z
msqlquery-demo/msqlquery/msqldatabase.cpp
Opostol/MSqlQuery
67cdfde4b1d94f1c5aff7fc6017e967d492fc3a2
[ "Unlicense" ]
1
2018-07-11T11:16:32.000Z
2018-07-11T11:16:32.000Z
#include "msqldatabase.h" #include "qthreadutils.h" #include "msqlthread.h" #include <QSqlDatabase> #include <QStringList> #include <QSqlDriver> #include <QDebug> #include <QReadWriteLock> #include <QWriteLocker> #include <QReadLocker> #include <QGlobalStatic> #include <QCoreApplication> const QString MSqlDatabase::defaultConnectionName(QString(QSqlDatabase::defaultConnection)+"_msqlquery_default"); struct MSqlConnections { QHash<QString, MSqlThread*> dict; bool isPostRoutineAdded = false; mutable QReadWriteLock lock; }; Q_GLOBAL_STATIC(MSqlConnections, getMSqlConnections) static void MSqlCleanup() { //must be called before QSqlDatabase cleanup routine //so, it must be added after QSqlDatabase MSqlConnections* connections = getMSqlConnections(); QWriteLocker locker(&connections->lock); //destruct all connection's threads //this causes calling thread to block until all threads are terminated for(auto i = connections->dict.begin(); i!=connections->dict.end(); ++i) delete i.value(); //make sure any of the threads getting destructed do not attempt to access //MSqlConnections because this will cause a deadlock connections->dict.clear(); } MSqlDatabase::MSqlDatabase() { } MSqlDatabase::~MSqlDatabase() { } MSqlDatabase MSqlDatabase::addDatabase(const QString &type, const QString &connectionName) { MSqlDatabase db; db.m_connectionName = connectionName; MSqlConnections* connections = getMSqlConnections(); QWriteLocker locker(&connections->lock); Q_UNUSED(locker) if(connections->dict.contains(connectionName)){ //destruct and remove old connection if one already exists delete connections->dict.value(connectionName); connections->dict.remove(connectionName); } //create new thread for connection MSqlThread* thread = new MSqlThread(); connections->dict.insert(connectionName, thread); //create database connection in newly created thread CallByWorker(thread->getWorker(), [=]{ QSqlDatabase::addDatabase(type, connectionName); }); if(!connections->isPostRoutineAdded){ //if post routine not registered //register post routine after calling QSqlDatabase::addDatabase //since postRoutines are called in reverse order of their addition qAddPostRoutine(MSqlCleanup); connections->isPostRoutineAdded= true; } return db; } MSqlDatabase MSqlDatabase::database(const QString &connectionName) { MSqlDatabase db; db.m_connectionName = connectionName; return db; } void MSqlDatabase::setHostName(const QString &host) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setHostName(host); }); } void MSqlDatabase::setDatabaseName(const QString &name) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setDatabaseName(name); }); } void MSqlDatabase::setUserName(const QString &name) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setUserName(name); }); } void MSqlDatabase::setPassword(const QString& password) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setPassword(password); }); } void MSqlDatabase::setConnectionOptions(const QString &options) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setConnectOptions(options); }); } void MSqlDatabase::setPort(int port) { QString connectionName = m_connectionName; PostToWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false) .setPort(port); }); } QString MSqlDatabase::hostName() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).hostName(); }); } QString MSqlDatabase::databaseName() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).databaseName(); }); } QString MSqlDatabase::userName() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).userName(); }); } QString MSqlDatabase::password() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).password(); }); } QString MSqlDatabase::connectionOptions() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).connectOptions(); }); } int MSqlDatabase::port() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).port(); }); } bool MSqlDatabase::transaction() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).transaction(); }); } bool MSqlDatabase::commit() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).commit(); }); } bool MSqlDatabase::rollback() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).rollback(); }); } QSqlError MSqlDatabase::lastError()const { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).lastError(); }); } bool MSqlDatabase::open() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).open(); }); } void MSqlDatabase::close() { QString connectionName = m_connectionName; CallByWorker(workerForConnection(connectionName), [=]{ QSqlDatabase::database(connectionName, false).close(); }); } bool MSqlDatabase::isOpen()const { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).isOpen(); }); } bool MSqlDatabase::isOpenError()const { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).isOpenError(); }); } bool MSqlDatabase::isValid()const { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).isValid(); }); } bool MSqlDatabase::subscribeToNotification(const QString &name) { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).driver()->subscribeToNotification(name); }); } QStringList MSqlDatabase::subscribedToNotifications()const { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).driver()->subscribedToNotifications(); }); } bool MSqlDatabase::unsubscribeFromNotification(const QString &name) { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).driver()->unsubscribeFromNotification(name); }); } const QSqlDriver *MSqlDatabase::driver() { QString connectionName = m_connectionName; return CallByWorker(workerForConnection(connectionName), [=]{ return QSqlDatabase::database(connectionName, false).driver(); }); } MSqlThread* MSqlDatabase::threadForConnection(QString connectionName) { MSqlConnections* connections = getMSqlConnections(); QReadLocker locker(&connections->lock); return connections->dict.value(connectionName, nullptr); } QObject* MSqlDatabase::workerForConnection(QString connectionName) { return threadForConnection(connectionName)->getWorker(); }
33.914498
113
0.726515
Opostol
5a5af17e4a33fe660465020bd1be228aa45d11b6
1,916
c++
C++
LeetCode/Add Two Numbers - Medium.c++
ammar-sayed-taha/problem-solving
9677a738c0cc30078f6450f40fcc26ba2a379a8b
[ "MIT" ]
1
2020-02-20T00:04:54.000Z
2020-02-20T00:04:54.000Z
LeetCode/Add Two Numbers - Medium.c++
ammar-sayed-taha/Problem-Solving
c3ef98b8b0ebfbcc31d45990822b81a9dc549fe8
[ "MIT" ]
null
null
null
LeetCode/Add Two Numbers - Medium.c++
ammar-sayed-taha/Problem-Solving
c3ef98b8b0ebfbcc31d45990822b81a9dc549fe8
[ "MIT" ]
null
null
null
/** * assume N: length of list1 and M: length of list 2 * Time Complex :O(N) where N >= M * Space Complexity: O(N) where N >= M */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode * zeroNode = new ListNode(0); string num1 = getNums(l1); string num2 = getNums(l2); string sum = sumLists(num1, num2); // create sumList to sum two numbers bacasue of overflow numbers if((sum.length() == 1 && sum[0] == '0' && num1.length() == 1) || (sum.length() == 1 && sum[0] == '0' && num2.length() == 1)) return zeroNode; // if input is l1=[0] or l2=[0] return buildTree(sum, sum.length()-1); } // get numbers from linked list into string string getNums(ListNode * node){ if(!node) return ""; return getNums(node->next) + to_string(node->val); } // build tree of string of numbers ListNode * buildTree(string sum, int index){ if(index < 0) return NULL; ListNode * node = new ListNode(int(sum[index] - 48)); node->next = buildTree(sum, index-1); return node; } // sum two string numbers string sumLists(string num1, string num2){ int len1 = num1.length(); int len2 = num2.length(); int index1 = len1-1, index2 = len2-1; string result = ""; int ch1,ch2, carry=0; while(index1 > -1 || index2 > -1){ if(index1 > -1) ch1 = num1[index1--] - 48; else ch1 = 0; if(index2 > -1) ch2 = num2[index2--] - 48; else ch2 = 0; int num = ch1+ch2+carry; if(num>9){ carry=1; num-=10; }else carry = 0; result = to_string(num) + result; } if(carry) result = to_string(carry) + result; return result; } };
29.030303
120
0.516701
ammar-sayed-taha
5a67a2b24c1e32c44c4b8219c6cd3c247060afe4
6,465
hpp
C++
simulation/libsimulator/include/simulator/function.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/include/simulator/function.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/include/simulator/function.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017, Arvid Norberg All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SIMULATOR_FUNCTION_HPP_INCLUDED #define SIMULATOR_FUNCTION_HPP_INCLUDED #include <utility> #include <memory> // for allocator_traits #include "simulator/mallocator.hpp" namespace sim { namespace aux { template <typename T, typename U> T exchange_(T& var, U&& new_val) { T temp = std::move(var); var = std::forward<U>(new_val); return temp; } template <typename T, typename Fun> T* allocate_handler(Fun h) { using alloc = typename boost::asio::associated_allocator<typename std::remove_reference<Fun>::type>::type; using our_alloc = typename std::allocator_traits<alloc>::template rebind_alloc<T>; our_alloc al(boost::asio::get_associated_allocator(h)); void* ptr = al.allocate(1); if (ptr == nullptr) throw std::bad_alloc(); try { return new (ptr) T(std::move(h)); } catch (...) { al.deallocate(reinterpret_cast<T*>(ptr), 1); throw; } } // this is a std::function-like class that supports move-only function // objects template <typename R, typename... A> struct callable { using call_fun_t = R (*)(void*, A&&...); using deallocate_fun_t = void (*)(void*); call_fun_t call_fun; deallocate_fun_t deallocate_fun; }; template <typename Handler, typename R, typename... A> R call_impl(void* mem, A&&... a); template <typename Handler, typename R, typename... A> void dealloc_impl(void* mem); template <typename Handler, typename R, typename... A> struct function_impl : callable<R, A...> { function_impl(Handler h) : handler(std::move(h)) { this->call_fun = call_impl<Handler, R, A&&...>; this->deallocate_fun = dealloc_impl<Handler, R, A&&...>; } Handler handler; }; template <typename Handler, typename R, typename... A> R call_impl(void* mem, A&&... a) { auto* obj = static_cast<function_impl<Handler, R, A...>*>(mem); Handler handler = std::move(obj->handler); obj->~function_impl(); using alloc = typename boost::asio::associated_allocator<Handler>::type; using our_alloc = typename std::allocator_traits<alloc>:: template rebind_alloc<typename std::remove_reference<decltype(*obj)>::type>; our_alloc al(boost::asio::get_associated_allocator(handler)); al.deallocate(obj, 1); return handler(std::forward<A>(a)...); } template <typename Handler, typename R, typename... A> void dealloc_impl(void* mem) { auto* obj = static_cast<function_impl<Handler, R, A...>*>(mem); Handler h = std::move(obj->handler); obj->~function_impl(); using alloc = typename boost::asio::associated_allocator<Handler>::type; using our_alloc = typename std::allocator_traits<alloc>:: template rebind_alloc<typename std::remove_reference<decltype(*obj)>::type>; our_alloc al(boost::asio::get_associated_allocator(h)); al.deallocate(obj, 1); } template <typename Fun> struct function; template <typename R, typename... A> struct function<R(A...)> { using result_type = R; using allocator_type = aux::mallocator<R(A...)>; allocator_type get_allocator() const { return allocator_type{}; } template <typename C> function(C c) : m_callable(allocate_handler<function_impl<C, R, A...>>(std::move(c))) {} function(function&& other) noexcept : m_callable(exchange_(other.m_callable, nullptr)) {} function& operator=(function&& other) noexcept { if (&other == this) return *this; clear(); m_callable = exchange_(other.m_callable, nullptr); return *this; } ~function() { clear(); } // boost.asio requires handlers to be copy-constructible, but it will move // them, if they're movable. So we trick asio into accepting this handler. // If it attempts to copy, it will cause a link error function(function const&) { assert(false && "functions should not be copied"); } function& operator=(function const&) = delete; function() = default; explicit operator bool() const { return m_callable != nullptr; } function& operator=(std::nullptr_t) { clear(); return *this; } void clear() { if (m_callable == nullptr) return; auto fun = m_callable->deallocate_fun; fun(m_callable); m_callable = nullptr; } template <typename... Args> R operator()(Args&&... a) { assert(m_callable); auto fun = m_callable->call_fun; return fun(exchange_(m_callable, nullptr), std::forward<A>(a)...); } private: callable<R, A...>* m_callable = nullptr; }; // index sequence, to unpack tuple template<std::size_t...> struct seq {}; template<std::size_t N, std::size_t... S> struct gens : gens<N-1, N-1, S...> {}; template<std::size_t... S> struct gens<0, S...> { using type = seq<S...>; }; // a binder for move-only types, and movable arguments. It's not a general // binder as it doesn't support partial application, it just binds all // arguments and ignores any arguments passed to the call template <typename Callable, typename R, typename... A> struct move_binder { move_binder(Callable c, A&&... a) : m_args(std::move(a)...) , m_callable(std::move(c)) {} move_binder(move_binder const&) = delete; move_binder& operator=(move_binder const&) = delete; move_binder(move_binder&&) = default; move_binder& operator=(move_binder&&) = default; // ignore any arguments passed in. This is used to ignore an error_code // argument for instance template <typename... Args> R operator()(Args...) { return call(typename gens<sizeof...(A)>::type()); } private: template<std::size_t... I> R call(seq<I...>) { return m_callable(std::move(std::get<I>(m_args))...); } std::tuple<A...> m_args; Callable m_callable; }; template <typename R, typename C, typename... A> move_binder<C, R, A...> move_bind(C c, A&&... a) { return move_binder<C, R, A...>(std::move(c), std::forward<A>(a)...); } } } #endif
29.253394
108
0.682289
SylemST-UtilCollection
5a6ace6c23e91d6a1108a30f4a3c1b0b09114333
3,351
cpp
C++
android-29/android/media/ThumbnailUtils.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/media/ThumbnailUtils.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/media/ThumbnailUtils.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../graphics/Bitmap.hpp" #include "../os/CancellationSignal.hpp" #include "../util/Size.hpp" #include "../../java/io/File.hpp" #include "../../JString.hpp" #include "./ThumbnailUtils.hpp" namespace android::media { // Fields jint ThumbnailUtils::OPTIONS_RECYCLE_INPUT() { return getStaticField<jint>( "android.media.ThumbnailUtils", "OPTIONS_RECYCLE_INPUT" ); } // QJniObject forward ThumbnailUtils::ThumbnailUtils(QJniObject obj) : JObject(obj) {} // Constructors ThumbnailUtils::ThumbnailUtils() : JObject( "android.media.ThumbnailUtils", "()V" ) {} // Methods android::graphics::Bitmap ThumbnailUtils::createAudioThumbnail(JString arg0, jint arg1) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createAudioThumbnail", "(Ljava/lang/String;I)Landroid/graphics/Bitmap;", arg0.object<jstring>(), arg1 ); } android::graphics::Bitmap ThumbnailUtils::createAudioThumbnail(java::io::File arg0, android::util::Size arg1, android::os::CancellationSignal arg2) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createAudioThumbnail", "(Ljava/io/File;Landroid/util/Size;Landroid/os/CancellationSignal;)Landroid/graphics/Bitmap;", arg0.object(), arg1.object(), arg2.object() ); } android::graphics::Bitmap ThumbnailUtils::createImageThumbnail(JString arg0, jint arg1) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createImageThumbnail", "(Ljava/lang/String;I)Landroid/graphics/Bitmap;", arg0.object<jstring>(), arg1 ); } android::graphics::Bitmap ThumbnailUtils::createImageThumbnail(java::io::File arg0, android::util::Size arg1, android::os::CancellationSignal arg2) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createImageThumbnail", "(Ljava/io/File;Landroid/util/Size;Landroid/os/CancellationSignal;)Landroid/graphics/Bitmap;", arg0.object(), arg1.object(), arg2.object() ); } android::graphics::Bitmap ThumbnailUtils::createVideoThumbnail(JString arg0, jint arg1) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createVideoThumbnail", "(Ljava/lang/String;I)Landroid/graphics/Bitmap;", arg0.object<jstring>(), arg1 ); } android::graphics::Bitmap ThumbnailUtils::createVideoThumbnail(java::io::File arg0, android::util::Size arg1, android::os::CancellationSignal arg2) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "createVideoThumbnail", "(Ljava/io/File;Landroid/util/Size;Landroid/os/CancellationSignal;)Landroid/graphics/Bitmap;", arg0.object(), arg1.object(), arg2.object() ); } android::graphics::Bitmap ThumbnailUtils::extractThumbnail(android::graphics::Bitmap arg0, jint arg1, jint arg2) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "extractThumbnail", "(Landroid/graphics/Bitmap;II)Landroid/graphics/Bitmap;", arg0.object(), arg1, arg2 ); } android::graphics::Bitmap ThumbnailUtils::extractThumbnail(android::graphics::Bitmap arg0, jint arg1, jint arg2, jint arg3) { return callStaticObjectMethod( "android.media.ThumbnailUtils", "extractThumbnail", "(Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap;", arg0.object(), arg1, arg2, arg3 ); } } // namespace android::media
28.398305
148
0.723963
YJBeetle
5a7d6fa149f270feb0ba867fbaa92235678f9430
534
cpp
C++
Youtube/Not_using_namespace_std.cpp
lance-lh/learning-c-plusplus
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
[ "MIT" ]
1
2019-03-27T13:00:02.000Z
2019-03-27T13:00:02.000Z
Youtube/Not_using_namespace_std.cpp
lance-lh/learning-c-plusplus
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
[ "MIT" ]
null
null
null
Youtube/Not_using_namespace_std.cpp
lance-lh/learning-c-plusplus
90342cc5d26a5adb87aa3e97795d4bbfca7bef52
[ "MIT" ]
1
2021-01-12T22:01:28.000Z
2021-01-12T22:01:28.000Z
#include<iostream> #include<string> namespace apple // it needs implicit conversion { void print(const std::string& text) { std::cout << text << std::endl; } } namespace orrange // if both exist, this one is a better choice { void print(const char* text) { std::string temp = text; std::reverse(temp.begin(), temp.end()); std::cout << temp << std::endl; } } using namespace apple; using namespace orrange; int main() { print("Hello!"); // "Hello" is a const char array, actually not string std::cin.get(); }
17.8
72
0.653558
lance-lh
5a83c0f2ac4d959c3a272ce53ae258398212f0ab
8,003
cpp
C++
src/utils/vmpi_private/mysql_wrapper/mysql_wrapper.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/utils/vmpi_private/mysql_wrapper/mysql_wrapper.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/utils/vmpi_private/mysql_wrapper/mysql_wrapper.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// // mysql_wrapper.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" extern "C" { #include "mysql.h" }; #include "imysqlwrapper.h" #include <stdio.h> static char *CopyString(const char *pStr) { if (!pStr) { pStr = ""; } char *pRet = new char[strlen(pStr) + 1]; strcpy(pRet, pStr); return pRet; } BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } class CCopiedRow { public: ~CCopiedRow() { m_Columns.PurgeAndDeleteElements(); } CUtlVector<char *> m_Columns; }; class CMySQLCopiedRowSet : public IMySQLRowSet { public: ~CMySQLCopiedRowSet() { m_Rows.PurgeAndDeleteElements(); m_ColumnNames.PurgeAndDeleteElements(); } virtual void Release() { delete this; } virtual int NumFields() { return m_ColumnNames.Count(); } virtual const char *GetFieldName(int iColumn) { return m_ColumnNames[iColumn]; } virtual bool NextRow() { ++m_iCurRow; return m_iCurRow < m_Rows.Count(); } virtual bool SeekToFirstRow() { m_iCurRow = 0; return m_iCurRow < m_Rows.Count(); } virtual CColumnValue GetColumnValue(int iColumn) { return CColumnValue(this, iColumn); } virtual CColumnValue GetColumnValue(const char *pColumnName) { return CColumnValue(this, GetColumnIndex(pColumnName)); } virtual const char *GetColumnValue_String(int iColumn) { if (iColumn < 0 || iColumn >= m_ColumnNames.Count()) return "<invalid column specified>"; else if (m_iCurRow < 0 || m_iCurRow >= m_Rows.Count()) return "<invalid row specified>"; else return m_Rows[m_iCurRow]->m_Columns[iColumn]; } virtual long GetColumnValue_Int(int iColumn) { return atoi(GetColumnValue_String(iColumn)); } virtual int GetColumnIndex(const char *pColumnName) { for (int i = 0; i < m_ColumnNames.Count(); i++) { if (stricmp(m_ColumnNames[i], pColumnName) == 0) return i; } return -1; } public: int m_iCurRow; CUtlVector<CCopiedRow *> m_Rows; CUtlVector<char *> m_ColumnNames; }; // -------------------------------------------------------------------------------------------------------- // // CMySQL class. // -------------------------------------------------------------------------------------------------------- // class CMySQL : public IMySQL { public: CMySQL(); virtual ~CMySQL(); virtual bool InitMySQL(const char *pDBName, const char *pHostName, const char *pUserName, const char *pPassword); virtual void Release(); virtual int Execute(const char *pString); virtual IMySQLRowSet *DuplicateRowSet(); virtual unsigned long InsertID(); virtual int NumFields(); virtual const char *GetFieldName(int iColumn); virtual bool NextRow(); virtual bool SeekToFirstRow(); virtual CColumnValue GetColumnValue(int iColumn); virtual CColumnValue GetColumnValue(const char *pColumnName); virtual const char *GetColumnValue_String(int iColumn); virtual long GetColumnValue_Int(int iColumn); virtual int GetColumnIndex(const char *pColumnName); // Cancels the storage of the rows from the latest query. void CancelIteration(); virtual const char *GetLastError(void); public: MYSQL *m_pSQL; MYSQL_RES *m_pResult; MYSQL_ROW m_Row; CUtlVector <MYSQL_FIELD> m_Fields; char m_szLastError[128]; }; EXPOSE_INTERFACE( CMySQL, IMySQL, MYSQL_WRAPPER_VERSION_NAME ); // -------------------------------------------------------------------------------------------------------- // // CMySQL implementation. // -------------------------------------------------------------------------------------------------------- // CMySQL::CMySQL() { m_pSQL = NULL; m_pResult = NULL; m_Row = NULL; } CMySQL::~CMySQL() { CancelIteration(); if (m_pSQL) { mysql_close(m_pSQL); m_pSQL = NULL; } } bool CMySQL::InitMySQL(const char *pDBName, const char *pHostName, const char *pUserName, const char *pPassword) { MYSQL *pSQL = mysql_init(NULL); if (!pSQL) return NULL; if (!mysql_real_connect(pSQL, pHostName, pUserName, pPassword, pDBName, 0, NULL, 0)) { Q_strncpy(m_szLastError, mysql_error(pSQL), sizeof(m_szLastError)); mysql_close(pSQL); return false; } m_pSQL = pSQL; return true; } void CMySQL::Release() { delete this; } int CMySQL::Execute(const char *pString) { CancelIteration(); int result = mysql_query(m_pSQL, pString); if (result == 0) { // Is this a query with a result set? m_pResult = mysql_store_result(m_pSQL); if (m_pResult) { // Store the field information. int count = mysql_field_count(m_pSQL); MYSQL_FIELD *pFields = mysql_fetch_fields(m_pResult); m_Fields.CopyArray(pFields, count); return 0; } else { // No result set. Was a set expected? if (mysql_field_count(m_pSQL) != 0) return 1; // error! The query expected data but didn't get it. } } else { const char *pError = mysql_error(m_pSQL); pError = pError; } return result; } IMySQLRowSet *CMySQL::DuplicateRowSet() { CMySQLCopiedRowSet *pSet = new CMySQLCopiedRowSet; pSet->m_iCurRow = -1; pSet->m_ColumnNames.SetSize(m_Fields.Count()); for (int i = 0; i < m_Fields.Count(); i++) pSet->m_ColumnNames[i] = CopyString(m_Fields[i].name); while (NextRow()) { CCopiedRow *pRow = new CCopiedRow; pSet->m_Rows.AddToTail(pRow); pRow->m_Columns.SetSize(m_Fields.Count()); for (int i = 0; i < m_Fields.Count(); i++) { pRow->m_Columns[i] = CopyString(m_Row[i]); } } return pSet; } unsigned long CMySQL::InsertID() { return mysql_insert_id(m_pSQL); } int CMySQL::NumFields() { return m_Fields.Count(); } const char *CMySQL::GetFieldName(int iColumn) { return m_Fields[iColumn].name; } bool CMySQL::NextRow() { if (!m_pResult) return false; m_Row = mysql_fetch_row(m_pResult); if (m_Row == 0) { return false; } else { return true; } } bool CMySQL::SeekToFirstRow() { if (!m_pResult) return false; mysql_data_seek(m_pResult, 0); return true; } CColumnValue CMySQL::GetColumnValue(int iColumn) { return CColumnValue(this, iColumn); } CColumnValue CMySQL::GetColumnValue(const char *pColumnName) { return CColumnValue(this, GetColumnIndex(pColumnName)); } const char *CMySQL::GetColumnValue_String(int iColumn) { if (m_Row && iColumn >= 0 && iColumn < m_Fields.Count() && m_Row[iColumn]) return m_Row[iColumn]; else return ""; } long CMySQL::GetColumnValue_Int(int iColumn) { return atoi(GetColumnValue_String(iColumn)); } int CMySQL::GetColumnIndex(const char *pColumnName) { for (int i = 0; i < m_Fields.Count(); i++) { if (stricmp(pColumnName, m_Fields[i].name) == 0) { return i; } } return -1; } void CMySQL::CancelIteration() { m_Fields.Purge(); if (m_pResult) { mysql_free_result(m_pResult); m_pResult = NULL; } m_Row = NULL; } const char *CMySQL::GetLastError(void) { // Default to the last error if m_pSQL was not successfully initialized const char *pszLastError = m_szLastError; if (m_pSQL) { pszLastError = mysql_error(m_pSQL); } return pszLastError; }
22.292479
117
0.580782
cstom4994
5a89fff9491c8a42e38cac9520558565357a282b
349
cpp
C++
codeforces/1618A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1618A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1618A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Polycarp and Sums of Subsequences #include <iostream> #include <vector> int main() { int t; std::cin >> t; while (t--) { std::vector<int> b(7); for (auto &el: b) { std::cin >> el; } std::cout << b[0] << ' ' << b[1] << ' ' << b[6] - b[0] - b[1] << std::endl; } return 0; }
15.173913
83
0.415473
sgrade
5a8fe2cb455366de690d7e6aadf8c5030866e7e1
2,107
cpp
C++
Nettitude/Injection/SeDebugPrivilege.cpp
nettitude/DLLInjection
633ce4cc88ef6edb685204e9f3683f8a42962c63
[ "Unlicense" ]
71
2016-09-01T08:52:19.000Z
2022-02-07T11:31:45.000Z
Nettitude/Injection/SeDebugPrivilege.cpp
nettitude/DLLInjection
633ce4cc88ef6edb685204e9f3683f8a42962c63
[ "Unlicense" ]
null
null
null
Nettitude/Injection/SeDebugPrivilege.cpp
nettitude/DLLInjection
633ce4cc88ef6edb685204e9f3683f8a42962c63
[ "Unlicense" ]
31
2016-09-20T10:22:57.000Z
2022-03-30T01:10:32.000Z
/* Copyright (c) 2015, Nettitude 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 Nettitude 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 NETTITUDE 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 "SeDebugPrivilege.h" extern "C" BOOL Inject_SetDebugPrivilege ( ) { BOOL bRet = FALSE; HANDLE hToken = NULL; LUID luid = { 0 }; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) { TOKEN_PRIVILEGES tokenPriv = { 0 }; tokenPriv.PrivilegeCount = 1; tokenPriv.Privileges[0].Luid = luid; tokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; bRet = AdjustTokenPrivileges(hToken, FALSE, &tokenPriv, sizeof(TOKEN_PRIVILEGES), NULL, NULL); } } return bRet; }
39.018519
106
0.755577
nettitude
5a96431c0947c30573b929acaee65c1270686cd4
44,752
cpp
C++
src/ui/mapeditor/map_editor.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/ui/mapeditor/map_editor.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/ui/mapeditor/map_editor.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version 3.9.0 Dec 31 2020) // http://www.wxformbuilder.org/ // // PLEASE DO *NOT* EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "ui/mapeditor/global_topo_editor_widget.h" #include "ui/mapeditor/local_topo_editor_widget.h" #include "ui/mapeditor/metric_editor_widget.h" #include "map_editor.h" /////////////////////////////////////////////////////////////////////////// using namespace vulcan::ui; EditorFrame::EditorFrame(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : UIMainFrame(parent, id, title, pos, size, style) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); wxBoxSizer* mapEditorSizer; mapEditorSizer = new wxBoxSizer(wxVERTICAL); mapEditorNotebook = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_DEFAULT_STYLE); localMetricNotebookPanel = new wxPanel(mapEditorNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer* localMetricPanelSizer; localMetricPanelSizer = new wxBoxSizer(wxHORIZONTAL); metricEditorWidget = new MetricEditorWidget(localMetricNotebookPanel, ID_METRIC_EDITOR_WIDGET, wxDefaultPosition, wxDefaultSize); localMetricPanelSizer->Add(metricEditorWidget, 1, wxALL | wxEXPAND, 5); wxBoxSizer* metricEditorOptionsSizer; metricEditorOptionsSizer = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer* metricMapLoadSizer; metricMapLoadSizer = new wxStaticBoxSizer(new wxStaticBox(localMetricNotebookPanel, wxID_ANY, wxT("Map Options")), wxVERTICAL); loadMetricFromFileButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_LOAD_METRIC_FROM_FILE_BUTTON, wxT("Load From File"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(loadMetricFromFileButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5); captureMetricFromLCMButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_CAPTURE_METRIC_FROM_LCM_BUTTON, wxT("Capture From LCM"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(captureMetricFromLCMButton, 0, wxALL | wxEXPAND, 5); createMetricButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_CREATE_METRIC_BUTTON, wxT("Create Empty"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(createMetricButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5); saveToFileMetricButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_SAVE_TO_FILE_METRIC_BUTTON, wxT("Save To File"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(saveToFileMetricButton, 0, wxALL | wxEXPAND, 5); sendViaLCMMetricButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_SEND_VIA_LCM_METRIC_BUTTON, wxT("Send Via LCM"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(sendViaLCMMetricButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5); importFromImageButton = new wxButton(metricMapLoadSizer->GetStaticBox(), ID_IMPORT_FROM_IMAGE_BUTTON, wxT("Import From Image"), wxDefaultPosition, wxDefaultSize, 0); metricMapLoadSizer->Add(importFromImageButton, 0, wxALL | wxEXPAND, 5); metricEditorOptionsSizer->Add(metricMapLoadSizer, 0, wxEXPAND, 5); wxStaticBoxSizer* cellEditingSizer; cellEditingSizer = new wxStaticBoxSizer(new wxStaticBox(localMetricNotebookPanel, wxID_ANY, wxT("Cell Editing Options")), wxVERTICAL); wxString editCellTypeRadioBoxChoices[] = {wxT("Hazard"), wxT("Quasi-Static"), wxT("Occupied"), wxT("Free"), wxT("Unobserved")}; int editCellTypeRadioBoxNChoices = sizeof(editCellTypeRadioBoxChoices) / sizeof(wxString); editCellTypeRadioBox = new wxRadioBox(cellEditingSizer->GetStaticBox(), ID_EDIT_CELL_TYPE_RADIO_BOX, wxT("Cell Type"), wxDefaultPosition, wxDefaultSize, editCellTypeRadioBoxNChoices, editCellTypeRadioBoxChoices, 1, wxRA_SPECIFY_COLS); editCellTypeRadioBox->SetSelection(0); cellEditingSizer->Add(editCellTypeRadioBox, 0, wxALL | wxEXPAND, 5); cellEditModeButton = new wxToggleButton(cellEditingSizer->GetStaticBox(), ID_CELL_EDIT_MODE_BUTTON, wxT("Edit Cells"), wxDefaultPosition, wxDefaultSize, 0); cellEditingSizer->Add(cellEditModeButton, 0, wxALL | wxEXPAND, 5); wxBoxSizer* lineAndFloodButtonSizer; lineAndFloodButtonSizer = new wxBoxSizer(wxHORIZONTAL); lineEditMetricButton = new wxToggleButton(cellEditingSizer->GetStaticBox(), ID_LINE_EDIT_METRIC_BUTTON, wxT("Line"), wxDefaultPosition, wxDefaultSize, 0); lineAndFloodButtonSizer->Add(lineEditMetricButton, 0, wxALL, 5); floodEditMetricButton = new wxToggleButton(cellEditingSizer->GetStaticBox(), ID_FLOOD_EDIT_METRIC_BUTTON, wxT("Flood"), wxDefaultPosition, wxDefaultSize, 0); lineAndFloodButtonSizer->Add(floodEditMetricButton, 0, wxALL, 5); cellEditingSizer->Add(lineAndFloodButtonSizer, 1, wxEXPAND, 5); wxBoxSizer* editingUndoSaveSizer; editingUndoSaveSizer = new wxBoxSizer(wxHORIZONTAL); undoCellsButton = new wxButton(cellEditingSizer->GetStaticBox(), ID_UNDO_CELLS_BUTTON, wxT("Undo"), wxDefaultPosition, wxDefaultSize, 0); editingUndoSaveSizer->Add(undoCellsButton, 0, wxALL, 5); saveCellsButton = new wxButton(cellEditingSizer->GetStaticBox(), ID_SAVE_CELLS_BUTTON, wxT("Save"), wxDefaultPosition, wxDefaultSize, 0); editingUndoSaveSizer->Add(saveCellsButton, 0, wxALL, 5); cellEditingSizer->Add(editingUndoSaveSizer, 0, 0, 5); metricEditorOptionsSizer->Add(cellEditingSizer, 0, wxEXPAND, 5); localMetricPanelSizer->Add(metricEditorOptionsSizer, 0, wxEXPAND, 5); localMetricNotebookPanel->SetSizer(localMetricPanelSizer); localMetricNotebookPanel->Layout(); localMetricPanelSizer->Fit(localMetricNotebookPanel); mapEditorNotebook->AddPage(localMetricNotebookPanel, wxT("Local Metric"), false, wxNullBitmap); localTopoNotebookPanel = new wxPanel(mapEditorNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer* localTopoPanelSizer; localTopoPanelSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* localTopoWidgetSizer; localTopoWidgetSizer = new wxBoxSizer(wxVERTICAL); localTopoEditorWidget = new LocalTopoEditorWidget(localTopoNotebookPanel, ID_LOCAL_TOPO_EDITOR_WIDGET, wxDefaultPosition, wxDefaultSize); localTopoWidgetSizer->Add(localTopoEditorWidget, 2, wxALL | wxEXPAND, 5); wxBoxSizer* localTopoTrainingSizer; localTopoTrainingSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticBoxSizer* labeledDataSizer; labeledDataSizer = new wxStaticBoxSizer(new wxStaticBox(localTopoNotebookPanel, wxID_ANY, wxT("Labeled Data:")), wxVERTICAL); labelDataList = new wxListCtrl(labeledDataSizer->GetStaticBox(), ID_LABEL_DATA_LIST, wxDefaultPosition, wxDefaultSize, wxLC_HRULES | wxLC_REPORT | wxLC_VRULES); labeledDataSizer->Add(labelDataList, 1, wxALL | wxEXPAND, 5); wxBoxSizer* trainAndTestSizer; trainAndTestSizer = new wxBoxSizer(wxHORIZONTAL); trainAndTestSizer->Add(0, 0, 1, wxEXPAND, 5); loadLabelsButton = new wxButton(labeledDataSizer->GetStaticBox(), ID_LOAD_LABELS_BUTTON, wxT("Load Labels"), wxDefaultPosition, wxDefaultSize, 0); trainAndTestSizer->Add(loadLabelsButton, 0, wxALL | wxEXPAND, 5); saveLabelsButton = new wxButton(labeledDataSizer->GetStaticBox(), ID_SAVE_LABELS_BUTTON, wxT("Save Labels"), wxDefaultPosition, wxDefaultSize, 0); trainAndTestSizer->Add(saveLabelsButton, 0, wxALL | wxEXPAND, 5); trainGatewaysButton = new wxButton(labeledDataSizer->GetStaticBox(), ID_TRAIN_GATEWAYS_BUTTON, wxT("Train Gateways"), wxDefaultPosition, wxDefaultSize, 0); trainAndTestSizer->Add(trainGatewaysButton, 0, wxALL, 5); trainAndTestButton = new wxButton(labeledDataSizer->GetStaticBox(), ID_TRAIN_AND_TEST_BUTTON, wxT("Train Areas"), wxDefaultPosition, wxDefaultSize, 0); trainAndTestSizer->Add(trainAndTestButton, 1, wxALL | wxEXPAND, 5); trainAndTestSizer->Add(0, 0, 1, wxEXPAND, 5); labeledDataSizer->Add(trainAndTestSizer, 0, wxEXPAND, 5); localTopoTrainingSizer->Add(labeledDataSizer, 2, wxEXPAND, 5); wxStaticBoxSizer* trainingDataSizer; trainingDataSizer = new wxStaticBoxSizer(new wxStaticBox(localTopoNotebookPanel, wxID_ANY, wxT("Training Data:")), wxVERTICAL); trainingDataList = new wxListBox(trainingDataSizer->GetStaticBox(), wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_MULTIPLE); trainingDataSizer->Add(trainingDataList, 1, wxALL | wxEXPAND, 5); wxBoxSizer* trainingDataButtonsSizer; trainingDataButtonsSizer = new wxBoxSizer(wxHORIZONTAL); trainingDataButtonsSizer->Add(0, 0, 1, wxEXPAND, 5); addTrainingDataButton = new wxButton(trainingDataSizer->GetStaticBox(), ID_ADD_TRAINING_DATA_BUTTON, wxT(" + "), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); trainingDataButtonsSizer->Add(addTrainingDataButton, 0, wxALL, 5); removeTrainingDataButton = new wxButton(trainingDataSizer->GetStaticBox(), ID_REMOVE_TRAINING_DATA_BUTTON, wxT(" - "), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); trainingDataButtonsSizer->Add(removeTrainingDataButton, 0, wxALL, 5); trainingDataButtonsSizer->Add(0, 0, 1, wxEXPAND, 5); trainingDataSizer->Add(trainingDataButtonsSizer, 0, wxEXPAND, 5); localTopoTrainingSizer->Add(trainingDataSizer, 1, wxEXPAND, 5); wxStaticBoxSizer* testDataSizer; testDataSizer = new wxStaticBoxSizer(new wxStaticBox(localTopoNotebookPanel, wxID_ANY, wxT("Test Data:")), wxVERTICAL); testDataList = new wxListBox(testDataSizer->GetStaticBox(), wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_MULTIPLE); testDataSizer->Add(testDataList, 1, wxALL | wxEXPAND, 5); wxBoxSizer* testDataButtonsSizer; testDataButtonsSizer = new wxBoxSizer(wxHORIZONTAL); testDataButtonsSizer->Add(0, 0, 1, 0, 5); addTestDataButton = new wxButton(testDataSizer->GetStaticBox(), ID_ADD_TEST_DATA_BUTTON, wxT(" + "), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); testDataButtonsSizer->Add(addTestDataButton, 0, wxALL, 5); removeTestDataButton = new wxButton(testDataSizer->GetStaticBox(), ID_REMOVE_TEST_DATA_BUTTON, wxT(" - "), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); testDataButtonsSizer->Add(removeTestDataButton, 0, wxALL, 5); testDataButtonsSizer->Add(0, 0, 1, 0, 5); testDataSizer->Add(testDataButtonsSizer, 0, wxEXPAND, 5); localTopoTrainingSizer->Add(testDataSizer, 1, wxEXPAND, 5); localTopoWidgetSizer->Add(localTopoTrainingSizer, 1, wxEXPAND, 5); localTopoPanelSizer->Add(localTopoWidgetSizer, 1, wxEXPAND, 5); localTopoEditOptionsScroll = new wxScrolledWindow(localTopoNotebookPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL); localTopoEditOptionsScroll->SetScrollRate(0, 5); wxBoxSizer* localTopoEditorOptionsSizer; localTopoEditorOptionsSizer = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer* localTopoIOOptionsSIzer; localTopoIOOptionsSIzer = new wxStaticBoxSizer(new wxStaticBox(localTopoEditOptionsScroll, wxID_ANY, wxT("I/O Options")), wxVERTICAL); loadLocalTopoLPMButton = new wxButton(localTopoIOOptionsSIzer->GetStaticBox(), ID_LOAD_LOCAL_TOPO_FROM_FILE_BUTTON, wxT("Load Map"), wxDefaultPosition, wxDefaultSize, 0); localTopoIOOptionsSIzer->Add(loadLocalTopoLPMButton, 0, wxALL | wxEXPAND, 5); storeLabelsButton = new wxButton(localTopoIOOptionsSIzer->GetStaticBox(), ID_STORE_LABELS_BUTTON, wxT("Store Map Info"), wxDefaultPosition, wxDefaultSize, 0); storeLabelsButton->SetToolTip( wxT("Save the hand-created gateways and hand-labels areas associated with the current map.")); localTopoIOOptionsSIzer->Add(storeLabelsButton, 0, wxALL | wxEXPAND, 5); currentMapNameLabel = new wxStaticText(localTopoIOOptionsSIzer->GetStaticBox(), wxID_ANY, wxT("Current Map:"), wxDefaultPosition, wxDefaultSize, 0); currentMapNameLabel->Wrap(-1); localTopoIOOptionsSIzer->Add(currentMapNameLabel, 0, wxALIGN_LEFT | wxALL, 5); currentMapNameText = new wxStaticText(localTopoIOOptionsSIzer->GetStaticBox(), wxID_ANY, wxT("None"), wxDefaultPosition, wxDefaultSize, 0); currentMapNameText->Wrap(-1); localTopoIOOptionsSIzer->Add(currentMapNameText, 0, wxALIGN_LEFT | wxALL, 5); localTopoEditorOptionsSizer->Add(localTopoIOOptionsSIzer, 0, wxEXPAND, 5); wxString localTopoEditModeRadioChoices[] = {wxT("Gateways"), wxT("Label"), wxT("Merge")}; int localTopoEditModeRadioNChoices = sizeof(localTopoEditModeRadioChoices) / sizeof(wxString); localTopoEditModeRadio = new wxRadioBox(localTopoEditOptionsScroll, ID_LOCAL_TOPO_EDIT_MODE_RADIO, wxT("Edit Mode"), wxDefaultPosition, wxDefaultSize, localTopoEditModeRadioNChoices, localTopoEditModeRadioChoices, 1, wxRA_SPECIFY_COLS); localTopoEditModeRadio->SetSelection(0); localTopoEditorOptionsSizer->Add(localTopoEditModeRadio, 0, wxALL | wxEXPAND, 5); wxStaticBoxSizer* gatewayEditingOptionsSizer; gatewayEditingOptionsSizer = new wxStaticBoxSizer(new wxStaticBox(localTopoEditOptionsScroll, wxID_ANY, wxT("Gateway Options")), wxVERTICAL); generateGatewaysButton = new wxButton(gatewayEditingOptionsSizer->GetStaticBox(), ID_AUTO_GENERATE_GATEWAYS_BUTTON, wxT("Auto-Generate"), wxDefaultPosition, wxDefaultSize, 0); generateGatewaysButton->SetToolTip(wxT("Use the default gateway creation algorithm to create the gateways.")); gatewayEditingOptionsSizer->Add(generateGatewaysButton, 0, wxALL | wxEXPAND, 5); handCreateGatewaysButton = new wxToggleButton(gatewayEditingOptionsSizer->GetStaticBox(), ID_HAND_CREATE_GATEWAYS_BUTTON, wxT("Hand-Create"), wxDefaultPosition, wxDefaultSize, 0); gatewayEditingOptionsSizer->Add(handCreateGatewaysButton, 0, wxALL | wxEXPAND, 5); loadGatewaysButton = new wxButton(gatewayEditingOptionsSizer->GetStaticBox(), ID_LOAD_GATEWAYS_BUTTON, wxT("Load From File"), wxDefaultPosition, wxDefaultSize, 0); loadGatewaysButton->SetToolTip( wxT("Load the gateways from the .gwy file stored in the same directory as the LPM.")); gatewayEditingOptionsSizer->Add(loadGatewaysButton, 0, wxALL | wxEXPAND, 5); createAreasFromGatewaysButton = new wxButton(gatewayEditingOptionsSizer->GetStaticBox(), ID_CREATE_AREAS_FROM_GATEWAYS_BUTTON, wxT("Create Areas"), wxDefaultPosition, wxDefaultSize, 0); createAreasFromGatewaysButton->SetToolTip( wxT("Create areas from the gateways that have been created for the current map.")); gatewayEditingOptionsSizer->Add(createAreasFromGatewaysButton, 0, wxALL | wxEXPAND, 5); localTopoEditorOptionsSizer->Add(gatewayEditingOptionsSizer, 0, wxEXPAND, 5); wxStaticBoxSizer* localAreaLabelingOptionsSizer; localAreaLabelingOptionsSizer = new wxStaticBoxSizer(new wxStaticBox(localTopoEditOptionsScroll, wxID_ANY, wxT("Labeling Options")), wxVERTICAL); wxString labelToAssignRadioChoices[] = {wxT("Path Segment"), wxT("Decision Point"), wxT("Destination")}; int labelToAssignRadioNChoices = sizeof(labelToAssignRadioChoices) / sizeof(wxString); labelToAssignRadio = new wxRadioBox(localAreaLabelingOptionsSizer->GetStaticBox(), ID_LABEL_TO_ASSIGN_RADIO, wxT("Label to Assign"), wxDefaultPosition, wxDefaultSize, labelToAssignRadioNChoices, labelToAssignRadioChoices, 1, wxRA_SPECIFY_COLS); labelToAssignRadio->SetSelection(0); localAreaLabelingOptionsSizer->Add(labelToAssignRadio, 0, wxALL | wxEXPAND, 5); assignLabelsButton = new wxToggleButton(localAreaLabelingOptionsSizer->GetStaticBox(), ID_ASSIGN_LABELS_BUTTON, wxT("Assign Labels"), wxDefaultPosition, wxDefaultSize, 0); localAreaLabelingOptionsSizer->Add(assignLabelsButton, 0, wxALL | wxEXPAND, 5); labelAllAreasButton = new wxButton(localAreaLabelingOptionsSizer->GetStaticBox(), ID_LABEL_ALL_AREAS_BUTTON, wxT("Label Remaining"), wxDefaultPosition, wxDefaultSize, 0); localAreaLabelingOptionsSizer->Add(labelAllAreasButton, 0, wxALL | wxEXPAND, 5); clearLocalAreaLabelsButton = new wxButton(localAreaLabelingOptionsSizer->GetStaticBox(), ID_CLEAR_LOCAL_AREA_LABELS_BUTTON, wxT("Clear Labels"), wxDefaultPosition, wxDefaultSize, 0); localAreaLabelingOptionsSizer->Add(clearLocalAreaLabelsButton, 0, wxALL | wxEXPAND, 5); simplifyViaLabelsButton = new wxButton(localAreaLabelingOptionsSizer->GetStaticBox(), ID_SIMPLIFY_VIA_LABELS_BUTTON, wxT("Simplify Via Labels"), wxDefaultPosition, wxDefaultSize, 0); localAreaLabelingOptionsSizer->Add(simplifyViaLabelsButton, 0, wxALL | wxEXPAND, 5); localTopoEditorOptionsSizer->Add(localAreaLabelingOptionsSizer, 0, wxALL | wxEXPAND, 5); wxStaticBoxSizer* localAreaMergeOptions; localAreaMergeOptions = new wxStaticBoxSizer(new wxStaticBox(localTopoEditOptionsScroll, wxID_ANY, wxT("Merge Options")), wxVERTICAL); selectLocalAreasButton = new wxToggleButton(localAreaMergeOptions->GetStaticBox(), ID_SELECT_LOCAL_AREAS_BUTTON, wxT("Select Areas"), wxDefaultPosition, wxDefaultSize, 0); localAreaMergeOptions->Add(selectLocalAreasButton, 0, wxALL | wxEXPAND, 5); mergeSelectedAreasButton = new wxButton(localAreaMergeOptions->GetStaticBox(), ID_MERGE_SELECTED_AREAS_BUTTON, wxT("Merge Selected"), wxDefaultPosition, wxDefaultSize, 0); localAreaMergeOptions->Add(mergeSelectedAreasButton, 0, wxALL | wxEXPAND, 5); clearSelectedAreasButton = new wxButton(localAreaMergeOptions->GetStaticBox(), ID_CLEAR_SELECTED_AREAS_BUTTON, wxT("Clear Selected"), wxDefaultPosition, wxDefaultSize, 0); localAreaMergeOptions->Add(clearSelectedAreasButton, 0, wxALL | wxEXPAND, 5); resetMergedAreasButton = new wxButton(localAreaMergeOptions->GetStaticBox(), ID_RESET_MERGED_AREAS_BUTTON, wxT("Reset Merged"), wxDefaultPosition, wxDefaultSize, 0); localAreaMergeOptions->Add(resetMergedAreasButton, 0, wxALL | wxEXPAND, 5); localTopoEditorOptionsSizer->Add(localAreaMergeOptions, 0, wxALL | wxEXPAND, 5); localTopoEditOptionsScroll->SetSizer(localTopoEditorOptionsSizer); localTopoEditOptionsScroll->Layout(); localTopoEditorOptionsSizer->Fit(localTopoEditOptionsScroll); localTopoPanelSizer->Add(localTopoEditOptionsScroll, 0, wxALL | wxEXPAND, 5); localTopoNotebookPanel->SetSizer(localTopoPanelSizer); localTopoNotebookPanel->Layout(); localTopoPanelSizer->Fit(localTopoNotebookPanel); mapEditorNotebook->AddPage(localTopoNotebookPanel, wxT("Local Topo"), true, wxNullBitmap); globalTopoNotebookPanel = new wxPanel(mapEditorNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer* globalTopoPanelSizer; globalTopoPanelSizer = new wxBoxSizer(wxHORIZONTAL); globalTopoEditorWidget = new GlobalTopoEditorWidget(globalTopoNotebookPanel, ID_GLOBAL_TOPO_EDITOR_WIDGET, wxDefaultPosition, wxDefaultSize); globalTopoPanelSizer->Add(globalTopoEditorWidget, 1, wxALL | wxEXPAND, 5); wxBoxSizer* globalTopoOptionsSizer; globalTopoOptionsSizer = new wxBoxSizer(wxVERTICAL); globalTopoPanelSizer->Add(globalTopoOptionsSizer, 0, wxEXPAND, 5); globalTopoNotebookPanel->SetSizer(globalTopoPanelSizer); globalTopoNotebookPanel->Layout(); globalTopoPanelSizer->Fit(globalTopoNotebookPanel); mapEditorNotebook->AddPage(globalTopoNotebookPanel, wxT("Global Topo"), false, wxNullBitmap); mapEditorSizer->Add(mapEditorNotebook, 1, wxEXPAND | wxALL, 5); this->SetSizer(mapEditorSizer); this->Layout(); editorStatusBar = this->CreateStatusBar(1, wxSTB_SIZEGRIP, wxID_ANY); this->Centre(wxBOTH); } EditorFrame::~EditorFrame() { } ImportImageDialogBase::ImportImageDialogBase(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); wxBoxSizer* importImageDialogSizer; importImageDialogSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer* selectImageSizer; selectImageSizer = new wxBoxSizer(wxHORIZONTAL); imageFilenameText = new wxTextCtrl(this, ID_IMAGE_FILENAME_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); selectImageSizer->Add(imageFilenameText, 1, wxALL, 5); selectImageButton = new wxButton(this, ID_SELECT_IMAGE_BUTTON, wxT("Select Image"), wxDefaultPosition, wxDefaultSize, 0); selectImageSizer->Add(selectImageButton, 0, wxALL, 5); importImageDialogSizer->Add(selectImageSizer, 0, wxEXPAND, 5); wxFlexGridSizer* imagePropertiesSizer; imagePropertiesSizer = new wxFlexGridSizer(0, 2, 0, 0); imagePropertiesSizer->SetFlexibleDirection(wxBOTH); imagePropertiesSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); imageDimensionsDescriptionLabel = new wxStaticText(this, wxID_ANY, wxT("Dimensions (cells):"), wxDefaultPosition, wxDefaultSize, 0); imageDimensionsDescriptionLabel->Wrap(-1); imagePropertiesSizer->Add(imageDimensionsDescriptionLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5); imageDimensionsLabel = new wxStaticText(this, wxID_ANY, wxT("0x0"), wxDefaultPosition, wxDefaultSize, 0); imageDimensionsLabel->Wrap(-1); imagePropertiesSizer->Add(imageDimensionsLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); cellScaleLabel = new wxStaticText(this, wxID_ANY, wxT("Scale (m/cell):"), wxDefaultPosition, wxDefaultSize, 0); cellScaleLabel->Wrap(-1); imagePropertiesSizer->Add(cellScaleLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5); cellScaleText = new wxTextCtrl(this, ID_CELL_SCALE_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); imagePropertiesSizer->Add(cellScaleText, 1, wxALL | wxEXPAND, 5); cellThresholdsLabel = new wxStaticText(this, wxID_ANY, wxT("Thresholds:"), wxDefaultPosition, wxDefaultSize, 0); cellThresholdsLabel->Wrap(-1); imagePropertiesSizer->Add(cellThresholdsLabel, 0, wxALIGN_RIGHT | wxALL, 5); m_staticline1 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); imagePropertiesSizer->Add(m_staticline1, 1, wxEXPAND | wxALL, 5); freeThresholdLabel = new wxStaticText(this, wxID_ANY, wxT("Free (0-255):"), wxDefaultPosition, wxDefaultSize, 0); freeThresholdLabel->Wrap(-1); imagePropertiesSizer->Add(freeThresholdLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5); freeThresholdText = new wxTextCtrl(this, ID_FREE_THRESHOLD_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); imagePropertiesSizer->Add(freeThresholdText, 1, wxALL | wxEXPAND, 5); occupiedThresholdLabel = new wxStaticText(this, wxID_ANY, wxT("Occupied (0-255):"), wxDefaultPosition, wxDefaultSize, 0); occupiedThresholdLabel->Wrap(-1); imagePropertiesSizer->Add(occupiedThresholdLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5); occupiedThresholdText = new wxTextCtrl(this, ID_OCCUPIED_THRESHOLD_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); imagePropertiesSizer->Add(occupiedThresholdText, 1, wxALL | wxEXPAND, 5); importImageButton = new wxButton(this, ID_IMPORT_IMAGE_BUTTON, wxT("Import"), wxDefaultPosition, wxDefaultSize, 0); imagePropertiesSizer->Add(importImageButton, 0, wxALIGN_RIGHT | wxALL, 5); cancelImportButton = new wxButton(this, ID_CANCEL_IMPORT_BUTTON, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0); imagePropertiesSizer->Add(cancelImportButton, 0, wxALIGN_LEFT | wxALL, 5); importImageDialogSizer->Add(imagePropertiesSizer, 1, wxEXPAND, 5); this->SetSizer(importImageDialogSizer); this->Layout(); this->Centre(wxBOTH); } ImportImageDialogBase::~ImportImageDialogBase() { } ClassificationTestResultsDialogBase::ClassificationTestResultsDialogBase(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); wxBoxSizer* classificationResultsSizer; classificationResultsSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer* summaryTitleSizer; summaryTitleSizer = new wxBoxSizer(wxHORIZONTAL); m_staticline4 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); summaryTitleSizer->Add(m_staticline4, 1, wxEXPAND | wxALL, 5); classificationResultsSummaryLabel = new wxStaticText(this, wxID_ANY, wxT("Summary:"), wxDefaultPosition, wxDefaultSize, 0); classificationResultsSummaryLabel->Wrap(-1); classificationResultsSummaryLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); summaryTitleSizer->Add(classificationResultsSummaryLabel, 0, wxALL, 5); m_staticline5 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); summaryTitleSizer->Add(m_staticline5, 1, wxEXPAND | wxALL, 5); classificationResultsSizer->Add(summaryTitleSizer, 0, wxEXPAND, 5); wxBoxSizer* trainingResultsSummarySizer; trainingResultsSummarySizer = new wxBoxSizer(wxHORIZONTAL); trainingResultsSummarySizer->Add(0, 0, 1, wxEXPAND, 5); trainingSetResultsLabel = new wxStaticText(this, wxID_ANY, wxT("Training Data:"), wxDefaultPosition, wxDefaultSize, 0); trainingSetResultsLabel->Wrap(-1); trainingSetResultsLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); trainingResultsSummarySizer->Add(trainingSetResultsLabel, 0, wxALL, 5); trainingResultsTotalLabel = new wxStaticText(this, wxID_ANY, wxT("Total:"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsTotalLabel->Wrap(-1); trainingResultsTotalLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); trainingResultsSummarySizer->Add(trainingResultsTotalLabel, 0, wxALL, 5); trainingResultsTotalText = new wxStaticText(this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsTotalText->Wrap(-1); trainingResultsSummarySizer->Add(trainingResultsTotalText, 0, wxALL, 5); trainingResultsCorrectLabel = new wxStaticText(this, wxID_ANY, wxT("Correct:"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsCorrectLabel->Wrap(-1); trainingResultsCorrectLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); trainingResultsSummarySizer->Add(trainingResultsCorrectLabel, 0, wxALL, 5); trainingResultsCorrectText = new wxStaticText(this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsCorrectText->Wrap(-1); trainingResultsSummarySizer->Add(trainingResultsCorrectText, 0, wxALL, 5); trainingResultsAccuracyLabel = new wxStaticText(this, wxID_ANY, wxT("Accuracy:"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsAccuracyLabel->Wrap(-1); trainingResultsAccuracyLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); trainingResultsSummarySizer->Add(trainingResultsAccuracyLabel, 0, wxALL, 5); trainingResultsAccuracyText = new wxStaticText(this, wxID_ANY, wxT("0%"), wxDefaultPosition, wxDefaultSize, 0); trainingResultsAccuracyText->Wrap(-1); trainingResultsSummarySizer->Add(trainingResultsAccuracyText, 0, wxALL, 5); trainingResultsSummarySizer->Add(0, 0, 1, wxEXPAND, 5); classificationResultsSizer->Add(trainingResultsSummarySizer, 0, wxEXPAND, 5); wxBoxSizer* testResultsSummarySizer; testResultsSummarySizer = new wxBoxSizer(wxHORIZONTAL); testResultsSummarySizer->Add(0, 0, 1, wxEXPAND, 5); testDataResultsLabel = new wxStaticText(this, wxID_ANY, wxT("Test Data:"), wxDefaultPosition, wxDefaultSize, 0); testDataResultsLabel->Wrap(-1); testDataResultsLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); testResultsSummarySizer->Add(testDataResultsLabel, 0, wxALL, 5); totalClassificationTestsLabel = new wxStaticText(this, wxID_ANY, wxT("Total:"), wxDefaultPosition, wxDefaultSize, 0); totalClassificationTestsLabel->Wrap(-1); totalClassificationTestsLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); testResultsSummarySizer->Add(totalClassificationTestsLabel, 0, wxALL, 5); totalClassificationTestsText = new wxStaticText(this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); totalClassificationTestsText->Wrap(-1); testResultsSummarySizer->Add(totalClassificationTestsText, 0, wxALL, 5); correctClassificationTestsLabel = new wxStaticText(this, wxID_ANY, wxT("Correct:"), wxDefaultPosition, wxDefaultSize, 0); correctClassificationTestsLabel->Wrap(-1); correctClassificationTestsLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); testResultsSummarySizer->Add(correctClassificationTestsLabel, 0, wxALL, 5); correctClassificationTestsText = new wxStaticText(this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); correctClassificationTestsText->Wrap(-1); testResultsSummarySizer->Add(correctClassificationTestsText, 0, wxALL, 5); classificationAccuracyLabel = new wxStaticText(this, wxID_ANY, wxT("Accuracy:"), wxDefaultPosition, wxDefaultSize, 0); classificationAccuracyLabel->Wrap(-1); classificationAccuracyLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); testResultsSummarySizer->Add(classificationAccuracyLabel, 0, wxALL, 5); classificationAccuracyText = new wxStaticText(this, wxID_ANY, wxT("0%"), wxDefaultPosition, wxDefaultSize, 0); classificationAccuracyText->Wrap(-1); testResultsSummarySizer->Add(classificationAccuracyText, 0, wxALL, 5); testResultsSummarySizer->Add(0, 0, 1, wxEXPAND, 5); classificationResultsSizer->Add(testResultsSummarySizer, 0, wxEXPAND, 5); wxBoxSizer* detailsSummarySizer; detailsSummarySizer = new wxBoxSizer(wxHORIZONTAL); m_staticline41 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); detailsSummarySizer->Add(m_staticline41, 1, wxEXPAND | wxALL, 5); detailedResultsLabel = new wxStaticText(this, wxID_ANY, wxT("Details:"), wxDefaultPosition, wxDefaultSize, 0); detailedResultsLabel->Wrap(-1); detailedResultsLabel->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString)); detailsSummarySizer->Add(detailedResultsLabel, 0, wxALL, 5); m_staticline51 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); detailsSummarySizer->Add(m_staticline51, 1, wxEXPAND | wxALL, 5); classificationResultsSizer->Add(detailsSummarySizer, 0, wxEXPAND, 5); classificationDetailsList = new wxDataViewListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxDV_HORIZ_RULES | wxDV_ROW_LINES); classificationResultsSizer->Add(classificationDetailsList, 1, wxALL | wxEXPAND, 5); wxBoxSizer* classificationResultsButtonsSizer; classificationResultsButtonsSizer = new wxBoxSizer(wxHORIZONTAL); classificationResultsButtonsSizer->Add(0, 0, 1, wxEXPAND, 5); saveClassifierButton = new wxButton(this, ID_SAVE_CLASSIFIER_BUTTON, wxT("Save Classifier"), wxDefaultPosition, wxDefaultSize, 0); classificationResultsButtonsSizer->Add(saveClassifierButton, 0, wxALL, 5); closeClassifierButton = new wxButton(this, ID_CLOSE_CLASSIFIER_BUTTON, wxT("Close"), wxDefaultPosition, wxDefaultSize, 0); classificationResultsButtonsSizer->Add(closeClassifierButton, 0, wxALL, 5); classificationResultsButtonsSizer->Add(0, 0, 1, wxEXPAND, 5); classificationResultsSizer->Add(classificationResultsButtonsSizer, 0, wxEXPAND, 5); this->SetSizer(classificationResultsSizer); this->Layout(); this->Centre(wxBOTH); } ClassificationTestResultsDialogBase::~ClassificationTestResultsDialogBase() { }
48.328294
119
0.56288
anuranbaka
5aa374e7856fe47fe00278225a9acc46e548a392
3,942
cpp
C++
Tests/algorithm.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
1
2019-05-08T16:45:02.000Z
2019-05-08T16:45:02.000Z
Tests/algorithm.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
14
2019-01-23T15:22:55.000Z
2021-08-27T23:23:42.000Z
Tests/algorithm.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
1
2022-02-05T09:04:53.000Z
2022-02-05T09:04:53.000Z
// // algorithm.cpp // KSSCore // // Created by Steven W. Klassen on 2014-12-27. // Copyright (c) 2014 Klassen Software Solutions. All rights reserved. // Licensing follows the MIT License. // #include <cstdlib> #include <vector> #include <kss/test/all.h> #include <kss/util/algorithm.hpp> using namespace std; using namespace kss::util; using namespace kss::test; namespace { class Counter { public: Counter(int reference) { _count = 0; _reference = reference; } Counter(const Counter& c) { _count = c._count; _reference = c._reference; } void increment() { ++_count; } void reset() { _count = 0; } int reference() const { return _reference; } int count() const { return _count; } private: int _count; int _reference; }; auto incr = [](Counter& c) { c.increment(); }; auto iseven = [](const Counter& c) { return ((c.reference() % 2) == 0); }; auto isdiv5 = [](const Counter& c){ return ((c.reference() % 5) == 0); }; } static TestSuite ts("::algorithm", { make_pair("forEachIf", [] { Counter counters[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; forEachIf(counters, counters+10, incr, iseven); KSS_ASSERT(counters[0].count() == 0 && counters[2].count() == 0 && counters[4].count() == 0 && counters[6].count() == 0 && counters[8].count() == 0); KSS_ASSERT(counters[1].count() == 1 && counters[3].count() == 1 && counters[5].count() == 1 && counters[7].count() == 1 && counters[9].count() == 1); auto op = forEachIf(counters, counters+10, incr, isdiv5); KSS_ASSERT(counters[0].count() == 0 && counters[2].count() == 0 && counters[6].count() == 0 && counters[8].count() == 0); KSS_ASSERT(counters[1].count() == 1 && counters[3].count() == 1 && counters[5].count() == 1 && counters[7].count() == 1); KSS_ASSERT(counters[4].count() == 1); KSS_ASSERT(counters[9].count() == 2); KSS_ASSERT(op == incr); }), make_pair("notEqual", [] { int ar1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int ar2[] = { 1, 2, -3, 4, 5, 6, 7, 8, 9, 10 }; int ar3[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int ar4[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int ar5[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; vector<int> v2 { 1, 2, -3, 4, 5, 6, 7, 8, 9, 10 }; vector<int> v3 { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; vector<int> v4 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; vector<int> v5 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; auto absEq = [](int a, int b) { return (abs(a) == abs(b)); }; // Simple comparisons. KSS_ASSERT(notEqual(ar1, ar1+10, ar2)); KSS_ASSERT(notEqual(ar1, ar1+10, ar3)); KSS_ASSERT(notEqual(ar1, ar1+10, ar4)); KSS_ASSERT(!notEqual(ar1, ar1+10, ar1)); KSS_ASSERT(!notEqual(ar1, ar1+10, ar5)); // Comparisons with an explicit operator. KSS_ASSERT(!notEqual(ar1, ar1+10, ar2, absEq)); KSS_ASSERT(notEqual(ar1, ar1+10, ar3, absEq)); KSS_ASSERT(notEqual(ar1, ar1+10, ar4, absEq)); KSS_ASSERT(!notEqual(ar1, ar1+10, ar1, absEq)); KSS_ASSERT(!notEqual(ar1, ar1+10, ar5, absEq)); // Comparisons between iterator types. KSS_ASSERT(notEqual(ar1, ar1+10, v2.begin())); KSS_ASSERT(notEqual(ar1, ar1+10, v3.begin())); KSS_ASSERT(notEqual(ar1, ar1+10, v4.begin())); KSS_ASSERT(!notEqual(ar1, ar1+10, v5.begin())); KSS_ASSERT(!notEqual(ar1, ar1+10, v2.begin(), absEq)); KSS_ASSERT(notEqual(ar1, ar1+10, v3.begin(), absEq)); }) });
34.884956
78
0.5
klassen-software-solutions
5aa380b57e4a4f18197f6f785c6fe1861d9faa2d
2,342
cpp
C++
src/math_floating_point.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
7
2017-07-12T11:15:54.000Z
2021-10-29T18:33:33.000Z
src/math_floating_point.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
18
2017-05-16T03:48:45.000Z
2022-03-16T19:51:26.000Z
src/math_floating_point.cpp
tmilev/calculator
e39280f23975241985393651fe7a52db5c7fd1d5
[ "Apache-2.0" ]
1
2018-08-02T09:05:08.000Z
2018-08-02T09:05:08.000Z
// The current file is licensed under the license terms found in the main header file "calculator.h". // For additional information refer to the file "calculator.h". #include "math_general.h" #include <math.h> double FloatingPoint::sqrtFloating(double argument) { return ::sqrt(argument); } double FloatingPoint::sinFloating(double argument) { return ::sin(argument); } std::string FloatingPoint::doubleToString(double input) { std::stringstream out; out.precision(8); out << std::fixed << input; std::string result = out.str(); bool hasDot = false; for (int i = static_cast<signed>(result.size()) - 1; i >= 0; i --) { if (result[static_cast<unsigned>(i)] == '.') { hasDot = true; break; } } if (!hasDot) { return result; } int firstNonZeroIndex = 0; for (firstNonZeroIndex = static_cast<signed>(result.size()) - 1; firstNonZeroIndex >= 0; firstNonZeroIndex --) { if (result[static_cast<unsigned>(firstNonZeroIndex)] == '.') { result.resize(static_cast<unsigned>(firstNonZeroIndex)); return result; } if (result[static_cast<unsigned>(firstNonZeroIndex)] != '0') { break; } } result.resize(static_cast<unsigned>(firstNonZeroIndex) + 1); return result; } double FloatingPoint::cosFloating(double argument) { return cos(argument); } double FloatingPoint::absFloating(double argument) { return argument >= 0 ? argument : - argument; } bool FloatingPoint::isNaN(const double &argument) { #ifdef MACRO_use_wasm return isnan(argument); #else return std::isnan(argument); #endif } double FloatingPoint::logFloating(double argument) { return log(argument); } double FloatingPoint::arctan(double argument) { return atan(argument); } double FloatingPoint::arccos(double argument) { return acos(argument); } double FloatingPoint::arcsin(double argument) { return asin(argument); } double FloatingPoint::floorFloating(double argument) { return floor(argument); } double FloatingPoint::power(double base, double exponent) { return pow(base, exponent); } unsigned int HashFunctions::hashFunction(const double& input) { if (FloatingPoint::isNaN(input)) { return 5; } return static_cast<unsigned>(input * 10000); } unsigned int MathRoutines::hashDouble(const double& input) { return HashFunctions::hashFunction(input); }
24.652632
114
0.704526
tmilev
5aa843a1a498535b7a7d9f7206a065c0519764e9
15,622
cpp
C++
sources/kv-storage.cpp
dimakirol/lab-10-kv-storage
00096f700ab304894b954ac55b3eee0b75109045
[ "MIT" ]
1
2020-05-12T09:00:02.000Z
2020-05-12T09:00:02.000Z
sources/kv-storage.cpp
dimakirol/lab-10-kv-storage
00096f700ab304894b954ac55b3eee0b75109045
[ "MIT" ]
null
null
null
sources/kv-storage.cpp
dimakirol/lab-10-kv-storage
00096f700ab304894b954ac55b3eee0b75109045
[ "MIT" ]
null
null
null
// Copyright 2019 dimakirol <your_email> #include <kv-storage.hpp> class RandomString { public: RandomString() { alpha = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890"; auto now = static_cast<unsigned int>(time(nullptr)); randomizer = static_cast<uint64_t>(rand_r(&now) % alpha.length()); random_string.assign(alpha, 0, value_size); } std::string SetRandomValue(int ThreadID) { randomizer += ThreadID; int64_t tmp_randomizer = randomizer; random_string.erase(tmp_randomizer % random_string.size(), 1); random_string = random_string + alpha[tmp_randomizer % alpha.size()]; return random_string; } std::atomic_int64_t randomizer; std::string alpha; std::string random_string; }; struct Params{ Params(){ input = ""; log_level = ""; threads = default_threads; out = "dbhr-storage.db"; } Params(std::string _input, std::string _log_level, uint32_t _threads){ input = _input; log_level = _log_level; threads = _threads; if (input.find("/") != std::string::npos){ out.assign(input, 0, input.rfind("/") + 1); } out += "dbhr-storage.db"; } std::string input; std::string log_level; uint32_t threads; std::string out; } typedef Params; struct hash_this{ hash_this(){ cf_name = std::string(""); key = std::string(""); value = std::string(""); } hash_this(std::string _cf_name, std::string _key, std::string _value){ cf_name = _cf_name; key = _key; value = _value; } std::string cf_name; std::string key; std::string value; } typedef hash_this; struct print_this{ print_this(){ cf_name = std::string(""); key = std::string(""); hash = std::string(""); } print_this(std::string _cf_name, std::string _key, std::string _hash){ cf_name = _cf_name; key = _key; hash = _hash; } std::string cf_name; std::string key; std::string hash; } typedef print_this; class BD_Hasher{ public: explicit BD_Hasher(Params &parameters){ source = parameters.input; log_level = parameters.log_level; notes_in_work.store(0); threads = parameters.threads; out = parameters.out; cf_names_are_ready.store(false); download_finished = false; hashing_finished = false; processing_queue = new std::queue <hash_this>; output_queue = new std::queue <print_this>; } ~BD_Hasher(){ delete processing_queue; delete output_queue; } private: void feel_db(std::string name){ Options options; options.create_if_missing = true; DB* db; Status s; std::vector <std::string> cf_names_; DB::ListColumnFamilies(DBOptions(), name, &cf_names_); std::vector<ColumnFamilyDescriptor> column_families; for (auto name : cf_names_){ column_families.push_back(ColumnFamilyDescriptor( name, ColumnFamilyOptions())); } std::vector<ColumnFamilyHandle*> handles; s = DB::Open(DBOptions(), name, column_families, &handles, &db); assert(s.ok()); RandomString random_str; WriteBatch batch; for (uint32_t i = 0; i < column_families.size(); ++i){ for (int j = 0; j < notes_number; ++j) { std::string key; if (!i){ key = "key_default_" + std::to_string(j); } else { key = "key_" + cf_names_[i] + "_" + std::to_string(j); } std::string value = random_str.SetRandomValue(j); batch.Put(handles[i], Slice(key), Slice(value)); } s = db->Write(WriteOptions(), &batch); assert(s.ok()); } for (auto handle : handles) { s = db->DestroyColumnFamilyHandle(handle); assert(s.ok()); } delete db; } void make_db(std::string name, std::vector <std::string> &cf_names_){ Options options; options.create_if_missing = true; DB* db; Status s = DB::Open(options, name, &db); assert(s.ok()); std::vector <ColumnFamilyHandle*> handles; ColumnFamilyHandle* cf; for (auto column_family : cf_names_) { if (column_family == "default") continue; s = db->CreateColumnFamily(ColumnFamilyOptions(), column_family, &cf); assert(s.ok()); handles.push_back(cf); } for (auto handle : handles) { s = db->DestroyColumnFamilyHandle(handle); assert(s.ok()); } delete db; } void log_it(){ if (log_level == "debug"){ BOOST_LOG_TRIVIAL(debug) << ss.str() << std::endl; } else if (log_level == "info"){ BOOST_LOG_TRIVIAL(info) << ss.str() << std::endl; } else if (log_level == "warning"){ BOOST_LOG_TRIVIAL(warning) << ss.str() << std::endl; } else if (log_level == "error"){ BOOST_LOG_TRIVIAL(error) << ss.str() << std::endl; } else if (log_level == "fatal"){ BOOST_LOG_TRIVIAL(fatal) << ss.str() << std::endl; } else if (log_level == "trace"){ BOOST_LOG_TRIVIAL(trace) << ss.str() << std::endl; } ss.str(""); } void downloading_notes(){ std::vector <hash_this> please_hash_it; DB* db; Status s; DB::ListColumnFamilies(DBOptions(), source, &cf_names); cf_names_are_ready.store(true); std::vector<ColumnFamilyDescriptor> column_families; for (auto name : cf_names){ column_families.push_back(ColumnFamilyDescriptor( name, ColumnFamilyOptions())); } std::vector<ColumnFamilyHandle*> handles; s = DB::Open(DBOptions(), source, column_families, &handles, &db); assert(s.ok()); std::vector< Iterator* > iterators; s = db->NewIterators(ReadOptions(), handles, &iterators); assert(s.ok()); auto iterator_column_names = cf_names.begin(); uint32_t i = 0; for (auto it : iterators) { for (it->SeekToFirst(); it->Valid(); it->Next()) { please_hash_it.push_back(hash_this(*iterator_column_names, it->key().data(), it->value().ToString())); } i++; iterator_column_names++; delete it; } for (auto handle : handles) { s = db->DestroyColumnFamilyHandle(handle); assert(s.ok()); } delete db; for (auto element : please_hash_it){ while (!safe_processing.try_lock()){ std::this_thread::sleep_for(std::chrono::milliseconds( kirill_sleeps_seconds)); } processing_queue->push(element); safe_processing.unlock(); } download_finished.store(true); ss << "All key-value paires successfully read!"; log_it(); } void parsing_notes(ctpl::thread_pool *parsing_threads) { std::string str_before_hash; std::string str_after_hash; hash_this struct_before_hash; bool empty_queue = true; while (!download_finished) { std::this_thread::yield(); } while (!safe_processing.try_lock()) { std::this_thread::sleep_for(std::chrono::milliseconds( masha_sleeps_seconds)); } struct_before_hash = processing_queue->front(); processing_queue->pop(); empty_queue = processing_queue->empty(); safe_processing.unlock(); if (!empty_queue) { parsing_threads->push(std::bind(&BD_Hasher::parsing_notes, this, parsing_threads)); } str_before_hash = struct_before_hash.key + struct_before_hash.value; picosha2::hash256_hex_string(str_before_hash, str_after_hash); print_this struct_after_hash(struct_before_hash.cf_name, struct_before_hash.key, str_after_hash); while (!safe_output.try_lock()) { std::this_thread::sleep_for(std::chrono::milliseconds( masha_sleeps_seconds)); } output_queue->push(struct_after_hash); safe_output.unlock(); if (download_finished.load() && empty_queue){ hashing_finished.store(true); ss << "Hashing is completed!"; log_it(); } } void writing_output() { if (!cf_names_are_ready) { std::this_thread::sleep_for(std::chrono::milliseconds( dima_sleeps_seconds)); } make_db(out, cf_names); Options options; options.create_if_missing = true; DB* db; Status s; std::vector<ColumnFamilyDescriptor> column_families; for (auto name : cf_names){ column_families.push_back(ColumnFamilyDescriptor( name, ColumnFamilyOptions())); } std::vector<ColumnFamilyHandle*> handles; s = DB::Open(DBOptions(), out, column_families, &handles, &db); assert(s.ok()); print_this object_to_print; bool empty_queue = true; while (empty_queue) { while (!safe_output.try_lock()) { std::this_thread::sleep_for( std::chrono::milliseconds(dima_sleeps_seconds)); } empty_queue = output_queue->empty(); safe_output.unlock(); } while (!(hashing_finished && empty_queue)) { while (!safe_output.try_lock()) { std::this_thread::sleep_for(std::chrono::milliseconds( dima_sleeps_seconds)); } object_to_print = output_queue->front(); output_queue->pop(); safe_output.unlock(); int i = 0; for (auto column_family_name : cf_names) { if (column_family_name == object_to_print.cf_name) { s = db->Put(WriteOptions(), handles[i], Slice(object_to_print.key), Slice(object_to_print.hash)); break; } ++i; } empty_queue = true; while (empty_queue) { empty_queue = output_queue->empty(); std::cout << "Notes in process: " << output_queue->size() << std::endl; if (empty_queue){ if (hashing_finished.load()) break; } } } for (auto handle : handles) { s = db->DestroyColumnFamilyHandle(handle); assert(s.ok()); } delete db; ss << "End database done!!!!!!!!!!!!!!!!!!!!!!"; log_it(); } public: void i_like_to_hash_it_hash_it(){ try { ss << "Starting........"; log_it(); std::vector<std::string> cf_names_; for (int i = 0; i < cf_names_number; ++i) { cf_names_.push_back(std::string("cf_" + std::to_string(i))); } make_db(source, cf_names_); feel_db(source); ss << "Database successfully created"; log_it(); ctpl::thread_pool working_threads(threads); working_threads.push(std::bind(&BD_Hasher::downloading_notes, this)); working_threads.push(std::bind(&BD_Hasher::parsing_notes, this, &working_threads)); writing_output(); print_rezult(source, out); } catch (std::logic_error const& e){ std::cout << e.what() << " was an error!"; } catch (...){ std::cout << "Unknown error! Ask those stupid coders:0"; } } private: std::string source; std::string log_level; uint32_t threads; std::string out; std::atomic_bool cf_names_are_ready; std::vector <std::string> cf_names; std::atomic_bool download_finished; std::atomic_bool hashing_finished; std::atomic_uint notes_in_work; std::queue <hash_this> * processing_queue; std::mutex safe_processing; std::queue <print_this> * output_queue; std::mutex safe_output; std::stringstream ss; }; Params parse_cmd(const po::variables_map& vm){ Params cmd_params; if (vm.count("log-level")) cmd_params.log_level = vm["log-level"].as<std::string>(); if (vm.count("thread-count")) cmd_params.threads = vm["thread-count"].as<uint32_t>(); if (vm.count("output")) cmd_params.out = vm["output"].as<std::string>(); if (vm.count("input-file")) cmd_params.input = vm["input-file"].as<std::string>(); return cmd_params; } Params command_line_processor(int argc, char* argv[]){ po::options_description desc("General options"); std::string task_type; desc.add_options() ("help,h", "Show help") ("type,t", po::value<std::string>(&task_type), "Select task: hash"); po::options_description parse_desc("Work options"); parse_desc.add_options() ("log-level,l", po::value<std::string>()->default_value("error"), "= \"info\"|\"warning\"|\"error\"\n" "\t= default: \"error\"") ("thread-count,t", po::value<uint32_t>()->default_value(default_threads), "=Input number of working threads\n" "\t= default: count of logical core") ("input-file", po::value<std::string>()->required(), "input file") ("output,O", po::value<std::string>(), "Output parameters file"); po::positional_options_description file_name; file_name.add("input-file", -1); po::variables_map vm; try { auto parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(); po::store(parsed, vm); po::notify(vm); if (task_type == "hash") { desc.add(parse_desc); parsed = po::command_line_parser(argc, argv).options(desc).positional(file_name).allow_unregistered().run(); po::store(parsed, vm); po::notify(vm); Params cmd_params = parse_cmd(vm); return cmd_params; } else { std::cout << "Usage:" << "\n" << " dbhr [options] <path/to/input/storage.db>" << std::endl; desc.add(parse_desc); std::cout << desc << std::endl; exit(0); } } catch(std::exception& ex) { std::cout << ex.what() << std::endl; exit(-1); } return Params(); } int main(int argc, char* argv[]){ try { Params cmd_params = command_line_processor(argc, argv); BD_Hasher hasher(cmd_params); hasher.i_like_to_hash_it_hash_it(); } catch(std::exception& ex) { std::cout << ex.what() << std::endl; } return 0; }
32.27686
78
0.537639
dimakirol
5aabcff4c5f609eadb6d9c1551193b52a7cb7b3c
2,011
hpp
C++
include/source.hpp
Neverlord/stream-simulator
d0dd4537bd83ec219cad44c7b68e9baab539d099
[ "BSD-3-Clause" ]
null
null
null
include/source.hpp
Neverlord/stream-simulator
d0dd4537bd83ec219cad44c7b68e9baab539d099
[ "BSD-3-Clause" ]
null
null
null
include/source.hpp
Neverlord/stream-simulator
d0dd4537bd83ec219cad44c7b68e9baab539d099
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef SOURCE_HPP #define SOURCE_HPP #include <QSpinBox> #include <QProgressBar> #include "entity.hpp" #include "mainwindow.hpp" class source : virtual public entity { public: source(environment* env, QWidget* parent, QString name); ~source() override; void start() override; void add_consumer(caf::actor consumer); protected: // Pointer to the next stage in the pipeline. std::vector<caf::actor> consumers_; // Pointer to the CAF stream handler to advance the stream manually. caf::stream_manager_ptr stream_manager_; }; #endif // SOURCE_HPP
41.895833
80
0.406763
Neverlord
5ab11f03536a1304aa5424c68a6028f627f6c339
2,291
cpp
C++
Tga3D/Source/tga2dcore/tga2d/imguiinterface/ImGuiInterface.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
1
2022-03-10T11:43:24.000Z
2022-03-10T11:43:24.000Z
Tga3D/Source/tga2dcore/tga2d/imguiinterface/ImGuiInterface.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
Tga3D/Source/tga2dcore/tga2d/imguiinterface/ImGuiInterface.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ImGuiInterface.h" #include <string> #include <tga2d/engine.h> #include <tga2d/graphics/DX11.h> //#pragma comment(lib, "..\\Libs\\imgui.lib") //#pragma comment(lib, "..\\Libs\\imgui_canvas.lib") using namespace Tga2D; namespace Tga2D { class ImGuiInterfaceImpl { public: ImFontAtlas myFontAtlas; }; } ImGuiInterface::ImGuiInterface() = default; ImGuiInterface::~ImGuiInterface() { #ifndef _RETAIL ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); #endif } #ifndef _RETAIL static ImFont* ImGui_LoadFont(ImFontAtlas& atlas, const char* name, float size, const ImVec2& displayOffset = ImVec2(0, 0)) { char* windir = nullptr; if (_dupenv_s(&windir, nullptr, "WINDIR") || windir == nullptr) return nullptr; static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x0104, 0x017C, // Polish characters and more 0, }; ImFontConfig config; config.OversampleH = 4; config.OversampleV = 4; config.PixelSnapH = false; auto path = std::string(windir) + "\\Fonts\\" + name; auto font = atlas.AddFontFromFileTTF(path.c_str(), size, &config, ranges); if (font) font->DisplayOffset = displayOffset; free(windir); return font; } #endif void ImGuiInterface::Init() { #ifndef _RETAIL myImpl = std::make_unique<ImGuiInterfaceImpl>(); ImGui_LoadFont(myImpl->myFontAtlas, "segoeui.ttf", 18.0f);//16.0f * 96.0f / 72.0f); myImpl->myFontAtlas.Build(); ImGui::CreateContext(&myImpl->myFontAtlas); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.IniFilename = nullptr; io.LogFilename = nullptr; // Setup ImGui binding ImGui_ImplWin32_Init(*Tga2D::Engine::GetInstance()->GetHWND()); ImGui_ImplDX11_Init(Tga2D::DX11::Device, Tga2D::DX11::Context); ImGui::StyleColorsDark(); #endif } void ImGuiInterface::PreFrame() { #ifndef _RETAIL ImGui_ImplWin32_NewFrame(); ImGui_ImplDX11_NewFrame(); ImGui::NewFrame(); #endif } void ImGuiInterface::Render() { #ifndef _RETAIL ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); #endif }
22.460784
124
0.694457
sarisman84
5ab2c93d1ca032b3ca83f5a53b44ca5e67a897a0
426
cpp
C++
Ass_2/C files/diff.cpp
pratik8696/Assignment
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
[ "MIT" ]
null
null
null
Ass_2/C files/diff.cpp
pratik8696/Assignment
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
[ "MIT" ]
null
null
null
Ass_2/C files/diff.cpp
pratik8696/Assignment
6fa02f4f7ec135b13dbebea9920eeb2a57bd1489
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ int a,b,c,d,e,f; printf("enter first number \n"); scanf("%d",&a); printf("enter second number \n"); scanf("%d",&b); c=a+b; d=a-b; e=a*b; f=a/b; printf("Addition of a and b is : %d\n",c); printf("Subtraction of a and b is : %d\n",d); printf("Multiplication of a and b is : %d\n",e); printf("Division of a and b is : %d\n",f); return 0; }
21.3
52
0.521127
pratik8696
5ab51771fe0383c47e0511fc6dd17dc448044783
1,857
hpp
C++
Encoder/SpectralNoiseShaping.hpp
Casper-Bonde-Bose/liblc3codec
6e8ad0bd28108201e86507cd8a0f4eb130a12c5c
[ "Apache-2.0" ]
30
2021-04-13T12:00:06.000Z
2022-03-22T06:13:13.000Z
Encoder/SpectralNoiseShaping.hpp
Casper-Bonde-Bose/liblc3codec
6e8ad0bd28108201e86507cd8a0f4eb130a12c5c
[ "Apache-2.0" ]
6
2021-04-06T09:29:10.000Z
2022-03-28T10:58:55.000Z
Encoder/SpectralNoiseShaping.hpp
Casper-Bonde-Bose/liblc3codec
6e8ad0bd28108201e86507cd8a0f4eb130a12c5c
[ "Apache-2.0" ]
20
2021-03-23T06:48:30.000Z
2022-03-20T13:03:49.000Z
/* * SpectralNoiseShaping.hpp * * Copyright 2019 HIMSA II K/S - www.himsa.com. Represented by EHIMA - www.ehima.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SPECTRAL_NOISE_SHAPING_H_ #define SPECTRAL_NOISE_SHAPING_H_ #include <cstdint> #include "Datapoints.hpp" #include "SnsQuantization.hpp" #include "Lc3Config.hpp" namespace Lc3Enc { class SpectralNoiseShaping { public: SpectralNoiseShaping(const Lc3Config& lc3Config_, const int* const I_fs_); virtual ~SpectralNoiseShaping(); void registerDatapoints(DatapointContainer* datapoints_); void run(const double* const X, const double* E_B, bool F_att); uint8_t get_ind_LF(); uint8_t get_ind_HF(); uint8_t get_shape_j(); uint8_t get_Gind(); int32_t get_LS_indA(); int32_t get_LS_indB(); uint32_t get_index_joint_j(); static const uint8_t N_b = 64; static const uint8_t Nscales = 16; static const uint8_t nbits_SNS = 38; const Lc3Config& lc3Config; const uint8_t g_tilt; double* X_S; private: const int* const I_fs; SnsQuantization snsQuantization; double scf[Nscales]; double g_SNS[N_b]; DatapointContainer* datapoints; }; }//namespace Lc3Enc #endif // SPECTRAL_NOISE_SHAPING_H_
27.716418
84
0.693592
Casper-Bonde-Bose
5ab6d31bddf6b45abb349ad04bb031ea01790950
690
cpp
C++
src/aadcUser/src/HSOG_Runtime/a2o/worldmodel/street/StraightDetection.cpp
AppliedAutonomyOffenburg/AADC_2015_A2O
19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac
[ "BSD-4-Clause" ]
1
2018-09-09T21:39:29.000Z
2018-09-09T21:39:29.000Z
src/aadcUser/src/HSOG_Runtime/a2o/worldmodel/street/StraightDetection.cpp
TeamAutonomousCarOffenburg/A2O_2015
19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac
[ "BSD-4-Clause" ]
null
null
null
src/aadcUser/src/HSOG_Runtime/a2o/worldmodel/street/StraightDetection.cpp
TeamAutonomousCarOffenburg/A2O_2015
19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac
[ "BSD-4-Clause" ]
1
2016-04-05T06:34:08.000Z
2016-04-05T06:34:08.000Z
#include "StraightDetection.h" using namespace A2O; StraightDetection::StraightDetection(const Pose2D& pose) : SegmentDetection(1), _pose(pose) { } StraightDetection::~StraightDetection() { } const Pose2D& StraightDetection::getPose() const { return _pose; } void StraightDetection::add(const Pose2D& pose) { _pose = Pose2D::average(_pose, pose, _detectionsCount, 1); incrementDetectionsCount(); } const double StraightDetection::getPositionDistanceTo(const Pose2D& pose) const { return _pose.getDistanceTo(pose); } const double StraightDetection::getAngularDistanceTo(const Pose2D& pose) const { return std::fabs(_pose.getAngle().getDistanceTo(pose.getAngle())); }
19.714286
79
0.76087
AppliedAutonomyOffenburg
5ac2871d9c8aca50d6c0e3bfd37b0943267623b2
551
hxx
C++
ROOTXMLPlot/PlottingSelections.hxx
luketpickering/ROOTXMLPlot
e2e05d14e930925cd740025fd042b1cc3f0bd91c
[ "MIT" ]
null
null
null
ROOTXMLPlot/PlottingSelections.hxx
luketpickering/ROOTXMLPlot
e2e05d14e930925cd740025fd042b1cc3f0bd91c
[ "MIT" ]
null
null
null
ROOTXMLPlot/PlottingSelections.hxx
luketpickering/ROOTXMLPlot
e2e05d14e930925cd740025fd042b1cc3f0bd91c
[ "MIT" ]
null
null
null
#ifndef __PLOTTTINGSELECTIONS_HXX_SEEN__ #define __PLOTTTINGSELECTIONS_HXX_SEEN__ #include <map> #include <string> #include "PlottingTypes.hxx" #include "PlottingUtils.hxx" namespace PlottingSelections { extern std::map<std::string, PlottingTypes::Selection1D> Selections1D; extern std::map<std::string, PlottingTypes::Selection2D> Selections2D; void InitSelectionsXML(std::string const &confFile); PlottingTypes::Selection1D const * FindSel1D(std::string name); PlottingTypes::Selection2D const * FindSel2D(std::string name); } #endif
27.55
72
0.791289
luketpickering
5ac98b0d9cf945b682fd78fa44a765804efeaf1b
8,169
cpp
C++
source/datastorage.cpp
SirDifferential/proceduralis
a614c9809ab0766ade78c1732668c05b30a7f263
[ "MIT" ]
9
2016-01-05T12:35:44.000Z
2021-04-20T23:30:59.000Z
source/datastorage.cpp
SirDifferential/proceduralis
a614c9809ab0766ade78c1732668c05b30a7f263
[ "MIT" ]
null
null
null
source/datastorage.cpp
SirDifferential/proceduralis
a614c9809ab0766ade78c1732668c05b30a7f263
[ "MIT" ]
null
null
null
#include "datastorage.hpp" #include "application.hpp" #include "toolbox.hpp" DataStorage::DataStorage() { } /** * Loads the data that is required by the game for * displaying the game before it officially starts * This includes loading screens, loading music * and similar * Returns 0 if successful */ int DataStorage::loadInitialData() { loadTextureAndStoreSprite("logo", "data/2D/engine_logo.png"); loadSound("biisi", "data/audio/biisi.ogg"); return 0; } /** * Load all the game's content * Returns 0 if successful */ int DataStorage::loadAllData() { return 0; } /** * Generates sf::Sprite, sf::Image and sf::Texture of size s * All three are stored in datastorage containers * Returns SpritePtr to the newly generated sprite */ SpritePtr DataStorage::generateSpriteTriplet(std::string name, sf::Vector2i s) { SpritePtr sprite = SpritePtr(new sf::Sprite()); storeSprite(name, sprite); TexturePtr texture = TexturePtr(new sf::Texture()); texture->create(s.x, s.y); storeTexture(name, texture); ImagePtr img = ImagePtr(new sf::Image()); img->create(s.x, s.y); storeImage(name, img); return sprite; } /** * Loads a new texture from the given path and stores the produced Texture in the textureContainer as a shared_ptr * The texture is stored based on the given name * Returns -1 if error, 0 if success */ int DataStorage::loadTexture(std::string name, std::string path) { std::shared_ptr<sf::Texture> texture = std::shared_ptr<sf::Texture>(new sf::Texture()); if (!texture->loadFromFile(path)) { std::cout << "-DataStorage: Error loading file " << path << std::endl; return -1; } textureContainer[name] = texture; std::cout << "+DataStorage: Successfully loaded " << path << " as " << name << std::endl; return 0; } /** * Loads a new texture from the given path and stores the produced Texture in the textureContainer as a shared_ptr * Also creates a new sprite with the original dimensions from this texture * Returns -1 if error, 0 if success */ int DataStorage::loadTextureAndStoreSprite(std::string name, std::string path) { TexturePtr texture(new sf::Texture()); if (!texture->loadFromFile(path)) { std::cout << "-DataStorage: Error loading file: " << path << std::endl; return -1; } textureContainer[name] = texture; SpritePtr sp(new sf::Sprite(*texture)); storeSprite(name, sp); std::cout << "+DataStorage: Successfully loaded " << path << " as " << name << std::endl; return 0; } /** * Stores an existing sprite into the spriteContainer */ int DataStorage::storeSprite(std::string name, std::shared_ptr<sf::Sprite> s) { spriteContainer[name] = s; return 0; } /** * Stores an existing iamge in the imageContainer */ int DataStorage::storeImage(std::string name, std::shared_ptr<sf::Image> i) { imageContainer[name] = i; return 0; } /** * Stores an existing texture in the textureContainer */ int DataStorage::storeTexture(std::string name, std::shared_ptr<sf::Texture> t) { textureContainer[name] = t; return 0; } /** * Loads a new texture from the filepath, and stores it in texture map by name * Returns a SpritePtr containing the entire texture */ SpritePtr DataStorage::loadAndGiveSprite(std::string name, std::string filepath) { loadTextureAndStoreSprite(name, filepath); return getSprite(name); } /** * Writes an image to the disk if the image exists */ void DataStorage::writeImageToDisk(std::string name) { auto img = getImage(name); if (img == nullptr) { std::cout << "!DataStorage: Unable to write file to disk: not found: " << name << std::endl; return; } if (img->saveToFile(app.getToolbox()->combineStringAndString(name, ".png"))) { std::cout << "+DataStorage: Wrote " << name << " to disk" << std::endl; } else { std::cout << "!DataStorage: Error writing file to disk: " << name << std::endl; } } /** * Creates a new texture and then returns a shared_ptr to it * params: * name: The name that will be given to the created sprite. Also stored in spriteContainer by this name * textureName: The texture that will be used for this, searched from textureContainer * sizeX, sizeY: The area of the rectangle that will be used out of the texture. You might want to use 100x100 of a 256x256 texture * coordX, coordY: The offset in the texture. You may want to take a 100x100 region out of 256x256 texture, but not from top left corner * Returns a pointer to the newly created texture, or nullptr if failed */ SpritePtr DataStorage::createAndGiveSprite(std::string name, std::string textureName, int sizeX, int sizeY, int coordX, int coordY) { sf::IntRect subRect; subRect.left = coordX; subRect.top = coordY; subRect.width = sizeX; subRect.height = sizeY; TexturePtr texturePointer = getTexture(textureName); if (texturePointer == nullptr) { std::cout << "-DataStorage: Cannot create texture. Desired texture not found in memory: " << textureName << std::endl; return nullptr; } SpritePtr sprite(new sf::Sprite((*texturePointer), subRect)); storeSprite(name, sprite); return sprite; } /** * Loads a new sound by filename. Also creates a soundbuffer object and stores it * Returns -1 if failure * * Does not support mp3. ogg is preferred over other formats */ int DataStorage::loadSound(std::string name, std::string path) { SoundBufferPtr buffer(new sf::SoundBuffer()); if (!(*buffer).loadFromFile(path)) { std::cout << "-DataStorage: Error loading audio file " << path << std::endl; return -1; } soundBufferContainer[name] = buffer; std::shared_ptr<sf::Sound> sound = std::shared_ptr<sf::Sound>(new sf::Sound()); sound->setBuffer((*buffer)); soundContainer[name] = sound; std::cout << "+DataStorage: Successfully loaded " << path << "as " << name << std::endl; return 0; } /** * Returns a shared_ptr<sf::Sprite> to a loaded sprite * or nullptr if not found */ SpritePtr DataStorage::getSprite(std::string name) { std::map<std::string, SpritePtr>::iterator iter; iter = spriteContainer.find(name); if (iter == spriteContainer.end()) { std::cout << "-DataStorage: Can't find requested sprite in map: " << name << std::endl; return nullptr; } return iter->second; } /** * Returns a shared_ptr<sf::Texture> to a loaded texture * or nullptr if not found */ TexturePtr DataStorage::getTexture(std::string name) { std::map<std::string, TexturePtr>::iterator iter; iter = textureContainer.find(name); if (iter == textureContainer.end()) { std::cout << "-DataStorage: Can't find requested texture in map: " << name << std::endl; return nullptr; } return iter->second; } /** * Returns a shared_ptr<sf::Sound> to a loaded sound * or nullptr if not found */ SoundPtr DataStorage::getSound(std::string name) { std::map<std::string, SoundPtr>::iterator iter; iter = soundContainer.find(name); if (iter == soundContainer.end()) { std::cout << "-DataStorage: Can't find requested soundfile in map: " << name << std::endl; return nullptr; } return iter->second; } /** * Returns a shared_ptr<sf::Image> to a loaded image * or nullptr if not found */ ImagePtr DataStorage::getImage(std::string name) { auto iter = imageContainer.find(name); if (iter == imageContainer.end()) { std::cout << "-DataStorage: Can't find image in map: " << name << std::endl; return nullptr; } return iter->second; } void DataStorage::deleteImage(std::string name) { auto iter = imageContainer.find(name); if (iter != imageContainer.end()) imageContainer.erase(iter); } void DataStorage::deleteTexture(std::string name) { auto iter = textureContainer.find(name); if (iter != textureContainer.end()) textureContainer.erase(iter); } void DataStorage::deleteSprite(std::string name) { auto iter = spriteContainer.find(name); if (iter != spriteContainer.end()) spriteContainer.erase(iter); }
28.663158
135
0.669849
SirDifferential
5acb38e153040ffdd31aaf5382c14ac9f81905f8
1,380
cpp
C++
src/common/errorsystem.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
1
2019-07-01T02:02:40.000Z
2019-07-01T02:02:40.000Z
src/common/errorsystem.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
src/common/errorsystem.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
#include "errorsystem.hpp" #include "logger.hpp" void Noctis::ErrorSystem::Error(StdStringView text) { g_Logger.SetForeColor(LoggerColor::ForeRed); g_Logger.Log("[%s] error:", m_CurFile.c_str()); g_Logger.Log(text); g_Logger.SetForeColor(LoggerColor::ForeGray); } void Noctis::ErrorSystem::Warning(StdStringView text) { g_Logger.SetForeColor(LoggerColor::ForeYellow); g_Logger.Log("[%s] warning:", m_CurFile.c_str()); g_Logger.Log(text); g_Logger.SetForeColor(LoggerColor::ForeGray); } void Noctis::ErrorSystem::SetCurrentFile(const StdString& file) { m_CurFile = file; } void Noctis::ErrorSystem::LogError(StdStringView filePath, u64 line, u64 column, StdStringView text) { g_Logger.SetForeColor(LoggerColor::ForeRed); g_Logger.Log("[%s:%u:%u] error:", filePath.empty() ? m_CurFile.c_str() : filePath.data(), line, column); g_Logger.Log(text); g_Logger.Log("\n"); g_Logger.SetForeColor(LoggerColor::ForeGray); } void Noctis::ErrorSystem::LogWarning(StdStringView filePath, u64 line, u64 column, StdStringView text) { g_Logger.SetForeColor(LoggerColor::ForeYellow); g_Logger.Log("[%s:%u:%u] warning:", filePath.empty() ? m_CurFile.c_str() : filePath.data(), line, column); g_Logger.Log(text); g_Logger.Log("\n"); g_Logger.SetForeColor(LoggerColor::ForeGray); } Noctis::ErrorSystem& Noctis::GetErrorSystem() { static ErrorSystem errSys; return errSys; }
28.75
107
0.747101
noct-lang
5ad04f44b6f307afebc8e3d7dc5ad38eb60d5d95
563
hpp
C++
cheats/features/backtrack/backtrack.hpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/features/backtrack/backtrack.hpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/features/backtrack/backtrack.hpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
#pragma once #include "../../game.hpp" #include "../../../SDK/interfaces/interfaces.hpp" #include <deque> #include <array> // TODO: fix setupbones for better results namespace backtrack { struct StoredRecord { float simTime = 0.0f; Vector head = { 0, 0, 0 }; // use origin to set abs or for whatever need Vector origin = { 0, 0 , 0 }; matrix3x4_t matrix[BONE_USED_BY_HITBOX] = {}; }; void run(CUserCmd* cmd); void update(); void init(); bool isValid(float simtime); float getLerp(); inline std::array<std::deque<StoredRecord>, 65> records; };
22.52
57
0.669627
DemonLoverHvH
62c4adf69d79740da7434ad50e62455657120e56
67,115
cpp
C++
opencl/test/unit_test/command_queue/blit_enqueue_1_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/command_queue/blit_enqueue_1_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/command_queue/blit_enqueue_1_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2019-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/helpers/local_memory_access_modes.h" #include "shared/source/helpers/pause_on_gpu_properties.h" #include "shared/source/helpers/vec.h" #include "shared/source/memory_manager/unified_memory_manager.h" #include "shared/test/common/cmd_parse/hw_parse.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/engine_descriptor_helper.h" #include "shared/test/common/helpers/unit_test_helper.h" #include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/mocks/mock_device.h" #include "shared/test/common/mocks/mock_timestamp_container.h" #include "shared/test/common/test_macros/test.h" #include "shared/test/unit_test/compiler_interface/linker_mock.h" #include "shared/test/unit_test/utilities/base_object_utils.h" #include "opencl/source/event/user_event.h" #include "opencl/source/mem_obj/buffer.h" #include "opencl/test/unit_test/command_queue/blit_enqueue_fixture.h" #include "opencl/test/unit_test/mocks/mock_cl_device.h" #include "opencl/test/unit_test/mocks/mock_command_queue.h" #include "opencl/test/unit_test/mocks/mock_context.h" #include "opencl/test/unit_test/mocks/mock_kernel.h" #include "opencl/test/unit_test/mocks/mock_program.h" #include "opencl/test/unit_test/test_macros/test_checks_ocl.h" namespace NEO { extern CommandStreamReceiverCreateFunc commandStreamReceiverFactory[2 * IGFX_MAX_CORE]; using BlitAuxTranslationTests = BlitEnqueueTests<1>; HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitAuxTranslationWhenConstructingCommandBufferThenEnsureCorrectOrder) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); auto initialBcsTaskCount = mockCmdQ->peekBcsTaskCount(bcsCsr->getOsContext().getEngineType()); mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, lws, 0, nullptr, nullptr); EXPECT_EQ(initialBcsTaskCount + 1, mockCmdQ->peekBcsTaskCount(bcsCsr->getOsContext().getEngineType())); // Gpgpu command buffer { auto cmdListCsr = getCmdList<FamilyType>(gpgpuCsr->getCS(0), 0); auto cmdListQueue = getCmdList<FamilyType>(commandQueue->getCS(0), 0); // Barrier expectPipeControl<FamilyType>(cmdListCsr.begin(), cmdListCsr.end()); // Aux to NonAux auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdListQueue.begin(), cmdListQueue.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); // Walker cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); // NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); // task count expectPipeControl<FamilyType>(++cmdFound, cmdListQueue.end()); } // BCS command buffer { auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Barrier auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); // Aux to NonAux cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); // wait for NDR (walker split) cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); // NonAux to Aux cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); // taskCount expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); } } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenGpuHangOnFlushBcsAndBlitAuxTranslationWhenConstructingCommandBufferThenOutOfResourcesIsReturned) { auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); ultBcsCsr->callBaseFlushBcsTask = false; ultBcsCsr->flushBcsTaskReturnValue = std::nullopt; auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); const auto result = mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, lws, 0, nullptr, nullptr); EXPECT_EQ(CL_OUT_OF_RESOURCES, result); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitAuxTranslationWhenConstructingBlockedCommandBufferThenEnsureCorrectOrder) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); auto initialBcsTaskCount = mockCmdQ->peekBcsTaskCount(bcsCsr->getOsContext().getEngineType()); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, lws, 1, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); EXPECT_EQ(initialBcsTaskCount + 1, mockCmdQ->peekBcsTaskCount(bcsCsr->getOsContext().getEngineType())); // Gpgpu command buffer { auto cmdListCsr = getCmdList<FamilyType>(gpgpuCsr->getCS(0), 0); auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto cmdListQueue = getCmdList<FamilyType>(*ultCsr->lastFlushedCommandStream, 0); // Barrier expectPipeControl<FamilyType>(cmdListCsr.begin(), cmdListCsr.end()); // Aux to NonAux auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdListQueue.begin(), cmdListQueue.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); // Walker cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); // NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); // task count expectPipeControl<FamilyType>(++cmdFound, cmdListQueue.end()); } // BCS command buffer { auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Barrier auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); // Aux to NonAux cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); // wait for NDR (walker split) cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); // NonAux to Aux cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); cmdFound = expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); // taskCount expectCommand<MI_FLUSH_DW>(++cmdFound, cmdList.end()); } EXPECT_FALSE(mockCmdQ->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingCommandBufferThenSynchronizeBarrier) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); auto cmdListCsr = getCmdList<FamilyType>(gpgpuCsr->getCS(0), 0); auto pipeControl = expectPipeControl<FamilyType>(cmdListCsr.begin(), cmdListCsr.end()); auto pipeControlCmd = genCmdCast<PIPE_CONTROL *>(*pipeControl); uint64_t barrierGpuAddress = NEO::UnitTestHelper<FamilyType>::getPipeControlPostSyncAddress(*pipeControlCmd); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); verifySemaphore<FamilyType>(semaphore, barrierGpuAddress); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, whenFlushTagUpdateThenMiFlushDwIsFlushed) { using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; bcsCsr->flushTagUpdate(); auto cmdListBcs = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto cmdFound = expectCommand<MI_FLUSH_DW>(cmdListBcs.begin(), cmdListBcs.end()); EXPECT_NE(cmdFound, cmdListBcs.end()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingCommandBufferThenSynchronizeBcsOutput) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 2>{{buffer0.get(), buffer1.get()}}); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); uint64_t auxToNonAuxOutputAddress[2] = {}; uint64_t nonAuxToAuxOutputAddress[2] = {}; { auto cmdListBcs = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto cmdFound = expectCommand<XY_COPY_BLT>(cmdListBcs.begin(), cmdListBcs.end()); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); auto miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); auxToNonAuxOutputAddress[0] = miflushDwCmd->getDestinationAddress(); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); auxToNonAuxOutputAddress[1] = miflushDwCmd->getDestinationAddress(); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdListBcs.end()); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); nonAuxToAuxOutputAddress[0] = miflushDwCmd->getDestinationAddress(); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); nonAuxToAuxOutputAddress[1] = miflushDwCmd->getDestinationAddress(); } { auto cmdListQueue = getCmdList<FamilyType>(commandQueue->getCS(0), 0); // Aux to NonAux auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdListQueue.begin(), cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, auxToNonAuxOutputAddress[0]); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, auxToNonAuxOutputAddress[1]); // Walker cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); // NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, nonAuxToAuxOutputAddress[0]); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, nonAuxToAuxOutputAddress[1]); } } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingCommandBufferThenSynchronizeKernel) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCmdQ->overrideIsCacheFlushForBcsRequired.enabled = true; mockCmdQ->overrideIsCacheFlushForBcsRequired.returnValue = false; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); auto kernelNode = mockCmdQ->timestampPacketContainer->peekNodes()[0]; auto kernelNodeAddress = TimestampPacketHelper::getContextEndGpuAddress(*kernelNode); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Aux to nonAux auto cmdFound = expectCommand<XY_COPY_BLT>(cmdList.begin(), cmdList.end()); // semaphore before NonAux to Aux auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); verifySemaphore<FamilyType>(semaphore, kernelNodeAddress); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingCommandBufferThenSynchronizeCacheFlush) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCmdQ->overrideIsCacheFlushForBcsRequired.enabled = true; mockCmdQ->overrideIsCacheFlushForBcsRequired.returnValue = true; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); auto cmdListBcs = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto cmdListQueue = getCmdList<FamilyType>(mockCmdQ->getCS(0), 0); uint64_t cacheFlushWriteAddress = 0; { auto cmdFound = expectCommand<WALKER_TYPE>(cmdListQueue.begin(), cmdListQueue.end()); cmdFound = expectPipeControl<FamilyType>(++cmdFound, cmdListQueue.end()); auto pipeControlCmd = genCmdCast<PIPE_CONTROL *>(*cmdFound); if (!pipeControlCmd->getDcFlushEnable()) { // skip pipe control with TimestampPacket write cmdFound = expectPipeControl<FamilyType>(++cmdFound, cmdListQueue.end()); pipeControlCmd = genCmdCast<PIPE_CONTROL *>(*cmdFound); } EXPECT_TRUE(pipeControlCmd->getDcFlushEnable()); EXPECT_TRUE(pipeControlCmd->getCommandStreamerStallEnable()); cacheFlushWriteAddress = NEO::UnitTestHelper<FamilyType>::getPipeControlPostSyncAddress(*pipeControlCmd); EXPECT_NE(0u, cacheFlushWriteAddress); } { // Aux to nonAux auto cmdFound = expectCommand<XY_COPY_BLT>(cmdListBcs.begin(), cmdListBcs.end()); // semaphore before NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListBcs.end()); verifySemaphore<FamilyType>(cmdFound, cacheFlushWriteAddress); } } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingCommandBufferThenSynchronizeEvents) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto event = make_releaseable<Event>(commandQueue.get(), CL_COMMAND_READ_BUFFER, 0, 0); MockTimestampPacketContainer eventDependencyContainer(*bcsCsr->getTimestampPacketAllocator(), 1); auto eventDependency = eventDependencyContainer.getNode(0); event->addTimestampPacketNodes(eventDependencyContainer); cl_event clEvent[] = {event.get()}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, clEvent, nullptr); auto eventDependencyAddress = TimestampPacketHelper::getContextEndGpuAddress(*eventDependency); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Barrier auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); // Event auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); verifySemaphore<FamilyType>(semaphore, eventDependencyAddress); cmdFound = expectCommand<XY_COPY_BLT>(++semaphore, cmdList.end()); expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenOutEventWhenDispatchingThenAssignNonAuxNodes) { using WALKER_TYPE = typename FamilyType::WALKER_TYPE; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); cl_event clEvent; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, &clEvent); auto event = castToObject<Event>(clEvent); auto &eventNodes = event->getTimestampPacketNodes()->peekNodes(); EXPECT_EQ(5u, eventNodes.size()); auto cmdListQueue = getCmdList<FamilyType>(commandQueue->getCS(0), 0); auto cmdFound = expectCommand<WALKER_TYPE>(cmdListQueue.begin(), cmdListQueue.end()); // NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); auto eventNodeAddress = TimestampPacketHelper::getContextEndGpuAddress(*eventNodes[1]); verifySemaphore<FamilyType>(cmdFound, eventNodeAddress); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); eventNodeAddress = TimestampPacketHelper::getContextEndGpuAddress(*eventNodes[2]); verifySemaphore<FamilyType>(cmdFound, eventNodeAddress); EXPECT_NE(0u, event->peekBcsTaskCountFromCommandQueue()); clReleaseEvent(clEvent); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitAuxTranslationWhenDispatchingThenEstimateCmdBufferSize) { using WALKER_TYPE = typename FamilyType::WALKER_TYPE; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto &hwInfo = device->getHardwareInfo(); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCmdQ->overrideIsCacheFlushForBcsRequired.enabled = true; mockCmdQ->overrideIsCacheFlushForBcsRequired.returnValue = false; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); KernelObjsForAuxTranslation kernelObjects; kernelObjects.insert({KernelObjForAuxTranslation::Type::MEM_OBJ, buffer0.get()}); kernelObjects.insert({KernelObjForAuxTranslation::Type::MEM_OBJ, buffer2.get()}); size_t numBuffersToEstimate = 2; size_t dependencySize = numBuffersToEstimate * TimestampPacketHelper::getRequiredCmdStreamSizeForNodeDependencyWithBlitEnqueue<FamilyType>(); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); mockCmdQ->storeMultiDispatchInfo = true; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, lws, 0, nullptr, nullptr); MultiDispatchInfo &multiDispatchInfo = mockCmdQ->storedMultiDispatchInfo; DispatchInfo *firstDispatchInfo = multiDispatchInfo.begin(); DispatchInfo *lastDispatchInfo = &(*multiDispatchInfo.rbegin()); EXPECT_NE(firstDispatchInfo, lastDispatchInfo); // walker split EXPECT_EQ(dependencySize, firstDispatchInfo->dispatchInitCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(0u, firstDispatchInfo->dispatchEpilogueCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(0u, lastDispatchInfo->dispatchInitCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(dependencySize, lastDispatchInfo->dispatchEpilogueCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitAuxTranslationWithRequiredCacheFlushWhenDispatchingThenEstimateCmdBufferSize) { using WALKER_TYPE = typename FamilyType::WALKER_TYPE; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto &hwInfo = device->getHardwareInfo(); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCmdQ->overrideIsCacheFlushForBcsRequired.enabled = true; mockCmdQ->overrideIsCacheFlushForBcsRequired.returnValue = true; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, false); auto buffer2 = createBuffer(1, true); KernelObjsForAuxTranslation kernelObjects; kernelObjects.insert({KernelObjForAuxTranslation::Type::MEM_OBJ, buffer0.get()}); kernelObjects.insert({KernelObjForAuxTranslation::Type::MEM_OBJ, buffer2.get()}); size_t numBuffersToEstimate = 2; size_t dependencySize = numBuffersToEstimate * TimestampPacketHelper::getRequiredCmdStreamSizeForNodeDependencyWithBlitEnqueue<FamilyType>(); size_t cacheFlushSize = MemorySynchronizationCommands<FamilyType>::getSizeForPipeControlWithPostSyncOperation(hwInfo); setMockKernelArgs(std::array<Buffer *, 3>{{buffer0.get(), buffer1.get(), buffer2.get()}}); mockCmdQ->storeMultiDispatchInfo = true; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, lws, 0, nullptr, nullptr); MultiDispatchInfo &multiDispatchInfo = mockCmdQ->storedMultiDispatchInfo; DispatchInfo *firstDispatchInfo = multiDispatchInfo.begin(); DispatchInfo *lastDispatchInfo = &(*multiDispatchInfo.rbegin()); EXPECT_NE(firstDispatchInfo, lastDispatchInfo); // walker split EXPECT_EQ(dependencySize, firstDispatchInfo->dispatchInitCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(0u, firstDispatchInfo->dispatchEpilogueCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(0u, lastDispatchInfo->dispatchInitCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); EXPECT_EQ(dependencySize + cacheFlushSize, lastDispatchInfo->dispatchEpilogueCommands.estimateCommandsSize(kernelObjects.size(), hwInfo, mockCmdQ->isCacheFlushForBcsRequired())); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingBlockedCommandBufferThenSynchronizeBarrier) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); auto cmdListCsr = getCmdList<FamilyType>(gpgpuCsr->getCS(0), 0); auto pipeControl = expectPipeControl<FamilyType>(cmdListCsr.begin(), cmdListCsr.end()); auto pipeControlCmd = genCmdCast<PIPE_CONTROL *>(*pipeControl); uint64_t barrierGpuAddress = NEO::UnitTestHelper<FamilyType>::getPipeControlPostSyncAddress(*pipeControlCmd); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); verifySemaphore<FamilyType>(semaphore, barrierGpuAddress); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingBlockedCommandBufferThenSynchronizeEvents) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto event = make_releaseable<Event>(commandQueue.get(), CL_COMMAND_READ_BUFFER, 0, 0); MockTimestampPacketContainer eventDependencyContainer(*bcsCsr->getTimestampPacketAllocator(), 1); auto eventDependency = eventDependencyContainer.getNode(0); event->addTimestampPacketNodes(eventDependencyContainer); UserEvent userEvent; cl_event waitlist[] = {&userEvent, event.get()}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 2, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); auto eventDependencyAddress = TimestampPacketHelper::getContextEndGpuAddress(*eventDependency); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Barrier auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdList.begin(), cmdList.end()); // Event auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); verifySemaphore<FamilyType>(semaphore, eventDependencyAddress); cmdFound = expectCommand<XY_COPY_BLT>(++semaphore, cmdList.end()); expectCommand<XY_COPY_BLT>(++cmdFound, cmdList.end()); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingBlockedCommandBufferThenSynchronizeKernel) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto mockCmdQ = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; mockCmdQ->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); auto kernelNode = mockCmdQ->timestampPacketContainer->peekNodes()[0]; auto kernelNodeAddress = TimestampPacketHelper::getContextEndGpuAddress(*kernelNode); auto cmdList = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); // Aux to nonAux auto cmdFound = expectCommand<XY_COPY_BLT>(cmdList.begin(), cmdList.end()); // semaphore before NonAux to Aux auto semaphore = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdList.end()); if (mockCmdQ->isCacheFlushForBcsRequired()) { semaphore = expectCommand<MI_SEMAPHORE_WAIT>(++semaphore, cmdList.end()); } verifySemaphore<FamilyType>(semaphore, kernelNodeAddress); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenConstructingBlockedCommandBufferThenSynchronizeBcsOutput) { using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 2>{{buffer0.get(), buffer1.get()}}); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); uint64_t auxToNonAuxOutputAddress[2] = {}; uint64_t nonAuxToAuxOutputAddress[2] = {}; { auto cmdListBcs = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto cmdFound = expectCommand<XY_COPY_BLT>(cmdListBcs.begin(), cmdListBcs.end()); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); auto miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); auxToNonAuxOutputAddress[0] = miflushDwCmd->getDestinationAddress(); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); auxToNonAuxOutputAddress[1] = miflushDwCmd->getDestinationAddress(); cmdFound = expectCommand<XY_COPY_BLT>(++cmdFound, cmdListBcs.end()); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); nonAuxToAuxOutputAddress[0] = miflushDwCmd->getDestinationAddress(); cmdFound = expectMiFlush<MI_FLUSH_DW>(++cmdFound, cmdListBcs.end()); miflushDwCmd = genCmdCast<MI_FLUSH_DW *>(*cmdFound); nonAuxToAuxOutputAddress[1] = miflushDwCmd->getDestinationAddress(); } { auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto cmdListQueue = getCmdList<FamilyType>(*ultCsr->lastFlushedCommandStream, 0); // Aux to NonAux auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(cmdListQueue.begin(), cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, auxToNonAuxOutputAddress[0]); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, auxToNonAuxOutputAddress[1]); // Walker cmdFound = expectCommand<WALKER_TYPE>(++cmdFound, cmdListQueue.end()); // NonAux to Aux cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, nonAuxToAuxOutputAddress[0]); cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(++cmdFound, cmdListQueue.end()); verifySemaphore<FamilyType>(cmdFound, nonAuxToAuxOutputAddress[1]); } EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenGpuHangOnFlushBcsTaskAndBlitTranslationWhenConstructingBlockedCommandBufferAndRunningItThenEventExecutionIsAborted) { auto buffer0 = createBuffer(1, true); auto buffer1 = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 2>{{buffer0.get(), buffer1.get()}}); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); ultBcsCsr->callBaseFlushBcsTask = false; ultBcsCsr->flushBcsTaskReturnValue = std::nullopt; UserEvent userEvent; cl_event waitlist[] = {&userEvent}; cl_event kernelEvent{}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, &kernelEvent); userEvent.setStatus(CL_COMPLETE); auto abortedEvent = castToObjectOrAbort<Event>(kernelEvent); EXPECT_EQ(Event::executionAbortedDueToGpuHang, abortedEvent->peekExecutionStatus()); abortedEvent->release(); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationWhenEnqueueIsCalledThenDoImplicitFlushOnGpgpuCsr) { auto buffer = createBuffer(1, true); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); EXPECT_EQ(0u, ultCsr->taskCount); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); EXPECT_EQ(1u, ultCsr->taskCount); EXPECT_TRUE(ultCsr->recordedDispatchFlags.implicitFlush); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenBlitTranslationOnGfxAllocationWhenEnqueueIsCalledThenDoImplicitFlushOnGpgpuCsr) { auto gfxAllocation = createGfxAllocation(1, true); setMockKernelArgs(std::array<GraphicsAllocation *, 1>{{gfxAllocation}}); auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); EXPECT_EQ(0u, ultCsr->taskCount); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); EXPECT_EQ(1u, ultCsr->taskCount); EXPECT_TRUE(ultCsr->recordedDispatchFlags.implicitFlush); device->getMemoryManager()->freeGraphicsMemory(gfxAllocation); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenCacheFlushRequiredWhenHandlingDependenciesThenPutAllNodesToDeferredList) { DebugManager.flags.ForceCacheFlushForBcs.set(1); auto gfxAllocation = createGfxAllocation(1, true); setMockKernelArgs(std::array<GraphicsAllocation *, 1>{{gfxAllocation}}); TimestampPacketContainer *deferredTimestampPackets = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->deferredTimestampPackets.get(); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); EXPECT_EQ(4u, deferredTimestampPackets->peekNodes().size()); // Barrier, CacheFlush, AuxToNonAux, NonAuxToAux device->getMemoryManager()->freeGraphicsMemory(gfxAllocation); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenCacheFlushRequiredWhenHandlingDependenciesForBlockedEnqueueThenPutAllNodesToDeferredList) { DebugManager.flags.ForceCacheFlushForBcs.set(1); auto gfxAllocation = createGfxAllocation(1, true); setMockKernelArgs(std::array<GraphicsAllocation *, 1>{{gfxAllocation}}); TimestampPacketContainer *deferredTimestampPackets = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->deferredTimestampPackets.get(); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); userEvent.setStatus(CL_COMPLETE); EXPECT_FALSE(commandQueue->isQueueBlocked()); EXPECT_EQ(4u, deferredTimestampPackets->peekNodes().size()); // Barrier, CacheFlush, AuxToNonAux, NonAuxToAux device->getMemoryManager()->freeGraphicsMemory(gfxAllocation); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenTerminatedLatestEnqueuedTaskWhenHandlingDependenciesForBlockedEnqueueThenDoNotPutAllNodesToDeferredListAndSetTimestampData) { DebugManager.flags.ForceCacheFlushForBcs.set(1); auto gfxAllocation = createGfxAllocation(1, true); setMockKernelArgs(std::array<GraphicsAllocation *, 1>{{gfxAllocation}}); TimestampPacketContainer *deferredTimestampPackets = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->deferredTimestampPackets.get(); TimestampPacketContainer *timestampPacketContainer = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->timestampPacketContainer.get(); UserEvent userEvent; cl_event waitlist[] = {&userEvent}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); userEvent.setStatus(-1); EXPECT_FALSE(commandQueue->isQueueBlocked()); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); EXPECT_EQ(timestampPacketContainer->peekNodes()[0]->getContextEndValue(0u), 0xffffffff); device->getMemoryManager()->freeGraphicsMemory(gfxAllocation); } HWTEST_TEMPLATED_F(BlitAuxTranslationTests, givenTerminatedTaskWhenHandlingDependenciesForBlockedEnqueueThenDoNotPutAllNodesToDeferredListAndDoNotSetTimestampData) { DebugManager.flags.ForceCacheFlushForBcs.set(1); auto gfxAllocation = createGfxAllocation(1, true); setMockKernelArgs(std::array<GraphicsAllocation *, 1>{{gfxAllocation}}); TimestampPacketContainer *deferredTimestampPackets = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->deferredTimestampPackets.get(); TimestampPacketContainer *timestampPacketContainer = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get())->timestampPacketContainer.get(); UserEvent userEvent; [[maybe_unused]] UserEvent *ue = &userEvent; cl_event waitlist[] = {&userEvent}; UserEvent userEvent1; [[maybe_unused]] UserEvent *ue1 = &userEvent1; cl_event waitlist1[] = {&userEvent1}; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist, nullptr); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 1, waitlist1, nullptr); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); userEvent.setStatus(-1); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); EXPECT_EQ(1u, timestampPacketContainer->peekNodes().size()); EXPECT_EQ(timestampPacketContainer->peekNodes()[0]->getContextEndValue(0u), 1u); userEvent1.setStatus(-1); EXPECT_FALSE(commandQueue->isQueueBlocked()); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); EXPECT_EQ(1u, timestampPacketContainer->peekNodes().size()); EXPECT_EQ(timestampPacketContainer->peekNodes()[0]->getContextEndValue(0u), 0xffffffff); device->getMemoryManager()->freeGraphicsMemory(gfxAllocation); } using BlitEnqueueWithNoTimestampPacketTests = BlitEnqueueTests<0>; HWTEST_TEMPLATED_F(BlitEnqueueWithNoTimestampPacketTests, givenNoTimestampPacketsWritewhenEnqueueingBlitOperationThenEnginesAreSynchronized) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; using WALKER_TYPE = typename FamilyType::WALKER_TYPE; const size_t bufferSize = 1u; auto buffer = createBuffer(bufferSize, false); auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); ASSERT_EQ(0u, ultCsr->taskCount); setMockKernelArgs(std::array<Buffer *, 1>{{buffer.get()}}); commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); char cpuBuffer[bufferSize]{}; commandQueue->enqueueReadBuffer(buffer.get(), CL_FALSE, 0, bufferSize, cpuBuffer, nullptr, 0, nullptr, nullptr); commandQueue->finish(); auto bcsCommands = getCmdList<FamilyType>(bcsCsr->getCS(0), 0); auto ccsCommands = getCmdList<FamilyType>(commandQueue->getCS(0), 0); auto cmdFound = expectCommand<MI_SEMAPHORE_WAIT>(bcsCommands.begin(), bcsCommands.end()); cmdFound = expectMiFlush<MI_FLUSH_DW>(cmdFound++, bcsCommands.end()); cmdFound = expectCommand<WALKER_TYPE>(ccsCommands.begin(), ccsCommands.end()); expectNoCommand<MI_SEMAPHORE_WAIT>(cmdFound++, ccsCommands.end()); } struct BlitEnqueueWithDebugCapabilityTests : public BlitEnqueueTests<0> { template <typename MI_SEMAPHORE_WAIT> void findSemaphores(GenCmdList &cmdList) { auto semaphore = find<MI_SEMAPHORE_WAIT *>(cmdList.begin(), cmdList.end()); while (semaphore != cmdList.end()) { auto semaphoreCmd = genCmdCast<MI_SEMAPHORE_WAIT *>(*semaphore); if (static_cast<uint32_t>(DebugPauseState::hasUserStartConfirmation) == semaphoreCmd->getSemaphoreDataDword() && debugPauseStateAddress == semaphoreCmd->getSemaphoreGraphicsAddress()) { EXPECT_EQ(MI_SEMAPHORE_WAIT::COMPARE_OPERATION::COMPARE_OPERATION_SAD_EQUAL_SDD, semaphoreCmd->getCompareOperation()); EXPECT_EQ(MI_SEMAPHORE_WAIT::WAIT_MODE::WAIT_MODE_POLLING_MODE, semaphoreCmd->getWaitMode()); semaphoreBeforeCopyFound++; } if (static_cast<uint32_t>(DebugPauseState::hasUserEndConfirmation) == semaphoreCmd->getSemaphoreDataDword() && debugPauseStateAddress == semaphoreCmd->getSemaphoreGraphicsAddress()) { EXPECT_EQ(MI_SEMAPHORE_WAIT::COMPARE_OPERATION::COMPARE_OPERATION_SAD_EQUAL_SDD, semaphoreCmd->getCompareOperation()); EXPECT_EQ(MI_SEMAPHORE_WAIT::WAIT_MODE::WAIT_MODE_POLLING_MODE, semaphoreCmd->getWaitMode()); semaphoreAfterCopyFound++; } semaphore = find<MI_SEMAPHORE_WAIT *>(++semaphore, cmdList.end()); } } template <typename MI_FLUSH_DW> void findMiFlushes(GenCmdList &cmdList) { auto miFlush = find<MI_FLUSH_DW *>(cmdList.begin(), cmdList.end()); while (miFlush != cmdList.end()) { auto miFlushCmd = genCmdCast<MI_FLUSH_DW *>(*miFlush); if (static_cast<uint32_t>(DebugPauseState::waitingForUserStartConfirmation) == miFlushCmd->getImmediateData() && debugPauseStateAddress == miFlushCmd->getDestinationAddress()) { EXPECT_EQ(MI_FLUSH_DW::POST_SYNC_OPERATION_WRITE_IMMEDIATE_DATA_QWORD, miFlushCmd->getPostSyncOperation()); miFlushBeforeCopyFound++; } if (static_cast<uint32_t>(DebugPauseState::waitingForUserEndConfirmation) == miFlushCmd->getImmediateData() && debugPauseStateAddress == miFlushCmd->getDestinationAddress()) { EXPECT_EQ(MI_FLUSH_DW::POST_SYNC_OPERATION_WRITE_IMMEDIATE_DATA_QWORD, miFlushCmd->getPostSyncOperation()); miFlushAfterCopyFound++; } miFlush = find<MI_FLUSH_DW *>(++miFlush, cmdList.end()); } } uint32_t semaphoreBeforeCopyFound = 0; uint32_t semaphoreAfterCopyFound = 0; uint32_t miFlushBeforeCopyFound = 0; uint32_t miFlushAfterCopyFound = 0; ReleaseableObjectPtr<Buffer> buffer; uint64_t debugPauseStateAddress = 0; int hostPtr = 0; }; HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenDebugFlagSetWhenDispatchingBlitEnqueueThenAddPausingCommands) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); debugPauseStateAddress = ultBcsCsr->getDebugPauseStateGPUAddress(); buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(1); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(ultBcsCsr->commandStream); findSemaphores<MI_SEMAPHORE_WAIT>(hwParser.cmdList); EXPECT_EQ(1u, semaphoreBeforeCopyFound); EXPECT_EQ(1u, semaphoreAfterCopyFound); findMiFlushes<MI_FLUSH_DW>(hwParser.cmdList); EXPECT_EQ(1u, miFlushBeforeCopyFound); EXPECT_EQ(1u, miFlushAfterCopyFound); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenGpuHangOnFlushBcsTaskAndDebugFlagSetWhenDispatchingBlitEnqueueThenOutOfResourcesIsReturned) { auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); ultBcsCsr->callBaseFlushBcsTask = false; ultBcsCsr->flushBcsTaskReturnValue = std::nullopt; buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(1); const auto result = commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); EXPECT_EQ(CL_OUT_OF_RESOURCES, result); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenDebugFlagSetToMinusTwoWhenDispatchingBlitEnqueueThenAddPausingCommandsForEachEnqueue) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); debugPauseStateAddress = ultBcsCsr->getDebugPauseStateGPUAddress(); buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(-2); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(ultBcsCsr->commandStream); findSemaphores<MI_SEMAPHORE_WAIT>(hwParser.cmdList); EXPECT_EQ(2u, semaphoreBeforeCopyFound); EXPECT_EQ(2u, semaphoreAfterCopyFound); findMiFlushes<MI_FLUSH_DW>(hwParser.cmdList); EXPECT_EQ(2u, miFlushBeforeCopyFound); EXPECT_EQ(2u, miFlushAfterCopyFound); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenPauseModeSetToBeforeOnlyWhenDispatchingBlitEnqueueThenAddPauseCommandsOnlyBeforeEnqueue) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); debugPauseStateAddress = ultBcsCsr->getDebugPauseStateGPUAddress(); buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(0); DebugManager.flags.PauseOnGpuMode.set(PauseOnGpuProperties::PauseMode::BeforeWorkload); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(ultBcsCsr->commandStream); findSemaphores<MI_SEMAPHORE_WAIT>(hwParser.cmdList); EXPECT_EQ(1u, semaphoreBeforeCopyFound); EXPECT_EQ(0u, semaphoreAfterCopyFound); findMiFlushes<MI_FLUSH_DW>(hwParser.cmdList); EXPECT_EQ(1u, miFlushBeforeCopyFound); EXPECT_EQ(0u, miFlushAfterCopyFound); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenPauseModeSetToAfterOnlyWhenDispatchingBlitEnqueueThenAddPauseCommandsOnlyAfterEnqueue) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); debugPauseStateAddress = ultBcsCsr->getDebugPauseStateGPUAddress(); buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(0); DebugManager.flags.PauseOnGpuMode.set(PauseOnGpuProperties::PauseMode::AfterWorkload); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(ultBcsCsr->commandStream); findSemaphores<MI_SEMAPHORE_WAIT>(hwParser.cmdList); EXPECT_EQ(0u, semaphoreBeforeCopyFound); EXPECT_EQ(1u, semaphoreAfterCopyFound); findMiFlushes<MI_FLUSH_DW>(hwParser.cmdList); EXPECT_EQ(0u, miFlushBeforeCopyFound); EXPECT_EQ(1u, miFlushAfterCopyFound); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenPauseModeSetToBeforeAndAfterWorkloadWhenDispatchingBlitEnqueueThenAddPauseCommandsAroundEnqueue) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; using MI_FLUSH_DW = typename FamilyType::MI_FLUSH_DW; auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); debugPauseStateAddress = ultBcsCsr->getDebugPauseStateGPUAddress(); buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; DebugManager.flags.PauseOnBlitCopy.set(0); DebugManager.flags.PauseOnGpuMode.set(PauseOnGpuProperties::PauseMode::BeforeAndAfterWorkload); commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(ultBcsCsr->commandStream); findSemaphores<MI_SEMAPHORE_WAIT>(hwParser.cmdList); EXPECT_EQ(1u, semaphoreBeforeCopyFound); EXPECT_EQ(1u, semaphoreAfterCopyFound); findMiFlushes<MI_FLUSH_DW>(hwParser.cmdList); EXPECT_EQ(1u, miFlushBeforeCopyFound); EXPECT_EQ(1u, miFlushAfterCopyFound); } HWTEST_TEMPLATED_F(BlitEnqueueWithDebugCapabilityTests, givenDebugFlagSetWhenCreatingCsrThenCreateDebugThread) { DebugManager.flags.PauseOnBlitCopy.set(1); auto localDevice = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(nullptr)); auto ultCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(localDevice->getDefaultEngine().commandStreamReceiver); EXPECT_NE(nullptr, ultCsr->userPauseConfirmation.get()); } struct BlitEnqueueFlushTests : public BlitEnqueueTests<1> { template <typename FamilyType> class MyUltCsr : public UltCommandStreamReceiver<FamilyType> { public: using UltCommandStreamReceiver<FamilyType>::UltCommandStreamReceiver; SubmissionStatus flush(BatchBuffer &batchBuffer, ResidencyContainer &allocationsForResidency) override { latestFlushedCounter = ++(*flushCounter); return UltCommandStreamReceiver<FamilyType>::flush(batchBuffer, allocationsForResidency); } static CommandStreamReceiver *create(bool withAubDump, ExecutionEnvironment &executionEnvironment, uint32_t rootDeviceIndex, const DeviceBitfield deviceBitfield) { return new MyUltCsr<FamilyType>(executionEnvironment, rootDeviceIndex, deviceBitfield); } uint32_t *flushCounter = nullptr; uint32_t latestFlushedCounter = 0; }; template <typename T> void setUpT() { auto csrCreateFcn = &commandStreamReceiverFactory[IGFX_MAX_CORE + defaultHwInfo->platform.eRenderCoreFamily]; variableBackup = std::make_unique<VariableBackup<CommandStreamReceiverCreateFunc>>(csrCreateFcn); *csrCreateFcn = MyUltCsr<T>::create; BlitEnqueueTests<1>::setUpT<T>(); } std::unique_ptr<VariableBackup<CommandStreamReceiverCreateFunc>> variableBackup; }; HWTEST_TEMPLATED_F(BlitEnqueueFlushTests, givenNonBlockedQueueWhenBlitEnqueuedThenFlushGpgpuCsrFirst) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; uint32_t flushCounter = 0; auto myUltGpgpuCsr = static_cast<MyUltCsr<FamilyType> *>(gpgpuCsr); myUltGpgpuCsr->flushCounter = &flushCounter; auto myUltBcsCsr = static_cast<MyUltCsr<FamilyType> *>(bcsCsr); myUltBcsCsr->flushCounter = &flushCounter; commandQueue->enqueueWriteBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); EXPECT_EQ(1u, myUltGpgpuCsr->latestFlushedCounter); EXPECT_EQ(2u, myUltBcsCsr->latestFlushedCounter); } HWTEST_TEMPLATED_F(BlitEnqueueFlushTests, givenGpuHangAndBlockingCallAndNonBlockedQueueWhenBlitEnqueuedThenOutOfResourcesIsReturned) { DebugManager.flags.MakeEachEnqueueBlocking.set(true); auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; uint32_t flushCounter = 0; auto myUltGpgpuCsr = static_cast<MyUltCsr<FamilyType> *>(gpgpuCsr); myUltGpgpuCsr->flushCounter = &flushCounter; auto myUltBcsCsr = static_cast<MyUltCsr<FamilyType> *>(bcsCsr); myUltBcsCsr->flushCounter = &flushCounter; auto mockCommandQueue = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCommandQueue->waitForAllEnginesReturnValue = WaitStatus::GpuHang; const auto enqueueResult = mockCommandQueue->enqueueWriteBuffer(buffer.get(), CL_FALSE, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); EXPECT_EQ(CL_OUT_OF_RESOURCES, enqueueResult); EXPECT_EQ(1, mockCommandQueue->waitForAllEnginesCalledCount); } HWTEST_TEMPLATED_F(BlitEnqueueFlushTests, givenBlockedQueueWhenBlitEnqueuedThenFlushGpgpuCsrFirst) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; uint32_t flushCounter = 0; auto myUltGpgpuCsr = static_cast<MyUltCsr<FamilyType> *>(gpgpuCsr); myUltGpgpuCsr->flushCounter = &flushCounter; auto myUltBcsCsr = static_cast<MyUltCsr<FamilyType> *>(bcsCsr); myUltBcsCsr->flushCounter = &flushCounter; UserEvent userEvent; cl_event waitlist[] = {&userEvent}; commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 1, waitlist, nullptr); userEvent.setStatus(CL_COMPLETE); EXPECT_EQ(1u, myUltGpgpuCsr->latestFlushedCounter); EXPECT_EQ(2u, myUltBcsCsr->latestFlushedCounter); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitEnqueueFlushTests, givenGpuHangOnFlushBcsTaskAndBlockedQueueWhenBlitEnqueuedThenEventIsAborted) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; uint32_t flushCounter = 0; auto myUltGpgpuCsr = static_cast<MyUltCsr<FamilyType> *>(gpgpuCsr); myUltGpgpuCsr->flushCounter = &flushCounter; auto myUltBcsCsr = static_cast<MyUltCsr<FamilyType> *>(bcsCsr); myUltBcsCsr->flushCounter = &flushCounter; myUltBcsCsr->callBaseFlushBcsTask = false; myUltBcsCsr->flushBcsTaskReturnValue = std::nullopt; UserEvent userEvent; cl_event waitlist[] = {&userEvent}; cl_event writeBufferEvent{}; commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 1, waitlist, &writeBufferEvent); userEvent.setStatus(CL_COMPLETE); auto abortedEvent = castToObjectOrAbort<Event>(writeBufferEvent); EXPECT_EQ(Event::executionAbortedDueToGpuHang, abortedEvent->peekExecutionStatus()); abortedEvent->release(); } HWTEST_TEMPLATED_F(BlitEnqueueFlushTests, givenDebugFlagSetWhenCheckingBcsCacheFlushRequirementThenReturnCorrectValue) { auto mockCommandQueue = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); DebugManager.flags.ForceCacheFlushForBcs.set(0); EXPECT_FALSE(mockCommandQueue->isCacheFlushForBcsRequired()); DebugManager.flags.ForceCacheFlushForBcs.set(1); EXPECT_TRUE(mockCommandQueue->isCacheFlushForBcsRequired()); } using BlitEnqueueTaskCountTests = BlitEnqueueTests<1>; HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, whenWaitUntilCompletionCalledThenWaitForSpecificBcsTaskCount) { uint32_t gpgpuTaskCount = 123; uint32_t bcsTaskCount = 123; CopyEngineState bcsState{bcsCsr->getOsContext().getEngineType(), bcsTaskCount}; commandQueue->waitUntilComplete(gpgpuTaskCount, Range{&bcsState}, 0, false); EXPECT_EQ(gpgpuTaskCount, static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(bcsTaskCount, static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenEventWithNotreadyBcsTaskCountThenDontReportCompletion) { const uint32_t gpgpuTaskCount = 123; const uint32_t bcsTaskCount = 123; *gpgpuCsr->getTagAddress() = gpgpuTaskCount; *bcsCsr->getTagAddress() = bcsTaskCount - 1; commandQueue->updateBcsTaskCount(bcsCsr->getOsContext().getEngineType(), bcsTaskCount); Event event(commandQueue.get(), CL_COMMAND_WRITE_BUFFER, 1, gpgpuTaskCount); event.setupBcs(bcsCsr->getOsContext().getEngineType()); event.updateCompletionStamp(gpgpuTaskCount, bcsTaskCount, 1, 0); event.updateExecutionStatus(); EXPECT_EQ(static_cast<cl_int>(CL_SUBMITTED), event.peekExecutionStatus()); *bcsCsr->getTagAddress() = bcsTaskCount; event.updateExecutionStatus(); EXPECT_EQ(static_cast<cl_int>(CL_COMPLETE), event.peekExecutionStatus()); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenEventWhenWaitingForCompletionThenWaitForCurrentBcsTaskCount) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); cl_event outEvent1, outEvent2; commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, &outEvent1); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, &outEvent2); clWaitForEvents(1, &outEvent2); EXPECT_EQ(2u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(2u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clWaitForEvents(1, &outEvent1); EXPECT_EQ(1u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(1u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clReleaseEvent(outEvent1); clReleaseEvent(outEvent2); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenBufferDumpingEnabledWhenEnqueueingThenSetCorrectDumpOption) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; DebugManager.flags.AUBDumpAllocsOnEnqueueReadOnly.set(true); DebugManager.flags.AUBDumpBufferFormat.set("BIN"); auto mockCommandQueue = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); { // BCS enqueue commandQueue->enqueueReadBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); EXPECT_TRUE(mockCommandQueue->notifyEnqueueReadBufferCalled); EXPECT_TRUE(mockCommandQueue->useBcsCsrOnNotifyEnabled); mockCommandQueue->notifyEnqueueReadBufferCalled = false; } { // Non-BCS enqueue DebugManager.flags.EnableBlitterForEnqueueOperations.set(0); commandQueue->enqueueReadBuffer(buffer.get(), true, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); EXPECT_TRUE(mockCommandQueue->notifyEnqueueReadBufferCalled); EXPECT_FALSE(mockCommandQueue->useBcsCsrOnNotifyEnabled); } } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenBlockedEventWhenWaitingForCompletionThenWaitForCurrentBcsTaskCount) { auto buffer = createBuffer(1, false); buffer->forceDisallowCPUCopy = true; int hostPtr = 0; auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); cl_event outEvent1, outEvent2; UserEvent userEvent; cl_event waitlist1 = &userEvent; cl_event *waitlist2 = &outEvent1; commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 1, &waitlist1, &outEvent1); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 1, waitlist2, &outEvent2); userEvent.setStatus(CL_COMPLETE); clWaitForEvents(1, &outEvent2); EXPECT_EQ(2u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(2u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clWaitForEvents(1, &outEvent1); EXPECT_EQ(1u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(1u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clReleaseEvent(outEvent1); clReleaseEvent(outEvent2); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenBlockedEnqueueWithoutKernelWhenWaitingForCompletionThenWaitForCurrentBcsTaskCount) { auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); cl_event outEvent1, outEvent2; UserEvent userEvent; cl_event waitlist1 = &userEvent; cl_event *waitlist2 = &outEvent1; commandQueue->enqueueMarkerWithWaitList(1, &waitlist1, &outEvent1); commandQueue->enqueueMarkerWithWaitList(1, waitlist2, &outEvent2); userEvent.setStatus(CL_COMPLETE); clWaitForEvents(1, &outEvent2); EXPECT_EQ(1u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(0u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clWaitForEvents(1, &outEvent1); EXPECT_EQ(0u, ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(0u, ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount.load()); clReleaseEvent(outEvent1); clReleaseEvent(outEvent2); EXPECT_FALSE(commandQueue->isQueueBlocked()); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenEventFromCpuCopyWhenWaitingForCompletionThenWaitForCurrentBcsTaskCount) { auto buffer = createBuffer(1, false); int hostPtr = 0; auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); ultGpgpuCsr->taskCount = 1; commandQueue->taskCount = 1; ultBcsCsr->taskCount = 2; commandQueue->updateBcsTaskCount(ultBcsCsr->getOsContext().getEngineType(), 2); cl_event outEvent1, outEvent2; commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, &outEvent1); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, &outEvent2); clWaitForEvents(1, &outEvent2); EXPECT_EQ(3u, static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(4u, static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); clWaitForEvents(1, &outEvent1); EXPECT_EQ(2u, static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); EXPECT_EQ(3u, static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr)->latestWaitForCompletionWithTimeoutTaskCount.load()); clReleaseEvent(outEvent1); clReleaseEvent(outEvent2); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenMarkerThatFollowsCopyOperationWhenItIsWaitedItHasProperDependencies) { auto buffer = createBuffer(1, false); int hostPtr = 0; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto mockCmdQueue = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); mockCmdQueue->commandQueueProperties |= CL_QUEUE_PROFILING_ENABLE; cl_event outEvent1; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); auto offset = mockCmdQueue->getCS(0).getUsed(); //marker needs to program semaphore commandQueue->enqueueMarkerWithWaitList(0, nullptr, &outEvent1); auto cmdListQueue = getCmdList<FamilyType>(mockCmdQueue->getCS(0), offset); expectCommand<MI_SEMAPHORE_WAIT>(cmdListQueue.begin(), cmdListQueue.end()); clReleaseEvent(outEvent1); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenWaitlistWithTimestampPacketWhenEnqueueingThenDeferWaitlistNodes) { device->getUltCommandStreamReceiver<FamilyType>().timestampPacketWriteEnabled = true; auto buffer = createBuffer(1, false); auto mockCmdQueue = static_cast<MockCommandQueueHw<FamilyType> *>(commandQueue.get()); TimestampPacketContainer *deferredTimestampPackets = mockCmdQueue->deferredTimestampPackets.get(); MockTimestampPacketContainer timestamp(*device->getGpgpuCommandStreamReceiver().getTimestampPacketAllocator(), 1); Event waitlistEvent(mockCmdQueue, 0, 0, 0); waitlistEvent.addTimestampPacketNodes(timestamp); cl_event waitlist[] = {&waitlistEvent}; mockCmdQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 1, waitlist, nullptr); auto deferredNodesCount = deferredTimestampPackets->peekNodes().size(); EXPECT_TRUE(deferredNodesCount >= 1); bool waitlistNodeFound = false; for (auto &node : deferredTimestampPackets->peekNodes()) { if (node->getGpuAddress() == timestamp.peekNodes()[0]->getGpuAddress()) { waitlistNodeFound = true; } } EXPECT_TRUE(waitlistNodeFound); mockCmdQueue->flush(); EXPECT_EQ(deferredNodesCount, deferredTimestampPackets->peekNodes().size()); mockCmdQueue->finish(); EXPECT_EQ(0u, deferredTimestampPackets->peekNodes().size()); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenMarkerThatFollowsCopyOperationWhenItIsWaitedItHasProperDependenciesOnWait) { auto buffer = createBuffer(1, false); int hostPtr = 0; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; cl_event outEvent1; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); commandQueue->enqueueMarkerWithWaitList(0, nullptr, &outEvent1); auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); //make sure we wait for both clWaitForEvents(1, &outEvent1); EXPECT_EQ(ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount, ultBcsCsr->taskCount); EXPECT_EQ(ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount, ultGpgpuCsr->taskCount); clWaitForEvents(1, &outEvent1); clReleaseEvent(outEvent1); } HWTEST_TEMPLATED_F(BlitEnqueueTaskCountTests, givenMarkerThatFollowsCopyOperationWhenItIsWaitedItHasProperDependenciesOnWaitEvenWhenMultipleMarkersAreSequenced) { auto buffer = createBuffer(1, false); int hostPtr = 0; using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; cl_event outEvent1, outEvent2; commandQueue->enqueueKernel(mockKernel->mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); commandQueue->enqueueWriteBuffer(buffer.get(), false, 0, 1, &hostPtr, nullptr, 0, nullptr, nullptr); commandQueue->enqueueMarkerWithWaitList(0, nullptr, &outEvent1); commandQueue->enqueueMarkerWithWaitList(0, nullptr, nullptr); commandQueue->enqueueMarkerWithWaitList(0, nullptr, &outEvent2); auto ultGpgpuCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(gpgpuCsr); auto ultBcsCsr = static_cast<UltCommandStreamReceiver<FamilyType> *>(bcsCsr); //make sure we wait for both clWaitForEvents(1, &outEvent2); EXPECT_EQ(ultBcsCsr->latestWaitForCompletionWithTimeoutTaskCount, ultBcsCsr->taskCount); EXPECT_EQ(ultGpgpuCsr->latestWaitForCompletionWithTimeoutTaskCount, ultGpgpuCsr->taskCount); clWaitForEvents(1, &outEvent2); clReleaseEvent(outEvent1); clReleaseEvent(outEvent2); } } // namespace NEO
44.241925
182
0.753453
mattcarter2017
62c546c1cbef1d98d36b2dca1330d78398364851
860
cpp
C++
p728e/self_dividing_numbers.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
1
2020-02-20T12:04:46.000Z
2020-02-20T12:04:46.000Z
p728e/self_dividing_numbers.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
null
null
null
p728e/self_dividing_numbers.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
null
null
null
// g++ -std=c++11 *.cpp -o test && ./test && rm -f test #include <vector> #include <iostream> using namespace std; class Solution { public: vector<int> selfDividingNumbers(int left, int right) { auto isSelfDividingNumber = [](int x) -> bool { int n = x; while (n) { if (n % 10 == 0 || x % (n % 10) != 0) return false; n /= 10; } return true; }; vector<int> ans; for (int n= left; n<= right; ++n) { if (isSelfDividingNumber(n)) ans.push_back(n); } return ans; } }; int main(int argc, char const *argv[]) { cout << "Self dividing numbers from 1 to 100 -> ["; Solution sol; auto ans = sol.selfDividingNumbers(1, 100); for (auto a: ans) cout << a << ", "; cout << "]" << endl; return 0; }
25.294118
67
0.489535
l33tdaima
62d37f1ac5e0834d7c92802fc4c0bc486ed7b155
52,826
cpp
C++
java/lib/NetworkTablesJNI.cpp
FRC-Team-5522/ntcore
64f2033972515d5bdd668fd83d59a14fdc45dc95
[ "BSD-3-Clause" ]
null
null
null
java/lib/NetworkTablesJNI.cpp
FRC-Team-5522/ntcore
64f2033972515d5bdd668fd83d59a14fdc45dc95
[ "BSD-3-Clause" ]
null
null
null
java/lib/NetworkTablesJNI.cpp
FRC-Team-5522/ntcore
64f2033972515d5bdd668fd83d59a14fdc45dc95
[ "BSD-3-Clause" ]
null
null
null
#include <jni.h> #include <atomic> #include <cassert> #include <condition_variable> #include <mutex> #include <sstream> #include <queue> #include <thread> #include "edu_wpi_first_wpilibj_networktables_NetworkTablesJNI.h" #include "ntcore.h" #include "support/atomic_static.h" #include "support/jni_util.h" #include "support/SafeThread.h" #include "llvm/ConvertUTF.h" #include "llvm/SmallString.h" #include "llvm/SmallVector.h" using namespace wpi::java; // // Globals and load/unload // // Used for callback. static JavaVM *jvm = nullptr; static JClass booleanCls; static JClass doubleCls; static JClass connectionInfoCls; static JClass entryInfoCls; static JException keyNotDefinedEx; static JException persistentEx; static JException illegalArgEx; static JException nullPointerEx; // Thread-attached environment for listener callbacks. static JNIEnv *listenerEnv = nullptr; static void ListenerOnStart() { if (!jvm) return; JNIEnv *env; JavaVMAttachArgs args; args.version = JNI_VERSION_1_2; args.name = const_cast<char*>("NTListener"); args.group = nullptr; if (jvm->AttachCurrentThreadAsDaemon(reinterpret_cast<void **>(&env), &args) != JNI_OK) return; if (!env || !env->functions) return; listenerEnv = env; } static void ListenerOnExit() { listenerEnv = nullptr; if (!jvm) return; jvm->DetachCurrentThread(); } extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { jvm = vm; JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; // Cache references to classes booleanCls = JClass(env, "java/lang/Boolean"); if (!booleanCls) return JNI_ERR; doubleCls = JClass(env, "java/lang/Double"); if (!doubleCls) return JNI_ERR; connectionInfoCls = JClass(env, "edu/wpi/first/wpilibj/networktables/ConnectionInfo"); if (!connectionInfoCls) return JNI_ERR; entryInfoCls = JClass(env, "edu/wpi/first/wpilibj/networktables/EntryInfo"); if (!entryInfoCls) return JNI_ERR; keyNotDefinedEx = JException( env, "edu/wpi/first/wpilibj/networktables/NetworkTableKeyNotDefined"); if (!keyNotDefinedEx) return JNI_ERR; persistentEx = JException( env, "edu/wpi/first/wpilibj/networktables/PersistentException"); if (!persistentEx) return JNI_ERR; illegalArgEx = JException(env, "java/lang/IllegalArgumentException"); if (!illegalArgEx) return JNI_ERR; nullPointerEx = JException(env, "java/lang/NullPointerException"); if (!nullPointerEx) return JNI_ERR; // Initial configuration of listener start/exit nt::SetListenerOnStart(ListenerOnStart); nt::SetListenerOnExit(ListenerOnExit); return JNI_VERSION_1_6; } JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) return; // Delete global references booleanCls.free(env); doubleCls.free(env); connectionInfoCls.free(env); entryInfoCls.free(env); keyNotDefinedEx.free(env); persistentEx.free(env); illegalArgEx.free(env); nullPointerEx.free(env); jvm = nullptr; } } // extern "C" // // Helper class to create and clean up a global reference // template <typename T> class JGlobal { public: JGlobal(JNIEnv *env, T obj) : m_obj(static_cast<T>(env->NewGlobalRef(obj))) {} ~JGlobal() { if (!jvm || nt::NotifierDestroyed()) return; JNIEnv *env; bool attached = false; // don't attach and de-attach if already attached to a thread. if (jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) == JNI_EDETACHED) { if (jvm->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) != JNI_OK) return; attached = true; } if (!env || !env->functions) return; env->DeleteGlobalRef(m_obj); if (attached) jvm->DetachCurrentThread(); } operator T() { return m_obj; } T obj() { return m_obj; } private: T m_obj; }; // // Helper class to create and clean up a weak global reference // template <typename T> class JWeakGlobal { public: JWeakGlobal(JNIEnv *env, T obj) : m_obj(static_cast<T>(env->NewWeakGlobalRef(obj))) {} ~JWeakGlobal() { if (!jvm || nt::NotifierDestroyed()) return; JNIEnv *env; bool attached = false; // don't attach and de-attach if already attached to a thread. if (jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) == JNI_EDETACHED) { if (jvm->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) != JNI_OK) return; attached = true; } if (!env || !env->functions) return; env->DeleteWeakGlobalRef(m_obj); if (attached) jvm->DetachCurrentThread(); } JLocal<T> obj(JNIEnv *env) { return JLocal<T>{env, env->NewLocalRef(m_obj)}; } private: T m_obj; }; // // Conversions from Java objects to C++ // inline std::shared_ptr<nt::Value> FromJavaRaw(JNIEnv *env, jbyteArray jarr) { CriticalJByteArrayRef ref{env, jarr}; if (!ref) return nullptr; return nt::Value::MakeRaw(ref); } inline std::shared_ptr<nt::Value> FromJavaRawBB(JNIEnv *env, jobject jbb, int len) { JByteArrayRef ref{env, jbb, len}; if (!ref) return nullptr; return nt::Value::MakeRaw(ref.str()); } inline std::shared_ptr<nt::Value> FromJavaRpc(JNIEnv *env, jbyteArray jarr) { CriticalJByteArrayRef ref{env, jarr}; if (!ref) return nullptr; return nt::Value::MakeRpc(ref.str()); } std::shared_ptr<nt::Value> FromJavaBooleanArray(JNIEnv *env, jbooleanArray jarr) { CriticalJBooleanArrayRef ref{env, jarr}; if (!ref) return nullptr; llvm::ArrayRef<jboolean> elements{ref}; size_t len = elements.size(); std::vector<int> arr; arr.reserve(len); for (size_t i = 0; i < len; ++i) arr.push_back(elements[i]); return nt::Value::MakeBooleanArray(arr); } std::shared_ptr<nt::Value> FromJavaDoubleArray(JNIEnv *env, jdoubleArray jarr) { CriticalJDoubleArrayRef ref{env, jarr}; if (!ref) return nullptr; return nt::Value::MakeDoubleArray(ref); } std::shared_ptr<nt::Value> FromJavaStringArray(JNIEnv *env, jobjectArray jarr) { size_t len = env->GetArrayLength(jarr); std::vector<std::string> arr; arr.reserve(len); for (size_t i = 0; i < len; ++i) { JLocal<jstring> elem{ env, static_cast<jstring>(env->GetObjectArrayElement(jarr, i))}; if (!elem) return nullptr; arr.push_back(JStringRef{env, elem}.str()); } return nt::Value::MakeStringArray(std::move(arr)); } // // Conversions from C++ to Java objects // static jobject MakeJObject(JNIEnv *env, const nt::Value& value) { static jmethodID booleanConstructor = nullptr; static jmethodID doubleConstructor = nullptr; if (!booleanConstructor) booleanConstructor = env->GetMethodID(booleanCls, "<init>", "(Z)V"); if (!doubleConstructor) doubleConstructor = env->GetMethodID(doubleCls, "<init>", "(D)V"); switch (value.type()) { case NT_BOOLEAN: return env->NewObject(booleanCls, booleanConstructor, (jboolean)(value.GetBoolean() ? 1 : 0)); case NT_DOUBLE: return env->NewObject(doubleCls, doubleConstructor, (jdouble)value.GetDouble()); case NT_STRING: return MakeJString(env, value.GetString()); case NT_RAW: return MakeJByteArray(env, value.GetRaw()); case NT_BOOLEAN_ARRAY: return MakeJBooleanArray(env, value.GetBooleanArray()); case NT_DOUBLE_ARRAY: return MakeJDoubleArray(env, value.GetDoubleArray()); case NT_STRING_ARRAY: return MakeJStringArray(env, value.GetStringArray()); case NT_RPC: return MakeJByteArray(env, value.GetRpc()); default: return nullptr; } } static jobject MakeJObject(JNIEnv *env, const nt::ConnectionInfo &info) { static jmethodID constructor = env->GetMethodID(connectionInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;IJI)V"); JLocal<jstring> remote_id{env, MakeJString(env, info.remote_id)}; JLocal<jstring> remote_ip{env, MakeJString(env, info.remote_ip)}; return env->NewObject(connectionInfoCls, constructor, remote_id.obj(), remote_ip.obj(), (jint)info.remote_port, (jlong)info.last_update, (jint)info.protocol_version); } static jobject MakeJObject(JNIEnv *env, const nt::EntryInfo &info) { static jmethodID constructor = env->GetMethodID(entryInfoCls, "<init>", "(Ljava/lang/String;IIJ)V"); JLocal<jstring> name{env, MakeJString(env, info.name)}; return env->NewObject(entryInfoCls, constructor, name.obj(), (jint)info.type, (jint)info.flags, (jlong)info.last_change); } extern "C" { /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: containsKey * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_containsKey (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val) return false; return true; } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getType * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getType (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val) return NT_UNASSIGNED; return val->type(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putBoolean * Signature: (Ljava/lang/String;Z)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putBoolean (JNIEnv *env, jclass, jstring key, jboolean value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } return nt::SetEntryValue(JStringRef{env, key}, nt::Value::MakeBoolean(value != JNI_FALSE)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putDouble * Signature: (Ljava/lang/String;D)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putDouble (JNIEnv *env, jclass, jstring key, jdouble value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } return nt::SetEntryValue(JStringRef{env, key}, nt::Value::MakeDouble(value)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putString * Signature: (Ljava/lang/String;Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putString (JNIEnv *env, jclass, jstring key, jstring value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } return nt::SetEntryValue(JStringRef{env, key}, nt::Value::MakeString(JStringRef{env, value})); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putRaw * Signature: (Ljava/lang/String;[B)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putRaw__Ljava_lang_String_2_3B (JNIEnv *env, jclass, jstring key, jbyteArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } auto v = FromJavaRaw(env, value); if (!v) return false; return nt::SetEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putRaw * Signature: (Ljava/lang/String;Ljava/nio/ByteBuffer;I)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putRaw__Ljava_lang_String_2Ljava_nio_ByteBuffer_2I (JNIEnv *env, jclass, jstring key, jobject value, jint len) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } auto v = FromJavaRawBB(env, value, len); if (!v) return false; return nt::SetEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putBooleanArray * Signature: (Ljava/lang/String;[Z)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putBooleanArray (JNIEnv *env, jclass, jstring key, jbooleanArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } auto v = FromJavaBooleanArray(env, value); if (!v) return false; return nt::SetEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putDoubleArray * Signature: (Ljava/lang/String;[D)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putDoubleArray (JNIEnv *env, jclass, jstring key, jdoubleArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } auto v = FromJavaDoubleArray(env, value); if (!v) return false; return nt::SetEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: putStringArray * Signature: (Ljava/lang/String;[Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_putStringArray (JNIEnv *env, jclass, jstring key, jobjectArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return false; } auto v = FromJavaStringArray(env, value); if (!v) return false; return nt::SetEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutBoolean * Signature: (Ljava/lang/String;Z)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutBoolean (JNIEnv *env, jclass, jstring key, jboolean value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } nt::SetEntryTypeValue(JStringRef{env, key}, nt::Value::MakeBoolean(value != JNI_FALSE)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutDouble * Signature: (Ljava/lang/String;D)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutDouble (JNIEnv *env, jclass, jstring key, jdouble value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } nt::SetEntryTypeValue(JStringRef{env, key}, nt::Value::MakeDouble(value)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutString * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutString (JNIEnv *env, jclass, jstring key, jstring value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } nt::SetEntryTypeValue(JStringRef{env, key}, nt::Value::MakeString(JStringRef{env, value})); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutRaw * Signature: (Ljava/lang/String;[B)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutRaw__Ljava_lang_String_2_3B (JNIEnv *env, jclass, jstring key, jbyteArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } auto v = FromJavaRaw(env, value); if (!v) return; nt::SetEntryTypeValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutRaw * Signature: (Ljava/lang/String;Ljava/nio/ByteBuffer;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutRaw__Ljava_lang_String_2Ljava_nio_ByteBuffer_2I (JNIEnv *env, jclass, jstring key, jobject value, jint len) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } auto v = FromJavaRawBB(env, value, len); if (!v) return; nt::SetEntryTypeValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutBooleanArray * Signature: (Ljava/lang/String;[Z)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutBooleanArray (JNIEnv *env, jclass, jstring key, jbooleanArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } auto v = FromJavaBooleanArray(env, value); if (!v) return; nt::SetEntryTypeValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutDoubleArray * Signature: (Ljava/lang/String;[D)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutDoubleArray (JNIEnv *env, jclass, jstring key, jdoubleArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } auto v = FromJavaDoubleArray(env, value); if (!v) return; nt::SetEntryTypeValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: forcePutStringArray * Signature: (Ljava/lang/String;[Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_forcePutStringArray (JNIEnv *env, jclass, jstring key, jobjectArray value) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } if (!value) { nullPointerEx.Throw(env, "value cannot be null"); return; } auto v = FromJavaStringArray(env, value); if (!v) return; nt::SetEntryTypeValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getValue * Signature: (Ljava/lang/String;)Ljava/lang/Object; */ JNIEXPORT jobject JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getValue__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJObject(env, *val); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getBoolean * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getBoolean__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsBoolean()) { keyNotDefinedEx.Throw(env, key); return false; } return val->GetBoolean(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getDouble * Signature: (Ljava/lang/String;)D */ JNIEXPORT jdouble JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getDouble__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsDouble()) { keyNotDefinedEx.Throw(env, key); return 0; } return val->GetDouble(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getString * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getString__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsString()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJString(env, val->GetString()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getRaw * Signature: (Ljava/lang/String;)[B */ JNIEXPORT jbyteArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getRaw__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsRaw()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJByteArray(env, val->GetRaw()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getBooleanArray * Signature: (Ljava/lang/String;)[Z */ JNIEXPORT jbooleanArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getBooleanArray__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsBooleanArray()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJBooleanArray(env, val->GetBooleanArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getDoubleArray * Signature: (Ljava/lang/String;)[D */ JNIEXPORT jdoubleArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getDoubleArray__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsDoubleArray()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJDoubleArray(env, val->GetDoubleArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getStringArray * Signature: (Ljava/lang/String;)[Ljava/lang/String; */ JNIEXPORT jobjectArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getStringArray__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsStringArray()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJStringArray(env, val->GetStringArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getValue * Signature: (Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object; */ JNIEXPORT jobject JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getValue__Ljava_lang_String_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring key, jobject defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val) return defaultValue; return MakeJObject(env, *val); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getBoolean * Signature: (Ljava/lang/String;Z)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getBoolean__Ljava_lang_String_2Z (JNIEnv *env, jclass, jstring key, jboolean defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsBoolean()) return defaultValue; return val->GetBoolean(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getDouble * Signature: (Ljava/lang/String;D)D */ JNIEXPORT jdouble JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getDouble__Ljava_lang_String_2D (JNIEnv *env, jclass, jstring key, jdouble defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsDouble()) return defaultValue; return val->GetDouble(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getString * Signature: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getString__Ljava_lang_String_2Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key, jstring defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsString()) return defaultValue; return MakeJString(env, val->GetString()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getRaw * Signature: (Ljava/lang/String;[B)[B */ JNIEXPORT jbyteArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getRaw__Ljava_lang_String_2_3B (JNIEnv *env, jclass, jstring key, jbyteArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsRaw()) return defaultValue; return MakeJByteArray(env, val->GetRaw()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getBooleanArray * Signature: (Ljava/lang/String;[Z)[Z */ JNIEXPORT jbooleanArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getBooleanArray__Ljava_lang_String_2_3Z (JNIEnv *env, jclass, jstring key, jbooleanArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsBooleanArray()) return defaultValue; return MakeJBooleanArray(env, val->GetBooleanArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getDoubleArray * Signature: (Ljava/lang/String;[D)[D */ JNIEXPORT jdoubleArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getDoubleArray__Ljava_lang_String_2_3D (JNIEnv *env, jclass, jstring key, jdoubleArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsDoubleArray()) return defaultValue; return MakeJDoubleArray(env, val->GetDoubleArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getStringArray * Signature: (Ljava/lang/String;[Ljava/lang/String;)[Ljava/lang/String; */ JNIEXPORT jobjectArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getStringArray__Ljava_lang_String_2_3Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key, jobjectArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsStringArray()) return defaultValue; return MakeJStringArray(env, val->GetStringArray()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultBoolean * Signature: (Ljava/lang/String;Z)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultBoolean (JNIEnv *env, jclass, jstring key, jboolean defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } return nt::SetDefaultEntryValue(JStringRef{env, key}, nt::Value::MakeBoolean(defaultValue != JNI_FALSE)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultDouble * Signature: (Ljava/lang/String;D)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultDouble (JNIEnv *env, jclass, jstring key, jdouble defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } return nt::SetDefaultEntryValue(JStringRef{env, key}, nt::Value::MakeDouble(defaultValue)); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultString * Signature: (Ljava/lang/String;Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultString (JNIEnv *env, jclass, jstring key, jstring defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return false; } return nt::SetDefaultEntryValue( JStringRef{env, key}, nt::Value::MakeString(JStringRef{env, defaultValue})); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultRaw * Signature: (Ljava/lang/String;[B)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultRaw (JNIEnv *env, jclass, jstring key, jbyteArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return false; } auto v = FromJavaRaw(env, defaultValue); return nt::SetDefaultEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultBooleanArray * Signature: (Ljava/lang/String;[Z)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultBooleanArray (JNIEnv *env, jclass, jstring key, jbooleanArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return false; } auto v = FromJavaBooleanArray(env, defaultValue); return nt::SetDefaultEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultDoubleArray * Signature: (Ljava/lang/String;[D)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultDoubleArray (JNIEnv *env, jclass, jstring key, jdoubleArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return false; } auto v = FromJavaDoubleArray(env, defaultValue); return nt::SetDefaultEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setDefaultStringArray * Signature: (Ljava/lang/String;[Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setDefaultStringArray (JNIEnv *env, jclass, jstring key, jobjectArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return false; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return false; } auto v = FromJavaStringArray(env, defaultValue); return nt::SetDefaultEntryValue(JStringRef{env, key}, v); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setEntryFlags * Signature: (Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setEntryFlags (JNIEnv *env, jclass, jstring key, jint flags) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } nt::SetEntryFlags(JStringRef{env, key}, flags); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getEntryFlags * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getEntryFlags (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } return nt::GetEntryFlags(JStringRef{env, key}); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: deleteEntry * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_deleteEntry (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return; } nt::DeleteEntry(JStringRef{env, key}); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: deleteAllEntries * Signature: ()V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_deleteAllEntries (JNIEnv *, jclass) { nt::DeleteAllEntries(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getEntries * Signature: (Ljava/lang/String;I)[Ledu/wpi/first/wpilibj/networktables/EntryInfo; */ JNIEXPORT jobjectArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getEntries (JNIEnv *env, jclass, jstring prefix, jint types) { if (!prefix) { nullPointerEx.Throw(env, "prefix cannot be null"); return nullptr; } auto arr = nt::GetEntryInfo(JStringRef{env, prefix}, types); jobjectArray jarr = env->NewObjectArray(arr.size(), entryInfoCls, nullptr); if (!jarr) return nullptr; for (size_t i = 0; i < arr.size(); ++i) { JLocal<jobject> jelem{env, MakeJObject(env, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); } return jarr; } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: flush * Signature: ()V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_flush (JNIEnv *, jclass) { nt::Flush(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: addEntryListener * Signature: (Ljava/lang/String;Ledu/wpi/first/wpilibj/networktables/NetworkTablesJNI/EntryListenerFunction;Z)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_addEntryListener (JNIEnv *envouter, jclass, jstring prefix, jobject listener, jint flags) { if (!prefix) { nullPointerEx.Throw(envouter, "prefix cannot be null"); return 0; } if (!listener) { nullPointerEx.Throw(envouter, "listener cannot be null"); return 0; } // the shared pointer to the weak global will keep it around until the // entry listener is destroyed auto listener_global = std::make_shared<JGlobal<jobject>>(envouter, listener); // cls is a temporary here; cannot be used within callback functor jclass cls = envouter->GetObjectClass(listener); if (!cls) return 0; // method ids, on the other hand, are safe to retain jmethodID mid = envouter->GetMethodID( cls, "apply", "(ILjava/lang/String;Ljava/lang/Object;I)V"); if (!mid) return 0; return nt::AddEntryListener( JStringRef{envouter, prefix}, [=](unsigned int uid, nt::StringRef name, std::shared_ptr<nt::Value> value, unsigned int flags_) { JNIEnv *env = listenerEnv; if (!env || !env->functions) return; // get the handler auto handler = listener_global->obj(); // convert the value into the appropriate Java type JLocal<jobject> jobj{env, MakeJObject(env, *value)}; if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); return; } if (!jobj) return; JLocal<jstring> jname{env, MakeJString(env, name)}; env->CallVoidMethod(handler, mid, (jint)uid, jname.obj(), jobj.obj(), (jint)(flags_)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } }, flags); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: removeEntryListener * Signature: (I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_removeEntryListener (JNIEnv *, jclass, jint entryListenerUid) { nt::RemoveEntryListener(entryListenerUid); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: addConnectionListener * Signature: (Ledu/wpi/first/wpilibj/networktables/NetworkTablesJNI/ConnectionListenerFunction;Z)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_addConnectionListener (JNIEnv *envouter, jclass, jobject listener, jboolean immediateNotify) { if (!listener) { nullPointerEx.Throw(envouter, "listener cannot be null"); return 0; } // the shared pointer to the weak global will keep it around until the // entry listener is destroyed auto listener_global = std::make_shared<JGlobal<jobject>>(envouter, listener); // cls is a temporary here; cannot be used within callback functor jclass cls = envouter->GetObjectClass(listener); if (!cls) return 0; // method ids, on the other hand, are safe to retain jmethodID mid = envouter->GetMethodID( cls, "apply", "(IZLedu/wpi/first/wpilibj/networktables/ConnectionInfo;)V"); if (!mid) return 0; return nt::AddConnectionListener( [=](unsigned int uid, bool connected, const nt::ConnectionInfo& conn) { JNIEnv *env = listenerEnv; if (!env || !env->functions) return; // get the handler auto handler = listener_global->obj(); //if (!handler) goto done; // can happen due to weak reference // convert into the appropriate Java type JLocal<jobject> jobj{env, MakeJObject(env, conn)}; if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); return; } if (!jobj) return; env->CallVoidMethod(handler, mid, (jint)uid, (jboolean)(connected ? 1 : 0), jobj.obj()); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } }, immediateNotify != JNI_FALSE); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: removeConnectionListener * Signature: (I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_removeConnectionListener (JNIEnv *, jclass, jint connListenerUid) { nt::RemoveConnectionListener(connListenerUid); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getRpc * Signature: (Ljava/lang/String;)[B */ JNIEXPORT jbyteArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getRpc__Ljava_lang_String_2 (JNIEnv *env, jclass, jstring key) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsRpc()) { keyNotDefinedEx.Throw(env, key); return nullptr; } return MakeJByteArray(env, val->GetRpc()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getRpc * Signature: (Ljava/lang/String;[B)[B */ JNIEXPORT jbyteArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getRpc__Ljava_lang_String_2_3B (JNIEnv *env, jclass, jstring key, jbyteArray defaultValue) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return nullptr; } if (!defaultValue) { nullPointerEx.Throw(env, "defaultValue cannot be null"); return nullptr; } auto val = nt::GetEntryValue(JStringRef{env, key}); if (!val || !val->IsRpc()) return defaultValue; return MakeJByteArray(env, val->GetRpc()); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: callRpc * Signature: (Ljava/lang/String;[B)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_callRpc__Ljava_lang_String_2_3B (JNIEnv *env, jclass, jstring key, jbyteArray params) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } if (!params) { nullPointerEx.Throw(env, "params cannot be null"); return 0; } return nt::CallRpc(JStringRef{env, key}, JByteArrayRef{env, params}); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: callRpc * Signature: (Ljava/lang/String;Ljava/nio/ByteBuffer;I)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_callRpc__Ljava_lang_String_2Ljava_nio_ByteBuffer_2I (JNIEnv *env, jclass, jstring key, jobject params, jint params_len) { if (!key) { nullPointerEx.Throw(env, "key cannot be null"); return 0; } if (!params) { nullPointerEx.Throw(env, "params cannot be null"); return 0; } return nt::CallRpc(JStringRef{env, key}, JByteArrayRef{env, params, params_len}); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setNetworkIdentity * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setNetworkIdentity (JNIEnv *env, jclass, jstring name) { if (!name) { nullPointerEx.Throw(env, "name cannot be null"); return; } nt::SetNetworkIdentity(JStringRef{env, name}); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: startServer * Signature: (Ljava/lang/String;Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_startServer (JNIEnv *env, jclass, jstring persistFilename, jstring listenAddress, jint port) { if (!persistFilename) { nullPointerEx.Throw(env, "persistFilename cannot be null"); return; } if (!listenAddress) { nullPointerEx.Throw(env, "listenAddress cannot be null"); return; } nt::StartServer(JStringRef{env, persistFilename}, JStringRef{env, listenAddress}.c_str(), port); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: stopServer * Signature: ()V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_stopServer (JNIEnv *, jclass) { nt::StopServer(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: startClient * Signature: ()V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_startClient__ (JNIEnv *env, jclass) { nt::StartClient(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: startClient * Signature: (Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_startClient__Ljava_lang_String_2I (JNIEnv *env, jclass, jstring serverName, jint port) { if (!serverName) { nullPointerEx.Throw(env, "serverName cannot be null"); return; } nt::StartClient(JStringRef{env, serverName}.c_str(), port); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: startClient * Signature: ([Ljava/lang/String;[I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_startClient___3Ljava_lang_String_2_3I (JNIEnv *env, jclass, jobjectArray serverNames, jintArray ports) { if (!serverNames) { nullPointerEx.Throw(env, "serverNames cannot be null"); return; } if (!ports) { nullPointerEx.Throw(env, "ports cannot be null"); return; } int len = env->GetArrayLength(serverNames); if (len != env->GetArrayLength(ports)) { illegalArgEx.Throw(env, "serverNames and ports arrays must be the same size"); return; } jint* portInts = env->GetIntArrayElements(ports, nullptr); if (!portInts) return; std::vector<std::string> names; std::vector<std::pair<nt::StringRef, unsigned int>> servers; names.reserve(len); servers.reserve(len); for (int i = 0; i < len; ++i) { JLocal<jstring> elem{ env, static_cast<jstring>(env->GetObjectArrayElement(serverNames, i))}; if (!elem) { nullPointerEx.Throw(env, "null string in serverNames"); return; } names.emplace_back(JStringRef{env, elem}.str()); servers.emplace_back(std::make_pair(nt::StringRef(names.back()), portInts[i])); } env->ReleaseIntArrayElements(ports, portInts, JNI_ABORT); nt::StartClient(servers); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: stopClient * Signature: ()V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_stopClient (JNIEnv *, jclass) { nt::StopClient(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setServer * Signature: (Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setServer__Ljava_lang_String_2I (JNIEnv *env, jclass, jstring serverName, jint port) { if (!serverName) { nullPointerEx.Throw(env, "serverName cannot be null"); return; } nt::SetServer(JStringRef{env, serverName}.c_str(), port); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setServer * Signature: ([Ljava/lang/String;[I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setServer___3Ljava_lang_String_2_3I (JNIEnv *env, jclass, jobjectArray serverNames, jintArray ports) { if (!serverNames) { nullPointerEx.Throw(env, "serverNames cannot be null"); return; } if (!ports) { nullPointerEx.Throw(env, "ports cannot be null"); return; } int len = env->GetArrayLength(serverNames); if (len != env->GetArrayLength(ports)) { illegalArgEx.Throw(env, "serverNames and ports arrays must be the same size"); return; } jint* portInts = env->GetIntArrayElements(ports, nullptr); if (!portInts) return; std::vector<std::string> names; std::vector<std::pair<nt::StringRef, unsigned int>> servers; names.reserve(len); servers.reserve(len); for (int i = 0; i < len; ++i) { JLocal<jstring> elem{ env, static_cast<jstring>(env->GetObjectArrayElement(serverNames, i))}; if (!elem) { nullPointerEx.Throw(env, "null string in serverNames"); return; } names.emplace_back(JStringRef{env, elem}.str()); servers.emplace_back(std::make_pair(nt::StringRef(names.back()), portInts[i])); } env->ReleaseIntArrayElements(ports, portInts, JNI_ABORT); nt::SetServer(servers); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: startDSClient * Signature: (I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_startDSClient (JNIEnv *env, jclass, jint port) { nt::StartDSClient(port); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: stopDSClient * Signature: (I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_stopDSClient (JNIEnv *env, jclass) { nt::StopDSClient(); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setUpdateRate * Signature: (D)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setUpdateRate (JNIEnv *, jclass, jdouble interval) { nt::SetUpdateRate(interval); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: getConnections * Signature: ()[Ledu/wpi/first/wpilibj/networktables/ConnectionInfo; */ JNIEXPORT jobjectArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_getConnections (JNIEnv *env, jclass) { auto arr = nt::GetConnections(); jobjectArray jarr = env->NewObjectArray(arr.size(), connectionInfoCls, nullptr); if (!jarr) return nullptr; for (size_t i = 0; i < arr.size(); ++i) { JLocal<jobject> jelem{env, MakeJObject(env, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); } return jarr; } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: savePersistent * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_savePersistent (JNIEnv *env, jclass, jstring filename) { if (!filename) { nullPointerEx.Throw(env, "filename cannot be null"); return; } const char *err = nt::SavePersistent(JStringRef{env, filename}); if (err) persistentEx.Throw(env, err); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: loadPersistent * Signature: (Ljava/lang/String;)[Ljava/lang/String; */ JNIEXPORT jobjectArray JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_loadPersistent (JNIEnv *env, jclass, jstring filename) { if (!filename) { nullPointerEx.Throw(env, "filename cannot be null"); return nullptr; } std::vector<std::string> warns; const char *err = nt::LoadPersistent(JStringRef{env, filename}, [&](size_t line, const char *msg) { std::ostringstream oss; oss << line << ": " << msg; warns.push_back(oss.str()); }); if (err) { persistentEx.Throw(env, err); return nullptr; } return MakeJStringArray(env, warns); } /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: now * Signature: ()J */ JNIEXPORT jlong JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_now (JNIEnv *, jclass) { return nt::Now(); } } // extern "C" namespace { struct LogMessage { public: LogMessage(unsigned int level, const char *file, unsigned int line, const char *msg) : m_level(level), m_file(file), m_line(line), m_msg(msg) {} void CallJava(JNIEnv* env, jobject func, jmethodID mid) { JLocal<jstring> file{env, MakeJString(env, m_file)}; JLocal<jstring> msg{env, MakeJString(env, m_msg)}; env->CallVoidMethod(func, mid, (jint)m_level, file.obj(), (jint)m_line, msg.obj()); } static const char* GetName() { return "NTLogger"; } static JavaVM* GetJVM() { return jvm; } private: unsigned int m_level; const char* m_file; unsigned int m_line; std::string m_msg; }; typedef JSingletonCallbackManager<LogMessage> LoggerJNI; } // anonymous namespace ATOMIC_STATIC_INIT(LoggerJNI) extern "C" { /* * Class: edu_wpi_first_wpilibj_networktables_NetworkTablesJNI * Method: setLogger * Signature: (Ledu/wpi/first/wpilibj/networktables/NetworkTablesJNI/LoggerFunction;I)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_networktables_NetworkTablesJNI_setLogger (JNIEnv *env, jclass, jobject func, jint minLevel) { if (!func) { nullPointerEx.Throw(env, "func cannot be null"); return; } // cls is a temporary here; cannot be used within callback functor jclass cls = env->GetObjectClass(func); if (!cls) return; // method ids, on the other hand, are safe to retain jmethodID mid = env->GetMethodID( cls, "apply", "(ILjava/lang/String;ILjava/lang/String;)V"); if (!mid) return; auto& logger = LoggerJNI::GetInstance(); logger.Start(); logger.SetFunc(env, func, mid); nt::SetLogger( [](unsigned int level, const char *file, unsigned int line, const char *msg) { LoggerJNI::GetInstance().Send(level, file, line, msg); }, minLevel); } } // extern "C"
30.377228
145
0.70878
FRC-Team-5522
62d50d0f201b54532f63c389d87c22c86c18ac06
2,043
hh
C++
Editor/src/EditorLayer.hh
Stolkerve/RoraymaEngine
e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2
[ "Apache-2.0" ]
null
null
null
Editor/src/EditorLayer.hh
Stolkerve/RoraymaEngine
e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2
[ "Apache-2.0" ]
null
null
null
Editor/src/EditorLayer.hh
Stolkerve/RoraymaEngine
e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <RoraymaEngine/RoraymaEngine.hh> #include <RoraymaEngine/Renderer/DynamicGrid.hh> #include <Portable_File_Dialogs/portable-file-dialogs.h> #include <pybind11/embed.h> #include "Panels/RenderingInfoPanel.hh" #include "Panels/EntitysPanel.hh" #include "Panels/ConsolePanel.hh" #include "Panels/FoldersPanel.hh" #include "Panels/CodeEditorPanel.hh" #include "Renderer/SelectedEntityOverlay.hh" using namespace rym; using namespace api; class EditorLayer : public Layer { public: EditorLayer(); virtual void OnStart() override; virtual void OnEvent(const Event& event) override; virtual void OnUpdate(float _delta) override; virtual void OnQuit() override; virtual void OnImGui() override; private: void UpdateEditorMode(float _delta); void UpdateGameMode(float _delta); void RenderCartesianPlane(); void CalculateDeltaWorlMouse(); void MoveEntity(const Entity* entity, float delta); void OpenScene(const std::vector<std::string>& scenesPath); void OpenScene(const std::string& scenePath); void SaveScene(const std::string& scenePath); void ChangeScene(const std::shared_ptr<Scene>& newScene); void ChangeScene(std::shared_ptr<Scene>&& newScene); glm::vec2 CaculateMouseViewport(); std::shared_ptr<Scene>* m_SelectedScene; std::shared_ptr<FrameBuffer> m_FrameBuffer; std::vector<std::shared_ptr<Scene>> m_Scenes; Entity* m_EntitySelected = nullptr; //DynamicGrid m_DynamicGrid; EditorCamera m_EditorCamera; SEOverlay m_SEOVerlay; RenderingInfoPanel m_RenderingInfoPanel; EntitysPanel m_EntitysPanel; FoldersPanel m_FoldersPanel; LayerMode m_LayerMode = LayerMode::EDITOR_MODE; glm::vec2 m_ViewportSize = { 0.0f, 0.0f }; glm::vec2 m_ViewportPos = { 0.0f, 0.0f }; glm::vec3 m_LastMouseViewport = { 0.f, 0.f, 0.f }; glm::vec3 m_FirstMouseViewport = { 0.f, 0.f, 0.f }; glm::vec3 m_MouseViewportDelta = { 0.f, 0.f, 0.f }; bool m_ViewportFocused; bool m_ViewportHovered; bool m_ViewportDocked; bool m_NeedResize; bool m_ScenesOpen = true; bool m_BlockSelectedEntity = false; };
28.375
60
0.771415
Stolkerve
62db8bf1ffbeb25058226e4c340685c3149a1755
5,882
cpp
C++
store/transaction_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
106
2015-01-20T14:49:12.000Z
2022-03-09T01:31:51.000Z
store/transaction_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
81
2015-02-23T23:23:41.000Z
2021-07-21T13:51:56.000Z
store/transaction_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
27
2015-09-30T20:33:34.000Z
2022-02-14T04:00:08.000Z
// Copyright 2011 The Kyua Authors. // 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 Google Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <map> #include <string> #include <atf-c++.hpp> #include "model/context.hpp" #include "model/metadata.hpp" #include "model/test_program.hpp" #include "store/read_backend.hpp" #include "store/read_transaction.hpp" #include "store/write_backend.hpp" #include "store/write_transaction.hpp" #include "utils/datetime.hpp" #include "utils/fs/operations.hpp" #include "utils/fs/path.hpp" #include "utils/logging/operations.hpp" #include "utils/sqlite/database.hpp" #include "utils/units.hpp" namespace datetime = utils::datetime; namespace fs = utils::fs; namespace logging = utils::logging; namespace units = utils::units; namespace { /// Puts and gets a context and validates the results. /// /// \param exp_context The context to save and restore. static void check_get_put_context(const model::context& exp_context) { const fs::path test_db("test.db"); if (fs::exists(test_db)) fs::unlink(test_db); { store::write_backend backend = store::write_backend::open_rw(test_db); store::write_transaction tx = backend.start_write(); tx.put_context(exp_context); tx.commit(); } { store::read_backend backend = store::read_backend::open_ro(test_db); store::read_transaction tx = backend.start_read(); model::context context = tx.get_context(); tx.finish(); ATF_REQUIRE(exp_context == context); } } } // anonymous namespace ATF_TEST_CASE(get_put_context__ok); ATF_TEST_CASE_HEAD(get_put_context__ok) { logging::set_inmemory(); set_md_var("require.files", store::detail::schema_file().c_str()); } ATF_TEST_CASE_BODY(get_put_context__ok) { std::map< std::string, std::string > env1; env1["A1"] = "foo"; env1["A2"] = "bar"; std::map< std::string, std::string > env2; check_get_put_context(model::context(fs::path("/foo/bar"), env1)); check_get_put_context(model::context(fs::path("/foo/bar"), env1)); check_get_put_context(model::context(fs::path("/foo/baz"), env2)); } ATF_TEST_CASE(get_put_test_case__ok); ATF_TEST_CASE_HEAD(get_put_test_case__ok) { logging::set_inmemory(); set_md_var("require.files", store::detail::schema_file().c_str()); } ATF_TEST_CASE_BODY(get_put_test_case__ok) { const model::metadata md2 = model::metadata_builder() .add_allowed_architecture("powerpc") .add_allowed_architecture("x86_64") .add_allowed_platform("amd64") .add_allowed_platform("macppc") .add_custom("user1", "value1") .add_custom("user2", "value2") .add_required_config("var1") .add_required_config("var2") .add_required_config("var3") .add_required_file(fs::path("/file1/yes")) .add_required_file(fs::path("/file2/foo")) .add_required_program(fs::path("/bin/ls")) .add_required_program(fs::path("cp")) .set_description("The description") .set_has_cleanup(true) .set_required_memory(units::bytes::parse("1k")) .set_required_user("root") .set_timeout(datetime::delta(520, 0)) .build(); const model::test_program test_program = model::test_program_builder( "atf", fs::path("the/binary"), fs::path("/some/root"), "the-suite") .add_test_case("tc1") .add_test_case("tc2", md2) .build(); int64_t test_program_id; { store::write_backend backend = store::write_backend::open_rw( fs::path("test.db")); backend.database().exec("PRAGMA foreign_keys = OFF"); store::write_transaction tx = backend.start_write(); test_program_id = tx.put_test_program(test_program); tx.put_test_case(test_program, "tc1", test_program_id); tx.put_test_case(test_program, "tc2", test_program_id); tx.commit(); } store::read_backend backend = store::read_backend::open_ro( fs::path("test.db")); backend.database().exec("PRAGMA foreign_keys = OFF"); store::read_transaction tx = backend.start_read(); const model::test_program_ptr loaded_test_program = store::detail::get_test_program(backend, test_program_id); ATF_REQUIRE(test_program == *loaded_test_program); } ATF_INIT_TEST_CASES(tcs) { ATF_ADD_TEST_CASE(tcs, get_put_context__ok); ATF_ADD_TEST_CASE(tcs, get_put_test_case__ok); }
34.397661
78
0.701292
racktopsystems
62dbb54076da1e7dc89c683c8f68d6e0dd05517f
8,630
hpp
C++
library/include/darcel/syntax/syntax_parser_expressions.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/include/darcel/syntax/syntax_parser_expressions.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/include/darcel/syntax/syntax_parser_expressions.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
1
2020-04-17T13:25:25.000Z
2020-04-17T13:25:25.000Z
#ifndef DARCEL_SYNTAX_PARSER_EXPRESSIONS_HPP #define DARCEL_SYNTAX_PARSER_EXPRESSIONS_HPP #include <cassert> #include <deque> #include <stack> #include "darcel/lexicon/token.hpp" #include "darcel/syntax/arity_syntax_error.hpp" #include "darcel/syntax/call_expression.hpp" #include "darcel/syntax/enum_expression.hpp" #include "darcel/syntax/function_expression.hpp" #include "darcel/syntax/invalid_member_syntax_error.hpp" #include "darcel/syntax/literal_expression.hpp" #include "darcel/syntax/ops.hpp" #include "darcel/syntax/redefinition_syntax_error.hpp" #include "darcel/syntax/syntax.hpp" #include "darcel/syntax/syntax_builders.hpp" #include "darcel/syntax/syntax_error.hpp" #include "darcel/syntax/syntax_parser.hpp" #include "darcel/syntax/unmatched_bracket_syntax_error.hpp" namespace darcel { inline std::unique_ptr<EnumExpression> SyntaxParser::parse_enum_expression( TokenIterator& cursor) { auto c = cursor; auto name = try_parse_identifier(c); if(!name.has_value()) { return nullptr; } auto e = get_current_scope().find<EnumDataType>(*name); if(e == nullptr) { return nullptr; } if(!match(*c, Punctuation::Mark::DOT)) { return nullptr; } ++c; auto symbol_location = c.get_location(); auto symbol = parse_identifier(c); auto index = get_index(*e, symbol); if(index == -1) { throw InvalidMemberSyntaxError(std::move(symbol_location), std::move(e), std::move(symbol)); } auto s = std::make_unique<EnumExpression>(cursor.get_location(), std::move(e), index); cursor = c; return s; } inline std::unique_ptr<FunctionExpression> SyntaxParser::parse_function_expression(TokenIterator& cursor) { auto c = cursor; auto name = try_parse_identifier(c); if(!name.has_value()) { return nullptr; } auto f = get_current_scope().find<Function>(*name); if(f == nullptr) { return nullptr; } auto node = std::make_unique<FunctionExpression>(cursor.get_location(), std::move(f)); cursor = c; return node; } inline std::unique_ptr<LiteralExpression> SyntaxParser:: parse_literal_expression(TokenIterator& cursor) { return std::visit( [&] (auto&& value) -> std::unique_ptr<LiteralExpression> { using T = std::decay_t<decltype(value)>; if constexpr(std::is_same_v<T, Literal>) { auto expression = std::make_unique<LiteralExpression>( cursor.get_location(), value); ++cursor; return expression; } return nullptr; }, cursor->get_instance()); } inline std::unique_ptr<VariableExpression> SyntaxParser::parse_variable_expression(TokenIterator& cursor) { auto c = cursor; auto name = try_parse_identifier(c); if(!name.has_value()) { return nullptr; } try { auto node = make_variable_expression(cursor.get_location(), get_current_scope(), *name); cursor = c; return node; } catch(const VariableNotFoundError&) { return nullptr; } } inline std::unique_ptr<Expression> SyntaxParser::parse_expression_term( TokenIterator& cursor) { if(auto node = parse_function_expression(cursor)) { return node; } else if(auto node = parse_literal_expression(cursor)) { return node; } else if(auto node = parse_variable_expression(cursor)) { return node; } else if(auto node = parse_enum_expression(cursor)) { return node; } return nullptr; } inline std::unique_ptr<Expression> SyntaxParser::parse_expression( TokenIterator& cursor) { struct op_token { Op m_op; Location m_location; }; std::deque<std::unique_ptr<Expression>> expressions; std::stack<op_token> operators; auto build_call_expression = [&] (const op_token& o) { auto arity = get_arity(o.m_op); if(static_cast<int>(expressions.size()) < arity) { throw AritySyntaxError(o.m_location, expressions.size(), o.m_op); } std::vector<std::unique_ptr<Expression>> arguments; for(auto i = 0; i < arity; ++i) { arguments.push_back(nullptr); } while(arity != 0) { arguments[arity - 1] = std::move(expressions.back()); expressions.pop_back(); --arity; } auto& function_name = get_function_name(o.m_op); auto f = get_current_scope().find<Function>(function_name); if(f == nullptr) { throw SyntaxError(SyntaxErrorCode::FUNCTION_NOT_FOUND, o.m_location); } auto callable = std::make_unique<FunctionExpression>(o.m_location, std::move(f)); auto call_expression = call(o.m_location, std::move(callable), std::move(arguments)); expressions.push_back(std::move(call_expression)); }; auto c = cursor; enum class parse_mode { TERM, OPERATOR }; auto mode = parse_mode::TERM; while(true) { if(mode == parse_mode::TERM) { if(match(*c, Bracket::Type::ROUND_OPEN)) { operators.push({Op::OPEN_BRACKET, c.get_location()}); ++c; } else if(auto node = parse_expression_term(c)) { expressions.push_back(std::move(node)); mode = parse_mode::OPERATOR; } else { break; } } else { if(match(*c, Bracket::Type::ROUND_OPEN)) { auto call_location = c.get_location(); ++c; std::vector<std::unique_ptr<Expression>> arguments; if(!match(*c, Bracket::Type::ROUND_CLOSE)) { while(true) { auto argument = parse_expression(c); if(argument == nullptr) { throw SyntaxError(SyntaxErrorCode::EXPRESSION_EXPECTED, c.get_location()); } arguments.push_back(std::move(argument)); if(match(*c, Bracket::Type::ROUND_CLOSE)) { break; } expect(c, Punctuation::Mark::COMMA); } } auto callable = std::move(expressions.back()); expressions.pop_back(); auto call_expression = call(call_location, std::move(callable), std::move(arguments)); expressions.push_back(std::move(call_expression)); ++c; } else if(c->get_type() == Token::Type::OPERATION) { auto& instance = std::get<Operation>(c->get_instance()); auto o = get_binary_op(instance); while(!operators.empty() && (operators.top().m_op != Op::OPEN_BRACKET && operators.top().m_op != Op::CLOSE_BRACKET && (get_precedence(operators.top().m_op) > get_precedence(o) || get_precedence(operators.top().m_op) == get_precedence(o) && get_associativity(o) == Associativity::LEFT_TO_RIGHT))) { build_call_expression(operators.top()); operators.pop(); } operators.push({o, c.get_location()}); ++c; mode = parse_mode::TERM; } else if(match(*c, Bracket::Type::ROUND_CLOSE)) { auto found_open_bracket = false; while(!operators.empty()) { auto o = operators.top(); operators.pop(); if(o.m_op == Op::OPEN_BRACKET) { found_open_bracket = true; break; } else { build_call_expression(o); } } if(!found_open_bracket) { break; } ++c; } else { break; } } } while(!operators.empty()) { auto o = operators.top(); operators.pop(); if(o.m_op == Op::OPEN_BRACKET || o.m_op == Op::CLOSE_BRACKET) { auto bracket = [&] { if(o.m_op == Op::OPEN_BRACKET) { return Bracket::Type::ROUND_OPEN; } return Bracket::Type::ROUND_CLOSE; }(); throw UnmatchedBracketSyntaxError(o.m_location, bracket); } build_call_expression(o); } if(expressions.empty()) { return nullptr; } auto e = std::move(expressions.front()); expressions.pop_front(); assert(expressions.empty()); cursor = c; return e; } inline std::unique_ptr<Expression> SyntaxParser::expect_expression( TokenIterator& cursor) { auto e = parse_expression(cursor); if(e == nullptr) { throw SyntaxError(SyntaxErrorCode::EXPRESSION_EXPECTED, cursor.get_location()); } return e; } } #endif
32.689394
77
0.597914
spiretrading
62e49aeefadb410fb1f6c956b11fef6b0488c1f4
39,667
cc
C++
libgav1/src/dsp/arm/loop_restoration_neon.cc
bootleg-q/external_libgav1
4ac298d5dc61c607a03eba5ba66def735b918a86
[ "Apache-2.0" ]
null
null
null
libgav1/src/dsp/arm/loop_restoration_neon.cc
bootleg-q/external_libgav1
4ac298d5dc61c607a03eba5ba66def735b918a86
[ "Apache-2.0" ]
null
null
null
libgav1/src/dsp/arm/loop_restoration_neon.cc
bootleg-q/external_libgav1
4ac298d5dc61c607a03eba5ba66def735b918a86
[ "Apache-2.0" ]
null
null
null
#include "src/dsp/dsp.h" #include "src/dsp/loop_restoration.h" #if LIBGAV1_ENABLE_NEON #include <arm_neon.h> #include <cassert> #include <cstddef> #include <cstdint> #include "src/dsp/arm/common_neon.h" #include "src/utils/constants.h" namespace libgav1 { namespace dsp { namespace low_bitdepth { namespace { // Wiener inline void PopulateWienerCoefficients( const RestorationUnitInfo& restoration_info, const int direction, int16_t* const filter) { // In order to keep the horizontal pass intermediate values within 16 bits we // initialize |filter[3]| to 0 instead of 128. filter[3] = 0; for (int i = 0; i < 3; ++i) { const int16_t coeff = restoration_info.wiener_info.filter[direction][i]; filter[i] = coeff; filter[6 - i] = coeff; filter[3] -= coeff * 2; } } inline int16x8_t HorizontalSum(const uint8x8_t a[7], int16_t filter[7]) { int16x8_t sum = vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[0])), filter[0]); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[1])), filter[1])); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[2])), filter[2])); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[3])), filter[3])); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[4])), filter[4])); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[5])), filter[5])); sum = vaddq_s16( sum, vmulq_n_s16(vreinterpretq_s16_u16(vmovl_u8(a[6])), filter[6])); sum = vrshrq_n_s16(sum, kInterRoundBitsHorizontal); // Delaying |horizontal_rounding| until after dowshifting allows the sum to // stay in 16 bits. // |horizontal_rounding| = 1 << (bitdepth + kWienerFilterBits - 1) // 1 << ( 8 + 7 - 1) // Plus |kInterRoundBitsHorizontal| and it works out to 1 << 11. sum = vaddq_s16(sum, vdupq_n_s16(1 << 11)); // Just like |horizontal_rounding|, adding |filter[3]| at this point allows // the sum to stay in 16 bits. // But wait! We *did* calculate |filter[3]| and used it in the sum! But it was // offset by 128. Fix that here: // |src[3]| * 128 >> 3 == |src[3]| << 4 sum = vaddq_s16(sum, vreinterpretq_s16_u16(vshll_n_u8(a[3], 4))); // Saturate to // [0, // (1 << (bitdepth + 1 + kWienerFilterBits - kInterRoundBitsHorizontal)) - 1)] // (1 << ( 8 + 1 + 7 - 3)) - 1) sum = vminq_s16(sum, vdupq_n_s16((1 << 13) - 1)); sum = vmaxq_s16(sum, vdupq_n_s16(0)); return sum; } template <int min_width> inline void VerticalSum(const int16_t* src_base, const ptrdiff_t src_stride, uint8_t* dst_base, const ptrdiff_t dst_stride, const int16x4_t filter[7], const int width, const int height) { static_assert(min_width == 4 || min_width == 8, ""); // -(1 << (bitdepth + kInterRoundBitsVertical - 1)) // -(1 << ( 8 + 11 - 1)) constexpr int vertical_rounding = -(1 << 18); if (min_width == 8) { int x = 0; do { const int16_t* src = src_base + x; uint8_t* dst = dst_base + x; int16x8_t a[7]; a[0] = vld1q_s16(src); src += src_stride; a[1] = vld1q_s16(src); src += src_stride; a[2] = vld1q_s16(src); src += src_stride; a[3] = vld1q_s16(src); src += src_stride; a[4] = vld1q_s16(src); src += src_stride; a[5] = vld1q_s16(src); src += src_stride; int y = 0; do { a[6] = vld1q_s16(src); src += src_stride; int32x4_t sum_lo = vdupq_n_s32(vertical_rounding); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[0]), filter[0]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[1]), filter[1]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[2]), filter[2]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[3]), filter[3]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[4]), filter[4]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[5]), filter[5]); sum_lo = vmlal_s16(sum_lo, vget_low_s16(a[6]), filter[6]); uint16x4_t sum_lo_16 = vqrshrun_n_s32(sum_lo, 11); int32x4_t sum_hi = vdupq_n_s32(vertical_rounding); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[0]), filter[0]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[1]), filter[1]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[2]), filter[2]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[3]), filter[3]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[4]), filter[4]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[5]), filter[5]); sum_hi = vmlal_s16(sum_hi, vget_high_s16(a[6]), filter[6]); uint16x4_t sum_hi_16 = vqrshrun_n_s32(sum_hi, 11); vst1_u8(dst, vqmovn_u16(vcombine_u16(sum_lo_16, sum_hi_16))); dst += dst_stride; a[0] = a[1]; a[1] = a[2]; a[2] = a[3]; a[3] = a[4]; a[4] = a[5]; a[5] = a[6]; } while (++y < height); x += 8; } while (x < width); } else if (min_width == 4) { const int16_t* src = src_base; uint8_t* dst = dst_base; int16x4_t a[7]; a[0] = vld1_s16(src); src += src_stride; a[1] = vld1_s16(src); src += src_stride; a[2] = vld1_s16(src); src += src_stride; a[3] = vld1_s16(src); src += src_stride; a[4] = vld1_s16(src); src += src_stride; a[5] = vld1_s16(src); src += src_stride; int y = 0; do { a[6] = vld1_s16(src); src += src_stride; int32x4_t sum = vdupq_n_s32(vertical_rounding); sum = vmlal_s16(sum, a[0], filter[0]); sum = vmlal_s16(sum, a[1], filter[1]); sum = vmlal_s16(sum, a[2], filter[2]); sum = vmlal_s16(sum, a[3], filter[3]); sum = vmlal_s16(sum, a[4], filter[4]); sum = vmlal_s16(sum, a[5], filter[5]); sum = vmlal_s16(sum, a[6], filter[6]); uint16x4_t sum_16 = vqrshrun_n_s32(sum, 11); StoreLo4(dst, vqmovn_u16(vcombine_u16(sum_16, sum_16))); dst += dst_stride; a[0] = a[1]; a[1] = a[2]; a[2] = a[3]; a[3] = a[4]; a[4] = a[5]; a[5] = a[6]; } while (++y < height); } } void WienerFilter_NEON(const void* const source, void* const dest, const RestorationUnitInfo& restoration_info, const ptrdiff_t source_stride, const ptrdiff_t dest_stride, const int width, const int height, RestorationBuffer* const buffer) { int16_t filter[kSubPixelTaps - 1]; const auto* src = static_cast<const uint8_t*>(source); auto* dst = static_cast<uint8_t*>(dest); // It should be possible to set this to |width|. ptrdiff_t buffer_stride = buffer->wiener_buffer_stride; // Casting once here saves a lot of vreinterpret() calls. The values are // saturated to 13 bits before storing. int16_t* wiener_buffer = reinterpret_cast<int16_t*>(buffer->wiener_buffer); // Horizontal filtering. PopulateWienerCoefficients(restoration_info, WienerInfo::kHorizontal, filter); // The taps have a radius of 3. Adjust |src| so we start reading with the top // left value. const int center_tap = 3; src -= center_tap * source_stride + center_tap; int y = 0; do { int x = 0; do { // This is just as fast as an 8x8 transpose but avoids over-reading extra // rows. It always over-reads by at least 1 value. On small widths (4xH) // it over-reads by 9 values. const uint8x16_t src_v = vld1q_u8(src + x); uint8x8_t b[7]; b[0] = vget_low_u8(src_v); b[1] = vget_low_u8(vextq_u8(src_v, src_v, 1)); b[2] = vget_low_u8(vextq_u8(src_v, src_v, 2)); b[3] = vget_low_u8(vextq_u8(src_v, src_v, 3)); b[4] = vget_low_u8(vextq_u8(src_v, src_v, 4)); b[5] = vget_low_u8(vextq_u8(src_v, src_v, 5)); b[6] = vget_low_u8(vextq_u8(src_v, src_v, 6)); int16x8_t sum = HorizontalSum(b, filter); vst1q_s16(wiener_buffer + x, sum); x += 8; } while (x < width); src += source_stride; wiener_buffer += buffer_stride; } while (++y < height + kSubPixelTaps - 2); // Vertical filtering. wiener_buffer = reinterpret_cast<int16_t*>(buffer->wiener_buffer); PopulateWienerCoefficients(restoration_info, WienerInfo::kVertical, filter); // Add 128 to |filter[3]| to fix the adjustment for the horizontal filtering. // This pass starts with 13 bits so there is no chance of keeping it in 16. const int16x4_t filter_v[7] = { vdup_n_s16(filter[0]), vdup_n_s16(filter[1]), vdup_n_s16(filter[2]), vdup_n_s16(filter[3] + 128), vdup_n_s16(filter[4]), vdup_n_s16(filter[5]), vdup_n_s16(filter[6])}; if (width == 4) { VerticalSum<4>(wiener_buffer, buffer_stride, dst, dest_stride, filter_v, width, height); } else { VerticalSum<8>(wiener_buffer, buffer_stride, dst, dest_stride, filter_v, width, height); } } // SGR inline uint16x4_t Sum3Horizontal(const uint16x8_t a) { const uint16x4_t sum = vadd_u16(vget_low_u16(a), vext_u16(vget_low_u16(a), vget_high_u16(a), 1)); return vadd_u16(sum, vext_u16(vget_low_u16(a), vget_high_u16(a), 2)); } inline uint32x4_t Sum3Horizontal(const uint32x4x2_t a) { const uint32x4_t sum = vaddq_u32(a.val[0], vextq_u32(a.val[0], a.val[1], 1)); return vaddq_u32(sum, vextq_u32(a.val[0], a.val[1], 2)); } inline uint16x8_t Sum3Vertical(const uint8x8_t a[3]) { const uint16x8_t sum = vaddl_u8(a[0], a[1]); return vaddw_u8(sum, a[2]); } inline uint32x4x2_t Sum3Vertical(const uint16x8_t a[3]) { uint32x4_t sum_a = vaddl_u16(vget_low_u16(a[0]), vget_low_u16(a[1])); sum_a = vaddw_u16(sum_a, vget_low_u16(a[2])); uint32x4_t sum_b = vaddl_u16(vget_high_u16(a[0]), vget_high_u16(a[1])); sum_b = vaddw_u16(sum_b, vget_high_u16(a[2])); return {sum_a, sum_b}; } inline uint16x4_t Sum5Horizontal(const uint16x8_t a) { uint16x4_t sum = vadd_u16(vget_low_u16(a), vext_u16(vget_low_u16(a), vget_high_u16(a), 1)); sum = vadd_u16(sum, vext_u16(vget_low_u16(a), vget_high_u16(a), 2)); sum = vadd_u16(sum, vext_u16(vget_low_u16(a), vget_high_u16(a), 3)); return vadd_u16(sum, vget_high_u16(a)); } inline uint32x4_t Sum5Horizontal(const uint32x4x2_t a) { uint32x4_t sum = vaddq_u32(a.val[0], vextq_u32(a.val[0], a.val[1], 1)); sum = vaddq_u32(sum, vextq_u32(a.val[0], a.val[1], 2)); sum = vaddq_u32(sum, vextq_u32(a.val[0], a.val[1], 3)); return vaddq_u32(sum, a.val[1]); } inline uint16x8_t Sum5Vertical(const uint8x8_t a[5]) { uint16x8_t sum = vaddl_u8(a[0], a[1]); sum = vaddq_u16(sum, vaddl_u8(a[2], a[3])); return vaddw_u8(sum, a[4]); } inline uint32x4x2_t Sum5Vertical(const uint16x8_t a[5]) { uint32x4_t sum_a = vaddl_u16(vget_low_u16(a[0]), vget_low_u16(a[1])); sum_a = vaddq_u32(sum_a, vaddl_u16(vget_low_u16(a[2]), vget_low_u16(a[3]))); sum_a = vaddw_u16(sum_a, vget_low_u16(a[4])); uint32x4_t sum_b = vaddl_u16(vget_high_u16(a[0]), vget_high_u16(a[1])); sum_b = vaddq_u32(sum_b, vaddl_u16(vget_high_u16(a[2]), vget_high_u16(a[3]))); sum_b = vaddw_u16(sum_b, vget_high_u16(a[4])); return {sum_a, sum_b}; } constexpr int kSgrProjScaleBits = 20; constexpr int kSgrProjRestoreBits = 4; constexpr int kSgrProjSgrBits = 8; constexpr int kSgrProjReciprocalBits = 12; constexpr int kIntermediateStride = 68; constexpr int kIntermediateHeight = 66; // a2 = ((z << kSgrProjSgrBits) + (z >> 1)) / (z + 1); constexpr uint16_t kA2Lookup[256] = { 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 256}; inline uint16x4_t Sum565(const uint16x8_t a) { // Multiply everything by 4. const uint16x8_t x4 = vshlq_n_u16(a, 2); // Everything * 5 const uint16x8_t x5 = vaddq_u16(x4, a); // The middle elements get added once more const uint16x4_t middle = vext_u16(vget_low_u16(a), vget_high_u16(a), 1); return vadd_u16(middle, Sum3Horizontal(x5)); } inline uint32x4_t Sum3HorizontalW(const uint32x4_t a, const uint32x4_t b) { const uint32x4_t sum = vaddq_u32(a, vextq_u32(a, b, 1)); return vaddq_u32(sum, vcombine_u32(vget_high_u32(a), vget_low_u32(b))); } inline uint32x4_t Sum565W(const uint16x8_t a) { // Multiply everything by 4. |b2| values can be up to 65088 which means we // have to step up to 32 bits immediately. const uint32x4_t x4_lo = vshll_n_u16(vget_low_u16(a), 2); const uint32x4_t x4_hi = vshll_n_u16(vget_high_u16(a), 2); // Everything * 5 const uint32x4_t x5_lo = vaddw_u16(x4_lo, vget_low_u16(a)); const uint32x4_t x5_hi = vaddw_u16(x4_hi, vget_high_u16(a)); // The middle elements get added once more const uint16x4_t middle = vext_u16(vget_low_u16(a), vget_high_u16(a), 1); return vaddw_u16(Sum3HorizontalW(x5_lo, x5_hi), middle); } template <int n> inline uint16x4_t CalculateA2(const uint32x4_t sum_sq, const uint16x4_t sum, const uint32_t s, const uint16x4_t v_255) { // a = |sum_sq| // d = |sum| // p = (a * n < d * d) ? 0 : a * n - d * d; const uint32x4_t dxd = vmull_u16(sum, sum); const uint32x4_t axn = vmulq_n_u32(sum_sq, n); // Ensure |p| does not underflow by using saturating subtraction. const uint32x4_t p = vqsubq_u32(axn, dxd); // z = RightShiftWithRounding(p * s, kSgrProjScaleBits); const uint32x4_t pxs = vmulq_n_u32(p, s); // For some reason vrshrn_n_u32() (narrowing shift) can only shift by 16 // and kSgrProjScaleBits is 20. const uint32x4_t shifted = vrshrq_n_u32(pxs, kSgrProjScaleBits); // Narrow |shifted| so we can use a D register for v_255. const uint16x4_t z = vmin_u16(v_255, vmovn_u32(shifted)); // a2 = ((z << kSgrProjSgrBits) + (z >> 1)) / (z + 1); const uint16_t lookup[4] = { kA2Lookup[vget_lane_u16(z, 0)], kA2Lookup[vget_lane_u16(z, 1)], kA2Lookup[vget_lane_u16(z, 2)], kA2Lookup[vget_lane_u16(z, 3)]}; return vld1_u16(lookup); } inline uint16x4_t CalculateB2Shifted(const uint16x4_t a2, const uint16x4_t sum, const uint32_t one_over_n) { // b2 = ((1 << kSgrProjSgrBits) - a2) * b * one_over_n // 1 << kSgrProjSgrBits = 256 // |a2| = [1, 256] // |sgrMa2| max value = 255 const uint16x4_t sgrMa2 = vsub_u16(vdup_n_u16(1 << kSgrProjSgrBits), a2); // |sum| is a box sum with radius 1 or 2. // For the first pass radius is 2. Maximum value is 5x5x255 = 6375. // For the second pass radius is 1. Maxmimum value is 3x3x255 = 2295. // |one_over_n| = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n // When radius is 2 |n| is 25. |one_over_n| is 164. // When radius is 1 |n| is 9. |one_over_n| is 455. const uint32x4_t b2 = vmulq_n_u32(vmull_u16(sgrMa2, sum), one_over_n); // static_cast<int>(RightShiftWithRounding(b2, kSgrProjReciprocalBits)); // |kSgrProjReciprocalBits| is 12. // Radius 2: 255 * 6375 * 164 >> 12 = 65088 (16 bits). // Radius 1: 255 * 2295 * 455 >> 12 = 65009 (16 bits). return vrshrn_n_u32(b2, kSgrProjReciprocalBits); } // RightShiftWithRounding( // (a * src_ptr[x] + b), kSgrProjSgrBits + shift - kSgrProjRestoreBits); template <int shift> inline uint16x4_t CalculateFilteredOutput(const uint16x4_t a, const uint32x4_t b, const uint16x4_t src) { // a: 256 * 32 = 8192 (14 bits) // b: 65088 * 32 = 2082816 (21 bits) const uint32x4_t axsrc = vmull_u16(a, src); // v: 8192 * 255 + 2082816 = 4171876 (22 bits) const uint32x4_t v = vaddq_u32(axsrc, b); // kSgrProjSgrBits = 8 // kSgrProjRestoreBits = 4 // shift = 4 or 5 // v >> 8 or 9 // 22 bits >> 8 = 14 bits return vrshrn_n_u32(v, kSgrProjSgrBits + shift - kSgrProjRestoreBits); } inline void BoxFilterProcess_FirstPass(const uint8_t* const src, const ptrdiff_t stride, const int width, const int height, const uint32_t s, uint16_t* const buf) { // Number of elements in the box being summed. const uint32_t n = 25; const uint32_t one_over_n = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n; const uint16x4_t v_255 = vdup_n_u16(255); // We have combined PreProcess and Process for the first pass by storing // intermediate values in the |a2| region. The values stored are one vertical // column of interleaved |a2| and |b2| values and consume 4 * |height| values. // This is |height| and not |height| * 2 because PreProcess only generates // output for every other row. When processing the next column we write the // new scratch values right after reading the previously saved ones. uint16_t* const temp = buf + kIntermediateStride * kIntermediateHeight; // The PreProcess phase calculates a 5x5 box sum for every other row // // PreProcess and Process have been combined into the same step. We need 8 // input values to generate 4 output values for PreProcess: // 0 1 2 3 4 5 6 7 // 2 = 0 + 1 + 2 + 3 + 4 // 3 = 1 + 2 + 3 + 4 + 5 // 4 = 2 + 3 + 4 + 5 + 6 // 5 = 3 + 4 + 5 + 6 + 7 // // and then we need 6 input values to generate 4 output values for Process: // 0 1 2 3 4 5 // 1 = 0 + 1 + 2 // 2 = 1 + 2 + 3 // 3 = 2 + 3 + 4 // 4 = 3 + 4 + 5 // // To avoid re-calculating PreProcess values over and over again we will do a // single column of 4 output values and store them interleaved in |temp|. Next // we will start the second column. When 2 rows have been calculated we can // calculate Process and output those into the top of |buf|. // The first phase needs a radius of 2 context values. The second phase needs // a context of radius 1 values. This means we start at (-3, -3). const uint8_t* const src_pre_process = src - 3 - 3 * stride; // Calculate and store a single column. Scope so we can re-use the variable // names for the next step. { const uint8_t* column = src_pre_process; uint16_t* temp_column = temp; uint8x8_t row[5]; row[0] = vld1_u8(column); column += stride; row[1] = vld1_u8(column); column += stride; row[2] = vld1_u8(column); column += stride; uint16x8_t row_sq[5]; row_sq[0] = vmull_u8(row[0], row[0]); row_sq[1] = vmull_u8(row[1], row[1]); row_sq[2] = vmull_u8(row[2], row[2]); int y = -1; do { row[3] = vld1_u8(column); column += stride; row[4] = vld1_u8(column); column += stride; row_sq[3] = vmull_u8(row[3], row[3]); row_sq[4] = vmull_u8(row[4], row[4]); const uint16x4_t sum = Sum5Horizontal(Sum5Vertical(row)); const uint32x4_t sum_sq = Sum5Horizontal(Sum5Vertical(row_sq)); const uint16x4_t a2 = CalculateA2<n>(sum_sq, sum, s, v_255); const uint16x4_t b2 = CalculateB2Shifted(a2, sum, one_over_n); vst1q_u16(temp_column, vcombine_u16(a2, b2)); temp_column += 8; row[0] = row[2]; row[1] = row[3]; row[2] = row[4]; row_sq[0] = row_sq[2]; row_sq[1] = row_sq[3]; row_sq[2] = row_sq[4]; y += 2; } while (y < height + 1); } int x = 0; do { // |src_pre_process| is X but we already processed the first column of 4 // values so we want to start at Y and increment from there. // X s s s Y s s // s s s s s s s // s s i i i i i // s s i o o o o // s s i o o o o const uint8_t* column = src_pre_process + x + 4; uint8x8_t row[5]; row[0] = vld1_u8(column); column += stride; row[1] = vld1_u8(column); column += stride; row[2] = vld1_u8(column); column += stride; row[3] = vld1_u8(column); column += stride; row[4] = vld1_u8(column); column += stride; uint16x8_t row_sq[5]; row_sq[0] = vmull_u8(row[0], row[0]); row_sq[1] = vmull_u8(row[1], row[1]); row_sq[2] = vmull_u8(row[2], row[2]); row_sq[3] = vmull_u8(row[3], row[3]); row_sq[4] = vmull_u8(row[4], row[4]); // Seed the loop with one line of output. Then, inside the loop, for each // iteration we can output one even row and one odd row and carry the new // line to the next iteration. In the diagram below 'i' values are // intermediary values from the first step and '-' values are empty. // iiii // ---- > even row // iiii - odd row // ---- > even row // iiii uint16_t* temp_column = temp; uint16x4_t sum565_a0; uint32x4_t sum565_b0; { const uint16x4_t sum = Sum5Horizontal(Sum5Vertical(row)); const uint32x4_t sum_sq = Sum5Horizontal(Sum5Vertical(row_sq)); const uint16x4_t a2 = CalculateA2<n>(sum_sq, sum, s, v_255); const uint16x4_t b2 = CalculateB2Shifted(a2, sum, one_over_n); // Exchange the previously calculated |a2| and |b2| values. const uint16x8_t a2_b2 = vld1q_u16(temp_column); vst1q_u16(temp_column, vcombine_u16(a2, b2)); temp_column += 8; // Pass 1 Process. These are the only values we need to propagate between // rows. sum565_a0 = Sum565(vcombine_u16(vget_low_u16(a2_b2), a2)); sum565_b0 = Sum565W(vcombine_u16(vget_high_u16(a2_b2), b2)); } row[0] = row[2]; row[1] = row[3]; row[2] = row[4]; row_sq[0] = row_sq[2]; row_sq[1] = row_sq[3]; row_sq[2] = row_sq[4]; const uint8_t* src_ptr = src + x; uint16_t* out_buf = buf + x; // Calculate one output line. Add in the line from the previous pass and // output one even row. Sum the new line and output the odd row. Carry the // new row into the next pass. int y = 0; do { row[3] = vld1_u8(column); column += stride; row[4] = vld1_u8(column); column += stride; row_sq[3] = vmull_u8(row[3], row[3]); row_sq[4] = vmull_u8(row[4], row[4]); const uint16x4_t sum = Sum5Horizontal(Sum5Vertical(row)); const uint32x4_t sum_sq = Sum5Horizontal(Sum5Vertical(row_sq)); const uint16x4_t a2 = CalculateA2<n>(sum_sq, sum, s, v_255); const uint16x4_t b2 = CalculateB2Shifted(a2, sum, one_over_n); const uint16x8_t a2_b2 = vld1q_u16(temp_column); vst1q_u16(temp_column, vcombine_u16(a2, b2)); temp_column += 8; uint16x4_t sum565_a1 = Sum565(vcombine_u16(vget_low_u16(a2_b2), a2)); uint32x4_t sum565_b1 = Sum565W(vcombine_u16(vget_high_u16(a2_b2), b2)); const uint8x8_t src_u8 = vld1_u8(src_ptr); src_ptr += stride; const uint16x4_t src_u16 = vget_low_u16(vmovl_u8(src_u8)); const uint16x4_t output = CalculateFilteredOutput<5>(vadd_u16(sum565_a0, sum565_a1), vaddq_u32(sum565_b0, sum565_b1), src_u16); vst1_u16(out_buf, output); out_buf += kIntermediateStride; const uint8x8_t src0_u8 = vld1_u8(src_ptr); src_ptr += stride; const uint16x4_t src0_u16 = vget_low_u16(vmovl_u8(src0_u8)); const uint16x4_t output1 = CalculateFilteredOutput<4>(sum565_a1, sum565_b1, src0_u16); vst1_u16(out_buf, output1); out_buf += kIntermediateStride; row[0] = row[2]; row[1] = row[3]; row[2] = row[4]; row_sq[0] = row_sq[2]; row_sq[1] = row_sq[3]; row_sq[2] = row_sq[4]; sum565_a0 = sum565_a1; sum565_b0 = sum565_b1; y += 2; } while (y < height); x += 4; } while (x < width); } inline void BoxFilterPreProcess_SecondPass(const uint8_t* const src, const ptrdiff_t stride, const int width, const int height, const uint32_t s, uint16_t* const a2) { // Number of elements in the box being summed. const uint32_t n = 9; const uint32_t one_over_n = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n; const uint16x4_t v_255 = vdup_n_u16(255); // Calculate intermediate results, including one-pixel border, for example, // if unit size is 64x64, we calculate 66x66 pixels. // Because of the vectors this calculates in blocks of 4 so we actually // get 68 values. This doesn't appear to be causing problems yet but it // might. const uint8_t* const src_top_left_corner = src - 1 - 2 * stride; int x = -1; do { const uint8_t* column = src_top_left_corner + x; uint16_t* a2_column = a2 + (x + 1); uint8x8_t row[3]; row[0] = vld1_u8(column); column += stride; row[1] = vld1_u8(column); column += stride; uint16x8_t row_sq[3]; row_sq[0] = vmull_u8(row[0], row[0]); row_sq[1] = vmull_u8(row[1], row[1]); int y = -1; do { row[2] = vld1_u8(column); column += stride; row_sq[2] = vmull_u8(row[2], row[2]); const uint16x4_t sum = Sum3Horizontal(Sum3Vertical(row)); const uint32x4_t sum_sq = Sum3Horizontal(Sum3Vertical(row_sq)); const uint16x4_t a2_v = CalculateA2<n>(sum_sq, sum, s, v_255); vst1_u16(a2_column, a2_v); a2_column += kIntermediateStride; vst1_u16(a2_column, CalculateB2Shifted(a2_v, sum, one_over_n)); a2_column += kIntermediateStride; row[0] = row[1]; row[1] = row[2]; row_sq[0] = row_sq[1]; row_sq[1] = row_sq[2]; } while (++y < height + 1); x += 4; } while (x < width + 1); } inline uint16x4_t Sum444(const uint16x8_t a) { return Sum3Horizontal(vshlq_n_u16(a, 2)); } inline uint32x4_t Sum444W(const uint16x8_t a) { return Sum3HorizontalW(vshll_n_u16(vget_low_u16(a), 2), vshll_n_u16(vget_high_u16(a), 2)); } inline uint16x4_t Sum343(const uint16x8_t a) { const uint16x4_t middle = vext_u16(vget_low_u16(a), vget_high_u16(a), 1); const uint16x4_t sum = Sum3Horizontal(a); return vadd_u16(vadd_u16(vadd_u16(sum, sum), sum), middle); } inline uint32x4_t Sum343W(const uint16x8_t a) { const uint16x4_t middle = vext_u16(vget_low_u16(a), vget_high_u16(a), 1); const uint32x4_t sum = Sum3HorizontalW(vmovl_u16(vget_low_u16(a)), vmovl_u16(vget_high_u16(a))); return vaddw_u16(vaddq_u32(vaddq_u32(sum, sum), sum), middle); } inline void BoxFilterProcess_SecondPass(const uint8_t* src, const ptrdiff_t stride, const int width, const int height, const uint32_t s, uint16_t* const intermediate_buffer) { uint16_t* const a2 = intermediate_buffer + kIntermediateStride * kIntermediateHeight; BoxFilterPreProcess_SecondPass(src, stride, width, height, s, a2); int x = 0; do { uint16_t* a2_ptr = a2 + x; const uint8_t* src_ptr = src + x; // |filtered_output| must match how |a2| values are read since they are // written out over the |a2| values which have already been used. uint16_t* filtered_output = a2_ptr; uint16x4_t sum343_a[2], sum444_a; uint32x4_t sum343_b[2], sum444_b; sum343_a[0] = Sum343(vld1q_u16(a2_ptr)); a2_ptr += kIntermediateStride; sum343_b[0] = Sum343W(vld1q_u16(a2_ptr)); a2_ptr += kIntermediateStride; const uint16x8_t a_1 = vld1q_u16(a2_ptr); a2_ptr += kIntermediateStride; sum343_a[1] = Sum343(a_1); sum444_a = Sum444(a_1); const uint16x8_t b_1 = vld1q_u16(a2_ptr); a2_ptr += kIntermediateStride; sum343_b[1] = Sum343W(b_1); sum444_b = Sum444W(b_1); int y = 0; do { const uint16x8_t a_2 = vld1q_u16(a2_ptr); a2_ptr += kIntermediateStride; const uint16x4_t sum343_a2 = Sum343(a_2); const uint16x4_t a_v = vadd_u16(vadd_u16(sum343_a[0], sum444_a), sum343_a2); sum444_a = Sum444(a_2); sum343_a[0] = sum343_a[1]; sum343_a[1] = sum343_a2; const uint16x8_t b_2 = vld1q_u16(a2_ptr); a2_ptr += kIntermediateStride; const uint32x4_t sum343_b2 = Sum343W(b_2); const uint32x4_t b_v = vaddq_u32(vaddq_u32(sum343_b[0], sum444_b), sum343_b2); sum444_b = Sum444W(b_2); sum343_b[0] = sum343_b[1]; sum343_b[1] = sum343_b2; // Load 8 values and discard 4. const uint8x8_t src_u8 = vld1_u8(src_ptr); const uint16x4_t src_u16 = vget_low_u16(vmovl_u8(src_u8)); vst1_u16(filtered_output, CalculateFilteredOutput<5>(a_v, b_v, src_u16)); src_ptr += stride; filtered_output += kIntermediateStride; } while (++y < height); x += 4; } while (x < width); } template <int min_width> inline void SelfGuidedSingleMultiplier(const uint8_t* src, const ptrdiff_t src_stride, uint16_t* box_filter_process_output, uint8_t* dst, const ptrdiff_t dst_stride, const int width, const int height, const int16_t w_combo, const int16x4_t w_single) { static_assert(min_width == 4 || min_width == 8, ""); int y = 0; do { if (min_width == 8) { int x = 0; do { const int16x8_t u = vreinterpretq_s16_u16( vshll_n_u8(vld1_u8(src + x), kSgrProjRestoreBits)); const int16x8_t p = vreinterpretq_s16_u16(vld1q_u16(box_filter_process_output + x)); // u * w1 + u * wN == u * (w1 + wN) int32x4_t v_lo = vmull_n_s16(vget_low_s16(u), w_combo); v_lo = vmlal_s16(v_lo, vget_low_s16(p), w_single); int32x4_t v_hi = vmull_n_s16(vget_high_s16(u), w_combo); v_hi = vmlal_s16(v_hi, vget_high_s16(p), w_single); const int16x4_t s_lo = vrshrn_n_s32(v_lo, kSgrProjRestoreBits + kSgrProjPrecisionBits); const int16x4_t s_hi = vrshrn_n_s32(v_hi, kSgrProjRestoreBits + kSgrProjPrecisionBits); vst1_u8(dst + x, vqmovun_s16(vcombine_s16(s_lo, s_hi))); x += 8; } while (x < width); } else if (min_width == 4) { const int16x8_t u = vreinterpretq_s16_u16(vshll_n_u8(vld1_u8(src), kSgrProjRestoreBits)); const int16x8_t p = vreinterpretq_s16_u16(vld1q_u16(box_filter_process_output)); // u * w1 + u * wN == u * (w1 + wN) int32x4_t v_lo = vmull_n_s16(vget_low_s16(u), w_combo); v_lo = vmlal_s16(v_lo, vget_low_s16(p), w_single); int32x4_t v_hi = vmull_n_s16(vget_high_s16(u), w_combo); v_hi = vmlal_s16(v_hi, vget_high_s16(p), w_single); const int16x4_t s_lo = vrshrn_n_s32(v_lo, kSgrProjRestoreBits + kSgrProjPrecisionBits); const int16x4_t s_hi = vrshrn_n_s32(v_hi, kSgrProjRestoreBits + kSgrProjPrecisionBits); StoreLo4(dst, vqmovun_s16(vcombine_s16(s_lo, s_hi))); } src += src_stride; dst += dst_stride; box_filter_process_output += kIntermediateStride; } while (++y < height); } template <int min_width> inline void SelfGuidedDoubleMultiplier(const uint8_t* src, const ptrdiff_t src_stride, uint16_t* box_filter_process_output[2], uint8_t* dst, const ptrdiff_t dst_stride, const int width, const int height, const int16x4_t w0, const int w1, const int16x4_t w2) { static_assert(min_width == 4 || min_width == 8, ""); int y = 0; do { if (min_width == 8) { int x = 0; do { // |wN| values are signed. |src| values can be treated as int16_t. const int16x8_t u = vreinterpretq_s16_u16( vshll_n_u8(vld1_u8(src + x), kSgrProjRestoreBits)); // |box_filter_process_output| is 14 bits, also safe to treat as // int16_t. const int16x8_t p0 = vreinterpretq_s16_u16(vld1q_u16(box_filter_process_output[0] + x)); const int16x8_t p1 = vreinterpretq_s16_u16(vld1q_u16(box_filter_process_output[1] + x)); int32x4_t v_lo = vmull_n_s16(vget_low_s16(u), w1); v_lo = vmlal_s16(v_lo, vget_low_s16(p0), w0); v_lo = vmlal_s16(v_lo, vget_low_s16(p1), w2); int32x4_t v_hi = vmull_n_s16(vget_high_s16(u), w1); v_hi = vmlal_s16(v_hi, vget_high_s16(p0), w0); v_hi = vmlal_s16(v_hi, vget_high_s16(p1), w2); // |s| is saturated to uint8_t. const int16x4_t s_lo = vrshrn_n_s32(v_lo, kSgrProjRestoreBits + kSgrProjPrecisionBits); const int16x4_t s_hi = vrshrn_n_s32(v_hi, kSgrProjRestoreBits + kSgrProjPrecisionBits); vst1_u8(dst + x, vqmovun_s16(vcombine_s16(s_lo, s_hi))); x += 8; } while (x < width); } else if (min_width == 4) { // |wN| values are signed. |src| values can be treated as int16_t. // Load 8 values but ignore 4. const int16x4_t u = vget_low_s16( vreinterpretq_s16_u16(vshll_n_u8(vld1_u8(src), kSgrProjRestoreBits))); // |box_filter_process_output| is 14 bits, also safe to treat as // int16_t. const int16x4_t p0 = vreinterpret_s16_u16(vld1_u16(box_filter_process_output[0])); const int16x4_t p1 = vreinterpret_s16_u16(vld1_u16(box_filter_process_output[1])); int32x4_t v = vmull_n_s16(u, w1); v = vmlal_s16(v, p0, w0); v = vmlal_s16(v, p1, w2); // |s| is saturated to uint8_t. const int16x4_t s = vrshrn_n_s32(v, kSgrProjRestoreBits + kSgrProjPrecisionBits); StoreLo4(dst, vqmovun_s16(vcombine_s16(s, s))); } src += src_stride; dst += dst_stride; box_filter_process_output[0] += kIntermediateStride; box_filter_process_output[1] += kIntermediateStride; } while (++y < height); } // Assume box_filter_process_output[2] are allocated before calling // this function. Their sizes are width * height, stride equals width. void SelfGuidedFilter_NEON(const void* const source, void* const dest, const RestorationUnitInfo& restoration_info, ptrdiff_t source_stride, ptrdiff_t dest_stride, const int width, const int height, RestorationBuffer* const /*buffer*/) { // The output frame is broken into blocks of 64x64 (32x32 if U/V are // subsampled). If either dimension is less than 32/64 it indicates it is at // the right or bottom edge of the frame. It is safe to overwrite the output // as it will not be part of the visible frame. This saves us from having to // handle non-multiple-of-8 widths. // We could round here, but the for loop with += 8 does the same thing. // width = (width + 7) & ~0x7; // -96 to 96 (Sgrproj_Xqd_Min/Max) const int8_t w0 = restoration_info.sgr_proj_info.multiplier[0]; const int8_t w1 = restoration_info.sgr_proj_info.multiplier[1]; const int16_t w2 = (1 << kSgrProjPrecisionBits) - w0 - w1; const int index = restoration_info.sgr_proj_info.index; const uint8_t radius_pass_0 = kSgrProjParams[index][0]; const uint8_t radius_pass_1 = kSgrProjParams[index][2]; const auto* src = static_cast<const uint8_t*>(source); auto* dst = static_cast<uint8_t*>(dest); // |intermediate_buffer| is broken down into three distinct regions, each with // size |kIntermediateStride| * |kIntermediateHeight|. // The first is for final output of the first pass of PreProcess/Process. It // can be stored in |width| * |height| (at most 64x64). // The second and third are scratch space for |a2| and |b2| values from // PreProcess. // // At the end of BoxFilterProcess_SecondPass() the output is stored over |a2|. uint16_t intermediate_buffer[3 * kIntermediateStride * kIntermediateHeight]; uint16_t* box_filter_process_output[2] = { intermediate_buffer, intermediate_buffer + kIntermediateStride * kIntermediateHeight}; // If |radius| is 0 then there is nothing to do. If |radius| is not 0, it is // always 2 for the first pass and 1 for the second pass. if (radius_pass_0 != 0) { BoxFilterProcess_FirstPass(src, source_stride, width, height, kSgrScaleParameter[index][0], intermediate_buffer); } if (radius_pass_1 != 0) { BoxFilterProcess_SecondPass(src, source_stride, width, height, kSgrScaleParameter[index][1], intermediate_buffer); } // Put |w[02]| in vectors because we can use vmull_n_s16() for |w1| but there // is no vmlal_n_s16(). const int16x4_t w0_v = vdup_n_s16(w0); const int16x4_t w2_v = vdup_n_s16(w2); if (radius_pass_0 != 0 && radius_pass_1 != 0) { if (width > 4) { SelfGuidedDoubleMultiplier<8>(src, source_stride, box_filter_process_output, dst, dest_stride, width, height, w0_v, w1, w2_v); } else /* if (width == 4) */ { SelfGuidedDoubleMultiplier<4>(src, source_stride, box_filter_process_output, dst, dest_stride, width, height, w0_v, w1, w2_v); } } else { int16_t w_combo; int16x4_t w_single; uint16_t* box_filter_process_output_n; if (radius_pass_0 != 0) { w_combo = w1 + w2; w_single = w0_v; box_filter_process_output_n = box_filter_process_output[0]; } else /* if (radius_pass_1 != 0) */ { w_combo = w1 + w0; w_single = w2_v; box_filter_process_output_n = box_filter_process_output[1]; } if (width > 4) { SelfGuidedSingleMultiplier<8>( src, source_stride, box_filter_process_output_n, dst, dest_stride, width, height, w_combo, w_single); } else /* if (width == 4) */ { SelfGuidedSingleMultiplier<4>( src, source_stride, box_filter_process_output_n, dst, dest_stride, width, height, w_combo, w_single); } } } void Init8bpp() { Dsp* const dsp = dsp_internal::GetWritableDspTable(8); assert(dsp != nullptr); dsp->loop_restorations[0] = WienerFilter_NEON; dsp->loop_restorations[1] = SelfGuidedFilter_NEON; } } // namespace } // namespace low_bitdepth void LoopRestorationInit_NEON() { low_bitdepth::Init8bpp(); } } // namespace dsp } // namespace libgav1 #else // !LIBGAV1_ENABLE_NEON namespace libgav1 { namespace dsp { void LoopRestorationInit_NEON() {} } // namespace dsp } // namespace libgav1 #endif // LIBGAV1_ENABLE_NEON
37.634725
80
0.626112
bootleg-q
62e5bd5ca39ef948c79d742c1541c39dfa50bdcf
358
hpp
C++
src/properties/Manager.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
4
2021-03-01T13:33:30.000Z
2021-03-14T20:05:00.000Z
src/properties/Manager.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
null
null
null
src/properties/Manager.hpp
mechanicsfoundry/raytracinginoneweekend-glsl
515905135456fe263be9bc13b708222c28827a4d
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include "IProperty.hpp" namespace Properties { class Manager { private: std::vector<IProperty*> properties; public: Manager() = default; Manager(const Manager&) = delete; void Add(IProperty* property); void Update(const float time_step); }; }
15.565217
43
0.611732
mechanicsfoundry
62e8100c09be0bf0e04e5166329ffcd5e777a3a7
1,438
cpp
C++
codeforces/G - Water Testing/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/G - Water Testing/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/G - Water Testing/Wrong answer on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729# created: Feb/05/2020 17:11 * solution_verdict: Wrong answer on test 3 language: GNU C++14 * run_time: 15 ms memory_used: 0 KB * problem: https://codeforces.com/gym/101873/problem/G ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; struct point { long x,y; point(){};point(long _x,long _y):x(_x),y(_y){} point operator+(point p){return point(x+p.x,y+p.y);} point operator-(point p){return point(x-p.x,y-p.y);} point operator*(long d){return point(x*d,y*d);} point operator/(long d){return point(x/d,y/d);} long operator^(point p){return x*p.y-y*p.x;} }; long polygoanArea(vector<point>&p) { int n=p.size();long area=0,an=0; for(int i=1;i<n-1;i++) { an+=__gcd(abs(p[i].x-p[i+1].x),abs(p[i].y-p[i+1].y)); area+=(p[i]-p[0])^(p[i+1]-p[0]); } return abs(area)/2-an+p.size()-3; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n;vector<point>v(n); for(int i=0;i<n;i++) cin>>v[i].x>>v[i].y; long ans=polygoanArea(v); cout<<ans<<endl; return 0; }
35.95
111
0.467316
kzvd4729
62eabd5002a716d594338913741a44380b9dfffa
1,745
cpp
C++
Source/Tools/ParticleEditor2D/ParticleEffectEditor.cpp
aster2013/ParticleEditor2D
2c0e5605c6df1e9fb796b728b05671ac2b609032
[ "MIT" ]
27
2015-01-21T07:39:32.000Z
2021-04-26T22:21:09.000Z
Source/Tools/ParticleEditor2D/ParticleEffectEditor.cpp
seem-sky/ParticleEditor2D
2c0e5605c6df1e9fb796b728b05671ac2b609032
[ "MIT" ]
1
2015-05-05T17:04:51.000Z
2015-05-07T17:42:06.000Z
Source/Tools/ParticleEditor2D/ParticleEffectEditor.cpp
seem-sky/ParticleEditor2D
2c0e5605c6df1e9fb796b728b05671ac2b609032
[ "MIT" ]
15
2015-06-04T10:22:05.000Z
2021-02-11T01:00:32.000Z
// // Copyright (c) 2014 the ParticleEditor2D project. // // 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 "ParticleEditor.h" #include "ParticleEffectEditor.h" namespace Urho3D { ParticleEffectEditor::ParticleEffectEditor(Context* context) : Object(context), updatingWidget_(false) { } ParticleEffectEditor::~ParticleEffectEditor() { } void ParticleEffectEditor::UpdateWidget() { updatingWidget_ = true; HandleUpdateWidget(); updatingWidget_ = false; } ParticleEffect2D* ParticleEffectEditor::GetEffect() const { return ParticleEditor::Get()->GetEffect(); } ParticleEmitter2D* ParticleEffectEditor::GetEmitter() const { return ParticleEditor::Get()->GetEmitter(); } }
28.145161
80
0.755301
aster2013
62f01052b08b5ca16cc5f6edce33a0f772c89d3b
1,094
cpp
C++
main/lucid/managed/Orbit/StarCatalog.cpp
irumsey/ijrumsey.com
3dcf909eada5a09d39e6bf89a1f0bf1fa7328789
[ "MIT" ]
null
null
null
main/lucid/managed/Orbit/StarCatalog.cpp
irumsey/ijrumsey.com
3dcf909eada5a09d39e6bf89a1f0bf1fa7328789
[ "MIT" ]
null
null
null
main/lucid/managed/Orbit/StarCatalog.cpp
irumsey/ijrumsey.com
3dcf909eada5a09d39e6bf89a1f0bf1fa7328789
[ "MIT" ]
null
null
null
#include "StarCatalog.h" #include <lucid/orbit/Ephemeris.h> #include <msclr/marshal_cppstd.h> namespace /* anonymous */ { namespace MI = msclr::interop; namespace orbit = ::lucid::orbit; } #define theCatalog (orbit::StarCatalog::instance()) namespace Lucid { namespace Orbit { /// /// /// StarCatalogEntry::StarCatalogEntry(orbit::StarCatalog::Entry const &entry) { _internal = new orbit::StarCatalog::Entry(entry); } StarCatalogEntry::~StarCatalogEntry() { this->!StarCatalogEntry(); } StarCatalogEntry::!StarCatalogEntry() { delete _internal; } System::String ^StarCatalogEntry::Type::get() { return MI::marshal_as<System::String ^>(_internal->type); } /// /// /// void StarCatalog::Initialize(System::String ^path) { theCatalog.initialize(MI::marshal_as<std::string>(path)); } void StarCatalog::Shutdown() { theCatalog.shutdown(); } size_t StarCatalog::Count() { return theCatalog.count(); } StarCatalogEntry ^StarCatalog::At(size_t index) { return gcnew StarCatalogEntry(theCatalog[index]); } } /// Orbit } /// Lucid
16.328358
75
0.681901
irumsey
62f1639e2530aae54c41d9b2b049a17af58471f2
6,375
cc
C++
src/TransformationUtils.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
6
2021-08-16T09:57:38.000Z
2021-12-02T11:06:23.000Z
src/TransformationUtils.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
null
null
null
src/TransformationUtils.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
null
null
null
// // Created by Martin Blicha on 01.06.21. // #include "TransformationUtils.h" #include "QuantifierElimination.h" bool isTransitionSystem(ChcDirectedGraph const & graph) { auto graphRepresentation = AdjacencyListsGraphRepresentation::from(graph); auto reversePostorder = graphRepresentation.reversePostOrder(); // TS has 3 vertices: Init, Body, Bad if (reversePostorder.size() != 3) { return false; } // TS has 3 edges: From Init to Body, self-loop on Body, from Body to Bad Vertex const & beg = graph.getVertex(reversePostorder[0]); Vertex const & loop = graph.getVertex(reversePostorder[1]); Vertex const & end = graph.getVertex(reversePostorder[2]); auto const & begOutEdges = graphRepresentation.getOutgoingEdgesFor(beg.id); if (begOutEdges.size() != 1 || graph.getTarget(begOutEdges[0]) != loop.id) { return false; } auto const & loopOutEdges = graphRepresentation.getOutgoingEdgesFor(loop.id); if (loopOutEdges.size() != 2) { return false; } bool selfLoop = std::find_if(loopOutEdges.begin(), loopOutEdges.end(), [&graph, loop](EId eid) { return graph.getTarget(eid) == loop.id; }) != loopOutEdges.end(); if (not selfLoop) { return false; } bool edgeToEnd = std::find_if(loopOutEdges.begin(), loopOutEdges.end(), [&graph, end](EId eid) { return graph.getTarget(eid) == end.id; }) != loopOutEdges.end(); if (not edgeToEnd) { return false; } if (not graphRepresentation.getOutgoingEdgesFor(end.id).empty()) { return false; } return true; } std::unique_ptr<TransitionSystem> toTransitionSystem(ChcDirectedGraph const & graph, Logic& logic) { auto reversePostOrder = AdjacencyListsGraphRepresentation::from(graph).reversePostOrder(); assert(reversePostOrder.size() == 3); TermUtils utils(logic); PTRef pred = graph.getStateVersion(reversePostOrder[1]); vec<PTRef> vars = utils.getVarsFromPredicateInOrder(pred); vec<PTRef> nextVars = utils.getVarsFromPredicateInOrder(graph.getNextStateVersion(reversePostOrder[1])); // We need to determine auxiliary variables from the loop edge auto edges = graph.getEdges(); auto it = std::find_if(edges.begin(), edges.end(), [&](EId eid) { return graph.getSource(eid) == reversePostOrder[1] and graph.getTarget(eid) == reversePostOrder[1]; }); assert(it != edges.end()); EId loopEdge = *it; PTRef loopLabel = graph.getEdgeLabel(loopEdge); auto allVars = TermUtils(logic).getVars(loopLabel); vec<PTRef> graphAuxiliaryVars; for (PTRef var : allVars) { if (std::find(vars.begin(), vars.end(), var) == vars.end() and std::find(nextVars.begin(), nextVars.end(), var) == nextVars.end()) { graphAuxiliaryVars.push(var); } } // Now we can continue building the transition system std::vector<SRef> stateVarTypes; std::transform(vars.begin(), vars.end(), std::back_inserter(stateVarTypes), [&logic](PTRef var){ return logic.getSortRef(var); }); std::vector<SRef> auxVarTypes; std::transform(graphAuxiliaryVars.begin(), graphAuxiliaryVars.end(), std::back_inserter(auxVarTypes), [&logic](PTRef var){ return logic.getSortRef(var); }); auto systemType = std::unique_ptr<SystemType>(new SystemType(std::move(stateVarTypes), std::move(auxVarTypes), logic)); auto stateVars = systemType->getStateVars(); auto nextStateVars = systemType->getNextStateVars(); auto auxiliaryVars = systemType->getAuxiliaryVars(); assert(stateVars.size() == vars.size_()); assert(nextStateVars.size() == nextVars.size_()); PTRef init = PTRef_Undef; PTRef transitionRelation = PTRef_Undef; PTRef bad = PTRef_Undef; for (auto const & edge : edges) { VId source = graph.getSource(edge); VId target = graph.getTarget(edge); bool isInit = source == reversePostOrder[0] && target == reversePostOrder[1]; bool isLoop = source == reversePostOrder[1] && target == reversePostOrder[1]; bool isEnd = source == reversePostOrder[1] && target == reversePostOrder[2]; assert(isInit || isLoop || isEnd); PTRef fla = graph.getEdgeLabel(edge); if (isInit) { std::unordered_map<PTRef, PTRef, PTRefHash> subMap; std::transform(nextVars.begin(), nextVars.end(), stateVars.begin(), std::inserter(subMap, subMap.end()), [](PTRef key, PTRef value) { return std::make_pair(key, value); }); init = utils.varSubstitute(fla, subMap); init = QuantifierElimination(logic).keepOnly(init, stateVars); // std::cout << logic.printTerm(init) << std::endl; } if (isLoop) { std::unordered_map<PTRef, PTRef, PTRefHash> subMap; std::transform(vars.begin(), vars.end(), stateVars.begin(), std::inserter(subMap, subMap.end()), [](PTRef key, PTRef value) { return std::make_pair(key, value); }); std::transform(nextVars.begin(), nextVars.end(), nextStateVars.begin(), std::inserter(subMap, subMap.end()), [](PTRef key, PTRef value) { return std::make_pair(key, value); }); std::transform(graphAuxiliaryVars.begin(), graphAuxiliaryVars.end(), auxiliaryVars.begin(), std::inserter(subMap, subMap.end()), [](PTRef key, PTRef value) { return std::make_pair(key, value); }); transitionRelation = utils.varSubstitute(fla, subMap); // std::cout << logic.printTerm(transitionRelation) << std::endl; } if (isEnd) { std::unordered_map<PTRef, PTRef, PTRefHash> subMap; std::transform(vars.begin(), vars.end(), stateVars.begin(), std::inserter(subMap, subMap.end()), [](PTRef key, PTRef value) { return std::make_pair(key, value); }); bad = utils.varSubstitute(fla, subMap); bad = QuantifierElimination(logic).keepOnly(bad, stateVars); // std::cout << logic.printTerm(bad) << std::endl; } } assert(init != PTRef_Undef && transitionRelation != PTRef_Undef && bad != PTRef_Undef); auto ts = std::unique_ptr<TransitionSystem>(new TransitionSystem(logic, std::move(systemType), init, transitionRelation, bad)); return ts; }
56.415929
160
0.643922
usi-verification-and-security
62f4b90ade6d7eb27553a3d8531e3a916f834084
3,515
cpp
C++
src/tools/bench_perft.cpp
sgriffin53/swizzles
61b2c81cee2a994adb623a5185c55823b194eb32
[ "MIT" ]
null
null
null
src/tools/bench_perft.cpp
sgriffin53/swizzles
61b2c81cee2a994adb623a5185c55823b194eb32
[ "MIT" ]
null
null
null
src/tools/bench_perft.cpp
sgriffin53/swizzles
61b2c81cee2a994adb623a5185c55823b194eb32
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <chess/position.hpp> #include <chrono> #include <cstdint> #include <iomanip> #include <iostream> [[nodiscard]] auto perft(chess::Position &pos, const int depth) noexcept -> std::uint64_t { if (depth == 0) { return 1ULL; } std::uint64_t nodes = 0ULL; const auto moves = pos.movegen(); for (const auto &move : moves) { pos.makemove<false>(move); if (pos.is_attacked(pos.get_king(!pos.turn()), pos.turn())) { pos.undomove(); continue; } nodes += perft(pos, depth - 1); pos.undomove(); } return nodes; } [[nodiscard]] auto format_ms(const std::chrono::milliseconds ms) noexcept -> std::string { const auto seconds = ms.count() / 1000; const auto milliseconds = ms.count() % 1000; return std::to_string(seconds) + "." + std::to_string((milliseconds / 100) % 10) + std::to_string((milliseconds / 10) % 10) + std::to_string(milliseconds % 10); } int main(const int argc, const char **argv) { const std::array<std::string, 13> fens = {{ "startpos", "bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9", "2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9", "b1q1rrkb/pppppppp/3nn3/8/P7/1PPP4/4PPPP/BQNNRKRB w GE - 1 9", "qbbnnrkr/2pp2pp/p7/1p2pp2/8/P3PP2/1PPP1KPP/QBBNNR1R w hf - 0 9", "1nbbnrkr/p1p1ppp1/3p4/1p3P1p/3Pq2P/8/PPP1P1P1/QNBBNRKR w HFhf - 0 9", "qnbnr1kr/ppp1b1pp/4p3/3p1p2/8/2NPP3/PPP1BPPP/QNB1R1KR w HEhe - 1 9", "q1bnrkr1/ppppp2p/2n2p2/4b1p1/2NP4/8/PPP1PPPP/QNB1RRKB w ge - 1 9", "qbn1brkr/ppp1p1p1/2n4p/3p1p2/P7/6PP/QPPPPP2/1BNNBRKR w HFhf - 0 9", "qnnbbrkr/1p2ppp1/2pp3p/p7/1P5P/2NP4/P1P1PPP1/Q1NBBRKR w HFhf - 0 9", "qn1rbbkr/ppp2p1p/1n1pp1p1/8/3P4/P6P/1PP1PPPK/QNNRBB1R w hd - 2 9", "qnr1bkrb/pppp2pp/3np3/5p2/8/P2P2P1/NPP1PP1P/QN1RBKRB w GDg - 3 9", "qb1nrkbr/1pppp1p1/1n3p2/p1B4p/8/3P1P1P/PPP1P1P1/QBNNRK1R w HEhe - 0 9", }}; int depth = 1; auto total_time = std::chrono::milliseconds(0); std::uint64_t total_nodes = 0; // Get depth if (argc > 1) { depth = std::stoi(argv[1]); } // Print chart title std::cout << std::left; std::cout << std::setw(5) << "Pos"; std::cout << std::right; std::cout << std::setw(10) << "Nodes"; std::cout << std::setw(12) << "Nodes Sum"; std::cout << std::setw(9) << "Time"; std::cout << std::setw(10) << "Time Sum"; std::cout << std::left; std::cout << " FEN"; std::cout << "\n"; for (std::size_t i = 0; i < fens.size(); ++i) { auto pos = chess::Position(fens.at(i)); // Perft const auto t0 = std::chrono::steady_clock::now(); const auto nodes = perft(pos, depth); const auto t1 = std::chrono::steady_clock::now(); const auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0); total_time += dt; total_nodes += nodes; // Print chart row std::cout << std::left; std::cout << std::setw(5) << i + 1; std::cout << std::right; std::cout << std::setw(10) << nodes; std::cout << std::setw(12) << total_nodes; std::cout << std::setw(9) << format_ms(dt); std::cout << std::setw(10) << format_ms(total_time); std::cout << std::left; std::cout << " " << fens.at(i); std::cout << "\n"; } return 0; }
33.798077
91
0.576671
sgriffin53
62f607229fe64c3cc64ee48ad9393741eef15b7e
2,675
cpp
C++
main.cpp
JacobLCarter/Doodlebugs
3dba972079cf2e09314b61dd2182d66450300368
[ "MIT" ]
null
null
null
main.cpp
JacobLCarter/Doodlebugs
3dba972079cf2e09314b61dd2182d66450300368
[ "MIT" ]
null
null
null
main.cpp
JacobLCarter/Doodlebugs
3dba972079cf2e09314b61dd2182d66450300368
[ "MIT" ]
null
null
null
/******************************************************************************* * Program Name: main.cpp * Author: Matt Dienhart * Date: 2/10/2018 * Description: (Group Project) This is the main client code for the predator * and prey simulation. ******************************************************************************/ #include "Game.hpp" #include "utils.hpp" #include <iostream> #include <string> int main() { //control variables int menuSelect = 0; //display welcome screen std::cout << "---------------------------------------------------" << std::endl; std::cout << "| Welcome to the predator-prey simulation! |" << std::endl; std::cout << "| |" << std::endl; std::cout << "| CS 162, Group 7 2.18.2018 |" << std::endl; std::cout << "---------------------------------------------------" << std::endl; //select start simulation or quit std::cout << " 1. Play Simulation 2. Quit " << std::endl; //get input from user std::cin >> menuSelect; //loop until valid input is given while (std::cin.fail() || menuSelect < 1 || menuSelect > 2) { std::cout << "Invalid entry, please try again." << std::endl; std::cin.clear(); std::cin.ignore(999, '\n'); std::cin >> menuSelect; } //clear input buffer std::cin.ignore(999, '\n'); //loop as long as user wants to keep starting new simulations while(menuSelect == 1) { //start a new simulation int steps; std::cout << "Enter the number of steps for the simulation to run: "; std::cin >> steps; //loop until valid input is given (steps must be positive and greater than 0) while (std::cin.fail() || steps < 1) { std::cout << "Invalid entry, please try again." << std::endl; std::cin.clear(); std::cin.ignore(999, '\n'); std::cin >> steps; } //clear the input buffer std::cin.ignore(999, '\n'); //start the simulation Game newGame(steps); newGame.playGame(); //ask if user wants to play again std::cout << "Would you like to run another simulation?" << std::endl; std::cout << " 1. Play Again 2. Quit " << std::endl; std::cin >> menuSelect; //loop until valid input is given while (std::cin.fail() || menuSelect < 1 || menuSelect > 2) { std::cout << "Invalid entry, please try again." << std::endl; std::cin.clear(); std::cin.ignore(999, '\n'); std::cin >> menuSelect; } //clear input buffer std::cin.ignore(999, '\n'); } return 0; }
32.228916
83
0.496822
JacobLCarter
62f6dcde97fb0d69f669b7f9460488884cfe1855
305
hpp
C++
cpp-terminal/private/inputOutputModeFlags.hpp
jupyter-xeus/terminal
932ca39faaa9a7adbef4a04c5286313553638eb3
[ "Unlicense" ]
2
2020-10-21T15:16:20.000Z
2020-10-21T15:27:30.000Z
cpp-terminal/private/inputOutputModeFlags.hpp
jupyter-xeus/terminal
932ca39faaa9a7adbef4a04c5286313553638eb3
[ "Unlicense" ]
1
2020-10-21T15:18:09.000Z
2020-10-21T15:18:09.000Z
cpp-terminal/private/inputOutputModeFlags.hpp
jupyter-xeus/terminal
932ca39faaa9a7adbef4a04c5286313553638eb3
[ "Unlicense" ]
1
2020-10-21T15:18:11.000Z
2020-10-21T15:18:11.000Z
#pragma once #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 #endif #ifndef DISABLE_NEWLINE_AUTO_RETURN #define DISABLE_NEWLINE_AUTO_RETURN 0x0008 #endif #ifndef ENABLE_VIRTUAL_TERMINAL_INPUT #define ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200 #endif
21.785714
50
0.84918
jupyter-xeus
62f7f183e0593529f8414d22e2cd8e6f5489c4d4
43,505
cpp
C++
main.cpp
alechh/test-opencv
ab82723e4f9dda88a63add60d5f28dda5a22bc73
[ "Apache-2.0" ]
1
2022-03-24T08:05:22.000Z
2022-03-24T08:05:22.000Z
main.cpp
alechh/test-opencv
ab82723e4f9dda88a63add60d5f28dda5a22bc73
[ "Apache-2.0" ]
null
null
null
main.cpp
alechh/test-opencv
ab82723e4f9dda88a63add60d5f28dda5a22bc73
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <set> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <opencv2/imgproc/imgproc_c.h> #include <opencv2/opencv.hpp> #include <cmath> #include "SpaceKB.h" #include "IntervalsList.h" #include "Interval.h" #include "ListOfIntervalsLists.h" #include "ListOfPolylines.h" #include "TLinearRegression.h" using namespace cv; using namespace std; /** * Calculation of points of a straight line along rho and theta * @param rho -- radial coordinate * @param theta -- angular coordinate * @param pt1 -- Point 1 * @param pt2 -- Point 2 */ void calculatingPoints(double rho, double theta, Point &pt1, Point &pt2) { double a, b, x0, y0; a = cos(theta); b = sin(theta); x0 = a * rho; y0 = b * rho; pt1.x = cvRound(x0 - 1000 * b); pt1.y = cvRound(y0 + 1000 * a); pt2.x = cvRound(x0 + 1000 * b); pt2.y = cvRound(y0 - 1000 * a); } /** * Making SpaceKB to find the approximating line through linear regression * @param vertical_lines -- vector of points through which the lines pass */ void makeSpaceKB(double &result_x, double &result_y, vector <tuple<Point, Point>> vertical_lines) { vector< tuple<double, double> > coefficientsKB; // Коэффициенты b и k прямых x = ky+b для построения пространства Kb for (auto & vertical_line : vertical_lines) { Point pt1, pt2; pt1 = get<0>(vertical_line); pt2 = get<1>(vertical_line); // x = k * y + b // Беру k со знаком -, потому что в OpenCV система координат инвертирована относительно оси OY double k = - double((pt2.x - pt1.x)) / (pt2.y - pt1.y); double b = pt1.x - pt1.y * double(pt2.x - pt1.x) / (pt2.y - pt1.y); coefficientsKB.emplace_back(make_tuple(b, k)); } if (coefficientsKB.begin() != coefficientsKB.end()) // если нашлось хотя бы 2 прямые { double approaching_x = -1; double approaching_y = -1; SpaceKB spaceKb(coefficientsKB); spaceKb.approaching_straight_line(approaching_x, approaching_y); // вычисление координат точки пересечения прямых if (approaching_x != -1 && approaching_y != -1) { result_x = approaching_x; result_y = approaching_y; } } } /** * Select the vertical lines from the all lines * @param lines * @param delta * @return */ vector <tuple<Point, Point>> selectionOfVerticalLines(vector<Vec2f> lines, int delta = 300) { vector <tuple<Point, Point>> vertical_lines; // множество пар точек, через которые проходят вертикальные прямые for (auto & line : lines) { double rho, theta; Point pt1, pt2; // 2 точки, через которые проходит прямая rho = line[0]; theta = line[1]; calculatingPoints(rho, theta, pt1, pt2); // вычисление двух точек прямой (pt1, pt2) if (abs(pt1.x - pt2.x) < delta) // если прямая подозрительна на вертикальную { vertical_lines.emplace_back(pt1, pt2); } } return vertical_lines; } /** * Draw lines * @param src -- Input image * @param lines -- vector of pairs of points of a straight line */ void drawLines(Mat &src, vector <tuple<Point, Point>> lines) { for (auto & line : lines) { Point pt1, pt2; pt1 = get<0>(line); pt2 = get<1>(line); cv::line(src, pt1, pt2, CV_RGB(0,255,0), 1, LINE_AA); // отрисовка прямой } } /** * Search for vertical straight lines on video using the Hough method * @param src -- Input image * @return vector of rho and theta pairs */ vector<Vec2f> findLinesHough(Mat &src) { Mat src_gray, src_canny; vector<Vec2f> lines; // прямые, найденные на изображении // Median blur----------------------- // int n = 3; // medianBlur(src, src, n); //cvtColor(src, src_gray, COLOR_BGR2GRAY); // Подготовка изображения для метода Хафа поиска прямых Canny(src, src_canny, 50, 200); // Подготовка изображения для метода Хафа поиска прямых HoughLines(src_canny, lines, 1, CV_PI / 180, 100); src_gray.release(); src_canny.release(); return lines; } /** * Draw vertical line * @param src -- Input image * @param x -- x coordinate of the line */ void drawVerticalLine(Mat &src, double x) { Point pt1, pt2; pt1.x = x; pt1.y = 0; pt2.x = x; pt2.y = src.rows; if (pt1.x != 0 && pt2.x != 0) { line(src, pt1, pt2, CV_RGB(250, 230, 0), 3, CV_AA); } } /** * Draw x coordinate of the point on the image * @param src -- Input image * @param x -- x coordinate */ void drawXOnImage(Mat &src, double x) { String text = to_string(x); int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; double fontScale = 2; int thickness = 3; int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; Point textOrg(15,50); // Position of the text putText(src, text, textOrg, fontFace, fontScale, Scalar(0, 0, 0), thickness, 8); } /** * Simple bubble sort for array of double * @param values -- array of double * @param size -- size of the array */ void bubbleSort(double *values, int size) { // сперва нужно перенести все NaN в конец массива int index_of_last_not_nan; // получение индекса последнего числа != nan for (int i = size - 1; i >= 0; i--) { if (!std::isnan(values[i])) { index_of_last_not_nan = i; break; } } // перемещение nan в конец массива for (int i = 0; i < size; i++) { if (std::isnan(values[i])) { std::swap(values[i], values[index_of_last_not_nan]); for (int j = size - 1; j >= 0; j--) { if (!std::isnan(values[j])) { index_of_last_not_nan = j; break; } } } } // сортировка for (size_t i = 0; i + 1 < size; i++) { for (size_t j = 0; j + 1 < size - i; j++) { if (values[j + 1] < values[j] && !std::isnan(values[j + 1]) && !std::isnan(values[j])) { std::swap(values[j], values[j + 1]); } } } } /** * The median value in the array * @param valuesForMedianFilter -- array of values for median filter * @param NUMBER_OF_MEDIAN_VALUES -- a number indicating the frequency of the median filter * @return -- median value */ double medianFilter(double *valuesForMedianFilter, const int NUMBER_OF_MEDIAN_VALUES) { int indexOfResult = (NUMBER_OF_MEDIAN_VALUES - 1) / 2; bubbleSort(valuesForMedianFilter, NUMBER_OF_MEDIAN_VALUES); return valuesForMedianFilter[indexOfResult]; } /** * Selection of vertical continuous segments, depending on their length, draw them in dst * @param src -- Input image * @param dst -- Output image * @param delta -- The coefficient by which we glue close segments together */ void makePolylines(Mat &src, Mat &dst, int delta = 10, int x_roi = 0, int width_roi = 0) { auto listOfPolylines = new ListOfPolylines; // заполняем listOfPolylines вертикальными отрезками for (int i = 0; i < src.cols; i++) { int begin = 0; int end = 0; for (int j = 1; j < src.rows; j++) { cv::Vec3b lastColor = src.at<Vec3b>(j - 1, i); cv::Vec3b newColor = src.at<Vec3b>(j, i); if (newColor != lastColor) { if (newColor == Vec3b(0, 0, 0)) // встретили черный цвет, значит это начало нового отрезка { if (j - end < delta) { // если есть 2 отрезка в одной колонке, которые очень близко, но разрвны с разрывом длиной delta // тогда мы их соединяем // end -- конец предыдущего найденного отрезка // также добавим фильтр roi (будем склеивать только центральные отрезки) if (width_roi != 0) { if (x_roi <= i && i <= x_roi + width_roi) { begin = end + 1; } else { begin = j; } } else { begin = end + 1; } } else { begin = j; } } else if (newColor == Vec3b(255, 255, 255)) { // встретили белый цвет, значит это конец отрезка end = j - 1; listOfPolylines->addPolyline(begin, end, i); } } } } // выводим вертикальные отрезки на изображение Polyline *currPolyline = listOfPolylines->head; while (currPolyline) { if (50 <= currPolyline->length() && currPolyline->length() <= src.rows) { Point pt1, pt2; pt1.x = currPolyline->column; pt1.y = currPolyline->begin; pt2.x = currPolyline->column; pt2.y = currPolyline->end; line(dst, pt1, pt2, Scalar(0, 0, 0), 1); } currPolyline = currPolyline->next; } // освобождаем память delete listOfPolylines; } /** * Gluing the borders of clusters that match the same color * @param src -- Input image * @param dst -- Output image */ void vectorisation(Mat &src, Mat &dst) { auto *listOfIntervalsLists = new ListOfIntervalsLists; int begin = 0; int end; // заполняем список списков интервалов для первой строки for (int j = 1; j < src.cols; j++) { if (src.at<Vec3b>(0, j) != src.at<Vec3b>(0, j - 1)) { end = j - 1; auto *intervalList = new IntervalsList; intervalList->addInterval(begin, end, 0, src.at<Vec3b>(0, j - 1)); begin = j; listOfIntervalsLists->addIntervalList(intervalList); } } // последний интервал в первой строке auto *intervalList = new IntervalsList; intervalList->addInterval(begin, src.cols - 1, 0, src.at<Vec3b>(0, src.cols - 1)); listOfIntervalsLists->addIntervalList(intervalList); // заполняем списки интервалов для остальных строк for (int i = 1; i < src.rows; i++) { // заполним первый интервал мусорными значениями (не добавляем его в список) auto *currInterval = new Interval(-1, -1, -1, src.at<Vec3b>(0, 0)); IntervalsList *currIntervalList = listOfIntervalsLists->head; int prevIntervalEnd = currIntervalList->tail->end; // эта переменная нужна для своевременного сдвига текущего списка интервалов begin = 0; for (int j = 1; j < src.cols; j++) { if (src.at<Vec3b>(i, j) != src.at<Vec3b>(i, j - 1)) // если нашли границу интервала { cv::Vec3b color = src.at<Vec3b>(i, j - 1); // цвет найденного интервала // удаление интервалов, которые мы не добавили (чтобы память не утекала) if (!currInterval->added) { delete currInterval; } end = j - 1; currInterval = new Interval(begin, end, i, color); begin = j; // сравниваем найденный интервал с интервалом из списка интервалов предыдущей строки // (они точно пересекаются, потому что мы вовремя двигаем указатель на список интервалов) if (color == currIntervalList->tail->color) // если интервалы относятся к одному кластеру (один цвет) { currInterval->added = true; currIntervalList->addInterval(currInterval); // сохраняем интервал в списке } } // сдвигаем указатель на список интервалов while (prevIntervalEnd <= currInterval->end && currIntervalList->next != nullptr) { currIntervalList = currIntervalList->next; prevIntervalEnd = currIntervalList->tail->end; } } if (!currInterval->added) { delete currInterval; } // добавление последнего интервала строки currInterval = new Interval(begin, src.cols - 1, i, src.at<Vec3b>(i, src.cols - 1)); if (currInterval->color == currIntervalList->tail->color) { currIntervalList->addInterval(currInterval); } else { delete currInterval; } } // нарисуем границы кластеров Mat result_of_vectorisation(src.rows, src.cols, src.type(), Scalar(255, 255, 255)); auto currIntervalList = listOfIntervalsLists->head; while (currIntervalList != nullptr) { auto currInterval = currIntervalList->head; while (currInterval != nullptr) { Point pt1, pt2; pt1.x = currInterval->begin; pt1.y = currInterval->y_coordinate; pt2.x = currInterval->end; pt2.y = currInterval->y_coordinate; circle(result_of_vectorisation, pt1, 1, Scalar(0, 0, 0), 1); circle(result_of_vectorisation, pt2, 1, Scalar(0, 0, 0), 1); currInterval = currInterval->next; } currIntervalList = currIntervalList->next; } dst = result_of_vectorisation; // освобождаем память result_of_vectorisation.release(); delete listOfIntervalsLists; } /** * Paint each pixel in its own color depending on the angle of the gradient * @param grad_x -- Array for x gradient * @param grad_y -- Array for y gradient * @param dst -- Output image */ void clustering(Mat& grad_x, Mat& grad_y, Mat& dst) { Mat angle(grad_x.rows, grad_x.cols, CV_64FC4); phase(grad_x, grad_y, angle); // вычисление углов градиента в каждой точке MatIterator_<Vec3b> it, end; int i = 0; int j = 0; for (it = dst.begin<Vec3b>(), end = dst.end<Vec3b>(); it != end; ++it) { float s = angle.at<float>(i, j); if (- CV_PI / 4 <= s && s <= CV_PI / 4) { // red (*it)[0] = 0; (*it)[1] = 0; (*it)[2] = 255; } else if (CV_PI / 4 < s && s <= 3.0 * CV_PI / 4) { // blue (*it)[0] = 255; (*it)[1] = 0; (*it)[2] = 0; } else if (3.0 * CV_PI / 4 < s && s <= 5.0 * CV_PI / 4) { // green (*it)[0] = 0; (*it)[1] = 255; (*it)[2] = 0; } else if (5.0 * CV_PI / 3 < s && s <= 7.0 * CV_PI / 4) { // yellow (*it)[0] = 0; (*it)[1] = 255; (*it)[2] = 255; } j++; if (j == angle.cols) { i++; j = 0; } } // освобождаем память angle.release(); } /** * Calculating the gradient angles * @param src -- Input image * @param grad_x -- Output for x gradient * @param grad_y -- Output for y gradient */ void simpleSobel(Mat &src, Mat &grad_x, Mat &grad_y) { Mat src_gauss, src_gray; GaussianBlur(src, src_gauss, Size(3, 3), 0, 0, BORDER_DEFAULT); cvtColor(src_gauss, src_gray, COLOR_BGR2GRAY); Sobel(src_gray, grad_x, CV_32F, 1, 0); Sobel(src_gray, grad_y, CV_32F, 0, 1); // освобождаем память src_gauss.release(); src_gray.release(); } /** * Discarding lines that are outside the Region Of Interest * @param lines -- vector of pairs of points of vertical lines * @param x_roi -- left border of the roi * @param width_roi -- width of the roi */ void roiForVerticalLines(vector< tuple<Point, Point> > &lines, int x_roi, int width_roi) { auto i = lines.begin(); while (i != lines.end()) { Point pt1 = get<0>(*i); Point pt2 = get<1>(*i); if (pt1.x < x_roi || pt1.x > x_roi + width_roi) { i = lines.erase(i); } else { i++; } } //-------------------------------------------- // Будем удалять прямые, которые наклонены не туда, куда они должны быть наклонены. // Например, если прямая слева от центра наклонена влево. // i = lines.begin(); // // while(i != lines.end()) // { // Point pt1 = get<0>(*i); // Point pt2 = get<1>(*i); // // // int image_center = x_roi + width_roi / 2; // // if (pt1.x < image_center && pt2.x < image_center) // { // // если прямая слева от центра // // if (pt1.y < pt2.y) // { // // если pt1 выше, чем pt2 // // if (pt1.x < pt2.x) // { // // если прямая наклонена не туда, куда нужно (это значит, что прямая нашлась неправильно) // i = lines.erase(i); // } // else // { // i++; // } // } // else // { // // если pt2 выше, чем pt1 // // if (pt2.x < pt1.x) // { // i = lines.erase(i); // } // else // { // i++; // } // } // } // else // { // // если прямая нашлась справа от центра // // if (pt1.y < pt2.y) // { // // если pt1 выше, чем pt2 // // if (pt1.x > pt2.x) // { // i = lines.erase(i); // } // else // { // i++; // } // } // else // { // // если pt2 выше // // if (pt2.x > pt1.x) // { // i = lines.erase(i); // } // else // { // i++; // } // } // // } // } //-------------------------------------------- } /** * A filter that allows to determine whether the same number of straight lines were found * to the left and right of the middle of the image * @param vertical_lines -- vector of pairs of points of a straight line * @param src_center -- x coordinate of the center of the image * @param delta -- Acceptable value for the deviation of the number of left segments from the number of right segments * @return */ bool quantitativeFilter(vector < tuple<Point, Point> > vertical_lines, int src_center, double delta = 2) { int countLeft = 0; // считаем количество прямых левее центра изображения for (auto & line : vertical_lines) { Point pt1 = get<0>(line); if (pt1.x <= src_center) { countLeft++; } } if (countLeft == 0 || vertical_lines.size() - countLeft == 0) { return false; } // если слева и справа прямых почти поровну (количество отличается на delta) if (countLeft / (vertical_lines.size() - countLeft) < delta) { return true; } else { return false; } } /** * Selecting the horizon line manually. Important: for each video, the result must be different * @param src -- Input image * @return tuple of the points of the horizon */ tuple<Point, Point> manuallySelectingHorizonLine(Mat src) { Point pt1, pt2; // for video PATH_road3 pt1.x = 0; pt1.y = src.rows / 2 + 12; pt2.x = src.cols - 1; pt2.y = src.rows / 2 + 78; return make_tuple(pt1, pt2); } /** * Get points of the accurate horizon line * @param y -- y coordinate of the horizon line * @param width -- width of the image * @return tuple of points of the line */ tuple<Point, Point> getAccurateHorizonLine(int y, int width) { Point pt1, pt2; pt1.x = 0; pt1.y = y; pt2.x = width - 1; pt2.y = y; return make_tuple(pt1, pt2); } /** * Get points of the accurate vertical line * @param x -- x coordinate of the vertical line * @param height -- height of the image * @return tuple of points of the line */ tuple<Point, Point> getAccurateVerticalLine(int x, int height) { Point pt1, pt2; pt1.x = x; pt1.y = 0; pt2.x = x; pt2.y = height - 1; return make_tuple(pt1, pt2); } /** * Calculating the vanishing point of straight road markings * @param roadMarkings -- vector of straight line point pairs of road markings * @return vanishing point */ Point findVanishingPointLane( vector< tuple<Point, Point> > roadMarkings) { vector< tuple<double, double> > coefficientsKB; double result_x, result_y; for (auto & line : roadMarkings) { Point pt1, pt2; pt1 = get<0>(line); pt2 = get<1>(line); // x = k * y + b double k = - double((pt2.x - pt1.x)) / (pt2.y - pt1.y); double b = pt1.x - pt1.y * double(pt2.x - pt1.x) / (pt2.y - pt1.y); coefficientsKB.emplace_back(make_tuple(b, k)); } if (coefficientsKB.begin() != coefficientsKB.end()) // если нашлось хотя бы 2 прямые { SpaceKB spaceKb(coefficientsKB); spaceKb.approaching_straight_line(result_x, result_y); // вычисление координат точки пересечения прямых } Point van_point_lane; // можно пользоваться заранее вычисленной точкой, а можно вычислять ее онлайн // van_point_lane.x = result_x; // van_point_lane.y = result_y; // for video PATH_road3 van_point_lane.x = 586; van_point_lane.y = 428; return van_point_lane; } /** * Calculating road marking lines from an image * @param src -- Input image * @return vector of straight line point pairs of road markings */ vector< tuple<Point, Point> > findRoadMarkingLines(Mat &src) { Mat src_canny; Mat src_hsv = Mat(src.cols, src.rows, 8, 3); vector<Mat> splitedHsv = vector<Mat>(); cvtColor(src, src_hsv, CV_RGB2HSV); split(src_hsv, splitedHsv); int sensivity = 120; int S_WHITE_MIN = 0; int V_WHITE_MIN = 255 - sensivity; int S_WHITE_MAX = sensivity; int V_WHITE_MAX = 255; for (int y = 0; y < src_hsv.cols; y++) { for (int x = 0; x < src_hsv.rows; x++) { // получаем HSV-компоненты пикселя int H = static_cast<int>(splitedHsv[0].at<uchar>(x, y)); // Тон int S = static_cast<int>(splitedHsv[1].at<uchar>(x, y)); // Интенсивность int V = static_cast<int>(splitedHsv[2].at<uchar>(x, y)); // Яркость if (!(S_WHITE_MIN <= S && S <= S_WHITE_MAX && V_WHITE_MIN <= V && V <= V_WHITE_MAX)) { src_hsv.at<Vec3b>(x, y)[0] = 0; src_hsv.at<Vec3b>(x, y)[1] = 0; src_hsv.at<Vec3b>(x, y)[2] = 0; } } } Canny(src_hsv, src_canny, 200, 360); vector<Vec4f> lines; HoughLinesP(src_canny, lines, 1, CV_PI / 180, 150, 5, 8); vector< tuple<Point, Point> > roadMarkings; // здесь будем хранить точки прямых левее и правее от центра for (auto & line : lines) { int x1 = line[0]; int y1 = line[1]; int x2 = line[2]; int y2 = line[3]; if (x1 > x2) { // делаем, чтобы крайняя левая точка прямой была (x1,y1) для удобства int temp_x1 = x1; int temp_y1 = y1; x1 = x2; y1 = y2; x2 = temp_x1; y2 = temp_y1; } if (x2 != x1) // если прямая не вертикальная { const double MIN_SLOPE = 0.3; const double MAX_SLOPE = 0.7; double slope = double(y2 - y1) / (x2 - x1); int epsilon = 20; if (MIN_SLOPE <= abs(slope) && abs(slope) <= MAX_SLOPE && y2 >= src.rows / 2 && y1 >= src.rows / 2 && abs(y2 - y1) >= epsilon) { // если нашлась прямая с нужным наклоном, в нижней половине изображения и достаточная по длине roadMarkings.emplace_back(make_tuple(Point(x1, y1), Point(x2, y2))); } } } // draw lines // for (auto & road_line : roadMarkings) // { // line(src, get<0>(road_line), get<1>(road_line), Scalar(255, 255, 255), 2); // } src_hsv.release(); src_canny.release(); return roadMarkings; } /** * Distance from a point to a straight line * @param pnt -- Point * @param f -- Linear function x = k * y + b * @return distance */ double distToLine(Point pnt, LinearFunction f) { // distance from point to line x - f.k * y - f.c = 0 return abs(double(pnt.x) - f.k * double(pnt.y) - f.b) / (sqrt(1 + f.k * f.k)); } /** * Calculating linear regressions based on contour points * @param m_points -- Points of the contour * @return vector of TLinearRegression */ vector<TLinearRegression> calcRegressions(vector<Point> m_points) { vector<TLinearRegression> regressions; if (m_points.size() < 2) { return regressions; } TLinearRegression regression; //add points 0-2 to regression for (size_t i = 0; i < 3; i++) { regression.addPoint(m_points[i].x, m_points[i].y); } LinearFunction f = regression.calculate(); double c_min_dist_threshold = 2; for (size_t i = 3; i < m_points.size(); ++i) { Point pnt = m_points[i]; if (distToLine(pnt, f) < c_min_dist_threshold) //also try to use regression.eps() to appreciate curvature of added points sequence { regression.addPoint(m_points[i].x, m_points[i].y); } else { regressions.emplace_back(regression); regression.clear(); while (i < m_points.size() - 2) { if (m_points[i].x == m_points[i + 1].x && m_points[i + 1].x == m_points[i + 2].x) { // если у следующих 3х точек одна абсцисса i++; } else { regression.addPoint(m_points[i].x, m_points[i].y); regression.addPoint(m_points[i + 1].x, m_points[i + 1].y); regression.addPoint(m_points[i + 2].x, m_points[i + 2].y); i += 2; break; } } } f = regression.calculate(); } if (regressions.size() == 0) { // если все точки контура лежат на одной прямой, то regression так и не добавится в regressions regressions.emplace_back(regression); } return regressions; } /** * Getting two points of a straight line x = k * y + b through the coefficients k,b * @param k -- the angle of inclination is straight * @param b -- offset * @return a tuple of straight points */ tuple<Point, Point> getPointsOfTheLine(double k, double b) { // x = k * y + b. Point pt1, pt2; pt1.y = 0; pt1.x = k * pt1.y + b; pt2.y = 720; pt2.x = k * pt2.y + b; return make_tuple(pt1, pt2); } /** * Getting a vector of pairs of straight points from a vector of linear functions * @param linearFunctions -- vector of Linear Functions x = k * y + b * @return vector of tuple of points of the straight lines */ vector < tuple<Point, Point> > findVectorOfPointsOfVerticalLines(vector <LinearFunction> linearFunctions) { vector < tuple<Point, Point> > vertical_lines; for (int i = 0; i < linearFunctions.size(); i++) { double delta = 0.05; // чтобы определить вертикальные прямые через угол наклона if (!std::isnan(linearFunctions[i].k) && !std::isnan(linearFunctions[i].b) && abs(linearFunctions[i].k) < delta) { Point pt1, pt2; tuple<Point, Point> points = getPointsOfTheLine(linearFunctions[i].k, linearFunctions[i].b); pt1 = get<0>(points); pt2 = get<1>(points); vertical_lines.template emplace_back(make_tuple(pt1, pt2)); } } return vertical_lines; } /** * Obtaining a vector of linear functions x = k * y + b via linear regression over contours * @param contours -- vector of contours * @return vector of LinearFunctions x = k * y + b */ vector <LinearFunction> linearRegressionForContours(vector< vector<Point> > contours) { vector <LinearFunction> linearFunctions; // вектор коэффициентов {k, b} линейных функций x = k * y + b // линейная регрессия по всем контурам for (size_t i = 0; i < contours.size(); i++) { // считаем регрессии от контура vector <TLinearRegression> regressions = calcRegressions(contours[i]); if (regressions.size() == 0) { continue; } // вычисление линейных функций x = k * y + b по полученным регрессиям for (size_t j = 0; j < regressions.size(); j++) { linearFunctions.template emplace_back(regressions[j].calculate()); } } return linearFunctions; } /** * Get angle between two straight lines * @param pt11 -- Point of the first line l1 * @param pt12 -- Point of the first line l1 * @param pt21 -- Point of the second line l2 * @param pt22 -- Point of the second line l2 * @return angle in degrees between l1 and l2 */ double angleBetweenStraightLines(Point pt11, Point pt12, Point pt21, Point pt22) { // y = k * x + b double k1, b1, k2, b2; if (pt12.x - pt11.x == 0) { // если прямая вертикальная k1 = pt11.x; b1 = 0; } else { k1 = double(pt12.y - pt11.y) / (pt12.x - pt11.x); b1 = - pt11.x * double(pt12.y - pt11.y) / (pt12.x - pt11.x) + pt11.y; } if (pt22.x - pt21.x == 0) { // если прямая вертикальная k2 = pt21.x; b2 = 0; } else { k2 = double(pt22.y - pt21.y) / (pt22.x - pt21.x); b2 = - pt21.x * double(pt22.y - pt21.y) / (pt22.x - pt21.x) + pt21.y; } double angle_radian = abs(atan((k2 - k1) / (1 + k2 * k1))); double angle_degree = angle_radian * (180.0 / CV_PI); return angle_degree; } /** * Function of finding straight vertical lines using Hough method * @tparam T * @param path -- path to the video file. 0 means that the video will be read from the webcam. * @param resize -- image resizing factor. */ template <class T> void selectingLinesUsingHoughMethod(T path, double eps, int max_frame_number, int &numberOfSuccessfulFrames, double resize = 1) { VideoCapture capture(path); if (!capture.isOpened()) { cerr<<"Error"<<endl; return; } Mat src; int frame_counter = 0; int n = 1; // Счетчик для медианного фильтра const int NUMBER_OF_MEDIAN_VALUES = 4; // Раз во сколько кадров проводим медианный фильтр double valuesForMedianFilterX[NUMBER_OF_MEDIAN_VALUES - 1]; // Массив значений, который будет сортироваться для медианного фильтра double valuesForMedianFilterY[NUMBER_OF_MEDIAN_VALUES - 1]; double prevResult_x = 0; // Сохранение предыдущего значения, чтобы выводить на экран Point van_point_verticals; while (true) { capture >> src; frame_counter++; vector<Vec2f> lines = findLinesHough(src); // нахождение прямых линий vector <tuple<Point, Point>> vertical_lines = selectionOfVerticalLines(lines); // выбор только вертикальных линий drawLines(src, vertical_lines); // отрисовка прямых линий double result_x = 0; // Вычисленная координата x точки схода прямых double result_y = 0; makeSpaceKB(result_x, result_y, vertical_lines); // построение пространства Kb, чтобы найти приближающую прямую через // линейную регрессию. Далее обратным отображением находим точку схода прямых if (n % NUMBER_OF_MEDIAN_VALUES == 0) // Если нужно провести медианный фильтр { prevResult_x = medianFilter(valuesForMedianFilterX, NUMBER_OF_MEDIAN_VALUES); // так как медианный фильтр делаем по координатам x, надо координате x сопоставить соответствующий y for (int i = 0; i < NUMBER_OF_MEDIAN_VALUES - 1; i++) { if (valuesForMedianFilterX[i] == prevResult_x) { van_point_verticals.x = prevResult_x; van_point_verticals.y = valuesForMedianFilterY[i]; break; } } } else { valuesForMedianFilterX[n - 1] = result_x; valuesForMedianFilterY[n - 1] = result_y; } // drawVerticalLine(src, prevResult_x); if (resize != 1) { cv::resize(src, src, cv::Size(), resize, resize); } if (n % NUMBER_OF_MEDIAN_VALUES == 0) { n = 1; } else { n++; } // нахождение линий дорожной разметки vector< tuple<Point, Point> > roadMarkings = findRoadMarkingLines(src); // определение точки пересечения дорожной разметки Point van_point_lane = findVanishingPointLane(roadMarkings); // получение линии горизонта, размеченной вручную tuple<Point, Point> currentHorizonLine = manuallySelectingHorizonLine(src); Point currentHorizon_pt1 = get<0>(currentHorizonLine); Point currentHorizon_pt2 = get<1>(currentHorizonLine); // получение горизонтальной линии tuple<Point, Point> accurateHorizonLine = getAccurateHorizonLine(currentHorizon_pt1.y, src.cols); Point accurateHorizon_pt1 = get<0>(accurateHorizonLine); Point accurateHorizon_pt2 = get<1>(accurateHorizonLine); // получение вертикальное линии tuple<Point, Point> accurateVerticalLine = getAccurateVerticalLine(van_point_lane.x, src.rows); Point accurateVertical_pt1 = get<0>(accurateVerticalLine); Point accurateVertical_pt2 = get<1>(accurateVerticalLine); line(src, van_point_lane, van_point_verticals, Scalar(255, 0, 0), 1, LINE_AA); line(src, currentHorizon_pt1, currentHorizon_pt2, Scalar(0, 0, 255), 1, LINE_AA); // line(src, accurateVertical_pt1, accurateVertical_pt2, Scalar(255, 0, 0), 1, LINE_AA); // line(src, accurateHorizon_pt1, accurateHorizon_pt2, Scalar(0, 0, 255), 1, LINE_AA); double angle_vertical = angleBetweenStraightLines(van_point_lane, van_point_verticals, accurateVertical_pt1, accurateVertical_pt2); double angle_horizon = angleBetweenStraightLines(currentHorizon_pt1, currentHorizon_pt2, accurateHorizon_pt1, accurateHorizon_pt2); double error_rate = abs(angle_vertical - angle_horizon); if (error_rate < eps) { numberOfSuccessfulFrames++; } // cout << frame_counter << endl; if (frame_counter == max_frame_number) { break; } //imshow("Result", src); int k = waitKey(25); if (k == 27) { break; } } } template <class T> void selectingLinesUsingGradient(T path, double eps, int max_frame_number, int &numberOfSuccessfulFrames, double resize = 1) { VideoCapture capture(path); if (!capture.isOpened()) { cerr<<"Error"<<endl; return; } Mat src, src_vectorization; Mat grad_x, grad_y; // VideoWriter outputVideo; // Size S = Size((int) capture.get(CAP_PROP_FRAME_WIDTH), (int) capture.get(CAP_PROP_FRAME_HEIGHT)); // int ex = static_cast<int>(capture.get(CAP_PROP_FOURCC)); // outputVideo.open("../result.mp4", ex, capture.get(CAP_PROP_FPS), S, true); int medianCount = 1; // Счетчик для медианного фильтра const int NUMBER_OF_MEDIAN_VALUES = 4; // Раз во сколько кадров проводим медианный фильтр double valuesForMedianFilterX[NUMBER_OF_MEDIAN_VALUES - 1]; // массив значений координат x, который будет сортироваться для медианного фильтра double valuesForMedianFilterY[NUMBER_OF_MEDIAN_VALUES - 1]; // массив значений координат y, чтобы после медианного фильтра восстановить точку van_point_verticals double medianResult_x = 0; // медианное значение для точки схода double result_x = 0; // координата x точки схода прямых double result_y = 0; // координата y точки схода прямых Point van_point_verticals; // точка схода прямых int frame_counter = 0; while (true) { capture >> src; frame_counter++; // задаем roi, чтобы отсечь неинтересующие прямые int x_roi = src.cols / 4; // где начинается roi int width_roi = src.cols / 2; // получение углов градиента simpleSobel(src, grad_x, grad_y); // кластеризация по углам градиента Mat src_clustering(src.rows, src.cols, src.type(), Scalar(0, 0, 0)); clustering(grad_x, grad_y, src_clustering); // векторизация границ кластеров vectorisation(src_clustering, src_vectorization); // отбираем вертикальные отрезки, преобразовав границы кластеров в отрезки Mat src_polylines(src.rows, src.cols, src.type(), Scalar(255, 255, 255)); makePolylines(src_vectorization, src_polylines, 10, x_roi, width_roi); // выделяем контуры cvtColor(src_polylines, src_polylines, COLOR_BGR2GRAY); Canny(src_polylines, src_polylines, 100, 200); vector< vector<Point> > contours; findContours(src_polylines, contours, RETR_LIST, CHAIN_APPROX_NONE); // получение вектора коэффициентов { k,b } линейных функций x = k * y + b, полученных из линейной регрессии по контурам vector <LinearFunction> linearFunctions = linearRegressionForContours(contours); // получение вектора точек найденных вертикальных прямых vector < tuple<Point, Point> > vertical_lines = findVectorOfPointsOfVerticalLines(linearFunctions); // выделяем прямые по контурам методом Хафа //vector<Vec2f> lines = findLinesHough(src_polylines); // выбор вертикальных прямых //vector < tuple<Point, Point> > vertical_lines = selectionOfVerticalLines(lines); // оставляем прямые, которые вписываются с центральную часть ширины width_roi, которая начинается с x_roi roiForVerticalLines(vertical_lines, x_roi, width_roi); // отрисовка прямых // drawLines(src, vertical_lines); // медианный фильтр if (medianCount % NUMBER_OF_MEDIAN_VALUES == 0) { // Если нужно провести медианный фильтр medianResult_x = medianFilter(valuesForMedianFilterX, NUMBER_OF_MEDIAN_VALUES); // так как медианный фильтр делаем по координатам x, надо координате x сопоставить соответствующий y for (int i = 0; i < NUMBER_OF_MEDIAN_VALUES - 1; i++) { if (valuesForMedianFilterX[i] == medianResult_x) { van_point_verticals.x = medianResult_x; van_point_verticals.y = valuesForMedianFilterY[i]; break; } } } else { //проверяем, что нашлось примерно поровну прямых слева и справа double quantityFactor = 1.5; // if (quantitativeFilter(vertical_lines, src.cols / 2, quantityFactor)) // { // makeSpaceKB(result_x, result_y, vertical_lines); // } makeSpaceKB(result_x, result_y, vertical_lines); valuesForMedianFilterX[medianCount - 1] = result_x; valuesForMedianFilterY[medianCount - 1] = result_y; } // drawVerticalLine(src, van_point_verticals.x); // нахождение линий дорожной разметки vector< tuple<Point, Point> > roadMarkings = findRoadMarkingLines(src); // определение точки пересечения дорожной разметки Point van_point_lane = findVanishingPointLane(roadMarkings); // получение линии горизонта, размеченной вручную tuple<Point, Point> currentHorizonLine = manuallySelectingHorizonLine(src); Point currentHorizon_pt1 = get<0>(currentHorizonLine); Point currentHorizon_pt2 = get<1>(currentHorizonLine); // получение горизонтальной линии tuple<Point, Point> accurateHorizonLine = getAccurateHorizonLine(currentHorizon_pt1.y, src.cols); Point accurateHorizon_pt1 = get<0>(accurateHorizonLine); Point accurateHorizon_pt2 = get<1>(accurateHorizonLine); // получение вертикальное линии tuple<Point, Point> accurateVerticalLine = getAccurateVerticalLine(van_point_lane.x, src.rows); Point accurateVertical_pt1 = get<0>(accurateVerticalLine); Point accurateVertical_pt2 = get<1>(accurateVerticalLine); //line(src, van_point_lane, van_point_verticals, Scalar(255, 0, 0), 1, LINE_AA); line(src, currentHorizon_pt1, currentHorizon_pt2, Scalar(0, 0, 255), 1, LINE_AA); // line(src, accurateVertical_pt1, accurateVertical_pt2, Scalar(255, 0, 0), 1, LINE_AA); // line(src, accurateHorizon_pt1, accurateHorizon_pt2, Scalar(0, 0, 255), 1, LINE_AA); double angle_vertical = angleBetweenStraightLines(van_point_lane, van_point_verticals, accurateVertical_pt1, accurateVertical_pt2); double angle_horizon = angleBetweenStraightLines(currentHorizon_pt1, currentHorizon_pt2, accurateHorizon_pt1, accurateHorizon_pt2); double error_rate = abs(angle_vertical - angle_horizon); if (error_rate < eps) { numberOfSuccessfulFrames++; } if (frame_counter == max_frame_number) { break; } //imshow("src", src); // увеличение счетчика для медианного фильтра if (medianCount % NUMBER_OF_MEDIAN_VALUES == 0) { medianCount = 1; } else { medianCount++; } // outputVideo << src; // сохранение результата в файл // освобождаем память grad_x.release(); grad_y.release(); src_polylines.release(); src_vectorization.release(); src_clustering.release(); src.release(); int k = waitKey(25); if (k == 27) { // освобождаем память capture.release(); break; } } } int main() { const string PATH_test = "../videos/test.AVI"; const string PATH_test2 = "../videos/test2.mp4"; const string PATH_road = "../videos/road.mp4"; const string PATH_road2 = "../videos/road2.mp4"; const string PATH_road3 = "../videos/road3.mp4"; for (int i = 5; i < 15; i++) { int numberOfSuccessfulFrames = 0; double eps = double(i) / 10; int max_frame_number = 500; //selectingLinesUsingHoughMethod(PATH_road3, eps, max_frame_number, numberOfSuccessfulFrames); selectingLinesUsingGradient(PATH_road3, eps, max_frame_number, numberOfSuccessfulFrames); cout << "Epsilon = " << eps << endl; cout << "\t Number of successful frames: " << numberOfSuccessfulFrames << endl; } return 0; }
30.465686
165
0.574026
alechh
62fe1ff258c2dc4f541843a34f65206639a3e010
45
hpp
C++
src/boost_log_expressions_message.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_log_expressions_message.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_log_expressions_message.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/log/expressions/message.hpp>
22.5
44
0.8
miathedev
62fe3593c590a7255760529e008fe587a59f957a
695
cpp
C++
src/regiondump.cpp
saadbruno/MinedMap
fbef307c90a96b39dde1f36f2ebe1f764c18bdd2
[ "BSD-2-Clause" ]
null
null
null
src/regiondump.cpp
saadbruno/MinedMap
fbef307c90a96b39dde1f36f2ebe1f764c18bdd2
[ "BSD-2-Clause" ]
null
null
null
src/regiondump.cpp
saadbruno/MinedMap
fbef307c90a96b39dde1f36f2ebe1f764c18bdd2
[ "BSD-2-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-2-Clause /* Copyright (c) 2018-2021, Matthias Schiffer <mschiffer@universe-factory.net> All rights reserved. */ #include "Buffer.hpp" #include "GZip.hpp" #include "Util.hpp" #include "NBT/Tag.hpp" #include "World/Region.hpp" #include <cstdio> #include <iostream> int main(int argc, char *argv[]) { using namespace MinedMap; if (argc != 2) { std::fprintf(stderr, "Usage: %s <regionfile>\n", argv[0]); return 1; } World::Region::visitChunks(argv[1], [&] (chunk_idx_t X, chunk_idx_t Z, const World::ChunkData *chunk) { std::cout << "Chunk(" << unsigned(X) << ", " << unsigned(Z) << "): " << *chunk->getRoot() << std::endl; }); return 0; }
21.060606
104
0.640288
saadbruno
1a056e69763217dfae0dfd7bcb476993907d25fb
2,982
cpp
C++
src/game/src/states/chooseMap/ChooseMapState.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
6
2021-04-20T10:32:29.000Z
2021-06-05T11:48:56.000Z
src/game/src/states/chooseMap/ChooseMapState.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
1
2021-05-18T21:00:12.000Z
2021-06-02T07:59:03.000Z
src/game/src/states/chooseMap/ChooseMapState.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
3
2020-09-12T08:54:04.000Z
2021-04-17T11:16:36.000Z
#include "ChooseMapState.h" #include <utility> #include "ChooseMapStateUIConfigBuilder.h" #include "TimerFactory.h" namespace game { namespace { const auto buttonColor = graphics::Color(251, 190, 102); const auto buttonHoverColor = graphics::Color(205, 128, 66); } ChooseMapState::ChooseMapState(const std::shared_ptr<window::Window>& windowInit, const std::shared_ptr<graphics::RendererPool>& rendererPoolInit, std::shared_ptr<utils::FileAccess> fileAccessInit, States& statesInit, std::shared_ptr<components::ui::UIManager> uiManagerInit, std::shared_ptr<TileMap> tileMapInit, std::unique_ptr<MapsReader> mapsReader) : State{windowInit, rendererPoolInit, std::move(fileAccessInit), statesInit}, uiManager{std::move(uiManagerInit)}, shouldBackToMenu{false}, tileMap{std::move(tileMapInit)}, mapsReader{std::move(mapsReader)}, mapFilePaths{this->mapsReader->readMapFilePaths()}, mapNames{this->mapsReader->readMapNames()}, paginatedButtonActionForButtonIndex{[&](int index) { const auto& mapPath = mapFilePaths[index]; tileMap->loadFromFile(mapPath); states.deactivateCurrentState(); states.addNextState(StateType::CustomGame); }} { ChooseMapStateUIConfigBuilder uiConfigBuilder; this->uiManager->createUI(uiConfigBuilder.createChooseMapUIConfig(this)); buttonsNavigator = std::make_unique<PaginatedButtonsNavigator>( uiManager, uiConfigBuilder.getNonNavigationButtonNames(), uiConfigBuilder.getIconNames(), mapNames, paginatedButtonActionForButtonIndex, 5, buttonColor, buttonHoverColor, utils::TimerFactory::createTimer(), utils::TimerFactory::createTimer()); buttonsNavigator->initialize(); } NextState ChooseMapState::update(const utils::DeltaTime& deltaTime, const input::Input& input) { if (const auto nextState = buttonsNavigator->update(deltaTime, input); nextState == NextState::Previous) { return NextState::Previous; } if (shouldBackToMenu) { return NextState::Menu; } uiManager->update(deltaTime, input); return NextState::Same; } void ChooseMapState::lateUpdate(const utils::DeltaTime&, const input::Input&) {} void ChooseMapState::render() { rendererPool->renderAll(); } StateType ChooseMapState::getType() const { return StateType::ChooseMap; } void ChooseMapState::activate() { active = true; uiManager->activate(); buttonsNavigator->activate(); } void ChooseMapState::deactivate() { active = false; uiManager->deactivate(); } void ChooseMapState::backToMenu() { shouldBackToMenu = true; } }
31.723404
108
0.64051
walter-strazak
1a07307aaf3a85edf9913efbd7ac10648c89dae5
544
cpp
C++
Components/Tower/Tower.cpp
Nayaco/OpenGLBoilerplate
a53d58c1c413b20ab17e73017fc65133949b7fff
[ "MIT" ]
null
null
null
Components/Tower/Tower.cpp
Nayaco/OpenGLBoilerplate
a53d58c1c413b20ab17e73017fc65133949b7fff
[ "MIT" ]
null
null
null
Components/Tower/Tower.cpp
Nayaco/OpenGLBoilerplate
a53d58c1c413b20ab17e73017fc65133949b7fff
[ "MIT" ]
null
null
null
#include "Tower.hpp" Tower::Tower() :aabbbox(glm::vec3(2.0f, 12.0f, 2.0f)) , model("Resources/Models/LightHouse/lightHouse.obj") { position = glm::vec3(9.5, 1.0, 9.5); center = glm::vec3(10.0, 1.0, 10.0); aabbbox.update(position); } void Tower::draw(Shader const &shader) { glm::mat4 model_matrix(1.0); model_matrix = glm::translate(model_matrix, center); model_matrix = glm::scale(model_matrix, glm::vec3(1.0, 1.0, 1.0) ); shader.use(); shader.setMat4("model", model_matrix); model.draw(shader); }
32
71
0.637868
Nayaco
1a26c5fb866a507b8696c3d428fd6bb9f5129513
22,214
cc
C++
flecsi-sp/burton/test/portage_tangram.cc
losalamos/flecsi-specializations
69c2f964e154d576a142c5c8ee707d050a5fb71d
[ "Unlicense" ]
1
2020-09-01T17:33:38.000Z
2020-09-01T17:33:38.000Z
flecsi-sp/burton/test/portage_tangram.cc
losalamos/flecsi-specializations
69c2f964e154d576a142c5c8ee707d050a5fb71d
[ "Unlicense" ]
31
2017-03-21T01:58:03.000Z
2020-01-23T00:43:32.000Z
flecsi-sp/burton/test/portage_tangram.cc
losalamos/flecsi-specializations
69c2f964e154d576a142c5c8ee707d050a5fb71d
[ "Unlicense" ]
12
2017-01-10T23:41:10.000Z
2022-03-23T20:33:17.000Z
/*~-------------------------------------------------------------------------~~* * Copyright (c) 2016 Los Alamos National Laboratory, LLC * All rights reserved *~-------------------------------------------------------------------------~~*/ //////////////////////////////////////////////////////////////////////////////// // \file // \brief Tests general features of the burton mesh. //////////////////////////////////////////////////////////////////////////////// // user includes #include <cinchtest.h> #include <flecsi/execution/execution.h> #include <flecsi-sp/burton/burton_mesh.h> #include <flecsi-sp/utils/types.h> #include <flecsi-sp/burton/mesh_interface.h> #include <flecsi-sp/burton/portage_helpers.h> // system includes #include <array> #include <cmath> #include <ctime> #include <fstream> #include <functional> #include <iostream> #include <random> #include <sstream> #include <string> // using statements using std::cout; using std::endl; using mesh_t = flecsi_sp::burton::burton_mesh_t; using index_spaces_t = mesh_t::index_spaces_t; using real_t = mesh_t::real_t; using vector_t = mesh_t::vector_t; using entity_kind_t = Portage::Entity_kind; using entity_type_t = Portage::Entity_type; using field_type_t = Portage::Field_type; namespace flecsi_sp { namespace burton { namespace test { template< typename T > real_t prescribed_function( const T & c ) { return 2.0 + c[0]; } //////////////////////////////////////////////////////////////////////////////// // Register the mesh state //////////////////////////////////////////////////////////////////////////////// flecsi_register_field( mesh_t, hydro, density, real_t, sparse, 1, index_spaces_t::cells ); flecsi_register_field( mesh_t, hydro, velocity, vector_t, sparse, 1, index_spaces_t::cells ); flecsi_register_field( mesh_t, hydro, volume_fraction, real_t, sparse, 1, index_spaces_t::cells ); flecsi_register_field( mesh_t, hydro, node_coordinates, mesh_t::vector_t, dense, 1, index_spaces_t::vertices ); /////////////////////////////////////////////////////////////////////////////// //! \brief Tack on an iteration number to a string /////////////////////////////////////////////////////////////////////////////// static auto zero_padded( std::size_t n, std::size_t padding = 6 ) { std::stringstream ss; ss << std::setw( padding ) << std::setfill( '0' ) << n; return ss.str(); } //////////////////////////////////////////////////////////////////////////////// /// \brief output the solution /// \param [in] mesh the mesh object /// \param [in] iteration the iteration count /// \param [in] d the bulk density //////////////////////////////////////////////////////////////////////////////// void output( utils::client_handle_r<mesh_t> mesh, size_t iteration, utils::sparse_handle_r<real_t> d, utils::sparse_handle_r<real_t> vf ) { clog(info) << "OUTPUT MESH TASK" << std::endl; // get the context auto & context = flecsi::execution::context_t::instance(); auto rank = context.color(); auto size = context.colors(); auto time = 0.0; constexpr auto num_dims = mesh_t::num_dimensions; // figure out this ranks file name auto output_filename = "burton.remap_test" + zero_padded(iteration) + "_rank" + zero_padded(rank) + ".vtk"; std::ofstream file(output_filename); file << "# vtk DataFile Version 3.0" << std::endl; file << "Remapping test" << std::endl; file << "ASCII" << std::endl; file << "DATASET UNSTRUCTURED_GRID" << std::endl; file.precision(14); file.setf( std::ios::scientific ); file << "POINTS " << mesh.num_vertices() << " double" << std::endl; for (auto v : mesh.vertices()) { for (int d=0; d<num_dims; d++ ) file << v->coordinates()[d] << " "; for (int d=num_dims; d<3; d++ ) file << 0 << " "; file << std::endl; } size_t vert_cnt = 0; const auto & cells = mesh.cells(); for ( auto c : cells ) vert_cnt += mesh.vertices(c).size() + 1; file << "CELLS " << cells.size() << " " << vert_cnt << std::endl; for ( auto c : cells ) { const auto & vs = mesh.vertices(c); file << vs.size() << " "; for ( auto v : vs ) file << v.id() << " "; file << std::endl; } file << "CELL_TYPES " << cells.size() << std::endl; for ( auto c : cells ) file << "7" << std::endl; file << "CELL_DATA " << cells.size() << std::endl; file << "SCALARS density double 1" << std::endl; file << "LOOKUP_TABLE default" << std::endl; for ( auto c : cells ) { auto bulk = 0.0; for (auto m: d.entries(c)){ // bulk += d(c,m); bulk += d(c,m) * vf(c,m); // file << d(c,m) << std::endl; } file << bulk << std::endl; } file.close(); } //////////////////////////////////////////////////////////////////////////////// /// \brief make a remapper object //////////////////////////////////////////////////////////////////////////////// template< typename mesh_wrapper_a_t, typename tolerances_t > auto make_interface_reconstructor( mesh_wrapper_a_t & mesh_wrapper_a, tolerances_t & tols, bool & all_convex ) { using mesh_wrapper_t = flecsi_sp::burton::portage_mesh_wrapper_t<mesh_t>; constexpr int num_dims = mesh_wrapper_a_t::mesh_t::num_dimensions; static_assert(num_dims != 3 || num_dims !=2 , "make_interface_reconstructor dimensions are out of range"); auto interface_reconstructor = std::make_shared<Tangram::Driver<Tangram::VOF, num_dims, mesh_wrapper_t, Tangram::SplitRnD<num_dims>, Tangram::ClipRnD<num_dims> > >(mesh_wrapper_a, tols, all_convex); return std::move(interface_reconstructor); } //////////////////////////////////////////////////////////////////////////////// /// \brief Test the remap capabilities of portage + tangram /// \param [in] mesh the mesh object /// \param [in] density_handle density field /// \param [in] volfrac_handle material volume fractions in cells /// \param [in] velocity_hanle velocity field /// \param [in] density_mutator /// \param [in] volfrac_mutator /// \param [in] velocity_mutator /// \param [in] coord0 the set of coordinates to be applied //////////////////////////////////////////////////////////////////////////////// void remap_tangram_test( utils::client_handle_r<mesh_t> mesh, utils::sparse_handle_rw<real_t> density_handle, utils::sparse_handle_rw<real_t> volfrac_handle, utils::sparse_handle_rw<vector_t> velocity_handle, utils::sparse_mutator<real_t> density_mutator, utils::sparse_mutator<real_t> volfrac_mutator, utils::sparse_mutator<vector_t> velocity_mutator, utils::dense_handle_r<vector_t> new_vertex_coords ) { using mesh_wrapper_t = flecsi_sp::burton::portage_mesh_wrapper_t<mesh_t>; constexpr auto num_dims = mesh_t::num_dimensions; auto max_mats = volfrac_handle.max_entries(); constexpr auto epsilon = 10*config::test_tolerance; // some mesh parameters const auto & cells = mesh.cells(); const auto & owned_cells = mesh.cells(flecsi::owned); auto num_cells = cells.size(); auto num_owned_cells = owned_cells.size(); // get the context auto & context = flecsi::execution::context_t::instance(); auto comm_rank = context.color(); auto comm_size = context.colors(); //--------------------------------------------------------------------------- // Compute some source and target mesh quantities. // Apply the new coordinates to the mesh and update its geometry. // Here we save some info we need. std::vector< real_t > target_cell_volume(mesh.num_cells()); std::vector< vector_t > target_cell_centroid(mesh.num_cells()); // update coordinates for ( auto v : mesh.vertices() ) std::swap(v->coordinates(), new_vertex_coords(v)); // compute new target mesh quantities for ( auto c: mesh.cells() ) { c->update(&mesh); target_cell_volume[c] = c->volume(); target_cell_centroid[c] = c->centroid(); } // Store the cell volumes for the source mesh std::vector< real_t > source_volume(mesh.num_cells()); // update coordinates back to old mesh for ( auto v : mesh.vertices() ) std::swap(v->coordinates(), new_vertex_coords(v)); // re-compute source mesh quantities for ( auto c: mesh.cells() ) { c->update(&mesh); source_volume[c] = c->volume(); } //--------------------------------------------------------------------------- // Set up portage mesh/data wrappers // Create the mesh wrapper objects portage_mesh_wrapper_t<mesh_t> source_mesh_wrapper(mesh); portage_mesh_wrapper_t<mesh_t> target_mesh_wrapper(mesh); target_mesh_wrapper.set_new_coordinates( &new_vertex_coords(0), target_cell_volume.data(), target_cell_centroid.data() ); // Create the state wrapper objects portage_mm_state_wrapper_t<mesh_t> source_state_wrapper(mesh); portage_mm_state_wrapper_t<mesh_t> target_state_wrapper(mesh); // Compute material/cell offsets std::vector< std::vector< int > > mat_cells(max_mats); std::vector< std::vector< int > > cell_mats(num_cells); std::vector< std::vector< int > > cell_mat_offsets(num_cells); for (size_t m=0; m<max_mats; ++m){ size_t mat_cell_id = 0; for (auto c: velocity_handle.indices(m) ){ mat_cells[m].push_back(c); cell_mats[c].push_back(m); cell_mat_offsets[c].push_back( mat_cell_id ); // bump counters mat_cell_id++; } } // Initialize material offsets and cells in wrappers source_state_wrapper.set_materials(mat_cells, cell_mats, cell_mat_offsets ); // Create a vector of strings that correspond to the names of the variables // that will be remapped static const char coordinate[] = {'x', 'y', 'z'}; std::vector<std::string> var_names; // First, set special internal fields auto volfrac_name = "mat_volfracs"; auto volfrac = source_state_wrapper.template add_cell_field<real_t>( std::string{"mat_volfracs"}, entity_kind_t::CELL, field_type_t::MULTIMATERIAL_FIELD); // now set fields to be reconstructed auto density_name = "density"; auto density = source_state_wrapper.template add_cell_field<real_t>( density_name, entity_kind_t::CELL, field_type_t::MULTIMATERIAL_FIELD); var_names.push_back(density_name); // Populate data to be remapped size_t offset{0}; for (int m=0; m<max_mats; ++m){ for (auto c: velocity_handle.indices(m) ){ volfrac[offset] = volfrac_handle(c,m); offset++; } } // Get the material centroid values via Tangram auto mpi_comm = MPI_COMM_WORLD; Wonton::MPIExecutor_type mpiexecutor(mpi_comm); bool all_convex = false; std::vector<Tangram::IterativeMethodTolerances_t> tols(2,{1000, 1e-15, 1e-15}); auto source_interface_reconstructor = make_interface_reconstructor(source_mesh_wrapper, tols, all_convex); // Create the mat centroid list auto centroid_list = source_state_wrapper.build_centroids(source_mesh_wrapper, source_interface_reconstructor, &mpiexecutor); // Hand-off mat centroid list to matcentroid pointer object offset = 0; for (int m=0; m<max_mats; ++m){ auto mat_index = 0; for (auto c: velocity_handle.indices(m) ){ density[offset] = prescribed_function( centroid_list[m][mat_index] ); offset++; mat_index++; } } // Make the remapper with source mesh/state - redistribution does // not apply to swept face remap auto remapper = make_remapper<num_dims>( source_mesh_wrapper, source_state_wrapper, target_mesh_wrapper, target_state_wrapper); // Do the remap compute_weights_intersect(remapper); constexpr auto RealMin = std::numeric_limits<double>::min(); constexpr auto RealMax = std::numeric_limits<double>::max(); for (const auto & var : var_names) { remapper.template interpolate< real_t, Portage::Entity_kind::CELL, Portage::Interpolate_2ndOrder >( var, var, RealMin, RealMax, Portage::Limiter_type::NOLIMITER, Portage::Boundary_Limiter_type::BND_NOLIMITER); } //--------------------------------------------------------------------------- // Swap old for new data // Checking conservation for remap test real_t total_density{0}; real_t total_volume{0}; // Calculate totals for old data for (auto c: mesh.cells(flecsi::owned)) { for ( auto m : velocity_handle.entries(c) ) { total_density += c->volume() * volfrac_mutator(c,m) * density_handle(c,m); total_volume += c->volume() * volfrac_mutator(c,m); } } // Swap old data for new data for (int mat_num=0; mat_num < max_mats; ++mat_num){ real_t const * remap_density; real_t const * remap_volfracs; target_state_wrapper.mat_get_celldata( "density", mat_num, &remap_density ); target_state_wrapper.mat_get_celldata( "mat_volfracs", mat_num, &remap_volfracs ); auto & these_mat_cells = mat_cells[mat_num]; these_mat_cells.clear(); target_state_wrapper.mat_get_cells(mat_num, &these_mat_cells); size_t count{0}; for ( auto c : these_mat_cells ) { density_mutator(c, mat_num) = remap_density[count]; volfrac_mutator(c, mat_num) = remap_volfracs[count]; count++; } } // Apply the new coordinates to the mesh and update its geometry for ( auto v : mesh.vertices() ) v->coordinates() = new_vertex_coords(v); mesh.update_geometry(); //--------------------------------------------------------------------------- // Post process // Check conservation for remap test real_t total_remap_density{0}; // Calculate the L1 and L2 norms real_t total_vol = 0.0; real_t L1 = 0.0; real_t L2 = 0.0; std::vector<double> vfrac_sum(num_cells, 0.0); std::vector<real_t> actual(num_cells, 0.0); for (int mat_num=0; mat_num < max_mats; ++mat_num){ for (auto element: mat_cells[mat_num]){ auto c = cells[element]; total_vol += c->volume() * volfrac_mutator(c,mat_num); actual[c.id()] += volfrac_mutator(c,mat_num) * density_mutator(c,mat_num); total_remap_density += c->volume() * volfrac_mutator(c,mat_num) * density_mutator(c,mat_num); vfrac_sum[c.id()] += volfrac_mutator(c,mat_num); } } for (auto c: mesh.cells(flecsi::owned)){ EXPECT_NEAR( vfrac_sum[c], 1.0, epsilon ); auto expected = prescribed_function( c->centroid() ); // L1,L2 errors auto each_error = std::abs(actual[c.id()] - expected); L1 += c->volume() * each_error; // L1 L2 += c->volume() * std::pow(each_error, 2); // L2 } // output L1, L2 errors for debug real_t total_vol_sum{0}, L1_sum{0}, L2_sum{0}; int ret; ret = MPI_Allreduce( &total_vol, &total_vol_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_comm); ret = MPI_Allreduce( &L1, &L1_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_comm); ret = MPI_Allreduce( &L2, &L2_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_comm); L1_sum = L1_sum/total_vol_sum; // L1 L2_sum = pow(L2_sum/total_vol_sum, 0.5); // L2 if ( comm_rank == 0 ) { printf("L1 Norm: %14.7e, Total Volume: %f \n", L1_sum, total_vol_sum); printf("L2 Norm: %14.7e, Total Volume: %f \n", L2_sum, total_vol_sum); EXPECT_NEAR(L1_sum, 0.0, epsilon); EXPECT_NEAR(L2_sum, 0.0, epsilon); EXPECT_NEAR( total_vol_sum, 1.0, epsilon ); } // Verify conservation real_t total_density_sum{0}, total_remap_density_sum{0}; ret = MPI_Allreduce( &total_density, &total_density_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_comm); ret = MPI_Allreduce( &total_remap_density, &total_remap_density_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_comm); EXPECT_NEAR( total_density_sum, total_remap_density_sum, epsilon); } //////////////////////////////////////////////////////////////////////////////// /// \brief Test the remap capabilities of portage /// \param [in] mesh the mesh object /// \param [in] mat_state a densely populated set of data //////////////////////////////////////////////////////////////////////////////// void initialize( utils::client_handle_r<mesh_t> mesh, utils::sparse_mutator<real_t> density, utils::sparse_mutator<real_t> vol_frac, utils::sparse_mutator<vector_t> velocity ) { for (auto c: mesh.cells(flecsi::owned)){ c->update(&mesh); const auto & centroid = c->centroid(); auto func = prescribed_function( centroid ); std::vector<int> mats; // MM initalization if (centroid[0] < -0.21875) mats.push_back(0); if (centroid[0] > -0.25) mats.push_back(1); // Single material initialization // if (centroid[0] < -0.25) mats.push_back(0); // if (centroid[0] > -0.25) mats.push_back(1); for ( auto m : mats ) { vol_frac(c,m) = static_cast<real_t>(1) / mats.size(); density(c,m) = func; velocity(c,m) = func; } } } //////////////////////////////////////////////////////////////////////////////// //! \brief modify the coordinates & solution //! //! \param [in] mesh the mesh object //! \param [out] coord0 storage for the mesh coordinates //////////////////////////////////////////////////////////////////////////////// void modify( utils::client_handle_r<mesh_t> mesh, utils::dense_handle_w<vector_t> coord ) { constexpr auto num_dims = mesh_t::num_dimensions; // Loop over vertices const auto & vs = mesh.vertices(); auto num_verts = vs.size(); std::mt19937 mt_rand(0); auto real_rand = std::bind( std::uniform_real_distribution<double>(0, 0.2), mt_rand); //Randomly modifies each of the vertices such that // no vertex moves by more than 40% of the spacing // in any direction. These vertices are then used // for the new mesh. double spacing = 1/std::pow(num_verts, 0.5); for (auto v : vs ) { auto vertex = v->coordinates(); for ( int j=0; j < num_dims; j++) { if ( vertex[j] < 0.5 && vertex[j] > 0) { auto perturbation = spacing * real_rand(); //perturbation = 0; vertex[j] -= perturbation; } else if (vertex[j] <= 0 && vertex[j]> -0.5) { auto perturbation = spacing * real_rand(); //perturbation = 0; vertex[j] += perturbation; } } coord(v) = vertex; } } //////////////////////////////////////////////////////////////////////////////// //! \brief restore the coordinates //! //! \param [in,out] mesh the mesh object //! \param [in] coord0 the mesh coordinates to restore //////////////////////////////////////////////////////////////////////////////// void restore( utils::client_handle_r<mesh_t> mesh, utils::dense_handle_r<vector_t> coord ) { // Loop over vertices auto vs = mesh.vertices(); auto num_verts = vs.size(); for ( mesh_t::counter_t i=0; i<num_verts; i++ ) { auto vt = vs[i]; vt->coordinates() = coord(vt); } }// TEST_F flecsi_register_mpi_task(remap_tangram_test, flecsi_sp::burton::test); flecsi_register_task(output, flecsi_sp::burton::test, loc, index|flecsi::leaf); // Different Initialization Tasks flecsi_register_task(initialize, flecsi_sp::burton::test, loc, index|flecsi::leaf); flecsi_register_task(restore, flecsi_sp::burton::test, loc, index|flecsi::leaf); flecsi_register_task(modify, flecsi_sp::burton::test, loc, index|flecsi::leaf); } // namespace } // namespace } // namespace namespace flecsi { namespace execution { //////////////////////////////////////////////////////////////////////////////// //! \brief the driver for all tests //////////////////////////////////////////////////////////////////////////////// void driver(int argc, char ** argv) { // get the mesh handle auto mesh_handle = flecsi_get_client_handle(mesh_t, meshes, mesh0); auto num_materials = 2; size_t time_cnt{0}; auto xn = flecsi_get_handle(mesh_handle, hydro, node_coordinates, vector_t, dense, 0); auto density_handle = flecsi_get_handle(mesh_handle, hydro, density, real_t, sparse, 0); auto volfrac_handle = flecsi_get_handle(mesh_handle, hydro, volume_fraction, real_t, sparse, 0); auto velocity_handle = flecsi_get_handle(mesh_handle, hydro, velocity, vector_t, sparse, 0); auto density_mutator = flecsi_get_mutator(mesh_handle, hydro, density, real_t, sparse, 0, num_materials); auto volfrac_mutator = flecsi_get_mutator(mesh_handle, hydro, volume_fraction, real_t, sparse, 0, num_materials); auto velocity_mutator = flecsi_get_mutator(mesh_handle, hydro, velocity, vector_t, sparse, 0, num_materials); flecsi_execute_task( initialize, flecsi_sp::burton::test, index, mesh_handle, density_mutator, volfrac_mutator, velocity_mutator); time_cnt++; flecsi_execute_task( output, flecsi_sp::burton::test, index, mesh_handle, time_cnt, density_handle, volfrac_handle); flecsi_execute_task( modify, flecsi_sp::burton::test, index, mesh_handle, xn); #if 1 std::cout << "Swept-face based remap..." << std::endl; flecsi_execute_mpi_task( remap_tangram_test, flecsi_sp::burton::test, mesh_handle, density_handle, volfrac_handle, velocity_handle, density_mutator, volfrac_mutator, velocity_mutator, xn); #else flecsi_execute_task( restore, flecsi_sp::burton::test, index, mesh_handle, xn); #endif time_cnt++; flecsi_execute_task( output, flecsi_sp::burton::test, index, mesh_handle, time_cnt, density_handle, volfrac_handle); } // driver } // namespace execution } // namespace flecsi //////////////////////////////////////////////////////////////////////////////// //! \brief Only here so test runs? //////////////////////////////////////////////////////////////////////////////// TEST(burton, portage) {}
32.008646
119
0.591159
losalamos
1a291ad4eb8c9e22e9f3840466bf734d83d9679b
1,188
cpp
C++
YASS/Particle.cpp
Marrow16180/YASS
8a27bc7f07f0b65b847b0be0a2683e650895a33a
[ "MIT" ]
null
null
null
YASS/Particle.cpp
Marrow16180/YASS
8a27bc7f07f0b65b847b0be0a2683e650895a33a
[ "MIT" ]
null
null
null
YASS/Particle.cpp
Marrow16180/YASS
8a27bc7f07f0b65b847b0be0a2683e650895a33a
[ "MIT" ]
null
null
null
#include "Particle.hpp" Particle::Particle() { // TODO: check whether this can be empty... } Particle::Particle ( const sf::Texture * texture, float rotation, sf::Vector2f position, sf::Vector2f scale, sf::Time lifetime, sf::Color color ) : sprite{*texture} , initialLifetime{lifetime} , lifetime{lifetime} { centerOrigin(sprite); sprite.setRotation(rotation); sprite.setPosition(position); sprite.setScale(scale); sprite.setColor(color); } void Particle::reconstruct(const sf::Texture * texture, float rotation, sf::Vector2f position, sf::Vector2f scale, sf::Time lifetime, sf::Color color) { sprite.setTexture(*texture); initialLifetime = lifetime; this->lifetime = lifetime; centerOrigin(sprite); sprite.setRotation(rotation); sprite.setPosition(position); sprite.setScale(scale); sprite.setColor(color); } bool Particle::alive() const { return lifetime > sf::Time::Zero; } void Particle::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(sprite, states); } void Particle::update(sf::Time dt) { lifetime -= dt; sprite.move(direction * linearVelocity * dt.asSeconds()); sprite.rotate(angularVelocity * dt.asSeconds()); }
21.214286
150
0.728956
Marrow16180
1a330adf76189bc21b7a9d5c2600209399904530
1,434
cpp
C++
test-namedecl.cpp
erdavila/typedecl
e3aaf4b6f0a44d0791d96a86049fd517e88ad428
[ "MIT" ]
1
2016-09-07T01:44:51.000Z
2016-09-07T01:44:51.000Z
test-namedecl.cpp
erdavila/typedecl
e3aaf4b6f0a44d0791d96a86049fd517e88ad428
[ "MIT" ]
null
null
null
test-namedecl.cpp
erdavila/typedecl
e3aaf4b6f0a44d0791d96a86049fd517e88ad428
[ "MIT" ]
null
null
null
#include <cassert> #include "typedecl.hpp" struct C {}; DEFINE_TYPEDECL(C); void testNameDecl() { assert(namedecl<int>("name") == "int name"); assert(namedecl<const int>("name") == "const int name"); assert(namedecl<int&>("name") == "int& name"); assert(namedecl<int[3]>("name") == "int name[3]"); assert(namedecl<int(*)[3][4]>("name") == "int(* name)[3][4]"); assert(namedecl<int**volatile(*)[]>("name") == "int**volatile(* name)[]"); assert(namedecl<int(*(&&)[4])[5]>("name") == "int(*(&& name)[4])[5]"); assert(namedecl<int(char)>("name") == "int name(char)"); assert(namedecl<void(*)()>("name") == "void(* name)()"); assert(namedecl<int(&&)(int)>("name") == "int(&& name)(int)"); assert(namedecl<int(char, ...)>("name") == "int name(char, ...)"); assert(namedecl<void(*)(...)>("name") == "void(* name)(...)"); assert(namedecl<int&(&&)(int, ...)>("name") == "int&(&& name)(int, ...)"); assert(namedecl<void() const volatile>("name") == "void name() const volatile"); assert(namedecl<void() &>("name") == "void name() &"); assert(namedecl<void() const &>("name") == "void name() const &"); assert(namedecl<C>("name") == "C name"); assert(namedecl<char C::*>("name") == "char C::* name"); assert(namedecl<int(C::*)(char)>("name") == "int(C::* name)(char)"); assert(namedecl<char(C::*)[4]>("name") == "char(C::* name)[4]"); assert(namedecl<bool(std::nullptr_t)>("is_null") == "bool is_null(std::nullptr_t)"); }
47.8
85
0.569735
erdavila
1a3d23bd2bdc663ba141191f2d9d746c2f24f625
365
cpp
C++
JsonBoolean.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
JsonBoolean.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
JsonBoolean.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
// // JsonBoolean.cpp // JSON // // Created by Iulian on 13.03.2013. // #include "JsonBoolean.hpp" JsonBoolean::JsonBoolean(bool vBool):JsonBase(),lBool(vBool){ lType=JsonType::Boolean; } JsonBoolean::~JsonBoolean(){ } JsonStream & operator <<(JsonStream & lout, const JsonBoolean &lin){ lout<<(lin.lBool ? "true" : "false"); return lout; }
17.380952
68
0.649315
JCodeARM
1a444d8bc7c68d50ac46033c3c526dcd36e33976
18,882
hpp
C++
include/codegen/include/System/NumberFormatter.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/NumberFormatter.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/NumberFormatter.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Decimal struct Decimal; // Forward declaring type: IFormatProvider class IFormatProvider; } // Forward declaring namespace: System::Globalization namespace System::Globalization { // Forward declaring type: NumberFormatInfo class NumberFormatInfo; // Forward declaring type: CultureInfo class CultureInfo; } // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: Thread class Thread; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: System namespace System { // Autogenerated type: System.NumberFormatter class NumberFormatter : public ::Il2CppObject { public: // Nested type: System::NumberFormatter::CustomInfo class CustomInfo; // private System.Globalization.NumberFormatInfo _nfi // Offset: 0x10 System::Globalization::NumberFormatInfo* nfi; // private System.Char[] _cbuf // Offset: 0x18 ::Array<::Il2CppChar>* cbuf; // private System.Boolean _NaN // Offset: 0x20 bool NaN; // private System.Boolean _infinity // Offset: 0x21 bool infinity; // private System.Boolean _isCustomFormat // Offset: 0x22 bool isCustomFormat; // private System.Boolean _specifierIsUpper // Offset: 0x23 bool specifierIsUpper; // private System.Boolean _positive // Offset: 0x24 bool positive; // private System.Char _specifier // Offset: 0x26 ::Il2CppChar specifier; // private System.Int32 _precision // Offset: 0x28 int precision; // private System.Int32 _defPrecision // Offset: 0x2C int defPrecision; // private System.Int32 _digitsLen // Offset: 0x30 int digitsLen; // private System.Int32 _offset // Offset: 0x34 int offset; // private System.Int32 _decPointPos // Offset: 0x38 int decPointPos; // private System.UInt32 _val1 // Offset: 0x3C uint val1; // private System.UInt32 _val2 // Offset: 0x40 uint val2; // private System.UInt32 _val3 // Offset: 0x44 uint val3; // private System.UInt32 _val4 // Offset: 0x48 uint val4; // private System.Int32 _ind // Offset: 0x4C int ind; // Get static field: static private readonly System.UInt64* MantissaBitsTable static uint64_t* _get_MantissaBitsTable(); // Set static field: static private readonly System.UInt64* MantissaBitsTable static void _set_MantissaBitsTable(uint64_t* value); // Get static field: static private readonly System.Int32* TensExponentTable static int* _get_TensExponentTable(); // Set static field: static private readonly System.Int32* TensExponentTable static void _set_TensExponentTable(int* value); // Get static field: static private readonly System.Char* DigitLowerTable static ::Il2CppChar* _get_DigitLowerTable(); // Set static field: static private readonly System.Char* DigitLowerTable static void _set_DigitLowerTable(::Il2CppChar* value); // Get static field: static private readonly System.Char* DigitUpperTable static ::Il2CppChar* _get_DigitUpperTable(); // Set static field: static private readonly System.Char* DigitUpperTable static void _set_DigitUpperTable(::Il2CppChar* value); // Get static field: static private readonly System.Int64* TenPowersList static int64_t* _get_TenPowersList(); // Set static field: static private readonly System.Int64* TenPowersList static void _set_TenPowersList(int64_t* value); // Get static field: static private readonly System.Int32* DecHexDigits static int* _get_DecHexDigits(); // Set static field: static private readonly System.Int32* DecHexDigits static void _set_DecHexDigits(int* value); // Get static field: static private System.NumberFormatter threadNumberFormatter static System::NumberFormatter* _get_threadNumberFormatter(); // Set static field: static private System.NumberFormatter threadNumberFormatter static void _set_threadNumberFormatter(System::NumberFormatter* value); // Get static field: static private System.NumberFormatter userFormatProvider static System::NumberFormatter* _get_userFormatProvider(); // Set static field: static private System.NumberFormatter userFormatProvider static void _set_userFormatProvider(System::NumberFormatter* value); // static private System.Void GetFormatterTables(System.UInt64* MantissaBitsTable, System.Int32* TensExponentTable, System.Char* DigitLowerTable, System.Char* DigitUpperTable, System.Int64* TenPowersList, System.Int32* DecHexDigits) // Offset: 0x135D7DC static void GetFormatterTables(uint64_t*& MantissaBitsTable, int*& TensExponentTable, ::Il2CppChar*& DigitLowerTable, ::Il2CppChar*& DigitUpperTable, int64_t*& TenPowersList, int*& DecHexDigits); // static private System.Void .cctor() // Offset: 0x135D7E0 static void _cctor(); // static private System.Int64 GetTenPowerOf(System.Int32 i) // Offset: 0x135D840 static int64_t GetTenPowerOf(int i); // private System.Void InitDecHexDigits(System.UInt32 value) // Offset: 0x135D8B0 void InitDecHexDigits(uint value); // private System.Void InitDecHexDigits(System.UInt64 value) // Offset: 0x135DB0C void InitDecHexDigits(uint64_t value); // private System.Void InitDecHexDigits(System.UInt32 hi, System.UInt64 lo) // Offset: 0x135DC30 void InitDecHexDigits(uint hi, uint64_t lo); // static private System.UInt32 FastToDecHex(System.Int32 val) // Offset: 0x135D978 static uint FastToDecHex(int val); // static private System.UInt32 ToDecHex(System.Int32 val) // Offset: 0x135DA48 static uint ToDecHex(int val); // static private System.Int32 FastDecHexLen(System.Int32 val) // Offset: 0x135DDFC static int FastDecHexLen(int val); // static private System.Int32 DecHexLen(System.UInt32 val) // Offset: 0x135DE24 static int DecHexLen(uint val); // private System.Int32 DecHexLen() // Offset: 0x135DEEC int DecHexLen(); // static private System.Int32 ScaleOrder(System.Int64 hi) // Offset: 0x135E010 static int ScaleOrder(int64_t hi); // private System.Int32 InitialFloatingPrecision() // Offset: 0x135E0A4 int InitialFloatingPrecision(); // static private System.Int32 ParsePrecision(System.String format) // Offset: 0x135E180 static int ParsePrecision(::Il2CppString* format); // private System.Void .ctor(System.Threading.Thread current) // Offset: 0x135E21C static NumberFormatter* New_ctor(System::Threading::Thread* current); // private System.Void Init(System.String format) // Offset: 0x135E328 void Init(::Il2CppString* format); // private System.Void InitHex(System.UInt64 value) // Offset: 0x135E450 void InitHex(uint64_t value); // private System.Void Init(System.String format, System.Int32 value, System.Int32 defPrecision) // Offset: 0x135E498 void Init(::Il2CppString* format, int value, int defPrecision); // private System.Void Init(System.String format, System.UInt32 value, System.Int32 defPrecision) // Offset: 0x135E53C void Init(::Il2CppString* format, uint value, int defPrecision); // private System.Void Init(System.String format, System.Int64 value) // Offset: 0x135E5C4 void Init(::Il2CppString* format, int64_t value); // private System.Void Init(System.String format, System.UInt64 value) // Offset: 0x135E650 void Init(::Il2CppString* format, uint64_t value); // private System.Void Init(System.String format, System.Double value, System.Int32 defPrecision) // Offset: 0x135E6D4 void Init(::Il2CppString* format, double value, int defPrecision); // private System.Void Init(System.String format, System.Decimal value) // Offset: 0x135EADC void Init(::Il2CppString* format, System::Decimal value); // private System.Void ResetCharBuf(System.Int32 size) // Offset: 0x135EC50 void ResetCharBuf(int size); // private System.Void Resize(System.Int32 len) // Offset: 0x135ECE8 void Resize(int len); // private System.Void Append(System.Char c) // Offset: 0x135ED48 void Append(::Il2CppChar c); // private System.Void Append(System.Char c, System.Int32 cnt) // Offset: 0x135EDCC void Append(::Il2CppChar c, int cnt); // private System.Void Append(System.String s) // Offset: 0x135EE70 void Append(::Il2CppString* s); // private System.Globalization.NumberFormatInfo GetNumberFormatInstance(System.IFormatProvider fp) // Offset: 0x135EF30 System::Globalization::NumberFormatInfo* GetNumberFormatInstance(System::IFormatProvider* fp); // private System.Void set_CurrentCulture(System.Globalization.CultureInfo value) // Offset: 0x135E2CC void set_CurrentCulture(System::Globalization::CultureInfo* value); // private System.Int32 get_IntegerDigits() // Offset: 0x135EF4C int get_IntegerDigits(); // private System.Int32 get_DecimalDigits() // Offset: 0x135EF5C int get_DecimalDigits(); // private System.Boolean get_IsFloatingSource() // Offset: 0x135EF70 bool get_IsFloatingSource(); // private System.Boolean get_IsZero() // Offset: 0x135EF84 bool get_IsZero(); // private System.Boolean get_IsZeroInteger() // Offset: 0x135EF94 bool get_IsZeroInteger(); // private System.Void RoundPos(System.Int32 pos) // Offset: 0x135EFB4 void RoundPos(int pos); // private System.Boolean RoundDecimal(System.Int32 decimals) // Offset: 0x135F12C bool RoundDecimal(int decimals); // private System.Boolean RoundBits(System.Int32 shift) // Offset: 0x135EFC0 bool RoundBits(int shift); // private System.Void RemoveTrailingZeros() // Offset: 0x135F274 void RemoveTrailingZeros(); // private System.Void AddOneToDecHex() // Offset: 0x135F140 void AddOneToDecHex(); // static private System.UInt32 AddOneToDecHex(System.UInt32 val) // Offset: 0x135F2B8 static uint AddOneToDecHex(uint val); // private System.Int32 CountTrailingZeros() // Offset: 0x135E9B8 int CountTrailingZeros(); // static private System.Int32 CountTrailingZeros(System.UInt32 val) // Offset: 0x135F360 static int CountTrailingZeros(uint val); // static private System.NumberFormatter GetInstance(System.IFormatProvider fp) // Offset: 0x135F3B4 static System::NumberFormatter* GetInstance(System::IFormatProvider* fp); // private System.Void Release() // Offset: 0x135F518 void Release(); // static public System.String NumberToString(System.String format, System.UInt32 value, System.IFormatProvider fp) // Offset: 0x135F5C0 static ::Il2CppString* NumberToString(::Il2CppString* format, uint value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.Int32 value, System.IFormatProvider fp) // Offset: 0x135F85C static ::Il2CppString* NumberToString(::Il2CppString* format, int value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.UInt64 value, System.IFormatProvider fp) // Offset: 0x135F910 static ::Il2CppString* NumberToString(::Il2CppString* format, uint64_t value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.Int64 value, System.IFormatProvider fp) // Offset: 0x135F9C0 static ::Il2CppString* NumberToString(::Il2CppString* format, int64_t value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.Single value, System.IFormatProvider fp) // Offset: 0x135FA70 static ::Il2CppString* NumberToString(::Il2CppString* format, float value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.Double value, System.IFormatProvider fp) // Offset: 0x135FDCC static ::Il2CppString* NumberToString(::Il2CppString* format, double value, System::IFormatProvider* fp); // static public System.String NumberToString(System.String format, System.Decimal value, System.IFormatProvider fp) // Offset: 0x135FFF8 static ::Il2CppString* NumberToString(::Il2CppString* format, System::Decimal value, System::IFormatProvider* fp); // private System.String IntegerToString(System.String format, System.IFormatProvider fp) // Offset: 0x135F674 ::Il2CppString* IntegerToString(::Il2CppString* format, System::IFormatProvider* fp); // private System.String NumberToString(System.String format, System.Globalization.NumberFormatInfo nfi) // Offset: 0x135FC2C ::Il2CppString* NumberToString(::Il2CppString* format, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatCurrency(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x13600D0 ::Il2CppString* FormatCurrency(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatDecimal(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x1360338 ::Il2CppString* FormatDecimal(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatHexadecimal(System.Int32 precision) // Offset: 0x1360968 ::Il2CppString* FormatHexadecimal(int precision); // private System.String FormatFixedPoint(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x1360454 ::Il2CppString* FormatFixedPoint(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatRoundtrip(System.Double origval, System.Globalization.NumberFormatInfo nfi) // Offset: 0x135FEF4 ::Il2CppString* FormatRoundtrip(double origval, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatRoundtrip(System.Single origval, System.Globalization.NumberFormatInfo nfi) // Offset: 0x135FB98 ::Il2CppString* FormatRoundtrip(float origval, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatGeneral(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x136053C ::Il2CppString* FormatGeneral(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatNumber(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x136068C ::Il2CppString* FormatNumber(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatPercent(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x1360800 ::Il2CppString* FormatPercent(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatExponential(System.Int32 precision, System.Globalization.NumberFormatInfo nfi) // Offset: 0x1360400 ::Il2CppString* FormatExponential(int precision, System::Globalization::NumberFormatInfo* nfi); // private System.String FormatExponential(System.Int32 precision, System.Globalization.NumberFormatInfo nfi, System.Int32 expDigits) // Offset: 0x13615A4 ::Il2CppString* FormatExponential(int precision, System::Globalization::NumberFormatInfo* nfi, int expDigits); // private System.String FormatCustom(System.String format, System.Globalization.NumberFormatInfo nfi) // Offset: 0x1360AD0 ::Il2CppString* FormatCustom(::Il2CppString* format, System::Globalization::NumberFormatInfo* nfi); // static private System.Void ZeroTrimEnd(System.Text.StringBuilder sb, System.Boolean canEmpty) // Offset: 0x1362308 static void ZeroTrimEnd(System::Text::StringBuilder* sb, bool canEmpty); // static private System.Boolean IsZeroOnly(System.Text.StringBuilder sb) // Offset: 0x1362218 static bool IsZeroOnly(System::Text::StringBuilder* sb); // static private System.Void AppendNonNegativeNumber(System.Text.StringBuilder sb, System.Int32 v) // Offset: 0x136206C static void AppendNonNegativeNumber(System::Text::StringBuilder* sb, int v); // private System.Void AppendIntegerString(System.Int32 minLength, System.Text.StringBuilder sb) // Offset: 0x1362174 void AppendIntegerString(int minLength, System::Text::StringBuilder* sb); // private System.Void AppendIntegerString(System.Int32 minLength) // Offset: 0x13614D4 void AppendIntegerString(int minLength); // private System.Void AppendDecimalString(System.Int32 precision, System.Text.StringBuilder sb) // Offset: 0x13621F8 void AppendDecimalString(int precision, System::Text::StringBuilder* sb); // private System.Void AppendDecimalString(System.Int32 precision) // Offset: 0x1361248 void AppendDecimalString(int precision); // private System.Void AppendIntegerStringWithGroupSeparator(System.Int32[] groups, System.String groupSeparator) // Offset: 0x1361000 void AppendIntegerStringWithGroupSeparator(::Array<int>* groups, ::Il2CppString* groupSeparator); // private System.Void AppendExponent(System.Globalization.NumberFormatInfo nfi, System.Int32 exponent, System.Int32 minDigits) // Offset: 0x1361770 void AppendExponent(System::Globalization::NumberFormatInfo* nfi, int exponent, int minDigits); // private System.Void AppendOneDigit(System.Int32 start) // Offset: 0x1361694 void AppendOneDigit(int start); // private System.Void AppendDigits(System.Int32 start, System.Int32 end) // Offset: 0x1361260 void AppendDigits(int start, int end); // private System.Void AppendDigits(System.Int32 start, System.Int32 end, System.Text.StringBuilder sb) // Offset: 0x1362B44 void AppendDigits(int start, int end, System::Text::StringBuilder* sb); // private System.Void Multiply10(System.Int32 count) // Offset: 0x1361674 void Multiply10(int count); // private System.Void Divide10(System.Int32 count) // Offset: 0x136204C void Divide10(int count); // private System.NumberFormatter GetClone() // Offset: 0x136153C System::NumberFormatter* GetClone(); }; // System.NumberFormatter } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::NumberFormatter*, "System", "NumberFormatter"); #pragma pack(pop)
50.218085
236
0.738004
Futuremappermydud
1a550c081d7f1d05ab4680274e01ebdd688f4f3d
7,734
hpp
C++
include/QvPlugin/PluginInterface.hpp
Shadowsocks-NET/QvPlugin-Interface
b767b4ceb48b29c739ba6b09db7c46dc2b9c2dff
[ "MIT" ]
null
null
null
include/QvPlugin/PluginInterface.hpp
Shadowsocks-NET/QvPlugin-Interface
b767b4ceb48b29c739ba6b09db7c46dc2b9c2dff
[ "MIT" ]
null
null
null
include/QvPlugin/PluginInterface.hpp
Shadowsocks-NET/QvPlugin-Interface
b767b4ceb48b29c739ba6b09db7c46dc2b9c2dff
[ "MIT" ]
2
2021-11-23T03:16:22.000Z
2021-11-23T03:17:47.000Z
#pragma once #include "QvPlugin/Common/QvPluginBase.hpp" #include "QvPlugin/Connections/ConnectionsBase.hpp" #include "QvPlugin/Handlers/EventHandler.hpp" #include "QvPlugin/Handlers/IProfilePreprocessor.hpp" #include "QvPlugin/Handlers/KernelHandler.hpp" #include "QvPlugin/Handlers/LatencyTestHandler.hpp" #include "QvPlugin/Handlers/OutboundHandler.hpp" #include "QvPlugin/Handlers/SubscriptionHandler.hpp" #include "QvPlugin/Utils/INetworkRequestHelper.hpp" #include <QDir> namespace Qv2rayBase::Plugin { class PluginManagerCore; } // namespace Qv2rayBase::Plugin #define Qv2rayInterface_IID "com.github.Qv2ray.Qv2rayPluginInterface" namespace Qv2rayPlugin { using namespace Qv2rayPlugin::Outbound; using namespace Qv2rayPlugin::Kernel; using namespace Qv2rayPlugin::Event; using namespace Qv2rayPlugin::Subscription; using namespace Qv2rayPlugin::Latency; template<typename> class Qv2rayInterface; namespace Gui { class Qv2rayGUIInterface; } /// /// \brief The Qv2rayInterfaceImpl class is the main entry for every Qv2ray plugins. /// class Qv2rayInterfaceImpl { friend class Qv2rayBase::Plugin::PluginManagerCore; template<typename> friend class Qv2rayPlugin::Qv2rayInterface; public: /// \internal const int QvPluginInterfaceVersion = QV2RAY_PLUGIN_INTERFACE_VERSION; virtual ~Qv2rayInterfaceImpl() = default; /// /// \brief GetMetadata gets metadata of a plugin /// \return A QvPluginMetadata structure containing plugin information /// virtual const QvPluginMetadata GetMetadata() const = 0; /// /// \brief InitializePlugin should be reimplemented by the plugin writer, this is called only once when /// a plugin is found and loaded after a checking for interface version. /// A plugin should initialize its outboundHandler, eventHandler, kernelInterface, subscriptionInterface accordingly. /// In case of a GUI plugin, the guiInterface should also be initialized. /// \return a boolean value indicating if the initialization succeeds. /// virtual bool InitializePlugin() = 0; virtual std::shared_ptr<Qv2rayPlugin::Outbound::IOutboundProcessor> OutboundHandler() const final { return m_OutboundHandler; } virtual std::shared_ptr<Qv2rayPlugin::Event::IEventHandler> EventHandler() const final { return m_EventHandler; } virtual std::shared_ptr<Qv2rayPlugin::Kernel::IKernelHandler> KernelInterface() const final { return m_KernelInterface; } virtual std::shared_ptr<Qv2rayPlugin::Subscription::IPluginSubscriptionInterface> SubscriptionAdapter() const final { return m_SubscriptionInterface; } virtual std::shared_ptr<Qv2rayPlugin::Latency::ILatencyHandler> LatencyTestHandler() const final { return m_LatencyTestHandler; } virtual std::shared_ptr<Qv2rayPlugin::Profile::IProfilePreprocessor> ProfilePreprocessor() const final { return m_ProfilePreprocessor; } virtual Gui::Qv2rayGUIInterface *GetGUIInterface() const final { return m_GUIInterface; } virtual QJsonObject GetSettings() const final { return m_Settings; } virtual QJsonValue GetHostContext(const QString &key) const final { return m_PluginHostContext.value(key); } /// /// \brief A signal that'll be connected to Qv2ray to provide logging function /// virtual void PluginLog(QString) = 0; /// /// \brief PluginErrorMessageBox shows an error messagebox to the user with title and message. /// \param title The title of that messagebox /// \param message The content of message /// virtual void PluginErrorMessageBox(QString title, QString message) = 0; /// /// \brief SettingsUpdated will be called by Qv2ray once the plugin setting is updated. /// virtual void SettingsUpdated() = 0; QDir WorkingDirectory() { return m_WorkingDirectory; } protected: QJsonObject m_Settings; QDir m_WorkingDirectory; std::shared_ptr<Qv2rayPlugin::Profile::IProfilePreprocessor> m_ProfilePreprocessor; std::shared_ptr<Qv2rayPlugin::Outbound::IOutboundProcessor> m_OutboundHandler; std::shared_ptr<Qv2rayPlugin::Event::IEventHandler> m_EventHandler; std::shared_ptr<Qv2rayPlugin::Kernel::IKernelHandler> m_KernelInterface; std::shared_ptr<Qv2rayPlugin::Subscription::IPluginSubscriptionInterface> m_SubscriptionInterface; std::shared_ptr<Qv2rayPlugin::Latency::ILatencyHandler> m_LatencyTestHandler; // Not defined as a shared_ptr since not all plugins need QtGui Gui::Qv2rayGUIInterface *m_GUIInterface; private: Qv2rayPlugin::Connections::IProfileManager *m_ProfileManager; Qv2rayPlugin::Utils::INetworkRequestHelper *m_NetworkRequestHelper; QJsonObject m_PluginHostContext; }; template<class Impl> class Qv2rayInterface : public Qv2rayInterfaceImpl { public: static inline Impl *PluginInstance; static void Log(const QString &msg) { PluginInstance->PluginLog(msg); } static void ShowMessageBox(const QString &title, const QString &message) { PluginInstance->PluginErrorMessageBox(title, message); } static Qv2rayPlugin::Connections::IProfileManager *ProfileManager() { return PluginInstance->m_ProfileManager; } static Qv2rayPlugin::Utils::INetworkRequestHelper *NetworkRequestHelper() { return PluginInstance->m_NetworkRequestHelper; } protected: explicit Qv2rayInterface(Impl *impl) : Qv2rayInterfaceImpl() { PluginInstance = impl; } }; } // namespace Qv2rayPlugin #define QV2RAY_PLUGIN(CLASS) \ Q_INTERFACES(Qv2rayPlugin::Qv2rayInterfaceImpl) \ Q_PLUGIN_METADATA(IID Qv2rayInterface_IID) \ public: \ explicit CLASS() : QObject(), Qv2rayInterface(this){}; \ ~CLASS(){}; \ \ Q_SIGNAL void PluginLog(QString) override; \ Q_SIGNAL void PluginErrorMessageBox(QString, QString) override; QT_BEGIN_NAMESPACE Q_DECLARE_INTERFACE(Qv2rayPlugin::Qv2rayInterfaceImpl, Qv2rayInterface_IID) QT_END_NAMESPACE
40.492147
170
0.584044
Shadowsocks-NET
1a59a077c05de1e316d92f779f1d8cd52b81b87c
346
cpp
C++
core/src/main/jni/scale_argb.cpp
vfishv/libyuv-android
f4e048aef31325717025269dc25e012305207dec
[ "Apache-2.0", "BSD-3-Clause" ]
17
2020-09-19T21:19:07.000Z
2022-03-10T08:21:47.000Z
core/src/main/jni/scale_argb.cpp
vfishv/libyuv-android
f4e048aef31325717025269dc25e012305207dec
[ "Apache-2.0", "BSD-3-Clause" ]
3
2020-05-29T12:36:29.000Z
2021-09-04T02:09:48.000Z
core/src/main/jni/scale_argb.cpp
vfishv/libyuv-android
f4e048aef31325717025269dc25e012305207dec
[ "Apache-2.0", "BSD-3-Clause" ]
9
2020-03-26T12:12:37.000Z
2022-03-10T09:37:53.000Z
#include <libyuv.h> #include "scale.h" using namespace libyuv; using namespace libyuv::jniutil; extern "C" { PLANES_1_TO_1(ARGBScale, argb, argb) // Clipped scale takes destination rectangle coordinates for clip values. PLANES_1_TO_1_CLIP(ARGBScaleClip, argb, argb) // Scale with YUV conversion to ARGB and clipping. // YUVToARGBScaleClip }
20.352941
73
0.774566
vfishv
1a5d8960bc15cfa1a9a3f24ed70b97bafdede915
808
cpp
C++
src/engine/ui/src/ui/widgets/ui_animation.cpp
Healthire/halley
aa58e1abe22cda9e80637922721c03574779cd81
[ "Apache-2.0" ]
null
null
null
src/engine/ui/src/ui/widgets/ui_animation.cpp
Healthire/halley
aa58e1abe22cda9e80637922721c03574779cd81
[ "Apache-2.0" ]
null
null
null
src/engine/ui/src/ui/widgets/ui_animation.cpp
Healthire/halley
aa58e1abe22cda9e80637922721c03574779cd81
[ "Apache-2.0" ]
null
null
null
#include "widgets/ui_animation.h" using namespace Halley; UIAnimation::UIAnimation(const String& id, Vector2f size, Vector2f animationOffset, AnimationPlayer animation) : UIWidget(id, size) , offset(animationOffset) , animation(animation) {} AnimationPlayer& UIAnimation::getPlayer() { return animation; } const AnimationPlayer& UIAnimation::getPlayer() const { return animation; } Sprite& UIAnimation::getSprite() { return sprite; } const Sprite& UIAnimation::getSprite() const { return sprite; } void UIAnimation::update(Time t, bool moved) { if (animation.hasAnimation()) { animation.update(t); animation.updateSprite(sprite); sprite.setPos(getPosition() + offset); } } void UIAnimation::draw(UIPainter& painter) const { if (animation.hasAnimation()) { painter.draw(sprite); } }
17.955556
110
0.742574
Healthire
1a6121f2e6565752b4bd2d3674294fa9cf366fc4
655
hpp
C++
RandomColorProvider.hpp
Chlorek/clkb
902254c157700f3466fdda196f4f0f4e85d740cc
[ "MIT" ]
1
2017-11-17T23:16:37.000Z
2017-11-17T23:16:37.000Z
RandomColorProvider.hpp
Chlorek/clkb
902254c157700f3466fdda196f4f0f4e85d740cc
[ "MIT" ]
null
null
null
RandomColorProvider.hpp
Chlorek/clkb
902254c157700f3466fdda196f4f0f4e85d740cc
[ "MIT" ]
null
null
null
/* * File: RandomColorProvider.hpp * Author: chlorek * * Created on November 19, 2017, 12:37 AM */ #ifndef RANDOMCOLORPROVIDER_HPP #define RANDOMCOLORPROVIDER_HPP #include <random> #include "ColorProvider.hpp" #include "Effect.hpp" namespace clkb { class RandomColorProvider : public ColorProvider { public: RandomColorProvider(); RandomColorProvider(const RandomColorProvider& o); virtual ~RandomColorProvider(); virtual RGB next(); private: static std::uniform_int_distribution<RGB::TYPE> randChannel; }; } #endif /* RANDOMCOLORPROVIDER_HPP */
22.586207
72
0.654962
Chlorek
1a6acaeac71ad735d2dea8ae4df20974ce80c0fa
8,491
cpp
C++
Samples/Win7Samples/Touch/MTManipulationInertia/cpp/ManipulationEventsink.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/Touch/MTManipulationInertia/cpp/ManipulationEventsink.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/Touch/MTManipulationInertia/cpp/ManipulationEventsink.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "ManipulationEventsink.h" #include "CoreObject.h" #include <math.h> CManipulationEventSink::CManipulationEventSink(HWND hWnd, CCoreObject *coRef, int iTimerId, BOOL inertia): m_coRef(coRef), m_hWnd(hWnd), m_iTimerId(iTimerId), m_bInertia(inertia), m_pConnPoint(NULL), m_cRefCount(1) { } HRESULT STDMETHODCALLTYPE CManipulationEventSink::ManipulationStarted( FLOAT x, FLOAT y) { UNREFERENCED_PARAMETER(x); UNREFERENCED_PARAMETER(y); // Stop object if it is in the state of inertia m_coRef->bIsInertiaActive = FALSE; KillTimer(m_hWnd, m_iTimerId); m_coRef->doDrawing->RestoreRealPosition(); return S_OK; } HRESULT STDMETHODCALLTYPE CManipulationEventSink::ManipulationDelta( FLOAT x, FLOAT y, FLOAT translationDeltaX, FLOAT translationDeltaY, FLOAT scaleDelta, FLOAT expansionDelta, FLOAT rotationDelta, FLOAT cumulativeTranslationX, FLOAT cumulativeTranslationY, FLOAT cumulativeScale, FLOAT cumulativeExpansion, FLOAT cumulativeRotation) { UNREFERENCED_PARAMETER(cumulativeRotation); UNREFERENCED_PARAMETER(cumulativeExpansion); UNREFERENCED_PARAMETER(cumulativeScale); UNREFERENCED_PARAMETER(cumulativeTranslationX); UNREFERENCED_PARAMETER(cumulativeTranslationY); UNREFERENCED_PARAMETER(expansionDelta); CDrawingObject* dObj = m_coRef->doDrawing; IManipulationProcessor* mp= m_coRef->manipulationProc; HRESULT hr = S_OK; // Apply transformation based on rotationDelta (in radians) FLOAT rads = 180.0f / 3.14159f; dObj->SetManipulationOrigin(x, y); dObj->Rotate(rotationDelta*rads); // Apply translation based on scaleDelta dObj->Scale(scaleDelta); // Apply translation based on translationDelta dObj->Translate(translationDeltaX, translationDeltaY, m_bInertia); if(!m_bInertia) { // Set values for one finger rotations FLOAT fPivotRadius = (FLOAT)(sqrt(pow(dObj->GetWidth()/2, 2)+ pow(dObj->GetHeight()/2, 2)))*0.4f; FLOAT fPivotPtX = dObj->GetCenterX(); FLOAT fPivotPtY = dObj->GetCenterY(); HRESULT hrPPX = mp->put_PivotPointX(fPivotPtX); HRESULT hrPPY = mp->put_PivotPointY(fPivotPtY); HRESULT hrPR = mp->put_PivotRadius(fPivotRadius); if(FAILED(hrPPX) || FAILED(hrPPY) || FAILED(hrPR)) { hr = E_FAIL; } } return hr; } HRESULT STDMETHODCALLTYPE CManipulationEventSink::ManipulationCompleted( FLOAT x, FLOAT y, FLOAT cumulativeTranslationX, FLOAT cumulativeTranslationY, FLOAT cumulativeScale, FLOAT cumulativeExpansion, FLOAT cumulativeRotation) { UNREFERENCED_PARAMETER(cumulativeRotation); UNREFERENCED_PARAMETER(cumulativeExpansion); UNREFERENCED_PARAMETER(cumulativeScale); UNREFERENCED_PARAMETER(cumulativeTranslationX); UNREFERENCED_PARAMETER(cumulativeTranslationY); UNREFERENCED_PARAMETER(x); UNREFERENCED_PARAMETER(y); HRESULT hr = S_OK; IInertiaProcessor* ip = m_coRef->inertiaProc; IManipulationProcessor* mp = m_coRef->manipulationProc; if(!m_bInertia) { HRESULT hrSI = SetupInertia(ip, mp); HRESULT hrCO = S_OK; if(FAILED(hrSI) || FAILED(hrCO)) { hr = E_FAIL; } // Set the core objects inertia state to TRUE so it can // be processed when another object is being manipulated m_coRef->bIsInertiaActive = TRUE; // Kick off timer that handles inertia SetTimer(m_hWnd, m_iTimerId, DESIRED_MILLISECONDS, NULL); } else { m_coRef->bIsInertiaActive = FALSE; // Stop timer that handles inertia KillTimer(m_hWnd, m_iTimerId); } return hr; } HRESULT CManipulationEventSink::SetupInertia(IInertiaProcessor* ip, IManipulationProcessor* mp) { HRESULT hr = S_OK; // Set desired properties for inertia events // Deceleration for tranlations in pixel / msec^2 HRESULT hrPutDD = ip->put_DesiredDeceleration(0.003f); // Deceleration for rotations in radians / msec^2 HRESULT hrPutDAD = ip->put_DesiredAngularDeceleration(0.000015f); // Set initial origins HRESULT hrPutIOX = ip->put_InitialOriginX(m_coRef->doDrawing->GetCenterX()); HRESULT hrPutIOY = ip->put_InitialOriginY(m_coRef->doDrawing->GetCenterY()); FLOAT fVX; FLOAT fVY; FLOAT fVR; HRESULT hrPutVX = mp->GetVelocityX(&fVX); HRESULT hrGetVY = mp->GetVelocityY(&fVY); HRESULT hrGetAV = mp->GetAngularVelocity(&fVR); // Set initial velocities for inertia processor HRESULT hrPutIVX = ip->put_InitialVelocityX(fVX); HRESULT hrPutIVY = ip->put_InitialVelocityY(fVY); HRESULT hrPutIAV = ip->put_InitialAngularVelocity(fVR); if(FAILED(hrPutDD) || FAILED(hrPutDAD) || FAILED(hrPutIOX) || FAILED(hrPutIOY) || FAILED(hrPutVX) || FAILED(hrGetVY) || FAILED(hrGetAV) || FAILED(hrPutIVX) || FAILED(hrPutIVY) || FAILED(hrPutIAV)) { hr = E_FAIL; } return hr; } ULONG CManipulationEventSink::AddRef() { return ++m_cRefCount; } ULONG CManipulationEventSink::Release() { m_cRefCount--; if(m_cRefCount == 0) { delete this; return 0; } return m_cRefCount; } HRESULT CManipulationEventSink::QueryInterface(REFIID riid, LPVOID *ppvObj) { HRESULT hr = S_OK; if(ppvObj == NULL) { hr = E_POINTER; } if(!FAILED(hr)) { *ppvObj = NULL; if (IID__IManipulationEvents == riid) { *ppvObj = static_cast<_IManipulationEvents*>(this); } else if (IID_IUnknown == riid) { *ppvObj = static_cast<IUnknown*>(this); } if(*ppvObj) { AddRef(); } else { hr = E_NOINTERFACE; } } return hr; } // Set up the connection to a manipulation or inertia processor BOOL CManipulationEventSink::SetupConnPt(IUnknown *manipulationProc) { BOOL success = FALSE; IConnectionPointContainer* pConPointContainer = NULL; // Only connect if there isn't already an active connection if (m_pConnPoint == NULL) { // Check if supports connectable objects success = SUCCEEDED(manipulationProc->QueryInterface(IID_IConnectionPointContainer, (LPVOID*)&(pConPointContainer))); // Get connection point interface if(success) { success = SUCCEEDED(pConPointContainer->FindConnectionPoint( _uuidof(_IManipulationEvents), &(m_pConnPoint))); } // Clean up connection point container if (pConPointContainer != NULL) { pConPointContainer->Release(); pConPointContainer = NULL; } // Hook event object to the connection point IUnknown* pUnk = NULL; if(success) { // Get pointer to manipulation event sink's IUnknown pointer success = SUCCEEDED(QueryInterface(IID_IUnknown, (LPVOID*)&pUnk)); } // Establish connection point to callback interface if(success) { success = SUCCEEDED(m_pConnPoint->Advise(pUnk, &(m_uID))); } // Clean up IUnknown pointer if(pUnk != NULL) { pUnk->Release(); } if (!success && m_pConnPoint != NULL) { m_pConnPoint->Release(); m_pConnPoint = NULL; } } return success; } VOID CManipulationEventSink::RemoveConnPt() { // Clean up the connection point associated to this event sink if(m_pConnPoint) { m_pConnPoint->Unadvise(m_uID); m_pConnPoint->Release(); m_pConnPoint = NULL; } }
27.65798
108
0.625604
windows-development
1a6d9ceb084e48078c2549991af7b253972790c6
52,624
cpp
C++
src/tkn/color.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
23
2019-07-11T14:47:39.000Z
2021-12-24T09:56:24.000Z
src/tkn/color.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
null
null
null
src/tkn/color.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
4
2021-04-06T18:20:43.000Z
2022-01-15T09:20:45.000Z
// Implementation contains code from the great pbrt-v3, licensed under BSD-2. // See Chapter 5 of http://www.pbr-book.org/3ed-2018/contents.html for // a detailed documentation. // Also: https://github.com/mmp/pbrt-v3/blob/master/src/spectrum.cpp. // We use their tables and general implementation ideas, but the // code is reworked/rewritten. // // pbrt source code is Copyright(c) 1998-2015 // Matt Pharr, Greg Humphreys, and Wenzel Jakob. // This file is part of pbrt. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <tkn/color.hpp> #include <dlg/dlg.hpp> namespace tkn { namespace cieXYZ { constexpr auto nSamples = 471u; extern const float x[nSamples]; extern const float y[nSamples]; extern const float z[nSamples]; extern const float lambda[nSamples]; constexpr float yIntegral = 106.856895f; } // namespace cieXYZ namespace rgbSpect { constexpr int nSamples = 32; extern const float lambda[nSamples]; extern const float reflWhite[nSamples]; extern const float reflCyan[nSamples]; extern const float reflYellow[nSamples]; extern const float reflMagenta[nSamples]; extern const float reflRed[nSamples]; extern const float reflGreen[nSamples]; extern const float reflBlue[nSamples]; extern const float illumWhite[nSamples]; extern const float illumCyan[nSamples]; extern const float illumYellow[nSamples]; extern const float illumMagenta[nSamples]; extern const float illumRed[nSamples]; extern const float illumGreen[nSamples]; extern const float illumBlue[nSamples]; } // namespace rgb2Spect float spectrumAverage(const float* lambda, const float* vals, unsigned n, float lambdaStart, float lambdaEnd) { dlg_check({ dlg_assert(n > 0); dlg_assert(lambdaStart <= lambdaEnd); for(auto i = 0u; i < n - 1; ++i) { dlg_assertm(lambda[i + 1] > lambda[i], "Samples not sorted"); } }); // Handle cases with out-of-bounds range or single sample only if(lambdaEnd <= lambda[0]) { return vals[0]; } else if(lambdaStart >= lambda[n - 1]) { return vals[n - 1]; } else if(n == 1) { return vals[0]; } // Add contributions of constant segments before/after samples float sum = 0; if(lambdaStart < lambda[0]) { sum += vals[0] * (lambda[0] - lambdaStart); } if(lambdaEnd > lambda[n - 1]) { sum += vals[n - 1] * (lambdaEnd - lambda[n - 1]); } // Advance to first relevant wavelength segment auto i = std::lower_bound(lambda, lambda + n, lambdaStart) - lambda; dlg_assert(i < n); i = i > 0 ? i - 1 : 0; // Same as above but with manual linear iteration // int i = 0; // while(lambda[i + 1] < lambdaStart) { // ++i; // } // dlg_assert(i + 1 < n); // Loop over wavelength sample segments and add contributions auto interp = [lambda, vals](float w, int i) { return nytl::mix(vals[i], vals[i + 1], (w - lambda[i]) / (lambda[i + 1] - lambda[i])); }; for(; i + 1 < n && lambdaEnd >= lambda[i]; ++i) { float segLambdaStart = std::max(lambdaStart, lambda[i]); float segLambdaEnd = std::min(lambdaEnd, lambda[i + 1]); sum += 0.5 * (interp(segLambdaStart, i) + interp(segLambdaEnd, i)) * (segLambdaEnd - segLambdaStart); } return sum / (lambdaEnd - lambdaStart); } float spectrumAverage(const float* vals, unsigned n, float srcStart, float srcEnd, float avgStart, float avgEnd) { dlg_assert(n > 0); // Handle cases with out-of-bounds range or single sample only if(avgEnd <= srcStart) { return vals[0]; } else if(avgStart >= srcEnd) { return vals[n - 1]; } else if(n == 1) { return vals[0]; } // Add contributions of constant segments before/after samples float sum = 0; if(avgStart < srcStart) { sum += vals[0] * (srcStart - avgStart); } if(avgEnd > srcEnd) { sum += vals[n - 1] * (avgEnd - srcEnd); } // Advance to first relevant wavelength segment auto srcStep = (srcEnd - srcStart) / n; unsigned i = std::floor((avgStart - srcStart) / srcStep); // Loop over wavelength sample segments and add contributions auto lambda = [srcStart, srcStep, n](unsigned i) { dlg_assert(i < n); return srcStart + i * srcStep; }; auto interp = [lambda, vals](float w, int i) { return nytl::mix(vals[i], vals[i + 1], (w - lambda(i)) / (lambda(i + 1) - lambda(i))); }; for(; i + 1 < n && avgEnd >= lambda(i); ++i) { float segLambdaStart = std::max(avgStart, lambda(i)); float segLambdaEnd = std::min(avgEnd, lambda(i + 1)); sum += 0.5 * (interp(segLambdaStart, i) + interp(segLambdaEnd, i)) * (segLambdaEnd - segLambdaStart); } return sum / (avgEnd - avgStart); } // https://en.wikipedia.org/wiki/Planck%27s_law float planck(float temp, float wavelength) { constexpr auto c = 299792458; // speed of light constexpr auto h = 6.62607015e-34; // planck constant constexpr auto kb = 1.380649e-23; // boltzman constant if(temp <= 0) { return 0.f; } auto lambda = wavelength * 1e-9; // convert from nm to meters auto l5 = lambda * lambda * lambda * lambda * lambda; return 2 * h * c * c / (l5 * std::exp(h * c / lambda * kb * temp) - 1); } SpectralColor blackbody(float temp) { SpectralColor res; for(auto i = 0u; i < res.samples.size(); ++i) { auto l = res.wavelength(i); res.samples[i] = planck(temp, l); dlg_assert(!std::isnan(res.samples[i]) && !std::isinf(res.samples[i])); } return res; } nytl::Vec3f blackbodyApproxRGB(float temp) { // http://www.zombieprototypes.com/?p=210 // this version based upon https://github.com/neilbartlett/color-temperature, // licensed under MIT as well, Copyright (c) 2015 Neil Bartlett float t = temp / 100.f; float r, g, b; struct Coeffs { float a, b, c, off; float compute(float x) { auto r = a + b * x + c * std::log(x + off); return std::clamp(r, 0.f, 255.f); } }; if(t < 66.0) { r = 255; } else { r = Coeffs { 351.97690566805693, 0.114206453784165, -40.25366309332127, -55 }.compute(t); } if(t < 66.0) { g = Coeffs { -155.25485562709179, -0.44596950469579133, 104.49216199393888, -2 }.compute(t); } else { g = Coeffs { 325.4494125711974, 0.07943456536662342, -28.0852963507957, -50 }.compute(t); } if(t >= 66.0) { b = 255; } else { if(t <= 20.0) { b = 0; } else { b = Coeffs { -254.76935184120902, 0.8274096064007395, 115.67994401066147, -10 }.compute(t); } } return {r / 255.f, g / 255.f, b / 255.f}; } SpectralColor SpectralColor::fromSamples(const float* lambda, const float* vals, unsigned n) { SpectralColor out; for(auto i = 0u; i < nSpectralSamples; ++i) { auto low = wavelength(i + 0); auto high = wavelength(i + 1); out.samples[i] = spectrumAverage(lambda, vals, n, low, high); } return out; } SpectralColor SpectralColor::fromSamples(const float* vals, unsigned n, float lambdaMin, float lambdaMax) { SpectralColor out; for(auto i = 0u; i < nSpectralSamples; ++i) { auto low = wavelength(i + 0); auto high = wavelength(i + 1); out.samples[i] = spectrumAverage(vals, n, lambdaMin, lambdaMax, low, high); } return out; } // SpectralColor namespace { struct Spectra { SpectralColor X; SpectralColor Y; SpectralColor Z; SpectralColor rgbRefl2SpectWhite; SpectralColor rgbRefl2SpectCyan; SpectralColor rgbRefl2SpectMagenta; SpectralColor rgbRefl2SpectYellow; SpectralColor rgbRefl2SpectRed; SpectralColor rgbRefl2SpectGreen; SpectralColor rgbRefl2SpectBlue; SpectralColor rgbIllum2SpectWhite; SpectralColor rgbIllum2SpectCyan; SpectralColor rgbIllum2SpectMagenta; SpectralColor rgbIllum2SpectYellow; SpectralColor rgbIllum2SpectRed; SpectralColor rgbIllum2SpectGreen; SpectralColor rgbIllum2SpectBlue; }; Spectra initSpectra() { Spectra ret; // NOTE: all of this can be optimized by doing the iteration // manually, some calculations are done in each 'fromSamples' // that could be pulled out for mutual 'lambda' and 'n'. ret.X = SpectralColor::fromSamples(cieXYZ::lambda, cieXYZ::x, cieXYZ::nSamples); ret.Y = SpectralColor::fromSamples(cieXYZ::lambda, cieXYZ::y, cieXYZ::nSamples); ret.Z = SpectralColor::fromSamples(cieXYZ::lambda, cieXYZ::z, cieXYZ::nSamples); using namespace rgbSpect; ret.rgbIllum2SpectBlue = SpectralColor::fromSamples(lambda, illumBlue, nSamples); ret.rgbIllum2SpectGreen = SpectralColor::fromSamples(lambda, illumGreen, nSamples); ret.rgbIllum2SpectRed = SpectralColor::fromSamples(lambda, illumRed, nSamples); ret.rgbIllum2SpectWhite = SpectralColor::fromSamples(lambda, illumWhite, nSamples); ret.rgbIllum2SpectCyan = SpectralColor::fromSamples(lambda, illumCyan, nSamples); ret.rgbIllum2SpectYellow = SpectralColor::fromSamples(lambda, illumYellow, nSamples); ret.rgbIllum2SpectMagenta = SpectralColor::fromSamples(lambda, illumMagenta, nSamples); ret.rgbRefl2SpectBlue = SpectralColor::fromSamples(lambda, reflBlue, nSamples); ret.rgbRefl2SpectGreen = SpectralColor::fromSamples(lambda, reflGreen, nSamples); ret.rgbRefl2SpectRed = SpectralColor::fromSamples(lambda, reflRed, nSamples); ret.rgbRefl2SpectWhite = SpectralColor::fromSamples(lambda, reflWhite, nSamples); ret.rgbRefl2SpectCyan = SpectralColor::fromSamples(lambda, reflCyan, nSamples); ret.rgbRefl2SpectYellow = SpectralColor::fromSamples(lambda, reflYellow, nSamples); ret.rgbRefl2SpectMagenta = SpectralColor::fromSamples(lambda, reflMagenta, nSamples); return ret; } const Spectra& staticSpectra() { static Spectra spectrums = initSpectra(); return spectrums; } } // anon namespace SpectralColor SpectralColor::fromRGBIllum(const nytl::Vec3f& rgb) { auto [r, g, b] = rgb; auto& spects = staticSpectra(); SpectralColor out; if (r <= g && r <= b) { // Compute illuminant _SampledSpectrum_ with _r_ as minimum out += r * spects.rgbIllum2SpectWhite; if (g <= b) { out += (g - r) * spects.rgbIllum2SpectCyan; out += (b - g) * spects.rgbIllum2SpectBlue; } else { out += (b - r) * spects.rgbIllum2SpectCyan; out += (g - b) * spects.rgbIllum2SpectGreen; } } else if (g <= r && g <= b) { // Compute illuminant _SampledSpectrum_ with _g_ as minimum out += g * spects.rgbIllum2SpectWhite; if (r <= b) { out += (r - g) * spects.rgbIllum2SpectMagenta; out += (b - r) * spects.rgbIllum2SpectBlue; } else { out += (b - g) * spects.rgbIllum2SpectMagenta; out += (r - b) * spects.rgbIllum2SpectRed; } } else { // Compute illuminant _SampledSpectrum_ with _b_ as minimum out += b * spects.rgbIllum2SpectWhite; if (r <= g) { out += (r - b) * spects.rgbIllum2SpectYellow; out += (g - r) * spects.rgbIllum2SpectGreen; } else { out += (g - b) * spects.rgbIllum2SpectYellow; out += (r - g) * spects.rgbIllum2SpectRed; } } out *= .86445f; clamp(out); return out; } SpectralColor SpectralColor::fromRGBRefl(const nytl::Vec3f& rgb) { auto [r, g, b] = rgb; auto& spects = staticSpectra(); SpectralColor out {}; if(r <= g && r <= b) { // Compute reflectance _SampledSpectrum_ with _r_ as minimum out += r * spects.rgbRefl2SpectWhite; if(b <= b) { out += (g - r) * spects.rgbRefl2SpectCyan; out += (b - g) * spects.rgbRefl2SpectBlue; } else { out += (b - r) * spects.rgbRefl2SpectCyan; out += (g - b) * spects.rgbRefl2SpectGreen; } } else if (g <= r && g <= b) { // Compute reflectance _SampledSpectrum_ with _g_ as minimum out += g * spects.rgbRefl2SpectWhite; if (r <= b) { out += (r - g) * spects.rgbRefl2SpectMagenta; out += (b - r) * spects.rgbRefl2SpectBlue; } else { out += (b - g) * spects.rgbRefl2SpectMagenta; out += (r - b) * spects.rgbRefl2SpectRed; } } else { // Compute reflectance _SampledSpectrum_ with _b_ as minimum out += b * spects.rgbRefl2SpectWhite; if (r <= g) { out += (r - b) * spects.rgbRefl2SpectYellow; out += (g - r) * spects.rgbRefl2SpectGreen; } else { out += (g - b) * spects.rgbRefl2SpectYellow; out += (r - g) * spects.rgbRefl2SpectRed; } } out *= .94; clamp(out); return out; } nytl::Vec3f toXYZ(const SpectralColor& spectrum) { nytl::Vec3f xyz {}; auto& spects = staticSpectra(); for(auto i = 0u; i < nSpectralSamples; ++i) { auto strength = spectrum.samples[i]; xyz.x += spects.X.samples[i] * strength; xyz.y += spects.Y.samples[i] * strength; xyz.z += spects.Z.samples[i] * strength; } float scale = (SpectralColor::lambdaEnd - SpectralColor::lambdaStart) / (cieXYZ::yIntegral * nSpectralSamples); return scale * xyz; } // tables namespace cieXYZ { const float x[nSamples] = { // CIE X function values 0.0001299000f, 0.0001458470f, 0.0001638021f, 0.0001840037f, 0.0002066902f, 0.0002321000f, 0.0002607280f, 0.0002930750f, 0.0003293880f, 0.0003699140f, 0.0004149000f, 0.0004641587f, 0.0005189860f, 0.0005818540f, 0.0006552347f, 0.0007416000f, 0.0008450296f, 0.0009645268f, 0.001094949f, 0.001231154f, 0.001368000f, 0.001502050f, 0.001642328f, 0.001802382f, 0.001995757f, 0.002236000f, 0.002535385f, 0.002892603f, 0.003300829f, 0.003753236f, 0.004243000f, 0.004762389f, 0.005330048f, 0.005978712f, 0.006741117f, 0.007650000f, 0.008751373f, 0.01002888f, 0.01142170f, 0.01286901f, 0.01431000f, 0.01570443f, 0.01714744f, 0.01878122f, 0.02074801f, 0.02319000f, 0.02620736f, 0.02978248f, 0.03388092f, 0.03846824f, 0.04351000f, 0.04899560f, 0.05502260f, 0.06171880f, 0.06921200f, 0.07763000f, 0.08695811f, 0.09717672f, 0.1084063f, 0.1207672f, 0.1343800f, 0.1493582f, 0.1653957f, 0.1819831f, 0.1986110f, 0.2147700f, 0.2301868f, 0.2448797f, 0.2587773f, 0.2718079f, 0.2839000f, 0.2949438f, 0.3048965f, 0.3137873f, 0.3216454f, 0.3285000f, 0.3343513f, 0.3392101f, 0.3431213f, 0.3461296f, 0.3482800f, 0.3495999f, 0.3501474f, 0.3500130f, 0.3492870f, 0.3480600f, 0.3463733f, 0.3442624f, 0.3418088f, 0.3390941f, 0.3362000f, 0.3331977f, 0.3300411f, 0.3266357f, 0.3228868f, 0.3187000f, 0.3140251f, 0.3088840f, 0.3032904f, 0.2972579f, 0.2908000f, 0.2839701f, 0.2767214f, 0.2689178f, 0.2604227f, 0.2511000f, 0.2408475f, 0.2298512f, 0.2184072f, 0.2068115f, 0.1953600f, 0.1842136f, 0.1733273f, 0.1626881f, 0.1522833f, 0.1421000f, 0.1321786f, 0.1225696f, 0.1132752f, 0.1042979f, 0.09564000f, 0.08729955f, 0.07930804f, 0.07171776f, 0.06458099f, 0.05795001f, 0.05186211f, 0.04628152f, 0.04115088f, 0.03641283f, 0.03201000f, 0.02791720f, 0.02414440f, 0.02068700f, 0.01754040f, 0.01470000f, 0.01216179f, 0.009919960f, 0.007967240f, 0.006296346f, 0.004900000f, 0.003777173f, 0.002945320f, 0.002424880f, 0.002236293f, 0.002400000f, 0.002925520f, 0.003836560f, 0.005174840f, 0.006982080f, 0.009300000f, 0.01214949f, 0.01553588f, 0.01947752f, 0.02399277f, 0.02910000f, 0.03481485f, 0.04112016f, 0.04798504f, 0.05537861f, 0.06327000f, 0.07163501f, 0.08046224f, 0.08973996f, 0.09945645f, 0.1096000f, 0.1201674f, 0.1311145f, 0.1423679f, 0.1538542f, 0.1655000f, 0.1772571f, 0.1891400f, 0.2011694f, 0.2133658f, 0.2257499f, 0.2383209f, 0.2510668f, 0.2639922f, 0.2771017f, 0.2904000f, 0.3038912f, 0.3175726f, 0.3314384f, 0.3454828f, 0.3597000f, 0.3740839f, 0.3886396f, 0.4033784f, 0.4183115f, 0.4334499f, 0.4487953f, 0.4643360f, 0.4800640f, 0.4959713f, 0.5120501f, 0.5282959f, 0.5446916f, 0.5612094f, 0.5778215f, 0.5945000f, 0.6112209f, 0.6279758f, 0.6447602f, 0.6615697f, 0.6784000f, 0.6952392f, 0.7120586f, 0.7288284f, 0.7455188f, 0.7621000f, 0.7785432f, 0.7948256f, 0.8109264f, 0.8268248f, 0.8425000f, 0.8579325f, 0.8730816f, 0.8878944f, 0.9023181f, 0.9163000f, 0.9297995f, 0.9427984f, 0.9552776f, 0.9672179f, 0.9786000f, 0.9893856f, 0.9995488f, 1.0090892f, 1.0180064f, 1.0263000f, 1.0339827f, 1.0409860f, 1.0471880f, 1.0524667f, 1.0567000f, 1.0597944f, 1.0617992f, 1.0628068f, 1.0629096f, 1.0622000f, 1.0607352f, 1.0584436f, 1.0552244f, 1.0509768f, 1.0456000f, 1.0390369f, 1.0313608f, 1.0226662f, 1.0130477f, 1.0026000f, 0.9913675f, 0.9793314f, 0.9664916f, 0.9528479f, 0.9384000f, 0.9231940f, 0.9072440f, 0.8905020f, 0.8729200f, 0.8544499f, 0.8350840f, 0.8149460f, 0.7941860f, 0.7729540f, 0.7514000f, 0.7295836f, 0.7075888f, 0.6856022f, 0.6638104f, 0.6424000f, 0.6215149f, 0.6011138f, 0.5811052f, 0.5613977f, 0.5419000f, 0.5225995f, 0.5035464f, 0.4847436f, 0.4661939f, 0.4479000f, 0.4298613f, 0.4120980f, 0.3946440f, 0.3775333f, 0.3608000f, 0.3444563f, 0.3285168f, 0.3130192f, 0.2980011f, 0.2835000f, 0.2695448f, 0.2561184f, 0.2431896f, 0.2307272f, 0.2187000f, 0.2070971f, 0.1959232f, 0.1851708f, 0.1748323f, 0.1649000f, 0.1553667f, 0.1462300f, 0.1374900f, 0.1291467f, 0.1212000f, 0.1136397f, 0.1064650f, 0.09969044f, 0.09333061f, 0.08740000f, 0.08190096f, 0.07680428f, 0.07207712f, 0.06768664f, 0.06360000f, 0.05980685f, 0.05628216f, 0.05297104f, 0.04981861f, 0.04677000f, 0.04378405f, 0.04087536f, 0.03807264f, 0.03540461f, 0.03290000f, 0.03056419f, 0.02838056f, 0.02634484f, 0.02445275f, 0.02270000f, 0.02108429f, 0.01959988f, 0.01823732f, 0.01698717f, 0.01584000f, 0.01479064f, 0.01383132f, 0.01294868f, 0.01212920f, 0.01135916f, 0.01062935f, 0.009938846f, 0.009288422f, 0.008678854f, 0.008110916f, 0.007582388f, 0.007088746f, 0.006627313f, 0.006195408f, 0.005790346f, 0.005409826f, 0.005052583f, 0.004717512f, 0.004403507f, 0.004109457f, 0.003833913f, 0.003575748f, 0.003334342f, 0.003109075f, 0.002899327f, 0.002704348f, 0.002523020f, 0.002354168f, 0.002196616f, 0.002049190f, 0.001910960f, 0.001781438f, 0.001660110f, 0.001546459f, 0.001439971f, 0.001340042f, 0.001246275f, 0.001158471f, 0.001076430f, 0.0009999493f, 0.0009287358f, 0.0008624332f, 0.0008007503f, 0.0007433960f, 0.0006900786f, 0.0006405156f, 0.0005945021f, 0.0005518646f, 0.0005124290f, 0.0004760213f, 0.0004424536f, 0.0004115117f, 0.0003829814f, 0.0003566491f, 0.0003323011f, 0.0003097586f, 0.0002888871f, 0.0002695394f, 0.0002515682f, 0.0002348261f, 0.0002191710f, 0.0002045258f, 0.0001908405f, 0.0001780654f, 0.0001661505f, 0.0001550236f, 0.0001446219f, 0.0001349098f, 0.0001258520f, 0.0001174130f, 0.0001095515f, 0.0001022245f, 0.00009539445f, 0.00008902390f, 0.00008307527f, 0.00007751269f, 0.00007231304f, 0.00006745778f, 0.00006292844f, 0.00005870652f, 0.00005477028f, 0.00005109918f, 0.00004767654f, 0.00004448567f, 0.00004150994f, 0.00003873324f, 0.00003614203f, 0.00003372352f, 0.00003146487f, 0.00002935326f, 0.00002737573f, 0.00002552433f, 0.00002379376f, 0.00002217870f, 0.00002067383f, 0.00001927226f, 0.00001796640f, 0.00001674991f, 0.00001561648f, 0.00001455977f, 0.00001357387f, 0.00001265436f, 0.00001179723f, 0.00001099844f, 0.00001025398f, 0.000009559646f, 0.000008912044f, 0.000008308358f, 0.000007745769f, 0.000007221456f, 0.000006732475f, 0.000006276423f, 0.000005851304f, 0.000005455118f, 0.000005085868f, 0.000004741466f, 0.000004420236f, 0.000004120783f, 0.000003841716f, 0.000003581652f, 0.000003339127f, 0.000003112949f, 0.000002902121f, 0.000002705645f, 0.000002522525f, 0.000002351726f, 0.000002192415f, 0.000002043902f, 0.000001905497f, 0.000001776509f, 0.000001656215f, 0.000001544022f, 0.000001439440f, 0.000001341977f, 0.000001251141f}; const float y[nSamples] = { // CIE Y function values 0.000003917000f, 0.000004393581f, 0.000004929604f, 0.000005532136f, 0.000006208245f, 0.000006965000f, 0.000007813219f, 0.000008767336f, 0.000009839844f, 0.00001104323f, 0.00001239000f, 0.00001388641f, 0.00001555728f, 0.00001744296f, 0.00001958375f, 0.00002202000f, 0.00002483965f, 0.00002804126f, 0.00003153104f, 0.00003521521f, 0.00003900000f, 0.00004282640f, 0.00004691460f, 0.00005158960f, 0.00005717640f, 0.00006400000f, 0.00007234421f, 0.00008221224f, 0.00009350816f, 0.0001061361f, 0.0001200000f, 0.0001349840f, 0.0001514920f, 0.0001702080f, 0.0001918160f, 0.0002170000f, 0.0002469067f, 0.0002812400f, 0.0003185200f, 0.0003572667f, 0.0003960000f, 0.0004337147f, 0.0004730240f, 0.0005178760f, 0.0005722187f, 0.0006400000f, 0.0007245600f, 0.0008255000f, 0.0009411600f, 0.001069880f, 0.001210000f, 0.001362091f, 0.001530752f, 0.001720368f, 0.001935323f, 0.002180000f, 0.002454800f, 0.002764000f, 0.003117800f, 0.003526400f, 0.004000000f, 0.004546240f, 0.005159320f, 0.005829280f, 0.006546160f, 0.007300000f, 0.008086507f, 0.008908720f, 0.009767680f, 0.01066443f, 0.01160000f, 0.01257317f, 0.01358272f, 0.01462968f, 0.01571509f, 0.01684000f, 0.01800736f, 0.01921448f, 0.02045392f, 0.02171824f, 0.02300000f, 0.02429461f, 0.02561024f, 0.02695857f, 0.02835125f, 0.02980000f, 0.03131083f, 0.03288368f, 0.03452112f, 0.03622571f, 0.03800000f, 0.03984667f, 0.04176800f, 0.04376600f, 0.04584267f, 0.04800000f, 0.05024368f, 0.05257304f, 0.05498056f, 0.05745872f, 0.06000000f, 0.06260197f, 0.06527752f, 0.06804208f, 0.07091109f, 0.07390000f, 0.07701600f, 0.08026640f, 0.08366680f, 0.08723280f, 0.09098000f, 0.09491755f, 0.09904584f, 0.1033674f, 0.1078846f, 0.1126000f, 0.1175320f, 0.1226744f, 0.1279928f, 0.1334528f, 0.1390200f, 0.1446764f, 0.1504693f, 0.1564619f, 0.1627177f, 0.1693000f, 0.1762431f, 0.1835581f, 0.1912735f, 0.1994180f, 0.2080200f, 0.2171199f, 0.2267345f, 0.2368571f, 0.2474812f, 0.2586000f, 0.2701849f, 0.2822939f, 0.2950505f, 0.3085780f, 0.3230000f, 0.3384021f, 0.3546858f, 0.3716986f, 0.3892875f, 0.4073000f, 0.4256299f, 0.4443096f, 0.4633944f, 0.4829395f, 0.5030000f, 0.5235693f, 0.5445120f, 0.5656900f, 0.5869653f, 0.6082000f, 0.6293456f, 0.6503068f, 0.6708752f, 0.6908424f, 0.7100000f, 0.7281852f, 0.7454636f, 0.7619694f, 0.7778368f, 0.7932000f, 0.8081104f, 0.8224962f, 0.8363068f, 0.8494916f, 0.8620000f, 0.8738108f, 0.8849624f, 0.8954936f, 0.9054432f, 0.9148501f, 0.9237348f, 0.9320924f, 0.9399226f, 0.9472252f, 0.9540000f, 0.9602561f, 0.9660074f, 0.9712606f, 0.9760225f, 0.9803000f, 0.9840924f, 0.9874812f, 0.9903128f, 0.9928116f, 0.9949501f, 0.9967108f, 0.9980983f, 0.9991120f, 0.9997482f, 1.0000000f, 0.9998567f, 0.9993046f, 0.9983255f, 0.9968987f, 0.9950000f, 0.9926005f, 0.9897426f, 0.9864444f, 0.9827241f, 0.9786000f, 0.9740837f, 0.9691712f, 0.9638568f, 0.9581349f, 0.9520000f, 0.9454504f, 0.9384992f, 0.9311628f, 0.9234576f, 0.9154000f, 0.9070064f, 0.8982772f, 0.8892048f, 0.8797816f, 0.8700000f, 0.8598613f, 0.8493920f, 0.8386220f, 0.8275813f, 0.8163000f, 0.8047947f, 0.7930820f, 0.7811920f, 0.7691547f, 0.7570000f, 0.7447541f, 0.7324224f, 0.7200036f, 0.7074965f, 0.6949000f, 0.6822192f, 0.6694716f, 0.6566744f, 0.6438448f, 0.6310000f, 0.6181555f, 0.6053144f, 0.5924756f, 0.5796379f, 0.5668000f, 0.5539611f, 0.5411372f, 0.5283528f, 0.5156323f, 0.5030000f, 0.4904688f, 0.4780304f, 0.4656776f, 0.4534032f, 0.4412000f, 0.4290800f, 0.4170360f, 0.4050320f, 0.3930320f, 0.3810000f, 0.3689184f, 0.3568272f, 0.3447768f, 0.3328176f, 0.3210000f, 0.3093381f, 0.2978504f, 0.2865936f, 0.2756245f, 0.2650000f, 0.2547632f, 0.2448896f, 0.2353344f, 0.2260528f, 0.2170000f, 0.2081616f, 0.1995488f, 0.1911552f, 0.1829744f, 0.1750000f, 0.1672235f, 0.1596464f, 0.1522776f, 0.1451259f, 0.1382000f, 0.1315003f, 0.1250248f, 0.1187792f, 0.1127691f, 0.1070000f, 0.1014762f, 0.09618864f, 0.09112296f, 0.08626485f, 0.08160000f, 0.07712064f, 0.07282552f, 0.06871008f, 0.06476976f, 0.06100000f, 0.05739621f, 0.05395504f, 0.05067376f, 0.04754965f, 0.04458000f, 0.04175872f, 0.03908496f, 0.03656384f, 0.03420048f, 0.03200000f, 0.02996261f, 0.02807664f, 0.02632936f, 0.02470805f, 0.02320000f, 0.02180077f, 0.02050112f, 0.01928108f, 0.01812069f, 0.01700000f, 0.01590379f, 0.01483718f, 0.01381068f, 0.01283478f, 0.01192000f, 0.01106831f, 0.01027339f, 0.009533311f, 0.008846157f, 0.008210000f, 0.007623781f, 0.007085424f, 0.006591476f, 0.006138485f, 0.005723000f, 0.005343059f, 0.004995796f, 0.004676404f, 0.004380075f, 0.004102000f, 0.003838453f, 0.003589099f, 0.003354219f, 0.003134093f, 0.002929000f, 0.002738139f, 0.002559876f, 0.002393244f, 0.002237275f, 0.002091000f, 0.001953587f, 0.001824580f, 0.001703580f, 0.001590187f, 0.001484000f, 0.001384496f, 0.001291268f, 0.001204092f, 0.001122744f, 0.001047000f, 0.0009765896f, 0.0009111088f, 0.0008501332f, 0.0007932384f, 0.0007400000f, 0.0006900827f, 0.0006433100f, 0.0005994960f, 0.0005584547f, 0.0005200000f, 0.0004839136f, 0.0004500528f, 0.0004183452f, 0.0003887184f, 0.0003611000f, 0.0003353835f, 0.0003114404f, 0.0002891656f, 0.0002684539f, 0.0002492000f, 0.0002313019f, 0.0002146856f, 0.0001992884f, 0.0001850475f, 0.0001719000f, 0.0001597781f, 0.0001486044f, 0.0001383016f, 0.0001287925f, 0.0001200000f, 0.0001118595f, 0.0001043224f, 0.00009733560f, 0.00009084587f, 0.00008480000f, 0.00007914667f, 0.00007385800f, 0.00006891600f, 0.00006430267f, 0.00006000000f, 0.00005598187f, 0.00005222560f, 0.00004871840f, 0.00004544747f, 0.00004240000f, 0.00003956104f, 0.00003691512f, 0.00003444868f, 0.00003214816f, 0.00003000000f, 0.00002799125f, 0.00002611356f, 0.00002436024f, 0.00002272461f, 0.00002120000f, 0.00001977855f, 0.00001845285f, 0.00001721687f, 0.00001606459f, 0.00001499000f, 0.00001398728f, 0.00001305155f, 0.00001217818f, 0.00001136254f, 0.00001060000f, 0.000009885877f, 0.000009217304f, 0.000008592362f, 0.000008009133f, 0.000007465700f, 0.000006959567f, 0.000006487995f, 0.000006048699f, 0.000005639396f, 0.000005257800f, 0.000004901771f, 0.000004569720f, 0.000004260194f, 0.000003971739f, 0.000003702900f, 0.000003452163f, 0.000003218302f, 0.000003000300f, 0.000002797139f, 0.000002607800f, 0.000002431220f, 0.000002266531f, 0.000002113013f, 0.000001969943f, 0.000001836600f, 0.000001712230f, 0.000001596228f, 0.000001488090f, 0.000001387314f, 0.000001293400f, 0.000001205820f, 0.000001124143f, 0.000001048009f, 0.0000009770578f, 0.0000009109300f, 0.0000008492513f, 0.0000007917212f, 0.0000007380904f, 0.0000006881098f, 0.0000006415300f, 0.0000005980895f, 0.0000005575746f, 0.0000005198080f, 0.0000004846123f, 0.0000004518100f}; const float z[nSamples] = { // CIE Z function values 0.0006061000f, 0.0006808792f, 0.0007651456f, 0.0008600124f, 0.0009665928f, 0.001086000f, 0.001220586f, 0.001372729f, 0.001543579f, 0.001734286f, 0.001946000f, 0.002177777f, 0.002435809f, 0.002731953f, 0.003078064f, 0.003486000f, 0.003975227f, 0.004540880f, 0.005158320f, 0.005802907f, 0.006450001f, 0.007083216f, 0.007745488f, 0.008501152f, 0.009414544f, 0.01054999f, 0.01196580f, 0.01365587f, 0.01558805f, 0.01773015f, 0.02005001f, 0.02251136f, 0.02520288f, 0.02827972f, 0.03189704f, 0.03621000f, 0.04143771f, 0.04750372f, 0.05411988f, 0.06099803f, 0.06785001f, 0.07448632f, 0.08136156f, 0.08915364f, 0.09854048f, 0.1102000f, 0.1246133f, 0.1417017f, 0.1613035f, 0.1832568f, 0.2074000f, 0.2336921f, 0.2626114f, 0.2947746f, 0.3307985f, 0.3713000f, 0.4162091f, 0.4654642f, 0.5196948f, 0.5795303f, 0.6456000f, 0.7184838f, 0.7967133f, 0.8778459f, 0.9594390f, 1.0390501f, 1.1153673f, 1.1884971f, 1.2581233f, 1.3239296f, 1.3856000f, 1.4426352f, 1.4948035f, 1.5421903f, 1.5848807f, 1.6229600f, 1.6564048f, 1.6852959f, 1.7098745f, 1.7303821f, 1.7470600f, 1.7600446f, 1.7696233f, 1.7762637f, 1.7804334f, 1.7826000f, 1.7829682f, 1.7816998f, 1.7791982f, 1.7758671f, 1.7721100f, 1.7682589f, 1.7640390f, 1.7589438f, 1.7524663f, 1.7441000f, 1.7335595f, 1.7208581f, 1.7059369f, 1.6887372f, 1.6692000f, 1.6475287f, 1.6234127f, 1.5960223f, 1.5645280f, 1.5281000f, 1.4861114f, 1.4395215f, 1.3898799f, 1.3387362f, 1.2876400f, 1.2374223f, 1.1878243f, 1.1387611f, 1.0901480f, 1.0419000f, 0.9941976f, 0.9473473f, 0.9014531f, 0.8566193f, 0.8129501f, 0.7705173f, 0.7294448f, 0.6899136f, 0.6521049f, 0.6162000f, 0.5823286f, 0.5504162f, 0.5203376f, 0.4919673f, 0.4651800f, 0.4399246f, 0.4161836f, 0.3938822f, 0.3729459f, 0.3533000f, 0.3348578f, 0.3175521f, 0.3013375f, 0.2861686f, 0.2720000f, 0.2588171f, 0.2464838f, 0.2347718f, 0.2234533f, 0.2123000f, 0.2011692f, 0.1901196f, 0.1792254f, 0.1685608f, 0.1582000f, 0.1481383f, 0.1383758f, 0.1289942f, 0.1200751f, 0.1117000f, 0.1039048f, 0.09666748f, 0.08998272f, 0.08384531f, 0.07824999f, 0.07320899f, 0.06867816f, 0.06456784f, 0.06078835f, 0.05725001f, 0.05390435f, 0.05074664f, 0.04775276f, 0.04489859f, 0.04216000f, 0.03950728f, 0.03693564f, 0.03445836f, 0.03208872f, 0.02984000f, 0.02771181f, 0.02569444f, 0.02378716f, 0.02198925f, 0.02030000f, 0.01871805f, 0.01724036f, 0.01586364f, 0.01458461f, 0.01340000f, 0.01230723f, 0.01130188f, 0.01037792f, 0.009529306f, 0.008749999f, 0.008035200f, 0.007381600f, 0.006785400f, 0.006242800f, 0.005749999f, 0.005303600f, 0.004899800f, 0.004534200f, 0.004202400f, 0.003900000f, 0.003623200f, 0.003370600f, 0.003141400f, 0.002934800f, 0.002749999f, 0.002585200f, 0.002438600f, 0.002309400f, 0.002196800f, 0.002100000f, 0.002017733f, 0.001948200f, 0.001889800f, 0.001840933f, 0.001800000f, 0.001766267f, 0.001737800f, 0.001711200f, 0.001683067f, 0.001650001f, 0.001610133f, 0.001564400f, 0.001513600f, 0.001458533f, 0.001400000f, 0.001336667f, 0.001270000f, 0.001205000f, 0.001146667f, 0.001100000f, 0.001068800f, 0.001049400f, 0.001035600f, 0.001021200f, 0.001000000f, 0.0009686400f, 0.0009299200f, 0.0008868800f, 0.0008425600f, 0.0008000000f, 0.0007609600f, 0.0007236800f, 0.0006859200f, 0.0006454400f, 0.0006000000f, 0.0005478667f, 0.0004916000f, 0.0004354000f, 0.0003834667f, 0.0003400000f, 0.0003072533f, 0.0002831600f, 0.0002654400f, 0.0002518133f, 0.0002400000f, 0.0002295467f, 0.0002206400f, 0.0002119600f, 0.0002021867f, 0.0001900000f, 0.0001742133f, 0.0001556400f, 0.0001359600f, 0.0001168533f, 0.0001000000f, 0.00008613333f, 0.00007460000f, 0.00006500000f, 0.00005693333f, 0.00004999999f, 0.00004416000f, 0.00003948000f, 0.00003572000f, 0.00003264000f, 0.00003000000f, 0.00002765333f, 0.00002556000f, 0.00002364000f, 0.00002181333f, 0.00002000000f, 0.00001813333f, 0.00001620000f, 0.00001420000f, 0.00001213333f, 0.00001000000f, 0.000007733333f, 0.000005400000f, 0.000003200000f, 0.000001333333f, 0.000000000000f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; const float lambda[nSamples] = { 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830 }; } // namespace cieXYZ namespace rgbSpect { const float lambda[nSamples] = { 380.000000, 390.967743, 401.935486, 412.903229, 423.870972, 434.838715, 445.806458, 456.774200, 467.741943, 478.709686, 489.677429, 500.645172, 511.612915, 522.580627, 533.548340, 544.516052, 555.483765, 566.451477, 577.419189, 588.386902, 599.354614, 610.322327, 621.290039, 632.257751, 643.225464, 654.193176, 665.160889, 676.128601, 687.096313, 698.064026, 709.031738, 720.000000}; const float reflWhite[nSamples] = { 1.0618958571272863e+00, 1.0615019980348779e+00, 1.0614335379927147e+00, 1.0622711654692485e+00, 1.0622036218416742e+00, 1.0625059965187085e+00, 1.0623938486985884e+00, 1.0624706448043137e+00, 1.0625048144827762e+00, 1.0624366131308856e+00, 1.0620694238892607e+00, 1.0613167586932164e+00, 1.0610334029377020e+00, 1.0613868564828413e+00, 1.0614215366116762e+00, 1.0620336151299086e+00, 1.0625497454805051e+00, 1.0624317487992085e+00, 1.0625249140554480e+00, 1.0624277664486914e+00, 1.0624749854090769e+00, 1.0625538581025402e+00, 1.0625326910104864e+00, 1.0623922312225325e+00, 1.0623650980354129e+00, 1.0625256476715284e+00, 1.0612277619533155e+00, 1.0594262608698046e+00, 1.0599810758292072e+00, 1.0602547314449409e+00, 1.0601263046243634e+00, 1.0606565756823634e+00}; const float reflCyan[nSamples] = { 1.0414628021426751e+00, 1.0328661533771188e+00, 1.0126146228964314e+00, 1.0350460524836209e+00, 1.0078661447098567e+00, 1.0422280385081280e+00, 1.0442596738499825e+00, 1.0535238290294409e+00, 1.0180776226938120e+00, 1.0442729908727713e+00, 1.0529362541920750e+00, 1.0537034271160244e+00, 1.0533901869215969e+00, 1.0537782700979574e+00, 1.0527093770467102e+00, 1.0530449040446797e+00, 1.0550554640191208e+00, 1.0553673610724821e+00, 1.0454306634683976e+00, 6.2348950639230805e-01, 1.8038071613188977e-01, -7.6303759201984539e-03, -1.5217847035781367e-04, -7.5102257347258311e-03, -2.1708639328491472e-03, 6.5919466602369636e-04, 1.2278815318539780e-02, -4.4669775637208031e-03, 1.7119799082865147e-02, 4.9211089759759801e-03, 5.8762925143334985e-03, 2.5259399415550079e-02}; const float reflMagenta[nSamples] = { 9.9422138151236850e-01, 9.8986937122975682e-01, 9.8293658286116958e-01, 9.9627868399859310e-01, 1.0198955019000133e+00, 1.0166395501210359e+00, 1.0220913178757398e+00, 9.9651666040682441e-01, 1.0097766178917882e+00, 1.0215422470827016e+00, 6.4031953387790963e-01, 2.5012379477078184e-03, 6.5339939555769944e-03, 2.8334080462675826e-03, -5.1209675389074505e-11, -9.0592291646646381e-03, 3.3936718323331200e-03, -3.0638741121828406e-03, 2.2203936168286292e-01, 6.3141140024811970e-01, 9.7480985576500956e-01, 9.7209562333590571e-01, 1.0173770302868150e+00, 9.9875194322734129e-01, 9.4701725739602238e-01, 8.5258623154354796e-01, 9.4897798581660842e-01, 9.4751876096521492e-01, 9.9598944191059791e-01, 8.6301351503809076e-01, 8.9150987853523145e-01, 8.4866492652845082e-01}; const float reflYellow[nSamples] = { 5.5740622924920873e-03, -4.7982831631446787e-03, -5.2536564298613798e-03, -6.4571480044499710e-03, -5.9693514658007013e-03, -2.1836716037686721e-03, 1.6781120601055327e-02, 9.6096355429062641e-02, 2.1217357081986446e-01, 3.6169133290685068e-01, 5.3961011543232529e-01, 7.4408810492171507e-01, 9.2209571148394054e-01, 1.0460304298411225e+00, 1.0513824989063714e+00, 1.0511991822135085e+00, 1.0510530911991052e+00, 1.0517397230360510e+00, 1.0516043086790485e+00, 1.0511944032061460e+00, 1.0511590325868068e+00, 1.0516612465483031e+00, 1.0514038526836869e+00, 1.0515941029228475e+00, 1.0511460436960840e+00, 1.0515123758830476e+00, 1.0508871369510702e+00, 1.0508923708102380e+00, 1.0477492815668303e+00, 1.0493272144017338e+00, 1.0435963333422726e+00, 1.0392280772051465e+00}; const float reflRed[nSamples] = { 1.6575604867086180e-01, 1.1846442802747797e-01, 1.2408293329637447e-01, 1.1371272058349924e-01, 7.8992434518899132e-02, 3.2205603593106549e-02, -1.0798365407877875e-02, 1.8051975516730392e-02, 5.3407196598730527e-03, 1.3654918729501336e-02, -5.9564213545642841e-03, -1.8444365067353252e-03, -1.0571884361529504e-02, -2.9375521078000011e-03, -1.0790476271835936e-02, -8.0224306697503633e-03, -2.2669167702495940e-03, 7.0200240494706634e-03, -8.1528469000299308e-03, 6.0772866969252792e-01, 9.8831560865432400e-01, 9.9391691044078823e-01, 1.0039338994753197e+00, 9.9234499861167125e-01, 9.9926530858855522e-01, 1.0084621557617270e+00, 9.8358296827441216e-01, 1.0085023660099048e+00, 9.7451138326568698e-01, 9.8543269570059944e-01, 9.3495763980962043e-01, 9.8713907792319400e-01}; const float reflGreen[nSamples] = { 2.6494153587602255e-03, -5.0175013429732242e-03, -1.2547236272489583e-02, -9.4554964308388671e-03, -1.2526086181600525e-02, -7.9170697760437767e-03, -7.9955735204175690e-03, -9.3559433444469070e-03, 6.5468611982999303e-02, 3.9572875517634137e-01, 7.5244022299886659e-01, 9.6376478690218559e-01, 9.9854433855162328e-01, 9.9992977025287921e-01, 9.9939086751140449e-01, 9.9994372267071396e-01, 9.9939121813418674e-01, 9.9911237310424483e-01, 9.6019584878271580e-01, 6.3186279338432438e-01, 2.5797401028763473e-01, 9.4014888527335638e-03, -3.0798345608649747e-03, -4.5230367033685034e-03, -6.8933410388274038e-03, -9.0352195539015398e-03, -8.5913667165340209e-03, -8.3690869120289398e-03, -7.8685832338754313e-03, -8.3657578711085132e-06, 5.4301225442817177e-03, -2.7745589759259194e-03}; const float reflBlue[nSamples] = { 9.9209771469720676e-01, 9.8876426059369127e-01, 9.9539040744505636e-01, 9.9529317353008218e-01, 9.9181447411633950e-01, 1.0002584039673432e+00, 9.9968478437342512e-01, 9.9988120766657174e-01, 9.8504012146370434e-01, 7.9029849053031276e-01, 5.6082198617463974e-01, 3.3133458513996528e-01, 1.3692410840839175e-01, 1.8914906559664151e-02, -5.1129770932550889e-06, -4.2395493167891873e-04, -4.1934593101534273e-04, 1.7473028136486615e-03, 3.7999160177631316e-03, -5.5101474906588642e-04, -4.3716662898480967e-05, 7.5874501748732798e-03, 2.5795650780554021e-02, 3.8168376532500548e-02, 4.9489586408030833e-02, 4.9595992290102905e-02, 4.9814819505812249e-02, 3.9840911064978023e-02, 3.0501024937233868e-02, 2.1243054765241080e-02, 6.9596532104356399e-03, 4.1733649330980525e-03}; const float illumWhite[nSamples] = { 1.1565232050369776e+00, 1.1567225000119139e+00, 1.1566203150243823e+00, 1.1555782088080084e+00, 1.1562175509215700e+00, 1.1567674012207332e+00, 1.1568023194808630e+00, 1.1567677445485520e+00, 1.1563563182952830e+00, 1.1567054702510189e+00, 1.1565134139372772e+00, 1.1564336176499312e+00, 1.1568023181530034e+00, 1.1473147688514642e+00, 1.1339317140561065e+00, 1.1293876490671435e+00, 1.1290515328639648e+00, 1.0504864823782283e+00, 1.0459696042230884e+00, 9.9366687168595691e-01, 9.5601669265393940e-01, 9.2467482033511805e-01, 9.1499944702051761e-01, 8.9939467658453465e-01, 8.9542520751331112e-01, 8.8870566693814745e-01, 8.8222843814228114e-01, 8.7998311373826676e-01, 8.7635244612244578e-01, 8.8000368331709111e-01, 8.8065665428441120e-01, 8.8304706460276905e-01}; const float illumCyan[nSamples] = { 1.1334479663682135e+00, 1.1266762330194116e+00, 1.1346827504710164e+00, 1.1357395805744794e+00, 1.1356371830149636e+00, 1.1361152989346193e+00, 1.1362179057706772e+00, 1.1364819652587022e+00, 1.1355107110714324e+00, 1.1364060941199556e+00, 1.1360363621722465e+00, 1.1360122641141395e+00, 1.1354266882467030e+00, 1.1363099407179136e+00, 1.1355450412632506e+00, 1.1353732327376378e+00, 1.1349496420726002e+00, 1.1111113947168556e+00, 9.0598740429727143e-01, 6.1160780787465330e-01, 2.9539752170999634e-01, 9.5954200671150097e-02, -1.1650792030826267e-02, -1.2144633073395025e-02, -1.1148167569748318e-02, -1.1997606668458151e-02, -5.0506855475394852e-03, -7.9982745819542154e-03, -9.4722817708236418e-03, -5.5329541006658815e-03, -4.5428914028274488e-03, -1.2541015360921132e-02}; const float illumMagenta[nSamples] = { 1.0371892935878366e+00, 1.0587542891035364e+00, 1.0767271213688903e+00, 1.0762706844110288e+00, 1.0795289105258212e+00, 1.0743644742950074e+00, 1.0727028691194342e+00, 1.0732447452056488e+00, 1.0823760816041414e+00, 1.0840545681409282e+00, 9.5607567526306658e-01, 5.5197896855064665e-01, 8.4191094887247575e-02, 8.7940070557041006e-05, -2.3086408335071251e-03, -1.1248136628651192e-03, -7.7297612754989586e-11, -2.7270769006770834e-04, 1.4466473094035592e-02, 2.5883116027169478e-01, 5.2907999827566732e-01, 9.0966624097105164e-01, 1.0690571327307956e+00, 1.0887326064796272e+00, 1.0637622289511852e+00, 1.0201812918094260e+00, 1.0262196688979945e+00, 1.0783085560613190e+00, 9.8333849623218872e-01, 1.0707246342802621e+00, 1.0634247770423768e+00, 1.0150875475729566e+00}; const float illumYellow[nSamples] = { 2.7756958965811972e-03, 3.9673820990646612e-03, -1.4606936788606750e-04, 3.6198394557748065e-04, -2.5819258699309733e-04, -5.0133191628082274e-05, -2.4437242866157116e-04, -7.8061419948038946e-05, 4.9690301207540921e-02, 4.8515973574763166e-01, 1.0295725854360589e+00, 1.0333210878457741e+00, 1.0368102644026933e+00, 1.0364884018886333e+00, 1.0365427939411784e+00, 1.0368595402854539e+00, 1.0365645405660555e+00, 1.0363938240707142e+00, 1.0367205578770746e+00, 1.0365239329446050e+00, 1.0361531226427443e+00, 1.0348785007827348e+00, 1.0042729660717318e+00, 8.4218486432354278e-01, 7.3759394894801567e-01, 6.5853154500294642e-01, 6.0531682444066282e-01, 5.9549794132420741e-01, 5.9419261278443136e-01, 5.6517682326634266e-01, 5.6061186014968556e-01, 5.8228610381018719e-01}; const float illumRed[nSamples] = { 5.4711187157291841e-02, 5.5609066498303397e-02, 6.0755873790918236e-02, 5.6232948615962369e-02, 4.6169940535708678e-02, 3.8012808167818095e-02, 2.4424225756670338e-02, 3.8983580581592181e-03, -5.6082252172734437e-04, 9.6493871255194652e-04, 3.7341198051510371e-04, -4.3367389093135200e-04, -9.3533962256892034e-05, -1.2354967412842033e-04, -1.4524548081687461e-04, -2.0047691915543731e-04, -4.9938587694693670e-04, 2.7255083540032476e-02, 1.6067405906297061e-01, 3.5069788873150953e-01, 5.7357465538418961e-01, 7.6392091890718949e-01, 8.9144466740381523e-01, 9.6394609909574891e-01, 9.8879464276016282e-01, 9.9897449966227203e-01, 9.8605140403564162e-01, 9.9532502805345202e-01, 9.7433478377305371e-01, 9.9134364616871407e-01, 9.8866287772174755e-01, 9.9713856089735531e-01}; const float illumGreen[nSamples] = { 2.5168388755514630e-02, 3.9427438169423720e-02, 6.2059571596425793e-03, 7.1120859807429554e-03, 2.1760044649139429e-04, 7.3271839984290210e-12, -2.1623066217181700e-02, 1.5670209409407512e-02, 2.8019603188636222e-03, 3.2494773799897647e-01, 1.0164917292316602e+00, 1.0329476657890369e+00, 1.0321586962991549e+00, 1.0358667411948619e+00, 1.0151235476834941e+00, 1.0338076690093119e+00, 1.0371372378155013e+00, 1.0361377027692558e+00, 1.0229822432557210e+00, 9.6910327335652324e-01, -5.1785923899878572e-03, 1.1131261971061429e-03, 6.6675503033011771e-03, 7.4024315686001957e-04, 2.1591567633473925e-02, 5.1481620056217231e-03, 1.4561928645728216e-03, 1.6414511045291513e-04, -6.4630764968453287e-03, 1.0250854718507939e-02, 4.2387394733956134e-02, 2.1252716926861620e-02}; const float illumBlue[nSamples] = { 1.0570490759328752e+00, 1.0538466912851301e+00, 1.0550494258140670e+00, 1.0530407754701832e+00, 1.0579930596460185e+00, 1.0578439494812371e+00, 1.0583132387180239e+00, 1.0579712943137616e+00, 1.0561884233578465e+00, 1.0571399285426490e+00, 1.0425795187752152e+00, 3.2603084374056102e-01, -1.9255628442412243e-03, -1.2959221137046478e-03, -1.4357356276938696e-03, -1.2963697250337886e-03, -1.9227081162373899e-03, 1.2621152526221778e-03, -1.6095249003578276e-03, -1.3029983817879568e-03, -1.7666600873954916e-03, -1.2325281140280050e-03, 1.0316809673254932e-02, 3.1284512648354357e-02, 8.8773879881746481e-02, 1.3873621740236541e-01, 1.5535067531939065e-01, 1.4878477178237029e-01, 1.6624255403475907e-01, 1.6997613960634927e-01, 1.5769743995852967e-01, 1.9069090525482305e-01}; } // namespace rgbSpect } // namespace tkn
37.642346
88
0.648943
nyorain
2b3ccbfb6d06f4ec20e667d932da3957b8bf3b63
3,050
cpp
C++
main.cpp
dczang53/NES_Emulator
741dce5e3587811ef08c9064916a26baced45c19
[ "MIT" ]
null
null
null
main.cpp
dczang53/NES_Emulator
741dce5e3587811ef08c9064916a26baced45c19
[ "MIT" ]
null
null
null
main.cpp
dczang53/NES_Emulator
741dce5e3587811ef08c9064916a26baced45c19
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <string> #include "include/Mapper.hpp" #include "include/Memory.hpp" #include "include/Ricoh2A03.hpp" #include "include/IO.hpp" #include "include/Ricoh2C02.hpp" #ifdef GTEST #include "testModules/gtestModules.hpp" #else #include "SDL2/SDL.h" #endif #define FPS 60 // defined FPS; change this to whatever you see fit // https://wiki.nesdev.org/w/index.php?title=Cycle_reference_chart#Clock_rates int main(int argc, char **argv) { #ifdef GTEST ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); #else std::string ROMfile; if (argc != 2) { std::cout << "enter file path to .nes cartridge file" << std::endl << "exiting" << std::endl; return 0; } else ROMfile = std::string(argv[1]); NES::Memory *memory = new NES::NESmemory(); ricoh2A03::CPU cpu(memory); ricoh2C02::PPU ppu(memory); NES::IO io(memory); memory->connectCPUandPPU(&cpu, &ppu); memory->initCartridge(ROMfile); cpu.rst(); ppu.rst(); const uint32_t frameMS = 1000 / FPS; uint32_t now = SDL_GetTicks(); uint32_t nextFrame; bool quit = false; bool pause = false; bool log = false; uint8_t clkMod3 = 0; while (!quit) { if (!pause) { nextFrame = now + frameMS; now = SDL_GetTicks(); if (now < nextFrame) SDL_Delay(nextFrame - now); do { ppu.tick(); if (clkMod3 == 0) { if (memory->DMAactive()) memory->handleDMA(); cpu.tick(!(memory->DMAactive())); memory->toggleCpuCycle(); } if (ppu.triggerNMI()) { cpu.nmi(); } if (memory->mapperIrqReq()) { cpu.irq(); memory->mapperIrqReset(); } memory->finalizeDMAreq(); if (clkMod3 >= 2) clkMod3 = 0; else clkMod3 += 1; } while (!ppu.frameComplete()); io.displayScreen(ppu.getScreen()); #ifdef DEBUG io.displayChrROM(ppu.getChrROM()); io.displayOAM(ppu.getOAM()); io.displayNT(ppu.getNT()); #endif } else SDL_Delay(frameMS); io.updateInputs(&quit, &pause, &log); #ifdef DEBUG cpu.enableLog(log); #endif } delete memory; return 0; #endif } // http://nesdev.com/NESDoc.pdf
29.047619
105
0.444918
dczang53
2b3f1f01eb71b5ded9477f9416a4ea0a425380cb
579
hpp
C++
include/TClosedBox.hpp
oldpocket/LoudSpeakerSystem
451447d00d00259405f2dd33ab0aa8425cc4ab89
[ "MIT" ]
null
null
null
include/TClosedBox.hpp
oldpocket/LoudSpeakerSystem
451447d00d00259405f2dd33ab0aa8425cc4ab89
[ "MIT" ]
null
null
null
include/TClosedBox.hpp
oldpocket/LoudSpeakerSystem
451447d00d00259405f2dd33ab0aa8425cc4ab89
[ "MIT" ]
null
null
null
/* This Unit contains class types, declarations and definitions related with the Closed Box Design calculations. */ #pragma once #include <cmath> #include "TBox.hpp" class TClosedBox: public TBox { public: TClosedBox(TDriver driver_); ~TClosedBox(); virtual TBoxResponse<float, 20, 200> getBoxResponse() override; virtual float getVb() override; virtual void setVb(float vb_) override; // Box Volume float vb; // Alpha float getA(); float getFC(); float getQTC(); // System cut-off frequency (f3) float getF3(); };
20.678571
81
0.666667
oldpocket
2b403645925453f3a89220dd9fe93c4f08b38fb9
262
cpp
C++
CodeForces/Magnets.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/Magnets.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/Magnets.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; vector<string> vec; int count = 0; vec.push_back("00"); for(int i = 1; i <= n; i++){ string s; cin>>s; if(s != vec[i-1]) count++; vec.push_back(s); } cout<<count<<endl; }
14.555556
29
0.561069
mysterio0801
2b471fb2e17827b938f5a521702b8d532b001da6
4,614
cpp
C++
NesSimulator/nessimulator.cpp
Embedfire/ebf_debian_qt_demo
91cd3e9328d7df1e481d2fc12bd83165ad025a80
[ "MIT" ]
1
2020-06-19T00:58:32.000Z
2020-06-19T00:58:32.000Z
NesSimulator/nessimulator.cpp
Embedfire/ebf_debian_qt_demo
91cd3e9328d7df1e481d2fc12bd83165ad025a80
[ "MIT" ]
null
null
null
NesSimulator/nessimulator.cpp
Embedfire/ebf_debian_qt_demo
91cd3e9328d7df1e481d2fc12bd83165ad025a80
[ "MIT" ]
null
null
null
/****************************************************************** Copyright (C) 2019 - All Rights Reserved by 文 件 名 : nessimulator.cpp --- 作 者 : Niyh(lynnhua) 论 坛 : http://www.firebbs.cn 编写日期 : 2019 说 明 : 历史纪录 : <作者> <日期> <版本> <内容> Niyh 2019 1.0.0 1 文件创建 *******************************************************************/ #include "nessimulator.h" #include "skin.h" #include <QPainter> #include <QMouseEvent> #include <QKeyEvent> #include <QApplication> #include <QFile> #include <QDebug> ////////////////////////////////////////////////////////////////////////////////////// SimulatorTitleBar::SimulatorTitleBar(QWidget *parent) : QtToolBar(parent) { m_strText = ""; this->setFixedHeight(50); m_rectBack = QRect(20, 10, 40, 40); } SimulatorTitleBar::~SimulatorTitleBar() { } void SimulatorTitleBar::SetText(const QString &text) { m_strText = text; this->update(); } void SimulatorTitleBar::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(this->rect(), QColor("#7f182E3A")); painter.drawPixmap(m_rectBack.topLeft(), QPixmap(":/images/photos/toolbar/ic_back.png")); painter.setPen("#ffffff"); painter.setFont(QFont(Skin::m_strAppFontNormal, 18)); painter.drawText(this->rect(), Qt::AlignCenter, m_strText); } void SimulatorTitleBar::mousePressEvent(QMouseEvent *e) { if (m_rectBack.contains(e->pos())) { emit signalBack(); } QWidget::mousePressEvent(e); } ////////////////////////////////////////////////////////////////////////////////////// NesGamePannel *s_gameWidgetPannel = NULL; NesSimulator::NesSimulator(QWidget *parent) : QtAnimationWidget(parent) { s_gameWidgetPannel = new NesGamePannel(this); m_titleBar = new SimulatorTitleBar(this); connect(m_titleBar, SIGNAL(signalBack()), this, SIGNAL(signalBackHome())); QString strFile = qApp->applicationDirPath() + "/nes/SuperMarie.nes"; if (QFile::exists(strFile)) { s_gameWidgetPannel->LoadGame(strFile); m_titleBar->SetText("SuperMarie.nes"); } } NesSimulator::~NesSimulator() { delete s_gameWidgetPannel; s_gameWidgetPannel = NULL; } void NesSimulator::resizeEvent(QResizeEvent *e) { s_gameWidgetPannel->resize(this->size()); s_gameWidgetPannel->move(0, 0); m_titleBar->setGeometry(0, -m_titleBar->height(), this->width(), m_titleBar->height()); QWidget::resizeEvent(e); } void NesSimulator::sendKeyPressed(QKeyEvent *event) { keyPressEvent(event); } void NesSimulator::sendKeyReleased(QKeyEvent *event) { keyReleaseEvent(event); } void NesSimulator::mousePressEvent(QMouseEvent *) { static bool bToolBarShow = false; bToolBarShow = !bToolBarShow; if (bToolBarShow) { m_titleBar->SetAnimation(QPoint(0, -m_titleBar->height()), QPoint(0, 0)); } else { m_titleBar->SetAnimation(QPoint(0, 0), QPoint(0, -m_titleBar->height())); } } void NesSimulator::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_W: s_gameWidgetPannel->setFlag(UP); break; case Qt::Key_S: s_gameWidgetPannel->setFlag(DOWN); break; case Qt::Key_A: s_gameWidgetPannel->setFlag(LEFT); break; case Qt::Key_D: s_gameWidgetPannel->setFlag(RIGHT); break; case Qt::Key_U: s_gameWidgetPannel->setFlag(A); break; case Qt::Key_I: s_gameWidgetPannel->setFlag(B); break; case Qt::Key_J: s_gameWidgetPannel->setFlag(C); break; case Qt::Key_K: case Qt::Key_Space: s_gameWidgetPannel->setFlag(D); break; } } void NesSimulator::keyReleaseEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_W: s_gameWidgetPannel->removeFlag(UP); break; case Qt::Key_S: s_gameWidgetPannel->removeFlag(DOWN); break; case Qt::Key_A: s_gameWidgetPannel->removeFlag(LEFT); break; case Qt::Key_D: s_gameWidgetPannel->removeFlag(RIGHT); break; case Qt::Key_U: s_gameWidgetPannel->removeFlag(A); break; case Qt::Key_I: s_gameWidgetPannel->removeFlag(B); break; case Qt::Key_J: s_gameWidgetPannel->removeFlag(C); break; case Qt::Key_K: case Qt::Key_Space: s_gameWidgetPannel->removeFlag(D); break; } }
25.776536
94
0.57629
Embedfire
2b4bd6bfd2f771bc9ff04accc47d40f286abae66
10,194
cpp
C++
soap/cmac-conversion/cmac_converter.cpp
OS-WASABI/CADG
b214edff82d4238e51569a42a6bdfab6806d768f
[ "BSD-3-Clause" ]
null
null
null
soap/cmac-conversion/cmac_converter.cpp
OS-WASABI/CADG
b214edff82d4238e51569a42a6bdfab6806d768f
[ "BSD-3-Clause" ]
22
2018-10-26T17:30:24.000Z
2019-04-15T23:38:18.000Z
soap/cmac-conversion/cmac_converter.cpp
OS-WASABI/CADG
b214edff82d4238e51569a42a6bdfab6806d768f
[ "BSD-3-Clause" ]
1
2019-03-23T16:02:17.000Z
2019-03-23T16:02:17.000Z
/// Converts any syntactically correct SOAP CAP document into a CMAC XML document. /** * * Copyright 2018 Vaniya Agrawal, Ross Arcemont, Kristofer Hoadley, * Shawn Hulce, Michael McCulley * * @file cmac_converter.cpp * @authors Ross Arcemont * @date January, 2019 */ #include <iostream> #include <string> #include <ctime> #include "cmac_converter.hpp" #include "../pugixml-1.9/src/pugixml.hpp" void CMAC::convert(std::string soap_filename, std::string cmac_filename) { // Obtaining the current date-time for later use. std::time_t time = std::time(0); std::tm* current_date_time = std::localtime(&time); std::string date_time_str = std::to_string((current_date_time->tm_year + 1900)) + '-' + std::to_string((current_date_time->tm_mon + 1)) + '-' + std::to_string(current_date_time->tm_mday) + 'T' + std::to_string(current_date_time->tm_hour) + ':' + std::to_string(current_date_time->tm_min) + ':' + std::to_string(current_date_time->tm_sec) + 'Z'; // Pulling the SOAP document into memory. pugi::xml_document soap_doc; pugi::xml_parse_result result = soap_doc.load_file(soap_filename.c_str()); pugi::xml_node cap_message = soap_doc.first_child().first_child().first_child(); // Creating the CMAC document and declaring its root node. pugi::xml_document cmac_doc; auto declaration_node = cmac_doc.append_child(pugi::node_declaration); declaration_node.append_attribute("version") = "1.0"; auto root_node = cmac_doc.append_child("CMAC_Alert_Attributes"); /** * Creating the node structure for the entire CMAC document. * All node variable names match the corresponding CMAC * structure as closely as possible. */ auto cmac_protocol_version = root_node.append_child("CMAC_protocol_version"); auto cmac_sending_gateway_id = root_node.append_child("CMAC_sending_gateway_id"); auto cmac_message_number = root_node.append_child("CMAC_message_number"); auto cmac_referenced_message_cap_identifier = root_node.append_child("CMAC_referenced_message_cap_identifier"); auto cmac_special_handling = root_node.append_child("CMAC_special_handling"); auto cmac_sender = root_node.append_child("CMAC_sender"); auto cmac_sent_date_time = root_node.append_child("CMAC_sent_date_time"); auto cmac_status = root_node.append_child("CMAC_status"); auto cmac_message_type = root_node.append_child("CMAC_message_type"); auto cmac_response_code = root_node.append_child("CMAC_response_code"); auto cmac_note = root_node.append_child("CMAC_note"); auto cmac_cap_alert_uri = root_node.append_child("CMAC_cap_alert_uri"); auto cmac_cap_identifier = root_node.append_child("CMAC_cap_identifier"); auto cmac_cap_sent_date_time = root_node.append_child("CMAC_cap_sent_date_time"); auto cmac_alert_info = root_node.append_child("CMAC_alert_info"); auto cmac_category = cmac_alert_info.append_child("CMAC_category"); auto cmac_event_code = cmac_alert_info.append_child("CMAC_event_code"); auto cmac_response_type = cmac_alert_info.append_child("CMAC_response_type"); auto cmac_severity = cmac_alert_info.append_child("CMAC_severity"); auto cmac_urgency = cmac_alert_info.append_child("CMAC_urgency"); auto cmac_certainty = cmac_alert_info.append_child("CMAC_certainty"); auto cmac_expires_date_time = cmac_alert_info.append_child("CMAC_expires_date_time"); auto cmac_sender_name = cmac_alert_info.append_child("CMAC_sender_name"); auto cmac_text_language = cmac_alert_info.append_child("CMAC_text_language"); auto cmac_text_alert_message_length = cmac_alert_info.append_child("CMAC_text_alert_message_length"); auto cmac_text_alert_message = cmac_alert_info.append_child("CMAC_text_alert_message"); auto cmac_alert_area = cmac_alert_info.append_child("CMAC_Alert_Area"); auto cmac_area_description = cmac_alert_area.append_child("CMAC_area_description"); auto cmac_polygon = cmac_alert_area.append_child("CMAC_polygon"); auto cmac_cmas_geocode = cmac_alert_area.append_child("CMAC_cmas_geocode"); // Creating geocode nodes and filling with content for (pugi::xml_node geocode = cap_message.child("info").child("area").first_child(); geocode; geocode = geocode.next_sibling()) { std::string node_name = geocode.name(); // std::cout << node_name << ' '; if (node_name.compare("geocode") == 0) { // std::cout << " made it "; auto cmac_cap_geocode = cmac_alert_area.append_child("CMAC_cap_geocode"); auto value_name = cmac_cap_geocode.append_child("valueName"); auto value = cmac_cap_geocode.append_child("value"); value_name.text().set(geocode.child("valueName").text().get()); value.text().set(geocode.child("value").text().get()); } } auto cmac_digital_signature = root_node.append_child("CMAC_Digital_Signature"); auto signature = cmac_digital_signature.append_child("Signature"); auto signed_info = signature.append_child("SignedInfo"); auto canonicalization_method = signed_info.append_child("CanonicalizationMethod"); auto signature_method = signed_info.append_child("SignatureMethod"); auto reference = signed_info.append_child("Reference"); auto transforms = reference.append_child("Transforms"); auto transform = transforms.append_child("Transform"); auto digest_method = reference.append_child("DigestMethod"); auto digest_value = reference.append_child("DigestValue"); auto signature_value = signature.append_child("SignatureValue"); auto key_info = signature.append_child("KeyInfo"); auto x509_data = key_info.append_child("X509Data"); auto x509_subject_name = x509_data.append_child("X509SubjectName"); auto x509_certificate = x509_data.append_child("X509Certificate"); // Setting values for all CMAC document nodes. cmac_protocol_version.text().set("1.0"); // TODO(Ross): Determine how to get gateway IP? cmac_sending_gateway_id.text().set(cap_message.child("sender").text().get()); // TODO(Ross): Determining how to identify CMSP-initiated value, when applicable. cmac_message_number.text().set(cap_message.child("identifier").text().get()); // TODO(Ross): Ensure correctness. cmac_special_handling.text().set(cap_message.child("scope").text().get()); cmac_sender.text().set(cap_message.child("sender").text().get()); cmac_sent_date_time.text().set(date_time_str.c_str()); cmac_status.text().set(cap_message.child("status").text().get()); cmac_message_type.text().set(cap_message.child("msgType").text().get()); cmac_response_code.text().set(cap_message.child("info").child("responseType").text().get()); if (cap_message.child("note")) { cmac_note.text().set(cap_message.child("note").text().get()); } cmac_cap_alert_uri.text().set("Temporary value"); // TODO(Ross): Determine how to obtain from the gateway. cmac_cap_identifier.text().set(cap_message.child("identifier").text().get()); cmac_cap_sent_date_time.text().set(cap_message.child("sent").text().get()); cmac_category.text().set(cap_message.child("info").child("category").text().get()); // TODO(Ross): Verify if this if-else is even necessary. std::string special_handling = cmac_special_handling.text().get(); if (special_handling.compare("Presidential") == 0) { cmac_event_code.text().set("EAN"); } else if (special_handling.compare("Child Abduction") == 0) { cmac_event_code.text().set("CAE"); } else if (special_handling.compare("Required Monthly Test") == 0) { cmac_event_code.text().set("RMT"); } cmac_response_type.text().set(cap_message.child("info").child("responseType").text().get()); cmac_severity.text().set(cap_message.child("info").child("severity").text().get()); cmac_urgency.text().set(cap_message.child("info").child("urgency").text().get()); cmac_certainty.text().set(cap_message.child("info").child("certainty").text().get()); cmac_expires_date_time.text().set(cap_message.child("info").child("expires").text().get()); cmac_sender_name.text().set(cap_message.child("info").child("senderName").text().get()); if (cap_message.child("language")) { cmac_text_language.text().set(cap_message.child("language").text().get()); } std::string alert_message = cap_message.child("info").child("description").text().get(); cmac_text_alert_message_length.text().set(alert_message.length()); cmac_text_alert_message.text().set(cap_message.child("info").child("description").text().get()); cmac_area_description.text().set(cap_message.child("info").child("area").child("areaDesc").text().get()); if (cap_message.child("info").child("area").child("polygon")) { cmac_polygon.text().set(cap_message.child("info").child("area").child("polygon").text().get()); } cmac_cmas_geocode.text().set(cap_message.child("info").child("area").child("polygon").text().get()); canonicalization_method.append_attribute("Algorithm"); canonicalization_method.attribute("Algorithm") = "http://www.w3.org/2001/10/xml-exc-c14n#"; signature_method.append_attribute("Algorithm"); signature_method.attribute("Algorithm") = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; reference.append_attribute("URI"); transform.append_attribute("Algorithm"); transform.attribute("Algorithm") = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; digest_method.append_attribute("Algorithm"); digest_method.attribute("Algorithm") = "http://www.w3.org/2001/04/xmlenc#sha256"; // Assigning temporary values for currently unknown information. digest_value.text().set("Temporary value"); signature_value.text().set("Temporary value"); x509_subject_name.text().set("Temporary value"); x509_certificate.text().set("Temporary value"); // Saving CMAC document. bool saved = cmac_doc.save_file(cmac_filename.c_str()); } // int main() { // CMAC::convert("soap_message_test.xml", "test.xml"); // }
50.97
115
0.716794
OS-WASABI
2b4c5f8bb872a9f732066a9dad757a5ae01b240a
496
cpp
C++
problems/firstDuplicate.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
53
2020-09-26T19:44:33.000Z
2021-09-30T20:38:52.000Z
problems/firstDuplicate.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
197
2020-08-25T18:13:56.000Z
2021-06-19T07:26:19.000Z
problems/firstDuplicate.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
204
2020-08-24T09:21:02.000Z
2022-02-13T06:13:42.000Z
#include<bits/stdc++.h> using namespace std; int findFirstDuplicate(int arr[]) { int sizeOfArray=sizeof(arr)/sizeof(arr[0]); unordered_set<int> store; for(int i=0;i<sizeOfArray;i++) { if(store.find(arr[i])!= store.end()) { return arr[i]; } store.insert(arr[i]); } return -1; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } cout<<findFirstDuplicate(arr); return 0; }
16.533333
47
0.528226
jaydulera
2b5237c255a5de724fc470e2350d94314a4dba8d
7,907
hh
C++
unisim/component/cxx/processor/arm/extregbank.hh
binsec/unisim_archisec
6556a45c180b6769dc1850ff3f695707d8835e90
[ "BSD-3-Clause" ]
null
null
null
unisim/component/cxx/processor/arm/extregbank.hh
binsec/unisim_archisec
6556a45c180b6769dc1850ff3f695707d8835e90
[ "BSD-3-Clause" ]
null
null
null
unisim/component/cxx/processor/arm/extregbank.hh
binsec/unisim_archisec
6556a45c180b6769dc1850ff3f695707d8835e90
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2007-2016, * Commissariat a l'Energie Atomique (CEA) * 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 CEA nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Yves Lhuillier (yves.lhuillier@cea.fr) */ #ifndef __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_EXTENSION_REGISTER_BANK_HH__ #define __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_EXTENSION_REGISTER_BANK_HH__ #include <stdexcept> #include <cstring> #include <inttypes.h> namespace unisim { namespace component { namespace cxx { namespace processor { namespace arm { template <typename T> struct ExtTypeInfo { enum { bytecount = sizeof (T) }; static void ToBytes( uint8_t* dst, T src ) { for (unsigned idx = 0; idx < sizeof (T); ++idx) { dst[idx] = src & 0xff; src >>= 8; } } static void FromBytes( T& dst, uint8_t const* src ) { T tmp = 0; for (unsigned idx = sizeof (T); idx-- > 0;) { tmp <<= 8; tmp |= uint32_t( src[idx] ); } dst = tmp; } }; template <> struct ExtTypeInfo<float> { enum bytecount_t { bytecount = 4 }; static void ToBytes( uint8_t* dst, float const& src ) { ExtTypeInfo<uint32_t>::ToBytes( dst, reinterpret_cast<uint32_t const&>( src ) ); } static void FromBytes( float& dst, uint8_t const* src ) { ExtTypeInfo<uint32_t>::FromBytes( reinterpret_cast<uint32_t&>( dst ), src ); } }; template <> struct ExtTypeInfo<double> { enum bytecount_t { bytecount = 8 }; static void ToBytes( uint8_t* dst, double const& src ) { ExtTypeInfo<uint64_t>::ToBytes( dst, reinterpret_cast<uint64_t const&>( src ) ); } static void FromBytes( double& dst, uint8_t const* src ) { ExtTypeInfo<uint64_t>::FromBytes( reinterpret_cast<uint64_t&>( dst ), src ); } }; enum ecstate_t { invalid = 0, valid = 1, exclusive = 3 }; struct Invalidate { unsigned start, size, bufsize; uint8_t buffer[16]; Invalidate( unsigned idx, unsigned _size ) : start( idx*_size ), size( _size ), bufsize( 0 ) {} }; struct Copy { unsigned start, size, mask; uint8_t* buffer; template <unsigned sizeT> Copy( unsigned idx, uint8_t (&_buffer) [sizeT] ) : start( idx*sizeT ), size( sizeT ), mask( 0 ), buffer( &_buffer[0] ) {} }; template <typename valT, unsigned countT> struct ExtRegCache { valT regs[countT]; uint8_t state[countT]; ExtRegCache() { for (unsigned idx = 0; idx < countT; ++idx) state[idx] = invalid; } enum regsize_t { regsize = ExtTypeInfo<valT>::bytecount }; void Do( Invalidate& inval ) { if (inval.start % inval.size) throw std::logic_error("Misaligned extended register manipulation"); unsigned idx = inval.start / regsize; if (idx >= countT) return; if (inval.size >= regsize) { if (inval.size % regsize) throw std::logic_error("Misaligned extended register manipulation"); unsigned end = idx + (inval.size / regsize); if (end > countT) throw std::logic_error("Misaligned extended register manipulation"); while (idx < end) { state[idx] = invalid; ++idx; } } else { if (regsize % inval.size) throw std::logic_error("Misaligned extended register manipulation"); if (state[idx] == invalid) return; state[idx] = invalid; if (inval.bufsize >= regsize) return; inval.bufsize = regsize; ExtTypeInfo<valT>::ToBytes( &inval.buffer[0], regs[idx] ); } } void Do( Copy& copy ) { if (copy.start % copy.size) throw std::logic_error("Misaligned extended register manipulation"); unsigned idx = copy.start / regsize; if (idx >= countT) return; if (copy.size == regsize) { if (state[idx] == invalid) return; state[idx] = valid; if (not copy.buffer) return; ExtTypeInfo<valT>::ToBytes( copy.buffer, regs[idx] ); copy.buffer = 0; } else if (copy.size > regsize) { if (copy.size % regsize) throw std::logic_error("Misaligned extended register manipulation"); unsigned end = idx + (copy.size / regsize); if (end > countT) throw std::logic_error("Misaligned extended register manipulation"); unsigned mask = ((1 << regsize) - 1); for (uint8_t* ptr = copy.buffer; idx < end; ++idx, ptr += regsize, mask <<= regsize) { if (state[idx] == invalid) continue; state[idx] = valid; if (not copy.buffer) continue; ExtTypeInfo<valT>::ToBytes( ptr, regs[idx] ); copy.mask |= mask; } if (copy.mask == unsigned((1 << copy.size)-1)) copy.buffer = 0; } else { if (regsize % copy.size) throw std::logic_error("Misaligned extended register manipulation"); if (state[idx] == invalid) return; state[idx] = valid; if (not copy.buffer) return; uint8_t buffer[regsize]; ExtTypeInfo<valT>::ToBytes( &buffer[0], regs[idx] ); std::memcpy( copy.buffer, &buffer[copy.start%regsize], copy.size ); copy.buffer = 0; } } template <typename dirT> valT const& GetReg( dirT& dir, unsigned idx ) { // Force validity if (state[idx] == invalid) { uint8_t buffer[regsize]; Copy copy( idx, buffer ); dir.DoAll( copy ); state[idx] = valid; ExtTypeInfo<valT>::FromBytes( regs[idx], &buffer[0] ); } return regs[idx]; } template <typename dirT> void SetReg( dirT& dir, unsigned idx, valT const& value ) { // Force exclusivity if (state[idx] != exclusive) { Invalidate invalidate( idx, regsize ); dir.DoAll( invalidate ); if (invalidate.bufsize) { for (unsigned count = invalidate.bufsize / regsize, vidx = idx & ~(count - 1), end = vidx + count; vidx < end; ++vidx) { if (state[vidx] != invalid) continue; ExtTypeInfo<valT>::FromBytes( regs[vidx], &invalidate.buffer[vidx*regsize] ); state[vidx] = valid; } } state[idx] = exclusive; } regs[idx] = value; } }; } // end of namespace arm } // end of namespace processor } // end of namespace cxx } // end of namespace component } // end of namespace unisim #endif /* __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_EXTENSION_REGISTER_BANK_HH__ */
36.606481
143
0.626786
binsec
2b59007c7794c7efdec9811e67c216d3573fed42
24,468
cpp
C++
magic3d/src/script/script_magic3d.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
4
2016-03-25T23:35:08.000Z
2019-05-15T18:56:07.000Z
magic3d/src/script/script_magic3d.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
null
null
null
magic3d/src/script/script_magic3d.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
2
2016-03-17T09:01:12.000Z
2020-01-18T13:04:05.000Z
/****************************************************************************** @Copyright Copyright (C) 2008 - 2016 by MagicTech. @Platform ANSI compatible ******************************************************************************/ /* Magic3D Engine Copyright (c) 2008-2016 Thiago C. Moraes http://www.magictech.com.br 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 <magic3d/script/script_magic3d.h> #include <magic3d/magic3d.h> const char Magic3D::ScriptMagic3D::className[] = "Magic3D"; Magic3D::ScriptClass<Magic3D::ScriptMagic3D>::ScriptEnum Magic3D::ScriptMagic3D::enums[] = {{NULL, 0}}; Magic3D::ScriptClass<Magic3D::ScriptMagic3D>::ScriptFunction Magic3D::ScriptMagic3D::functions[] = { ScriptClassFunction(ScriptMagic3D, getPlatform, "string getPlatform()", "Return the current platform."), ScriptClassFunction(ScriptMagic3D, isMobile, "bool isMobile()", "Return true if running in a mobile device."), ScriptClassFunction(ScriptMagic3D, getObject, "Object* getObject(string name)", "Get an object from scene by name."), ScriptClassFunction(ScriptMagic3D, setCamera3D, "void setCamera3D(string name)", "Set current perspective camera."), ScriptClassFunction(ScriptMagic3D, setCamera2D, "void setCamera2D(string name)", "Set current orthographic camera."), ScriptClassFunction(ScriptMagic3D, setLayerVisible, "void setLayerVisible(string name, bool visible)", "Set the visibility of a layer."), ScriptClassFunction(ScriptMagic3D, isLayerVisible, "bool isLayerVisible()", "Get the visibility of a layer."), ScriptClassFunction(ScriptMagic3D, setRelativeMouseMode, "void setRelativeMouseMode(bool relative)", "Set the mouse position relative."), ScriptClassFunction(ScriptMagic3D, getCursorX, "int getCursorX()", "Get the cursor X position."), ScriptClassFunction(ScriptMagic3D, getCursorY, "int getCursorY()", "Get the cursor Y position."), ScriptClassFunction(ScriptMagic3D, setWindowWidth, "void setWindowWidth(int width)", "Set the window width."), ScriptClassFunction(ScriptMagic3D, getWindowWidth, "int getWindowWidth()", "Get the window width."), ScriptClassFunction(ScriptMagic3D, setWindowHeight, "void setWindowHeight(int height)", "Set the window height."), ScriptClassFunction(ScriptMagic3D, getWindowHeight, "int getWindowHeight()", "Get the window height."), ScriptClassFunction(ScriptMagic3D, getWindowAspectX, "void getWindowAspectX()", "Get the window horizontal aspect."), ScriptClassFunction(ScriptMagic3D, getWindowAspectY, "void getWindowAspectY()", "Get the window vertical aspect."), ScriptClassFunction(ScriptMagic3D, getTicks, "float getTicks()", "Get the current time in miliseconds."), ScriptClassFunction(ScriptMagic3D, getElapsedTime, "float getElapsedTime()", "Get the elapsed time since last update."), ScriptClassFunction(ScriptMagic3D, getElapsedTimeReal, "float getElapsedTimeReal()", "Get the elapsed time since last update without scale."), ScriptClassFunction(ScriptMagic3D, getTimeSinceStart, "float getTimeSinceStart()", "Get the elapsed time since the start."), ScriptClassFunction(ScriptMagic3D, getTimeScale, "float getTimeScale()", "Get the time scale."), ScriptClassFunction(ScriptMagic3D, setTimeScale, "float setTimeScale(float scale)", "Set the time scale."), ScriptClassFunction(ScriptMagic3D, pick, "Object* pick(string camera, float x, float y, int viewport, bool all)", "Pick an object."), ScriptClassFunction(ScriptMagic3D, getPosition2D, "Vector3 getPosition2D(Vector3 position, int viewport)", "Get 2D position."), ScriptClassFunction(ScriptMagic3D, getPosition3D, "Vector3 getPosition3D(float x, float y, float depth, int viewport)", "Get 3D position."), ScriptClassFunction(ScriptMagic3D, getPosition3DOnPlane, "Vector3 getPosition3DOnPlane(float x, float y, Vector3 planeNormal, Vector3 planePosition, int viewport)", "Get 3D position on a plane."), ScriptClassFunction(ScriptMagic3D, log, "void log(const char* text)", "Write a message in the log file."), ScriptClassFunction(ScriptMagic3D, loadScene, "void loadScene(string mge)", "Load scene closing current."), ScriptClassFunction(ScriptMagic3D, loadSceneAdditive, "loadSceneAdditive(string mge)", "Load scene without clear current."), ScriptClassFunction(ScriptMagic3D, loadConfig, "void loadConfig()", "Load configuration file."), ScriptClassFunction(ScriptMagic3D, saveConfig, "void saveConfig()", "Save configuration file."), ScriptClassFunction(ScriptMagic3D, isConfigEmpty, "bool isConfigEmpty()", "Return true if configuration is empty."), ScriptClassFunction(ScriptMagic3D, clearConfig, "void clearConfig()", "Clear all configurations."), ScriptClassFunction(ScriptMagic3D, setConfigInteger, "void setConfigInteger(string key, int value)", "Set a configuration value."), ScriptClassFunction(ScriptMagic3D, setConfigFloat, "void setConfigFloat(string key, float value)", "Set a configuration value."), ScriptClassFunction(ScriptMagic3D, setConfigBoolean, "void setConfigBoolean(string key, bool value)", "Set a configuration value."), ScriptClassFunction(ScriptMagic3D, setConfigString, "void setConfigString(string key, string value)", "Set a configuration value."), ScriptClassFunction(ScriptMagic3D, getConfigInteger, "int getConfigInteger(string key)", "Get a configuration value."), ScriptClassFunction(ScriptMagic3D, getConfigFloat, "float getConfigFloat(string key)", "Get a configuration value."), ScriptClassFunction(ScriptMagic3D, getConfigBoolean, "bool getConfigBoolean(string key)", "Get a configuration value."), ScriptClassFunction(ScriptMagic3D, getConfigString, "string getConfigString(string key)", "Get a configuration value."), ScriptClassFunction(ScriptMagic3D, isConfigured, "bool isConfigured(string key)", "Return true if configuration key is found."), ScriptClassFunction(ScriptMagic3D, debugLine, "void debugLine(Vector3 pos1, Vector3 pos2, bool orthographic, Color color)", "Render a debug line."), ScriptClassFunction(ScriptMagic3D, rayCastObject, "Object* rayCastObject(Vector3 start, Vector3 end, bool orthographic)", ""), ScriptClassFunction(ScriptMagic3D, rayCastPoint, "Vector3 rayCastPoint(Vector3 start, Vector3 end, bool orthographic)", ""), ScriptClassFunction(ScriptMagic3D, rayCastNormal, "Vector3 rayCastNormal(Vector3 start, Vector3 end, bool orthographic)", ""), ScriptClassFunction(ScriptMagic3D, rotateCamera, "void rotateCamera(float x, float y, float z, bool rotate)", ""), ScriptClassFunction(ScriptMagic3D, setStereoscopy, "void setStereoscopy(bool stereoscopy, bool screenEffects)", ""), ScriptClassFunction(ScriptMagic3D, connect, "void connect(string ip, int port)", ""), ScriptClassFunction(ScriptMagic3D, disconnect, "void disconnect(bool now)", ""), ScriptClassFunction(ScriptMagic3D, isConnected, "bool isConnected()", ""), ScriptClassFunction(ScriptMagic3D, setNick, "void setNick(string nick)", ""), ScriptClassFunction(ScriptMagic3D, getNick, "string getNick()", ""), ScriptClassFunction(ScriptMagic3D, sendCommand, "void sendCommand(string command, string value)", ""), ScriptClassFunction(ScriptMagic3D, sendText, "void sendText(string text)", ""), ScriptClassFunction(ScriptMagic3D, spawnNetworkObject, "Object* spawnNetworkObject(string name)", ""), ScriptClassFunction(ScriptMagic3D, sendObject, "void sendObject(string name)", ""), ScriptClassFunction(ScriptMagic3D, sendInput, "void sendInput(int input, int event, float x, float y, float z, float w)", ""), ScriptClassFunction(ScriptMagic3D, getObjectNick, "string getObjectNick(string name)", ""), {NULL, NULL, NULL, NULL} }; Magic3D::ScriptMagic3D::ScriptMagic3D(lua_State *lua) : ScriptBasic(className) { if (lua) { } } Magic3D::ScriptMagic3D::~ScriptMagic3D() { } int Magic3D::ScriptMagic3D::getPlatform(lua_State *lua) { lua_pushstring(lua, Magic3D::getInstance()->getPlatform().c_str()); return 1; } int Magic3D::ScriptMagic3D::isMobile(lua_State *lua) { lua_pushboolean(lua, Magic3D::getInstance()->isMobile()); return 1; } int Magic3D::ScriptMagic3D::getObject(lua_State *lua) { Object* object = ResourceManager::getObjects()->get(luaL_checkstring(lua, 1)); if (object) { ScriptObject* obj = new ScriptObject(object); ScriptClass<ScriptObject>::push(lua, obj, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::setCamera3D(lua_State *lua) { Object* object = ResourceManager::getObjects()->get(luaL_checkstring(lua, 1)); if (object && object->getType() == eOBJECT_CAMERA) { Renderer::getInstance()->getCurrentViewPort()->setPerspective(static_cast<Camera*>(object)); } else { Log::log(eLOG_FAILURE, "Invalid Camera!"); } return 0; } int Magic3D::ScriptMagic3D::setCamera2D(lua_State *lua) { Object* object = ResourceManager::getObjects()->get(luaL_checkstring(lua, 1)); if (object && object->getType() == eOBJECT_CAMERA) { Renderer::getInstance()->getCurrentViewPort()->setOrthographic(static_cast<Camera*>(object)); } else { Log::log(eLOG_FAILURE, "Invalid Camera!"); } return 0; } int Magic3D::ScriptMagic3D::setLayerVisible(lua_State *lua) { std::string layerName = luaL_checkstring(lua, 1); bool visible = lua_toboolean(lua, 2); Layer* layer = Scene::getInstance()->getLayer(layerName); if (layer) { layer->setVisible(visible); } return 0; } int Magic3D::ScriptMagic3D::isLayerVisible(lua_State *lua) { std::string layerName = luaL_checkstring(lua, 1); Layer* layer = Scene::getInstance()->getLayer(layerName); if (layer) { lua_pushboolean(lua, layer->isVisible()); } return 1; } int Magic3D::ScriptMagic3D::setRelativeMouseMode(lua_State *lua) { Renderer::getInstance()->getWindow()->setRelativeMouseMode(lua_toboolean(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::getCursorX(lua_State *lua) { lua_pushinteger(lua, Renderer::getInstance()->getWindow()->getCursorX()); return 1; } int Magic3D::ScriptMagic3D::getCursorY(lua_State *lua) { lua_pushinteger(lua, Renderer::getInstance()->getWindow()->getCursorY()); return 1; } int Magic3D::ScriptMagic3D::setWindowWidth(lua_State *lua) { Renderer::getInstance()->getWindow()->resize(luaL_checkinteger(lua, 1), Renderer::getInstance()->getWindow()->getHeight()); return 0; } int Magic3D::ScriptMagic3D::getWindowWidth(lua_State *lua) { lua_pushinteger(lua, Renderer::getInstance()->getWindow()->getWidth()); return 1; } int Magic3D::ScriptMagic3D::setWindowHeight(lua_State *lua) { Renderer::getInstance()->getWindow()->resize(Renderer::getInstance()->getWindow()->getWidth(), luaL_checkinteger(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::getWindowHeight(lua_State *lua) { lua_pushinteger(lua, Renderer::getInstance()->getWindow()->getHeight()); return 1; } int Magic3D::ScriptMagic3D::getWindowAspectX(lua_State *lua) { lua_pushnumber(lua, Renderer::getInstance()->getWindow()->getWindowScreenAspect().getX()); return 1; } int Magic3D::ScriptMagic3D::getWindowAspectY(lua_State *lua) { lua_pushnumber(lua, Renderer::getInstance()->getWindow()->getWindowScreenAspect().getY()); return 1; } int Magic3D::ScriptMagic3D::getTicks(lua_State *lua) { lua_pushnumber(lua, Magic3D::getInstance()->getTicks()); return 1; } int Magic3D::ScriptMagic3D::getElapsedTime(lua_State *lua) { lua_pushnumber(lua, Magic3D::getInstance()->getElapsedTime()); return 1; } int Magic3D::ScriptMagic3D::getElapsedTimeReal(lua_State *lua) { lua_pushnumber(lua, Magic3D::getInstance()->getElapsedTimeReal()); return 1; } int Magic3D::ScriptMagic3D::getTimeSinceStart(lua_State *lua) { lua_pushnumber(lua, Magic3D::getInstance()->getTimeSinceStart()); return 1; } int Magic3D::ScriptMagic3D::getTimeScale(lua_State *lua) { lua_pushnumber(lua, Magic3D::getInstance()->getTimeScale()); return 1; } int Magic3D::ScriptMagic3D::setTimeScale(lua_State *lua) { Magic3D::getInstance()->setTimeScale(luaL_checknumber(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::pick(lua_State *lua) { Object* object = ResourceManager::getObjects()->get(luaL_checkstring(lua, 1)); if (object && object->getType() == eOBJECT_CAMERA) { Camera* camera = static_cast<Camera*>(object); Object* picked = camera->pick(luaL_checknumber(lua, 2), luaL_checknumber(lua, 3), luaL_checkinteger(lua, 4), lua_toboolean(lua, 5)); if (picked) { ScriptObject* obj = new ScriptObject(picked); ScriptClass<ScriptObject>::push(lua, obj, true); } else { lua_pushnil(lua); } } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::getPosition2D(lua_State *lua) { ViewPort* view = Renderer::getInstance()->getViewPort(luaL_checkinteger(lua, 2)); if (view && view->getPerspective()) { Camera* camera = view->getPerspective(); ScriptVector3* vector = ScriptClass<ScriptVector3>::check(lua, 1); ScriptVector3* vec = new ScriptVector3(camera->getPosition2D(vector->getValue(), view)); ScriptClass<ScriptVector3>::push(lua, vec, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::getPosition3D(lua_State *lua) { ViewPort* view = Renderer::getInstance()->getViewPort(luaL_checkinteger(lua, 4)); if (view && view->getPerspective()) { Camera* camera = view->getPerspective(); ScriptVector3* vec = new ScriptVector3(camera->getPosition3D(luaL_checknumber(lua, 1), luaL_checknumber(lua, 2), luaL_checknumber(lua, 3), view)); ScriptClass<ScriptVector3>::push(lua, vec, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::getPosition3DOnPlane(lua_State *lua) { ViewPort* view = Renderer::getInstance()->getViewPort(luaL_checkinteger(lua, 5)); if (view && view->getPerspective()) { Camera* camera = view->getPerspective(); ScriptVector3* pN = ScriptClass<ScriptVector3>::check(lua, 3); ScriptVector3* pP = ScriptClass<ScriptVector3>::check(lua, 4); ScriptVector3* vec = new ScriptVector3(camera->getPosition3DOnPlane(luaL_checknumber(lua, 1), luaL_checknumber(lua, 2), pN->getValue(), pP->getValue(), view)); ScriptClass<ScriptVector3>::push(lua, vec, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::log(lua_State *lua) { Log::log(eLOG_FAILURE, luaL_checkstring(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::loadScene(lua_State *lua) { std::string path(luaL_checkstring(lua, 1)); Magic3D::getInstance()->loadScene(path); return 0; } int Magic3D::ScriptMagic3D::loadSceneAdditive(lua_State *lua) { std::string path(luaL_checkstring(lua, 1)); Magic3D::getInstance()->loadSceneAdditive(path); return 0; } int Magic3D::ScriptMagic3D::isConfigEmpty(lua_State *lua) { lua_pushboolean(lua, Config::getInstance()->isEmpty()); return 1; } int Magic3D::ScriptMagic3D::clearConfig(lua_State *lua) { if (lua) { } Config::getInstance()->clear(); return 0; } int Magic3D::ScriptMagic3D::loadConfig(lua_State *lua) { if (lua) { } Config::getInstance()->load(); return 0; } int Magic3D::ScriptMagic3D::saveConfig(lua_State *lua) { if (lua) { } Config::getInstance()->save(); return 0; } int Magic3D::ScriptMagic3D::setConfigInteger(lua_State *lua) { Config::getInstance()->setInteger(luaL_checkstring(lua, 1), luaL_checkinteger(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::setConfigFloat(lua_State *lua) { Config::getInstance()->setFloat(luaL_checkstring(lua, 1), luaL_checknumber(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::setConfigBoolean(lua_State *lua) { Config::getInstance()->setBoolean(luaL_checkstring(lua, 1), lua_toboolean(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::setConfigString(lua_State *lua) { Config::getInstance()->setString(luaL_checkstring(lua, 1), luaL_checkstring(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::getConfigInteger(lua_State *lua) { lua_pushinteger(lua, Config::getInstance()->getInteger(luaL_checkstring(lua, 1))); return 1; } int Magic3D::ScriptMagic3D::getConfigFloat(lua_State *lua) { lua_pushnumber(lua, Config::getInstance()->getFloat(luaL_checkstring(lua, 1))); return 1; } int Magic3D::ScriptMagic3D::getConfigBoolean(lua_State *lua) { lua_pushboolean(lua, Config::getInstance()->getBoolean(luaL_checkstring(lua, 1))); return 1; } int Magic3D::ScriptMagic3D::getConfigString(lua_State *lua) { lua_pushstring(lua, Config::getInstance()->getString(luaL_checkstring(lua, 1)).c_str()); return 1; } int Magic3D::ScriptMagic3D::isConfigured(lua_State *lua) { lua_pushboolean(lua, Config::getInstance()->isConfigured(luaL_checkstring(lua, 1))); return 1; } int Magic3D::ScriptMagic3D::debugLine(lua_State *lua) { ScriptVector3* l1 = ScriptClass<ScriptVector3>::check(lua, 1); ScriptVector3* l2 = ScriptClass<ScriptVector3>::check(lua, 2); bool ortho = lua_toboolean(lua, 3); ScriptColor* color = ScriptClass<ScriptColor>::check(lua, 4); Renderer::getInstance()->addLine(l1->getValue(), l2->getValue(), ortho, color->getValue()); return 0; } int Magic3D::ScriptMagic3D::rayCastObject(lua_State *lua) { ScriptVector3* start = ScriptClass<ScriptVector3>::check(lua, 1); ScriptVector3* end = ScriptClass<ScriptVector3>::check(lua, 2); RayCastReturn ray = Physics::getInstance()->rayCast(start->getValue(), end->getValue(), lua_toboolean(lua, 3)); if (ray.physicsObject) { ScriptObject* obj = new ScriptObject(static_cast<Object*>(ray.physicsObject)); ScriptClass<ScriptObject>::push(lua, obj, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::rayCastPoint(lua_State *lua) { ScriptVector3* start = ScriptClass<ScriptVector3>::check(lua, 1); ScriptVector3* end = ScriptClass<ScriptVector3>::check(lua, 2); RayCastReturn ray = Physics::getInstance()->rayCast(start->getValue(), end->getValue(), lua_toboolean(lua, 3)); if (ray.physicsObject) { ScriptVector3* point = new ScriptVector3(ray.point); ScriptClass<ScriptVector3>::push(lua, point, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::rayCastNormal(lua_State *lua) { ScriptVector3* start = ScriptClass<ScriptVector3>::check(lua, 1); ScriptVector3* end = ScriptClass<ScriptVector3>::check(lua, 2); RayCastReturn ray = Physics::getInstance()->rayCast(start->getValue(), end->getValue(), lua_toboolean(lua, 3)); if (ray.physicsObject) { ScriptVector3* normal = new ScriptVector3(ray.normal); ScriptClass<ScriptVector3>::push(lua, normal, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::rotateCamera(lua_State* lua) { float angleX = luaL_checknumber(lua, 1); float angleY = luaL_checknumber(lua, 2); float angleZ = luaL_checknumber(lua, 3); bool rotate = lua_toboolean(lua, 4); Quaternion ax = Quaternion::rotationX(Math::radians(angleX)); Quaternion ay = Quaternion::rotationY(Math::radians(angleY)); Quaternion az = Quaternion::rotationY(Math::radians(angleZ)); Camera* camera = Renderer::getInstance()->getCurrentViewPort()->getPerspective(); if (camera) { if (rotate) { camera->setRotation(ay * (camera->getRotation() * ax)); } else { camera->setRotation(az * ay * ax); } } return 0; } int Magic3D::ScriptMagic3D::setStereoscopy(lua_State* lua) { float stereoscopy = lua_toboolean(lua, 1); float screenEffects = lua_toboolean(lua, 2); Magic3D::getInstance()->setStereoscopy(stereoscopy); Material* material = ResourceManager::getMaterials()->get("screen"); if (material) { MaterialVar_Boolean* mb = static_cast<MaterialVar_Boolean*>(material->getVar("stereoscopy")); if (mb) { mb->setValue(0, stereoscopy); } } Renderer::getInstance()->setUsingScreenEffects(screenEffects); return 0; } int Magic3D::ScriptMagic3D::connect(lua_State* lua) { Network::getInstance()->connect(luaL_checkstring(lua, 1), luaL_checkinteger(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::disconnect(lua_State* lua) { Network::getInstance()->disconnect(lua_toboolean(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::isConnected(lua_State* lua) { lua_pushboolean(lua, Network::getInstance()->isConnected()); return 1; } int Magic3D::ScriptMagic3D::setNick(lua_State* lua) { Network::getInstance()->setNick(luaL_checkstring(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::getNick(lua_State* lua) { lua_pushstring(lua, Network::getInstance()->getNick().c_str()); return 1; } int Magic3D::ScriptMagic3D::sendCommand(lua_State* lua) { Network::getInstance()->sendCommand(luaL_checkstring(lua, 1), luaL_checkstring(lua, 2)); return 0; } int Magic3D::ScriptMagic3D::sendText(lua_State* lua) { Network::getInstance()->sendText(luaL_checkstring(lua, 1)); return 0; } int Magic3D::ScriptMagic3D::spawnNetworkObject(lua_State* lua) { Object* object = Network::getInstance()->spawnObject(luaL_checkstring(lua, 1)); if (object) { Script::getInstance()->addToTemp(object); ScriptObject* obj = new ScriptObject(object); ScriptClass<ScriptObject>::push(lua, obj, true); } else { lua_pushnil(lua); } return 1; } int Magic3D::ScriptMagic3D::sendObject(lua_State* lua) { Object* object = ResourceManager::getObjects()->get(luaL_checkstring(lua, 1)); if (object) { Network::getInstance()->sendObject(object, true); } return 0; } int Magic3D::ScriptMagic3D::sendInput(lua_State* lua) { INPUT input = (INPUT)luaL_checkinteger(lua, 1); EVENT event = EVENT(luaL_checkinteger(lua, 2)); float x = luaL_checknumber(lua, 3); float y = luaL_checknumber(lua, 4); float z = luaL_checknumber(lua, 5); float w = luaL_checknumber(lua, 6); Input::getInstance()->dispatchEvent(input, event, x, y, z, w); return 0; } int Magic3D::ScriptMagic3D::getObjectNick(lua_State* lua) { enet_uint32 id = Network::getInstance()->getObjectClientID(luaL_checkstring(lua, 1)); lua_pushstring(lua, Network::getInstance()->getClientNick(id).c_str()); return 1; }
34.755682
201
0.681257
magic-tech
2b59be3d91eaccae8af04d68df0de189c30c8365
378
hpp
C++
nbv_planner/include/nbv_planner/octomap_reset_node.hpp
cbw36/yak
8d7c7048f366afcf1c4d9e55db187c6c66410a47
[ "MIT" ]
26
2017-11-01T20:25:54.000Z
2020-10-19T17:39:18.000Z
nbv_planner/include/nbv_planner/octomap_reset_node.hpp
cbw36/yak
8d7c7048f366afcf1c4d9e55db187c6c66410a47
[ "MIT" ]
16
2017-07-05T20:28:20.000Z
2019-06-07T22:21:01.000Z
nbv_planner/include/nbv_planner/octomap_reset_node.hpp
cbw36/yak
8d7c7048f366afcf1c4d9e55db187c6c66410a47
[ "MIT" ]
10
2017-06-27T16:05:35.000Z
2021-04-06T07:55:49.000Z
#include <ros/ros.h> #include <visualization_msgs/InteractiveMarkerFeedback.h> #include <std_srvs/Empty.h> class OctomapResetter { public: OctomapResetter(ros::NodeHandle& nh); void UpdateCallback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr& feedback); ros::Subscriber volume_update_subscriber_; ros::ServiceClient volume_reset_client_; private: };
22.235294
93
0.806878
cbw36
2b615bb170e49a765bcb1aadccf75d3315e01fee
1,206
hpp
C++
libraries/protocol/include/deip/protocol/operations/create_research_operation.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/protocol/include/deip/protocol/operations/create_research_operation.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/protocol/include/deip/protocol/operations/create_research_operation.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
#pragma once #include <deip/protocol/base.hpp> #include <deip/protocol/block_header.hpp> #include <deip/protocol/version.hpp> #include <fc/optional.hpp> namespace deip { namespace protocol { using deip::protocol::percent; using deip::protocol::external_id_type; struct create_research_operation : public entity_operation { external_id_type external_id; account_name_type account; string description; flat_set<external_id_type> disciplines; bool is_private; optional<percent> review_share; // deprecated optional<percent> compensation_share; // deprecated optional<flat_set<account_name_type>> members; // deprecated extensions_type extensions; string entity_id() const { return "external_id"; } external_id_type get_entity_id() const { return external_id; } void validate() const; void get_required_active_authorities(flat_set<account_name_type>& a) const { a.insert(account); } }; } } FC_REFLECT(deip::protocol::create_research_operation, (external_id) (account) (description) (disciplines) (is_private) (review_share) // deprecated (compensation_share) // deprecated (members) // deprecated (extensions) )
24.12
78
0.737977
DEIPworld
2b68e4718afc13a2fbd75b28d710b0585614149c
4,541
cpp
C++
shared/test/unit_test/gen8/test_device_caps_gen8.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/unit_test/gen8/test_device_caps_gen8.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/unit_test/gen8/test_device_caps_gen8.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/helpers/hw_helper.h" #include "shared/test/common/fixtures/device_fixture.h" #include "shared/test/common/test_macros/test.h" using namespace NEO; using Gen8DeviceCaps = Test<DeviceFixture>; GEN8TEST_F(Gen8DeviceCaps, GivenDefaultWhenCheckingPreemptionModeThenDisabledIsReported) { EXPECT_TRUE(PreemptionMode::Disabled == pDevice->getHardwareInfo().capabilityTable.defaultPreemptionMode); } GEN8TEST_F(Gen8DeviceCaps, BdwProfilingTimerResolution) { const auto &caps = pDevice->getDeviceInfo(); EXPECT_EQ(80u, caps.outProfilingTimerResolution); } GEN8TEST_F(Gen8DeviceCaps, givenHwInfoWhenRequestedComputeUnitsUsedForScratchThenReturnValidValue) { const auto &hwInfo = pDevice->getHardwareInfo(); auto &hwHelper = HwHelper::get(hwInfo.platform.eRenderCoreFamily); uint32_t expectedValue = hwInfo.gtSystemInfo.MaxSubSlicesSupported * hwInfo.gtSystemInfo.MaxEuPerSubSlice * hwInfo.gtSystemInfo.ThreadCount / hwInfo.gtSystemInfo.EUCount; EXPECT_EQ(expectedValue, hwHelper.getComputeUnitsUsedForScratch(&hwInfo)); EXPECT_EQ(expectedValue, pDevice->getDeviceInfo().computeUnitsUsedForScratch); } GEN8TEST_F(Gen8DeviceCaps, givenHwInfoWhenRequestedMaxFrontEndThreadsThenReturnValidValue) { const auto &hwInfo = pDevice->getHardwareInfo(); EXPECT_EQ(HwHelper::getMaxThreadsForVfe(hwInfo), pDevice->getDeviceInfo().maxFrontEndThreads); } GEN8TEST_F(Gen8DeviceCaps, GivenBdwWhenCheckftr64KBpagesThenFalse) { EXPECT_FALSE(defaultHwInfo->capabilityTable.ftr64KBpages); } GEN8TEST_F(Gen8DeviceCaps, GivenDefaultSettingsWhenCheckingPreemptionModeThenPreemptionIsDisabled) { EXPECT_TRUE(PreemptionMode::Disabled == pDevice->getHardwareInfo().capabilityTable.defaultPreemptionMode); } GEN8TEST_F(Gen8DeviceCaps, WhenCheckingKmdNotifyMechanismThenPropertiesAreSetCorrectly) { EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.enableKmdNotify); EXPECT_EQ(50000, pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds); EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.enableQuickKmdSleep); EXPECT_EQ(5000, pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds); EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.enableQuickKmdSleepForSporadicWaits); EXPECT_EQ(200000, pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.delayQuickKmdSleepForSporadicWaitsMicroseconds); EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.enableQuickKmdSleepForDirectSubmission); EXPECT_EQ(0, pDevice->getHardwareInfo().capabilityTable.kmdNotifyProperties.delayQuickKmdSleepForDirectSubmissionMicroseconds); } GEN8TEST_F(Gen8DeviceCaps, WhenCheckingCompressionThenItIsDisabled) { EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.ftrRenderCompressedBuffers); EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.ftrRenderCompressedImages); } GEN8TEST_F(Gen8DeviceCaps, WhenCheckingImage3dDimensionsThenCapsAreSetCorrectly) { const auto &sharedCaps = pDevice->getDeviceInfo(); EXPECT_EQ(2048u, sharedCaps.image3DMaxDepth); } GEN8TEST_F(Gen8DeviceCaps, givenHwInfoWhenSlmSizeIsRequiredThenReturnCorrectValue) { EXPECT_EQ(64u, pDevice->getHardwareInfo().capabilityTable.slmSize); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckSupportCacheFlushAfterWalkerThenFalse) { EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.supportCacheFlushAfterWalker); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckBlitterOperationsSupportThenReturnFalse) { EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.blitterOperationsSupported); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckFtrSupportsInteger64BitAtomicsThenReturnTrue) { EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.ftrSupportsInteger64BitAtomics); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckingImageSupportThenReturnTrue) { EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.supportsImages); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckingMediaBlockSupportThenReturnTrue) { EXPECT_TRUE(pDevice->getHardwareInfo().capabilityTable.supportsMediaBlock); } GEN8TEST_F(Gen8DeviceCaps, givenGen8WhenCheckingDeviceEnqueueSupportThenReturnFalse) { EXPECT_FALSE(pDevice->getHardwareInfo().capabilityTable.supportsDeviceEnqueue); }
46.814433
133
0.834398
mattcarter2017
2b72c99827866390bf6838cbc4e52529c4efbe6d
3,667
cpp
C++
src/av6/oop_av63.cpp
finki-mk/OOP
6b75df2dfe7911763b67788c0b4063807743866a
[ "MIT" ]
4
2017-09-15T09:40:30.000Z
2022-02-26T07:38:31.000Z
src/av6/oop_av63.cpp
finki-mk/OOP
6b75df2dfe7911763b67788c0b4063807743866a
[ "MIT" ]
2
2017-03-01T20:53:50.000Z
2017-04-15T20:27:15.000Z
src/av6/oop_av63.cpp
finki-mk/OOP
6b75df2dfe7911763b67788c0b4063807743866a
[ "MIT" ]
6
2017-02-17T23:49:07.000Z
2021-02-23T12:43:38.000Z
#include <iostream> #include <string.h> #define MAX 100 using namespace std; class Ucenik { private: char *ime; float prosek; int godina; public: Ucenik (const char* ii = "", float pp = 0, int gg = 0) { ime = new char[strlen(ii) + 1]; strcpy (ime, ii); prosek = pp; godina = gg; } Ucenik (const Ucenik& u) { ime = new char[strlen(u.ime) ]; strcpy (ime , u.ime); prosek = u.prosek; godina = u.godina; } ~Ucenik() { delete [] ime; } Ucenik& operator= (const Ucenik& u) { if (this != &u) { delete [] ime; ime = new char[strlen(u.ime)] ; strcpy (ime, u.ime) ; prosek = u.prosek ; godina = u.godina ; } return *this ; } Ucenik& operator++() { //prefiksen operator godina++ ; return *this ; } Ucenik operator++(int) { //postfiksen operator Ucenik u(*this) ; godina++ ; return u; } float getProsek() { return prosek; } // globalna funkcija za preoptovaruvanje na operatorot << // ovaa funkcija e prijatelska na klasata Ucenik friend ostream& operator<< (ostream& o, const Ucenik& u) { return o << "Ime:" << u.ime << ", godina:" << u.godina << ",prosek:" << u.prosek << endl; } friend bool operator> (const Ucenik& u1, const Ucenik& u2); }; //globalna funkcija za preoptovaruvanje na operatorot > bool operator> (const Ucenik& u1, const Ucenik& u2) { return (u1.prosek > u2.prosek); } class Paralelka { private: Ucenik* spisok; int vkupno; public: Paralelka (Ucenik* s = 0, int v = 0) { vkupno = v; spisok = new Ucenik [vkupno]; for (int i = 0; i < vkupno ; i ++) spisok[i] = s[i]; } Paralelka (const Paralelka &p) { this -> vkupno = p.vkupno; this -> spisok = new Ucenik[vkupno]; for (int i = 0; i < vkupno; i ++) spisok[i] = p.spisok[i]; } ~Paralelka() { delete [] spisok; } Paralelka& operator+= (Ucenik u) { Ucenik* tmp = new Ucenik[vkupno + 1]; for (int i = 0; i < vkupno; i++) tmp[i] = spisok[i]; tmp [vkupno ++] = u; delete [] spisok; spisok = tmp; return * this ; } Paralelka& operator++() { for (int i = 0; i < vkupno; i++) spisok[i]++; return *this; } Paralelka operator++(int) { Paralelka p(*this); for (int i = 0; i < vkupno; i++) spisok[i]++; return p; } friend ostream& operator<< (ostream& o, const Paralelka& p) { for (int i = 0; i < p.vkupno; i ++) o << p.spisok[i]; return o; } void nagradi() { for (int i = 0; i < vkupno; i++) if (spisok[i].getProsek() == 10.0) cout << spisok[i]; } void najvisokProsek() { Ucenik tmpU = spisok[0]; for (int i = 0; i < vkupno; i++) if ( spisok[i] > tmpU) tmpU = spisok[i]; cout << "Najvisok prosek vo paralelkata:" << tmpU.getProsek() << endl; } }; int main () { Ucenik u1("Martina Martinovska", 9.5, 3); Ucenik u2("Darko Darkoski", 7.3, 2); Ucenik u3("Angela Angelovska", 10, 3); Paralelka p; p += u1; p += u2; p += u3; cout << p; cout << "Nagradeni:" << endl; p.nagradi(); cout << endl; p.najvisokProsek(); cout << endl; u2++; cout << p; cout << endl; p++; cout << p; return 0; }
21.958084
97
0.481865
finki-mk
2b7a4527cd98274048b08f095580ece6860722d1
960
cpp
C++
old_content/Templates/Flows/Stoer-Wagner.cpp
codelegend/Algorithms
7e1e3de99702ad3d5fa62d65d0afdb1d9de77394
[ "MIT" ]
5
2020-06-04T19:16:36.000Z
2021-11-18T16:34:30.000Z
old_content/Templates/Flows/Stoer-Wagner.cpp
codelegend/Algorithms
7e1e3de99702ad3d5fa62d65d0afdb1d9de77394
[ "MIT" ]
1
2020-09-29T09:10:40.000Z
2020-09-29T09:10:40.000Z
old_content/Templates/Flows/Stoer-Wagner.cpp
codelegend/Algorithms
7e1e3de99702ad3d5fa62d65d0afdb1d9de77394
[ "MIT" ]
1
2020-10-18T20:16:41.000Z
2020-10-18T20:16:41.000Z
LL adj[N][N]; // input, ONLY SET THIS LL wt[N]; bool pres[N], A[N]; // temp-vars(dont-touch) pair<LL, VI> mincut(int n) { // no.of.verts pair<LL, VI> res(INF, VI()); vector<VI> comp(n); for (int i = 0; i < n; i++) comp[i].push_back(i); fill(pres, pres + N, true); for (int ph = 0; ph < n - 1; ph++) { memset(A, 0, sizeof A); memset(wt, 0, sizeof wt); for (int i = 1, prev = -1; i <= n - ph; i++) { int sel = -1; for (int u = 0; u < n; u++) if (pres[u] && !A[u] && (sel==-1 || wt[u]>wt[sel])) sel=u; if (i == n - ph) { // last phase if (wt[sel]<res.first) res=make_pair(wt[sel], comp[sel]); comp[prev].insert(comp[prev].end(), ALL(comp[sel])); for (int u = 0; u < n; u++) adj[u][prev] = adj[prev][u] += adj[u][sel]; pres[sel] = false; } else { for (int u = 0; u < n; u++) wt[u] += adj[u][sel]; A[sel] = true; prev = sel; } } } return res; }
36.923077
66
0.465625
codelegend
2b85104075d65c007ed73097fe83a14b16bedeca
3,727
cpp
C++
src/components/mmu/mmu.cpp
elmerucr/E64
1f7d57fadc6804948aa832d0f5f6800a8631f622
[ "MIT" ]
null
null
null
src/components/mmu/mmu.cpp
elmerucr/E64
1f7d57fadc6804948aa832d0f5f6800a8631f622
[ "MIT" ]
null
null
null
src/components/mmu/mmu.cpp
elmerucr/E64
1f7d57fadc6804948aa832d0f5f6800a8631f622
[ "MIT" ]
null
null
null
/* * mmu.cpp * E64 * * Copyright © 2019-2022 elmerucr. All rights reserved. */ #include "mmu.hpp" #include "common.hpp" #include "rom.hpp" E64::mmu_ic::mmu_ic() { ram = new uint8_t[RAM_SIZE * sizeof(uint8_t)]; reset(); } E64::mmu_ic::~mmu_ic() { delete ram; ram = nullptr; } void E64::mmu_ic::reset() { // fill alternating blocks with 0x00 and 0xff (hard reset) for (int i=0; i < RAM_SIZE; i++) ram[i] = (i & 64) ? 0xff : 0x00; // if available, update rom image update_rom_image(); } uint8_t E64::mmu_ic::read_memory_8(uint16_t address) { uint16_t page = address >> 8; if (page == IO_VICV_BLIT) { if ((address & 0b11111110) == 0) { return vicv.read_byte(address & 0x01); } else { return machine.blitter->io_read_8(address & 0xff); } } else if (page == IO_BLIT_MEMORY) { return machine.blitter->indirect_memory_read_8(address & 0xff); } else if (page == IO_SOUND_PAGE) { return machine.sound->read_byte(address & 0xff); } else if (page == IO_TIMER_PAGE) { return machine.timer->read_byte(address & 0xff); } else if (page == IO_CIA_PAGE) { return machine.cia->read_byte(address & 0xff); } else if ((page & IO_ROM_PAGE) == IO_ROM_PAGE) { return current_rom_image[address & 0x1fff]; } else { return ram[address & 0xffff]; } } void E64::mmu_ic::write_memory_8(uint16_t address, uint8_t value) { uint16_t page = address >> 8; if (page == IO_VICV_BLIT) { if ((address & 0b11111110) == 0) { vicv.write_byte(address & 0x01, value & 0xff); } else { machine.blitter->io_write_8(address & 0xff, value & 0xff); } } else if (page == IO_BLIT_MEMORY) { machine.blitter->indirect_memory_write_8(address & 0xff, value & 0xff); } else if (page == IO_SOUND_PAGE) { machine.sound->write_byte(address & 0xff, value & 0xff); } else if (page == IO_TIMER_PAGE) { machine.timer->write_byte(address & 0xff, value & 0xff); } else if (page == IO_CIA_PAGE) { machine.cia->write_byte(address & 0xff, value & 0xff); } else { ram[address & 0xffff] = value & 0xff; } } void E64::mmu_ic::update_rom_image() { FILE *f = fopen(host.settings.path_to_rom, "r"); if (f) { printf("[mmu] found 'rom.bin' in %s, using this image\n", host.settings.settings_path); fread(current_rom_image, 8192, 1, f); fclose(f); } else { printf("[mmu] no 'rom.bin' in %s, using built-in rom\n", host.settings.settings_path); for(int i=0; i<8192; i++) current_rom_image[i] = rom[i]; } } bool E64::mmu_ic::inject_binary(char *file) { uint16_t start_address; uint16_t end_address; uint16_t vector; const uint8_t magic_code[4] = { 'e'+0x80, '6'+0x80, '4'+0x80, 'x'+0x80 }; FILE *f = fopen(file, "rb"); uint8_t byte; if (f) { start_address = fgetc(f) << 8; start_address |= fgetc(f); //vector = fgetc(f) << 8; //vector |= fgetc(f); end_address = start_address; while(end_address) { byte = fgetc(f); if( feof(f) ) { break; } write_memory_8(end_address++, byte); } fclose(f); hud.show_notification("%s\n\n" "loading $%04x bytes from $%04x to $%04x", file, end_address - start_address, start_address, end_address); printf("[mmu] %s\n" "[mmu] loading $%04x bytes from $%04x to $%04x\n", file, end_address - start_address, start_address, end_address); // also update some ram vectors of guest os ram[OS_FILE_START_ADDRESS] = start_address >> 8; ram[OS_FILE_START_ADDRESS+1] = start_address & 0xff; ram[OS_FILE_END_ADDRESS] = end_address >> 8; ram[OS_FILE_END_ADDRESS+1] = end_address & 0xff; return true; } else { hud.terminal->printf("[mmu] error: can't open %s\n", file); return false; } }
24.846667
74
0.636437
elmerucr
2b9579a99136705b757c53192829aa804c9f59b9
66,056
cpp
C++
devel/miniC/minic/src/ccodebase.cpp
svenschmidt75/compiler
df3185312db939a04876d652e809f7c23f71a188
[ "MIT" ]
null
null
null
devel/miniC/minic/src/ccodebase.cpp
svenschmidt75/compiler
df3185312db939a04876d652e809f7c23f71a188
[ "MIT" ]
null
null
null
devel/miniC/minic/src/ccodebase.cpp
svenschmidt75/compiler
df3185312db939a04876d652e809f7c23f71a188
[ "MIT" ]
null
null
null
/*************************************************************************** * Copyright (C) 2005 by Sven Schmidt * * s.schmidt@lboro.ac.uk * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "ccodebase.h" /* Statische Datenelemente MÜSSEN definiert werden! */ CCodeBase::Register CCodeBase::dataReg[maxRegister] = { 0 }; CCodeBase::Register CCodeBase::adressReg[maxRegister] = { 0 }; CCodeBase::CCodeBase() { } CCodeBase::CCodeBase( CSymbolTable *_symTab, CSyntaxTree *_syntaxTree ) { //Zeiger auf den Syntaxbaum syntaxTree = _syntaxTree; //Zeiger auf die Symboltabelle symTab = _symTab; } CCodeBase::~CCodeBase() { } CCodeBase::Register CCodeBase::getFreeAdressRegister( void ) { Register i = 0; //nächstes freies Register holen while( ( i < maxRegister ) && ( adressReg[i] != 0 ) ) //nächstes Register früfen i++; //kein freies Register mehr vorhanden? if( i == maxRegister ) { //nein, Ende cerr << "CCodeBase::getFreeAdressRegister: Number of available adress registers exeeded!" << endl; //Ende exit( 1 ); } //Adressregister i ist nun belegt adressReg[i] = 1; //freies Datenregister zurückliefern return( i ); } void CCodeBase::freeAdressRegister( CCodeBase::Register reg ) { //gibt es das Adressregister überhaupt? if( ( reg >= 0 ) && ( reg < maxRegister ) ) { //ja, ist es überhaupt belegt? if( adressReg[reg] ) //ja, freigeben adressReg[reg] = 0; else //Meldung cerr << "CCodeBase::freeAdressRegister: Adress register " << reg << " not occupied!" << endl; } else { //nein, Ende cerr << "CCodeBase::freeAdressRegister: Adress register " << reg << " not existent!" << endl; //Ende exit( 1 ); } } CCodeBase::Register CCodeBase::getFreeDataRegister( void ) { Register i = 0; //nächstes freies Register holen while( ( i < maxRegister ) && ( dataReg[i] != 0 ) ) //nächstes Register früfen i++; //kein freies Register mehr vorhanden? if( i == maxRegister ) { //nein, Ende cerr << "CCodeBase::getFreeDataRegister: Number of available data registers exeeded!" << endl; //Ende exit( 1 ); } //Datenregister i ist nun belegt dataReg[i] = 1; //freies Datenregister zurückliefern return( i ); } void CCodeBase::freeDataRegister( CCodeBase::Register reg ) { //gibt es das Datenregister überhaupt? if( ( reg >= 0 ) && ( reg < maxRegister ) ) { //ja, ist es überhaupt belegt? if( dataReg[reg] ) //ja, freigeben dataReg[reg] = 0; else //Meldung cerr << "CCodeBase::freeDataRegister: Data register " << reg << " not occupied!" << endl; } else { //nein, Ende cerr << "CCodeBase::freeDataRegister: Data register " << reg << " not existent!" << endl; //Ende exit( 1 ); } } void CCodeBase::print( long index ) { /* Dieser Routine wird der Index der Wurzel des Syntaxbaumes übergeben, für den hier Code erzeugt werden soll. */ long left, right, next; //undefiniert? if( index == -1 ) //ja, Ende return; //linkes Kind left = syntaxTree->getLeftChild( index ); //rechtes Kind right = syntaxTree->getRightChild( index ); //nächstes Statement in der Verkettung holen next = syntaxTree->getNextStmt( index ); /* Es wird von rechts nach linke ausgewertet!!! Also wird zuerst alle rechten Kinder Code erzeugt, und erste DANACH für alle linken!!! */ //Zeile im Quelltext line = syntaxTree->getLine( index ); /* Hier können jetzt LEAFs stehen oder NODEs. */ //Knoten? if( syntaxTree->isNode( index ) ) { //ist ein Knoten CSyntaxTree::STOperator op = syntaxTree->getOperator( index ); //welcher Operator? switch( op ) { case CSyntaxTree::_LOG_AND: { //logisches und, && CSymbolTable::storageType leftType, rightType; Register ldr, rdr, dr; long l1, dummy, gen; //in der _ifStr-Struktur steht das Sprungziel syntaxTree->getIfStmt( index, dummy, dummy, dummy, l1, dummy ); //in parent steht der Index des Labels gen = syntaxTree->getParent( l1 ); //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Datenregister für das Ergebnis holen dr = getFreeDataRegister(); //das Eregbnis auf false setzen cout << "\tmove.b\t#0,d" << dr << endl; //linkes Kind == false? cout << "\tcmp.b\t#0,d" << ldr << endl; //Sprung cout << "\tbeq\t\tL" << gen << endl; //rechtes Kind == false? cout << "\tcmp.b\t#0,d" << rdr << endl; //Sprung cout << "\tbeq\t\tL" << gen << endl; //beide true, das Eregbnis auf true setzen cout << "\tmove.b\t#1,d" << dr << endl; //Label erzeugen print( l1 ); //das Ergenbis steht in dr, also ldr und rdr freigeben freeDataRegister( ldr ); freeDataRegister( rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( dr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Expression has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den &&-Knoten eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_LOG_OR: { //logisches oder, || CSymbolTable::storageType leftType, rightType; Register ldr, rdr, dr; long l1, l2, dummy, gen1, gen2; //in der _ifStr-Struktur steht das Sprungziel syntaxTree->getIfStmt( index, dummy, dummy, dummy, l1, l2 ); //in parent steht der Index des Labels gen1 = syntaxTree->getParent( l1 ); gen2 = syntaxTree->getParent( l2 ); //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Datenregister für das Ergebnis holen dr = getFreeDataRegister(); //das Eregbnis auf false setzen cout << "\tmove.b\t#0,d" << dr << endl; //linkes Kind == false? cout << "\tcmp.b\t#0,d" << ldr << endl; //Sprung cout << "\tbne\t\tL" << gen2 << endl; //rechtes Kind == false? cout << "\tcmp.b\t#0,d" << rdr << endl; //Sprung cout << "\tbne\t\tL" << gen2 << endl; //beide false cout << "\tbra\t\tL" << gen1 << endl; //Label erzeugen print( l2 ); //beide true, das Eregbnis auf true setzen cout << "\tmove.b\t#1,d" << dr << endl; //Label erzeugen print( l1 ); //das Ergenbis steht in dr, also ldr und rdr freigeben freeDataRegister( ldr ); freeDataRegister( rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( dr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Expression has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den ||-Knoten eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_LOG_NOT: { //logisches nicht, ! CSymbolTable::storageType rightType; Register dr, rdr; /* Dieser Knoten hat nur ein rechtes Kind! */ //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Datenregister für das Ergebnis holen dr = getFreeDataRegister(); //prüfen auf false und entsprechend setzen cout << "\tcmp.b\t#0,d" << rdr << endl; cout << "\tseq.b\td" << dr << endl; //das Ergenbis steht in dr, also rdr freigeben freeDataRegister( rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( dr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Expression has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den !-Knoten eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_IF: { //if-Statement ausgeben CSymbolTable::storageType leftType, rightType; Register dr, rdr; long expr, stmt1, stmt2, l1, l2, gen1, gen2; //Informationen holen syntaxTree->getIfStmt( index, expr, stmt1, stmt2, l1, l2 ); //die Label holen if( l1 != -1 ) //es gibt einen else-Teil gen1 = syntaxTree->getParent( l1 ); //Sprung hinter else-Teil gen2 = syntaxTree->getParent( l2 ); //Code für expr ausgeben print( expr ); //Datenregister des Ergebnis holen dr = syntaxTree->getDataRegister( expr ); //Ergebnis auf true oder false testen cout << "\ttst.b\td" << dr << endl; //gibt es einen else-Teil? if( stmt2 == -1 ) //nein, gibt es nicht cout << "\tbne\t\tL" << gen2 << endl; else //ja, gibt es cout << "\tbne\t\tL" << gen1 << endl; //if-Teil ausgeben (true-Teil) print( stmt1 ); //gibt es einen else-Teil? if( stmt2 == -1 ) //nein, Label erzeugen print( l2 ); else { //ja, Sprung hinter den else-Teil cout << "\tbra\t\tL" << gen2 << endl; //Label erzeugen print( l1 ); //else-Teil ausgeben print( stmt2 ); //Label ausgeben print( l2 ); } //das Datenregister für die Auswertung von expr freigeben freeDataRegister( dr ); break; } case CSyntaxTree::_WHILE: { //while-Statement ausgeben CSymbolTable::storageType leftType, rightType; Register dr, rdr; long expr, stmt, dummy, l1, l2, gen1, gen2; //Informationen holen syntaxTree->getIfStmt( index, expr, stmt, dummy, l1, l2 ); //in parent steht der Index des Labels gen1 = syntaxTree->getParent( l1 ); gen2 = syntaxTree->getParent( l2 ); //das Label am Anfang des expr-Teils ausgeben print( l1 ); //Code für expr ausgeben print( expr ); //Datenregister des Ergebnis holen dr = syntaxTree->getDataRegister( expr ); //Ergebnis auf true oder false testen cout << "\ttst.b\td" << dr << endl; //Ergebnis ist false cout << "\tbne\t\tL" << gen2 << endl; //stmt-Teil ausgeben (true-Teil) print( stmt ); //Sprung zum Anfang des expr-Teils cout << "\tbra\t\tL" << gen1 << endl; //Label am Ende des stmt-Teils erzeugen print( l2 ); //das Datenregister für die Auswertung von expr freigeben freeDataRegister( dr ); break; } case CSyntaxTree::_DOWHILE: { //do-while-Statement ausgeben CSymbolTable::storageType leftType, rightType; Register dr, rdr; long expr, stmt, dummy, l1, l2, gen1, gen2; //Informationen holen syntaxTree->getIfStmt( index, expr, stmt, dummy, l1, l2 ); //in parent steht der Index des Labels gen1 = syntaxTree->getParent( l1 ); gen2 = syntaxTree->getParent( l2 ); //das Label am Anfang des stmt-Teils ausgeben print( l1 ); //stmt-Teil ausgeben print( stmt ); //Code für expr ausgeben print( expr ); //Datenregister des Ergebnis holen dr = syntaxTree->getDataRegister( expr ); //Ergebnis auf true oder false testen cout << "\ttst.b\td" << dr << endl; //Ergebnis ist false, Schleife verlassen cout << "\tbne\t\tL" << gen2 << endl; //Schleifenbody nochmal ausführen cout << "\tbra\t\tL" << gen1 << endl; //Label am Ende des stmt-Teils erzeugen print( l2 ); //das Datenregister für die Auswertung von expr freigeben freeDataRegister( dr ); break; } case CSyntaxTree::_LABEL: { //ein Label wird sofort ausgegeben long lab; //die Nummer des Labels steht in parent lab = syntaxTree->getParent( index ); //Label ausgeben cout << "L" << lab << ":" << endl; break; } case CSyntaxTree::_BLK_STMT: { //Block-Statement vector<long> stmt; long localVarSize, stmtSize, i; //Länge der lokalen Variablen dieses Blocks localVarSize = syntaxTree->getLocalVar( index ); //Platz für lokale Variablen auf dem Laufzeit-Stack schaffen cout << "\tlink.l\ta6,#-" << localVarSize << endl; //Code für Block ausgeben print( right ); //Platz für lokale Variablen auf dem Laufzeit-Stack entfernen cout << "\tunlk.l\ta6" << endl; break; } case CSyntaxTree::_EQ: { //gleich, equal CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tseq.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den ==-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_NEQ: { //ungleich, not equal CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tsne.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den !=-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_LT: { //kleiner als, less than CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tslt.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den <-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_LE: { //kleiner gleich, less equal CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tsle.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den <=-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_GT: { //größer als, greater than CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tsgt.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den >-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_GE: { //größer gleich, greater equal CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Verleichs-Operator ausgeben cout << "\tcmp"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //nimm das Register rdr um das Ergebnis zu speichern cout << "\tsge.b\td" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Comparision has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den <=-Knoten eintragen syntaxTree->setDataRegister( index, rdr, CSymbolTable::_BOOL ); break; } case CSyntaxTree::_BIN_AND: { //binäres und CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //binäres und ausgeben cout << "\tand"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Binary and has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den &-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_BIN_OR: { //binäres oder CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //binäres oder ausgeben cout << "\tor"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Binary or has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den |-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_BIN_XOR: { //binäres x-oder CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //binäres x-oder ausgeben cout << "\txor"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Binary xor has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den ^-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_BIN_NOT: { //binäres nicht CSymbolTable::storageType type; Register dr; /* Dieser Knoten hat nur ein rechtes Kind! */ //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen dr = syntaxTree->getDataRegister( right ); //binäres nicht ausgeben cout << "\tnot"; //Breite ausgeben printStorageType( type ); //Register ausgeben cout << "\td" << dr << endl; //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( dr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Binary not has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den ~-Knoten eintragen syntaxTree->setDataRegister( index, dr, type ); break; } case CSyntaxTree::_LEFT_SHIFT: { //links shift CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //>> ausgeben cout << "\tlsl"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << rdr << ",d" << ldr << endl; //das Ergenbis steht in ldr, also rdr freigeben freeDataRegister( rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( ldr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Left shift has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den <<-Knoten eintragen syntaxTree->setDataRegister( index, ldr, leftType ); break; } case CSyntaxTree::_RIGHT_SHIFT: { //rechts shift CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //>> ausgeben cout << "\tlsr"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << rdr << ",d" << ldr << endl; //das Ergenbis steht in ldr, also rdr freigeben freeDataRegister( rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( ldr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Right shift has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den >>-Knoten eintragen syntaxTree->setDataRegister( index, ldr, leftType ); break; } case CSyntaxTree::_MUL: { //Multiplikation CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Multiplikation ausgeben cout << "\tmul"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Multiplication has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den *-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_DIV: { //Division CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Division ausgeben cout << "\tdiv"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Division has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den /-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_ADD: { //Addition CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Addition ausgeben cout << "\tadd"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Addition has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den +-Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_SUB: { //Subtraktion CSymbolTable::storageType leftType, rightType; Register ldr, rdr; //Code für das linke Kind ausgeben print( left ); //storage type des linken Kindes leftType = syntaxTree->getDataRegisterStorageType( left ); //Datenregister des linken Kindex holen ldr = syntaxTree->getDataRegister( left ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindex holen rdr = syntaxTree->getDataRegister( right ); //Subtraktion ausgeben cout << "\tsub"; //Breite ausgeben printStorageType( leftType ); //Register ausgeben cout << "\t"; cout << "d" << ldr << ",d" << rdr << endl; //das Ergenbis steht in rdr, also ldr freigeben freeDataRegister( ldr ); //Wurzel? if( syntaxTree->isRoot( index ) ) { //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); //Zeile holen long line = syntaxTree->getLine( index ); //Ausdruck hat keinen Effekt cerr << "CCodeBase::print: Line " << line << ": Subtraction has no effect!" << endl; } else //Knoten wird noch benötigt, Register in den --Knoten eintragen syntaxTree->setDataRegister( index, rdr, leftType ); break; } case CSyntaxTree::_EQU: { //Zuweisung CSymbolTable::storageType leftType, rightType, type; Register rdr; //ist das linke Kind ein Leaf? if( syntaxTree->isNode( left ) ) { //nein, ist ein Knoten cerr << "CCodeBase::print: Left child is node in equ-expression!" << endl; //Ende exit( 1 ); } //Index in Symboltabelle holen long symTabIndex = syntaxTree->getSymTabIndex( left ); //Storage type holen leftType = symTab->getStorageType( symTabIndex ); //Code für das rechte Kind ausgeben print( right ); //storage type des rechten Kindes rightType = syntaxTree->getDataRegisterStorageType( right ); //Datenregister des rechten Kindes holen rdr = syntaxTree->getDataRegister( right ); //Inhalt des Datenregisters rdr speichern SaveLValue( left, rdr ); //Wurzel? if( syntaxTree->isRoot( index ) ) //ja, ist die Wurzel, Datenregister freigeben freeDataRegister( rdr ); else { //Knoten wird noch benötigt, Register in den =-Knoten eintragen syntaxTree->setDataRegister( index, rdr, type ); /* Wenn eine Zuweisung nicht Root ist, dann könnte es sich um einen Fehler handeln! */ //Zeile holen long line = syntaxTree->getLine( index ); //Warnung ausgeben cerr << "CCodeBase::print: line " << line << ": Possible wrong assignment!" << endl; } break; } case CSyntaxTree::_SHORT2BOOL: { /* Eine Typkonvertierung von SHORT zu BOOL durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ SHORT sein if( type != CSymbolTable::_SHORT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); //Code ausgeben cout << "\ttst.w\td" << dr << endl; //nun in 0 oder 1 wandeln cout << "\tsne.b\td" << dr << endl; break; } case CSyntaxTree::_SHORT2CHAR: { /* Eine Typkonvertierung von SHORT zu CHAR durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ SHORT sein if( type != CSymbolTable::_SHORT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_CHAR ); /* Hier muss kein Code erzeugt werden, da einfach statt move.w move.b benutzt wird. */ break; } case CSyntaxTree::_SHORT2INT: { /* Eine Typkonvertierung von SHORT zu INT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ SHORT sein if( type != CSymbolTable::_SHORT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_INT ); //Code ausgeben cout << "\text.l\td" << dr << endl; break; } case CSyntaxTree::_SHORT2LONG: { /* Eine Typkonvertierung von SHORT zu LONG durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ SHORT sein if( type != CSymbolTable::_SHORT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_LONG ); //Code ausgeben cout << "\text.l\td" << dr << endl; break; } case CSyntaxTree::_INT2BOOL: { /* Eine Typkonvertierung von INT zu BOOL durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ INT sein if( type != CSymbolTable::_INT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); //Code ausgeben cout << "\ttst.l\td" << dr << endl; //nun in 0 oder 1 wandeln cout << "\tsne.b\td" << dr << endl; break; } case CSyntaxTree::_INT2LONG: { /* Eine Typkonvertierung von INT zu LONG durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ INT sein if( type != CSymbolTable::_INT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_LONG ); /* Hier muss kein Code erzeugt werden, da intern LONG und INT äquivalent sind. */ break; } case CSyntaxTree::_INT2SHORT: { /* Eine Typkonvertierung von INT zu SHORT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ INT sein if( type != CSymbolTable::_INT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_SHORT ); /* Hier muss kein Code erzeugt werden, da einfach statt move.l move.w benutzt wird. */ break; } case CSyntaxTree::_INT2CHAR: { /* Eine Typkonvertierung von INT zu CHAR durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ INT sein if( type != CSymbolTable::_INT ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_CHAR ); /* Hier muss kein Code erzeugt werden, da einfach statt move.l move.b benutzt wird. */ break; } case CSyntaxTree::_BOOL2CHAR: { /* Eine Typkonvertierung von BOOL zu CHAR durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ BOOL sein if( type != CSymbolTable::_BOOL ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_CHAR ); /* Hier muss kein Code ausgegeben werden, da BOOL und CHAR beide 8 Bit-Datentypen sind. */ break; } case CSyntaxTree::_BOOL2SHORT: { /* Eine Typkonvertierung von BOOL zu SHORT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ BOOL sein if( type != CSymbolTable::_BOOL ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_SHORT ); //Code ausgeben cout << "\text.w\td" << dr << endl; break; } case CSyntaxTree::_BOOL2INT: { /* Eine Typkonvertierung von BOOL zu INT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ BOOL sein if( type != CSymbolTable::_BOOL ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_INT ); //Code ausgeben cout << "\textb.l\td" << dr << endl; break; } case CSyntaxTree::_BOOL2LONG: { /* Eine Typkonvertierung von BOOL zu LONG durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ BOOL sein if( type != CSymbolTable::_BOOL ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_LONG ); //Code ausgeben cout << "\textb.l\td" << dr << endl; break; } case CSyntaxTree::_CHAR2BOOL: { /* Eine Typkonvertierung von CHAR zu BOOL durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ CHAR sein if( type != CSymbolTable::_CHAR ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); //Code ausgeben cout << "\ttst.b\td" << dr << endl; //nun in 0 oder 1 wandeln cout << "\tsne.b\td" << dr << endl; break; } case CSyntaxTree::_CHAR2SHORT: { /* Eine Typkonvertierung von CHAR zu SHORT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ CHAR sein if( type != CSymbolTable::_CHAR ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_SHORT ); //Code ausgeben cout << "\text.w\td" << dr << endl; break; } case CSyntaxTree::_CHAR2INT: { /* Eine Typkonvertierung von CHAR zu INT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ CHAR sein if( type != CSymbolTable::_CHAR ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_INT ); //Code ausgeben cout << "\textb.l\td" << dr << endl; break; } case CSyntaxTree::_CHAR2LONG: { /* Eine Typkonvertierung von CHAR zu LONG durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ CHAR sein if( type != CSymbolTable::_CHAR ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_LONG ); //Code ausgeben cout << "\textb.l\td" << dr << endl; break; } case CSyntaxTree::_LONG2INT: { /* Eine Typkonvertierung von LONG zu INT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ LONG sein if( type != CSymbolTable::_LONG ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_INT ); /* Hier muss kein Code erzeugt werden, da intern LONG und INT äquivalent sind. */ break; } case CSyntaxTree::_LONG2SHORT: { /* Eine Typkonvertierung von LONG zu SHORT durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ LONG sein if( type != CSymbolTable::_LONG ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_SHORT ); /* Hier muss kein Code erzeugt werden, da einfach statt move.l move.w benutzt wird. */ break; } case CSyntaxTree::_LONG2CHAR: { /* Eine Typkonvertierung von LONG zu CHAR durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ LONG sein if( type != CSymbolTable::_LONG ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_CHAR ); /* Hier muss kein Code erzeugt werden, da einfach statt move.l move.b benutzt wird. */ break; } case CSyntaxTree::_LONG2BOOL: { /* Eine Typkonvertierung von LONG zu BOOL durchführen. Dieser Knoten hat nur ein rechtes Kind! */ CSymbolTable::storageType type; Register dr; //zuerst das rechte Kind auswerten print( right ); //im Knoten des rechten Kindes steht jetzt das Register //storage type des rechten Kindes type = syntaxTree->getDataRegisterStorageType( right ); //Datenregister holen, das gecastet werden soll dr = syntaxTree->getDataRegister( right ); //das Datenregister muss vom Typ LONG sein if( type != CSymbolTable::_LONG ) { //Zeile holen long line = syntaxTree->getLine( index ); //Fehler cerr << "CCodeBase::print: Line " << line << ": Wrong type in data register!" << endl; //Ende exit( 1 ); } //Register eintragen syntaxTree->setDataRegister( index, dr, CSymbolTable::_BOOL ); //Code ausgeben cout << "\ttst.l\td" << dr << endl; //nun in 0 oder 1 wandeln cout << "\tsne.b\td" << dr << endl; break; } /* default: { //unbekannter Operator cerr << "CCodeBase::print: Unknown operator " << op << "!" << endl; //Ende exit( 1 ); } */ } //nächstes Statement in der Stement-Verkettung ausgeben print( next ); } else { //ist ein Leaf CSymbolTable::storageType type; Register dr; //Index in Symboltabelle holen long symTabIndex = syntaxTree->getSymTabIndex( index ); //Storage type holen type = symTab->getStorageType( symTabIndex ); //den Inhalt der Vereinbarung in ein Datenregister laden dr = LoadRValue( index ); //Register eintragen syntaxTree->setDataRegister( index, dr, type ); } } void CCodeBase::printStorageType( CSymbolTable::storageType type ) const { //Storage Type ausgeben //welcher storage type? switch( type ) { case CSymbolTable::_CHAR: case CSymbolTable::_BOOL: { //Bytes und Bools benötigen ein Byte cout << ".b"; break; } case CSymbolTable::_SHORT: { //Shorts benötigen zwei Bytes cout << ".w"; break; } case CSymbolTable::_INT: case CSymbolTable::_LONG: { //Integers benötigen vier Bytes cout << ".l"; break; } default: { //Fehler cerr << "CCodeBase::printStorageType: Unknown storage type!" << endl; //Ende exit( 1 ); } } } CCodeBase::Register CCodeBase::LoadRValue( long index ) { //lädt eine lokale/globale Vereinbarung in ein Datenregister CSymbolTable::varType varType; CCodeBase::Register reg; long symTabIndex; int offset; //wenn index ein Node ist, dann wurde das Ergebnis ja schon in ein Datenregister //abgelegt if( syntaxTree->isNode( index ) ) //ja, ist ein Node return( syntaxTree->getDataRegister( index ) ); //hole ein freies Datenregister reg = getFreeDataRegister(); //Index in Symboltabelle holen symTabIndex = syntaxTree->getSymTabIndex( index ); //Typ holen varType = symTab->getType( symTabIndex ); //Offset der lokalen Variablen zum lokalen Stackframe holen offset = symTab->getOffset( symTabIndex ); //Storage type holen CSymbolTable::storageType storageType = symTab->getStorageType( symTabIndex ); //Offset berechnen offset = offset + symTab->getWidthInBytes( storageType ); //Register eintragen syntaxTree->setDataRegister( index, reg, storageType ); //Name der Variablen char *name = symTab->getName( symTabIndex ); //Zahl, nicht Variable? if( varType == CSymbolTable::_NUMBER ) { long val = syntaxTree->getNumber( index ); //ist eine Zahl cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //Zahl direkt angeben cout << "\t#" << val << ",d" << reg; } //lokale oder globale Variable? else if( symTab->isLocal( symTabIndex ) ) { //lokale Variable //ist die lokale Variable in einem anderen Block deklariert? int diff = syntaxTree->getBlkDiff( index ); //anderer Block? if( diff ) { CCodeBase::Register adrReg; int i; //hole ein freies Adressregister adrReg = getFreeAdressRegister(); //ja, den Stackframe laden, in dem die lokale Variable deklariert wurde cout << "\tmove.l\t(a6),a" << adrReg << endl; //alle weiteren Level abarbeiten for( i = 1; i < diff; i++ ) //Zeiger auf Stackframe für lokale Variablen holen cout << "\tmove.l\t(a" << adrReg << "),a" << adrReg << endl; //lokale Variable in Datenregister laden cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //von adrReg aus cout << "\t-" << offset << "(a" << adrReg << "),d" << reg; //Adressregister freigeben freeAdressRegister( adrReg ); } else { //nein, im gleichen Block //lokale Variable in Datenregister laden cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //von adrReg aus cout << "\t-" << offset << "(a6),d" << reg; } } else { //ist eine globale Variable cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //in Datenregister laden cout << "\t" << name << ",d" << reg; } //Name der Variablen ausgeben if( name ) //als Kommentar anhängen cout << "\t;" << name << endl; else //neue Zeile cout << endl; //Datenregister zurückliefern return( reg ); } void CCodeBase::SaveLValue( long index, CCodeBase::Register reg ) { //speichert den Inhalt des Datenregisters reg in eine Vereinbarung //Index in Symboltabelle holen long symTabIndex = syntaxTree->getSymTabIndex( index ); //Offset zum Stackframe holen int offset = symTab->getOffset( symTabIndex ); //Storage type holen CSymbolTable::storageType storageType = symTab->getStorageType( symTabIndex ); //Offset berechnen offset = offset + symTab->getWidthInBytes( storageType ); //Name der Variablen char *name = symTab->getName( symTabIndex ); //lokale oder globale Variable? if( symTab->isLocal( symTabIndex ) ) { //lokale Variable //ist die lokale Variable in einem anderen Block deklariert? int diff = syntaxTree->getBlkDiff( index ); //anderer Block? if( diff ) { CCodeBase::Register adrReg; int i; //hole ein freies Adressregister adrReg = getFreeAdressRegister(); //ja, den Stackframe laden, in dem die lokale Variable deklariert wurde cout << "\tmove.l\t(a6),a" << adrReg << endl; //alle weiteren Level abarbeiten for( i = 1; i < diff; i++ ) //Zeiger auf Stackframe für lokale Variablen holen cout << "\tmove.l\t(a" << adrReg << "),a" << adrReg << endl; //Datenregister eintragen cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //von adrReg aus cout << "\td" << reg << ",-" << offset << "(a" << adrReg << ")"; //Adressregister freigeben freeAdressRegister( adrReg ); } else { //nein, im gleichen Block //von Datenregister aus cout << "\tmove"; //storage Type ausgeben printStorageType( storageType ); //Datenregister cout << "\td" << reg << ",-" << offset << "(a6)"; } } else { //ist eine globale Variable //von Datenregister aus cout << "\tmove"; //storage Type ausgeben printStorageType( syntaxTree->getDataRegisterStorageType( index ) ); //Datenregister cout << "\td" << reg << "," << name; } //Kommentar cout << "\t;" << name << endl; }
23.532597
100
0.627528
svenschmidt75
2ba42ed851b19c360c6bef54a5af00fb4bc9788a
8,804
cpp
C++
test/math/math_test.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
163
2015-03-16T08:42:32.000Z
2022-01-11T21:40:22.000Z
test/math/math_test.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
17
2015-04-12T20:57:50.000Z
2020-10-10T10:51:45.000Z
test/math/math_test.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
21
2015-04-12T20:45:11.000Z
2022-01-14T20:50:16.000Z
// Copyright mogemimi. Distributed under the MIT license. #include "pomdog/math/degree.hpp" #include "pomdog/math/math.hpp" #include "pomdog/math/radian.hpp" #include <catch_amalgamated.hpp> namespace math = pomdog::math; using pomdog::Degree; using pomdog::Radian; TEST_CASE("MathHelper", "[MathHelper]") { SECTION("Constants") { // NOTE: float REQUIRE(math::Pi<float> == 3.1415926535f); REQUIRE(math::TwoPi<float> == 6.2831853071f); REQUIRE(math::OneOverPi<float> == 0.3183098861f); REQUIRE(math::OneOver2Pi<float> == 0.1591549430f); REQUIRE(math::PiOver2<float> == 1.5707963267f); REQUIRE(math::PiOver4<float> == 0.7853981633f); // NOTE: double REQUIRE(math::Pi<double> == 3.14159265358979323846); REQUIRE(math::TwoPi<double> == 6.28318530717958647692); REQUIRE(math::OneOverPi<double> == 0.31830988618379067154); REQUIRE(math::OneOver2Pi<double> == 0.15915494309189533576); REQUIRE(math::PiOver2<double> == 1.57079632679489661923); REQUIRE(math::PiOver4<double> == 0.78539816339744830962); } SECTION("Clamp") { REQUIRE(math::Clamp(std::numeric_limits<double>::lowest(), 0.0, 1.0) == 0.0); REQUIRE(math::Clamp(0.0, 0.0, 1.0) == 0.0); REQUIRE(math::Clamp(0.5, 0.0, 1.0) == 0.5); REQUIRE(math::Clamp(1.0, 0.0, 1.0) == 1.0); REQUIRE(math::Clamp(std::numeric_limits<double>::max(), 0.0, 1.0) == 1.0); REQUIRE(math::Clamp(std::numeric_limits<float>::lowest(), 0.0f, 1.0f) == 0.0f); REQUIRE(math::Clamp(0.0f, 0.0f, 1.0f) == 0.0); REQUIRE(math::Clamp(0.5f, 0.0f, 1.0f) == 0.5); REQUIRE(math::Clamp(1.0f, 0.0f, 1.0f) == 1.0); REQUIRE(math::Clamp(std::numeric_limits<float>::max(), 0.0f, 1.0f) == 1.0f); REQUIRE(math::Clamp(-4.3f, -4.0f, 5.0f) == -4.0f); REQUIRE(math::Clamp(-2.5f, -4.0f, 5.0f) == -2.5f); REQUIRE(math::Clamp(0.0f, -4.0f, 5.0f) == 0.0f); REQUIRE(math::Clamp(3.5f, -4.0f, 5.0f) == 3.5f); REQUIRE(math::Clamp(5.7f, -4.0f, 5.0f) == 5.0f); } SECTION("Saturate") { REQUIRE(math::Saturate(std::numeric_limits<double>::lowest()) == 0.0); REQUIRE(math::Saturate(-0.1) == 0.0); REQUIRE(math::Saturate(0.0) == 0.0); REQUIRE(math::Saturate(0.1) == 0.1); REQUIRE(math::Saturate(0.5) == 0.5); REQUIRE(math::Saturate(0.9) == 0.9); REQUIRE(math::Saturate(1.0) == 1.0); REQUIRE(math::Saturate(1.1) == 1.0); REQUIRE(math::Saturate(std::numeric_limits<double>::max()) == 1.0); REQUIRE(math::Saturate(std::numeric_limits<float>::lowest()) == 0.0f); REQUIRE(math::Saturate(-0.1f) == 0.0f); REQUIRE(math::Saturate(0.0f) == 0.0f); REQUIRE(math::Saturate(0.1f) == 0.1f); REQUIRE(math::Saturate(0.5f) == 0.5f); REQUIRE(math::Saturate(0.9f) == 0.9f); REQUIRE(math::Saturate(1.0f) == 1.0f); REQUIRE(math::Saturate(1.1f) == 1.0f); REQUIRE(math::Saturate(std::numeric_limits<float>::max()) == 1.0f); } SECTION("Lerp") { constexpr auto epsilon = std::numeric_limits<float>::epsilon(); REQUIRE(std::abs(0.0f - math::Lerp(0.0f, 1.0f, 0.0f)) < epsilon); REQUIRE(std::abs(0.2f - math::Lerp(0.0f, 1.0f, 0.2f)) < epsilon); REQUIRE(std::abs(0.5f - math::Lerp(0.0f, 1.0f, 0.5f)) < epsilon); REQUIRE(std::abs(0.8f - math::Lerp(0.0f, 1.0f, 0.8f)) < epsilon); REQUIRE(std::abs(1.0f - math::Lerp(0.0f, 1.0f, 1.0f)) < epsilon); REQUIRE(std::abs(-1.0f - math::Lerp(-1.0f, 1.0f, 0.0f)) < epsilon); REQUIRE(std::abs(-0.6f - math::Lerp(-1.0f, 1.0f, 0.2f)) < epsilon); REQUIRE(std::abs(0.0f - math::Lerp(-1.0f, 1.0f, 0.5f)) < epsilon); REQUIRE(std::abs(0.6f - math::Lerp(-1.0f, 1.0f, 0.8f)) < epsilon); REQUIRE(std::abs(1.0f - math::Lerp(-1.0f, 1.0f, 1.0f)) < epsilon); REQUIRE(std::abs(-0.5f - math::Lerp(-0.5f, 0.5f, 0.0f)) < epsilon); REQUIRE(std::abs(-0.3f - math::Lerp(-0.5f, 0.5f, 0.2f)) < epsilon); REQUIRE(std::abs(0.0f - math::Lerp(-0.5f, 0.5f, 0.5f)) < epsilon); REQUIRE(std::abs(0.3f - math::Lerp(-0.5f, 0.5f, 0.8f)) < epsilon); REQUIRE(std::abs(0.5f - math::Lerp(-0.5f, 0.5f, 1.0f)) < epsilon); REQUIRE(math::Lerp(0.0f, 1.0f, 0.0f) < math::Lerp(0.0f, 1.0f, 0.1f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.1f) < math::Lerp(0.0f, 1.0f, 0.2f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.2f) < math::Lerp(0.0f, 1.0f, 0.3f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.3f) < math::Lerp(0.0f, 1.0f, 0.4f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.4f) < math::Lerp(0.0f, 1.0f, 0.5f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.5f) < math::Lerp(0.0f, 1.0f, 0.6f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.6f) < math::Lerp(0.0f, 1.0f, 0.7f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.7f) < math::Lerp(0.0f, 1.0f, 0.8f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.8f) < math::Lerp(0.0f, 1.0f, 0.9f)); REQUIRE(math::Lerp(0.0f, 1.0f, 0.9f) < math::Lerp(0.0f, 1.0f, 1.0f)); } SECTION("SmoothStep") { constexpr auto epsilon = std::numeric_limits<float>::epsilon(); REQUIRE(std::abs(0.0f - math::SmoothStep(0.0f, 1.0f, 0.0f)) < epsilon); REQUIRE(std::abs(0.5f - math::SmoothStep(0.0f, 1.0f, 0.5f)) < epsilon); REQUIRE(std::abs(1.0f - math::SmoothStep(0.0f, 1.0f, 1.0f)) < epsilon); REQUIRE(std::abs(-1.0f - math::SmoothStep(-1.0f, 1.0f, 0.0f)) < epsilon); REQUIRE(std::abs(0.0f - math::SmoothStep(-1.0f, 1.0f, 0.5f)) < epsilon); REQUIRE(std::abs(1.0f - math::SmoothStep(-1.0f, 1.0f, 1.0f)) < epsilon); REQUIRE(std::abs(-0.5f - math::SmoothStep(-0.5f, 0.5f, 0.0f)) < epsilon); REQUIRE(std::abs(0.0f - math::SmoothStep(-0.5f, 0.5f, 0.5f)) < epsilon); REQUIRE(std::abs(0.5f - math::SmoothStep(-0.5f, 0.5f, 1.0f)) < epsilon); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.0f) < math::SmoothStep(0.0f, 1.0f, 0.1f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.1f) < math::SmoothStep(0.0f, 1.0f, 0.2f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.2f) < math::SmoothStep(0.0f, 1.0f, 0.3f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.3f) < math::SmoothStep(0.0f, 1.0f, 0.4f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.4f) < math::SmoothStep(0.0f, 1.0f, 0.5f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.5f) < math::SmoothStep(0.0f, 1.0f, 0.6f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.6f) < math::SmoothStep(0.0f, 1.0f, 0.7f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.7f) < math::SmoothStep(0.0f, 1.0f, 0.8f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.8f) < math::SmoothStep(0.0f, 1.0f, 0.9f)); REQUIRE(math::SmoothStep(0.0f, 1.0f, 0.9f) < math::SmoothStep(0.0f, 1.0f, 1.0f)); } SECTION("ToDegrees") { constexpr auto epsilon = 0.0000001f; REQUIRE(std::abs(0.0f - math::ToDegrees(0.0f).value) < epsilon); REQUIRE(std::abs(45.0f - math::ToDegrees(0.7853981633f).value) < epsilon); REQUIRE(std::abs(90.0f - math::ToDegrees(1.5707963267f).value) < epsilon); REQUIRE(std::abs(180.0f - math::ToDegrees(3.1415926535f).value) < epsilon); REQUIRE(std::abs(360.0f - math::ToDegrees(6.2831853071f).value) < epsilon); REQUIRE(std::abs(0.0f - math::ToDegrees(Radian<float>(0.0f)).value) < epsilon); REQUIRE(std::abs(45.0f - math::ToDegrees(Radian<float>(0.7853981633f)).value) < epsilon); REQUIRE(std::abs(90.0f - math::ToDegrees(Radian<float>(1.5707963267f)).value) < epsilon); REQUIRE(std::abs(180.0f - math::ToDegrees(Radian<float>(3.1415926535f)).value) < epsilon); REQUIRE(std::abs(360.0f - math::ToDegrees(Radian<float>(6.2831853071f)).value) < epsilon); } SECTION("ToRadians") { constexpr auto epsilon = 0.0000005f; REQUIRE(std::abs(0.0f - math::ToRadians(0.0f).value) < epsilon); REQUIRE(std::abs(0.7853981633f - math::ToRadians(45.0f).value) < epsilon); REQUIRE(std::abs(1.5707963267f - math::ToRadians(90.0f).value) < epsilon); REQUIRE(std::abs(3.1415926535f - math::ToRadians(180.0f).value) < epsilon); REQUIRE(std::abs(6.2831853071f - math::ToRadians(360.0f).value) < epsilon); REQUIRE(std::abs(0.0f - math::ToRadians(Degree<float>(0.0f)).value) < epsilon); REQUIRE(std::abs(0.7853981633f - math::ToRadians(Degree<float>(45.0f)).value) < epsilon); REQUIRE(std::abs(1.5707963267f - math::ToRadians(Degree<float>(90.0f)).value) < epsilon); REQUIRE(std::abs(3.1415926535f - math::ToRadians(Degree<float>(180.0f)).value) < epsilon); REQUIRE(std::abs(6.2831853071f - math::ToRadians(Degree<float>(360.0f)).value) < epsilon); } }
53.357576
98
0.582235
mogemimi
2badcec43f0678aaf67e823200155df19f01511f
2,935
hpp
C++
rconthread.hpp
patrickjane/arkclusterchat
f05ac88188e48e611dec8d731db728175e0d4201
[ "MIT" ]
4
2017-08-11T09:06:31.000Z
2020-08-25T16:53:21.000Z
rconthread.hpp
patrickjane/arkclusterchat
f05ac88188e48e611dec8d731db728175e0d4201
[ "MIT" ]
2
2018-01-26T22:13:23.000Z
2018-01-28T17:11:01.000Z
rconthread.hpp
patrickjane/arkclusterchat
f05ac88188e48e611dec8d731db728175e0d4201
[ "MIT" ]
1
2019-11-26T20:02:40.000Z
2019-11-26T20:02:40.000Z
//*************************************************************************** // File rconthread.hpp // Date 23.07.17 - #1 // Copyright (c) 2017-2017 s710 (s710 (at) posteo (dot) de). All rights reserved. // -------------------------------------------------------------------------- // Ark ClusterChat / RCON thread //*************************************************************************** #ifndef __RCONTHREAD_HPP__ #define __RCONTHREAD_HPP__ #include <list> // std::list #include <string> // std::string #include "thread.hpp" class RConChannel; //*************************************************************************** // struct Work, class WorkList //*************************************************************************** struct Work { std::string message; std::string server; }; class WorkList { friend class RConThread; public: int enqueue(Work* work) { int res= 0; mutex.lock(); list.push_back(work); res= (int)list.size(); mutex.unlock(); return res; } Work* dequeue() { Work* res= 0; mutex.lock(); std::list<Work*>::iterator it= list.begin(); if (it != list.end()) { res= *it; list.pop_front(); } mutex.unlock(); return res; } size_t getCount() { return list.size(); } private: Mutex mutex; std::list<Work*> list; }; //*************************************************************************** // class RConThread //*************************************************************************** class RConThread : public Thread { public: RConThread(std::list<RConThread*>* threads); virtual ~RConThread(); // functions void wakeUp(); void enqueue(Work* work) { queue.enqueue(work); wakeUp(); } int start(int blockTimeout, const char* aHostName, int aPport, const char* aPasswd, const char* aMap); int stop() { return Thread::stop(&waitCond); } protected: // frame int run(); int init(); int exit(); int read(); int write(Work* work); int command(const char* command); // functions int control(); void tell(const char* format, ...); void error(const char* format, ...); void resizeBuffer(int newSize); // data Mutex waitMutex; CondVar waitCond; WorkList queue; // write: other thread read: rconthread char* hostName; char* passwd; char* tellBuffer; char* map; char* sendBuffer; int sendBufferSize; int port; RConChannel* channel; std::list<RConThread*>* threads; }; //----------------------------------------------------------------- #endif // __RCONTHREAD_HPP__
22.234848
108
0.425894
patrickjane
ad9327b96a26520ac33b7ec5c7890d2430908100
2,549
cpp
C++
code/aoce_vulkan_extra/layer/VkLowPassLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
71
2020-10-15T03:13:50.000Z
2022-03-30T02:04:28.000Z
code/aoce_vulkan_extra/layer/VkLowPassLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
9
2021-02-20T10:30:10.000Z
2022-03-04T07:59:58.000Z
code/aoce_vulkan_extra/layer/VkLowPassLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
19
2021-01-01T12:03:02.000Z
2022-03-21T07:59:59.000Z
#include "VkLowPassLayer.hpp" #include "aoce_vulkan/layer/VkPipeGraph.hpp" #include "aoce_vulkan/vulkan/VulkanManager.hpp" namespace aoce { namespace vulkan { namespace layer { VkSaveFrameLayer::VkSaveFrameLayer(/* args */) { // 是否自己使用ComputeShader复制 bUserPipe = true; // 告诉外面,不需要自动连接别层输入 bInput = true; glslPath = "glsl/copyImage.comp.spv"; } VkSaveFrameLayer::~VkSaveFrameLayer() {} void VkSaveFrameLayer::saveImageInfo(const ImageFormat& imageFormat, int32_t nodeIndex, int32_t outNodeIndex) { inFormats[0] = imageFormat; outFormats[0] = imageFormat; inLayers[0].nodeIndex = nodeIndex; inLayers[0].siteIndex = outNodeIndex; } void VkSaveFrameLayer::onCommand() { inTexs.clear(); inTexs.push_back( vkPipeGraph->getOutTex(inLayers[0].nodeIndex, inLayers[0].siteIndex)); if (bUserPipe) { VkLayer::onInitLayer(); VkLayer::onInitPipe(); VkLayer::onCommand(); } else { inTexs[0]->addBarrier(cmd, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_READ_BIT); outTexs[0]->addBarrier(cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT); VulkanManager::copyImage(cmd, inTexs[0].get(), outTexs[0]->image); } } VkLowPassLayer::VkLowPassLayer(/* args */) { saveLayer = std::make_unique<VkSaveFrameLayer>(); } VkLowPassLayer::~VkLowPassLayer() {} void VkLowPassLayer::onInitGraph() { VkDissolveBlendLayer::onInitGraph(); pipeGraph->addNode(saveLayer.get()); } void VkLowPassLayer::onInitNode() { saveLayer->addLine(this, 0, 1); } void VkLowPassLayer::onInitLayer() { VkLayer::onInitLayer(); saveLayer->saveImageInfo(inFormats[0], getGraphIndex(), 0); } VkHighPassLayer::VkHighPassLayer(/* args */) { lowLayer = std::make_unique<VkLowPassLayer>(); paramet = 0.5f; lowLayer->updateParamet(paramet); } VkHighPassLayer::~VkHighPassLayer() {} void VkHighPassLayer::onUpdateParamet() { lowLayer->updateParamet(paramet); } void VkHighPassLayer::onInitGraph() { VkDifferenceBlendLayer::onInitGraph(); pipeGraph->addNode(lowLayer->getLayer()); } void VkHighPassLayer::onInitNode() { lowLayer->addLine(this, 0, 1); setStartNode(this, 0); setStartNode(lowLayer.get(), 1); } } // namespace layer } // namespace vulkan } // namespace aoce
28.322222
80
0.666928
msqljj
ad9e454749b63ebb0939c58da3f8fc7866f7b236
1,216
hpp
C++
include/threepp/objects/Points.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
include/threepp/objects/Points.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
include/threepp/objects/Points.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
// https://github.com/mrdoob/three.js/blob/r129/src/objects/Points.js #ifndef THREEPP_POINTS_HPP #define THREEPP_POINTS_HPP #include "threepp/core/BufferGeometry.hpp" #include "threepp/core/Object3D.hpp" #include "threepp/materials/PointsMaterial.hpp" namespace threepp { class Points : public Object3D { public: std::shared_ptr<BufferGeometry> geometry() override { return geometry_; } std::shared_ptr<Material> material() override { return material_; } static std::shared_ptr<Points> create( std::shared_ptr<BufferGeometry> geometry = BufferGeometry::create(), std::shared_ptr<Material> material = PointsMaterial::create()) { return std::shared_ptr<Points>(new Points(std::move(geometry), std::move(material))); } protected: Points(std::shared_ptr<BufferGeometry> geometry, std::shared_ptr<Material> material) : geometry_(std::move(geometry)), material_(std::move(material)) { } private: std::shared_ptr<BufferGeometry> geometry_; std::shared_ptr<Material> material_; }; }// namespace threepp #endif//THREEPP_POINTS_HPP
27.022222
97
0.657895
maidamai0
ada2aa5ff834075ae22b491f1394209a9afeb361
4,576
cpp
C++
moos-ivp-local/src/lib_anrp_util/NMEAMessage.cpp
ucsb-coast-lab/rcProto-MOOS-master1
e886b11cae14bc6cff860621b1c2c6480033e077
[ "MIT" ]
9
2016-02-25T03:25:53.000Z
2022-03-27T09:47:50.000Z
moos-ivp-local/src/lib_anrp_util/NMEAMessage.cpp
ucsb-coast-lab/rcProto-MOOS-master1
e886b11cae14bc6cff860621b1c2c6480033e077
[ "MIT" ]
null
null
null
moos-ivp-local/src/lib_anrp_util/NMEAMessage.cpp
ucsb-coast-lab/rcProto-MOOS-master1
e886b11cae14bc6cff860621b1c2c6480033e077
[ "MIT" ]
4
2016-06-02T17:42:42.000Z
2021-12-15T09:37:55.000Z
/************************************************************************* * NMEAMessage.cpp - ************************************************************************* * (c) 2004 Andrew Patrikalakis <anrp@cml3.mit.edu> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *************************************************************************/ #include "NMEAMessage.h" #include <string> #include <stdlib.h> #include <vector> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <ctype.h> using namespace std; enum mode { MODE_INPUT = 0, MODE_OUTPUT, MODE_UNKNOWN, }; NMEAMessage::NMEAMessage() { msg = ""; parts.resize(0); mode = MODE_UNKNOWN; } NMEAMessage::NMEAMessage(string s) { NMEAMessage(); Set(s); } NMEAMessage::NMEAMessage(const char *s) { NMEAMessage(); Set(s); } NMEAMessage::~NMEAMessage() { parts.clear(); } static int gen_cksum(const char *str) { const char *st, *ed; int sum = 0; st = strchr(str, '$'); if(st == NULL) st = strchr(str, '!'); ed = strchr(str, '*'); if (!st || !ed) { return 0; } for (st++; st < ed; st++) { sum ^= *st; } return sum; } int NMEAMessage::VerifyChecksum() { char out[3]; const char *ed; snprintf(out, 3, "%02x", gen_cksum(msg.c_str())); ed = strchr(msg.c_str(), '*'); if ((tolower(out[0]) == tolower(*(ed + 1))) && (tolower(out[1]) == tolower(*(ed + 2)))) { return 0; } else { return -1; } } int NMEAMessage::Parse() { bool has_cs = true; if (msg[0] != '$') if(msg[0] != '!') return -1; if(msg.find('*') == string::npos) { has_cs = false; } else { if(msg.find('*') == msg.size()-1) { has_cs = false; } } if (has_cs && VerifyChecksum() == -1) { if(getenv("NMEAMESSAGE_SHUTUP") == NULL) fprintf(stderr, "NMEAMessage:: bad checksum on [%s]\n", msg.c_str()); } parts.resize(0); char *s = strdup(msg.c_str() + 1), *sp, *p; sp = s; if(strrchr(s, '*')) *(strrchr(s, '*')) = 0; while ((p = strchr(s, ',')) != NULL) { *p = 0; parts.push_back(string(s)); s = p + 1; } parts.push_back(string(s)); free(sp); return 0; } void NMEAMessage::Set(string s) { msg = s; mode = MODE_INPUT; Parse(); } void NMEAMessage::Set(const char *s) { if (s == NULL) { fprintf(stderr, "<null message>"); return ; } msg = string(s); mode = MODE_INPUT; Parse(); } string NMEAMessage::Part(int i) { if (i >= (signed int)parts.size() || i < 0) return "<NMEAMessage::out of bounds>"; return parts[i]; } string NMEAMessage::PartPlus(int i) { if(i >= (signed int)parts.size() || i < 0) { return ""; } string ret = ""; for(int j=i; j<parts.size(); j++) { ret += parts[j]; ret += ","; } ret.erase(ret.size()-1, 1); return ret; } string NMEAMessage::Get() { return msg; } int NMEAMessage::print(bool usecs, const char *s, ...) { va_list ap; va_start(ap, s); char tmpbuf[1024]; vsnprintf(tmpbuf, 1024, s, ap); va_end(ap); char tmpbuf2[1030]; char tmpbuf3[1038]; snprintf(tmpbuf2, 1030, "$%s%s", tmpbuf, usecs ? "*" : "\r\n"); if (usecs) { snprintf(tmpbuf3, 1038, "%s%02X\r\n", tmpbuf2, 0xff & gen_cksum(tmpbuf2)); } msg = string(usecs ? tmpbuf3 : tmpbuf2); mode = MODE_OUTPUT; Parse(); return 0; } void NMEAMessage::Dump() { fprintf(stderr, "> %s <\n", msg.c_str()); } #ifdef TESTING int main(int argc, char *argv[]) { NMEAMessage m; m.print(true, argv[1]); printf("%s\n", m.Get().c_str()); for (int i = 0; i < m.GetL(); i++) { printf("> %i \"%s\"\n", i, m.Part(i).c_str()); } return 0; } #endif
19.226891
74
0.52229
ucsb-coast-lab
ada50f60a87313240d2748040514cd6b22f31ee0
1,007
cpp
C++
src/render/Drawable/UidDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Drawable/UidDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Drawable/UidDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <mtt/render/Drawable/UidDrawableModificator.h> #include <mtt/render/DrawPlan/DrawPlanBuildInfo.h> using namespace mtt; void UidDrawableModificator::setUid(UID newValue) noexcept { _uid = newValue; } void UidDrawableModificator::draw(DrawPlanBuildInfo& buildInfo, DrawableModificator** next, size_t modifiactorsLeft, Drawable& drawable) const { const void* oldUID = buildInfo.extraData.data(DrawPlanBuildExtraData::objectUIDIndex); try { buildInfo.extraData.setData(&_uid, DrawPlanBuildExtraData::objectUIDIndex); drawNext(buildInfo, next, modifiactorsLeft, drawable); } catch (...) { buildInfo.extraData.setData(oldUID, DrawPlanBuildExtraData::objectUIDIndex); throw; } buildInfo.extraData.setData(oldUID, DrawPlanBuildExtraData::objectUIDIndex); }
28.771429
79
0.616683
AluminiumRat
ada58fce04c811acd874e121149921c954de5608
2,990
cpp
C++
EXAMPLES/MFC/UTILITY/Guidegen/guidgen.cpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
EXAMPLES/MFC/UTILITY/Guidegen/guidgen.cpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
EXAMPLES/MFC/UTILITY/Guidegen/guidgen.cpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
// guidgen.cpp : Defines the class behaviors for the application. // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1995 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "guidgen.h" #include "guidgdlg.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CGuidGenApp BEGIN_MESSAGE_MAP(CGuidGenApp, CWinApp) //{{AFX_MSG_MAP(CGuidGenApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CGuidGenApp construction CGuidGenApp::CGuidGenApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CGuidGenApp object CGuidGenApp theApp; ///////////////////////////////////////////////////////////////////////////// // CGuidGenApp initialization BOOL CGuidGenApp::InitInstance() { SetRegistryKey(_T("Microsoft\\MFC 3.0 Samples")); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. Enable3dControls(); if (::CoInitialize(NULL) != S_OK) { AfxMessageBox(IDP_ERR_INIT_OLE); return FALSE; } // process command line arguments CWnd* pParentWnd = NULL; for (LPCTSTR lpsz = m_lpCmdLine; *lpsz != 0; ++lpsz) { if (*lpsz != '-' && *lpsz != '/') continue; switch (lpsz[1]) { // "/A" or "/a" allows the window to be parented to the IDE window // add GUIDGEN /A to your tools menu for easy access! case 'a': case 'A': pParentWnd = CWnd::GetForegroundWindow(); break; } } CGuidGenDlg dlg(pParentWnd); m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } int CGuidGenApp::ExitInstance() { ::CoUninitialize(); return CWinApp::ExitInstance(); }
27.181818
78
0.61505
earthsiege2
adb10b8531bea767b9cdb8873759a2500db7243c
2,932
cpp
C++
EU4toV2/Source/EU4World/EU4Version.cpp
beerhall/paradoxGameConverters
96b6f91ebc413795afd63f40f6ecf4ca83fa9460
[ "MIT" ]
114
2015-06-07T20:27:45.000Z
2020-08-16T05:05:56.000Z
EU4toV2/Source/EU4World/EU4Version.cpp
iamdafu/paradoxGameConverters
674364a22917155642ade923e5dfbe38a5fa9610
[ "MIT" ]
553
2015-07-20T23:58:26.000Z
2019-06-13T21:45:56.000Z
EU4toV2/Source/EU4World/EU4Version.cpp
iamdafu/paradoxGameConverters
674364a22917155642ade923e5dfbe38a5fa9610
[ "MIT" ]
106
2015-07-27T00:21:16.000Z
2020-06-10T10:13:13.000Z
/*Copyright (c) 2017 The Paradox Game Converters Project 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 "EU4Version.h" #include "Log.h" EU4Version::EU4Version() { first = 0; second = 0; third = 0; fourth = 0; } EU4Version::EU4Version(shared_ptr<Object> obj) { vector<shared_ptr<Object>> numObj; // the number in this part of the version numObj = obj->getValue("first"); if (numObj.size() > 0) { first = atoi(numObj[0]->getLeaf().c_str()); } numObj = obj->getValue("second"); if (numObj.size() > 0) { second = atoi(numObj[0]->getLeaf().c_str()); } numObj = obj->getValue("third"); if (numObj.size() > 0) { third = atoi(numObj[0]->getLeaf().c_str()); } numObj = obj->getValue("forth"); if (numObj.size() > 0) { fourth = atoi(numObj[0]->getLeaf().c_str()); } } EU4Version::EU4Version(string version) { int dot = version.find_first_of('.'); // the dots separating the version parts first = atoi(version.substr(0, dot).c_str()); version = version.substr(dot + 1, version.size()); dot = version.find_first_of('.'); second = atoi(version.substr(0, dot).c_str()); version = version.substr(dot + 1, version.size()); dot = version.find_first_of('.'); third = atoi(version.substr(0, dot).c_str()); version = version.substr(dot + 1, version.size()); dot = version.find_first_of('.'); fourth = atoi(version.substr(0, dot).c_str()); } bool EU4Version::operator >= (EU4Version& rhs) const { if (first > rhs.first) { return true; } else if ((first == rhs.first) && (second > rhs.second)) { return true; } else if ((first == rhs.first) && (second == rhs.second) && (third > rhs.third)) { return true; } else if ((first == rhs.first) && (second == rhs.second) && (third == rhs.third) && (fourth > rhs.fourth)) { return true; } else if ((first == rhs.first) && (second == rhs.second) && (third == rhs.third) && (fourth == rhs.fourth)) { return true; } else { return false; } }
26.899083
107
0.687244
beerhall
adb14aeb2e4f5ebb2287d7f219e64a8e9c4db383
3,651
hpp
C++
include/MOE/MahiOpenExo/JointHardware.hpp
mahilab/MOE
e35e855a8b36fe8a619eada276d95739dfb30ca8
[ "MIT" ]
null
null
null
include/MOE/MahiOpenExo/JointHardware.hpp
mahilab/MOE
e35e855a8b36fe8a619eada276d95739dfb30ca8
[ "MIT" ]
null
null
null
include/MOE/MahiOpenExo/JointHardware.hpp
mahilab/MOE
e35e855a8b36fe8a619eada276d95739dfb30ca8
[ "MIT" ]
null
null
null
#pragma once #include <MOE/MahiOpenExo/Joint.hpp> #include <MOE/MahiOpenExo/MoeConfigurationHardware.hpp> #include <Mahi/Daq/Handle.hpp> #include <Mahi/Util/Math/Butterworth.hpp> namespace moe { //============================================================================== // CLASS DECLARATION //============================================================================== class JointHardware : public Joint { public: /// Constructor JointHardware(const std::string &name, std::array<double, 2> position_limits, double velocity_limit, double torque_limit, mahi::robo::Limiter limiter, double actuator_transmission, std::shared_ptr<mahi::daq::EncoderHandle> position_sensor, double position_transmission, const double &velocity_sensor, VelocityEstimator velocity_estimator, double velocity_transmission, double motor_kt, double amp_gain, mahi::daq::DOHandle motor_enable_handle, mahi::daq::TTL motor_enable_value, mahi::daq::AOHandle amp_write_handle, mahi::util::Frequency velocity_filter_sample_rate = mahi::util::hertz(1000)); /// Converts PositionSensor position to Joint Position double get_position(); /// Converts PositionSensor velocity to Joint velocity double get_velocity(); /// Sets the joint torque to #new_torque void set_torque(double new_torque); /// Enables the joint's position sensor, velocity sensor, and actuator bool enable(); /// Disables the joint's position sensor, velocity sensor, and actuator bool disable(); /// if velocity estimator is Software, this filters velocity. Otherwise this does nothing void filter_velocity() override; private: std::shared_ptr<mahi::daq::EncoderHandle> m_position_sensor; // pointer to the PositionSensor of this Joint const double &m_velocity_sensor; // Pointer to the VelocitySensor of this Joint // filter variables VelocityEstimator m_velocity_estimator; // Velocity Estimator of this Joint mahi::util::Butterworth m_velocity_filter; // filter for velocity double m_pos_last = 0; // last position value for velocity filter double m_time_last = -0.001; // last time value for velocity filter double m_vel_filtered = 0; // filtered velocity for velocity filter mahi::util::Clock m_clock; // clock for velocity filter double m_actuator_transmission; // transmission ratio describing the // multiplicative gain in torque from Joint // space to Actuator space, actuator Torque = // actuator transmission * joint torque double m_position_transmission; // gain in position from PositionSensor space to Joint space, joint position = position sensor transmission * sensed position double m_velocity_transmission; // gain in velocity from VelocitySensor space to Joint space, joint velocity = velocity sensor transmission * sensed velocity double m_motor_kt; // motor gain in T/A double m_amp_gain; // amplifier gain in A/V mahi::daq::DOHandle m_motor_enable_handle; // DO channel used to control if motor is enabled/disabled mahi::daq::TTL m_motor_enable_value; // Digital value to set for to enable motor through the amplifier mahi::daq::AOHandle m_amp_write_handle; // AO channel to write to for setting desired torque values }; } // namespace moe
46.21519
161
0.645303
mahilab
adb71fcdcd91caa885e3e9d2e3fe28c34053d608
880
hpp
C++
src/ui/widgets/graphics_items/unallocated_block_graphics_item.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
3
2019-04-26T17:48:24.000Z
2021-11-08T20:21:51.000Z
src/ui/widgets/graphics_items/unallocated_block_graphics_item.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
90
2019-04-25T17:23:10.000Z
2022-02-12T19:49:55.000Z
src/ui/widgets/graphics_items/unallocated_block_graphics_item.hpp
judoassistant/judoassistant
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
[ "MIT" ]
null
null
null
#pragma once #include <QGraphicsItem> #include "core/stores/match_store.hpp" #include "core/rulesets/ruleset.hpp" #include "core/draw_systems/draw_system.hpp" class CategoryStore; class UnallocatedBlockGraphicsItem : public QGraphicsItem { public: static constexpr int WIDTH = 200; static constexpr int HEIGHT = 80; static constexpr int PADDING = 5; UnallocatedBlockGraphicsItem(const CategoryStore &category, MatchType type); QRectF boundingRect() const override; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override; void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; private: const CategoryStore *mCategory; MatchType mType; };
27.5
100
0.778409
svendcsvendsen
adc5efdeb5dc5502affd2d3f539711cd3abf2e8a
2,966
hpp
C++
include/wf700tk/detail/message_base.hpp
VJSchneid/wf-700tk
d94b18437a90b0b081c71dc3c7eac3c0aed494a5
[ "BSL-1.0" ]
null
null
null
include/wf700tk/detail/message_base.hpp
VJSchneid/wf-700tk
d94b18437a90b0b081c71dc3c7eac3c0aed494a5
[ "BSL-1.0" ]
null
null
null
include/wf700tk/detail/message_base.hpp
VJSchneid/wf-700tk
d94b18437a90b0b081c71dc3c7eac3c0aed494a5
[ "BSL-1.0" ]
null
null
null
#ifndef WF700TK_DETAIL_MESSAGE_BASE_HPP #define WF700TK_DETAIL_MESSAGE_BASE_HPP #include <array> namespace wf700tk::detail { struct message_base { message_base(unsigned char length, bool is_request); constexpr const static unsigned char start_byte_ = 0x02; constexpr const static unsigned char end_byte_ = 0x03; constexpr const static unsigned char request_byte_ = 0x10; constexpr const static unsigned char response_byte_ = 0x20; constexpr const static unsigned int tail_size_ = 2; unsigned char length() const; bool ack(unsigned char v); unsigned char ack() const; std::array<unsigned char, 3> head_; }; #if false enum class msg_type : unsigned char { master_to_wf700tk = 0x10, wf700tk_to_master = 0x20 }; /** * @brief The msg_head struct contains all * information for the starting sequence * with exceptions to the length */ struct msg_head { public: constexpr msg_type type() const noexcept { return type_; } constexpr void type(msg_type v) noexcept { type_ = v; } /// @returns false if v is invalid, i.e. exceeds 0b111 constexpr bool type(unsigned char v) noexcept { if (v > 0b111) { return false; } type_ = static_cast<msg_type>(v << 4); return true; } constexpr unsigned char ack() const noexcept { return ack_; } /// @returns false if v is invalid, i.e. exceeds 0xf constexpr bool ack(unsigned char v) noexcept { if (v > 0x0f) { return false; } ack_ = v; return true; } private: msg_type type_ = msg_type::master_to_wf700tk; unsigned char ack_ = 0x00; }; /** * @brief WF-700TK message holding generic data content * * This class holds the message head information and customizable data * fields for the message. * * @tparam DataType The type used to generate the message's data * @param[in] isRequest \a true if message is send from master to WF-700TK * otherwise \a false */ template <typename Data> struct message : public msg_head, private Data::value_type { using data_type = typename Data::value_type; constexpr message() noexcept : data_type() { Data::set_defaults(*this); } constexpr const data_type &data() const noexcept { return static_cast<const data_type &>(*this); } constexpr data_type &data() noexcept { return static_cast<data_type &>(*this); } constexpr unsigned char length() const noexcept { return Data::data_length(*this) + 5; } }; struct null_data { struct value_type { unsigned length = 0; }; constexpr static void set_defaults(message<null_data> &v) noexcept { v.type(msg_type::master_to_wf700tk); } constexpr static unsigned char data_length(message<null_data> &v) { return v.data().length; } }; #endif } // namespace wf700tk::detail #endif // WF700TK_DETAIL_MESSAGE_BASE_HPP
26.017544
77
0.667903
VJSchneid
adcafd7fc9fbfe74c79079c638e60482ac060482
2,007
cpp
C++
Utility/Context/ActivationFunctionContext.cpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
Utility/Context/ActivationFunctionContext.cpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
Utility/Context/ActivationFunctionContext.cpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
#include "ActivationFunctionContext.hpp" #include "CoreLogger.hpp" ActivationFunction ActivationFunctionContext::m_activationFunctionTable[ACTIVATION_FUNCTIONS_COUNT]; const bool ActivationFunctionContext::m_initialized = false; void ActivationFunctionContext::Initialize() { if (!m_initialized) { m_activationFunctionTable[LINEAR_ACTIVATION_FUNCTION] = [](const Neuron input) { return input; }; m_activationFunctionTable[FAST_SIGMOID_ACTIVATION_FUNCTION] = [](const Neuron input) { return input / (1 + std::fabs(input)); }; m_activationFunctionTable[RELU_ACTIVATION_FUNCTION] = [](const Neuron input) { return input < 0 ? 0 : input; }; m_activationFunctionTable[LEAKY_RELU_ACTIVATION_FUNCTION] = [](const Neuron input) { return input >= 0 ? input : input * 0.1; }; m_activationFunctionTable[TANH_ACTIVATION_FUNCTION] = [](const Neuron input) { return tanh(input); }; CoreLogger::PrintSuccess("ActivationFunctionContext initialized correctly"); } else CoreLogger::PrintError("Activation function context initialization was performed more than once!"); } Neuron ActivationFunctionContext::Compute(const size_t index, const Neuron neuron) { if (index >= ACTIVATION_FUNCTIONS_COUNT) { CoreLogger::PrintError("Activation function index is out of range!"); return m_activationFunctionTable[LINEAR_ACTIVATION_FUNCTION](neuron); } return m_activationFunctionTable[index](neuron); } std::string ActivationFunctionContext::GetString(const size_t index) { switch (index) { case FAST_SIGMOID_ACTIVATION_FUNCTION: return "Fast sigmoid activation function"; case RELU_ACTIVATION_FUNCTION: return "ReLU activation function"; case LEAKY_RELU_ACTIVATION_FUNCTION: return "Leaky ReLU activation function"; case TANH_ACTIVATION_FUNCTION: return "Tanh activation function"; case LINEAR_ACTIVATION_FUNCTION: return "Linear activation function"; } CoreLogger::PrintError("Activation function index is out of range!"); return GetString(LINEAR_ACTIVATION_FUNCTION); }
38.596154
130
0.788241
devmichalek
add59680e33fcec8675fe6895e0c7f91da55b7cb
1,839
hpp
C++
src/algorithms/data_structures/hashmap/group_shifted_strings.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
src/algorithms/data_structures/hashmap/group_shifted_strings.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
src/algorithms/data_structures/hashmap/group_shifted_strings.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#ifndef CPPNOTESMAIN_GROUP_SHIFTED_STRINGS_HPP #define CPPNOTESMAIN_GROUP_SHIFTED_STRINGS_HPP /* https://leetcode.com/problems/group-shifted-strings/ Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. Example: Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Output: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] */ #include <unordered_map> #include <vector> namespace Algo::DS::HashMap { class ShiftedStrings { std::unordered_map<std::string, std::vector<std::string>> m_groups; std::string get_base(std::string str) { if (str.empty()) { return {}; } const auto distance = str.front() - 'a'; for (auto& c : str) { const auto c_distance = c - 'a'; if (c_distance >= distance) { c -= distance; } else { const auto shift = distance - c_distance - 1; c = 'z' - shift; } } return str; } public: std::vector<std::vector<std::string>> group(const std::vector<std::string>& strings) { for (const auto& str : strings) { const auto base = get_base(str); m_groups[base].push_back(str); } std::vector<std::vector<std::string>> result; for (const auto& [_, group] : m_groups) { result.push_back(group); } return result; } }; } #endif //CPPNOTESMAIN_GROUP_SHIFTED_STRINGS_HPP
27.044118
94
0.540511
iamantony
add74ec39cf147f3afbcfaecb3b1fcc0dddf1cb2
658
hpp
C++
src/comppackdb.hpp
BurAndBY/pkgj
ba4ecba588b2204c150b7780ceeda123545c408f
[ "BSD-2-Clause" ]
904
2018-03-09T05:20:11.000Z
2022-03-26T02:37:33.000Z
src/comppackdb.hpp
BurAndBY/pkgj
ba4ecba588b2204c150b7780ceeda123545c408f
[ "BSD-2-Clause" ]
383
2018-03-11T02:47:37.000Z
2022-03-17T11:51:32.000Z
src/comppackdb.hpp
BurAndBY/pkgj
ba4ecba588b2204c150b7780ceeda123545c408f
[ "BSD-2-Clause" ]
132
2018-03-12T22:35:16.000Z
2022-03-03T17:06:55.000Z
#pragma once #include "http.hpp" #include "sqlite.hpp" #include <array> #include <memory> #include <optional> #include <string> #include <vector> #include <cstdint> class CompPackDatabase { public: struct Item { std::string path; std::string app_version; }; CompPackDatabase(const std::string& dbPath); void update(Http* http, const std::string& update_url); std::optional<Item> get(const std::string& titleid); private: static constexpr auto MAX_DB_SIZE = 4 * 1024 * 1024; std::string _dbPath; SqlitePtr _sqliteDb = nullptr; void parse_entries(std::string& db_data); void reopen(); };
16.45
59
0.664134
BurAndBY