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
f9ab887a9818e9fa3a2d15da97b21762827202fe
1,808
hpp
C++
level_editor/export/cpp.hpp
xiroV/game-tools
01b7d4f0269cfdcb70901ed07705d1467ed66f37
[ "MIT" ]
1
2021-11-05T10:06:16.000Z
2021-11-05T10:06:16.000Z
level_editor/export/cpp.hpp
xiroV/game-tools
01b7d4f0269cfdcb70901ed07705d1467ed66f37
[ "MIT" ]
24
2021-10-03T15:33:16.000Z
2021-11-29T22:24:57.000Z
level_editor/export/cpp.hpp
xiroV/game-tools
01b7d4f0269cfdcb70901ed07705d1467ed66f37
[ "MIT" ]
null
null
null
#ifndef __EXPORT_CPP__ #define __EXPORT_CPP__ #include "exporter.hpp" #include <sstream> struct CppExporter : Exporter { CppExporter() { setName("C++"); setExtension("hpp"); } std::string generate(Editor* editor) { stringstream output; output << "//version " << editor->version << endl; output << endl; output << "#include <string>" << endl; output << "#include <vector>" << endl; output << "#include \"level_data.hpp\"" << endl; output << endl; output << "struct " << editor->levelName << " : LevelData {"<< endl << " std::vector<LevelObject> objects;" << endl; output << " void init() override {" << endl; output << " objects = {" << endl; for (Object const& obj : editor->objects) { output << " {" << obj.x << ", " << obj.y << ", " << obj.width << ", " << obj.height << ", " << obj.rotation << ", " << "\"" << editor->objectTypes[obj.type].name << "\"," << "{"; for (ObjectData const& keyValuePair : obj.data) { output << "{\"" << keyValuePair.key << "\", \"" << keyValuePair.value << "\"},"; } output << "}"; output << "}," << endl; } output << " };" << endl << " };" << endl << endl; output << " std::vector<LevelObject> &getObjects() override {" << endl << " return objects;" << endl << " }" << endl << "};" << endl << endl; return output.str(); } }; #endif
30.133333
100
0.400442
xiroV
f9acf061a969b56be116e9f4506f5b48d03977a4
788
hpp
C++
include/canard/net/ofp/v13/detail/basic_queue_property.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
include/canard/net/ofp/v13/detail/basic_queue_property.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
8
2016-07-21T11:29:13.000Z
2016-12-03T05:16:42.000Z
include/canard/net/ofp/v13/detail/basic_queue_property.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
#ifndef CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP #define CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP #include <canard/net/ofp/detail/basic_queue_property.hpp> #include <canard/net/ofp/v13/openflow.hpp> namespace canard { namespace net { namespace ofp { namespace v13 { namespace queue_properties { namespace queue_property_detail { template <class T> using basic_queue_property = ofp::detail::basic_queue_property< T , ofp::v13::protocol::ofp_queue_prop_header , ofp::v13::protocol::ofp_queue_properties >; } // namespace queue_property_detail } // namespace queue_properties } // namespace v13 } // namespace ofp } // namespace net } // namespace canard #endif // CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP
27.172414
70
0.796954
amedama41
f9ae0c07f267178fe9e0d47a92d739f1423e4cf2
985
hpp
C++
include/saci/qt/radio_btn/radio_btn.hpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
1
2020-07-29T20:42:58.000Z
2020-07-29T20:42:58.000Z
include/saci/qt/radio_btn/radio_btn.hpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
null
null
null
include/saci/qt/radio_btn/radio_btn.hpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
null
null
null
// Copyright Ricardo Calheiros de Miranda Cosme 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "saci/qt/base_widget.hpp" #include "saci/qt/radio_btn/detail/view_to_model.hpp" #include <QRadioButton> namespace saci { namespace qt { struct radio_btn : base_widget< QRadioButton, bool, detail::radio_btn_to_model > { using base = base_widget<QRadioButton, bool, detail::radio_btn_to_model>; radio_btn() = default; template<typename ObservableObject> radio_btn(ObservableObject& model, QRadioButton& widget) : base(model, widget, SIGNAL(toggled(bool)), SLOT(propagates(bool)), [](QRadioButton& widget, bool v) { widget.setChecked(v); }) {} }; }}
24.02439
61
0.598985
ricardocosme
f9b3f5b5a0ad2fea452a20a10754d26251db1b3a
2,015
cpp
C++
C9_Histogram/Template/main.cpp
StarryThrone/OpenCV_Learning_Notes
b52151f443cdde38daf1962b7dc5429b0f050f13
[ "MIT" ]
2
2020-09-03T09:49:23.000Z
2021-06-11T09:20:13.000Z
C9_Histogram/Template/main.cpp
StarryThrone/OpenCV_Learning_Notes
b52151f443cdde38daf1962b7dc5429b0f050f13
[ "MIT" ]
null
null
null
C9_Histogram/Template/main.cpp
StarryThrone/OpenCV_Learning_Notes
b52151f443cdde38daf1962b7dc5429b0f050f13
[ "MIT" ]
1
2020-09-03T09:49:30.000Z
2020-09-03T09:49:30.000Z
// // main.cpp // Template // // Created by chenjie on 2020/7/15. // Copyright © 2020 chenjie. All rights reserved. // #include <iostream> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> void help(const char * argv[]) { std::cout << "\n" << "\nExample: using matchTemplate(). The call is:\n" << "\n" << argv [0] << " <template> <image_to_be_searched?\n" << "\nExample:\n" << argv[0] << "../BlueCup.jpg ../adrian.jpg" << "\n" << " This routine will search using all methods:\n" << " cv::TM_SQDIFF 0\n" << " cv::TM_SQDIFF_NORMED 1\n" << " cv::TM_CCORR 2\n" << " cv::TM_CCORR_NORMED 3\n" << " cv::TM_CCOEFF 4\n" << " cv::TM_CCOEFF_NORMED 5\n" << "\n" << std::endl; } int main(int argc, const char * argv[]) { if (argc != 3) { help(argv); return -1; } // 读取匹配模版图像 cv::Mat templ = cv::imread(argv[1], 1); if (templ.empty()) { std::cout << "Error on reading template " << argv[1] << std::endl; help(argv); return -1; } // 读取待查找图像 cv::Mat src = cv::imread(argv[2], 1); if (src.empty()) { std::cout << "Error on reading src image " << argv[2] << std::endl; help(argv); return -1; } // 使用6种不同的方法执行模版匹配操作 cv::Mat ftmp[6]; for (int i = 0; i < 6; ++i) { cv::matchTemplate( src, templ, ftmp[i], i); cv::normalize(ftmp[i],ftmp[i],1,0,cv::NORM_MINMAX); } // 显示匹配结果 cv::imshow("Template", templ); cv::imshow("Image", src); cv::imshow("SQDIFF", ftmp[0]); cv::imshow("SQDIFF_NORMED", ftmp[1]); cv::imshow("CCORR", ftmp[2]); cv::imshow("CCORR_NORMED", ftmp[3]); cv::imshow("CCOEFF", ftmp[4]); cv::imshow("CCOEFF_NORMED", ftmp[5]); // 挂起程序等待用户输入事件 cv::waitKey(0); return 0; }
26.866667
78
0.490819
StarryThrone
f9b621e1b5224710b65b5ac0ba9c61a63ac17024
8,348
cpp
C++
src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp
TheDoubleB/acpl
cae3169da73bbec9fcab261ba01b2170d3a22de2
[ "BSD-3-Clause" ]
null
null
null
src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp
TheDoubleB/acpl
cae3169da73bbec9fcab261ba01b2170d3a22de2
[ "BSD-3-Clause" ]
null
null
null
src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp
TheDoubleB/acpl
cae3169da73bbec9fcab261ba01b2170d3a22de2
[ "BSD-3-Clause" ]
null
null
null
#ifndef ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP #define ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP // WARNING: Do not modify this file because it was generated using i18nproc #include "../../Charsets.h" #include "../../_cp/Memory.inc.cpp" namespace acpl { namespace i18n { class Charset_ISO_8859_16_2001 { public: static inline bool IsCompatible(const char *nMimeName, acpl::Charsets::ByteOrderMask nBom, acpl::Charsets::Fpc &nFpc) { if (nMimeName != NULL && acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO-8859-16") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO_8859-16") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "latin10") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "l10") != 0 && acpl::pi::_string_ascii_strcasecmp(nMimeName, "iso-ir-226") != 0) return false; if (nBom != acpl::Charsets::bomNone) return false; nFpc.Set( IsCompatible, GetMimeName, IsBomSuggested, CreateBom, MinSeqSize, MaxSeqSize, Decode, Encode ); return true; } static inline const char *GetMimeName() { return "ISO-8859-16"; } static inline bool IsBomSuggested() { return false; } static inline acpl::SizeT CreateBom(acpl::UInt8 *, acpl::SizeT) { return 0; } static inline acpl::SizeT MinSeqSize() { return 1; } static inline acpl::SizeT MaxSeqSize() { return 1; } static inline acpl::SizeT Decode(const acpl::UInt8 *nBfr, acpl::SizeT nBfrSize, acpl::Unichar &nUnicodeChar) { if (nBfrSize >= 1) { acpl::UInt8 oChar = *nBfr; // Mirror mappings if ( oChar <= 0xA0 || oChar == 0xA7 || oChar == 0xA9 || oChar == 0xAB || oChar == 0xAD || (oChar >= 0xB0 && oChar <= 0xB1) || (oChar >= 0xB6 && oChar <= 0xB7) || oChar == 0xBB || (oChar >= 0xC0 && oChar <= 0xC2) || oChar == 0xC4 || (oChar >= 0xC6 && oChar <= 0xCF) || (oChar >= 0xD2 && oChar <= 0xD4) || oChar == 0xD6 || (oChar >= 0xD9 && oChar <= 0xDC) || (oChar >= 0xDF && oChar <= 0xE2) || oChar == 0xE4 || (oChar >= 0xE6 && oChar <= 0xEF) || (oChar >= 0xF2 && oChar <= 0xF4) || oChar == 0xF6 || (oChar >= 0xF9 && oChar <= 0xFC) || oChar == 0xFF ) { nUnicodeChar = static_cast<acpl::Unichar>(oChar); return 1; } // Unique mappings if (oChar == 0xA1) nUnicodeChar = 0x0104; else if (oChar == 0xA2) nUnicodeChar = 0x0105; else if (oChar == 0xA3) nUnicodeChar = 0x0141; else if (oChar == 0xA4) nUnicodeChar = 0x20AC; else if (oChar == 0xA5) nUnicodeChar = 0x201E; else if (oChar == 0xA6) nUnicodeChar = 0x0160; else if (oChar == 0xA8) nUnicodeChar = 0x0161; else if (oChar == 0xAA) nUnicodeChar = 0x0218; else if (oChar == 0xAC) nUnicodeChar = 0x0179; else if (oChar == 0xAE) nUnicodeChar = 0x017A; else if (oChar == 0xAF) nUnicodeChar = 0x017B; else if (oChar == 0xB2) nUnicodeChar = 0x010C; else if (oChar == 0xB3) nUnicodeChar = 0x0142; else if (oChar == 0xB4) nUnicodeChar = 0x017D; else if (oChar == 0xB5) nUnicodeChar = 0x201D; else if (oChar == 0xB8) nUnicodeChar = 0x017E; else if (oChar == 0xB9) nUnicodeChar = 0x010D; else if (oChar == 0xBA) nUnicodeChar = 0x0219; else if (oChar == 0xBC) nUnicodeChar = 0x0152; else if (oChar == 0xBD) nUnicodeChar = 0x0153; else if (oChar == 0xBE) nUnicodeChar = 0x0178; else if (oChar == 0xBF) nUnicodeChar = 0x017C; else if (oChar == 0xC3) nUnicodeChar = 0x0102; else if (oChar == 0xC5) nUnicodeChar = 0x0106; else if (oChar == 0xD0) nUnicodeChar = 0x0110; else if (oChar == 0xD1) nUnicodeChar = 0x0143; else if (oChar == 0xD5) nUnicodeChar = 0x0150; else if (oChar == 0xD7) nUnicodeChar = 0x015A; else if (oChar == 0xD8) nUnicodeChar = 0x0170; else if (oChar == 0xDD) nUnicodeChar = 0x0118; else if (oChar == 0xDE) nUnicodeChar = 0x021A; else if (oChar == 0xE3) nUnicodeChar = 0x0103; else if (oChar == 0xE5) nUnicodeChar = 0x0107; else if (oChar == 0xF0) nUnicodeChar = 0x0111; else if (oChar == 0xF1) nUnicodeChar = 0x0144; else if (oChar == 0xF5) nUnicodeChar = 0x0151; else if (oChar == 0xF7) nUnicodeChar = 0x015B; else if (oChar == 0xF8) nUnicodeChar = 0x0171; else if (oChar == 0xFD) nUnicodeChar = 0x0119; else if (oChar == 0xFE) nUnicodeChar = 0x021B; else return 0; return 1; } return 0; } static inline acpl::SizeT Encode(acpl::Unichar nUnicodeChar, acpl::UInt8 *nBfr, acpl::SizeT nBfrSize) { if (nBfrSize >= 1) { // Mirror mappings if ( nUnicodeChar <= 0xA0 || nUnicodeChar == 0xA7 || nUnicodeChar == 0xA9 || nUnicodeChar == 0xAB || nUnicodeChar == 0xAD || (nUnicodeChar >= 0xB0 && nUnicodeChar <= 0xB1) || (nUnicodeChar >= 0xB6 && nUnicodeChar <= 0xB7) || nUnicodeChar == 0xBB || (nUnicodeChar >= 0xC0 && nUnicodeChar <= 0xC2) || nUnicodeChar == 0xC4 || (nUnicodeChar >= 0xC6 && nUnicodeChar <= 0xCF) || (nUnicodeChar >= 0xD2 && nUnicodeChar <= 0xD4) || nUnicodeChar == 0xD6 || (nUnicodeChar >= 0xD9 && nUnicodeChar <= 0xDC) || (nUnicodeChar >= 0xDF && nUnicodeChar <= 0xE2) || nUnicodeChar == 0xE4 || (nUnicodeChar >= 0xE6 && nUnicodeChar <= 0xEF) || (nUnicodeChar >= 0xF2 && nUnicodeChar <= 0xF4) || nUnicodeChar == 0xF6 || (nUnicodeChar >= 0xF9 && nUnicodeChar <= 0xFC) || nUnicodeChar == 0xFF ) { *nBfr = static_cast<acpl::UInt8>(nUnicodeChar); return 1; } // Unique mappings if (nUnicodeChar == 0x0104) *nBfr = 0xA1; else if (nUnicodeChar == 0x0105) *nBfr = 0xA2; else if (nUnicodeChar == 0x0141) *nBfr = 0xA3; else if (nUnicodeChar == 0x20AC) *nBfr = 0xA4; else if (nUnicodeChar == 0x201E) *nBfr = 0xA5; else if (nUnicodeChar == 0x0160) *nBfr = 0xA6; else if (nUnicodeChar == 0x0161) *nBfr = 0xA8; else if (nUnicodeChar == 0x0218) *nBfr = 0xAA; else if (nUnicodeChar == 0x0179) *nBfr = 0xAC; else if (nUnicodeChar == 0x017A) *nBfr = 0xAE; else if (nUnicodeChar == 0x017B) *nBfr = 0xAF; else if (nUnicodeChar == 0x010C) *nBfr = 0xB2; else if (nUnicodeChar == 0x0142) *nBfr = 0xB3; else if (nUnicodeChar == 0x017D) *nBfr = 0xB4; else if (nUnicodeChar == 0x201D) *nBfr = 0xB5; else if (nUnicodeChar == 0x017E) *nBfr = 0xB8; else if (nUnicodeChar == 0x010D) *nBfr = 0xB9; else if (nUnicodeChar == 0x0219) *nBfr = 0xBA; else if (nUnicodeChar == 0x0152) *nBfr = 0xBC; else if (nUnicodeChar == 0x0153) *nBfr = 0xBD; else if (nUnicodeChar == 0x0178) *nBfr = 0xBE; else if (nUnicodeChar == 0x017C) *nBfr = 0xBF; else if (nUnicodeChar == 0x0102) *nBfr = 0xC3; else if (nUnicodeChar == 0x0106) *nBfr = 0xC5; else if (nUnicodeChar == 0x0110) *nBfr = 0xD0; else if (nUnicodeChar == 0x0143) *nBfr = 0xD1; else if (nUnicodeChar == 0x0150) *nBfr = 0xD5; else if (nUnicodeChar == 0x015A) *nBfr = 0xD7; else if (nUnicodeChar == 0x0170) *nBfr = 0xD8; else if (nUnicodeChar == 0x0118) *nBfr = 0xDD; else if (nUnicodeChar == 0x021A) *nBfr = 0xDE; else if (nUnicodeChar == 0x0103) *nBfr = 0xE3; else if (nUnicodeChar == 0x0107) *nBfr = 0xE5; else if (nUnicodeChar == 0x0111) *nBfr = 0xF0; else if (nUnicodeChar == 0x0144) *nBfr = 0xF1; else if (nUnicodeChar == 0x0151) *nBfr = 0xF5; else if (nUnicodeChar == 0x015B) *nBfr = 0xF7; else if (nUnicodeChar == 0x0171) *nBfr = 0xF8; else if (nUnicodeChar == 0x0119) *nBfr = 0xFD; else if (nUnicodeChar == 0x021B) *nBfr = 0xFE; else return 0; return 1; } return 0; } }; } } #endif // ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP
35.07563
121
0.575827
TheDoubleB
f9ba535a534d174b4e4fe63eaf45c5f8e6fc2f59
7,950
cpp
C++
playing/renderer/yas_playing_renderer.cpp
objective-audio/playing
b1bfe5f7e73d182717efafc6fd2e53257e92d8fd
[ "MIT" ]
null
null
null
playing/renderer/yas_playing_renderer.cpp
objective-audio/playing
b1bfe5f7e73d182717efafc6fd2e53257e92d8fd
[ "MIT" ]
null
null
null
playing/renderer/yas_playing_renderer.cpp
objective-audio/playing
b1bfe5f7e73d182717efafc6fd2e53257e92d8fd
[ "MIT" ]
null
null
null
// // yas_playing_renderer.cpp // #include "yas_playing_renderer.h" #include <audio/yas_audio_graph_io.h> #include <audio/yas_audio_io.h> #include <playing/yas_playing_types.h> using namespace yas; using namespace yas::playing; renderer::renderer(audio::io_device_ptr const &device) : graph(audio::graph::make_shared()), _device(device), _rendering_sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})), _rendering_pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)), _output_sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})), _output_pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)), _sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})), _pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)), _channel_count(observing::value::holder<std::size_t>::make_shared(std::size_t(0))), _format(observing::value::holder<renderer_format>::make_shared( {.sample_rate = 0, .pcm_format = audio::pcm_format::float32, .channel_count = 0})), _io(this->graph->add_io(this->_device)), _converter(audio::graph_avf_au::make_shared(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter)), _tap(audio::graph_tap::make_shared()) { this->_update_format(); this->_rendering_sample_rate->observe([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool); this->_rendering_pcm_format->observe([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool); this->_device->observe_io_device([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool); auto set_config_handler = [this] { this->_format->set_value(renderer_format{.sample_rate = this->_sample_rate->value(), .pcm_format = this->_pcm_format->value(), .channel_count = this->_channel_count->value()}); }; this->_sample_rate->observe([set_config_handler](auto const &) { set_config_handler(); }) .end() ->add_to(this->_pool); this->_pcm_format->observe([set_config_handler](auto const &) { set_config_handler(); }).end()->add_to(this->_pool); this->_channel_count->observe([set_config_handler](auto const &) { set_config_handler(); }) .sync() ->add_to(this->_pool); this->_output_sample_rate->observe([this](auto const &) { this->_update_connection(); }).end()->add_to(this->_pool); this->_output_pcm_format->observe([this](auto const &) { this->_update_connection(); }).end()->add_to(this->_pool); this->_format->observe([this](auto const &) { this->_update_connection(); }).sync()->add_to(this->_pool); this->_is_rendering ->observe([this](bool const &is_rendering) { if (is_rendering) { this->graph->start_render(); } else { this->graph->stop(); } }) .sync() ->add_to(this->_pool); } renderer_format const &renderer::format() const { return this->_format->value(); } observing::syncable renderer::observe_format(renderer_format_observing_handler_f &&handler) { return this->_format->observe(std::move(handler)); } void renderer::set_rendering_sample_rate(sample_rate_t const sample_rate) { this->_rendering_sample_rate->set_value(sample_rate); } void renderer::set_rendering_pcm_format(audio::pcm_format const pcm_format) { this->_rendering_pcm_format->set_value(pcm_format); } void renderer::set_rendering_handler(renderer_rendering_f &&handler) { this->_tap->set_render_handler([handler = std::move(handler)](audio::node_render_args const &args) { if (args.bus_idx != 0) { return; } auto const &buffer = args.buffer; if (buffer->format().is_interleaved()) { return; } if (handler) { handler(buffer); } }); } void renderer::set_is_rendering(bool const is_rendering) { this->_is_rendering->set_value(is_rendering); } void renderer::_update_format() { if (auto const &output_format = this->_device->output_format()) { this->_output_sample_rate->set_value(output_format->sample_rate()); if (auto const &rendering_pcm_format = this->_rendering_pcm_format->value(); rendering_pcm_format != audio::pcm_format::other) { this->_output_pcm_format->set_value(rendering_pcm_format); } else { this->_output_pcm_format->set_value(output_format->pcm_format()); } this->_sample_rate->set_value(this->_rendering_sample_rate->value() ?: output_format->sample_rate()); this->_channel_count->set_value(output_format->channel_count()); this->_pcm_format->set_value(output_format->pcm_format()); } else { this->_output_sample_rate->set_value(0); this->_output_pcm_format->set_value(audio::pcm_format::other); this->_sample_rate->set_value(0); this->_channel_count->set_value(0); this->_pcm_format->set_value(audio::pcm_format::other); } } void renderer::_update_connection() { if (this->_connection) { this->graph->disconnect(*this->_connection); this->_connection = std::nullopt; } if (this->_converter_connection) { this->graph->disconnect(*this->_converter_connection); this->_converter_connection = std::nullopt; } auto const &output_format = this->_device->output_format(); auto const output_sample_rate = output_format.has_value() ? output_format.value().sample_rate() : 0; auto const output_pcm_format = output_format.has_value() ? output_format.value().pcm_format() : audio::pcm_format::other; sample_rate_t const &config_sample_rate = this->_sample_rate->value(); audio::pcm_format const &config_pcm_format = this->_pcm_format->value(); std::size_t const ch_count = this->_channel_count->value(); audio::pcm_format const pcm_format = this->_pcm_format->value(); if (output_sample_rate > 0 && config_sample_rate > 0 && ch_count > 0 && pcm_format != audio::pcm_format::other && config_pcm_format != audio::pcm_format::other) { if (output_sample_rate != config_sample_rate || output_pcm_format != config_pcm_format) { audio::format const input_format{{.sample_rate = static_cast<double>(config_sample_rate), .channel_count = static_cast<uint32_t>(ch_count), .pcm_format = config_pcm_format}}; audio::format const output_format{{.sample_rate = static_cast<double>(output_sample_rate), .channel_count = static_cast<uint32_t>(ch_count), .pcm_format = pcm_format}}; this->_converter->raw_au->set_input_format(input_format, 0); this->_converter->raw_au->set_output_format(output_format, 0); this->_converter_connection = this->graph->connect(this->_tap->node, this->_converter->node, input_format); this->_connection = this->graph->connect(this->_converter->node, this->_io->output_node, output_format); } else { audio::format const format{{.sample_rate = static_cast<double>(config_sample_rate), .channel_count = static_cast<uint32_t>(ch_count), .pcm_format = pcm_format}}; this->_connection = this->graph->connect(this->_tap->node, this->_io->output_node, format); } } } renderer_ptr renderer::make_shared(audio::io_device_ptr const &device) { return renderer_ptr(new renderer{device}); }
46.491228
120
0.653962
objective-audio
f9c0500254198312e8e26665062d2cba531b2a30
1,290
cpp
C++
Engine/C_BoxCollider.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
2
2019-11-22T23:34:36.000Z
2019-11-27T10:27:35.000Z
Engine/C_BoxCollider.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
Engine/C_BoxCollider.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
#include "C_BoxCollider.h" #include "C_Mesh.h" #include "GameObject.h" C_BoxCollider::C_BoxCollider(GameObject* go) : C_Collider(go) { name.assign("Box Collider"); type = ComponentType::BOX_COLLIDER; size = float3::one; } void C_BoxCollider::CreateShape(C_Mesh* mesh) { if (is_loaded == false) { size = (mesh != nullptr) ? mesh->mesh_aabb.Size() : size = float3::one; center = (mesh != nullptr) ? mesh->mesh_aabb.CenterPoint() : float3::zero; } float3 shape_size = float3::one * 0.5f; shape = new btBoxShape(btVector3(shape_size.x, shape_size.y, shape_size.z)); } void C_BoxCollider::AdjustShape() { scaled_center = center; float3 scaled_size = size.Mul(linked_go->transform->scale.Abs()); scaled_size = CheckInvalidCollider(scaled_size); shape->setLocalScaling(btVector3(scaled_size.x, scaled_size.y, scaled_size.z)); } void C_BoxCollider::SaveCollider(Config& config) { config.AddFloatArray("size", (float*)&size, 3); } void C_BoxCollider::LoadCollider(Config& config) { size = config.GetFloat3("size", { 1.f ,1.f, 1.f }); } float3 C_BoxCollider::CheckInvalidCollider(float3 size) { return size.Max(float3(0.01, 0.01, 0.01)); } void C_BoxCollider::DrawInfoCollider() { ImGui::Title("Size", 1); ImGui::DragFloat3("##size", size.ptr(), 0.1f, 0.01f, FLT_MAX); }
24.807692
88
0.710853
SOLID-TEAM
f9c0d26e22b18d634103e0f8cf7d527f96ac0048
56,128
cpp
C++
examples/MyFS/myfs.cpp
baz1/SimpleFuse
f047fb327d36f99fde7e05145903eb5630c18679
[ "0BSD" ]
2
2015-07-02T17:31:10.000Z
2015-11-09T22:00:40.000Z
examples/MyFS/myfs.cpp
baz1/SimpleFuse
f047fb327d36f99fde7e05145903eb5630c18679
[ "0BSD" ]
null
null
null
examples/MyFS/myfs.cpp
baz1/SimpleFuse
f047fb327d36f99fde7e05145903eb5630c18679
[ "0BSD" ]
null
null
null
#include "myfs.h" #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <arpa/inet.h> #include <time.h> #include <QByteArray> #define READONLY_FS 0 #define DIR_BLOCK_SIZE 0x400 #define REG_BLOCK_SIZE 0x1000 #define MAX_OPEN_FILES 1000 #if DIR_BLOCK_SIZE < REG_BLOCK_SIZE #define MIN_BLOCK_SIZE DIR_BLOCK_SIZE #else #define MIN_BLOCK_SIZE REG_BLOCK_SIZE #endif #define SEEK_ERROR ((off_t) (-1)) static char str_buffer[0x100]; /* We will make it single-threaded to avoid any further concurrency issues */ MyFS::MyFS(QString mountPoint, QString filename) : QSimpleFuse(mountPoint, true), filename(convStr(filename)), fd(-1) { } MyFS::~MyFS() { delete[] filename; } void MyFS::createNewFilesystem(QString filename) { char *cFilename = convStr(filename); int fd = creat(cFilename, 0666); delete[] cFilename; if (fd < 0) { perror("creat"); return; } if (ftruncate(fd, 0x100000) < 0) /* 1MB as a starting size */ { perror("ftruncate"); close(fd); return; } quint32 addr; quint16 mshort; addr = htonl(8); if (write(fd, &addr, 4) != 4) goto abort; addr = htonl(DIR_BLOCK_SIZE + 8); if (write(fd, &addr, 4) != 4) goto abort; addr = htonl(DIR_BLOCK_SIZE); if (write(fd, &addr, 4) != 4) goto abort; addr = 0; if (write(fd, &addr, 4) != 4) goto abort; addr = htonl(time(0)); if (write(fd, &addr, 4) != 4) goto abort; mshort = htons(2); if (write(fd, &mshort, 2) != 2) goto abort; mshort = htons(SF_MODE_DIRECTORY | 0777); if (write(fd, &mshort, 2) != 2) goto abort; addr = htonl(8); if (write(fd, &addr, 4) != 4) goto abort; str_buffer[0] = 1; if (write(fd, str_buffer, 1) != 1) goto abort; str_buffer[1] = '.'; if (write(fd, str_buffer + 1, 1) != 1) goto abort; /* /../ is the same as / (root directory) (overwritten by fuse, but let's do it the right way) */ if (write(fd, &addr, 4) != 4) goto abort; str_buffer[0] = 2; if (write(fd, str_buffer, 1) != 1) goto abort; str_buffer[0] = '.'; if (write(fd, str_buffer, 2) != 2) goto abort; addr = 0; if (write(fd, &addr, 4) != 4) goto abort; if (lseek(fd, DIR_BLOCK_SIZE + 8, SEEK_SET) != DIR_BLOCK_SIZE + 8) goto abort; addr = htonl(0x100000 - DIR_BLOCK_SIZE - 8); if (write(fd, &addr, 4) != 4) goto abort; addr = 0; if (write(fd, &addr, 4) != 4) goto abort; close(fd); return; abort: perror("read"); close(fd); } void MyFS::sInit() { fd = open(filename, O_RDWR); if (fd < 0) { perror("open"); return; } if (read(fd, &root_address, 4) != 4) goto read_error; root_address = ntohl(root_address); if (read(fd, &first_blank, 4) != 4) goto read_error; first_blank = ntohl(first_blank); return; read_error: perror("read"); close(fd); fd = -1; } void MyFS::sDestroy() { if (fd >= 0) { close(fd); fd = -1; } } int MyFS::sGetSize(quint64 &size, quint64 &free) { if (fd < 0) return -EIO; /* Get total size */ off_t length = lseek(fd, 0, SEEK_END); if (length == SEEK_ERROR) return -EIO; size = (quint64) length; /* Get free size */ free = 0; if (first_blank) { quint32 current = first_blank, to_add; while (true) { if (lseek(fd, current, SEEK_SET) != current) return -EIO; if (read(fd, &to_add, 4) != 4) return -EIO; to_add = ntohl(to_add); if (to_add > 8) free += to_add - 8; if (read(fd, &current, 4) != 4) return -EIO; if (!current) break; current = ntohl(current); } } return 0; } int MyFS::sGetAttr(const lString &pathname, sAttr &attr) { if (fd < 0) return -EIO; quint32 addr; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, addr); if (ret_value != 0) return ret_value; return myGetAttr(addr, attr); } int MyFS::sMkFile(const lString &pathname, quint16 mst_mode) { #if READONLY_FS Q_UNUSED(pathname); Q_UNUSED(mst_mode); return -EROFS; #else if (fd < 0) return -EIO; /* Create the file block */ quint32 file; int ret_value = getBlock(mst_mode & SF_MODE_DIRECTORY ? DIR_BLOCK_SIZE : REG_BLOCK_SIZE, file); if (ret_value != 0) return ret_value; quint32 addr = htonl(time(0)); if (write(fd, &addr, 4) != 4) return -EIO; quint16 mshort = htons((mst_mode & SF_MODE_DIRECTORY) ? 2 : 1); if (write(fd, &mshort, 2) != 2) return -EIO; mshort = htons(mst_mode); if (write(fd, &mshort, 2) != 2) return -EIO; if (mst_mode & SF_MODE_DIRECTORY) { addr = htonl(file); if (write(fd, &addr, 4) != 4) return -EIO; str_buffer[0] = 1; if (write(fd, str_buffer, 1) != 1) return -EIO; str_buffer[1] = '.'; if (write(fd, str_buffer + 1, 1) != 1) return -EIO; addr = 0; /* Temporary null address */ if (write(fd, &addr, 4) != 4) return -EIO; str_buffer[0] = 2; if (write(fd, str_buffer, 1) != 1) return -EIO; str_buffer[0] = '.'; if (write(fd, str_buffer, 2) != 2) return -EIO; addr = 0; if (write(fd, &addr, 4) != 4) return -EIO; /* Link to pathname */ ret_value = myLink(file, pathname, &addr); if (ret_value != 0) return ret_value; /* Change reference to parent directory */ if (lseek(fd, file + 22, SEEK_SET) == SEEK_ERROR) return -EIO; addr = htonl(addr); if (write(fd, &addr, 4) != 4) return -EIO; } else { quint32 fsize = 0; if (write(fd, &fsize, 4) != 4) return -EIO; /* Link to pathname */ return myLink(file, pathname); } return 0; #endif /* READONLY_FS */ } int MyFS::sRmFile(const lString &pathname, bool isDir) { #if READONLY_FS Q_UNUSED(pathname); Q_UNUSED(isDir); return -EROFS; #else if (fd < 0) return -EIO; return myUnlink(pathname, isDir); #endif /* READONLY_FS */ } int MyFS::sMvFile(const lString &pathBefore, const lString &pathAfter) { #if READONLY_FS Q_UNUSED(pathBefore); Q_UNUSED(pathAfter); return -EROFS; #else if (fd < 0) return -EIO; bool isDir; quint32 file; int ret_value = myUnlink(pathBefore, isDir, &file); if (ret_value != 0) return ret_value; if (isDir) { quint32 parentAddr; ret_value = myLink(file, pathAfter, &parentAddr); if (ret_value != 0) return ret_value; /* Change reference to parent directory */ quint32 next_block; if (lseek(fd, file + 4, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; if (lseek(fd, 8, SEEK_CUR) == SEEK_ERROR) return -EIO; while (true) { quint32 addr; if (read(fd, &addr, 4) != 4) return -EIO; if (!addr) { if (!next_block) return -EIO; /* Corrupted data */ next_block = ntohl(next_block) + 4; if (lseek(fd, next_block, SEEK_SET) != next_block) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; continue; } unsigned char nameLen; if (read(fd, &nameLen, 1) != 1) return -EIO; if (read(fd, &str_buffer, nameLen) != nameLen) return -EIO; if ((nameLen == 2) && (memcmp("..", str_buffer, 2) == 0)) { if (lseek(fd, -7, SEEK_CUR) == SEEK_ERROR) return -EIO; parentAddr = htonl(parentAddr); if (write(fd, &parentAddr, 4) != 4) return -EIO; return 0; } } } else { return myLink(file, pathAfter); } #endif /* READONLY_FS */ } int MyFS::sLink(const lString &pathFrom, const lString &pathTo) { #if READONLY_FS Q_UNUSED(pathFrom); Q_UNUSED(pathTo); return -EROFS; #else if (fd < 0) return -EIO; quint32 addrTo; lString shallowCopy = pathTo; int ret_value = getAddress(shallowCopy, addrTo); if (ret_value != 0) return ret_value; if (lseek(this->fd, addrTo + 12, SEEK_SET) == SEEK_ERROR) return -EIO; quint16 nlink, mshort; if (read(this->fd, &nlink, 2) != 2) return -EIO; nlink = ntohs(nlink); if (nlink == 0xFFFF) return -EMLINK; if (read(this->fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_DIRECTORY) return -EPERM; ret_value = myLink(addrTo, pathFrom); if (ret_value != 0) return ret_value; if (lseek(this->fd, addrTo + 12, SEEK_SET) == SEEK_ERROR) return -EIO; nlink = htons(nlink + 1); if (write(this->fd, &nlink, 2) != 2) return -EIO; return 0; #endif /* READONLY_FS */ } int MyFS::sChMod(const lString &pathname, quint16 mst_mode) { #if READONLY_FS Q_UNUSED(pathname); Q_UNUSED(mst_mode); return -EROFS; #else if (fd < 0) return -EIO; quint32 nodeAddr; quint16 mshort; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, nodeAddr); if (ret_value != 0) return ret_value; nodeAddr += 14; if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); mshort = (mshort & (~0x1FF)) | (mst_mode & 0x1FF); if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr) return -EIO; mshort = htons(mshort); if (write(fd, &mshort, 2) != 2) return -EIO; return 0; #endif /* READONLY_FS */ } int MyFS::sTruncate(const lString &pathname, quint64 newsize) { #if READONLY_FS Q_UNUSED(pathname); Q_UNUSED(newsize); return -EROFS; #else if (fd < 0) return -EIO; if (newsize > 0xFFFFFFFFL) return -EINVAL; quint32 nodeAddr; quint16 mshort; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, nodeAddr); if (ret_value != 0) return ret_value; if (lseek(fd, nodeAddr + 14, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_DIRECTORY) return -EISDIR; if (!(mshort & S_IWUSR)) return -EACCES; return myTruncate(nodeAddr, (quint32) newsize); #endif /* READONLY_FS */ } int MyFS::sUTime(const lString &pathname, time_t mst_atime, time_t mst_mtime) { Q_UNUSED(mst_atime); #if READONLY_FS Q_UNUSED(pathname); Q_UNUSED(mst_mtime); return -EROFS; #else if (fd < 0) return -EIO; quint32 nodeAddr; quint32 mtime; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, nodeAddr); if (ret_value != 0) return ret_value; nodeAddr += 8; if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr) return -EIO; mtime = htonl(mst_mtime); if (write(fd, &mtime, 4) != 4) return -EIO; return 0; #endif /* READONLY_FS */ } int MyFS::sOpen(const lString &pathname, int flags, quint32 &fd) { if (this->fd < 0) return -EIO; #if READONLY_FS if (flags & (O_WRONLY | O_RDWR)) return -EROFS; #endif /* READONLY_FS */ OpenFile myFile; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, myFile.nodeAddr); if (ret_value != 0) return ret_value; if (lseek(this->fd, myFile.nodeAddr, SEEK_SET) != myFile.nodeAddr) return -EIO; if (read(this->fd, &myFile.partLength, 4) != 4) return -EIO; if (read(this->fd, &myFile.nextAddr, 4) != 4) return -EIO; if (lseek(this->fd, 6, SEEK_CUR) == SEEK_ERROR) return -EIO; quint16 mshort; if (read(this->fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_DIRECTORY) return -EISDIR; myFile.flags = (flags & O_NOATIME) ? OPEN_FILE_FLAGS_NOATIME : 0; if (!(flags & O_WRONLY)) { myFile.flags |= OPEN_FILE_FLAGS_PREAD; if (!(mshort & S_IRUSR)) return -EACCES; } if (flags & (O_WRONLY | O_RDWR)) { myFile.flags |= OPEN_FILE_FLAGS_PWRITE; if (!(mshort & S_IWUSR)) return -EACCES; } else { if (flags & O_TRUNC) return -EACCES; } if (flags & O_TRUNC) { myFile.fileLength = 0; if (write(this->fd, &myFile.fileLength, 4) != 4) return -EIO; } else { if (read(this->fd, &myFile.fileLength, 4) != 4) return -EIO; myFile.fileLength = ntohl(myFile.fileLength); } fd = 0; while ((fd < (quint32) openFiles.count()) && openFiles.at(fd).nodeAddr) ++fd; myFile.partLength = ntohl(myFile.partLength); myFile.nextAddr = ntohl(myFile.nextAddr); myFile.partAddr = myFile.nodeAddr; myFile.partOffset = 0; myFile.isRegular = true; if ((flags & O_APPEND) && !(flags & O_TRUNC)) { quint32 available = myFile.partLength - 20; while (available <= (myFile.fileLength - myFile.partOffset)) { myFile.partOffset += available; if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr) return -EIO; myFile.partAddr = myFile.nextAddr; if (read(this->fd, &myFile.partLength, 4) != 4) return -EIO; if (read(this->fd, &myFile.nextAddr, 4) != 4) return -EIO; myFile.partLength = ntohl(myFile.partLength); myFile.nextAddr = ntohl(myFile.nextAddr); available = myFile.partLength - 8; } myFile.currentAddr = myFile.partAddr + (myFile.partOffset ? 8 : 20) + (myFile.fileLength - myFile.partOffset); } else { myFile.currentAddr = myFile.nodeAddr + 20; } if (fd == (quint32) openFiles.count()) { if (fd > MAX_OPEN_FILES) return -ENFILE; openFiles.append(myFile); } else { openFiles[fd] = myFile; } return 0; } int MyFS::sRead(quint32 fd, void *buf, quint32 count, quint64 offset) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular)) return -EBADF; if (this->fd < 0) return -EIO; OpenFile &myFile = openFiles[fd]; if (!(myFile.flags & OPEN_FILE_FLAGS_PREAD)) return -EBADF; if (offset > myFile.fileLength) return -EOVERFLOW; if (offset + count > myFile.fileLength) count = myFile.fileLength - offset; if (!setPosition(myFile, offset)) return -EIO; quint32 toread = qMin((quint32) count, myFile.partLength - (myFile.currentAddr - myFile.partAddr)); if (read(this->fd, buf, toread) != toread) return -EIO; if (toread == (quint32) count) { myFile.currentAddr += count; return count; } buf = (void*) (((quint8*) buf) + toread); int original_count = count; count -= toread; quint32 available = myFile.partLength - (myFile.partOffset ? 8 : 20); while (true) { myFile.partOffset += available; if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr) return -EIO; myFile.partAddr = myFile.nextAddr; if (read(this->fd, &myFile.partLength, 4) != 4) return -EIO; if (read(this->fd, &myFile.nextAddr, 4) != 4) return -EIO; myFile.partLength = ntohl(myFile.partLength); myFile.nextAddr = ntohl(myFile.nextAddr); available = myFile.partLength - 8; toread = qMin((quint32) count, available); if (read(this->fd, buf, toread) != toread) return -EIO; if (toread == (quint32) count) { myFile.currentAddr = myFile.partAddr + 8 + count; return original_count; } buf = (void*) (((quint8*) buf) + toread); count -= toread; available = myFile.partLength - 8; } } int MyFS::sWrite(quint32 fd, const void *buf, quint32 count, quint64 offset) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular)) return -EBADF; if (this->fd < 0) return -EIO; OpenFile &myFile = openFiles[fd]; if (!(myFile.flags & OPEN_FILE_FLAGS_PWRITE)) return -EBADF; if (offset + count > myFile.fileLength) { if (offset + count > 0xFFFFFFFFL) return -EFBIG; int ret_value = myTruncate(myFile.nodeAddr, (quint32) (offset + count)); if (ret_value != 0) return ret_value; } if (!setPosition(myFile, offset)) return -EIO; quint32 towrite = qMin((quint32) count, myFile.partLength - (myFile.currentAddr - myFile.partAddr)); if (write(this->fd, buf, towrite) != towrite) return -EIO; myFile.flags |= OPEN_FILE_FLAGS_MODIFIED; if (towrite == (quint32) count) { myFile.currentAddr += count; return count; } quint8 *mbuf = (quint8*) buf; mbuf += towrite; int original_count = count; count -= towrite; quint32 available = myFile.partLength - (myFile.partOffset ? 8 : 20); while (true) { myFile.partOffset += available; if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr) return -EIO; myFile.partAddr = myFile.nextAddr; if (read(this->fd, &myFile.partLength, 4) != 4) return -EIO; if (read(this->fd, &myFile.nextAddr, 4) != 4) return -EIO; myFile.partLength = ntohl(myFile.partLength); myFile.nextAddr = ntohl(myFile.nextAddr); available = myFile.partLength - 8; towrite = qMin((quint32) count, available); if (write(this->fd, mbuf, towrite) != towrite) return -EIO; if (towrite == (quint32) count) { myFile.currentAddr = myFile.partAddr + 8 + count; return original_count; } mbuf += towrite; count -= towrite; available = myFile.partLength - 8; } } int MyFS::sSync(quint32 fd) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular)) return -EBADF; return 0; } int MyFS::sClose(quint32 fd) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular)) return -EBADF; OpenFile *file = &openFiles[fd]; if (file->flags & OPEN_FILE_FLAGS_MODIFIED) { if (this->fd < 0) return -EIO; if (lseek(this->fd, file->nodeAddr + 8, SEEK_SET) == SEEK_ERROR) return -EIO; quint32 mytime = htonl(time(0)); if (write(this->fd, &mytime, 4) != 4) return -EIO; } file->nodeAddr = 0; while ((!openFiles.isEmpty()) && (!openFiles.last().nodeAddr)) openFiles.removeLast(); return 0; } int MyFS::sOpenDir(const lString &pathname, quint32 &fd) { if (this->fd < 0) return -EIO; OpenFile myDir; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, myDir.nodeAddr); if (ret_value != 0) return ret_value; if (lseek(this->fd, myDir.nodeAddr + 4, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(this->fd, &myDir.nextAddr, 4) != 4) return -EIO; if (lseek(this->fd, 6, SEEK_CUR) == SEEK_ERROR) return -EIO; quint16 mshort; if (read(this->fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_REGULARFILE) return -ENOTDIR; if (!(mshort & S_IRUSR)) return -EACCES; fd = 0; while ((fd < (quint32) openFiles.count()) && openFiles.at(fd).nodeAddr) ++fd; myDir.currentAddr = myDir.nodeAddr + 16; myDir.nextAddr = ntohl(myDir.nextAddr); myDir.isRegular = false; if (fd == (quint32) openFiles.count()) { if (fd > MAX_OPEN_FILES) return -ENFILE; openFiles.append(myDir); } else { openFiles[fd] = myDir; } return 0; } int MyFS::sReadDir(quint32 fd, char *&name) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || openFiles.at(fd).isRegular) return -EBADF; if (this->fd < 0) return -EIO; OpenFile *file = &openFiles[fd]; if (lseek(this->fd, file->currentAddr, SEEK_SET) != file->currentAddr) return -EIO; quint32 addr; while (true) { if (read(this->fd, &addr, 4) != 4) return -EIO; if (addr == 0) { if (!file->nextAddr) { name = NULL; return 0; } file->nextAddr += 4; if (lseek(this->fd, file->nextAddr, SEEK_SET) != file->nextAddr) goto ioerror; file->currentAddr = file->nextAddr + 4; if (read(this->fd, &file->nextAddr, 4) != 4) goto ioerror; file->nextAddr = ntohl(file->nextAddr); continue; } unsigned char sLen; if (read(this->fd, &sLen, 1) != 1) return -EIO; if (read(this->fd, str_buffer, sLen) != sLen) return -EIO; file->currentAddr += 5; file->currentAddr += sLen; str_buffer[sLen] = 0; name = str_buffer; return 0; } ioerror: file->nodeAddr = 0; return -EIO; } int MyFS::sCloseDir(quint32 fd) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || openFiles.at(fd).isRegular) return -EBADF; OpenFile *file = &openFiles[fd]; file->nodeAddr = 0; while ((!openFiles.isEmpty()) && (!openFiles.last().nodeAddr)) openFiles.removeLast(); return 0; } int MyFS::sAccess(const lString &pathname, quint8 mode) { if (fd < 0) return -EIO; quint32 addr; lString shallowCopy = pathname; int ret_value = getAddress(shallowCopy, addr); if (ret_value != 0) return ret_value; if (mode == F_OK) return 0; #if READONLY_FS if (mode & W_OK) return -EROFS; #endif /* READONLY_FS */ if (lseek(fd, addr + 14, SEEK_SET) == SEEK_ERROR) return -EIO; quint16 mshort; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if ((mode & R_OK) && (!(mshort & S_IRUSR))) return -EACCES; if ((mode & W_OK) && (!(mshort & S_IWUSR))) return -EACCES; if ((mode & X_OK) && (!(mshort & S_IXUSR))) return -EACCES; return 0; } int MyFS::sFTruncate(quint32 fd, quint64 newsize) { #if READONLY_FS Q_UNUSED(fd); Q_UNUSED(newsize); return -EROFS; #else if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular)) return -EBADF; if (this->fd < 0) return -EIO; if (newsize > 0xFFFFFFFFL) return -EINVAL; OpenFile *file = &openFiles[fd]; file->fileLength = (quint32) newsize; return myTruncate(file->nodeAddr, file->fileLength); #endif /* READONLY_FS */ } int MyFS::sFGetAttr(quint32 fd, sAttr &attr) { if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr)) return -EBADF; if (this->fd < 0) return -EIO; return myGetAttr(openFiles.at(fd).nodeAddr, attr); } /* Links the regular file pointed by file to pathname, WITHOUT updating the nlink field */ int MyFS::myLink(quint32 file, const lString &pathname, quint32 *parentAddr) { /* Get the last part of the path */ lString shallowCopy = pathname; if (shallowCopy.str_len == 0) return -ENOENT; while ((shallowCopy.str_len > 0) && (shallowCopy.str_value[shallowCopy.str_len - 1] == '/')) --shallowCopy.str_len; if (shallowCopy.str_len == 0) return -EEXIST; int len = shallowCopy.str_len; while (shallowCopy.str_value[shallowCopy.str_len - 1] != '/') --shallowCopy.str_len; len -= shallowCopy.str_len; int start = shallowCopy.str_len; if (len > 0xFF) return -ENAMETOOLONG; /* Get the address of the parent directory */ quint32 dirAddr; int ret_value = getAddress(shallowCopy, dirAddr); if (ret_value != 0) return ret_value; /* Check whether or not this is indeed a directory */ if (lseek(fd, dirAddr, SEEK_SET) != dirAddr) return -EIO; quint32 block_size; if (read(fd, &block_size, 4) != 4) return -EIO; block_size = ntohl(block_size); quint32 next_block; if (read(fd, &next_block, 4) != 4) return -EIO; if (read(fd, str_buffer, 4) != 4) return -EIO; quint16 mshort, nlink; if (read(fd, &nlink, 2) != 2) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_REGULARFILE) return -ENOTDIR; /* Check the permissions */ if (!(mshort & S_IWUSR)) return -EACCES; /* Modify the last modification time */ if (lseek(fd, dirAddr + 8, SEEK_SET) == SEEK_ERROR) return -EIO; quint32 linkDate = htonl(time(0)); if (write(fd, &linkDate, 4) != 4) return -EIO; /* Add new entry */ quint32 currentPart = dirAddr; quint32 addr; if (parentAddr) { *parentAddr = dirAddr; addr = dirAddr + 12; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; if (nlink == 0xFFFF) return -EMLINK; nlink = htons(ntohs(nlink) + 1); if (write(fd, &nlink, 2) != 2) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; } else { addr = dirAddr + 16; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; } while (true) { if (read(fd, &addr, 4) != 4) return -EIO; if (addr == 0) { off_t currentPos = lseek(fd, 0, SEEK_CUR); if (currentPos == SEEK_ERROR) return -EIO; quint32 used = (quint32) currentPos; used -= currentPart; if (block_size - used >= (quint32) len + 5) { /* Add entry to the existing list */ currentPos -= 4; if (lseek(fd, currentPos, SEEK_SET) != currentPos) return -EIO; file = htonl(file); if (write(fd, &file, 4) != 4) return -EIO; unsigned char sLen = (unsigned char) len; if (write(fd, &sLen, 1) != 1) return -EIO; if (write(fd, pathname.str_value + start, len) != len) return -EIO; if (write(fd, &addr, 4) != 4) return -EIO; } else if (next_block != 0) { /* Go to the next part */ next_block = ntohl(next_block); if (lseek(fd, next_block, SEEK_SET) != next_block) return -EIO; currentPart = next_block; if (read(fd, &block_size, 4) != 4) return -EIO; block_size = ntohl(block_size); if (read(fd, &next_block, 4) != 4) return -EIO; continue; } else { /* Create a new part to add the entry */ ret_value = getBlock(DIR_BLOCK_SIZE, next_block); if (ret_value != 0) { freeBlock(file); return ret_value; } file = htonl(file); if (write(fd, &file, 4) != 4) return -EIO; unsigned char sLen = (unsigned char) len; if (write(fd, &sLen, 1) != 1) return -EIO; if (write(fd, pathname.str_value + start, len) != len) return -EIO; if (write(fd, &addr, 4) != 4) return -EIO; currentPart += 4; if (lseek(fd, currentPart, SEEK_SET) != currentPart) return -EIO; next_block = htonl(next_block); if (write(fd, &next_block, 4) != 4) return -EIO; } return 0; } else { unsigned char sLen; if (read(fd, &sLen, 1) != 1) return -EIO; if (read(fd, str_buffer, sLen) != sLen) return -EIO; if ((sLen == len) && (memcmp(str_buffer, pathname.str_value + start, len) == 0)) { freeBlock(file); return -EEXIST; } } } } int MyFS::myUnlink(const lString &pathname, bool &isDir, quint32 *nodeAddr) { /* Get the last part of the path */ lString shallowCopy = pathname; if (shallowCopy.str_len == 0) return -ENOENT; while ((shallowCopy.str_len > 0) && (shallowCopy.str_value[shallowCopy.str_len - 1] == '/')) --shallowCopy.str_len; if (shallowCopy.str_len == 0) return -EEXIST; int len = shallowCopy.str_len; while (shallowCopy.str_value[shallowCopy.str_len - 1] != '/') --shallowCopy.str_len; len -= shallowCopy.str_len; int start = shallowCopy.str_len; /* Get the address of the parent directory */ quint32 dirAddr, beforeAddr = 0, currentAddr; int ret_value = getAddress(shallowCopy, dirAddr); if (ret_value != 0) return ret_value; /* Check whether or not this is indeed a directory */ currentAddr = dirAddr + 4; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; quint32 next_block; if (read(fd, &next_block, 4) != 4) return -EIO; if (read(fd, str_buffer, 4) != 4) return -EIO; quint16 mshort; if (read(fd, &mshort, 2) != 2) return -EIO; quint16 nlink = ntohs(mshort); if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (mshort & SF_MODE_REGULARFILE) return -ENOTDIR; /* Check the permissions */ if (!(mshort & S_IWUSR)) return -EACCES; /* Look for the pathname entry */ while (true) { quint32 addr; if (read(fd, &addr, 4) != 4) return -EIO; if (!addr) { if (!next_block) return -ENOENT; beforeAddr = currentAddr; currentAddr = ntohl(next_block) + 4; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; continue; } unsigned char nameLen; if (read(fd, &nameLen, 1) != 1) return -EIO; if (read(fd, &str_buffer, nameLen) != nameLen) return -EIO; if ((nameLen == len) && (memcmp(pathname.str_value + start, str_buffer, len) == 0)) { /* Found it. */ addr = ntohl(addr); off_t nextEntry = lseek(fd, 0, SEEK_CUR); if (nextEntry == SEEK_ERROR) return -EIO; /* Check if the file is opened. */ for (int i = 0; i < openFiles.count(); ++i) { if (openFiles.at(i).nodeAddr == addr) return -EBUSY; } /* Check if isDir has the right value. */ if (lseek(fd, addr + 14, SEEK_SET) != addr + 14) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (nodeAddr) { isDir = (bool) (mshort & SF_MODE_DIRECTORY); *nodeAddr = addr; } else { if (isDir ^ ((bool) (mshort & SF_MODE_DIRECTORY))) return isDir ? -ENOTDIR : -EISDIR; /* Remove addr (or just decrease the link counter) */ if (!isDir) { if (lseek(fd, addr + 12, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort) - 1; if (mshort) { if (lseek(fd, -2, SEEK_CUR) == SEEK_ERROR) return -EIO; mshort = htons(mshort); if (write(fd, &mshort, 2) != 2) return -EIO; } else { ret_value = freeBlocks(addr); if (ret_value != 0) return ret_value; } } else { /* If this is a directory, check if it is empty */ quint32 myfd; char *entryName; ret_value = sOpenDir(pathname, myfd); if (ret_value != 0) return ret_value; while (true) { ret_value = sReadDir(myfd, entryName); if (ret_value != 0) return ret_value; if (entryName == NULL) break; if (strcmp(entryName, ".") == 0) continue; if (strcmp(entryName, "..") == 0) continue; sCloseDir(myfd); return -ENOTEMPTY; } sCloseDir(myfd); /* Remove addr */ ret_value = freeBlocks(addr); if (ret_value != 0) return ret_value; } } /* Remove the corresponding entry in the parent */ if (lseek(fd, nextEntry, SEEK_SET) != nextEntry) return -EIO; if (read(fd, &addr, 4) != 4) return -EIO; if ((!addr) && (((quint32) nextEntry) == currentAddr + 4)) { /* Empty part to remove */ if (lseek(fd, beforeAddr, SEEK_SET) != beforeAddr) return -EIO; if (write(fd, &next_block, 4) != 4) return -EIO; ret_value = freeBlock(currentAddr - 4); if (ret_value != 0) return ret_value; } else { /* Move following entries */ len += 5; if (lseek(fd, -(len + 4), SEEK_CUR) == SEEK_ERROR) return -EIO; if (write(fd, &addr, 4) != 4) return -EIO; while (addr) { if (lseek(fd, len, SEEK_CUR) == SEEK_ERROR) return -EIO; if (read(fd, &nameLen, 1) != 1) return -EIO; if (read(fd, &str_buffer, nameLen) != nameLen) return -EIO; if (read(fd, &addr, 4) != 4) return -EIO; if (lseek(fd, -(len + 5 + (int) nameLen), SEEK_CUR) == SEEK_ERROR) return -EIO; if (write(fd, &nameLen, 1) != 1) return -EIO; if (write(fd, &str_buffer, nameLen) != nameLen) return -EIO; if (write(fd, &addr, 4) != 4) return -EIO; } } /* Change the last modification time */ dirAddr += 8; if (lseek(fd, dirAddr, SEEK_SET) != dirAddr) return -EIO; addr = htonl(time(0)); if (write(fd, &addr, 4) != 4) return -EIO; /* And the number of hard links if need be */ if (isDir) { nlink = htons(nlink - 1); if (write(fd, &nlink, 2) != 2) return -EIO; } return 0; } } } int MyFS::myGetAttr(quint32 addr, sAttr &attr) { addr += 8; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; if (read(fd, &addr, 4) != 4) return -EIO; attr.mst_atime = (time_t) ntohl(addr); attr.mst_mtime = attr.mst_atime; quint16 mshort; if (read(fd, &mshort, 2) != 2) return -EIO; attr.mst_nlink = (quint32) ntohs(mshort); if (read(fd, &mshort, 2) != 2) return -EIO; attr.mst_mode = ntohs(mshort); if (attr.mst_mode & SF_MODE_REGULARFILE) { if (read(fd, &addr, 4) != 4) return -EIO; attr.mst_size = (quint64) ntohl(addr); } return 0; } int MyFS::myTruncate(quint32 addr, quint32 newsize) { #if READONLY_FS Q_UNUSED(addr); Q_UNUSED(newsize); return -EROFS; #else quint32 block_size, next_block, file_size, mytime; quint32 modifNodeAddr = addr, modifNodeSize = (quint32) newsize, modifNodePart = 0; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; if (read(fd, &block_size, 4) != 4) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; mytime = htonl(time(0)); if (write(fd, &mytime, 4) != 4) return -EIO; if (lseek(fd, 4, SEEK_CUR) == SEEK_ERROR) return -EIO; if (read(fd, &file_size, 4) != 4) return -EIO; file_size = ntohl(file_size); if (file_size == newsize) return 0; if (file_size < newsize) { /* We have to increase the size of the file, by appending zeros at the end */ if (lseek(fd, -4, SEEK_CUR) == SEEK_ERROR) return -EIO; quint32 mynewsize = (quint32) newsize; mynewsize = htonl(mynewsize); if (write(fd, &mynewsize, 4) != 4) return -EIO; bool isFistBlock = true; block_size = ntohl(block_size) - 20; while (block_size < file_size) { file_size -= block_size; newsize -= block_size; if (!next_block) return -EIO; /* Corrupted data */ next_block = ntohl(next_block); if (lseek(fd, next_block, SEEK_SET) != next_block) return -EIO; addr = next_block; if (read(fd, &block_size, 4) != 4) return -EIO; isFistBlock = false; block_size = ntohl(block_size) - 8; if (read(fd, &next_block, 4) != 4) return -EIO; } memset(str_buffer, 0, 0x100); if (block_size > file_size) { if (lseek(fd, addr + (isFistBlock ? 20 : 8) + file_size, SEEK_SET) == SEEK_ERROR) return -EIO; if (!myWriteB(qMin(block_size - file_size, (quint32) (newsize - file_size)))) return -EIO; } while (newsize > block_size) { newsize -= block_size; if (!next_block) { int ret_value = getBlock(newsize + 8, next_block); if ((ret_value != 0) && (ret_value != -ENOSPC)) return ret_value; if (ret_value == -ENOSPC) { if (next_block <= 8) return -ENOSPC; block_size = next_block - 8; ret_value = getBlock(next_block, next_block); if (ret_value != 0) return ret_value; } else { block_size = newsize; } if (lseek(fd, addr + 4, SEEK_SET) == SEEK_ERROR) return -EIO; addr = next_block; if (!modifNodePart) modifNodePart = next_block; next_block = htonl(next_block); if (write(fd, &next_block, 4) != 4) return -EIO; next_block = 0; if (lseek(fd, addr + 8, SEEK_SET) == SEEK_ERROR) return -EIO; } else { addr = ntohl(next_block); if (lseek(fd, addr, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(fd, &block_size, 4) != 4) return -EIO; block_size = ntohl(block_size); if (read(fd, &next_block, 4) != 4) return -EIO; } if (!myWriteB(qMin(block_size, (quint32) newsize))) return -EIO; } /* Update the file descriptors */ for (int i = 0; i < openFiles.count(); ++i) { if (openFiles.at(i).nodeAddr == modifNodeAddr) { if (modifNodePart && (!openFiles.at(i).nextAddr)) openFiles[i].nextAddr = modifNodePart; openFiles[i].fileLength = modifNodeSize; } } return 0; } else { /* We have to reduce the size of the file */ if (lseek(fd, -4, SEEK_CUR) == SEEK_ERROR) return -EIO; quint32 mynewsize = (quint32) newsize; mynewsize = htonl(mynewsize); if (write(fd, &mynewsize, 4) != 4) return -EIO; if (!next_block) return 0; next_block = ntohl(next_block); newsize -= ntohl(block_size) - 20; while (newsize > 0) { if (lseek(fd, next_block, SEEK_SET) != next_block) return -EIO; addr = next_block; if (read(fd, &block_size, 4) != 4) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; if (!next_block) return 0; next_block = ntohl(next_block); newsize -= ntohl(block_size) - 8; } addr += 4; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; addr = 0; if (write(fd, &addr, 4) != 4) return -EIO; int ret_value = freeBlocks(next_block); if (ret_value != 0) return ret_value; /* Update the file descriptors */ for (int i = 0; i < openFiles.count(); ++i) { if (openFiles.at(i).nodeAddr == modifNodeAddr) { if (openFiles.at(i).partOffset >= modifNodeSize) { openFiles[i].partAddr = openFiles[i].nodeAddr; openFiles[i].currentAddr = openFiles[i].nodeAddr + 20; if (lseek(fd, modifNodeAddr, SEEK_SET) != modifNodeAddr) return -EIO; quint32 &pLen = openFiles[i].partLength; quint32 &pNext = openFiles[i].nextAddr; if (read(fd, &pLen, 4) != 4) return -EIO; pLen = ntohl(pLen); if (read(fd, &pNext, 4) != 4) return -EIO; pNext = ntohl(pNext); openFiles[i].partOffset = 0; } else if (openFiles.at(i).partOffset + openFiles.at(i).partLength >= modifNodeSize) { openFiles[i].nextAddr = 0; } openFiles[i].fileLength = modifNodeSize; } } return 0; } #endif /* READONLY_FS */ } bool MyFS::setPosition(OpenFile &file, quint32 offset) { if (offset < file.partOffset) { /* Scan the file from the beginning */ file.partAddr = file.nodeAddr; if (lseek(fd, file.nodeAddr, SEEK_SET) != file.nodeAddr) return false; if (read(fd, &file.partLength, 4) != 4) return false; if (read(fd, &file.nextAddr, 4) != 4) return false; file.partLength = ntohl(file.partLength); file.nextAddr = ntohl(file.nextAddr); file.currentAddr = file.nodeAddr + 20; file.partOffset = 0; } /* Scan the file until the right offset range */ quint32 available = file.partLength - (file.partOffset ? 8 : 20); while (offset >= file.partOffset + available) { file.partOffset += available; if (lseek(fd, file.nextAddr, SEEK_SET) != file.nextAddr) return false; file.partAddr = file.nextAddr; if (read(fd, &file.partLength, 4) != 4) return false; if (read(fd, &file.nextAddr, 4) != 4) return false; file.partLength = ntohl(file.partLength); file.nextAddr = ntohl(file.nextAddr); available = file.partLength - 8; } file.currentAddr = file.partAddr + (file.partOffset ? 8 : 20) + (offset - file.partOffset); if (lseek(fd, file.currentAddr, SEEK_SET) != file.currentAddr) return -EIO; return true; } bool MyFS::myWriteB(quint32 size) { while (size > 0x100) { if (write(fd, str_buffer, 0x100) != 0x100) return false; size -= 0x100; } return (write(fd, str_buffer, size) == size); } char *MyFS::convStr(const QString &str) { char *result = new char[str.length() + 1]; QByteArray strData = str.toLocal8Bit(); memcpy(result, strData.data(), str.length()); result[str.length()] = 0; return result; } /* Allocates some blocks (linked together), puts the address of the first one into addr and returns 0 on success. */ int MyFS::getBlocks(quint32 size, quint32 &addr) { Q_ASSERT(size > 0); int ret_value; quint32 next_block = 0; while (true) { ret_value = getBlock(size + 8, addr); if ((ret_value != 0) && (ret_value != -ENOSPC)) return ret_value; if (ret_value == 0) { if (next_block) { if (lseek(fd, -4, SEEK_CUR) != -SEEK_ERROR) return -EIO; if (write(fd, &next_block, 4) != 4) return -EIO; } return 0; } if (addr <= 8) { if (next_block) freeBlocks(next_block); return -ENOSPC; } size -= addr - 8; ret_value = getBlock(addr, addr); if (ret_value != 0) return ret_value; if (next_block) { if (lseek(fd, -4, SEEK_CUR) != -SEEK_ERROR) return -EIO; if (write(fd, &next_block, 4) != 4) return -EIO; } next_block = htonl(addr); } } /* Allocates the block, writes its size in the first 4 bytes, 0 on the 4 next bytes, puts its address into addr and returns 0 on success. In this case, fd will point to the 9-th byte of that block at the end of the call. In the case it returns -ENOSPC, addr will contain the maximum free block size. */ int MyFS::getBlock(quint32 size, quint32 &addr) { #if READONLY_FS Q_UNUSED(size); Q_UNUSED(addr); return -EROFS; #else Q_ASSERT(size > 0); quint32 currentAddr = first_blank, refAddr = 4, bsize; addr = 0; while (true) { if (!currentAddr) return -ENOSPC; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; if (read(fd, &bsize, 4) != 4) return -EIO; bsize = ntohl(bsize); if (bsize >= size) { if (bsize >= size + MIN_BLOCK_SIZE) { /* We split the space in two parts */ if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; bsize -= size; addr = currentAddr + bsize; bsize = htonl(bsize); if (write(fd, &bsize, 4) != 4) return -EIO; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; bsize = htonl(size); if (write(fd, &bsize, 4) != 4) return -EIO; currentAddr = 0; if (write(fd, &currentAddr, 4) != 4) return -EIO; } else { /* We use all the space */ addr = currentAddr; if (read(fd, &currentAddr, 4) != 4) return -EIO; if (lseek(fd, refAddr, SEEK_SET) != refAddr) return -EIO; if (write(fd, &currentAddr, 4) != 4) return -EIO; if (lseek(fd, addr + 4, SEEK_SET) != addr + 4) return -EIO; bsize = 0; if (write(fd, &bsize, 4) != 4) return -EIO; } return 0; } else { if (bsize > addr) addr = bsize; } refAddr = currentAddr + 4; if (read(fd, &currentAddr, 4) != 4) return -EIO; currentAddr = ntohl(currentAddr); } #endif /* READONLY_FS */ } /* Frees the block at address addr and its following parts, and returns 0 on success. */ int MyFS::freeBlocks(quint32 addr) { int ret_value; quint32 next_block; while (true) { if (lseek(fd, addr + 4, SEEK_SET) == SEEK_ERROR) return -EIO; if (read(fd, &next_block, 4) != 4) return -EIO; ret_value = freeBlock(addr); if (ret_value != 0) return ret_value; if (!next_block) break; addr = ntohl(next_block); } return 0; } /* Frees the block at address addr and returns 0 on success. */ int MyFS::freeBlock(quint32 addr) { #if READONLY_FS Q_UNUSED(addr); return -EROFS; #else /* Get the length of the block to free */ quint32 block_len; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; if (read(fd, &block_len, 4) != 4) return -EIO; block_len = ntohl(block_len); /* Search for the next free block */ quint32 refAddr = 0, currentAddr = first_blank, prev_len = 0; while (currentAddr < addr) { refAddr = currentAddr; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; if (read(fd, &prev_len, 4) != 4) return -EIO; prev_len = ntohl(prev_len); if (read(fd, &currentAddr, 4) != 4) return -EIO; if (!currentAddr) break; currentAddr = ntohl(currentAddr); } /* Check merging requirements */ if (refAddr + prev_len == addr) { if (addr + block_len == currentAddr) { /* Merge with the previous and the next free block */ quint32 currentLen, currentNext; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; if (read(fd, &currentLen, 4) != 4) return -EIO; currentLen = ntohl(currentLen); if (read(fd, &currentNext, 4) != 4) return -EIO; if (lseek(fd, refAddr, SEEK_SET) != refAddr) return -EIO; block_len += prev_len; block_len += currentLen; block_len = htonl(block_len); if (write(fd, &block_len, 4) != 4) return -EIO; if (write(fd, &currentNext, 4) != 4) return -EIO; } else { /* Merge with the previous free block */ if (lseek(fd, refAddr, SEEK_SET) != refAddr) return -EIO; block_len += prev_len; block_len = htonl(block_len); if (write(fd, &block_len, 4) != 4) return -EIO; currentAddr = htonl(currentAddr); if (write(fd, &currentAddr, 4) != 4) return -EIO; } } else { /* Change the link of the previous block */ refAddr += 4; if (lseek(fd, refAddr, SEEK_SET) != refAddr) return -EIO; refAddr = htonl(addr); if (write(fd, &refAddr, 4) != 4) return -EIO; if (addr + block_len == currentAddr) { /* Merge with the next free block */ quint32 currentLen, currentNext; if (lseek(fd, currentAddr, SEEK_SET) != currentAddr) return -EIO; if (read(fd, &currentLen, 4) != 4) return -EIO; currentLen = ntohl(currentLen); if (read(fd, &currentNext, 4) != 4) return -EIO; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; block_len += currentLen; block_len = htonl(block_len); if (write(fd, &block_len, 4) != 4) return -EIO; if (write(fd, &currentNext, 4) != 4) return -EIO; } else { /* Do not merge with anything */ addr += 4; if (lseek(fd, addr, SEEK_SET) != addr) return -EIO; currentAddr = htonl(currentAddr); if (write(fd, &currentAddr, 4) != 4) return -EIO; } } return 0; #endif /* READONLY_FS */ } int MyFS::getAddress(lString &pathname, quint32 &result) { if (pathname.str_value[0] != '/') return -ENOENT; while ((pathname.str_value[pathname.str_len - 1] == '/') && (pathname.str_len > 0)) --pathname.str_len; if (pathname.str_len == 0) { result = root_address; return 0; } /* Checking whether or not the result is in the cache */ QString sValue = QString::fromLocal8Bit(pathname.str_value, pathname.str_len); result = cache.value(sValue, 0); if (result != 0) return 0; /* Get the last part of the path */ int len = pathname.str_len; while (pathname.str_value[pathname.str_len - 1] != '/') --pathname.str_len; len -= pathname.str_len; int start = pathname.str_len; /* Run this function recursively on the beginning of the path */ int ret_value = getAddress(pathname, result); if (ret_value != 0) return ret_value; /* Look for the last part of the pathname in the parent directory */ result += 4; if (lseek(fd, result, SEEK_SET) != result) return -EIO; if (read(fd, &result, 4) != 4) return -EIO; if (read(fd, &str_buffer, 6) != 6) return -EIO; quint16 mshort; if (read(fd, &mshort, 2) != 2) return -EIO; mshort = ntohs(mshort); if (!(mshort & SF_MODE_DIRECTORY)) return -ENOTDIR; if (!(mshort & S_IXUSR)) return -EACCES; while (true) { quint32 addr; if (read(fd, &addr, 4) != 4) return -EIO; if (!addr) { if (!result) return -ENOENT; result = ntohl(result) + 4; if (lseek(fd, result, SEEK_SET) != result) return -EIO; if (read(fd, &result, 4) != 4) return -EIO; continue; } unsigned char nameLen; if (read(fd, &nameLen, 1) != 1) return -EIO; if (read(fd, &str_buffer, nameLen) != nameLen) return -EIO; if ((nameLen == len) && (memcmp(pathname.str_value + start, str_buffer, len) == 0)) { result = ntohl(addr); /* Store the result in the cache (we won't care about limiting the cache size) */ cache[sValue] = result; return 0; } } }
32.146621
137
0.510173
baz1
f9ca369eb57fcf984b3a7fd04161ad537301539a
8,940
cxx
C++
Kinematics/StarKinematics.cxx
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
Kinematics/StarKinematics.cxx
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
Kinematics/StarKinematics.cxx
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
#include "StarKinematics.h" #include "StarGenerator/EVENT/StarGenEvent.h" #include "StarGenerator/EVENT/StarGenParticle.h" #include "StarGenerator/UTIL/StarParticleData.h" #include "StarGenerator/UTIL/StarRandom.h" #include <boost/algorithm/string.hpp> #include <vector> #include <string> #include <algorithm> #include <random> #define random myrandom // ---------------------------------------------------------------------------- StarParticleData &data = StarParticleData::instance(); StarRandom &random = StarRandom::Instance(); static std::random_device _stl_rd; static std::mt19937 _mt19937( _stl_rd() ); StarGenEvent *gEvent = 0; StarGenEvent *gUser = 0; // ---------------------------------------------------------------------------- StarKinematics::StarKinematics( const Char_t *name ) : StarGenerator(name) { mEvent = new StarGenEvent("kine"); gEvent = mEvent; mUser = new StarGenEvent("user"); gUser = mUser; } // ---------------------------------------------------------------------------- Int_t StarKinematics::PreGenerate() { return kStOK; } // ---------------------------------------------------------------------------- Int_t StarKinematics::Generate() { // Copy user event into mEvent for ( Int_t i=0;i<mUser->GetNumberOfParticles(); i++ ) { mEvent -> AddParticle( (*mUser)[i] ); } // And clear the user event mUser->Clear(); return kStOK; } // ---------------------------------------------------------------------------- Int_t StarKinematics::PostGenerate() { return kStOK; } // ---------------------------------------------------------------------------- StarGenParticle *StarKinematics::AddParticle() { StarGenParticle *p = mUser->AddParticle(); p->SetStatus( StarGenParticle::kFinal ); return p; } // ---------------------------------------------------------------------------- StarGenParticle *StarKinematics::AddParticle( const Char_t *type ) { TParticlePDG *pdg = data(type); assert(pdg); Int_t id = pdg->PdgCode(); StarGenParticle *p = AddParticle(); p->SetStatus( StarGenParticle::kFinal ); p->SetMass( pdg->Mass() ); p->SetId( id ); return p; } // ---------------------------------------------------------------------------- void StarKinematics::Kine(Int_t ntrack, const Char_t *_type, Double_t ptlow, Double_t pthigh, Double_t ylow, Double_t yhigh, Double_t philow, Double_t phihigh ) { std::string type = _type; std::vector<std::string> types; boost::split( types, type, [](char c){ return (c==' ' || c== ',');} ); for ( Int_t i=0;i<ntrack;i++ ) { std::shuffle( types.begin(), types.end(), _mt19937 ); type = types[0]; StarGenParticle *p = AddParticle(type.c_str()); // Sample pt, eta, phi if ( 0 == IAttr("energy") ) { // uniform in pT double pt = random(ptlow, pthigh); double y = random(ylow, yhigh ); double phi= random(philow, phihigh ); double m = p->GetMass(); double mt = pt; if ( IAttr("rapidity" ) ) { // switch from pseudorapidity to plain vanilla rapidity mt = TMath::Sqrt( pt*pt + m*m ); } double px = pt * TMath::Cos( phi ); double py = pt * TMath::Sin( phi ); double pz = mt * TMath::SinH( y ); double E = mt * TMath::CosH( y ); p->SetPx( px ); p->SetPy( py ); p->SetPz( pz ); p->SetEnergy( E ); p->SetVx( 0. ); // put vertex at 0,0,0,0 p->SetVy( 0. ); p->SetVz( 0. ); p->SetTof( 0. ); } if ( IAttr("energy") ) { // uniform in energy. assert( 0==IAttr("rapidity") ); // only flat in eta, not rapidity double E = random(ptlow, pthigh); double y = random(ylow, yhigh ); // y is eta here, not rapidity double phi= random(philow, phihigh ); double m = p->GetMass(); double pmom = TMath::Sqrt(E*E - m*m); double pt = 2.0 * pmom * TMath::Exp( -y ) / ( 1 + TMath::Exp( -2.0*y ) ); double mt = pt; if ( IAttr("rapidity" ) ) { // switch from pseudorapidity to plain vanilla rapidity mt = TMath::Sqrt( pt*pt + m*m ); } double px = pt * TMath::Cos( phi ); double py = pt * TMath::Sin( phi ); double pz = mt * TMath::SinH( y ); //double E = mt * TMath::CosH( y ); p->SetPx( px ); p->SetPy( py ); p->SetPz( pz ); p->SetEnergy( E ); p->SetVx( 1e-11); // put vertex at 0,0,0,0 p->SetVy( 1e-11); p->SetVz( 1e-11); p->SetTof( 0. ); } } } // ---------------------------------------------------------------------------- void StarKinematics::Dist( Int_t ntrack, const Char_t *_type, TF1 *ptFunc, TF1 *etaFunc, TF1 *phiFunc ) { std::string type = _type; std::vector<std::string> types; boost::split( types, type, [](char c){ return (c==' ' || c== ',');} ); for ( Int_t i=0; i<ntrack; i++ ) { std::shuffle( types.begin(), types.end(), _mt19937 ); type = types[0]; StarGenParticle *p = AddParticle(type.c_str()); Double_t pt = ptFunc -> GetRandom(); Double_t y = etaFunc -> GetRandom(); Double_t phi = (phiFunc) ? phiFunc->GetRandom() : random( 0., TMath::TwoPi() ); Double_t m = p->GetMass(); double mt = pt; if ( IAttr("rapidity" ) ) { // switch from pseudorapidity to plain vanilla rapidity mt = TMath::Sqrt( pt*pt + m*m ); } double px = pt * TMath::Cos( phi ); double py = pt * TMath::Sin( phi ); double pz = mt * TMath::SinH( y ); double E = mt * TMath::CosH( y ); p->SetPx( px ); p->SetPy( py ); p->SetPz( pz ); p->SetEnergy( E ); p->SetVx( 0. ); // put vertex at 0,0,0,0 p->SetVy( 0. ); p->SetVz( 0. ); p->SetTof( 0. ); } } // ---------------------------------------------------------------------------- void StarKinematics::Dist( Int_t ntrack, const Char_t *_type, TH1 *ptFunc, TH1 *etaFunc, TH1 *phiFunc ) { std::string type = _type; std::vector<std::string> types; boost::split( types, type, [](char c){ return (c==' ' || c== ',');} ); for ( Int_t i=0; i<ntrack; i++ ) { std::shuffle( types.begin(), types.end(), _mt19937 ); type = types[0]; StarGenParticle *p = AddParticle(type.c_str()); Double_t pt = ptFunc -> GetRandom(); Double_t y = etaFunc -> GetRandom(); Double_t phi = (phiFunc) ? phiFunc->GetRandom() : random( 0., TMath::TwoPi() ); Double_t m = p->GetMass(); double mt = pt; if ( IAttr("rapidity" ) ) { // switch from pseudorapidity to plain vanilla rapidity mt = TMath::Sqrt( pt*pt + m*m ); } double px = pt * TMath::Cos( phi ); double py = pt * TMath::Sin( phi ); double pz = mt * TMath::SinH( y ); double E = mt * TMath::CosH( y ); p->SetPx( px ); p->SetPy( py ); p->SetPz( pz ); p->SetEnergy( E ); p->SetVx( 0. ); // put vertex at 0,0,0,0 p->SetVy( 0. ); p->SetVz( 0. ); p->SetTof( 0. ); } } // ---------------------------------------------------------------------------- const double deg2rad = TMath::DegToRad(); void StarKinematics::Cosmic( int ntrack, const char* _type, double plow, double phigh, double radius, double zmin, double zmax, double dphi ) { std::string type = _type; std::vector<std::string> types; boost::split( types, type, [](char c){ return (c==' ' || c== ',');} ); for ( Int_t i=0; i<ntrack; i++ ) { std::shuffle( types.begin(), types.end(), _mt19937 ); type = types[0]; StarGenParticle *p = AddParticle(type.c_str()); // Generate a random vertex double zvertex = random( zmin, zmax ); double phi = random( 0.0, TMath::TwoPi() ); double xvertex = radius * TMath::Cos(phi); double yvertex = radius * TMath::Sin(phi); xvertex *= 10; // cm --> mm per HEPEVT standard yvertex *= 10; // cm --> mm zvertex *= 10; // cm --> mm // Initialize vertex X,Y ... to get unit vector pointing to beam line TVector3 vertex(xvertex,yvertex,0); // Unit vector pointing away from beamline TVector3 direct = vertex.Unit(); // Sample momentum distribution double pmag = random(plow, phigh); // Momentum vector pointing in towards the beamline _momentum = -pmag * direct; // Now, randomize phi and theta by +/- dphi degrees about the momentum axis phi = _momentum.Phi() + deg2rad * random( -dphi, +dphi ); double theta = _momentum.Theta() + deg2rad * random( -dphi, +dphi ); _momentum.SetPhi(phi); _momentum.SetTheta(theta); Double_t m = p->GetMass(); Double_t E2 = _momentum.Mag2() + m*m; Double_t E = sqrt(E2); p->SetPx( _momentum.Px() ); p->SetPy( _momentum.Py() ); p->SetPz( _momentum.Pz() ); p->SetEnergy( E ); p->SetVx( xvertex ); p->SetVy( yvertex ); p->SetVz( zvertex ); p->SetTof( 0. ); } } // ----------------------------------------------------------------------------
28.745981
141
0.518345
klendathu2k
f9d1ed93dae68ffa66228391dfc9dbcc5cc41bf0
8,827
cpp
C++
samples/gl-320-buffer-uniform.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
571
2015-01-08T16:29:38.000Z
2022-03-16T06:45:42.000Z
samples/gl-320-buffer-uniform.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
45
2015-01-15T12:47:28.000Z
2022-03-04T09:22:32.000Z
samples/gl-320-buffer-uniform.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
136
2015-01-31T15:24:57.000Z
2022-02-17T19:26:24.000Z
#include "test.hpp" namespace { char const* VERT_SHADER_SOURCE("gl-320/buffer-uniform.vert"); char const* FRAG_SHADER_SOURCE("gl-320/buffer-uniform.frag"); struct vertex_v3fn3fc4f { vertex_v3fn3fc4f ( glm::vec3 const & Position, glm::vec3 const & Normal, glm::vec4 const & Color ) : Position(Position), Normal(Normal), Color(Color) {} glm::vec3 Position; glm::vec3 Normal; glm::vec4 Color; }; GLsizei const VertexCount(4); GLsizeiptr const VertexSize = VertexCount * sizeof(vertex_v3fn3fc4f); vertex_v3fn3fc4f const VertexData[VertexCount] = { vertex_v3fn3fc4f(glm::vec3(-1.0f,-1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3( 1.0f,-1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3( 1.0f, 1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3(-1.0f, 1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)) }; GLsizei const ElementCount(6); GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort); GLushort const ElementData[ElementCount] = { 0, 1, 2, 2, 3, 0 }; /* GLsizei const VertexCount(4); GLsizeiptr const VertexSize = VertexCount * sizeof(vertex_v3fn3fc4f); vertex_v3fn3fc4f const VertexData[VertexCount] = { vertex_v3fn3fc4f(glm::vec3(-1.000f, -0.732f, -0.732f), glm::normalize(glm::vec3(-1.000f, -0.732f, -0.732f)), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3( 1.000f, -0.732f, -0.732f), glm::normalize(glm::vec3( 1.000f, -0.732f, -0.732f)), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3( 0.000f, 1.000f, -0.732f), glm::normalize(glm::vec3( 0.000f, 1.000f, -0.732f)), glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)), vertex_v3fn3fc4f(glm::vec3( 0.000f, 0.000f, 1.000f), glm::normalize(glm::vec3( 0.000f, 0.000f, 1.000f)), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)) }; GLsizei const ElementCount(12); GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort); GLushort const ElementData[ElementCount] = { 0, 2, 1, 0, 1, 3, 1, 2, 3, 2, 0, 3 }; */ namespace buffer { enum type { VERTEX, ELEMENT, PER_SCENE, PER_PASS, PER_DRAW, MAX }; }//namespace buffer namespace uniform { enum type { PER_SCENE = 0, PER_PASS = 1, PER_DRAW = 2, LIGHT = 3 }; }; struct material { glm::vec3 Ambient; float Padding1; glm::vec3 Diffuse; float Padding2; glm::vec3 Specular; float Shininess; }; struct light { glm::vec3 Position; }; struct transform { glm::mat4 P; glm::mat4 MV; glm::mat3 Normal; }; }//namespace class sample : public framework { public: sample(int argc, char* argv[]) : framework(argc, argv, "gl-320-buffer-uniform", framework::CORE, 3, 2), VertexArrayName(0), ProgramName(0), UniformPerDraw(0), UniformPerPass(0), UniformPerScene(0) {} private: std::array<GLuint, buffer::MAX> BufferName; GLuint ProgramName; GLuint VertexArrayName; GLint UniformPerDraw; GLint UniformPerPass; GLint UniformPerScene; bool initProgram() { bool Validated = true; compiler Compiler; if(Validated) { compiler Compiler; GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core"); GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core"); ProgramName = glCreateProgram(); glAttachShader(ProgramName, VertShaderName); glAttachShader(ProgramName, FragShaderName); glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position"); glBindAttribLocation(ProgramName, semantic::attr::NORMAL, "Normal"); glBindAttribLocation(ProgramName, semantic::attr::COLOR, "Color"); glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color"); glLinkProgram(ProgramName); Validated = Validated && Compiler.check(); Validated = Validated && Compiler.check_program(ProgramName); } if(Validated) { this->UniformPerDraw = glGetUniformBlockIndex(ProgramName, "per_draw"); this->UniformPerPass = glGetUniformBlockIndex(ProgramName, "per_pass"); this->UniformPerScene = glGetUniformBlockIndex(ProgramName, "per_scene"); glUniformBlockBinding(ProgramName, this->UniformPerDraw, uniform::PER_DRAW); glUniformBlockBinding(ProgramName, this->UniformPerPass, uniform::PER_PASS); glUniformBlockBinding(ProgramName, this->UniformPerScene, uniform::PER_SCENE); } return Validated; } bool initVertexArray() { glGenVertexArrays(1, &VertexArrayName); glBindVertexArray(VertexArrayName); glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]); glVertexAttribPointer(semantic::attr::POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(0)); glVertexAttribPointer(semantic::attr::NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(sizeof(glm::vec3))); glVertexAttribPointer(semantic::attr::COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(sizeof(glm::vec3) + sizeof(glm::vec3))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(semantic::attr::POSITION); glEnableVertexAttribArray(semantic::attr::NORMAL); glEnableVertexAttribArray(semantic::attr::COLOR); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]); glBindVertexArray(0); return true; } bool initBuffer() { glGenBuffers(buffer::MAX, &BufferName[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementSize, ElementData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]); glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); { glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_DRAW]); glBufferData(GL_UNIFORM_BUFFER, sizeof(transform), nullptr, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } { light Light = {glm::vec3(0.0f, 0.0f, 100.f)}; glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_PASS]); glBufferData(GL_UNIFORM_BUFFER, sizeof(Light), &Light, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } { material Material = {glm::vec3(0.7f, 0.0f, 0.0f), 0.0f, glm::vec3(0.0f, 0.5f, 0.0f), 0.0f, glm::vec3(0.0f, 0.0f, 0.5f), 128.0f}; glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_SCENE]); glBufferData(GL_UNIFORM_BUFFER, sizeof(Material), &Material, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } return true; } bool begin() { bool Validated = true; if(Validated) Validated = initProgram(); if(Validated) Validated = initBuffer(); if(Validated) Validated = initVertexArray(); glEnable(GL_DEPTH_TEST); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDrawBuffer(GL_BACK); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return false; return Validated; } bool end() { glDeleteVertexArrays(1, &VertexArrayName); glDeleteBuffers(buffer::MAX, &BufferName[0]); glDeleteProgram(ProgramName); return true; } bool render() { glm::vec2 WindowSize(this->getWindowSize()); { glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_DRAW]); transform* Transform = static_cast<transform*>(glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(transform), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)); glm::mat4 const Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f); glm::mat4 const View = this->view(); glm::mat4 const Model = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() * 0.5f, glm::vec3(0.0f, 0.0f, 1.0f)); Transform->MV = View * Model; Transform->P = Projection; Transform->Normal = glm::mat3(glm::transpose(glm::inverse(Transform->MV))); glUnmapBuffer(GL_UNIFORM_BUFFER); glBindBuffer(GL_UNIFORM_BUFFER, 0); } glViewport(0, 0, static_cast<GLsizei>(WindowSize.x), static_cast<GLsizei>(WindowSize.y)); glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.2f, 0.2f, 0.2f, 1.0f)[0]); glClearBufferfv(GL_DEPTH, 0, &glm::vec1(1.0f)[0]); glUseProgram(ProgramName); glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_SCENE, BufferName[buffer::PER_SCENE]); glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_PASS, BufferName[buffer::PER_PASS]); glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_DRAW, BufferName[buffer::PER_DRAW]); glBindVertexArray(VertexArrayName); glDrawElementsInstancedBaseVertex(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, nullptr, 1, 0); return true; } }; int main(int argc, char* argv[]) { int Error = 0; sample Sample(argc, argv); Error += Sample(); return Error; }
28.940984
151
0.71066
galek
f9d74d219afb8904a906f72c4f7923276f721e35
527
cpp
C++
Day 04/string2.cpp
tushar-nath/100-days-of-code
860c088968521d953f5ca9222f70037e95cb4ad4
[ "MIT" ]
null
null
null
Day 04/string2.cpp
tushar-nath/100-days-of-code
860c088968521d953f5ca9222f70037e95cb4ad4
[ "MIT" ]
null
null
null
Day 04/string2.cpp
tushar-nath/100-days-of-code
860c088968521d953f5ca9222f70037e95cb4ad4
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string str = "TUSHAR"; // convert to upper strings for (int i=0; i<str.length(); i++) { if(str[i>='a' && str[i]<='z']) { str[i]-=32; cout<<str[i]; } } // convert to lower strings for (int i=0; i<str.length(); i++) { if(str[i>='A' && str[i]<='Z']) { str[i]+=32; cout<<str[i]; } } return 0; }
15.5
38
0.421252
tushar-nath
f9dd51dc663a65c0e9c2954e3f9a6bd117a80f77
10,537
cpp
C++
src/afv/VoiceSession.cpp
pierr3/afv-native
b85ddc102ae25600954f0f528169d701f685132f
[ "BSD-3-Clause" ]
2
2022-02-02T20:50:25.000Z
2022-02-27T09:21:44.000Z
src/afv/VoiceSession.cpp
xpilot-project/afv-native
afd4e4481a6a2eb373af36d2da322ad7ac104849
[ "BSD-3-Clause" ]
null
null
null
src/afv/VoiceSession.cpp
xpilot-project/afv-native
afd4e4481a6a2eb373af36d2da322ad7ac104849
[ "BSD-3-Clause" ]
1
2022-01-10T18:23:32.000Z
2022-01-10T18:23:32.000Z
/* afv/VoiceSession.cpp * * This file is part of AFV-Native. * * Copyright (c) 2019 Christopher Collins * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "afv-native/afv/VoiceSession.h" #include <nlohmann/json.hpp> #include "afv-native/Log.h" #include "afv-native/afv/APISession.h" #include "afv-native/afv/params.h" #include "afv-native/afv/dto/Transceiver.h" #include "afv-native/afv/dto/voice_server/Heartbeat.h" #include "afv-native/http/Request.h" #include "afv-native/cryptodto/UDPChannel.h" using namespace afv_native::afv; using namespace afv_native; using json = nlohmann::json; VoiceSession::VoiceSession(APISession &session, const std::string &callsign): mSession(session), mCallsign(callsign), mBaseUrl(""), mVoiceSessionSetupRequest("", http::Method::POST, json()), mVoiceSessionTeardownRequest("", http::Method::DEL, json()), mTransceiverUpdateRequest("", http::Method::POST, json()), mChannel(session.getEventBase()), mHeartbeatTimer(mSession.getEventBase(), std::bind(&VoiceSession::sendHeartbeatCallback, this)), mLastHeartbeatReceived(0), mHeartbeatTimeout(mSession.getEventBase(), std::bind(&VoiceSession::heartbeatTimedOut, this)), mLastError(VoiceSessionError::NoError) { updateBaseUrl(); } VoiceSession::~VoiceSession() { mHeartbeatTimer.disable(); mHeartbeatTimeout.disable(); mChannel.close(); mVoiceSessionSetupRequest.reset(); } bool VoiceSession::Connect() { // we cannot start the voice session if the API session is in any state OTHER than running... if (mSession.getState() != APISessionState::Running) { return false; } mVoiceSessionSetupRequest.reset(); // fix up the request URL updateBaseUrl(); mSession.setAuthenticationFor(mVoiceSessionSetupRequest); mVoiceSessionSetupRequest.setCompletionCallback(std::bind(&VoiceSession::voiceSessionSetupRequestCallback, this, std::placeholders::_1, std::placeholders::_2)); auto &transferManager = mSession.getTransferManager(); mVoiceSessionSetupRequest.shareState(transferManager); mVoiceSessionSetupRequest.doAsync(transferManager); return true; } void VoiceSession::voiceSessionSetupRequestCallback(http::Request *req, bool success) { if (success) { if (req->getStatusCode() == 200) { auto *restreq = dynamic_cast<http::RESTRequest *>(req); assert(restreq != nullptr); try { auto j = restreq->getResponse(); dto::PostCallsignResponse cresp; j.get_to(cresp); if (!setupSession(cresp)) { failSession(); } } catch (json::exception &e) { LOG("voicesession", "exception parsing voice session setup: %s", e.what()); mLastError = VoiceSessionError::BadResponseFromAPIServer; failSession(); } } else { LOG("voicesession", "request for voice session failed: got status %d", req->getStatusCode()); mLastError = VoiceSessionError::BadResponseFromAPIServer; failSession(); } } else { LOG("voicesession", "request for voice session failed: got internal error %s", req->getCurlError().c_str()); mLastError = VoiceSessionError::BadResponseFromAPIServer; failSession(); } } bool VoiceSession::setupSession(const dto::PostCallsignResponse &cresp) { mChannel.close(); mChannel.setAddress(cresp.VoiceServer.AddressIpV4); mChannel.setChannelConfig(cresp.VoiceServer.ChannelConfig); if (!mChannel.open()) { LOG("VoiceSession:setupSession", "unable to open UDP session"); mLastError = VoiceSessionError::UDPChannelError; return false; } mVoiceSessionSetupRequest.reset(); mVoiceSessionTeardownRequest.reset(); mLastHeartbeatReceived = util::monotime_get(); mHeartbeatTimer.enable(afvHeartbeatIntervalMs); mHeartbeatTimeout.enable(afvHeartbeatTimeoutMs); mChannel.registerDtoHandler( "HA", [this](const unsigned char *data, size_t len) { this->receivedHeartbeat(); }); mLastError = VoiceSessionError::NoError; StateCallback.invokeAll(VoiceSessionState::Connected); // now that everything's been invoked, attach our callback for reconnect handling mSession.StateCallback.addCallback(this, std::bind(&VoiceSession::sessionStateCallback, this, std::placeholders::_1)); return true; } void VoiceSession::failSession() { mHeartbeatTimer.disable(); mHeartbeatTimeout.disable(); mChannel.close(); mVoiceSessionSetupRequest.reset(); // before we invoke state callbacks, remove our session handler so we don't get recursive loops. mSession.StateCallback.removeCallback(this); if (mLastError != VoiceSessionError::NoError) { StateCallback.invokeAll(VoiceSessionState::Error); } else { StateCallback.invokeAll(VoiceSessionState::Disconnected); } } void VoiceSession::sendHeartbeatCallback() { dto::Heartbeat hbDto(mCallsign); if (mChannel.isOpen()) { mChannel.sendDto(hbDto); mHeartbeatTimer.enable(afvHeartbeatIntervalMs); } } void VoiceSession::receivedHeartbeat() { mLastHeartbeatReceived = util::monotime_get(); mHeartbeatTimeout.disable(); mHeartbeatTimeout.enable(afvHeartbeatTimeoutMs); } void VoiceSession::heartbeatTimedOut() { util::monotime_t now = util::monotime_get(); LOG("voicesession", "heartbeat timeout - %d ms elapsed - disconnecting", now - mLastHeartbeatReceived); mLastError = VoiceSessionError::Timeout; Disconnect(true, true); } void VoiceSession::Disconnect(bool do_close, bool reconnect) { if (do_close) { mVoiceSessionTeardownRequest.reset(); mVoiceSessionTeardownRequest.setUrl(mBaseUrl); mSession.setAuthenticationFor(mVoiceSessionTeardownRequest); // because we're likely going to get discarded by our owner when this function returns, we // need to hold onto a shared_ptr reference to prevent cleanup until *AFTER* this callback completes. auto &transferManager = mSession.getTransferManager(); mVoiceSessionTeardownRequest.setCompletionCallback( [](http::Request *req, bool success) mutable { if (success) { if (req->getStatusCode() != 200) { LOG("VoiceSession:Disconnect", "Callsign Dereg Failed. Status Code: %d", req->getStatusCode()); } } else { LOG("VoiceSession:Disconnect", "Callsign Dereg Failed. Internal Error: %s", req->getCurlError().c_str()); } }); // and now schedule this request to be performed. mVoiceSessionTeardownRequest.shareState(transferManager); mVoiceSessionTeardownRequest.doAsync(transferManager); } failSession(); if(reconnect) { mSession.Connect(); } } void VoiceSession::postTransceiverUpdate( const std::vector<dto::Transceiver> &txDto, std::function<void(http::Request *, bool)> callback) { updateBaseUrl(); mTransceiverUpdateRequest.reset(); mSession.setAuthenticationFor(mTransceiverUpdateRequest); // only send the transceivers that have a valid frequency (read: not zero) std::vector<dto::Transceiver> filteredDto; std::copy_if(txDto.begin(), txDto.end(), std::back_inserter(filteredDto), [](dto::Transceiver t){ return t.Frequency > 0; }); mTransceiverUpdateRequest.setRequestBody(filteredDto); mTransceiverUpdateRequest.setCompletionCallback(callback); // and now schedule this request to be performed. auto &transferManager = mSession.getTransferManager(); mTransceiverUpdateRequest.shareState(transferManager); mTransceiverUpdateRequest.doAsync(transferManager); LOG("VoiceSession", "postTransceiverUpdate"); } bool VoiceSession::isConnected() const { return mChannel.isOpen(); } void VoiceSession::setCallsign(const std::string &newCallsign) { if (!mChannel.isOpen()) { mCallsign = newCallsign; } } afv_native::cryptodto::UDPChannel &VoiceSession::getUDPChannel() { return mChannel; } void VoiceSession::updateBaseUrl() { mBaseUrl = mSession.getBaseUrl() + "/api/v1/users/" + mSession.getUsername() + "/callsigns/" + mCallsign; mVoiceSessionSetupRequest.setUrl(mBaseUrl); mVoiceSessionTeardownRequest.setUrl(mBaseUrl); mTransceiverUpdateRequest.setUrl(mBaseUrl + "/transceivers"); } VoiceSessionError VoiceSession::getLastError() const { return mLastError; } void VoiceSession::sessionStateCallback(APISessionState state) { switch (state) { case afv::APISessionState::Disconnected: case afv::APISessionState::Error: if (isConnected()) { failSession(); } break; default: break; } }
36.842657
164
0.690329
pierr3
f9e0b6413b2ef2e1ae6b6723e406dc63f4a53f55
52,602
cpp
C++
src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define LOG_NDEBUG 0 #undef LOG_TAG #define LOG_TAG "FakeHwcTest" #include "FakeComposerClient.h" #include "FakeComposerService.h" #include "FakeComposerUtils.h" #include <gui/DisplayEventReceiver.h> #include <gui/ISurfaceComposer.h> #include <gui/LayerDebugInfo.h> #include <gui/LayerState.h> #include <gui/Surface.h> #include <gui/SurfaceComposerClient.h> #include <android/hidl/manager/1.0/IServiceManager.h> #include <android/looper.h> #include <android/native_window.h> #include <binder/ProcessState.h> #include <hwbinder/ProcessState.h> #include <log/log.h> #include <private/gui/ComposerService.h> #include <ui/DisplayInfo.h> #include <utils/Looper.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <limits> using namespace std::chrono_literals; using namespace android; using namespace android::hardware; using namespace sftest; namespace { // Mock test helpers using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::_; using Transaction = SurfaceComposerClient::Transaction; /////////////////////////////////////////////// struct TestColor { public: uint8_t r; uint8_t g; uint8_t b; uint8_t a; }; constexpr static TestColor RED = {195, 63, 63, 255}; constexpr static TestColor LIGHT_RED = {255, 177, 177, 255}; constexpr static TestColor GREEN = {63, 195, 63, 255}; constexpr static TestColor BLUE = {63, 63, 195, 255}; constexpr static TestColor DARK_GRAY = {63, 63, 63, 255}; constexpr static TestColor LIGHT_GRAY = {200, 200, 200, 255}; // Fill an RGBA_8888 formatted surface with a single color. static void fillSurfaceRGBA8(const sp<SurfaceControl>& sc, const TestColor& color, bool unlock = true) { ANativeWindow_Buffer outBuffer; sp<Surface> s = sc->getSurface(); ASSERT_TRUE(s != nullptr); ASSERT_EQ(NO_ERROR, s->lock(&outBuffer, nullptr)); uint8_t* img = reinterpret_cast<uint8_t*>(outBuffer.bits); for (int y = 0; y < outBuffer.height; y++) { for (int x = 0; x < outBuffer.width; x++) { uint8_t* pixel = img + (4 * (y * outBuffer.stride + x)); pixel[0] = color.r; pixel[1] = color.g; pixel[2] = color.b; pixel[3] = color.a; } } if (unlock) { ASSERT_EQ(NO_ERROR, s->unlockAndPost()); } } inline RenderState makeSimpleRect(int left, int top, int right, int bottom) { RenderState res; res.mDisplayFrame = hwc_rect_t{left, top, right, bottom}; res.mPlaneAlpha = 1.0f; res.mSwapCount = 0; res.mSourceCrop = hwc_frect_t{0.f, 0.f, static_cast<float>(right - left), static_cast<float>(bottom - top)}; return res; } inline RenderState makeSimpleRect(unsigned int left, unsigned int top, unsigned int right, unsigned int bottom) { EXPECT_LE(left, static_cast<unsigned int>(INT_MAX)); EXPECT_LE(top, static_cast<unsigned int>(INT_MAX)); EXPECT_LE(right, static_cast<unsigned int>(INT_MAX)); EXPECT_LE(bottom, static_cast<unsigned int>(INT_MAX)); return makeSimpleRect(static_cast<int>(left), static_cast<int>(top), static_cast<int>(right), static_cast<int>(bottom)); } //////////////////////////////////////////////// class DisplayTest : public ::testing::Test { public: class MockComposerClient : public FakeComposerClient { public: MOCK_METHOD2(getDisplayType, Error(Display display, ComposerClient::DisplayType* outType)); MOCK_METHOD4(getDisplayAttribute, Error(Display display, Config config, IComposerClient::Attribute attribute, int32_t* outValue)); // Re-routing to basic fake implementation Error getDisplayAttributeFake(Display display, Config config, IComposerClient::Attribute attribute, int32_t* outValue) { return FakeComposerClient::getDisplayAttribute(display, config, attribute, outValue); } }; protected: static int processDisplayEvents(int fd, int events, void* data); void SetUp() override; void TearDown() override; void waitForDisplayTransaction(); bool waitForHotplugEvent(PhysicalDisplayId displayId, bool connected); sp<IComposer> mFakeService; sp<SurfaceComposerClient> mComposerClient; MockComposerClient* mMockComposer; std::unique_ptr<DisplayEventReceiver> mReceiver; sp<Looper> mLooper;; std::deque<DisplayEventReceiver::Event> mReceivedDisplayEvents; }; void DisplayTest::SetUp() { // TODO: The mMockComposer should be a unique_ptr, but it needs to // outlive the test class. Currently ComposerClient only dies // when the service is replaced. The Mock deletes itself when // removeClient is called on it, which is ugly. This can be // changed if HIDL ServiceManager allows removing services or // ComposerClient starts taking the ownership of the contained // implementation class. Moving the fake class to the HWC2 // interface instead of the current Composer interface might also // change the situation. mMockComposer = new MockComposerClient; sp<ComposerClient> client = new ComposerClient(mMockComposer); mFakeService = new FakeComposerService(client); (void)mFakeService->registerAsService("mock"); android::hardware::ProcessState::self()->startThreadPool(); android::ProcessState::self()->startThreadPool(); EXPECT_CALL(*mMockComposer, getDisplayType(PRIMARY_DISPLAY, _)) .WillOnce(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL), Return(Error::NONE))); // Primary display will be queried twice for all 5 attributes. One // set of queries comes from the SurfaceFlinger proper an the // other set from the VR composer. // TODO: Is VR composer always present? Change to atLeast(5)? EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, _, _)) .Times(2 * 5) .WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake)); startSurfaceFlinger(); // Fake composer wants to enable VSync injection mMockComposer->onSurfaceFlingerStart(); mComposerClient = new SurfaceComposerClient; ASSERT_EQ(NO_ERROR, mComposerClient->initCheck()); mReceiver.reset(new DisplayEventReceiver()); mLooper = new Looper(false); mLooper->addFd(mReceiver->getFd(), 0, ALOOPER_EVENT_INPUT, processDisplayEvents, this); } void DisplayTest::TearDown() { mLooper = nullptr; mReceiver = nullptr; mComposerClient->dispose(); mComposerClient = nullptr; // Fake composer needs to release SurfaceComposerClient before the stop. mMockComposer->onSurfaceFlingerStop(); stopSurfaceFlinger(); mFakeService = nullptr; // TODO: Currently deleted in FakeComposerClient::removeClient(). Devise better lifetime // management. mMockComposer = nullptr; } int DisplayTest::processDisplayEvents(int /*fd*/, int /*events*/, void* data) { auto self = static_cast<DisplayTest*>(data); ssize_t n; DisplayEventReceiver::Event buffer[1]; while ((n = self->mReceiver->getEvents(buffer, 1)) > 0) { for (int i=0 ; i<n ; i++) { self->mReceivedDisplayEvents.push_back(buffer[i]); } } ALOGD_IF(n < 0, "Error reading events (%s)\n", strerror(-n)); return 1; } void DisplayTest::waitForDisplayTransaction() { // Both a refresh and a vsync event are needed to apply pending display // transactions. mMockComposer->refreshDisplay(EXTERNAL_DISPLAY); mMockComposer->runVSyncAndWait(); // Extra vsync and wait to avoid a 10% flake due to a race. mMockComposer->runVSyncAndWait(); } bool DisplayTest::waitForHotplugEvent(PhysicalDisplayId displayId, bool connected) { int waitCount = 20; while (waitCount--) { while (!mReceivedDisplayEvents.empty()) { auto event = mReceivedDisplayEvents.front(); mReceivedDisplayEvents.pop_front(); ALOGV_IF(event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, "event hotplug: displayId %" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT ", connected %d\t", event.header.displayId, event.hotplug.connected); if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG && event.header.displayId == displayId && event.hotplug.connected == connected) { return true; } } mLooper->pollOnce(1); } return false; } TEST_F(DisplayTest, Hotplug) { ALOGD("DisplayTest::Hotplug"); EXPECT_CALL(*mMockComposer, getDisplayType(EXTERNAL_DISPLAY, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL), Return(Error::NONE))); // The attribute queries will get done twice. This is for defaults EXPECT_CALL(*mMockComposer, getDisplayAttribute(EXTERNAL_DISPLAY, 1, _, _)) .Times(2 * 3) .WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake)); // ... and then special handling for dimensions. Specifying these // rules later means that gmock will try them first, i.e., // ordering of width/height vs. the default implementation for // other queries is significant. EXPECT_CALL(*mMockComposer, getDisplayAttribute(EXTERNAL_DISPLAY, 1, IComposerClient::Attribute::WIDTH, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<3>(400), Return(Error::NONE))); EXPECT_CALL(*mMockComposer, getDisplayAttribute(EXTERNAL_DISPLAY, 1, IComposerClient::Attribute::HEIGHT, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<3>(200), Return(Error::NONE))); mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::CONNECTED); waitForDisplayTransaction(); EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, true)); { const auto display = SurfaceComposerClient::getPhysicalDisplayToken(EXTERNAL_DISPLAY); ASSERT_FALSE(display == nullptr); DisplayInfo info; ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info)); ASSERT_EQ(400u, info.w); ASSERT_EQ(200u, info.h); auto surfaceControl = mComposerClient->createSurface(String8("Display Test Surface Foo"), info.w, info.h, PIXEL_FORMAT_RGBA_8888, 0); ASSERT_TRUE(surfaceControl != nullptr); ASSERT_TRUE(surfaceControl->isValid()); fillSurfaceRGBA8(surfaceControl, BLUE); { TransactionScope ts(*mMockComposer); ts.setDisplayLayerStack(display, 0); ts.setLayer(surfaceControl, INT32_MAX - 2) .show(surfaceControl); } } mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::DISCONNECTED); mMockComposer->clearFrames(); mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::CONNECTED); waitForDisplayTransaction(); EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, false)); EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, true)); { const auto display = SurfaceComposerClient::getPhysicalDisplayToken(EXTERNAL_DISPLAY); ASSERT_FALSE(display == nullptr); DisplayInfo info; ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info)); ASSERT_EQ(400u, info.w); ASSERT_EQ(200u, info.h); auto surfaceControl = mComposerClient->createSurface(String8("Display Test Surface Bar"), info.w, info.h, PIXEL_FORMAT_RGBA_8888, 0); ASSERT_TRUE(surfaceControl != nullptr); ASSERT_TRUE(surfaceControl->isValid()); fillSurfaceRGBA8(surfaceControl, BLUE); { TransactionScope ts(*mMockComposer); ts.setDisplayLayerStack(display, 0); ts.setLayer(surfaceControl, INT32_MAX - 2) .show(surfaceControl); } } mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::DISCONNECTED); } TEST_F(DisplayTest, HotplugPrimaryDisplay) { ALOGD("DisplayTest::HotplugPrimaryDisplay"); mMockComposer->hotplugDisplay(PRIMARY_DISPLAY, IComposerCallback::Connection::DISCONNECTED); waitForDisplayTransaction(); EXPECT_TRUE(waitForHotplugEvent(PRIMARY_DISPLAY, false)); { const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY); EXPECT_FALSE(display == nullptr); DisplayInfo info; auto result = SurfaceComposerClient::getDisplayInfo(display, &info); EXPECT_NE(NO_ERROR, result); } mMockComposer->clearFrames(); EXPECT_CALL(*mMockComposer, getDisplayType(PRIMARY_DISPLAY, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL), Return(Error::NONE))); // The attribute queries will get done twice. This is for defaults EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, _, _)) .Times(2 * 3) .WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake)); // ... and then special handling for dimensions. Specifying these // rules later means that gmock will try them first, i.e., // ordering of width/height vs. the default implementation for // other queries is significant. EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, IComposerClient::Attribute::WIDTH, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<3>(400), Return(Error::NONE))); EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, IComposerClient::Attribute::HEIGHT, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<3>(200), Return(Error::NONE))); mMockComposer->hotplugDisplay(PRIMARY_DISPLAY, IComposerCallback::Connection::CONNECTED); waitForDisplayTransaction(); EXPECT_TRUE(waitForHotplugEvent(PRIMARY_DISPLAY, true)); { const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY); EXPECT_FALSE(display == nullptr); DisplayInfo info; auto result = SurfaceComposerClient::getDisplayInfo(display, &info); EXPECT_EQ(NO_ERROR, result); ASSERT_EQ(400u, info.w); ASSERT_EQ(200u, info.h); } } //////////////////////////////////////////////// class TransactionTest : public ::testing::Test { protected: // Layer array indexing constants. constexpr static int BG_LAYER = 0; constexpr static int FG_LAYER = 1; static void SetUpTestCase(); static void TearDownTestCase(); void SetUp() override; void TearDown() override; sp<SurfaceComposerClient> mComposerClient; sp<SurfaceControl> mBGSurfaceControl; sp<SurfaceControl> mFGSurfaceControl; std::vector<RenderState> mBaseFrame; uint32_t mDisplayWidth; uint32_t mDisplayHeight; static FakeComposerClient* sFakeComposer; }; FakeComposerClient* TransactionTest::sFakeComposer; void TransactionTest::SetUpTestCase() { // TODO: See TODO comment at DisplayTest::SetUp for background on // the lifetime of the FakeComposerClient. sFakeComposer = new FakeComposerClient; sp<ComposerClient> client = new ComposerClient(sFakeComposer); sp<IComposer> fakeService = new FakeComposerService(client); (void)fakeService->registerAsService("mock"); android::hardware::ProcessState::self()->startThreadPool(); android::ProcessState::self()->startThreadPool(); startSurfaceFlinger(); // Fake composer wants to enable VSync injection sFakeComposer->onSurfaceFlingerStart(); } void TransactionTest::TearDownTestCase() { // Fake composer needs to release SurfaceComposerClient before the stop. sFakeComposer->onSurfaceFlingerStop(); stopSurfaceFlinger(); // TODO: This is deleted when the ComposerClient calls // removeClient. Devise better lifetime control. sFakeComposer = nullptr; } void TransactionTest::SetUp() { ALOGI("TransactionTest::SetUp"); mComposerClient = new SurfaceComposerClient; ASSERT_EQ(NO_ERROR, mComposerClient->initCheck()); ALOGI("TransactionTest::SetUp - display"); const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY); ASSERT_FALSE(display == nullptr); DisplayInfo info; ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info)); mDisplayWidth = info.w; mDisplayHeight = info.h; // Background surface mBGSurfaceControl = mComposerClient->createSurface(String8("BG Test Surface"), mDisplayWidth, mDisplayHeight, PIXEL_FORMAT_RGBA_8888, 0); ASSERT_TRUE(mBGSurfaceControl != nullptr); ASSERT_TRUE(mBGSurfaceControl->isValid()); fillSurfaceRGBA8(mBGSurfaceControl, BLUE); // Foreground surface mFGSurfaceControl = mComposerClient->createSurface(String8("FG Test Surface"), 64, 64, PIXEL_FORMAT_RGBA_8888, 0); ASSERT_TRUE(mFGSurfaceControl != nullptr); ASSERT_TRUE(mFGSurfaceControl->isValid()); fillSurfaceRGBA8(mFGSurfaceControl, RED); Transaction t; t.setDisplayLayerStack(display, 0); t.setLayer(mBGSurfaceControl, INT32_MAX - 2); t.show(mBGSurfaceControl); t.setLayer(mFGSurfaceControl, INT32_MAX - 1); t.setPosition(mFGSurfaceControl, 64, 64); t.show(mFGSurfaceControl); // Synchronous transaction will stop this thread, so we set up a // delayed, off-thread vsync request before closing the // transaction. In the test code this is usually done with // TransactionScope. Leaving here in the 'vanilla' form for // reference. ASSERT_EQ(0, sFakeComposer->getFrameCount()); sFakeComposer->runVSyncAfter(1ms); t.apply(); sFakeComposer->waitUntilFrame(1); // Reference data. This is what the HWC should see. static_assert(BG_LAYER == 0 && FG_LAYER == 1, "Unexpected enum values for array indexing"); mBaseFrame.push_back(makeSimpleRect(0u, 0u, mDisplayWidth, mDisplayHeight)); mBaseFrame[BG_LAYER].mSwapCount = 1; mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 64, 64 + 64)); mBaseFrame[FG_LAYER].mSwapCount = 1; auto frame = sFakeComposer->getFrameRects(0); ASSERT_TRUE(framesAreSame(mBaseFrame, frame)); } void TransactionTest::TearDown() { ALOGD("TransactionTest::TearDown"); mComposerClient->dispose(); mBGSurfaceControl = 0; mFGSurfaceControl = 0; mComposerClient = 0; sFakeComposer->runVSyncAndWait(); mBaseFrame.clear(); sFakeComposer->clearFrames(); ASSERT_EQ(0, sFakeComposer->getFrameCount()); sp<ISurfaceComposer> sf(ComposerService::getComposerService()); std::vector<LayerDebugInfo> layers; status_t result = sf->getLayerDebugInfo(&layers); if (result != NO_ERROR) { ALOGE("Failed to get layers %s %d", strerror(-result), result); } else { // If this fails, the test being torn down leaked layers. EXPECT_EQ(0u, layers.size()); if (layers.size() > 0) { for (auto layer = layers.begin(); layer != layers.end(); ++layer) { std::cout << to_string(*layer).c_str(); } // To ensure the next test has clean slate, will run the class // tear down and setup here. TearDownTestCase(); SetUpTestCase(); } } ALOGD("TransactionTest::TearDown - complete"); } TEST_F(TransactionTest, LayerMove) { ALOGD("TransactionTest::LayerMove"); // The scope opens and closes a global transaction and, at the // same time, makes sure the SurfaceFlinger progresses one frame // after the transaction closes. The results of the transaction // should be available in the latest frame stored by the fake // composer. { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 128, 128); // NOTE: No changes yet, so vsync will do nothing, HWC does not get any calls. // (How to verify that? Throw in vsync and wait a 2x frame time? Separate test?) // // sFakeComposer->runVSyncAndWait(); } fillSurfaceRGBA8(mFGSurfaceControl, GREEN); sFakeComposer->runVSyncAndWait(); ASSERT_EQ(3, sFakeComposer->getFrameCount()); // Make sure the waits didn't time out and there's // no extra frames. // NOTE: Frame 0 is produced in the SetUp. auto frame1Ref = mBaseFrame; frame1Ref[FG_LAYER].mDisplayFrame = hwc_rect_t{128, 128, 128 + 64, 128 + 64}; // Top-most layer moves. EXPECT_TRUE(framesAreSame(frame1Ref, sFakeComposer->getFrameRects(1))); auto frame2Ref = frame1Ref; frame2Ref[FG_LAYER].mSwapCount++; EXPECT_TRUE(framesAreSame(frame2Ref, sFakeComposer->getFrameRects(2))); } TEST_F(TransactionTest, LayerResize) { ALOGD("TransactionTest::LayerResize"); { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 128, 128); } fillSurfaceRGBA8(mFGSurfaceControl, GREEN); sFakeComposer->runVSyncAndWait(); ASSERT_EQ(3, sFakeComposer->getFrameCount()); // Make sure the waits didn't time out and there's // no extra frames. auto frame1Ref = mBaseFrame; // NOTE: The resize should not be visible for frame 1 as there's no buffer with new size posted. EXPECT_TRUE(framesAreSame(frame1Ref, sFakeComposer->getFrameRects(1))); auto frame2Ref = frame1Ref; frame2Ref[FG_LAYER].mSwapCount++; frame2Ref[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 128, 64 + 128}; frame2Ref[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 128.f, 128.f}; EXPECT_TRUE(framesAreSame(frame2Ref, sFakeComposer->getFrameRects(2))); } TEST_F(TransactionTest, LayerCrop) { // TODO: Add scaling to confirm that crop happens in buffer space? { TransactionScope ts(*sFakeComposer); Rect cropRect(16, 16, 32, 32); ts.setCrop_legacy(mFGSurfaceControl, cropRect); } ASSERT_EQ(2, sFakeComposer->getFrameCount()); auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{16.f, 16.f, 32.f, 32.f}; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64 + 16, 64 + 16, 64 + 32, 64 + 32}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerSetLayer) { { TransactionScope ts(*sFakeComposer); ts.setLayer(mFGSurfaceControl, INT_MAX - 3); } ASSERT_EQ(2, sFakeComposer->getFrameCount()); // The layers will switch order, but both are rendered because the background layer is // transparent (RGBA8888). std::vector<RenderState> referenceFrame(2); referenceFrame[0] = mBaseFrame[FG_LAYER]; referenceFrame[1] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerSetLayerOpaque) { { TransactionScope ts(*sFakeComposer); ts.setLayer(mFGSurfaceControl, INT_MAX - 3); ts.setFlags(mBGSurfaceControl, layer_state_t::eLayerOpaque, layer_state_t::eLayerOpaque); } ASSERT_EQ(2, sFakeComposer->getFrameCount()); // The former foreground layer is now covered with opaque layer - it should have disappeared std::vector<RenderState> referenceFrame(1); referenceFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, SetLayerStack) { ALOGD("TransactionTest::SetLayerStack"); { TransactionScope ts(*sFakeComposer); ts.setLayerStack(mFGSurfaceControl, 1); } // Foreground layer should have disappeared. ASSERT_EQ(2, sFakeComposer->getFrameCount()); std::vector<RenderState> refFrame(1); refFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerShowHide) { ALOGD("TransactionTest::LayerShowHide"); { TransactionScope ts(*sFakeComposer); ts.hide(mFGSurfaceControl); } // Foreground layer should have disappeared. ASSERT_EQ(2, sFakeComposer->getFrameCount()); std::vector<RenderState> refFrame(1); refFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.show(mFGSurfaceControl); } // Foreground layer should be back ASSERT_EQ(3, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerSetAlpha) { { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 0.75f); } ASSERT_EQ(2, sFakeComposer->getFrameCount()); auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mPlaneAlpha = 0.75f; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerSetFlags) { { TransactionScope ts(*sFakeComposer); ts.setFlags(mFGSurfaceControl, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden); } // Foreground layer should have disappeared. ASSERT_EQ(2, sFakeComposer->getFrameCount()); std::vector<RenderState> refFrame(1); refFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, LayerSetMatrix) { struct matrixTestData { float matrix[4]; hwc_transform_t expectedTransform; hwc_rect_t expectedDisplayFrame; }; // The matrix operates on the display frame and is applied before // the position is added. So, the foreground layer rect is (0, 0, // 64, 64) is first transformed, potentially yielding negative // coordinates and then the position (64, 64) is added yielding // the final on-screen rectangles given. const matrixTestData MATRIX_TESTS[7] = // clang-format off {{{-1.f, 0.f, 0.f, 1.f}, HWC_TRANSFORM_FLIP_H, {0, 64, 64, 128}}, {{1.f, 0.f, 0.f, -1.f}, HWC_TRANSFORM_FLIP_V, {64, 0, 128, 64}}, {{0.f, 1.f, -1.f, 0.f}, HWC_TRANSFORM_ROT_90, {0, 64, 64, 128}}, {{-1.f, 0.f, 0.f, -1.f}, HWC_TRANSFORM_ROT_180, {0, 0, 64, 64}}, {{0.f, -1.f, 1.f, 0.f}, HWC_TRANSFORM_ROT_270, {64, 0, 128, 64}}, {{0.f, 1.f, 1.f, 0.f}, HWC_TRANSFORM_FLIP_H_ROT_90, {64, 64, 128, 128}}, {{0.f, 1.f, 1.f, 0.f}, HWC_TRANSFORM_FLIP_V_ROT_90, {64, 64, 128, 128}}}; // clang-format on constexpr int TEST_COUNT = sizeof(MATRIX_TESTS) / sizeof(matrixTestData); for (int i = 0; i < TEST_COUNT; i++) { // TODO: How to leverage the HWC2 stringifiers? const matrixTestData& xform = MATRIX_TESTS[i]; SCOPED_TRACE(i); { TransactionScope ts(*sFakeComposer); ts.setMatrix(mFGSurfaceControl, xform.matrix[0], xform.matrix[1], xform.matrix[2], xform.matrix[3]); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mTransform = xform.expectedTransform; referenceFrame[FG_LAYER].mDisplayFrame = xform.expectedDisplayFrame; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } } #if 0 TEST_F(TransactionTest, LayerSetMatrix2) { { TransactionScope ts(*sFakeComposer); // TODO: PLEASE SPEC THE FUNCTION! ts.setMatrix(mFGSurfaceControl, 0.11f, 0.123f, -2.33f, 0.22f); } auto referenceFrame = mBaseFrame; // TODO: Is this correct for sure? //referenceFrame[FG_LAYER].mTransform = HWC_TRANSFORM_FLIP_V & HWC_TRANSFORM_ROT_90; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } #endif TEST_F(TransactionTest, DeferredTransaction) { // Synchronization surface constexpr static int SYNC_LAYER = 2; auto syncSurfaceControl = mComposerClient->createSurface(String8("Sync Test Surface"), 1, 1, PIXEL_FORMAT_RGBA_8888, 0); ASSERT_TRUE(syncSurfaceControl != nullptr); ASSERT_TRUE(syncSurfaceControl->isValid()); fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY); { TransactionScope ts(*sFakeComposer); ts.setLayer(syncSurfaceControl, INT32_MAX - 1); ts.setPosition(syncSurfaceControl, mDisplayWidth - 2, mDisplayHeight - 2); ts.show(syncSurfaceControl); } auto referenceFrame = mBaseFrame; referenceFrame.push_back(makeSimpleRect(mDisplayWidth - 2, mDisplayHeight - 2, mDisplayWidth - 1, mDisplayHeight - 1)); referenceFrame[SYNC_LAYER].mSwapCount = 1; EXPECT_EQ(2, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); // set up two deferred transactions on different frames - these should not yield composited // frames { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 0.75); ts.deferTransactionUntil_legacy(mFGSurfaceControl, syncSurfaceControl->getHandle(), syncSurfaceControl->getSurface()->getNextFrameNumber()); } EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 128, 128); ts.deferTransactionUntil_legacy(mFGSurfaceControl, syncSurfaceControl->getHandle(), syncSurfaceControl->getSurface()->getNextFrameNumber() + 1); } EXPECT_EQ(4, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); // should trigger the first deferred transaction, but not the second one fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY); sFakeComposer->runVSyncAndWait(); EXPECT_EQ(5, sFakeComposer->getFrameCount()); referenceFrame[FG_LAYER].mPlaneAlpha = 0.75f; referenceFrame[SYNC_LAYER].mSwapCount++; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); // should show up immediately since it's not deferred { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 1.0); } referenceFrame[FG_LAYER].mPlaneAlpha = 1.f; EXPECT_EQ(6, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); // trigger the second deferred transaction fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY); sFakeComposer->runVSyncAndWait(); // TODO: Compute from layer size? referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{128, 128, 128 + 64, 128 + 64}; referenceFrame[SYNC_LAYER].mSwapCount++; EXPECT_EQ(7, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(TransactionTest, SetRelativeLayer) { constexpr int RELATIVE_LAYER = 2; auto relativeSurfaceControl = mComposerClient->createSurface(String8("Test Surface"), 64, 64, PIXEL_FORMAT_RGBA_8888, 0); fillSurfaceRGBA8(relativeSurfaceControl, LIGHT_RED); // Now we stack the surface above the foreground surface and make sure it is visible. { TransactionScope ts(*sFakeComposer); ts.setPosition(relativeSurfaceControl, 64, 64); ts.show(relativeSurfaceControl); ts.setRelativeLayer(relativeSurfaceControl, mFGSurfaceControl->getHandle(), 1); } auto referenceFrame = mBaseFrame; // NOTE: All three layers will be visible as the surfaces are // transparent because of the RGBA format. referenceFrame.push_back(makeSimpleRect(64, 64, 64 + 64, 64 + 64)); referenceFrame[RELATIVE_LAYER].mSwapCount = 1; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); // A call to setLayer will override a call to setRelativeLayer { TransactionScope ts(*sFakeComposer); ts.setLayer(relativeSurfaceControl, 0); } // Previous top layer will now appear at the bottom. auto referenceFrame2 = mBaseFrame; referenceFrame2.insert(referenceFrame2.begin(), referenceFrame[RELATIVE_LAYER]); EXPECT_EQ(3, sFakeComposer->getFrameCount()); EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } class ChildLayerTest : public TransactionTest { protected: constexpr static int CHILD_LAYER = 2; void SetUp() override { TransactionTest::SetUp(); mChild = mComposerClient->createSurface(String8("Child surface"), 10, 10, PIXEL_FORMAT_RGBA_8888, 0, mFGSurfaceControl.get()); fillSurfaceRGBA8(mChild, LIGHT_GRAY); sFakeComposer->runVSyncAndWait(); mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 10, 64 + 10)); mBaseFrame[CHILD_LAYER].mSwapCount = 1; ASSERT_EQ(2, sFakeComposer->getFrameCount()); ASSERT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame())); } void TearDown() override { mChild = 0; TransactionTest::TearDown(); } sp<SurfaceControl> mChild; }; TEST_F(ChildLayerTest, Positioning) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 10, 10); // Move to the same position as in the original setup. ts.setPosition(mFGSurfaceControl, 64, 64); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 0, 0); } auto referenceFrame2 = mBaseFrame; referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 64, 0 + 64}; referenceFrame2[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0 + 10, 0 + 10, 0 + 10 + 10, 0 + 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, Cropping) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 5, 5)); } // NOTE: The foreground surface would be occluded by the child // now, but is included in the stack because the child is // transparent. auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 5, 0 + 5}; referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 5.f, 5.f}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 5, 0 + 5}; referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 5.f, 5.f}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, Constraints) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mFGSurfaceControl, 0, 0); ts.setPosition(mChild, 63, 63); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{63, 63, 64, 64}; referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 1.f, 1.f}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, Scaling) { { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 0, 0); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setMatrix(mFGSurfaceControl, 2.0, 0, 0, 2.0); } auto referenceFrame2 = mBaseFrame; referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 128}; referenceFrame2[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 20, 20}; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, LayerAlpha) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); ts.setAlpha(mChild, 0.5); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10}; referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 0.5); } auto referenceFrame2 = referenceFrame; referenceFrame2[FG_LAYER].mPlaneAlpha = 0.5f; referenceFrame2[CHILD_LAYER].mPlaneAlpha = 0.25f; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, ReparentChildren) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 10, 10); ts.setPosition(mFGSurfaceControl, 64, 64); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.reparentChildren(mFGSurfaceControl, mBGSurfaceControl->getHandle()); } auto referenceFrame2 = referenceFrame; referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64}; referenceFrame2[CHILD_LAYER].mDisplayFrame = hwc_rect_t{10, 10, 10 + 10, 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, DetachChildrenSameClient) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 10, 10); ts.setPosition(mFGSurfaceControl, 64, 64); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 0, 0); ts.detachChildren(mFGSurfaceControl); } { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 64, 64); ts.hide(mChild); } std::vector<RenderState> refFrame(2); refFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; refFrame[FG_LAYER] = mBaseFrame[FG_LAYER]; EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, DetachChildrenDifferentClient) { sp<SurfaceComposerClient> newComposerClient = new SurfaceComposerClient; sp<SurfaceControl> childNewClient = newComposerClient->createSurface(String8("New Child Test Surface"), 10, 10, PIXEL_FORMAT_RGBA_8888, 0, mFGSurfaceControl.get()); ASSERT_TRUE(childNewClient != nullptr); ASSERT_TRUE(childNewClient->isValid()); fillSurfaceRGBA8(childNewClient, LIGHT_GRAY); { TransactionScope ts(*sFakeComposer); ts.hide(mChild); ts.show(childNewClient); ts.setPosition(childNewClient, 10, 10); ts.setPosition(mFGSurfaceControl, 64, 64); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.detachChildren(mFGSurfaceControl); ts.setPosition(mFGSurfaceControl, 0, 0); } { TransactionScope ts(*sFakeComposer); ts.setPosition(mFGSurfaceControl, 64, 64); ts.setPosition(childNewClient, 0, 0); ts.hide(childNewClient); } // Nothing should have changed. The child control becomes a no-op // zombie on detach. See comments for detachChildren in the // SurfaceControl.h file. EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, InheritNonTransformScalingFromParent) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); } { TransactionScope ts(*sFakeComposer); ts.setOverrideScalingMode(mFGSurfaceControl, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); // We cause scaling by 2. ts.setSize(mFGSurfaceControl, 128, 128); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 128}; referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 64.f, 64.f}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 20, 20}; referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 10.f, 10.f}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } // Regression test for b/37673612 TEST_F(ChildLayerTest, ChildrenWithParentBufferTransform) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); } // We set things up as in b/37673612 so that there is a mismatch between the buffer size and // the WM specified state size. { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 128, 64); } sp<Surface> s = mFGSurfaceControl->getSurface(); auto anw = static_cast<ANativeWindow*>(s.get()); native_window_set_buffers_transform(anw, NATIVE_WINDOW_TRANSFORM_ROT_90); native_window_set_buffers_dimensions(anw, 64, 128); fillSurfaceRGBA8(mFGSurfaceControl, RED); sFakeComposer->runVSyncAndWait(); // The child should still be in the same place and not have any strange scaling as in // b/37673612. auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 64}; referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 64.f, 128.f}; referenceFrame[FG_LAYER].mSwapCount++; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10}; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); } TEST_F(ChildLayerTest, Bug36858924) { // Destroy the child layer mChild.clear(); // Now recreate it as hidden mChild = mComposerClient->createSurface(String8("Child surface"), 10, 10, PIXEL_FORMAT_RGBA_8888, ISurfaceComposerClient::eHidden, mFGSurfaceControl.get()); // Show the child layer in a deferred transaction { TransactionScope ts(*sFakeComposer); ts.deferTransactionUntil_legacy(mChild, mFGSurfaceControl->getHandle(), mFGSurfaceControl->getSurface()->getNextFrameNumber()); ts.show(mChild); } // Render the foreground surface a few times // // Prior to the bugfix for b/36858924, this would usually hang while trying to fill the third // frame because SurfaceFlinger would never process the deferred transaction and would therefore // never acquire/release the first buffer ALOGI("Filling 1"); fillSurfaceRGBA8(mFGSurfaceControl, GREEN); sFakeComposer->runVSyncAndWait(); ALOGI("Filling 2"); fillSurfaceRGBA8(mFGSurfaceControl, BLUE); sFakeComposer->runVSyncAndWait(); ALOGI("Filling 3"); fillSurfaceRGBA8(mFGSurfaceControl, RED); sFakeComposer->runVSyncAndWait(); ALOGI("Filling 4"); fillSurfaceRGBA8(mFGSurfaceControl, GREEN); sFakeComposer->runVSyncAndWait(); } class ChildColorLayerTest : public ChildLayerTest { protected: void SetUp() override { TransactionTest::SetUp(); mChild = mComposerClient->createSurface(String8("Child surface"), 0, 0, PIXEL_FORMAT_RGBA_8888, ISurfaceComposerClient::eFXSurfaceColor, mFGSurfaceControl.get()); { TransactionScope ts(*sFakeComposer); ts.setColor(mChild, {LIGHT_GRAY.r / 255.0f, LIGHT_GRAY.g / 255.0f, LIGHT_GRAY.b / 255.0f}); ts.setCrop_legacy(mChild, Rect(0, 0, 10, 10)); } sFakeComposer->runVSyncAndWait(); mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 10, 64 + 10)); mBaseFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.0f, 0.0f, 0.0f, 0.0f}; mBaseFrame[CHILD_LAYER].mSwapCount = 0; ASSERT_EQ(2, sFakeComposer->getFrameCount()); ASSERT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame())); } }; TEST_F(ChildColorLayerTest, LayerAlpha) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); ts.setAlpha(mChild, 0.5); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10}; referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 0.5); } auto referenceFrame2 = referenceFrame; referenceFrame2[FG_LAYER].mPlaneAlpha = 0.5f; referenceFrame2[CHILD_LAYER].mPlaneAlpha = 0.25f; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(ChildColorLayerTest, LayerZeroAlpha) { { TransactionScope ts(*sFakeComposer); ts.show(mChild); ts.setPosition(mChild, 0, 0); ts.setPosition(mFGSurfaceControl, 0, 0); ts.setAlpha(mChild, 0.5); } auto referenceFrame = mBaseFrame; referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64}; referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10}; referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f; EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame())); { TransactionScope ts(*sFakeComposer); ts.setAlpha(mFGSurfaceControl, 0.0f); } std::vector<RenderState> refFrame(1); refFrame[BG_LAYER] = mBaseFrame[BG_LAYER]; EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame())); } class LatchingTest : public TransactionTest { protected: void lockAndFillFGBuffer() { fillSurfaceRGBA8(mFGSurfaceControl, RED, false); } void unlockFGBuffer() { sp<Surface> s = mFGSurfaceControl->getSurface(); ASSERT_EQ(NO_ERROR, s->unlockAndPost()); sFakeComposer->runVSyncAndWait(); } void completeFGResize() { fillSurfaceRGBA8(mFGSurfaceControl, RED); sFakeComposer->runVSyncAndWait(); } void restoreInitialState() { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 64, 64); ts.setPosition(mFGSurfaceControl, 64, 64); ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 64, 64)); } }; TEST_F(LatchingTest, SurfacePositionLatching) { // By default position can be updated even while // a resize is pending. { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 32, 32); ts.setPosition(mFGSurfaceControl, 100, 100); } // The size should not have updated as we have not provided a new buffer. auto referenceFrame1 = mBaseFrame; referenceFrame1[FG_LAYER].mDisplayFrame = hwc_rect_t{100, 100, 100 + 64, 100 + 64}; EXPECT_TRUE(framesAreSame(referenceFrame1, sFakeComposer->getLatestFrame())); restoreInitialState(); // Now we repeat with setGeometryAppliesWithResize // and verify the position DOESN'T latch. { TransactionScope ts(*sFakeComposer); ts.setGeometryAppliesWithResize(mFGSurfaceControl); ts.setSize(mFGSurfaceControl, 32, 32); ts.setPosition(mFGSurfaceControl, 100, 100); } EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame())); completeFGResize(); auto referenceFrame2 = mBaseFrame; referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{100, 100, 100 + 32, 100 + 32}; referenceFrame2[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 32.f, 32.f}; referenceFrame2[FG_LAYER].mSwapCount++; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } TEST_F(LatchingTest, CropLatching) { // Normally the crop applies immediately even while a resize is pending. { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 128, 128); ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 63, 63)); } auto referenceFrame1 = mBaseFrame; referenceFrame1[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 63, 64 + 63}; referenceFrame1[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 63.f, 63.f}; EXPECT_TRUE(framesAreSame(referenceFrame1, sFakeComposer->getLatestFrame())); restoreInitialState(); { TransactionScope ts(*sFakeComposer); ts.setSize(mFGSurfaceControl, 128, 128); ts.setGeometryAppliesWithResize(mFGSurfaceControl); ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 63, 63)); } EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame())); completeFGResize(); auto referenceFrame2 = mBaseFrame; referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 63, 64 + 63}; referenceFrame2[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 63.f, 63.f}; referenceFrame2[FG_LAYER].mSwapCount++; EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame())); } } // namespace int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); sftest::FakeHwcEnvironment* fakeEnvironment = new sftest::FakeHwcEnvironment; ::testing::AddGlobalTestEnvironment(fakeEnvironment); ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
37.734577
100
0.675221
dAck2cC2
f9e7b6666e7721cd253c562107c7a71029b49ad3
2,789
cpp
C++
problem_105.cpp
Xinghui-Wu/LeetCode
531d6a0bfa37ec4c729940f35a438c764e71e699
[ "MIT" ]
null
null
null
problem_105.cpp
Xinghui-Wu/LeetCode
531d6a0bfa37ec4c729940f35a438c764e71e699
[ "MIT" ]
null
null
null
problem_105.cpp
Xinghui-Wu/LeetCode
531d6a0bfa37ec4c729940f35a438c764e71e699
[ "MIT" ]
null
null
null
/** * 105. Construct Binary Tree from Preorder and Inorder Traversal * * Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. * * Constraints: * 1 <= preorder.length <= 3000 * inorder.length == preorder.length * -3000 <= preorder[i], inorder[i] <= 3000 * preorder and inorder consist of unique values. * Each value of inorder also appears in preorder. * preorder is guaranteed to be the preorder traversal of the tree. * inorder is guaranteed to be the inorder traversal of the tree. * * Difficulty: Medium * Related Topics: Array, Hash Table, Divide and Conquer, Tree, Binary Tree */ #include <iostream> #include <vector> #include <unordered_map> #include "node.h" using namespace std; class Solution { private: // Build a hashmap to record the relation of value and index for inorder. unordered_map<int, size_t> inorder_index_map; // Keep track of the element that will be used to construct the root. int current_preorder; public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { inorder_index_map.clear(); for (size_t i = 0; i < inorder.size(); i++) { inorder_index_map.insert({inorder[i], i}); } current_preorder = 0; TreeNode* root = build_subtree(preorder, 0, preorder.size() - 1); return root; } /** * To find the left and right subtrees, it will look for the root in inorder. * Everything on the left should be the left subtree, and everything on the right should be the right subtree. * Both subtrees can be constructed by making another recursion call. * Always use the next element in preorder to initialize a root. */ TreeNode* build_subtree(vector<int>& preorder, int left, int right) { if (left > right) { return nullptr; } // Select the element indexed by current_preorder as the root. TreeNode* root = new TreeNode(preorder[current_preorder++]); // Locate the element indexed by current_preorder in inorder list. int inorder_index = inorder_index_map[root->val]; // Recursively build the left and right subtrees. root->left = build_subtree(preorder, left, inorder_index - 1); root->right = build_subtree(preorder, inorder_index + 1, right); return root; } }; int main() { vector<int> preorder = {3, 9, 20, 15, 7}; vector<int> inorder = {9, 3, 15, 20, 7}; Solution solution; TreeNode* root = solution.buildTree(preorder, inorder); output_level_order_traversal(root); return 0; }
30.315217
199
0.660452
Xinghui-Wu
f9ed1a6ff70fbe1cad9b750ec3fc6ced9712456a
1,633
cpp
C++
console/PhraseManager.cpp
mwgit00/cpox
9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c
[ "MIT" ]
null
null
null
console/PhraseManager.cpp
mwgit00/cpox
9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c
[ "MIT" ]
null
null
null
console/PhraseManager.cpp
mwgit00/cpox
9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c
[ "MIT" ]
null
null
null
#include <fstream> #include <sstream> #include <iostream> #include <opencv2/core/core.hpp> #include "PhraseManager.h" PhraseManager::PhraseManager() : default_phrase({ "this is a test", "" }), phrases(), next_phrase_index(0) { } PhraseManager::~PhraseManager() { } bool PhraseManager::load(const std::string& rs) { bool result = false; cv::FileStorage fs; fs.open(rs, cv::FileStorage::READ); if (fs.isOpened()) { cv::FileNode n; n = fs["phrases"]; if (n.isSeq()) { cv::FileNodeIterator iter; for (iter = n.begin(); iter != n.end(); iter++) { cv::FileNode& rnn = *iter; phrases.push_back(T_phrase_info({ rnn["text"], rnn["wav"] })); } // sanity check result = true; for (const auto& r : phrases) { if (!r.text.length()) { result = false; break; } } } } next_phrase_index = 0; return result; } const PhraseManager::T_phrase_info& PhraseManager::next_phrase(void) { if (phrases.size()) { int n = next_phrase_index; if (false) { // random for next time ///@TODO -- add support for a random mode } else { // in sequence from file next_phrase_index = (next_phrase_index + 1) % phrases.size(); } return phrases[n]; } else { return default_phrase; } }
19.211765
78
0.478261
mwgit00
f9f3d2a2b250479d5d0ce89f366ed1fa5d9c6245
672
hpp
C++
include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Types/generated/Vector2.hpp> namespace RED4ext { namespace ink { struct SingleDrawMetric { static constexpr const char* NAME = "inkSingleDrawMetric"; static constexpr const char* ALIAS = NAME; bool exeedsLimit; // 00 uint8_t unk01[0x4 - 0x1]; // 1 Vector2 hierarchySize; // 04 uint8_t unk0C[0x10 - 0xC]; // C DynArray<uint32_t> usedTextures; // 10 }; RED4EXT_ASSERT_SIZE(SingleDrawMetric, 0x20); } // namespace ink } // namespace RED4ext
24
62
0.720238
Cyberpunk-Extended-Development-Team
f9f9d16de2b711be2cd02a3f67e4759abeabb55f
561
hh
C++
Sources/AGEngine/Render/Textures/PixelTypesFormats.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Render/Textures/PixelTypesFormats.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Render/Textures/PixelTypesFormats.hh
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#pragma once # include <Utils/OpenGL.hh> # include <unordered_map> struct PixelType { public: size_t size; public: PixelType() : size(0) { } PixelType(size_t size) : size(size) { } PixelType(PixelType const &copy) : size(copy.size) { } PixelType(PixelType &&move) : size(move.size) { } }; std::unordered_map<GLenum, PixelType> available_type_pixel = { { GL_UNSIGNED_BYTE, PixelType(1) }, { GL_UNSIGNED_INT, PixelType(4) }, { GL_UNSIGNED_SHORT, PixelType(2) }, { GL_UNSIGNED_INT_24_8, PixelType(4) }, { GL_FLOAT, PixelType(4) } };
14.384615
60
0.673797
Another-Game-Engine
e6013180dcfd4783f0ec756ec1979cc001bb67b0
2,540
cpp
C++
Tempest/ui/controls/dialog.cpp
enotio/Tempest
1a7105cfca3669d54c696ad8188f04f25159c0a0
[ "MIT" ]
5
2017-05-31T21:25:57.000Z
2020-01-14T14:11:41.000Z
Tempest/ui/controls/dialog.cpp
enotio/Tempest
1a7105cfca3669d54c696ad8188f04f25159c0a0
[ "MIT" ]
2
2017-11-13T14:32:21.000Z
2018-10-03T17:07:36.000Z
Tempest/ui/controls/dialog.cpp
enotio/Tempest
1a7105cfca3669d54c696ad8188f04f25159c0a0
[ "MIT" ]
2
2018-01-31T14:06:58.000Z
2018-10-02T11:46:34.000Z
#include "dialog.h" #include <Tempest/SystemAPI> #include <Tempest/Window> #include <Tempest/Layout> #include <Tempest/Application> using namespace Tempest; struct Dialog::LayShadow : Tempest::Layout { void applyLayout(){ for(Widget* w:widgets()){ Point pos = w->pos(); if(w->x()+w->w()>owner()->w()) pos.x = owner()->w()-w->w(); if(w->y()+w->h()>owner()->h()) pos.y = owner()->h()-w->h(); if(pos.x<=0) pos.x = 0; if(pos.y<=0) pos.y = 0; w->setPosition(pos); } } }; struct Dialog::Overlay : public Tempest::WindowOverlay { bool isModal = true; Dialog * dlg = nullptr; void mouseDownEvent(MouseEvent& e){ e.accept(); } void mouseMoveEvent(MouseEvent& e){ e.accept(); } void mouseWheelEvent(MouseEvent& e){ e.accept(); } void paintEvent(PaintEvent& e){ dlg->paintShadow(e); paintNested(e); } void keyDownEvent(Tempest::KeyEvent& e){ dlg->keyDownEvent(e); e.accept(); } void keyUpEvent(Tempest::KeyEvent& e){ dlg->keyUpEvent(e); e.accept(); } void gestureEvent(Tempest::AbstractGestureEvent &e) { e.accept(); } }; Dialog::Dialog() : owner_ov(nullptr) { resize(300,200); setDragable(1); } Dialog::~Dialog() { close(); } int Dialog::exec() { if(!owner_ov){ owner_ov = new Overlay(); owner_ov->dlg = this; T_ASSERT( SystemAPI::instance().addOverlay( owner_ov )!=0 ); owner_ov->setLayout( new LayShadow() ); owner_ov->layout().add( this ); } setVisible(true); setPosition( (owner_ov->w()-w())/2, (owner_ov->h()-h())/2 ); while( owner_ov && !Application::isQuit() ) { Application::processEvents(); } return 0; } void Dialog::close() { if( owner_ov ){ Tempest::WindowOverlay* ov = owner_ov; owner_ov = 0; setVisible(0); CloseEvent e; this->closeEvent(e); ov->layout().take(this); ov->deleteLater(); } } void Dialog::setModal(bool m) { if(owner_ov) owner_ov->isModal = m; } bool Dialog::isModal() const { return owner_ov ? owner_ov->isModal : false; } void Dialog::closeEvent( CloseEvent & e ) { if(!owner_ov) e.ignore(); else close(); } void Dialog::keyDownEvent(KeyEvent &e) { if(e.key==KeyEvent::K_ESCAPE) close(); } void Dialog::paintShadow(PaintEvent &e) { if(!owner_ov) return; Painter p(e); p.setBlendMode(alphaBlend); p.setColor(0,0,0,0.5); p.drawRect(0,0,owner_ov->w(),owner_ov->h()); }
18.676471
64
0.583071
enotio
e601af42c7968e56411ca1a9afbc905c6b1658c8
1,485
cpp
C++
src/DataWriter/LocalFile.cpp
NIMML/ENISI-MSM
1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4
[ "Apache-2.0" ]
2
2017-01-23T15:33:07.000Z
2017-01-23T17:51:24.000Z
src/DataWriter/LocalFile.cpp
NIMML/ENISI-MSM
1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4
[ "Apache-2.0" ]
null
null
null
src/DataWriter/LocalFile.cpp
NIMML/ENISI-MSM
1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4
[ "Apache-2.0" ]
2
2016-12-09T18:44:46.000Z
2017-08-30T00:02:15.000Z
/* * LocalFile.cpp * * Created on: Apr 8, 2016 * Author: shoops */ #include "LocalFile.h" #include "repast_hpc/RepastProcess.h" #include "grid/Properties.h" #include <sstream> using namespace ENISI; // static std::map< std::string, LocalFile * > LocalFile::INSTANCES; // static std::ofstream & LocalFile::debug() { return LocalFile::instance("", "log")->stream(); } // static LocalFile * LocalFile::instance(const std::string & name, const std::string extension) { std::map< std::string, LocalFile * >::iterator found = INSTANCES.find(name); if (found == INSTANCES.end()) { found = INSTANCES.insert(std::make_pair(name, new LocalFile(name, extension))).first; } return found->second; } // static void LocalFile::close() { std::map< std::string, LocalFile * >::iterator it = INSTANCES.begin(); std::map< std::string, LocalFile * >::iterator end = INSTANCES.end(); for (; it != end; ++it) { delete it->second; } } LocalFile::LocalFile(const std::string & name, const std::string extension): mOstream() { std::string config; Properties::instance(Properties::model)->getValue("config", config); std::stringstream Name; Name << config << "/" << name << "_" << repast::RepastProcess::instance()->rank() << "." << extension; mOstream.open(Name.str().c_str()); } // virtual LocalFile::~LocalFile() { mOstream.close(); } std::ofstream & LocalFile::stream() { return mOstream; }
20.342466
104
0.63165
NIMML
e6043b61083693edbce8bb0af6929e97e3dee1d4
15,611
cc
C++
problems/ObsDrivingModel/ObsDrivingModel.cc
ppnathan/HMSHS
ae65c7622cf4b10d710722084d73a2ad8636bc9e
[ "Apache-2.0" ]
null
null
null
problems/ObsDrivingModel/ObsDrivingModel.cc
ppnathan/HMSHS
ae65c7622cf4b10d710722084d73a2ad8636bc9e
[ "Apache-2.0" ]
null
null
null
problems/ObsDrivingModel/ObsDrivingModel.cc
ppnathan/HMSHS
ae65c7622cf4b10d710722084d73a2ad8636bc9e
[ "Apache-2.0" ]
null
null
null
#include "ObsDrivingModel.h" #include "Utilities.h" #include <cmath> #include <cstdlib> #include <random> #include <iostream> #include <array> using namespace std; const double Discount_ObsDrMdl = 0.95; const int NumCStateVar_ObsDrMdl = 2; // number of continuous state variables const int NumDState_ObsDrMdl = 8; //number of discrete states const int NumCObsVar_ObsDrMdl = 2; // number of continuous observation variables const int NumDObs_ObsDrMdl = 3; //number of discrete observations const int NumDControls_ObsDrMdl = 4; // number of discrete controls enum { ASC0 = 0, ASC1 = 1, ATC0 = 2, ATC1 = 3, DSC0 = 4, DSC1 = 5, DTC0 = 6, DTC1 = 7}; // q: AC0:(Attentive, Controller 0); AC1:(Attentive, Controller 1); DC0:(Distracted, Controller 0); DC1:(Distracted, Controller 1); //(q>>2: 0=Attentive or 1=Distracted), (q & 0x02: 0=Straight or 1=Turn), (q & 0x01: 0 = C0 or 1 = C1) enum {V00 = 0, V01 = 1, V10 = 2, V11 = 3}; // sigma: V00:(Reminder off, Execute C0); V01:(Reminder off, Execute C1); V10:(Reminder on, Execute C0); V11:(Reminder on, Execute C1); //((sigma>>1): 0 = Reminder off or 1 = Reminder on; (sigma & 0x01): 0 = Controller0 or 1 = Controller1) ObsDrivingModel::ObsDrivingModel():Model(NumCStateVar_ObsDrMdl, NumDState_ObsDrMdl,NumCObsVar_ObsDrMdl, NumDObs_ObsDrMdl, NumDControls_ObsDrMdl, Discount_ObsDrMdl), deltaT(1),noisemean(0), AttStraightNoiseStdDev(0.0361), AttTurnNoiseStdDev(0.0539), DisStraightNoiseStdDev(0.0548), DisTurnNoiseStdDev(0.0678), AttCarDistNoiseStdDev(0.2555), DisCarDistNoiseStdDev(0.2337), AttTurnConst(0.0117), DisTurnConst(0.0065), AttRelSpd(-0.1767), DisRelSpd(-0.2012), c(0.25) { double rewardcoefficient[NumDControls_ObsDrMdl][6] = {{0, 0, 0, 0, 1, 0}, //0 + 0x +0x^2 + 0xy + 0y + y^2 {0, 0, 0, 0, 1, -0.01}, {0, 0, 0, 0, 1, -0.01}, {0, 0, 0, 0, 1, -0.02} }; double attentiverewardcoefficient[NumDControls_ObsDrMdl][6] = {{15, 0, 0, 0, 1, 0}, //0 + 0x +0x^2 + 0xy + 0y + y^2 {15, 0, 0, 0, 1, -0.02}, {15, 0, 0, 0, 1, -0.02}, {15, 0, 0, 0, 1, -0.04} }; vector<vector<double> > tmpvector(NumDState_ObsDrMdl, vector<double>(6, 0)); for(int i =0; i<NumDControls_ObsDrMdl; i++){ for(int j =0; j<NumDState_ObsDrMdl; j++) { for(int k =0; k<6; k++){ if(j>>2 == 0) tmpvector[j][k] = attentiverewardcoefficient[i][k]; else tmpvector[j][k] = rewardcoefficient[i][k]; } } RewardCoeff.push_back(tmpvector); } }; DState ObsDrivingModel::sampleDState(const DState& q, const DControl& sigma) const{ array<double,8> init = {this->getDStateTransProb(ASC0, q, sigma), this->getDStateTransProb(ASC1, q, sigma), this->getDStateTransProb(ATC0, q, sigma), this->getDStateTransProb(ATC1, q, sigma), this->getDStateTransProb(DSC0, q, sigma), this->getDStateTransProb(DSC1, q, sigma), this->getDStateTransProb(DTC0, q, sigma), this->getDStateTransProb(DTC1, q, sigma) }; discrete_distribution<int> distribution(init.begin(), init.end()); return distribution(generator); }; CState ObsDrivingModel::sampleCState(const DState& q_next, const CState& x_k) const { normal_distribution<double> attStraightNormalRand(this->noisemean, this->AttStraightNoiseStdDev); normal_distribution<double> attTurnNormalRand(this->noisemean, this->AttTurnNoiseStdDev); normal_distribution<double> disStraightNormalRand(this->noisemean, this->DisStraightNoiseStdDev); normal_distribution<double> disTurnNormalRand(this->noisemean, this->DisTurnNoiseStdDev); normal_distribution<double> attCarDistNormalRand(this->noisemean, this->AttCarDistNoiseStdDev); normal_distribution<double> disCarDistNormalRand(this->noisemean, this->DisCarDistNoiseStdDev); double attStraightNoise = attStraightNormalRand(generator); double attTurnNoise = attTurnNormalRand(generator); double disStraightNoise = disStraightNormalRand(generator); double disTurnNoise = disTurnNormalRand(generator); double attCarDistNoise = attCarDistNormalRand(generator); double disCarDistNoise = disCarDistNormalRand(generator); CState x_next; switch(q_next){ case ASC0: x_next.push_back(x_k[0] + attStraightNoise); x_next.push_back(x_k[1] + AttRelSpd + attCarDistNoise); break; case ASC1: x_next.push_back(x_k[0] + attStraightNoise); x_next.push_back(x_k[1] + AttRelSpd + c + attCarDistNoise); break; case ATC0: x_next.push_back(x_k[0] + AttTurnConst + attTurnNoise); x_next.push_back(x_k[1] + AttRelSpd + attCarDistNoise); break; case ATC1: x_next.push_back(x_k[0] + AttTurnConst + attTurnNoise); x_next.push_back(x_k[1] + AttRelSpd + c + attCarDistNoise); break; case DSC0: x_next.push_back(x_k[0] + disStraightNoise); x_next.push_back(x_k[1] + DisRelSpd + disCarDistNoise); break; case DSC1: x_next.push_back(x_k[0] + disStraightNoise); x_next.push_back(x_k[1] + DisRelSpd + c + disCarDistNoise); break; case DTC0: x_next.push_back(x_k[0] + DisTurnConst + disTurnNoise); x_next.push_back(x_k[1] + DisRelSpd + disCarDistNoise); break; case DTC1: x_next.push_back(x_k[0] + DisTurnConst + disTurnNoise); x_next.push_back(x_k[1] + DisRelSpd + c + disCarDistNoise); break; default: printf("q_next out of domain\n"); exit(1); } return x_next; }; DObs ObsDrivingModel::sampleDObs(const DState& q_next) const { double ObsProb[3][2] = { {0.7617, 0.0145}, {0.2225, 0.42}, {0.0158, 0.5655} }; array<double,3> init = {ObsProb[1][q_next>>2], ObsProb[2][q_next>>2], ObsProb[3][q_next>>2]}; discrete_distribution<int> distribution(init.begin(), init.end()); return distribution(generator); // bernoulli_distribution bernlRand(1 - this->obserr); // if(bernlRand(generator)) // return q_next>>1; // else // return ((q_next>>1) == 0)? 1:0; }; double ObsDrivingModel::getCStateTransProb(CState const& x_next, DState const& q_next, CState const& x_k) const { double difference[2]; double p1, p2; switch(q_next){ case ASC0: difference[0] = x_next[0] - x_k[0]; difference[1] = x_next[1] - x_k[1] - AttRelSpd; p1 = 1.0/(AttStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttStraightNoiseStdDev*AttStraightNoiseStdDev)); p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev)); return p1*p2; case ASC1: difference[0] = x_next[0] - x_k[0]; difference[1] = x_next[1] -x_k[1] - AttRelSpd - c; p1 = 1.0/(AttStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttStraightNoiseStdDev*AttStraightNoiseStdDev)); p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev)); return p1*p2; case ATC0: difference[0] = x_next[0] - x_k[0] - AttTurnConst; difference[1] = x_next[1] - x_k[1] - AttRelSpd; p1 = 1.0/(AttTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttTurnNoiseStdDev*AttTurnNoiseStdDev)); p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev)); return p1*p2; case ATC1: difference[0] = x_next[0] - x_k[0] - AttTurnConst; difference[1] = x_next[1] - x_k[1] - AttRelSpd - c; p1 = 1.0/(AttTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttTurnNoiseStdDev*AttTurnNoiseStdDev)); p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev)); return p1*p2; case DSC0: difference[0] = x_next[0] - x_k[0]; difference[1] = x_next[1] - x_k[1] - DisRelSpd; p1 = 1.0/(DisStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisStraightNoiseStdDev*DisStraightNoiseStdDev)); p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev)); return p1*p2; case DSC1: difference[0] = x_next[0] -x_k[0]; difference[1] = x_next[1] -x_k[1]- DisRelSpd -c; p1 = 1.0/(DisStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisStraightNoiseStdDev*DisStraightNoiseStdDev)); p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev)); return p1*p2; case DTC0: difference[0] = x_next[0] - x_k[0] - DisTurnConst; difference[1] = x_next[1] - x_k[1] - DisRelSpd; p1 = 1.0/(DisTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisTurnNoiseStdDev*DisTurnNoiseStdDev)); p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev)); return p1*p2; case DTC1: difference[0] = x_next[0] - x_k[0] - DisTurnConst; difference[1] = x_next[1] - x_k[1] - DisRelSpd - c; p1 = 1.0/(DisTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisTurnNoiseStdDev*DisTurnNoiseStdDev)); p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev)); return p1*p2; default: printf("q_next out of domain\n"); exit(1); } }; double ObsDrivingModel::getDStateTransProb(DState const& q_next, DState const& q_k, DControl const& sigma_k) const { double sigma0[2][2] = { {0.95, 0.05}, {0.05, 0.95} }; double sigma1[2][2] = { {0.95, 0.8}, {0.05, 0.2}}; double P_att_S2T = 0.0377; double P_dis_S2T = 0.2797; double transprob_sigma0[4][4] = { { sigma0[0][0]*(1-P_att_S2T), 0 , sigma0[0][1] , 0 }, { sigma0[0][0]*P_att_S2T , sigma0[0][0], 0 , sigma0[0][1] }, { sigma0[1][0] , 0 , sigma0[1][1]*(1-P_dis_S2T), 0 }, { 0 , sigma0[1][0], sigma0[1][1]*P_dis_S2T , sigma0[1][1] } }; double transprob_sigma1[4][4] = { { sigma1[0][0]*(1-P_att_S2T), 0 , sigma1[0][1] , 0 }, { sigma1[0][0]*P_att_S2T , sigma1[0][0], 0 , sigma1[0][1] }, { sigma1[1][0] , 0 , sigma1[1][1]*(1-P_dis_S2T), 0 }, { 0 , sigma1[1][0], sigma1[1][1]*P_dis_S2T , sigma1[1][1] } }; if((sigma_k>>1) == 0) // (sigma_k == V00) || (sigma_k == V01) { return transprob_sigma0[q_next>>1][q_k>>1]*((q_next & 0x01) == (sigma_k & 0x01)); } else // (sigma_k == V10) || (sigma_k == V11) { return transprob_sigma1[q_next>>1][q_k>>1]*((q_next & 0x01) == (sigma_k & 0x01)); } }; double ObsDrivingModel::getDiscreteObsProb(DObs const& zq_k, DState const& q_k) const { double ObsProb[3][2] = { {0.7617, 0.0145}, {0.2225, 0.42}, {0.0158, 0.5655} }; return ObsProb[zq_k][q_k>>2]; }; CState ObsDrivingModel::getNextCStateNoNoise(const DState& q_next, const CState& x_k) const{ CState x_next; switch(q_next){ case ASC0: x_next.push_back(x_k[0]); x_next.push_back(x_k[1] + AttRelSpd); break; case ASC1: x_next.push_back(x_k[0]); x_next.push_back(x_k[1] + AttRelSpd+c); break; case ATC0: x_next.push_back(x_k[0]+AttTurnConst); x_next.push_back(x_k[1] + AttRelSpd); break; case ATC1: x_next.push_back(x_k[0]+AttTurnConst); x_next.push_back(x_k[1] + AttRelSpd+c); break; case DSC0: x_next.push_back(x_k[0]); x_next.push_back(x_k[1] + DisRelSpd); break; case DSC1: x_next.push_back(x_k[0]); x_next.push_back(x_k[1] + DisRelSpd+c); break; case DTC0: x_next.push_back(x_k[0] + DisTurnConst); x_next.push_back(x_k[1] + DisRelSpd); break; case DTC1: x_next.push_back(x_k[0] + DisTurnConst); x_next.push_back(x_k[1] + DisRelSpd+c); break; default: printf("q_next out of domain\n"); exit(1); } return x_next; }; vector<double> ObsDrivingModel::get1stDerivative(const DState& q, const CState& x) const { vector<double> firstderivative; firstderivative.push_back(1); firstderivative.push_back(0); firstderivative.push_back(0); firstderivative.push_back(1); return firstderivative; }; vector<double> ObsDrivingModel::get2ndDerivative(const DState& q, const CState& x) const{ return vector<double>(1, 0); }; double ObsDrivingModel::getReward(DState const& q, CState const& x, DControl const& sigma) const { return RewardCoeff[sigma][q][0] + RewardCoeff[sigma][q][1]*x[0] + RewardCoeff[sigma][q][2]*x[0]*x[0] + RewardCoeff[sigma][q][3]*x[0]*x[1] + RewardCoeff[sigma][q][4]*x[1] + RewardCoeff[sigma][q][5]*x[1]*x[1]; }; vector<vector<vector<double> > > ObsDrivingModel::getRewardCoeff() const { return RewardCoeff; }; vector<vector<double> > ObsDrivingModel::getCovariance() const { vector<vector<double> > covariance; for(DState q =0; q<NumDState_ObsDrMdl; q++) { vector<double> cov_tmp; if (q>>1 ==0 ){ //AS cov_tmp.push_back(AttStraightNoiseStdDev*AttStraightNoiseStdDev); cov_tmp.push_back(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev); } else if(q>>1 ==1 ){ //AT cov_tmp.push_back(AttTurnNoiseStdDev*AttTurnNoiseStdDev); cov_tmp.push_back(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev); } else if(q>>1 == 2){ //DS cov_tmp.push_back(DisStraightNoiseStdDev*DisStraightNoiseStdDev); cov_tmp.push_back(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev); } else{ //DT cov_tmp.push_back(DisTurnNoiseStdDev*DisTurnNoiseStdDev); cov_tmp.push_back(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev); } covariance.push_back(cov_tmp); } return covariance; } double ObsDrivingModel::getCost(const DState& q, const CState& x, const DControl& sigma) const { double R_sigma1[2] = {0, 5}; double R_sigma2[2] = {0, 5}; return x[0]*x[0] + R_sigma1[sigma>>1] + R_sigma2[sigma&0x01]; }; double ObsDrivingModel::sample(const DState& q_k, const CState& x_k, const DControl& sigma_k, DState& q_next, CState& x_next, DObs& obs_out) const{ q_next = sampleDState(q_k, sigma_k); // cout<<"q_next = "<<q_next<<" "; x_next = sampleCState(q_next, x_k); // cout<<"x_next[0] = "<<x_next[0]<<" "; obs_out = sampleDObs(q_next); // cout<<"obs_out = "<<obs_out<<endl; return this->getDStateTransProb(q_next, q_k, sigma_k)* this->getCStateTransProb(x_next, q_next, x_k) * this->getDiscreteObsProb(q_next, obs_out); };
38.450739
219
0.637819
ppnathan
e60eefd2a4367f50df8e934ceef2a4e4b7effb88
2,114
cpp
C++
src/Jogo/Parametros/ParametrosJogo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Parametros/ParametrosJogo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Parametros/ParametrosJogo.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
// // ParametrosJogo.cpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 11/15/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #include "ParametrosJogo.hpp" namespace Game { namespace Parametros { ParametrosJogo::ParametrosJogo(const string& filename): Parametro(filename), player_name("Sem Nome"), is_dual_player(false) { } ParametrosJogo::~ParametrosJogo() { this->g_arquivos.clear(); } bool ParametrosJogo::loadFromFile(const string &filename){ bool status = true; try { if (this->filename != this->g_arquivos.getFilename()) this->g_arquivos.setFilename(filename); // Check file load if (!this->g_arquivos.load()) throw runtime_error("Error loading file."); // Obtem informação do arquivo //this->setPlayerName(this->g_arquivos.getData()["player_name"]); // Sempre inicia sem nome this->setDualPlayer(this->g_arquivos.getData()["is_dual_player"] == 1); } catch(std::exception e){ status = false; cerr << "ERROR: ParametrosJogo::loadFromFile(): " << e.what() << endl; } return status; } bool ParametrosJogo::saveToFile(const string &filename) { if (this->filename != this->g_arquivos.getFilename()) this->g_arquivos.setFilename(filename); // Cria json com valores da classe json data; data["player_name"] = this->getPlayerName(); data["is_dual_player"] = this->is_dual_player ? 1 : 0; // Passa json para o gerenciador de arquivos g_arquivos.setData(data); // Manda ao gerenciador de arquivos guardar o json g_arquivos.save(); data.clear(); return true; } // Getters & Setters void ParametrosJogo::setDualPlayer(const bool &is_dual_player) { this->is_dual_player = is_dual_player; } const bool& ParametrosJogo::isDualPlayer() const { return this->is_dual_player; } void ParametrosJogo::setPlayerName(const string &player_name) { this->player_name = player_name; } const string& ParametrosJogo::getPlayerName() const { return this->player_name; } }}
26.425
99
0.666982
MatheusKunnen
e610610c4ac6c02db0e766e301c853bd10a164ff
2,694
hpp
C++
libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file byte.hpp * * @brief byte の定義 * * @author myoukaku */ #ifndef BKSGE_FND_CSTDDEF_BYTE_HPP #define BKSGE_FND_CSTDDEF_BYTE_HPP #include <cstddef> #if defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603) namespace bksge { using std::byte; using std::to_integer; } // namespace bksge #else #include <bksge/fnd/type_traits/enable_if.hpp> #include <bksge/fnd/type_traits/is_integral.hpp> #include <bksge/fnd/config.hpp> namespace bksge { enum class byte : unsigned char {}; template <typename IntegerType> inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, IntegerType> to_integer(byte b) BKSGE_NOEXCEPT { return IntegerType(b); } inline BKSGE_CONSTEXPR byte operator|(byte lhs, byte rhs) BKSGE_NOEXCEPT { return byte(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs)); } inline BKSGE_CONSTEXPR byte operator&(byte lhs, byte rhs) BKSGE_NOEXCEPT { return byte(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs)); } inline BKSGE_CONSTEXPR byte operator^(byte lhs, byte rhs) BKSGE_NOEXCEPT { return byte(static_cast<unsigned char>(lhs) ^ static_cast<unsigned char>(rhs)); } inline BKSGE_CONSTEXPR byte operator~(byte b) BKSGE_NOEXCEPT { return byte(~static_cast<unsigned char>(b)); } inline BKSGE_CXX14_CONSTEXPR byte& operator|=(byte& lhs, byte rhs) BKSGE_NOEXCEPT { return lhs = lhs | rhs; } inline BKSGE_CXX14_CONSTEXPR byte& operator&=(byte& lhs, byte rhs) BKSGE_NOEXCEPT { return lhs = lhs & rhs; } inline BKSGE_CXX14_CONSTEXPR byte& operator^=(byte& lhs, byte rhs) BKSGE_NOEXCEPT { return lhs = lhs ^ rhs; } template <typename IntegerType> inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte> operator<<(byte lhs, IntegerType shift) BKSGE_NOEXCEPT { return byte(static_cast<unsigned char>(lhs) << shift); } template <typename IntegerType> inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte> operator>>(byte lhs, IntegerType shift) BKSGE_NOEXCEPT { return byte(static_cast<unsigned char>(lhs) >> shift); } template <typename IntegerType> inline BKSGE_CXX14_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>& operator<<=(byte& lhs, IntegerType shift) BKSGE_NOEXCEPT { return lhs = lhs << shift; } template <typename IntegerType> inline BKSGE_CXX14_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>& operator>>=(byte& lhs, IntegerType shift) BKSGE_NOEXCEPT { return lhs = lhs >> shift; } } // namespace bksge #endif #endif // BKSGE_FND_CSTDDEF_BYTE_HPP
24.490909
95
0.732739
myoukaku
e6112822a4a125b3bf17a44ecc3084b3f678223d
4,381
hpp
C++
include/propane_literals.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
3
2021-02-28T12:52:43.000Z
2021-12-31T00:12:48.000Z
include/propane_literals.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
null
null
null
include/propane_literals.hpp
AggroBird/propane
83134d11f6a90798db8937761ab707d95c520f1b
[ "MIT" ]
null
null
null
#ifndef _HEADER_PROPANE_LITERALS #define _HEADER_PROPANE_LITERALS #include "propane_common.hpp" namespace propane { union literal_t { constexpr literal_t() : as_u64(0) {} constexpr literal_t(int8_t i8) : as_i8(i8) {} constexpr literal_t(uint8_t u8) : as_u8(u8) {} constexpr literal_t(int16_t i16) : as_i16(i16) {} constexpr literal_t(uint16_t u16) : as_u16(u16) {} constexpr literal_t(int32_t i32) : as_i32(i32) {} constexpr literal_t(uint32_t u32) : as_u32(u32) {} constexpr literal_t(int64_t i64) : as_i64(i64) {} constexpr literal_t(uint64_t u64) : as_u64(u64) {} constexpr literal_t(float f32) : as_f32(f32) {} constexpr literal_t(double f64) : as_f64(f64) {} constexpr literal_t(void* vptr) : as_vptr(vptr) {} int8_t as_i8; uint8_t as_u8; int16_t as_i16; uint16_t as_u16; int32_t as_i32; uint32_t as_u32; int64_t as_i64; uint64_t as_u64; float as_f32; double as_f64; void* as_vptr; }; static_assert(sizeof(literal_t) == sizeof(uint64_t), "Literal size invalid"); template<typename value_t> struct parse_result { parse_result() = default; parse_result(type_idx type, value_t value) : type(type), value(value) {} type_idx type = type_idx::invalid; value_t value = value_t(0ull); inline bool is_valid() const noexcept { return type != type_idx::invalid; } inline operator bool() const noexcept { return is_valid(); } }; // Parse unsigned longs, which is the largest number representable in the current // environment. From ulong, it can be range-checked with anything smaller parse_result<uint64_t> parse_ulong(const char*& beg, const char* end, int32_t base); parse_result<uint64_t> parse_ulong(const char*& beg, const char* end); parse_result<uint64_t> parse_ulong(std::string_view str); // Parse the largest integer readable (ulong), and then determine integer type and negate if provided // Return value is an union with all possible data types parse_result<literal_t> parse_int_literal(const char*& beg, const char* end); parse_result<literal_t> parse_int_literal(std::string_view str); // Parse any literal (including floating point) parse_result<literal_t> parse_literal(const char*& beg, const char* end); parse_result<literal_t> parse_literal(std::string_view str); // Parse the largest number readable (ulong), and then apply integer type and negate if provided // Cast the result to the specified type template<typename value_t> concept literal_int = std::is_integral_v<value_t> || std::is_enum_v<value_t>; template<literal_int value_t> parse_result<value_t> parse_int_literal_cast(const char*& beg, const char* end) { parse_result<value_t> result; if (auto literal = parse_int_literal(beg, end)) { switch (literal.type) { // First, cast to the encountered constant, then negate if applicable, then cast to the destination number type case type_idx::i8: { result.value = value_t(literal.value.as_i8); break; } case type_idx::u8: { result.value = value_t(literal.value.as_u8); break; } case type_idx::i16: { result.value = value_t(literal.value.as_i16); break; } case type_idx::u16: { result.value = value_t(literal.value.as_u16); break; } case type_idx::i32: { result.value = value_t(literal.value.as_i32); break; } case type_idx::u32: { result.value = value_t(literal.value.as_u32); break; } case type_idx::i64: { result.value = value_t(literal.value.as_i64); break; } case type_idx::u64: { result.value = value_t(literal.value.as_u64); break; } default: return result; } result.type = derive_type_index_v<value_t>; } return result; } template<literal_int value_t> parse_result<value_t> parse_int_literal_cast(std::string_view str) { const char* beg = str.data(); const char* end = beg + str.size(); return parse_int_literal_cast<value_t>(beg, end); } } #endif
41.72381
127
0.642091
AggroBird
e611bcfcfc4c01f24dfade65f71ddfc63663f6b9
303
cpp
C++
53-maximum-subarray/53-maximum-subarray.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
2
2022-01-02T19:15:00.000Z
2022-01-05T21:12:24.000Z
53-maximum-subarray/53-maximum-subarray.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
null
null
null
53-maximum-subarray/53-maximum-subarray.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
1
2022-03-11T17:11:07.000Z
2022-03-11T17:11:07.000Z
class Solution { public: int maxSubArray(vector<int>& nums) { int currmax=nums[0]; int finmax=nums[0]; for(int i=1;i<nums.size();i++){ currmax=max(nums[i],nums[i]+currmax); finmax=max(currmax,finmax); } return finmax; } };
23.307692
49
0.508251
Ananyaas
e615a38c81405eb59bcf0ca3526a29d44bbe194f
12,002
cpp
C++
src/particle_system/ParticleSystem.cpp
SirKoto/particle_sim
76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660
[ "MIT" ]
2
2022-01-10T18:22:34.000Z
2022-02-23T23:18:36.000Z
src/particle_system/ParticleSystem.cpp
SirKoto/particle_sim
76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660
[ "MIT" ]
null
null
null
src/particle_system/ParticleSystem.cpp
SirKoto/particle_sim
76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660
[ "MIT" ]
null
null
null
#include "ParticleSystem.hpp" #include <array> #include <glad/glad.h> #include <imgui.h> #include <numeric> #include "graphics/my_gl_header.hpp" using namespace particle; ParticleSystem::ParticleSystem() { const std::filesystem::path proj_dir(PROJECT_DIR); const std::filesystem::path shad_dir = proj_dir / "resources/shaders"; m_ico_mesh = TriangleMesh(proj_dir / "resources/ply/icosahedron.ply"); m_ico_mesh.upload_to_gpu(); m_advect_compute_program = ShaderProgram( &Shader(shad_dir / "advect_particles.comp", Shader::Type::Compute), 1 ); m_simple_spawner_program = ShaderProgram( &Shader(shad_dir / "simple_spawner.comp", Shader::Type::Compute), 1 ); glGenVertexArrays(1, &m_ico_draw_vao); // Generate particle buffers glGenBuffers(2, m_vbo_particle_buffers); glGenBuffers(2, m_draw_indirect_buffers); glGenBuffers(2, m_alive_particle_indices); glGenBuffers(1, &m_dead_particle_indices); glGenBuffers(1, &m_dead_particle_count); glGenBuffers(1, &m_sphere_ssb); for (uint32_t i = 0; i < 2; ++i) { // Initialise indirect draw buffer, and bind in 3 glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_draw_indirect_buffers[i]); DrawElementsIndirectCommand command{ (uint32_t)m_ico_mesh.get_faces().size() * 3, // num elements 0, // instance count 0, // first index 0, // basevertex 0 // baseinstance }; glBufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(DrawElementsIndirectCommand), &command, GL_DYNAMIC_DRAW); } // Setup configuration m_system_config.max_particles = 500; m_system_config.gravity = 9.8f; m_system_config.particle_size = 1.0e-1f; m_system_config.simulation_space_size = 10.0f; m_system_config.k_v = 0.9999f; m_system_config.bounce = 0.5f; m_system_config.friction = 0.01f; m_spawner_config.pos = glm::vec3(5.0f); m_spawner_config.mean_lifetime = 2.0f; m_spawner_config.var_lifetime = 1.0f; m_spawner_config.particle_speed = 5.f; // Generate buffer config glGenBuffers(1, &m_system_config_bo); glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_system_config_bo); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(ParticleSystemConfig) + sizeof(ParticleSpawnerConfig), nullptr, GL_STATIC_DRAW); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SYSTEM_CONFIG, m_system_config_bo); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); update_sytem_config(); // Initialize shapes glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_sphere_ssb); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Sphere), nullptr, GL_STATIC_DRAW); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); initialize_system(); update_intersection_sphere(); update_intersection_mesh(); } void ParticleSystem::update(float time, float dt) { // Bind in compute shader as bindings 1 and 2 // 1 is previous frame, and 2 is the next glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_PARTICLES_IN, m_vbo_particle_buffers[m_flipflop_state]); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_PARTICLES_OUT, m_vbo_particle_buffers[1 - (uint32_t)m_flipflop_state]); glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_ALIVE_IN, m_draw_indirect_buffers[m_flipflop_state]); glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_ALIVE_OUT, m_draw_indirect_buffers[1 - (uint32_t)m_flipflop_state]); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_ALIVE_LIST_IN, m_alive_particle_indices[m_flipflop_state]); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_ALIVE_LIST_OUT, m_alive_particle_indices[1 - (uint32_t)m_flipflop_state]); // Clear the atomic counter of alive particles glClearNamedBufferSubData(m_draw_indirect_buffers[1 - m_flipflop_state], GL_R32F, offsetof(DrawElementsIndirectCommand, primCount), sizeof(uint32_t), GL_RED, GL_FLOAT, nullptr); uint32_t num_particles_to_instantiate; { m_accum_particles_emmited += m_emmit_particles_per_second * dt; float floor_part = std::floor(m_accum_particles_emmited); m_accum_particles_emmited -= floor_part; num_particles_to_instantiate = static_cast<uint32_t>(floor_part); } if (num_particles_to_instantiate != 0) { m_simple_spawner_program.use_program(); glUniform1f(0, time); glUniform1f(1, dt); glUniform1ui(2, num_particles_to_instantiate); glDispatchCompute(num_particles_to_instantiate / 32 + (num_particles_to_instantiate % 32 == 0 ? 0 : 1), 1, 1); glMemoryBarrier(GL_ALL_BARRIER_BITS); } // Start compute shader m_advect_compute_program.use_program(); glUniform1f(0, dt); glDispatchCompute(m_system_config.max_particles / 32 + (m_system_config.max_particles % 32 == 0 ? 0 : 1) , 1, 1); // flip state m_flipflop_state = !m_flipflop_state; } void ParticleSystem::gl_render_particles() const { glMemoryBarrier(GL_ALL_BARRIER_BITS); glBindVertexArray(m_ico_draw_vao); glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_draw_indirect_buffers[m_flipflop_state]); glDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)0); glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); glBindVertexArray(0); } void ParticleSystem::imgui_draw() { bool update = false; ImGui::PushID("Particlesystem"); ImGui::Text("Particle System Config"); update |= ImGui::DragFloat("Gravity", &m_system_config.gravity, 0.01f); update |= ImGui::DragFloat("Particle size", &m_system_config.particle_size, 0.01f, 0.0f, 2.0f); update |= ImGui::InputFloat("Simulation space size", &m_system_config.simulation_space_size, 0.1f); update |= ImGui::InputFloat("Verlet damping", &m_system_config.k_v, 0.0001f, 0.0f, "%.5f"); update |= ImGui::InputFloat("Bounciness", &m_system_config.bounce, 0.1f); update |= ImGui::InputFloat("Friction", &m_system_config.friction, 0.01f); ImGui::Separator(); if (ImGui::TreeNode("Spawner Config")) { ImGui::DragFloat("Particles/Second", &m_emmit_particles_per_second, 1.0f, 10.0f); update |= ImGui::DragFloat3("Position", &m_spawner_config.pos.x, 0.01f); update |= ImGui::DragFloat("Initial Velocity", &m_spawner_config.particle_speed, 0.02f, 0.0f, FLT_MAX); update |= ImGui::DragFloat("Mean lifetime", &m_spawner_config.mean_lifetime, 0.2f, 0.0f, FLT_MAX); update |= ImGui::DragFloat("Var lifetime", &m_spawner_config.var_lifetime, 0.2f, 0.0f, FLT_MAX); ImGui::TreePop(); } ImGui::Separator(); ImGui::TextDisabled("Config system limit. Needs to reset simulation"); bool reset = ImGui::InputScalar("Max particles", ImGuiDataType_U32, &m_system_config.max_particles); if (reset || ImGui::Button("Reset simulation")) { update_sytem_config(); initialize_system(); } else if (update) { update_sytem_config(); } ImGui::Separator(); if (ImGui::Checkbox("Sphere collisions", &m_intersect_sphere_enabled)) { update_intersection_sphere(); } ImGui::Separator(); if (ImGui::Checkbox("Mesh collisions", &m_intersect_mesh_enabled)) { update_intersection_mesh(); } ImGui::PopID(); } void ParticleSystem::set_sphere(const glm::vec3& pos, float radius) { m_sphere.pos = pos; m_sphere.radius = radius; glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_sphere_ssb); glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(Sphere), &m_sphere); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } void ParticleSystem::remove_sphere() { m_intersect_sphere_enabled = false; update_intersection_sphere(); } void ParticleSystem::set_mesh(const TriangleMesh& mesh, const glm::mat4& transform) { m_intersect_mesh = TriangleMesh(mesh); m_intersect_mesh.apply_transform(transform); m_intersect_mesh.upload_to_gpu(); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_VERTICES, m_intersect_mesh.get_vbo_vertices()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_INDICES, m_intersect_mesh.get_vbo_indices()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_NORMALS, m_intersect_mesh.get_vbo_normals()); } void ParticleSystem::reset_bindings() const { glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SYSTEM_CONFIG, m_system_config_bo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_VERTICES, m_intersect_mesh.get_vbo_vertices()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_INDICES, m_intersect_mesh.get_vbo_indices()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_NORMALS, m_intersect_mesh.get_vbo_normals()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SHAPE_SPHERE, m_sphere_ssb); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_DEAD_LIST, m_dead_particle_indices); glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_DEAD, m_dead_particle_count); } void ParticleSystem::initialize_system() { // TODO m_accum_particles_emmited = 1.0f; m_flipflop_state = false; std::vector<Particle> particles(m_system_config.max_particles, { glm::vec3(5.0f) }); for (uint32_t i = 0; i < m_system_config.max_particles; ++i) { particles[i].pos.x += (float)i; particles[i].pos.y += (float)(i) * 0.2f; } if (m_max_particles_in_buffers < m_system_config.max_particles) { for (uint32_t i = 0; i < 2; ++i) { // Reserve particle data glBindBuffer(GL_ARRAY_BUFFER, m_vbo_particle_buffers[i]); glBufferData(GL_ARRAY_BUFFER, sizeof(Particle) * m_system_config.max_particles, nullptr, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Reserve particle indices glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_alive_particle_indices[i]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(uint32_t) * m_system_config.max_particles, nullptr, GL_DYNAMIC_DRAW); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_dead_particle_indices); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(uint32_t) * m_system_config.max_particles, nullptr, GL_DYNAMIC_DRAW); m_max_particles_in_buffers = m_system_config.max_particles; } // Initialize dead particles (all) { std::vector<uint32_t> dead_indices(m_system_config.max_particles); std::iota(dead_indices.rbegin(), dead_indices.rend(), 0); glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_dead_particle_indices); glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, // offset sizeof(uint32_t) * m_system_config.max_particles, // size dead_indices.data()); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, m_dead_particle_count); glNamedBufferData(m_dead_particle_count, sizeof(uint32_t), &m_system_config.max_particles, GL_STATIC_DRAW); glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0); // Initialise indirect draw buffer, and bind in 3, to use the atomic counter to track the particles that are alive for (uint32_t i = 0; i < 2; ++i) { glClearNamedBufferSubData(m_draw_indirect_buffers[i], GL_R32F, offsetof(DrawElementsIndirectCommand, primCount), sizeof(uint32_t), GL_RED, GL_FLOAT, nullptr); } glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); // Create VAO to draw. Only 1 to use the buffer to get the instances glBindVertexArray(m_ico_draw_vao); m_ico_mesh.gl_bind_to_vao(); glBindVertexArray(0); reset_bindings(); } void ParticleSystem::update_sytem_config() { glNamedBufferSubData( m_system_config_bo, // buffer name 0, // offset sizeof(ParticleSystemConfig), // size &m_system_config // data ); glNamedBufferSubData( m_system_config_bo, // buffer name sizeof(ParticleSystemConfig), // offset sizeof(ParticleSpawnerConfig), // size &m_spawner_config // data ); } void ParticleSystem::update_intersection_sphere() { m_advect_compute_program.use_program(); if (m_intersect_sphere_enabled) { glUniform1ui(1, 1); } else { glUniform1ui(1, 0); } glUseProgram(0); } void ParticleSystem::update_intersection_mesh() { m_advect_compute_program.use_program(); if (m_intersect_mesh_enabled) { glUniform1ui(2, 1); } else { glUniform1ui(2, 0); } glUseProgram(0); }
32.61413
128
0.754624
SirKoto
e62412a371c674a02c9eca53c78e7d56f0f30e64
2,406
hh
C++
menon/bits/toctrans.hh
menonfled/menon_cpp_lib
729bb581023e7558360fd17ac0866e20b2d7ec40
[ "BSL-1.0" ]
1
2020-09-10T16:47:09.000Z
2020-09-10T16:47:09.000Z
menon/bits/toctrans.hh
menonfled/menon_cpp_lib
729bb581023e7558360fd17ac0866e20b2d7ec40
[ "BSL-1.0" ]
null
null
null
menon/bits/toctrans.hh
menonfled/menon_cpp_lib
729bb581023e7558360fd17ac0866e20b2d7ec40
[ "BSL-1.0" ]
null
null
null
/// @file menon/bits/toctrans.hh /// 文字種変換関数の定義 /// @author @menonfled #ifndef MENON_BITS_TOCTRANS_HH_ #define MENON_BITS_TOCTRANS_HH_ #pragma once #include "menon/bits/sv.hh" #include "menon/bits/isctype.hh" #include <string> #include <algorithm> #include <iterator> namespace menon { /// 変換種別 using ctrans_t = char (*)(char); /// 小文字への変換 /// @param[in] c 変換対象の文字 /// @return cが大文字の場合は対応する小文字を、それ以外はcを返す。 template <typename Char> constexpr Char tolower(Char c) { if (isupper(c)) return static_cast<Char>(c | 0x20); return c; } /// 大文字への変換 /// @param[in] c 変換対象の文字 /// @return cが小文字の場合は対応する大文字を、それ以外はcを返す。 template <typename Char> constexpr Char toupper(Char c) { if (islower(c)) return static_cast<Char>(c & ~0x20); return c; } /// 指定した種別による変換 /// @param[in] c 変換対象の文字 /// @param[in] trans 変換種別 /// @return transで指定した文字種にcを変換した結果を返す。 template <typename Char> constexpr Char toctrans(Char c, ctrans_t trans) { if (trans == tolower<char>) c = tolower(c); else if (trans == toupper<char>) c = toupper(c); return c; } /// 文字列から変換種別への変換 /// @param[in] name 変換種別に対応する文字列 /// @return nameに対応する変換種別を返す。 constexpr ctrans_t ctrans(std::string_view name) { if (name == "tolower") return tolower; if (name == "toupper") return toupper; return {}; } /// 文字列を小文字に変換する。 /// @param[in] s 変換対象の文字列 /// @return sに含まれる'A'~'Z'を'a'~'z'に変換した文字列を返す。 template <typename String> auto strtolower(String const& s) { using ::menon::sv; auto t = sv(s); using sv_type = decltype(t); using char_type = typename sv_type::value_type; std::basic_string<char_type> r; r.reserve(t.size()); std::transform(t.cbegin(), t.cend(), std::back_inserter(r), &menon::tolower<char_type>); return r; } /// 文字列を大文字に変換する。 /// @param[in] s 変換対象の文字列 /// @return sに含まれる'a'~'z'を'A'~'Z'に変換した文字列を返す。 template <typename String> auto strtoupper(String const& s) { using ::menon::sv; auto t = sv(s); using sv_type = decltype(t); using char_type = typename sv_type::value_type; std::basic_string<char_type> r; r.reserve(t.size()); std::transform(t.cbegin(), t.cend(), std::back_inserter(r), &menon::toupper<char_type>); return r; } } #endif // !MENON_BITS_TOCTRANS_HH_
23.821782
92
0.620116
menonfled
e63072a5d3a0e0744932ff7bb0938786ca0d2037
301
hpp
C++
include/timsort.hpp
Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF
a97d75a2352d50dd99108d9ccbfd0a3cf04c1635
[ "MIT" ]
null
null
null
include/timsort.hpp
Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF
a97d75a2352d50dd99108d9ccbfd0a3cf04c1635
[ "MIT" ]
null
null
null
include/timsort.hpp
Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF
a97d75a2352d50dd99108d9ccbfd0a3cf04c1635
[ "MIT" ]
null
null
null
#pragma once namespace itis { struct TimSort { static const int RUN = 32; static void insertionSort(int arr[], int left, int right); static void merge(int arr[], int l, int m, int r); static void timSort(int arr[], int n); static void printArray(int arr[], int n); }; }
16.722222
62
0.627907
Algorithms-and-Data-Structures-2021
e6320df0947ee3ac02fffc5347ee4dc9e9f86578
354
hpp
C++
include/xigua/symbol.hpp
LiquidHelium/Xigua
bd7d1153d483f9c07607ffd7c6b292c264793f2f
[ "MIT" ]
2
2015-06-26T04:32:19.000Z
2016-02-02T11:36:41.000Z
include/xigua/symbol.hpp
LiquidHelium/Xigua
bd7d1153d483f9c07607ffd7c6b292c264793f2f
[ "MIT" ]
null
null
null
include/xigua/symbol.hpp
LiquidHelium/Xigua
bd7d1153d483f9c07607ffd7c6b292c264793f2f
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "xigua/data.hpp" #include "xigua/string.hpp" namespace xig { class symbol : public base_string { public: symbol(std::string value) : base_string(value) {} virtual ~symbol() {} virtual data_type type() const; virtual const symbol &as_symbol() const; }; extern data_ptr make_symbol(std::string str); }
16.857143
51
0.711864
LiquidHelium
e63417cdc7cc8c0163219865231516a018739167
3,520
hpp
C++
include/ast/nodes/node_base.hpp
momikey/rhea
6aadc65eefbb40d9dddf585c33b3225da3929abd
[ "MIT" ]
1
2020-08-31T08:39:05.000Z
2020-08-31T08:39:05.000Z
include/ast/nodes/node_base.hpp
momikey/rhea
6aadc65eefbb40d9dddf585c33b3225da3929abd
[ "MIT" ]
null
null
null
include/ast/nodes/node_base.hpp
momikey/rhea
6aadc65eefbb40d9dddf585c33b3225da3929abd
[ "MIT" ]
null
null
null
#ifndef RHEA_AST_NODE_BASE_HPP #define RHEA_AST_NODE_BASE_HPP #include <string> #include <vector> #include <memory> #include <utility> #include <tao/pegtl.hpp> #include "../parse_tree_node.hpp" #include "../../types/types.hpp" #include "../../util/compat.hpp" #include "../../visitor/visitor_fwd.hpp" /* * The base node for the annotated AST. This is different from * the AST skeleton generated by the parser, but it follows the * structure of that tree, and each node in the annotated AST * will contain an observing pointer to the corresponding node * in the generated AST. * * Note that this node and its children are *classes* rather than * structs. This, IMO, better communicates their status as a * polymorphic hierarchy, since the generated AST will store pointers * to this base class and access the children through its interface. * * Although I haven't decided on code style guidelines for Rhea, * I feel that the annotated AST classes should be capitalized. Again, * this is for clarity's sake: they're not the same as, e.g., grammar * rules. */ namespace rhea { namespace ast { // The base type for all AST nodes class ASTNode { public: ASTNode(): position({}, "") {} virtual ~ASTNode() {} virtual std::string to_string() = 0; virtual util::any visit(visitor::Visitor* v); tao::pegtl::position position; }; // "Top-level" node types class Expression : public ASTNode { public: // All expressions have a type. This may be fixed or calculated, // so we make it a method. virtual types::TypeInfo expression_type() { return types::UnknownType{}; } util::any visit(visitor::Visitor* v) override; }; class Statement : public ASTNode { public: util::any visit(visitor::Visitor* v) override; // TODO: Some statements can declare symbols. If we make a quick // pass through some levels of the AST, we can pick these out, // which saves us from having to forward declare as in C/C++. // (We can implement this as a second visitor pass, done before // the "main" one.) }; // A lot of nodes need to store lists of children. These will // always be unique_ptrs to AST nodes, but we may want to restrict // that to a specific subtype, so we use a template alias here. template <typename T> using child_vector = std::vector<std::unique_ptr<T>>; // std::unique_ptrs to the main node types. We use these a lot, // so it helps to have aliases. using node_ptr = std::unique_ptr<ASTNode>; using expression_ptr = std::unique_ptr<Expression>; using statement_ptr = std::unique_ptr<Statement>; // Maker functions, in the vein of make_unique. template <typename Expr, typename... Args> inline expression_ptr make_expression(Args&&... args) { return std::make_unique<Expr>(std::forward<Args>(args)...); } template <typename Stmt, typename... Args> inline statement_ptr make_statement(Args&&... args) { return std::make_unique<Stmt>(std::forward<Args>(args)...); } // Functions can be of different types. This enum allows us // to choose which type. enum class FunctionType { Basic, // i.e., not special Predicate, // implied boolean return type Operator, // operators are always called implicitly Unchecked // can't take conditions }; }} #endif /* RHEA_AST_NODE_BASE_HPP */
34.509804
82
0.663068
momikey
e63f3938979647ce2b55bf1bbc754db53ab5bbe7
1,760
cpp
C++
The_Eye/src/PID.cpp
michprev/drone
51c659cdd4e1d50446a563bb11e800defda9a298
[ "MIT" ]
2
2017-06-03T01:07:16.000Z
2017-07-14T17:49:16.000Z
The_Eye/src/PID.cpp
michprev/drone
51c659cdd4e1d50446a563bb11e800defda9a298
[ "MIT" ]
5
2017-04-24T20:29:04.000Z
2017-06-26T17:40:53.000Z
The_Eye/src/PID.cpp
michprev/drone
51c659cdd4e1d50446a563bb11e800defda9a298
[ "MIT" ]
null
null
null
/* * PID.cpp * * Created on: 14. 7. 2017 * Author: michp */ #include <PID.h> namespace flyhero { // assume that PID will be computed at 1 kHz PID::PID(float i_max, float Kp, float Ki, float Kd) : d_term_lpf(Biquad_Filter::FILTER_LOW_PASS, 1000, 20) { this->last_t = 0; this->integrator = 0; this->Kp = Kp; this->Ki = Ki; this->Kd = Kd; this->i_max = i_max; this->last_d = NAN; this->last_error = NAN; } float PID::Get_PID(float error) { // ticks in us float dt = (Timer::Get_Tick_Count() - this->last_t) * 0.000001; float output = 0; if (this->last_t == 0 || dt > 1000) { this->integrator = 0; dt = 0; } this->last_t = Timer::Get_Tick_Count(); // proportional component output += error * this->Kp; // integral component if (this->Ki != 0 && dt > 0) { this->integrator += error * this->Ki * dt; if (this->integrator < -this->i_max) this->integrator = -this->i_max; if (this->integrator > this->i_max) this->integrator = this->i_max; output += this->integrator; } // derivative component if (this->Kd != 0 && dt > 0) { float derivative; if (std::isnan(this->last_d)) { derivative = 0; this->last_d = 0; } else derivative = (error - this->last_error) / dt; // apply 20 Hz biquad LPF derivative = this->d_term_lpf.Apply_Filter(derivative); this->last_error = error; this->last_d = derivative; output += derivative * this->Kd; } return output; } void PID::Set_Kp(float Kp) { this->Kp = Kp; } void PID::Set_Ki(float Ki) { this->Ki = Ki; } void PID::Set_Kd(float Kd) { this->Kd = Kd; } void PID::Set_I_Max(float i_max) { this->i_max = i_max; } } /* namespace flyhero */
18.924731
65
0.586932
michprev
e645edf799785e82b1db9cdb60ec5f2b15a9d2f2
3,796
cpp
C++
sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp
Savraska2/GTS
78c8b4d634f1379eb3e33642716717f53bf7e1ad
[ "BSD-3-Clause" ]
61
2016-03-26T03:04:43.000Z
2021-09-17T02:11:18.000Z
sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
92
2016-04-10T23:40:22.000Z
2022-03-11T21:49:12.000Z
sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
18
2016-03-26T11:19:14.000Z
2021-08-07T00:26:02.000Z
#include "pri.h" #include "tw_win_l2_dss.h" /* get onevalue(container) */ int tw_win_l2_dss::_cap_get_ctnr_onevalue( TW_UINT16 ui16_cap, TW_ONEVALUE *p_tw_onevalue ) { TW_CAPABILITY tw_capability; TW_ONEVALUE *p_tw_ov; /* TWAIN機器からデータを取ってくる */ if (OK != this->_cap_get_ctnr( ui16_cap, &tw_capability ) ) { pri_funct_err_bttvr( "Error : this->_cap_get_ctnr() returns NG." ); return NG; } /* データのコンテナタイプが違う */ if (TWON_ONEVALUE != tw_capability.ConType) { pri_funct_err_bttvr( "Error : tw_capability.ConType is not TWON_ONEVALUE." ); /* Windows 特有のおまじない1/3 */ GlobalFree( (HANDLE)tw_capability.hContainer ); return NG; } /* Windows 特有のおまじない2/3 */ p_tw_ov = (pTW_ONEVALUE)GlobalLock( (HANDLE)tw_capability.hContainer ); /* データをコピーする */ (*p_tw_onevalue) = (*p_tw_ov); /* Windows 特有のおまじない3/3 */ GlobalUnlock( (HANDLE)tw_capability.hContainer ); GlobalFree( (HANDLE)tw_capability.hContainer ); return OK; } /*--------------------------------------------------------*/ /* get_current onevalue(container) */ int tw_win_l2_dss::_cap_getcrnt_ctnr_onevalue( TW_UINT16 ui16_cap, TW_ONEVALUE *p_tw_onevalue ) { TW_CAPABILITY tw_capability; TW_ONEVALUE *p_tw_ov; /* TWAIN機器からデータを取ってくる */ if (OK != this->_cap_getcrnt_ctnr(ui16_cap,&tw_capability)) { pri_funct_err_bttvr( "Error : this->_cap_getcrnt_ctnr() returns NG." ); return NG; } /* データのコンテナタイプが違う */ if (TWON_ONEVALUE != tw_capability.ConType) { pri_funct_err_bttvr( "Error : tw_capability.ConType is not TWON_ONEVALUE." ); /* Windows 特有のおまじない1/3 */ GlobalFree( (HANDLE)tw_capability.hContainer ); return NG; } /* Windows 特有のおまじない2/3 */ p_tw_ov = (pTW_ONEVALUE)GlobalLock( (HANDLE)tw_capability.hContainer ); /* データをコピーする */ (*p_tw_onevalue) = (*p_tw_ov); /* Windows 特有のおまじない3/3 */ GlobalUnlock( (HANDLE)tw_capability.hContainer ); GlobalFree( (HANDLE)tw_capability.hContainer ); return OK; } /*--------------------------------------------------------*/ int tw_win_l2_dss::_cap_get_ctnr_onevalue_bool( TW_UINT32 *ui32p_val, TW_UINT16 ui16_cap, char *cp_cap_name ) { TW_ONEVALUE tw_onevalue; if (OK != this->_cap_get_ctnr_onevalue( ui16_cap, &tw_onevalue )) { pri_funct_err_bttvr( "Error : this->_cap_get_ctnr_onevalue(%s<%u>,) returns NG.", cp_cap_name, ui16_cap ); return NG; } if (TWTY_BOOL != tw_onevalue.ItemType) { pri_funct_err_bttvr( "Error : %s tw_onevalue.ItemType is not TWTY_BOOL.", cp_cap_name ); return NG; } *ui32p_val = tw_onevalue.Item; return OK; } int tw_win_l2_dss::_cap_get_ctnr_onevalue_fix32( double *dp_val, TW_UINT16 ui16_cap, char *cp_cap_name ) { TW_ONEVALUE tw_onevalue; if (OK != this->_cap_get_ctnr_onevalue( ui16_cap, &tw_onevalue )) { pri_funct_err_bttvr( "Error : this->_cap_get_ctnr_onevalue(%s<%u>,) returns NG.", cp_cap_name, ui16_cap ); return NG; } if (TWTY_FIX32 != tw_onevalue.ItemType) { pri_funct_err_bttvr( "Error : %s tw_onevalue.ItemType is not TWTY_FIX32.", cp_cap_name ); return NG; } this->_fix32_to_double( (TW_FIX32 *)&(tw_onevalue.Item), dp_val ); return OK; } /*--------------------------------------------------------*/ int tw_win_l2_dss::_cap_getcrnt_ctnr_onevalue_ui16( TW_UINT16 *ui16p_val, TW_UINT16 ui16_cap, char *cp_cap_name ) { TW_ONEVALUE tw_onevalue; if (OK != this->_cap_getcrnt_ctnr_onevalue( ui16_cap, &tw_onevalue )) { pri_funct_err_bttvr( "Error : this->_cap_getcrnt_ctnr_onevalue(%s<%u>,) returns NG.", cp_cap_name, ui16_cap ); return NG; } if (TWTY_UINT16 != tw_onevalue.ItemType) { pri_funct_err_bttvr( "Error : %s tw_onevalue.ItemType is not TWTY_UINT16.", cp_cap_name ); return NG; } /* ui32-->ui16だがオーバーフローの問題が起こる可能性は低い */ *ui16p_val = (unsigned short)(tw_onevalue.Item); return OK; }
23.288344
113
0.683878
Savraska2
e647699d6383da70228636b92a12954a852576e0
5,309
cpp
C++
src/bsa.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
1
2021-06-16T15:49:07.000Z
2021-06-16T15:49:07.000Z
src/bsa.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
src/bsa.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
#include "bsa.hpp" #include "for_each.hpp" #include <fstream> #include <numeric> namespace libbsarch { /* Properties */ fs::path bsa::get_filename() const { wchar_t name[max_string_buffer_size]; bsa_filename_get(archive_.get(), max_string_buffer_size, name); return name; } bsa_archive_type_t bsa::get_type() const { return bsa_archive_type_get(archive_.get()); } uint32_t bsa::get_version() const { return bsa_version_get(archive_.get()); } fs::path bsa::get_format_name() const { wchar_t format_name[max_string_buffer_size]; bsa_format_name_get(archive_.get(), max_string_buffer_size, format_name); return format_name; } uint32_t bsa::get_file_count() const { return bsa_file_count_get(archive_.get()); } uint32_t bsa::get_archive_flags() const { return bsa_archive_flags_get(archive_.get()); } void bsa::set_archive_flags(uint32_t flags) { bsa_archive_flags_set(archive_.get(), flags); } uint32_t bsa::get_file_flags() const { return bsa_file_flags_get(archive_.get()); } void bsa::set_file_flags(uint32_t flags) { bsa_file_flags_set(archive_.get(), flags); } void bsa::set_compressed(bool value) { bsa_compress_set(archive_.get(), value); } void bsa::set_share_data(bool value) { bsa_share_data_set(archive_.get(), value); } bool bsa::get_compressed() const { return bsa_compress_get(archive_.get()); } bool bsa::get_share_data() const { return bsa_share_data_get(archive_.get()); } void bsa::load(const fs::path &archive_path) { const auto &result = bsa_load_from_file(archive_.get(), archive_path.wstring().c_str()); checkResult(result); } void bsa::close() { bsa_close(archive_.get()); } extracted_data bsa::extract_to_memory(file_record record) const { const auto &result = bsa_extract_file_data_by_record(archive_.get(), record.value); checkResult(result); return extracted_data(result.buffer, archive_.get()); } extracted_data bsa::extract_to_memory(const fs::path &relative_path) const { const auto &result = bsa_extract_file_data_by_filename(archive_.get(), relative_path.wstring().c_str()); checkResult(result); return extracted_data(result.buffer, archive_.get()); } void bsa::extract_to_disk(const fs::path &relative_path, const fs::path &absolute_path, bool overwrite_existing) const { auto record = find_file_record(relative_path); extract_to_disk(record, absolute_path, overwrite_existing); } void bsa::extract_to_disk(file_record record, const std::filesystem::path &absolute_path, bool overwrite_existing) const { { static std::mutex mut; std::lock_guard g(mut); const bool exist = fs::exists(absolute_path); if (exist && !overwrite_existing) return; if (exist) fs::remove(absolute_path); } auto data = extract_to_memory(record); std::fstream file(absolute_path, std::ios::out | std::ios::binary); file.write(static_cast<const char *>(data.get_buffer()), data.get_size()); } void bsa::extract_all_to_disk(const fs::path &directory, bool overwrite_current_files) const { std::vector<uint32_t> indexes(get_file_count()); std::iota(indexes.begin(), indexes.end(), 0); for_each(indexes.cbegin(), indexes.cend(), [this, overwrite_current_files, directory](auto &&idx) { auto record = get_file_record(idx); auto relative_path = get_relative_path(idx); fs::path absolute_path = directory / relative_path; fs::path absolute_directory = fs::path(absolute_path).remove_filename(); { static std::mutex mut; std::lock_guard g(mut); fs::create_directories(absolute_directory); } try { extract_to_disk(record, absolute_path, overwrite_current_files); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } }); } void bsa::iterate_files(bsa_file_iteration_proc_t file_iteration_proc, void *context) const { bsa_iterate_files(archive_.get(), file_iteration_proc, context); } file_record bsa::get_file_record(uint32_t index) const { return {bsa_get_file_record(archive_.get(), index)}; } file_record bsa::find_file_record(const fs::path &filename) const { return {bsa_find_file_record(archive_.get(), filename.wstring().c_str())}; } std::filesystem::path bsa::get_relative_path(uint32_t index) const { bsa_entry_list list; const auto &result = bsa_get_resource_list(archive_.get(), list.get_unchecked().get(), L""); checkResult(result); return list.get(index); } std::vector<fs::path> bsa::list_files() const { bsa_entry_list list; const auto &result = bsa_get_resource_list(archive_.get(), list.get_unchecked().get(), L""); checkResult(result); return list.list(); } const detail::bsa_wrapper &bsa::get_unchecked() const { return archive_; } detail::bsa_wrapper &bsa::get_unchecked() { return archive_; } } // namespace libbsarch
25.524038
109
0.661141
Guekka
e64bece9fc801f3f8e96ca46aa7fcf92b6f95146
2,101
cpp
C++
src/gpio_reader.cpp
botamochi6277/ros2_pigpio
9f0a78ffd9092f628fae66897f96bdf0bfae8aca
[ "MIT" ]
2
2021-06-10T21:17:17.000Z
2022-02-22T04:39:16.000Z
src/gpio_reader.cpp
botamochi6277/ros2_pigpio
9f0a78ffd9092f628fae66897f96bdf0bfae8aca
[ "MIT" ]
null
null
null
src/gpio_reader.cpp
botamochi6277/ros2_pigpio
9f0a78ffd9092f628fae66897f96bdf0bfae8aca
[ "MIT" ]
1
2021-02-19T13:35:55.000Z
2021-02-19T13:35:55.000Z
/** * @file gpio_reader.cpp * * @brief ROS2 Talker to read inputted digital signals. * **/ #include <chrono> #include <memory> #include <thread> #include <sstream> #include <iomanip> #include <pigpiod_if2.h> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/bool.hpp" using namespace std::chrono_literals; class DigitalReader : public rclcpp::Node { private: int pi_; int pin_; bool is_pull_up_; rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr publisher_; size_t count_; void timer_callback() { auto message = std_msgs::msg::Bool(); message.data = gpio_read(pi_, pin_); RCLCPP_INFO(this->get_logger(), "Publishing: '%d'", message.data); publisher_->publish(message); } public: DigitalReader() : Node("gpio_publisher"), count_(0) { this->declare_parameter<int>("pin", 23); this->declare_parameter<bool>("is_pull_up", true); this->get_parameter("pin", pin_); this->get_parameter("is_pull_up", is_pull_up_); if (is_pull_up_) { RCLCPP_INFO(this->get_logger(), "Read GPIO-%02d (PULL_UP)", pin_); } else { RCLCPP_INFO(this->get_logger(), "Read GPIO-%02d (PULL_DOWN)", pin_); } pi_ = pigpio_start(NULL, NULL); /* Connect to Pi. */ if (pi_ < 0) { RCLCPP_ERROR(this->get_logger(), "cannot connect pigpiod"); rclcpp::shutdown(); exit(1); } else { set_mode(pi_, pin_, PI_INPUT); if (is_pull_up_) { set_pull_up_down(pi_, pin_, PI_PUD_UP); } else { set_pull_up_down(pi_, pin_, PI_PUD_OFF); } std::stringstream ss; ss << "gpio_input_" << std::setw(2) << pin_; publisher_ = this->create_publisher<std_msgs::msg::Bool>(ss.str(), 10); timer_ = this->create_wall_timer( 500ms, std::bind(&DigitalReader::timer_callback, this)); } } ~DigitalReader() { pigpio_stop(pi_); } }; int main(int argc, char **argv) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<DigitalReader>()); rclcpp::shutdown(); return 0; }
23.087912
77
0.62732
botamochi6277
e65354b81f42d1761eba0f59ee2aa38135a6c8a0
8,797
hpp
C++
csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
2
2019-12-17T13:16:48.000Z
2019-12-17T13:16:51.000Z
csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
null
null
null
csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * *Copyright: [email protected] * *Author: f * *File name: csf_connect_buffer.hpp * *Version: 1.0 * *Date: 20-10月-2018 21:30:24 * *Description: Class(csf_connect_buffer) 为方便实现各种网络操作而定义的该结构,主要为网络连接发送接收而使用buffer信息。 该数据结构主要是对unsigned char*、csf_buffer、csf_csfstring、csf_chain等原来类型,针对网络发送需求的特殊封闭。 * *Others: * *History: * *******************************************************************************/ #if !defined(CSF_CONNECT_BUFFER_H_INCLUDED_) #define CSF_CONNECT_BUFFER_H_INCLUDED_ #include "csf_typedef.h" namespace csf { namespace core { namespace module { namespace connect { /** * 为方便实现各种网络操作而定义的该结构,主要为网络连接发送接收而使用buffer信息。 * 该数据结构主要是对unsigned char*、csf_buffer、csf_csfstring、csf_chain等原来类型,针对网络发送需求的特殊封闭。 * @author f * @version 1.0 * @created 20-10月-2018 21:30:24 */ template<typename ValueType = csf_buffer> class csf_connect_buffer { public: inline explicit csf_connect_buffer() : m_container(csf_nullptr) , m_length(0) , m_is_sync(csf_false) , m_is_free(csf_false) , m_is_filled(csf_false) { } /** * 主要功能是:根据对应长度创建csf_connect_buffer * 返回:无 * * @param len 表示需要发送的缓存长度 */ inline explicit csf_connect_buffer(const csf_uint32 len) : csf_connect_buffer(new ValueType(len), len) { m_is_free = csf_true; } /** * 主要功能是:根据buufer对象和对应长度创建csf_connect_buffer * 返回:无 * * @param buffer 表示csf_connect_buffer的宿主对象地址 * @param len 表示需要发送的缓存长度 */ inline explicit csf_connect_buffer(ValueType* buffer, const csf_uint32 len) : m_container(buffer) , m_length(len) , m_is_sync(csf_false) , m_is_free(csf_false) , m_is_filled(csf_false) { } virtual ~csf_connect_buffer() { destroy(); } /** * 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等 * * @param new_value */ inline void set_container(ValueType* new_value) { if (csf_nullptr != new_value) { set_container(new_value, new_value->length()); } } /** * 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等 * * @param new_value 表示csf_connect_buffer的宿主对象地址 * @param len 表示需要发送的缓存长度 */ inline void set_container(ValueType* new_value, const csf_uint32 len) { m_container = new_value; set_is_free(csf_false); set_length(len); } /** * 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等 */ inline ValueType* get_container() { return m_container; } /** * 表示当前的缓存数据内容 */ inline csf_uchar* get_buffer() { if (csf_nullptr != get_container()) { return get_container()->get_buffer(); } return csf_nullptr; } /** * 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式 * * @param new_value 表示是否采用同步的方式发送,false表示异步;true表示同步; */ inline void set_is_sync(const csf_bool new_value) { m_is_sync = new_value; } /** * 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式 */ inline csf_bool get_is_sync() { return m_is_sync; } /** * 表示发送或接收的内容长度 * * @param new_value 表示需要发送的数据长度 */ inline void set_length(const csf_uint32 new_value) { m_length = new_value; } /** * 表示发送或接收的内容长度 */ inline csf_uint32 get_length() { return m_length; } /** * 主要功能是:根据数据长度创建一个宿主对象 * 返回:无 * * @param len 表示需要发送的缓存长度 */ inline csf_int32 create(const csf_uint32 len) { if (get_buffer()) { return csf_failure; } set_container(new ValueType(len)); set_is_free(csf_true); set_length(len); return csf_succeed; } /** * 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。 */ inline csf_bool get_is_free() { return m_is_free; } /** * 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。 * * @param new_value * 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。 * */ inline void set_is_free(const csf_bool new_value) { m_is_free = new_value; } /** * 主要功能是:清空所有缓存空间数据; * 返回:无 */ inline csf_void clear() { set_length(0); set_is_sync(csf_false); set_is_free(csf_false); set_is_filled(csf_false); if (csf_nullptr != get_container()) { return get_container()->clear(); } } /** * 主要功能是:根据对象是否为空,长度是否为空,判断当前的csf_connect_buffer是否合法; * 返回:对象不为空,长度不为0则返回true;其他情况返回false */ inline csf_bool is_valid() { if (csf_nullptr == get_container() || csf_nullptr == get_buffer() || size() <= 0) { return csf_false; } return csf_true; } /** * 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制, * 可以提高部分网络应用的性能。 */ inline csf_bool get_is_filled() { return m_is_filled; } /** * 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制, * 可以提高部分网络应用的性能。 * * @param new_value */ inline void set_is_filled(csf_bool new_value) { m_is_filled = new_value; } /** * 表示获取buffer总缓存长度 */ inline csf_uint32 size() { if (csf_nullptr != get_container()) { return get_container()->size(); } return 0; } /** * 表示获取buffer未使用的空间长度 */ inline csf_uint32 avail() { if (csf_nullptr != get_container()) { return get_container()->avail(); } return 0; } /** * 表示当前实际已经使用的缓存的长度 */ inline csf_uint32 length() { if (csf_nullptr != get_container()) { return get_container()->length(); } return 0; } /** * 将内存数据添加到buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码; * * @param buf 表示数据内存的起始地址 * @param len 表示内存数据的长度 */ inline csf_int32 cat(const csf_uchar* buf, const csf_uint32 len) { if (csf_nullptr != get_container()) { return get_container()->cat(buf, len); } return 0; } /** * 表示buffer是否为空,为空返回true,否则返回false。长度为0或null都为空,返回true。 */ inline csf_bool empty() { if (csf_nullptr != get_container()) { return get_container()->empty(); } return csf_true; } /** * 表示将csf_string插入到csf_buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码; * * @param str 表示标准字符内容 */ inline csf_int32 cat(const csf_string& str) { if (csf_nullptr != get_container()) { return get_container()->cat(str); } return 0; } /** * 表示将一个char*字符串插入到buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码; * * @param buf 表示插入char*内容 */ inline csf_int32 cat(const csf_char* buf) { if (csf_nullptr != get_container()) { return get_container()->cat(buf); } return 0; } /** * 表示将csf_buffer插入到csf_buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码; * * @param buffer 表示需要添加的buffer内容 */ inline csf_int32 cat(csf_buffer& buffer) { if (csf_nullptr != get_container()) { return get_container()->cat(buffer); } return 0; } // protected: /** * 表示释放buffer中的start指定的内存,并将buffer清空为null */ inline csf_void destroy() { if (get_is_free() && get_container()) { delete get_container(); set_is_free(csf_false); set_container(csf_nullptr); } } private: /** * 表示实际用于接收和发送的缓存长度 * * @param new_value */ inline void set_size(csf_uint32 new_value) { m_size = new_value; } /** * 表示实际用于接收和发送的缓存长度 */ inline csf_uint32 get_size() { return m_size; } private: /** * 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式 */ csf_bool m_is_sync = csf_false; /** * 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等 */ ValueType* m_container; /** * 表示发送或接收的内容长度 */ csf_uint32 m_length = 0; /** * 表示实际用于接收和发送的缓存长度 */ csf_uint32 m_size = 0; /** * 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。 */ csf_bool m_is_free = csf_false; /** * 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制, * 可以提高部分网络应用的性能。 */ csf_bool m_is_filled = csf_false; }; } } } } #endif // !defined(CSF_CONNECT_BUFFER_H_INCLUDED_)
22.384224
87
0.585995
Kitty-Kitty
e6561561ff1441ce3424dcc2ce02511e2e8d0c9c
757
cc
C++
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
8
2016-06-12T08:06:46.000Z
2018-04-11T20:34:50.000Z
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
null
null
null
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
9
2016-08-01T05:58:28.000Z
2020-05-06T11:09:53.000Z
#include "ps.h" typedef float Val; DEFINE_int32(nt, 1, "num of server threads"); int CreateServerNode(int argc, char *argv[]) { ps::OnlineServer<Val> server(ps::IOnlineHandle<Val>(), 1, FLAGS_nt); return 0; } int WorkerNodeMain(int argc, char *argv[]) { using namespace ps; int n = 1000000; auto key = std::make_shared<std::vector<Key>>(n); for (int i = 0; i < n; ++i) (*key)[i] = kMaxKey / n * i; auto val = std::make_shared<std::vector<Val>>(n, 1.0); KVWorker<Val> wk; std::vector<Val> recv_val; for (int i = 0; i < 10; ++i) { SyncOpts opts; opts.AddFilter(Filter::KEY_CACHING); opts.AddFilter(Filter::COMPRESSING); wk.Wait(wk.ZPush(key, val, opts)); wk.Wait(wk.ZPull(key, &recv_val, opts)); } return 0; }
25.233333
70
0.630119
CNevd
e65e16c48f7fd9ad68a9176a47e4333fa2b20780
8,098
cpp
C++
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <cmath> #include "CharnesCooper.hpp" #include "Dinkelbach.hpp" #include "YGGY.hpp" #include "FMILP.hpp" namespace grbfrc { FMILP::FMILP(GRBEnv& env, GRBLinExpr objNumerator, GRBLinExpr objDenominator, int objSense) : baseModel { new GRBModel(env) } { objective.numerator = objNumerator; objective.denominator = objDenominator; baseModel->setObjective(objDenominator); objective.sense = objSense; objective.uniSign = UniSignStatus::maybe; solution = nullptr; } FMILP::FMILP(GRBEnv& grbEnv) : FMILP(grbEnv, 0.0, 0.0, GRB_MAXIMIZE) { objective.uniSign = UniSignStatus::yes; } FMILP::FMILP(GRBEnv& grbEnv, GRBLinExpr objNumerator, GRBLinExpr objDenominator) : FMILP(grbEnv, objNumerator, objDenominator, GRB_MAXIMIZE) { } FMILP::FMILP(GRBEnv& grbEnv, int objSense) : FMILP(grbEnv, 0.0, 0.0, objSense) { objective.uniSign = UniSignStatus::yes; } GRBModel FMILP::baseModelCopy() { return *baseModel; } FMILP FMILP::copy() { return *this; } int FMILP::get(GRB_IntAttr attr) { return baseModel->get(attr); } double FMILP::get(GRB_DoubleAttr attr) { return baseModel->get(attr); } std::string FMILP::get(GRB_StringAttr attr) { return baseModel->get(attr); } void FMILP::set(GRB_IntAttr attr, int val) { baseModel->set(attr, val); } void FMILP::set(GRB_DoubleAttr attr, double val) { baseModel->set(attr, val); } void FMILP::set(GRB_StringAttr attr, std::string val) { baseModel->set(attr, val); } void FMILP::set(GRB_IntParam param, int val) { baseModel->set(param, val); } void FMILP::set(GRB_DoubleParam param, double val) { baseModel->set(param, val); } void FMILP::set(GRB_StringParam param, std::string val) { baseModel->set(param, val); } void FMILP::setEnv(GRB_IntParam para, int val) { (baseModel->getEnv()).set(para, val); } GRBVar& FMILP::addVar(double lowerBound, double upperBound, char type, std::string name) { vars.push_back(new GRBVar(baseModel->addVar(lowerBound, upperBound, 0.0, type, name))); return *(vars.back()); } GRBVar& FMILP::addVar(double lowerBound, double upperBound, double numeratorCoeff, double denominatorCoeff, char type, std::string name) { vars.push_back(new GRBVar(baseModel->addVar(lowerBound, upperBound, denominatorCoeff, type, name))); objective.numerator += numeratorCoeff * (*(vars.back())); objective.denominator += denominatorCoeff * (*(vars.back())); return *(vars.back()); } void FMILP::setStartSolution(GRBVar& var, double val) { if (!startSol) startSol = new std::vector<double>(vars.size()); else startSol->resize(vars.size()); int index { 0 }; for (GRBVar* varp : vars) { if (varp->sameAs(var)) (*startSol)[index] = val; index++; } } GRBVar* FMILP::getVars() { return baseModel->getVars(); } void FMILP::update() { baseModel->update(); } void FMILP::setObjNumerator(GRBLinExpr& objNumerator) { objective.numerator = objNumerator; } void FMILP::setObjDenominator(GRBLinExpr& objDenominator) { objective.denominator = objDenominator; } int FMILP::getObjSense() { return objective.sense; } void FMILP::setObjSense(int objSense) { objective.sense = objSense; baseModel->set(GRB_IntAttr_ModelSense, objSense); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, const GRBLinExpr rhsExpr, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsExpr, name); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, GRBVar rhsVar, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsVar, name); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, double rhsVal, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsVal, name); } void FMILP::addConstr(GRBVar lhsVar, char sense, GRBVar rhsVar, std::string name) { baseModel->addConstr(lhsVar, sense, rhsVar, name); } void FMILP::addConstr(GRBVar lhsVar, char sense, double rhsVal, std::string name) { baseModel->addConstr(lhsVar, sense, rhsVal, name); } void FMILP::addConstr(GRBTempConstr tc, std::string name) { baseModel->addConstr(tc, name); } void FMILP::addConstr(const GRBLinExpr expr, double lower, double upper) { baseModel->addConstr(expr, GRB_GREATER_EQUAL, lower); baseModel->addConstr(expr, GRB_LESS_EQUAL, upper); } GRBConstr* FMILP::getConstrs() { return baseModel->getConstrs(); } GRBLinExpr FMILP::getRow(GRBConstr& constr) { return baseModel->getRow(constr); } bool FMILP::isFLP() { if (baseModel->get(GRB_IntAttr_NumIntVars) == 0) return true; else return false; } bool FMILP::checkUnisignance(std::string sign) { /** * * test */ if (sign == "positive") baseModel->setObjective(objective.denominator, GRB_MINIMIZE); else if (sign == "negative") baseModel->setObjective(objective.denominator, GRB_MAXIMIZE); baseModel->optimize(); if (sign == "positive" && baseModel->get(GRB_IntAttr_Status) == GRB_OPTIMAL) { if (baseModel->get(GRB_DoubleAttr_ObjVal) > 0) { objective.uniSign = UniSignStatus::yes; return true; } else return false ; } else return false; if (sign == "negative" && baseModel->get(GRB_IntAttr_Status) == GRB_OPTIMAL) { if (baseModel->get(GRB_DoubleAttr_ObjVal) < 0) { objective.uniSign = UniSignStatus::yes; return true; } else return false; } else return false; } bool FMILP::isUnisignant() { /** test * \callgraph * * */ if (checkUnisignance("positive")) { objective.uniSign = UniSignStatus::yes; return true; } else if (checkUnisignance("negative")) { objective.uniSign = UniSignStatus::yes; return true; } else { objective.uniSign = UniSignStatus::no; return false; } } double FMILP::getObjVal() { return solution->objVal; } double FMILP::getVal(GRBVar& var) { int index { 0 }; for (GRBVar* varp : vars) { if (varp->sameAs(var)) return (solution->varVals)[index]; index++; } return 0.0; // bad } /* void FMILP::runCharnesCooper(int time_limit) { baseModel->update(); CharnesCooper chaco(*this); chaco.run(time_limit); chaco.writeSolution(); } void FMILP::runCharnesCooper(GRBCallback& callback, int time_limit) { baseModel->update(); CharnesCooper chaco(*this); chaco.run(callback, time_limit); chaco.writeSolution(); } */ /* GRBModel FMILP::getCharnesCooperTransform() { CharnesCooper chaco(*this); return chaco.getTransform(); } GRBModel FMILP::getYGGYTransform() { GRBModel model(baseModel->getEnv()); return model; } */ void FMILP::printSolution() { if (solution) { std::cout << "\n########################### Solution ############################\n\n"; for (int i = 0; i < baseModel->get(GRB_IntAttr_NumVars); i++) { double varval { solution->varVals[i] }; if (varval == 0.0) varval = std::abs(varval); std::cout << vars[i]->get(GRB_StringAttr_VarName) << ": " << varval << std::endl; } std::cout << std::endl; std::cout << "ObjVal: " << solution->objVal << std::endl; std::cout << "\n#################################################################\n\n"; } else std::cout << "There is no solution to print!" << std::endl; } } // namespace grbfrc
25.071207
102
0.602371
KohlbacherLab
e666d0e98ccec9274120bbefe284ad1d6224d4a3
2,194
cpp
C++
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
8
2018-07-29T17:17:22.000Z
2021-11-23T02:45:54.000Z
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
68
2018-04-20T16:38:10.000Z
2019-01-04T19:32:38.000Z
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
4
2018-08-19T00:03:42.000Z
2021-07-13T16:56:05.000Z
#include "LuaPluginHandler.hpp" #include "LuaPluginAPI.hpp" #include <iostream> lua_State* LuaPluginHandler::L = nullptr; LuaPluginHandler::LuaPluginHandler() { Init(); } LuaPluginHandler::~LuaPluginHandler() { Cleanup(); } void LuaPluginHandler::Init() { L = luaL_newstate(); assert(L != nullptr); luaL_openlibs(L); LuaServer::Init(L); } void LuaPluginHandler::Cleanup() { for (int i = 0; i < kEventTypeEnd; ++i) { m_signalMap[i].disconnect_all_slots(); assert(m_signalMap[i].empty()); } for (auto& obj : m_plugins) delete obj; lua_close(L); L = nullptr; } void LuaPluginHandler::Reset() { Cleanup(); m_plugins.clear(); m_pluginQueue.clear(); Init(); } void LuaPluginHandler::AddPlugin(LuaPlugin* plugin) { m_plugins.push_back(plugin); } void LuaPluginHandler::LoadPlugin(std::string filename) { LuaPlugin* plugin = new LuaPlugin; try { plugin->LoadScript(L, filename); plugin->Init(); } catch(std::runtime_error const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in LoadPlugin(): %s", e.what()); delete plugin; return; } AddPlugin(plugin); auto table = make_luatable(); table["name"] = plugin->GetName(); TriggerEvent(EventType::kOnPluginLoaded, nullptr, table); } void LuaPluginHandler::QueuePlugin(std::string filename) { m_pluginQueue.push_back(filename); } void LuaPluginHandler::FlushPluginQueue() { for (auto& filename : m_pluginQueue) LoadPlugin(filename); m_pluginQueue.clear(); } void LuaPluginHandler::RegisterEvent(int type, luabridge::LuaRef func) { if (func.isFunction()) { try { m_signalMap[type].connect(boost::bind((std::function<void(Client*, luabridge::LuaRef)>)func, _1, _2)); } catch (luabridge::LuaException const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in RegisterEvent(): %s", e.what()); } } } void LuaPluginHandler::TriggerEvent(int type, Client* client, luabridge::LuaRef table) { try { m_signalMap[type](client, table); } catch (luabridge::LuaException const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in TriggerEvent(): %s", e.what()); } } void LuaPluginHandler::TickPlugins() { for (auto& obj : m_plugins) obj->Tick(); }
18.59322
105
0.704193
GiantCrocodile
e673f66218dba5f03459dc4447ab2cafb83ff7c1
4,405
cpp
C++
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
#include <stdarg.h> #include <stdlib.h> #include <Arduino.h> #include <limits.h> #include "gpio_pins.h" #include "utils.h" /* reset the esp8266 also make sure to pull D3 and D0 high and D8 pull down see https://github.com/esp8266/Arduino/issues/1017 */ void utils_restart(void) { delay(500); ESP.restart(); delay(500); } /* on_off is 1 or 0 not HIGH or LOW */ void utils_set_led(int led_pin, int on_off) { int on_value = -1; // agh, fucking LEDs have different polarities UTILS_ASSERT(LED_DOOR==LED_BUILTIN_ESP); switch(led_pin) { case LED_BUILTIN_PCB: case LED_DOOR: on_value = LOW; break; case LED_WIFI: on_value = HIGH; break; default: UTILS_ASSERT(0); } if (on_off==1) { digitalWrite(led_pin, on_value); } else { digitalWrite(led_pin, on_value ^ 0x1); } } /* given baseline time (event_time_ms), get elapsed time. reset event_time_ms if the elapsed time wraps */ long utils_get_elapsed_msec_and_reset(long* pevent_time_ms) { long elapsed_ms; elapsed_ms = millis() - *pevent_time_ms; if (elapsed_ms < 0) { elapsed_ms = LONG_MAX; *pevent_time_ms = millis(); // reset } return elapsed_ms; } // from http://playground.arduino.cc/Code/PrintFloats // printFloat prints out the float 'value' rounded to 'places' places after the decimal point void utils_print_float(float value, int places) { // this is used to cast digits int digit; float tens = 0.1; int tenscount = 0; int i; float tempfloat = value; // make sure we round properly. this could use pow from <math.h>, but doesn't seem worth the import // if this rounding step isn't here, the value 54.321 prints as 54.3209 // calculate rounding term d: 0.5/pow(10,places) float d = 0.5; if (value < 0) d *= -1.0; // divide by ten for each decimal place for (i = 0; i < places; i++) d/= 10.0; // this small addition, combined with truncation will round our values properly tempfloat += d; // first get value tens to be the large power of ten less than value // tenscount isn't necessary but it would be useful if you wanted to know after this how many chars the number will take if (value < 0) tempfloat *= -1.0; while ((tens * 10.0) <= tempfloat) { tens *= 10.0; tenscount += 1; } // write out the negative if needed if (value < 0) Serial.print('-'); if (tenscount == 0) Serial.print(0, DEC); for (i=0; i< tenscount; i++) { digit = (int) (tempfloat/tens); Serial.print(digit, DEC); tempfloat = tempfloat - ((float)digit * tens); tens /= 10.0; } // if no places after decimal, stop now and return if (places <= 0) return; // otherwise, write the point and continue on Serial.print('.'); // now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value for (i = 0; i < places; i++) { tempfloat *= 10.0; digit = (int) tempfloat; Serial.print(digit,DEC); // once written, subtract off that digit tempfloat = tempfloat - (float) digit; } //Serial.flush(); // don't flush because it screws up interrupt!! } // // enabling serial output slows down everything, can screw up mic readings #define ENABLE_OUTPUT 1 // printf-like fcn for debug void utils_log(const char *fmt, ... ) { #if ENABLE_OUTPUT char tmp[128]; // resulting string limited to 128 chars va_list args; va_start (args, fmt ); vsnprintf(tmp, 128, fmt, args); va_end (args); Serial.print(tmp); //Serial.flush(); // don't flush because it screws up interrupt!! #endif } void utils_assert(const char* pfilename, int line_number, int arg) { int blink = 1; if (arg) { return; } { char tmp[128]; // resulting string limited to 128 chars char fmt[] = "assertion at %s:%d\n"; sprintf(tmp, fmt, pfilename, line_number); Serial.print(tmp); Serial.flush(); } while(1) { digitalWrite(LED_BUILTIN_ESP, blink); digitalWrite(LED_BUILTIN_PCB, blink); digitalWrite(LED_WIFI, blink); blink ^= 0x1; delay(250); } }
23.940217
124
0.609762
robyu
e68128e1ee6ef3659e28c5e3098c6c928d81fe97
2,484
cxx
C++
gastpc/psreco/NeutrinoEnergy.cxx
LBNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
3
2016-04-13T12:14:53.000Z
2017-03-28T22:46:03.000Z
gastpc/psreco/NeutrinoEnergy.cxx
DUNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
null
null
null
gastpc/psreco/NeutrinoEnergy.cxx
DUNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
1
2015-03-03T10:32:47.000Z
2015-03-03T10:32:47.000Z
// ------------------------------------------------------------------- /// \file NeutrinoEnergy.cxx /// \brief /// /// \author <[email protected]> /// \date Creation: 21 Feb 2017 // ------------------------------------------------------------------- #include "NeutrinoEnergy.h" #include "MCGenInfo.h" #include "MCParticle.h" #include "RecoParticle.h" #include "Units.h" #include "Utils.h" #include <Ntuple/NtpMCEventRecord.h> #include <Interaction/Interaction.h> #include <Interaction/Kinematics.h> #include <cmath> NeutrinoEnergy::NeutrinoEnergy(std::vector<std::pair<gastpc::MCParticle*, gastpc::RecoParticle*>> v): true_energy_(0.), reco_energy_(0.), true_y_(0.), reco_y_(0.) { for (auto particle: v) { if (!particle.first || !particle.second) continue; int reco_pdg = std::abs(particle.second->GetPDGCode()); double momentum = Utils::Magnitude(particle.second->GetInitialMomentum()); if (reco_pdg == 11) { double mass_e = 0.5109989461 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_e*mass_e); reco_y_ = std::sqrt(momentum*momentum + mass_e*mass_e); } else if (reco_pdg == 13) { double mass_mu = 105.6583745 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_mu*mass_mu); reco_y_ = std::sqrt(momentum*momentum + mass_mu*mass_mu); } else if (reco_pdg == 211) { double mass_pi = 139.57018 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_pi*mass_pi); } else if (reco_pdg == 2212) { reco_energy_ += momentum; } else if (reco_pdg == 111) { reco_energy_ += momentum; } } // Use first element of vector (any would do) to extract the true // neutrino energy and inelasticity from genie record gastpc::MCGenInfo* mcgi = v[0].first->GetMCGenInfo(); genie::NtpMCEventRecord* gmcrec = mcgi->GetGeneratorRecord(); genie::Interaction* interaction = (gmcrec->event)->Summary(); true_energy_ = (interaction->InitState().ProbeE(genie::kRfLab)) * gastpc::GeV; // Calculate inelasticity reco_y_ = 1. - reco_y_ / reco_energy_; true_y_ = (interaction->KinePtr()->y(true)); } NeutrinoEnergy::~NeutrinoEnergy() { } double NeutrinoEnergy::RecoEnergy() const { return reco_energy_; } double NeutrinoEnergy::TrueEnergy() const { return true_energy_; } double NeutrinoEnergy::RecoY() const { return reco_y_; } double NeutrinoEnergy::TrueY() const { return true_y_; }
25.608247
101
0.638486
LBNE
e687ad1ca9524ae5ad13e11e2a854149310d8744
726
cpp
C++
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
#include "sampo_pch.hpp" #include "platform/windows/network/windows_socket_api.hpp" #include <WinSock2.h> namespace Sampo { void WindowsSocketAPI::Init() { WSADATA startupResultData; int error = WSAStartup(MAKEWORD(2, 2), &startupResultData); if (error != 0) { SAMPO_CORE_CRITICAL("WSAStartup error: ({0})", WSAGetLastError()); } s_Running = true; } void WindowsSocketAPI::Shutdown() { if (s_Running) { s_Running = false; int error = WSACleanup(); if (error != 0) { SAMPO_CORE_ERROR("WSACleanup error: ({0})", WSAGetLastError()); } } } }
22
79
0.535813
jesseroffel
e689ae5c2e118018376af25033897d7b771220b3
1,261
cpp
C++
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/memory/allocator.hpp> #include <boost/simd/memory/is_aligned.hpp> #include <vector> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/relation.hpp> #include <nt2/sdk/unit/tests/basic.hpp> NT2_TEST_CASE_TPL(vector, BOOST_SIMD_TYPES) { using boost::simd::is_aligned; std::vector<T, boost::simd::allocator<T> > p(5); NT2_TEST( is_aligned( &p[0] ) ); for(int i=0;i<5;++i) p[i] = T(10)*i; for(int i=0;i<5;++i) NT2_TEST_EQUAL(p[i],T(10)*i); } NT2_TEST_CASE_TPL(vector_n, BOOST_SIMD_TYPES) { using boost::simd::is_aligned; std::vector<T, boost::simd::allocator<T, 4> > p(5); NT2_TEST( is_aligned( &p[0],4 ) ); for(int i=0;i<5;++i) p[i] = T(10)*i; for(int i=0;i<5;++i) NT2_TEST_EQUAL(p[i],T(10)*i); }
35.027778
80
0.559873
psiha
e68d8d80fd2ef5c4213afd8d966f4d905ea98169
1,962
cpp
C++
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <string> #include <bitset> #include <algorithm> constexpr int BIT_COUNT = 12; enum RatingType { OXYGEN_RATING, CO2_RATING }; int calculateNumberOfOnesAtColumn(std::vector<std::string>& bitsets, int columnIndex) { int result = 0; for (auto& bset : bitsets) { if (bset[columnIndex] == '1') { result++; } } return result; } int calculateRating(std::vector<std::string> bitsets, RatingType type) { int index = 0; while(true) { int onesInColumn = calculateNumberOfOnesAtColumn(bitsets, index); int zeroesInColumn = bitsets.size() - onesInColumn; char mostCommonBit = (onesInColumn >= zeroesInColumn) ? '1' : '0'; auto oxygenCriteria = [=](auto bset) -> bool { return bset[index] != mostCommonBit; }; bitsets.erase( std::remove_if( bitsets.begin(), bitsets.end(), [=](auto bset) -> bool { if (type == RatingType::OXYGEN_RATING) { return bset[index] != mostCommonBit; } else { return bset[index] == mostCommonBit; } }), bitsets.end()); index++; if (index == BIT_COUNT || bitsets.size() == 1) { break; } } auto onlyNumberLeft = bitsets[0]; long rating = 0; for (int i = 0; i < BIT_COUNT; i++) { int bitValue = (onlyNumberLeft[i] == '1') ? 1 : 0; rating |= bitValue << (BIT_COUNT - 1 - i); } return rating; } int main() { std::ifstream inputStream("./input"); std::string bits; long oxygenGeneratorRating = 0; long co2ScrubberRating = 0; std::vector<std::string> bitsets; while(inputStream >> bits) { bitsets.emplace_back(bits); } oxygenGeneratorRating = calculateRating(bitsets, RatingType::OXYGEN_RATING); co2ScrubberRating = calculateRating(bitsets, RatingType::CO2_RATING); std::cout << "Result: " << oxygenGeneratorRating * co2ScrubberRating << "\n"; }
24.222222
90
0.616718
ympek
e68dfc1d775b77a2be6b347fa2224175c93b64f7
853
cpp
C++
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 2e18; const long long mod = 1e18; const long long hashmod = 100003; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int a,b,c; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--) { cin >> a >> b >> c; if(a > b) swap(a,b); if(b > c) swap(b,c); if(a > b) swap(a,b); if((a+b+c) % 9 == 0) { if((a+b+c)/9 > a) cout << "NO\n"; else cout << "YES\n"; } else cout << "NO\n"; } }
21.871795
46
0.621336
python-programmer1512
e694da08754a7e9fe2f91053a5d44cdfc8f09b42
4,303
cpp
C++
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
1
2020-07-02T13:13:36.000Z
2020-07-02T13:13:36.000Z
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
null
null
null
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <ostream> #include <cstdlib> #include <string> #include <vector> #include <algorithm> #include <boost/program_options.hpp> #include "files_comparator.h" #include "scanner.h" namespace po = boost::program_options; using str_vector=std::vector<std::string>; size_t const DEFAULT_BLOCK_SZ = 1024UL; // Default block size std::ostream& operator<<(std::ostream& out, std::vector<std::string> const vect) { for(auto e: vect) { out << " " << e; } return out; } void output_report(std::ostream& out, OTUS::FilesComparator::Report_t const& report, bool isVerbose=false) { if(isVerbose) { out << "=========================================" << std::endl; out << "== Report: total of " << report.size() << " groups of identical files" << std::endl; out << "=========================================" << std::endl; } for(auto& files_group: report) { for (auto& f: files_group) { out << f << std::endl; } out << std::endl; } } std::vector<OTUS::Scanner::fspath> convert_paths(std::vector<std::string> arg) { std::vector<OTUS::Scanner::fspath> res; std::transform(arg.begin(), arg.end(), std::back_inserter(res), [](auto s){return boost::filesystem::path(s);}); // @TODO: Check if paths are valid! return res; } int main(int argc, const char** argv) { po::options_description desc("Finding the identical files"); desc.add_options() ("help,h", "this help") ("path,I", po::value<std::vector<std::string>>(), "search paths") ("exclude,x", po::value<std::vector<std::string>>(), "exclude directories from search, optional") ("depth,d", po::value<size_t>()->default_value(OTUS::DEF_MAX_DEPTH), "depth of recursive search") ("verbose,v", po::bool_switch(), "verbose output") ("block_sz,b", po::value<size_t>()->default_value(DEFAULT_BLOCK_SZ), "block size") ("mask,m", po::value<std::vector<std::string>>(), "masks (regexp), optional") ("hash,H", po::value<std::string>()->default_value("crc32"), "hash method, options are: crc32 (default), md5") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } bool isVerbose = vm["verbose"].as<bool>(); if(isVerbose) std::cout << "Verbose: " << isVerbose << std::endl; size_t max_depth = vm["depth"].as<size_t>(); if(isVerbose) std::cout << "Max depth: " << vm["depth"].as<size_t>() << std::endl; size_t block_sz = vm["block_sz"].as<size_t>(); if(isVerbose) std::cout << "Block sz: " << block_sz << std::endl; str_vector paths{"./"}; if(vm.count("path")) paths = vm["path"].as<std::vector<std::string>>(); if(isVerbose) std::cout << "Paths: " << paths << std::endl; if (vm.count("exclude") && isVerbose) std::cout << "Exclude: " << vm["exclude"].as<std::vector<std::string>>() << std::endl; if (vm.count("mask") && isVerbose) std::cout << "Masks: " << vm["mask"].as<std::vector<std::string>>() << std::endl; if(isVerbose) std::cout << "Hash: " << vm["hash"].as<std::string>() << std::endl; try { OTUS::HashKind hash_kind = OTUS::hash_name_from_string(vm["hash"].as<std::string>()); OTUS::Scanner scanner(convert_paths(paths)); scanner.set_verbose(vm["verbose"].as<bool>()); if(vm.count("exclude")) scanner.exclude_paths(convert_paths(vm["exclude"].as<std::vector<std::string>>())); if(vm.count("mask")) scanner.masks(vm["mask"].as<std::vector<std::string>>()); scanner.set_depth(max_depth); auto comparator = OTUS::FilesComparator::create_subscribed(scanner, block_sz, hash_kind, isVerbose); scanner.run(); OTUS::FilesComparator::Report_t report = comparator->report(); output_report(std::cout, report, isVerbose); } catch(const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; std::cout << desc << "\n"; return EXIT_SUCCESS; } return EXIT_SUCCESS; }
33.356589
118
0.571462
vaefremov
e69cba15c43aff44e72649283e229b1050cb163b
1,052
cpp
C++
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include <random> // // Unnamed namespace for things only used in this file // namespace { /** @brief a global pseudo-random number generator so that I don't have repeats of number sequences * * Gets set in the first call to "nextRandomNumber". */ std::function<float()> globalRandomGenerator; } // end of the unnamed namespace float test::nextRandomNumber() { if( ! ::globalRandomGenerator ) { std::default_random_engine engine; typename std::uniform_real_distribution<float> random(0,100); ::globalRandomGenerator=std::bind( random, engine ); } return ::globalRandomGenerator(); } bool test::Point3D::operator==( const Point3D& other ) { return x==other.x && y==other.y && z==other.z; } template<> void test::setRandom( test::Point3D& point ) { point.x=nextRandomNumber(); point.y=nextRandomNumber(); point.z=nextRandomNumber(); } std::ostream& test::operator<<( std::ostream& output, const test::Point3D& point ) { output << "[" << point.x << "," << point.y << "," << point.z << "]"; return output; }
23.377778
100
0.686312
mark-grimes
e6a2197b7e42dadfdb3816dbdad9d88dd303f1c2
2,047
cpp
C++
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
1
2021-07-16T18:17:24.000Z
2021-07-16T18:17:24.000Z
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
null
null
null
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
null
null
null
//================================================================================================== /** RABERU - Fancy Parameters Library Copyright : RABERU Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #define TTS_MAIN #include <tts/tts.hpp> #include <kumi.hpp> TTS_CASE("Check map(f, tuple) behavior") { TTS_WHEN("Given a tuple t") { auto t = kumi::tuple{1,2.,3.4f,'5'}; TTS_AND_THEN(" - we call map(f,t)") { auto s = map( [](auto m) { return sizeof(m); }, t ); auto[m0,m1,m2,m3] = s; TTS_EQUAL(m0, sizeof(int) ); TTS_EQUAL(m1, sizeof(double)); TTS_EQUAL(m2, sizeof(float) ); TTS_EQUAL(m3, sizeof(char) ); } TTS_AND_THEN(" - we call map(f,t,u)") { auto u = kumi::tuple{2,3,4,5}; auto s = map( [](auto m, auto n) { return n * sizeof(m); }, t, u ); auto[m0,m1,m2,m3] = s; TTS_EQUAL(m0, 2*sizeof(int) ); TTS_EQUAL(m1, 3*sizeof(double)); TTS_EQUAL(m2, 4*sizeof(float) ); TTS_EQUAL(m3, 5*sizeof(char) ); } } } TTS_CASE("Check map(f, tuple) constexpr behavior") { TTS_WHEN("Given a tuple t") { constexpr auto t = kumi::tuple{1,2.,3.4f,'5'}; TTS_AND_THEN(" - we call t.map(f)") { constexpr auto s = map( [](auto m) { return sizeof(m); }, t ); TTS_CONSTEXPR_EQUAL(get<0>(s), sizeof(int) ); TTS_CONSTEXPR_EQUAL(get<1>(s), sizeof(double)); TTS_CONSTEXPR_EQUAL(get<2>(s), sizeof(float) ); TTS_CONSTEXPR_EQUAL(get<3>(s), sizeof(char) ); } TTS_AND_THEN(" - we call t.map(f,u)") { constexpr auto u = kumi::tuple{2,3,4,5}; constexpr auto s = map( [](auto m, auto n) { return n * sizeof(m); }, t, u ); TTS_CONSTEXPR_EQUAL(get<0>(s), 2*sizeof(int) ); TTS_CONSTEXPR_EQUAL(get<1>(s), 3*sizeof(double)); TTS_CONSTEXPR_EQUAL(get<2>(s), 4*sizeof(float) ); TTS_CONSTEXPR_EQUAL(get<3>(s), 5*sizeof(char) ); } } }
28.830986
100
0.514411
kitegi
e6a4453a4a7f687ba271e8577e9b8498ab986ffb
7,380
cpp
C++
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
15
2015-11-10T10:39:53.000Z
2022-03-29T07:07:53.000Z
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2015-10-23T12:18:45.000Z
2019-07-02T09:55:46.000Z
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2017-04-13T12:28:38.000Z
2019-07-03T21:58:51.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2015, P.A.N.D.O.R.A. Team. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the P.A.N.D.O.R.A. Team 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: Alexandros Philotheou, Manos Tsardoulias * Angelos Triantafyllidis <[email protected]> *********************************************************************/ #include "utils/parameters.h" /** @brief The namespaces for this package **/ namespace flir_lepton { namespace flir_lepton_image_processing { //////////////////// Blob detection - specific parameters //////////////////// int Parameters::Blob::min_threshold = 0; int Parameters::Blob::max_threshold = 200; int Parameters::Blob::threshold_step = 100; int Parameters::Blob::min_area = 550; int Parameters::Blob::max_area = 300000; double Parameters::Blob::min_convexity = 0; double Parameters::Blob::max_convexity = 100; double Parameters::Blob::min_inertia_ratio = 0; double Parameters::Blob::max_circularity = 1.0; double Parameters::Blob::min_circularity = 0.3; bool Parameters::Blob::filter_by_color = 0; bool Parameters::Blob::filter_by_circularity = 1; ///////////////////////// Debug-specific parameters ////////////////////////// // Show the thermal image that arrives in the thermal node bool Parameters::Debug::show_thermal_image = false; // In the terminal's window, show the probabilities of candidate holes bool Parameters::Debug::show_probabilities = false; bool Parameters::Debug::show_find_rois = false; int Parameters::Debug::show_find_rois_size = 1000; bool Parameters::Debug::show_denoise_edges = false; int Parameters::Debug::show_denoise_edges_size = 900; bool Parameters::Debug::show_connect_pairs = false; int Parameters::Debug::show_connect_pairs_size = 1200; bool Parameters::Debug::show_get_shapes_clear_border = false; int Parameters::Debug::show_get_shapes_clear_border_size = 1200; ////////////////// Parameters specific to the Thermal node //////////////////// // The thermal detection method // If set to 0 process the binary image acquired from temperatures MultiArray // If set to 1 process the sensor/Image from thermal sensor int Parameters::Thermal::detection_method = 0; // The probability extraction method // 0 for Gaussian function // 1 for Logistic function int Parameters::Thermal::probability_method = 1; float Parameters::Thermal::min_thermal_probability = 0.3; // Gausian variables float Parameters::Thermal::optimal_temperature = 35; float Parameters::Thermal::tolerance = 10; // Logistic variables float Parameters::Thermal::low_acceptable_temperature = 32; float Parameters::Thermal::high_acceptable_temperature = 38; float Parameters::Thermal::left_tolerance = 4; float Parameters::Thermal::right_tolerance = 8; ///////////// Parameters of acceptable temperature for threshold ///////////// float Parameters::Thermal::low_temperature = 28; float Parameters::Thermal::high_temperature = 40; ////////////////////// Parameters of the thermal image /////////////////////// int Parameters::ThermalImage::WIDTH = 80; int Parameters::ThermalImage::HEIGHT = 60; ///////////////////// Edge detection specific parameters ///////////////////// // canny parameters int Parameters::Edge::canny_ratio = 3; int Parameters::Edge::canny_kernel_size = 3; int Parameters::Edge::canny_low_threshold = 50; int Parameters::Edge::canny_blur_noise_kernel_size = 3; // The opencv edge detection method: // 0 for the Canny edge detector // 1 for the Scharr edge detector // 2 for the Sobel edge detector // 3 for the Laplacian edge detector // 4 for mixed Scharr / Sobel edge detection int Parameters::Edge::edge_detection_method = 2; // Threshold parameters int Parameters::Edge::denoised_edges_threshold = 10; // When mixed edge detection is selected, this toggle switch // is needed in order to shift execution from one edge detector // to the other. // 1 for the Scharr edge detector, // 2 for the Sobel edge detector int Parameters::Edge::mixed_edges_toggle_switch = 1; ////////////////// Image representation specific parameters ////////////////// // The depth sensor's horizontal field of view in rads float Parameters::Image::horizontal_field_of_view = static_cast<float>(58) / 180 * M_PI; // The depth sensor's vertical field of view in rads float Parameters::Image::vertical_field_of_view = static_cast<float>(45) / 180 * M_PI; // Depth and RGB images' representation method. // 0 if image used is used as obtained from the image sensor // 1 through wavelet analysis int Parameters::Image::image_representation_method = 0; // Method to scale the CV_32F image to CV_8UC1 int Parameters::Image::scale_method = 0; // Term criteria for segmentation purposes int Parameters::Image::term_criteria_max_iterations = 5; double Parameters::Image::term_criteria_max_epsilon = 1; /////////////////// Outline discovery specific parameters //////////////////// // The detection method used to obtain the outline of a blob // 0 for detecting by means of brushfire // 1 for detecting by means of raycasting int Parameters::Outline::outline_detection_method = 0; // When using raycast instead of brushfire to find the (approximate here) // outline of blobs, raycast_keypoint_partitions dictates the number of // rays, or equivalently, the number of partitions in which the blob is // partitioned in search of the blob's borders int Parameters::Outline::raycast_keypoint_partitions = 32; // Loose ends connection parameters int Parameters::Outline::AB_to_MO_ratio = 4; int Parameters::Outline::minimum_curve_points = 50; } // namespace flir_lepton_image_processing } // namespace flir_lepton
39.891892
81
0.702981
angetria
e6a549ac9e60654755928fbf79dec92943890818
16,051
cpp
C++
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Security.Cryptography.X509Certificates // Name: X509Certificate // C++ Typed Name: mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate #include <gtest/gtest.h> #include <mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Security { namespace Cryptography { namespace X509Certificates { //Constructors Tests //X509Certificate(std::vector<mscorlib::System::Byte*> data) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_1) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::IntPtr handle) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_2) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate &cert) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_3) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate() TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,DefaultConstructor) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_5) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_6) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_7) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_8) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_9) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::String password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_10) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::Security::SecureString password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_11) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_12) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_13) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::Runtime::Serialization::SerializationInfo info, mscorlib::System::Runtime::Serialization::StreamingContext context) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_14) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests // Method Equals // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate other TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Equals_1_Test) { } // Method GetCertHash // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetCertHash_Test) { } // Method GetCertHashString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetCertHashString_Test) { } // Method GetEffectiveDateString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetEffectiveDateString_Test) { } // Method GetExpirationDateString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetExpirationDateString_Test) { } // Method GetFormat // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetFormat_Test) { } // Method GetHashCode // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetHashCode_Test) { } // Method GetIssuerName // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetIssuerName_Test) { } // Method GetKeyAlgorithm // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithm_Test) { } // Method GetKeyAlgorithmParameters // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithmParameters_Test) { } // Method GetKeyAlgorithmParametersString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithmParametersString_Test) { } // Method GetName // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetName_Test) { } // Method GetPublicKey // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetPublicKey_Test) { } // Method GetPublicKeyString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetPublicKeyString_Test) { } // Method GetRawCertData // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetRawCertData_Test) { } // Method GetRawCertDataString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetRawCertDataString_Test) { } // Method GetSerialNumber // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetSerialNumber_Test) { } // Method GetSerialNumberString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetSerialNumberString_Test) { } // Method ToString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,ToString_1_Test) { } // Method ToString // Signature: mscorlib::System::Boolean fVerbose TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,ToString_2_Test) { } // Method Equals // Signature: mscorlib::System::Object obj TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Equals_2_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_1_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType, mscorlib::System::String password TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_2_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType, mscorlib::System::Security::SecureString password TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_3_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_1_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_2_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_3_Test) { } // Method Import // Signature: mscorlib::System::String fileName TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_4_Test) { } // Method Import // Signature: mscorlib::System::String fileName, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_5_Test) { } // Method Import // Signature: mscorlib::System::String fileName, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_6_Test) { } // Method Reset // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Reset_Test) { } //Public Static Methods Tests // Method CreateFromCertFile // Signature: mscorlib::System::String filename TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,CreateFromCertFile_StaticTest) { } // Method CreateFromSignedFile // Signature: mscorlib::System::String filename TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,CreateFromSignedFile_StaticTest) { } //Public Properties Tests // Property Issuer // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Issuer_Test) { } // Property Subject // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Subject_Test) { } // Property Handle // Return Type: mscorlib::System::IntPtr // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Handle_Test) { } } } } } }
34.151064
226
0.722323
brunolauze
e6a6096dc9c35918ce09bdd653dc04af88d9c0ac
4,250
cpp
C++
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; bool done[50][1<<15]; double dp[50][1<<15]; int N; vector<int> I, E, M; double go(int k, int have) { if (k == -1) return 0.0; if (done[k][have]) return dp[k][have]; done[k][have] = 1; double &ret = dp[k][have]; ret = 0.0; for (int i=0; i<N; ++i) if ((have & M[i]) == M[i]) ret += max(go(k-1, have), I[i]-E[i] + go(k-1, (have | (1<<i)))); else ret += go(k-1, have); ret /= N; return ret; } class CrazyComponents { public: double expectedProfit(int k, vector <string> components, vector <int> income, vector <int> expense) { N = components.size(); I = income; E = expense; memset(done, 0, sizeof done); M.assign(N, 0); for (int i=0; i<N; ++i) { istringstream is(components[i]); int x; while (is >> x) M[i] |= (1<<x); } return go(k-1, 0); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; string Arr1[] = { "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 1, 2 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1.5; verify_case(0, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_1() { int Arg0 = 2; string Arr1[] = { "1", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 10, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 2 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1.5; verify_case(1, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_2() { int Arg0 = 3; string Arr1[] = { "1 2", "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 100, 0, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0, 0 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 7.407407407407408; verify_case(2, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_3() { int Arg0 = 5; string Arr1[] = { "1", "2", "0", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 4, 5, 6, 7 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0, 0, 8 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 0.0; verify_case(3, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_4() { int Arg0 = 10; string Arr1[] = { "", "", "", "", "", "", "", "", "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 142352, 2342, 34534, 2344, 12346, 7589, 79872, 973453, 96233, 34567 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 12432, 2345, 3678, 456, 345, 457, 56758, 4564, 774, 34567 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1269258.9999999998; verify_case(4, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CrazyComponents ___test; ___test.run_test(-1); } // END CUT HERE
48.850575
558
0.571529
ibudiselic
e6a799067dc2efa0333720915a68138f7731ed44
669
hpp
C++
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
#ifndef FILTER_FIR_CCR_FAST_HPP #define FILTER_FIR_CCR_FAST_HPP #include <vector> #include <complex> #include "Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr.hpp" namespace aff3ct { namespace module { template <typename R = float> class Filter_FIR_ccr_fast : public Filter_FIR_ccr<R> { protected: int M; int P; public: Filter_FIR_ccr_fast (const int N, const std::vector<R> b); virtual ~Filter_FIR_ccr_fast(); virtual Filter_FIR_ccr_fast<R>* clone() const; protected: virtual void _filter(const R *X_N1, R *Y_N2, const int frame_id); virtual void _filter_old(const R *X_N1, R *Y_N2, const int frame_id); }; } } #endif //FILTER_FIR_CCR_FAST_HPP
19.114286
71
0.763827
rtajan
e6ab81000a8c5f072d041835ff9887b24ded1e64
42
cpp
C++
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
1
2021-11-19T02:56:04.000Z
2021-11-19T02:56:04.000Z
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
#include "trade.h" Trade::Trade() { }
6
18
0.547619
joestilin
e6b0e1cc12facd8462d70acacc250ca1de37ab14
630
cpp
C++
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
3,262
2016-04-10T15:24:10.000Z
2022-03-31T17:47:08.000Z
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
53
2016-10-09T16:25:04.000Z
2022-01-10T13:52:37.000Z
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
193
2017-10-23T06:08:41.000Z
2022-03-22T12:59:58.000Z
#include "dummy_network.h" using namespace Halley; void DummyNetworkAPI::init() {} void DummyNetworkAPI::deInit() {} std::unique_ptr<NetworkService> DummyNetworkAPI::createService(NetworkProtocol protocol, int port) { return std::make_unique<DummyNetworkService>(); } void DummyNetworkService::update() { } void DummyNetworkService::setAcceptingConnections(bool accepting) { } std::shared_ptr<IConnection> DummyNetworkService::tryAcceptConnection() { return std::shared_ptr<IConnection>(); } std::shared_ptr<IConnection> DummyNetworkService::connect(String address, int port) { return std::shared_ptr<IConnection>(); }
21
98
0.78254
sunhay
e6b6fe8b805312934bd44da71c48d5238f644536
150,137
cpp
C++
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
null
null
null
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
53
2021-02-01T22:31:16.000Z
2022-03-01T04:01:47.000Z
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
1
2021-02-03T13:54:23.000Z
2021-02-03T13:54:23.000Z
#include "DLX/RegisterNames.hpp" #include <catch2/catch_test_macros.hpp> #include <DLX/InstructionLibrary.hpp> #include <DLX/Parser.hpp> #include <DLX/Processor.hpp> static dlx::InstructionLibrary lib; static dlx::Processor proc; static dlx::ParsedProgram res; TEST_CASE("Operation exceptions") { constexpr std::int32_t signed_min = phi::i32::limits_type::min(); constexpr std::int32_t signed_max = phi::i32::limits_type::max(); constexpr std::uint32_t unsigned_max = phi::u32::limits_type::max(); SECTION("Signed addition overflow") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min + 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed addition underflow") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max - 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned addition overflow") { res = dlx::Parser::Parse(lib, "ADDU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 0u); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 4u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed subtraction overflow") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min + 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -5); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed subtraction underflow") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max - 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned subtraction underflow") { res = dlx::Parser::Parse(lib, "SUBU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 0u); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 1u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 1u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max - 4u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Signed multiplication overflow") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, signed_max); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == signed_max); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed multiplication underflow") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, signed_min); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == signed_min); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned multiplication overflow") { res = dlx::Parser::Parse(lib, "MULTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed division by zero") { res = dlx::Parser::Parse(lib, "DIV R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); res = dlx::Parser::Parse(lib, "DIVI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Unsigned division by zero") { res = dlx::Parser::Parse(lib, "DIVU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Float division by zero") { res = dlx::Parser::Parse(lib, "DIVF F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F4, 0.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Double division by zero") { res = dlx::Parser::Parse(lib, "DIVD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 0.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Shift left bad shift") { // Logical res = dlx::Parser::Parse(lib, "SLL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); // Arithmetic res = dlx::Parser::Parse(lib, "SLA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); } SECTION("Shift right bad shift") { // Logical res = dlx::Parser::Parse(lib, "SRL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); // Arithmetic res = dlx::Parser::Parse(lib, "SRA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); } SECTION("Jump to non existing label") { // J res = dlx::Parser::Parse(lib, "J label"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::UnknownLabel); // JAL res = dlx::Parser::Parse(lib, "JAL label"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::UnknownLabel); } SECTION("Invalid jump register") { // JR res = dlx::Parser::Parse(lib, "JR R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // JALR res = dlx::Parser::Parse(lib, "JALR R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("Loading invalid address") { SECTION("LB") { res = dlx::Parser::Parse(lib, "LB R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LBU") { res = dlx::Parser::Parse(lib, "LBU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LH") { res = dlx::Parser::Parse(lib, "LH R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LHU") { res = dlx::Parser::Parse(lib, "LHU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LW") { res = dlx::Parser::Parse(lib, "LW R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LWU") { res = dlx::Parser::Parse(lib, "LWU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LF") { res = dlx::Parser::Parse(lib, "LF F0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LD") { res = dlx::Parser::Parse(lib, "LD F0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } } SECTION("Storing invalid address") { SECTION("SB") { res = dlx::Parser::Parse(lib, "SB #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SBU") { res = dlx::Parser::Parse(lib, "SBU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SH") { res = dlx::Parser::Parse(lib, "SH #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SHU") { res = dlx::Parser::Parse(lib, "SHU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SW") { res = dlx::Parser::Parse(lib, "SW #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SWU") { res = dlx::Parser::Parse(lib, "SWU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SF") { res = dlx::Parser::Parse(lib, "SF #4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF #-4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF #5000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF 4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF -4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF 5000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SD") { res = dlx::Parser::Parse(lib, "SD #4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD #-4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD #5000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD 4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD -4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD 5000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } } } TEST_CASE("ADD") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 6); } TEST_CASE("ADDI") { res = dlx::Parser::Parse(lib, "ADDI R1 R2 #30"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("ADDU") { res = dlx::Parser::Parse(lib, "ADDU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 19u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 19u); } TEST_CASE("ADDUI") { res = dlx::Parser::Parse(lib, "ADDUI R1 R2 #19"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("ADDF") { res = dlx::Parser::Parse(lib, "ADDF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f + 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("ADDD") { res = dlx::Parser::Parse(lib, "ADDD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0 + 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SUB") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 50); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 30); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 20); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 50); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 30); } TEST_CASE("SUBI") { res = dlx::Parser::Parse(lib, "SUBI R1 R2 #25"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 50); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 25); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 50); } TEST_CASE("SUBU") { res = dlx::Parser::Parse(lib, "SUBU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 50u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 30u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 20u); } TEST_CASE("SUBUI") { res = dlx::Parser::Parse(lib, "SUBUI R1 R2 #25"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 50u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 25u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 50u); } TEST_CASE("SUBF") { res = dlx::Parser::Parse(lib, "SUBF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f - 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 1.0f); } TEST_CASE("SUBD") { res = dlx::Parser::Parse(lib, "SUBD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 2.0 - 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("MULT") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("MULTI") { res = dlx::Parser::Parse(lib, "MULTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("MULTU") { res = dlx::Parser::Parse(lib, "MULTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("MULTUI") { res = dlx::Parser::Parse(lib, "MULTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("MULTF") { res = dlx::Parser::Parse(lib, "MULTF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 3.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 3.0f * 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 3.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("MULTD") { res = dlx::Parser::Parse(lib, "MULTD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 3.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 3.0 * 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 3.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("DIV") { res = dlx::Parser::Parse(lib, "DIV R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); // Divide by zero proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVI") { res = dlx::Parser::Parse(lib, "DIVI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 6); // Divide by zero res = dlx::Parser::Parse(lib, "DIVI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVU") { res = dlx::Parser::Parse(lib, "DIVU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 6u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); // Divide by zero proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVUI") { res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 6u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 6u); // Divide by zero res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVF") { res = dlx::Parser::Parse(lib, "DIVF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 12.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 12.0f / 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 12.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("DIVD") { res = dlx::Parser::Parse(lib, "DIVD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 12.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 12.0 / 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 12.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SLL") { res = dlx::Parser::Parse(lib, "SLL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 16); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SLLI") { res = dlx::Parser::Parse(lib, "SLLI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); res = dlx::Parser::Parse(lib, "SLLI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SRL") { res = dlx::Parser::Parse(lib, "SRL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2147483647); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SRLI") { res = dlx::Parser::Parse(lib, "SRLI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1073741823); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); res = dlx::Parser::Parse(lib, "SRLI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SLA") { res = dlx::Parser::Parse(lib, "SLA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 16); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SLAI") { res = dlx::Parser::Parse(lib, "SLAI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); res = dlx::Parser::Parse(lib, "SLAI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SRA") { res = dlx::Parser::Parse(lib, "SRA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -2147483647); // 0b10000000'00000000'00000000'00000001 proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1073741824); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -2147483647); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1073741825); // 0b01000000'00000000'00000000'00000001 proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); // 0b00100000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 536870912); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1073741825); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SRAI") { res = dlx::Parser::Parse(lib, "SRAI R1 R2 #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -2147483647); // 0b10000000'00000000'00000000'00000001 proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1073741824); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -2147483647); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1073741825); // 0b01000000'00000000'00000000'00000001 proc.ExecuteCurrentProgram(); // 0b00100000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 536870912); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1073741825); res = dlx::Parser::Parse(lib, "SRAI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("AND") { res = dlx::Parser::Parse(lib, "AND R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("ANDI") { res = dlx::Parser::Parse(lib, "ANDI R1 R2 #5"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("OR") { res = dlx::Parser::Parse(lib, "OR R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("ORI") { res = dlx::Parser::Parse(lib, "ORI R1 R2 #8"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 9); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("XOR") { res = dlx::Parser::Parse(lib, "XOR R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 7); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 7); } TEST_CASE("XORI") { res = dlx::Parser::Parse(lib, "XORI R1 R2 #7"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("SLT") { res = dlx::Parser::Parse(lib, "SLT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SLTI") { res = dlx::Parser::Parse(lib, "SLTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); } TEST_CASE("SLTU") { res = dlx::Parser::Parse(lib, "SLTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 5u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SLTUI") { res = dlx::Parser::Parse(lib, "SLTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); } TEST_CASE("LTF") { res = dlx::Parser::Parse(lib, "LTF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("LTD") { res = dlx::Parser::Parse(lib, "LTD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("SGT") { res = dlx::Parser::Parse(lib, "SGT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SGTI") { res = dlx::Parser::Parse(lib, "SGTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SGTU") { res = dlx::Parser::Parse(lib, "SGTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SGTUI") { res = dlx::Parser::Parse(lib, "SGTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("GTF") { res = dlx::Parser::Parse(lib, "GTF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("GTD") { res = dlx::Parser::Parse(lib, "GTD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SLE") { res = dlx::Parser::Parse(lib, "SLE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SLEI") { res = dlx::Parser::Parse(lib, "SLEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SLEU") { res = dlx::Parser::Parse(lib, "SLEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 5u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SLEUI") { res = dlx::Parser::Parse(lib, "SLEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("LEF") { res = dlx::Parser::Parse(lib, "LEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("LED") { res = dlx::Parser::Parse(lib, "LED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("SGE") { res = dlx::Parser::Parse(lib, "SGE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); } TEST_CASE("SGEI") { res = dlx::Parser::Parse(lib, "SGEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SGEU") { res = dlx::Parser::Parse(lib, "SGEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); } TEST_CASE("SGEUI") { res = dlx::Parser::Parse(lib, "SGEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("GEF") { res = dlx::Parser::Parse(lib, "GEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("GED") { res = dlx::Parser::Parse(lib, "GED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SEQ") { res = dlx::Parser::Parse(lib, "SEQ R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SEQI") { res = dlx::Parser::Parse(lib, "SEQI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SEQU") { res = dlx::Parser::Parse(lib, "SEQU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SEQUI") { res = dlx::Parser::Parse(lib, "SEQUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("EQF") { res = dlx::Parser::Parse(lib, "EQF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("EQD") { res = dlx::Parser::Parse(lib, "EQD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SNE") { res = dlx::Parser::Parse(lib, "SNE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SNEI") { res = dlx::Parser::Parse(lib, "SNEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); } TEST_CASE("SNEU") { res = dlx::Parser::Parse(lib, "SNEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SNEUI") { res = dlx::Parser::Parse(lib, "SNEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); } TEST_CASE("NEF") { res = dlx::Parser::Parse(lib, "NEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("NED") { res = dlx::Parser::Parse(lib, "NED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("BEQZ") { const char* data = R"( BEQZ R1 true HALT true: ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 0); } TEST_CASE("BNEZ") { const char* data = R"( BNEZ R1 true HALT true: ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 0); } TEST_CASE("BFPT") { const char* data = R"( BFPT true HALT true: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(true); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(false); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); } TEST_CASE("BFPF") { const char* data = R"( BFPF false HALT false: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(false); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(true); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); } TEST_CASE("J") { const char* data = R"( J jump_label HALT jump_label: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); } TEST_CASE("JR") { const char* data = R"( JR R1 HALT ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("JAL") { const char* data = R"( JAL jump_label HALT jump_label: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R31, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R31).get() == 1); } TEST_CASE("JALR") { const char* data = R"( JALR R1 HALT ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R31).get() == 1); } TEST_CASE("LHI") { res = dlx::Parser::Parse(lib, "LHI R1 #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == (1 << 16)); } TEST_CASE("LB") { res = dlx::Parser::Parse(lib, "LB R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreByte(1000u, static_cast<std::int8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LB R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreByte(1000u, static_cast<std::int8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LBU") { res = dlx::Parser::Parse(lib, "LBU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedByte(1000u, static_cast<std::uint8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LBU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedByte(1000u, static_cast<std::uint8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LH") { res = dlx::Parser::Parse(lib, "LH R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreHalfWord(1000u, static_cast<std::int16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LH R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreHalfWord(1000u, static_cast<std::int16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LHU") { res = dlx::Parser::Parse(lib, "LHU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedHalfWord(1000u, static_cast<std::uint16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LHU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedHalfWord(1000u, static_cast<std::uint16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LW") { res = dlx::Parser::Parse(lib, "LW R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreWord(1000u, 21); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LW R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreWord(1000u, 21); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LWU") { res = dlx::Parser::Parse(lib, "LWU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedWord(1000u, 21u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LWU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedWord(1000u, 21u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LF") { res = dlx::Parser::Parse(lib, "LF F0 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ClearMemory(); proc.GetMemory().StoreFloat(1000u, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); res = dlx::Parser::Parse(lib, "LF F0 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ClearMemory(); proc.GetMemory().StoreFloat(1000u, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); } TEST_CASE("LD") { res = dlx::Parser::Parse(lib, "LD F0 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.ClearMemory(); proc.GetMemory().StoreDouble(1000u, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); res = dlx::Parser::Parse(lib, "LD F0 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.ClearMemory(); proc.GetMemory().StoreDouble(1000u, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); } TEST_CASE("SB") { res = dlx::Parser::Parse(lib, "SB #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SB 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SBU") { res = dlx::Parser::Parse(lib, "SBU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SBU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SH") { res = dlx::Parser::Parse(lib, "SH #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SH 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SHU") { res = dlx::Parser::Parse(lib, "SHU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SHU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SW") { res = dlx::Parser::Parse(lib, "SW #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SW 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SWU") { res = dlx::Parser::Parse(lib, "SWU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SWU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SF") { res = dlx::Parser::Parse(lib, "SF #1000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadFloat(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0f); res = dlx::Parser::Parse(lib, "SF 1000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadFloat(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0f); } TEST_CASE("SD") { res = dlx::Parser::Parse(lib, "SD #1000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, 1.0); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadDouble(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0); res = dlx::Parser::Parse(lib, "SD 1000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, 1.0); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadDouble(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0); } TEST_CASE("MOVF") { res = dlx::Parser::Parse(lib, "MOVF F0 F1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); } TEST_CASE("MOVD") { res = dlx::Parser::Parse(lib, "MOVD F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("MOVFP2I") { res = dlx::Parser::Parse(lib, "MOVFP2I R1 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -1); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() != -1); } TEST_CASE("MOVI2FP") { res = dlx::Parser::Parse(lib, "MOVI2FP F0 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); } TEST_CASE("CVTF2D") { res = dlx::Parser::Parse(lib, "CVTF2D F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("CVTF2I") { res = dlx::Parser::Parse(lib, "CVTF2I F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("CVTD2F") { res = dlx::Parser::Parse(lib, "CVTD2F F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTD2I") { res = dlx::Parser::Parse(lib, "CVTD2I F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTI2F") { res = dlx::Parser::Parse(lib, "CVTI2F F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTI2D") { res = dlx::Parser::Parse(lib, "CVTI2D F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != 1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("TRAP") { res = dlx::Parser::Parse(lib, "TRAP #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("HALT") { res = dlx::Parser::Parse(lib, "HALT"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("NOP") { res = dlx::Parser::Parse(lib, "NOP"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("R0 is read only") { res = dlx::Parser::Parse(lib, "ADDI R0 R0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R0).get() == 0); } TEST_CASE("Empty source code") { res = dlx::Parser::Parse(lib, ""); REQUIRE(res.m_ParseErrors.empty()); CHECK(res.m_Instructions.empty()); CHECK(res.m_JumpData.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("Misaligned addresses - Crash-8cb7670c0bacefed7af9ea62bcb5a03b95296b8e") { // Signed half words res = dlx::Parser::Parse(lib, "LH R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Unsigned half words res = dlx::Parser::Parse(lib, "LHU R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Signed words res = dlx::Parser::Parse(lib, "LW R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #1002"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Unsigned words res = dlx::Parser::Parse(lib, "LWU R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #1002"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); }
32.888719
99
0.668716
AMS21
e6ba69ec8d219d9ea1fc3f561aee804957bc9cac
2,175
cpp
C++
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
118
2019-10-12T01:29:07.000Z
2022-02-22T08:08:18.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
15
2019-09-02T16:51:39.000Z
2021-02-21T20:03:58.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
11
2019-10-21T15:53:23.000Z
2022-02-20T20:56:39.000Z
#include <Engine/Rendering/Base/Vertex.h> vk::VertexInputBindingDescription ScrapEngine::Render::Vertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(Vertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 4> ScrapEngine::Render::Vertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 4> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos)), vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color)), vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, tex_coord)), vk::VertexInputAttributeDescription(3, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, normal)), }; return attribute_descriptions; } vk::VertexInputBindingDescription ScrapEngine::Render::SkyboxVertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(SkyboxVertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 3> ScrapEngine::Render::SkyboxVertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 3> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(SkyboxVertex, pos)), vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(SkyboxVertex, color)), vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(SkyboxVertex, tex_coord)) }; return attribute_descriptions; } vk::VertexInputBindingDescription ScrapEngine::Render::OffscreenVertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(OffscreenVertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 1> ScrapEngine::Render::OffscreenVertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 1> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(OffscreenVertex, pos)) }; return attribute_descriptions; }
44.387755
117
0.801379
alundb
e6c2d82b75336758e82b25efa3b6fb390287e316
939
cpp
C++
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
1
2021-09-14T11:25:21.000Z
2021-09-14T11:25:21.000Z
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
null
null
null
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define lowbit(x) (x&-x) #define rep(i, l, r) for(int i = l; i < r; i ++) #define all(x) (x).begin(),(x).end() #define fi first #define se second using namespace std; typedef long long LL; typedef pair<int,int> PII; typedef vector<int> VI; typedef vector<vector<int>> VII; typedef vector<PII> VPII; void read(VI& a){ for(int& x : a) cin >> x; } signed main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n, q; cin >> n >> q; VI arr(n); map<int, int> mp; VII po(n + 10); int cnt = 0, idx = 1; for(int& x : arr){ cin >> x; if(!mp[x]) mp[x] = ++ cnt; po[mp[x]].push_back(idx ++); } while(q --){ int a, k; cin >> a >> k; if(!mp[a]) cout << -1; else{ if(k > po[mp[a]].size()) cout << -1; else cout << po[mp[a]][k - 1]; } cout << '\n'; } return 0; }
22.902439
48
0.496273
Sansiff
e6c4cd92efd92423aeef514615fa23a57c6c2aa9
5,598
cpp
C++
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
Weheineman/STL
2f4c5792b2be4f56b4130817803ca21f7a3ee8f4
[ "Apache-2.0" ]
2
2021-01-19T02:43:19.000Z
2021-11-20T05:21:42.000Z
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
null
null
null
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
4
2020-04-24T05:04:54.000Z
2020-05-17T22:48:58.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <memory> #include <tuple> #include <utility> using namespace std; #ifdef __clang__ #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // This test intentionally uses 0 as null. #endif // __clang__ struct A {}; struct B : public A {}; struct X {}; struct Y : public X {}; void cat(pair<A*, A*>) {} void cat(pair<A*, X*>) {} void cat(pair<X*, A*>) {} void cat(pair<X*, X*>) {} void dog(tuple<A*, A*>) {} void dog(tuple<A*, X*>) {} void dog(tuple<X*, A*>) {} void dog(tuple<X*, X*>) {} struct Quark {}; struct Proton { Proton(Quark&) {} }; struct Neutron { Neutron(const Quark&) {} }; void takes_pair(pair<Proton, Proton>) {} void takes_pair(pair<Proton, Neutron>) {} void takes_pair(pair<Neutron, Proton>) {} void takes_pair(pair<Neutron, Neutron>) {} void takes_tuple(tuple<Proton, Proton>) {} void takes_tuple(tuple<Proton, Neutron>) {} void takes_tuple(tuple<Neutron, Proton>) {} void takes_tuple(tuple<Neutron, Neutron>) {} void test_alloc(); int main() { B* b = nullptr; Y* y = nullptr; pair<B*, B*> pbb(b, b); pair<B*, Y*> pby(b, y); pair<Y*, B*> pyb(y, b); pair<Y*, Y*> pyy(y, y); tuple<B*, B*> tbb(b, b); tuple<B*, Y*> tby(b, y); tuple<Y*, B*> tyb(y, b); tuple<Y*, Y*> tyy(y, y); // template <class U, class V> pair(U&& x, V&& y); pair<A*, X*> p1(b, y); pair<A*, X*> p2(b, 0); pair<A*, X*> p3(0, y); pair<A*, X*> p4(0, 0); (void) p4; // template <class... UTypes> explicit tuple(UTypes&&... u); tuple<A*, X*> t1(b, y); tuple<A*, X*> t2(b, 0); tuple<A*, X*> t3(0, y); tuple<A*, X*> t4(0, 0); (void) t4; // template <class U, class V> pair(const pair<U, V>& p); cat(pbb); cat(pby); cat(pyb); cat(pyy); // template <class U, class V> pair(pair<U, V>&& p); cat(move(pbb)); cat(move(pby)); cat(move(pyb)); cat(move(pyy)); // template <class U1, class U2> tuple(const pair<U1, U2>& u); dog(pbb); dog(pby); dog(pyb); dog(pyy); // template <class U1, class U2> tuple(pair<U1, U2>&& u); dog(move(pbb)); dog(move(pby)); dog(move(pyb)); dog(move(pyy)); // template <class... UTypes> tuple(const tuple<UTypes...>& u); dog(tbb); dog(tby); dog(tyb); dog(tyy); // template <class... UTypes> tuple(tuple<UTypes...>&& u); dog(move(tbb)); dog(move(tby)); dog(move(tyb)); dog(move(tyy)); const pair<Quark, Quark> meow; const tuple<Quark, Quark> purr; // template <class U, class V> pair(const pair<U, V>& p); takes_pair(meow); // template <class U1, class U2> tuple(const pair<U1, U2>& u); takes_tuple(meow); // template <class... UTypes> tuple(const tuple<UTypes...>& u); takes_tuple(purr); test_alloc(); } struct Meow { Meow(const tuple<int>&) {} Meow(const pair<int, int>&) {} }; void test_alloc() { { allocator<int> al; // template <class Alloc> tuple(allocator_arg_t, const Alloc& a); tuple<A*> t1(allocator_arg, al); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, const Types&...); tuple<A*> t2(allocator_arg, al, 0); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, const UTypes&&...); tuple<A*> t3(allocator_arg, al, nullptr); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, const tuple&); tuple<A*> t4(allocator_arg, al, t2); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, tuple&&); tuple<A*> t5(allocator_arg, al, move(t2)); tuple<B*> b(nullptr); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, const tuple<UTypes...>&); tuple<A*> t6(allocator_arg, al, b); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, tuple<UTypes...>&&); tuple<A*> t7(allocator_arg, al, move(b)); pair<B*, Y*> by(nullptr, nullptr); // template <class Alloc, class U1, class U2> tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&); tuple<A*, X*> t8(allocator_arg, al, by); // template <class Alloc, class U1, class U2> tuple(allocator_arg_t, const Alloc& a, pair<U1, U2>&&); tuple<A*, X*> t9(allocator_arg, al, move(by)); // const UTypes&&... tuple<int> ti(0); tuple<Meow> t10(allocator_arg, al, ti); tuple<Meow> t11(allocator_arg, al, move(ti)); pair<int, int> pii(0, 0); tuple<Meow> t12(allocator_arg, al, pii); tuple<Meow> t13(allocator_arg, al, move(pii)); } { tuple<A*> t1; (void) t1; tuple<A*> t2(0); tuple<A*> t3(nullptr); (void) t3; tuple<A*> t4(t2); (void) t4; tuple<A*> t5(move(t2)); (void) t5; tuple<B*> b(nullptr); tuple<A*> t6(b); tuple<A*> t7(move(b)); pair<B*, Y*> by(nullptr, nullptr); tuple<A*, X*> t8(by); tuple<A*, X*> t9(move(by)); tuple<int> ti(0); tuple<Meow> t10(ti); tuple<Meow> t11(move(ti)); pair<int, int> pii(0, 0); tuple<Meow> t12(pii); tuple<Meow> t13(move(pii)); } }
25.445455
116
0.535191
Weheineman
e6c82103c4ac637802c2f235e4fe96c575168d86
206
cc
C++
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
5
2019-08-01T07:52:27.000Z
2022-03-27T08:09:35.000Z
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
1
2020-10-03T17:29:59.000Z
2020-11-17T10:03:10.000Z
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
6
2019-08-24T08:55:56.000Z
2022-02-09T08:41:44.000Z
#include <iostream> void reset(int &i) { i = 0; } int main(void) { int i = 100; std::cout << "i = " << i << std::endl; reset(i); std::cout << "i = " << i << std::endl; return 0; }
12.875
42
0.451456
williamgherman
e6ce736d68bf7cb04368e6302e243e2d21e118e2
3,856
hpp
C++
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
9
2020-06-24T11:22:15.000Z
2022-01-13T14:14:13.000Z
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
1
2021-05-10T13:48:04.000Z
2021-05-10T13:48:04.000Z
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
2
2021-11-08T11:59:29.000Z
2022-03-15T13:50:54.000Z
#pragma once #include "defaults.hpp" #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <map> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <gtkmm/builder.h> #include <gtkmm.h> #include <glib.h> #include "LCCErrorModelRecord.hpp" #include "LCCErrorLogger.hpp" /** * \brief UI Class for the internal Errors that occured within the LCC, mostly Commonroad-related, that do not lead to crashes and are shown to the user * \ingroup lcc_ui */ class LCCErrorViewUI { private: //! GTK builder for the UI Glib::RefPtr<Gtk::Builder> ui_builder; //! Parent box of the view, to integrate it into the overall UI Gtk::Box* parent; //! TreeView that contains the LCC error messages Gtk::TreeView* error_treeview; //! Label for the treeview Gtk::Label* error_label_header; //! Window that contains error_treeview to make it scrollable Gtk::ScrolledWindow* error_scrolled_window; //! Check button to automatically scroll to the latest error message when active Gtk::CheckButton* autoscroll_check_button; //! Reset button to reset/clear the currently shown error messages Gtk::Button* error_button_reset; //! Defines the TreeView layout LCCErrorModelRecord error_record; //! Status storage for the UI, contains all entries of error_treeview Glib::RefPtr<Gtk::ListStore> error_list_store; //UI update functions and objects /** * \brief Function called by ui_thread to periodically activate the dispatcher that in turn calls GTK's UI thread, to perform UI updates */ void update_ui(); /** * \brief Callback for GTK's UI dispatcher, all UI changes done during runtime should be performed within this function */ void dispatcher_callback(); //! To communicate between the current thread and GTK's UI thread Glib::Dispatcher ui_dispatcher; //! UI thread that periodically ativates the GTK dispatcher to perform an update in the UI std::thread ui_thread; //! Tells ui_thread if it should still be running std::atomic_bool run_thread; /** * \brief Callback function to enable autoscroll if autoscroll_check_button is used * \param allocation Irrelevant parameter that is part of the callback */ void on_size_change_autoscroll(Gtk::Allocation& allocation); /** * \brief Delete all currently shown error logs */ void reset_list_store(); /** * \brief Check for scroll event to turn off automatic scrolling in case the user scrolls manually through the error list * \param scroll_event The scroll event */ bool scroll_callback(GdkEventScroll* scroll_event); /** * \brief Callback for tooltip (to show full message on mouse hover) * \param x x coordinate e.g. of the mouse pointer * \param y y coordinate e.g. of the mouse pointer * \param keyboard_tooltip If the tooltip was triggered by the keyboard * \param tooltip Reference to the tooltip to be shown */ bool tooltip_callback(int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip); //! Variable for the reset action - if true, reset the logs (is performed within the UI) std::atomic_bool reset_logs; public: /** * \brief Constructor to create the UI element */ LCCErrorViewUI(); /** * \brief Destructor to destroy the UI thread on object destruction */ ~LCCErrorViewUI(); /** * \brief Function to get the parent widget, so that this UI element can be placed within another UI element */ Gtk::Widget* get_parent(); /** * \brief Might be called from outside, e.g. when a new 'simulation' is run, to reset the current error messages */ void reset(); };
33.824561
152
0.699689
Durrrr95
e6d02cd27f2410ff894e4f29876fe87754a18442
3,004
cpp
C++
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
1
2019-05-03T18:00:39.000Z
2019-05-03T18:00:39.000Z
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
// // ActiveItem.cpp // pgf+ // // Created by Emil Djupfeldt on 2012-07-04. // Copyright (c) 2012 Chalmers University of Technology. All rights reserved. // #include <gf/stringutil.h> #include <gf/parser/ActiveItem.h> namespace gf { namespace parser { ActiveItem::ActiveItem(uint32_t begin, uint32_t category, gf::reader::CncFun* cncFun, const std::vector<uint32_t>& domain, uint32_t constituent, uint32_t position) : begin(begin), category(category), cncFun(cncFun), domain(domain), constituent(constituent), position(position) { } ActiveItem::~ActiveItem() { gf::release(cncFun); } uint32_t ActiveItem::getBegin() const { return begin; } uint32_t ActiveItem::getCategory() const { return category; } gf::reader::CncFun* ActiveItem::getFunction() const { return cncFun; } const std::vector<uint32_t>& ActiveItem::getDomain() const { return domain; } uint32_t ActiveItem::getConstituent() const { return constituent; } uint32_t ActiveItem::getPosition() const { return position; } gf::reader::Symbol* ActiveItem::nextSymbol() const { if (hasNextSymbol()) { return cncFun->getSequences().at(constituent)->getSymbols().at(position); } return NULL; } bool ActiveItem::hasNextSymbol() const { return position < cncFun->getSequences().at(constituent)->getSymbols().size(); } bool ActiveItem::operator==(const ActiveItem& other) const { return begin == other.begin && category == other.category && cncFun == other.cncFun && domain == other.domain && constituent == other.constituent && position == other.position; } bool ActiveItem::operator!=(const ActiveItem& other) const { return !(*this == other); } std::string ActiveItem::toString() const { std::string ret; ret = "["; ret+= gf::toString(begin) + ";"; ret+= gf::toString(category) + "->" + cncFun->getName(); ret+= "[" + domainToString() + "];"; ret+= gf::toString(constituent) + ";"; ret+= gf::toString(position); ret+= "]"; return ret; } std::string ActiveItem::domainToString() const { std::string ret; for (std::vector<uint32_t>::const_iterator it = domain.begin(); it != domain.end(); it++) { ret+= (it == domain.begin() ? "" : ", ") + gf::toString(*it); } return ret; } } }
30.969072
171
0.500333
egladil
e6d2da9d3ea57374b0bbbddfb8561453a8f34803
4,162
hpp
C++
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/nio/charset/fwd-POI.hpp> #include <java/util/fwd-POI.hpp> #include <java/io/FilterOutputStream.hpp> #include <java/lang/Appendable.hpp> #include <java/io/Closeable.hpp> struct default_init_tag; class java::io::PrintStream : public FilterOutputStream , public virtual ::java::lang::Appendable , public virtual Closeable { public: typedef FilterOutputStream super; private: bool autoFlush { }; OutputStreamWriter* charOut { }; bool closing { }; ::java::util::Formatter* formatter { }; BufferedWriter* textOut { }; bool trouble { }; protected: void ctor(OutputStream* out); void ctor(::java::lang::String* fileName); void ctor(File* file); /*void ctor(bool autoFlush, OutputStream* out); (private) */ void ctor(OutputStream* out, bool autoFlush); void ctor(::java::lang::String* fileName, ::java::lang::String* csn); void ctor(File* file, ::java::lang::String* csn); /*void ctor(bool autoFlush, OutputStream* out, ::java::nio::charset::Charset* charset); (private) */ /*void ctor(bool autoFlush, ::java::nio::charset::Charset* charset, OutputStream* out); (private) */ void ctor(OutputStream* out, bool autoFlush, ::java::lang::String* encoding); public: PrintStream* append(::java::lang::CharSequence* csq) override; PrintStream* append(char16_t c) override; PrintStream* append(::java::lang::CharSequence* csq, int32_t start, int32_t end) override; virtual bool checkError(); public: /* protected */ virtual void clearError(); public: void close() override; /*void ensureOpen(); (private) */ void flush() override; virtual PrintStream* format(::java::lang::String* format, ::java::lang::ObjectArray* args); virtual PrintStream* format(::java::util::Locale* l, ::java::lang::String* format, ::java::lang::ObjectArray* args); /*void newLine(); (private) */ virtual void print(bool b); virtual void print(char16_t c); virtual void print(int32_t i); virtual void print(int64_t l); virtual void print(float f); virtual void print(double d); virtual void print(::char16_tArray* s); virtual void print(::java::lang::String* s); virtual void print(::java::lang::Object* obj); virtual PrintStream* printf(::java::lang::String* format, ::java::lang::ObjectArray* args); virtual PrintStream* printf(::java::util::Locale* l, ::java::lang::String* format, ::java::lang::ObjectArray* args); virtual void println(); virtual void println(bool x); virtual void println(char16_t x); virtual void println(int32_t x); virtual void println(int64_t x); virtual void println(float x); virtual void println(double x); virtual void println(::char16_tArray* x); virtual void println(::java::lang::String* x); virtual void println(::java::lang::Object* x); /*static ::java::lang::Object* requireNonNull(::java::lang::Object* obj, ::java::lang::String* message); (private) */ public: /* protected */ virtual void setError(); /*static ::java::nio::charset::Charset* toCharset(::java::lang::String* csn); (private) */ public: void write(int32_t b) override; /*void write(::char16_tArray* buf); (private) */ /*void write(::java::lang::String* s); (private) */ void write(::int8_tArray* buf, int32_t off, int32_t len) override; // Generated PrintStream(OutputStream* out); PrintStream(::java::lang::String* fileName); PrintStream(File* file); PrintStream(OutputStream* out, bool autoFlush); PrintStream(::java::lang::String* fileName, ::java::lang::String* csn); PrintStream(File* file, ::java::lang::String* csn); PrintStream(OutputStream* out, bool autoFlush, ::java::lang::String* encoding); protected: PrintStream(const ::default_init_tag&); public: static ::java::lang::Class *class_(); void write(::int8_tArray* b); private: virtual ::java::lang::Class* getClass0(); };
36.831858
121
0.675637
pebble2015
e6d745196d151d41dd1541723ccf20c32233acab
2,572
cpp
C++
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; char res[100000]; void addString(char *pro) { int len1=strlen(res); int len2=strlen(pro); int l_low,l_high; // cout<<len1<<" "<<len2<<endl; if(len1<=len2) { l_low=len1; l_high=len2; } else { l_low=len2; l_high=len1; } int temp=0; for(int i=1;i<=l_low;i++) { temp=((res[len1-i]-'0')+(pro[len2-i])-'0')+temp; // cout<<temp<<endl; res[(l_high+1)-i]=(temp%10)+'0'; // cout<<sum[i]<<endl; temp=temp/10; } // cout<<sum[2]<<endl; if(l_low==len1) { //cout<<"in if: "<<sum<<endl; int k; for(k=len2-len1-1;k>=0;k--) { temp=pro[k]-'0'+temp; res[k+1]=(temp%10)+'0'; temp=temp/10; } if(temp>0) { res[k+1]=temp+'0'; } else res[k+1]='0'; res[len2+1]='\0'; } else if(l_low==len2) { // cout<<"in else: "<<sum<<endl; int k; for(k=len1-len2-1;k>=0;k--) { temp=res[k]-'0'+temp; res[k+1]=(temp%10)+'0'; temp=temp/10; } if(temp>0) { res[k+1]=temp+'0'; } else res[k+1]='0'; res[len1+1]='\0'; } //cout<<sum<<endl; } int main() { char str1[500]; char str2[500]; while(gets(str1)) { gets(str2); res[0]='0'; res[1]='\0'; int len1 = strlen(str1); int len2 = strlen(str2); int k=0; for(int i=len2-1;i>=0;i--) { char pro[100000]; int temp=0; int n= str2[i]-'0'; for(int j=len1-1;j>=0;j--) { temp = (str1[j]-'0')*n+temp; pro[j+1]= temp%10+'0'; temp/=10; } // cout<<pro<<endl; pro[0]=temp+'0'; for(int a=0;a<k;a++) { pro[len1+1+a]='0'; } pro[len1+1+k]='\0'; // cout<<pro<<endl; // cout<<res<<endl; addString(pro); k++; } int len=strlen(res); int flag=0; for(int i=0;i<len;i++) { if(flag==0&&res[i]=='0') continue; else { flag=1; printf("%c",res[i]); } } cout<<"\n"; } return 0; }
16.921053
56
0.360031
akazad13
e6daaeae978fb7901e8a4730c14c67f9e1c05706
8,142
cpp
C++
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
1
2021-12-10T09:27:45.000Z
2021-12-10T09:27:45.000Z
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
null
null
null
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
null
null
null
#include "MNIST/MNISTHelper.h" #include "Window/Window.h" #include "AI/Util/Random.h" #include "AI/Util/Util.h" #include "AI/Util/ImGuiMatrixRenderer.h" #include "AI/Network.h" #include "AI/Math.h" #include "AI/Metrics.h" #include "AI/Console.h" #include <future> int main() { try { // Zufallszahlengenerator zurücksetzen, um bei jedem // Neustart neue Gewichtungen und Bias zu erzeugen. AI::Util::Random::Reset(); // Der Datensatz, mit welchem das Netz getestet wird (enthält andere Samples). const AI::TrainingData testData{MNIST::Load( "dataset/test-images", "dataset/test-labels")}; // Der Datensatz, mit welchem das Netz trainiert wird. const AI::TrainingData trainingData{MNIST::Load( "dataset/train-images", "dataset/train-labels")}; AI::Network network({{784}, {16}, {16}, {10}}); std::future<void> trainingFuture; Window window{1024, 768}; AI::Matrix mat{784, 1}; mat.setZero(); while (window.IsRunning()) { window.BeginFrame(); AI::Console::ClearMessages(); // ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); ImVec2 v = ImGui::GetMainViewport()->Pos; ImVec2 s = ImGui::GetMainViewport()->Size; ImGui::SetNextWindowPos(v); ImGui::SetNextWindowSize(s); ImGui::Begin("Docking", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); ImGui::DockSpace(ImGui::GetID("DockSpace")); ImGui::End(); ImGui::Begin("Training"); static int numEpochs = 30; ImGui::Text("Anzahl der Epochen"); ImGui::InputInt("##numEpochs", &numEpochs); static int miniBatchSize = 20; ImGui::Text("Größe der Mini-Batches"); ImGui::InputInt("##miniBatchSize", &miniBatchSize); static float eta = 3.f; ImGui::Text("Lernrate"); ImGui::InputFloat("##eta", &eta); ImGui::Separator(); if (!network.IsTrainingRunning() && ImGui::Button("Trainieren")) { trainingFuture = std::async(std::launch::async, [&]() { network.SGD(trainingData, numEpochs, miniBatchSize, eta, testData); }); } if (network.IsTrainingRunning()) { if (ImGui::Button("Fertigstellen")) { network.StopTraining(); } ImGui::Text("Trainingsfortschritt:"); ImGui::ProgressBar(network.GetCurrentSGDProgress()); ImGui::Text("Aktuelle Epoche:"); ImGui::ProgressBar(network.GetCurrentEpochProgress()); } ImGui::End(); ImGui::Begin("Zeichnen", nullptr, ImGuiWindowFlags_NoMove); { ImVec2 vMin = ImGui::GetWindowContentRegionMin(); ImVec2 vMax = ImGui::GetWindowContentRegionMax(); vMin.x += ImGui::GetWindowPos().x; vMin.y += ImGui::GetWindowPos().y; vMax.x += ImGui::GetWindowPos().x; vMax.y += ImGui::GetWindowPos().y; float mousePosInWindowX = ImGui::GetIO().MousePos.x - vMin.x; float mousePosInWindowY = ImGui::GetIO().MousePos.y - vMin.y; std::function<void(int j, int i, float val)> set = [&](int j, int i, float val) { if (j < 28 && i < 28 && j >= 0 && i >= 0) { float &var = mat(j * 28 + i); var += val; if (var > 1.f) var = 1.f; } }; if (mousePosInWindowX >= 0 && mousePosInWindowX < vMax.x) { if (mousePosInWindowY >= 0 && mousePosInWindowY < vMax.y) { if (ImGui::IsMouseDragging(ImGuiMouseButton_Left) && ImGui::IsWindowHovered()) { int i = mousePosInWindowX / 10; int j = mousePosInWindowY / 10; float factor = 1.f; set(j, i, 1.f); for (int x = -1; x <= 1; ++x) { set(j, i + x, 0.3f); } for (int y = -1; y <= 1; ++y) { set(j + y, i, 0.3f); } } } } } ImGui::RenderMatrix(mat); ImGui::End(); ImGui::Begin("Steuerung"); static AI::Matrix res; static int right = 0; static int total = 0; if (ImGui::Button("Testen")) { res = network.Feedforward(mat); total++; } if (total != 0) { ImGui::SameLine(); if (ImGui::Button("Zurücksetzen")) { res.setZero(); right = 0; total = 0; } } if (!res.isZero()) { size_t greatestIndex = AI::Util::FindGreatestIndex(res); for (size_t i = 0; i < 10; ++i) { float num = res(i, 0); int color = 255 * num; if (greatestIndex == i) { ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); ImGui::PushStyleColor(ImGuiCol_Border, IM_COL32(255, 255, 0, 255)); } ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(color, color, color, 255)); ImGui::Button(AI::StringFormat("%i %.3f", i, num).c_str()); if (greatestIndex == i) { ImGui::PopStyleVar(); ImGui::PopStyleColor(); } ImGui::PopStyleColor(); } if (ImGui::Button("Ja")) { mat.setZero(); res.setZero(); right++; } ImGui::SameLine(); if (ImGui::Button("Nein")) { mat.setZero(); res.setZero(); } } if (total != 0) { ImGui::Text("Genauigkeit: %.2f%%", right / static_cast<float>(total) * 100.f); } ImGui::End(); ImGui::Begin("Samples"); static int sample = 0; static AI::Matrix matrix = testData[sample].input; ImGui::RenderMatrix(matrix); if (ImGui::DragInt("Sample", &sample, 1.f, 0, testData.size() - 1)) { matrix = testData[sample].input; } if (ImGui::Button("Test")) { res = network.Feedforward(matrix); } ImGui::End(); ImGui::Begin("Konsole"); for (int i = 0; i < AI::Console::GetMessages().size(); ++i) { ImGui::Text(AI::Console::GetMessages()[i].c_str()); } ImGui::End(); window.EndFrame(); } trainingFuture.wait(); } catch (const std::runtime_error &error) { LINE_OUT("[Exception] " + std::string{error.what()}); } return 0; }
34.066946
261
0.436748
eugen-bondarev
5c7922737adf0a6bfed77e962d6922dd305a7f70
984
hpp
C++
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
1
2019-08-14T12:31:50.000Z
2019-08-14T12:31:50.000Z
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
// // Created by nhyarlathotep on 30/11/18. // #pragma once #include <string> #include "../../includes/Utils.hpp" namespace Game { struct MonsterInfo { public: MonsterInfo() : _type(""), _pos{0, 0}, _timer(0), _endGame(false) {} MonsterInfo(std::string &&type, float x, float y, float setTimer) : _type(type), _pos{x, y}, _timer(setTimer), _endGame(false) {} MonsterInfo(std::string &&type, Game::vector2f sPos, float setTimer = 0) : _type(type), _pos(sPos), _timer(setTimer), _endGame(false) {} friend std::istream &operator>>(std::istream &is, MonsterInfo &mInfo) { is >> mInfo._type; is >> mInfo._pos.x; is >> mInfo._pos.y; is >> mInfo._timer; mInfo._endGame = is.eof(); return is; } public: std::string _type; Game::vector2f _pos; float _timer; bool _endGame; }; }
25.894737
82
0.537602
KillianG
5c7b9e56bc2e1e64d4c40eff512cbf20fd251d09
14,565
cpp
C++
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
// // Created by Harrand on 14/12/2018. // #include "socket.hpp" #include "amethyst.hpp" bool am::detail::is_initialised = false; SocketDescriptor::SocketDescriptor(am::net::transmission::protocol transmission_protocol, am::net::internet::protocol internet_protocol): transmission_protocol(transmission_protocol), internet_protocol(internet_protocol){} ISocket::ISocket(SocketDescriptor descriptor): descriptor(descriptor), bound(false), port(std::nullopt), destination_address(std::nullopt) { if(!am::detail::is_initialised) std::cerr << "ISocket::ISocket(...): Amethyst not initialised.\n"; } const SocketDescriptor& ISocket::get_info() const { return this->descriptor; } #ifdef AMETHYST_WINDOWS SocketWindows::SocketWindows(SocketDescriptor descriptor): ISocket(descriptor), socket_handle(INVALID_SOCKET), connection_handle(INVALID_SOCKET) { using namespace am::net; int af; switch(this->descriptor.internet_protocol) { default: case internet::protocol::IPV4: af = AF_INET; break; case internet::protocol::IPV6: af = AF_INET6; break; } int type, protocol; switch(this->descriptor.transmission_protocol) { default: case transmission::protocol::TCP: type = SOCK_STREAM; protocol = IPPROTO_TCP; break; case transmission::protocol::UDP: type = SOCK_DGRAM; protocol = IPPROTO_UDP; break; } this->socket_handle = socket(af, type, protocol); auto error = WSAGetLastError(); if(error != 0) am::debug::print("SocketWindows::SocketWindows(...) Initialisation Error Code: ", error, "\n"); } SocketWindows::~SocketWindows() { this->unbind(); closesocket(this->socket_handle); } bool SocketWindows::bind(unsigned int port) { using namespace am::net::internet; int result; switch(this->descriptor.internet_protocol) { case protocol::IPV6: { sockaddr_in6 address; memset(&address, 0, sizeof(address)); address.sin6_family = AF_INET6; address.sin6_port = htons(port); //address.sin6_addr.s_addr = inet_addr("0.0.0.0"); result = ::bind(this->socket_handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)); } break; case protocol::IPV4: default: { sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = inet_addr("0.0.0.0"); result = ::bind(this->socket_handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)); } break; } if(result == -1) { am::debug::print("SocketWindows::bind(...) could not bind correctly and produced error code: ", WSAGetLastError(), "\n"); //std::cerr << "SocketWindows::bind(...) produced error code " << WSAGetLastError() << "\n"; return false; } this->bound = true; this->port = {port}; return true; } bool SocketWindows::listen(std::size_t maximum_queue_length) { if(!this->bound) { am::debug::print("SocketWindows::listen(...) invoked but the Socket is not bound! Aborting.\n"); return false; } int result = ::listen(this->socket_handle, maximum_queue_length); if(result == -1) { am::debug::print("SocketWindows::listen(...) produced error code ", WSAGetLastError(), "\n"); return false; } return true; } bool SocketWindows::connect(const std::string& address, unsigned int port) { using namespace am::net::transmission; if(this->get_info().transmission_protocol == protocol::TCP) { addrinfo connection_info; addrinfo *response = nullptr; memset(&connection_info, 0, sizeof(connection_info)); connection_info.ai_family = AF_UNSPEC; switch (this->get_info().transmission_protocol) { case protocol::TCP: connection_info.ai_socktype = SOCK_STREAM; connection_info.ai_protocol = IPPROTO_TCP; break; case protocol::UDP: connection_info.ai_socktype = SOCK_DGRAM; connection_info.ai_protocol = IPPROTO_UDP; break; } if (getaddrinfo(address.c_str(), std::to_string(port).c_str(), &connection_info, &response) != 0) { /*AMETHYST_DEBUG_PRINT((std::string( "SocketWindows::connect(...) could not resolve the target address. It produced error ") + std::to_string(WSAGetLastError()) + ".\n").c_str());*/ am::debug::print("SocketWindows::connect(...) could not resolve the target address. It produced error code: ", WSAGetLastError(), "\n"); return false; } addrinfo *response_pointer = nullptr; for (response_pointer = response; response_pointer != nullptr; response_pointer = response_pointer->ai_next) { if (::connect(this->socket_handle, response_pointer->ai_addr, static_cast<int>(response_pointer->ai_addrlen)) == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::connect(...) could not connect to the target address. It produced error ") +std::to_string(WSAGetLastError()) + ".\n").c_str()); am::debug::print("SocketWindows::connect(...) could not connect to the target address. It produced error code: ", WSAGetLastError(), "\n"); return false; } } freeaddrinfo(response); } this->destination_address = {{{this->get_info().internet_protocol}, address}}; this->port = {port}; return true; } std::optional<Address> SocketWindows::accept() { this->connection_handle = ::accept(this->socket_handle, nullptr, nullptr); if(this->connection_handle == INVALID_SOCKET) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::accept(...) did not connect to a valid socket and produced error code ") + std::to_string(WSAGetLastError())).c_str()) am::debug::print("SocketWindows::accept(...) did not connect to a valid socket and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } sockaddr_in other_socket; socklen_t len = sizeof(other_socket); getpeername(this->connection_handle, (sockaddr*)&other_socket, &len); AddressWindows other_socket_address{other_socket}; this->destination_address = {static_cast<Address>(other_socket_address)}; return this->destination_address; } bool SocketWindows::send(const std::string& data) { using namespace am::net::transmission; if(this->get_info().transmission_protocol == protocol::TCP) { int result = ::send(this->socket_handle, data.c_str(), data.size(), 0); if (result == SOCKET_ERROR) { /*AMETHYST_DEBUG_PRINT((std::string( "SocketWindows::send(...) could not send data correctly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str());*/ am::debug::print("SocketWindows::send(...) could not send data correctly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return false; } return true; } else // UDP Send { if(!this->destination_address.has_value() || !this->port.has_value()) { // Never connected. //AMETHYST_DEBUG_PRINT("SocketWindows::send(...) invoked (UDP) but there is no destination address!"); am::debug::print("SocketWindows::send(...) invoked (UDP) but there is no destination address.\n"); return false; } AddressWindows dest_address = {this->destination_address.value()}; sockaddr_in win_address = dest_address.get_winsock_address_ipv4(this->port.value()); int result = sendto(this->socket_handle, data.c_str(), data.size(), 0, reinterpret_cast<sockaddr*>(&win_address), sizeof(win_address)); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::send(...) could not send data correctly (UDP) and produced error code") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::send(...) could not send data correctly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return false; } return true; } } std::size_t SocketWindows::peek_receive_size() { using namespace am::net::transmission; std::string buffer; if(this->get_info().transmission_protocol == protocol::TCP) { if (this->connection_handle == INVALID_SOCKET) { /*AMETHYST_DEBUG_PRINT( "SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection. Aborting...");*/ am::debug::print("SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection.\n"); return 0; } buffer.resize(am::net::consts::maximum_tcp_packet_size); int result = ::recv(this->connection_handle, buffer.data(), buffer.size(), MSG_PEEK); if (result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return 0; } return result; } else // UDP Receive { buffer.resize(am::net::consts::maximum_udp_packet_size); int result = recvfrom(this->socket_handle, buffer.data(), buffer.size(), MSG_PEEK, nullptr, nullptr); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return 0; } return result; } } std::optional<std::string> SocketWindows::receive(std::size_t buffer_size) { using namespace am::net::transmission; std::string buffer; buffer.resize(buffer_size); if(this->get_info().transmission_protocol == protocol::TCP) { if (this->connection_handle == INVALID_SOCKET) { /*AMETHYST_DEBUG_PRINT( "SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection. Aborting...");*/ am::debug::print("SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection.\n"); return std::nullopt; } int result = ::recv(this->connection_handle, buffer.data(), buffer_size, 0); if (result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } return buffer; } else // UDP Receive { int result = recvfrom(this->socket_handle, buffer.data(), buffer_size, 0, nullptr, nullptr); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } return buffer; } } std::optional<std::string> SocketWindows::receive_boundless() { return this->receive(this->peek_receive_size()); } bool SocketWindows::unbind() { return closesocket(this->socket_handle) == 0; } #elif AMETHYST_UNIX SocketUnix::SocketUnix(SocketDescriptor descriptor): ISocket(descriptor), socket_handle(-1) { using namespace am::net; int af; switch(this->descriptor.internet_protocol) { case internet::protocol::IPV4: default: af = AF_INET; break; case internet::protocol::IPV6: af = AF_INET6; break; } int type; switch(this->descriptor.transmission_protocol) { case transmission::protocol::TCP: default: type = SOCK_STREAM; break; case transmission::protocol::UDP: type = SOCK_DGRAM; break; } this->socket_handle = socket(af, type, 0); AMETHYST_DEBUG_PRINT((std::string("SocketUnix::SocketUnix(...) Initialisation Error Code: ") + strerror(errno)).c_str()); } bool SocketUnix::bind(unsigned int port) { // TODO: Implement } #endif
43.477612
222
0.57082
Harrand
5c7bb3a079dcd91bec6adbbfd9be63e19f32225e
9,550
cpp
C++
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
1
2019-01-09T05:16:42.000Z
2019-01-09T05:16:42.000Z
/* * Author: Jon Trulson <[email protected]> * Copyright (c) 2015 Intel Corporation. * * 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 <unistd.h> #include <math.h> #include <string> #include <stdexcept> #include "at42qt1070.h" using namespace std; const uint8_t AVE_KEY_MAX = 6; const uint8_t AKS_KEY_MAX = 3; const uint8_t NO_GUARD_KEY = 7; AT42QT1070::AT42QT1070(PinName sda, PinName scl, uint8_t address) : _i2c(sda, scl), _addr(address << 1) { initialize(); } AT42QT1070::AT42QT1070(I2C& i2c, uint8_t address) : _i2c(i2c), _addr(address << 1) { initialize(); } void AT42QT1070::initialize() { _i2c.frequency(AT42QT1070_I2C_MAX_FREQUENCY); // spec list <230ms as boot up time, wait here to be sure wait_ms(230); reset(); wait_ms(230); if (readChipID() != 0x2E) { return; // throw std::runtime_error("Chip ID does not match the // expected value (2Eh)"); } _buttonStates = 0; _calibrating = false; _overflow = false; } //-------------------------------------------------------------------------------- AT42QT1070::~AT42QT1070() { _i2c.stop(); } //-------------------------------------------------------------------------------- bool AT42QT1070::writeByte(uint8_t reg, uint8_t byte) { const char cmd[] = { reg, byte }; if (0 == _i2c.write(_addr, cmd, 2)) return true; else return false; } //-------------------------------------------------------------------------------- bool AT42QT1070::writeWord(uint8_t reg, uint16_t word) { const char cmd[] = { reg, word & 0xff, (word & 0xff00) >> 8 }; if (0 == _i2c.write(_addr, cmd, 3)) return true; else return false; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::readByte(uint8_t reg) { char data = 0; const char cmd = reg; _i2c.write(_addr, &cmd, 1); _i2c.read(_addr, &data, 1); return data; } //-------------------------------------------------------------------------------- uint16_t AT42QT1070::readWord(uint8_t reg) { uint16_t res = 0; char data[] = { 0, 0 }; const char cmd = reg; _i2c.write(_addr, &cmd, 1); _i2c.read(_addr, data, 2); res = data[1] << 8 & data[0]; return res; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::readChipID(void) { return readByte(REG_CHIPID); } //-------------------------------------------------------------------------------- void AT42QT1070::updateState() { uint8_t status = readByte(REG_DETSTATUS); // if we are calibrating, don't change anything if (status & DET_CALIBRATE) { _calibrating = true; return; } else { _calibrating = false; } if (status & DET_OVERFLOW) _overflow = true; else _overflow = false; // if a touch is occurring, read the button states if (status & DET_TOUCH) { uint8_t keys = readByte(REG_KEYSTATUS); // high bit is reserved, filter it out _buttonStates = keys & ~0x80; } else { _buttonStates = 0; } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getButtonsState() { uint8_t status = readByte(REG_DETSTATUS); uint8_t keys = readByte(REG_KEYSTATUS); // if we are calibrating, don't change anything if (status & DET_CALIBRATE) { _calibrating = true; return 0; } // Old library only read buttons if one of them was touched. // We want to read either way so that change line gets reset. // Therefore read command has been moved outside of if statement. if (status & DET_TOUCH) { // high bit is reserved, filter it out _buttonStates = keys & ~0x80; } else { _buttonStates = 0; } // set the top bit in _buttonStates to signal overflow if (status & DET_OVERFLOW) { _buttonStates |= 0x80; } return _buttonStates; } //-------------------------------------------------------------------------------- bool AT42QT1070::isButtonPressed(const uint8_t button) { uint8_t buttonsState = 0; if (button <= 6) { buttonsState = getButtonsState(); } return (buttonsState & (0x1 << button)); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getLowPowerMode(void) { return readByte(REG_LP); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setLowPowerMode(uint8_t mode) { writeByte(REG_LP, mode); return getLowPowerMode(); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getMaxOn(void) { return readByte(REG_MAXON); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setMaxOn(uint8_t maxon) { writeByte(REG_MAXON, maxon); return getMaxOn(); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getAVE(uint8_t key) { uint8_t value = 0; uint8_t ave = 0; if (key <= AVE_KEY_MAX) { value = readByte(REG_AVE0 + key); ave = (value & 0xFC) >> 2; } return ave; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setAVE(uint8_t key, uint8_t ave) { uint8_t value = 0; // if (key > AVE_KEY_MAX) { // throw std::invalid_argument("Only keys 0-6 are allowed"); // } // switch (ave) { // case 1: // case 2: // case 4: // case 8: // case 16: // case 32: // break; // default: // throw std::invalid_argument("Invalid averaging factor"); // } value = readByte(REG_AVE0 + key); value = value & 0x03; value = value | (ave << 2); writeByte(REG_AVE0 + key, value); return getAVE(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getAKSGroup(uint8_t key) { uint8_t value = 0; uint8_t aks = 0; if (key <= AKS_KEY_MAX) { value = readByte(REG_AVE0 + key); aks = value & 0x03; } return aks; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setAKSGroup(uint8_t key, uint8_t group) { uint8_t value = 0; if (key <= AVE_KEY_MAX && group <= AKS_KEY_MAX) { value = readByte(REG_AVE0 + key); value = value & 0xFC; value = value | group; writeByte(REG_AVE0 + key, value); } return getAKSGroup(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getDetectionIntegrator(uint8_t key) { if (key <= AKS_KEY_MAX) { return readByte(REG_DI0 + key); } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setDetectionIntegrator(uint8_t key, uint8_t di) { if (key <= AVE_KEY_MAX) { writeByte(REG_DI0 + key, di); } return getDetectionIntegrator(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getThreshold(uint8_t key) { if (key <= AKS_KEY_MAX) { return readByte(REG_NTHR0 + key); } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setThreshold(uint8_t key, uint8_t nthr) { if (key <= AVE_KEY_MAX) { writeByte(REG_NTHR0 + key, nthr); } return getThreshold(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setGuard(uint8_t key=NO_GUARD_KEY) { // TODO add setters for FO/MaxCal instead of clearing here if (key <= AVE_KEY_MAX || key == NO_GUARD_KEY) { writeByte(REG_GUARD, (0x0f) & key); } return (0x0f) & readByte(REG_GUARD); } //-------------------------------------------------------------------------------- bool AT42QT1070::reset() { // write a non-zero value to the reset register return writeByte(REG_RESET, 0xff); } //-------------------------------------------------------------------------------- bool AT42QT1070::calibrate() { // write a non-zero value to the calibrate register return writeByte(REG_CALIBRATE, 0xff); }
28.939394
82
0.500942
apadin1
5c7f01471c4e4eddbeff7cc9d5213d0319069cd2
1,443
hh
C++
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
null
null
null
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ // file RealFunction.hh //-------------------------------------------------------------- #ifndef XRAD__File_RealFunction_cc #define XRAD__File_RealFunction_cc //-------------------------------------------------------------- #include "UniversalInterpolation.h" XRAD_BEGIN //-------------------------------------------------------------- // // Интерполяция // //-------------------------------------------------------------- template<XRAD__RealFunction_template> auto RealFunction<XRAD__RealFunction_template_args>::in(double x) const -> floating64_type<value_type> { interpolators::icubic.ApplyOffsetCorrection(x); const FilterKernelReal *filter = interpolators::icubic.GetNeededFilter(x); return filter->Apply((*this), integral_part(x)); } template<XRAD__RealFunction_template> auto RealFunction<XRAD__RealFunction_template_args>::d_dx(double x) const -> floating64_type<value_type> { interpolators::sinc_derivative.ApplyOffsetCorrection(x); const FilterKernelReal *filter = interpolators::sinc_derivative.GetNeededFilter(x); return filter->Apply((*this), integral_part(x)); } //-------------------------------------------------------------- XRAD_END //-------------------------------------------------------------- #endif // XRAD__File_RealFunction_cc
32.795455
104
0.586279
n-kulberg
5c8205a2eaadae8a73b6b9947801857862681897
11,036
hpp
C++
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
3
2015-03-31T23:09:12.000Z
2017-05-17T07:23:53.000Z
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
null
null
null
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
2
2015-11-06T20:29:49.000Z
2021-09-07T11:08:08.000Z
/** * Reactive * * (c) 2012-2014 Axel Etcheverry * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #pragma once #include <limits> #include <string> #include <inttypes.h> #include <reactive/json/func.hpp> namespace reactive { namespace json { template <typename Iter> class parser { protected: Iter m_cur; Iter m_end; int m_last_ch; bool m_ungot; int m_line; public: parser(const Iter& first_, const Iter& last_) : m_cur(first_), m_end(last_), m_last_ch(-1), m_ungot(false), m_line(1) { } int getc() { if (m_ungot) { m_ungot = false; return m_last_ch; } if (m_cur == m_end) { m_last_ch = -1; return -1; } if (m_last_ch == '\n') { m_line++; } m_last_ch = *m_cur & 0xff; ++m_cur; return m_last_ch; } void ungetc() { if (m_last_ch != -1) { JSON_ASSERT(!m_ungot); m_ungot = true; } } inline Iter cur() const { return m_cur; } inline int line() const { return m_line; } void skipWs() { while (1) { int ch = getc(); if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { ungetc(); break; } } } bool expect(int expect_) { skipWs(); if (getc() != expect_) { ungetc(); return false; } return true; } bool match(const std::string& pattern_) { for (std::string::const_iterator pi(pattern_.begin()); pi != pattern_.end(); ++pi) { if (getc() != *pi) { ungetc(); return false; } } return true; } }; template<typename Iter> inline int _parse_quadhex(parser<Iter> &in_) { int uni_ch = 0, hex; for (int i = 0; i < 4; i++) { if ((hex = in_.getc()) == -1) { return -1; } if ('0' <= hex && hex <= '9') { hex -= '0'; } else if ('A' <= hex && hex <= 'F') { hex -= 'A' - 0xa; } else if ('a' <= hex && hex <= 'f') { hex -= 'a' - 0xa; } else { in_.ungetc(); return -1; } uni_ch = uni_ch * 16 + hex; } return uni_ch; } template<typename String, typename Iter> inline bool _parse_codepoint(String& out, parser<Iter>& in) { int uni_ch; if ((uni_ch = _parse_quadhex(in)) == -1) { return false; } if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { if (0xdc00 <= uni_ch) { // a second 16-bit of a surrogate pair appeared return false; } // first 16-bit of surrogate pair, get the next one if (in.getc() != '\\' || in.getc() != 'u') { in.ungetc(); return false; } int second = _parse_quadhex(in); if (!(0xdc00 <= second && second <= 0xdfff)) { return false; } uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); uni_ch += 0x10000; } if (uni_ch < 0x80) { out.push_back(uni_ch); } else { if (uni_ch < 0x800) { out.push_back(0xc0 | (uni_ch >> 6)); } else { if (uni_ch < 0x10000) { out.push_back(0xe0 | (uni_ch >> 12)); } else { out.push_back(0xf0 | (uni_ch >> 18)); out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); } out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); } out.push_back(0x80 | (uni_ch & 0x3f)); } return true; } template<typename String, typename Iter> inline bool _parse_string(String& out, parser<Iter>& in) { while (1) { int ch = in.getc(); if (ch < ' ') { in.ungetc(); return false; } else if (ch == '"') { return true; } else if (ch == '\\') { if ((ch = in.getc()) == -1) { return false; } switch (ch) { #define MAP(sym, val) case sym: out.push_back(val); break MAP('"', '\"'); MAP('\\', '\\'); MAP('/', '/'); MAP('b', '\b'); MAP('f', '\f'); MAP('n', '\n'); MAP('r', '\r'); MAP('t', '\t'); #undef MAP case 'u': if (!_parse_codepoint(out, in)) { return false; } break; default: return false; } } else { out.push_back(ch); } } return false; } template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, parser<Iter>& in) { if (!ctx.parseArrayStart()) { return false; } std::size_t idx = 0; if (in.expect(']')) { return ctx.parseArrayStop(idx); } do { if (!ctx.parseArrayItem(in, idx)) { return false; } idx++; } while (in.expect(',')); return in.expect(']') && ctx.parseArrayStop(idx); } template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, parser<Iter>& in) { if (!ctx.parseObjectStart()) { return false; } if (in.expect('}')) { return true; } do { std::string key; if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) { return false; } if (!ctx.parseObjectItem(in, key)) { return false; } } while (in.expect(',')); return in.expect('}'); } template <typename Iter> inline std::string _parse_number(parser<Iter>& in) { std::string num_str; while (1) { int ch = in.getc(); if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') { num_str.push_back(ch); } else if (ch == '.') { num_str.push_back('.'); } else { in.ungetc(); break; } } return num_str; } template <typename Context, typename Iter> inline bool _parse(Context& ctx, parser<Iter>& in) { in.skipWs(); int ch = in.getc(); switch (ch) { #define IS(ch, text, op) case ch: \ if (in.match(text) && op) \ { \ return true; \ } \ else \ { \ return false; \ } IS('n', "ull", ctx.setNull()); IS('f', "alse", ctx.setBool(false)); IS('t', "rue", ctx.setBool(true)); #undef IS case '"': return ctx.parseString(in); case '[': return _parse_array(ctx, in); case '{': return _parse_object(ctx, in); default: if (('0' <= ch && ch <= '9') || ch == '-') { double f; char *endp; in.ungetc(); std::string num_str = _parse_number(in); if (num_str.empty()) { return false; } { errno = 0; intmax_t ival = strtoimax(num_str.c_str(), &endp, 10); if ( (errno == 0) && (std::numeric_limits<int64_t>::min() <= ival) && (ival <= std::numeric_limits<int64_t>::max()) && (endp == (num_str.c_str() + num_str.size())) ) { ctx.setInt64(ival); return true; } } f = strtod(num_str.c_str(), &endp); if (endp == (num_str.c_str() + num_str.size())) { ctx.setNumber(f); return true; } return false; } break; } in.ungetc(); return false; } template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { parser<Iter> in(first, last); if (!_parse(ctx, in) && err != NULL) { char buf[64]; snprintf(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); *err = buf; while (1) { int ch = in.getc(); if (ch == -1 || ch == '\n') { break; } else if (ch >= ' ') { err->push_back(ch); } } } return in.cur(); } } // end of json namespace } // end of reactive namespace
23.682403
94
0.339888
ReactiveFramework
5c8af8e5c95364b69a355d9d39cc1ac9ee93bd89
6,391
cpp
C++
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
/* AudioOutputFilterBiquad Implements a Biquad filter Copyright (C) 2012 Nigel Redmon Copyright (C) 2021 William Bérubé 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/>. */ #include <Arduino.h> #include "AudioOutputFilterBiquad.h" AudioOutputFilterBiquad::AudioOutputFilterBiquad(AudioOutput *sink) { this->sink = sink; type = bq_type_lowpass; a0 = 1.0; a1 = a2 = b1 = b2 = 0.0; Fc = 0.50; Q = 0.707; peakGain = 0.0; z1 = z2 = 0.0; } AudioOutputFilterBiquad::AudioOutputFilterBiquad(int type, float Fc, float Q, float peakGain, AudioOutput *sink) { this->sink = sink; SetBiquad(type, Fc, Q, peakGain); z1 = z2 = 0.0; } AudioOutputFilterBiquad::~AudioOutputFilterBiquad() {} bool AudioOutputFilterBiquad::SetRate(int hz) { return sink->SetRate(hz); } bool AudioOutputFilterBiquad::SetBitsPerSample(int bits) { return sink->SetBitsPerSample(bits); } bool AudioOutputFilterBiquad::SetChannels(int channels) { return sink->SetChannels(channels); } bool AudioOutputFilterBiquad::SetGain(float gain) { return sink->SetGain(gain); } void AudioOutputFilterBiquad::SetType(int type) { this->type = type; CalcBiquad(); } void AudioOutputFilterBiquad::SetFc(float Fc) { this->Fc = Fc; CalcBiquad(); } void AudioOutputFilterBiquad::SetQ(float Q) { this->Q = Q; CalcBiquad(); } void AudioOutputFilterBiquad::SetPeakGain(float peakGain) { this->peakGain = peakGain; CalcBiquad(); } void AudioOutputFilterBiquad::SetBiquad(int type, float Fc, float Q, float peakGain) { this->type = type; this->Fc = Fc; this->Q = Q; this->peakGain = peakGain; CalcBiquad(); } void AudioOutputFilterBiquad::CalcBiquad() { float norm; float V = pow(10, fabs(peakGain) / 20.0); float K = tan(M_PI * Fc); switch (this->type) { case bq_type_lowpass: norm = 1 / (1 + K / Q + K * K); a0 = K * K * norm; a1 = 2 * a0; a2 = a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_highpass: norm = 1 / (1 + K / Q + K * K); a0 = 1 * norm; a1 = -2 * a0; a2 = a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_bandpass: norm = 1 / (1 + K / Q + K * K); a0 = K / Q * norm; a1 = 0; a2 = -a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_notch: norm = 1 / (1 + K / Q + K * K); a0 = (1 + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = a0; b1 = a1; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_peak: if (peakGain >= 0) { // boost norm = 1 / (1 + 1/Q * K + K * K); a0 = (1 + V/Q * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - V/Q * K + K * K) * norm; b1 = a1; b2 = (1 - 1/Q * K + K * K) * norm; } else { // cut norm = 1 / (1 + V/Q * K + K * K); a0 = (1 + 1/Q * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - 1/Q * K + K * K) * norm; b1 = a1; b2 = (1 - V/Q * K + K * K) * norm; } break; case bq_type_lowshelf: if (peakGain >= 0) { // boost norm = 1 / (1 + sqrt(2) * K + K * K); a0 = (1 + sqrt(2*V) * K + V * K * K) * norm; a1 = 2 * (V * K * K - 1) * norm; a2 = (1 - sqrt(2*V) * K + V * K * K) * norm; b1 = 2 * (K * K - 1) * norm; b2 = (1 - sqrt(2) * K + K * K) * norm; } else { // cut norm = 1 / (1 + sqrt(2*V) * K + V * K * K); a0 = (1 + sqrt(2) * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - sqrt(2) * K + K * K) * norm; b1 = 2 * (V * K * K - 1) * norm; b2 = (1 - sqrt(2*V) * K + V * K * K) * norm; } break; case bq_type_highshelf: if (peakGain >= 0) { // boost norm = 1 / (1 + sqrt(2) * K + K * K); a0 = (V + sqrt(2*V) * K + K * K) * norm; a1 = 2 * (K * K - V) * norm; a2 = (V - sqrt(2*V) * K + K * K) * norm; b1 = 2 * (K * K - 1) * norm; b2 = (1 - sqrt(2) * K + K * K) * norm; } else { // cut norm = 1 / (V + sqrt(2*V) * K + K * K); a0 = (1 + sqrt(2) * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - sqrt(2) * K + K * K) * norm; b1 = 2 * (K * K - V) * norm; b2 = (V - sqrt(2*V) * K + K * K) * norm; } break; } i_a0 = a0 * BQ_DECAL; i_a1 = a1 * BQ_DECAL; i_a2 = a2 * BQ_DECAL; i_b1 = b1 * BQ_DECAL; i_b2 = b2 * BQ_DECAL; i_lz1 = i_rz1 = z1 * BQ_DECAL; i_lz2 = i_rz2 = z2 * BQ_DECAL; i_Fc = Fc * BQ_DECAL; i_Q = Q * BQ_DECAL; i_peakGain = peakGain * BQ_DECAL; } bool AudioOutputFilterBiquad::begin() { return sink->begin(); } bool AudioOutputFilterBiquad::ConsumeSample(int16_t sample[2]) { int32_t leftSample = (sample[LEFTCHANNEL] << BQ_SHIFT) / 2; int32_t rightSample = (sample[RIGHTCHANNEL] << BQ_SHIFT) / 2; int64_t leftOutput = ((leftSample * i_a0) >> BQ_SHIFT) + i_lz1; i_lz1 = ((leftSample * i_a1) >> BQ_SHIFT) + i_lz2 - ((i_b1 * leftOutput) >> BQ_SHIFT); i_lz2 = ((leftSample * i_a2) >> BQ_SHIFT) - ((i_b2 * leftOutput) >> BQ_SHIFT); int64_t rightOutput = ((rightSample * i_a0) >> BQ_SHIFT) + i_rz1; i_rz1 = ((rightSample * i_a1) >> BQ_SHIFT) + i_rz2 - ((i_b1 * rightOutput) >> BQ_SHIFT); i_rz2 = ((rightSample * i_a2) >> BQ_SHIFT) - ((i_b2 * rightOutput) >> BQ_SHIFT); int16_t out[2]; out[LEFTCHANNEL] = (int16_t)(leftOutput >> BQ_SHIFT); out[RIGHTCHANNEL] = (int16_t)(rightOutput >> BQ_SHIFT); return sink->ConsumeSample(out); } bool AudioOutputFilterBiquad::stop() { return sink->stop(); }
25.979675
112
0.531216
ChSt98
5c8c9e8e71dc7e6470f831d96531d1c2f58990d0
493
cpp
C++
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
1
2020-07-05T06:30:32.000Z
2020-07-05T06:30:32.000Z
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
null
null
null
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <unordered_set> using namespace std; string longestSubstring(string s) { unordered_set<int> elements; string out = ""; for (int i = 0; i < s.length(); i++) { if (elements.find(s[i]) == elements.end()) { elements.insert(s[i]); out += s[i]; } } return out; } int main() { string s = "aababcda"; string ans = longestSubstring(s); cout << ans; }
17.607143
50
0.545639
gulatigaurav
5c8d79e38b1f1ef107ff8d6f5f75a83f37d1eab8
635
cpp
C++
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/recursive-digit-sum/problem // Jordan Tonni #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; int superDigit(string str) { if(str.length() <= 1) return std::stoi(str); int sd = 0; for(const auto c : str) sd += c - '0'; return superDigit(to_string(sd)); } int main() { string n, p; int k; cin >> n >> k; if(k % 10 != 0){ while(k--) p += n; } else p += n; cout << superDigit(p); return 0; }
15.119048
68
0.525984
jordantonni
5c9bc277b1e705ee679b8e4911895c3e545b7f16
448
cpp
C++
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Ehab and another construction problem #include <stdio.h> int main(){ int x; scanf("%d\n", &x); bool found = false; for (int b = x; b > 0; --b){ for (int a = b; !found && a > 0; --a){ if (b % a == 0 && a * b > x && a / b < x){ printf("%d %d\n", a, b); found = true; break; } } } if (!found) printf("-1\n"); return 0; }
16.592593
54
0.368304
sgrade
5c9f3244ed7d678a5693bbf38ff79d7d5ff02087
503
hpp
C++
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
43
2016-08-02T19:50:34.000Z
2022-01-29T01:33:35.000Z
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
232
2016-08-05T07:57:59.000Z
2022-03-31T01:50:23.000Z
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
41
2016-08-03T19:16:40.000Z
2022-01-24T19:11:29.000Z
class CfgWaypoints { class Teamwork { class Fortify { displayName = "Fortify"; file = "\x\tmf\addons\AI\functions\fnc_fortify.sqf"; /* 0: GROUP 1: ARRAY - Waypoint position 2: OBJECT - Target to which waypoint is attached to */ icon = "a3\ui_f\data\igui\cfg\simpletasks\types\defend_ca.paa"; class Attributes { }; }; }; };
23.952381
75
0.459245
Drofseh
5cab68a0049564f99d1ea69987754f7b088a621e
3,722
cpp
C++
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
#include <iostream> # include <cmath> int factorial(int x){ if(x<=1){ return 1; } else{ return factorial(x-1)*x; } } double binomial(int n, int k){ if(k==0 || n==k){ return -1; } else{ return factorial(n)/(factorial(k)*(factorial (n-k))); } } double mileToKilometer(){ double mile; std::cout<<"Geben Sie die Meilen an!\n"; std::cin >> mile; double kilometer; kilometer = mile * 1.6 ; std::cout << "Kilometer sind " << kilometer << std::endl; return kilometer; } bool is_prime(){ int x; std::cout<<"Geben Sie eine ganze Zahl ein!\n"; std::cin >> x; int i=2; while (i<x){ if(x % i == 0){ std::cout << "Zahl ist nicht prim!\n "; return false; } else{ ++i; } std::cout << "Zahl ist prim!\n "; return true; } } double surface(){ double radius; double hight; std::cout<<"Geben Sie den Radius an!\n"; std::cin >> radius; std::cout<<"Geben Sie die Höhe an!\n"; std::cin >> hight; double surface; surface = 2 * M_PI * radius + (radius + hight); std::cout << "Oberfläche betraegt " << surface << std::endl; return surface; } double capacity(){ double radius; double hight; std::cout<<"Geben Sie den Radius an!\n"; std::cin >> radius; std::cout<<"Geben Sie die Höhe an!\n"; std::cin >> hight; double capacity; capacity = M_PI * pow(radius,2) * hight; std::cout << "Volumen betraegt " << capacity << std::endl; return capacity; } int checksum (){ int a; std::cout << "Geben Sie eine Zahl ein!\n "; std::cin >> a; int checksum=0; while (a>0){ checksum += a%10; a/=10; } std::cout <<" Quersumme ist " << checksum << std::endl; return checksum; } int gcd(){ int p; std::cout<<"Geben sie eine ganze Zahl ein!\n"; std::cin >> p ; int q; std::cout<<"Geben sie eine ganze Zahl ein!\n"; std::cin >> q ; int r = 0; while (q != 0){ r= p % q; p = q; q = r; } std::cout << "Der ggT ist " << p << std::endl; } long int aufgabe1_10() { long int sumMultiples = 0; long int x=0; while (x<=1000) { if(x % 3 ==0 || x % 5 == 0){ sumMultiples += x; } ++x; } std::cout << "Zahl ist " << sumMultiples << std::endl; return sumMultiples; } long int aufgabe1_3() { long int zahl = 20; long int x=1; while(x<=20) { if(zahl % x != 0) { zahl += 20; // zahl = zahl + 20; x=0; } ++x; } std::cout << "Zahl ist " << zahl << std::endl; return zahl; } int main() { std::cout << "Hello, World!\n"; aufgabe1_3(); aufgabe1_10(); checksum(); gcd(); capacity(); surface(); is_prime(); std::cout<<"Geben sie eine ganze Zahl ein!\n"; int x; std::cin >> x; if(x<=0){ std::cout<<"X muss größer 0 sein\n"; } else{ std::cout<<"Die Zahl ist"<< factorial(x)<<std::endl; } std::cout<<"Geben sie eine n und k ein!\n" ; int n; int k; std::cin >> n >> k; if(n<k){ std::cout<<"n muss größer k sein!"; } else{ std::cout << "Binomialkoeffizient ist " << binomial << std::endl; } return 0; }
18.334975
73
0.448684
LS060598
5cb0851f56d134d2cf19e6c4cccc526a8b8bec94
8,353
cpp
C++
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
1
2021-08-20T06:44:10.000Z
2021-08-20T06:44:10.000Z
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
4
2017-03-27T17:55:29.000Z
2018-01-29T22:51:40.000Z
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
1
2021-08-20T06:44:10.000Z
2021-08-20T06:44:10.000Z
#include "FileManager.hpp" #include "parser/RmdParser.hpp" #include "PreviewData.hpp" #include "common/RC2Utils.hpp" #include "common/FormattedException.hpp" #include <cassert> #include <algorithm> #include <RInside.h> #include <boost/algorithm/string/trim.hpp> #include <boost/bind.hpp> #include <sstream> #include "Errors.hpp" #include "RC2Logging.h" #include <nlohmann/json.hpp> #include "vendor/cpp-base64/base64.h" /* * 1. if the source file hasn't changed, nothing to do. Note if data files have changed, need to update any chunks that refer to them * 2. reparse source file * 3. figure out which chunks need updating * 4. execute the code * 5. create cache entry * 6. return results for chunk */ using std::unique_ptr; using std::endl; using json = nlohmann::json; //void handleFileChange(PreviewData *data, bool isSpaceOrTab ( char c ) { return c == 32 || c == 9; } namespace RC2 { RC2::PreviewData::PreviewData ( int pid, FileManager* fmanager, FileInfo& finfo, EnvironmentWatcher* globalEnv, PreviewDelegate *delegate ) : previewId ( pid ), fileManager ( fmanager ), fileInfo ( finfo ), delegate_( delegate ), previewEnv ( globalEnv ) { long fid = fileInfo.id; fileManager->addChangeListener ( fid, boost::bind ( &PreviewData::fileChanged, this, fid, ALL ), &fileConnection ); } RC2::PreviewData::~PreviewData() { // FIXME: is this a memory leak? // fileConnection->disconnect(); } void RC2::PreviewData::update ( FileInfo& updatedInfo, string& updateIdent, int targetChunkId, bool includePrevious ) { assert ( updatedInfo.id == fileInfo.id ); currentUpdateIdentifier_ = updateIdent; LOG_INFO << "got update request ident:" << updateIdent; fileInfo = updatedInfo; string contents = SlurpFile ( fileInfo.name.c_str() ); currentChunks_ = parser.parseRmdSource ( contents ); bool usePrevious = includePrevious; int targetId = targetChunkId; // if target is less than zero, execute all chunks if ( targetId < 0) { targetId = currentChunks_.size() - 1; usePrevious = true; } auto chunks2Update = whichChunksNeedUpdate ( targetId, usePrevious ); // send update started message nlohmann::json results; results["msg"] = "previewUpdateStarted"; results["updateIdentifier"] = currentUpdateIdentifier_; results["activeChunks"] = chunks2Update; results["previewId"] = previewId; delegate_->sendPreviewJson(results.dump()); // start execution executeChunks ( chunks2Update ); currentUpdateIdentifier_ = ""; } void RC2::PreviewData::fileChanged ( long changedId, ChangeType type ) { LOG_INFO << "fileChanged called:" << changedId << endl; } void RC2::PreviewData::executeChunks ( vector<int> chunksToUpdate ) { // 1. create cache entry- // 2. evaluate // 3. turn results into json // 4. send results LOG_INFO << "executing " << chunksToUpdate.size() << " chunks"; // TODO: handle exceptions for ( auto idx: chunksToUpdate ) { Chunk* aChunk = currentChunks_[idx]; if ( aChunk->type() == markdown ) continue; // TODO: handle inline code chunks auto cacheEntry = chunkMap[idx].get(); auto oldCrc = cacheEntry->crc; try { LOG_INFO << "executing " << aChunk->content() << std::endl; executeChunk ( aChunk, cacheEntry ); nlohmann::json results; results["msg"] = "previewUpdated"; results["chunkId"] = idx; results["updateIdentifier"] = currentUpdateIdentifier_; results["previewId"] = previewId; results["content"] = cacheEntry->lastOutput; results["complete"] = false; string str = results.dump(2); delegate_->sendPreviewJson(str); } catch ( GenericException& e ) { LOG_INFO << "generic exception: " << e.code(); } } json finalResults; finalResults["chunkId"] = -1; finalResults["msg"] = "previewUpdated"; finalResults["updateIdentifier"] = currentUpdateIdentifier_; finalResults["previewId"] = previewId; finalResults["complete"] = true; finalResults["content"] = ""; delegate_->sendPreviewJson(finalResults.dump(2)); } string RC2::PreviewData::executeChunk ( Chunk* chunk, ChunkCacheEntry* cacheEntry ) { SEXP answer; Rcpp::Environment env; // TODO: use environment from cacheEntry previewEnv.captureEnvironment(); previewEnv.getEnvironment ( env ); string userCode = chunk->innerContent(); boost::algorithm::trim_if ( userCode, &isSpaceOrTab ); env.assign ( "rc2.code", userCode ); env.assign ( "rc2.env", env ); // watch for files fileManager->resetWatch(); string code = "rc2.evaluateCode(rc2.code, parent = rc2.env)"; try { delegate_->executePreviewCode(code, answer, &env); } catch (const RException& e) { LOG_INFO << "preview query failed:" << e.getCode(); return ""; // FIXME: should get error message from sexp, use that as what() } catch (const std::exception& e) { LOG_WARNING << "error executing code"; } env.remove("rc2.code"); env.remove("rc2.env"); env.remove("allItems"); // should have been removed by R package. wasn't for some reason if ( (answer == nullptr) || Rf_isVector(answer) == FALSE) { Rcpp::StringVector emsg = Rcpp::as<Rcpp::StringVector>(answer); LOG_INFO << "type=" << TYPEOF(answer) << " error; " << emsg[0]; throw GenericException ( "query failed", kError_QueryFailed ); } std::stringstream outStr; Rcpp::List results ( answer ); for ( auto itr = results.begin(); itr != results.end(); ++itr ) { Rcpp::List curList ( *itr ); string elType = curList.attr ( "class" ); if ( elType == "rc2src" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["src"] ) ); outStr << "<div style=\"rc2-preview-src\">" << strs[0] << "</div>" << endl; } else if ( elType == "rc2value" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["str"] ) ); outStr << "<div style=\"rc2-preview-out\">" << strs[0] << "</div>" << endl; } else if ( elType == "rc2err" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["message"] ) ); Rcpp::StringVector calls ( Rcpp::as<Rcpp::StringVector> ( curList["call"] ) ); outStr << "<div style=\"rc2-error\">" << strs[0] << "(location: " << calls[0] << ")</div>" << endl; } else if ( elType == "rc2plot") { BinaryData imgData; Rcpp::StringVector names ( Rcpp::as<Rcpp::StringVector> ( curList["fname"] ) ); string fname(names[0]); SlurpBinaryFile(fname, imgData); string encodedStr = base64_encode((unsigned char*)imgData.data.get(), imgData.getSize(), false); outStr << "<div style=\"rc2-plot\"><img src=\"data:image/png;base64," << encodedStr << "\"></div>" << endl; } else { LOG_INFO << "unsupported ype returned from evaluate: " << elType; } } auto output = outStr.str(); cacheEntry->cacheOutput(output); cacheEntry->crc = cacheEntry->generateCRC(); return output; } void RC2::PreviewData::checkCache() { EnvironmentWatcher* parent = &previewEnv; for ( int i=0; i < currentChunks().size(); ++i ) { if ( chunkMap.count ( i ) > 0 ) continue; chunkMap[i] = std::make_unique<ChunkCacheEntry> ( i, parent ); parent = &chunkMap[i]->envWatcher; } } vector<int> RC2::PreviewData::whichChunksNeedUpdate ( int targetChunkId, bool includePrevious ) { // TODO: implement more intelligent checking vector<int> toExecute; int startIndex = targetChunkId; // if the number of chunks changed, we'll invalidate everything for now // TODO: use the ChunkCacheEntry(s) to determine if the cache can be used if ( currentChunks_.size() != chunkMap.size() ) { chunkMap.clear(); // insert new cache entries checkCache(); } if ( includePrevious ) { startIndex = 0; } else { // adjust targetId if any previous chunks need to be executed for ( int i = startIndex - 1; i >= 0; --i ) { // TODO: to support inline chunks, need to see if mdown chunk has inline code and if the cache of it is empty auto centry = chunkMap[i].get(); auto chunk = currentChunks_[i]; if ( chunk->type() == code && !centry->outputCached ) { startIndex = i; } } } for ( int i=startIndex; i <= targetChunkId; ++i ) { auto chunk = currentChunks_[i]; // include all markdowns, will ignore ones with no inline code chunks if ( chunk->type() == code ) { toExecute.push_back ( i ); } else if ( chunk->type() == markdown ) { auto mchunk = dynamic_cast<MarkdownChunk*> ( chunk ); if ( mchunk == nullptr || mchunk->inlineChunkCount() < 1 ) { continue; } toExecute.push_back ( i ); } } return toExecute; } }; //end namespace
35.696581
140
0.681552
rc2server
5cb2d65e6986f1bcc82f1b380e6d8c103ad389c4
4,917
cpp
C++
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
2
2022-01-22T10:02:07.000Z
2022-02-16T19:30:17.000Z
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
null
null
null
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
null
null
null
#include "odom.hpp" using std::placeholders::_1; SimpleOdom::SimpleOdom() : Node{"odom_node"} { // get params std::string imu_topic = "INSERT IMU TOPIC"; std::string dvl_topic = "INSERT DVL TOPIC"; std::string odom_topic = "INSERT ESTIMATED ODOMETRY TOPIC"; std::string mocap_topic; std::string imu_link; std::string dvl_link; //if (!nh.getParam("simple_odom/imu_topic", imu_topic)) // imu_topic = "/auv/imu"; //if (!nh.getParam("simple_odom/dvl_topic", dvl_topic)) // dvl_topic = "/auv/odom"; //if (!nh.getParam("simple_odom/mocap_topic", mocap_topic)) // mocap_topic = "/qualisys/Body_1/pose"; //if (!nh.getParam("simple_odom/odom_topic", odom_topic)) // odom_topic = "/odometry/filtered"; //if (!nh.getParam("simple_odom/imu_link", imu_link)) // imu_link = "imu_0"; //if (!nh.getParam("simple_odom/dvl_link", dvl_link)) // dvl_link = "dvl_link"; //if (!nh.getParam("simple_odom/publish_rate", update_rate)) // update_rate = 20; // set up IMU and DVL transforms tf2_ros::Buffer tf_buffer(); tf2_ros::TransformListener tf_listener(tf_buffer); double timeout = 10; // seconds to wait for transforms to become available RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Waiting for IMU and DVL transforms.."); geometry_msgs::msg::TransformStamped imu_transform = tf_buffer.lookupTransform("base_link", imu_link, rclcpp::Time(0), rclcpp::Duration(timeout)); //rclcpp::Time is forced to wall time and is not recommended for general use. geometry_msgs::msg::TransformStamped dvl_transform = tf_buffer.lookupTransform("base_link", dvl_link, rclcpp::Time(0), rclcpp::Duration(timeout)); tf2::fromMsg(imu_transform.transform.rotation, imu_rotation); tf2::fromMsg(dvl_transform.transform.rotation, dvl_rotation); tf2::fromMsg(dvl_transform.transform.translation, dvl_translation); // subscribers and publishers auto imu_sub = node->create_subscription<sensor_msgs::msg::Imu>(imu_topic, 1, std::bind(&SimpleOdom::imuCallback, this, _1)); auto dvl_sub = node->create_subscription<geometry_msgs::msg::TwistWithCovarianceStamped>(dvl_topic, 1, std::bind(&SimpleOdom::dvlCallback, this, _1)); auto mocap_sub = node->create_subscription<geometry_msgs::msg::PoseStamped>(mocap_topic, 1, std::bind(&SimpleOdom::mocapCallback, this, _1)); auto odom_pub = node->create_publisher<nav_msgs::msg::Odometry>(odom_topic, 1); //imu_sub = nh.subscribe(imu_topic, 1, &SimpleOdom::imuCallback, this); //dvl_sub = nh.subscribe(dvl_topic, 1, &SimpleOdom::dvlCallback, this); //mocap_sub = nh.subscribe(mocap_topic, 1, &SimpleOdom::mocapCallback, this); //odom_pub = nh.advertise<nav_msgs::Odometry>(odom_topic, 1); // wait for first imu, dvl and mocap msg //ROS_INFO("Waiting for initial IMU, DVL and MOCAP msgs.."); //ros::topic::waitForMessage<sensor_msgs::Imu>(imu_topic, nh); //ros::topic::waitForMessage<geometry_msgs::TwistWithCovarianceStamped>(dvl_topic, nh); //ros::topic::waitForMessage<geometry_msgs::PoseStamped>(mocap_topic, nh); // There is no waitForMessage-equivalent in ROS2, https://answers.ros.org/question/378693/waitformessage-ros2-equivalent/ RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "SimpleOdom initialized"); } void SimpleOdom::spin() { rclcpp::Rate rate(update_rate); while (rclcpp::ok()) { auto node = std::make_shared<SimpleOdom>(); // execute waiting callbacks rclcpp::spin_some(node); // create odom msg nav_msgs::msg::Odometry odometry_msg; odometry_msg.pose.pose.position = tf2::toMsg(position); // Might need to convert this to stamped versions odometry_msg.pose.pose.orientation = tf2::toMsg(orientation); odometry_msg.twist.twist.angular.x = angular_vel[0]; odometry_msg.twist.twist.angular.y = angular_vel[1]; odometry_msg.twist.twist.angular.z = angular_vel[2]; odometry_msg.twist.twist.linear.x = linear_vel[0]; odometry_msg.twist.twist.linear.y = linear_vel[1]; odometry_msg.twist.twist.linear.z = linear_vel[2]; // publish odom_pub->publish(odometry_msg); loop_rate.sleep(); } } void SimpleOdom::imuCallback(const sensor_msgs::msg::Imu& imu_msg) { tf2::Vector3 angular_vel_imu; tf2::fromMsg(imu_msg.angular_velocity, angular_vel_imu); angular_vel = tf2::quatRotate(imu_rotation, angular_vel_imu); } void SimpleOdom::dvlCallback(const geometry_msgs::msg::TwistWithCovarianceStamped& twist_msg) { tf2::Vector3 linear_vel_dvl, linear_vel_uncorrected; tf2::fromMsg(twist_msg.twist.twist.linear, linear_vel_dvl); linear_vel_uncorrected = tf2::quatRotate(dvl_rotation, linear_vel_dvl); // compensate for translation of DVL linear_vel = linear_vel_uncorrected + angular_vel.cross(dvl_translation); // from fossen2021 eq 14.3 } void SimpleOdom::mocapCallback(const geometry_msgs::msg::PoseStamped& msg) { tf2::fromMsg(msg.pose.position, position); tf2::fromMsg(msg.pose.orientation, orientation); }
43.513274
226
0.736221
bjornrho
5cbae0a72d1758e5044bdca6d3541255440b565e
4,619
cpp
C++
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
#include "VesselBuilder1.h" #include "DialogControl.h" #include "VariableDragManager.h" #include "AnimationManager.h" #define LogV(x,...) VB1->Log->Log(x,##__VA_ARGS__) VariableDragManager::VariableDragManager(VesselBuilder1* _VB1) { VB1 = _VB1; vard_def.clear(); return; } VariableDragManager::~VariableDragManager() { VB1 = NULL; return; } void VariableDragManager::AddUndefinedVardDef() { VARD_DEF vd = VARD_DEF(); vd.defined = false; UINT index = vard_def.size(); char nbuf[256] = { '\0' }; sprintf(nbuf, "VariableDrag_%i", index); vd.name.assign(nbuf); vard_def.push_back(vd); return; } UINT VariableDragManager::AddVardDef(string name, UINT anim_idx, double factor, VECTOR3 ref) { VARD_DEF vd = VARD_DEF(); vd.name = name; vd.ref = ref; vd.factor = factor; vd.anim_idx = anim_idx; vd.defined = true; UINT index = vard_def.size(); vard_def.push_back(vd); DefineVarDef(index); return index; } void VariableDragManager::DefineVarDef(def_idx d_idx) { double *state_ptr = VB1->AnimMng->GetAnimStatePtr(vard_def[d_idx].anim_idx); VB1->CreateVariableDragElement(state_ptr, vard_def[d_idx].factor, vard_def[d_idx].ref); // LogV("state pointer value:%.3f", *state_ptr); vard_def[d_idx].defined = true; return; } void VariableDragManager::DefineAll() { for (UINT i = 0; i < GetVardDefCount(); i++) { if (IsVardDefDefined(i)) { DefineVarDef(i); } } return; } void VariableDragManager::UnDefineVardDef(def_idx d_idx) { vard_def[d_idx].defined = false; VB1->ClearVariableDragElements(); DefineAll(); return; } void VariableDragManager::DeleteVarDef(def_idx d_idx) { vard_def.erase(vard_def.begin() + d_idx); VB1->ClearVariableDragElements(); DefineAll(); return; } string VariableDragManager::GetVardName(def_idx d_idx) { return vard_def[d_idx].name; } void VariableDragManager::SetVardName(def_idx d_idx, string newname) { vard_def[d_idx].name = newname; return; } UINT VariableDragManager::GetVardDefCount() { return vard_def.size(); } void VariableDragManager::Clear() { vard_def.clear(); VB1->ClearVariableDragElements(); return; } void VariableDragManager::GetVardParams(def_idx d_idx, double &factor, VECTOR3 &ref, UINT &anim_idx) { factor = vard_def[d_idx].factor; ref = vard_def[d_idx].ref; anim_idx = vard_def[d_idx].anim_idx; return; } void VariableDragManager::SetVardParams(def_idx d_idx, double factor, VECTOR3 ref, UINT anim_index) { vard_def[d_idx].factor = factor; vard_def[d_idx].ref = ref; vard_def[d_idx].anim_idx = anim_index; return; } bool VariableDragManager::IsVardDefDefined(def_idx d_idx) { return vard_def[d_idx].defined; } void VariableDragManager::ParseCfgFile(FILEHANDLE fh) { LogV("Parsing Variable Drag Section"); UINT vard_counter = 0; char cbuf[256] = { '\0' }; int id; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); while (oapiReadItem_int(fh, cbuf, id)) { char namebuf[256] = { '\0' }; sprintf(cbuf, "VARIABLEDRAG_%i_NAME", vard_counter); oapiReadItem_string(fh, cbuf, namebuf); string name(namebuf); double factor; int anim_idx; VECTOR3 ref; sprintf(cbuf, "VARIABLEDRAG_%i_FACTOR", vard_counter); oapiReadItem_float(fh, cbuf, factor); sprintf(cbuf, "VARIABLEDRAG_%i_REF", vard_counter); oapiReadItem_vec(fh, cbuf, ref); sprintf(cbuf, "VARIABLEDRAG_%i_ANIM", vard_counter); oapiReadItem_int(fh, cbuf, anim_idx); AddVardDef(name, anim_idx, factor, ref); vard_counter++; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); } LogV("Parsing Variable Drag Section Completed, found %i definitions",vard_counter); return; } void VariableDragManager::WriteCfg(FILEHANDLE fh) { oapiWriteLine(fh, " "); oapiWriteLine(fh, ";<-------------------------VARIABLE DRAG ITEMS DEFINITIONS------------------------->"); oapiWriteLine(fh, " "); UINT vard_counter = 0; for (UINT i = 0; i < GetVardDefCount(); i++) { if (!IsVardDefDefined(i)) { continue; } char cbuf[256] = { '\0' }; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); oapiWriteItem_int(fh, cbuf, vard_counter); sprintf(cbuf, "VARIABLEDRAG_%i_NAME", vard_counter); char namebuf[256] = { '\0' }; sprintf(namebuf, "%s", GetVardName(i).c_str()); oapiWriteItem_string(fh, cbuf, namebuf); double factor; UINT anim_idx; VECTOR3 ref; GetVardParams(i, factor, ref, anim_idx); sprintf(cbuf, "VARIABLEDRAG_%i_FACTOR", vard_counter); oapiWriteItem_float(fh, cbuf, factor); sprintf(cbuf, "VARIABLEDRAG_%i_REF", vard_counter); oapiWriteItem_vec(fh, cbuf, ref); sprintf(cbuf, "VARIABLEDRAG_%i_ANIM", vard_counter); oapiWriteItem_int(fh, cbuf, anim_idx); oapiWriteLine(fh, " "); vard_counter++; } return; }
30.589404
107
0.720935
fredenigma
5cbc08086b52406335f93c7ce9191a7df6735618
1,865
cpp
C++
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
6
2020-10-09T02:48:54.000Z
2021-07-30T06:31:20.000Z
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
#include "TextureCommons.h" #include "VulkanTexture.h" #include "VulkanDevice.h" namespace vku { void createSinglePixelTexture(VulkanDevice* device, unsigned char *pixels, VulkanTexture **texture) { *texture = new VulkanTexture(); VulkanTexture* pixTex = *texture; pixTex->image = new VulkanImage(device, VulkanImageInfo{ .width = 1, .height = 1, .format = VK_FORMAT_R8G8B8A8_UNORM, .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT }); VkDeviceSize imageSize = 1 * 1 * 4; VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; device->createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(*device, stagingBufferMemory, 0, imageSize, 0, &data); memcpy(data, pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(*device, stagingBufferMemory); // create image and load from buffer pixTex->image->loadFromBuffer(stagingBuffer); vkDestroyBuffer(*device, stagingBuffer, nullptr); vkFreeMemory(*device, stagingBufferMemory, nullptr); VulkanImageViewInfo viewInfo{}; pixTex->image->writeImageViewInfo(&viewInfo); pixTex->view = new VulkanImageView(device, viewInfo); pixTex->sampler = new VulkanSampler(device, VulkanSamplerInfo{}); } TextureCommons::TextureCommons(VulkanDevice* device) { // make 1x1 white texture unsigned char white[] = { 0xff,0xff,0xff,0xff }; unsigned char black[] = { 0x00,0x00,0x00,0x00 }; unsigned char norm[] = { 0x00,0x00,0xff,0x00 }; createSinglePixelTexture(device, white, &white1x1); createSinglePixelTexture(device, black, &black1x1); createSinglePixelTexture(device, norm, &zNorm); } TextureCommons::~TextureCommons() { delete white1x1; delete black1x1; delete zNorm; } }
30.57377
102
0.751743
wessles
5cbfb57dbf158fd18afd8345200ef56aa1a67373
141
cpp
C++
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SGame.h" #include "iTweenPCH.h" #include "iTAux.h"
23.5
78
0.751773
ZDron3
5cc264622f7cfd4487387e6b7699b8960507b69c
14,948
cc
C++
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include "test.hh" #include "script_parse.hh" class TestScriptParseCtx : public plux::ScriptParseCtx, public TestSuite { public: TestScriptParseCtx() : plux::ScriptParseCtx(), TestSuite("ScriptParseCtx") { register_test("starts_with", std::bind(&TestScriptParseCtx::test_starts_with, this)); register_test("ends_with", std::bind(&TestScriptParseCtx::test_ends_with, this)); register_test("substr", std::bind(&TestScriptParseCtx::test_substr, this)); } virtual ~TestScriptParseCtx() { } void test_starts_with() { do_test_starts_with("my full line", 0); do_test_starts_with(" my full line", 2); } void do_test_starts_with(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("starts_with, full line", true, starts_with("my full line")); ASSERT_EQUAL("starts_with, prefix", true, starts_with("my ")); ASSERT_EQUAL("starts_with, other prefix", false, starts_with("their")); ASSERT_EQUAL("starts_with, long line", false, starts_with("my full line, long")); } void test_ends_with() { do_test_ends_with("my full line", 0); do_test_ends_with(" my full line", 2); } void do_test_ends_with(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("ends_with, full line", true, ends_with("my full line")); ASSERT_EQUAL("ends_with, suffix", true, ends_with(" line")); ASSERT_EQUAL("ends_with, other suffix", false, ends_with("word")); ASSERT_EQUAL("ends_with, long line", false, ends_with("my full line, long")); } void test_substr() { do_test_substr("my full line", 0); do_test_substr(" my full line", 2); } void do_test_substr(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("substr, full line", "my full line", substr(0, 0)); ASSERT_EQUAL("substr, prefix", "my", substr(0, 10)); ASSERT_EQUAL("substr, suffix", "line", substr(8, 0)); ASSERT_EQUAL("substr, middle", "full", substr(3, 5)); } }; class TestScriptParse : public plux::ScriptParse, public TestSuite { public: TestScriptParse(std::istream* is) : plux::ScriptParse(":memory:", is), TestSuite("ScriptParse") { register_test("next_line", std::bind(&TestScriptParse::test_next_line, this)); register_test("parse", std::bind(&TestScriptParse::test_parse, this)); register_test("parse_function", std::bind(&TestScriptParse::test_parse_function, this)); register_test("parse_header_require", std::bind(&TestScriptParse::test_parse_config, this)); register_test("parse_shell", std::bind(&TestScriptParse::test_parse_shell, this)); register_test("parse_call", std::bind(&TestScriptParse::test_parse_line_call, this)); register_test("parse_line_cmd_output", std::bind(&TestScriptParse::test_parse_line_cmd_output, this)); register_test("parse_line_cmd_error", std::bind(&TestScriptParse::test_parse_line_cmd_error, this)); register_test("parse_line_cmd_match", std::bind(&TestScriptParse::test_parse_line_cmd_match, this)); register_test("parse_line_cmd_global", std::bind(&TestScriptParse::test_parse_line_cmd_global, this)); register_test("parse_line_cmd_local", std::bind(&TestScriptParse::test_parse_line_cmd_local, this)); register_test("parse_line_cmd_timeout", std::bind(&TestScriptParse::test_parse_line_cmd_timeout, this)); register_test("parse_line_cmd_unknown", std::bind(&TestScriptParse::test_parse_line_cmd_unknown, this)); } void test_next_line() { plux::ScriptParseCtx ctx; // ensure that last line (without newline) is parsed std::istringstream is1("last line"); set_is(&is1); ASSERT_EQUAL("last line", true, next_line(ctx)); ASSERT_EQUAL("last line", "last line", ctx.line); ASSERT_EQUAL("last line", false, next_line(ctx)); // parse line with only - on it std::istringstream is2(" -\n !test\n"); set_is(&is2); ASSERT_EQUAL("only -", true, next_line(ctx)); ASSERT_EQUAL("only -", " -", ctx.line); ASSERT_EQUAL("only -", true, next_line(ctx)); ASSERT_EQUAL("only -", " !test", ctx.line); ASSERT_EQUAL("only -", false, next_line(ctx)); // skip blank/empty lines and comments std::istringstream is3("\n \n #test\nlast"); set_is(&is3); ASSERT_EQUAL("skip blank", true, next_line(ctx)); ASSERT_EQUAL("skip blank", "last", ctx.line); ASSERT_EQUAL("skip blank", false, next_line(ctx)); } void test_parse() { // FIXME: script does not start with [doc] // FIXME: not [enddoc] as first [ after [doc] // FIXME: unexpected content in headers // FIXME: unexpected content in shell // FIXME: unexpected content in cleanup // FIXME: verify shell is cleanup after [cleanup] } void test_parse_function() { std::istringstream is1("!echo true\n" "?true\n" "[endfunction]\n"); set_is(&is1); auto line = parse_function(ctx("[function no-args]")); auto fun = dynamic_cast<plux::Function*>(line); ASSERT_EQUAL("no args", true, fun != nullptr); ASSERT_EQUAL("no args", "no-args", fun->name()); ASSERT_EQUAL("no args", 0, fun->num_args()); ASSERT_EQUAL("no args", 2, fun->line_end() - fun->line_begin()); delete line; std::istringstream is2("!echo $arg1 $arg2\n" "[endfunction]\n"); set_is(&is2); line = parse_function(ctx("[function args arg1 arg2]")); fun = dynamic_cast<plux::Function*>(line); ASSERT_EQUAL("args", true, fun != nullptr); ASSERT_EQUAL("args", "args", fun->name()); ASSERT_EQUAL("args", 2, fun->num_args()); ASSERT_EQUAL("args", "arg1", *fun->args_begin()); ASSERT_EQUAL("args", "arg2", *(fun->args_begin() + 1)); ASSERT_EQUAL("args", 1, fun->line_end() - fun->line_begin()); delete line; } void test_parse_config() { auto line = parse_config(ctx("[config require=V1]")); auto hdr = dynamic_cast<plux::HeaderConfigRequire*>(line); ASSERT_EQUAL("var only", true, hdr != nullptr); ASSERT_EQUAL("var only", "V1", hdr->key()); ASSERT_EQUAL("var only", "", hdr->val()); delete line; line = parse_config(ctx("[config require=V1=V2]")); hdr = dynamic_cast<plux::HeaderConfigRequire*>(line); ASSERT_EQUAL("var only", true, hdr != nullptr); ASSERT_EQUAL("var only", "V1", hdr->key()); ASSERT_EQUAL("var only", "V2", hdr->val()); delete line; } void test_parse_shell() { std::string name; ASSERT_EQUAL("valid", true, parse_shell(ctx("[shell test]"), name)); ASSERT_EQUAL("valid", std::string("test"), name); ASSERT_EQUAL("valid with offset", true, parse_shell(ctx("[shell with-dash]"), name)); ASSERT_EQUAL("valid with offset", "with-dash", name); try { parse_shell(ctx("[shell missing-end"), name); ASSERT_EQUAL("missing end", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("missing end", "shell command does not end with ]", ex.error()); } try { parse_shell(ctx("[shell invalid/char]"), name); ASSERT_EQUAL("invalid char", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("invalid char", "invalid shell name: invalid/char. only " "A-Z, a-z, 0-9, - and _ allowed", ex.error()); } try { parse_shell(ctx("[shell cleanup]"), name); ASSERT_EQUAL("reserved name (cleanup)", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("reserved name (cleanup)", "invalid shell name: cleanup. only " "A-Z, a-z, 0-9, - and _ allowed", ex.error()); } ASSERT_EQUAL("not shell", false, parse_shell(ctx("[cleanup]"), name)); } void test_parse_line_call() { plux::Line* line; line = parse_line_cmd(ctx("[call no-args]")); auto cline = dynamic_cast<plux::LineCall*>(line); ASSERT_EQUAL("call", true, cline != nullptr); ASSERT_EQUAL("call", "no-args", cline->name()); ASSERT_EQUAL("call", 0, cline->num_args()); delete line; line = parse_line_cmd(ctx("[call args one two]")); cline = dynamic_cast<plux::LineCall*>(line); ASSERT_EQUAL("call, args", true, cline != nullptr); ASSERT_EQUAL("call, args", "args", cline->name()); ASSERT_EQUAL("call, args", 2, cline->num_args()); delete line; } void test_parse_line_cmd_output() { plux::Line* line; line = parse_line_cmd(ctx("!echo 'test'")); auto oline = dynamic_cast<plux::LineOutput*>(line); ASSERT_EQUAL("output", true, oline != nullptr); ASSERT_EQUAL("output", std::string("echo 'test'\n"), oline->output()); delete line; } void test_parse_line_cmd_error() { plux::Line* line; line = parse_line_cmd(ctx("-")); auto eline = dynamic_cast<plux::LineSetErrorPattern*>(line); ASSERT_EQUAL("clear error", true, eline != nullptr); ASSERT_EQUAL("clear error", "", eline->pattern()); delete line; line = parse_line_cmd(ctx("-error")); eline = dynamic_cast<plux::LineSetErrorPattern*>(line); ASSERT_EQUAL("set error", true, eline != nullptr); ASSERT_EQUAL("set error", "error", eline->pattern()); delete line; } void test_parse_line_cmd_match() { plux::Line* line; line = parse_line_cmd(ctx("???exact match")); auto eline = dynamic_cast<plux::LineExactMatch*>(line); ASSERT_EQUAL("exact match", true, eline != nullptr); ASSERT_EQUAL("exact match", "exact match", eline->pattern()); delete line; line = parse_line_cmd(ctx("??match $HOME")); auto vline = dynamic_cast<plux::LineVarMatch*>(line); ASSERT_EQUAL("var match", true, vline != nullptr); ASSERT_EQUAL("var match", "match $HOME", vline->pattern()); delete line; line = parse_line_cmd(ctx("?^A.*$var$")); auto rline = dynamic_cast<plux::LineRegexMatch*>(line); ASSERT_EQUAL("regex match", true, rline != nullptr); ASSERT_EQUAL("regex match", "^A.*$var$", rline->pattern()); delete line; } void test_parse_line_cmd_global() { plux::Line* line; line = parse_line_cmd(ctx("[global my=value]")); auto gline = dynamic_cast<plux::LineVarAssignGlobal*>(line); ASSERT_EQUAL("global", true, gline != nullptr); ASSERT_EQUAL("global", "my", gline->key()); ASSERT_EQUAL("global", "value", gline->val()); delete line; } void test_parse_line_cmd_local() { plux::Line* line; line = parse_line_cmd(ctx("[local my=value]")); auto lline = dynamic_cast<plux::LineVarAssignShell*>(line); ASSERT_EQUAL("local", true, lline != nullptr); ASSERT_EQUAL("local", "my-shell", lline->shell()); ASSERT_EQUAL("local", "my", lline->key()); ASSERT_EQUAL("local", "value", lline->val()); delete line; } void test_parse_line_cmd_timeout() { plux::Line* line; line = parse_line_cmd(ctx("[timeout]")); auto tline = dynamic_cast<plux::LineTimeout*>(line); ASSERT_EQUAL("timeout default", true, tline != nullptr); ASSERT_EQUAL("timeout default", plux::default_timeout_ms, tline->timeout()); delete line; line = parse_line_cmd(ctx("[timeout 2]")); tline = dynamic_cast<plux::LineTimeout*>(line); ASSERT_EQUAL("timeout 2s", true, tline != nullptr); ASSERT_EQUAL("timeout 2s", 2000, tline->timeout()); delete line; try { parse_line_cmd(ctx("[timeout nan]")); ASSERT_EQUAL("timeout nan", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("timeout nan", "invalid timeout, not a valid number", ex.error()); } } void test_parse_line_cmd_unknown() { try { parse_line_cmd(ctx("% unknown command")); ASSERT_EQUAL("unknown", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("unknown", "unexpected content", ex.error()); } try { parse_line_cmd(ctx("[unknown]")); ASSERT_EQUAL("unknown", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("unknown", "unexpected content, unsupported function", ex.error()); } } plux::ScriptParseCtx& ctx(const std::string& line) { _ctx.shell = "my-shell"; _ctx.start = 2; _ctx.line = " " + line; return _ctx; } private: plux::ScriptParseCtx _ctx; }; int main(int argc, char* argv[]) { TestScriptParseCtx test_script_parse_ctx; std::istringstream is(""); TestScriptParse test_script_parse(&is); try { return TestSuite::main(argc, argv); } catch (plux::PluxException& ex) { std::cerr << ex.to_string() << std::endl; return 1; } }
35.254717
79
0.549906
pekdon
5cc4f924f678b5da011b1e6ab201cb0f04b1e7a3
576
cpp
C++
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
58
2020-08-02T16:38:43.000Z
2021-04-11T15:17:07.000Z
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
29
2020-08-03T08:48:05.000Z
2020-10-05T08:25:09.000Z
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
44
2020-08-02T16:51:08.000Z
2021-03-04T13:51:01.000Z
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define ll long long int int p = 1; using namespace std; void fun(ll x, ll n){ cout << x << " "; x = p > 0 ? x - 5 : x + 5; if(x != n){ if(x <= 0){ p = 0; } fun(x,n); }else{ cout << x << endl; } } int main() { ll t; cin >> t; while(t--){ ll n; cin >> n; p = 1; if(n == 0){ cout << n << endl; }else{ fun(n,n); } } return 0; }
15.567568
30
0.383681
tanayduggad0299
5cc92b4690bd96ef62a0acfafa82483ca2617abc
49,629
cpp
C++
cubicvr/source/datatree/DataTree.cpp
cjcliffe/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
48
2015-02-04T09:43:20.000Z
2021-09-29T00:45:28.000Z
cubicvr/source/datatree/DataTree.cpp
mcanthony/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
2
2016-06-08T09:03:52.000Z
2021-04-09T01:01:47.000Z
cubicvr/source/datatree/DataTree.cpp
mcanthony/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
17
2015-07-24T08:28:44.000Z
2021-04-09T02:14:21.000Z
/* * DataElement/DataNode/DataTree -- structured serialization/unserialization system * designed for the CoolMule project :) * Copyright (C) 2003 by Charles J. Cliffe 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 <CubicVR/datatree/DataTree.h> #include <CubicVR/StringUtil.h> #include <CubicVR/Logger.h> #include <fstream> /* DataElement class */ DataElement::DataElement() { data_type = DATA_NULL; data_val = NULL; data_size = 0; } DataElement::~DataElement() { if (data_val) delete data_val; } void DataElement::data_init(long data_size_in) { if (data_val) delete data_val; data_size = data_size_in; data_val = new char[data_size]; } int DataElement::getDataType() { return data_type; } long DataElement::getDataSize() { return data_size; } //void DataElement::set(const bool &bool_in) //{ // data_type = DATA_BOOL; // data_init(sizeof(bool)); // memcpy(data_val,&bool_in,data_size); //} void DataElement::set(const int &int_in) { data_type = DATA_INT; data_init(sizeof(int)); memcpy(data_val,&int_in,data_size); } void DataElement::set(const long &long_in) { data_type = DATA_LONG; data_init(sizeof(long)); memcpy(data_val,&long_in,data_size); } void DataElement::set(const float &float_in) { data_type = DATA_FLOAT; data_init(sizeof(float)); memcpy(data_val,&float_in,data_size); } void DataElement::set(const double &double_in) { data_type = DATA_DOUBLE; data_init(sizeof(double)); memcpy(data_val,&double_in,data_size); } void DataElement::set(const char *data_in, long size_in) { data_type = DATA_FLOAT; data_init(size_in); memcpy(data_val,data_in,data_size); } void DataElement::set(const char *data_in) { data_type = DATA_CHAR; data_init(strlen(data_in)+1); memcpy(data_val,data_in,data_size); } void DataElement::set(const string &str_in) { data_type = DATA_STRING; data_init(str_in.length()+1); memcpy(data_val,str_in.c_str(),data_size); } void DataElement::set(const XYZ &xyz_in) { data_type = DATA_XYZ; data_init(sizeof(cvrFloat)*3); cvrFloat xyz_dbl[3]; xyz_dbl[0] = xyz_in.x; xyz_dbl[1] = xyz_in.y; xyz_dbl[2] = xyz_in.z; memcpy(data_val,xyz_dbl,data_size); } void DataElement::set(vector<XYZ> &xyzvect_in) { vector<XYZ>::iterator i; long vectsize; long ptr; data_type = DATA_XYZVECTOR; vectsize = xyzvect_in.size()*sizeof(cvrFloat)*3; data_init(vectsize); ptr = 0; cvrFloat xyz_dbl[3]; for (i = xyzvect_in.begin(); i != xyzvect_in.end(); i++) { xyz_dbl[0] = (*i).x; xyz_dbl[1] = (*i).y; xyz_dbl[2] = (*i).z; memcpy(data_val+ptr, xyz_dbl, sizeof(cvrFloat)*3); ptr += sizeof(cvrFloat)*3; } } void DataElement::set(vector<string> &strvect_in) { vector<string>::iterator i; long vectsize; long ptr; data_type = DATA_STRVECTOR; vectsize = 0; for (i = strvect_in.begin(); i != strvect_in.end(); i++) { vectsize += (*i).length()+1; } data_init(vectsize); ptr = 0; for (i = strvect_in.begin(); i != strvect_in.end(); i++) { int str_length; str_length = (*i).length()+1; memcpy(data_val+ptr, (*i).c_str(), str_length); ptr += str_length; } } void DataElement::set(std::set<string> &strset_in) { std::set<string>::iterator i; vector<string> tmp_vect; for (i = strset_in.begin(); i != strset_in.end(); i++) { tmp_vect.push_back(*i); } set(tmp_vect); } void DataElement::set(vector<int> &intvect_in) { long ptr; int temp_int; data_type = DATA_INTVECTOR; data_init(sizeof(int)*intvect_in.size()); vector<int>::iterator i; ptr = 0; for (i = intvect_in.begin(); i != intvect_in.end(); i++) { temp_int = *i; memcpy(data_val+ptr, &temp_int, sizeof(int)); ptr += sizeof(int); } } void DataElement::set(vector<long> &longvect_in) { long ptr; long temp_long; data_type = DATA_LONGVECTOR; data_init(sizeof(long)*longvect_in.size()); vector<long>::iterator i; ptr = 0; for (i = longvect_in.begin(); i != longvect_in.end(); i++) { temp_long = *i; memcpy(data_val+ptr, &temp_long, sizeof(long)); ptr += sizeof(long); } } void DataElement::set(vector<float> &floatvect_in) { long ptr; float temp_float; data_type = DATA_FLOATVECTOR; data_init(sizeof(float)*floatvect_in.size()); // vector<float>::iterator i; // // ptr = 0; // // for (i = floatvect_in.begin(); i != floatvect_in.end(); i++) // { // temp_float = *i; // memcpy(data_val+ptr, &temp_float, sizeof(float)); // ptr += sizeof(float); // } memcpy(data_val,&floatvect_in[0],sizeof(float)*floatvect_in.size()); } void DataElement::set(vector<double> &doublevect_in) { long ptr; double temp_double; data_type = DATA_DOUBLEVECTOR; data_init(sizeof(double)*doublevect_in.size()); vector<double>::iterator i; ptr = 0; for (i = doublevect_in.begin(); i != doublevect_in.end(); i++) { temp_double = *i; memcpy(data_val+ptr, &temp_double, sizeof(double)); ptr += sizeof(double); } } //void DataElement::get(bool &bool_in) throw (DataTypeMismatchException) //{ // if (!data_type) return; // if (data_type != DATA_BOOL) throw(new DataTypeMismatchException("Type mismatch, not a BOOL")); // // memcpy(&bool_in, data_val, data_size); //} void DataElement::get(int &int_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_INT && data_type != DATA_LONG) throw(new DataTypeMismatchException("Type mismatch, not a INT")); if (data_type == DATA_LONG) { long tmp_long; memcpy(&tmp_long, data_val, data_size); int_in = (int)tmp_long; } else { memcpy(&int_in, data_val, data_size); } } void DataElement::get(long &long_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_LONG && data_type != DATA_INT) throw(new DataTypeMismatchException("Type mismatch, not a LONG")); if (data_type == DATA_INT) { int tmp_int; memcpy(&tmp_int, data_val, data_size); long_in = (long)tmp_int; } else { memcpy(&long_in, data_val, data_size); } } void DataElement::get(float &float_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_FLOAT && data_type != DATA_DOUBLE && data_type != DATA_INT && data_type != DATA_LONG) throw(new DataTypeMismatchException("Type mismatch, not a FLOAT")); if (data_type == DATA_DOUBLE) { float tmp_double; memcpy(&tmp_double, data_val, data_size); float_in = (float)tmp_double; } else if (data_type == DATA_LONG) { long tmpInt; get(tmpInt); float_in = (float)tmpInt; } else if (data_type == DATA_INT) { int tmpInt; get(tmpInt); float_in = (float)tmpInt; } else { memcpy(&float_in, data_val, data_size); } } void DataElement::get(double &double_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_DOUBLE && data_type != DATA_FLOAT) throw(new DataTypeMismatchException("Type mismatch, not a DOUBLE")); if (data_type == DATA_FLOAT) { float tmp_float; memcpy(&tmp_float, data_val, data_size); double_in = (double)tmp_float; } else { memcpy(&double_in, data_val, data_size); } } void DataElement::get(char **data_in) throw (DataTypeMismatchException) { if (data_type != DATA_CHAR) throw(new DataTypeMismatchException("Type mismatch, not a CHAR")); *data_in = new char[data_size]; memcpy(*data_in, data_val, data_size); } void DataElement::get(string &str_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_STRING && data_type != DATA_CHAR) throw(new DataTypeMismatchException("Type mismatch, not a STRING")); if (!str_in.empty()) // flush the string { str_in.erase(str_in.begin(),str_in.end()); } str_in.append(data_val); } void DataElement::get(vector<string> &strvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_STRVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a STRING VECTOR")); ptr = 0; while (ptr != data_size) { strvect_in.push_back(string(data_val+ptr)); ptr += strlen(data_val+ptr)+1; } } void DataElement::get(std::set<string> &strset_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_STRVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a STRING VECTOR/SET")); std::vector<string> tmp_vect; std::vector<string>::iterator i; get(tmp_vect); for (i = tmp_vect.begin(); i != tmp_vect.end(); i++) { strset_in.insert(*i); } } void DataElement::get(vector<int> &intvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_INTVECTOR && data_type != DATA_LONGVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a INT VECTOR")); ptr = 0; if (data_type == DATA_LONGVECTOR) { long temp_long; while (ptr < data_size) { temp_long = 0; memcpy(&temp_long,data_val+ptr,sizeof(long)); intvect_in.push_back((int)temp_long); ptr += sizeof(long); } } else { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); intvect_in.push_back(temp_int); ptr += sizeof(int); } } } void DataElement::get(vector<long> &longvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_LONGVECTOR && data_type != DATA_INTVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a LONG VECTOR")); ptr = 0; if (data_type == DATA_LONGVECTOR) { long temp_long; while (ptr < data_size) { temp_long = 0; memcpy(&temp_long,data_val+ptr,sizeof(long)); longvect_in.push_back(temp_long); ptr += sizeof(long); } } else { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); longvect_in.push_back((long)temp_int); ptr += sizeof(int); } } } void DataElement::get(vector<float> &floatvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_FLOATVECTOR && data_type != DATA_DOUBLEVECTOR && data_type != DATA_INTVECTOR && data_type != DATA_LONGVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a FLOAT VECTOR")); ptr = 0; if (data_type == DATA_DOUBLEVECTOR) { float temp_double; while (ptr < data_size) { temp_double = 0; memcpy(&temp_double,data_val+ptr,sizeof(double)); floatvect_in.push_back((float)temp_double); ptr += sizeof(double); } } if (data_type == DATA_INTVECTOR) { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); floatvect_in.push_back((float)temp_int); ptr += sizeof(int); } } else { float temp_float; while (ptr < data_size) { temp_float = 0; memcpy(&temp_float,data_val+ptr,sizeof(float)); floatvect_in.push_back(temp_float); ptr += sizeof(float); } } } void DataElement::get(vector<double> &doublevect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_DOUBLEVECTOR && data_type != DATA_FLOATVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a DOUBLE VECTOR")); ptr = 0; if (data_type == DATA_FLOATVECTOR) { float temp_float; while (ptr < data_size) { temp_float = 0; memcpy(&temp_float,data_val+ptr,sizeof(float)); doublevect_in.push_back((double)temp_float); ptr += sizeof(float); } } else { double temp_double; while (ptr < data_size) { temp_double = 0; memcpy(&temp_double,data_val+ptr,sizeof(double)); doublevect_in.push_back(temp_double); ptr += sizeof(double); } } } void DataElement::get(XYZ &xyz_in) throw (DataTypeMismatchException) { if (!data_type) return; cvrFloat xyz_dbl[3]; if (data_type != DATA_XYZ) throw(new DataTypeMismatchException("Type mismatch, not a XYZ")); memcpy(&xyz_dbl, data_val, data_size); xyz_in = XYZ(xyz_dbl[0],xyz_dbl[1],xyz_dbl[2]); } void DataElement::get(vector<XYZ> &xyzvect_in) throw (DataTypeMismatchException) { if (!data_type) return; XYZ temp_xyz; cvrFloat dbl_xyz[3]; long ptr; if (data_type != DATA_XYZVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a XYZ VECTOR")); ptr = 0; while (ptr < data_size) { memcpy(&dbl_xyz,data_val+ptr,sizeof(cvrFloat)*3); xyzvect_in.push_back(XYZ(dbl_xyz[0],dbl_xyz[1],dbl_xyz[2])); ptr += sizeof(cvrFloat)*3; } } long DataElement::getSerializedSize() { return sizeof(unsigned char)+sizeof(unsigned int)+data_size; } long DataElement::getSerialized(char **ser_str) { long ser_size = getSerializedSize(); *ser_str = new char[ser_size]; char *ser_pointer; ser_pointer = *ser_str; memcpy(ser_pointer, &data_type, sizeof(unsigned char)); ser_pointer+=sizeof(unsigned char); memcpy(ser_pointer, &data_size, sizeof(unsigned int)); ser_pointer+=sizeof(unsigned int); memcpy(ser_pointer, data_val, data_size); return ser_size; } void DataElement::setSerialized(char *ser_str) { char *ser_pointer = ser_str; memcpy(&data_type,ser_pointer,sizeof(unsigned char)); ser_pointer+=sizeof(unsigned char); memcpy(&data_size,ser_pointer,sizeof(unsigned int)); ser_pointer+=sizeof(unsigned int); data_init(data_size); memcpy(data_val,ser_pointer,data_size); } /* DataNode class */ DataNode::DataNode() { ptr = 0; parentNode = NULL; } DataNode::DataNode(const char *name_in) { ptr = 0; node_name = name_in; parentNode = NULL; } DataNode::~DataNode() { for (vector<DataNode *>::iterator i = children.begin(); i != children.end(); i++) { delete *i; } } void DataNode::setName(const char *name_in) { node_name = name_in; } DataElement &DataNode::element() { return data_elem; } DataNode &DataNode::newChild(const char *name_in) { children.push_back(new DataNode(name_in)); childmap[name_in].push_back(children.back()); children.back()->setParentNode(*this); return *children.back(); } DataNode &DataNode::child(const char *name_in, int index) throw (DataInvalidChildException) { DataNode *child_ret; child_ret = childmap[name_in][index]; if (!child_ret) { stringstream error_str; error_str << "no child '" << index << "' in DataNode '" << node_name << "'"; throw (DataInvalidChildException(error_str.str().c_str())); } return *child_ret; } DataNode &DataNode::child(int index) throw (DataInvalidChildException) { DataNode *child_ret; child_ret = children[index]; if (!child_ret) { stringstream error_str; error_str << "no child '" << index << "' in DataNode '" << node_name << "'"; throw (DataInvalidChildException(error_str.str().c_str())); } return *child_ret; } int DataNode::numChildren() { return children.size(); } int DataNode::numChildren(const char *name_in) { return childmap[name_in].size(); } bool DataNode::hasAnother() { return children.size() != ptr; } bool DataNode::hasAnother(const char *name_in) { return childmap[name_in].size() != childmap_ptr[name_in]; } DataNode &DataNode::getNext() throw (DataInvalidChildException) { return child(ptr++); } DataNode &DataNode::getNext(const char *name_in) throw (DataInvalidChildException) { return child(name_in,childmap_ptr[name_in]++); } void DataNode::rewind() { ptr = 0; } void DataNode::rewind(const char *name_in) { childmap_ptr[name_in] = 0; } /* DataTree class */ DataTree::DataTree(const char *name_in) { dn_root.setName(name_in); } DataTree::DataTree() { } DataTree::~DataTree() { }; DataNode &DataTree::rootNode() { return dn_root; } /* GameObject *newGO = createGO(filename); if(newGO) { printf("Loading GameObject from XML\n"); TiXmlDocument doc( filename.c_str() ); if(doc.LoadFile()) { printf("Loaded XML\n"); TiXmlNode *root = doc.FirstChild( "gameobject" ); if(root) { printf("Found root\n"); TiXmlNode *goc = root->FirstChild( "goc" ); while(goc) { printf("Game object\n"); TiXmlElement *gocEl = goc->ToElement(); std::string type = gocEl->Attribute("type"); if(type == "gocMesh") { printf("MESH COMPONENT!\n"); GameObjectComponent *gocComponent = new gocMesh(); newGO->addGOC(gocComponent); gocMesh *mesh = static_cast<gocMesh *>(gocComponent); mesh->load_xml(goc); mesh->bind(scene); } else if(type == "gocRigid") { printf("RIGID COMPONENT!\n"); GameObjectComponent *mRigid = new gocRigid(); newGO->addGOC(mRigid); gocRigid *rigid = static_cast<gocRigid *>(mRigid); rigid->load_xml(goc); rigid->bind((RigidScene *)scene); } else if(type == "gocLight") { printf("LIGHT COMPONENT!\n"); GameObjectComponent *mLight = new gocLight(); newGO->addGOC(mLight); gocLight *light = static_cast<gocLight *>(mLight); light->load_xml(goc); light->bind(scene); } else if(type == "gocCamera") { printf("CAMERA COMPONENT!\n"); GameObjectComponent *mCamera = new gocCamera(); newGO->addGOC(mCamera); gocCamera *camera = static_cast<gocCamera *>(mCamera); camera->load_xml(goc); camera->bind(scene); } else if(type == "gocTerrain") { printf("TERRAIN COMPONENT!\n"); GameObjectComponent *mTerrain = new gocTerrain(); newGO->addGOC(mTerrain); gocTerrain *terrain = static_cast<gocTerrain *>(mTerrain); terrain->load_xml(goc); terrain->bind((RigidScene *)scene); } else if(type == "gocScript") { printf("SCRIPT COMPONENT!\n"); GameObjectComponent *mScript = new gocScript(); newGO->addGOC(mScript); gocScript *script = static_cast<gocScript *>(mScript); script->load_xml(goc); //script->bind(scene); } printf("Type: %s\n", type.c_str()); goc = goc->NextSibling(); } } else { printf("No root\n"); } //printf("%s\n", root->Value()); } else { printf("Couldn't load: %s\n", filename.c_str()); } void write_simple_doc2( ) { // same as write_simple_doc1 but add each node // as early as possible into the tree. TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); TiXmlElement * element = new TiXmlElement( "Hello" ); doc.LinkEndChild( element ); TiXmlText * text = new TiXmlText( "World" ); element->LinkEndChild( text ); dump_to_stdout( &doc ); doc.SaveFile( "madeByHand2.xml" ); } */ std::string trim(std::string& s,const std::string& drop = " ") { std::string r=s.erase(s.find_last_not_of(drop)+1); return r.erase(0,r.find_first_not_of(drop)); } void DataTree::decodeXMLText(DataNode *elem, const char *src_text, DT_FloatingPointPolicy fpp) { long tmp_long; int tmp_int; double tmp_double; float tmp_float; string tmp_str; string tmp_str2; std::stringstream tmp_stream; std::stringstream tmp_stream2; XYZ tmp_xyz; vector<long> tmp_longvect; vector<long>::iterator tmp_longvect_i; vector<int> tmp_intvect; vector<double> tmp_doublevect; vector<double>::iterator tmp_doublevect_i; vector<float> tmp_floatvect; vector<XYZ> tmp_xyzvect; bool vInts = false; string in_text = src_text; trim(in_text); trim(in_text,"\r\n"); tmp_stream.clear(); tmp_stream2.clear(); if (in_text.find_first_not_of("0123456789-") == string::npos) { tmp_stream << in_text; tmp_stream >> tmp_long; tmp_int = tmp_long; if (tmp_int == tmp_long) { elem->element().set((int)tmp_int); } else { elem->element().set((long)tmp_long); } } else if (in_text.find_first_not_of("0123456789.e+-") == string::npos) { tmp_stream << in_text; if (fpp == USE_FLOAT) { tmp_stream >> tmp_float; elem->element().set((float)tmp_float); } else { tmp_stream >> tmp_double; elem->element().set((double)tmp_double); } } else if (in_text.find_first_not_of("0123456789.,e+-") == string::npos) { str_replace(","," ",in_text); tmp_stream << in_text; tmp_stream >> tmp_xyz.x; tmp_stream >> tmp_xyz.y; tmp_stream >> tmp_xyz.z; elem->element().set(tmp_xyz); } else if (in_text.find_first_not_of("0123456789- ") == string::npos) { tmp_stream << in_text; vInts = true; while (!tmp_stream.eof()) { tmp_stream >> tmp_long; tmp_int = tmp_long; if (tmp_int != tmp_long) { vInts = false; // printf("Failed int: [%d] != [%ld]\n",tmp_int,tmp_long); } tmp_longvect.push_back((long)tmp_long); } if (vInts) { tmp_intvect.clear(); for (tmp_longvect_i = tmp_longvect.begin(); tmp_longvect_i != tmp_longvect.end(); tmp_longvect_i++) { tmp_intvect.push_back(*tmp_longvect_i); } tmp_longvect.clear(); elem->element().set(tmp_intvect); } else { elem->element().set(tmp_longvect); } } else if (in_text.find_first_not_of("0123456789.e-+ ") == string::npos) { tmp_stream << in_text; if (fpp == USE_FLOAT) { tmp_floatvect.clear(); } else { tmp_doublevect.clear(); } while (!tmp_stream.eof()) { if (fpp == USE_FLOAT) { tmp_stream >> tmp_float; tmp_floatvect.push_back(tmp_float); } else { tmp_stream >> tmp_double; tmp_doublevect.push_back(tmp_double); } } if (fpp == USE_FLOAT) { elem->element().set(tmp_floatvect); } else { elem->element().set(tmp_doublevect); } } else if (in_text.find_first_not_of("0123456789.,e-+ ") == string::npos) { tmp_stream << in_text; while (!tmp_stream.eof()) { tmp_stream >> tmp_str2; str_replace(","," ",tmp_str2); tmp_stream2 << tmp_str2; tmp_stream2 >> tmp_xyz.x; tmp_stream2 >> tmp_xyz.y; tmp_stream2 >> tmp_xyz.z; tmp_stream2.clear(); tmp_xyzvect.push_back(tmp_xyz); } elem->element().set(tmp_xyzvect); } else { elem->element().set(src_text); // printf( "Unhandled DataTree XML Field: [%s]", tmp_str.c_str() ); } } void DataTree::setFromXML(DataNode *elem, TiXmlNode *elxml, bool root_node, DT_FloatingPointPolicy fpp) { TiXmlText *pText; int t = elxml->Type(); string tmp_str; switch ( t ) { case TiXmlNode::DOCUMENT: // printf( "Document" ); break; case TiXmlNode::ELEMENT: if (!root_node) elem = &elem->newChild(elxml->Value()); const TiXmlAttribute *attribs; attribs = elxml->ToElement()->FirstAttribute(); while (attribs) { //Logger::log(LOG_DEBUG,"attrib value: @%s = %s\n\n",attribs->Name(), attribs->Value()); // following badgerfish xml->json and xml->ruby convention for attributes.. string attrName("@"); attrName.append(attribs->Name()); decodeXMLText(&elem->newChild(attrName.c_str()), attribs->Value(), fpp); attribs = attribs->Next(); } // printf( "Element \"%s\"", elxml->Value()); break; case TiXmlNode::COMMENT: // printf( "Comment: \"%s\"", elxml->Value()); break; case TiXmlNode::UNKNOWN: // printf( "Unknown" ); break; case TiXmlNode::TEXT: pText = elxml->ToText(); decodeXMLText(elem, pText->Value(), fpp); // pText = elxml->ToText(); // printf( "Text: [%s]", pText->Value() ); break; case TiXmlNode::DECLARATION: // printf( "Declaration" ); break; default: break; } // printf( "\n" ); TiXmlNode * pChild; if (!elxml->NoChildren()) { if (elxml->FirstChild()->Type() == TiXmlNode::ELEMENT) { if (elxml->FirstChild()->Value() == TIXML_STRING("str")) { std::vector<std::string> tmp_strvect; for ( pChild = elxml->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if (pChild->Value() == TIXML_STRING("str")) { if (!pChild->FirstChild()) { tmp_strvect.push_back(""); continue; } pText = pChild->FirstChild()->ToText(); if (pText) { tmp_str = pText->Value(); tmp_strvect.push_back(tmp_str); } } } elem->element().set(tmp_strvect); return; } } } for ( pChild = elxml->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { setFromXML( elem, pChild, false, fpp ); } } void DataTree::nodeToXML(DataNode *elem, TiXmlElement *elxml) { DataNode *child; elem->rewind(); while (elem->hasAnother()) { child = &elem->getNext(); std::string nodeName = child->getName(); TiXmlElement *element; element = new TiXmlElement(nodeName.length()?nodeName.c_str():"node"); std::string tmp; std::stringstream tmp_stream; TiXmlText *text; XYZ tmp_xyz; std::vector<XYZ> tmp_xyzvect; std::vector<XYZ>::iterator tmp_xyzvect_i; std::vector<float> tmp_floatvect; std::vector<float>::iterator tmp_floatvect_i; std::vector<double> tmp_doublevect; std::vector<double>::iterator tmp_doublevect_i; std::vector<int> tmp_intvect; std::vector<int>::iterator tmp_intvect_i; std::vector<long> tmp_longvect; std::vector<long>::iterator tmp_longvect_i; std::vector<string> tmp_stringvect; std::vector<string>::iterator tmp_stringvect_i; TiXmlElement *tmp_node; char *tmp_pstr; double tmp_double; float tmp_float; long tmp_long; int tmp_int; switch (child->element().getDataType()) { case DATA_NULL: break; case DATA_INT: child->element().get(tmp_int); tmp_stream.clear(); tmp_stream << tmp_int; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_LONG: child->element().get(tmp_long); tmp_stream.clear(); tmp_stream << tmp_long; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_FLOAT: child->element().get(tmp_float); tmp_stream.clear(); tmp_stream << tmp_float; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_DOUBLE: child->element().get(tmp_double); tmp_stream.clear(); tmp_stream << tmp_double; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_CHAR: child->element().get(&tmp_pstr); // following badgerfish xml->json and xml->ruby convention for attributes.. if (nodeName.substr(0,1)==string("@")) { elxml->SetAttribute(nodeName.substr(1).c_str(), tmp_pstr); delete element; element = NULL; } else { text = new TiXmlText(tmp_pstr); element->LinkEndChild(text); } delete tmp_pstr; break; case DATA_STRING: child->element().get(tmp); if (nodeName.substr(0,1)==string("@")) { elxml->SetAttribute(nodeName.substr(1).c_str(), tmp.c_str()); delete element; element = NULL; } else { text = new TiXmlText(tmp.c_str()); element->LinkEndChild(text); } break; case DATA_STRVECTOR: child->element().get(tmp_stringvect); tmp_stream.clear(); for (tmp_stringvect_i = tmp_stringvect.begin(); tmp_stringvect_i != tmp_stringvect.end(); tmp_stringvect_i++) { tmp_node = new TiXmlElement("str"); text = new TiXmlText((*tmp_stringvect_i).c_str()); tmp_node->LinkEndChild(text); element->LinkEndChild(tmp_node); } tmp_stringvect.clear(); break; case DATA_INTVECTOR: child->element().get(tmp_intvect); tmp_stream.clear(); for (tmp_intvect_i = tmp_intvect.begin(); tmp_intvect_i != tmp_intvect.end(); tmp_intvect_i++) { tmp_stream << (*tmp_intvect_i); if (tmp_intvect_i != tmp_intvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_intvect.clear(); break; case DATA_LONGVECTOR: child->element().get(tmp_longvect); tmp_stream.clear(); for (tmp_longvect_i = tmp_longvect.begin(); tmp_longvect_i != tmp_longvect.end(); tmp_longvect_i++) { tmp_stream << (*tmp_longvect_i); if (tmp_longvect_i != tmp_longvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_longvect.clear(); break; case DATA_FLOATVECTOR: child->element().get(tmp_floatvect); tmp_stream.clear(); for (tmp_floatvect_i = tmp_floatvect.begin(); tmp_floatvect_i != tmp_floatvect.end(); tmp_floatvect_i++) { tmp_stream << (*tmp_floatvect_i); if (tmp_floatvect_i != tmp_floatvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_floatvect.clear(); break; case DATA_DOUBLEVECTOR: child->element().get(tmp_doublevect); tmp_stream.clear(); for (tmp_doublevect_i = tmp_doublevect.begin(); tmp_doublevect_i != tmp_doublevect.end(); tmp_doublevect_i++) { tmp_stream << (*tmp_doublevect_i); if (tmp_doublevect_i != tmp_doublevect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_doublevect.clear(); break; case DATA_XYZ: child->element().get(tmp_xyz); tmp_stream.clear(); tmp_stream << tmp_xyz.x; tmp_stream << ","; tmp_stream << tmp_xyz.y; tmp_stream << ","; tmp_stream << tmp_xyz.z; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_XYZVECTOR: child->element().get(tmp_xyzvect); tmp_stream.clear(); for (tmp_xyzvect_i = tmp_xyzvect.begin(); tmp_xyzvect_i != tmp_xyzvect.end(); tmp_xyzvect_i++) { tmp_stream << (*tmp_xyzvect_i).x; tmp_stream << ","; tmp_stream << (*tmp_xyzvect_i).y; tmp_stream << ","; tmp_stream << (*tmp_xyzvect_i).z; if (tmp_xyzvect_i != tmp_xyzvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_xyzvect.clear(); break; } if (element) { elxml->LinkEndChild(element); if (child->numChildren()) { nodeToXML(child,element); } } } elem->rewind(); } void DataTree::printXML() /* get serialized size + return node names header */ { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); DataNode *root = &rootNode(); string rootName = root->getName(); TiXmlElement *element = new TiXmlElement(rootName.empty()?"root":rootName.c_str()); doc.LinkEndChild( element ); if (!root->numChildren()) doc.Print(); nodeToXML(root,element); root->rewind(); doc.Print(); } long DataTree::getSerializedSize(DataElement &de_node_names, bool debug) /* get serialized size + return node names header */ { long total_size = 0; stack<DataNode *> dn_stack; vector<string> node_names; map<string, int, string_less> node_name_index_map; DataElement de_name_index; // just used for sizing purposes DataElement de_num_children; de_name_index.set((int)0); de_num_children.set((int)0); int de_name_index_size = de_name_index.getSerializedSize(); int de_num_children_size = de_num_children.getSerializedSize(); dn_stack.push(&dn_root); while (!dn_stack.empty()) { int name_index; // int num_children; /* build the name list */ if (dn_stack.top()->getName().empty()) { name_index = 0; /* empty string */ } else if (node_name_index_map[dn_stack.top()->getName().c_str()] == 0) { node_names.push_back(string(dn_stack.top()->getName())); name_index = node_names.size(); node_name_index_map[dn_stack.top()->getName().c_str()] = name_index; } else { name_index = node_name_index_map[dn_stack.top()->getName().c_str()]; } /* add on the size of the name index and number of children */ total_size += de_name_index_size; total_size += de_num_children_size; total_size += dn_stack.top()->element().getSerializedSize(); /* debug output */ if (debug) { for (unsigned int i = 0; i < dn_stack.size()-1; i++) cout << "--"; cout << (dn_stack.top()->getName().empty()?"NULL":dn_stack.top()->getName()) << "(" << dn_stack.top()->element().getSerializedSize() << ")"; cout << " type: " << dn_stack.top()->element().getDataType() << endl; //cout << " index: " << name_index << endl; } /* end debug output */ /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } /* set the header for use in serialization */ de_node_names.set(node_names); total_size += de_node_names.getSerializedSize(); return total_size; } void DataNode::findAll(const char *name_in, vector<DataNode *> &node_list_out) { stack<DataNode *> dn_stack; /* start at the root */ dn_stack.push(this); if (string(getName()) == string(name_in)) node_list_out.push_back(this); while (!dn_stack.empty()) { while (dn_stack.top()->hasAnother(name_in)) { node_list_out.push_back(&dn_stack.top()->getNext(name_in)); } /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } } long DataTree::getSerialized(char **ser_str, bool debug) { long data_ptr = 0; long data_size = 0; stack<DataNode *> dn_stack; vector<string> node_names; map<string, int, string_less> node_name_index_map; /* header of node names, grabbed from getserializedsize to avoid having to memmove() or realloc() */ DataElement de_node_names; data_size = getSerializedSize(de_node_names,debug); *ser_str = (char *)malloc(data_size); char *data_out = *ser_str; /* name list header */ char *de_node_names_serialized; long de_node_names_serialized_size; de_node_names.getSerialized(&de_node_names_serialized); de_node_names_serialized_size = de_node_names.getSerializedSize(); /* copy the header and increase the pointer */ memcpy(data_out,de_node_names_serialized,de_node_names_serialized_size); data_ptr += de_node_names_serialized_size; // if (debug) Logger::log(LOG_DEBUG,"serialized header size: %d",de_node_names_serialized_size); /* start at the root */ dn_stack.push(&dn_root); while (!dn_stack.empty()) { int name_index; int num_children; DataElement de_name_index; DataElement de_num_children; char *de_name_index_serialized; char *de_num_children_serialized; char *element_serialized; long de_name_index_serialized_size; long de_num_children_serialized_size; long element_serialized_size; /* build the name list */ if (dn_stack.top()->getName().empty()) { name_index = 0; /* empty string */ } else if (node_name_index_map[dn_stack.top()->getName().c_str()] == 0) { node_names.push_back(string(dn_stack.top()->getName())); name_index = node_names.size(); node_name_index_map[dn_stack.top()->getName().c_str()] = name_index; } else { name_index = node_name_index_map[dn_stack.top()->getName().c_str()]; } num_children = dn_stack.top()->numChildren(); de_name_index.set(name_index); de_num_children.set(num_children); de_name_index_serialized_size = de_name_index.getSerializedSize(); de_num_children_serialized_size = de_num_children.getSerializedSize(); element_serialized_size = dn_stack.top()->element().getSerializedSize(); de_name_index.getSerialized(&de_name_index_serialized); de_num_children.getSerialized(&de_num_children_serialized); dn_stack.top()->element().getSerialized(&element_serialized); /* add on the name index and number of children */ memcpy(data_out+data_ptr,de_name_index_serialized,de_name_index_serialized_size); data_ptr += de_name_index_serialized_size; memcpy(data_out+data_ptr,de_num_children_serialized,de_num_children_serialized_size); data_ptr += de_num_children_serialized_size; /* add on the data element */ memcpy(data_out+data_ptr,element_serialized,element_serialized_size); data_ptr += element_serialized_size; delete de_name_index_serialized; delete de_num_children_serialized; delete element_serialized; /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } return data_size; } void DataTree::setSerialized(char *ser_str, bool debug) { long data_ptr = 0; // long data_size = 0; stack<DataNode *> dn_stack; stack<int> dn_childcount_stack; vector<string> node_names; DataElement de_node_names; de_node_names.setSerialized(ser_str); data_ptr+=de_node_names.getSerializedSize(); de_node_names.get(node_names); DataElement de_name_index; DataElement de_num_children; DataElement de_element; dn_stack.push(&dn_root); dn_childcount_stack.push(0); /* root (parent null) has no siblings */ /* unserialization is a little less straightforward since we have to do a countdown of remaining children */ while (!dn_stack.empty()) { int name_index; int num_children; /* pull the index of the name of this node */ de_name_index.setSerialized(ser_str+data_ptr); data_ptr += de_name_index.getSerializedSize(); /* pull the number of children this node has */ de_num_children.setSerialized(ser_str+data_ptr); data_ptr += de_num_children.getSerializedSize(); /* get values from the temp dataelements */ de_name_index.get(name_index); de_num_children.get(num_children); /* pull the node's element */ dn_stack.top()->element().setSerialized(ser_str+data_ptr); data_ptr += dn_stack.top()->element().getSerializedSize(); /* debug output */ if (debug) { for (unsigned int i = 0; i < dn_stack.size()-1; i++) cout << "--"; cout << (name_index?node_names[name_index-1]:"NULL") << "(" << dn_stack.top()->element().getSerializedSize() << ")"; cout << " index: " << name_index << endl; } /* end debug output */ /* name index >= 1 means it has a name */ if (name_index) { dn_stack.top()->setName(node_names[name_index-1].c_str()); } else /* name is nil */ { dn_stack.top()->setName(""); } if (num_children) /* Has children, create first child and push it to the top */ { dn_childcount_stack.push(num_children); /* push the child count onto the stack */ de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); /* add this child onto the top of the stack */ dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); dn_childcount_stack.top()--; /* decrement to count the new child */ } else /* No children, move on to the next sibling */ { if (dn_childcount_stack.top()) /* any siblings remaining? */ { de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); dn_stack.pop(); dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); /* create the next sibling and throw it on the stack */ dn_childcount_stack.top()--; /* decrement to count the new sibling */ } else /* This is the last sibling, move up the stack and find the next */ { while (!dn_stack.empty()) /* move up the stack until we find the next sibling */ { if (dn_childcount_stack.top()) { de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); dn_stack.pop(); dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); /* throw it on the stack */ dn_childcount_stack.top()--; /* count it */ break; } else { dn_childcount_stack.pop(); dn_stack.pop(); /* if no more siblings found the stack will empty naturally */ } } } } } } bool DataTree::LoadFromFileXML(const std::string& filename, DT_FloatingPointPolicy fpp) { TiXmlDocument doc(filename.c_str()); bool loadOkay = doc.LoadFile(); if (!loadOkay) { Logger::log(LOG_ERROR,"LoadFromFileXML[error loading]: \"%s\"\n",filename.c_str()); return false; } TiXmlNode *xml_root_node = doc.RootElement(); if (!xml_root_node) { Logger::log(LOG_ERROR,"LoadFromFileXML[error no root]: \"%s\"\n",filename.c_str()); return false; } rootNode().setName(xml_root_node->ToElement()->Value()); setFromXML(&rootNode(),xml_root_node,true,fpp); return true; } bool DataTree::SaveToFileXML(const std::string& filename) { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); string rootName = rootNode().getName(); TiXmlElement *element = new TiXmlElement(rootName.empty()?"root":rootName.c_str()); doc.LinkEndChild( element ); nodeToXML(&rootNode(),element); doc.SaveFile(filename.c_str()); return true; } /* bool DataTree::SaveToFile(const std::string& filename) { char *serialized; long dataSize = getSerialized(&serialized); std::ofstream fout(filename.c_str(), ios::binary); fout.write(serialized, dataSize); fout << flush; fout.close(); delete serialized; return true; } bool DataTree::LoadFromFile(const std::string& filename) { char *serialized; long dataSize; ifstream fin(filename.c_str(), ios::binary); fin.seekg (0, ios::end); dataSize = fin.tellg(); fin.seekg (0, ios::beg); serialized = new char[dataSize]; fin.read(serialized,dataSize); fin.close(); setSerialized(serialized); delete serialized; return true; } */ bool DataTree::SaveToFile(const std::string& filename, bool compress, int compress_level) { long dataSize, compressedSize, headerSize; char *serialized, *hdr_serialized, *compressed; DataTree dtHeader; dataSize = getSerialized(&serialized); if (compress) { compressed = new char[(int)ceil(dataSize*1.5)]; compressedSize = fastlz_compress_level(compress_level, serialized, dataSize, compressed); compressed = (char *)realloc(compressed, compressedSize); delete serialized; } DataNode &header = dtHeader.rootNode(); header^"version" = 1.0f; header^"compression" = string(compress?"FastLZ":"none"); header^"uncompressed_size" = dataSize; headerSize = dtHeader.getSerialized(&hdr_serialized); std::ofstream fout(filename.c_str(), ios::binary); fout.write((char *) &headerSize, sizeof(long)); fout.write((char *) &(compress?compressedSize:dataSize), sizeof(long)); fout.write(hdr_serialized, headerSize); fout.write(compress?compressed:serialized, compress?compressedSize:dataSize); fout << flush; fout.close(); delete hdr_serialized; if (!compress) { delete serialized; } else { delete compressed; } return true; } bool DataTree::LoadFromFile(const std::string& filename) { char *compressed,*serialized,*hdr_serialized; long dataSize,headerSize,compressedSize; ifstream fin(filename.c_str(), ios::binary); fin.read((char *)&headerSize, sizeof(long)); fin.read((char *)&compressedSize, sizeof(long)); hdr_serialized = new char[headerSize]; fin.read(hdr_serialized,headerSize); DataTree dtHeader; dtHeader.setSerialized(hdr_serialized); DataNode &header = dtHeader.rootNode(); string compressionType = header["compression"]; dataSize = header["uncompressed_size"]; bool uncompress = false; if (compressionType=="FastLZ") { uncompress = true; } if (uncompress) { compressed = new char[compressedSize]; fin.read(compressed,compressedSize); serialized = new char[dataSize]; fastlz_decompress(compressed, compressedSize, serialized, dataSize); delete compressed; } else { serialized = new char[dataSize]; fin.read(serialized,dataSize); } fin.close(); setSerialized(serialized); delete serialized; delete hdr_serialized; return true; }
24.150365
208
0.61998
cjcliffe
5ccaa325836b93a5ff0d33f132e41ce37c1035e8
4,684
hpp
C++
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
/// @file gnuplotHelper.hpp /// @author Enrico Fraccaroli /// @date Oct 02 2017 /// @copyright /// Copyright (c) 2017 Enrico Fraccaroli <[email protected]> #pragma once #include "gptValue.hpp" #include "gptBound.hpp" #include <iostream> #ifdef WIN32 #define GNUPLOT_NAME "pgnuplot -persistent" #else #define GNUPLOT_NAME "gnuplot" #endif /// @brief Gnuplot trace generation tracer. class GPTTracer { private: /// The title of the trace. std::string _title; /// The type of terminal. std::string _terminal; /// The background color. std::string _background; /// The foreground color. std::string _foreground; /// The font dimension of the keys. unsigned int _font_key; /// The font dimension for the x axis label. unsigned int _font_size_x_axis; /// The font dimension for the y axis label. unsigned int _font_size_y_axis; /// The boundaries for the x axis. GPTBound * _bound_x; /// The boundaries for the y axis. GPTBound * _bound_y; /// Pipe used to communicate with gnuplot. FILE * _pipe; /// The x axis variable. GPTVariable * _x_variable; /// The y axis variables. std::vector<GPTVariable *> _y_variables; public: /// @brief Constructor. GPTTracer(); /// @brief Constructor. GPTTracer(std::string title, std::string terminal, std::string background, std::string foreground, const unsigned int & font_key, const unsigned int & font_size_x_axis, const unsigned int & font_size_y_axis); /// @brief Destructor. ~GPTTracer(); /// @brief Open the pipe to gnuplot. inline void open() { this->close(); #ifdef WIN32 _pipe = _popen(GNUPLOT_NAME, "w"); #else _pipe = popen(GNUPLOT_NAME, "w"); #endif } /// @brief Checks whether the pipe is open. inline bool isOpened() const { return _pipe != nullptr; } /// @brief Closes the pipe. inline void close() { if (this->isOpened()) { #ifdef WIN32 _pclose(_pipe); #else pclose(_pipe); #endif _pipe = nullptr; } } /// @brief Flushes data on pipe. inline void flush() { if (this->isOpened()) { fflush(_pipe); } } /// @brief Allows to set the boundaries for the x axis. inline void setBoundX(double _lower_bound, double _upper_bound) { _bound_x = new GPTBound(_lower_bound, _upper_bound); } /// @brief Allows to set the boundaries for the y axis. inline void setBoundY(double _lower_bound, double _upper_bound) { _bound_y = new GPTBound(_lower_bound, _upper_bound); } /// @brief Allows to set the variable for the x axis. template<typename T> inline void setVariableX(T * _variable, const std::string & _name, const std::string & _format, const unsigned int & _lineWidth) { assert(_variable); _x_variable = new GPTGenericVariable<T>(_variable, _name, _format, _lineWidth); } /// @brief Allows to add a variable on the y axis. template<typename T> inline void addVariableY(T * _variable, const std::string & _name, const std::string & _format, const unsigned int & _lineWidth) { assert(_variable); _y_variables.emplace_back( new GPTGenericVariable<T>(_variable, _name, _format, _lineWidth)); } /// @brief Prints the data. inline void printData(const bool & visualize) { this->open(); this->setup(); this->addPlotLine(); this->addDataPoints(); this->flush(); // Waits for the user to look at the graph. if (visualize) { std::cin.clear(); std::cin.ignore(std::cin.rdbuf()->in_avail()); std::cin.get(); } } /// @brief Samples the data. inline void sampleData() { _x_variable->sampleValue(); for (auto value : _y_variables) { value->sampleValue(); } } private: void addPlotLine(); void addDataPoints(); void setup(); };
25.736264
69
0.538002
Galfurian
5ccd42bdd220904da181e9a6038210af00f3fc75
2,834
cpp
C++
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
// This is free and unencumbered software released into the public domain. #include "NetPlayGameState.h" #include "NetPlayPlayerController.h" #include "GameFramework/PlayerState.h" #include "Engine/World.h" #include "Engine/LocalPlayer.h" ANetPlayGameState::ANetPlayGameState() { PrimaryActorTick.bStartWithTickEnabled = false; } void ANetPlayGameState::BeginPlay() { Super::BeginPlay(); ANetPlayPlayerController* FirstLocalPlayerController = nullptr; for (auto Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator) { auto PlayerController = Cast<ANetPlayPlayerController>(Iterator->Get()); if (PlayerController) { AddTickPrerequisiteActor(PlayerController); ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(PlayerController->Player); if (LocalPlayer && FirstLocalPlayerController == nullptr) { FirstLocalPlayerController = PlayerController; } } } if (FirstLocalPlayerController != nullptr) { FirstLocalPlayerController->ServerSync(); } } void ANetPlayGameState::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); auto Unread = EarliestUnread(); if (Unread <= CurrentFrame) { auto OneBeforeUnread = Unread - 1; for (auto& Relevant : NetPlayRelevant) { auto RollsBack = Cast<IRollsBack>(Relevant); RollsBack->Rollback(CurrentFrame - OneBeforeUnread); } auto ReplayFrame = CurrentFrame; for (CurrentFrame = Unread; CurrentFrame <= ReplayFrame; CurrentFrame++) { for (auto& Relevant : NetPlayRelevant) { Relevant->Tick(DeltaSeconds); } } } else { CurrentFrame++; } } TArray<uint8> ANetPlayGameState::State() { return TArray<uint8>(); } void ANetPlayGameState::SyncState(const TArray<uint8>& State) { return; } void ANetPlayGameState::Sync(const TArray<uint8>& State, int Seed, int PlayerId, int Frame) { SetActorTickEnabled(true); SyncState(State); CurrentFrame = Frame; RandomStream.Initialize(Seed); ReceiveSync(); } void ANetPlayGameState::PeerSync(int Frame, int PlayerId) { ReceivePeerSync(PlayerId); } void ANetPlayGameState::PeerInput(const TArray<uint8>& Input, int PlayerId, int Frame) { // This needs to be handled more gracefully at some point. check(Frame < MinimumRead() + NETPLAY_HISTORY); ReadAndRecievedForPlayer[PlayerId].Recieved = Frame; } int ANetPlayGameState::MinimumRead() { int Min = INT_MAX; for (auto& Pair : ReadAndRecievedForPlayer) { Min = FMath::Min(Pair.Value.Read, Min); } return Min; } int ANetPlayGameState::EarliestUnread() { int Min = INT_MAX; for (auto& Pair : ReadAndRecievedForPlayer) { if (Pair.Value.Recieved > Pair.Value.Read) { Min = FMath::Min(Pair.Value.Read + 1, Min); } } return Min; } void ANetPlayGameState::RegisterForRollback(AActor* Actor) { NetPlayRelevant.Add(Actor); Actor->AddTickPrerequisiteActor(this); }
19.680556
91
0.732534
avrcolak
5cce960449eee7db899f7ae6645e096442c3665b
385
hpp
C++
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifndef __VERTEXBUFFER_HPP__ #define __VERTEXBUFFER_HPP__ #include <Arbiter/Core/Common/Base.hpp> ARBITER_NAMESPACE_BEGIN OPENGL_NAMESPACE_BEGIN class VertexBuffer : public std::enable_shared_from_this<VertexBuffer> { private: public: VertexBuffer(); virtual ~VertexBuffer() = default; }; OPENGL_NAMESPACE_END ARBITER_NAMESPACE_END #endif // __VERTEXBUFFER_HPP__
16.73913
70
0.820779
cookieniffler
5cceb2450ee4b50e0e6b6ed4cda07357e228ef7a
2,237
hpp
C++
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
namespace Gecode { namespace String { forceinline ExecStatus LowerCase::post(Home home, StringView x0, StringView x1) { if (x0.same(x1)) { StringVar y(home, x0.may_chars(), x0.min_length(), x0.max_length()); (void) new (home) LowerCase(home, x0, y); rel (home, x1, STRT_EQ, y); } else (void) new (home) LowerCase(home, x0, x1); return ES_OK; } forceinline Actor* LowerCase::copy(Space& home) { return new (home) LowerCase(home, *this); } forceinline LowerCase::LowerCase(Home home, StringView y0, StringView y1) : MixBinaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM> (home, y0, y1) {} forceinline LowerCase::LowerCase(Space& home, LowerCase& p) : MixBinaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM>(home, p) {} forceinline ExecStatus LowerCase::propagate(Space& home, const ModEventDelta&) { // std::cerr<<"LowerCase::propagate "<<x1<<" = lcase("<<x0<<")\n"; int n = x0.pdomain()->length(); NSBlocks lx(n); bool changed = false; for (int i = 0; i < n; ++i) { const DSBlock& bi = x0.pdomain()->at(i); NSIntSet si(bi.S); if (!(bi.S.disjoint(String::UpperCase::_UCASE_SET))) { NSIntSet ti(si); ti.intersect(String::UpperCase::_UCASE_SET); si.exclude(ti); ti.shift(32); si.include(ti); changed = true; } lx[i] = NSBlock(si, bi.l, bi.u); } if (changed) lx.normalize(); GECODE_ME_CHECK(x1.dom(home, lx)); changed = false; n = x1.pdomain()->length(); NSBlocks uy(n); for (int i = 0; i < n; ++i) { const DSBlock& bi = x1.pdomain()->at(i); NSIntSet si(bi.S); if (!(bi.S.disjoint(String::UpperCase::_LCASE_SET))) { NSIntSet ti(si); ti.intersect(String::UpperCase::_LCASE_SET); ti.shift(-32); si.include(ti); changed = true; } uy[i] = NSBlock(si, bi.l, bi.u); } if (changed) uy.normalize(); GECODE_ME_CHECK(x0.dom(home, uy)); // std::cerr<<"LowerCase::propagated "<<x1<<" = lcase("<<x0<<")\n"; assert (x0.pdomain()->is_normalized() && x1.pdomain()->is_normalized()); return ES_FIX; } }}
29.434211
77
0.589629
ramadini
5cd3cba9c9a6bccc9fc7b507b1f7c64f73c48bd2
3,039
cpp
C++
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
12
2021-09-28T14:37:22.000Z
2022-03-04T17:54:11.000Z
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
null
null
null
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
8
2021-11-05T18:56:55.000Z
2022-01-10T11:14:24.000Z
/* Copyright 2021 Enjin Pte. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "JsonTestSuite.hpp" #include "enjinsdk/models/PlayerFilter.hpp" #include <string> #include <vector> using namespace enjin::sdk::models; using namespace enjin::test::suites; class PlayerFilterTest : public JsonTestSuite, public testing::Test { public: PlayerFilter class_under_test; constexpr static char POPULATED_JSON_OBJECT[] = R"({"and":[],"or":[],"id":"1","id_in":[]})"; static PlayerFilter create_default_filter() { return PlayerFilter().set_and(std::vector<PlayerFilter>()) .set_or(std::vector<PlayerFilter>()) .set_id("1") .set_id_in(std::vector<std::string>()); } }; TEST_F(PlayerFilterTest, SerializeNoSetFieldsReturnsEmptyJsonObject) { // Arrange const std::string expected(EMPTY_JSON_OBJECT); // Act std::string actual = class_under_test.serialize(); // Assert ASSERT_EQ(expected, actual); } TEST_F(PlayerFilterTest, SerializeSetFieldsReturnsExpectedJsonObject) { // Arrange const std::string expected(POPULATED_JSON_OBJECT); class_under_test.set_and(std::vector<PlayerFilter>()) .set_or(std::vector<PlayerFilter>()) .set_id("1") .set_id_in(std::vector<std::string>()); // Act std::string actual = class_under_test.serialize(); // Assert ASSERT_EQ(expected, actual); } TEST_F(PlayerFilterTest, EqualityNeitherSideIsPopulatedReturnsTrue) { // Arrange PlayerFilter lhs; PlayerFilter rhs; // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(PlayerFilterTest, EqualityBothSidesArePopulatedReturnsTrue) { // Arrange PlayerFilter lhs = create_default_filter(); PlayerFilter rhs = create_default_filter(); // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(PlayerFilterTest, EqualityLeftSideIsPopulatedReturnsFalse) { // Arrange PlayerFilter lhs = create_default_filter(); PlayerFilter rhs; // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); } TEST_F(PlayerFilterTest, EqualityRightSideIsPopulatedReturnsFalse) { // Arrange PlayerFilter lhs; PlayerFilter rhs = create_default_filter(); // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); }
26.657895
75
0.663047
BlockChain-Station
5cd406d58760cf9d9e8efdeb2542dc5789565895
3,885
cc
C++
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* ------------------------------------------------------------------------- Spline Author: Ethan Coon ([email protected]) Spline fit of a curve, given points, values, and derivatives of those values. If needed, this could easily provide a constructor without derivatives, and use an algorithm to construct these derivatives. Provides options for monotonicity preservation. ------------------------------------------------------------------------- */ #include <algorithm> #include "SplinedCurve.hh" namespace Amanzi { namespace Utils { SplinedCurve::SplinedCurve(std::vector<double> x, std::vector<double> y, std::vector<double> dydx, SplineEndpoints_t endpoints, bool enforce_monotonicity) : x_(x), y_(y), dy_(dydx), left_(endpoints.first), right_(endpoints.second), mono_(enforce_monotonicity) { Setup_(); }; void SplinedCurve::Setup(std::vector<double> x, std::vector<double> y, std::vector<double> dydx, SplineEndpoints_t endpoints, bool enforce_monotonicity) { x_ = x; y_ = y; dy_ = dydx; left_ = endpoints.first; right_ = endpoints.second; mono_ = enforce_monotonicity; Setup_(); } void SplinedCurve::Setup_() { if (x_.size() < 2) { Errors::Message msg("SplinedCurve must get arrays of length 2 or greater."); Exceptions::amanzi_throw(msg); } if (x_.size() != y_.size() || x_.size() != dy_.size()) { Errors::Message msg("SplinedCurve must get arrays of equal length."); Exceptions::amanzi_throw(msg); } dx_.resize(x_.size()-1,0.); for (int i=0; i!=dx_.size(); ++i) { dx_[i] = x_[i+1] - x_[i]; if (dx_[i] <= 0.) { Errors::Message msg("SplinedCurve independent variable x must be monotonically increasing."); Exceptions::amanzi_throw(msg); } } // enforce monotonicity using the approach of Hyman '83 Accurate // Mono. Pres. Cubic Interp. if (mono_) { // determine whether monotonically increasing, decreasing, or zero double mean_slope = (y_[y_.size()-1] - y_[0]); // calculate the finite difference slopes std::vector<double> dy_fd(dx_.size(),0.); for (int i=0; i!=dx_.size(); ++i) { dy_fd[i] = (y_[i+1] - y_[i]) / dx_[i]; } // enforce sufficient monotonicity constraint on slopes if (mean_slope > 0.) { double min_slope = *std::min_element(dy_.begin(), dy_.end()); if (min_slope < 0.) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with postive mean slope but slopes provided are not uniformly non-negative."); Exceptions::amanzi_throw(msg); } // dy = min( 3*min(S-1/2, S+1/2), dy) for (int i=1; i!=dy_.size()-1; ++i) { dy_[i] = std::min( 3*std::min(dy_fd[i-1], dy_fd[i]), dy_[i]); } } else if (mean_slope < 0.) { double max_slope = *std::max_element(dy_.begin(), dy_.end()); if (max_slope > 0.) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with negative mean slope but slopes provided are not uniformly non-positive."); Exceptions::amanzi_throw(msg); } // dy = max( 3*max(S-1/2, S+1/2), dy) for (int i=1; i!=dy_.size()-1; ++i) { dy_[i] = std::max( 3*std::max(dy_fd[i-1], dy_fd[i]), dy_[i]); } } else { double min_slope = *std::min_element(dy_.begin(), dy_.end()); double max_slope = *std::max_element(dy_.begin(), dy_.end()); if (min_slope != 0.0 || max_slope != 0.0) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with zero mean slope but slopes provided are not uniformly zero."); Exceptions::amanzi_throw(msg); } } } } } // namespace } // namespace
29.884615
155
0.578121
fmyuan
5cda6079665f1ebe1e439c0679a8f1472e87f266
9,069
cpp
C++
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
3
2016-01-27T00:34:21.000Z
2019-08-14T07:13:09.000Z
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
null
null
null
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
1
2019-09-05T04:59:59.000Z
2019-09-05T04:59:59.000Z
/* * Copyright (c) 2013 Pavlo Lavrenenko * * 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 <Font.h> #include <Logger.h> #include <stdexcept> #include <algorithm> #include <vector> #include <cstring> #include <cassert> #include <stdexcept> #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H namespace Graphene { void Font::initFreeType() { if (Font::library == nullptr) { FT_Library library; if (FT_Init_FreeType(&library) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Init_FreeType()")); } Font::library.reset(library, FT_Done_FreeType); } } std::shared_ptr<FT_LibraryRec> Font::library; Font::Font(const std::string& filename, int size, int dpi): filename(filename), size(size), dpi(dpi) { Font::initFreeType(); FT_Face face; if (FT_New_Face(Font::library.get(), this->filename.c_str(), 0, &face) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_New_Face()")); } this->face.reset(face, FT_Done_Face); FT_F26Dot6 fontSize = this->size << 6; // Size in 1/64th of a pixel if (FT_Set_Char_Size(this->face.get(), fontSize, 0, this->dpi, 0) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Set_Char_Size()")); } } const std::string& Font::getFilename() const { return this->filename; } int Font::getSize() const { return this->size; } int Font::getDPI() const { return this->dpi; } void Font::renderChar(wchar_t charCode, const std::shared_ptr<RawImage>& image) { int imagePixelBytes = image->getPixelDepth() >> 3; if (imagePixelBytes != 4) { throw std::invalid_argument(LogFormat("Image should have 32 bits per pixel")); } auto& charGlyph = this->getCharGlyph(charCode); FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(charGlyph->record.get()); FT_Bitmap charBitmap = bitmapGlyph->bitmap; int imageWidth = image->getWidth(); if (static_cast<unsigned int>(imageWidth) < charBitmap.width) { throw std::runtime_error(LogFormat("Image width is %d but character requires %d", imageWidth, charBitmap.width)); } int imageHeight = image->getHeight(); if (static_cast<unsigned int>(imageHeight) < charBitmap.rows) { throw std::runtime_error(LogFormat("Image height is %d but character requires %d", imageHeight, charBitmap.rows)); } int imagePixelsSize = image->getPixelsSize(); int imageRowSize = imageWidth * imagePixelBytes; int charRowSize = charBitmap.width; // Single byte (alpha) unsigned char* imagePixels = reinterpret_cast<unsigned char*>(image->getPixels()); const unsigned char* charPixels = charGlyph->pixels.get(); for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++) { int imageRowOffset = charRow * imageRowSize; int charRowOffset = charRow * charRowSize; for (unsigned int alphaPixel = 0; alphaPixel < charBitmap.width; alphaPixel++) { int alphaOffset = (alphaPixel * imagePixelBytes) + 3; // Offset to RGB[A] alpha assert(imageRowOffset + alphaOffset < imagePixelsSize); imagePixels[imageRowOffset + alphaOffset] = charPixels[charRowOffset + alphaPixel]; } } } void Font::renderString(const std::wstring& stringText, const std::shared_ptr<RawImage>& image) { int imagePixelBytes = image->getPixelDepth() >> 3; if (imagePixelBytes != 4) { throw std::invalid_argument(LogFormat("RawImage should have 32 bits per pixel")); } FT_BBox stringBox = { }; std::vector<std::shared_ptr<CharGlyph>> stringGlyphs; for (auto charCode: stringText) { auto& charGlyph = this->getCharGlyph(charCode); stringBox.yMin = std::min<int>(stringBox.yMin, charGlyph->box->yMin); stringBox.yMax = std::max<int>(stringBox.yMax, charGlyph->box->yMax); stringBox.xMax += charGlyph->record->advance.x >> 16; // 16.16 fixed float format stringGlyphs.emplace_back(charGlyph); } int stringWidth = stringBox.xMax + 1; // Extra pixel in case string box is miscalculated int stringHeight = stringBox.yMax - stringBox.yMin; int stringAdvance = 0; int imageWidth = image->getWidth(); if (imageWidth < stringWidth) { throw std::runtime_error(LogFormat("Image width is %d but string requires %d", imageWidth, stringWidth)); } int imageHeight = image->getHeight(); if (imageHeight < stringHeight) { throw std::runtime_error(LogFormat("Image height is %d but string requires %d", imageHeight, stringHeight)); } int imagePixelsSize = image->getPixelsSize(); unsigned char* imagePixels = reinterpret_cast<unsigned char*>(image->getPixels()); for (auto& charGlyph: stringGlyphs) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(charGlyph->record.get()); FT_Bitmap charBitmap = bitmapGlyph->bitmap; unsigned char* charPixels = charGlyph->pixels.get(); int stringRow = stringBox.yMax - charGlyph->box->yMax; // Character Y offset in string int charRowSize = charBitmap.width; // Single byte (alpha) for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++, stringRow++) { int imagePixelsOffset = (stringRow * imageWidth + stringAdvance) * imagePixelBytes; int charRowOffset = charRow * charRowSize; for (unsigned int alphaPixel = 0; alphaPixel < charBitmap.width; alphaPixel++) { int alphaOffset = (alphaPixel * imagePixelBytes) + 3; // Offset to RGB[A] alpha assert(imagePixelsOffset + alphaOffset < imagePixelsSize); imagePixels[imagePixelsOffset + alphaOffset] = charPixels[charRowOffset + alphaPixel]; } } stringAdvance += charGlyph->record->advance.x >> 16; // 16.16 fixed float format } } const std::shared_ptr<Font::CharGlyph>& Font::getCharGlyph(wchar_t charCode) { auto charGlyphIt = this->charGlyphs.find(charCode); if (charGlyphIt != this->charGlyphs.end()) { return charGlyphIt->second; } FT_UInt charIndex = FT_Get_Char_Index(this->face.get(), charCode); if (FT_Load_Glyph(this->face.get(), charIndex, FT_LOAD_RENDER) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Load_Glyph()")); } FT_GlyphSlot glyphSlot = this->face->glyph; if (glyphSlot->format != FT_GLYPH_FORMAT_BITMAP) { throw std::runtime_error(LogFormat("Invalid glyph format")); } FT_Glyph glyph; if (FT_Get_Glyph(glyphSlot, &glyph)) { throw std::runtime_error(LogFormat("FT_Get_Glyph()")); } auto charGlyph = std::make_shared<CharGlyph>(); charGlyph->record = std::shared_ptr<FT_GlyphRec>(glyph, FT_Done_Glyph); charGlyph->box = std::make_shared<FT_BBox>(); FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, charGlyph->box.get()); // Invert the control box Y coordinates to reposition inverted bitmap int yMin = charGlyph->box->yMin; int yMax = charGlyph->box->yMax; charGlyph->box->yMin = -yMax; charGlyph->box->yMax = -yMin; FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph); FT_Bitmap charBitmap = bitmapGlyph->bitmap; int bitmapSize = charBitmap.width * charBitmap.rows; charGlyph->pixels = std::shared_ptr<unsigned char[]>(new unsigned char[bitmapSize]); unsigned char* pixels = charGlyph->pixels.get(); // Bitmap is inverted vertically relative to the texture coordinates space // and contains alpha (transparency) values only (no color information). for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++) { int pixelsRowOffset = charRow * charBitmap.width; int charRowOffset = (charBitmap.rows - charRow - 1) * charBitmap.width; std::memcpy(pixels + pixelsRowOffset, charBitmap.buffer + charRowOffset, charBitmap.width); } return this->charGlyphs.emplace(charCode, charGlyph).first->second; } } // namespace Graphene
39.090517
122
0.685522
santa01
5cdb9e56c7b928ae8ee77ae76099f5bd30ee0fbc
1,368
cpp
C++
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 01-02-2019 16:56:20 * solution_verdict: Partially Accepted language: C++14 * run_time: 0.00 sec memory_used: 14.9M * problem: https://www.codechef.com/FEB19B/problems/GUESSRT ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; const long mod=1e9+7; long bigmod(long b,long p,long mod) { long ret=1LL; while(p) { if(p%2)ret=(ret*b)%mod; b=(b*b)%mod;p/=2; } return ret; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int t;cin>>t; while(t--) { int n,k,m;cin>>n>>k>>m; long up=1,dw=1;long ans=0; while(m--) { if(!m) { ans=(ans+(up*bigmod((dw*n%mod),mod-2,mod))%mod)%mod; } else { if(n>k)n%=k; else { ans=(ans+(up*bigmod((dw*n%mod),mod-2,mod))%mod)%mod; dw=(dw*n)%mod;up=(up*(n-1))%mod; n+=k; } } } //cout<<n<<" "<<up<<" "<<dw<<endl; cout<<ans<<"\n"; } return 0; }
26.823529
111
0.384503
kzvd4729
5cdbcfda8170a4e834375ebcb4b6b8cf4e0b9bbe
1,195
cpp
C++
src/reverse-linked-list-ii.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/reverse-linked-list-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/reverse-linked-list-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (m >= n) return head; ListNode* dummyHead = new ListNode(-1); dummyHead->next = head; int cur = 1; ListNode *mHead, *nHead, *mPreHead; ListNode *pre = dummyHead; for (ListNode* p=head; p!=NULL; p=p->next, pre=pre->next) { if (cur == m) { mPreHead = pre; mHead = p; } if (cur == n) { nHead = p; break; } cur ++; } // reverse ListNode *p1, *p2; p1 = mHead; p2 = mHead->next; while (p1!=nHead) { ListNode* tmp = p2->next; p2->next = p1; p1 = p2; p2 = tmp; } ListNode* tmp = mPreHead->next; tmp->next = p2; mPreHead->next = p1; return dummyHead->next; } };
21.339286
65
0.43431
Liuchang0812
5cdc8c96401b0adfad7ac71605778bbbb36ede23
7,673
hpp
C++
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2019-2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "widget.hpp" #include "button_delegate.hpp" #include "label_widget.hpp" #include "button_type.hpp" #include "../animator.hpp" #include "../l10n.hpp" #include "../notifier.hpp" #include <memory> #include <string> #include <array> #include <optional> #include <future> namespace tt { class abstract_button_widget : public widget { public: using super = widget; using delegate_type = button_delegate; using callback_ptr_type = typename delegate_type::callback_ptr_type; observable<label> on_label = l10n("on"); observable<label> off_label = l10n("off"); observable<label> other_label = l10n("other"); observable<alignment> label_alignment; abstract_button_widget( gui_window &window, std::shared_ptr<widget> parent, std::shared_ptr<delegate_type> delegate = std::make_shared<delegate_type>()) noexcept : super(window, std::move(parent)), _delegate(std::move(delegate)) { _delegate->subscribe(*this, _relayout_callback); } void init() noexcept override { super::init(); _on_label_widget = this->make_widget<label_widget>(); _off_label_widget = this->make_widget<label_widget>(); _other_label_widget = this->make_widget<label_widget>(); _on_label_widget->alignment = label_alignment; _off_label_widget->alignment = label_alignment; _other_label_widget->alignment = label_alignment; _on_label_widget->label = on_label; _off_label_widget->label = off_label; _other_label_widget->label = other_label; _delegate->init(*this); } void deinit() noexcept override { _delegate->deinit(*this); super::deinit(); } template<typename Label> void set_label(Label const &rhs) noexcept { tt_axiom(gui_system_mutex.recurse_lock_count()); on_label = rhs; off_label = rhs; other_label = rhs; } [[nodiscard]] button_state state() const noexcept { tt_axiom(gui_system_mutex.recurse_lock_count()); return _delegate->state(*this); } /** Subscribe a callback to call when the button is activated. */ template<typename Callback> [[nodiscard]] callback_ptr_type subscribe(Callback &&callback) noexcept { ttlet lock = std::scoped_lock(gui_system_mutex); return _notifier.subscribe(std::forward<Callback>(callback)); } /** Unsubscribe a callback. */ void unsubscribe(callback_ptr_type &callback_ptr) noexcept { ttlet lock = std::scoped_lock(gui_system_mutex); return _notifier.unsubscribe(callback_ptr); } [[nodiscard]] bool update_constraints(hires_utc_clock::time_point display_time_point, bool need_reconstrain) noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); if (super::update_constraints(display_time_point, need_reconstrain)) { this->_minimum_size = _on_label_widget->minimum_size(); this->_preferred_size = _on_label_widget->preferred_size(); this->_maximum_size = _on_label_widget->maximum_size(); this->_minimum_size = max(this->_minimum_size, _off_label_widget->minimum_size()); this->_preferred_size = max(this->_preferred_size, _off_label_widget->preferred_size()); this->_maximum_size = max(this->_maximum_size, _off_label_widget->maximum_size()); this->_minimum_size = max(this->_minimum_size, _other_label_widget->minimum_size()); this->_preferred_size = max(this->_preferred_size, _other_label_widget->preferred_size()); this->_maximum_size = max(this->_maximum_size, _other_label_widget->maximum_size()); tt_axiom(this->_minimum_size <= this->_preferred_size && this->_preferred_size <= this->_maximum_size); return true; } else { return false; } } [[nodiscard]] void update_layout(hires_utc_clock::time_point displayTimePoint, bool need_layout) noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); need_layout |= std::exchange(this->_request_relayout, false); if (need_layout) { auto state_ = state(); this->_on_label_widget->visible = state_ == button_state::on; this->_off_label_widget->visible = state_ == button_state::off; this->_other_label_widget->visible = state_ == button_state::other; this->_on_label_widget->set_layout_parameters_from_parent(_label_rectangle); this->_off_label_widget->set_layout_parameters_from_parent(_label_rectangle); this->_other_label_widget->set_layout_parameters_from_parent(_label_rectangle); } widget::update_layout(displayTimePoint, need_layout); } [[nodiscard]] color background_color() const noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); if (_pressed) { return theme::global(theme_color::fill, this->_semantic_layer + 2); } else { return super::background_color(); } } [[nodiscard]] hit_box hitbox_test(point2 position) const noexcept final { tt_axiom(gui_system_mutex.recurse_lock_count()); if (_visible_rectangle.contains(position)) { return hit_box{weak_from_this(), _draw_layer, enabled ? hit_box::Type::Button : hit_box::Type::Default}; } else { return hit_box{}; } } [[nodiscard]] bool accepts_keyboard_focus(keyboard_focus_group group) const noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); return is_normal(group) and enabled; } void activate() noexcept { _delegate->activate(*this); run_from_main_loop([this]() { this->_notifier(); }); } [[nodiscard]] bool handle_event(command command) noexcept override { ttlet lock = std::scoped_lock(gui_system_mutex); if (enabled) { switch (command) { case command::gui_activate: activate(); return true; case command::gui_enter: activate(); this->window.update_keyboard_target(keyboard_focus_group::normal, keyboard_focus_direction::forward); return true; default:; } } return super::handle_event(command); } [[nodiscard]] bool handle_event(mouse_event const &event) noexcept final { ttlet lock = std::scoped_lock(gui_system_mutex); auto handled = super::handle_event(event); if (event.cause.leftButton) { handled = true; if (enabled) { if (compare_then_assign(_pressed, static_cast<bool>(event.down.leftButton))) { request_redraw(); } if (event.type == mouse_event::Type::ButtonUp && rectangle().contains(event.position)) { handled |= handle_event(command::gui_activate); } } } return handled; } protected: aarectangle _label_rectangle; std::shared_ptr<label_widget> _on_label_widget; std::shared_ptr<label_widget> _off_label_widget; std::shared_ptr<label_widget> _other_label_widget; bool _pressed = false; notifier<void()> _notifier; std::shared_ptr<delegate_type> _delegate; }; } // namespace tt
33.801762
130
0.652418
PinkFlufflyLlama
5cdf2b6a1306c7ced727a0796dd0bd65b5e6589f
484
hpp
C++
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef UISPRITE_HPP #define UISPRITE_HPP #include "TextureSheet.hpp" #include "GameObject.hpp" #include <string> using namespace std; /** * @brief 表示英文字符 * @warn 不管给如的字符大小写,绘制的一律大写 */ class UIString : public GameObject{ public: static UIString* Create(); void SetText(string t); string GetText() const; void Scale(float sx, float sy); private: void draw() override; void update() override; UIString(); TextureSheet ts; string text; }; #endif
17.925926
35
0.68595
VisualGMQ
5ce59e33cc592a3407f0e9dd072ad153623052b9
1,527
cpp
C++
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
// // Created by tyoun on 10/24/2021. // #include <catch2/catch.hpp> #include <string> #include <iostream> using std::string; TEST_CASE("String operations ") { string s{"a dog"}; s += " is a dog"; SECTION("Test concatenation") { REQUIRE(s == "a dog is a dog"); } SECTION("String find method") { //Return the index of first occurance of string p in s REQUIRE(s.find("dog")== 2); REQUIRE(s.find("dog", 3) == 11); } SECTION("npos? what even is this") { REQUIRE(s.find("doug") == string::npos); } SECTION("substring function") { REQUIRE(s.substr(7, 5) == "s a d"); } SECTION("replace function") { REQUIRE(s.replace(2, 3,"frog") == "a frog is a dog"); } SECTION("erase and insert function ") { s.replace(2, 3,"frog"); REQUIRE(s.erase(6, 3) == "a frog a dog"); s.insert(0, "is "); REQUIRE(s == "is a frog a dog"); REQUIRE(s < "is a frog a toad"); REQUIRE((s < "is a frog a cat") == false); } SECTION("Don't forget about string.append") { string sentence{"She"}; sentence.append(" Is playing"); sentence += " the piano"; std::cout << sentence << "\n"; } SECTION("More concatenation") { string subject{ "She"}; string verb {"is playing"}; string object {"the piano"}; string sentence = subject + " " + verb + " " + object + "."; std::cout << sentence << "\n"; } }
23.492308
98
0.518009
tyoungjr
5ce82c5014b4101d41dee1a7f051794d378edf5e
999
cpp
C++
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "AsioTlsTcpSocket.hpp" #include "AsioBaseTcpSocket.ipp" #include "AsioService.hpp" BEGIN_INANITY_NET template class AsioBaseTcpSocket<Botan::TLS::Stream<boost::asio::ip::tcp::socket> >; AsioTlsTcpSocket::AsioTlsTcpSocket(ptr<AsioService> service, std::unique_ptr<Botan::TLS::Context>&& tlsContext) : AsioBaseTcpSocket(service, service->GetIoService(), *tlsContext), tlsContext(std::move(tlsContext)) {} void AsioTlsTcpSocket::ShutdownNonSynced() { try { socket.lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_send); } catch(boost::system::system_error) { } } void AsioTlsTcpSocket::CloseNonSynced() { try { socket.lowest_layer().close(); } catch(boost::system::system_error error) { } } boost::asio::basic_socket<boost::asio::ip::tcp>& AsioTlsTcpSocket::GetLowestSocket() { return socket.lowest_layer(); } void AsioTlsTcpSocket::SetNoDelay(bool noDelay) { socket.lowest_layer().set_option(boost::asio::ip::tcp::no_delay(noDelay)); } END_INANITY_NET
22.2
111
0.74975
quyse
5ce8ff0732486f241dbe06166e5543ad5c5a88fd
26,297
cpp
C++
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * @desc 新手引导信息 * @date 2015-06-30 * @author 120103 * @file data/User.h ******************************************************************************/ #include "Guid.h" #include "Item.h" #include "Building.h" #include "Crusade.h" #include "GlobalMacros.h" #include "DestroyData.h" namespace data { static Guid* _instance = nullptr; const std::string Guid::TABLE_GUID = "user_guid"; const std::string Guid::GUID_USER_OPERATION = "userOperation"; const std::string Guid::UPDATE_GUID = "updateGuid"; const std::string Guid::DELETE_GUID = "deleteGuid"; Guid::Guid() { this->init(); } Guid::~Guid() { } Guid* Guid::getInstance() { if (!_instance) { _instance = new Guid(); } return _instance; } void Guid::destroyInstance() { if (_instance) { CC_SAFE_DELETE(_instance); } } void Guid::init() { _db = DBConnector::getInstance()->open(); std::stringstream sql; sql << "SELECT COUNT(*) AS `num` FROM `" << Guid::TABLE_GUID.c_str() << "` LIMIT 1"; /*int num = _db->getOne(sql.str()).asInt(); if (num == 0) { }*/ _db->upgrade(TABLE_GUID, Table::getInstance()->getTableByName(TABLE_GUID), Table::getInstance()->getCSVByName(TABLE_GUID)); _maxGuidNum = 0; _guidFinishNum = 0; //如果战斗引导未完成重置并重新引导.. isFinishBattleGuide(); //计算剩余没完成引导任务数.. sql.clear(); sql.str(""); sql << "SELECT * FROM `" << TABLE_GUID.c_str()<< "`WHERE `cstep`< `tstep`"; cocos2d::Value all = _db->getAll(sql.str()); for(int i = 0 ; i < all.asValueVector().size();i++) { cocos2d::ValueMap map =all.asValueVector().at(i).asValueMap(); if(map["cstep"].asInt() < map["tstep"].asInt()) { _maxGuidNum++; } } } bool Guid::isFinishBattleGuide() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getGuideTaskFinishState(ATTACK1)&& getGuideTaskFinishState(ATTACK2) &&getGuideTaskFinishState(AUTO_ATTACK)&& getGuideTaskFinishState(FOOD_BACK)) { return true; } else { setStepByGuidId(ATTACK1,STEP0); setStepByGuidId(ATTACK2, STEP0); setStepByGuidId(AUTO_ATTACK, STEP0); setStepByGuidId(FOOD_BACK, STEP0); if(getGuideTaskFinishState(EXPLORE)) { data::User::getInstance()->setGuideID(EXPLORE); } data::User::getInstance()->setAutoBattle(false); return false; } } return true; } bool Guid::FinishBattleGuide() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { setStepByGuidId(ATTACK1,STEP1); setStepByGuidId(ATTACK2, STEP1); setStepByGuidId(AUTO_ATTACK, STEP1); setStepByGuidId(FOOD_BACK, STEP1); } return false; } bool Guid::isNeedClearData() { //如果玩家上次进行了新手引导,但是并没有完成,对不起请重新来过,就是这么任性.. if(DEBUG_SHOW_GUID&&!isGuidFinish()) { int currentID =getCurrentGuidId(); if (currentID== GOLD) { if(getStepByGuidId(GOLD) < getMaxStepByGuidId(GOLD) && getStepByGuidId(GOLD)>0) { return true; } } else if(currentID > GOLD && currentID <WAR) { return true; } else if(currentID == WAR) { if(getStepByGuidId(WAR) < getMaxStepByGuidId(WAR)) { return true; } } } return false; } int Guid::getCurrentGuidId() { return User::getInstance()->getGuideID(); } bool Guid::isCanFastOperateWorkers() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int currentID = getCurrentGuidId(); if(currentID == WORKERS_USER1||currentID == WORKERS_USE1|| currentID == WORKERS_USE2|| currentID == WORKERS_USE3) { if(getGuideTaskFinishState(currentID)) { return true; } return false; } } return true; } int Guid::getGuideLayer() { if(!isGuidFinish()&& DEBUG_SHOW_GUID) { int guideID = getCurrentGuidId(); int currentStep = getStepByGuidId(guideID); if(guideID == GOLD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_BUILD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_BUILD&& currentStep == STEP1) { return BUID_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP0) { return BUID_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WAREHOUSE_USE1&& currentStep == STEP0) { return COLLECTION_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP2) { return RESOUCE_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP3) { return RESOUCE_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP5) { return BUID_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP6) { return BUID_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP7) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP8) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP9) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP1) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP2) { return MAIN_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP3) { return MAIN_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP4) { return BUID_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP3) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP1) { return BUID_LAYER; } else if(guideID == STORE_BUILD&& currentStep == STEP2) { return BUID_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP3) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP5) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP6) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP7) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP8) { return BUID_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP3) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP4) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP5) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP1) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == SOLDIERS_BUILD&&currentStep == STEP0) { return BUID_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP2) { return VENTURE_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP3) { return VENTURE_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP5) { return BUID_LAYER; } else if(guideID == TRAINING && currentStep == STEP0 ) { return BUID_LAYER; } else if(guideID == TRAINING && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == TRAINING && currentStep == STEP2) { return HERO_LAYER; } else if(guideID == TRAINING && currentStep == STEP3) { char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID << "` SET `cstep`='" << STEP2 <<"' WHERE `gid` = '" << TRAINING << "'" << comment; _db->query(sql.str()); return HERO_LAYER; } else if(guideID == WAR && currentStep == STEP0) { return HERO_LAYER; } else if(guideID == WAR && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WAR && currentStep == STEP2) { return VENTURE_LAYER; } else if(guideID == WAR && currentStep == STEP3) { return VENTURE_LAYER; } else if(guideID == WAR && currentStep == STEP4) { return VENTURE_LAYER; } else if(guideID == WAREHOUSE_USE2&&currentStep == STEP0) { return RESOUCE_LAYER; } else if(guideID == MOVE && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == CITY && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == FOOD && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == EXPLORE && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == ATTACK1 && currentStep == STEP0) { return -1; } else if(guideID == ATTACK2 && currentStep == STEP0) { return -1; } else if(guideID == AUTO_ATTACK && currentStep == STEP0) { return -1; } else if(guideID == FOOD_BACK && currentStep == STEP0) { return -1; } else if(guideID == DROP_GET && currentStep == STEP0) { return -1; } else if(guideID == DROP_GET && currentStep == STEP1) { return -1; } } return -1; } int Guid::getStepByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); return date; } void Guid::setStepByGuidId(int GuidID,int nStep) { char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID.c_str() << "` SET `cstep`='" << nStep <<"' WHERE `gid` = '" << GuidID << "'" << comment; _db->query(sql.str()); } cocos2d::ValueMap Guid::getInfoByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); cocos2d::ValueMap info; info["guidId"] =GuidID; info["step"] =date; return info; } int Guid::getMaxStepByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `tstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); return date; } cocos2d::ValueMap Guid::getGuidInfo() { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << getCurrentGuidId() << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); cocos2d::ValueMap info; info["guidId"] =getCurrentGuidId(); info["step"] =date; return info; } bool Guid::showGuid(int GuidId) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(GuidId == FOOD_BACK) { if(getGuideTaskFinishState(AUTO_ATTACK)) { User::getInstance()->setGuideID(GuidId); } } else if(GuidId == ATTACK1) { if(!getGuideTaskFinishState(ATTACK1)) { User::getInstance()->setGuideID(GuidId); } else { if(!getGuideTaskFinishState(ATTACK2)) { User::getInstance()->setGuideID(ATTACK2); } else { if(!getGuideTaskFinishState(AUTO_ATTACK)) { User::getInstance()->setGuideID(AUTO_ATTACK); } } } } else if(GuidId == SHELTER_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { if(!getGuideTaskFinishState(SHELTER_GUID)&& getGuideTaskFinishState(EXPLORE)) { User::getInstance()->setGuideID(SHELTER_GUID); } } } else { if(GuidId != 0) { User::getInstance()->setGuideID(GuidId); } else { if(getCurrentGuidId() == WAREHOUSE_USE2) { //不需要重复显示仓库卖出引导.. return false; } } } int currentID = getCurrentGuidId(); if(getStepByGuidId(currentID) < getMaxStepByGuidId(currentID)) { if(currentID == SHELTER_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { cocos2d::ValueMap info; info["step"] = getStepByGuidId(currentID)+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); return true; } } else { cocos2d::ValueMap info; info["step"] = getStepByGuidId(currentID)+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); return true; } } } return false; } void Guid::showBattleSelectGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = BATTLE_SELECT; dispatch(UPDATE_GUID,&info); } } void Guid::showHomeGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = HOME_GUID; dispatch(UPDATE_GUID,&info); } } void Guid::showBattleChoiceGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = BATTLE_CHOICE; dispatch(UPDATE_GUID,&info); } } bool Guid::isCanShowShelterGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { if(!getGuideTaskFinishState(SHELTER_GUID)&& getGuideTaskFinishState(EXPLORE)) { return true; } } return false; } return false; } bool Guid::isCanShowMapGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(!getGuideTaskFinishState(MOVE)) { data::User::getInstance()->setGuideID(MOVE); return true; } else if(!getGuideTaskFinishState(CITY)) { data::User::getInstance()->setGuideID(CITY); return true; } else if(!getGuideTaskFinishState(FOOD)) { data::User::getInstance()->setGuideID(FOOD); return true; } else if(!getGuideTaskFinishState(EXPLORE)) { data::User::getInstance()->setGuideID(EXPLORE); return true; } else if(!getGuideTaskFinishState(MOVE1)) { data::User::getInstance()->setGuideID(MOVE1); return true; } else if(!getGuideTaskFinishState(MOVE2)) { data::User::getInstance()->setGuideID(MOVE2); return true; } else { return false; } } return false; } bool Guid::isCanShowHomeGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int breadnum = data::Crusade::getInstance()->getPackageCurrent(data::Item::FOOD); if(isCanShowShelterGuid()||isCanShowMapGuid()) { return false; } else if(breadnum <= 2 && _homeGuid == false) { return true; } } return false; } bool Guid::isCanMoveOtherDirection() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getGuideTaskFinishState(MOVE2)) { return true; } return false; } return true; } bool Guid::getGuideTaskFinishState(int GuidID) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getStepByGuidId(GuidID) >= getMaxStepByGuidId(GuidID)) { return true; } return false; } return true; } void Guid::clearAllGuid() { User::getInstance()->setGuide(true); dispatch(DELETE_GUID, NULL); } void Guid::updateGuidInfo(int operationType) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int currentID = getCurrentGuidId(); int nStep = getStepByGuidId(currentID); //战斗选择界面引导不需要进行记录,只要条件合适就引导.. if(operationType == data::Guid::BATTLE_SELECT_SURE) { battleSelectSure(); } else if(operationType == data::Guid::BATTLE_CHOICE_SURE) { battleChoiceSure(); } else if(getStepByGuidId(currentID) < getMaxStepByGuidId(currentID)) { if(currentID == WAREHOUSE_USE1 && nStep == STEP7)//非一次点击就完成的新手引导.. { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 10) { restartTask(); } else { nextTask(operationType); } } else if(currentID == SHELTER_BUILD && nStep == STEP2) { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == WORKERS_USER1 && nStep == STEP2) { if (Building::getInstance()->getUserWorkerAmountByWID(Building::PLANT_WORKERID) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == STORE_BUILD && nStep == STEP3) { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == WAR && nStep == STEP2) { if (Crusade::getInstance()->getPackageCurrent(Item::ItemID::FOOD) < Item::getInstance()->getUserItemAmountByIID(Item::ItemID::FOOD)&&Crusade::getInstance()->getPackageCurrent(Item::ItemID::FOOD)<15 &&Crusade::getInstance()->getPackageSpace()<15) { restartTask(); } else { nextTask(operationType); } } else //一次点击就完成的新手引导.. { nextTask(operationType); } } } } void Guid::restartTask() { //未完成继续当前任务.. cocos2d::ValueMap info; info["step"] = getStepByGuidId(getCurrentGuidId())+1; info["guidId"] = getCurrentGuidId(); dispatch(UPDATE_GUID,&info); } void Guid::nextTask(int operationType) { int currentID = getCurrentGuidId(); //未进行同一项操作.. if (_preOperationType != operationType||_preOperationType == ATTACK1||currentID == MOVE1||currentID == MOVE2) { _preOperationType = operationType; char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID << "` SET `cstep`='" << getStepByGuidId(currentID) +1 <<"' WHERE `gid` = '" << currentID << "'" << comment; _db->query(sql.str()); int nstep = getStepByGuidId(currentID); //是否完成了该引导任务.. if(nstep < getMaxStepByGuidId(currentID)) { //未完成继续.. cocos2d::ValueMap info; info["step"] = nstep+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); } else { cocos2d::ValueMap info; info["step"] = nstep+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); //完成了完成度加1.. _guidFinishNum++; if(_guidFinishNum >= _maxGuidNum) { User::getInstance()->setGuide(true); } //更新当前执行的新手任务引导.. if (currentID < STORE_BUILD || (currentID >= WAR&& currentID < MOVE2)) { User::getInstance()->setGuideID(currentID + 1); currentID = getCurrentGuidId(); if (currentID == STORE_BUILD) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == MOVE) { //这一步需要手动显示下一步引导.. //data::Guid::getInstance()->showGuid(); } else if (currentID == CITY) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == FOOD) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == EXPLORE) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if(currentID == MOVE1) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if(currentID == MOVE2) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } } else if(currentID == WAREHOUSE_USE2) { User::getInstance()->setGuideID(currentID + 1); } } } } void Guid::battleSelectSure() { //未完成继续.. cocos2d::ValueMap info; info["step"] = 2; info["guidId"] = BATTLE_SELECT; dispatch(UPDATE_GUID,&info); } void Guid::battleChoiceSure() { //未完成继续.. cocos2d::ValueMap info; info["step"] = 2; info["guidId"] = BATTLE_CHOICE; dispatch(UPDATE_GUID,&info); } bool Guid::isGuidFinish() { return User::getInstance()->getGuide(); } }
28.306781
213
0.493745
thales-vogso
5ceab5aa4910df6bb9f11de46f0f9acbee827ba9
1,787
cpp
C++
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * Copyright (c) 2015, David Tran, Faculty of Computer Science, * University of Applied Sciences Rapperswil (HSR), * 8640 Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "ConnectorArgsTest.h" #include "Socket.h" #include "Tracer.h" ConnectorArgsTest::ConnectorArgsTest() { } ConnectorArgsTest::~ConnectorArgsTest() { StartTrace(ConnectorArgsTest.Dtor); } void ConnectorArgsTest::ArgsTest() { StartTrace(ConnectorArgsTest.ArgsTest); ConnectorArgs ca("192.168.1.1", 9999, 40); ASSERT_EQUAL(ca.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca.Port(), 9999); ASSERT_EQUAL(ca.ConnectTimeout(), 40); ConnectorArgs ca1("", 9999, 40); ASSERT_EQUAL(ca1.IPAddress(), "127.0.0.1"); ASSERT_EQUAL(ca1.Port(), 9999); ASSERT_EQUAL(ca1.ConnectTimeout(), 40); // Default constructor ConnectorArgs ca2; ASSERT_EQUAL(ca2.IPAddress(), "127.0.0.1"); ASSERT_EQUAL(ca2.Port(), 80); ASSERT_EQUAL(ca2.ConnectTimeout(), 0); // assignment operator ConnectorArgs ca3; ca3 = ca; ASSERT_EQUAL(ca3.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca3.Port(), 9999); ASSERT_EQUAL(ca3.ConnectTimeout(), 40); // copy constructor ConnectorArgs ca4(ca); ASSERT_EQUAL(ca4.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca4.Port(), 9999); ASSERT_EQUAL(ca4.ConnectTimeout(), 40); } // builds up a suite of tests, add a line for each testmethod void ConnectorArgsTest::runAllTests(cute::suite &s) { StartTrace(ConnectorArgsTest.suite); s.push_back(CUTE_SMEMFUN(ConnectorArgsTest, ArgsTest)); }
28.822581
102
0.738668
zer0infinity
5ced779dec0001f9d5535a8b85d6ef0d009c7891
1,980
cpp
C++
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
null
null
null
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
6
2020-11-29T18:27:05.000Z
2021-12-24T13:14:47.000Z
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
8
2020-11-03T17:09:11.000Z
2021-12-04T14:24:49.000Z
#include "SSet.h" #include "benchmark/benchmark.h" #include <iostream> #include <sstream> static void BM_subsetBruteFromFile10T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_10.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile10F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_10.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile15T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_15.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile15F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_15.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile20T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_20.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile20F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_20.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile25T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_25.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile25F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_25.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } BENCHMARK(BM_subsetBruteFromFile10T); BENCHMARK(BM_subsetBruteFromFile10F); BENCHMARK(BM_subsetBruteFromFile15T); BENCHMARK(BM_subsetBruteFromFile15F); BENCHMARK(BM_subsetBruteFromFile20T); BENCHMARK(BM_subsetBruteFromFile20F); BENCHMARK(BM_subsetBruteFromFile25T); BENCHMARK(BM_subsetBruteFromFile25F); BENCHMARK_MAIN();
26.756757
64
0.733838
DandyForever
5cefa78e5d383773238ce9f7714f4fc64f3c7781
3,767
cpp
C++
MathTL/algebra/symmetric_matrix.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
MathTL/algebra/symmetric_matrix.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
MathTL/algebra/symmetric_matrix.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
// implementation of MathTL::*TriangularMatrix inline functions #include <algorithm> #include <cassert> namespace MathTL { template <class C> inline SymmetricMatrix<C>::SymmetricMatrix(const size_type n) : LowerTriangularMatrix<C>(n) { } template <class C> inline SymmetricMatrix<C>::SymmetricMatrix(const SymmetricMatrix<C>& M) : LowerTriangularMatrix<C>(M) { } template <class C> SymmetricMatrix<C>::SymmetricMatrix(const size_type n, const char* str, const bool byrow) : LowerTriangularMatrix<C>(n,n,str,byrow) { } template <class C> inline void SymmetricMatrix<C>::resize(const size_type n) { LowerTriangularMatrix<C>::resize(n); } template <class C> inline const C SymmetricMatrix<C>::operator () (const size_type row, const size_type column) const { return LowerTriangularMatrix<C>::entries_[LowerTriangularMatrix<C>::triangle_index(row,column, LowerTriangularMatrix<C>::rowdim_, LowerTriangularMatrix<C>::coldim_)]; } template <class C> inline const C SymmetricMatrix<C>::get_entry(const size_type row, const size_type column) const { return this->operator () (row, column); } template <class C> inline C& SymmetricMatrix<C>::operator () (const size_type row, const size_type column) { return LowerTriangularMatrix<C>::entries_[LowerTriangularMatrix<C>::triangle_index(row,column, LowerTriangularMatrix<C>::rowdim_, LowerTriangularMatrix<C>::coldim_)]; } template <class C> inline void SymmetricMatrix<C>::set_entry(const size_type row, const size_type column, const C value) { this->operator () (row, column) = value; } template <class C> template <class C2> inline bool SymmetricMatrix<C>::operator == (const SymmetricMatrix<C2>& M) const { return LowerTriangularMatrix<C>::operator == (M); } template <class C> template <class C2> inline bool SymmetricMatrix<C>::operator != (const SymmetricMatrix<C2>& M) const { return !((*this) == M); } template <class C> SymmetricMatrix<C>& SymmetricMatrix<C>::operator = (const SymmetricMatrix<C>& M) { LowerTriangularMatrix<C>::operator = (M); return *this; } template <class C> template <class VECTOR> void SymmetricMatrix<C>::apply(const VECTOR& x, VECTOR& Mx) const { assert(Mx.size() == LowerTriangularMatrix<C>::rowdim_); for (typename SymmetricMatrix<C>::size_type i(0); i < LowerTriangularMatrix<C>::rowdim_; i++) { Mx[i] = 0; for (typename SymmetricMatrix<C>::size_type j(0); j < LowerTriangularMatrix<C>::coldim_; j++) Mx[i] += this->operator () (i, j) * x[j]; } } template <class C> template <class VECTOR> void SymmetricMatrix<C>::apply_transposed(const VECTOR& x, VECTOR& Mtx) const { apply(x, Mtx); } template <class C> void SymmetricMatrix<C>::print(std::ostream &os, const unsigned int tabwidth, const unsigned int precision) const { if (LowerTriangularMatrix<C>::empty()) os << "[]" << std::endl; // Matlab style else { unsigned int old_precision = os.precision(precision); for (typename SymmetricMatrix<C>::size_type i(0); i < SymmetricMatrix<C>::row_dimension(); ++i) { for (typename SymmetricMatrix<C>::size_type j(0); j < SymmetricMatrix<C>::column_dimension(); ++j) os << std::setw(tabwidth) << std::setprecision(precision) << this->operator () (i, j); os << std::endl; } os.precision(old_precision); } } template <class C> inline std::ostream& operator << (std::ostream& os, const SymmetricMatrix<C>& M) { M.print(os); return os; } }
24.782895
98
0.647996
kedingagnumerikunimarburg
5cf0fd512ce372f381352717a818f7fab7f03081
1,619
cpp
C++
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
3
2016-05-22T16:44:18.000Z
2021-06-12T00:38:59.000Z
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
null
null
null
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
1
2021-01-16T23:15:30.000Z
2021-01-16T23:15:30.000Z
#include "stdhdrs.h" #ifndef USE_TENTER_BILLING #include "Server.h" #include "../ShareLib/DBCmd.h" #include "CmdMsg.h" void BillConnectMsg(CBPacket::SP& msg) { CLCString protocolVersion(17); protocolVersion.Format("%s", BILL_SERVER_VERSION); msg->Init(BM_CONNECT); RefMsg(msg) << protocolVersion << (unsigned char) gserver.m_serverno << (unsigned char) GAMEID; } void BillBalanceReqMsg(CBPacket::SP& msg, int userindex, const char* idname) { CLCString id(51); id.Format("%s", idname); msg->Init(MSG_BILLITEM_CASHBALANCE_REQ); RefMsg(msg) << id << (unsigned char) CPID << userindex; } void BillCanbuyReqMsg(CBPacket::SP& msg, int userindex, const char* idname, int ctid[], char count, const char* ip) { CLCString id(51); id.Format("%s", idname); CLCString lcIP(16); lcIP.Format("%s", ip); msg->Init(MSG_BILLITEM_CANBUY_REQ); RefMsg(msg) << id << (unsigned char) CPID << userindex << lcIP << (unsigned char) count; for(int i = 0; i < MAX_PURCHASEITEM && i < count; i++) { RefMsg(msg) << ctid[i]; } } void BillBuyReqMsg(CBPacket::SP& msg, int userindex, const char* userid, int serial, int ctid[], const char* ip, char count) { msg->Init(MSG_BILLITEM_BUY_REQ); msg->m_serial = serial; CLCString id(51); id.Format("%s", userid); CLCString lcIP(16); lcIP.Format("%s", ip); RefMsg(msg) << id << (unsigned char) CPID << userindex << lcIP << (unsigned char) count; for(int i = 0; i < MAX_PURCHASEITEM && i < count; i++) { RefMsg(msg) << ctid[i]; } } #endif
21.302632
125
0.62446
Light-Games-Ink
5cf65a31c0bfabb00320ec9f264e7d52a2c9ba75
2,933
cpp
C++
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
3
2015-01-28T17:51:34.000Z
2016-09-01T01:53:19.000Z
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
1
2015-05-07T15:47:16.000Z
2015-05-07T15:47:16.000Z
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
null
null
null
/****************************************************************************** * * Name: SvgDocument.cpp * Project: Fog-Framework (Copyright (c) 2006-2011, Petr Kobalicek <[email protected]>) C++/CLI Interface * Author: Maxim Rylov * ****************************************************************************** * The MIT License (MIT) * * Copyright (C) 2012, Maxim Rylov * * 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 "stdafx.h" #include "SvgDocument.h" #include "Enums.h" #include "clix.h" #include "ManagedStreamDevice.h" #include "Fog/Core/Tools/Stream.h" #include "Fog/G2d/Svg/SvgDom.h" namespace FogNET { using namespace clix; SvgDocument::SvgDocument(void) { m_svgDocument = new Fog::SvgDocument(); } SvgDocument::~SvgDocument() { delete m_svgDocument; m_svgDocument = NULL; } SizeF SvgDocument::GetSize() { Fog::SizeF size = m_svgDocument->getDocumentSize(); return SizeF(size.w, size.h); } SvgDocument^ SvgDocument::FromFile(String ^fileName) { std::string str = marshalString<E_UTF8>(fileName); Fog::StringW fileNameW = Fog::StringW::fromUtf8(str.c_str(), str.length()); SvgDocument ^doc = gcnew SvgDocument(); doc->m_svgDocument->readFromFile(fileNameW); return doc; } SvgDocument^ SvgDocument::FromStream(Stream ^stream) { if (!stream->CanRead) throw gcnew IOException("stream is closed"); ManagedStreamDevice* msd = new ManagedStreamDevice(stream); Fog::Stream* fStream = new Fog::Stream((Fog::StreamDevice*)msd); SvgDocument ^doc = gcnew SvgDocument(); doc->m_svgDocument->readFromStream(*fStream); return doc; } void SvgDocument::Render(Painter ^painter) { m_svgDocument->render((Fog::Painter*)painter->GetNativePointer()); } }
32.230769
113
0.652915
Rungee